Example usage for javax.json JsonObject getInt

List of usage examples for javax.json JsonObject getInt

Introduction

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

Prototype

int getInt(String name);

Source Link

Document

A convenience method for getJsonNumber(name).intValue()

Usage

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

private void getHFCAIdentity(JsonObject result) {
    type = result.getString("type");
    if (result.containsKey("secret")) {
        this.secret = result.getString("secret");
    }//  w  w  w.  j  a  va 2s  .com
    maxEnrollments = result.getInt("max_enrollments");
    affiliation = result.getString("affiliation");
    JsonArray attributes = result.getJsonArray("attrs");

    Collection<Attribute> attrs = new ArrayList<Attribute>();
    if (attributes != null && !attributes.isEmpty()) {
        for (int i = 0; i < attributes.size(); i++) {
            JsonObject attribute = attributes.getJsonObject(i);
            Attribute attr = new Attribute(attribute.getString("name"), attribute.getString("value"),
                    attribute.getBoolean("ecert", false));
            attrs.add(attr);
        }
    }
    this.attrs = attrs;
}

From source file:DesignGUI.java

private void parseStackExchange(String jsonStr) {
    JsonReader reader = null;/*from  w ww. j  a v  a 2s .  c  om*/
    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:info.dolezel.jarss.rest.v1.FeedsService.java

private JsonObjectBuilder getFeedCategory(EntityManager em, FeedCategory fc) {
    JsonObjectBuilder obj = Json.createObjectBuilder();
    int fcUnread = 0;
    Collection<Feed> feeds;
    JsonArrayBuilder nodes = Json.createArrayBuilder();

    obj.add("id", fc.getId());
    obj.add("title", fc.getName());

    feeds = fc.getFeeds();/*from ww w .jav a  2 s. c  o m*/
    for (Feed feed : feeds) {
        JsonObject objFeed = getFeed(em, feed).build();

        fcUnread = objFeed.getInt("unread");

        nodes.add(objFeed);
    }

    obj.add("unread", fcUnread);
    obj.add("nodes", nodes);
    obj.add("isCategory", true);

    return obj;
}

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 w  ww  . ja  v a 2s . c om

    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 void importRoomList() {
    this.roomIdToRoomMap = new HashMap<>();
    List<Room> roomList = new ArrayList<>();

    String roomsUrl = conferenceBaseUrl + "/rooms/";
    LOGGER.debug("Sending a request to: " + roomsUrl);
    JsonObject rootObject = readJson(roomsUrl, JsonReader::readObject);

    JsonArray roomArray = rootObject.getJsonArray("rooms");
    for (int i = 0; i < roomArray.size(); i++) {
        JsonObject roomObject = roomArray.getJsonObject(i);
        String id = roomObject.getString("id");
        int capacity = roomObject.getInt("capacity");

        if (!Arrays.asList(IGNORED_ROOM_IDS).contains(id)) {
            Room room = new Room((long) i);
            room.setName(id);//ww w.j av  a 2 s  .c  o m
            room.setCapacity(capacity);
            room.setTalkTypeSet(getTalkTypeSetForCapacity(capacity));
            for (TalkType talkType : room.getTalkTypeSet()) {
                talkType.getCompatibleRoomSet().add(room);
            }
            room.setTagSet(new HashSet<>());
            room.setUnavailableTimeslotSet(new HashSet<>());
            roomList.add(room);
            roomIdToRoomMap.put(id, room);
        }
    }

    roomList.sort(Comparator.comparing(Room::getName));
    solution.setRoomList(roomList);
}

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

/**
 * Deletes a given key. The response is as follows:
 * //from w  w w . ja v  a 2  s.c o 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:eu.forgetit.middleware.component.Extractor.java

private synchronized String getVideoPath(JsonObject jsonBody) {

    long pofId = jsonBody.getInt("pofId");
    logger.debug("Retrieved PoF ID: " + pofId);

    String jsonContentDir = jsonBody.getString("sipContentDir");
    if (jsonContentDir != null)
        sipContentDirPath = jsonContentDir;
    logger.debug("Retrieved SIP Content Directory: " + sipContentDirPath);

    String rootPublicDir = ConfigurationManager.getConfiguration().getString("pofmiddleware.pub.dir");
    File publicDir = new File(rootPublicDir, String.valueOf(pofId));
    logger.debug("Publication Dir: " + publicDir.getAbsolutePath());
    if (!publicDir.exists())
        publicDir.mkdirs();//  w  w w  . j a va  2s . c  o  m

    String rootPublicURL = ConfigurationManager.getConfiguration().getString("pofmiddleware.pub.url");
    String publicURL = rootPublicURL + File.separator + pofId;
    logger.debug("Publication URL: " + publicURL);

    List<String> videoList = getFilteredVideoList(sipContentDirPath);

    numOfVideos = videoList.size();

    logger.debug("Video List for Analysis: " + videoList);

    StringBuilder videoPaths = new StringBuilder();

    int i = 0;

    for (String videoFilePath : videoList) {
        File videoFile = new File(videoFilePath);
        String uniqueImageFileName = "vd-" + UUID.randomUUID().toString() + "."
                + FilenameUtils.getExtension(videoFilePath);
        File outputFile = new File(publicDir, uniqueImageFileName);
        try {

            FileUtils.copyFile(videoFile, outputFile);

            String videoPath = publicURL + File.separator + outputFile.getName();

            logger.debug("videoPath: " + videoList);

            if (i == 0)
                videoPaths.append(videoPath);
            else
                // Store only the first video .. one video per call
                videoPaths.append("+" + videoPath);

            i++;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    logger.debug("videoPaths: " + videoPaths);

    return videoPaths.toString();
}

From source file:org.rhwlab.dispim.nucleus.NucleusData.java

public NucleusData(JsonObject jsonObj) {
    this.time = jsonObj.getInt("Time");
    this.name = jsonObj.getString("Name");
    String precString = jsonObj.getJsonString("Precision").getString();
    this.A = precisionFromString(precString);
    this.xC = jsonObj.getJsonNumber("X").longValue();
    this.yC = jsonObj.getJsonNumber("Y").longValue();
    this.zC = jsonObj.getJsonNumber("Z").longValue();
    this.exp = jsonObj.getJsonNumber("Expression").longValue();

    this.eigenA = new EigenDecomposition(A);
    this.adjustedA = this.A.copy();
    this.adjustedEigenA = new EigenDecomposition(adjustedA);

    double[] adj = new double[3];
    adj[0] = adj[1] = adj[2] = 1.0;//ww  w .  j  av  a 2 s.  c om
    this.setAdjustment(adj);
}

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

/**
 * Creates/updates an entry in etcd. The response as follows:
 * /* ww  w.j a  va  2  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 a  va2s  .c o m*/
        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;
}