use of javax.json.Json in project nifi by apache.
the class SiteToSiteBulletinReportingTask method onTrigger.
@Override
public void onTrigger(final ReportingContext context) {
final boolean isClustered = context.isClustered();
final String nodeId = context.getClusterNodeIdentifier();
if (nodeId == null && isClustered) {
getLogger().debug("This instance of NiFi is configured for clustering, but the Cluster Node Identifier is not yet available. " + "Will wait for Node Identifier to be established.");
return;
}
if (lastSentBulletinId < 0) {
Map<String, String> state;
try {
state = context.getStateManager().getState(Scope.LOCAL).toMap();
} catch (IOException e) {
getLogger().error("Failed to get state at start up due to:" + e.getMessage(), e);
return;
}
if (state.containsKey(LAST_EVENT_ID_KEY)) {
lastSentBulletinId = Long.parseLong(state.get(LAST_EVENT_ID_KEY));
}
}
final BulletinQuery bulletinQuery = new BulletinQuery.Builder().after(lastSentBulletinId).build();
final List<Bulletin> bulletins = context.getBulletinRepository().findBulletins(bulletinQuery);
if (bulletins == null || bulletins.isEmpty()) {
getLogger().debug("No events to send because no events are stored in the repository.");
return;
}
final OptionalLong opMaxId = bulletins.stream().mapToLong(t -> t.getId()).max();
final Long currMaxId = opMaxId.isPresent() ? opMaxId.getAsLong() : -1;
if (currMaxId < lastSentBulletinId) {
getLogger().warn("Current bulletin max id is {} which is less than what was stored in state as the last queried event, which was {}. " + "This means the bulletins repository restarted its ids. Restarting querying from the beginning.", new Object[] { currMaxId, lastSentBulletinId });
lastSentBulletinId = -1;
}
if (currMaxId == lastSentBulletinId) {
getLogger().debug("No events to send due to the current max id being equal to the last id that was sent.");
return;
}
final String platform = context.getProperty(PLATFORM).evaluateAttributeExpressions().getValue();
final Map<String, ?> config = Collections.emptyMap();
final JsonBuilderFactory factory = Json.createBuilderFactory(config);
final JsonObjectBuilder builder = factory.createObjectBuilder();
final DateFormat df = new SimpleDateFormat(TIMESTAMP_FORMAT);
df.setTimeZone(TimeZone.getTimeZone("Z"));
final long start = System.nanoTime();
// Create a JSON array of all the events in the current batch
final JsonArrayBuilder arrayBuilder = factory.createArrayBuilder();
for (final Bulletin bulletin : bulletins) {
if (bulletin.getId() > lastSentBulletinId) {
arrayBuilder.add(serialize(factory, builder, bulletin, df, platform, nodeId));
}
}
final JsonArray jsonArray = arrayBuilder.build();
// Send the JSON document for the current batch
try {
final Transaction transaction = getClient().createTransaction(TransferDirection.SEND);
if (transaction == null) {
getLogger().info("All destination nodes are penalized; will attempt to send data later");
return;
}
final Map<String, String> attributes = new HashMap<>();
final String transactionId = UUID.randomUUID().toString();
attributes.put("reporting.task.transaction.id", transactionId);
attributes.put("reporting.task.name", getName());
attributes.put("reporting.task.uuid", getIdentifier());
attributes.put("reporting.task.type", this.getClass().getSimpleName());
attributes.put("mime.type", "application/json");
final byte[] data = jsonArray.toString().getBytes(StandardCharsets.UTF_8);
transaction.send(data, attributes);
transaction.confirm();
transaction.complete();
final long transferMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
getLogger().info("Successfully sent {} Bulletins to destination in {} ms; Transaction ID = {}; First Event ID = {}", new Object[] { bulletins.size(), transferMillis, transactionId, bulletins.get(0).getId() });
} catch (final IOException e) {
throw new ProcessException("Failed to send Bulletins to destination due to IOException:" + e.getMessage(), e);
}
// Store the id of the last event so we know where we left off
try {
context.getStateManager().setState(Collections.singletonMap(LAST_EVENT_ID_KEY, String.valueOf(currMaxId)), Scope.LOCAL);
} catch (final IOException ioe) {
getLogger().error("Failed to update state to {} due to {}; this could result in events being re-sent after a restart.", new Object[] { currMaxId, ioe.getMessage() }, ioe);
}
lastSentBulletinId = currMaxId;
}
use of javax.json.Json in project docker-java-api by amihaiemil.
the class RtContainersTestCase method wellformedUriAndPayloadForCreateJson.
/**
* Test for {@link RtContainers#create(JsonObject)}: request URI must be
* well-formed and payload must include the input JSON.
* @throws Exception If something goes wrong.
*/
@Test
public void wellformedUriAndPayloadForCreateJson() throws Exception {
final JsonObject json = Json.createObjectBuilder().add("Image", "ubuntu").add("Entrypoint", "script.sh").add("StopSignal", "SIGTERM").build();
new RtContainers(new AssertRequest(new Response(HttpStatus.SC_CREATED, "{ \"Id\": \"df2419f4\" }"), new Condition("Resource path must be /create", req -> req.getRequestLine().getUri().endsWith("/create")), new Condition("Payload must include the input JSON attributes.", req -> {
final JsonObject payload = new PayloadOf(req);
// @checkstyle LineLength (3 lines)
return payload.getString("Image").equals(json.getString("Image")) && payload.getString("Entrypoint").equals(json.getString("Entrypoint")) && payload.getString("StopSignal").equals(json.getString("StopSignal"));
})), URI.create("http://localhost/test")).create(json);
}
use of javax.json.Json in project docker-java-api by amihaiemil.
the class RtContainersTestCase method wellformedUriAndPayloadForCreateNameAndJson.
/**
* Test for {@link RtContainers#create(String, JsonObject)}: request URI
* must be well-formed and payload must include the input JSON.
* @throws Exception If something goes wrong.
*/
@Test
public void wellformedUriAndPayloadForCreateNameAndJson() throws Exception {
final JsonObject json = Json.createObjectBuilder().add("Image", "ubuntu").add("Entrypoint", "script.sh").add("StopSignal", "SIGTERM").build();
new RtContainers(new AssertRequest(new Response(HttpStatus.SC_CREATED, "{ \"Id\": \"df2419f4\" }"), new Condition("Resource path must be /create?name=image_name", // @checkstyle LineLength (1 line)
req -> req.getRequestLine().getUri().endsWith("/create?name=image_name")), new Condition("Payload must include the input JSON attributes.", req -> {
final JsonObject payload = new PayloadOf(req);
// @checkstyle LineLength (3 lines)
return payload.getString("Image").equals(json.getString("Image")) && payload.getString("Entrypoint").equals(json.getString("Entrypoint")) && payload.getString("StopSignal").equals(json.getString("StopSignal"));
})), URI.create("http://localhost/test")).create("image_name", json);
}
use of javax.json.Json in project CoreNLP by stanfordnlp.
the class JSONAnnotationReader method toToken.
public CoreLabel toToken(JsonObject json) {
CoreLabel token = tokenFactory.makeToken();
token.setIndex(json.getInt("index"));
token.setValue(json.getString("word", null));
token.setWord(json.getString("word", null));
token.setOriginalText(json.getString("originalText", null));
token.setLemma(json.getString("lemma", null));
token.setBeginPosition(json.getInt("characterOffsetBegin"));
token.setEndPosition(json.getInt("characterOffsetEnd"));
token.setTag(json.getString("pos", null));
token.setNER(json.getString("ner", null));
token.set(CoreAnnotations.NormalizedNamedEntityTagAnnotation.class, json.getString("normalizedNER", null));
token.set(CoreAnnotations.SpeakerAnnotation.class, json.getString("speaker", null));
token.set(CoreAnnotations.TrueCaseAnnotation.class, json.getString("truecase", null));
token.set(CoreAnnotations.TrueCaseTextAnnotation.class, json.getString("truecaseText", null));
token.set(CoreAnnotations.BeforeAnnotation.class, json.getString("before", null));
token.set(CoreAnnotations.AfterAnnotation.class, json.getString("after", null));
token.set(CoreAnnotations.WikipediaEntityAnnotation.class, json.getString("entitylink", null));
token.set(TimeAnnotations.TimexAnnotation.class, toNullable(json.getJsonObject("timex"), obj -> toTimex(obj)));
return token;
}
use of javax.json.Json in project dataverse by IQSS.
the class JsonPrinter method json.
public static JsonObjectBuilder json(IpGroup grp) {
// collect single addresses
List<String> singles = grp.getRanges().stream().filter(IpAddressRange::isSingleAddress).map(IpAddressRange::getBottom).map(IpAddress::toString).collect(toList());
// collect "real" ranges
List<List<String>> ranges = grp.getRanges().stream().filter(rng -> !rng.isSingleAddress()).map(rng -> Arrays.asList(rng.getBottom().toString(), rng.getTop().toString())).collect(toList());
JsonObjectBuilder bld = jsonObjectBuilder().add("alias", grp.getPersistedGroupAlias()).add("identifier", grp.getIdentifier()).add("id", grp.getId()).add("name", grp.getDisplayName()).add("description", grp.getDescription());
if (!singles.isEmpty()) {
bld.add("addresses", asJsonArray(singles));
}
if (!ranges.isEmpty()) {
JsonArrayBuilder rangesBld = Json.createArrayBuilder();
ranges.forEach(r -> rangesBld.add(Json.createArrayBuilder().add(r.get(0)).add(r.get(1))));
bld.add("ranges", rangesBld);
}
return bld;
}
Aggregations