List of usage examples for com.fasterxml.jackson.core JsonProcessingException getMessage
@Override
public String getMessage()
From source file:com.discover.cls.processors.cls.AttributesToTypedJSON.java
@Override public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException { final FlowFile original = session.get(); if (original == null) { return;/*from w w w . jav a2s.c om*/ } final Map<String, String> atrList = buildAttributesMapForFlowFile(original, context.getProperty(ATTRIBUTES_LIST).evaluateAttributeExpressions(original).getValue(), context.getProperty(INCLUDE_CORE_ATTRIBUTES).asBoolean(), context.getProperty(NULL_VALUE_FOR_EMPTY_STRING).asBoolean()); final Map<String, Object> typedList = new LinkedHashMap<>(); try { for (Map.Entry<String, String> attribute : atrList.entrySet()) { if (isCoreAttribute(attribute)) { typedList.put(attribute.getKey(), attribute.getValue()); } else { try { if (attribute.getValue() != null) { JsonNode node = OBJECT_MAPPER.readTree(attribute.getValue().getBytes()); Object o = OBJECT_MAPPER.treeToValue(node, Object.class); typedList.put(attribute.getKey(), o); } else { typedList.put(attribute.getKey(), null); } } catch (JsonProcessingException e) { // Any JSON that can't be parsed is stored as a string. typedList.put(attribute.getKey(), attribute.getValue()); } } } switch (context.getProperty(DESTINATION).getValue()) { case DESTINATION_ATTRIBUTE: FlowFile atFlowfile = session.putAttribute(original, JSON_ATTRIBUTE_NAME, OBJECT_MAPPER.writeValueAsString(typedList)); session.transfer(atFlowfile, REL_SUCCESS); break; case DESTINATION_CONTENT: FlowFile conFlowFile = session.write(original, new StreamCallback() { @Override public void process(InputStream in, OutputStream out) throws IOException { try (OutputStream outputStream = new BufferedOutputStream(out)) { outputStream.write(OBJECT_MAPPER.writeValueAsBytes(typedList)); } } }); conFlowFile = session.putAttribute(conFlowFile, CoreAttributes.MIME_TYPE.key(), APPLICATION_JSON); session.transfer(conFlowFile, REL_SUCCESS); break; } } catch (IOException e) { getLogger().error(e.getMessage()); session.transfer(original, REL_FAILURE); } }
From source file:ac.ucy.cs.spdx.service.Compatibility.java
@POST @Path("/node/") @Consumes(MediaType.TEXT_PLAIN)//www. j a v a2 s . c o m @Produces(MediaType.APPLICATION_JSON) public String addNode(String jsonString) { ObjectMapper mapper = new ObjectMapper(); JsonNode licenseNode = null; try { licenseNode = mapper.readTree(jsonString); } catch (JsonProcessingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } ArrayList<String> licenses = new ArrayList<String>(); String nodeIdentifier = licenseNode.get("nodeIdentifier").toString(); nodeIdentifier = nodeIdentifier.substring(1, nodeIdentifier.length() - 1); String nodeCategory = licenseNode.get("nodeCategory").toString(); nodeCategory = nodeCategory.substring(1, nodeCategory.length() - 1); Category category = Category.UNCATEGORIZED; if (nodeCategory == "PERMISSIVE") { category = Category.PERMISSIVE; } else if (nodeCategory == "WEAK_COPYLEFT") { category = Category.WEAK_COPYLEFT; } else if (nodeCategory == "STRONG_COPYLEFT") { category = Category.STRONG_COPYLEFT; } else { category = Category.UNCATEGORIZED; } JsonNode licensesJSON = licenseNode.get("nodelicenses"); for (int i = 0; i < licensesJSON.size(); i++) { String licenseId = licensesJSON.get(i).get("identifier").toString(); licenseId = licenseId.substring(1, licenseId.length() - 1); licenses.add(licenseId); } try { LicenseGraph.addLicenseNode(nodeIdentifier, category, licenses.toArray(new String[licenses.size()])); } catch (LicenseNodeAlreadyExistsException e) { e.printStackTrace(); return "{\"status\":\"failure\",\"message\":\"" + e.getMessage() + "\"}"; } LicenseGraph.exportGraph(); return "{\"status\":\"success\",\"message\":\"" + nodeIdentifier + " added in the system.\"}";// {"nodeIdentifier":"Caldera","nodeCategory":"PERMISSIVE","nodelicenses":[{"identifier":"Caldera"}]} }
From source file:com.unboundid.scim2.common.GenericScimResource.java
private static Date getDateForString(final String dateString) throws ScimException { try {/*from w w w .j a v a 2s .c om*/ return JsonUtils.getObjectReader().forType(Date.class).readValue(dateString); } catch (JsonProcessingException ex) { throw new ServerErrorException(ex.getMessage()); } catch (IOException ex) { throw new ServerErrorException(ex.getMessage()); } }
From source file:controllers.core.RoadmapController.java
/** * Display the planning (gantt) of the current roadmap. * // w w w . j av a 2s. c o m * the list of portfolio entries depends of the current filter configuration * * the gantt view is construct as:<br/> * -for each portfolio entry we get its life cycle process and its last * planned dates (there is one date by milestone)<br/> * -for each phase of the life cycle process, we get its start milestone and * we find the corresponding planned date (that is the start date) from the * last planned dates. We do the same for the end milestone<br/> * -we display one interval (bar) by phase according to the computed start * and end dates (see just above) */ public Result viewPlanning() { try { // get the filter config String uid = getUserSessionManagerPlugin().getUserSessionId(ctx()); FilterConfig<PortfolioEntryListView> filterConfig = this.getTableProvider() .get().portfolioEntry.filterConfig.getCurrent(uid, request()); OrderBy<PortfolioEntry> orderBy = filterConfig.getSortExpression(); ExpressionList<PortfolioEntry> expressionList = PortfolioEntryDynamicHelper .getPortfolioEntriesViewAllowedAsQuery(filterConfig.getSearchExpression(), orderBy, getSecurityService()); // initiate the source items (gantt) List<SourceItem> items = new ArrayList<SourceItem>(); // compute the items (for each portfolio entry) for (PortfolioEntry portfolioEntry : expressionList.findList()) { // get the active life cycle process instance LifeCycleInstance processInstance = portfolioEntry.activeLifeCycleInstance; // get the roadmap phases of a process List<LifeCyclePhase> lifeCyclePhases = LifeCycleMilestoneDao .getLCPhaseRoadmapAsListByLCProcess(processInstance.lifeCycleProcess.id); if (lifeCyclePhases != null && !lifeCyclePhases.isEmpty()) { // get the last planned milestone instances List<PlannedLifeCycleMilestoneInstance> lastPlannedMilestoneInstances = LifeCyclePlanningDao .getPlannedLCMilestoneInstanceLastAsListByPE(portfolioEntry.id); if (lastPlannedMilestoneInstances != null && lastPlannedMilestoneInstances.size() > 0) { // transform the list of last planned milestone // instances to // a map Map<Long, PlannedLifeCycleMilestoneInstance> lastPlannedMilestoneInstancesAsMap = new HashMap<>(); for (PlannedLifeCycleMilestoneInstance plannedMilestoneInstance : lastPlannedMilestoneInstances) { lastPlannedMilestoneInstancesAsMap.put(plannedMilestoneInstance.lifeCycleMilestone.id, plannedMilestoneInstance); } /* * compute the common components for all phases */ // get the CSS class String cssClass = GANTT_DEFAULT_CSS_CLASS; PortfolioEntryReport report = portfolioEntry.lastPortfolioEntryReport; if (report != null && report.portfolioEntryReportStatusType != null) { cssClass = report.portfolioEntryReportStatusType.cssClass; } // create the source data value (used when clicking on a // phase) SourceDataValue sourceDataValue = new SourceDataValue( controllers.core.routes.PortfolioEntryController.overview(portfolioEntry.id).url(), portfolioEntry.getName(), portfolioEntry.getDescription(), views.html.modelsparts.display_actor.render(portfolioEntry.manager).body(), views.html.framework_views.parts.formats.display_list_of_values .render(portfolioEntry.portfolios, "display").body()); boolean isFirstLoop = true; for (LifeCyclePhase phase : lifeCyclePhases) { if (lastPlannedMilestoneInstancesAsMap.containsKey(phase.startLifeCycleMilestone.id) && lastPlannedMilestoneInstancesAsMap .containsKey(phase.endLifeCycleMilestone.id)) { // get the from date Date from = LifeCyclePlanningDao.getPlannedLCMilestoneInstanceAsPassedDate( lastPlannedMilestoneInstancesAsMap .get(phase.startLifeCycleMilestone.id).id); // get the to date Date to = LifeCyclePlanningDao.getPlannedLCMilestoneInstanceAsPassedDate( lastPlannedMilestoneInstancesAsMap.get(phase.endLifeCycleMilestone.id).id); if (from != null && to != null) { to = JqueryGantt.cleanToDate(from, to); // add gap for the from date if (phase.gapDaysStart != null && phase.gapDaysStart.intValue() > 0) { Calendar c = Calendar.getInstance(); c.setTime(from); c.add(Calendar.DATE, phase.gapDaysStart); from = c.getTime(); } // remove gap for the to date if (phase.gapDaysEnd != null && phase.gapDaysEnd.intValue() > 0) { Calendar c = Calendar.getInstance(); c.setTime(to); c.add(Calendar.DATE, -1 * phase.gapDaysEnd); to = c.getTime(); } String name = ""; if (isFirstLoop) { if (portfolioEntry.getGovernanceId() != null) { name += portfolioEntry.getGovernanceId() + " - "; } name += portfolioEntry.getName(); } SourceItem item = new SourceItem(name, ""); item.values.add(new SourceValue(from, to, "", phase.getName(), cssClass, sourceDataValue)); items.add(item); isFirstLoop = false; } } } } } } String source = ""; try { ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); source = ow.writeValueAsString(items); } catch (JsonProcessingException e) { Logger.error(e.getMessage()); } return ok(views.html.core.roadmap.roadmap_view_planning.render(source)); } catch (Exception e) { return ControllersUtils.logAndReturnUnexpectedError(e, log, getConfiguration(), getI18nMessagesPlugin()); } }
From source file:com.unboundid.scim2.common.GenericScimResource.java
private static String getStringForDate(final Date date) throws ScimException { try {//from ww w . j a v a 2s .co m return JsonUtils.getObjectWriter().writeValueAsString(date); } catch (JsonProcessingException ex) { // this really should not happen, but we will handle it and // translate to a SCIM exception just in case. throw new ServerErrorException(ex.getMessage()); } }
From source file:de.fraunhofer.iosb.ilt.sta.persistence.postgres.EntityInserter.java
/** * Sets both the geometry and location in the clause. * * @param <T> The type of the clause. * @param clause The insert or update clause to add to. * @param locationPath The path to the location column. * @param geomPath The path to the geometry column. * @param encodingType The encoding type. * @param location The location./*from w ww .ja v a2s .c o m*/ * @return The insert or update clause. */ private <T extends StoreClause> T insertGeometry(T clause, StringPath locationPath, GeometryPath<Geometry> geomPath, String encodingType, final Object location) { if ("application/vnd.geo+json".equalsIgnoreCase(encodingType)) { // TODO: Postgres does not support Feature. Object geoLocation = location; if (location instanceof Feature) { geoLocation = ((Feature) location).getGeometry(); } String geoJson; String locJson; try { geoJson = new GeoJsonSerializer().serialize(geoLocation); if (geoLocation == location) { locJson = geoJson; } else { locJson = new GeoJsonSerializer().serialize(location); } } catch (JsonProcessingException ex) { LOGGER.error("Failed to store.", ex); throw new IllegalArgumentException( "encoding specifies geoJson, but location not parsable as such."); } try { // geojson.jackson allows invalid polygons, geolatte catches those. new JsonMapper().fromJson(geoJson, Geometry.class); } catch (JsonException ex) { throw new IllegalArgumentException("Invalid geoJson: " + ex.getMessage()); } clause.set(geomPath, Expressions.template(Geometry.class, "ST_Force3D(ST_GeomFromGeoJSON({0}))", geoJson)); clause.set(locationPath, locJson); } else { String json; json = objectToJson(location); clause.setNull(geomPath); clause.set(locationPath, json); } return clause; }
From source file:controllers.core.PortfolioEntryPlanningController.java
/** * Display global gantt chart of the initiative. * // www . j av a2s . c o m * Life cycle phases of the process (with is_roadmap_phase = false)<br/> * Life cycle milestones (diamond)<br/> * Planning packages<br/> * Iterations<br/> * * Configuration:<br/> * -Display phases<br/> * -Display milestones<br/> * -Display packages<br/> * -Display iterations<br/> * * * @param id * the portfolio entry id */ @With(CheckPortfolioEntryExists.class) @Dynamic(IMafConstants.PORTFOLIO_ENTRY_DETAILS_DYNAMIC_PERMISSION) public Result overview(Long id) { // load the overview configuration from the user preference OverviewConfiguration conf = OverviewConfiguration.load(this.getPreferenceManagerPlugin()); // prepare the overview configuration form Form<OverviewConfiguration> overviewConfigurationForm = overviewConfigurationFormTemplate.fill(conf); // get the portfolioEntry PortfolioEntry portfolioEntry = PortfolioEntryDao.getPEById(id); // get the active life cycle process instance LifeCycleInstance processInstance = portfolioEntry.activeLifeCycleInstance; // get the last planned milestone instances List<PlannedLifeCycleMilestoneInstance> lastPlannedMilestoneInstances = LifeCyclePlanningDao .getPlannedLCMilestoneInstanceLastAsListByPE(portfolioEntry.id); // initiate the sortable collection SortableCollection<ComplexSortableObject> sortableCollection = new SortableCollection<>(); /** Life cycle phases of the process (with is_roadmap_phase = false) **/ if (conf.phases) { // get the all phases of a process List<LifeCyclePhase> lifeCyclePhases = LifeCycleMilestoneDao .getLCPhaseAsListByLCProcess(processInstance.lifeCycleProcess.id); if (lifeCyclePhases != null && !lifeCyclePhases.isEmpty() && lastPlannedMilestoneInstances != null && lastPlannedMilestoneInstances.size() > 0) { // get the CSS class String cssClass = "success"; // create the source data value SourceDataValue dataValue = new SourceDataValue( controllers.core.routes.PortfolioEntryGovernanceController.index(portfolioEntry.id).url(), null, null, null, null); // transform the list of last planned milestone instances to a // map Map<Long, PlannedLifeCycleMilestoneInstance> lastPlannedMilestoneInstancesAsMap = new HashMap<Long, PlannedLifeCycleMilestoneInstance>(); for (PlannedLifeCycleMilestoneInstance plannedMilestoneInstance : lastPlannedMilestoneInstances) { lastPlannedMilestoneInstancesAsMap.put(plannedMilestoneInstance.lifeCycleMilestone.id, plannedMilestoneInstance); } for (LifeCyclePhase phase : lifeCyclePhases) { if (lastPlannedMilestoneInstancesAsMap.containsKey(phase.startLifeCycleMilestone.id) && lastPlannedMilestoneInstancesAsMap.containsKey(phase.endLifeCycleMilestone.id)) { // get the from date Date from = LifeCyclePlanningDao.getPlannedLCMilestoneInstanceAsPassedDate( lastPlannedMilestoneInstancesAsMap.get(phase.startLifeCycleMilestone.id).id); // get the to date Date to = LifeCyclePlanningDao.getPlannedLCMilestoneInstanceAsPassedDate( lastPlannedMilestoneInstancesAsMap.get(phase.endLifeCycleMilestone.id).id); if (from != null && to != null) { to = JqueryGantt.cleanToDate(from, to); // add gap for the from date if (phase.gapDaysStart != null && phase.gapDaysStart.intValue() > 0) { Calendar c = Calendar.getInstance(); c.setTime(from); c.add(Calendar.DATE, phase.gapDaysStart); from = c.getTime(); } // remove gap for the to date if (phase.gapDaysEnd != null && phase.gapDaysEnd.intValue() > 0) { Calendar c = Calendar.getInstance(); c.setTime(to); c.add(Calendar.DATE, -1 * phase.gapDaysEnd); to = c.getTime(); } SourceItem item = new SourceItem(phase.getName(), null); item.values.add(new SourceValue(from, to, "", phase.getName(), cssClass, dataValue)); sortableCollection.addObject(new ComplexSortableObject(from, 1, phase.order != null ? phase.order : 0, item)); } } } } } /** Life cycle milestones (diamond) **/ if (conf.milestones && lastPlannedMilestoneInstances != null && lastPlannedMilestoneInstances.size() > 0) { // get the CSS class String cssClass = "diamond diamond-danger"; for (PlannedLifeCycleMilestoneInstance plannedMilestoneInstance : lastPlannedMilestoneInstances) { // create the source data value SourceDataValue dataValue = new SourceDataValue( controllers.core.routes.PortfolioEntryGovernanceController .viewMilestone(portfolioEntry.id, plannedMilestoneInstance.lifeCycleMilestone.id) .url(), null, null, null, null); // get the from date Date from = LifeCyclePlanningDao .getPlannedLCMilestoneInstanceAsPassedDate(plannedMilestoneInstance.id); // get the to date Date to = from; if (from != null) { SourceItem item = new SourceItem(plannedMilestoneInstance.lifeCycleMilestone.getShortName(), null); item.values.add(new SourceValue(from, to, "", "", cssClass, dataValue)); sortableCollection.addObject(new ComplexSortableObject(from, 2, 0, item)); } } } /** Planning packages **/ if (conf.packages) { for (PortfolioEntryPlanningPackage planningPackage : PortfolioEntryPlanningPackageDao .getPEPlanningPackageAsListByPE(portfolioEntry.id)) { // create the source data value SourceDataValue dataValue = new SourceDataValue( controllers.core.routes.PortfolioEntryPlanningController .viewPackage(portfolioEntry.id, planningPackage.id).url(), null, null, null, null); // get the from date Date from = planningPackage.startDate; // get the to date Date to = planningPackage.endDate; if (to != null) { String cssClass = null; if (from != null) { to = JqueryGantt.cleanToDate(from, to); cssClass = "warning"; } else { from = to; cssClass = "diamond diamond-warning"; } SourceItem item = new SourceItem(planningPackage.name, null); item.values.add(new SourceValue(from, to, "", planningPackage.name, cssClass, dataValue)); sortableCollection.addObject(new ComplexSortableObject(from, 5, 0, item)); } } } /** Iterations **/ if (conf.iterations) { for (Iteration iteration : IterationDAO.getIterationAllAsListByPE(portfolioEntry.id)) { SourceDataValue dataValue = new SourceDataValue( controllers.core.routes.PortfolioEntryDeliveryController .viewIteration(portfolioEntry.id, iteration.id).url(), null, null, null, null); // get the from date Date from = iteration.startDate; // get the to date Date to = iteration.endDate; if (to != null) { String cssClass = null; if (from != null) { to = JqueryGantt.cleanToDate(from, to); cssClass = "primary"; } else { from = to; cssClass = "diamond diamond-primary"; } SourceItem item = new SourceItem(iteration.name, null); item.values.add(new SourceValue(from, to, "", iteration.name, cssClass, dataValue)); sortableCollection.addObject(new ComplexSortableObject(from, 4, 0, item)); } } } /** construct the gantt **/ List<SourceItem> items = new ArrayList<SourceItem>(); for (ISortableObject sortableObject : sortableCollection.getSorted()) { Logger.debug(sortableObject.getSortableAttributesAsString()); SourceItem item = (SourceItem) sortableObject.getObject(); items.add(item); } String ganttSource = ""; try { ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); ganttSource = ow.writeValueAsString(items); } catch (JsonProcessingException e) { Logger.error(e.getMessage()); } return ok(views.html.core.portfolioentryplanning.overview.render(portfolioEntry, ganttSource, overviewConfigurationForm)); }
From source file:sg.ncl.MainController.java
@PostMapping("/update_experiment/{teamId}/{expId}") public String updateExperimentFormSubmit(@ModelAttribute("edit_experiment") Experiment2 editExperiment, BindingResult bindingResult, @PathVariable String teamId, @PathVariable String expId, RedirectAttributes redirectAttributes) throws WebServiceRuntimeException { // check max duration for errors if (bindingResult.hasErrors() || !editExperiment.getMaxDuration().toString().matches("\\d+")) { redirectAttributes.addFlashAttribute(MESSAGE, MAX_DURATION_ERROR); return REDIRECT_UPDATE_EXPERIMENT + teamId + "/" + expId; }/*from w w w . ja v a 2 s .c om*/ // get original experiment HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity response = restTemplate.exchange(properties.getExperiment(expId), HttpMethod.GET, request, String.class); Experiment2 experiment = extractExperiment(response.getBody().toString()); experiment.setNsFileContent(editExperiment.getNsFileContent()); experiment.setMaxDuration(editExperiment.getMaxDuration()); objectMapper.registerModule(new JavaTimeModule()); String jsonExperiment; try { jsonExperiment = objectMapper.writeValueAsString(experiment); } catch (JsonProcessingException e) { log.debug("update experiment convert to json error: {}", experiment); redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); return REDIRECT_UPDATE_EXPERIMENT + teamId + "/" + expId; } // identical endpoint as delete experiment but different HTTP method restTemplate.setErrorHandler(new MyResponseErrorHandler()); request = createHttpEntityWithBody(jsonExperiment); ResponseEntity updateExperimentResponse; try { updateExperimentResponse = restTemplate.exchange(properties.getDeleteExperiment(teamId, expId), HttpMethod.PUT, request, String.class); } catch (Exception e) { log.warn("Error connecting to experiment service to update experiment", e.getMessage()); redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); return REDIRECT_EXPERIMENTS; } String updateExperimentResponseBody = updateExperimentResponse.getBody().toString(); try { if (RestUtil.isError(updateExperimentResponse.getStatusCode())) { MyErrorResource error = objectMapper.readValue(updateExperimentResponseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); switch (exceptionState) { case NS_FILE_PARSE_EXCEPTION: case EXPERIMENT_MODIFY_EXCEPTION: log.warn("update experiment failed for Team: {}, Exp: {}", teamId, expId); redirectAttributes.addFlashAttribute(MESSAGE, "Error in parsing NS File"); redirectAttributes.addFlashAttribute("exp_output", error.getMessage()); break; case OBJECT_OPTIMISTIC_LOCKING_FAILURE_EXCEPTION: // do nothing log.info("update experiment database locking failure"); break; default: // do nothing break; } return REDIRECT_UPDATE_EXPERIMENT + teamId + "/" + expId; } else { // everything ok log.info("update experiment success for Team:{}, Exp: {}", teamId, expId); redirectAttributes.addFlashAttribute(EXPERIMENT_MESSAGE, getExperimentMessage(experiment.getName(), experiment.getTeamName()) + " has been modified. You may proceed to start the experiment."); return REDIRECT_EXPERIMENTS; } } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } }