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:io.hops.hopsworks.api.jobs.JobService.java

/**
 * Get the log information related to a job. The return value is a JSON
 * object, with format logset=[{"time":"JOB
 * EXECUTION TIME"}, {"log":"INFORMATION LOG"}, {"err":"ERROR LOG"}]
 * <p>/*from   ww w .  j av  a2 s  .c o  m*/
 * @param jobId
 * @param sc
 * @param req
 * @return
 */
@GET
@Path("/{jobId}/showlog")
@Produces(MediaType.APPLICATION_JSON)
@AllowedProjectRoles({ AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST })
public Response getLogInformation(@PathParam("jobId") int jobId, @Context SecurityContext sc,
        @Context HttpServletRequest req) {

    JsonObjectBuilder builder = Json.createObjectBuilder();
    JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
    List<Execution> executionHistory = exeFacade.findbyProjectAndJobId(project, jobId);
    JsonObjectBuilder arrayObjectBuilder;
    if (executionHistory != null && !executionHistory.isEmpty()) {
        for (Execution e : executionHistory) {
            arrayObjectBuilder = Json.createObjectBuilder();
            arrayObjectBuilder.add("jobId", e.getJob().getId());
            arrayObjectBuilder.add("appId", e.getAppId() == null ? "" : e.getAppId());
            arrayObjectBuilder.add("time", e.getSubmissionTime().toString());
            arrayBuilder.add(arrayObjectBuilder);
        }
    } else {
        arrayObjectBuilder = Json.createObjectBuilder();
        arrayObjectBuilder.add("jobId", "");
        arrayObjectBuilder.add("appId", "");
        arrayObjectBuilder.add("time", "Not available");
        arrayObjectBuilder.add("log", "No log available");
        arrayObjectBuilder.add("err", "No log available");
        arrayBuilder.add(arrayObjectBuilder);
    }
    builder.add("logset", arrayBuilder);

    return noCacheResponse.getNoCacheResponseBuilder(Response.Status.OK).entity(builder.build()).build();
}

From source file:eu.forgetit.middleware.component.Extractor.java

public void executeImageAnalysis(Exchange exchange) {

    taskStep = "EXTRACTOR_IMAGE_ANALYSIS";

    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);

    if (jsonBody != null) {

        String 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 imageAnalysisPath = Paths.get(metadataPath.toString(), "imageAnalysis.xml");

                String imagePaths = getImagePaths(contentPath, pofId);

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

                    String response = service.img_request(imagePaths, "all", null);

                    FileUtils.writeStringToFile(imageAnalysisPath.toFile(), response);

                    logger.debug("Image Analysis completed for " + imagePaths);
                }//  w  w  w  .ja va  2  s . c o m

            } catch (IOException 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:org.hyperledger.fabric_ca.sdk.HFCAClient.java

JsonObject getResult(HttpResponse response, String body, String type)
        throws HTTPException, ParseException, IOException {

    int respStatusCode = response.getStatusLine().getStatusCode();
    HttpEntity entity = response.getEntity();
    logger.trace(format("response status %d, HttpEntity %s ", respStatusCode, "" + entity));
    String responseBody = entity != null ? EntityUtils.toString(entity) : null;
    logger.trace(format("responseBody: %s ", responseBody));

    // If the status code in the response is greater or equal to the status code set in the client object then an exception will
    // be thrown, otherwise, we continue to read the response and return any error code that is less than 'statusCode'
    if (respStatusCode >= statusCode) {
        HTTPException e = new HTTPException(
                format("%s request to %s failed request body %s. Response: %s", type, url, body, responseBody),
                respStatusCode);/*from ww  w . j a v a  2 s  .  co  m*/
        logger.error(e.getMessage());
        throw e;
    }
    if (responseBody == null) {

        HTTPException e = new HTTPException(
                format("%s request to %s failed request body %s with null response body returned.", type, url,
                        body),
                respStatusCode);
        logger.error(e.getMessage());
        throw e;

    }

    logger.debug("Status: " + respStatusCode);

    JsonReader reader = Json.createReader(new StringReader(responseBody));
    JsonObject jobj = (JsonObject) reader.read();

    JsonObjectBuilder job = Json.createObjectBuilder();
    job.add("statusCode", respStatusCode);

    JsonArray errors = jobj.getJsonArray("errors");
    // If the status code is greater than or equal to 400 but less than or equal to the client status code setting,
    // then encountered an error and we return back the status code, and log the error rather than throwing an exception.
    if (respStatusCode < statusCode && respStatusCode >= 400) {
        if (errors != null && !errors.isEmpty()) {
            JsonObject jo = errors.getJsonObject(0);
            String errorMsg = format(
                    "[HTTP Status Code: %d] - %s request to %s failed request body %s error message: [Error Code %d] - %s",
                    respStatusCode, type, url, body, jo.getInt("code"), jo.getString("message"));
            logger.error(errorMsg);
        }
        return job.build();
    }
    if (errors != null && !errors.isEmpty()) {
        JsonObject jo = errors.getJsonObject(0);
        HTTPException e = new HTTPException(
                format("%s request to %s failed request body %s error message: [Error Code %d] - %s", type, url,
                        body, jo.getInt("code"), jo.getString("message")),
                respStatusCode);
        throw e;
    }

    boolean success = jobj.getBoolean("success");
    if (!success) {
        HTTPException e = new HTTPException(
                format("%s request to %s failed request body %s Body of response did not contain success", type,
                        url, body),
                respStatusCode);
        logger.error(e.getMessage());
        throw e;
    }

    JsonObject result = jobj.getJsonObject("result");
    if (result == null) {
        HTTPException e = new HTTPException(
                format("%s request to %s failed request body %s " + "Body of response did not contain result",
                        type, url, body),
                respStatusCode);
        logger.error(e.getMessage());
        throw e;
    }

    JsonArray messages = jobj.getJsonArray("messages");
    if (messages != null && !messages.isEmpty()) {
        JsonObject jo = messages.getJsonObject(0);
        String message = format(
                "%s request to %s failed request body %s response message: [Error Code %d] - %s", type, url,
                body, jo.getInt("code"), jo.getString("message"));
        logger.info(message);
    }

    // Construct JSON object that contains the result and HTTP status code
    for (Entry<String, JsonValue> entry : result.entrySet()) {
        job.add(entry.getKey(), entry.getValue());
    }
    job.add("statusCode", respStatusCode);
    result = job.build();

    logger.debug(format("%s %s, body:%s result: %s", type, url, body, "" + result));
    return result;
}

From source file:com.buffalokiwi.aerodrome.jet.orders.OrderRec.java

/**
 * Turn this object into Jet json //w  w  w  .j a va  2 s .co  m
 * @return json 
 */
@Override
public JsonObject toJSON() {
    final JsonObject shipTo = Json.createObjectBuilder().add("recipient", shippingTo.toJSON())
            .add("address", shippingToAddress.toJSON()).build();

    final JsonObjectBuilder b = Json.createObjectBuilder().add("merchant_order_id", merchantOrderId)
            .add("reference_order_id", referenceOrderId)
            .add("customer_reference_order_id", customerReferenceOrderId)
            .add("fulfillment_node", fulfillmentNode).add("alt_order_id", altOrderId)
            .add("hash_email", hashEmail).add("status", status.getText())
            .add("exception_state", exceptionState.getText())
            .add("order_placed_date", orderPlacedDate.getDateString(JetDate.FMT_ZULU))
            .add("order_transmission_date", orderTransmissionDate.getDateString(JetDate.FMT_ZULU))
            //.add( "jet_request_directed_cancel", (( jetRequestDirectedCancel ) ? "true" : "false" ))
            .add("order_detail", orderDetail.toJSON()).add("buyer", buyer.toJSON()).add("shipping_to", shipTo)
            .add("order_totals", orderTotals.toJSON()).add("has_shipments", hasShipments)
            .add("acknowledgement_status", ackStatus.getText());

    if (orderReadyDate != null)
        b.add("order_ready_date", orderReadyDate.getDateString(JetDate.FMT_ZULU_ZERO));

    if (orderAckDate != null)
        b.add("order_acknowledge_date", orderAckDate.getDateString(JetDate.FMT_LOCAL_MICRO));

    if (shipments != null)
        b.add("shipments", shipmentsToJson());

    if (orderItems != null)
        b.add("order_items", orderItemsToJson());

    return b.build();
}

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;//  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:io.hops.hopsworks.api.jobs.JobService.java

/**
 * Get all the jobs in this project that have a running execution. The return
 * value is a JSON object, where each job
 * id is a key and the corresponding boolean indicates whether the job is
 * running or not.//from w  ww. j  ava  2s .c o  m
 * <p/>
 * @param sc
 * @param req
 * @return
 */
@GET
@Path("/running")
@Produces(MediaType.APPLICATION_JSON)
@AllowedProjectRoles({ AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST })
public Response getConfigurationTemplate(@Context SecurityContext sc, @Context HttpServletRequest req) {
    List<Jobs> running = jobFacade.getRunningJobs(project);
    List<Jobs> allJobs = jobFacade.findForProject(project);
    JsonObjectBuilder builder = Json.createObjectBuilder();
    for (Jobs desc : allJobs) {
        try {
            List<Execution> jobExecutions = exeFacade.findForJob(desc);
            if (jobExecutions != null && jobExecutions.isEmpty() == false) {
                Execution execution = jobExecutions.get(0);
                builder.add(desc.getId().toString(),
                        Json.createObjectBuilder().add("running", false)
                                .add("state", execution.getState().toString())
                                .add("finalStatus", execution.getFinalStatus().toString())
                                .add("progress", execution.getProgress())
                                .add("duration", execution.getExecutionDuration())
                                .add("submissiontime", execution.getSubmissionTime().toString()));
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            LOGGER.log(Level.WARNING, "No execution was found: {0}", e.getMessage());
        }
    }
    for (Jobs desc : running) {
        try {
            Execution execution = exeFacade.findForJob(desc).get(0);
            long executiontime = System.currentTimeMillis() - execution.getSubmissionTime().getTime();
            //not given appId (not submited yet)
            if (execution.getAppId() == null && executiontime > 60000l * 5) {
                exeFacade.updateState(execution, JobState.INITIALIZATION_FAILED);
                exeFacade.updateFinalStatus(execution, JobFinalStatus.FAILED);
                continue;
            }

            String trackingUrl = appAttemptStateFacade.findTrackingUrlByAppId(execution.getAppId());
            builder.add(desc.getId().toString(), Json.createObjectBuilder().add("running", true)
                    .add("state", execution.getState().toString())
                    .add("finalStatus", execution.getFinalStatus().toString())
                    .add("progress", execution.getProgress()).add("duration", execution.getExecutionDuration())
                    .add("submissiontime", execution.getSubmissionTime().toString()).add("url", trackingUrl));
        } catch (ArrayIndexOutOfBoundsException e) {
            LOGGER.log(Level.WARNING, "No execution was found: {0}", e.getMessage());
        }
    }
    return noCacheResponse.getNoCacheResponseBuilder(Response.Status.OK).entity(builder.build()).build();
}

From source file:fr.ortolang.diffusion.core.CoreServiceBean.java

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public String snapshotWorkspace(String wskey) throws CoreServiceException, KeyNotFoundException,
        AccessDeniedException, WorkspaceReadOnlyException, WorkspaceUnchangedException {
    LOGGER.log(Level.FINE, "snapshoting workspace [" + wskey + "]");
    try {//  w w w .  jav a 2s.  c o  m
        String caller = membership.getProfileKeyForConnectedIdentifier();
        List<String> subjects = membership.getConnectedIdentifierSubjects();

        OrtolangObjectIdentifier identifier = registry.lookup(wskey);
        checkObjectType(identifier, Workspace.OBJECT_TYPE);
        authorisation.checkPermission(wskey, subjects, "update");

        Workspace workspace = em.find(Workspace.class, identifier.getId());
        if (workspace == null) {
            throw new CoreServiceException(
                    "unable to load workspace with id [" + identifier.getId() + "] from storage");
        }
        if (applyReadOnly(caller, subjects, workspace)) {
            throw new WorkspaceReadOnlyException(
                    "unable to snapshot workspace with key [" + wskey + "] because it is read only");
        }

        String name = String.valueOf(workspace.getClock());

        if (!workspace.hasChanged()) {
            throw new WorkspaceUnchangedException(
                    "unable to snapshot because workspace has no pending modifications since last snapshot");
        }

        try {
            JsonObjectBuilder builder = Json.createObjectBuilder();
            builder.add("wskey", wskey);
            builder.add("snapshotName", name);
            builder.add("wsalias", workspace.getAlias());

            JsonObject jsonObject = builder.build();
            String hash = binarystore.put(new ByteArrayInputStream(jsonObject.toString().getBytes()));

            List<String> mds = findMetadataObjectsForTargetAndName(workspace.getHead(),
                    MetadataFormat.WORKSPACE);

            if (mds.isEmpty()) {
                LOGGER.log(Level.INFO, "creating workspace metadata for root collection");
                createMetadataObject(wskey, "/", MetadataFormat.WORKSPACE, hash, null, false);
            } else {
                LOGGER.log(Level.INFO, "updating workspace metadata for root collection");
                updateMetadataObject(wskey, "/", MetadataFormat.WORKSPACE, hash, null, false);
            }
        } catch (BinaryStoreServiceException | DataCollisionException | CoreServiceException
                | KeyNotFoundException | InvalidPathException | AccessDeniedException | MetadataFormatException
                | PathNotFoundException | KeyAlreadyExistsException e) {
            throw new CoreServiceException(
                    "cannot create workspace metadata for collection root : " + e.getMessage());
        }

        workspace.setKey(wskey);
        workspace.incrementClock();

        OrtolangObjectIdentifier hidentifier = registry.lookup(workspace.getHead());
        checkObjectType(hidentifier, Collection.OBJECT_TYPE);
        Collection collection = em.find(Collection.class, hidentifier.getId());
        if (collection == null) {
            throw new CoreServiceException(
                    "unable to load head collection with id [" + hidentifier.getId() + "] from storage");
        }
        collection.setKey(workspace.getHead());

        Collection clone = cloneCollection(workspace.getHead(), collection, workspace.getClock());

        workspace.addSnapshot(new SnapshotElement(name, collection.getKey()));
        workspace.setHead(clone.getKey());
        workspace.setChanged(false);
        em.merge(workspace);

        registry.update(wskey);

        ArgumentsBuilder argsBuilder = new ArgumentsBuilder(2).addArgument("ws-alias", workspace.getAlias())
                .addArgument("snapshot-name", name);
        notification.throwEvent(wskey, caller, Workspace.OBJECT_TYPE,
                OrtolangEvent.buildEventType(CoreService.SERVICE_NAME, Workspace.OBJECT_TYPE, "snapshot"),
                argsBuilder.build());
        return name;
    } catch (KeyLockedException | NotificationServiceException | RegistryServiceException
            | MembershipServiceException | AuthorisationServiceException | CloneException e) {
        ctx.setRollbackOnly();
        LOGGER.log(Level.SEVERE, "unexpected error occurred while snapshoting workspace", e);
        throw new CoreServiceException("unable to snapshot workspace with key [" + wskey + "]", e);
    }
}