Example usage for javax.json JsonObject getJsonArray

List of usage examples for javax.json JsonObject getJsonArray

Introduction

In this page you can find the example usage for javax.json JsonObject getJsonArray.

Prototype

JsonArray getJsonArray(String name);

Source Link

Document

Returns the array value to which the specified name is mapped.

Usage

From source file:org.wildfly.test.integration.microprofile.health.MicroProfileHealthHTTPEndpointTestCase.java

void checkGlobalOutcome(ManagementClient managementClient, boolean mustBeUP, String probeName)
        throws IOException {

    final String healthURL = "http://" + managementClient.getMgmtAddress() + ":"
            + managementClient.getMgmtPort() + "/health";

    try (CloseableHttpClient client = HttpClients.createDefault()) {

        CloseableHttpResponse resp = client.execute(new HttpGet(healthURL));
        assertEquals(mustBeUP ? 200 : 503, resp.getStatusLine().getStatusCode());

        String content = getContent(resp);
        resp.close();//ww  w . jav  a2  s  . co  m

        try (JsonReader jsonReader = Json.createReader(new StringReader(content))) {
            JsonObject payload = jsonReader.readObject();
            String outcome = payload.getString("outcome");
            assertEquals(mustBeUP ? "UP" : "DOWN", outcome);

            if (probeName != null) {
                for (JsonValue check : payload.getJsonArray("checks")) {
                    if (probeName.equals(check.asJsonObject().getString("name"))) {
                        // probe name found
                        assertEquals(mustBeUP ? "UP" : "DOWN", check.asJsonObject().getString("state"));
                        return;
                    }
                }
                fail("Probe named " + probeName + " not found in " + content);
            }
        }
    }
}

From source file:org.kitodo.data.elasticsearch.index.type.AuthorityTypeTest.java

@Test
public void shouldCreateFirstDocument() throws Exception {
    AuthorityType authorityType = new AuthorityType();

    Authority authority = prepareData().get(0);
    HttpEntity document = authorityType.createDocument(authority);

    JsonObject actual = Json.createReader(new StringReader(EntityUtils.toString(document))).readObject();

    assertEquals("Key title doesn't match to given value!", "First",
            AuthorityTypeField.TITLE.getStringValue(actual));

    JsonArray userGroups = actual.getJsonArray(AuthorityTypeField.USER_GROUPS.getKey());
    assertEquals("Size userGroups doesn't match to given value!", 1, userGroups.size());

    JsonObject userGroup = userGroups.getJsonObject(0);
    assertEquals("Key userGroups.id doesn't match to given value!", 1,
            UserGroupTypeField.ID.getIntValue(userGroup));
    assertEquals("Key userGroups.title doesn't match to given value!", "First",
            UserGroupTypeField.TITLE.getStringValue(userGroup));
}

From source file:org.fuin.esmp.Downloads.java

/**
 * Loads the data from the JSON download versions file.
 * /*from   w  ww  .  ja  v  a  2  s  .c  o  m*/
 * @throws IOException
 *             Parsing the event store version file failed.
 */
public final void parse() throws IOException {

    final Reader reader = new FileReader(jsonDownloadsFile);
    try {
        final JsonReader jsonReader = Json.createReader(reader);
        final JsonArray osArray = jsonReader.readArray();
        for (int i = 0; i < osArray.size(); i++) {
            final JsonObject osObj = (JsonObject) osArray.get(i);
            final String os = osObj.getString("os");
            final String currentVersion = osObj.getString("currentVersion");
            final JsonArray downloadsArray = osObj.getJsonArray("downloads");
            final List<DownloadVersion> versions = new ArrayList<>();
            for (int j = 0; j < downloadsArray.size(); j++) {
                final JsonObject downloadObj = (JsonObject) downloadsArray.get(j);
                final String version = downloadObj.getString("version");
                final String url = downloadObj.getString("url");
                versions.add(new DownloadVersion(version, url));
            }
            Collections.sort(versions);
            osList.add(new DownloadOS(os, currentVersion, versions));
        }
        Collections.sort(osList);
    } finally {
        reader.close();
    }

    for (final DownloadOS os : osList) {
        LOG.info("Latest '" + os + "': " + os.getLatestVersion() + " (Versions: " + os.getVersions().size()
                + ")");
    }

}

From source file:DesignGUI.java

private void parseStackExchange(String jsonStr) {
    JsonReader reader = null;//ww  w .j ava2  s.c  o  m
    StringBuilder content = new StringBuilder();

    this.jEditorPane_areaShow.setContentType("text/html");

    content.append("<html></body>");
    try {
        reader = Json.createReader(new StringReader(jsonStr));
        JsonObject jsonObject = reader.readObject();
        reader.close();
        JsonArray array = jsonObject.getJsonArray("items");
        for (JsonObject result : array.getValuesAs(JsonObject.class)) {

            JsonObject ownerObject = result.getJsonObject("owner");
            //   int ownerReputation = ownerObject.getInt("reputation");
            //  System.out.println("Reputation:"+ownerReputation);
            int viewCount = result.getInt("view_count");
            content.append("<br>View Count :" + viewCount + "<br>");

            int answerCount = result.getInt("answer_count");
            content.append("Answer Count :" + answerCount + "<br>");

            String title = result.getString("title");
            content.append("Title: <FONT COLOR=green>" + title + "</FONT>.<br>");

            String link = result.getString("link");

            content.append("URL :<a href=");
            content.append("'link'>" + link);
            content.append("</a>.<br>");

            //  String body = result.getString("body"); 
            //  content.append("Body:"+body);

            /* JsonArray tagsArray = result.getJsonArray("tags");
             StringBuilder tagBuilder = new StringBuilder();
             int i = 1;
             for(JsonValue tag : tagsArray){
            tagBuilder.append(tag.toString());
            if(i < tagsArray.size())
                tagBuilder.append(",");
            i++;
             }
            content.append("Tags: "+tagBuilder.toString());*/
        }

        content.append("</body></html>");
        this.jEditorPane_areaShow.setText(content.toString());
        System.out.println(content.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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();/*  ww w.java  2  s.com*/
    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:org.bsc.confluence.rest.AbstractRESTConfluenceService.java

protected Stream<JsonObject> mapToStream(Response res) {

    final ResponseBody body = res.body();

    try (Reader r = body.charStream()) {

        final JsonReader rdr = Json.createReader(r);

        final JsonObject root = rdr.readObject();

        final Stream.Builder<JsonObject> stream = Stream.builder();

        // Check for Array
        if (root.containsKey("results")) {
            final JsonArray results = root.getJsonArray("results");

            if (results != null) {
                for (int ii = 0; ii < results.size(); ++ii)
                    stream.add(results.getJsonObject(ii));
            }//from w w  w .  ja  v a2  s.co m
        } else {
            stream.add(root);
        }

        return stream.build();

    } catch (IOException | JsonParsingException e) {
        throw new Error(e);
    }

}

From source file:de.pangaea.fixo3.CreateEsonetYellowPages.java

private void run() throws OWLOntologyCreationException, OWLOntologyStorageException, FileNotFoundException {
    m = new OntologyManager(ns);
    m.addTitle("ESONET Yellow Pages Ontology");
    m.addVersion("1.0");
    m.addDate("2016-11-23");
    m.addCreator("Markus Stocker");
    m.addSeeAlso("http://www.esonetyellowpages.com/");
    m.addImport(SSN.ns);/*from   w  w w . java2s .co  m*/

    m.addSubClass(Frequency, MeasurementProperty);
    m.addLabel(Frequency, "Frequency");
    m.addSubClass(ProfilingRange, MeasurementProperty);
    m.addLabel(ProfilingRange, "Profiling Range");
    m.addSubClass(CellSize, MeasurementProperty);
    m.addLabel(CellSize, "Cell Size");
    m.addSubClass(OperatingDepth, MeasurementProperty);
    m.addLabel(OperatingDepth, "Operating Depth");
    m.addSubClass(TemperatureRange, MeasurementProperty);
    m.addLabel(TemperatureRange, "Temperature Range");
    m.addSubClass(MeasuringRange, MeasurementProperty);
    m.addLabel(MeasuringRange, "Measuring Range");

    m.addClass(WaterCurrent);
    m.addLabel(WaterCurrent, "Water Current");
    m.addSubClass(WaterCurrent, FeatureOfInterest);

    m.addClass(CarbonDioxide);
    m.addLabel(CarbonDioxide, "Carbon Dioxide");
    m.addSubClass(CarbonDioxide, FeatureOfInterest);

    m.addClass(Speed);
    m.addLabel(Speed, "Speed");
    m.addSubClass(Speed, Property);
    m.addObjectSome(Speed, isPropertyOf, WaterCurrent);

    m.addClass(PartialPressure);
    m.addLabel(PartialPressure, "Partial Pressure");
    m.addSubClass(PartialPressure, Property);
    m.addObjectSome(PartialPressure, isPropertyOf, CarbonDioxide);

    m.addClass(DopplerEffect);
    m.addSubClass(DopplerEffect, Stimulus);
    m.addLabel(DopplerEffect, "Doppler Effect");
    m.addComment(DopplerEffect,
            "The Doppler effect (or the Doppler shift) is the change in frequency of a wave (or other periodic event) for an observer moving relative to its source.");
    m.addSource(DopplerEffect, IRI.create("https://en.wikipedia.org/wiki/Doppler_effect"));
    m.addObjectAll(DopplerEffect, isProxyFor, Speed);

    m.addClass(Infrared);
    m.addSubClass(Infrared, Stimulus);
    m.addLabel(Infrared, "Infrared");
    m.addComment(Infrared, "Infrared (IR) is an invisible radiant energy.");
    m.addSource(Infrared, IRI.create("https://en.wikipedia.org/wiki/Infrared"));
    m.addObjectAll(Infrared, isProxyFor, PartialPressure);

    m.addClass(AcousticDopplerCurrentProfiler);
    m.addLabel(AcousticDopplerCurrentProfiler, "Acoustic Doppler Current Profiler");
    m.addSource(AcousticDopplerCurrentProfiler,
            IRI.create("https://en.wikipedia.org/wiki/Acoustic_Doppler_current_profiler"));
    m.addComment(AcousticDopplerCurrentProfiler,
            "An acoustic Doppler current profiler (ADCP) is a hydroacoustic current meter similar to a sonar, attempting to measure water current velocities over a depth range using the Doppler effect of sound waves scattered back from particles within the water column.");
    m.addObjectAll(AcousticDopplerCurrentProfiler, detects, DopplerEffect);
    m.addObjectAll(AcousticDopplerCurrentProfiler, observes, Speed);
    m.addSubClass(AcousticDopplerCurrentProfiler, HydroacousticCurrentMeter);

    m.addClass(PartialPressureOfCO2Analyzer);
    m.addLabel(PartialPressureOfCO2Analyzer, "Partial Pressure of CO2 Analyzer");
    m.addObjectAll(PartialPressureOfCO2Analyzer, detects, Infrared);
    m.addObjectAll(PartialPressureOfCO2Analyzer, observes, PartialPressure);
    m.addSubClass(PartialPressureOfCO2Analyzer, SensingDevice);

    m.addClass(HydroacousticCurrentMeter);
    m.addLabel(HydroacousticCurrentMeter, "Hydroacoustic Current Meter");
    m.addSubClass(HydroacousticCurrentMeter, SensingDevice);

    JsonReader jr = Json.createReader(new FileReader(new File(eypDevicesFile)));
    JsonArray ja = jr.readArray();

    for (JsonObject jo : ja.getValuesAs(JsonObject.class)) {
        String name = jo.getString("name");
        String label = jo.getString("label");
        String comment = jo.getString("comment");
        String seeAlso = jo.getString("seeAlso");
        JsonArray equivalentClasses = jo.getJsonArray("equivalentClasses");
        JsonArray subClasses = jo.getJsonArray("subClasses");

        addDeviceType(name, label, comment, seeAlso, equivalentClasses, subClasses);
    }

    m.save(eypFile);
    m.saveInferred(eypInferredFile);
}

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

public void executeTextContextualization(Exchange exchange) {

    taskStep = "CONTEXTUALIZER_CONTEXTUALIZE_DOCUMENTS";

    logger.debug("New message retrieved for " + taskStep);

    JsonObjectBuilder job = Json.createObjectBuilder();

    JsonObject headers = MessageTools.getHeaders(exchange);

    long taskId = Long.parseLong(headers.getString("taskId"));
    scheduler.updateTask(taskId, TaskStatus.RUNNING, taskStep, null);

    JsonObject jsonBody = MessageTools.getBody(exchange);

    String cmisServerId = null;/*from   ww w.  j a  v  a 2  s. com*/

    if (jsonBody != null) {

        cmisServerId = jsonBody.getString("cmisServerId");
        JsonArray jsonEntities = jsonBody.getJsonArray("entities");

        job.add("cmisServerId", cmisServerId);
        job.add("entities", jsonEntities);

        for (JsonValue jsonValue : jsonEntities) {

            JsonObject jsonObject = (JsonObject) jsonValue;

            String type = jsonObject.getString("type");

            if (type.equals(Collection.class.getName()))
                continue;

            long pofId = jsonObject.getInt("pofId");

            try {

                String collectorStorageFolder = ConfigurationManager.getConfiguration()
                        .getString("collector.storage.folder");

                Path sipPath = Paths.get(collectorStorageFolder + File.separator + pofId);

                Path metadataPath = Paths.get(sipPath.toString(), "metadata");

                Path contentPath = Paths.get(sipPath.toString(), "content");

                Path contextAnalysisPath = Paths.get(metadataPath.toString(), "worldContext.json");

                logger.debug("Looking for text documents in folder: " + contentPath);

                List<File> documentList = getFilteredDocumentList(contentPath);

                logger.debug("Document List for Contextualization: " + documentList);

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

                    File[] documents = documentList.stream().toArray(File[]::new);

                    context = service.contextualize(documents);

                    logger.debug("World Context:\n");

                    for (String contextEntry : context) {

                        logger.debug(contextEntry);
                    }

                    StringBuilder contextResult = new StringBuilder();

                    for (int i = 0; i < context.length; i++) {

                        Map<String, String> jsonMap = new HashMap<>();
                        jsonMap.put("filename", documents[i].getName());
                        jsonMap.put("context", context[i]);

                        contextResult.append(jsonMap.toString());

                    }

                    FileUtils.writeStringToFile(contextAnalysisPath.toFile(), contextResult.toString());

                    logger.debug("Document Contextualization completed for " + documentList);

                }

            } catch (IOException | ResourceInstantiationException | ExecutionException e) {

                e.printStackTrace();

            }

        }

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

    } else {

        scheduler.updateTask(taskId, TaskStatus.FAILED, taskStep, null);

        job.add("Message", "Task " + taskId + " failed");

        scheduler.sendMessage("activemq:queue:ERROR.QUEUE", exchange.getIn().getHeaders(), job.build());

    }

}

From source file:org.optaplanner.examples.conferencescheduling.persistence.ConferenceSchedulingCfpDevoxxImporter.java

private Set<String> extractContentTagSet(JsonObject talkObject) {
    if (talkObject.containsKey("tags")) {
        return talkObject.getJsonArray("tags").stream().map(JsonObject.class::cast)
                .filter(tagObject -> !tagObject.getString("value").isEmpty())
                .map(tagObject -> tagObject.getString("value")).collect(Collectors.toSet());
    }//from   w ww  .  ja  v  a  2  s  . c  o m
    return new HashSet<>();
}

From source file:org.optaplanner.examples.conferencescheduling.persistence.ConferenceSchedulingCfpDevoxxImporter.java

private void importTrackIdSet() {
    this.trackIdSet = new HashSet<>();
    String tracksUrl = conferenceBaseUrl + "/tracks";
    LOGGER.debug("Sending a request to: " + tracksUrl);
    JsonObject rootObject = readJson(tracksUrl, JsonReader::readObject);

    JsonArray tracksArray = rootObject.getJsonArray("tracks");
    for (int i = 0; i < tracksArray.size(); i++) {
        trackIdSet.add(tracksArray.getJsonObject(i).getString("id"));
    }//  w  ww .  j  a  va 2s  .c  om
}