Exemplo n.º 1
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")
Exemplo n.º 2
0
    def delete_metadata_from_dataverse(self, worldmap_layer_info):
        """
        Delete map layer metadata from the Dataverse

        returns (True, None)
            or (False, 'error message of some type')
        """
        MetadataUpdater.check_for_required_methods(worldmap_layer_info)


        params = worldmap_layer_info.get_params_for_dv_delete_layer_metadata()
        api_delete_metadata_url = get_api_url_delete_metadata(self.dataverse_server_url)


        LOGGER.debug('params to send: %s', params)
        LOGGER.debug('update url: %s', api_delete_metadata_url)
        LOGGER.debug('payload: %s', json.dumps(params))

        req = None
        try:
            req = requests.post(api_delete_metadata_url,\
                    data=json.dumps(params),\
                    timeout=self.timeout_seconds)
        except requests.exceptions.Timeout:
            return (False, 'This request timed out.  (Time limit: %s seconds(s))'\
                % self.timeout_seconds)

        except requests.exceptions.ConnectionError as exception_obj:
            err_msg = ('%s %s') % (ERROR_DV_NO_SERVER_RESPONSE, api_delete_metadata_url)

            log_connect_error_message(err_msg, LOGGER, exception_obj)

            return (False, err_msg)


        #msgt('status code/text: %s/%s' % (\
        #                        req.status_code,
        #                        req.text.encode('utf-8'))

        if req.status_code == 404:
            return (False,\
                    '%s %s' % (ERROR_DV_PAGE_NOT_FOUND, api_delete_metadata_url))

        if req.status_code == 200:
            return (True, None)# 'Delete success')

        else:
            # See if an error message was sent back...
            error_msg = None
            try:
                dv_response_dict = req.json()
                if dv_response_dict.has_key('message'):
                    error_msg = dv_response_dict['message']
            except ValueError:
                LOGGER.error('Metadata update failed.  Status code: %s\nResponse:%s',\
                    req.status_code, req.text.encode('utf-8'))

            if error_msg is None:
                error_msg = 'Sorry! The update failed.'

            LOGGER.error('Status code: %s\nError message:%s',\
                req.status_code, error_msg)

            return (False, error_msg)
Exemplo n.º 3
0
    def send_info_to_dataverse(self, worldmap_layer_info):
        """
        Go through the process of sending params to dataverse
        :param dv_metadata_params: python dict used to POST to dataverse
        :returns: JSON with "success" flag and either error or data
        :rtype: JSON string
        """
        MetadataUpdater.check_for_required_methods(worldmap_layer_info)

        dv_metadata_params = worldmap_layer_info.get_params_for_dv_update()
        self.update_embed_link_for_https(dv_metadata_params)

        #print ('dv_metadata_params', dv_metadata_params)

        # FIXME: temp fix for DV error
        # Make joinDescription an empty String instead of None
        if dv_metadata_params.get('joinDescription', None) is None:
            dv_metadata_params['joinDescription'] = ''

        api_update_url = get_api_url_update_map_metadata(self.dataverse_server_url)

        #print ('params to send: %s' % dv_metadata_params)
        #print ('-' * 40)
        print ('update url: %s' % api_update_url)
        #print ('-' * 40)
        #print ('payload: %s' % json.dumps(dv_metadata_params))
        #print ('-' * 40)

        req = None
        try:
            req = requests.post(api_update_url,\
                data=json.dumps(dv_metadata_params),\
                timeout=self.timeout_seconds)
        except requests.exceptions.Timeout:
            return self.get_result_msg(False,\
                'This request timed out.  (Time limit: %s seconds(s))'\
                % self.timeout_seconds)

        except requests.exceptions.ConnectionError as exception_obj:

            err_msg = ('%s %s') % (ERROR_DV_NO_SERVER_RESPONSE, api_update_url)

            log_connect_error_message(err_msg, LOGGER, exception_obj)

            return self.get_result_msg(False, err_msg)


        if req.status_code == 404:

            LOGGER.error('Metadata update failed.  Page not found: %s',\
                api_update_url)

            return self.get_result_msg(\
                    False,
                    '%s %s' % (ERROR_DV_PAGE_NOT_FOUND, api_update_url))

        elif not req.status_code == 200:

            # See if an error message was sent back...
            error_msg = None
            try:
                dv_response_dict = req.json()
                if dv_response_dict.has_key('message'):
                    error_msg = dv_response_dict['message']
            except:
                LOGGER.error('Metadata update failed.  Status code: %s\nResponse:%s',\
                    req.status_code, req.text.encode('utf-8'))

            if error_msg is None:
                error_msg = '%s (status code: %s)<br />endpoint: %s' % (\
                                ERROR_DV_METADATA_UPDATE,
                                req.status_code,
                                api_update_url)

            return self.get_result_msg(False, error_msg)

        dv_response_dict = req.json()

        if dv_response_dict.get('status', False) in ('OK', 'success'):
            dv_response_dict.pop('status')
            #print('4) send result')
            return self.get_result_msg(True, '', data_dict=dv_response_dict)

        elif dv_response_dict.has_key('message'):
            return self.get_result_msg(False, dv_response_dict['message'])
        else:
            return self.get_result_msg(False, 'The import failed for an unknown reason')
Exemplo n.º 4
0
    def make_callback(self):
        """Make callback via a POST request"""

        if self.has_err:
            return False

        # Prepare data for request
        #
        token_data = {settings.DATAVERSE_TOKEN_KEYNAME : self.dataverse_token}

        # Make the request
        #
        try:
            r = requests.post(self.callback_url, data=json.dumps(token_data))
        except requests.exceptions.ConnectionError as exception_obj:

            err_msg = ('<p><b>Details for administrator:</b>'
                      ' Could not contact the Dataverse server:'
                      ' {0}</p>').format(self.callback_url)

            self.add_err_msg(err_msg, FAILED_TO_RETRIEVE_DATAVERSE_FILE)

            log_connect_error_message(err_msg, LOGGER, exception_obj)

            return False


        # ------------------------------
        # Check for valid status code
        # ------------------------------
        if not r.status_code == 200:
            err_msg1 = 'Status code from dataverse: %s' % (r.status_code)
            #err_msg2 = err_msg1 + '\nResponse: %s' % (r.text)
            self.add_err_msg(err_msg1, FAILED_BAD_STATUS_CODE_FROM_WORLDMAP)
            return False

        # ------------------------------
        # Attempt to convert response to JSON
        # ------------------------------
        try:
            jresp = r.json()
        except ValueError:
            err_msg1 = ('Failed to convert response to JSON\n'\
                        'Status code from dataverse: %s') % (r.status_code)
            #err_msg2 = err_msg1 + '\nResponse: %s' % (r.text)
            #LOGGER.error(err_msg2)
            self.add_err_msg(err_msg1, FAILED_TO_CONVERT_RESPONSE_TO_JSON)
            return False

        # ------------------------------
        # Examine response
        #
        # (1) Identify the mapping type
        # (2) Send the file through the appropriate path
        #   - e.g. shapefile, tabular file, etc.
        # ------------------------------

        # status of "OK" or "success"?
        #
        if not (jresp.has_key('status') and jresp['status'] in ['OK', 'success']):
            self.add_err_msg('Failed to retrieve Dataverse data. (status was not "OK")')
            return False

        # Contains "data" key (good use JSON schema in future)
        #
        self.dv_data_dict = jresp.get('data', None)
        #import ipdb; ipdb.set_trace()
        if self.dv_data_dict is None:
            self.add_err_msg('Dataverse data did not contain key: "data"')
            return False

        return True
Exemplo n.º 5
0
    def make_callback(self):
        """Make callback via a POST request"""

        if self.has_err:
            return False

        # Prepare data for request
        #
        token_data = {settings.DATAVERSE_TOKEN_KEYNAME: self.dataverse_token}

        # Make the request
        #
        try:
            r = requests.post(self.callback_url, data=json.dumps(token_data))
        except requests.exceptions.ConnectionError as exception_obj:

            err_msg = ('<p><b>Details for administrator:</b>'
                       ' Could not contact the Dataverse server:'
                       ' {0}</p>').format(self.callback_url)

            self.add_err_msg(err_msg, FAILED_TO_RETRIEVE_DATAVERSE_FILE)

            log_connect_error_message(err_msg, LOGGER, exception_obj)

            return False

        # ------------------------------
        # Check for valid status code
        # ------------------------------
        if not r.status_code == 200:
            err_msg1 = 'Status code from dataverse: %s' % (r.status_code)
            #err_msg2 = err_msg1 + '\nResponse: %s' % (r.text)
            self.add_err_msg(err_msg1, FAILED_BAD_STATUS_CODE_FROM_WORLDMAP)
            return False

        # ------------------------------
        # Attempt to convert response to JSON
        # ------------------------------
        try:
            jresp = r.json()
        except ValueError:
            err_msg1 = ('Failed to convert response to JSON\n'\
                        'Status code from dataverse: %s') % (r.status_code)
            #err_msg2 = err_msg1 + '\nResponse: %s' % (r.text)
            #LOGGER.error(err_msg2)
            self.add_err_msg(err_msg1, FAILED_TO_CONVERT_RESPONSE_TO_JSON)
            return False

        # ------------------------------
        # Examine response
        #
        # (1) Identify the mapping type
        # (2) Send the file through the appropriate path
        #   - e.g. shapefile, tabular file, etc.
        # ------------------------------

        # status of "OK" or "success"?
        #
        if not (jresp.has_key('status')
                and jresp['status'] in ['OK', 'success']):
            self.add_err_msg(
                'Failed to retrieve Dataverse data. (status was not "OK")')
            return False

        # Contains "data" key (good use JSON schema in future)
        #
        self.dv_data_dict = jresp.get('data', None)
        #import ipdb; ipdb.set_trace()
        if self.dv_data_dict is None:
            self.add_err_msg('Dataverse data did not contain key: "data"')
            return False

        return True
Exemplo n.º 6
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")