Example usage for javax.json JsonBuilderFactory createObjectBuilder

List of usage examples for javax.json JsonBuilderFactory createObjectBuilder

Introduction

In this page you can find the example usage for javax.json JsonBuilderFactory createObjectBuilder.

Prototype

JsonObjectBuilder createObjectBuilder();

Source Link

Document

Creates a JsonObjectBuilder instance that is used to build JsonObject .

Usage

From source file:httputils.RavelloHttpClient.java

public JsonObject publishBlueprint(String applicationName, int blueprintId, int stopTime, int startupDelay,
        String preferredCloud, String preferredRegion, boolean startAllVms, boolean costOptimized)
        throws RavelloException, InterruptedException {
    JsonObject value = null;/*  www . ja  v  a 2s  .  com*/
    HttpResponse response = null;

    try {
        response = this.getBlueprint(blueprintId);
        if (!HttpUtil.verifyResponseWithoutConsuming(response)) {
            EntityUtils.consumeQuietly(response.getEntity());
            throw new RavelloException("Failed to get blueprint number " + blueprintId + " error: "
                    + response.getStatusLine().toString());
        }
        JsonObject vmTemp = HttpUtil.convertResponseToJson(response);
        EntityUtils.consume(response.getEntity());

        JsonBuilderFactory factory = Json.createBuilderFactory(null);
        Iterator<Map.Entry<String, JsonValue>> it = vmTemp.entrySet().iterator();
        JsonObjectBuilder builder = factory.createObjectBuilder();
        Map.Entry<String, JsonValue> ent;
        while (it.hasNext()) {
            ent = it.next();
            if (!ent.getKey().equals("id") && !ent.getKey().equals("owner")) {
                builder.add(ent.getKey(), ent.getValue());
            }
        }
        builder.add("name", applicationName);
        value = builder.build();
        vmTemp = null;

        response = this.createApplication(value);
        this.verifyResponseAndConsume(response, "Failed to create application - error: ");

        value = HttpUtil.convertResponseToJson(response);
        EntityUtils.consumeQuietly(response.getEntity());

        int appId = value.getInt("id");

        if (costOptimized) {
            value = factory.createObjectBuilder().add("startAllVms", startAllVms).build();
        } else {
            value = factory.createObjectBuilder().add("startAllVms", startAllVms)
                    .add("preferredCloud", preferredCloud).add("preferredRegion", preferredRegion)
                    .add("optimizationLevel", "PERFORMANCE_OPTIMIZED").build();
        }
        response = this.post("/applications/" + appId + "/publish", value);
        this.verifyResponseAndConsume(response, "Failed to publish application - error: ");

        value = factory.createObjectBuilder().add("expirationFromNowSeconds", stopTime).build();
        response = this.post("/applications/" + appId + "/setExpiration", value);
        if (!HttpUtil.verifyResponseAndConsume(response)) {
            throw new RavelloException("Failed to set expiration time for application - error: "
                    + response.getStatusLine().toString() + "\n"
                    + "THIS ERROR MAY CAUSE APPLICATION TO RUN INDEFINITELY - MAKE SURE TO CHECK IT STOPPED");
        }

        if (!startAllVms) {
            response = this.getApplication(appId);
            if (!HttpUtil.verifyResponseWithoutConsuming(response)) {
                EntityUtils.consumeQuietly(response.getEntity());
                throw new RavelloException(
                        "Failed to get application status - error: " + response.getStatusLine().toString());
            }
            value = HttpUtil.convertResponseToJson(response);

            return value;
        }

        String state;
        JsonArray jArr;
        boolean allStarted;
        while (true) {
            allStarted = true;
            response = this.getApplication(appId);
            if (!HttpUtil.verifyResponseWithoutConsuming(response)) {
                EntityUtils.consumeQuietly(response.getEntity());
                throw new RavelloException(
                        "Failed to get application status - error: " + response.getStatusLine().toString());
            }
            value = HttpUtil.convertResponseToJson(response);

            jArr = value.getJsonObject("deployment").getJsonArray("vms");
            for (int jt = 0; jt < jArr.size(); jt++) {
                state = jArr.getJsonObject(jt).getString("state");
                allStarted = state.equals("STARTED");
                if (state.equals("ERROR")) {
                    throw new RavelloException(
                            "vm" + jArr.getJsonObject(jt).getString("name") + " failed to start");
                }
                if (!allStarted) {
                    break;
                }
            }

            if (allStarted) {
                break;
            } else {
                EntityUtils.consumeQuietly(response.getEntity());
                Thread.sleep(20000);
            }
        }

    } catch (ClientProtocolException e) {
        throw new RavelloException("ClientProtocolException - " + e.getMessage());
    } catch (IOException e) {
        throw new RavelloException("IOException - " + e.getMessage());
    } catch (NullPointerException e) {
        throw new RavelloException("NullPointerException - " + e.getMessage());
    }

    Thread.sleep(startupDelay * 1000);

    return value;
}

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(// www .ja v  a2  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 void addField(final JsonObjectBuilder builder, final JsonBuilderFactory factory,
        final String key, final Map<String, String> values) {
    if (values == null) {
        return;/*from ww  w  . j  a  va 2 s  .com*/
    }

    final JsonObjectBuilder mapBuilder = factory.createObjectBuilder();
    for (final Map.Entry<String, String> entry : values.entrySet()) {
        if (entry.getKey() == null || entry.getValue() == null) {
            continue;
        }

        mapBuilder.add(entry.getKey(), entry.getValue());
    }

    builder.add(key, mapBuilder);
}

From source file:org.opendaylight.centinel.output.CentinelOutput.java

@Override
public void write(Message message) throws Exception {

    JsonObject inputJson = null;/*from  ww w. ja va2s  . com*/
    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);
    }
}