List of usage examples for javax.json Json createObjectBuilder
public static JsonObjectBuilder createObjectBuilder()
From source file:io.hops.hopsworks.api.jobs.JobService.java
@GET @Path("/getLogByJobId/{jobId}/{submissionTime}/{type}") @Produces(MediaType.APPLICATION_JSON)//from ww w. ja v a 2s .com @AllowedProjectRoles({ AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST }) public Response getLogByJobId(@PathParam("jobId") Integer jobId, @PathParam("submissionTime") String submissionTime, @PathParam("type") String type) throws GenericException, JobException { if (jobId == null || jobId <= 0) { throw new IllegalArgumentException("jobId must be a non-null positive integer number."); } if (submissionTime == null) { throw new IllegalArgumentException("submissionTime was not provided."); } Jobs job = jobFacade.find(jobId); if (job == null) { throw new JobException(RESTCodes.JobErrorCode.JOB_NOT_FOUND, Level.FINE, "JobId:" + jobId); } SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy"); Date date; try { date = sdf.parse(submissionTime); } catch (ParseException ex) { throw new GenericException(RESTCodes.GenericErrorCode.INCOMPLETE_REQUEST, Level.WARNING, "Cannot get log. Incorrect submission time. Error offset:" + ex.getErrorOffset(), ex.getMessage(), ex); } Execution execution = exeFacade.findByJobIdAndSubmissionTime(date, job); if (execution == null) { throw new JobException(RESTCodes.JobErrorCode.JOB_EXECUTION_NOT_FOUND, Level.FINE, "JobId " + jobId); } if (!execution.getState().isFinalState()) { throw new JobException(RESTCodes.JobErrorCode.JOB_EXECUTION_INVALID_STATE, Level.FINE, "Job still running."); } if (!execution.getJob().getProject().equals(this.project)) { throw new JobException(RESTCodes.JobErrorCode.JOB_ACCESS_ERROR, Level.FINE, "Requested execution does not belong to a job of project: " + project.getName()); } JsonObjectBuilder arrayObjectBuilder = Json.createObjectBuilder(); DistributedFileSystemOps dfso = null; try { dfso = dfs.getDfsOps(); readLog(execution, type, dfso, arrayObjectBuilder); } catch (IOException ex) { LOGGER.log(Level.SEVERE, null, ex); } finally { if (dfso != null) { dfso.close(); } } return noCacheResponse.getNoCacheResponseBuilder(Response.Status.OK).entity(arrayObjectBuilder.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);//ww w . ja v a 2 s . co 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.kuali.student.enrollment.class2.acal.service.impl.AcademicCalendarViewHelperServiceImpl.java
/** * Process before adding a term, key date group, holiday calendar or event * */// w w w . j a va2 s . c om @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); } }