Esempio n. 1
0
    def update_dataverse_with_worldmap_info(self):
        """
        Send WorldMap JSON data back to the Dataverse
        """
        print('update_dataverse_with_worldmap_info 1')
        LOGGER.debug("update_dataverse_with_worldmap_info: %s" % self.worldmap_layerinfo  )
        if self.worldmap_layerinfo is None:
            LOGGER.warn("Attempted to send Worldmap info to Dataverse when 'worldmap_layerinfo_object' was None")
            return False

        MetadataUpdater.run_update_via_popen(self.worldmap_layerinfo)
        #try:

        #except:
        #    LOGGER.warn('Error.  Layer created and saved BUT update to dataverse failed')
        #    return False

        return True
Esempio n. 2
0
    def update_dataverse_with_worldmap_info(self):
        """
        Send WorldMap JSON data back to the Dataverse
        """
        print('update_dataverse_with_worldmap_info 1')
        LOGGER.debug("update_dataverse_with_worldmap_info: %s" %
                     self.worldmap_layerinfo)
        if self.worldmap_layerinfo is None:
            LOGGER.warn(
                "Attempted to send Worldmap info to Dataverse when 'worldmap_layerinfo_object' was None"
            )
            return False

        MetadataUpdater.run_update_via_popen(self.worldmap_layerinfo)
        #try:

        #except:
        #    LOGGER.warn('Error.  Layer created and saved BUT update to dataverse failed')
        #    return False

        return True
Esempio n. 3
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. 4
0
def view_shapefile(request, shp_md5, **kwargs):
    """
    (1) Does a map of this shapefile exist in the db?

    (2) Does a map of this shapefile exist in WorldMap?

    (3) Show the initial page with "Visualize" button

    This is fantastically long and messy -- need to break it up

    Retrieve and view a :model:`gis_shapefiles.ShapefileInfo` object

    :shp_md5: unique md5 hash for a :model:`gis_shapefiles.ShapefileInfo`
    :template:`shapefiles/main_outline_shp.html`
    """
    LOGGER.debug('view_shapefile 1')
    # -------------------------------------------
    # Flags for template - Is this the first time the file is being visualized?
    # -------------------------------------------
    first_time_notify = kwargs.get('first_time_notify', False)

    # Attempt to retrieve the shapefile information
    # -------------------------------------------
    LOGGER.debug(
        'view_shapefile 2 - Attempt to retrieve the shapefile information')
    try:
        shapefile_info = ShapefileInfo.objects.get(md5=shp_md5)
    except ShapefileInfo.DoesNotExist:
        raise Http404('Shapefile not found.')

    # -------------------------------------------------------------------
    # Does a fully checked shapefile exist with a worldmap layer?
    # -------------------------------------------------------------------
    LOGGER.debug(
        'view_shapefile 3 - Does a shapefile exist with a worldmap layer?')

    shp_service = SendShapefileService(**dict(shapefile_info=shapefile_info))
    if shp_service.flow1_does_map_already_exist():
        LOGGER.debug('view_shapefile 3a - Map already exists')

        worldmap_layerinfo = shp_service.get_worldmap_layerinfo()
        if worldmap_layerinfo is None:
            return HttpResponse('<br />'.join(shp_service.err_msgs))
        else:
            MetadataUpdater.run_update_via_popen(worldmap_layerinfo)
            return view_classify_shapefile(request, worldmap_layerinfo,
                                           first_time_notify)

    # -------------------------------------------
    # Gather common parameters for the template
    # -------------------------------------------
    d = get_common_lookup(request)
    d['gis_data_info'] = shapefile_info
    d['shapefile_info'] = shapefile_info
    d['page_title'] = PANEL_TITLE_MAP_DATA_FILE
    d['WORLDMAP_SERVER_URL'] = settings.WORLDMAP_SERVER_URL
    d[GEOCONNECT_STEP_KEY] = STEP1_EXAMINE
    if first_time_notify:
        d['first_time_notify'] = True

    # -------------------------------------------
    # Early pass: Validate that this .zip is a shapefile--a single shapefile
    #    - Should we move this out?  Check being done at Dataverse
    #    - Also, no need to move the file if viz already exists
    # -------------------------------------------
    LOGGER.debug('view_shapefile 4 - Validate that .zip is a single shapefile')
    if not shapefile_info.zipfile_checked:
        LOGGER.debug('zipfile_checked NOT checked')

        zip_checker = ShapefileZipCheck(shapefile_info.dv_file,
                                        **{'is_django_file_field': True})
        #zip_checker = ShapefileZipCheck(shapefile_info.get_dv_file_fullpath())
        zip_checker.validate()

        # -----------------------------
        # Error: No shapefiles found
        #   Show error message
        # -----------------------------
        if zip_checker.has_err:
            return view_zip_checker_error(request, shapefile_info, zip_checker,
                                          d)

        # -----------------------------
        # Load the single shapefile
        # -----------------------------

        shapefile_info.has_shapefile = True
        shapefile_info.zipfile_checked = True
        shapefile_info.save()

        list_of_shapefile_set_names = zip_checker.get_shapefile_setnames()
        success = zip_checker.load_shapefile_from_open_zip(
            list_of_shapefile_set_names[0], shapefile_info)

        if not success:
            d['Err_Found'] = True
            if zip_checker.err_type == ZIPCHECK_FAILED_TO_PROCCESS_SHAPEFILE:
                d['Err_Shapefile_Could_Not_Be_Opened'] = True
                d['zip_name_list'] = zip_checker.get_zipfile_names()
            else:
                d['Err_Msg'] = zip_checker.err_msg

            shapefile_info.has_shapefile = False
            shapefile_info.save()
            LOGGER.error('Shapefile not loaded. (%s)' % shp_md5)
            zip_checker.close_zip()
            return render(request, 'shapefiles/main_outline_shp.html', d)

    # -------------------------------------------
    # The examination failed
    # No shapefile was found in this .zip
    # -------------------------------------------
    LOGGER.debug('view_shapefile 5 - No shapefile was found in this .zip')
    if not shapefile_info.has_shapefile:
        LOGGER.debug('No shapefile found in .zip')

        d['Err_Found'] = True
        d['Err_No_Shapefiles_Found'] = True
        d['WORLDMAP_MANDATORY_IMPORT_EXTENSIONS'] = WORLDMAP_MANDATORY_IMPORT_EXTENSIONS
        return render(request, 'shapefiles/main_outline_shp.html', d)

    # -------------------------------------------------------------------
    # Shapefile fully checked, is there a worldmap layer?
    # -------------------------------------------------------------------
    LOGGER.debug(
        'view_shapefile 6 - Shapefile fully checked, is there a worldmap layer? '
    )
    shp_service = SendShapefileService(**dict(shapefile_info=shapefile_info))

    if shp_service.flow1_does_map_already_exist():
        LOGGER.debug('view_shapefile 6a - Worldmap layer exists')

        worldmap_layerinfo = shp_service.get_worldmap_layerinfo()
        if worldmap_layerinfo is None:
            return HttpResponse('<br />'.join(shp_service.err_msgs))
        else:
            MetadataUpdater.run_update_via_popen(worldmap_layerinfo)
            return view_classify_shapefile(request, worldmap_layerinfo,
                                           first_time_notify)

    return render(request, 'shapefiles/main_outline_shp.html', d)
Esempio n. 5
0
def view_shapefile(request, shp_md5, **kwargs):
    """
    (1) Does a map of this shapefile exist in the db?

    (2) Does a map of this shapefile exist in WorldMap?

    (3) Show the initial page with "Visualize" button

    This is fantastically long and messy -- need to break it up

    Retrieve and view a :model:`gis_shapefiles.ShapefileInfo` object

    :shp_md5: unique md5 hash for a :model:`gis_shapefiles.ShapefileInfo`
    :template:`shapefiles/main_outline_shp.html`
    """
    LOGGER.debug('view_shapefile 1')
    # -------------------------------------------
    # Flags for template - Is this the first time the file is being visualized?
    # -------------------------------------------
    first_time_notify = kwargs.get('first_time_notify', False)

    # Attempt to retrieve the shapefile information
    # -------------------------------------------
    LOGGER.debug('view_shapefile 2 - Attempt to retrieve the shapefile information')
    try:
        shapefile_info = ShapefileInfo.objects.get(md5=shp_md5)
    except ShapefileInfo.DoesNotExist:
        raise Http404('Shapefile not found.')

    # -------------------------------------------------------------------
    # Does a fully checked shapefile exist with a worldmap layer?
    # -------------------------------------------------------------------
    LOGGER.debug('view_shapefile 3 - Does a shapefile exist with a worldmap layer?')

    shp_service = SendShapefileService(**dict(shapefile_info=shapefile_info))
    if shp_service.flow1_does_map_already_exist():
        LOGGER.debug('view_shapefile 3a - Map already exists')

        worldmap_layerinfo = shp_service.get_worldmap_layerinfo()
        if worldmap_layerinfo is None:
            return HttpResponse('<br />'.join(shp_service.err_msgs))
        else:
            MetadataUpdater.run_update_via_popen(worldmap_layerinfo)
            return view_classify_shapefile(request, worldmap_layerinfo, first_time_notify)

    # -------------------------------------------
    # Gather common parameters for the template
    # -------------------------------------------
    d = get_common_lookup(request)
    d['gis_data_info'] = shapefile_info
    d['shapefile_info'] = shapefile_info
    d['page_title'] = PANEL_TITLE_MAP_DATA_FILE
    d['WORLDMAP_SERVER_URL'] = settings.WORLDMAP_SERVER_URL
    d[GEOCONNECT_STEP_KEY] = STEP1_EXAMINE
    if first_time_notify:
        d['first_time_notify'] = True

    # -------------------------------------------
    # Early pass: Validate that this .zip is a shapefile--a single shapefile
    #    - Should we move this out?  Check being done at Dataverse
    #    - Also, no need to move the file if viz already exists
    # -------------------------------------------
    LOGGER.debug('view_shapefile 4 - Validate that .zip is a single shapefile')
    if not shapefile_info.zipfile_checked:
        LOGGER.debug('zipfile_checked NOT checked')

        zip_checker = ShapefileZipCheck(shapefile_info.dv_file, **{'is_django_file_field': True})
        #zip_checker = ShapefileZipCheck(shapefile_info.get_dv_file_fullpath())
        zip_checker.validate()

        # -----------------------------
        # Error: No shapefiles found
        #   Show error message
        # -----------------------------
        if zip_checker.has_err:
            return view_zip_checker_error(request, shapefile_info, zip_checker, d)

        # -----------------------------
        # Load the single shapefile
        # -----------------------------

        shapefile_info.has_shapefile = True
        shapefile_info.zipfile_checked = True
        shapefile_info.save()

        list_of_shapefile_set_names = zip_checker.get_shapefile_setnames()
        success = zip_checker.load_shapefile_from_open_zip(list_of_shapefile_set_names[0], shapefile_info)

        if not success:
            d['Err_Found'] = True
            if zip_checker.err_type == ZIPCHECK_FAILED_TO_PROCCESS_SHAPEFILE:
                d['Err_Shapefile_Could_Not_Be_Opened'] = True
                d['zip_name_list'] = zip_checker.get_zipfile_names()
            else:
                d['Err_Msg'] = zip_checker.err_msg

            shapefile_info.has_shapefile = False
            shapefile_info.save()
            LOGGER.error('Shapefile not loaded. (%s)' % shp_md5)
            zip_checker.close_zip()
            return render(request, 'shapefiles/main_outline_shp.html', d)

    # -------------------------------------------
    # The examination failed
    # No shapefile was found in this .zip
    # -------------------------------------------
    LOGGER.debug('view_shapefile 5 - No shapefile was found in this .zip')
    if not shapefile_info.has_shapefile:
        LOGGER.debug('No shapefile found in .zip')

        d['Err_Found'] = True
        d['Err_No_Shapefiles_Found'] = True
        d['WORLDMAP_MANDATORY_IMPORT_EXTENSIONS'] = WORLDMAP_MANDATORY_IMPORT_EXTENSIONS
        return render(request, 'shapefiles/main_outline_shp.html', d)

    # -------------------------------------------------------------------
    # Shapefile fully checked, is there a worldmap layer?
    # -------------------------------------------------------------------
    LOGGER.debug('view_shapefile 6 - Shapefile fully checked, is there a worldmap layer? ')
    shp_service = SendShapefileService(**dict(shapefile_info=shapefile_info))

    if shp_service.flow1_does_map_already_exist():
        LOGGER.debug('view_shapefile 6a - Worldmap layer exists')

        worldmap_layerinfo = shp_service.get_worldmap_layerinfo()
        if worldmap_layerinfo is None:
            return HttpResponse('<br />'.join(shp_service.err_msgs))
        else:
            MetadataUpdater.run_update_via_popen(worldmap_layerinfo)
            return view_classify_shapefile(request, worldmap_layerinfo, first_time_notify)

    return render(request, 'shapefiles/main_outline_shp.html', d)
Esempio n. 6
0
def view_map_tabular_file_form(request):
    """
    AJAX call: Join your tabular file to an existing WorldMap layer
    using the column selected in this form
    """
    #for k, v in request.POST.items():
    #        print k, v

    # -----------------------------------------
    # Retrieve the id of the Tabular info object
    # -----------------------------------------
    tabular_file_info_id = request.POST.get('tabular_file_info_id', -1)

    try:
        tabular_info = TabularFileInfo.objects.get(pk=tabular_file_info_id)
    except TabularFileInfo.DoesNotExist:
        err_msg = 'Sorry! The Tabular File was not found. (tabular_file_info_id)'
        json_msg = MessageHelperJSON.get_json_fail_msg(err_msg)
        return HttpResponse(json_msg,
                            content_type="application/json",
                            status=200)
        #raise Http404('No TabularFileInfo for id: %s' % tabular_file_info_id)

    # -----------------------------------------
    # Retrieve available Geocode types and join Layers
    #   note: geocode_types_from_worldmap not needed here
    # -----------------------------------------
    (geocode_types_from_worldmap,
     available_layers_list) = get_geocode_types_and_join_layers()

    # -----------------------------------------
    # Create form with initial + POST data
    # -----------------------------------------
    form_single_column = ChooseSingleColumnForm(tabular_info.id,\
                    available_layers_list,\
                    tabular_info.column_names,\
                    request.POST)

    # -----------------------------------------
    # Check the form's validity
    # -----------------------------------------
    if not form_single_column.is_valid():
        json_msg = MessageHelperJSON.get_json_fail_msg(\
                        format_errors_as_text(form_single_column, for_web=True))
        return HttpResponse(json_msg,
                            content_type="application/json",
                            status=200)

    #print 'cleaned_data', form_single_column.cleaned_data

    # -----------------------------------------
    # Get Dataverse info dict
    # -----------------------------------------
    dataverse_metadata_dict = get_dataverse_info_dict(tabular_info)

    # -----------------------------------------
    # Use the WorldMap API and
    # try to create a layer
    # -----------------------------------------
    tj_map_maker = TableJoinMapMaker(
        tabular_info,
        dataverse_metadata_dict,
        form_single_column.cleaned_data.get('chosen_column'),
        form_single_column.cleaned_data.get('chosen_layer'),
    )
    success = tj_map_maker.run_map_create()
    msg('success: %s' % success)
    if not success:
        json_msg = MessageHelperJSON.get_json_fail_msg(\
                    'Sorry! ' + tj_map_maker.get_error_msg())
        msg('error msg: %s' % json_msg)
        return HttpResponse(json_msg,
                            content_type="application/json",
                            status=200)

    # -----------------------------------------
    # Succeeded!  Create a WorldMapTabularLayerInfo object
    # -----------------------------------------
    worldmap_tabular_info = WorldMapTabularLayerInfo.build_from_worldmap_json(tabular_info,\
                                tj_map_maker.get_map_info())

    if worldmap_tabular_info is None:
        LOGGER.error("Failed to create WorldMapTabularLayerInfo using %s",\
            tj_map_maker.get_map_info())
        user_msg = 'Sorry! Failed to create map. Please try again. (code: s1)'
        json_msg = MessageHelperJSON.get_json_fail_msg(user_msg)
        return HttpResponse(json_msg,
                            content_type="application/json",
                            status=200)

    # -----------------------------------------
    # Notify Dataverse of the new map
    # -----------------------------------------
    MetadataUpdater.run_update_via_popen(worldmap_tabular_info)

    # -----------------------------------------
    # Build the Map HTML chunk to replace the form
    # -----------------------------------------
    map_html, user_message_html = build_map_html(request,
                                                 worldmap_tabular_info)
    if map_html is None:  # Failed!  Send an error
        LOGGER.error("Failed to create map HTML using WorldMapTabularLayerInfo: %s (%d)",\
            worldmap_tabular_info, worldmap_tabular_info.id)
        user_msg = 'Sorry! Failed to create map. Please try again. (code: s2)'
        json_msg = MessageHelperJSON.get_json_fail_msg(user_msg)
        return HttpResponse(json_msg,
                            content_type="application/json",
                            status=200)

    # -----------------------------------------
    # Looks good.  In the JSON response, send
    #   back the map HTML
    # -----------------------------------------
    data_dict = dict(map_html=map_html,
                     user_message_html=user_message_html,
                     id_main_panel_title=PANEL_TITLE_STYLE_MAP)

    json_msg = MessageHelperJSON.get_json_success_msg("great job",
                                                      data_dict=data_dict)

    return HttpResponse(json_msg, content_type="application/json", status=200)
Esempio n. 7
0
def view_process_lat_lng_form(request):
    """
    Create a WorldMap layer from your tabular file
    using the latitude and longitude columns selected in this form
    """

    tabular_file_info_id = request.POST.get('tabular_file_info_id', -1)

    try:
        tabular_info = TabularFileInfo.objects.get(pk=tabular_file_info_id)
    except TabularFileInfo.DoesNotExist:
        err_msg = 'Sorry! The Tabular File was not found. (tabular_file_info_id)'
        json_msg = MessageHelperJSON.get_json_fail_msg(err_msg)
        return HttpResponse(json_msg,
                            content_type="application/json",
                            status=200)
        #raise Http404('No TabularFileInfo for id: %s' % tabular_file_info_id)

    form_lat_lng = LatLngColumnsForm(tabular_info.id,\
                        tabular_info.column_names,\
                        request.POST)
    if not form_lat_lng.is_valid():
        json_msg = MessageHelperJSON.get_json_fail_msg(\
                    format_errors_as_text(form_lat_lng,\
                                        for_web=True)\
                                    )
        #json_msg = MessageHelperJSON.get_json_fail_msg(f.err_msg_for_web)
        return HttpResponse(json_msg,
                            content_type="application/json",
                            status=200)


    (success, worldmap_data_or_err_msg) = create_map_from_datatable_lat_lng(\
                        tabular_info,\
                        form_lat_lng.get_latitude_colname(),\
                        form_lat_lng.get_longitude_colname(),\
                        )

    # -----------------------------------------
    # Failed! Send error message
    # -----------------------------------------
    if not success:
        json_msg = MessageHelperJSON.get_json_fail_msg(\
                'Sorry! ' + worldmap_data_or_err_msg)
        return HttpResponse(json_msg,
                            content_type="application/json",
                            status=200)

    # -----------------------------------------
    # Succeeded!  Create a WorldMapTabularLayerInfo object
    # -----------------------------------------
    user_msg, response_data = worldmap_data_or_err_msg
    #json_msg = MessageHelperJSON.get_json_success_msg(user_msg, data_dict=response_data)
    #return HttpResponse(json_msg, content_type="application/json", status=200)

    worldmap_latlng_info = WorldMapTabularLayerInfo.build_from_worldmap_json(tabular_info,\
                            response_data)

    if worldmap_latlng_info is None:
        LOGGER.error("Failed to create WorldMapLatLngInfo using data: %s",\
                    response_data)
        user_msg = 'Sorry! Failed to create map. Please try again. (code: s4)'
        json_msg = MessageHelperJSON.get_json_fail_msg(user_msg)
        return HttpResponse(json_msg,
                            content_type="application/json",
                            status=200)

    # -----------------------------------------
    # Notify Dataverse of the new map
    # -----------------------------------------
    MetadataUpdater.run_update_via_popen(worldmap_latlng_info)

    # -----------------------------------------
    # Possible that this failed?
    # Make sure at least 1 row mapped
    # -----------------------------------------
    # Skip for now!  Error in row counts for Lat/Lng!
    """
    if worldmap_latlng_info.did_any_rows_map() is False:
        # Delete the worldmap_latlng_info object
        worldmap_latlng_info.delete()

        # Send back a user error message
        user_msg = "Sorry!  We couldn't map any of those latitude and longitude values."
        return HttpResponse(MessageHelperJSON.get_json_fail_msg(user_msg),\
                content_type="application/json",\
                status=200)
    """
    # -----------------------------------------
    # Build the Map HTML chunk to replace the form
    # -----------------------------------------
    map_html, user_message_html = build_map_html(request, worldmap_latlng_info)
    if map_html is None:  # Failed!  Send an error
        LOGGER.error("Failed to create map HTML using WorldMapLatLngInfo: %s (%d)",\
            worldmap_latlng_info, worldmap_latlng_info.id)
        user_msg = 'Sorry! Failed to create map. Please try again. (code: s5)'
        json_msg = MessageHelperJSON.get_json_fail_msg(user_msg)
        return HttpResponse(json_msg,
                            content_type="application/json",
                            status=200)

    # -----------------------------------------
    # Looks good.  In the JSON response, send
    #   back the map HTML
    # -----------------------------------------
    data_dict = dict(map_html=map_html,
                     user_message_html=user_message_html,
                     id_main_panel_title=PANEL_TITLE_STYLE_MAP)

    json_msg = MessageHelperJSON.get_json_success_msg("great job",
                                                      data_dict=data_dict)

    return HttpResponse(json_msg, content_type="application/json", status=200)
Esempio n. 8
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")