Example usage for javax.json JsonObjectBuilder build

List of usage examples for javax.json JsonObjectBuilder build

Introduction

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

Prototype

JsonObject build();

Source Link

Document

Returns the JSON object associated with this object builder.

Usage

From source file:uk.trainwatch.app.util.Memo.java

@Override
public void runUtility() throws Exception {
    LOG.log(Level.INFO, "Initialising");

    Consumer<? super JsonStructure> consumer = RabbitMQ.jsonConsumer(con, "a51.li.memo");

    for (String fileName : files) {
        String t = title;/*from   w  w  w.ja  v  a2 s  .c o m*/
        if (t == null) {
            t = fileName;
        }

        LOG.log(Level.INFO, "Reading {0}", fileName);

        String text;
        try (BufferedReader r = new BufferedReader(new FileReader(fileName))) {
            text = r.lines().collect(Collectors.joining("<br/>"));
        }

        LOG.log(Level.INFO, "Generating json");

        JsonObjectBuilder b = Json.createObjectBuilder().add("user", user).add("hash", hash).add("type", type)
                .add("title", t).add("text", text);

        if (expires != null) {
            b.add("expires", expires.toString());
        }

        if (tweetAs != null) {
            b.add("tweetAs", tweetAs).add("tweet", t);
        }

        JsonObject o = b.build();

        LOG.log(Level.INFO, "Tweeting {0}", o);

        consumer.accept(o);

        LOG.log(Level.INFO, "Done");
    }

    System.exit(0);
}

From source file:org.grogshop.services.endpoints.impl.ShopUserProfileServiceImpl.java

@Override
public Response get(@PathParam("id") Long user_id) throws ServiceException {
    Profile p = profileService.getById(user_id);
    if (p == null) {
        throw new ServiceException("Profile for " + user_id + " doesn't exists");
    }//from   w  w  w . j a  v  a2 s  . c  o  m
    JsonObjectBuilder jsonObjBuilder = Json.createObjectBuilder();
    jsonObjBuilder.add("bio", (p.getIntroduction() == null) ? "" : p.getIntroduction());
    jsonObjBuilder.add("location", (p.getPostcode() == null) ? "" : p.getPostcode());
    jsonObjBuilder.add("username", (p.getRealname() == null) ? "" : p.getRealname());

    JsonObject jsonObj = jsonObjBuilder.build();
    return Response.ok(jsonObj.toString()).build();
}

From source file:co.runrightfast.vertx.orientdb.ODatabaseDocumentTxHealthCheck.java

@Override
protected Result check() throws Exception {
    try (final ODatabaseDocumentTx db = oDatabaseDocumentTxSupplier.get()) {
        final JsonObjectBuilder msgBuilder = Json.createObjectBuilder().add("db", getDatabaseInfo(db));
        if (CollectionUtils.isNotEmpty(documentObjects)) {
            final JsonObjectBuilder counts = Json.createObjectBuilder();
            documentObjects.stream().forEach(documentObject -> browseClass(db, documentObject, counts));
            msgBuilder.add("counts", counts);
        }/*www.  j  a  v  a 2s  . c  o m*/

        final JsonObject msg = msgBuilder.build();
        if (isHealthy(msg)) {
            return HealthCheck.Result.healthy(msg.toString());
        }
        return HealthCheck.Result.unhealthy(msg.toString());
    } catch (final Exception e) {
        final JsonObjectBuilder msg = Json.createObjectBuilder().add("db",
                Json.createObjectBuilder().add("name", databaseName).build());
        return HealthCheck.Result
                .unhealthy(new ODatabaseDocumentTxHealthCheckException(msg.build().toString(), e));
    }
}

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

private static JsonObject initQCObject(QC qc) {
    mergeUIDs(qc);/* w  w w.  j ava  2 s . com*/
    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.piwik.java.tracking.PiwikTracker.java

/**
 * Send multiple requests in a single HTTP call.  More efficient than sending
 * several individual requests.  Specify the AuthToken if parameters that require
 * an auth token is used./*from w  w  w. j a  v a2  s.c  o m*/
 * @param requests the requests to send
 * @param authToken specify if any of the parameters use require AuthToken
 * @return the response from these requests
 * @throws IOException thrown if there was a problem with this connection
 */
public HttpResponse sendBulkRequest(Iterable<PiwikRequest> requests, String authToken) throws IOException {
    if (authToken != null && authToken.length() != PiwikRequest.AUTH_TOKEN_LENGTH) {
        throw new IllegalArgumentException(
                authToken + " is not " + PiwikRequest.AUTH_TOKEN_LENGTH + " characters long.");
    }

    JsonObjectBuilder ob = Json.createObjectBuilder();
    JsonArrayBuilder ab = Json.createArrayBuilder();

    for (PiwikRequest request : requests) {
        ab.add("?" + request.getQueryString());
    }

    ob.add(REQUESTS, ab);

    if (authToken != null) {
        ob.add(AUTH_TOKEN, authToken);
    }

    HttpClient client = getHttpClient();
    HttpPost post = new HttpPost(uriBuilder.build());
    post.setEntity(new StringEntity(ob.build().toString(), ContentType.APPLICATION_JSON));

    return client.execute(post);
}

From source file:au.org.ands.vocabs.toolkit.provider.transform.SolrIndexTransformProvider.java

@Override
public final boolean transform(final TaskInfo taskInfo, final JsonNode subtask,
        final HashMap<String, String> results) {
    Path dir = Paths.get(ToolkitFileUtils.getTaskHarvestOutputPath(taskInfo));
    ConceptHandler conceptHandler = new ConceptHandler();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
        for (Path entry : stream) {
            RDFFormat format = Rio.getParserFormatForFileName(entry.toString());
            RDFParser rdfParser = Rio.createParser(format);
            rdfParser.setRDFHandler(conceptHandler);
            FileInputStream is = new FileInputStream(entry.toString());
            rdfParser.parse(is, entry.toString());

            logger.debug("Reading RDF:" + entry.toString());

        }//ww  w  . ja va  2 s.  c  om
    } catch (DirectoryIteratorException | IOException | RDFParseException | RDFHandlerException ex) {
        // I/O error encountered during the iteration,
        // the cause is an IOException
        results.put(TaskStatus.EXCEPTION, "Exception in SolrIndexTransform while Parsing RDF");
        logger.error("Exception in SolrIndexTransform while Parsing RDF:", ex);
        return false;
    }

    String resultFileName = ToolkitFileUtils.getTaskOutputPath(taskInfo, "concepts_solr.json");
    try {
        FileOutputStream out = new FileOutputStream(resultFileName);
        JsonObjectBuilder job = Json.createObjectBuilder();
        job.add("concepts_count", conceptHandler.getCountedPrefLabels());
        results.put("concepts_count", Integer.toString(conceptHandler.getCountedPrefLabels()));
        job.add("concepts_text", conceptHandler.getConceptText());
        results.put("concepts_solr", resultFileName);

        JsonWriter jsonWriter = Json.createWriter(out);
        jsonWriter.writeObject(job.build());
        jsonWriter.close();
    } catch (FileNotFoundException ex) {
        results.put(TaskStatus.EXCEPTION, "Exception in SolrIndexTransform while generating result");
        logger.error("Exception in SolrIndexTransform generating result:", ex);
        return false;
    }
    return true;
}

From source file:com.adobe.cq.wcm.core.components.internal.models.v1.ImageImpl.java

protected void buildJson() {
    JsonArrayBuilder smartSizesJsonBuilder = Json.createArrayBuilder();
    for (int size : smartSizes) {
        smartSizesJsonBuilder.add(size);
    }//from w w w.  j  av  a2 s  .  c  om
    JsonArrayBuilder smartImagesJsonBuilder = Json.createArrayBuilder();
    for (String image : smartImages) {
        smartImagesJsonBuilder.add(image);
    }
    JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
    jsonObjectBuilder.add(JSON_SMART_IMAGES, smartImagesJsonBuilder);
    jsonObjectBuilder.add(JSON_SMART_SIZES, smartSizesJsonBuilder);
    jsonObjectBuilder.add(JSON_LAZY_ENABLED, !disableLazyLoading);
    json = jsonObjectBuilder.build().toString();
}

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

public JsonObject selectAll_havahol(String filter_h_id) throws SQLException {
    checkConnection();/*  www  .j  av  a2s  .c  om*/

    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.hyperledger.fabric.sdk.MemberServicesFabricCAImpl.java

/**
 * Enroll the user with member service/*  w w  w.j  a v a  2s .  c o 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:edu.harvard.iq.dataverse.datasetutility.FileUploadTestPage.java

public String getReplacementFileMetadataAsJSON() {

    FileMetadata fm = getReplacementFileMetadata();
    if (fm == null) {
        msgt("Something is wrong here!!! Write error response 1");
        return null;
    }//ww w  . j  a  v  a 2 s  .co m

    JsonObjectBuilder jobj = json(fm.getDataFile(), fm);

    if (jobj == null) {
        msgt("Something is wrong here!!! Write error response 2");
        return null;
    }

    return jobj.build().toString();
}