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:eu.forgetit.middleware.component.Contextualizer.java

public void executeTextContextualization(Exchange exchange) {

    taskStep = "CONTEXTUALIZER_CONTEXTUALIZE_DOCUMENTS";

    logger.debug("New message retrieved for " + taskStep);

    JsonObjectBuilder job = Json.createObjectBuilder();

    JsonObject headers = MessageTools.getHeaders(exchange);

    long taskId = Long.parseLong(headers.getString("taskId"));
    scheduler.updateTask(taskId, TaskStatus.RUNNING, taskStep, null);

    JsonObject jsonBody = MessageTools.getBody(exchange);

    String cmisServerId = null;//from w  w w.j  a v a  2s  . c o m

    if (jsonBody != null) {

        cmisServerId = jsonBody.getString("cmisServerId");
        JsonArray jsonEntities = jsonBody.getJsonArray("entities");

        job.add("cmisServerId", cmisServerId);
        job.add("entities", jsonEntities);

        for (JsonValue jsonValue : jsonEntities) {

            JsonObject jsonObject = (JsonObject) jsonValue;

            String type = jsonObject.getString("type");

            if (type.equals(Collection.class.getName()))
                continue;

            long pofId = jsonObject.getInt("pofId");

            try {

                String collectorStorageFolder = ConfigurationManager.getConfiguration()
                        .getString("collector.storage.folder");

                Path sipPath = Paths.get(collectorStorageFolder + File.separator + pofId);

                Path metadataPath = Paths.get(sipPath.toString(), "metadata");

                Path contentPath = Paths.get(sipPath.toString(), "content");

                Path contextAnalysisPath = Paths.get(metadataPath.toString(), "worldContext.json");

                logger.debug("Looking for text documents in folder: " + contentPath);

                List<File> documentList = getFilteredDocumentList(contentPath);

                logger.debug("Document List for Contextualization: " + documentList);

                if (documentList != null && !documentList.isEmpty()) {

                    File[] documents = documentList.stream().toArray(File[]::new);

                    context = service.contextualize(documents);

                    logger.debug("World Context:\n");

                    for (String contextEntry : context) {

                        logger.debug(contextEntry);
                    }

                    StringBuilder contextResult = new StringBuilder();

                    for (int i = 0; i < context.length; i++) {

                        Map<String, String> jsonMap = new HashMap<>();
                        jsonMap.put("filename", documents[i].getName());
                        jsonMap.put("context", context[i]);

                        contextResult.append(jsonMap.toString());

                    }

                    FileUtils.writeStringToFile(contextAnalysisPath.toFile(), contextResult.toString());

                    logger.debug("Document Contextualization completed for " + documentList);

                }

            } catch (IOException | ResourceInstantiationException | ExecutionException e) {

                e.printStackTrace();

            }

        }

        exchange.getOut().setBody(job.build().toString());
        exchange.getOut().setHeaders(exchange.getIn().getHeaders());

    } else {

        scheduler.updateTask(taskId, TaskStatus.FAILED, taskStep, null);

        job.add("Message", "Task " + taskId + " failed");

        scheduler.sendMessage("activemq:queue:ERROR.QUEUE", exchange.getIn().getHeaders(), job.build());

    }

}

From source file:ch.bfh.abcvote.util.controllers.CommunicationController.java

/**
 * Posts the given ballot to the bulletin board
 * @param ballot Ballot to be posted to the bulletin board
 * @param useTor Boolean indicating if Ballot should be posted over the Tor network
 *//*w  w w.j  a  va2  s.  c  o  m*/
public void postBallot(Ballot ballot, Boolean useTor) {
    JsonObjectBuilder jBuilder = Json.createObjectBuilder();
    //Translate ballot object into a json string 
    JsonArrayBuilder optionsBuilder = Json.createArrayBuilder();
    for (String option : ballot.getSelectedOptions()) {
        optionsBuilder.add(option);
    }
    jBuilder.add("e", optionsBuilder);
    jBuilder.add("u_Hat", ballot.getU_HatString());
    jBuilder.add("c", ballot.getCString());
    jBuilder.add("d", ballot.getDString());
    jBuilder.add("pi1", ballot.getPi1String());
    jBuilder.add("pi2", ballot.getPi2String());
    jBuilder.add("pi3", ballot.getPi3String());

    JsonObject model = jBuilder.build();

    //josn gets posted to the bulletin board
    try {
        boolean requestOK = postJsonStringToURL(
                bulletinBoardUrl + "/elections/" + ballot.getElection().getId() + "/ballots", model.toString(),
                useTor);
        if (requestOK) {
            System.out.println("Ballot posted!");
        } else {
            System.out.println("Was not able to post Ballot!");
        }
    } catch (IOException ex) {
        System.out.println("Was not able to post Ballot!");
    }
}

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

/**
 * Send shipping exceptions to jet /*from w ww.ja v  a 2  s .  com*/
 * @param sku Sku 
 * @param nodes Filfillment nodes 
 * @return
 * @throws APIException
 * @throws JetException 
 */
@Override
public IJetAPIResponse sendPutProductShippingExceptions(final String sku, final List<FNodeShippingRec> nodes)
        throws APIException, JetException {
    checkSku(sku);

    if (nodes == null)
        throw new IllegalArgumentException("nodes cannot be null");

    APILog.info(LOG, "Sending", sku, "shipping exceptions");

    final JsonArrayBuilder b = Json.createArrayBuilder();
    for (final FNodeShippingRec node : nodes) {
        b.add(node.toJSON());
    }

    final JsonObjectBuilder o = Json.createObjectBuilder();
    o.add("fulfillment_nodes", b);

    final IJetAPIResponse response = put(config.getAddProductShipExceptionUrl(sku), o.build().toString(),
            getJSONHeaderBuilder().build());

    return response;
}

From source file:com.amazon.alexa.avs.config.DeviceConfig.java

/**
 * Serialize this object to JSON.//from www  . j av  a  2 s  .  co m
 *
 * @return A JSON representation of this object.
 */
public JsonObject toJson() {

    JsonObjectBuilder builder = Json.createObjectBuilder().add(PRODUCT_ID, productId).add(DSN, dsn)
            .add(PROVISIONING_METHOD, provisioningMethod.toString())
            .add(WAKE_WORD_AGENT_ENABLED, wakeWordAgentEnabled).add(LOCALE, locale.toLanguageTag())
            .add(AVS_HOST, avsHost.toString());

    if (companionAppInfo != null) {
        builder.add(COMPANION_APP, companionAppInfo.toJson());
    }

    if (companionServiceInfo != null) {
        builder.add(COMPANION_SERVICE, companionServiceInfo.toJson());
    }

    return builder.build();
}

From source file:org.btc4j.daemon.BtcJsonRpcHttpClient.java

public JsonValue invoke(String method, JsonArray parameters) throws BtcException {
    JsonObjectBuilder builder = Json.createObjectBuilder();
    builder.add(JSONRPC_REALM, JSONRPC_VERSION).add(JSONRPC_METHOD, method);
    if (parameters != null) {
        builder.add(JSONRPC_PARAMS, parameters);
    } else {//from w ww.ja  va  2  s . c  om
        builder.addNull(JSONRPC_PARAMS);
    }
    String guid = UUID.randomUUID().toString();
    builder.add(JSONRPC_ID, guid);
    JsonObject request = builder.build();
    JsonObject response = jsonObject(jsonValue(jsonInvoke(String.valueOf(request))));
    if (response == null) {
        LOG.severe(BTC4J_DAEMON_DATA_NULL_JSON);
        throw new BtcException(BtcException.BTC4J_ERROR_CODE,
                BtcException.BTC4J_ERROR_MESSAGE + ": " + BTC4J_DAEMON_DATA_NULL_JSON);
    }
    if (!(guid.equals(jsonId(response)))) {
        LOG.severe(BTC4J_DAEMON_DATA_INVALID_ID);
        throw new BtcException(BtcException.BTC4J_ERROR_CODE,
                BtcException.BTC4J_ERROR_MESSAGE + ": " + BTC4J_DAEMON_DATA_INVALID_ID);
    }
    JsonValue error = response.get(JSONRPC_ERROR);
    if ((error != null) && (error.getValueType().equals(ValueType.OBJECT))) {
        JsonObject errorObj = (JsonObject) error;
        int code = errorObj.getInt(JSONRPC_CODE);
        String message = errorObj.getString(JSONRPC_MESSAGE);
        JsonObject data = (JsonObject) errorObj.get(JSONRPC_DATA);
        String dataStr = (data == null) ? "" : (" " + String.valueOf(data));
        LOG.severe("error: " + code + " " + message + dataStr);
        throw new BtcException(code, message + dataStr);
    }
    return response.get(JSONRPC_RESULT);

}

From source file:edu.harvard.iq.dataverse.api.imports.ImportServiceBean.java

@TransactionAttribute(REQUIRES_NEW)
public JsonObjectBuilder handleFile(DataverseRequest dataverseRequest, Dataverse owner, File file,
        ImportType importType, PrintWriter validationLog, PrintWriter cleanupLog)
        throws ImportException, IOException {

    System.out.println("handling file: " + file.getAbsolutePath());
    String ddiXMLToParse;/*w  w  w . jav a2  s .  co  m*/
    try {
        ddiXMLToParse = new String(Files.readAllBytes(file.toPath()));
        JsonObjectBuilder status = doImport(dataverseRequest, owner, ddiXMLToParse,
                file.getParentFile().getName() + "/" + file.getName(), importType, cleanupLog);
        status.add("file", file.getName());
        logger.log(Level.INFO, "completed doImport {0}/{1}",
                new Object[] { file.getParentFile().getName(), file.getName() });
        return status;
    } catch (ImportException ex) {
        String msg = "Import Exception processing file " + file.getParentFile().getName() + "/" + file.getName()
                + ", msg:" + ex.getMessage();
        logger.info(msg);
        if (validationLog != null) {
            validationLog.println(msg);
        }
        return Json.createObjectBuilder().add("message", "Import Exception processing file "
                + file.getParentFile().getName() + "/" + file.getName() + ", msg:" + ex.getMessage());
    } catch (IOException e) {
        Throwable causedBy = e.getCause();
        while (causedBy != null && causedBy.getCause() != null) {
            causedBy = causedBy.getCause();
        }
        String stackLine = "";
        if (causedBy != null && causedBy.getStackTrace() != null && causedBy.getStackTrace().length > 0) {
            stackLine = causedBy.getStackTrace()[0].toString();
        }
        String msg = "Unexpected Error in handleFile(), file:" + file.getParentFile().getName() + "/"
                + file.getName();
        if (e.getMessage() != null) {
            msg += "message: " + e.getMessage();
        }
        msg += ", caused by: " + causedBy;
        if (causedBy != null && causedBy.getMessage() != null) {
            msg += ", caused by message: " + causedBy.getMessage();
        }
        msg += " at line: " + stackLine;

        validationLog.println(msg);
        e.printStackTrace();

        return Json.createObjectBuilder().add("message", "Unexpected Exception processing file "
                + file.getParentFile().getName() + "/" + file.getName() + ", msg:" + e.getMessage());

    }
}

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

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

    String parent = configuration.getDirectory();
    String inputFileName = new File(parent, mapping.getEntityName()).getAbsolutePath();
    List<Map<String, String>> csvs = reader.readFromFile(new File(inputFileName));

    csvs.removeIf(map -> !value.equals(map.get(by)));

    if (!csvs.isEmpty()) {
        Map<String, String> csv = csvs.get(0);

        String mappingFileName = inputFileName.replace(".csv", "_mapping.csv");
        List<Mapping> mappings = mappingConverter.getMappingForFile(new File(mappingFileName));

        String json = converter.convert(csv, mappings).toString();

        try (JsonReader jsonReader = Json.createReader(new StringReader(json))) {
            JsonObject jsonObject = jsonReader.readObject();
            builder.add(mapping.getTo(), jsonObject);
        }//from w w  w .  ja  v  a2 s.c  o  m
    } else {
        logger.warn("The CSV file contained reference to {} {} from input file {}, " + "but it does not exist.",
                by, value, mapping.getEntityName());
    }
}

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

/**
 * Adds product quantity and inventory data
 * @param product product data/* ww  w .  j  av a2  s .  c o m*/
 * @return success
 * @throws APIException
 * @throws JetException
 */
@Override
public IJetAPIResponse sendPutProductInventory(final String sku, final List<FNodeInventoryRec> nodes)
        throws JetException, APIException {
    Utils.checkNull(sku, "sku");
    Utils.checkNull(nodes, "nodes");

    APILog.info(LOG, "Sending", sku, "inventory");

    final JsonObjectBuilder o = Json.createObjectBuilder();

    if (!nodes.isEmpty()) {
        final JsonArrayBuilder a = Json.createArrayBuilder();
        nodes.forEach(v -> a.add(v.toJSON()));
        o.add("fulfillment_nodes", a.build());
    }

    final IJetAPIResponse response = patch(config.getAddProductInventoryUrl(sku), o.build().toString(),
            getJSONHeaderBuilder().build());

    return response;
}

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

@Override
public void convert(JsonObjectBuilder builder, Mapping mapping, String value) {
    List<String> codes = getArrayValues(value);
    String by = getBy(mapping.getType());

    String parent = configuration.getDirectory();
    String inputFileName = new File(parent, mapping.getEntityName()).getAbsolutePath();
    List<Map<String, String>> csvs = reader.readFromFile(new File(inputFileName));
    csvs.removeIf(map -> !codes.contains(map.get(by)));

    JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();

    if (!csvs.isEmpty()) {
        String mappingFileName = inputFileName.replace(".csv", "_mapping.csv");
        List<Mapping> mappings = mappingConverter.getMappingForFile(new File(mappingFileName));

        for (Map<String, String> csv : csvs) {
            String json = converter.convert(csv, mappings).toString();

            try (JsonReader jsonReader = Json.createReader(new StringReader(json))) {
                arrayBuilder.add(jsonReader.readObject());
            }//from   w w w  .  j  a  v  a  2 s . co m
        }
    }

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

From source file:org.btc4j.daemon.BtcJsonRpcHttpClient.java

public String jsonError(String id, int code, String message) {
    JsonObjectBuilder builder = Json.createObjectBuilder().add(JSONRPC_REALM, JSONRPC_VERSION)
            .addNull(JSONRPC_RESULT);//w  w  w.j  ava 2 s  . c o  m
    JsonObject error = Json.createObjectBuilder().add(JSONRPC_CODE, code).add(JSONRPC_MESSAGE, message)
            .addNull(JSONRPC_DATA).build();
    builder.add(JSONRPC_ERROR, error).add(JSONRPC_ID, id);
    return String.valueOf(builder.build());
}