Example usage for javax.json JsonObjectBuilder build

List of usage examples for javax.json JsonObjectBuilder build

Introduction

In this page you can find the example usage for javax.json JsonObjectBuilder build.

Prototype

JsonObject build();

Source Link

Document

Returns the JSON object associated with this object builder.

Usage

From source file:com.adobe.cq.wcm.core.components.extension.contentfragment.internal.models.v1.ContentFragmentImpl.java

@Nonnull
@Override/* w  w  w . j a va 2 s . c om*/
public String getEditorJSON() {
    JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
    jsonObjectBuilder.add("title", fragment.getTitle());
    jsonObjectBuilder.add("path", path);
    if (variationName != null) {
        jsonObjectBuilder.add("variation", variationName);
    }
    if (elementNames != null) {
        JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
        for (String ele : elementNames) {
            arrayBuilder.add(ele);
        }
        jsonObjectBuilder.add("elements", arrayBuilder);
    }
    Iterator<Resource> associatedContentIter = fragment.getAssociatedContent();
    if (associatedContentIter.hasNext()) {
        JsonArrayBuilder associatedContentArray = Json.createArrayBuilder();
        while (associatedContentIter.hasNext()) {
            Resource resource = associatedContentIter.next();
            ValueMap vm = resource.adaptTo(ValueMap.class);
            JsonObjectBuilder contentObject = Json.createObjectBuilder();
            if (vm != null && vm.containsKey(JCR_TITLE)) {
                contentObject.add("title", vm.get(JCR_TITLE, String.class));
            }
            contentObject.add("path", resource.getPath());
            associatedContentArray.add(contentObject);
        }
        jsonObjectBuilder.add("associatedContent", associatedContentArray);
    }
    return jsonObjectBuilder.build().toString();
}

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}/* www.j  a  v  a2 s  . c  o m*/
 * @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;
    }

}

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

public void testVideoAnalysis(Exchange exchange) {

    logger.debug("New message retrieved");

    JsonObject jsonBody = MessageTools.getBody(exchange);

    JsonObjectBuilder job = Json.createObjectBuilder();

    for (Entry<String, JsonValue> entry : jsonBody.entrySet()) {
        job.add(entry.getKey(), entry.getValue());
    }//from ww  w.ja  v  a  2s .  c  o  m

    if (jsonBody != null) {

        String videoPath = jsonBody.getString("videoPath");
        logger.debug("Retrieved Video Path: " + videoPath);

        job.add("videoPath", videoPath);

        String method = jsonBody.getString("method");
        logger.debug("Retrieved VAM: " + method);

        job.add("method", method);

        // ONE video per call

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

            logger.debug("Executing Video Analysis Method: " + method);

            String result = service.video_request(videoPath, method);

            //System.out.println("VAM method "+method+" result:\n"+result);

            //  Video analysis service response
            String response = service.video_results(videoPath);

            logger.debug("VAM method " + method + " result:\n" + response);

            job.add("result", response);

        } else {

            logger.debug("Unable to process video, wrong request");

            job.add("result", "Unable to process video, wrong request");

        }

        exchange.getOut().setBody(job.build().toString());
        exchange.getOut().setHeaders(exchange.getIn().getHeaders());

    }

}

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

public void videoNDDAnalysis(Exchange exchange) {

    logger.debug("New message retrieved");

    JsonObject jsonBody = MessageTools.getBody(exchange);

    JsonObjectBuilder job = Json.createObjectBuilder();

    for (Entry<String, JsonValue> entry : jsonBody.entrySet()) {
        job.add(entry.getKey(), entry.getValue());
    }//  w ww.ja  v  a2  s  .co  m

    if (jsonBody != null) {

        //String videoPaths = getVideoPath(jsonBody);

        String videoPath = jsonBody.getString("videoPath");
        logger.debug("Retrieved Video Path: " + videoPath);

        job.add("videoPath", videoPath);

        //String method = jsonBody.getString("method");
        //System.out.println("Retrieved VAM: "+method);

        // ONE video per call

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

            logger.debug("Executing Video Analysis Method: Near Duplicate Detection");

            String response_tmp = service.video_ndd_request(videoPath);

            logger.debug("Video NDD Analysis method result:\n" + response_tmp);

            // call id is returned at the response 
            String callid;
            String[] callid_tmp = response_tmp.split("::");
            callid = callid_tmp[1].trim();
            String response = service.video_ndd_result(callid);

            logger.debug("Video NDD result:\n" + response);

            job.add("result", response);

        } else {

            logger.debug("Unable to process video, wrong request");

            job.add("result", "Unable to process video, wrong request");

        }

        exchange.getOut().setBody(job.build().toString());
        exchange.getOut().setHeaders(exchange.getIn().getHeaders());

    }

}

From source file:org.apache.nifi.reporting.SiteToSiteProvenanceReportingTask.java

static JsonObject serialize(final JsonBuilderFactory factory, final JsonObjectBuilder builder,
        final ProvenanceEventRecord event, final DateFormat df, final String componentName,
        final String hostname, final URL nifiUrl, final String applicationName, final String platform,
        final String nodeIdentifier) {
    addField(builder, "eventId", UUID.randomUUID().toString());
    addField(builder, "eventOrdinal", event.getEventId());
    addField(builder, "eventType", event.getEventType().name());
    addField(builder, "timestampMillis", event.getEventTime());
    addField(builder, "timestamp", df.format(event.getEventTime()));
    addField(builder, "durationMillis", event.getEventDuration());
    addField(builder, "lineageStart", event.getLineageStartDate());
    addField(builder, "details", event.getDetails());
    addField(builder, "componentId", event.getComponentId());
    addField(builder, "componentType", event.getComponentType());
    addField(builder, "componentName", componentName);
    addField(builder, "entityId", event.getFlowFileUuid());
    addField(builder, "entityType", "org.apache.nifi.flowfile.FlowFile");
    addField(builder, "entitySize", event.getFileSize());
    addField(builder, "previousEntitySize", event.getPreviousFileSize());
    addField(builder, factory, "updatedAttributes", event.getUpdatedAttributes());
    addField(builder, factory, "previousAttributes", event.getPreviousAttributes());

    addField(builder, "actorHostname", hostname);
    if (nifiUrl != null) {
        // TO get URL Prefix, we just remove the /nifi from the end of the URL. We know that the URL ends with
        // "/nifi" because the Property Validator enforces it
        final String urlString = nifiUrl.toString();
        final String urlPrefix = urlString.substring(0, urlString.length() - DESTINATION_URL_PATH.length());

        final String contentUriBase = urlPrefix + "/nifi-api/provenance-events/" + event.getEventId()
                + "/content/";
        final String nodeIdSuffix = nodeIdentifier == null ? "" : "?clusterNodeId=" + nodeIdentifier;
        addField(builder, "contentURI", contentUriBase + "output" + nodeIdSuffix);
        addField(builder, "previousContentURI", contentUriBase + "input" + nodeIdSuffix);
    }/*  ww w .  j a  v a2s  .  co  m*/

    addField(builder, factory, "parentIds", event.getParentUuids());
    addField(builder, factory, "childIds", event.getChildUuids());
    addField(builder, "transitUri", event.getTransitUri());
    addField(builder, "remoteIdentifier", event.getSourceSystemFlowFileIdentifier());
    addField(builder, "alternateIdentifier", event.getAlternateIdentifierUri());
    addField(builder, "platform", platform);
    addField(builder, "application", applicationName);

    return builder.build();
}

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

/**
 * Post the given result to a election to the bulletin board
 * @param result //  ww  w .ja  va 2  s.  co  m
 * result to be posted to the bulletin board
 */
public void postResult(ElectionResult result) {
    Election election = result.getElection();
    ElectionTopic topic = election.getTopic();
    HashMap<String, Integer> optionResults = result.getOptionCount();
    //translate the ElectionResult object into a json String
    JsonObjectBuilder jBuilder = Json.createObjectBuilder();

    //TODO get email address from certificate 
    jBuilder.add("author", "alice@bfh.ch");

    JsonArrayBuilder resultBuilder = Json.createArrayBuilder();

    JsonObjectBuilder topicBuilder = Json.createObjectBuilder();

    topicBuilder.add("topic", topic.getTitle());
    topicBuilder.add("pick", topic.getPick());

    JsonArrayBuilder optionsBuilder = Json.createArrayBuilder();

    for (String option : topic.getOptions()) {
        JsonObjectBuilder optionBuilder = Json.createObjectBuilder();
        optionBuilder.add("optTitle", option);
        optionBuilder.add("count", optionResults.get(option));
        optionsBuilder.add(optionBuilder);
    }
    topicBuilder.add("options", optionsBuilder);

    resultBuilder.add(topicBuilder);

    jBuilder.add("result", resultBuilder);
    JsonArrayBuilder ballotsBuilder = Json.createArrayBuilder();
    for (Ballot ballot : result.getBallots()) {
        JsonObjectBuilder ballotBuilder = Json.createObjectBuilder();
        //Translate ballot object into a json string 
        JsonArrayBuilder ballotOptionsBuilder = Json.createArrayBuilder();
        for (String option : ballot.getSelectedOptions()) {
            ballotOptionsBuilder.add(option);
        }
        ballotBuilder.add("id", ballot.getId());
        ballotBuilder.add("e", ballotOptionsBuilder);
        ballotBuilder.add("valid", ballot.isValid());
        ballotBuilder.add("reason", ballot.getReason());

        ballotsBuilder.add(ballotBuilder);
    }

    jBuilder.add("ballots", ballotsBuilder);

    JsonObject model = jBuilder.build();

    //sign json string 
    SignatureController signController = new SignatureController();
    JsonObject signedModel = null;

    try {
        signedModel = signController.signJson(model);
    } catch (Exception ex) {
        Logger.getLogger(CommunicationController.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        //post JWS with the result to the bulletin board
        boolean requestOK = postJsonStringToURL(
                bulletinBoardUrl + "/elections/" + election.getId() + "/results", signedModel.toString(),
                false);
        if (requestOK) {
            System.out.println("Results posted!");
        } else {
            System.out.println("Was not able to post Results! Did not receive expected http 200 status.");
        }
    } catch (IOException ex) {
        System.out.println("Was not able to post Results! IOException");
    }

}

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  www.j av  a2s.c  om*/
    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:org.hyperledger.fabric_ca.sdk.HFCAClient.java

/**
 * Generate certificate revocation list.
 *
 * @param registrar     admin user configured in CA-server
 * @param revokedBefore Restrict certificates returned to revoked before this date if not null.
 * @param revokedAfter  Restrict certificates returned to revoked after this date if not null.
 * @param expireBefore  Restrict certificates returned to expired before this date if not null.
 * @param expireAfter   Restrict certificates returned to expired after this date if not null.
 * @throws InvalidArgumentException//from  w  w w  . j av a  2  s .  com
 */

public String generateCRL(User registrar, Date revokedBefore, Date revokedAfter, Date expireBefore,
        Date expireAfter) throws InvalidArgumentException, GenerateCRLException {

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

    if (registrar == null) {
        throw new InvalidArgumentException("registrar is not set");
    }

    try {
        setUpSSL();

        //---------------------------------------
        JsonObjectBuilder factory = Json.createObjectBuilder();
        if (revokedBefore != null) {
            factory.add("revokedBefore", Util.dateToString(revokedBefore));
        }
        if (revokedAfter != null) {
            factory.add("revokedAfter", Util.dateToString(revokedAfter));
        }
        if (expireBefore != null) {
            factory.add("expireBefore", Util.dateToString(expireBefore));
        }
        if (expireAfter != null) {
            factory.add("expireAfter", Util.dateToString(expireAfter));
        }
        if (caName != null) {
            factory.add(HFCAClient.FABRIC_CA_REQPROP, caName);
        }

        JsonObject jsonObject = factory.build();

        StringWriter stringWriter = new StringWriter();
        JsonWriter jsonWriter = Json.createWriter(new PrintWriter(stringWriter));
        jsonWriter.writeObject(jsonObject);
        jsonWriter.close();
        String body = stringWriter.toString();

        //---------------------------------------

        // send revoke request
        JsonObject ret = httpPost(url + HFCA_GENCRL, body, registrar);

        return ret.getString("CRL");

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new GenerateCRLException(e.getMessage(), e);
    }
}

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

/**
 * Process before adding a term, key date group, holiday calendar or event
 *
 *///  w ww. ja va 2s  . c  o  m
@Override
public void processBeforeAddLine(ViewModel model, Object addLine, String collectionId, String collectionPath) {

    processAddBlankLines(model);

    if (addLine instanceof AcademicTermWrapper) {
        AcademicTermWrapper newLine = (AcademicTermWrapper) addLine;
        AcademicCalendarForm acalForm = (AcademicCalendarForm) model;
        //need to handle Term vs subTerm in different way
        try {
            if (newLine.getTermType() != null && !StringUtils.isBlank(newLine.getTermType())) {
                TypeInfo termType = getAcalService().getTermType(newLine.getTermType(), createContextInfo());
                // check if term is subterm vs parent term
                getParentTermType(newLine);

                if (newLine.getParentTerm() == null || StringUtils.isBlank(newLine.getParentTerm())) { //try to add a term
                    newLine.setTermNameForUI(termType.getName());
                    newLine.setName(termType.getName() + " "
                            + DateFormatters.DEFULT_YEAR_FORMATTER.format(newLine.getStartDate()));
                    newLine.setTypeInfo(termType);
                    newLine.setSubTerm(false);
                } else { //try to add a subterm
                    newLine.setTermNameForUI(termType.getName());
                    newLine.setName(termType.getName() + " "
                            + DateFormatters.DEFULT_YEAR_FORMATTER.format(newLine.getStartDate()));
                    newLine.setTypeInfo(termType);
                    newLine.setSubTerm(true);
                    AcademicTermWrapper parentTermWrapper = getParentTermInForm(newLine.getParentTerm(),
                            acalForm.getTermWrapperList());
                    if (parentTermWrapper != null) {
                        populateParentTermToSubterm(parentTermWrapper, newLine);
                    }
                    parentTermWrapper.setHasSubterm(true);
                    parentTermWrapper.getSubterms().add(newLine);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    } else if (addLine instanceof KeyDatesGroupWrapper) {
        KeyDatesGroupWrapper group = (KeyDatesGroupWrapper) addLine;
        if (StringUtils.isNotEmpty(group.getKeyDateGroupType())) {
            try {
                TypeInfo termType = getTypeInfo(group.getKeyDateGroupType());
                group.setKeyDateGroupNameUI(termType.getName());
                group.setTypeInfo(termType);
                KeyDateWrapper keyDate = new KeyDateWrapper();
                group.getKeydates().add(keyDate);
                ((AcademicCalendarForm) model).getAddedCollectionItems().add(keyDate);

                //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());
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    } else if (addLine instanceof HolidayCalendarInfo) {
        HolidayCalendarInfo inputLine = (HolidayCalendarInfo) addLine;
        try {
            System.out.println("HC id =" + inputLine.getId());

            HolidayCalendarInfo exists = getAcalService().getHolidayCalendar(inputLine.getId(),
                    createContextInfo());

            inputLine.setName(exists.getName());
            inputLine.setId(exists.getId());
            inputLine.setTypeKey(exists.getTypeKey());
            inputLine.setAdminOrgId(exists.getAdminOrgId());
            inputLine.setStartDate(exists.getStartDate());
            inputLine.setEndDate(exists.getEndDate());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    } else if (addLine instanceof HolidayCalendarWrapper) {
        HolidayCalendarWrapper inputLine = (HolidayCalendarWrapper) addLine;
        List<HolidayWrapper> holidays = new ArrayList<HolidayWrapper>();
        try {
            String holidayCalendarId = inputLine.getId();
            if (!StringUtils.isEmpty(holidayCalendarId)) {
                HolidayCalendarInfo hcInfo = getAcalService().getHolidayCalendar(inputLine.getId(),
                        createContextInfo());
                inputLine.setHolidayCalendarInfo(hcInfo);
                inputLine.setAdminOrgName(AcalCommonUtils.getAdminOrgNameById(hcInfo.getAdminOrgId()));
                StateInfo hcState = getAcalService().getHolidayCalendarState(hcInfo.getStateKey(),
                        createContextInfo());
                inputLine.setStateName(hcState.getName());
                List<HolidayInfo> holidayInfoList = getAcalService()
                        .getHolidaysForHolidayCalendar(hcInfo.getId(), createContextInfo());
                for (HolidayInfo holidayInfo : holidayInfoList) {
                    HolidayWrapper holiday = new HolidayWrapper(holidayInfo);
                    TypeInfo typeInfo = getAcalService().getHolidayType(holidayInfo.getTypeKey(),
                            createContextInfo());
                    holiday.setTypeName(typeInfo.getName());
                    holidays.add(holiday);
                }
                inputLine.setHolidays(holidays);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    } else if (addLine instanceof HolidayWrapper) {
        HolidayWrapper holiday = (HolidayWrapper) addLine;
        try {
            holiday.setTypeName(getTypeInfo(holiday.getTypeKey()).getName());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (!AcalCommonUtils.isValidDateRange(holiday.getStartDate(), holiday.getEndDate())) {
            GlobalVariables.getMessageMap().putWarningForSectionId("KS-HolidayCalendar-HolidaySection",
                    CalendarConstants.MessageKeys.ERROR_INVALID_DATE_RANGE, holiday.getTypeName(),
                    AcalCommonUtils.formatDate(holiday.getStartDate()),
                    AcalCommonUtils.formatDate(holiday.getEndDate()));
        }
    } else {
        super.processBeforeAddLine(model, addLine, collectionId, collectionPath);
    }
}

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

/**
 * Converts the given election object to a Json String. The Json string is then signed.
 * The resulting JWS gets posted to the bulletin board
 * @param election// ww  w.j  av a 2s  .com
 * election object to be posted to the bulletin board
 */
public void postElection(Election election) {
    JsonObjectBuilder jBuilder = Json.createObjectBuilder();
    DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    //Add Header information to the json object
    //TODO get email address from certificate 
    jBuilder.add("author", "alice@bfh.ch");
    jBuilder.add("electionTitle", election.getTitle());
    jBuilder.add("beginDate", election.getStartDate().format(format));
    jBuilder.add("endDate", election.getEndDate().format(format));
    //toDo: get AppVersion dynamically from build 
    jBuilder.add("appVersion", "0.15");

    jBuilder.add("coefficients", election.getCredentialPolynomialString());
    jBuilder.add("electionGenerator", election.getH_HatString());

    //Add votingTopic to the Json Object
    JsonObjectBuilder votingTopicBuilder = Json.createObjectBuilder();
    votingTopicBuilder.add("topic", election.getTopic().getTitle());
    votingTopicBuilder.add("pick", election.getTopic().getPick());

    JsonArrayBuilder optionsBuilder = Json.createArrayBuilder();
    for (String option : election.getTopic().getOptions()) {
        optionsBuilder.add(option);
    }
    votingTopicBuilder.add("options", optionsBuilder);

    jBuilder.add("votingTopic", votingTopicBuilder);

    //Add the list of selected Voters to the Json object
    JsonArrayBuilder votersBuilder = Json.createArrayBuilder();

    for (Voter voter : election.getVoterList()) {
        JsonObjectBuilder voterBuilder = Json.createObjectBuilder();
        voterBuilder.add("email", voter.getEmail());
        voterBuilder.add("publicCredential", voter.getPublicCredential());
        voterBuilder.add("appVersion", voter.getAppVersion());

        votersBuilder.add(voterBuilder);
    }

    jBuilder.add("voters", votersBuilder);

    JsonObject model = jBuilder.build();
    //finished Json gets singed
    SignatureController signController = new SignatureController();
    JsonObject signedModel = null;

    try {
        signedModel = signController.signJson(model);
    } catch (Exception ex) {
        Logger.getLogger(CommunicationController.class.getName()).log(Level.SEVERE, null, ex);
    }

    //JWS gets posted to the bulletin board
    try {
        boolean requestOK = postJsonStringToURL(bulletinBoardUrl + "/elections", signedModel.toString(), false);
        if (requestOK) {
            System.out.println("Election posted!");
        } else {
            System.out.println("Was not able to post Election! Did not receive expected http 200 status.");
        }
    } catch (IOException ex) {
        System.out.println("Was not able to post Election! IOException");
    }

}