Example usage for javax.json Json createObjectBuilder

List of usage examples for javax.json Json createObjectBuilder

Introduction

In this page you can find the example usage for javax.json Json createObjectBuilder.

Prototype

public static JsonObjectBuilder createObjectBuilder() 

Source Link

Document

Creates a JSON object builder

Usage

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

private JsonObject affToJsonObject() {
    JsonObjectBuilder ob = Json.createObjectBuilder();
    if (client.getCAName() != null) {
        ob.add(HFCAClient.FABRIC_CA_REQPROP, client.getCAName());
    }//  w  ww  .j av  a2  s . c o m
    if (this.updateName != null) {
        ob.add("name", updateName);
        this.updateName = null;
    } else {
        ob.add("name", name);
    }

    return ob.build();
}

From source file:com.buffalokiwi.aerodrome.jet.JetAPI.java

/**
 * Retrieve the payload for the login/authentication request.
 * This creates an object with "user" and "pass" properties with values 
 * from the current JetConfig object./*from w w  w.java2s. c  o  m*/
 * @return The built JSON
 */
private JsonObject getLoginPayload() {
    return Json.createObjectBuilder().add("user", config.getUsername()).add("pass", config.getPassword())
            .build();
}

From source file:org.kuali.student.enrollment.class2.acal.service.impl.AcademicCalendarViewHelperServiceImpl.java

public AcademicTermWrapper populateTermWrapper(TermInfo termInfo, boolean isCopy, boolean calculateInstrDays)
        throws Exception {

    getLog().debug("Populating Term - {}", termInfo.getId());

    TypeInfo type = getAcalService().getTermType(termInfo.getTypeKey(), createContextInfo());

    AcademicTermWrapper termWrapper = new AcademicTermWrapper(termInfo, isCopy);
    termWrapper.setTypeInfo(type);/*from w ww.  ja va2 s .c o m*/
    termWrapper.setTermNameForUI(type.getName());
    if (isCopy) {
        termWrapper.setName(type.getName());
    }

    //Populate examdates
    List<ExamPeriodInfo> examPeriodInfos = getAcalService().getExamPeriodsForTerm(termInfo.getId(),
            createContextInfo());
    if (examPeriodInfos != null && examPeriodInfos.size() > 0) { //only one or none
        for (ExamPeriodInfo examPeriodInfo : examPeriodInfos) {
            ExamPeriodWrapper examPeriodWrapper = new ExamPeriodWrapper(examPeriodInfo, isCopy);
            examPeriodWrapper.setExcludeSaturday(Boolean.parseBoolean(examPeriodInfo
                    .getAttributeValue(AcademicCalendarServiceConstants.EXAM_PERIOD_EXCLUDE_SATURDAY_ATTR)));
            examPeriodWrapper.setExcludeSunday(Boolean.parseBoolean(examPeriodInfo
                    .getAttributeValue(AcademicCalendarServiceConstants.EXAM_PERIOD_EXCLUDE_SUNDAY_ATTR)));
            termWrapper.getExamdates().add(examPeriodWrapper);
        }
    }

    //Populate keydates
    List<KeyDateInfo> keydateList = getAcalService().getKeyDatesForTerm(termInfo.getId(), createContextInfo());
    List<TypeInfo> keyDateTypes = getTypeService().getAllowedTypesForType(termInfo.getTypeKey(),
            createContextInfo());

    Map<String, KeyDatesGroupWrapper> keyDateGroup = new HashMap<String, KeyDatesGroupWrapper>();

    for (KeyDateInfo keyDateInfo : keydateList) {
        KeyDateWrapper keyDateWrapper = new KeyDateWrapper(keyDateInfo, isCopy);
        type = getTypeService().getType(keyDateInfo.getTypeKey(), createContextInfo());
        keyDateWrapper.setTypeInfo(type);
        keyDateWrapper.setKeyDateNameUI(type.getName());

        addKeyDateGroup(keyDateTypes, keyDateWrapper, keyDateGroup);
    }

    for (KeyDatesGroupWrapper group : keyDateGroup.values()) {
        if (!group.getKeydates().isEmpty()) {

            //KSENROLL-12648: workaround for rice 2.4 upgrade issue.
            //Construct key date types JSON string for js to populate key date type dropdown in key date add blank line
            if (StringUtils.isBlank(group.getKeyDateTypesJSON())) {
                List<TypeInfo> types = getTypeService().getTypesForGroupType(group.getKeyDateGroupType(),
                        createContextInfo());
                JsonObjectBuilder keyDateTypesJsonBuilder = Json.createObjectBuilder();
                for (TypeInfo typeInfo : types) {
                    if (!group.isKeyDateExists(typeInfo.getKey())) {
                        keyDateTypesJsonBuilder.add(typeInfo.getKey(),
                                typeInfo.getName().replace("\"", "\\\""));
                    }
                }
                group.setKeyDateTypesJSON(keyDateTypesJsonBuilder.build().toString());
            }

            termWrapper.getKeyDatesGroupWrappers().add(group);
        }
    }

    if (calculateInstrDays) {
        populateInstructionalDays(termWrapper);
    }

    return termWrapper;
}

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

/**
 * Turn this object into jet json /*from   w ww .j ava 2  s.c o  m*/
 * @return json
 */
public JsonObject toJSON() {
    JsonArrayBuilder adj = Json.createArrayBuilder();

    for (FeeAdjRec f : adjustments) {
        adj.add(f.toJSON());
    }

    return Json.createObjectBuilder().add("order_item_id", orderItemId).add("alt_order_item_id", altOrderItemId)
            .add("merchant_sku", merchantSku).add("product_title", title)
            .add("request_order_quantity", requestOrderQty)
            .add("request_order_cancel_qty", requestOrderCancelQty).add("adjustment_reason", adjReason)
            .add("item_tax_code", taxCode).add("url", url).add("price_adjustment", priceAdj.asBigDecimal())
            .add("item_fees", fees.asBigDecimal()).add("tax_info", taxInfo).add("fee_adjustments", adj.build())
            .add("regulatory_fees", regFees.asBigDecimal())
            .add("order_item_acknowledgement_status", itemAckStatus.getText())
            .add("item_price", itemPrice.toJSON()).build();
}

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

/**
 * Posts the given ballot to the bulletin board
 * @param ballot Ballot to be posted to the bulletin board
 * @param useTor Boolean indicating if Ballot should be posted over the Tor network
 *//*from   w  w w .  jav  a 2s.c  o  m*/
public void postBallot(Ballot ballot, Boolean useTor) {
    JsonObjectBuilder jBuilder = Json.createObjectBuilder();
    //Translate ballot object into a json string 
    JsonArrayBuilder optionsBuilder = Json.createArrayBuilder();
    for (String option : ballot.getSelectedOptions()) {
        optionsBuilder.add(option);
    }
    jBuilder.add("e", optionsBuilder);
    jBuilder.add("u_Hat", ballot.getU_HatString());
    jBuilder.add("c", ballot.getCString());
    jBuilder.add("d", ballot.getDString());
    jBuilder.add("pi1", ballot.getPi1String());
    jBuilder.add("pi2", ballot.getPi2String());
    jBuilder.add("pi3", ballot.getPi3String());

    JsonObject model = jBuilder.build();

    //josn gets posted to the bulletin board
    try {
        boolean requestOK = postJsonStringToURL(
                bulletinBoardUrl + "/elections/" + ballot.getElection().getId() + "/ballots", model.toString(),
                useTor);
        if (requestOK) {
            System.out.println("Ballot posted!");
        } else {
            System.out.println("Was not able to post Ballot!");
        }
    } catch (IOException ex) {
        System.out.println("Was not able to post Ballot!");
    }
}

From source file:io.bitgrillr.gocddockerexecplugin.DockerExecPluginTest.java

@Test
public void handleExecuteNestedCleanupError() throws Exception {
    UnitTestUtils.mockJobConsoleLogger();
    PowerMockito.mockStatic(DockerUtils.class);
    PowerMockito.doNothing().when(DockerUtils.class);
    DockerUtils.pullImage(anyString());//from   w  w w  .  j  a  v a  2s. c  om
    when(DockerUtils.createContainer(anyString(), anyString(), anyMap())).thenReturn("123");
    when(DockerUtils.getContainerUid(anyString())).thenReturn("4:5");
    when(DockerUtils.execCommand(anyString(), any(), anyString(), any()))
            .thenThrow(new DockerException("FAIL1"));
    PowerMockito.doThrow(new DockerException("FAIL2")).when(DockerUtils.class);
    DockerUtils.removeContainer(anyString());
    PowerMockito.mockStatic(SystemHelper.class);
    when(SystemHelper.getSystemUid()).thenReturn("7:8");

    DefaultGoPluginApiRequest request = new DefaultGoPluginApiRequest(null, null, "execute");
    JsonObject requestBody = Json.createObjectBuilder()
            .add("config",
                    Json.createObjectBuilder()
                            .add("IMAGE", Json.createObjectBuilder().add("value", "ubuntu:latest").build())
                            .add("COMMAND", Json.createObjectBuilder().add("value", "ls").build())
                            .add("ARGUMENTS", Json.createObjectBuilder().build()).build())
            .add("context", Json.createObjectBuilder().add("workingDirectory", "pipelines/test")
                    .add("environmentVariables", Json.createObjectBuilder().build()).build())
            .build();
    request.setRequestBody(requestBody.toString());
    final GoPluginApiResponse response = new DockerExecPlugin().handle(request);

    assertEquals("Expected 2xx response", DefaultGoPluginApiResponse.SUCCESS_RESPONSE_CODE,
            response.responseCode());
    final JsonObject responseBody = Json.createReader(new StringReader(response.responseBody())).readObject();
    assertEquals("Expected failure", Boolean.FALSE, responseBody.getBoolean("success"));
    assertEquals("Wrong message", "FAIL1", responseBody.getString("message"));
}

From source file:no.sintef.jarfter.Jarfter.java

private JsonObject jsonWrappedTransformUri(String transformation_uri) {
    return Json.createObjectBuilder().add("transformation_uri", transformation_uri).build();
}

From source file:no.sintef.jarfter.Jarfter.java

private JsonObject jsonWrap(String field, String value) {
    return Json.createObjectBuilder().add(field, value).build();
}

From source file:be.fedict.dcat.datagovbe.Drupal.java

/**
 * Add a dataset to the Drupal website.//from www  .j  a va 2 s.co  m
 * 
 * @param uri identifier of the dataset
 * @throws RepositoryException
 */
private void add(IRI uri) throws RepositoryException {
    Map<IRI, ListMultimap<String, String>> dataset = store.queryProperties(uri);

    if (dataset.isEmpty()) {
        logger.warn("Empty dataset for {}", uri.stringValue());
        return;
    }

    for (String lang : langs) {
        if (!hasLang(dataset, lang)) {
            continue;
        }

        JsonObjectBuilder builder = Json.createObjectBuilder();

        addDataset(builder, dataset, lang);

        // Get DCAT distributions
        List<String> dists = getMany(dataset, DCAT.DISTRIBUTION, "");
        addDists(builder, dists, lang);

        // Add new or update existing dataset ?
        String id = getOne(dataset, DCTERMS.IDENTIFIER, "");
        String node = checkExistsTrans(builder, id, lang);

        // Build the JSON array
        JsonObject obj = builder.build();
        logger.debug(obj.toString());

        Request r = node.isEmpty() ? prepare(Drupal.POST, Drupal.NODE)
                : prepare(Drupal.PUT, Drupal.NODE + "/" + node);
        r.bodyString(obj.toString(), ContentType.APPLICATION_JSON);

        try {
            StatusLine status = exec.authPreemptive(host).execute(r).returnResponse().getStatusLine();
            logger.debug(status.toString());
        } catch (IOException ex) {
            logger.error("Could not update {}", uri.toString(), ex);
        }
    }
}

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

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

public HFCAInfo info() throws InfoException, InvalidArgumentException {

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

    setUpSSL();

    try {

        JsonObjectBuilder factory = Json.createObjectBuilder();

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

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

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

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

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

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

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

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

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

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

}