Example usage for javax.json JsonObject keySet

List of usage examples for javax.json JsonObject keySet

Introduction

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

Prototype

Set<K> keySet();

Source Link

Document

Returns a Set view of the keys contained in this map.

Usage

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

private static void validateDefault(final JsonObject json, final Collection<String> expectedKeys,
        final String expectedMessage) {
    final Set<String> remainingKeys = new HashSet<>(json.keySet());

    // Check all the expected keys
    for (String key : expectedKeys) {
        checkNonNull(json, key);/*from  www .  ja  v a2 s.c o  m*/
        Assert.assertTrue("Missing key " + key + " from JSON object: " + json, remainingKeys.remove(key));
    }

    // Should have no more remaining keys
    Assert.assertTrue("There are remaining keys that were not validated: " + remainingKeys,
            remainingKeys.isEmpty());

    Assert.assertEquals("org.jboss.logging.Logger", json.getString("loggerClassName"));
    Assert.assertEquals(LoggingServiceActivator.LOGGER.getName(), json.getString("loggerName"));
    Assert.assertTrue("Invalid level found in " + json.get("level"), isValidLevel(json.getString("level")));
    Assert.assertEquals(expectedMessage, json.getString("message"));
}

From source file:org.apache.unomi.services.services.SegmentServiceImpl.java

public static void dumpJSON(JsonValue tree, String key, String depthPrefix) {
    if (key != null)
        logger.info(depthPrefix + "Key " + key + ": ");
    switch (tree.getValueType()) {
    case OBJECT:/*from  w ww .ja  va  2s . co  m*/
        logger.info(depthPrefix + "OBJECT");
        JsonObject object = (JsonObject) tree;
        for (String name : object.keySet())
            dumpJSON(object.get(name), name, depthPrefix + "  ");
        break;
    case ARRAY:
        logger.info(depthPrefix + "ARRAY");
        JsonArray array = (JsonArray) tree;
        for (JsonValue val : array)
            dumpJSON(val, null, depthPrefix + "  ");
        break;
    case STRING:
        JsonString st = (JsonString) tree;
        logger.info(depthPrefix + "STRING " + st.getString());
        break;
    case NUMBER:
        JsonNumber num = (JsonNumber) tree;
        logger.info(depthPrefix + "NUMBER " + num.toString());
        break;
    case TRUE:
    case FALSE:
    case NULL:
        logger.info(depthPrefix + tree.getValueType().toString());
        break;
    }
}

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

@Test
public void shouldCreateDocumentWithCorrectAmountOfKeys() 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("Amount of keys is incorrect!", 2, actual.keySet().size());

    JsonArray userGroups = AuthorityTypeField.USER_GROUPS.getJsonArray(actual);
    JsonObject userGroup = userGroups.getJsonObject(0);
    assertEquals("Amount of keys in userGroups is incorrect!", 2, userGroup.keySet().size());
}

From source file:io.bibleget.VersionsSelect.java

public VersionsSelect() throws ClassNotFoundException {
    biblegetDB = BibleGetDB.getInstance();
    String bibleVersionsStr = biblegetDB.getMetaData("VERSIONS");
    JsonReader jsonReader = Json.createReader(new StringReader(bibleVersionsStr));
    JsonObject bibleVersionsObj = jsonReader.readObject();
    Set<String> versionsabbrev = bibleVersionsObj.keySet();
    bibleVersions = new BasicEventList<>();
    if (!versionsabbrev.isEmpty()) {
        for (String s : versionsabbrev) {
            String versionStr = bibleVersionsObj.getString(s); //store these in an array
            String[] array;//from   ww w  .  ja  va  2s. c om
            array = versionStr.split("\\|");
            bibleVersions.add(new BibleVersion(s, array[0], array[1],
                    StringUtils.capitalize(new Locale(array[2]).getDisplayLanguage())));
        }
    }

    versionsByLang = new SeparatorList<>(bibleVersions, new VersionComparator(), 1, 1000);

    int listLength = versionsByLang.size();
    enabledFlags = new boolean[listLength];

    ListIterator itr = versionsByLang.listIterator();
    while (itr.hasNext()) {
        int idx = itr.nextIndex();
        Object next = itr.next();
        enabledFlags[idx] = !(next.getClass().getSimpleName().equals("GroupSeparator"));
        if (enabledFlags[idx]) {
            versionCount++;
        } else {
            versionLangs++;
        }
    }

    this.setModel(new DefaultEventListModel<>(versionsByLang));
    this.setCellRenderer(new VersionCellRenderer());
    this.setSelectionModel(new DisabledItemSelectionModel());
}

From source file:com.rhcloud.javaee.movieinfo.business.actor.boundry.ActorResourceIT.java

@Test
public void actor_integration_OptimisticLockingCheck() {
    // Get Actor/*from  www .ja  v  a2 s  . c om*/
    Response getResponse = null;
    try {
        getResponse = provider.target().path(FORWARD_SLASH + ACTORS_PATH + FORWARD_SLASH + 1)
                .request(APPLICATION_JSON).get();
    } finally {
        System.out.println("Server responded ? " + (getResponse != null));
        assumeThat(getResponse, is(notNullValue()));
    }

    final String fn = "John";
    final String ln = "Doe";

    // Post Actor
    Response postResponse = provider.target().path(FORWARD_SLASH + ACTORS_PATH).request(APPLICATION_JSON)
            .post(Entity.json(createActor(fn, ln)));
    assertThat(postResponse, is(successful()));

    String location = postResponse.getHeaderString("Location");
    assertThat(location, is(notNullValue()));
    System.out.println(
            "ActorResourceIT.actor_integration_OptimisticLockingCheck() Post Actor Response Location : "
                    + location);

    try {
        // Get Actor
        Response actorResponse = provider.target(location).request(APPLICATION_JSON).get();
        assertThat(actorResponse, is(successful()));

        JsonObject actor = actorResponse.readEntity(JsonObject.class);
        assertThat(actor.getString(FIRSTNAME), is(equalTo(fn)));
        assertThat(actor.getString(LASTNAME), is(equalTo(ln)));
        assertThat(actor.keySet(), hasItem(VERSION));

        long version = actor.getJsonNumber(VERSION).longValue();
        System.out.println("ActorResourceIT.actor_integration_OptimisticLockingCheck() Get Actor : " + actor);

        // Update Actor Once
        final String newFn = "Jane";
        JsonObject actorUpdate = Json.createObjectBuilder().add(FIRSTNAME, newFn).add(LASTNAME, ln)
                .add(VERSION, version).build();
        Response putResponse = provider.target(location).request(APPLICATION_JSON)
                .put(Entity.json(actorUpdate));
        assertThat(putResponse, is(successful()));

        JsonObject updatedActor = putResponse.readEntity(JsonObject.class);
        assertThat(updatedActor.getString(FIRSTNAME), is(equalTo(newFn)));
        assertThat(updatedActor.getString(LASTNAME), is(equalTo(ln)));
        System.out.println(
                "ActorResourceIT.actor_integration_OptimisticLockingCheck() update Actor once Response : "
                        + updatedActor);

        // Update Actor Second time
        final String newFn2 = "Jamie";
        actorUpdate = Json.createObjectBuilder().add(FIRSTNAME, newFn2).add(LASTNAME, ln).add(VERSION, version)
                .build();
        putResponse = provider.target(location).request(APPLICATION_JSON).put(Entity.json(actorUpdate));
        assertThat(putResponse.getStatus(), is(409));
        System.out.println(
                "ActorResourceIT.actor_integration_OptimisticLockingCheck() update Actor second time Response : "
                        + putResponse);
        final MultivaluedMap<String, Object> putResponseHeaders = putResponse.getHeaders();
        putResponseHeaders.forEach((key, value) -> {
            System.out.println(
                    "actor_integration_OptimisticLockingCheck() : key : " + key + ", value : " + value);
        });

        assertThat((String) putResponseHeaders.getFirst("Cause"),
                containsString("There was a conflict. Details are :"));
        assertThat((String) putResponseHeaders.getFirst("additional-info"),
                containsString("Row was updated or deleted by another transaction"));

    } finally {
        // Delete Actor
        Response deleteActor = provider.target(location).request(APPLICATION_JSON).delete();
        assertThat(deleteActor, is(successful()));
        System.out.println("ActorResourceIT.actor_integration_OptimisticLockingCheck() Delete Actor Response : "
                + deleteActor);

    }
}

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)));
            }/*  www . ja v  a 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:io.bibleget.BibleGetFrame.java

/**
 *
 * @throws ClassNotFoundException/*from w w w .  jav  a 2 s.co m*/
 */
private void prepareDynamicInformation() throws ClassNotFoundException {
    biblegetDB = BibleGetDB.getInstance();
    String bibleVersionsStr = biblegetDB.getMetaData("VERSIONS");
    JsonReader jsonReader = Json.createReader(new StringReader(bibleVersionsStr));
    JsonObject bibleVersionsObj = jsonReader.readObject();
    Set<String> versionsabbrev = bibleVersionsObj.keySet();
    bibleVersions = new BasicEventList<>();
    if (!versionsabbrev.isEmpty()) {
        for (String s : versionsabbrev) {
            String versionStr = bibleVersionsObj.getString(s); //store these in an array
            String[] array;
            array = versionStr.split("\\|");
            bibleVersions.add(new BibleVersion(s, array[0], array[1],
                    StringUtils.capitalize(new Locale(array[2]).getDisplayLanguage())));
        }
    }

    List<String> preferredVersions = new ArrayList<>();
    String retVal = (String) biblegetDB.getOption("PREFERREDVERSIONS");
    if (null == retVal) {
        //System.out.println("Attempt to retrieve PREFERREDVERSIONS from the Database resulted in null value");
    } else {
        //System.out.println("Retrieved PREFERREDVERSIONS from the Database. Value is:"+retVal);
        String[] favoriteVersions = StringUtils.split(retVal, ',');
        preferredVersions = Arrays.asList(favoriteVersions);
    }
    if (preferredVersions.isEmpty()) {
        preferredVersions.add("NVBSE");
    }
    List<Integer> preferredVersionsIndices = new ArrayList<>();

    versionsByLang = new SeparatorList<>(bibleVersions, new VersionComparator(), 1, 1000);
    int listLength = versionsByLang.size();
    enabledFlags = new boolean[listLength];
    ListIterator itr = versionsByLang.listIterator();
    while (itr.hasNext()) {
        int idx = itr.nextIndex();
        Object next = itr.next();
        enabledFlags[idx] = !(next.getClass().getSimpleName().equals("GroupSeparator"));
        if (next.getClass().getSimpleName().equals("BibleVersion")) {
            BibleVersion thisBibleVersion = (BibleVersion) next;
            if (preferredVersions.contains(thisBibleVersion.getAbbrev())) {
                preferredVersionsIndices.add(idx);
            }
        }
    }
    indices = ArrayUtils
            .toPrimitive(preferredVersionsIndices.toArray(new Integer[preferredVersionsIndices.size()]));
    //System.out.println("value of indices array: "+Arrays.toString(indices));

}

From source file:com.floreantpos.ui.views.payment.SettleTicketDialog.java

private void addCoupon(Ticket ticket, JsonObject jsonObject) {
    Set<String> keys = jsonObject.keySet();
    for (String key : keys) {
        JsonNumber jsonNumber = jsonObject.getJsonNumber(key);
        double doubleValue = jsonNumber.doubleValue();

        TicketDiscount coupon = new TicketDiscount();
        coupon.setName(key);/*from  w w  w.  j  a v a  2s.com*/
        coupon.setType(Discount.FIXED_PER_ORDER);
        coupon.setValue(doubleValue);

        ticket.addTodiscounts(coupon);
    }
}

From source file:org.btc4j.daemon.BtcJsonRpcHttpClient.java

public BtcCoinbase jsonCoinbase(JsonValue value) throws BtcException {
    JsonObject object = jsonObject(value);
    if (object == null) {
        return null;
    }/*from w w  w  . ja  v  a2  s.  c  o m*/
    BtcCoinbase coin = new BtcCoinbase();
    Map<String, String> auxiliary = new HashMap<String, String>();
    JsonValue aux = object.get(BTCOBJ_COIN_AUX);
    if ((aux != null) && (aux.getValueType() == JsonValue.ValueType.OBJECT) && (aux instanceof JsonObject)) {
        JsonObject auxObject = (JsonObject) aux;
        for (String key : auxObject.keySet()) {
            auxiliary.put(key, auxObject.getString(key, ""));
        }
    }
    coin.setAux(auxiliary);
    coin.setValue(jsonDouble(object, BTCOBJ_COIN_VALUE));
    return coin;
}

From source file:de.tu_dortmund.ub.data.dswarm.Task.java

@Override
public String call() {

    // init logger
    PropertyConfigurator.configure(config.getProperty("service.log4j-conf"));

    logger.info("[" + config.getProperty("service.name") + "] " + "Starting 'Task' ...");

    // init IDs of the prototype project
    String dataModelID = config.getProperty("prototype.dataModelID");
    String projectID = config.getProperty("prototype.projectID");
    String outputDataModelID = config.getProperty("prototype.outputDataModelID");

    // init process values
    String inputResourceID = null;
    String message = null;/*w w w  .j  a va2  s. c o m*/

    try {

        // get the resource id of the current data model >> updateResourceID replaces resourceID
        String updateResourceID = null;
        try {
            updateResourceID = getProjectResourceID(dataModelID);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        logger.info("[" + config.getProperty("service.name") + "] updateResourceID = " + updateResourceID);

        // upload resource and update a InputDataModel
        String inputResourceJson = uploadFileAndUpdateResource(updateResourceID, resource,
                "resource for project '" + resource, config.getProperty("project.name") + "' - case " + cnt);
        JsonReader jsonReader = Json.createReader(IOUtils.toInputStream(inputResourceJson, "UTF-8"));
        inputResourceID = jsonReader.readObject().getString("uuid");
        logger.info("[" + config.getProperty("service.name") + "] inputResourceID = " + inputResourceID);

        if (updateResourceID != null) {

            // update the datamodel (will use it's (update) resource)
            updateDataModel(dataModelID);

            // configuration and processing of the task
            String jsonResponse = executeTask(dataModelID, projectID, outputDataModelID);

            if (jsonResponse != null) {

                if (Boolean.parseBoolean(config.getProperty("results.persistInFolder"))) {

                    if (Boolean.parseBoolean(config.getProperty("results.writeDMPJson"))) {
                        // save DMP results in files
                        FileUtils.writeStringToFile(new File(config.getProperty("results.folder")
                                + File.separatorChar + dataModelID + "." + cnt + ".json"), jsonResponse);
                    }

                    // build rdf graph
                    ValueFactory factory = ValueFactoryImpl.getInstance();

                    Graph graph = new LinkedHashModel();

                    URI graphUri = factory.createURI(config.getProperty("results.rdf.graph"));

                    URI subject = null;
                    URI predicate = null;
                    URI object = null;
                    Literal literal = null;
                    Statement statement = null;

                    JsonReader dmpJsonResult = Json.createReader(IOUtils.toInputStream(jsonResponse, "UTF-8"));
                    JsonArray records = dmpJsonResult.readArray();

                    for (JsonObject record : records.getValuesAs(JsonObject.class)) {

                        subject = factory
                                .createURI(record.getJsonString("__record_id").toString().replaceAll("\"", ""));

                        for (JsonObject triple : record.getJsonArray("__record_data")
                                .getValuesAs(JsonObject.class)) {

                            for (String key : triple.keySet()) {

                                if (key.endsWith("rdf-syntax-ns#type")) {
                                    predicate = RDF.TYPE;
                                    object = factory.createURI(
                                            triple.getJsonString(key).toString().replaceAll("\"", ""));
                                    statement = factory.createStatement(subject, predicate, object, graphUri);
                                    graph.add(statement);
                                } else {

                                    predicate = factory.createURI(key);

                                    switch (triple.get(key).getValueType().toString()) {

                                    case "STRING": {

                                        try {
                                            object = factory.createURI(
                                                    triple.getJsonString(key).toString().replaceAll("\"", ""));
                                            statement = factory.createStatement(subject, predicate, object,
                                                    graphUri);
                                            graph.add(statement);
                                        } catch (Exception e) {
                                            literal = factory.createLiteral(
                                                    triple.getJsonString(key).toString().replaceAll("\"", ""));
                                            statement = factory.createStatement(subject, predicate, literal,
                                                    graphUri);
                                            graph.add(statement);
                                        }
                                        break;
                                    }
                                    case "ARRAY": {

                                        for (JsonString value : triple.getJsonArray(key)
                                                .getValuesAs(JsonString.class)) {

                                            try {
                                                object = factory
                                                        .createURI(value.toString().replaceAll("\"", ""));
                                                statement = factory.createStatement(subject, predicate, object,
                                                        graphUri);
                                                graph.add(statement);
                                            } catch (Exception e) {
                                                literal = factory
                                                        .createLiteral(value.toString().replaceAll("\"", ""));
                                                statement = factory.createStatement(subject, predicate, literal,
                                                        graphUri);
                                                graph.add(statement);
                                            }
                                        }
                                        break;
                                    }
                                    default: {

                                        logger.info("Unhandled ValueType: " + triple.get(key).getValueType());
                                    }
                                    }
                                }
                            }
                        }
                    }

                    if (graph.size() > 0) {
                        // save rdf data as 'results.rdf.format' in 'results.folder'
                        RDFFormat format = null;
                        switch (config.getProperty("results.rdf.format")) {

                        case "xml": {

                            format = RDFFormat.RDFXML;
                            break;
                        }
                        case "nquads": {

                            format = RDFFormat.NQUADS;
                            break;
                        }
                        case "jsonld": {

                            format = RDFFormat.JSONLD;
                            break;
                        }
                        case "ttl": {

                            format = RDFFormat.TURTLE;
                            break;
                        }
                        default: {

                            format = RDFFormat.RDFXML;
                        }
                        }

                        try {
                            FileOutputStream out = new FileOutputStream(
                                    config.getProperty("results.folder") + File.separatorChar + dataModelID
                                            + "." + cnt + ".rdf." + config.getProperty("results.rdf.format"));
                            RDFWriter writer = Rio.createWriter(format, out);

                            writer.startRDF();
                            for (Statement st : graph) {
                                writer.handleStatement(st);
                            }
                            writer.endRDF();

                            out.close();

                        } catch (RDFHandlerException | IOException e) {
                            e.printStackTrace();
                        }

                        message = "'" + resource + "' transformed. results in '"
                                + config.getProperty("results.folder") + File.separatorChar + dataModelID + "."
                                + cnt + ".rdf." + config.getProperty("results.rdf.format") + "'";
                    } else {

                        message = "'" + resource + "' transformed but result is empty.";
                    }
                }
            } else {

                message = "'" + resource + "' not transformed: error in task execution.";
            }
        }
    } catch (Exception e) {

        logger.error("[" + config.getProperty("service.name") + "] Processing resource '" + resource
                + "' failed with a " + e.getClass().getSimpleName());
        e.printStackTrace();
    }

    return message;
}