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);
}
}
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();
}
}
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.");
}
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();
}
}
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());
}
}
Aggregations