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:org.rhwlab.dispim.nucleus.NucleusData.java

public JsonObjectBuilder asJson() {
    JsonObjectBuilder builder = Json.createObjectBuilder();
    builder.add("Name", name);
    builder.add("Time", time);
    builder.add("X", xC);
    builder.add("Y", yC);
    builder.add("Z", zC);
    builder.add("Precision", precisionAsString(adjustedA));

    builder.add("Expression", this.exp);
    return builder;
}

From source file:info.dolezel.jarss.rest.v1.FeedsService.java

private JsonObjectBuilder getFeedCategory(EntityManager em, FeedCategory fc) {
    JsonObjectBuilder obj = Json.createObjectBuilder();
    int fcUnread = 0;
    Collection<Feed> feeds;
    JsonArrayBuilder nodes = Json.createArrayBuilder();

    obj.add("id", fc.getId());
    obj.add("title", fc.getName());

    feeds = fc.getFeeds();/*w w w. ja  va  2  s . c o  m*/
    for (Feed feed : feeds) {
        JsonObject objFeed = getFeed(em, feed).build();

        fcUnread = objFeed.getInt("unread");

        nodes.add(objFeed);
    }

    obj.add("unread", fcUnread);
    obj.add("nodes", nodes);
    obj.add("isCategory", true);

    return obj;
}

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

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

    List<String> values = getArrayValues(value);
    String by = getBy(mapping.getType());

    JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();

    for (String v : values) {
        JsonObject object = service.findBy(by, v);

        if (null == object) {
            logger.warn("The CSV file contained reference to entity {} "
                    + "with {} {} but such reference does not exist.", mapping.getEntityName(), by, v);
        } else {/*  w  w  w .ja va 2s  .c o  m*/
            arrayBuilder.add(object);
        }
    }

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

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

public void testZeedAnalysis(Exchange exchange) {

    logger.debug("New message retrieved");

    JsonObject jsonBody = MessageTools.getBody(exchange);

    JsonObjectBuilder job = Json.createObjectBuilder();

    for (Entry<String, JsonValue> entry : jsonBody.entrySet()) {
        job.add(entry.getKey(), entry.getValue());
    }//from   w  ww  . j  ava 2  s  . c o m

    if (jsonBody != null) {

        String diary = jsonBody.getString("diary");
        logger.debug("Retrieved Video Path: " + diary);

        job.add("diary", diary);

        String imagePath = jsonBody.getString("imgPath");
        logger.debug("Retrieved VAM: " + imagePath);

        job.add("imgPath", imagePath);

        // ONE video per call

        if (diary != null && !diary.isEmpty()) {
            if (imagePath != null && !imagePath.isEmpty()) {

                logger.debug(
                        "Executing Zero Example Event Detection Method for image collection: " + imagePath);

                String response = service.zeed_request(diary, imagePath);

                logger.debug("Zeed method for text file: " + imagePath + " result:\n" + response);

            } else {

                logger.debug("Unable to process image collection, wrong request");

            }

        } else {

            logger.debug("Unable to process textual information, wrong request");

        }

    }

}

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

public void testVideoAnalysis(Exchange exchange) {

    logger.debug("New message retrieved");

    JsonObject jsonBody = MessageTools.getBody(exchange);

    JsonObjectBuilder job = Json.createObjectBuilder();

    for (Entry<String, JsonValue> entry : jsonBody.entrySet()) {
        job.add(entry.getKey(), entry.getValue());
    }/*from  w w w.j av a 2s.c o m*/

    if (jsonBody != null) {

        String videoPath = jsonBody.getString("videoPath");
        logger.debug("Retrieved Video Path: " + videoPath);

        job.add("videoPath", videoPath);

        String method = jsonBody.getString("method");
        logger.debug("Retrieved VAM: " + method);

        job.add("method", method);

        // ONE video per call

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

            logger.debug("Executing Video Analysis Method: " + method);

            String result = service.video_request(videoPath, method);

            //System.out.println("VAM method "+method+" result:\n"+result);

            //  Video analysis service response
            String response = service.video_results(videoPath);

            logger.debug("VAM method " + method + " result:\n" + response);

            job.add("result", response);

        } else {

            logger.debug("Unable to process video, wrong request");

            job.add("result", "Unable to process video, wrong request");

        }

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

    }

}

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

public void videoNDDAnalysis(Exchange exchange) {

    logger.debug("New message retrieved");

    JsonObject jsonBody = MessageTools.getBody(exchange);

    JsonObjectBuilder job = Json.createObjectBuilder();

    for (Entry<String, JsonValue> entry : jsonBody.entrySet()) {
        job.add(entry.getKey(), entry.getValue());
    }/*from   w ww .  j  a  va 2s.  c  o  m*/

    if (jsonBody != null) {

        //String videoPaths = getVideoPath(jsonBody);

        String videoPath = jsonBody.getString("videoPath");
        logger.debug("Retrieved Video Path: " + videoPath);

        job.add("videoPath", videoPath);

        //String method = jsonBody.getString("method");
        //System.out.println("Retrieved VAM: "+method);

        // ONE video per call

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

            logger.debug("Executing Video Analysis Method: Near Duplicate Detection");

            String response_tmp = service.video_ndd_request(videoPath);

            logger.debug("Video NDD Analysis method result:\n" + response_tmp);

            // call id is returned at the response 
            String callid;
            String[] callid_tmp = response_tmp.split("::");
            callid = callid_tmp[1].trim();
            String response = service.video_ndd_result(callid);

            logger.debug("Video NDD result:\n" + response);

            job.add("result", response);

        } else {

            logger.debug("Unable to process video, wrong request");

            job.add("result", "Unable to process video, wrong request");

        }

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

    }

}

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

/**
 * Post the given result to a election to the bulletin board
 * @param result //  w  w w . j a  v  a2s.c om
 * result to be posted to the bulletin board
 */
public void postResult(ElectionResult result) {
    Election election = result.getElection();
    ElectionTopic topic = election.getTopic();
    HashMap<String, Integer> optionResults = result.getOptionCount();
    //translate the ElectionResult object into a json String
    JsonObjectBuilder jBuilder = Json.createObjectBuilder();

    //TODO get email address from certificate 
    jBuilder.add("author", "alice@bfh.ch");

    JsonArrayBuilder resultBuilder = Json.createArrayBuilder();

    JsonObjectBuilder topicBuilder = Json.createObjectBuilder();

    topicBuilder.add("topic", topic.getTitle());
    topicBuilder.add("pick", topic.getPick());

    JsonArrayBuilder optionsBuilder = Json.createArrayBuilder();

    for (String option : topic.getOptions()) {
        JsonObjectBuilder optionBuilder = Json.createObjectBuilder();
        optionBuilder.add("optTitle", option);
        optionBuilder.add("count", optionResults.get(option));
        optionsBuilder.add(optionBuilder);
    }
    topicBuilder.add("options", optionsBuilder);

    resultBuilder.add(topicBuilder);

    jBuilder.add("result", resultBuilder);
    JsonArrayBuilder ballotsBuilder = Json.createArrayBuilder();
    for (Ballot ballot : result.getBallots()) {
        JsonObjectBuilder ballotBuilder = Json.createObjectBuilder();
        //Translate ballot object into a json string 
        JsonArrayBuilder ballotOptionsBuilder = Json.createArrayBuilder();
        for (String option : ballot.getSelectedOptions()) {
            ballotOptionsBuilder.add(option);
        }
        ballotBuilder.add("id", ballot.getId());
        ballotBuilder.add("e", ballotOptionsBuilder);
        ballotBuilder.add("valid", ballot.isValid());
        ballotBuilder.add("reason", ballot.getReason());

        ballotsBuilder.add(ballotBuilder);
    }

    jBuilder.add("ballots", ballotsBuilder);

    JsonObject model = jBuilder.build();

    //sign json string 
    SignatureController signController = new SignatureController();
    JsonObject signedModel = null;

    try {
        signedModel = signController.signJson(model);
    } catch (Exception ex) {
        Logger.getLogger(CommunicationController.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        //post JWS with the result to the bulletin board
        boolean requestOK = postJsonStringToURL(
                bulletinBoardUrl + "/elections/" + election.getId() + "/results", signedModel.toString(),
                false);
        if (requestOK) {
            System.out.println("Results posted!");
        } else {
            System.out.println("Was not able to post Results! Did not receive expected http 200 status.");
        }
    } catch (IOException ex) {
        System.out.println("Was not able to post Results! IOException");
    }

}

From source file:com.seniorproject.semanticweb.services.WebServices.java

public String prepareResultWithCount(ArrayList<String> in) throws IOException {
    Multiset<String> multiset = HashMultiset.create();
    for (int i = 0; i < in.size(); i++) {
        if (in.get(i).length() > 0 && !in.get(i).equals("\"\"")) {
            multiset.add(in.get(i));/*from   w  ww  . j  a v a2 s  .  c  o  m*/
        }
    }
    JsonArrayBuilder out = Json.createArrayBuilder();
    JsonObjectBuilder resultObject = Json.createObjectBuilder();
    for (Multiset.Entry<String> entry : multiset.entrySet()) {
        List<String> matchList = new ArrayList<>();
        Pattern regex = Pattern.compile("[^\\s\"']+|\"[^\"]*\"|'[^']*'");
        Matcher regexMatcher = regex.matcher(entry.getElement());
        while (regexMatcher.find()) {
            matchList.add(regexMatcher.group());
        }
        resultObject.add("elem", matchList.get(0));
        resultObject.add("count", entry.getCount());
        if (matchList.size() >= 2) {
            String label = "";
            for (int j = 1; j < matchList.size(); j++) {
                label += matchList.get(j);
            }
            resultObject.add("label", label);
        } else {
            resultObject.add("label", "");
        }
        out.add(resultObject);
    }

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

From source file:io.hops.hopsworks.api.pythonDeps.PythonDepsService.java

@GET
@Path("/environmentTypes")
@AllowedProjectRoles({ AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST })
@Produces(MediaType.APPLICATION_JSON)//  w w  w  . ja  v a2s .  c  o  m
public Response environmentTypes() throws ServiceException {

    JsonObjectBuilder response = Json.createObjectBuilder();

    String cpuHost = hostsFacade.findCPUHost();

    if (cpuHost != null) {
        response.add("CPU", true);
    } else {
        response.add("CPU", false);
    }

    String gpuHost = hostsFacade.findGPUHost();
    if (gpuHost != null) {
        response.add("GPU", true);
    } else {
        response.add("GPU", false);
    }

    if (cpuHost == null && gpuHost == null) {
        throw new ServiceException(RESTCodes.ServiceErrorCode.HOST_NOT_FOUND, Level.WARNING,
                "Could not find any CPU or GPU host");
    }

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

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

/**
 * Converts the given election object to a Json String. The Json string is then signed.
 * The resulting JWS gets posted to the bulletin board
 * @param election//from  ww w . jav  a2 s . c o  m
 * election object to be posted to the bulletin board
 */
public void postElection(Election election) {
    JsonObjectBuilder jBuilder = Json.createObjectBuilder();
    DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    //Add Header information to the json object
    //TODO get email address from certificate 
    jBuilder.add("author", "alice@bfh.ch");
    jBuilder.add("electionTitle", election.getTitle());
    jBuilder.add("beginDate", election.getStartDate().format(format));
    jBuilder.add("endDate", election.getEndDate().format(format));
    //toDo: get AppVersion dynamically from build 
    jBuilder.add("appVersion", "0.15");

    jBuilder.add("coefficients", election.getCredentialPolynomialString());
    jBuilder.add("electionGenerator", election.getH_HatString());

    //Add votingTopic to the Json Object
    JsonObjectBuilder votingTopicBuilder = Json.createObjectBuilder();
    votingTopicBuilder.add("topic", election.getTopic().getTitle());
    votingTopicBuilder.add("pick", election.getTopic().getPick());

    JsonArrayBuilder optionsBuilder = Json.createArrayBuilder();
    for (String option : election.getTopic().getOptions()) {
        optionsBuilder.add(option);
    }
    votingTopicBuilder.add("options", optionsBuilder);

    jBuilder.add("votingTopic", votingTopicBuilder);

    //Add the list of selected Voters to the Json object
    JsonArrayBuilder votersBuilder = Json.createArrayBuilder();

    for (Voter voter : election.getVoterList()) {
        JsonObjectBuilder voterBuilder = Json.createObjectBuilder();
        voterBuilder.add("email", voter.getEmail());
        voterBuilder.add("publicCredential", voter.getPublicCredential());
        voterBuilder.add("appVersion", voter.getAppVersion());

        votersBuilder.add(voterBuilder);
    }

    jBuilder.add("voters", votersBuilder);

    JsonObject model = jBuilder.build();
    //finished Json gets singed
    SignatureController signController = new SignatureController();
    JsonObject signedModel = null;

    try {
        signedModel = signController.signJson(model);
    } catch (Exception ex) {
        Logger.getLogger(CommunicationController.class.getName()).log(Level.SEVERE, null, ex);
    }

    //JWS gets posted to the bulletin board
    try {
        boolean requestOK = postJsonStringToURL(bulletinBoardUrl + "/elections", signedModel.toString(), false);
        if (requestOK) {
            System.out.println("Election posted!");
        } else {
            System.out.println("Was not able to post Election! Did not receive expected http 200 status.");
        }
    } catch (IOException ex) {
        System.out.println("Was not able to post Election! IOException");
    }

}