Search in sources :

Example 1 with MapLayerMetadata

use of edu.harvard.iq.dataverse.MapLayerMetadata in project dataverse by IQSS.

the class WorldMapRelatedData method deleteWorldMapLayerData.

// end updateWorldMapLayerData
/*
        For WorldMap/GeoConnect Usage
        Delete MayLayerMetadata object for a given Datafile

        POST params
        {
           "GEOCONNECT_TOKEN": "-- some 64 char token which contains a link to the DataFile --"
        }
    */
@POST
@Path(DELETE_MAP_LAYER_DATA_API_PATH_FRAGMENT)
public Response deleteWorldMapLayerData(String jsonData) {
    /*----------------------------------
            Parse the json message.
            - Auth check: GEOCONNECT_TOKEN
        //----------------------------------*/
    if (jsonData == null) {
        logger.log(Level.SEVERE, "jsonData is null");
        return error(Response.Status.BAD_REQUEST, "No JSON data");
    }
    // (1) Parse JSON
    // 
    JsonObject jsonInfo;
    try (StringReader rdr = new StringReader(jsonData)) {
        jsonInfo = Json.createReader(rdr).readObject();
    } catch (JsonParsingException jpe) {
        logger.log(Level.SEVERE, "Json: " + jsonData);
        return error(Response.Status.BAD_REQUEST, "Error parsing Json: " + jpe.getMessage());
    }
    // (2) Retrieve token string
    String worldmapTokenParam = this.retrieveTokenValueFromJson(jsonInfo);
    if (worldmapTokenParam == null) {
        return error(Response.Status.BAD_REQUEST, "Token not found in JSON request.");
    }
    // (3) Retrieve WorldMapToken and make sure it is valid
    // 
    WorldMapToken wmToken = this.tokenServiceBean.retrieveAndRefreshValidToken(worldmapTokenParam);
    if (wmToken == null) {
        return error(Response.Status.UNAUTHORIZED, "No access. Invalid token.");
    }
    // 
    if (!(tokenServiceBean.canTokenUserEditFile(wmToken))) {
        tokenServiceBean.expireToken(wmToken);
        return error(Response.Status.UNAUTHORIZED, "No access. Invalid token.");
    }
    // (5) Attempt to retrieve DataFile and mapLayerMetadata
    DataFile dfile = wmToken.getDatafile();
    MapLayerMetadata mapLayerMetadata = this.mapLayerMetadataService.findMetadataByDatafile(dfile);
    if (mapLayerMetadata == null) {
        return error(Response.Status.EXPECTATION_FAILED, "No map layer metadata found.");
    }
    // 
    if (!(this.mapLayerMetadataService.deleteMapLayerMetadataObject(mapLayerMetadata, wmToken.getDataverseUser()))) {
        return error(Response.Status.PRECONDITION_FAILED, "Failed to delete layer");
    }
    ;
    return ok("Map layer metadata deleted.");
}
Also used : DataFile(edu.harvard.iq.dataverse.DataFile) MapLayerMetadata(edu.harvard.iq.dataverse.MapLayerMetadata) StringReader(java.io.StringReader) JsonObject(javax.json.JsonObject) WorldMapToken(edu.harvard.iq.dataverse.worldmapauth.WorldMapToken) JsonParsingException(javax.json.stream.JsonParsingException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 2 with MapLayerMetadata

use of edu.harvard.iq.dataverse.MapLayerMetadata in project dataverse by IQSS.

the class WorldMapRelatedData method updateWorldMapLayerData.

/*
        For WorldMap/GeoConnect Usage
        Create/Updated a MapLayerMetadata object for a given Datafile id
        
        Example of jsonLayerData String:
        {
             "layerName": "geonode:boston_census_blocks_zip_cr9"
            , "layerLink": "http://localhost:8000/data/geonode:boston_census_blocks_zip_cr9"
            , "embedMapLink": "http://localhost:8000/maps/embed/?layer=geonode:boston_census_blocks_zip_cr9"
            , "worldmapUsername": "dv_pete"
        }
    */
@POST
@Path(UPDATE_MAP_LAYER_DATA_API_PATH_FRAGMENT)
public Response updateWorldMapLayerData(String jsonLayerData) {
    // ----------------------------------
    if (jsonLayerData == null) {
        logger.log(Level.SEVERE, "jsonLayerData is null");
        return error(Response.Status.BAD_REQUEST, "No JSON data");
    }
    // (1) Parse JSON
    // 
    JsonObject jsonInfo;
    try (StringReader rdr = new StringReader(jsonLayerData)) {
        jsonInfo = Json.createReader(rdr).readObject();
    } catch (JsonParsingException jpe) {
        logger.log(Level.SEVERE, "Json: " + jsonLayerData);
        return error(Response.Status.BAD_REQUEST, "Error parsing Json: " + jpe.getMessage());
    }
    // Retrieve token string
    String worldmapTokenParam = this.retrieveTokenValueFromJson(jsonInfo);
    if (worldmapTokenParam == null) {
        return error(Response.Status.BAD_REQUEST, "Token not found in JSON request.");
    }
    // Retrieve WorldMapToken and make sure it is valid
    // 
    WorldMapToken wmToken = this.tokenServiceBean.retrieveAndRefreshValidToken(worldmapTokenParam);
    if (wmToken == null) {
        return error(Response.Status.UNAUTHORIZED, "No access. Invalid token.");
    }
    // 
    if (!(tokenServiceBean.canTokenUserEditFile(wmToken))) {
        tokenServiceBean.expireToken(wmToken);
        return error(Response.Status.UNAUTHORIZED, "No access. Invalid token.");
    }
    // 
    for (String attr : MapLayerMetadata.MANDATORY_JSON_FIELDS) {
        if (!jsonInfo.containsKey(attr)) {
            return error(Response.Status.BAD_REQUEST, "Error parsing Json.  Key not found [" + attr + "]\nRequired keys are: " + MapLayerMetadata.MANDATORY_JSON_FIELDS);
        }
    }
    // (3) Attempt to retrieve DataverseUser
    AuthenticatedUser dvUser = wmToken.getDataverseUser();
    if (dvUser == null) {
        return error(Response.Status.NOT_FOUND, "DataverseUser not found for token");
    }
    // (4) Attempt to retrieve DataFile
    DataFile dfile = wmToken.getDatafile();
    if (dfile == null) {
        return error(Response.Status.NOT_FOUND, "DataFile not found for token");
    }
    // check permissions!
    if (!permissionService.request(createDataverseRequest(dvUser)).on(dfile.getOwner()).has(Permission.EditDataset)) {
        String errMsg = "The user does not have permission to edit metadata for this file. (MapLayerMetadata)";
        return error(Response.Status.FORBIDDEN, errMsg);
    }
    // (5) See if a MapLayerMetadata already exists
    // 
    MapLayerMetadata mapLayerMetadata = this.mapLayerMetadataService.findMetadataByDatafile(dfile);
    if (mapLayerMetadata == null) {
        // Create a new mapLayerMetadata object
        mapLayerMetadata = new MapLayerMetadata();
    }
    // Create/Update new MapLayerMetadata object and save it
    mapLayerMetadata.setDataFile(dfile);
    mapLayerMetadata.setDataset(dfile.getOwner());
    mapLayerMetadata.setLayerName(jsonInfo.getString("layerName"));
    mapLayerMetadata.setLayerLink(jsonInfo.getString("layerLink"));
    mapLayerMetadata.setEmbedMapLink(jsonInfo.getString("embedMapLink"));
    mapLayerMetadata.setWorldmapUsername(jsonInfo.getString("worldmapUsername"));
    if (jsonInfo.containsKey("mapImageLink")) {
        mapLayerMetadata.setMapImageLink(jsonInfo.getString("mapImageLink"));
    }
    // If this was a tabular join set the attributes:
    // - isJoinLayer
    // - joinDescription
    // 
    String joinDescription = jsonInfo.getString("joinDescription", null);
    if ((joinDescription == null) || (joinDescription.equals(""))) {
        mapLayerMetadata.setIsJoinLayer(true);
        mapLayerMetadata.setJoinDescription(joinDescription);
    } else {
        mapLayerMetadata.setIsJoinLayer(false);
        mapLayerMetadata.setJoinDescription(null);
    }
    // Set the mapLayerLinks
    // 
    String mapLayerLinks = jsonInfo.getString("mapLayerLinks", null);
    if ((mapLayerLinks == null) || (mapLayerLinks.equals(""))) {
        mapLayerMetadata.setMapLayerLinks(null);
    } else {
        mapLayerMetadata.setMapLayerLinks(mapLayerLinks);
    }
    // mapLayer.save();
    MapLayerMetadata savedMapLayerMetadata = mapLayerMetadataService.save(mapLayerMetadata);
    if (savedMapLayerMetadata == null) {
        logger.log(Level.SEVERE, "Json: " + jsonLayerData);
        return error(Response.Status.BAD_REQUEST, "Failed to save map layer!  Original JSON: ");
    }
    // notify user
    userNotificationService.sendNotification(dvUser, wmToken.getCurrentTimestamp(), UserNotification.Type.MAPLAYERUPDATED, dfile.getOwner().getLatestVersion().getId());
    // ------------------------------------------
    try {
        logger.info("retrieveMapImageForIcon");
        this.mapLayerMetadataService.retrieveMapImageForIcon(savedMapLayerMetadata);
    } catch (IOException ex) {
        logger.severe("Failed to retrieve image from WorldMap server");
        Logger.getLogger(WorldMapRelatedData.class.getName()).log(Level.SEVERE, null, ex);
    }
    return ok("map layer object saved!");
}
Also used : DataFile(edu.harvard.iq.dataverse.DataFile) MapLayerMetadata(edu.harvard.iq.dataverse.MapLayerMetadata) StringReader(java.io.StringReader) JsonObject(javax.json.JsonObject) WorldMapToken(edu.harvard.iq.dataverse.worldmapauth.WorldMapToken) IOException(java.io.IOException) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) JsonParsingException(javax.json.stream.JsonParsingException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 3 with MapLayerMetadata

use of edu.harvard.iq.dataverse.MapLayerMetadata in project dataverse by IQSS.

the class WorldMapPermissionHelper method canUserSeeExploreWorldMapButton.

/**
 *  WARNING: Before calling this, make sure the user has download
 *  permission for the file!!  (See DatasetPage.canDownloadFile())
 *
 * Should there be a Explore WorldMap Button for this file?
 *   See table in: https://github.com/IQSS/dataverse/issues/1618
 *
 *  (1) Does the file have MapLayerMetadata?
 *  (2) Are the proper settings in place
 *
 * @param fm FileMetadata
 * @return boolean
 */
private boolean canUserSeeExploreWorldMapButton(FileMetadata fm, boolean permissionsChecked) {
    if (fm == null) {
        return false;
    }
    // This is only here to make the public method users think...
    if (!permissionsChecked) {
        return false;
    }
    if (this.fileMetadataWorldMapExplore.containsKey(fm.getId())) {
        // logger.info("using cached result for candownloadfile on filemetadata "+fid);
        return this.fileMetadataWorldMapExplore.get(fm.getId());
    }
    /* -----------------------------------------------------
           Does a Map Exist?
         ----------------------------------------------------- */
    if (!(this.hasMapLayerMetadata(fm))) {
        // See if it does
        MapLayerMetadata layer_metadata = mapLayerMetadataService.findMetadataByDatafile(fm.getDataFile());
        if (layer_metadata != null) {
            if (mapLayerMetadataLookup == null) {
                loadMapLayerMetadataLookup(fm.getDataFile().getOwner());
            }
            // yes: keep going...
            mapLayerMetadataLookup.put(layer_metadata.getDataFile().getId(), layer_metadata);
        } else {
            // Nope: no button
            this.fileMetadataWorldMapExplore.put(fm.getId(), false);
            return false;
        }
    }
    /*
            Is setting for GeoconnectViewMaps true?
            Nope? no button
        */
    if (!settingsWrapper.isTrueForKey(SettingsServiceBean.Key.GeoconnectViewMaps, false)) {
        this.fileMetadataWorldMapExplore.put(fm.getId(), false);
        return false;
    }
    if (fm.getDatasetVersion().isDeaccessioned()) {
        if (this.doesSessionUserHavePermission(Permission.EditDataset, fm)) {
            // Yes, save answer and return true
            this.fileMetadataWorldMapExplore.put(fm.getId(), true);
            return true;
        } else {
            this.fileMetadataWorldMapExplore.put(fm.getId(), false);
            return false;
        }
    }
    // Check for restrictions
    boolean isRestrictedFile = fm.isRestricted();
    // --------------------------------------------------------------------
    if (!isRestrictedFile) {
        // Yes, save answer and return true
        this.fileMetadataWorldMapExplore.put(fm.getId(), true);
        return true;
    }
    if (session.getUser() instanceof GuestUser) {
        this.fileMetadataWorldMapExplore.put(fm.getId(), false);
        return false;
    }
    if (!this.doesSessionUserHavePermission(Permission.DownloadFile, fm)) {
        // Yes, save answer and return true
        this.fileMetadataWorldMapExplore.put(fm.getId(), false);
        return false;
    }
    /* -----------------------------------------------------
             Yes: User can view button!
         ----------------------------------------------------- */
    this.fileMetadataWorldMapExplore.put(fm.getId(), true);
    return true;
}
Also used : MapLayerMetadata(edu.harvard.iq.dataverse.MapLayerMetadata) GuestUser(edu.harvard.iq.dataverse.authorization.users.GuestUser)

Example 4 with MapLayerMetadata

use of edu.harvard.iq.dataverse.MapLayerMetadata in project dataverse by IQSS.

the class DeleteMapLayerMetadataCommand method execute.

@Override
public Boolean execute(CommandContext ctxt) throws CommandException {
    if (dataFile == null) {
        return false;
    }
    MapLayerMetadata mapLayerMetadata = ctxt.mapLayerMetadata().findMetadataByDatafile(dataFile);
    if (mapLayerMetadata == null) {
        return false;
    }
    boolean mapDeleted = ctxt.mapLayerMetadata().deleteMapLayerMetadataObject(mapLayerMetadata, getUser());
    logger.info("Boolean returned from deleteMapLayerMetadataObject: " + mapDeleted);
    return mapDeleted;
}
Also used : MapLayerMetadata(edu.harvard.iq.dataverse.MapLayerMetadata)

Example 5 with MapLayerMetadata

use of edu.harvard.iq.dataverse.MapLayerMetadata in project dataverse by IQSS.

the class WorldMapRelatedData method checkWorldMapAPI.

// test call to track down problems
// http://127.0.0.1:8080/api/worldmap/t/
@GET
@Path("t/{identifier}")
public Response checkWorldMapAPI(@Context HttpServletRequest request, @PathParam("identifier") int identifier) {
    MapLayerMetadata mapLayerMetadata = this.mapLayerMetadataService.find(new Long(identifier));
    logger.info("mapLayerMetadata retrieved. Try to retrieve image (after 1st time):<br />" + mapLayerMetadata.getMapImageLink());
    try {
        this.mapLayerMetadataService.retrieveMapImageForIcon(mapLayerMetadata);
    } catch (IOException ex) {
        logger.info("IOException. Failed to retrieve image. Error:" + ex);
    // Logger.getLogger(WorldMapRelatedData.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception e2) {
        logger.info("Failed to retrieve image. Error:" + e2);
    }
    return ok("Looks good " + identifier + " " + mapLayerMetadata.getLayerName());
}
Also used : MapLayerMetadata(edu.harvard.iq.dataverse.MapLayerMetadata) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) JsonParsingException(javax.json.stream.JsonParsingException) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Aggregations

MapLayerMetadata (edu.harvard.iq.dataverse.MapLayerMetadata)7 JsonParsingException (javax.json.stream.JsonParsingException)3 Path (javax.ws.rs.Path)3 DataFile (edu.harvard.iq.dataverse.DataFile)2 WorldMapToken (edu.harvard.iq.dataverse.worldmapauth.WorldMapToken)2 IOException (java.io.IOException)2 StringReader (java.io.StringReader)2 JsonObject (javax.json.JsonObject)2 POST (javax.ws.rs.POST)2 AuthenticatedUser (edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)1 GuestUser (edu.harvard.iq.dataverse.authorization.users.GuestUser)1 URISyntaxException (java.net.URISyntaxException)1 JsonObjectBuilder (javax.json.JsonObjectBuilder)1 GET (javax.ws.rs.GET)1