Search in sources :

Example 1 with JsonParsingException

use of javax.json.stream.JsonParsingException in project sling by apache.

the class JsonContentParser method toJsonObjectWithJsonTicks.

private JsonObject toJsonObjectWithJsonTicks(InputStream is) {
    String jsonString;
    try {
        jsonString = IOUtils.toString(is, CharEncoding.UTF_8);
    } catch (IOException ex) {
        throw new ParseException("Error getting JSON string.", ex);
    }
    // convert ticks to double quotes
    jsonString = JsonTicksConverter.tickToDoubleQuote(jsonString);
    try (JsonReader reader = jsonReaderFactory.createReader(new StringReader(jsonString))) {
        return reader.readObject();
    } catch (JsonParsingException ex) {
        throw new ParseException("Error parsing JSON content: " + ex.getMessage(), ex);
    }
}
Also used : StringReader(java.io.StringReader) JsonReader(javax.json.JsonReader) JsonString(javax.json.JsonString) IOException(java.io.IOException) ParseException(org.apache.sling.jcr.contentparser.ParseException) JsonParsingException(javax.json.stream.JsonParsingException)

Example 2 with JsonParsingException

use of javax.json.stream.JsonParsingException 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 3 with JsonParsingException

use of javax.json.stream.JsonParsingException 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 4 with JsonParsingException

use of javax.json.stream.JsonParsingException in project dataverse by IQSS.

the class WorldMapRelatedData method getWorldMapDatafileInfo.

/**
 * Retrieve FileMetadata for Use by WorldMap.
 *  This includes information about the DataFile, Dataset, DatasetVersion, and Dataverse
 *
 * @param jsonTokenData
 * @param request
 * @return
 */
@POST
// + "{worldmap_token}")
@Path(GET_WORLDMAP_DATAFILE_API_PATH_FRAGMENT)
public Response getWorldMapDatafileInfo(String jsonTokenData, @Context HttpServletRequest request) {
    // , @PathParam("worldmap_token") String worldmapTokenParam) {
    if (true) {
    // return okResponse("Currently deactivated");
    // return okResponse("remote server: " + request.getRemoteAddr());
    }
    logger.info("API call: getWorldMapDatafileInfo");
    // ----------------------------------
    // Auth check: Parse the json message and check for a valid GEOCONNECT_TOKEN_KEY and GEOCONNECT_TOKEN_VALUE
    // -- For testing, the GEOCONNECT_TOKEN_VALUE will be dynamic, found in the db
    // ----------------------------------
    logger.info("(1) jsonTokenData: " + jsonTokenData);
    // Parse JSON
    JsonObject jsonTokenInfo;
    try (StringReader rdr = new StringReader(jsonTokenData)) {
        jsonTokenInfo = Json.createReader(rdr).readObject();
    } catch (JsonParsingException jpe) {
        logger.log(Level.SEVERE, "Json: " + jsonTokenData);
        return error(Response.Status.BAD_REQUEST, "Error parsing Json: " + jpe.getMessage());
    }
    logger.info("(1a) jsonTokenInfo: " + jsonTokenInfo);
    // Retrieve token string
    String worldmapTokenParam = this.retrieveTokenValueFromJson(jsonTokenInfo);
    logger.info("(1b) token from JSON: " + worldmapTokenParam);
    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 = tokenServiceBean.retrieveAndRefreshValidToken(worldmapTokenParam);
    logger.info("(2) token retrieved from db: " + wmToken);
    if (wmToken == null) {
        return error(Response.Status.UNAUTHORIZED, "No access. Invalid token.");
    }
    // Make sure the token's User still has permissions to access the file
    // 
    logger.info("(3) check permissions");
    if (!(tokenServiceBean.canTokenUserEditFile(wmToken))) {
        tokenServiceBean.expireToken(wmToken);
        return error(Response.Status.UNAUTHORIZED, "No access. Invalid token.");
    }
    // (1) Retrieve token connected data: DataverseUser, DataFile
    // 
    // Make sure token user and file are still available
    // 
    AuthenticatedUser dvUser = wmToken.getDataverseUser();
    if (dvUser == null) {
        return error(Response.Status.NOT_FOUND, "DataverseUser not found for token");
    }
    DataFile dfile = wmToken.getDatafile();
    if (dfile == null) {
        return error(Response.Status.NOT_FOUND, "DataFile not found for token");
    }
    // (1a) Retrieve FileMetadata
    FileMetadata dfile_meta = dfile.getFileMetadata();
    if (dfile_meta == null) {
        return error(Response.Status.NOT_FOUND, "FileMetadata not found");
    }
    // (2) Now get the dataset and the latest DatasetVersion
    Dataset dset = dfile.getOwner();
    if (dset == null) {
        return error(Response.Status.NOT_FOUND, "Owning Dataset for this DataFile not found");
    }
    // (2a) latest DatasetVersion
    // !! How do you check if the lastest version has this specific file?
    // 
    DatasetVersion dset_version = dset.getLatestVersion();
    if (dset_version == null) {
        return error(Response.Status.NOT_FOUND, "Latest DatasetVersion for this DataFile not found");
    }
    // (3) get Dataverse
    Dataverse dverse = dset.getOwner();
    if (dverse == null) {
        return error(Response.Status.NOT_FOUND, "Dataverse for this DataFile's Dataset not found");
    }
    // (4) Roll it all up in a JSON response
    final JsonObjectBuilder jsonData = Json.createObjectBuilder();
    // ------------------------------------
    if (dfile.isShapefileType()) {
        jsonData.add("mapping_type", "shapefile");
    } else if (dfile.isTabularData()) {
        jsonData.add("mapping_type", "tabular");
    } else {
        logger.log(Level.SEVERE, "This was neither a Shapefile nor a Tabular data file.  DataFile id: " + dfile.getId());
        return error(Response.Status.BAD_REQUEST, "Sorry! This file does not have mapping data. Please contact the Dataverse administrator. DataFile id: " + dfile.getId());
    }
    // ------------------------------------
    // DataverseUser Info
    // ------------------------------------
    jsonData.add("dv_user_id", dvUser.getId());
    jsonData.add("dv_username", dvUser.getUserIdentifier());
    jsonData.add("dv_user_email", dvUser.getEmail());
    // ------------------------------------
    // Dataverse URLs to this server
    // ------------------------------------
    String serverName = systemConfig.getDataverseSiteUrl();
    jsonData.add("return_to_dataverse_url", dset_version.getReturnToFilePageURL(serverName, dset, dfile));
    jsonData.add("datafile_download_url", dfile.getMapItFileDownloadURL(serverName));
    // ------------------------------------
    // Dataverse
    // ------------------------------------
    // jsonData.add("dataverse_installation_name", "Harvard Dataverse"); // todo / fix
    // is this enough to distinguish a dataverse installation?
    jsonData.add("dataverse_installation_name", systemConfig.getDataverseSiteUrl());
    jsonData.add("dataverse_id", dverse.getId());
    jsonData.add("dataverse_name", dverse.getName());
    String dataverseDesc = dverse.getDescription();
    if (dataverseDesc == null || dataverseDesc.equalsIgnoreCase("")) {
        dataverseDesc = "";
    }
    jsonData.add("dataverse_description", dataverseDesc);
    // ------------------------------------
    // Dataset Info
    // ------------------------------------
    jsonData.add("dataset_id", dset.getId());
    // ------------------------------------
    // DatasetVersion Info
    // ------------------------------------
    // database id
    jsonData.add("dataset_version_id", dset_version.getId());
    // major/minor version number, e.g. 3.1
    jsonData.add("dataset_semantic_version", dset_version.getSemanticVersion());
    jsonData.add("dataset_name", dset_version.getTitle());
    jsonData.add("dataset_citation", dset_version.getCitation(true));
    // Need to fix to/do
    jsonData.add("dataset_description", "");
    jsonData.add("dataset_is_public", dset_version.isReleased());
    // ------------------------------------
    // DataFile/FileMetaData Info
    // ------------------------------------
    jsonData.add("datafile_id", dfile.getId());
    jsonData.add("datafile_label", dfile_meta.getLabel());
    // jsonData.add("filename", dfile_meta.getLabel());
    jsonData.add("datafile_expected_md5_checksum", dfile.getChecksumValue());
    Long fsize = dfile.getFilesize();
    if (fsize == null) {
        fsize = new Long(-1);
    }
    jsonData.add("datafile_filesize", fsize);
    jsonData.add("datafile_content_type", dfile.getContentType());
    jsonData.add("datafile_create_datetime", dfile.getCreateDate().toString());
    // restriction status of the DataFile
    jsonData.add("datafile_is_restricted", dfile.isRestricted());
    return ok(jsonData);
}
Also used : Dataset(edu.harvard.iq.dataverse.Dataset) FileMetadata(edu.harvard.iq.dataverse.FileMetadata) JsonObject(javax.json.JsonObject) WorldMapToken(edu.harvard.iq.dataverse.worldmapauth.WorldMapToken) DatasetVersion(edu.harvard.iq.dataverse.DatasetVersion) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) Dataverse(edu.harvard.iq.dataverse.Dataverse) DataFile(edu.harvard.iq.dataverse.DataFile) StringReader(java.io.StringReader) JsonObjectBuilder(javax.json.JsonObjectBuilder) JsonParsingException(javax.json.stream.JsonParsingException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 5 with JsonParsingException

use of javax.json.stream.JsonParsingException in project tomee by apache.

the class PublicKeyResolver method parseJwks.

private Map<String, Key> parseJwks(final String publicKey) {
    final JsonObject jwks;
    try {
        jwks = Json.createReader(new StringReader(publicKey)).readObject();
    } catch (final JsonParsingException e) {
        return Collections.emptyMap();
    }
    try {
        final JsonArray keys = jwks.getJsonArray(JWK_SET_MEMBER_NAME);
        for (final JsonValue key : keys) {
            validateJwk(key.asJsonObject());
        }
    } catch (final Exception e) {
        throw new DeploymentException("MicroProfile Public Key JWKS invalid format.");
    }
    try {
        final JsonWebKeySet keySet = new JsonWebKeySet(publicKey);
        final Map<String, Key> keys = keySet.getJsonWebKeys().stream().collect(Collectors.toMap(JsonWebKey::getKeyId, JsonWebKey::getKey));
        return Collections.unmodifiableMap(keys);
    } catch (final JoseException e) {
        throw new DeploymentException(JWTAuthConfigurationProperties.PUBLIC_KEY_ERROR + " JWK.", e);
    }
}
Also used : JsonArray(javax.json.JsonArray) JoseException(org.jose4j.lang.JoseException) StringReader(java.io.StringReader) JsonValue(javax.json.JsonValue) JsonObject(javax.json.JsonObject) DeploymentException(javax.enterprise.inject.spi.DeploymentException) JsonWebKeySet(org.jose4j.jwk.JsonWebKeySet) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) URISyntaxException(java.net.URISyntaxException) DeploymentException(javax.enterprise.inject.spi.DeploymentException) IOException(java.io.IOException) JoseException(org.jose4j.lang.JoseException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) JsonParsingException(javax.json.stream.JsonParsingException) JsonWebKey(org.jose4j.jwk.JsonWebKey) Key(java.security.Key) JsonParsingException(javax.json.stream.JsonParsingException)

Aggregations

StringReader (java.io.StringReader)10 JsonParsingException (javax.json.stream.JsonParsingException)10 JsonObject (javax.json.JsonObject)9 POST (javax.ws.rs.POST)6 Path (javax.ws.rs.Path)6 AuthenticatedUser (edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)4 WorldMapToken (edu.harvard.iq.dataverse.worldmapauth.WorldMapToken)4 IOException (java.io.IOException)4 DataFile (edu.harvard.iq.dataverse.DataFile)3 Dataverse (edu.harvard.iq.dataverse.Dataverse)3 Dataset (edu.harvard.iq.dataverse.Dataset)2 DatasetVersion (edu.harvard.iq.dataverse.DatasetVersion)2 MapLayerMetadata (edu.harvard.iq.dataverse.MapLayerMetadata)2 JsonParseException (edu.harvard.iq.dataverse.util.json.JsonParseException)2 EJBException (javax.ejb.EJBException)2 DeploymentException (javax.enterprise.inject.spi.DeploymentException)2 JsonObjectBuilder (javax.json.JsonObjectBuilder)2 JsonReader (javax.json.JsonReader)2 JsonString (javax.json.JsonString)2 ConstraintViolationException (javax.validation.ConstraintViolationException)2