Ejemplo n.º 1
0
def dvn_import(request):
    if request.POST:
        user = None
        title = request.POST["title"]
        abstract = request.POST["abstract"]
        email = request.POST["email"]
        content = request.FILES.values()[0]
        name = request.POST["shapefile_name"]
        token = request.POST["geoconnect_token"]
        keywords = "" if "keywords" not in request.POST else request.POST["keywords"]

        if token != settings.DVN_TOKEN:
            return HttpResponse(status=401, content=json.dumps({
                "success": False,
                "errormsgs": "Invalid token %s" % token}))

        if "worldmap_username" in request.POST:
            try:
                user = User.objects.get(username=request.POST["username"])
            except:
                pass

        if user is None:
            existing_user = User.objects.filter(email=email)
            if existing_user.count() > 0:
                user = existing_user[0]
            else:
                user = _create_new_user(email, None, None, None)

        if not user:
            return HttpResponse(status=500, content=json.dumps({"success" : False,
                    "errormsgs": "A user account could not be created for email %s" % email}))
        else:
            name = slugify(name.replace(".","_"))
            file = write_file(content)
            try:
                saved_layer = save(name, file, user,
                               overwrite = False,
                               abstract = abstract,
                               title = title,
                               keywords = keywords.split()
                )
                return HttpResponse(status=200, content=json.dumps({
                    "success": True,
                    "layer_name": saved_layer.typename,
                    "layer_link": "%sdata/%s" % (settings.SITEURL, saved_layer.service_typename),
                    "embed_map_link": "%smaps/embed/?layer=%s" % (settings.SITEURL, saved_layer.service_typename),
                    "worldmap_username": user.username
                }))

            except Exception, e:
                logger.error("Unexpected error during dvn import: %s : %s", name, escape(str(e)))
                return HttpResponse(json.dumps({
                    "success": False,
                    "errormsgs": ["Unexpected error during upload: %s" %  escape(str(e))]}))
Ejemplo n.º 2
0
def dvn_import(request):

    if not has_proper_auth(request):
        json_msg = MessageHelperJSON.get_json_msg(success=False, msg="Authentication failed.")
        return HttpResponse(status=401, content=json_msg, content_type="application/json")
    
    if request.POST:
        user = None
        title = request.POST["title"]
        abstract = request.POST["abstract"]
        email = request.POST["email"]
        content = request.FILES.values()[0]
        name = request.POST["shapefile_name"]
        #dataverse_info = request.POST.get('dataverse_info', None)
        keywords = "" if "keywords" not in request.POST else request.POST["keywords"]

        #print request.POST.items()

        if "worldmap_username" in request.POST:
            try:
                user = User.objects.get(username=request.POST["username"])
            except:
                pass

        if user is None:
            existing_user = User.objects.filter(email=email)
            if existing_user.count() > 0:
                user = existing_user[0]
            else:
                user = _create_new_user(email, None, None, None)

        if not user:
            json_msg = MessageHelperJSON.get_json_msg(success=False, msg="A user account could not be created for email %s" % email)
            return HttpResponse(status=200, content=json_msg, content_type="application/json")
            
        else:
            name = slugify(name.replace(".","_"))
            file_obj = write_file(content)
            try:
                
                # Save the actual layer
                saved_layer = save(name, file_obj, user,
                               overwrite = False,
                               abstract = abstract,
                               title = title,
                               keywords = keywords.split()
                )

                # Look for DataverseInfo in the request.POST
                #   If it exists, create a DataverseLayerMetadata object
                #
                add_dataverse_layer_metadata(saved_layer, request.POST)

                # Prepare a JSON reponse
                # 
                layer_metadata_obj = LayerMetadata(**{ 'geonode_layer_object' : saved_layer})

                # Return the response!
                json_msg = MessageHelperJSON.get_json_msg(success=True, msg='worked', data_dict=layer_metadata_obj.get_metadata_dict())
                #print '-' * 40
                #print 'json_msg', json_msg
                return HttpResponse(status=200, content=json_msg, content_type="application/json")
                """
                return HttpResponse(status=200, content=json.dumps({
                    "success": True,
                    "layer_name": saved_layer.typename,
                    "layer_link": "%sdata/%s" % (settings.SITEURL, saved_layer.typename),
                    "embed_map_link": "%smaps/embed/?layer=%s" % (settings.SITEURL, saved_layer.typename),
                    "worldmap_username": user.username
                }))
                """
            
            except:
                e = sys.exc_info()[0]
                logger.error("Unexpected error during dvn import: %s : %s" % (name, escape(str(e))))
                err_msg = "Unexpected error during upload: %s" %  escape(str(e))
                json_msg = MessageHelperJSON.get_json_msg(success=False, msg=err_msg)
                return HttpResponse(content=json_msg, content_type="application/json")
            
    else:
        json_msg = MessageHelperJSON.get_json_msg(success=False, msg="Requests must be POST not GET")
        return HttpResponse(status=401, content=json_msg, content_type="application/json")
Ejemplo n.º 3
0
def view_add_worldmap_shapefile(request):
    """
    Process a Dataverse POST request to create a Layer with an accompanying LayerMetadata object
    """
    #   Is this request a POST?
    #
    if not request.POST:
        json_msg = MessageHelperJSON.get_json_msg(\
                            success=False,
                            msg="The request must be a POST.")
        return HttpResponse(status=401,
                            content=json_msg,
                            content_type="application/json")

    #   Does the request have proper auth?
    #   -> check is now done by the ShapefileImportDataForm

    #   Is there a file in this request
    #
    if (not request.FILES) or len(request.FILES) == 0:
        LOGGER.error("Shapefile import error.  No FILES in request")
        json_msg = MessageHelperJSON.get_json_msg(success=False\
                                , msg="File not found.  Did you send a file?")

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

    if not len(request.FILES) == 1:
        LOGGER.error("Shapefile import error.  Only send 1 file")
        json_msg = MessageHelperJSON.get_json_msg(\
                                success=False,
                                msg="This request only accepts a single file")

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

    Post_Data_As_Dict = request.POST.dict()

    #   Is this a valid request?  Check parameters.
    #
    form_shapefile_import = ShapefileImportDataForm(Post_Data_As_Dict)
    if not form_shapefile_import.is_valid():
        #
        #   Invalid, send back an error message
        #
        LOGGER.error("Shapefile import error: \n%s",\
                     format_errors_as_text(form_shapefile_import))
        json_msg = MessageHelperJSON.get_json_msg(\
                    success=False,
                    msg=('Incorrect params for ShapefileImportDataForm:'
                         ' <br />%s') % form_shapefile_import.errors)

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

    #-----------------------------------------------------------
    #   start: check for existing layer
    #   Does a layer already exist for this file?
    #   Check for an existing DataverseLayerMetadata object.
    #-----------------------------------------------------------
    existing_dv_layer_metadata = None
    LOGGER.info("pre existing layer check")
    try:
        existing_dv_layer_metadata = check_for_existing_layer(
            Post_Data_As_Dict)
        LOGGER.info("found existing layer")
    except ValidationError as e:
        error_msg = "The dataverse information failed validation: %s" % Post_Data_As_Dict
        LOGGER.error(error_msg)

        json_msg = MessageHelperJSON.get_json_msg(\
                        success=False,
                        msg="(The WorldMap could not verify the data.)")

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

    #-----------------------------------------------------------
    #   end: check for existing layer
    #   A layer was found!
    #   Update the DataverseLayerMetadata and return the layer.
    #   * Update the worldmap user? *
    #-----------------------------------------------------------
    if existing_dv_layer_metadata:
        LOGGER.info("Found existing layer!")

        update_the_layer_metadata(existing_dv_layer_metadata,
                                  Post_Data_As_Dict)

        layer_metadata_obj = LayerMetadata(
            existing_dv_layer_metadata.map_layer)

        json_msg = MessageHelperJSON.get_json_msg(\
                            success=True,
                            msg='worked',
                            data_dict=layer_metadata_obj.get_metadata_dict())
        return HttpResponse(status=200,
                            content=json_msg,
                            content_type="application/json")

    #
    #   Using the ShapefileImportDataForm,
    #   get/set the attributes needed to create a layer
    #
    import_data = form_shapefile_import.cleaned_data

    title = import_data['title']
    abstract = import_data['abstract']
    dv_user_email = import_data['dv_user_email']
    worldmap_username = import_data['worldmap_username']
    shapefile_name = import_data['shapefile_name']
    keywords = import_data['keywords']

    transferred_file = request.FILES.values()[0]

    # Retrieve or create a User object
    #  2/2016 - Changed.  Use the user who made the API call to this method
    #
    user_object = request.user

    #   Format file name and save actual file
    #
    shapefile_name = slugify(shapefile_name.replace(".", "_"))
    file_obj = write_the_dataverse_file(transferred_file)
    #print ('file_obj', file_obj)

    # ------------------------------------------
    #   Save the actual layer
    # ------------------------------------------

    # Truncate name.  Note the 'save method' checks for name clashes and appends
    #   a random string at the end
    new_layer_name = shapefile_name[:10]
    try:
        saved_layer = save(new_layer_name,
                           file_obj,
                           user_object,
                           overwrite=False,
                           abstract=abstract,
                           title=title,
                           keywords=keywords.split())

        # ------------------------------------------
        # Look for DataverseInfo in the Post_Data_As_Dict
        #   If it exists, create a DataverseLayerMetadata object
        # ------------------------------------------
        dataverse_layer_metadata = add_dataverse_layer_metadata(\
                                        saved_layer, Post_Data_As_Dict)

        if dataverse_layer_metadata is None:
            LOGGER.error("Failed to create a DataverseLayerMetadata object")
            json_msg = MessageHelperJSON.get_json_msg(\
                            success=False,
                            msg="Failed to create a DataverseLayerMetadata object")

            # remove the layer
            #
            if saved_layer:
                saved_layer.delete()

            # Error
            return HttpResponse(status=400,
                                content=json_msg,
                                content_type="application/json")

        # Prepare a JSON response
        #
        layer_metadata_obj = LayerMetadata(saved_layer)

        # Return the response!
        json_msg = MessageHelperJSON.get_json_msg(\
                        success=True,
                        msg='Shapefile successfully imported',
                        data_dict=layer_metadata_obj.get_metadata_dict())
        #print '-' * 40
        #print 'json_msg', json_msg

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

    except:
        e = sys.exc_info()[0]
        LOGGER.error("Unexpected error during dvn import: %s : %s",\
                     shapefile_name, escape(str(e)))
        err_msg = "Unexpected error during upload: %s" % escape(str(e))
        json_msg = MessageHelperJSON.get_json_msg(success=False, msg=err_msg)
        return HttpResponse(status=500,
                            content=json_msg,
                            content_type="application/json")
Ejemplo n.º 4
0
def dvn_import(request):

    if not has_proper_auth(request):
        json_msg = MessageHelperJSON.get_json_msg(success=False,
                                                  msg="Authentication failed.")
        return HttpResponse(status=401,
                            content=json_msg,
                            content_type="application/json")

    if request.POST:
        user = None
        title = request.POST["title"]
        abstract = request.POST["abstract"]
        email = request.POST["email"]
        content = request.FILES.values()[0]
        name = request.POST["shapefile_name"]
        #dataverse_info = request.POST.get('dataverse_info', None)
        keywords = "" if "keywords" not in request.POST else request.POST[
            "keywords"]

        #print request.POST.items()

        if "worldmap_username" in request.POST:
            try:
                user = User.objects.get(username=request.POST["username"])
            except:
                pass

        if user is None:
            existing_user = User.objects.filter(email=email)
            if existing_user.count() > 0:
                user = existing_user[0]
            else:
                user = _create_new_user(email, None, None, None)

        if not user:
            json_msg = MessageHelperJSON.get_json_msg(
                success=False,
                msg="A user account could not be created for email %s" % email)
            return HttpResponse(status=200,
                                content=json_msg,
                                content_type="application/json")

        else:
            name = slugify(name.replace(".", "_"))
            file_obj = write_file(content)
            try:

                # Save the actual layer
                saved_layer = save(name,
                                   file_obj,
                                   user,
                                   overwrite=False,
                                   abstract=abstract,
                                   title=title,
                                   keywords=keywords.split())

                # Look for DataverseInfo in the request.POST
                #   If it exists, create a DataverseLayerMetadata object
                #
                add_dataverse_layer_metadata(saved_layer, request.POST)

                # Prepare a JSON reponse
                #
                layer_metadata_obj = LayerMetadata(
                    **{'geonode_layer_object': saved_layer})

                # Return the response!
                json_msg = MessageHelperJSON.get_json_msg(
                    success=True,
                    msg='worked',
                    data_dict=layer_metadata_obj.get_metadata_dict())
                #print '-' * 40
                #print 'json_msg', json_msg
                return HttpResponse(status=200,
                                    content=json_msg,
                                    content_type="application/json")
                """
                return HttpResponse(status=200, content=json.dumps({
                    "success": True,
                    "layer_name": saved_layer.typename,
                    "layer_link": "%sdata/%s" % (settings.SITEURL, saved_layer.typename),
                    "embed_map_link": "%smaps/embed/?layer=%s" % (settings.SITEURL, saved_layer.typename),
                    "worldmap_username": user.username
                }))
                """

            except:
                e = sys.exc_info()[0]
                logger.error("Unexpected error during dvn import: %s : %s" %
                             (name, escape(str(e))))
                err_msg = "Unexpected error during upload: %s" % escape(str(e))
                json_msg = MessageHelperJSON.get_json_msg(success=False,
                                                          msg=err_msg)
                return HttpResponse(content=json_msg,
                                    content_type="application/json")

    else:
        json_msg = MessageHelperJSON.get_json_msg(
            success=False, msg="Requests must be POST not GET")
        return HttpResponse(status=401,
                            content=json_msg,
                            content_type="application/json")