Example usage for javax.json JsonObjectBuilder add

List of usage examples for javax.json JsonObjectBuilder add

Introduction

In this page you can find the example usage for javax.json JsonObjectBuilder add.

Prototype

JsonObjectBuilder add(String name, JsonArrayBuilder builder);

Source Link

Document

Adds a name/ JsonArray pair to the JSON object associated with this object builder.

Usage

From source file:no.sintef.jarfter.PostgresqlInteractor.java

public JsonObject selectAll_havahol(String filter_h_id) throws SQLException {
    checkConnection();/*  w  w w . j a v  a 2s  .c  o m*/

    String h_id = "h_id";
    String visual_name = "visual_name";
    String file = "file";
    PreparedStatement st = conn.prepareStatement("SELECT h_id, visual_name FROM havahol WHERE h_id ~ ?;");
    if (filter_h_id == null) {
        st.setString(1, ".*");
    } else {
        st.setString(1, filter_h_id);
    }
    ResultSet rs = st.executeQuery();
    JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
    while (rs.next()) {
        JsonObjectBuilder job = Json.createObjectBuilder();
        job.add(h_id, rs.getString(h_id));
        job.add(visual_name, rs.getString(visual_name));

        jsonArrayBuilder.add(job.build());
    }

    rs.close();
    st.close();
    return Json.createObjectBuilder().add("havahol", jsonArrayBuilder.build()).build();
}

From source file:org.openlmis.converter.DirectDateTypeConverter.java

@Override
public void convert(JsonObjectBuilder builder, Mapping mapping, String value) {
    if (isBlank(value) || "null".equals(value)) {
        logger.debug("Blank/null value for field: {}", mapping.getTo());
        return;//from w  w w  .j a v  a2  s.co m
    }

    String date = parseDate(value);

    if (null == date || "null".equals(date)) {
        logger.debug("Can't parse date {} for field: {}", value, mapping.getTo());
        return;
    }

    builder.add(mapping.getTo(), date);
}

From source file:com.buffalokiwi.aerodrome.jet.products.ShippingExceptionRec.java

/**
 * Retrieve the JSON object for this//from w w  w. j a  v a2  s.c om
 * @return json
 */
@Override
public JsonObject toJSON() {
    JsonObjectBuilder o = Json.createObjectBuilder();
    if (serviceLevel != ShippingServiceLevel.NONE)
        o.add("service_level", serviceLevel.getText());

    if (shippingMethod != ShippingMethod.NONE)
        o.add("shipping_method", shippingMethod.getText());

    if (overrideType != ShipOverrideType.NONE) {
        o.add("override_type", overrideType.getText());
        //..Don't use the currency formatted string here.  Jet wants a float.
        o.add("shipping_charge_amount", shippingChargeAmount.asBigDecimal());
    }

    o.add("shipping_exception_type", shippingExceptionType.getText());

    return o.build();
}

From source file:no.sintef.jarfter.PostgresqlInteractor.java

public JsonObject selectAllTransfomations(String filter_uri) throws JarfterException {
    checkConnection();/*from  w  w  w  .j  a  v a2  s.com*/

    String table = "transformations";
    String uri = "uri";
    String name = "name";
    String metadata = "metadata";
    String clojure = "clojure";
    JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
    try {
        PreparedStatement st = conn.prepareStatement("SELECT " + uri + ", " + name + ", " + metadata + ", "
                + clojure + " FROM transformations WHERE uri ~ ?;");
        if (filter_uri == null) {
            st.setString(1, ".*");
        } else {
            st.setString(1, filter_uri);
        }
        log("selectAllTransfomations - calling executeQuery");
        ResultSet rs = st.executeQuery();
        while (rs.next()) {
            JsonObjectBuilder job = Json.createObjectBuilder();
            job.add(uri, rs.getString(uri));
            job.add(name, rs.getString(name));
            job.add(metadata, rs.getString(metadata));
            job.add(clojure, rs.getString(clojure));
            jsonArrayBuilder.add(job.build());
        }

        rs.close();
        st.close();
    } catch (SQLException sqle) {
        log("selectAllTransformations - got SQLException");
        error(sqle);
        throw new JarfterException(JarfterException.Error.SQL_UNKNOWN_ERROR, sqle.getLocalizedMessage());
    }
    return Json.createObjectBuilder().add(table, jsonArrayBuilder.build()).build();
}

From source file:org.dcm4che3.tool.qc.QC.java

private static JsonObject initQCObject(QC qc) {
    mergeUIDs(qc);//from  w w  w. j  a v a  2s .  c  o m
    JsonObjectBuilder builder = Json.createObjectBuilder().add("operation", qc.getOperation().toString())
            .add("updateScope",
                    qc.getUpdateScope() == null ? QCUpdateScope.NONE.toString()
                            : qc.getUpdateScope().toString())
            .add("moveSOPUIDs", toArrayBuilder(qc.getMoveUIDs()))
            .add("cloneSOPUIDs", toArrayBuilder(qc.getCloneUIDs()))
            .add("restoreOrRejectUIDs", toArrayBuilder(qc.getRrUIDs()))
            .add("targetStudyUID", qc.getTargetStudyUID())
            .add("qcRejectionCode", toCodeObject(qc.getQcRejectionCode()))
            .add("targetSeriesData", toAttributesObject(qc.getTargetSeriesAttrs()))
            .add("targetStudyData", toAttributesObject(qc.getTargetStudyAttrs()))
            .add("updateData", toAttributesObject(qc.getUpdateAttrs()));
    if (qc.getPid() != null)
        builder.add("pid", toIDWithIssuerObject(qc.getPid()));
    return builder.build();
}

From source file:org.openlmis.converter.IdTypeConverter.java

@Override
public void convert(JsonObjectBuilder builder, Mapping mapping, String value) {
    BaseCommunicationService service = services.getService(mapping.getEntityName());
    String by = getBy(mapping.getType());

    JsonObject jsonRepresentation = service.findBy(by, value);

    if (null == jsonRepresentation) {
        logger.warn("The CSV file contained reference to entity {} "
                + "with {} {} but such reference does not exist.", mapping.getEntityName(), by, value);
    } else {//www.ja va2 s  . com
        builder.add(mapping.getTo(), jsonRepresentation.getString(ID));
    }
}

From source file:org.hyperledger.fabric.sdk.MemberServicesFabricCAImpl.java

/**
 * Enroll the user with member service/*from   w  w  w.  j a va  2  s  .  co  m*/
 *
 * @param req Enrollment request with the following fields: name, enrollmentSecret
 * @return enrollment
 */
public Enrollment enroll(EnrollmentRequest req) throws EnrollmentException {

    logger.debug(String.format("[MemberServicesFabricCAImpl.enroll] [%s]", req));
    if (req == null) {
        throw new RuntimeException("req is not set");
    }
    final String user = req.getEnrollmentID();
    final String secret = req.getEnrollmentSecret();
    if (StringUtil.isNullOrEmpty(user)) {
        throw new RuntimeException("req.enrollmentID is not set");
    }
    if (StringUtil.isNullOrEmpty(secret)) {
        throw new RuntimeException("req.enrollmentSecret is not set");
    }

    logger.debug("[MemberServicesFabricCAImpl.enroll] Generating keys...");

    try {
        // generate ECDSA keys: signing and encryption keys
        KeyPair signingKeyPair = cryptoPrimitives.ecdsaKeyGen();
        logger.debug("[MemberServicesFabricCAImpl.enroll] Generating keys...done!");
        //  KeyPair encryptionKeyPair = cryptoPrimitives.ecdsaKeyGen();

        PKCS10CertificationRequest csr = cryptoPrimitives.generateCertificationRequest(user, signingKeyPair);
        String pem = cryptoPrimitives.certificationRequestToPEM(csr);
        JsonObjectBuilder factory = Json.createObjectBuilder();
        factory.add("certificate_request", pem);
        JsonObject postObject = factory.build();
        StringWriter stringWriter = new StringWriter();

        JsonWriter jsonWriter = Json.createWriter(new PrintWriter(stringWriter));

        jsonWriter.writeObject(postObject);

        jsonWriter.close();

        String str = stringWriter.toString();

        logger.debug("[MemberServicesFabricCAImpl.enroll] Generating keys...done!");

        String responseBody = httpPost(url + COP_ENROLLMENBASE, str,
                new UsernamePasswordCredentials(user, secret));

        logger.debug("response" + responseBody);

        JsonReader reader = Json.createReader(new StringReader(responseBody));
        JsonObject jsonst = (JsonObject) reader.read();
        String result = jsonst.getString("result");
        boolean success = jsonst.getBoolean("success");
        logger.debug(String.format("[MemberServicesFabricCAImpl] enroll success:[%s], result:[%s]", success,
                result));

        if (!success) {
            EnrollmentException e = new EnrollmentException("COP Failed response success is false. " + result,
                    new Exception());
            logger.error(e.getMessage());
            throw e;
        }

        Base64.Decoder b64dec = Base64.getDecoder();
        String signedPem = new String(b64dec.decode(result.getBytes()));
        logger.info(String.format("[MemberServicesFabricCAImpl] enroll returned pem:[%s]", signedPem));

        Enrollment enrollment = new Enrollment();
        enrollment.setKey(signingKeyPair);
        enrollment.setPublicKey(Hex.toHexString(signingKeyPair.getPublic().getEncoded()));
        enrollment.setCert(signedPem);
        return enrollment;

    } catch (Exception e) {
        EnrollmentException ee = new EnrollmentException(String.format("Failed to enroll user %s ", user), e);
        logger.error(ee.getMessage(), ee);
        throw ee;
    }

}

From source file:co.runrightfast.core.application.event.AppEvent.java

private void addException(final JsonObjectBuilder json) {
    if (exception != null) {
        final JsonObjectBuilder exBuilder = Json.createObjectBuilder()
                .add("class", exception.getClass().getName())
                .add("stacktrace", ExceptionUtils.getStackTrace(exception));
        final Throwable rootCause = ExceptionUtils.getRootCause(exception);
        if (rootCause != null) {
            exBuilder.add("rootCause", rootCause.getClass().getName());
        }/*from   w  ww. j  ava  2  s  . c  o  m*/
        json.add("exception", exBuilder);
    }
}

From source file:com.adobe.cq.wcm.core.components.extension.contentfragment.internal.models.v1.ContentFragmentImpl.java

@Nonnull
@Override//from  w w  w  .  j  a  va 2  s. c o  m
public String getEditorJSON() {
    JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
    jsonObjectBuilder.add("title", fragment.getTitle());
    jsonObjectBuilder.add("path", path);
    if (variationName != null) {
        jsonObjectBuilder.add("variation", variationName);
    }
    if (elementNames != null) {
        JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
        for (String ele : elementNames) {
            arrayBuilder.add(ele);
        }
        jsonObjectBuilder.add("elements", arrayBuilder);
    }
    Iterator<Resource> associatedContentIter = fragment.getAssociatedContent();
    if (associatedContentIter.hasNext()) {
        JsonArrayBuilder associatedContentArray = Json.createArrayBuilder();
        while (associatedContentIter.hasNext()) {
            Resource resource = associatedContentIter.next();
            ValueMap vm = resource.adaptTo(ValueMap.class);
            JsonObjectBuilder contentObject = Json.createObjectBuilder();
            if (vm != null && vm.containsKey(JCR_TITLE)) {
                contentObject.add("title", vm.get(JCR_TITLE, String.class));
            }
            contentObject.add("path", resource.getPath());
            associatedContentArray.add(contentObject);
        }
        jsonObjectBuilder.add("associatedContent", associatedContentArray);
    }
    return jsonObjectBuilder.build().toString();
}

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;// w  w  w.j  a va  2  s.  c  o m
    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;
}