Example usage for javax.json JsonObject getJsonArray

List of usage examples for javax.json JsonObject getJsonArray

Introduction

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

Prototype

JsonArray getJsonArray(String name);

Source Link

Document

Returns the array value to which the specified name is mapped.

Usage

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);//from   ww  w. java 2s. com
            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.optaplanner.examples.conferencescheduling.persistence.ConferenceSchedulingCfpDevoxxImporter.java

private void importTalkTypeList() {
    this.talkTypeNameToTalkTypeMap = new HashMap<>();
    List<TalkType> talkTypeList = new ArrayList<>();

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

    JsonArray talkTypeArray = rootObject.getJsonArray("proposalTypes");
    for (int i = 0; i < talkTypeArray.size(); i++) {
        JsonObject talkTypeObject = talkTypeArray.getJsonObject(i);
        String talkTypeName = talkTypeObject.getString("id");
        if (talkTypeNameToTalkTypeMap.keySet().contains(talkTypeName)) {
            LOGGER.warn("Duplicate talk type in " + proposalTypeUrl + " at index " + i + ".");
            continue;
        }/*from  ww  w .  j  a  va  2s  .  c o  m*/

        TalkType talkType = new TalkType((long) i, talkTypeName);
        talkType.setCompatibleRoomSet(new HashSet<>());
        talkType.setCompatibleTimeslotSet(new HashSet<>());

        talkTypeList.add(talkType);
        talkTypeNameToTalkTypeMap.put(talkTypeName, talkType);
    }

    solution.setTalkTypeList(talkTypeList);
}

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

private JsonArray getMappingsFromProject(final String projectID, final String serviceName,
        final String engineDswarmAPI) throws Exception {

    try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {

        // Hole Mappings aus dem Projekt mit 'projectID'
        final String uri = engineDswarmAPI + DswarmBackendStatics.PROJECTS_ENDPOINT + APIStatics.SLASH
                + projectID;/*from  w  ww . jav  a2 s  .com*/
        final HttpGet httpGet = new HttpGet(uri);

        LOG.info(String.format("[%s][%d] request : %s", serviceName, cnt, httpGet.getRequestLine()));

        try (final CloseableHttpResponse httpResponse = httpclient.execute(httpGet)) {

            final int statusCode = httpResponse.getStatusLine().getStatusCode();
            final String response = TPUUtil.getResponseMessage(httpResponse);

            switch (statusCode) {

            case 200: {

                LOG.debug(String.format("[%s][%d] responseJson : %s", serviceName, cnt, response));

                final JsonObject jsonObject = TPUUtil.getJsonObject(response);

                final JsonArray mappings = jsonObject.getJsonArray(DswarmBackendStatics.MAPPINGS_IDENTIFIER);

                LOG.debug(String.format("[%s][%d] mappings : %s", serviceName, cnt, mappings.toString()));

                return mappings;
            }
            default: {

                LOG.error(String.format("[%s][%d] %d : %s", serviceName, cnt, statusCode,
                        httpResponse.getStatusLine().getReasonPhrase()));

                throw new Exception("something went wrong at mappings retrieval: " + response);
            }
            }
        }
    }
}

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. ja va 2 s. c  o m
    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:org.hyperledger.fabric_ca.sdk.HFCAAffiliation.java

private void generateResponse(JsonObject result) {
    if (result.containsKey("name")) {
        this.name = result.getString("name");
    }//from w  ww .  ja  va 2 s .  c  o  m
    if (result.containsKey("affiliations")) {
        JsonArray affiliations = result.getJsonArray("affiliations");
        if (affiliations != null && !affiliations.isEmpty()) {
            for (int i = 0; i < affiliations.size(); i++) {
                JsonObject aff = affiliations.getJsonObject(i);
                this.childHFCAAffiliations.add(new HFCAAffiliation(aff));
            }
        }
    }
    if (result.containsKey("identities")) {
        JsonArray ids = result.getJsonArray("identities");
        if (ids != null && !ids.isEmpty()) {
            for (int i = 0; i < ids.size(); i++) {
                JsonObject id = ids.getJsonObject(i);
                HFCAIdentity hfcaID = new HFCAIdentity(id);
                this.identities.add(hfcaID);
            }
        }
    }
}

From source file:com.buffalokiwi.aerodrome.jet.orders.OrderItemRec.java

/**
 * Create an OrderItemRec from jet json 
 * @param json jet json/*from   w  w  w.  j  a va 2s  .  c  o m*/
 * @return instance
 */
public static OrderItemRec fromJson(final JsonObject json) throws JetException {

    final Builder b = (new Builder()).setOrderItemId(json.getString("order_item_id", ""))
            .setAltOrderItemId(json.getString("alt_order_item_id", ""))
            .setMerchantSku(json.getString("merchant_sku", "")).setTitle(json.getString("product_title", ""))
            .setRequestOrderQty(json.getInt("request_order_quantity", 0))

            //..This appears to have been removed.  I don't know if jet still returns this value or not.
            .setRequestOrderCancelQty(json.getInt("request_order_cancel_qty", 0))

            .setAdjReason(json.getString("adjustment_reason", ""))
            .setTaxCode(json.getString("item_tax_code", "")).setUrl(json.getString("url", ""))
            .setPriceAdj(Utils.jsonNumberToMoney(json, "price_adjustment"))
            .setFees(Utils.jsonNumberToMoney(json, "item_fees")).setTaxInfo(json.getString("tax_info", "")) //..This might not work...
            .setRegFees(Utils.jsonNumberToMoney(json, "regulatory_fees"))
            .setAdjustments(jsonToFeeAdj(json.getJsonArray("fee_adjustments")))
            .setItemAckStatus(ItemAckStatus.fromText(json.getString("order_item_acknowledgement_status", "")));

    final JsonObject price = json.getJsonObject("item_price");
    if (price != null)
        b.setItemPrice(ItemPriceRec.fromJson(price));

    return b.build();
}

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

/**
 * read retrieves a specific identity//from  w w w .j  a va 2 s.c om
 *
 * @param registrar The identity of the registrar (i.e. who is performing the registration).
 * @return statusCode The HTTP status code in the response
 * @throws IdentityException    if retrieving an identity fails.
 * @throws InvalidArgumentException Invalid (null) argument specified
 */

public int read(User registrar) throws IdentityException, InvalidArgumentException {
    if (registrar == null) {
        throw new InvalidArgumentException("Registrar should be a valid member");
    }

    String readIdURL = "";
    try {
        readIdURL = HFCA_IDENTITY + "/" + enrollmentID;
        logger.debug(format("identity  url: %s, registrar: %s", readIdURL, registrar.getName()));

        JsonObject result = client.httpGet(readIdURL, registrar);

        statusCode = result.getInt("statusCode");
        if (statusCode < 400) {
            type = result.getString("type");
            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;

            logger.debug(format("identity  url: %s, registrar: %s done.", readIdURL, registrar));
        }
        this.deleted = false;
        return statusCode;
    } catch (HTTPException e) {
        String msg = format("[Code: %d] - Error while getting user '%s' from url '%s': %s", e.getStatusCode(),
                getEnrollmentId(), readIdURL, e.getMessage());
        IdentityException identityException = new IdentityException(msg, e);
        logger.error(msg);
        throw identityException;
    } catch (Exception e) {
        String msg = format("Error while getting user '%s' from url '%s': %s", enrollmentID, readIdURL,
                e.getMessage());
        IdentityException identityException = new IdentityException(msg, e);
        logger.error(msg);
        throw identityException;
    }

}

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

/**
 * Gets a list of all the posted ballots of the given election form the bulletin board and returns it
 * @param election/* www .  j  a  va  2 s .c  o m*/
 * Election for which the list of ballots should be retrieved 
 * @return 
 * the list of all posted ballots to the given election
 */
public List<Ballot> getBallotsByElection(Election election) {
    List<Ballot> ballots = new ArrayList<Ballot>();
    try {

        URL url = new URL(bulletinBoardUrl + "/elections/" + election.getId() + "/ballots");

        InputStream urlInputStream = url.openStream();
        JsonReader jsonReader = Json.createReader(urlInputStream);
        JsonArray obj = jsonReader.readArray();
        DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //transforms the recieved json string into a list of ballot objects
        for (JsonObject result : obj.getValuesAs(JsonObject.class)) {

            int id = Integer.parseInt(result.getString("id"));
            LocalDateTime timeStamp = LocalDateTime.parse(result.getString("timestamp"), format);

            JsonObject jsonData = result.getJsonObject("jsonData");
            List<String> selectedOptions = new ArrayList<String>();
            JsonArray optionsArray = jsonData.getJsonArray("e");
            for (int i = 0; i < optionsArray.size(); i++) {
                selectedOptions.add(optionsArray.getString(i));
            }
            String u_HatString = jsonData.getString("u_Hat");
            String cString = jsonData.getString("c");
            String dString = jsonData.getString("d");
            String pi1String = jsonData.getString("pi1");
            String pi2String = jsonData.getString("pi2");
            String pi3String = jsonData.getString("pi3");
            //create ballot object and add it to the list
            Ballot ballot = new Ballot(id, election, selectedOptions, u_HatString, cString, dString, pi1String,
                    pi2String, pi3String, timeStamp);
            System.out.println(ballot.isValid());
            ballots.add(ballot);
        }

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

}

From source file:eu.forgetit.middleware.component.Extractor.java

public void executeImageAnalysis(Exchange exchange) {

    taskStep = "EXTRACTOR_IMAGE_ANALYSIS";

    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);

    if (jsonBody != null) {

        String 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 imageAnalysisPath = Paths.get(metadataPath.toString(), "imageAnalysis.xml");

                String imagePaths = getImagePaths(contentPath, pofId);

                if (imagePaths != null && !imagePaths.isEmpty()) {

                    String response = service.img_request(imagePaths, "all", null);

                    FileUtils.writeStringToFile(imageAnalysisPath.toFile(), response);

                    logger.debug("Image Analysis completed for " + imagePaths);
                }/*from   w ww .  j  a va  2 s  .c  om*/

            } catch (IOException 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:de.tu_dortmund.ub.data.dswarm.Task.java

/**
 * configuration and processing of the task
 *
 * @param inputDataModelID//from w w  w  . j  a v  a  2  s. c o m
 * @param projectID
 * @param outputDataModelID
 * @return
 */
private String executeTask(String inputDataModelID, String projectID, String outputDataModelID)
        throws Exception {

    String jsonResponse = null;

    CloseableHttpClient httpclient = HttpClients.createDefault();

    try {

        // Hole Mappings aus dem Projekt mit 'projectID'
        HttpGet httpGet = new HttpGet(config.getProperty("engine.dswarm.api") + "projects/" + projectID);

        CloseableHttpResponse httpResponse = httpclient.execute(httpGet);

        logger.info("[" + config.getProperty("service.name") + "] " + "request : " + httpGet.getRequestLine());

        String mappings = "";

        try {

            int statusCode = httpResponse.getStatusLine().getStatusCode();
            HttpEntity httpEntity = httpResponse.getEntity();

            switch (statusCode) {

            case 200: {

                StringWriter writer = new StringWriter();
                IOUtils.copy(httpEntity.getContent(), writer, "UTF-8");
                String responseJson = writer.toString();

                logger.info("[" + config.getProperty("service.name") + "] responseJson : " + responseJson);

                JsonReader jsonReader = Json.createReader(IOUtils.toInputStream(responseJson, "UTF-8"));
                JsonObject jsonObject = jsonReader.readObject();

                mappings = jsonObject.getJsonArray("mappings").toString();

                logger.info("[" + config.getProperty("service.name") + "] mappings : " + mappings);

                break;
            }
            default: {

                logger.error("[" + config.getProperty("service.name") + "] " + statusCode + " : "
                        + httpResponse.getStatusLine().getReasonPhrase());
            }
            }

            EntityUtils.consume(httpEntity);
        } finally {
            httpResponse.close();
        }

        // Hole InputDataModel
        String inputDataModel = "";

        httpGet = new HttpGet(config.getProperty("engine.dswarm.api") + "datamodels/" + inputDataModelID);

        httpResponse = httpclient.execute(httpGet);

        logger.info("[" + config.getProperty("service.name") + "] " + "request : " + httpGet.getRequestLine());

        try {

            int statusCode = httpResponse.getStatusLine().getStatusCode();
            HttpEntity httpEntity = httpResponse.getEntity();

            switch (statusCode) {

            case 200: {

                StringWriter writer = new StringWriter();
                IOUtils.copy(httpEntity.getContent(), writer, "UTF-8");
                inputDataModel = writer.toString();

                logger.info("[" + config.getProperty("service.name") + "] inputDataModel : " + inputDataModel);

                JsonReader jsonReader = Json.createReader(IOUtils.toInputStream(inputDataModel, "UTF-8"));
                JsonObject jsonObject = jsonReader.readObject();

                String inputResourceID = jsonObject.getJsonObject("data_resource").getString("uuid");

                logger.info("[" + config.getProperty("service.name") + "] mappings : " + mappings);

                break;
            }
            default: {

                logger.error("[" + config.getProperty("service.name") + "] " + statusCode + " : "
                        + httpResponse.getStatusLine().getReasonPhrase());
            }
            }

            EntityUtils.consume(httpEntity);
        } finally {
            httpResponse.close();
        }

        // Hole OutputDataModel
        String outputDataModel = "";

        httpGet = new HttpGet(config.getProperty("engine.dswarm.api") + "datamodels/" + outputDataModelID);

        httpResponse = httpclient.execute(httpGet);

        logger.info("[" + config.getProperty("service.name") + "] " + "request : " + httpGet.getRequestLine());

        try {

            int statusCode = httpResponse.getStatusLine().getStatusCode();
            HttpEntity httpEntity = httpResponse.getEntity();

            switch (statusCode) {

            case 200: {

                StringWriter writer = new StringWriter();
                IOUtils.copy(httpEntity.getContent(), writer, "UTF-8");
                outputDataModel = writer.toString();

                logger.info(
                        "[" + config.getProperty("service.name") + "] outputDataModel : " + outputDataModel);

                break;
            }
            default: {

                logger.error("[" + config.getProperty("service.name") + "] " + statusCode + " : "
                        + httpResponse.getStatusLine().getReasonPhrase());
            }
            }

            EntityUtils.consume(httpEntity);
        } finally {
            httpResponse.close();
        }

        // erzeuge Task-JSON
        String task = "{";
        task += "\"name\":\"" + "Task Batch-Prozess 'CrossRef'" + "\",";
        task += "\"description\":\"" + "Task Batch-Prozess 'CrossRef' zum InputDataModel '" + inputDataModelID
                + "'\",";
        task += "\"job\": { " + "\"mappings\": " + mappings + "," + "\"uuid\": \"" + UUID.randomUUID() + "\""
                + " },";
        task += "\"input_data_model\":" + inputDataModel + ",";
        task += "\"output_data_model\":" + outputDataModel;
        task += "}";

        logger.info("[" + config.getProperty("service.name") + "] task : " + task);

        // POST /dmp/tasks/
        HttpPost httpPost = new HttpPost(config.getProperty("engine.dswarm.api") + "tasks?persist="
                + config.getProperty("results.persistInDMP"));
        StringEntity stringEntity = new StringEntity(task,
                ContentType.create("application/json", Consts.UTF_8));
        httpPost.setEntity(stringEntity);

        logger.info("[" + config.getProperty("service.name") + "] " + "request : " + httpPost.getRequestLine());

        httpResponse = httpclient.execute(httpPost);

        try {

            int statusCode = httpResponse.getStatusLine().getStatusCode();
            HttpEntity httpEntity = httpResponse.getEntity();

            switch (statusCode) {

            case 200: {

                logger.info("[" + config.getProperty("service.name") + "] " + statusCode + " : "
                        + httpResponse.getStatusLine().getReasonPhrase());

                StringWriter writer = new StringWriter();
                IOUtils.copy(httpEntity.getContent(), writer, "UTF-8");
                jsonResponse = writer.toString();

                logger.info("[" + config.getProperty("service.name") + "] jsonResponse : " + jsonResponse);

                break;
            }
            default: {

                logger.error("[" + config.getProperty("service.name") + "] " + statusCode + " : "
                        + httpResponse.getStatusLine().getReasonPhrase());
            }
            }

            EntityUtils.consume(httpEntity);
        } finally {
            httpResponse.close();
        }

    } finally {
        httpclient.close();
    }

    return jsonResponse;
}