List of usage examples for javax.json JsonObjectBuilder add
JsonObjectBuilder add(String name, JsonArrayBuilder builder);
From source file:org.kuali.student.ap.coursesearch.service.impl.CourseDetailsViewHelperServiceImpl.java
/** * @see org.kuali.student.ap.coursesearch.service.CourseDetailsViewHelperService#createFilterValidRegGroupsEvent *///from w w w. j a v a2 s . com @Override public JsonObjectBuilder createFilterValidRegGroupsEvent(String termId, String courseOfferingCode, String formatOfferingId, List<String> regGroups, JsonObjectBuilder eventList, Map<Object, Object> additionalRestrictions) { JsonObjectBuilder filterEvent = Json.createObjectBuilder(); filterEvent.add("termId", termId.replace(".", "-")); filterEvent.add("courseOfferingCode", courseOfferingCode); filterEvent.add("formatOfferingId", formatOfferingId); // Deconstruct reg groups into list of AO and FO ids List<String> validFormatOfferings = new ArrayList<String>(); List<String> validActivities = new ArrayList<String>(); boolean singleRegGroupIdentified = false; for (String id : regGroups) { List<String> activityIds = new ArrayList<>(); List<String> formatIds = new ArrayList<>(); try { SearchRequestInfo request = new SearchRequestInfo( CourseSearchConstants.KSAP_COURSE_SEARCH_AO_IDS_BY_OFFERED_REG_GROUP_ID_KEY); request.addParam(CourseSearchConstants.SearchParameters.REG_GROUP_ID, id); List<SearchResultRowInfo> rows = KsapFrameworkServiceLocator.getSearchService() .search(request, KsapFrameworkServiceLocator.getContext().getContextInfo()).getRows(); boolean hasSelectedActivities = false; for (SearchResultRowInfo row : rows) { String activityId = KsapHelperUtil.getCellValue(row, CourseSearchConstants.SearchResultColumns.ACTIVITY_OFFERING_ID); activityIds.add(activityId); //Determine if any activities of a single reg group have been selected if (regGroups.size() == 1 && additionalRestrictions != null && additionalRestrictions.get("selectedActivities") != null && ((List<String>) additionalRestrictions.get("selectedActivities")) .contains(activityId)) singleRegGroupIdentified = true; } request = new SearchRequestInfo( CourseSearchConstants.KSAP_COURSE_SEARCH_FO_IDS_BY_OFFERED_REG_GROUP_ID_KEY); request.addParam(CourseSearchConstants.SearchParameters.REG_GROUP_ID, id); rows = KsapFrameworkServiceLocator.getSearchService() .search(request, KsapFrameworkServiceLocator.getContext().getContextInfo()).getRows(); for (SearchResultRowInfo row : rows) { formatIds.add(KsapHelperUtil.getCellValue(row, CourseSearchConstants.SearchResultColumns.FORMAT_OFFERING_ID)); } } catch (InvalidParameterException e) { throw new IllegalArgumentException("Lui Service lookup error", e); } catch (MissingParameterException e) { throw new IllegalArgumentException("Lui Service lookup error", e); } catch (OperationFailedException e) { throw new IllegalArgumentException("Lui Service lookup error", e); } catch (PermissionDeniedException e) { throw new IllegalArgumentException("Lui Service lookup error", e); } if (activityIds != null && !activityIds.isEmpty()) { validActivities.addAll(activityIds); } if (formatIds != null && !formatIds.isEmpty()) { validFormatOfferings.addAll(formatIds); } } //Send single regGroupId identified (i.e. selected) event if (singleRegGroupIdentified) { try { filterEvent.add("regGroupId", KSCollectionUtils.getRequiredZeroElement(regGroups)); } catch (OperationFailedException e) { throw new IllegalArgumentException("Failure retrieving registration group", e); } } else { filterEvent.add("regGroupId", ""); } // Create json array of valid activity ids and add it to event JsonArrayBuilder activities = Json.createArrayBuilder(); for (String activity : validActivities) { activities.add(activity); } filterEvent.add("activities", activities); // Create json array of valid format ids and add it to event JsonArrayBuilder formats = Json.createArrayBuilder(); for (String format : validFormatOfferings) { formats.add(format); } filterEvent.add("formatOfferings", formats); eventList.add("FILTER_COURSE_OFFERING", filterEvent); return eventList; }
From source file:io.hops.hopsworks.api.jobs.JobService.java
/** * Get the log information related to a job. The return value is a JSON * object, with format logset=[{"time":"JOB * EXECUTION TIME"}, {"log":"INFORMATION LOG"}, {"err":"ERROR LOG"}] * <p>/*w w w . ja v a2 s.c o m*/ * @param jobId * @param sc * @param req * @return */ @GET @Path("/{jobId}/showlog") @Produces(MediaType.APPLICATION_JSON) @AllowedProjectRoles({ AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST }) public Response getLogInformation(@PathParam("jobId") int jobId, @Context SecurityContext sc, @Context HttpServletRequest req) { JsonObjectBuilder builder = Json.createObjectBuilder(); JsonArrayBuilder arrayBuilder = Json.createArrayBuilder(); List<Execution> executionHistory = exeFacade.findbyProjectAndJobId(project, jobId); JsonObjectBuilder arrayObjectBuilder; if (executionHistory != null && !executionHistory.isEmpty()) { for (Execution e : executionHistory) { arrayObjectBuilder = Json.createObjectBuilder(); arrayObjectBuilder.add("jobId", e.getJob().getId()); arrayObjectBuilder.add("appId", e.getAppId() == null ? "" : e.getAppId()); arrayObjectBuilder.add("time", e.getSubmissionTime().toString()); arrayBuilder.add(arrayObjectBuilder); } } else { arrayObjectBuilder = Json.createObjectBuilder(); arrayObjectBuilder.add("jobId", ""); arrayObjectBuilder.add("appId", ""); arrayObjectBuilder.add("time", "Not available"); arrayObjectBuilder.add("log", "No log available"); arrayObjectBuilder.add("err", "No log available"); arrayBuilder.add(arrayObjectBuilder); } builder.add("logset", arrayBuilder); return noCacheResponse.getNoCacheResponseBuilder(Response.Status.OK).entity(builder.build()).build(); }
From source file:be.fedict.dcat.datagovbe.Drupal.java
/** * Check if node or translations exist on Drupal site. * //from www . j a va 2 s.c om * @param builder * @param id * @param lang * @return */ private String checkExistsTrans(JsonObjectBuilder builder, String id, String lang) { String node = checkExists(id, lang); // Exists in another language ? if (node.isEmpty()) { String lowlang = ""; int lownode = Integer.MAX_VALUE; for (String otherlang : langs) { if (!otherlang.equals(lang)) { String othernode = checkExists(id, otherlang); if (!othernode.isEmpty()) { int n = Integer.parseInt(othernode); // Node with lowest ID is source if (n < lownode) { lownode = n; lowlang = otherlang; } } } } if (!lowlang.isEmpty()) { builder.add(Drupal.SOURCE, Json.createObjectBuilder().add(lowlang, lownode)); } } return node; }
From source file:be.fedict.dcat.datagovbe.Drupal.java
/** * Add DCAT datasets//from w ww. java 2 s . c o m * * @param builder * @param uris * @param lang * @throws RepositoryException */ private void addDists(JsonObjectBuilder builder, List<String> uris, String lang) throws RepositoryException { HashSet<String> accesses = new HashSet<>(); HashSet<String> downloads = new HashSet<>(); HashSet<String> rights = new HashSet<>(); HashSet<String> types = new HashSet<>(); for (String uri : uris) { Map<IRI, ListMultimap<String, String>> dist = store.queryProperties(store.getURI(uri)); if (hasLang(dist, lang)) { // Data.gov.be displays this information as fields on dataset // not on distribution. accesses.add(getLink(dist, DCAT.ACCESS_URL)); downloads.add(getLink(dist, DCAT.DOWNLOAD_URL)); rights.add(getLink(dist, DCTERMS.RIGHTS)); types.add(getOne(dist, DATAGOVBE.MEDIA_TYPE, "")); builder.add(Drupal.FLD_LICENSE, arrayTermsJson(dist, DATAGOVBE.LICENSE)); } } // remove duplicate links downloads.removeAll(accesses); rights.removeAll(accesses); builder.add(Drupal.FLD_DETAILS, urlArrayJson(accesses)).add(Drupal.FLD_LINKS, urlArrayJson(downloads)) .add(Drupal.FLD_CONDITIONS, urlArrayJson(rights)).add(Drupal.FLD_FORMAT, arrayTermsJson(types)); }
From source file:io.hops.hopsworks.api.jobs.JobService.java
/** * Get all the jobs in this project that have a running execution. The return * value is a JSON object, where each job * id is a key and the corresponding boolean indicates whether the job is * running or not./*from w ww .j ava2s . c om*/ * <p/> * @param sc * @param req * @return */ @GET @Path("/running") @Produces(MediaType.APPLICATION_JSON) @AllowedProjectRoles({ AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST }) public Response getConfigurationTemplate(@Context SecurityContext sc, @Context HttpServletRequest req) { List<Jobs> running = jobFacade.getRunningJobs(project); List<Jobs> allJobs = jobFacade.findForProject(project); JsonObjectBuilder builder = Json.createObjectBuilder(); for (Jobs desc : allJobs) { try { List<Execution> jobExecutions = exeFacade.findForJob(desc); if (jobExecutions != null && jobExecutions.isEmpty() == false) { Execution execution = jobExecutions.get(0); builder.add(desc.getId().toString(), Json.createObjectBuilder().add("running", false) .add("state", execution.getState().toString()) .add("finalStatus", execution.getFinalStatus().toString()) .add("progress", execution.getProgress()) .add("duration", execution.getExecutionDuration()) .add("submissiontime", execution.getSubmissionTime().toString())); } } catch (ArrayIndexOutOfBoundsException e) { LOGGER.log(Level.WARNING, "No execution was found: {0}", e.getMessage()); } } for (Jobs desc : running) { try { Execution execution = exeFacade.findForJob(desc).get(0); long executiontime = System.currentTimeMillis() - execution.getSubmissionTime().getTime(); //not given appId (not submited yet) if (execution.getAppId() == null && executiontime > 60000l * 5) { exeFacade.updateState(execution, JobState.INITIALIZATION_FAILED); exeFacade.updateFinalStatus(execution, JobFinalStatus.FAILED); continue; } String trackingUrl = appAttemptStateFacade.findTrackingUrlByAppId(execution.getAppId()); builder.add(desc.getId().toString(), Json.createObjectBuilder().add("running", true) .add("state", execution.getState().toString()) .add("finalStatus", execution.getFinalStatus().toString()) .add("progress", execution.getProgress()).add("duration", execution.getExecutionDuration()) .add("submissiontime", execution.getSubmissionTime().toString()).add("url", trackingUrl)); } catch (ArrayIndexOutOfBoundsException e) { LOGGER.log(Level.WARNING, "No execution was found: {0}", e.getMessage()); } } return noCacheResponse.getNoCacheResponseBuilder(Response.Status.OK).entity(builder.build()).build(); }
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);/*from ww w . j a v a 2 s .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
/** * 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 .ja v a 2 s. c o m*/ */ 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.hyperledger.fabric_ca.sdk.HFCAClient.java
/** * Return information on the Fabric Certificate Authority. * No credentials are needed for this API. * * @return {@link HFCAInfo}// w w w .j av a 2 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:be.fedict.dcat.datagovbe.Drupal.java
/** * Add a dataset to Drupal form/*from w ww . ja v a 2 s .co m*/ * * @param builder * @param dataset * @param lang * @throws RepositoryException */ private void addDataset(JsonObjectBuilder builder, Map<IRI, ListMultimap<String, String>> dataset, String lang) throws RepositoryException { String id = getOne(dataset, DCTERMS.IDENTIFIER, ""); String title = stripTags(getOne(dataset, DCTERMS.TITLE, lang)); // Just copy the title if description is empty String desc = getOne(dataset, DCTERMS.DESCRIPTION, lang); desc = (desc.isEmpty()) ? title : stripTags(desc); // Max size for Drupal title if (title.length() > Drupal.LEN_TITLE) { logger.warn("Title {} too long", title); title = ellipsis(title, Drupal.LEN_TITLE); } Date modif = getModif(dataset); String keywords = getKeywords(dataset, lang); // Max size for Drupal keywords if (keywords.length() > Drupal.LEN_KEYWORDS) { logger.warn("Keywords {} too long", keywords); keywords = ellipsis(keywords, Drupal.LEN_KEYWORDS); } Map<IRI, ListMultimap<String, String>> publ = getPublisher(dataset); JsonArrayBuilder emails = fieldArrayJson(getDatasetMails(dataset)); JsonArrayBuilder orgs = fieldArrayJson(getDatasetOrgs(dataset, lang)); builder.add(Drupal.TYPE, Drupal.TYPE_DATA).add(Drupal.LANGUAGE, lang) .add(Drupal.AUTHOR, Json.createObjectBuilder().add(Drupal.ID, userid)).add(Drupal.TITLE, title) .add(Drupal.BODY, Json.createObjectBuilder().add(Drupal.VALUE, desc).add(Drupal.SUMMARY, "") .add(Drupal.FORMAT, Drupal.FORMAT_HTML)) .add(Drupal.FLD_UPSTAMP, modif.getTime() / 1000L) .add(Drupal.FLD_FREQ, arrayTermsJson(dataset, DATAGOVBE.FREQ)) .add(Drupal.FLD_CAT, arrayTermsJson(dataset, DATAGOVBE.THEME)) .add(Drupal.FLD_GEO, arrayTermsJson(dataset, DATAGOVBE.SPATIAL)) .add(Drupal.FLD_PUBLISHER, arrayTermsJson(publ, DATAGOVBE.ORG)).add(Drupal.FLD_ORG, orgs) .add(Drupal.FLD_MAIL, emails).add(Drupal.FLD_KEYWORDS, keywords).add(Drupal.FLD_ID, id); String fromtill = getOne(dataset, DCTERMS.TEMPORAL, ""); if (fromtill.isEmpty()) { builder.addNull(Drupal.FLD_TIME); } else { builder.add(Drupal.FLD_TIME, fromtill); } }
From source file:io.hops.hopsworks.api.jobs.JobService.java
private void readLog(Execution e, String type, DistributedFileSystemOps dfso, JsonObjectBuilder arrayObjectBuilder) throws IOException { String message;// w w w .j ava 2 s.c o m String stdPath; String path = (type.equals("log") ? e.getStdoutPath() : e.getStderrPath()); String retry = (type.equals("log") ? "retriableOut" : "retriableErr"); boolean status = (type.equals("log") ? e.getFinalStatus().equals(JobFinalStatus.SUCCEEDED) : true); String hdfsPath = "hdfs://" + path; if (path != null && !path.isEmpty() && dfso.exists(hdfsPath)) { if (dfso.listStatus(new org.apache.hadoop.fs.Path(hdfsPath))[0].getLen() > settings .getJobLogsDisplaySize()) { stdPath = path.split(this.project.getName())[1]; int fileIndex = stdPath.lastIndexOf("/"); String stdDirPath = stdPath.substring(0, fileIndex); arrayObjectBuilder.add(type, "Log is too big to display. Please retrieve it by clicking "); arrayObjectBuilder.add(type + "Path", "/project/" + this.project.getId() + "/datasets" + stdDirPath); } else { try (InputStream input = dfso.open(hdfsPath)) { message = IOUtils.toString(input, "UTF-8"); } arrayObjectBuilder.add(type, message.isEmpty() ? "No information." : message); if (message.isEmpty() && e.getState().isFinalState() && e.getAppId() != null && status) { arrayObjectBuilder.add(retry, "true"); } } } else { arrayObjectBuilder.add(type, "No log available"); if (e.getState().isFinalState() && e.getAppId() != null && status) { arrayObjectBuilder.add(retry, "true"); } } }