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:com.open.shift.support.controller.SupportResource.java

@GET
@Produces(MediaType.APPLICATION_JSON)/*from   w  w  w .  j  a va 2s  .  c om*/
@Path("areachart")
public JsonObject generateAreaChart() throws Exception {
    System.out.println("The injected hashcode is " + this.supportDAO);
    int usa[] = { 0, 0, 0, 0, 0, 6, 11, 32, 110, 235, 369, 640, 1005, 1436, 2063, 3057, 4618, 6444, 9822, 15468,
            20434, 24126, 27387, 29459, 31056, 31982, 32040, 31233, 29224, 27342, 26662, 26956, 27912, 28999,
            28965, 27826, 25579, 25722, 24826, 24605, 24304, 23464, 23708, 24099, 24357, 24237, 24401, 24344,
            23586, 22380, 21004, 17287, 14747, 13076, 12555, 12144, 11009, 10950, 10871, 10824, 10577, 10527,
            10475, 10421, 10358, 10295, 10104 };

    int ussr[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 25, 50, 120, 150, 200, 426, 660, 869, 1060, 1605, 2471,
            3322, 4238, 5221, 6129, 7089, 8339, 9399, 10538, 11643, 13092, 14478, 15915, 17385, 19055, 21205,
            23044, 25393, 27935, 30062, 32049, 33952, 35804, 37431, 39197, 45000, 43000, 41000, 39000, 37000,
            35000, 33000, 31000, 29000, 27000, 25000, 24000, 23000, 22000, 21000, 20000, 19000, 18000, 18000,
            17000, 16000 };

    URL u = ctx.getResource("/WEB-INF/classes/templates/area.json");
    String areaJson = null;
    if (OS.indexOf("win") >= 0) {
        areaJson = u.toString().substring(6);
    } else if (OS.indexOf("nux") >= 0) {
        areaJson = u.toString().substring(5);
    }
    System.out.println("The areaJson is " + areaJson);

    JsonReader reader = Json.createReader(new FileReader(areaJson));
    JsonObject main = reader.readObject();

    JsonObject yaxis = main.getJsonObject("yAxis");

    JsonObjectBuilder title = Json.createObjectBuilder().add("text", "US and USSR Deposits");
    JsonObjectBuilder ytitle = Json.createObjectBuilder().add("text", "Amount Deposisted");
    JsonArrayBuilder usaData = Json.createArrayBuilder();
    for (Integer usa1 : usa) {
        usaData.add(usa1);
    }

    JsonArrayBuilder ussrData = Json.createArrayBuilder();
    for (Integer uss1 : ussr) {
        ussrData.add(uss1);
    }

    JsonObjectBuilder usaSeries = Json.createObjectBuilder().add("name", "USA").add("data", usaData);
    JsonObjectBuilder ussrSeries = Json.createObjectBuilder().add("name", "USSR").add("data", ussrData);
    JsonArrayBuilder series = Json.createArrayBuilder().add(usaSeries).add(ussrSeries);

    //main json object builder
    JsonObjectBuilder mainJsonObj = Json.createObjectBuilder();
    for (Map.Entry<String, JsonValue> mainObj : main.entrySet()) {
        String key = mainObj.getKey();
        JsonValue value = mainObj.getValue();

        if (key.equalsIgnoreCase("yAxis")) {
            String yaxisLabel = "labels";
            mainJsonObj.add(key, Json.createObjectBuilder().add(yaxisLabel, yaxis.getJsonObject(yaxisLabel))
                    .add("title", ytitle.build()));
        } else {
            mainJsonObj.add(key, value);
        }

    }
    mainJsonObj.add("title", title.build()).add("series", series.build());

    return mainJsonObj.build();

}

From source file:de.pangaea.fixo3.xml.ProcessXmlFiles.java

private void run() throws FileNotFoundException, SAXException, IOException, ParserConfigurationException,
        XPathExpressionException {
    // src/test/resources/, src/main/resources/files
    File folder = new File("src/main/resources/files");
    File[] files = folder.listFiles(new FileFilter() {

        @Override/*ww  w  .  j a va 2  s .  c o  m*/
        public boolean accept(File pathname) {
            if (pathname.getName().endsWith(".xml"))
                return true;

            return false;
        }
    });

    JsonArrayBuilder json = Json.createArrayBuilder();

    Document doc;
    String deviceLabel, deviceComment, deviceImage;

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);

    final Map<String, String> prefixToNS = new HashMap<>();
    prefixToNS.put(XMLConstants.XML_NS_PREFIX, XMLConstants.XML_NS_URI);
    prefixToNS.put(XMLConstants.XMLNS_ATTRIBUTE, XMLConstants.XMLNS_ATTRIBUTE_NS_URI);
    prefixToNS.put("sml", "http://www.opengis.net/sensorml/2.0");
    prefixToNS.put("gml", "http://www.opengis.net/gml/3.2");
    prefixToNS.put("gmd", "http://www.isotc211.org/2005/gmd");

    XPath x = XPathFactory.newInstance().newXPath();
    x.setNamespaceContext(new NamespaceContext() {
        @Override
        public String getNamespaceURI(String prefix) {
            Objects.requireNonNull(prefix, "Namespace prefix cannot be null");
            final String uri = prefixToNS.get(prefix);
            if (uri == null) {
                throw new IllegalArgumentException("Undeclared namespace prefix: " + prefix);
            }
            return uri;
        }

        @Override
        public String getPrefix(String namespaceURI) {
            throw new UnsupportedOperationException();
        }

        @Override
        public Iterator<?> getPrefixes(String namespaceURI) {
            throw new UnsupportedOperationException();
        }
    });

    XPathExpression exGmlName = x.compile("/sml:PhysicalSystem/gml:name");
    XPathExpression exGmlDescription = x.compile("/sml:PhysicalSystem/gml:description");
    XPathExpression exGmdUrl = x.compile(
            "/sml:PhysicalSystem/sml:documentation/sml:DocumentList/sml:document/gmd:CI_OnlineResource/gmd:linkage/gmd:URL");
    XPathExpression exTerm = x
            .compile("/sml:PhysicalSystem/sml:classification/sml:ClassifierList/sml:classifier/sml:Term");

    int m = 0;
    int n = 0;

    for (File file : files) {
        log.info(file.getName());
        doc = dbf.newDocumentBuilder().parse(new FileInputStream(file));

        deviceLabel = exGmlName.evaluate(doc).trim();
        deviceComment = exGmlDescription.evaluate(doc).trim();
        deviceImage = exGmdUrl.evaluate(doc).trim();
        NodeList terms = (NodeList) exTerm.evaluate(doc, XPathConstants.NODESET);

        JsonObjectBuilder jobDevice = Json.createObjectBuilder();

        jobDevice.add("name", toUri(deviceLabel));
        jobDevice.add("label", deviceLabel);
        jobDevice.add("comment", toAscii(deviceComment));
        jobDevice.add("image", deviceImage);

        JsonArrayBuilder jabSubClasses = Json.createArrayBuilder();

        for (int i = 0; i < terms.getLength(); i++) {
            Node term = terms.item(i);
            NodeList attributes = term.getChildNodes();

            String attributeLabel = null;
            String attributeValue = null;

            for (int j = 0; j < attributes.getLength(); j++) {
                Node attribute = attributes.item(j);
                String attributeName = attribute.getNodeName();

                if (attributeName.equals("sml:label")) {
                    attributeLabel = attribute.getTextContent();
                } else if (attributeName.equals("sml:value")) {
                    attributeValue = attribute.getTextContent();
                }
            }

            if (attributeLabel == null || attributeValue == null) {
                throw new RuntimeException("Attribute label or value cannot be null [attributeLabel = "
                        + attributeLabel + "; attributeValue = " + attributeValue + "]");
            }

            if (attributeLabel.equals("model")) {
                continue;
            }

            if (attributeLabel.equals("manufacturer")) {
                jobDevice.add("manufacturer", attributeValue);
                continue;
            }

            n++;

            Quantity quantity = getQuantity(attributeValue);

            if (quantity == null) {
                continue;
            }

            m++;

            JsonObjectBuilder jobSubClass = Json.createObjectBuilder();
            JsonObjectBuilder jobCapability = Json.createObjectBuilder();
            JsonObjectBuilder jobQuantity = Json.createObjectBuilder();

            String quantityLabel = getQuantityLabel(attributeLabel);
            String capabilityLabel = deviceLabel + " " + quantityLabel;

            jobCapability.add("label", capabilityLabel);

            jobQuantity.add("label", quantity.getLabel());

            if (quantity.getValue() != null) {
                jobQuantity.add("value", quantity.getValue());
            } else if (quantity.getMinValue() != null && quantity.getMaxValue() != null) {
                jobQuantity.add("minValue", quantity.getMinValue());
                jobQuantity.add("maxValue", quantity.getMaxValue());
            } else {
                throw new RuntimeException(
                        "Failed to determine quantity value [attributeValue = " + attributeValue + "]");
            }

            jobQuantity.add("unitCode", quantity.getUnitCode());
            jobQuantity.add("type", toUri(quantityLabel));

            jobCapability.add("quantity", jobQuantity);
            jobSubClass.add("capability", jobCapability);

            jabSubClasses.add(jobSubClass);
        }

        jobDevice.add("subClasses", jabSubClasses);

        json.add(jobDevice);
    }

    Map<String, Object> properties = new HashMap<>(1);
    properties.put(JsonGenerator.PRETTY_PRINTING, true);

    JsonWriterFactory jsonWriterFactory = Json.createWriterFactory(properties);
    JsonWriter jsonWriter = jsonWriterFactory.createWriter(new FileWriter(new File(jsonFileName)));
    jsonWriter.write(json.build());
    jsonWriter.close();

    System.out.println("Fraction of characteristics included: " + m + "/" + n);
}

From source file:org.trellisldp.http.MultipartUploader.java

/**
 * Get a list of the uploads// w ww .  ja  v a 2s  . c om
 * @param partition the partition
 * @param id the upload id
 * @return a response
 *
 * <p>Note: the response structure will be like this:</p>
 * <pre>{
 *   "1": "somehash",
 *   "2": "otherhash",
 *   "3": "anotherhash"
 * }</pre>
 */
@GET
@Timed
@Produces("application/json")
public String listUploads(@PathParam("partition") final String partition, @PathParam("id") final String id) {
    final JsonObjectBuilder builder = Json.createObjectBuilder();

    binaryService.getResolverForPartition(partition).filter(BinaryService.Resolver::supportsMultipartUpload)
            .filter(res -> res.uploadSessionExists(id)).map(res -> res.listParts(id))
            .orElseThrow(NotFoundException::new).forEach(x -> builder.add(x.getKey().toString(), x.getValue()));

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

From source file:skillpro.asset.views.wizardpages.ConfirmationPage.java

private void registerSEE(SEE see) throws ClientProtocolException, IOException {
    System.out.println("SEE[seeID: " + see.getSeeID() + ", opcuaMES: "
            + see.getMESCommunication().getSecondElement() + "opcua: " + see.getOpcUAAddress() + ", amlFile: "
            + !see.getAmlDescription().isEmpty() + "]");
    String serviceName = "registerSEE";

    JsonObjectBuilder jsonBuilder = Json.createObjectBuilder();
    if (see.getSeeID() != null && !see.getSeeID().trim().isEmpty()) {
        jsonBuilder.add("seeId", see.getSeeID() == null ? UUID.randomUUID().toString() : see.getSeeID());
    }//  ww  w  .  jav a  2  s  .  c om

    if (see.getMESCommunication().getFirstElement() == MESCommType.OPCUA) {
        jsonBuilder.add("opcuaAddress", see.getMESCommunication().getSecondElement());
    }

    if (see.getResource() != null) {
        jsonBuilder.add("assetTypeNames", see.getResource().getName());
    }

    jsonBuilder.add("simulation", see.isSimulation() + "");

    if (see.getAmlDescription() != null && !see.getAmlDescription().trim().isEmpty()) {
        jsonBuilder.add("amlFile", see.getAmlDescription());
    }

    HttpPost request = new HttpPost(AMSServiceUtility.serviceAddress + serviceName);

    request.setEntity(new StringEntity(jsonBuilder.build().toString(), "UTF-8"));
    System.out.println(request.getRequestLine() + " =====================================");
    request.setHeader("Content-type", "application/json");

    HttpClient client = HttpClientBuilder.create().build();
    ;
    client.execute(request);
}

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());
    }/*from w  w  w. ja  va  2s .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)//from  ww w . j av  a  2s. c  om
@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:org.rhwlab.dispim.nucleus.Nucleus.java

public JsonObjectBuilder asJson() {
    JsonObjectBuilder builder = nucData.asJson();
    builder.add("cell", cellName);
    builder.add("usernamed", this.userNamed);
    if (this.parent != null) {
        builder.add("parent", this.parent.getName());
    }//from w ww .j  a v a 2 s .c  o m
    if (child1 != null) {
        builder.add("child1", this.child1.asJson());
    }
    if (child2 != null) {
        builder.add("child2", this.child2.asJson());
    }
    return builder;
}

From source file:org.trellisldp.http.MultipartUploader.java

/**
 *  Add a segment of a binary/*from   w  w  w  .jav a  2s  .  com*/
 *  @param partition the partition
 *  @param id the upload session identifier
 *  @param partNumber the part number
 *  @param part the input stream
 *  @return a response
 *
 *  <p>Note: the response will be a json structure, such as:</p>
 *  <pre>{
 *    "digest": "a-hash"
 *  }</pre>
 */
@PUT
@Timed
@Path("{partNumber}")
@Produces("application/json")
public String uploadPart(@PathParam("partition") final String partition, @PathParam("id") final String id,
        @PathParam("partNumber") final Integer partNumber, final InputStream part) {

    final JsonObjectBuilder builder = Json.createObjectBuilder();

    final String digest = binaryService.getResolverForPartition(partition)
            .filter(BinaryService.Resolver::supportsMultipartUpload).filter(res -> res.uploadSessionExists(id))
            .map(res -> res.uploadPart(id, partNumber, part)).orElseThrow(NotFoundException::new);

    return builder.add("digest", digest).build().toString();
}

From source file:edu.harvard.iq.dataverse.mydata.MyDataFinder.java

/**
 * "publication_statuses" : [ name 1, name 2, etc.]
 * /*from www  .  j  a v a2 s  .co  m*/
 * @return 
 */
public JsonObjectBuilder getSelectedFilterParamsAsJSON() {

    JsonObjectBuilder jsonData = Json.createObjectBuilder();
    jsonData.add("publication_statuses", this.filterParams.getListofSelectedPublicationStatuses())
            .add("role_names", this.getListofSelectedRoles());

    return jsonData;
}

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/*from  w w w . java2  s  .  c om*/
 * 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;
    }

}