List of usage examples for javax.json JsonBuilderFactory createArrayBuilder
JsonArrayBuilder createArrayBuilder();
From source file:org.apache.nifi.reporting.SiteToSiteProvenanceReportingTask.java
@Override public void onTrigger(final ReportingContext context) { final boolean isClustered = context.isClustered(); final String nodeId = context.getClusterNodeIdentifier(); if (nodeId == null && isClustered) { getLogger().debug(//from w w w . ja v a 2 s .com "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; } final ProcessGroupStatus procGroupStatus = context.getEventAccess().getControllerStatus(); final String rootGroupName = procGroupStatus == null ? null : procGroupStatus.getName(); final Map<String, String> componentMap = createComponentMap(procGroupStatus); final String nifiUrl = context.getProperty(INSTANCE_URL).evaluateAttributeExpressions().getValue(); URL url; try { url = new URL(nifiUrl); } catch (final MalformedURLException e1) { // already validated throw new AssertionError(); } final String hostname = url.getHost(); 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")); consumer.consumeEvents(context.getEventAccess(), context.getStateManager(), events -> { final long start = System.nanoTime(); // Create a JSON array of all the events in the current batch final JsonArrayBuilder arrayBuilder = factory.createArrayBuilder(); for (final ProvenanceEventRecord event : events) { final String componentName = componentMap.get(event.getComponentId()); arrayBuilder.add(serialize(factory, builder, event, df, componentName, hostname, url, rootGroupName, 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().debug("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("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 {} Provenance Events to destination in {} ms; Transaction ID = {}; First Event ID = {}", new Object[] { events.size(), transferMillis, transactionId, events.get(0).getEventId() }); } catch (final IOException e) { throw new ProcessException( "Failed to send Provenance Events to destination due to IOException:" + e.getMessage(), e); } }); }
From source file:org.apache.nifi.reporting.SiteToSiteProvenanceReportingTask.java
private static JsonArrayBuilder createJsonArray(JsonBuilderFactory factory, final Collection<String> values) { final JsonArrayBuilder builder = factory.createArrayBuilder(); for (final String value : values) { if (value != null) { builder.add(value);//from www.ja v a 2 s. c o m } } return builder; }
From source file:org.opendaylight.centinel.output.CentinelOutput.java
@Override public void write(Message message) throws Exception { JsonObject inputJson = null;/*from ww w. j av a 2 s .c o m*/ String body; try { Schema schemaStream = ReflectData.get().getSchema(StreamPojo.class); GenericRecord avroRecordStream = new Record(schemaStream); Schema schemaRules = ReflectData.get().getSchema(RulesPojo.class); GenericRecord recordRules = new Record(schemaRules); Stream stream = message.getStreams().get(0); StreamPojo streamPojo = new StreamPojo(stream); avroRecordStream.put("creatoruserid", streamPojo.getCreatoruserid()); avroRecordStream.put("matchingtype", streamPojo.getMatchingtype()); avroRecordStream.put("description", streamPojo.getDescription()); avroRecordStream.put("disabled", streamPojo.getDisabled()); StreamRule streamRule = stream.getStreamRules().get(0); RulesPojo rule = new RulesPojo(streamRule); recordRules.put("field", rule.getField()); recordRules.put("streamId", rule.getStreamId()); recordRules.put("ruleId", rule.getId()); recordRules.put("type", rule.getType()); recordRules.put("inverted", rule.getInverted()); recordRules.put("value", rule.getValue()); avroRecordStream.put("rules", recordRules); avroRecordStream.put("streamId", streamPojo.getId()); avroRecordStream.put("title", streamPojo.getTitle()); MessagePojo messagePojo = new MessagePojo(message); Schema schemaMatchingMessage = ReflectData.get().getSchema(MessagePojo.class); GenericRecord recordMatchingMessage = new Record(schemaMatchingMessage); recordMatchingMessage.put("fields", messagePojo.getFields()); recordMatchingMessage.put("id", messagePojo.getId()); recordMatchingMessage.put("hostName", messagePojo.getHostName()); recordMatchingMessage.put("sourceInetAddress", messagePojo.isSourceInetAddress()); recordMatchingMessage.put("journalOffset", messagePojo.getJournalOffset()); recordMatchingMessage.put("message", messagePojo.getMessage()); recordMatchingMessage.put("source", messagePojo.getSource()); recordMatchingMessage.put("sourceInput", messagePojo.getSourceInput()); recordMatchingMessage.put("streams", avroRecordStream); recordMatchingMessage.put("timestamp", messagePojo.getTimestamp()); recordMatchingMessage.put("validErrors", messagePojo.getValidErrors()); body = recordMatchingMessage.toString(); body = body.replace("timestamp", "event_timestamp"); String regex = "([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9.]{6})Z"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(body); if (matcher.find()) { String str = "\"" + matcher.group() + "\""; str = str.replace("T", " "); str = str.replace("Z", ""); body = body.replaceAll(regex, str); } } catch (Exception e) { throw e; } JsonBuilderFactory factory = Json.createBuilderFactory(null); inputJson = factory.createObjectBuilder() .add("input", factory.createObjectBuilder().add("eventType", "stream").add("eventBodyType", "avro") .add("eventBody", body).add("eventKeys", factory.createArrayBuilder().add("event_timestamp").add("streams:streamId") .add("fields:message").add("fields:facility").add("fields:severity") .add("fields:log_time").add("fields:hostname"))) .build(); final URL url; try { url = new URL("http://" + properties.getProperty("centinel_ip") + ":" + properties.getProperty("centinel_port") + "/restconf/operations/eventinput:notify-event"); } catch (MalformedURLException e) { throw new AlarmCallbackException("Error while constructing URL of Slack API.", e); } // Create authentication string and encode it to Base64 final String admin = "admin"; String authStr = admin + ":" + admin; String encodedAuthStr = Base64.encodeBase64String(authStr.getBytes()); try { // Create Http connection HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // Set connection properties connection.setRequestMethod("POST"); connection.setRequestProperty("Authorization", "Basic " + encodedAuthStr); connection.setRequestProperty("Accept", MediaType.APPLICATION_JSON); connection.setRequestProperty("content-type", MediaType.APPLICATION_JSON); // Send post request connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(inputJson.toString()); out.flush(); out.close(); // Get the response from connection's inputStream connection.getInputStream(); } catch (IOException e) { throw new AlarmCallbackException("Could not open connection to Centinel Rest API", e); } }