Search in sources :

Example 6 with JsonParsingException

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

the class PublicKeyResolver method parseJwk.

private Map<String, Key> parseJwk(final String publicKey) {
    final JsonObject jwk;
    try {
        jwk = Json.createReader(new StringReader(publicKey)).readObject();
    } catch (final JsonParsingException e) {
        return Collections.emptyMap();
    }
    if (jwk.containsKey(JWK_SET_MEMBER_NAME)) {
        return Collections.emptyMap();
    }
    validateJwk(jwk);
    try {
        final JsonWebKey key = JsonWebKey.Factory.newJwk(publicKey);
        return Collections.singletonMap(key.getKeyId(), key.getKey());
    } catch (final JoseException e) {
        throw new DeploymentException(JWTAuthConfigurationProperties.PUBLIC_KEY_ERROR + " JWK.", e);
    }
}
Also used : JoseException(org.jose4j.lang.JoseException) StringReader(java.io.StringReader) JsonWebKey(org.jose4j.jwk.JsonWebKey) JsonObject(javax.json.JsonObject) DeploymentException(javax.enterprise.inject.spi.DeploymentException) JsonParsingException(javax.json.stream.JsonParsingException)

Example 7 with JsonParsingException

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

the class PutSlack method onTrigger.

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;
    }
    JsonObjectBuilder builder = Json.createObjectBuilder();
    String text = context.getProperty(WEBHOOK_TEXT).evaluateAttributeExpressions(flowFile).getValue();
    if (text != null && !text.isEmpty()) {
        builder.add("text", text);
    } else {
        // Slack requires the 'text' attribute
        getLogger().error("FlowFile should have non-empty " + WEBHOOK_TEXT.getName());
        flowFile = session.penalize(flowFile);
        session.transfer(flowFile, REL_FAILURE);
        return;
    }
    String channel = context.getProperty(CHANNEL).evaluateAttributeExpressions(flowFile).getValue();
    if (channel != null && !channel.isEmpty()) {
        String error = validateChannel(channel);
        if (error == null) {
            builder.add("channel", channel);
        } else {
            getLogger().error("Invalid channel '{}': {}", new Object[] { channel, error });
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, REL_FAILURE);
            return;
        }
    }
    String username = context.getProperty(USERNAME).evaluateAttributeExpressions(flowFile).getValue();
    if (username != null && !username.isEmpty()) {
        builder.add("username", username);
    }
    String iconUrl = context.getProperty(ICON_URL).evaluateAttributeExpressions(flowFile).getValue();
    if (iconUrl != null && !iconUrl.isEmpty()) {
        builder.add("icon_url", iconUrl);
    }
    String iconEmoji = context.getProperty(ICON_EMOJI).evaluateAttributeExpressions(flowFile).getValue();
    if (iconEmoji != null && !iconEmoji.isEmpty()) {
        builder.add("icon_emoji", iconEmoji);
    }
    try {
        // Get Attachments Array
        if (!attachments.isEmpty()) {
            JsonArrayBuilder jsonArrayBuiler = Json.createArrayBuilder();
            for (PropertyDescriptor attachment : attachments) {
                String s = context.getProperty(attachment).evaluateAttributeExpressions(flowFile).getValue();
                JsonReader reader = Json.createReader(new StringReader(s));
                JsonObject attachmentJson = reader.readObject();
                jsonArrayBuiler.add(attachmentJson);
            }
            builder.add("attachments", jsonArrayBuiler);
        }
        JsonObject jsonObject = builder.build();
        StringWriter stringWriter = new StringWriter();
        JsonWriter jsonWriter = Json.createWriter(stringWriter);
        jsonWriter.writeObject(jsonObject);
        jsonWriter.close();
        URL url = new URL(context.getProperty(WEBHOOK_URL).getValue());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream());
        String payload = "payload=" + URLEncoder.encode(stringWriter.getBuffer().toString(), "UTF-8");
        outputStream.writeBytes(payload);
        outputStream.close();
        int responseCode = conn.getResponseCode();
        if (responseCode >= 200 && responseCode < 300) {
            getLogger().info("Successfully posted message to Slack");
            session.transfer(flowFile, REL_SUCCESS);
            session.getProvenanceReporter().send(flowFile, context.getProperty(WEBHOOK_URL).getValue());
        } else {
            getLogger().error("Failed to post message to Slack with response code {}", new Object[] { responseCode });
            flowFile = session.penalize(flowFile);
            session.transfer(flowFile, REL_FAILURE);
            context.yield();
        }
    } catch (JsonParsingException e) {
        getLogger().error("Failed to parse JSON", e);
        flowFile = session.penalize(flowFile);
        session.transfer(flowFile, REL_FAILURE);
    } catch (IOException e) {
        getLogger().error("Failed to open connection", e);
        flowFile = session.penalize(flowFile);
        session.transfer(flowFile, REL_FAILURE);
        context.yield();
    }
}
Also used : FlowFile(org.apache.nifi.flowfile.FlowFile) PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) DataOutputStream(java.io.DataOutputStream) JsonObject(javax.json.JsonObject) IOException(java.io.IOException) JsonWriter(javax.json.JsonWriter) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) StringWriter(java.io.StringWriter) StringReader(java.io.StringReader) JsonReader(javax.json.JsonReader) JsonArrayBuilder(javax.json.JsonArrayBuilder) JsonObjectBuilder(javax.json.JsonObjectBuilder) JsonParsingException(javax.json.stream.JsonParsingException)

Example 8 with JsonParsingException

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

the class WorldMapRelatedData method deleteWorldMapToken.

// end deleteWorldMapLayerData
/*
        For WorldMap/GeoConnect Usage
        Explicitly expire a WorldMap token, removing token from the database

        POST params
        {
           "GEOCONNECT_TOKEN": "-- some 64 char token which contains a link to the DataFile --"
        }
    */
@POST
@Path(DELETE_WORLDMAP_TOKEN_PATH_FRAGMENT)
public Response deleteWorldMapToken(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
    // 
    WorldMapToken wmToken = this.tokenServiceBean.findByName(worldmapTokenParam);
    if (wmToken == null) {
        return error(Response.Status.NOT_FOUND, "Token not found.");
    }
    // (4) Delete the token
    // 
    tokenServiceBean.deleteToken(wmToken);
    return ok("Token has been deleted.");
}
Also used : 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 9 with JsonParsingException

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

the class Dataverses method createDataset.

@POST
@Path("{identifier}/datasets")
public Response createDataset(String jsonBody, @PathParam("identifier") String parentIdtf) {
    try {
        User u = findUserOrDie();
        Dataverse owner = findDataverseOrDie(parentIdtf);
        JsonObject json;
        try (StringReader rdr = new StringReader(jsonBody)) {
            json = Json.createReader(rdr).readObject();
        } catch (JsonParsingException jpe) {
            LOGGER.log(Level.SEVERE, "Json: {0}", jsonBody);
            return error(Status.BAD_REQUEST, "Error parsing Json: " + jpe.getMessage());
        }
        Dataset ds = new Dataset();
        ds.setOwner(owner);
        JsonObject jsonVersion = json.getJsonObject("datasetVersion");
        if (jsonVersion == null) {
            return error(Status.BAD_REQUEST, "Json POST data are missing datasetVersion object.");
        }
        try {
            try {
                DatasetVersion version = new DatasetVersion();
                version.setDataset(ds);
                // Use the two argument version so that the version knows which dataset it's associated with.
                version = jsonParser().parseDatasetVersion(jsonVersion, version);
                // force "initial version" properties
                version.setMinorVersionNumber(null);
                version.setVersionNumber(null);
                version.setVersionState(DatasetVersion.VersionState.DRAFT);
                LinkedList<DatasetVersion> versions = new LinkedList<>();
                versions.add(version);
                version.setDataset(ds);
                ds.setVersions(versions);
            } catch (javax.ejb.TransactionRolledbackLocalException rbe) {
                throw rbe.getCausedByException();
            }
        } catch (JsonParseException ex) {
            LOGGER.log(Level.INFO, "Error parsing dataset version from Json", ex);
            return error(Status.BAD_REQUEST, "Error parsing datasetVersion: " + ex.getMessage());
        } catch (Exception e) {
            LOGGER.log(Level.WARNING, "Error parsing dataset version from Json", e);
            return error(Status.INTERNAL_SERVER_ERROR, "Error parsing datasetVersion: " + e.getMessage());
        }
        Dataset managedDs = execCommand(new CreateDatasetCommand(ds, createDataverseRequest(u)));
        return created("/datasets/" + managedDs.getId(), Json.createObjectBuilder().add("id", managedDs.getId()).add("persistentId", managedDs.getGlobalId()));
    } catch (WrappedResponse ex) {
        return ex.getResponse();
    }
}
Also used : AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) User(edu.harvard.iq.dataverse.authorization.users.User) Dataset(edu.harvard.iq.dataverse.Dataset) CreateDatasetCommand(edu.harvard.iq.dataverse.engine.command.impl.CreateDatasetCommand) JsonObject(javax.json.JsonObject) DatasetVersion(edu.harvard.iq.dataverse.DatasetVersion) JsonParseException(edu.harvard.iq.dataverse.util.json.JsonParseException) Dataverse(edu.harvard.iq.dataverse.Dataverse) LinkedList(java.util.LinkedList) JsonParseException(edu.harvard.iq.dataverse.util.json.JsonParseException) EJBException(javax.ejb.EJBException) JsonParsingException(javax.json.stream.JsonParsingException) ConstraintViolationException(javax.validation.ConstraintViolationException) StringReader(java.io.StringReader) JsonParsingException(javax.json.stream.JsonParsingException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 10 with JsonParsingException

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

the class Dataverses method addDataverse.

@POST
@Path("{identifier}")
public Response addDataverse(String body, @PathParam("identifier") String parentIdtf) {
    Dataverse d;
    JsonObject dvJson;
    try (StringReader rdr = new StringReader(body)) {
        dvJson = Json.createReader(rdr).readObject();
        d = jsonParser().parseDataverse(dvJson);
    } catch (JsonParsingException jpe) {
        LOGGER.log(Level.SEVERE, "Json: {0}", body);
        return error(Status.BAD_REQUEST, "Error parsing Json: " + jpe.getMessage());
    } catch (JsonParseException ex) {
        Logger.getLogger(Dataverses.class.getName()).log(Level.SEVERE, "Error parsing dataverse from json: " + ex.getMessage(), ex);
        return error(Response.Status.BAD_REQUEST, "Error parsing the POSTed json into a dataverse: " + ex.getMessage());
    }
    try {
        if (!parentIdtf.isEmpty()) {
            Dataverse owner = findDataverseOrDie(parentIdtf);
            d.setOwner(owner);
        }
        // set the dataverse - contact relationship in the contacts
        for (DataverseContact dc : d.getDataverseContacts()) {
            dc.setDataverse(d);
        }
        AuthenticatedUser u = findAuthenticatedUserOrDie();
        d = execCommand(new CreateDataverseCommand(d, createDataverseRequest(u), null, null));
        return created("/dataverses/" + d.getAlias(), json(d));
    } catch (WrappedResponse ww) {
        Throwable cause = ww.getCause();
        StringBuilder sb = new StringBuilder();
        if (cause == null) {
            return ww.refineResponse("cause was null!");
        }
        while (cause.getCause() != null) {
            cause = cause.getCause();
            if (cause instanceof ConstraintViolationException) {
                ConstraintViolationException constraintViolationException = (ConstraintViolationException) cause;
                for (ConstraintViolation<?> violation : constraintViolationException.getConstraintViolations()) {
                    sb.append(" Invalid value: <<<").append(violation.getInvalidValue()).append(">>> for ").append(violation.getPropertyPath()).append(" at ").append(violation.getLeafBean()).append(" - ").append(violation.getMessage());
                }
            }
        }
        String error = sb.toString();
        if (!error.isEmpty()) {
            LOGGER.log(Level.INFO, error);
            return ww.refineResponse(error);
        }
        return ww.getResponse();
    } catch (EJBException ex) {
        Throwable cause = ex;
        StringBuilder sb = new StringBuilder();
        sb.append("Error creating dataverse.");
        while (cause.getCause() != null) {
            cause = cause.getCause();
            if (cause instanceof ConstraintViolationException) {
                ConstraintViolationException constraintViolationException = (ConstraintViolationException) cause;
                for (ConstraintViolation<?> violation : constraintViolationException.getConstraintViolations()) {
                    sb.append(" Invalid value: <<<").append(violation.getInvalidValue()).append(">>> for ").append(violation.getPropertyPath()).append(" at ").append(violation.getLeafBean()).append(" - ").append(violation.getMessage());
                }
            }
        }
        LOGGER.log(Level.SEVERE, sb.toString());
        return error(Response.Status.INTERNAL_SERVER_ERROR, "Error creating dataverse: " + sb.toString());
    } catch (Exception ex) {
        LOGGER.log(Level.SEVERE, "Error creating dataverse", ex);
        return error(Response.Status.INTERNAL_SERVER_ERROR, "Error creating dataverse: " + ex.getMessage());
    }
}
Also used : JsonObject(javax.json.JsonObject) DataverseContact(edu.harvard.iq.dataverse.DataverseContact) JsonString(javax.json.JsonString) JsonParseException(edu.harvard.iq.dataverse.util.json.JsonParseException) CreateDataverseCommand(edu.harvard.iq.dataverse.engine.command.impl.CreateDataverseCommand) Dataverse(edu.harvard.iq.dataverse.Dataverse) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) JsonParseException(edu.harvard.iq.dataverse.util.json.JsonParseException) EJBException(javax.ejb.EJBException) JsonParsingException(javax.json.stream.JsonParsingException) ConstraintViolationException(javax.validation.ConstraintViolationException) ConstraintViolation(javax.validation.ConstraintViolation) StringReader(java.io.StringReader) ConstraintViolationException(javax.validation.ConstraintViolationException) EJBException(javax.ejb.EJBException) JsonParsingException(javax.json.stream.JsonParsingException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

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