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:tools.xor.logic.DefaultJson.java

protected void checkBigIntegerField() throws JSONException {
    final BigInteger largeInteger = new BigInteger("12345678998765432100000123456789987654321");

    // create person
    JsonObjectBuilder jsonBuilder = Json.createObjectBuilder();
    jsonBuilder.add("name", "DILIP_DALTON");
    jsonBuilder.add("displayName", "Dilip Dalton");
    jsonBuilder.add("description", "Software engineer in the bay area");
    jsonBuilder.add("userName", "daltond");
    jsonBuilder.add("largeInteger", largeInteger);

    Settings settings = new Settings();
    settings.setEntityClass(Employee.class);
    Employee employee = (Employee) aggregateService.create(jsonBuilder.build(), settings);
    assert (employee.getId() != null);
    assert (employee.getName().equals("DILIP_DALTON"));
    assert (employee.getLargeInteger().equals(largeInteger));

    Object jsonObject = aggregateService.read(employee, settings);
    JsonObject json = (JsonObject) jsonObject;
    System.out.println("JSON string: " + json.toString());
    assert (((JsonString) json.get("name")).getString().equals("DILIP_DALTON"));
    assert (((JsonNumber) json.get("largeInteger")).bigIntegerValue().equals(largeInteger));
}

From source file:tools.xor.logic.DefaultJson.java

protected void checkEntityField() {
    final String TASK_NAME = "SETUP_DSL";

    // Create task
    JsonObjectBuilder jsonBuilder = Json.createObjectBuilder();
    jsonBuilder.add("name", TASK_NAME);
    jsonBuilder.add("displayName", "Setup DSL");
    jsonBuilder.add("description", "Setup high-speed broadband internet using DSL technology");

    // Create quote
    final BigDecimal price = new BigDecimal("123456789.987654321");
    jsonBuilder.add("quote", Json.createObjectBuilder().add("price", price));

    Settings settings = getSettings();//w w  w. j a  va 2  s .  c  o m
    settings.setEntityClass(Task.class);
    Task task = (Task) aggregateService.create(jsonBuilder.build(), settings);
    assert (task.getId() != null);
    assert (task.getName().equals(TASK_NAME));
    assert (task.getQuote() != null);
    assert (task.getQuote().getId() != null);
    assert (task.getQuote().getPrice().equals(price));

    Object jsonObject = aggregateService.read(task, settings);
    JsonObject jsonTask = (JsonObject) jsonObject;
    System.out.println("JSON string: " + jsonTask.toString());
    assert (((JsonString) jsonTask.get("name")).getString().equals(TASK_NAME));
    JsonObject jsonQuote = jsonTask.getJsonObject("quote");
    assert (((JsonNumber) jsonQuote.get("price")).bigDecimalValue().equals(price));
}

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

/**
 * Registers a new voter with the given email address and the given public credentials u on the bulletin board
 * @param email/* ww w. j  a  va2s . c o  m*/
 * email address under which the new voter should be registered
 * @param parameters
 * parameters used by the bulletin board
 * @param u 
 * public voter credential u
 * @return returns true if a new voter could be registered
 */
//TODO check if parameters are still needed
public boolean registerNewVoter(String email, Parameters parameters, Element u) {

    //create Voter json
    JsonObjectBuilder jBuilder = Json.createObjectBuilder();

    jBuilder.add("email", email);
    jBuilder.add("publicCredential", u.convertToString());
    jBuilder.add("appVersion", "1.15");

    JsonObject model = jBuilder.build();

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

    //post Voter
    try {
        boolean requestOK = postJsonStringToURL(bulletinBoardUrl + "/voters", signedModel.toString(), false);
        if (requestOK) {
            System.out.println("Voter posted!");
            return true;
        } else {
            System.out.println("Was not able to post Voter!");
            return false;
        }
    } catch (IOException ex) {
        System.out.println("Was not able to post Voter!");
        return false;
    }

}

From source file:org.hyperledger.fabric_ca.sdk.HFCAAffiliation.java

private JsonObject affToJsonObject() {
    JsonObjectBuilder ob = Json.createObjectBuilder();
    if (client.getCAName() != null) {
        ob.add(HFCAClient.FABRIC_CA_REQPROP, client.getCAName());
    }//  w  w  w  .j  av  a  2  s. com
    if (this.updateName != null) {
        ob.add("name", updateName);
        this.updateName = null;
    } else {
        ob.add("name", name);
    }

    return ob.build();
}

From source file:io.hops.hopsworks.api.tensorflow.TfServingService.java

@GET
@Path("/logs/{servingId}")
@Produces(MediaType.APPLICATION_JSON)// w w w. j  a  v a2  s.c  o m
@AllowedProjectRoles({ AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST })
public Response getLogs(@PathParam("servingId") int servingId, @Context SecurityContext sc,
        @Context HttpServletRequest req) throws AppException {
    if (projectId == null) {
        throw new AppException(Response.Status.BAD_REQUEST.getStatusCode(), "Incomplete request!");
    }

    String hdfsUser = getHdfsUser(sc);
    if (hdfsUser == null) {
        throw new AppException(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
                "Could not find your username. Report a bug.");
    }

    HdfsUsers user = hdfsUsersFacade.findByName(hdfsUser);
    if (user == null) {
        throw new AppException(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
                "Possible inconsistency - could not find your user.");
    }

    HdfsUsers servingHdfsUser = hdfsUsersFacade.findByName(hdfsUser);
    if (!hdfsUser.equals(servingHdfsUser.getName())) {
        throw new AppException(Response.Status.FORBIDDEN.getStatusCode(),
                "Attempting to start a serving not created by current user");
    }

    TfServing tfServing = tfServingFacade.findById(servingId);
    if (!tfServing.getProject().equals(project)) {
        return noCacheResponse.getNoCacheResponseBuilder(Response.Status.FORBIDDEN).build();
    }

    String logString = TfServingProcessMgr.getLogs(tfServing);

    JsonObjectBuilder arrayObjectBuilder = Json.createObjectBuilder();
    if (logString != null) {
        arrayObjectBuilder.add("stdout", logString);
    } else {
        throw new AppException(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
                "Could not get the logs for serving");
    }

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

From source file:tools.xor.logic.DefaultJson.java

protected void checkSetField() {
    final String TASK_NAME = "SETUP_DSL";
    final String CHILD_TASK_NAME = "TASK_1";

    // Create task
    JsonObjectBuilder jsonBuilder = Json.createObjectBuilder();
    jsonBuilder.add("name", TASK_NAME);
    jsonBuilder.add("displayName", "Setup DSL");
    jsonBuilder.add("description", "Setup high-speed broadband internet using DSL technology");

    // Create and add 1 child task
    jsonBuilder.add("taskChildren",
            Json.createArrayBuilder().add(Json.createObjectBuilder().add("name", CHILD_TASK_NAME)
                    .add("displayName", "Task 1").add("description", "This is the first child task")));

    Settings settings = getSettings();/*from   ww  w  . java2s  .  c  o m*/
    settings.setEntityClass(Task.class);
    Task task = (Task) aggregateService.create(jsonBuilder.build(), settings);
    assert (task.getId() != null);
    assert (task.getName().equals(TASK_NAME));
    assert (task.getTaskChildren() != null);
    System.out.println("Children size: " + task.getTaskChildren().size());
    assert (task.getTaskChildren().size() == 1);
    for (Task child : task.getTaskChildren()) {
        System.out.println("Task name: " + child.getName());
    }

    Object jsonObject = aggregateService.read(task, settings);
    JsonObject jsonTask = (JsonObject) jsonObject;
    System.out.println("JSON string for object: " + jsonTask.toString());
    assert (((JsonString) jsonTask.get("name")).getString().equals(TASK_NAME));
    JsonArray jsonChildren = jsonTask.getJsonArray("taskChildren");
    assert (((JsonArray) jsonChildren).size() == 1);
}

From source file:tools.xor.logic.DefaultJson.java

protected void checkDateField() throws JSONException {
    // create person
    JsonObjectBuilder jsonBuilder = Json.createObjectBuilder();
    jsonBuilder.add("name", "DILIP_DALTON");
    jsonBuilder.add("displayName", "Dilip Dalton");
    jsonBuilder.add("description", "Software engineer in the bay area");
    jsonBuilder.add("userName", "daltond");

    // 1/1/15 7:00 PM EST
    final long CREATED_ON = 1420156800000L;
    Date createdOn = new Date(CREATED_ON);
    DateFormat df = new SimpleDateFormat(ImmutableJsonProperty.ISO8601_FORMAT);
    jsonBuilder.add("createdOn", df.format(createdOn));

    Settings settings = new Settings();
    settings.setEntityClass(Person.class);
    Person person = (Person) aggregateService.create(jsonBuilder.build(), settings);
    assert (person.getId() != null);
    assert (person.getName().equals("DILIP_DALTON"));
    assert (person.getCreatedOn().getTime() == CREATED_ON);

    Object jsonObject = aggregateService.read(person, settings);
    JsonObject json = (JsonObject) jsonObject;
    System.out.println("JSON string: " + json.toString());
    assert (((JsonString) json.get("name")).getString().equals("DILIP_DALTON"));
    assert (((JsonString) json.get("createdOn")).getString().equals("2015-01-01T16:00:00.000-0800"));
}

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

/**
 * Retrieve the JSON object for this/*from   w  w  w .  ja v a2s .  c  o  m*/
 * @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:com.buffalokiwi.aerodrome.jet.products.JetAPIProduct.java

/**
 * Send shipping exceptions to jet /*from  w  w w. j  a v  a 2  s . c  o m*/
 * @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:eu.forgetit.middleware.component.Condensator.java

public void imageClustering(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  . co m

    if (jsonBody != null) {

        String xmlPath = jsonBody.getString("extractorOutput");
        logger.debug("Retrieved XML of image collection Path: " + xmlPath);
        job.add("extractorOutput", xmlPath);

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

            String response = service.request(xmlPath);
            logger.debug("Image clustering result:\n" + response);
            job.add("result", response);

        } else {
            logger.debug("Unable to process XML results, wrong request");
            job.add("result", "Unable to process XML results, wrong request");
        }

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

    }
}