Example usage for javax.json JsonReader readObject

List of usage examples for javax.json JsonReader readObject

Introduction

In this page you can find the example usage for javax.json JsonReader readObject.

Prototype

JsonObject readObject();

Source Link

Document

Returns a JSON object that is represented in the input source.

Usage

From source file:io.bibleget.BibleGetFrame.java

/**
 *
 * @throws ClassNotFoundException/*  w  w  w  .j  a v a 2 s. c  o 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:DesignGUI.java

private void parseStackExchange(String jsonStr) {
    JsonReader reader = null;
    StringBuilder content = new StringBuilder();

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

    content.append("<html></body>");
    try {//from w  w  w.ja v  a 2 s .  c om
        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:de.tu_dortmund.ub.data.dswarm.Ingest.java

public String call() {

    final String serviceName = config.getProperty(TPUStatics.SERVICE_NAME_IDENTIFIER);
    final String engineDswarmAPI = config.getProperty(TPUStatics.ENGINE_DSWARM_API_IDENTIFIER);

    LOG.info(String.format("[%s] Starting 'Ingest (Task)' no. '%d' ...", serviceName, cnt));

    final String dataModelID = this.dataModelID;
    final String updateResourceID = resourceID;

    try {/*from www.  j a v a 2  s .  c o m*/
        // build a InputDataModel for the resource
        final String name = String.format("resource for project '%s'", resource);
        final String description = String.format("'%s' - case %d", projectName, cnt);
        final String inputResourceJson = uploadFileAndUpdateResource(updateResourceID, resource, name,
                description, serviceName, engineDswarmAPI);
        final JsonReader jsonReader;

        if (inputResourceJson == null) {

            LOG.error("something went wrong at resource update");

            return null;
        }

        jsonReader = Json.createReader(IOUtils.toInputStream(inputResourceJson, APIStatics.UTF_8));
        final String inputResourceID = jsonReader.readObject().getString(DswarmBackendStatics.UUID_IDENTIFIER);
        LOG.info(String.format("[%s] inputResourceID = %s", serviceName, inputResourceID));

        if (inputResourceID != null) {

            // update the datamodel (will use it's (update) resource)
            updateDataModelContent(dataModelID, serviceName, engineDswarmAPI);

            // we don't need to transform after each ingest of a slice of records,
            // so transform and export will be done separately
            LOG.info(String.format("[%s] (Note: Only ingest, but no transformation or export done.)",
                    serviceName));
        }

        // no need to clean up resources or datamodels anymore

        LOG.info(String.format("[%s] Finished 'Ingest (Task)' no. '%d' ...", serviceName, cnt));

        return null;
    } catch (final Exception e) {

        final String message = String.format("[%s] Processing resource '%s' failed with a %s", serviceName,
                resource, e.getClass().getSimpleName());

        LOG.error(message, e);

        throw new RuntimeException(message, e);
    }
}

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 2  s .co 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.apache.tamaya.etcd.EtcdAccessor.java

/**
 * Access all properties. The response of:
 * /*from ww  w  .j a  va2  s  . co  m*/
 * <pre>
 * {
 * "action": "get",
 * "node": {
 * "key": "/",
 * "dir": true,
 * "nodes": [
 * {
 * "key": "/foo_dir",
 * "dir": true,
 * "modifiedIndex": 2,
 * "createdIndex": 2
 * },
 * {
 * "key": "/foo",
 * "value": "two",
 * "modifiedIndex": 1,
 * "createdIndex": 1
 * }
 * ]
 * }
 * }
 * </pre>
 * 
 * is mapped to a regular Tamaya properties map as follows:
 * 
 * <pre>
 *    key1=myvalue
 *     _key1.source=[etcd]http://127.0.0.1:4001
 *     _key1.createdIndex=12
 *     _key1.modifiedIndex=34
 *     _key1.ttl=300
 *     _key1.expiration=...
 *
 *      key2=myvaluexxx
 *     _key2.source=[etcd]http://127.0.0.1:4001
 *     _key2.createdIndex=12
 *
 *      key3=val3
 *     _key3.source=[etcd]http://127.0.0.1:4001
 *     _key3.createdIndex=12
 *     _key3.modifiedIndex=2
 * </pre>
 *
 * @param directory remote directory to query.
 * @param recursive allows to set if querying is performed recursively
 * @return all properties read from the remote server.
 */
public Map<String, String> getProperties(String directory, boolean recursive) {
    final Map<String, String> result = new HashMap<>();
    try {
        final HttpGet get = new HttpGet(serverURL + "/v2/keys/" + directory + "?recursive=" + recursive);
        get.setConfig(RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(socketTimeout)
                .setConnectionRequestTimeout(timeout).setConnectTimeout(connectTimeout).build());
        try (CloseableHttpResponse response = httpclient.execute(get)) {

            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 != null) {
                    addNodes(result, node);
                }
                EntityUtils.consume(entity);
            }
        }
    } catch (final Exception e) {
        LOG.log(Level.INFO, "Error reading properties for '" + directory + "' from etcd: " + serverURL, e);
        result.put("_ERROR", "Error reading properties for '" + directory + "' from etcd: " + serverURL + ": "
                + e.toString());
    }
    return result;
}

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

/**
 * Deletes a given key. The response is as follows:
 * /*  w w  w.  j a va  2 s.co  m*/
 * <pre>
 *     _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=...
 *     _key.prevNode.value=...
 * </pre>
 *
 * @param key the key to be deleted.
 * @return the response mpas as described above.
 */
public Map<String, String> delete(String key) {
    final Map<String, String> result = new HashMap<>();
    try {
        final HttpDelete delete = new HttpDelete(serverURL + "/v2/keys/" + key);
        delete.setConfig(RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(socketTimeout)
                .setConnectionRequestTimeout(timeout).setConnectTimeout(connectTimeout).build());
        try (CloseableHttpResponse response = httpclient.execute(delete)) {
            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("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")));
                }
                parsePrevNode(key, result, o);
                EntityUtils.consume(entity);
            }
        }
    } catch (final Exception e) {
        LOG.log(Level.INFO, "Error deleting key '" + key + "' from etcd: " + serverURL, e);
        result.put("_ERROR", "Error deleting '" + key + "' from etcd: " + serverURL + ": " + e.toString());
    }
    return result;
}

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

/**
 * Ask etcd for a single key, value pair. Hereby the response returned from
 * etcd://  w w  w .j a v  a2  s.  co  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:
 * // ww  w  .ja  v  a2 s  .  co  m
 * <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:ch.bfh.abcvote.util.controllers.CommunicationController.java

/**
 * Gets the parameters of the bulletin board from the bulletin board and converts the recieved Json in a Parameters object and returns it
 * @return returns bulletin board's parameters in form of a parameter object
 *//*from  w  ww. j  a  v  a  2s  .c o m*/
public Parameters getParameters() {
    try {
        //Get parameters json with a get request 
        URL url = new URL(bulletinBoardUrl + "/parameters");

        InputStream urlInputStream = url.openStream();
        JsonReader jsonReader = Json.createReader(urlInputStream);
        JsonObject obj = jsonReader.readObject();
        //Json contains String representations of the parameter elements
        String oString = obj.getString("o");
        String pString = obj.getString("p");
        String h0String = obj.getString("h0");
        String h1String = obj.getString("h1");
        String h2String = obj.getString("h2");
        String g0String = obj.getString("g0");
        String g1String = obj.getString("g1");

        //Converting the parameter Element Strings into Parameters Object containing the restored Parameter Elements
        Parameters parameters = new Parameters(oString, pString, h0String, h1String, h2String, g0String,
                g1String);
        return parameters;
    } catch (Exception x) {
        System.err.println(x);
        return null;
    }

}

From source file:ch.bfh.abcvote.util.controllers.CommunicationController.java

/**
 * Gets the information for the given ElectionID from the bulletin board and returns it as a election object
 * @param electionId// w  ww. j  a  v  a 2s  . co  m
 * the identifier (id) for the desired election
 * @return returns tje election object for a given id
 */
public Election getElectionById(int electionId) {
    Election election = null;
    try {

        URL url = new URL(bulletinBoardUrl + "/elections/" + electionId);

        InputStream urlInputStream = url.openStream();
        JsonReader jsonReader = Json.createReader(urlInputStream);
        JsonObject obj = jsonReader.readObject();
        DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        Parameters parameters = this.getParameters();

        //gets the json string and transforms it into a election object

        //translates the header information of the election
        String title = obj.getString("electionTitle");
        LocalDateTime beginDate = LocalDateTime.parse(obj.getString("beginDate"), format);
        LocalDateTime endDate = LocalDateTime.parse(obj.getString("endDate"), format);
        String appVersion = obj.getString("appVersion");
        String coefficientsString = obj.getString("coefficients");
        String h_HatString = obj.getString("electionGenerator");
        List<Voter> voterlist = new ArrayList<Voter>();

        //get th list of voters
        for (JsonObject result : obj.getJsonArray("voters").getValuesAs(JsonObject.class)) {

            String voterEmail = result.getString("email");
            String voterPublicCredential = result.getString("publicCredential");
            String voterAppVersion = result.getString("appVersion");

            Voter voter = new Voter(voterEmail, voterPublicCredential, voterAppVersion);
            voterlist.add(voter);
        }
        //get the votingTopic
        JsonObject electionTopicObj = obj.getJsonObject("votingTopic");

        String topic = electionTopicObj.getString("topic");
        int pick = electionTopicObj.getInt("pick");

        ElectionTopic electionTopic = new ElectionTopic(topic, pick);
        JsonArray optionsArray = electionTopicObj.getJsonArray("options");
        for (int i = 0; i < optionsArray.size(); i++) {
            electionTopic.addOption(optionsArray.getString(i));
        }

        election = new Election(electionId, title, voterlist, parameters, beginDate, endDate, electionTopic,
                appVersion, h_HatString, coefficientsString);

    } catch (IOException x) {
        System.err.println(x);
    }
    return election;
}