Esempio n. 1
0
def ajax_get_join_targets(request, selected_geo_type):
    """
    Ajax - Retrieve JoinTarget information that matches
            a selected geospatial identification type

    Returns a list for use in loading a dropdown box
    """
    jt = get_latest_jointarget_information()

    join_target_info = jt.get_available_layers_list_by_type(selected_geo_type)
    if join_target_info is None:
        err_msg = ("Sorry! No Join Targets found"
                   " for Geospatial type: %s") % selected_geo_type

        json_msg = MessageHelperJSON.get_json_msg(success=False,
                                                  msg=err_msg)
        return HttpResponse(status=400,
                            content=json_msg,
                            content_type="application/json")


    json_msg = MessageHelperJSON.get_json_msg(success=True,
                                              msg="success",
                                              data_dict=join_target_info)

    return HttpResponse(status=200, content=json_msg, content_type="application/json")
Esempio n. 2
0
def ajax_get_join_targets(request, selected_geo_type):
    """
    Ajax - Retrieve JoinTarget information that matches
            a selected geospatial identification type

    Returns a list for use in loading a dropdown box
    """
    jt = get_latest_jointarget_information()

    join_target_info = jt.get_available_layers_list_by_type(selected_geo_type)
    if join_target_info is None:
        err_msg = "Sorry! No Join Targets found for Geospatial type: {0}".format(
            selected_geo_type)
        json_msg = MessageHelperJSON.get_json_msg(success=False,\
                                msg=err_msg)
        return HttpResponse(status=400,
                            content=json_msg,
                            content_type="application/json")


    json_msg = MessageHelperJSON.get_json_msg(success=True,\
                                msg="success",\
                                data_dict=join_target_info)

    return HttpResponse(status=200,
                        content=json_msg,
                        content_type="application/json")
Esempio n. 3
0
def ajax_join_targets_with_descriptions(request, selected_geo_type=None):
    """For use when choosing a join target through the UI
    Return JSON list with:
       join target id
       name
       description
    """
    jt = get_latest_jointarget_information()

    join_target_info = jt.get_available_layers_list_by_type(selected_geo_type,
                                                            for_json=True)

    if join_target_info is None:
        err_msg = "Sorry! No Join Targets found for Geospatial type: {0}".format(
            selected_geo_type)
        json_msg = MessageHelperJSON.get_json_msg(success=False,\
                                msg=err_msg)
        return HttpResponse(status=400,
                            content=json_msg,
                            content_type="application/json")

    else:
        json_msg = MessageHelperJSON.get_json_msg(success=True,\
                                msg="success",\
                                data_dict=join_target_info)

        return HttpResponse(status=200,
                            content=json_msg,
                            content_type="application/json")
Esempio n. 4
0
def view_unmatched_lat_lng_rows_json(request, tab_md5):
    """
    View the unmatched rows resulting from trying to map lat/lng columns
    """

    # Retrieve the Tabular file information
    # ----------------------------------
    try:
        worldmap_info = WorldMapLatLngInfo.objects.get(md5=tab_md5)
    except WorldMapLatLngInfo.DoesNotExist:
        raise Http404('No WorldMapLatLngInfo for md5: %s' % tab_md5)

    if worldmap_info.core_data and\
        'unmapped_records_list' in worldmap_info.core_data:
        # Unmatched records exist

        template_dict = dict(
            ummatched_rows=worldmap_info.core_data['unmapped_records_list'],
            column_names=worldmap_info.attribute_data)

        unmatched_rows_html = render_to_string(
            'metadata/unmatched_tabular_rows.html', template_dict, request)

        return HttpResponse(unmatched_rows_html)
        json_msg = MessageHelperJSON.get_json_msg(success=True,\
                        msg="Records found",\
                        data_dict=worldmap_info.core_data['unmapped_records_list'])
    else:
        # No unmatched records exist
        json_msg = MessageHelperJSON.get_json_msg(success=False,\
                        msg="No unmatched records found.")

    #from django.template.loader import render_to_string

    return HttpResponse(json_msg, content_type="application/json")
Esempio n. 5
0
def view_unmatched_join_rows_json(request, tab_md5):
    """
    View the unmatched rows resulting from a Table Join
    """
    # ----------------------------------
    # Retrieve the Tabular file information
    # ----------------------------------
    try:
        worldmap_info = WorldMapJoinLayerInfo.objects.get(md5=tab_md5)
    except WorldMapJoinLayerInfo.DoesNotExist:
        raise Http404('No WorldMapJoinLayerInfo for md5: %s' % tab_md5)

    if worldmap_info.core_data and\
        'unmatched_records_list' in worldmap_info.core_data:
        # Unmatched records exist
        unmatched_row_dict = dict(ummatched_rows=worldmap_info.core_data.get(
            'unmatched_records_list', None),
                                  column_names=worldmap_info.attribute_data)

        unmatched_rows_html = render_to_string(
            'metadata/unmatched_records.html', unmatched_row_dict, request)

        return HttpResponse(unmatched_rows_html)
        json_msg = MessageHelperJSON.get_json_msg(success=True,\
                        msg="Records found",\
                        data_dict=worldmap_info.core_data['unmatched_rows'])
    else:
        # No unmatched records exist
        json_msg = MessageHelperJSON.get_json_msg(success=False,\
                        msg="No unmatched records found.")

    return HttpResponse(json_msg, content_type="application/json")
Esempio n. 6
0
def ajax_join_targets_with_descriptions(request, selected_geo_type=None):
    """For use when choosing a join target through the UI
    Return JSON list with:
       join target id
       name
       description
    """
    jt = get_latest_jointarget_information()

    join_target_info = jt.get_available_layers_list_by_type(selected_geo_type, for_json=True)

    if join_target_info is None:
        err_msg = "Sorry! No Join Targets found for Geospatial type: {0}".format(selected_geo_type)
        json_msg = MessageHelperJSON.get_json_msg(success=False,\
                                msg=err_msg)
        return HttpResponse(status=400, content=json_msg, content_type="application/json")

    else:
        json_msg = MessageHelperJSON.get_json_msg(success=True,\
                                msg="success",\
                                data_dict=join_target_info)

        return HttpResponse(status=200, content=json_msg, content_type="application/json")
Esempio n. 7
0
def view_unmatched_lat_lng_rows_json(request, tab_md5):
    """
    View the unmatched rows resulting from trying to map lat/lng columns
    """

    # Retrieve the Tabular file information
    # ----------------------------------
    try:
        worldmap_info = WorldMapLatLngInfo.objects.get(md5=tab_md5)
    except WorldMapLatLngInfo.DoesNotExist:
        raise Http404('No WorldMapLatLngInfo for md5: %s' % tab_md5)

    if worldmap_info.core_data and\
        'unmapped_records_list' in worldmap_info.core_data:
        # Unmatched records exist

        template_dict = dict(ummatched_rows=worldmap_info.core_data['unmapped_records_list'],
                        column_names=worldmap_info.attribute_data)

        unmatched_rows_html = render_to_string('metadata/unmatched_tabular_rows.html',
                                template_dict,
                                request)

        return HttpResponse(unmatched_rows_html)
        json_msg = MessageHelperJSON.get_json_msg(success=True,\
                        msg="Records found",\
                        data_dict=worldmap_info.core_data['unmapped_records_list'])
    else:
        # No unmatched records exist
        json_msg = MessageHelperJSON.get_json_msg(success=False,\
                        msg="No unmatched records found.")


    #from django.template.loader import render_to_string

    return HttpResponse(json_msg, content_type="application/json")
Esempio n. 8
0
def view_unmatched_join_rows_json(request, tab_md5):
    """
    View the unmatched rows resulting from a Table Join
    """
    # ----------------------------------
    # Retrieve the Tabular file information
    # ----------------------------------
    try:
        worldmap_info = WorldMapJoinLayerInfo.objects.get(md5=tab_md5)
    except WorldMapJoinLayerInfo.DoesNotExist:
        raise Http404('No WorldMapJoinLayerInfo for md5: %s' % tab_md5)

    if worldmap_info.core_data and\
        'unmatched_records_list' in worldmap_info.core_data:
        # Unmatched records exist
        unmatched_row_dict = dict(
            ummatched_rows=worldmap_info.core_data.get('unmatched_records_list', None),
            column_names=worldmap_info.attribute_data)

        unmatched_rows_html = render_to_string('metadata/unmatched_records.html',
            unmatched_row_dict,
            request)

        return HttpResponse(unmatched_rows_html)

        json_msg = MessageHelperJSON.get_json_msg(\
                        success=True,
                        msg="Records found",
                        data_dict=worldmap_info.core_data['unmatched_rows'])
    else:
        # No unmatched records exist
        json_msg = MessageHelperJSON.get_json_msg(\
                        success=False,
                        msg="No unmatched records found.")

    return HttpResponse(json_msg, content_type="application/json")
Esempio n. 9
0
def view_classify_layer_form(request, import_success_md5):
    """
    (note: This should be refactored into a class...)
    Given a ClassifyLayerForm submission, return a JSON response

    :param import_success_md5: str, md5 identifying a WorldMapLayerInfo object
    :returns JSON response: JSON generated with the MessageHelperJSON.get_json_msg function
    """
    # --------------------------------------------------------------
    # Is it a POST?
    # --------------------------------------------------------------
    if not request.POST:
        err_note = 'A POST request must be used to classify the layer.'

        div_content = format_major_error_message(err_note,\
            import_success_md5=import_success_md5)
        json_msg = MessageHelperJSON.get_json_msg(success=False,\
                        msg=err_note,\
                        data_dict=dict(div_content=div_content))
        # technically a 405 error, but we want the JSON message to appear
        return HttpResponse(status=200,\
                        content=json_msg,\
                        content_type="application/json")

    # --------------------------------------------------------------
    # Is the WorldMapLayerInfo object md5 available?
    # --------------------------------------------------------------
    if not import_success_md5:
        err_note = ('Sorry! The layer could not be identified.'
                    '\n\nThe Styling option is not available.')
        json_msg = MessageHelperJSON.get_json_msg(\
                    success=False,
                    msg=err_note,
                    data_dict=dict(div_content=format_major_error_message(err_note)))
        # technically a 404 error, but we want the JSON message to appear
        return HttpResponse(status=200,
                            content=json_msg,
                            content_type="application/json")

    # --------------------------------------------------------------
    # Does the WorldMapLayerInfo object exist?
    # --------------------------------------------------------------
    if not 'data_source_type' in request.POST:
        err_note = ('Sorry! The layer could not be identified.'
                    '\n\nThe Styling option is not available. (id:ds2)')
        json_msg = MessageHelperJSON.get_json_msg(\
                    success=False,
                    msg=err_note,
                    data_dict=dict(div_content=format_major_error_message(err_note)))
        return HttpResponse(status=200,
                            content=json_msg,
                            content_type="application/json")

    # Retrieve an object containing the WorldMap data
    #
    worldmap_layerinfo = get_worldmap_info_object(request.POST['data_source_type'],\
                                import_success_md5)

    if worldmap_layerinfo is None:
        err_note = ('Sorry! The layer could not be identified.'
                    '\n\nThe Styling option is not available.'
                    ' (id:ds3) %s' % request.POST['data_source_type'])

        json_msg = MessageHelperJSON.get_json_msg(\
                    success=False,
                    msg=err_note,
                    data_dict=dict(div_content=format_major_error_message(err_note)))
        # technically a 410 error, but we want the JSON message to appear
        return HttpResponse(status=200,
                            content=json_msg,
                            content_type="application/json")

    d = {'ATTRIBUTE_VALUE_DELIMITER': ATTRIBUTE_VALUE_DELIMITER}

    # --------------------------------------------------------------
    # Is the form valid?
    # --------------------------------------------------------------

    # Load up classification form parameters and validate this request
    #   e.g. Is the classification attribute in the AJAX call actually
    #       part of this layer? etc.
    #
    classify_form = ClassifyLayerForm(\
                        request.POST,
                        **worldmap_layerinfo.get_dict_for_classify_form())

    # --------------------------------------------------------------
    # Invalid forms are status=200 so caught by ajax
    # --------------------------------------------------------------
    if not classify_form.is_valid():  # Oops, not valid (shouldn't happen)
        user_message = ('There was an error with the styling form.'
                        ' Please check the errors below.')
        additional_info = dict(classify_form=classify_form,
                               worldmap_layerinfo=worldmap_layerinfo,
                               error_msg=user_message)
        d.update(additional_info)

        form_content = render_to_string(\
                            'classification/view_classify_form.html',
                            d,
                            request)
        json_msg = MessageHelperJSON.get_json_msg(\
                                success=False,
                                msg=user_message,
                                data_dict={'div_content':form_content})
        return HttpResponse(status=200,
                            content=json_msg,
                            content_type="application/json")

    initial_classify_params = classify_form.get_params_dict_for_classification(
    )
    if initial_classify_params is None:
        LOGGER.error(
            'Failed with *valid* form: classify_form.get_params_dict_for_classification()'
        )
        json_msg = MessageHelperJSON.get_json_msg(success=False,\
            msg='The layer styling form contains errors (code: 2)')
        return HttpResponse(status=200,
                            content=json_msg,
                            content_type="application/json")

    #----------------------------------------------------------
    # Prepare params for classify request against WorldMap API
    #
    #----------------------------------------------------------
    initial_classify_params.update(\
            worldmap_layerinfo.get_params_to_check_for_existing_layer_metadata())

    api_form = ClassifyRequestDataForm(initial_classify_params)
    if not api_form.is_valid():
        err_msg = ('Validation failed with ClassifyRequestDataForm.'
                   'Errors: %s') % api_form.errors
        LOGGER.error(err_msg)
        json_msg = MessageHelperJSON.get_json_msg(\
                        success=False,
                        msg='The layer styling form contains errors (code: 3)')
        return HttpResponse(status=200,
                            content=json_msg,
                            content_type="application/json")

    classify_params = api_form.cleaned_data

    classify_url = classify_form.get_worldmap_classify_api_url()

    LOGGER.debug('classify_params', classify_params)

    resp = None
    try:
        resp = requests.post(classify_url,\
                    data=classify_params,\
                    auth=settings.WORLDMAP_ACCOUNT_AUTH,\
                    timeout=settings.WORLDMAP_DEFAULT_TIMEOUT)

    except requests.exceptions.ConnectionError as exception_obj:
        err_msg = ('<b>Details for administrator:</b>'
                   'Could not contact the Dataverse server: %s')\
                   % (classify_url)

        log_connect_error_message(err_msg, LOGGER, exception_obj)

        json_msg = MessageHelperJSON.get_json_msg(\
                    success=False,
                    msg='Sorry!  The classification failed.<br /><p>%s</p>' % err_msg)

        return HttpResponse(status=200,
                            content=json_msg,
                            content_type="application/json")

    if not resp.status_code == 200:
        try:
            json_resp = resp.json()
        except ValueError:
            error_msg = ('Worldmap classification failed. Status code:'
                         ' %s\nText;%s')\
                         % (resp.status_code, resp.text.encode('utf-8'))

            LOGGER.error(error_msg)

            json_msg = MessageHelperJSON.get_json_msg(\
                            success=False,
                            msg='Sorry!  The classification failed.')
            return HttpResponse(status=200,
                                content=json_msg,
                                content_type="application/json")

        wm_err_msg = json_resp.get('message', None)
        if wm_err_msg is None:
            wm_err_msg = 'No message given.'

        err_msg = 'Sorry!  The classification failed.<p>%s</p>' % wm_err_msg

        json_msg = MessageHelperJSON.get_json_msg(success=False, msg=err_msg)

        return HttpResponse(status=200,
                            content=json_msg,
                            content_type="application/json")

    # RESPONSE CODE IS 200

    # --------------------------------------------------------------
    # convert response to JSON
    # --------------------------------------------------------------
    try:
        json_resp = resp.json()
    except ValueError:
        LOGGER.error('Worldmap response was not valid json: %s',\
                resp.text.encode('utf-8'))
        json_msg = MessageHelperJSON.get_json_msg(success=False,\
            msg='Sorry!  The classification failed.')
        return HttpResponse(status=200,\
            content=json_msg,\
            content_type="application/json")

    # --------------------------------------------------------------
    #   Classification Failed
    # --------------------------------------------------------------
    if not json_resp.get("success") is True:
        LOGGER.info('Worldmap response did not have success==true: %s',
                    resp.text)
        user_msg = 'Sorry!  The classification failed.<br /><br />%s' %\
                    json_resp.get('message', 'nada')
        json_msg = MessageHelperJSON.get_json_msg(success=False, msg=user_msg)
        return HttpResponse(status=200,
                            content=json_msg,
                            content_type="application/json")

    # --------------------------------------------------------------
    #   Validate the response
    # --------------------------------------------------------------
    f_val = WorldMapToGeoconnectMapLayerMetadataValidationForm(
        json_resp.get('data', None))
    if not f_val.is_valid():
        LOGGER.error('Classify return data failed validation: %s',
                     f_val.errors)
        user_msg = 'Sorry!  The classification failed.<br /><br />%s' \
                        % json_resp.get('message', f_val.errors)
        json_msg = MessageHelperJSON.get_json_msg(success=False, msg=user_msg)
        return HttpResponse(status=200,
                            content=json_msg,
                            content_type="application/json")

    # --------------------------------------------------------------
    #   Looks good, update the WorldMapLayerInfo's attribute info
    # --------------------------------------------------------------
    if hasattr(worldmap_layerinfo, 'add_attribute_info_as_json_string'):
        # handle shapefiles

        worldmap_layerinfo.add_attribute_info_as_json_string(
            f_val.cleaned_data['attribute_info'])

        worldmap_layerinfo.save()

    elif hasattr(worldmap_layerinfo, 'attribute_data'):
        # handle tabular files

        worldmap_layerinfo.attribute_info =\
            JSONHelper.to_python_or_none(f_val.cleaned_data['attribute_info'])

        worldmap_layerinfo.download_links =\
            JSONHelper.to_python_or_none(f_val.cleaned_data['download_links'])

        worldmap_layerinfo.save()
    else:
        LOGGER.error(dir(worldmap_layerinfo))
        LOGGER.error(type(worldmap_layerinfo))
        LOGGER.error('nada?')

    # --------------------------------------------------------------
    # Refresh the classify form with the latest WorldMap parameter information
    # --------------------------------------------------------------
    classify_form = ClassifyLayerForm(\
                        request.POST,
                        **worldmap_layerinfo.get_dict_for_classify_form())

    # --------------------------------------------------------------
    # Update the Dataverse metadata -- so that the new icon will be refreshed
    # --------------------------------------------------------------

    # Is all this needed, or should there be a
    # Dataverse API call to only update the image?
    MetadataUpdater.run_update_via_popen(worldmap_layerinfo)

    msg_params = classify_form.get_params_for_display()

    success_msg = render_to_string('classification/classify_success_msg.html',
                                   msg_params)

    d.update(
        dict(classify_form=classify_form,
             success_msg=success_msg,
             SELECT_LABEL=SELECT_LABEL))

    form_content = render_to_string('classification/view_classify_form.html',
                                    d, request)


    json_msg = MessageHelperJSON.get_json_msg(\
                    success=True,
                    msg=success_msg, #'Success!'
                    data_dict={'div_content':form_content})

    return HttpResponse(status=200,
                        content=json_msg,
                        content_type="application/json")
Esempio n. 10
0
def view_classify_layer_form(request, import_success_md5):
    """
    (note: This should be refactored into a class...)
    Given a ClassifyLayerForm submission, return a JSON response

    :param import_success_md5: str, md5 identifying a WorldMapLayerInfo object
    :returns JSON response: JSON generated with the MessageHelperJSON.get_json_msg function
    """
    # --------------------------------------------------------------
    # Is it a POST?
    # --------------------------------------------------------------
    if not request.POST:
        err_note = 'A POST request must be used to classify the layer.'

        div_content = format_major_error_message(err_note,\
            import_success_md5=import_success_md5)
        json_msg = MessageHelperJSON.get_json_msg(success=False,\
                        msg=err_note,\
                        data_dict=dict(div_content=div_content))
        # technically a 405 error, but we want the JSON message to appear
        return HttpResponse(status=200,\
                        content=json_msg,\
                        content_type="application/json")

    # --------------------------------------------------------------
    # Is the WorldMapLayerInfo object md5 available?
    # --------------------------------------------------------------
    if not import_success_md5:
        err_note = ('Sorry! The layer could not be identified.'
                    '\n\nThe Styling option is not available.')
        json_msg = MessageHelperJSON.get_json_msg(\
                    success=False,
                    msg=err_note,
                    data_dict=dict(div_content=format_major_error_message(err_note)))
        # technically a 404 error, but we want the JSON message to appear
        return HttpResponse(status=200, content=json_msg, content_type="application/json")

    # --------------------------------------------------------------
    # Does the WorldMapLayerInfo object exist?
    # --------------------------------------------------------------
    if not 'data_source_type' in request.POST:
        err_note = ('Sorry! The layer could not be identified.'
                    '\n\nThe Styling option is not available. (id:ds2)')
        json_msg = MessageHelperJSON.get_json_msg(\
                    success=False,
                    msg=err_note,
                    data_dict=dict(div_content=format_major_error_message(err_note)))
        return HttpResponse(status=200, content=json_msg, content_type="application/json")

    # Retrieve an object containing the WorldMap data
    #
    worldmap_layerinfo = get_worldmap_info_object(request.POST['data_source_type'],\
                                import_success_md5)

    if worldmap_layerinfo is None:
        err_note = ('Sorry! The layer could not be identified.'
                    '\n\nThe Styling option is not available.'
                    ' (id:ds3) %s' % request.POST['data_source_type'])

        json_msg = MessageHelperJSON.get_json_msg(\
                    success=False,
                    msg=err_note,
                    data_dict=dict(div_content=format_major_error_message(err_note)))
        # technically a 410 error, but we want the JSON message to appear
        return HttpResponse(status=200, content=json_msg, content_type="application/json")


    d = {'ATTRIBUTE_VALUE_DELIMITER' : ATTRIBUTE_VALUE_DELIMITER}

    # --------------------------------------------------------------
    # Is the form valid?
    # --------------------------------------------------------------

    # Load up classification form parameters and validate this request
    #   e.g. Is the classification attribute in the AJAX call actually
    #       part of this layer? etc.
    #
    classify_form = ClassifyLayerForm(\
                        request.POST,
                        **worldmap_layerinfo.get_dict_for_classify_form())

    # --------------------------------------------------------------
    # Invalid forms are status=200 so caught by ajax
    # --------------------------------------------------------------
    if not classify_form.is_valid():    # Oops, not valid (shouldn't happen)
        user_message = ('There was an error with the styling form.'
                        ' Please check the errors below.')
        additional_info = dict(classify_form=classify_form,
                               worldmap_layerinfo=worldmap_layerinfo,
                               error_msg=user_message)
        d.update(additional_info)

        form_content = render_to_string(\
                            'classification/view_classify_form.html',
                            d,
                            request)
        json_msg = MessageHelperJSON.get_json_msg(\
                                success=False,
                                msg=user_message,
                                data_dict={'div_content':form_content})
        return HttpResponse(status=200, content=json_msg, content_type="application/json")

    initial_classify_params = classify_form.get_params_dict_for_classification()
    if initial_classify_params is None:
        LOGGER.error('Failed with *valid* form: classify_form.get_params_dict_for_classification()')
        json_msg = MessageHelperJSON.get_json_msg(success=False,\
            msg='The layer styling form contains errors (code: 2)')
        return HttpResponse(status=200, content=json_msg, content_type="application/json")

    #----------------------------------------------------------
    # Prepare params for classify request against WorldMap API
    #
    #----------------------------------------------------------
    initial_classify_params.update(\
            worldmap_layerinfo.get_params_to_check_for_existing_layer_metadata())

    api_form = ClassifyRequestDataForm(initial_classify_params)
    if not api_form.is_valid():
        err_msg = ('Validation failed with ClassifyRequestDataForm.'
                   'Errors: %s') % api_form.errors
        LOGGER.error(err_msg)
        json_msg = MessageHelperJSON.get_json_msg(\
                        success=False,
                        msg='The layer styling form contains errors (code: 3)')
        return HttpResponse(status=200, content=json_msg, content_type="application/json")


    classify_params = api_form.cleaned_data

    classify_url = classify_form.get_worldmap_classify_api_url()

    LOGGER.debug('classify_params', classify_params)

    resp = None
    try:
        resp = requests.post(classify_url,\
                    data=classify_params,\
                    auth=settings.WORLDMAP_ACCOUNT_AUTH,\
                    timeout=settings.WORLDMAP_DEFAULT_TIMEOUT)

    except requests.exceptions.ConnectionError as exception_obj:
        err_msg = ('<b>Details for administrator:</b>'
                   'Could not contact the Dataverse server: %s')\
                   % (classify_url)

        log_connect_error_message(err_msg, LOGGER, exception_obj)

        json_msg = MessageHelperJSON.get_json_msg(\
                    success=False,
                    msg='Sorry!  The classification failed.<br /><p>%s</p>' % err_msg)

        return HttpResponse(status=200, content=json_msg, content_type="application/json")

    if not resp.status_code == 200:
        try:
            json_resp = resp.json()
        except ValueError:
            error_msg = ('Worldmap classification failed. Status code:'
                         ' %s\nText;%s')\
                         % (resp.status_code, resp.text.encode('utf-8'))

            LOGGER.error(error_msg)

            json_msg = MessageHelperJSON.get_json_msg(\
                            success=False,
                            msg='Sorry!  The classification failed.')
            return HttpResponse(status=200, content=json_msg, content_type="application/json")

        wm_err_msg = json_resp.get('message', None)
        if wm_err_msg is None:
            wm_err_msg = 'No message given.'

        err_msg = 'Sorry!  The classification failed.<p>%s</p>' % wm_err_msg

        json_msg = MessageHelperJSON.get_json_msg(success=False, msg=err_msg)

        return HttpResponse(status=200, content=json_msg, content_type="application/json")


    # RESPONSE CODE IS 200

    # --------------------------------------------------------------
    # convert response to JSON
    # --------------------------------------------------------------
    try:
        json_resp = resp.json()
    except ValueError:
        LOGGER.error('Worldmap response was not valid json: %s',\
                resp.text.encode('utf-8'))
        json_msg = MessageHelperJSON.get_json_msg(success=False,\
            msg='Sorry!  The classification failed.')
        return HttpResponse(status=200,\
            content=json_msg,\
            content_type="application/json")

    # --------------------------------------------------------------
    #   Classification Failed
    # --------------------------------------------------------------
    if not json_resp.get("success") is True:
        LOGGER.info('Worldmap response did not have success==true: %s', resp.text)
        user_msg = 'Sorry!  The classification failed.<br /><br />%s' %\
                    json_resp.get('message', 'nada')
        json_msg = MessageHelperJSON.get_json_msg(success=False, msg=user_msg)
        return HttpResponse(status=200, content=json_msg, content_type="application/json")

    # --------------------------------------------------------------
    #   Validate the response
    # --------------------------------------------------------------
    f_val = WorldMapToGeoconnectMapLayerMetadataValidationForm(json_resp.get('data', None))
    if not f_val.is_valid():
        LOGGER.error('Classify return data failed validation: %s', f_val.errors)
        user_msg = 'Sorry!  The classification failed.<br /><br />%s' \
                        % json_resp.get('message', f_val.errors)
        json_msg = MessageHelperJSON.get_json_msg(success=False, msg=user_msg)
        return HttpResponse(status=200, content=json_msg, content_type="application/json")

    # --------------------------------------------------------------
    #   Looks good, update the WorldMapLayerInfo's attribute info
    # --------------------------------------------------------------
    if hasattr(worldmap_layerinfo, 'add_attribute_info_as_json_string'):
        # handle shapefiles

        worldmap_layerinfo.add_attribute_info_as_json_string(f_val.cleaned_data['attribute_info'])

        worldmap_layerinfo.save()

    elif hasattr(worldmap_layerinfo, 'attribute_data'):
        # handle tabular files

        worldmap_layerinfo.attribute_info =\
            JSONHelper.to_python_or_none(f_val.cleaned_data['attribute_info'])

        worldmap_layerinfo.download_links =\
            JSONHelper.to_python_or_none(f_val.cleaned_data['download_links'])

        worldmap_layerinfo.save()
    else:
        LOGGER.error(dir(worldmap_layerinfo))
        LOGGER.error(type(worldmap_layerinfo))
        LOGGER.error('nada?')

    # --------------------------------------------------------------
    # Refresh the classify form with the latest WorldMap parameter information
    # --------------------------------------------------------------
    classify_form = ClassifyLayerForm(\
                        request.POST,
                        **worldmap_layerinfo.get_dict_for_classify_form())

    # --------------------------------------------------------------
    # Update the Dataverse metadata -- so that the new icon will be refreshed
    # --------------------------------------------------------------

    # Is all this needed, or should there be a
    # Dataverse API call to only update the image?
    MetadataUpdater.run_update_via_popen(worldmap_layerinfo)

    msg_params = classify_form.get_params_for_display()

    success_msg = render_to_string('classification/classify_success_msg.html', msg_params)

    d.update(dict(classify_form=classify_form,
                  success_msg=success_msg,
                  SELECT_LABEL=SELECT_LABEL))

    form_content = render_to_string('classification/view_classify_form.html',
                                    d,
                                    request)


    json_msg = MessageHelperJSON.get_json_msg(\
                    success=True,
                    msg=success_msg, #'Success!'
                    data_dict={'div_content':form_content})

    return HttpResponse(status=200, content=json_msg, content_type="application/json")