Example usage for javax.json JsonObject containsKey

List of usage examples for javax.json JsonObject containsKey

Introduction

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

Prototype

boolean containsKey(Object key);

Source Link

Document

Returns true if this map contains a mapping for the specified key.

Usage

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

/**
 * Ask etcd for a single key, value pair. Hereby the response returned from
 * etcd://from  ww w  . ja  v a2s  . c  o m
 * 
 * <pre>
 * {
 * "action": "get",
 * "node": {
 * "createdIndex": 2,
 * "key": "/message",
 * "modifiedIndex": 2,
 * "value": "Hello world"
 * }
 * }
 * </pre>
 * 
 * is mapped to:
 * 
 * <pre>
 *     key=value
 *     _key.source=[etcd]http://127.0.0.1:4001
 *     _key.createdIndex=12
 *     _key.modifiedIndex=34
 *     _key.ttl=300
 *     _key.expiration=...
 * </pre>
 *
 * @param key the requested key
 * @return the mapped result, including meta-entries.
 */
public Map<String, String> get(String key) {
    final Map<String, String> result = new HashMap<>();
    try {
        final HttpGet httpGet = new HttpGet(serverURL + "/v2/keys/" + key);
        httpGet.setConfig(RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(socketTimeout)
                .setConnectionRequestTimeout(timeout).setConnectTimeout(connectTimeout).build());
        try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                final HttpEntity entity = response.getEntity();
                final JsonReader reader = readerFactory
                        .createReader(new StringReader(EntityUtils.toString(entity)));
                final JsonObject o = reader.readObject();
                final JsonObject node = o.getJsonObject("node");
                if (node.containsKey("value")) {
                    result.put(key, node.getString("value"));
                    result.put("_" + key + ".source", "[etcd]" + serverURL);
                }
                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")));
                }
                EntityUtils.consume(entity);
            } else {
                result.put("_" + key + ".NOT_FOUND.target", "[etcd]" + serverURL);
            }
        }
    } catch (final Exception e) {
        LOG.log(Level.INFO, "Error reading key '" + key + "' from etcd: " + serverURL, e);
        result.put("_ERROR", "Error reading key '" + key + "' from etcd: " + serverURL + ": " + e.toString());
    }
    return result;
}

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

/**
 * Creates/updates an entry in etcd. The response as follows:
 * /*from  w  w  w .  j  av  a2 s.  c  om*/
 * <pre>
 *     {
 * "action": "set",
 * "node": {
 * "createdIndex": 3,
 * "key": "/message",
 * "modifiedIndex": 3,
 * "value": "Hello etcd"
 * },
 * "prevNode": {
 * "createdIndex": 2,
 * "key": "/message",
 * "value": "Hello world",
 * "modifiedIndex": 2
 * }
 * }
 * </pre>
 * 
 * is mapped to:
 * 
 * <pre>
 *     key=value
 *     _key.source=[etcd]http://127.0.0.1:4001
 *     _key.createdIndex=12
 *     _key.modifiedIndex=34
 *     _key.ttl=300
 *     _key.expiry=...
 *      // optional
 *     _key.prevNode.createdIndex=12
 *     _key.prevNode.modifiedIndex=34
 *     _key.prevNode.ttl=300
 *     _key.prevNode.expiration=...
 * </pre>
 *
 * @param key        the property key, not null
 * @param value      the value to be set
 * @param ttlSeconds the ttl in seconds (optional)
 * @return the result map as described above.
 */
public Map<String, String> set(String key, String value, Integer ttlSeconds) {
    final Map<String, String> result = new HashMap<>();
    try {
        final HttpPut put = new HttpPut(serverURL + "/v2/keys/" + key);
        put.setConfig(RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(socketTimeout)
                .setConnectionRequestTimeout(timeout).setConnectTimeout(connectTimeout).build());
        final List<NameValuePair> nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair("value", value));
        if (ttlSeconds != null) {
            nvps.add(new BasicNameValuePair("ttl", ttlSeconds.toString()));
        }
        put.setEntity(new UrlEncodedFormEntity(nvps));
        try (CloseableHttpResponse response = httpclient.execute(put)) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED
                    || response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                final HttpEntity entity = response.getEntity();
                final JsonReader reader = readerFactory
                        .createReader(new StringReader(EntityUtils.toString(entity)));
                final JsonObject o = reader.readObject();
                final JsonObject node = o.getJsonObject("node");
                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, node.getString("value"));
                result.put("_" + key + ".source", "[etcd]" + serverURL);
                parsePrevNode(key, result, node);
                EntityUtils.consume(entity);
            }
        }
    } catch (final Exception e) {
        LOG.log(Level.INFO, "Error writing to etcd: " + serverURL, e);
        result.put("_ERROR", "Error writing '" + key + "' to etcd: " + serverURL + ": " + e.toString());
    }
    return result;
}

From source file:edu.harvard.hms.dbmi.bd2k.irct.ri.i2b2transmart.I2B2TranSMARTResourceImplementation.java

@Override
public List<Entity> getPathRelationship(Entity path, OntologyRelationship relationship, SecureSession session)
        throws ResourceInterfaceException {
    List<Entity> returns = super.getPathRelationship(path, relationship, session);

    // Get the counts from the tranSMART server
    try {/*from w  w w. j av  a2s  .  c om*/
        HttpClient client = createClient(session);
        String basePath = path.getPui();
        String[] pathComponents = basePath.split("/");

        if (pathComponents.length > 3) {
            String myPath = "\\";
            for (String pathComponent : Arrays.copyOfRange(pathComponents, 3, pathComponents.length)) {
                myPath += "\\" + pathComponent;
            }
            basePath = pathComponents[0] + "/" + pathComponents[1] + "/" + pathComponents[2];

            HttpPost post = new HttpPost(this.transmartURL + "/chart/childConceptPatientCounts");
            List<NameValuePair> formParameters = new ArrayList<NameValuePair>();
            formParameters.add(new BasicNameValuePair("charttype", "childconceptpatientcounts"));
            formParameters.add(new BasicNameValuePair("concept_key", myPath + "\\"));
            formParameters.add(new BasicNameValuePair("concept_level", ""));

            post.setEntity(new UrlEncodedFormEntity(formParameters));

            HttpResponse response = client.execute(post);

            JsonReader jsonReader = Json.createReader(response.getEntity().getContent());

            JsonObject counts = jsonReader.readObject().getJsonObject("counts");

            for (Entity singleReturn : returns) {
                String singleReturnMyPath = convertPUItoI2B2Path(singleReturn.getPui());

                if (counts.containsKey(singleReturnMyPath)) {
                    singleReturn.getCounts().put("count", counts.getInt(singleReturnMyPath));
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return returns;
}

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

private String getValue(JsonObject obj, String field) {
    if (field.contains(".")) {
        String thisField = field.split("\\.")[0];
        String remaining = field.replaceFirst(thisField + ".", "");
        return getValue(obj.getJsonObject(thisField), remaining);
    }/*from  w w w  . ja  v  a2 s  .c om*/
    if (obj.containsKey(field)) {
        ValueType vt = obj.get(field).getValueType();
        if (vt == ValueType.NUMBER) {
            return obj.getJsonNumber(field).toString();
        } else if (vt == ValueType.TRUE) {
            return "TRUE";
        } else if (vt == ValueType.FALSE) {
            return "FALSE";
        }
        return obj.getString(field);
    }
    return "";
}

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

private List<Speaker> extractSpeakerList(String confType, JsonObject talkObject, String code, String title) {
    List<Speaker> speakerList = new ArrayList<>();

    String mainSpeakerName = talkObject.getString("mainSpeaker");
    if (Arrays.asList(IGNORED_SPEAKER_NAMES).contains(mainSpeakerName)) {
        return speakerList;
    }//from ww  w.  ja v a2s .  c o m

    speakerList.add(getSpeakerOrCreateOneIfNull(confType, code, title, mainSpeakerName));
    if (talkObject.containsKey("secondarySpeaker")) {
        String secondarySpeakerName = talkObject.getString("secondarySpeaker");
        speakerList.add(getSpeakerOrCreateOneIfNull(confType, code, title, secondarySpeakerName));
    }

    if (talkObject.containsKey("otherSpeakers")) {
        JsonArray otherSpeakersArray = talkObject.getJsonArray("otherSpeakers");
        for (JsonValue otherSpeakerName : otherSpeakersArray) {
            speakerList.add(getSpeakerOrCreateOneIfNull(confType, code, title,
                    otherSpeakerName.toString().replaceAll("\"", "")));
        }
    }

    return speakerList;
}

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

@Override
public Result runProcess(SecureSession session, IRCTProcess process, Result result)
        throws ResourceInterfaceException {
    HttpClient client = createClient(session);
    try {//from   ww  w .  ja  v a 2s.  c  o  m
        ResultSet resultSetField = (ResultSet) process.getObjectValues().get("RESULTSET");
        String chromosomeColumn = process.getStringValues().get("CHROMOSOME");
        String positionColumn = process.getStringValues().get("POSITION");
        String referenceColumn = process.getStringValues().get("REFERENCE");
        String variantColumn = process.getStringValues().get("VARIANT");

        ResultSet rs = createResultSet(result, resultSetField);

        // Move to First
        resultSetField.first();
        // Loop through all rows and get the data needed for the bulk
        // request
        resultSetField.beforeFirst();
        JsonArrayBuilder jsonArray = Json.createArrayBuilder();
        while (resultSetField.next()) {

            String queryString = resultSetField.getString(chromosomeColumn);
            queryString += "-" + resultSetField.getString(positionColumn);
            queryString += "-" + resultSetField.getString(referenceColumn);
            queryString += "-" + resultSetField.getString(variantColumn);

            // Run the Bulk request(s)
            jsonArray.add(queryString);

        }

        HttpPost post = new HttpPost(this.resourceURL + "/rest/bulk/variant");

        // Set Header
        try {
            post.setEntity(new StringEntity(jsonArray.build().toString()));
            HttpResponse response = client.execute(post);
            JsonReader reader = Json.createReader(response.getEntity().getContent());
            JsonObject responseObject = reader.readObject();

            //Merge the results back into the result set
            resultSetField.beforeFirst();
            rs.first();
            while (resultSetField.next()) {
                rs.appendRow();
                //Copy the original data over
                for (Column column : resultSetField.getColumns()) {
                    rs.updateString(column.getName(), resultSetField.getString(column.getName()));
                }
                //Add the new data if it exists
                String queryString = resultSetField.getString(chromosomeColumn);
                queryString += "-" + resultSetField.getString(positionColumn);
                queryString += "-" + resultSetField.getString(referenceColumn);
                queryString += "-" + resultSetField.getString(variantColumn);

                if (responseObject.containsKey(queryString)) {
                    JsonObject varObject = responseObject.getJsonObject(queryString).getJsonObject("variant");
                    for (String newColumnString : this.exacColumns) {
                        String value = getValue(varObject, newColumnString);
                        if (value != null) {
                            rs.updateString(newColumnString, value.toString());
                        }
                    }
                }
            }

            result.setData(rs);
            result.setResultStatus(ResultStatus.COMPLETE);
        } catch (IOException | PersistableException e) {
            e.printStackTrace();
            result.setResultStatus(ResultStatus.ERROR);
            result.setMessage(e.getMessage());
        }

    } catch (ResultSetException e) {
        e.printStackTrace();
        result.setResultStatus(ResultStatus.ERROR);
        result.setMessage(e.getMessage());
    }

    return result;
}

From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java

/**
 * Return information on the Fabric Certificate Authority.
 * No credentials are needed for this API.
 *
 * @return {@link HFCAInfo}//from   ww w.  j  a  va 2  s . c o  m
 * @throws InfoException
 * @throws InvalidArgumentException
 */

public HFCAInfo info() throws InfoException, InvalidArgumentException {

    logger.debug(format("info url:%s", url));
    if (cryptoSuite == null) {
        throw new InvalidArgumentException("Crypto primitives not set.");
    }

    setUpSSL();

    try {

        JsonObjectBuilder factory = Json.createObjectBuilder();

        if (caName != null) {
            factory.add(HFCAClient.FABRIC_CA_REQPROP, caName);
        }
        JsonObject body = factory.build();

        String responseBody = httpPost(url + HFCA_INFO, body.toString(), (UsernamePasswordCredentials) null);

        logger.debug("response:" + responseBody);

        JsonReader reader = Json.createReader(new StringReader(responseBody));
        JsonObject jsonst = (JsonObject) reader.read();

        boolean success = jsonst.getBoolean("success");
        logger.debug(format("[HFCAClient] enroll success:[%s]", success));

        if (!success) {
            throw new EnrollmentException(format("FabricCA failed info %s", url));
        }

        JsonObject result = jsonst.getJsonObject("result");
        if (result == null) {
            throw new InfoException(
                    format("FabricCA info error  - response did not contain a result url %s", url));
        }

        String caName = result.getString("CAName");
        String caChain = result.getString("CAChain");
        String version = null;
        if (result.containsKey("Version")) {
            version = result.getString("Version");
        }
        String issuerPublicKey = null;
        if (result.containsKey("IssuerPublicKey")) {
            issuerPublicKey = result.getString("IssuerPublicKey");
        }
        String issuerRevocationPublicKey = null;
        if (result.containsKey("IssuerRevocationPublicKey")) {
            issuerRevocationPublicKey = result.getString("IssuerRevocationPublicKey");
        }

        logger.info(format("CA Name: %s, Version: %s, issuerPublicKey: %s, issuerRevocationPublicKey: %s",
                caName, caChain, issuerPublicKey, issuerRevocationPublicKey));
        return new HFCAInfo(caName, caChain, version, issuerPublicKey, issuerRevocationPublicKey);

    } catch (Exception e) {
        InfoException ee = new InfoException(format("Url:%s, Failed to get info", url), e);
        logger.error(e.getMessage(), e);
        throw ee;
    }

}

From source file:fr.ortolang.diffusion.core.CoreServiceBean.java

@TransactionAttribute(TransactionAttributeType.SUPPORTS)
private void buildHandleList(String wsalias, String tag, String key, Set<OrtolangObjectPid> pids,
        PathBuilder path, String apiUrlBase, String marketUrlBase)
        throws CoreServiceException, KeyNotFoundException, OrtolangException, InvalidPathException {
    try {/*  www  . j  a v  a2 s  .  c o  m*/
        OrtolangObject object = findObject(key);
        LOGGER.log(Level.FINE, "Generating pid for key: " + key);
        String target = ((path.isRoot()) ? marketUrlBase : apiUrlBase) + "/" + wsalias + "/" + tag
                + ((path.isRoot()) ? "" : path.build());
        String dynHandle = OrtolangConfig.getInstance().getProperty(OrtolangConfig.Property.HANDLE_PREFIX) + "/"
                + wsalias + ((path.isRoot()) ? "" : path.build());
        String staticHandle = OrtolangConfig.getInstance().getProperty(OrtolangConfig.Property.HANDLE_PREFIX)
                + "/" + wsalias + "/" + tag + ((path.isRoot()) ? "" : path.build());
        OrtolangObjectPid dpid = new OrtolangObjectPid(OrtolangObjectPid.Type.HANDLE, dynHandle, key, target,
                false);
        boolean adddpid = true;
        for (OrtolangObjectPid pid : pids) {
            if (pid.getName().equals(dpid.getName()) && pid.isUserbased()) {
                adddpid = false;
                break;
            }
        }
        if (adddpid) {
            pids.add(dpid);
        }
        OrtolangObjectPid spid = new OrtolangObjectPid(OrtolangObjectPid.Type.HANDLE, staticHandle, key, target,
                false);
        boolean addspid = true;
        for (OrtolangObjectPid pid : pids) {
            if (pid.getName().equals(spid.getName()) && pid.isUserbased()) {
                addspid = false;
                break;
            }
        }
        if (addspid) {
            pids.add(spid);
        }
        if (object instanceof MetadataSource) {
            MetadataElement mde = ((MetadataSource) object).findMetadataByName(MetadataFormat.PID);
            if (mde != null) {
                LOGGER.log(Level.FINE, "PID metadata found, load json and generate corresponding pids");
                MetadataObject md = readMetadataObject(mde.getKey());
                try {
                    JsonReader reader = Json.createReader(binarystore.get(md.getStream()));
                    JsonObject json = reader.readObject();
                    if (json.containsKey("pids")) {
                        JsonArray jpids = json.getJsonArray("pids");
                        for (int i = 0; i < jpids.size(); i++) {
                            JsonObject jpid = jpids.getJsonObject(i);
                            LOGGER.log(Level.FINE, "Generating metadata based pid for key: " + key);
                            String ctarget = ((path.isRoot()) ? marketUrlBase : apiUrlBase) + "/" + wsalias
                                    + "/" + tag + ((path.isRoot()) ? "" : path.build());
                            OrtolangObjectPid upid = new OrtolangObjectPid(OrtolangObjectPid.Type.HANDLE,
                                    jpid.getString("value"), key, ctarget, true);
                            Iterator<OrtolangObjectPid> iter = pids.iterator();
                            while (iter.hasNext()) {
                                OrtolangObjectPid pid = iter.next();
                                if (pid.getName().equals(upid.getName())) {
                                    iter.remove();
                                }
                            }
                            pids.add(upid);
                        }
                    }
                    reader.close();
                } catch (BinaryStoreServiceException | DataNotFoundException e) {
                    LOGGER.log(Level.SEVERE, "unable to read pid metadata", e);
                }
            }
        }
        if (object instanceof Collection) {
            for (CollectionElement element : ((Collection) object).getElements()) {
                buildHandleList(wsalias, tag, element.getKey(), pids, path.clone().path(element.getName()),
                        apiUrlBase, marketUrlBase);
            }
        }
    } catch (AccessDeniedException e) {
        LOGGER.log(Level.INFO, "Unable to generate a PID for an object that has been set private.");
    }
}