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:com.buffalokiwi.aerodrome.jet.orders.OrderRec.java

/**
 * Turn Jet Json into an OrderRec//from   w w  w.  j a  v  a  2 s.  c o  m
 * @param json Jet json
 * @return object 
 */
public static OrderRec fromJson(final JsonObject json) {
    Utils.checkNull(json, "json");
    final Builder b = new Builder().setMerchantOrderId(json.getString("merchant_order_id", ""))
            .setReferenceOrderId(json.getString("reference_order_id", ""))
            .setCustomerReferenceOrderId(json.getString("customer_reference_order_id", ""))
            .setFulfillmentNode(json.getString("fulfillment_node", ""))
            .setAltOrderId(json.getString("alt_order_id", "")).setHashEmail(json.getString("hash_email", ""))
            .setStatus(OrderStatus.fromText(json.getString("status", "")))
            .setExceptionState(OrderExceptionState.fromText(json.getString("exception_state", "")))
            .setOrderPlacedDate(JetDate.fromJetValueOrNull(json.getString("order_placed_date", "")))
            .setOrderTransmissionDate(JetDate.fromJetValueOrNull(json.getString("order_transmission_date", "")))
            .setJetRequestDirectedCancel(json.getBoolean("jet_requested_directed_cancel", false))
            .setOrderReadyDate(JetDate.fromJetValueOrNull(json.getString("order_ready_date", "")))
            .setHasShipments(json.getBoolean("has_shipments", false))
            .setOrderAckDate(JetDate.fromJetValueOrNull(json.getString("order_acknowledge_date", "")))
            .setAckStatus(AckStatus.fromText(json.getString("acknowledgement_status", "")));

    buildOrderDetail(b, json.getJsonObject("order_detail"));
    buildBuyer(b, json.getJsonObject("buyer"));
    buildShipTo(b, json.getJsonObject("shipping_to"));
    buildOrderTotals(b, json.getJsonObject("order_totals"));

    try {
        buildOrderItems(b, json.getJsonArray("order_items"));
    } catch (JetException e) {
        APILog.error(LOG, e, "Failed to generate order items");
    }

    //..Build the shipments
    final JsonArray shipments = json.getJsonArray("shipments");
    if (shipments != null) {
        for (int i = 0; i < shipments.size(); i++) {
            final JsonObject shipment = shipments.getJsonObject(i);
            if (shipment == null)
                continue;

            b.getShipments().add(ShipmentRec.fromJson(shipment));
        }
    }

    return new OrderRec(b);
}

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

JsonObject getResult(HttpResponse response, String body, String type)
        throws HTTPException, ParseException, IOException {

    int respStatusCode = response.getStatusLine().getStatusCode();
    HttpEntity entity = response.getEntity();
    logger.trace(format("response status %d, HttpEntity %s ", respStatusCode, "" + entity));
    String responseBody = entity != null ? EntityUtils.toString(entity) : null;
    logger.trace(format("responseBody: %s ", responseBody));

    // If the status code in the response is greater or equal to the status code set in the client object then an exception will
    // be thrown, otherwise, we continue to read the response and return any error code that is less than 'statusCode'
    if (respStatusCode >= statusCode) {
        HTTPException e = new HTTPException(
                format("%s request to %s failed request body %s. Response: %s", type, url, body, responseBody),
                respStatusCode);// w w w.j  a  v a  2s . c  o m
        logger.error(e.getMessage());
        throw e;
    }
    if (responseBody == null) {

        HTTPException e = new HTTPException(
                format("%s request to %s failed request body %s with null response body returned.", type, url,
                        body),
                respStatusCode);
        logger.error(e.getMessage());
        throw e;

    }

    logger.debug("Status: " + respStatusCode);

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

    JsonObjectBuilder job = Json.createObjectBuilder();
    job.add("statusCode", respStatusCode);

    JsonArray errors = jobj.getJsonArray("errors");
    // If the status code is greater than or equal to 400 but less than or equal to the client status code setting,
    // then encountered an error and we return back the status code, and log the error rather than throwing an exception.
    if (respStatusCode < statusCode && respStatusCode >= 400) {
        if (errors != null && !errors.isEmpty()) {
            JsonObject jo = errors.getJsonObject(0);
            String errorMsg = format(
                    "[HTTP Status Code: %d] - %s request to %s failed request body %s error message: [Error Code %d] - %s",
                    respStatusCode, type, url, body, jo.getInt("code"), jo.getString("message"));
            logger.error(errorMsg);
        }
        return job.build();
    }
    if (errors != null && !errors.isEmpty()) {
        JsonObject jo = errors.getJsonObject(0);
        HTTPException e = new HTTPException(
                format("%s request to %s failed request body %s error message: [Error Code %d] - %s", type, url,
                        body, jo.getInt("code"), jo.getString("message")),
                respStatusCode);
        throw e;
    }

    boolean success = jobj.getBoolean("success");
    if (!success) {
        HTTPException e = new HTTPException(
                format("%s request to %s failed request body %s Body of response did not contain success", type,
                        url, body),
                respStatusCode);
        logger.error(e.getMessage());
        throw e;
    }

    JsonObject result = jobj.getJsonObject("result");
    if (result == null) {
        HTTPException e = new HTTPException(
                format("%s request to %s failed request body %s " + "Body of response did not contain result",
                        type, url, body),
                respStatusCode);
        logger.error(e.getMessage());
        throw e;
    }

    JsonArray messages = jobj.getJsonArray("messages");
    if (messages != null && !messages.isEmpty()) {
        JsonObject jo = messages.getJsonObject(0);
        String message = format(
                "%s request to %s failed request body %s response message: [Error Code %d] - %s", type, url,
                body, jo.getInt("code"), jo.getString("message"));
        logger.info(message);
    }

    // Construct JSON object that contains the result and HTTP status code
    for (Entry<String, JsonValue> entry : result.entrySet()) {
        job.add(entry.getKey(), entry.getValue());
    }
    job.add("statusCode", respStatusCode);
    result = job.build();

    logger.debug(format("%s %s, body:%s result: %s", type, url, body, "" + result));
    return result;
}

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

/**
 * Gets all certificates that the registrar is allowed to see and based on filter parameters that
 * are part of the certificate request./* w w  w.  ja  v  a 2s.c o  m*/
 *
 * @param registrar The identity of the registrar (i.e. who is performing the registration).
 * @param req The certificate request that contains filter parameters
 * @return HFCACertificateResponse object
 * @throws HFCACertificateException Failed to process get certificate request
 */
public HFCACertificateResponse getHFCACertificates(User registrar, HFCACertificateRequest req)
        throws HFCACertificateException {
    try {
        logger.debug(format("certificate url: %s, registrar: %s", HFCA_CERTIFICATE, registrar.getName()));

        JsonObject result = httpGet(HFCA_CERTIFICATE, registrar, req.getQueryParameters());

        int statusCode = result.getInt("statusCode");
        Collection<HFCACredential> certs = new ArrayList<>();
        if (statusCode < 400) {
            JsonArray certificates = result.getJsonArray("certs");
            if (certificates != null && !certificates.isEmpty()) {
                for (int i = 0; i < certificates.size(); i++) {
                    String certPEM = certificates.getJsonObject(i).getString("PEM");
                    certs.add(new HFCAX509Certificate(certPEM));
                }
            }
            logger.debug(format("certificate url: %s, registrar: %s done.", HFCA_CERTIFICATE, registrar));
        }
        return new HFCACertificateResponse(statusCode, certs);
    } catch (HTTPException e) {
        String msg = format("[Code: %d] - Error while getting certificates from url '%s': %s",
                e.getStatusCode(), HFCA_CERTIFICATE, e.getMessage());
        HFCACertificateException certificateException = new HFCACertificateException(msg, e);
        logger.error(msg);
        throw certificateException;
    } catch (Exception e) {
        String msg = format("Error while getting certificates from url '%s': %s", HFCA_CERTIFICATE,
                e.getMessage());
        HFCACertificateException certificateException = new HFCACertificateException(msg, e);
        logger.error(msg);
        throw certificateException;
    }
}

From source file:de.pangaea.fixo3.CreateFixO3.java

private void addFixedOceanObservatory(JsonObject jo) {
    String label;/*w w  w.java2  s. c om*/

    if (jo.containsKey("label"))
        label = jo.getString("label");
    else
        throw new RuntimeException("Label is expected [jo = " + jo + "]");

    IRI observatory = IRI.create(FIXO3.ns.toString() + md5Hex(label));

    m.addIndividual(observatory);
    m.addType(observatory, FixedPointOceanObservatory);
    m.addLabel(observatory, label);

    if (jo.containsKey("title")) {
        m.addTitle(observatory, jo.getString("title"));
    }
    if (jo.containsKey("comment")) {
        m.addComment(observatory, jo.getString("comment"));
    }
    if (jo.containsKey("source")) {
        m.addSource(observatory, IRI.create(jo.getString("source")));
    }
    if (jo.containsKey("location")) {
        JsonObject j = jo.getJsonObject("location");

        String place, coordinates;

        if (j.containsKey("place"))
            place = j.getString("place");
        else
            throw new RuntimeException("Place is expected [j = " + j + "]");

        if (j.containsKey("coordinates"))
            coordinates = j.getString("coordinates");
        else
            throw new RuntimeException("Coordinates are expected [j = " + j + "]");

        String fl = place + " @ " + coordinates;
        String gl = coordinates;

        IRI feature = IRI.create(FIXO3.ns.toString() + md5Hex(fl));
        IRI geometry = IRI.create(FIXO3.ns.toString() + md5Hex(gl));

        m.addIndividual(feature);
        m.addType(feature, Feature);
        m.addLabel(feature, fl);
        m.addObjectAssertion(observatory, location, feature);

        if (coordinates.startsWith("POINT"))
            m.addType(geometry, Point);
        else
            throw new RuntimeException("Coordinates not recognized, expected POINT [j = " + j + "]");

        m.addIndividual(geometry);
        m.addLabel(geometry, gl);
        m.addObjectAssertion(feature, hasGeometry, geometry);
        m.addDataAssertion(geometry, asWKT, coordinates, wktLiteral);
    }

    if (!jo.containsKey("attachedSystems"))
        return;

    JsonArray attachedSystems = jo.getJsonArray("attachedSystems");

    for (JsonObject j : attachedSystems.getValuesAs(JsonObject.class)) {
        String l, t;

        if (j.containsKey("label"))
            l = j.getString("label");
        else
            throw new RuntimeException("Label expected [j = " + j + "]");

        if (j.containsKey("type"))
            t = j.getString("type");
        else
            throw new RuntimeException("Type excepted [j = " + j + "]");

        IRI system = IRI.create(FIXO3.ns.toString() + md5Hex(l));

        m.addIndividual(system);
        m.addType(system, IRI.create(t));
        m.addLabel(system, l);
        m.addObjectAssertion(observatory, attachedSystem, system);
    }
}

From source file:csg.files.CSGFiles.java

@Override
public void loadData(AppDataComponent data, AppDataComponent recData, AppDataComponent schData,
        AppDataComponent projectData, AppDataComponent courseData, String filePath) throws IOException {
    // CLEAR THE OLD DATA OUT
    TAData dataManager = (TAData) data;/* w  ww.  j a va 2s  .  com*/
    ScheduleData schDataManager = (ScheduleData) schData;
    RecitationData recDataManager = (RecitationData) recData;
    ProjectData projectDataManager = (ProjectData) projectData;
    CourseData courseDataManager = (CourseData) courseData;
    workspace = (CSGWorkspace) app.getWorkspaceComponent();

    // LOAD THE JSON FILE WITH ALL THE DATA
    JsonObject json = loadJSONFile(filePath);

    // LOAD THE START AND END HOURS
    String startHour = json.getString(JSON_START_HOUR);
    String endHour = json.getString(JSON_END_HOUR);
    dataManager.initHours(startHour, endHour);

    // NOW RELOAD THE WORKSPACE WITH THE LOADED DATA
    app.getWorkspaceComponent().reloadWorkspace(app.getTADataComponent());

    int startDay = json.getInt(JSON_STARTDAY);
    int startMonth = json.getInt(JSON_STARTMONTH);
    int startYear = json.getInt(JSON_STARTYEAR);

    courseDataManager.setStartDay(startDay);
    courseDataManager.setStartMonth(startMonth);
    courseDataManager.setStartYear(startYear);

    if (startDay != 0 && startMonth != 0 && startYear != 0) {
        LocalDate startDate = LocalDate.of(startYear, startMonth, startDay);
        workspace.getMonStartDatePicker().setValue(startDate);
    } else {
        workspace.getMonStartDatePicker().setValue(null);
    }

    int endDay = json.getInt(JSON_ENDDAY);
    int endMonth = json.getInt(JSON_ENDMONTH);
    int endYear = json.getInt(JSON_ENDYEAR);

    courseDataManager.setEndDay(endDay);
    courseDataManager.setEndMonth(endMonth);
    courseDataManager.setEndYear(endYear);

    if (endDay != 0 && endMonth != 0 && endYear != 0) {
        LocalDate endDate = LocalDate.of(endYear, endMonth, endDay);
        workspace.getFriEndDatePicker().setValue(endDate);
    } else {
        workspace.getFriEndDatePicker().setValue(null);
    }

    // NOW LOAD ALL THE UNDERGRAD TAs
    JsonArray jsonTAArray = json.getJsonArray(JSON_UNDERGRAD_TAS);
    for (int i = 0; i < jsonTAArray.size(); i++) {
        JsonObject jsonTA = jsonTAArray.getJsonObject(i);
        String name = jsonTA.getString(JSON_NAME);
        String email = jsonTA.getString(JSON_EMAIL);
        boolean ug = jsonTA.getBoolean(JSON_UG);
        BooleanProperty isUndergrad = new SimpleBooleanProperty();
        isUndergrad.setValue(ug);
        dataManager.addTA(name, email, isUndergrad);
    }

    // AND THEN ALL THE OFFICE HOURS
    JsonArray jsonOfficeHoursArray = json.getJsonArray(JSON_OFFICE_HOURS);
    for (int i = 0; i < jsonOfficeHoursArray.size(); i++) {
        JsonObject jsonOfficeHours = jsonOfficeHoursArray.getJsonObject(i);
        String day = jsonOfficeHours.getString(JSON_DAY);
        String time = jsonOfficeHours.getString(JSON_TIME);
        String name = jsonOfficeHours.getString(JSON_NAME);
        dataManager.addOfficeHoursReservation(day, time, name);
    }

    JsonArray jsonRecitationArray = json.getJsonArray(JSON_RECITATION);
    for (int i = 0; i < jsonRecitationArray.size(); i++) {
        JsonObject jsonRec = jsonRecitationArray.getJsonObject(i);
        String section = jsonRec.getString(JSON_SECTION);
        String instructor = jsonRec.getString(JSON_INSTRUCTOR);
        String dayTime = jsonRec.getString(JSON_DAYTIME);
        String location = jsonRec.getString(JSON_LOCATION);
        String firstTA = jsonRec.getString(JSON_FIRSTTA);
        String secondTA = jsonRec.getString(JSON_SECONDTA);
        recDataManager.addRecitation(section, instructor, dayTime, location, firstTA, secondTA);
    }

    JsonArray jsonScheduleArray = json.getJsonArray(JSON_SCHEDULEITEM);
    for (int i = 0; i < jsonScheduleArray.size(); i++) {
        JsonObject jsonSch = jsonScheduleArray.getJsonObject(i);
        String type = jsonSch.getString(JSON_TYPE);
        int month = jsonSch.getInt(JSON_MONTH);
        int day = jsonSch.getInt(JSON_DAY);
        int year = jsonSch.getInt(JSON_YEAR);
        String time = jsonSch.getString(JSON_TIME);
        String title = jsonSch.getString(JSON_TITLE);
        String topic = jsonSch.getString(JSON_TOPIC);
        String link = jsonSch.getString(JSON_LINK);
        String criteria = jsonSch.getString(JSON_CRITERIA);
        schDataManager.addScheduleItem(type, LocalDate.of(year, month, day), time, title, topic, link,
                criteria);
    }

    JsonArray jsonTeamArray = json.getJsonArray(JSON_TEAMS);
    for (int i = 0; i < jsonTeamArray.size(); i++) {
        JsonObject jsonTeam = jsonTeamArray.getJsonObject(i);
        String name = jsonTeam.getString(JSON_NAME);
        String color = jsonTeam.getString(JSON_COLOR);
        String textColor = jsonTeam.getString(JSON_TEXTCOLOR);
        String link = jsonTeam.getString(JSON_LINK);
        projectDataManager.addTeam(name, color, textColor, link);
    }

    JsonArray jsonStudentArray = json.getJsonArray(JSON_STUDENTS);
    for (int i = 0; i < jsonStudentArray.size(); i++) {
        JsonObject jsonStudent = jsonStudentArray.getJsonObject(i);
        String firstName = jsonStudent.getString(JSON_FIRSTNAME);
        String lastName = jsonStudent.getString(JSON_LASTNAME);
        String team = jsonStudent.getString(JSON_TEAM);
        String role = jsonStudent.getString(JSON_ROLE);
        projectDataManager.addStudent(firstName, lastName, team, role);
    }

    JsonArray jsonTemplateArray = json.getJsonArray(JSON_COURSETEMPLATE);
    courseDataManager.getTemplates().clear();
    for (int i = 0; i < jsonTemplateArray.size(); i++) {
        JsonObject jsonTemplate = jsonTemplateArray.getJsonObject(i);
        boolean use = jsonTemplate.getBoolean(JSON_USE);
        String navbar = jsonTemplate.getString(JSON_NAVBAR);
        String fileName = jsonTemplate.getString(JSON_FILENAME);
        String script = jsonTemplate.getString(JSON_SCRIPT);
        courseDataManager.addTemplate(use, navbar, fileName, script);
    }

    JsonObject courseJson = json.getJsonObject(JSON_COURSE);
    courseDataManager.setNumber(courseJson.getString(JSON_NUMBER));
    courseDataManager.setSemester(courseJson.getString(JSON_SEMESTER));
    courseDataManager.setSubject(courseJson.getString(JSON_SUBJECT));
    courseDataManager.setYear(courseJson.getString(JSON_YEAR));
    courseDataManager.setTitle(courseJson.getString(JSON_TITLE));
    courseDataManager.setInsName(courseJson.getString(JSON_INSTRUCTORNAME));
    courseDataManager.setInsHome(courseJson.getString(JSON_INSTRUCTORHOME));
    courseDataManager.setBannerLink(courseJson.getString(JSON_BANNER));
    courseDataManager.setLeftFooterLink(courseJson.getString(JSON_LEFTFOOTER));
    courseDataManager.setRightFooterLink(courseJson.getString(JSON_RIGHTFOOTER));
    courseDataManager.setTemplateDir(courseJson.getString(JSON_TEMPLATEDIR));
    courseDataManager.setExportDir(courseJson.getString(JSON_EXPORTDIR));
    courseDataManager.setStyleSheet(courseJson.getString(JSON_STYLESHEET));

    workspace.getSubjectCombo().setValue(courseDataManager.getSubject());
    workspace.getNumCombo().setValue(courseDataManager.getNumber());
    workspace.getSemCombo().setValue(courseDataManager.getSemester());
    workspace.getYearCombo().setValue(courseDataManager.getYear());
    workspace.getTitleTextField().setText(courseDataManager.getTitle());
    workspace.getInsNameTextField().setText(courseDataManager.getInsName());
    workspace.getInsHomeTextField().setText(courseDataManager.getInsHome());
    workspace.getStyleSheetCombo().setValue(courseDataManager.getStyleSheet());

    if (!courseDataManager.getBannerLink().isEmpty()) {
        FileInputStream bannerLocation = new FileInputStream(courseJson.getString(JSON_BANNER));
        Image newImg = new Image(bannerLocation);
        workspace.getBannerImage().setImage(newImg);
    } else {
        workspace.getBannerImage().setImage(null);
    }

    if (!courseDataManager.getLeftFooterLink().isEmpty()) {
        FileInputStream leftFooterLocation = new FileInputStream(courseJson.getString(JSON_LEFTFOOTER));
        Image newImg2 = new Image(leftFooterLocation);
        workspace.getLeftFooterImage().setImage(newImg2);
    } else {
        workspace.getLeftFooterImage().setImage(null);
    }

    if (!courseDataManager.getRightFooterLink().isEmpty()) {
        FileInputStream rightFooterLocation = new FileInputStream(courseJson.getString(JSON_RIGHTFOOTER));
        Image newImg3 = new Image(rightFooterLocation);
        workspace.getRightFooterImage().setImage(newImg3);
    } else {
        workspace.getRightFooterImage().setImage(null);
    }
    workspace.getCourseTemplateLocLabel().setText(courseJson.getString(JSON_TEMPLATEDIR));
    workspace.getExportLabel().setText(courseJson.getString(JSON_EXPORTDIR));

}

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

/**
 * Enroll the user with member service//from w  w w  .ja v  a 2s  .  c  om
 *
 * @param user   Identity name to enroll
 * @param secret Secret returned via registration
 * @param req    Enrollment request with the following fields: hosts, profile, csr, label, keypair
 * @return enrollment
 * @throws EnrollmentException
 * @throws InvalidArgumentException
 */

public Enrollment enroll(String user, String secret, EnrollmentRequest req)
        throws EnrollmentException, InvalidArgumentException {

    logger.debug(format("url:%s enroll user: %s", url, user));

    if (Utils.isNullOrEmpty(user)) {
        throw new InvalidArgumentException("enrollment user is not set");
    }
    if (Utils.isNullOrEmpty(secret)) {
        throw new InvalidArgumentException("enrollment secret is not set");
    }

    if (cryptoSuite == null) {
        throw new InvalidArgumentException("Crypto primitives not set.");
    }

    setUpSSL();

    try {
        String pem = req.getCsr();
        KeyPair keypair = req.getKeyPair();
        if (null != pem && keypair == null) {
            throw new InvalidArgumentException(
                    "If certificate signing request is supplied the key pair needs to be supplied too.");
        }
        if (keypair == null) {
            logger.debug("[HFCAClient.enroll] Generating keys...");

            // generate ECDSA keys: signing and encryption keys
            keypair = cryptoSuite.keyGen();

            logger.debug("[HFCAClient.enroll] Generating keys...done!");
        }

        if (pem == null) {
            String csr = cryptoSuite.generateCertificationRequest(user, keypair);
            req.setCSR(csr);
        }

        if (caName != null && !caName.isEmpty()) {
            req.setCAName(caName);
        }
        String body = req.toJson();

        String responseBody = httpPost(url + HFCA_ENROLL, body, new UsernamePasswordCredentials(user, secret));

        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 enrollment for user %s response success is false.", user));
        }

        JsonObject result = jsonst.getJsonObject("result");
        if (result == null) {
            throw new EnrollmentException(
                    format("FabricCA failed enrollment for user %s - response did not contain a result", user));
        }

        Base64.Decoder b64dec = Base64.getDecoder();

        String signedPem = new String(b64dec.decode(result.getString("Cert").getBytes(UTF_8)));
        logger.debug(format("[HFCAClient] enroll returned pem:[%s]", signedPem));

        JsonArray messages = jsonst.getJsonArray("messages");
        if (messages != null && !messages.isEmpty()) {
            JsonObject jo = messages.getJsonObject(0);
            String message = format("Enroll request response message [code %d]: %s", jo.getInt("code"),
                    jo.getString("message"));
            logger.info(message);
        }
        logger.debug("Enrollment done.");

        return new X509Enrollment(keypair, signedPem);

    } catch (EnrollmentException ee) {
        logger.error(format("url:%s, user:%s  error:%s", url, user, ee.getMessage()), ee);
        throw ee;

    } catch (Exception e) {
        EnrollmentException ee = new EnrollmentException(format("Url:%s, Failed to enroll user %s ", url, user),
                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 {/*from w  w w  . j a v a 2 s  .c  om*/
        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.");
    }
}