Example usage for javax.json Json createObjectBuilder

List of usage examples for javax.json Json createObjectBuilder

Introduction

In this page you can find the example usage for javax.json Json createObjectBuilder.

Prototype

public static JsonObjectBuilder createObjectBuilder() 

Source Link

Document

Creates a JSON object builder

Usage

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;/*from   w  w w  . j  a  va  2  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: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.ja  v  a 2 s.c  om

    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: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/* w  w  w  .  ja v  a 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:tools.xor.logic.DefaultJson.java

protected void checkBigDecimalField() throws JSONException {
    final BigDecimal largeDecimal = new BigDecimal("12345678998765432100000.123456789987654321");

    // 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("largeDecimal", largeDecimal);

    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.getLargeDecimal().equals(largeDecimal));

    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("largeDecimal")).bigDecimalValue().equals(largeDecimal));
}

From source file:org.grogshop.services.endpoints.impl.ShopItemsServiceImpl.java

@Override
public Response get(@PathParam("id") Long item_id) throws ServiceException {
    Item i = itemsService.getById(item_id);
    JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
    jsonObjectBuilder.add("id", (i.getId() == null) ? "" : i.getId().toString())
            .add("user_id", (i.getUser().getId() == null) ? "" : i.getUser().getId().toString())
            .add("user_email", (i.getUser().getEmail() == null) ? "" : i.getUser().getEmail())
            .add("club_id", (i.getClub().getId() == null) ? "" : i.getClub().getId().toString())
            .add("type", (i.getType() == null) ? "" : i.getType().toString())
            .add("name", (i.getName() == null) ? "" : i.getName())
            .add("description", (i.getDescription() == null) ? "" : i.getDescription())
            .add("hasImage", i.hasImage())
            .add("minPrice", (i.getMinPrice() == null) ? "" : i.getMinPrice().toString())
            .add("maxPrice", (i.getMaxPrice() == null) ? "" : i.getMaxPrice().toString());
    if (i.getTags() != null) {
        JsonArrayBuilder jsonArrayBuilderInterest = Json.createArrayBuilder();
        for (String s : i.getTags()) {
            jsonArrayBuilderInterest.add(Json.createObjectBuilder().add("text", s));
        }/*from   w  ww  .  j  av a  2s  .co  m*/
        jsonObjectBuilder.add("tags", jsonArrayBuilderInterest);
    }
    JsonObject build = jsonObjectBuilder.build();
    return Response.ok(build.toString()).build();

}

From source file:nl.sidn.dnslib.message.records.dnssec.RRSIGResourceRecord.java

@Override
public JsonObject toJSon() {
    Date exp = new Date();
    exp.setTime((long) (signatureExpiration * 1000));

    Date incep = new Date();
    incep.setTime((long) (signatureInception * 1000));

    JsonObjectBuilder builder = super.createJsonBuilder();
    return builder
            .add("rdata", Json.createObjectBuilder().add("type-covered", typeCovered.name())
                    .add("algorithm", algorithm.name()).add("labels", labels).add("original-ttl", originalTtl)
                    .add("sig-exp", DATE_FMT.format(exp)).add("sig-inc", DATE_FMT.format(incep))
                    .add("keytag", (int) keytag).add("signer-name", signerName)
                    .add("signature", new Base64(Integer.MAX_VALUE, "".getBytes()).encodeAsString(signature)))
            .build();/*from   ww w . j a va 2  s  .  c o  m*/
}

From source file:com.amazon.alexa.avs.auth.companionservice.CompanionServiceClient.java

JsonObject callService(String path, Map<String, String> parameters) throws IOException {
    HttpURLConnection con = null;
    InputStream response = null;/*from  w w w .j  av  a  2  s .co m*/
    try {
        String queryString = mapToQueryString(parameters);
        URL obj = new URL(deviceConfig.getCompanionServiceInfo().getServiceUrl(), path + queryString);
        con = (HttpURLConnection) obj.openConnection();

        if (con instanceof HttpsURLConnection) {
            ((HttpsURLConnection) con).setSSLSocketFactory(pinnedSSLSocketFactory);
        }

        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestMethod("GET");

        if ((con.getResponseCode() >= 200) || (con.getResponseCode() < 300)) {
            response = con.getInputStream();
        }

        if (response != null) {
            String responsestring = IOUtils.toString(response);
            JsonReader reader = Json
                    .createReader(new ByteArrayInputStream(responsestring.getBytes(StandardCharsets.UTF_8)));
            IOUtils.closeQuietly(response);
            return reader.readObject();
        }
        return Json.createObjectBuilder().build();
    } catch (IOException e) {
        if (con != null) {
            response = con.getErrorStream();

            if (response != null) {
                String responsestring = IOUtils.toString(response);
                JsonReader reader = Json.createReader(
                        new ByteArrayInputStream(responsestring.getBytes(StandardCharsets.UTF_8)));
                JsonObject error = reader.readObject();

                String errorName = error.getString("error", null);
                String errorMessage = error.getString("message", null);

                if (!StringUtils.isBlank(errorName) && !StringUtils.isBlank(errorMessage)) {
                    throw new RemoteServiceException(errorName + ": " + errorMessage);
                }
            }
        }
        throw e;
    } finally {
        if (response != null) {
            IOUtils.closeQuietly(response);
        }
    }
}

From source file:org.bsc.confluence.rest.AbstractRESTConfluenceService.java

/**
 *
 * @param inputData//from  ww  w .j a v  a 2 s. com
 * @return
 */
protected final void rxAddLabels(String id, String... labels) {

    final JsonArrayBuilder inputBuilder = Json.createArrayBuilder();

    for (String name : labels) {

        inputBuilder.add(Json.createObjectBuilder().add("prefix", "global").add("name", name));

    }

    final JsonArray inputData = inputBuilder.build();

    final MediaType storageFormat = MediaType.parse("application/json");

    final RequestBody inputBody = RequestBody.create(storageFormat, inputData.toString());

    final HttpUrl url = urlBuilder().addPathSegment("content").addPathSegment(id).addPathSegment("label")
            .build();

    fromUrlPOST(url, inputBody, "add label");
}

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

/**
 * Get a list of the uploads/*from  w  w  w .  j av  a 2  s.c  o m*/
 * @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:com.buffalokiwi.aerodrome.jet.products.JetAPIProduct.java

/**
 * Adds product quantity and inventory data
 * @param product product data/*  w  w w  . j  a  va  2 s. c  om*/
 * @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;
}