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.owasp.dependencycheck.analyzer.NspAnalyzer.java

@Override
protected void analyzeDependency(Dependency dependency, Engine engine) throws AnalysisException {
    engine.removeDependency(dependency);
    final File file = dependency.getActualFile();
    if (!file.isFile() || file.length() == 0 || !shouldProcess(file)) {
        return;// w w w.j a v  a2 s.  co m
    }

    try (JsonReader jsonReader = Json.createReader(FileUtils.openInputStream(file))) {

        // Retrieves the contents of package.json from the Dependency
        final JsonObject packageJson = jsonReader.readObject();

        // Create a sanitized version of the package.json
        final JsonObject sanitizedJson = SanitizePackage.sanitize(packageJson);

        // Create a new 'package' object that acts as a container for the sanitized package.json
        final JsonObjectBuilder builder = Json.createObjectBuilder();
        final JsonObject nspPayload = builder.add("package", sanitizedJson).build();

        // Submits the package payload to the nsp check service
        final List<Advisory> advisories = searcher.submitPackage(nspPayload);

        for (Advisory advisory : advisories) {
            /*
             * Create a new vulnerability out of the advisory returned by nsp.
             */
            final Vulnerability vuln = new Vulnerability();
            vuln.setCvssScore(advisory.getCvssScore());
            vuln.setDescription(advisory.getOverview());
            vuln.setName(String.valueOf(advisory.getId()));
            vuln.setSource(Vulnerability.Source.NSP);
            vuln.addReference("NSP", "Advisory " + advisory.getId() + ": " + advisory.getTitle(),
                    advisory.getAdvisory());

            /*
             * Create a single vulnerable software object - these do not use CPEs unlike the NVD.
             */
            final VulnerableSoftware vs = new VulnerableSoftware();
            //TODO consider changing this to available versions on the dependency
            //  - the update is a part of the version, not versions to update to
            //vs.setUpdate(advisory.getPatchedVersions());

            vs.setName(advisory.getModule() + ":" + advisory.getVulnerableVersions());
            vuln.setVulnerableSoftware(new HashSet<>(Arrays.asList(vs)));

            final Dependency existing = findDependency(engine, advisory.getModule(), advisory.getVersion());
            if (existing == null) {
                final Dependency nodeModule = createDependency(dependency, advisory.getModule(),
                        advisory.getVersion(), "transitive");
                nodeModule.addVulnerability(vuln);
                engine.addDependency(nodeModule);
            } else {
                existing.addVulnerability(vuln);
            }
        }
    } catch (URLConnectionFailureException e) {
        this.setEnabled(false);
        throw new AnalysisException(e.getMessage(), e);
    } catch (IOException e) {
        LOGGER.debug("Error reading dependency or connecting to Node Security Platform - check API", e);
        this.setEnabled(false);
        throw new AnalysisException(e.getMessage(), e);
    } catch (JsonException e) {
        throw new AnalysisException(String.format("Failed to parse %s file.", file.getPath()), e);
    }
}

From source file:uk.trainwatch.app.util.Memo.java

@Override
public void runUtility() throws Exception {
    LOG.log(Level.INFO, "Initialising");

    Consumer<? super JsonStructure> consumer = RabbitMQ.jsonConsumer(con, "a51.li.memo");

    for (String fileName : files) {
        String t = title;//  ww  w. jav  a  2  s.  c o m
        if (t == null) {
            t = fileName;
        }

        LOG.log(Level.INFO, "Reading {0}", fileName);

        String text;
        try (BufferedReader r = new BufferedReader(new FileReader(fileName))) {
            text = r.lines().collect(Collectors.joining("<br/>"));
        }

        LOG.log(Level.INFO, "Generating json");

        JsonObjectBuilder b = Json.createObjectBuilder().add("user", user).add("hash", hash).add("type", type)
                .add("title", t).add("text", text);

        if (expires != null) {
            b.add("expires", expires.toString());
        }

        if (tweetAs != null) {
            b.add("tweetAs", tweetAs).add("tweet", t);
        }

        JsonObject o = b.build();

        LOG.log(Level.INFO, "Tweeting {0}", o);

        consumer.accept(o);

        LOG.log(Level.INFO, "Done");
    }

    System.exit(0);
}

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: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 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: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  ww.j  a  va  2s . co  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:eu.forgetit.middleware.component.Condensator.java

public void imageClustering_bkp(Exchange exchange) {

    logger.debug("New message retrieved");

    JsonObject headers = MessageTools.getHeaders(exchange);

    long taskId = headers.getInt("taskId");
    scheduler.updateTask(taskId, TaskStatus.RUNNING, "IMAGE CLUSTERING", null);

    MessageTools.setHeaders(exchange, headers);

    JsonObject jsonBody = MessageTools.getBody(exchange);

    if (jsonBody != null) {

        try {//  w  ww  . j  a  v  a 2  s  .  c  o m

            String jsonNofImagesElement = jsonBody.getString("numOfImages");
            String minCLusteringImages = headers.getString("minClusteringImages");

            int nofImages = 0;
            int minNofImages = 0;

            if (jsonNofImagesElement != null)
                nofImages = Integer.parseInt(jsonNofImagesElement);

            if (minCLusteringImages != null)
                minNofImages = Integer.parseInt(minCLusteringImages);
            else
                minNofImages = 0;

            String jsonImageAnalysisResult = jsonBody.getString("imageAnalysis-all");
            if (jsonImageAnalysisResult != null)
                imageAnalysisResult = jsonImageAnalysisResult;
            logger.debug("Retrieved Image Analysis Result: " + imageAnalysisResult);

            String jsonMetadataDir = jsonBody.getString("sipMetadataDir");
            if (jsonMetadataDir != null)
                sipMetadataDirPath = jsonMetadataDir;
            logger.debug("Retrieved SIP Metadata Directory: " + sipMetadataDirPath);

            if (nofImages >= minNofImages) {

                logger.debug("Executing Image Collection Clustering");

                String response = service.request(imageAnalysisResult);

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

                File resultFile = new File(sipMetadataDirPath, "clustering.xml");

                FileUtils.writeStringToFile(resultFile, response);

                JsonObjectBuilder job = Json.createObjectBuilder();

                job.add("clustering", resultFile.getAbsolutePath());

                for (Entry<String, JsonValue> entry : jsonBody.entrySet()) {
                    job.add(entry.getKey(), entry.getValue());
                }

                exchange.getIn().setBody(jsonBody.toString());

            } else {

                logger.debug("Found only " + nofImages + " images, below threshold (" + minCLusteringImages
                        + ")... skipping.");
            }

        } catch (NumberFormatException | IOException e) {

            e.printStackTrace();
        }

    } else {

        JsonObjectBuilder job = Json.createObjectBuilder().add("taskStatus", TaskStatus.FAILED.toString());

        for (Entry<String, JsonValue> entry : headers.entrySet()) {
            job.add(entry.getKey(), entry.getValue());
        }

        MessageTools.setHeaders(exchange, headers);

    }

}

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();//  w  w  w.  j a v a  2 s . c  om
    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:com.adobe.cq.wcm.core.components.internal.models.v1.ImageImpl.java

protected void buildJson() {
    JsonArrayBuilder smartSizesJsonBuilder = Json.createArrayBuilder();
    for (int size : smartSizes) {
        smartSizesJsonBuilder.add(size);
    }/*from w  ww  .  java  2 s .  c om*/
    JsonArrayBuilder smartImagesJsonBuilder = Json.createArrayBuilder();
    for (String image : smartImages) {
        smartImagesJsonBuilder.add(image);
    }
    JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
    jsonObjectBuilder.add(JSON_SMART_IMAGES, smartImagesJsonBuilder);
    jsonObjectBuilder.add(JSON_SMART_SIZES, smartSizesJsonBuilder);
    jsonObjectBuilder.add(JSON_LAZY_ENABLED, !disableLazyLoading);
    json = jsonObjectBuilder.build().toString();
}

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  www.  ja  va2  s .  c  om

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

    }
}