Example usage for javax.json JsonObject get

List of usage examples for javax.json JsonObject get

Introduction

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

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

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 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();//from w w  w  . j  a  va  2  s . 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: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 w ww  .j a  v  a  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.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.owasp.dependencycheck.analyzer.NodePackageAnalyzer.java

@Override
protected void analyzeFileType(Dependency dependency, Engine engine) throws AnalysisException {
    final File file = dependency.getActualFile();
    JsonReader jsonReader;/*www.j  a v a 2 s  .c  o m*/
    try {
        jsonReader = Json.createReader(FileUtils.openInputStream(file));
    } catch (IOException e) {
        throw new AnalysisException("Problem occurred while reading dependency file.", e);
    }
    try {
        final JsonObject json = jsonReader.readObject();
        final EvidenceCollection productEvidence = dependency.getProductEvidence();
        final EvidenceCollection vendorEvidence = dependency.getVendorEvidence();
        if (json.containsKey("name")) {
            final Object value = json.get("name");
            if (value instanceof JsonString) {
                final String valueString = ((JsonString) value).getString();
                productEvidence.addEvidence(PACKAGE_JSON, "name", valueString, Confidence.HIGHEST);
                vendorEvidence.addEvidence(PACKAGE_JSON, "name_project",
                        String.format("%s_project", valueString), Confidence.LOW);
            } else {
                LOGGER.warn("JSON value not string as expected: {}", value);
            }
        }
        addToEvidence(json, productEvidence, "description");
        addToEvidence(json, vendorEvidence, "author");
        addToEvidence(json, dependency.getVersionEvidence(), "version");
        dependency.setDisplayFileName(String.format("%s/%s", file.getParentFile().getName(), file.getName()));
    } catch (JsonException e) {
        LOGGER.warn("Failed to parse package.json file.", e);
    } finally {
        jsonReader.close();
    }
}

From source file:org.hyperledger.fabric.sdk.NetworkConfig.java

private static void setPeerRole(String channelName, PeerOptions peerOptions, JsonObject jsonPeer, PeerRole role)
        throws NetworkConfigurationException {
    String propName = roleNameRemap(role);
    JsonValue val = jsonPeer.get(propName);
    if (val != null) {
        Boolean isSet = getJsonValueAsBoolean(val);
        if (isSet == null) {
            // This is an invalid boolean value
            throw new NetworkConfigurationException(
                    format("Error constructing channel %s. Role %s has invalid boolean value: %s", channelName,
                            propName, val.toString()));
        }//from  w  w w.  ja v  a  2 s .c  o m
        if (isSet) {
            peerOptions.addPeerRole(role);
        }
    }
}

From source file:org.hyperledger.fabric.sdk.NetworkConfig.java

private static String extractPemString(JsonObject json, String fieldName, String msgPrefix)
        throws NetworkConfigurationException {

    String path = null;//  ww  w  . j av  a 2  s. c  o m
    String pemString = null;

    JsonObject jsonField = getJsonValueAsObject(json.get(fieldName));
    if (jsonField != null) {
        path = getJsonValueAsString(jsonField.get("path"));
        pemString = getJsonValueAsString(jsonField.get("pem"));
    }

    if (path != null && pemString != null) {
        throw new NetworkConfigurationException(
                format("%s should not specify both %s path and pem", msgPrefix, fieldName));
    }

    if (path != null) {
        // Determine full pathname and ensure the file exists
        File pemFile = new File(path);
        String fullPathname = pemFile.getAbsolutePath();
        if (!pemFile.exists()) {
            throw new NetworkConfigurationException(
                    format("%s: %s file %s does not exist", msgPrefix, fieldName, fullPathname));
        }
        try (FileInputStream stream = new FileInputStream(pemFile)) {
            pemString = IOUtils.toString(stream, "UTF-8");
        } catch (IOException ioe) {
            throw new NetworkConfigurationException(format("Failed to read file: %s", fullPathname), ioe);
        }

    }

    return pemString;
}

From source file:org.apache.tamaya.etcd.EtcdAccessor.java

/**
 * Recursively read out all key/values from this etcd JSON array.
 *
 * @param result map with key, values and metadata.
 * @param node   the node to parse./*from w w w.j  a v  a2  s .  com*/
 */
private void addNodes(Map<String, String> result, JsonObject node) {
    if (!node.containsKey("dir") || "false".equals(node.get("dir").toString())) {
        final String key = node.getString("key").substring(1);
        result.put(key, node.getString("value"));
        if (node.containsKey("createdIndex")) {
            result.put("_" + key + ".createdIndex", String.valueOf(node.getInt("createdIndex")));
        }
        if (node.containsKey("modifiedIndex")) {
            result.put("_" + key + ".modifiedIndex", String.valueOf(node.getInt("modifiedIndex")));
        }
        if (node.containsKey("expiration")) {
            result.put("_" + key + ".expiration", String.valueOf(node.getString("expiration")));
        }
        if (node.containsKey("ttl")) {
            result.put("_" + key + ".ttl", String.valueOf(node.getInt("ttl")));
        }
        result.put("_" + key + ".source", "[etcd]" + serverURL);
    } else {
        final JsonArray nodes = node.getJsonArray("nodes");
        if (nodes != null) {
            for (int i = 0; i < nodes.size(); i++) {
                addNodes(result, nodes.getJsonObject(i));
            }
        }
    }
}

From source file:edu.harvard.hms.dbmi.bd2k.irct.ri.exac.EXACResourceImplementation.java

private List<String> getNames(String prefix, JsonObject obj) {
    List<String> returns = new ArrayList<String>();
    for (String field : obj.keySet()) {
        if (obj.get(field).getValueType() == ValueType.OBJECT) {
            if (prefix.equals("")) {
                returns.addAll(getNames(field, obj.getJsonObject(field)));
            } else {
                returns.addAll(getNames(prefix + "." + field, obj.getJsonObject(field)));
            }//from   ww w. j a va  2  s .  c  o  m
        } else if (obj.get(field).getValueType() != ValueType.ARRAY) {
            if (prefix.equals("")) {
                returns.add(field);
            } else {
                returns.add(prefix + "." + field);
            }
        }
    }

    return returns;
}

From source file:org.jboss.as.test.integration.logging.formatters.JsonFormatterTestCase.java

@Test
public void testKeyOverrides() throws Exception {
    final Map<String, String> keyOverrides = new HashMap<>();
    keyOverrides.put("timestamp", "dateTime");
    keyOverrides.put("sequence", "seq");
    final Map<String, String> metaData = new LinkedHashMap<>();
    metaData.put("test-key-1", "test-value-1");
    metaData.put("key-no-value", null);
    // Configure the subsystem
    configure(keyOverrides, metaData, true);

    final String msg = "Logging test: JsonFormatterTestCase.defaultLoggingTest";
    final Map<String, String> params = new LinkedHashMap<>();
    // Indicate we need an exception logged
    params.put(LoggingServiceActivator.LOG_EXCEPTION_KEY, "true");
    // Add an NDC value
    params.put(LoggingServiceActivator.NDC_KEY, "test.ndc.value");
    // Add some map entries for MDC values
    params.put("mdcKey1", "mdcValue1");
    params.put("mdcKey2", "mdcValue2");

    final List<String> expectedKeys = createDefaultKeys();
    expectedKeys.remove("timestamp");
    expectedKeys.remove("sequence");
    expectedKeys.addAll(keyOverrides.values());
    expectedKeys.addAll(metaData.keySet());
    expectedKeys.add("exception");
    expectedKeys.add("stackTrace");
    expectedKeys.add("sourceFileName");
    expectedKeys.add("sourceMethodName");
    expectedKeys.add("sourceClassName");
    expectedKeys.add("sourceLineNumber");
    expectedKeys.add("sourceModuleVersion");
    expectedKeys.add("sourceModuleName");

    final int statusCode = getResponse(msg, params);
    Assert.assertTrue("Invalid response statusCode: " + statusCode, statusCode == HttpStatus.SC_OK);

    // Validate each line
    for (String s : Files.readAllLines(logFile, StandardCharsets.UTF_8)) {
        if (s.trim().isEmpty())
            continue;
        try (JsonReader reader = Json.createReader(new StringReader(s))) {
            final JsonObject json = reader.readObject();
            validateDefault(json, expectedKeys, msg);

            // Timestamp should have been renamed to dateTime
            Assert.assertNull("Found timestamp entry in " + s, json.get("timestamp"));

            // Sequence should have been renamed to seq
            Assert.assertNull("Found sequence entry in " + s, json.get("sequence"));

            // Validate MDC
            final JsonObject mdcObject = json.getJsonObject("mdc");
            Assert.assertEquals("mdcValue1", mdcObject.getString("mdcKey1"));
            Assert.assertEquals("mdcValue2", mdcObject.getString("mdcKey2"));

            // Validate the meta-data
            Assert.assertEquals("test-value-1", json.getString("test-key-1"));
            Assert.assertEquals("Expected a null type but got " + json.get("key-no-value"),
                    JsonValue.ValueType.NULL, json.get("key-no-value").getValueType());

            validateStackTrace(json, true, true);
        }//  ww  w . j av a 2  s.  c  om
    }
}