List of usage examples for com.fasterxml.jackson.core JsonProcessingException getMessage
@Override
public String getMessage()
From source file:org.mitre.mpf.mvc.controller.JobController.java
@RequestMapping(value = { "/jobs-paged" }, method = RequestMethod.POST) @ResponseBody//from w w w .ja va 2s.c o m public String getJobStatusSessionFiltered( @RequestParam(value = "useSession", required = false) boolean useSession, @RequestParam(value = "draw", required = false) int draw, @RequestParam(value = "start", required = false) int start, @RequestParam(value = "length", required = false) int length, @RequestParam(value = "search", required = false) String search, @RequestParam(value = "sort", required = false) String sort) { log.debug("Params useSession:{} draw:{} start:{},length:{},search:{},sort:{} ", useSession, draw, start, length, search, sort); List<SingleJobInfo> jobInfoModels = getJobStatusVersionOne(null, useSession); Collections.reverse(jobInfoModels);//newest first //handle search if (search != null && search.length() > 0) { search = search.toLowerCase(); List<SingleJobInfo> search_results = new ArrayList<SingleJobInfo>(); for (int i = 0; i < jobInfoModels.size(); i++) { SingleJobInfo info = jobInfoModels.get(i); DateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm a"); //apply search to id,pipeline name, status, dates if (info.getJobId().toString().contains(search) || info.getPipelineName().toLowerCase().contains(search) || info.getJobStatus().toLowerCase().contains(search) || (info.getEndDate() != null && df.format(info.getEndDate()).toLowerCase().contains(search)) || (info.getStartDate() != null && df.format(info.getStartDate()).toLowerCase().contains(search))) { search_results.add(info); } } jobInfoModels = search_results; } int records_total = jobInfoModels.size(); int records_filtered = records_total;// Total records, after filtering (i.e. the total number of records after filtering has been applied - not just the number of records being returned for this page of data). //handle paging int end = start + length; end = (end > records_total) ? records_total : end; start = (start <= end) ? start : end; List<SingleJobInfo> jobInfoModelsFiltered = jobInfoModels.subList(start, end); //build json String error = null; String json = "[]"; ObjectMapper jsonMapper = new ObjectMapper(); try { json = jsonMapper.writeValueAsString(jobInfoModelsFiltered); } catch (JsonProcessingException e) { error = "Error converting Jobs List to JSON : " + e.getMessage(); log.error(error); } return "{\"draw\":" + draw + ",\"recordsTotal\":" + records_total + ",\"recordsFiltered\":" + records_filtered + ",\"error\":" + error + ",\"data\":" + json + "}"; }
From source file:com.servioticy.api.commons.data.SO.java
/** Create a new Service Object * * @param userId/*from w w w . ja v a2 s . c o m*/ * @param body */ public SO(String userId, String body) { UUID uuid = UUID.randomUUID(); // servioticy key = soId // TODO improve key and soId generation this.userId = userId; soId = String.valueOf(System.currentTimeMillis()) + uuid.toString().replaceAll("-", ""); soKey = soId; JsonNode root; try { root = mapper.readTree(body); ((ObjectNode) soRoot).put("id", soId); ((ObjectNode) soRoot).put("userId", userId); if (root.path("public").isMissingNode()) { ((ObjectNode) soRoot).put("public", "false"); } else { ((ObjectNode) soRoot).put("public", root.get("public").asText()); } long time = System.currentTimeMillis(); ((ObjectNode) soRoot).put("createdAt", time); ((ObjectNode) soRoot).put("updatedAt", time); ((ObjectNode) soRoot).putAll((ObjectNode) root); // Parsing streams if (root.path("streams").isMissingNode()) { throw new ServIoTWebApplicationException(Response.Status.BAD_REQUEST, "Service Object without streams"); } else { ((ObjectNode) soRoot).put("streams", StreamsMapper.parse(root.get("streams"))); } // Parsing actuations if exists if (!root.path("actions").isMissingNode()) { ((ObjectNode) soRoot).put("actions", ActionsMapper.parse(root.get("actions"))); } // If is a CSO with groups field create the derivate subscriptions if (!root.path("groups").isMissingNode()) { createGroupsSubscriptions(root.get("groups")); } } catch (JsonProcessingException e) { LOG.error(e); throw new ServIoTWebApplicationException(Response.Status.BAD_REQUEST, "JsonProcessingException - " + e.getMessage()); } catch (IOException e) { LOG.error(e); throw new ServIoTWebApplicationException(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage()); } }
From source file:org.bwgz.quotation.activity.QuotationActivity.java
@Override protected void onSaveInstanceState(Bundle bundle) { super.onSaveInstanceState(bundle); Log.d(TAG, String.format("onSaveInstanceState - outState: %s", bundle)); try {/*w ww . j a va 2s . c o m*/ ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(history); Log.d(TAG, String.format("history out: %s", json)); bundle.putString(HISTORY, json); } catch (JsonProcessingException e) { Log.e(TAG, String.format("Cannot save history - %s", e.getMessage())); } }
From source file:org.venice.piazza.servicecontroller.async.AsynchronousServiceWorker.java
/** * Handles a non-success completed Status message. * /*from ww w .j ava2 s . co m*/ * @param instance * The service instance. * @param serviceStatus * The StatusUpdate received from the external User Service */ private void processErrorStatus(String jobId, String status, String message) { // Remove the Instance from the Instance Table accessor.deleteAsyncServiceInstance(jobId); // Create a new Status Update to send to the Job Manager. StatusUpdate statusUpdate = new StatusUpdate(); statusUpdate.setStatus(status); // Create the Message for the Error Result of the Status statusUpdate.setResult(new ErrorResult(message, null)); // Send the Job Status through Kafka. try { ProducerRecord<String, String> prodRecord = new ProducerRecord<String, String>( String.format("%s-%s", JobMessageFactory.UPDATE_JOB_TOPIC_NAME, SPACE), jobId, objectMapper.writeValueAsString(statusUpdate)); producer.send(prodRecord); } catch (JsonProcessingException exception) { // The message could not be serialized. Record this. LOGGER.error("Could not send Error Status to Job Manager. Error serializing Status", exception); logger.log("Could not send Error Status to Job Manager. Error serializing Status: " + exception.getMessage(), Severity.ERROR); } }
From source file:io.fabric8.maven.plugin.mojo.build.ApplyMojo.java
private Route createRouteForService(String routeDomainPostfix, String namespace, Service service) { Route route = null;//from w w w . j ava2s.c om String id = KubernetesHelper.getName(service); if (StringUtils.isNotBlank(id) && hasExactlyOneService(service, id)) { route = new Route(); ObjectMeta routeMeta = KubernetesHelper.getOrCreateMetadata(route); routeMeta.setName(id); routeMeta.setNamespace(namespace); RouteSpec routeSpec = new RouteSpec(); RouteTargetReference objectRef = new RouteTargetReferenceBuilder().withName(id).build(); //objectRef.setNamespace(namespace); routeSpec.setTo(objectRef); if (StringUtils.isNotBlank(routeDomainPostfix)) { routeSpec.setHost(prepareHostForRoute(routeDomainPostfix, id)); } else { routeSpec.setHost(""); } route.setSpec(routeSpec); String json; try { json = ResourceUtil.toJson(route); } catch (JsonProcessingException e) { json = e.getMessage() + ". object: " + route; } log.debug("Created route: " + json); } return route; }
From source file:io.fabric8.maven.plugin.mojo.build.ApplyMojo.java
private Ingress createIngressForService(String routeDomainPostfix, String namespace, Service service) { Ingress ingress = null;/*from ww w . j ava2 s . co m*/ String serviceName = KubernetesHelper.getName(service); ServiceSpec serviceSpec = service.getSpec(); if (serviceSpec != null && StringUtils.isNotBlank(serviceName) && shouldCreateExternalURLForService(service, serviceName)) { String ingressId = serviceName; String host = ""; if (StringUtils.isNotBlank(routeDomainPostfix)) { host = serviceName + "." + namespace + "." + FileUtil.stripPrefix(routeDomainPostfix, "."); } List<HTTPIngressPath> paths = new ArrayList<>(); List<ServicePort> ports = serviceSpec.getPorts(); if (ports != null) { for (ServicePort port : ports) { Integer portNumber = port.getPort(); if (portNumber != null) { HTTPIngressPath path = new HTTPIngressPathBuilder().withNewBackend() .withServiceName(serviceName) .withServicePort(KubernetesHelper.createIntOrString(portNumber)).endBackend() .build(); paths.add(path); } } } if (paths.isEmpty()) { return ingress; } ingress = new IngressBuilder().withNewMetadata().withName(ingressId).withNamespace(namespace) .endMetadata().withNewSpec().addNewRule().withHost(host).withNewHttp().withPaths(paths) .endHttp().endRule().endSpec().build(); String json; try { json = ResourceUtil.toJson(ingress); } catch (JsonProcessingException e) { json = e.getMessage() + ". object: " + ingress; } log.debug("Created ingress: " + json); } return ingress; }
From source file:org.o3project.ocnrm.rest.GUIRestApiTest.java
/** * Test method for//from www . ja va 2 s. c om * {@link org.o3project.ocnrm.rest.GUIRestApi#getNWComponentInfo()} */ @Test public void testGetNWComponentInfoWithJsonProcessingException() throws Exception { Logger dummyLogger = mock(Logger.class); Field field = target.getClass().getSuperclass().getDeclaredField("logger"); field.setAccessible(true); field.set(target, dummyLogger); Field seqNo = target.getClass().getSuperclass().getDeclaredField("seqNo"); seqNo.setAccessible(true); PowerMockito.doReturn(nwId).when(target, "getQueryValue", anyString()); JsonProcessingException mock = mock(JsonProcessingException.class); when(mock.getMessage()).thenReturn("message"); PowerMockito.doThrow(mock).when(target, "makeFlows", eq(nwId)); Representation response = target.getNWComponentInfo(); JSONObject result = new JSONObject(response.getText()); assertThat(result.toString(), is("{}")); verify(dummyLogger, times(1)).error( (String) seqNo.get(target) + "\t" + "JsonProcessingException is occured: " + mock.getMessage()); }
From source file:com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.distributed.kubernetes.v2.KubernetesV2Service.java
default String getResourceYaml(AccountDeploymentDetails<KubernetesAccount> details, GenerateService.ResolvedConfiguration resolvedConfiguration) { ServiceSettings settings = resolvedConfiguration.getServiceSettings(getService()); SpinnakerRuntimeSettings runtimeSettings = resolvedConfiguration.getRuntimeSettings(); String namespace = getNamespace(settings); List<ConfigSource> configSources = stageConfig(details, resolvedConfiguration); List<SidecarConfig> sidecarConfigs = details.getDeploymentConfiguration().getDeploymentEnvironment() .getSidecars().getOrDefault(getService().getServiceName(), new ArrayList<>()); List<String> initContainers = details.getDeploymentConfiguration().getDeploymentEnvironment() .getInitContainers().getOrDefault(getService().getServiceName(), new ArrayList<>()).stream() .map(o -> {//from w w w. j a v a2 s . c o m try { return getObjectMapper().writeValueAsString(o); } catch (JsonProcessingException e) { throw new HalException(Problem.Severity.FATAL, "Invalid init container format: " + e.getMessage(), e); } }).collect(Collectors.toList()); if (initContainers.isEmpty()) { initContainers = null; } List<String> hostAliases = details.getDeploymentConfiguration().getDeploymentEnvironment().getHostAliases() .getOrDefault(getService().getServiceName(), new ArrayList<>()).stream().map(o -> { try { return getObjectMapper().writeValueAsString(o); } catch (JsonProcessingException e) { throw new HalException(Problem.Severity.FATAL, "Invalid host alias format: " + e.getMessage(), e); } }).collect(Collectors.toList()); if (hostAliases.isEmpty()) { hostAliases = null; } configSources.addAll(sidecarConfigs .stream().filter(c -> StringUtils.isNotEmpty(c.getMountPath())).map(c -> new ConfigSource() .setMountPath(c.getMountPath()).setId(c.getName()).setType(ConfigSource.Type.emptyDir)) .collect(Collectors.toList())); Map<String, String> env = configSources.stream().map(ConfigSource::getEnv).map(Map::entrySet) .flatMap(Collection::stream).collect(Collectors.toMap(Entry::getKey, Entry::getValue)); List<String> volumes = configSources.stream() .collect(Collectors.toMap(ConfigSource::getId, (i) -> i, (a, b) -> a)).values().stream() .map(this::getVolumeYaml).collect(Collectors.toList()); volumes.addAll(settings.getKubernetes().getVolumes().stream() .collect(Collectors.toMap(ConfigSource::getId, (i) -> i, (a, b) -> a)).values().stream() .map(this::getVolumeYaml).collect(Collectors.toList())); volumes.addAll( sidecarConfigs.stream().map(SidecarConfig::getConfigMapVolumeMounts).flatMap(Collection::stream) .map(c -> new ConfigSource().setMountPath(c.getMountPath()).setId(c.getConfigMapName()) .setType(ConfigSource.Type.configMap)) .map(this::getVolumeYaml).collect(Collectors.toList())); env.putAll(settings.getEnv()); Integer targetSize = settings.getTargetSize(); CustomSizing customSizing = details.getDeploymentConfiguration().getDeploymentEnvironment() .getCustomSizing(); if (customSizing != null) { Map componentSizing = customSizing.getOrDefault(getService().getServiceName(), new HashMap()); targetSize = (Integer) componentSizing.getOrDefault("replicas", targetSize); } String primaryContainer = buildContainer(getService().getCanonicalName(), details, settings, configSources, env); List<String> sidecarContainers = getSidecars(runtimeSettings).stream().map(SidecarService::getService) .map(s -> buildContainer(s.getCanonicalName(), details, runtimeSettings.getServiceSettings(s), configSources, env)) .collect(Collectors.toList()); sidecarContainers .addAll(sidecarConfigs.stream().map(this::buildCustomSidecar).collect(Collectors.toList())); List<String> containers = new ArrayList<>(); containers.add(primaryContainer); containers.addAll(sidecarContainers); TemplatedResource podSpec = new JinjaJarResource("/kubernetes/manifests/podSpec.yml") .addBinding("containers", containers).addBinding("initContainers", initContainers) .addBinding("hostAliases", hostAliases) .addBinding("imagePullSecrets", settings.getKubernetes().getImagePullSecrets()) .addBinding("serviceAccountName", settings.getKubernetes().getServiceAccountName()) .addBinding("terminationGracePeriodSeconds", terminationGracePeriodSeconds()) .addBinding("volumes", volumes); String version = makeValidLabel(details.getDeploymentConfiguration().getVersion()); if (version.isEmpty()) { version = "unknown"; } return new JinjaJarResource("/kubernetes/manifests/deployment.yml") .addBinding("name", getService().getCanonicalName()).addBinding("namespace", namespace) .addBinding("replicas", targetSize).addBinding("version", version) .addBinding("podAnnotations", settings.getKubernetes().getPodAnnotations()) .addBinding("podSpec", podSpec.toString()).toString(); }
From source file:com.sm.store.server.StoreCallBack.java
/** * check type of header SerializableType * @param header/*from w w w . j a v a2 s . c om*/ * @param response */ protected void serializerResponse(Header header, Response response) { switch (header.getSerializableType()) { case Json: String result; try { result = mapper.writeValueAsString(response.getPayload()); } catch (JsonProcessingException jsp) { logger.error(jsp.getMessage(), jsp); result = "ERROR :" + jsp.getMessage(); } response.setPayload(embeddedSerializer.toBytes(result)); break; case PassThrough: if (!(response.getPayload() instanceof byte[])) response.setPayload(embeddedSerializer.toBytes(response.getPayload())); break; default: response.setPayload(embeddedSerializer.toBytes(response.getPayload())); } }
From source file:org.venice.piazza.servicecontroller.async.AsynchronousServiceWorker.java
/** * Polls for the Status of the Asynchronous Service Instance. This will update any status information in the Status * table, and will also check if the Status is in a completed State. If a completed state is detected (success or * fail) then it will initialize the logic to handle the result or error. * /*from w ww.ja va 2 s. co m*/ * @param instance */ @Async public void pollStatus(AsyncServiceInstance instance) { try { // Get the Service, so we can fetch the URL Service service = accessor.getServiceById(instance.getServiceId()); // Build the GET URL String url = String.format("%s/%s/%s", service.getUrl(), STATUS_ENDPOINT, instance.getInstanceId()); // Get the Status of the job. StatusUpdate status = restTemplate.getForObject(url, StatusUpdate.class); if (status == null) { throw new DataInspectException("Null Status received from Service."); } // Act appropriately based on the status received if ((status.getStatus().equals(StatusUpdate.STATUS_PENDING)) || (status.getStatus().equals(StatusUpdate.STATUS_RUNNING)) || (status.getStatus().equals(StatusUpdate.STATUS_SUBMITTED))) { // If this service is not done, then mark the status and we'll poll again later. instance.setStatus(status); instance.setLastCheckedOn(new DateTime()); accessor.updateAsyncServiceInstance(instance); // Route the current Job Status through Kafka. try { ProducerRecord<String, String> prodRecord = new ProducerRecord<String, String>( String.format("%s-%s", JobMessageFactory.UPDATE_JOB_TOPIC_NAME, SPACE), instance.getJobId(), objectMapper.writeValueAsString(status)); producer.send(prodRecord); } catch (JsonProcessingException exception) { // The message could not be serialized. Record this. LOGGER.error("Json processing error occured", exception); logger.log("Could not send Running Status Message to Job Manager. Error serializing Status: " + exception.getMessage(), Severity.ERROR); } } else if (status.getStatus().equals(StatusUpdate.STATUS_SUCCESS)) { // Queue up a subsequent request to get the Result of the Instance processSuccessStatus(service, instance); } else if ((status.getStatus().equals(StatusUpdate.STATUS_ERROR)) || (status.getStatus().equals(StatusUpdate.STATUS_FAIL)) || (status.getStatus().equals(StatusUpdate.STATUS_CANCELLED))) { // Errors encountered. Report this and bubble it back up through the Job ID. String errorMessage = String.format("Instance %s reported back Status %s. ", instance.getInstanceId(), status.getStatus()); if (status.getResult() instanceof ErrorResult) { // If we can parse any further details on the error, then do so here. ErrorResult errorResult = (ErrorResult) status.getResult(); errorMessage = String.format("%s Details: %s, %s", errorMessage, errorResult.getMessage(), errorResult.getDetails()); } logger.log(errorMessage, Severity.ERROR); processErrorStatus(instance.getJobId(), status.getStatus(), errorMessage); } else { // If it's an unknown status, then we can't process it. updateFailureCount(instance); logger.log(String.format( "Unknown Status %s encountered for Service ID %s Instance %s under Job ID %s. The number of Errors has been incremented (%s)", status.getStatus(), instance.getServiceId(), instance.getInstanceId(), instance.getJobId(), instance.getNumberErrorResponses()), Severity.WARNING); } } catch (HttpClientErrorException | HttpServerErrorException exception) { updateFailureCount(instance); String error = String.format( "HTTP Error Status %s encountered for Service ID %s Instance %s under Job ID %s. The number of Errors has been incremented (%s)", exception.getStatusCode().toString(), instance.getServiceId(), instance.getInstanceId(), instance.getJobId(), instance.getNumberErrorResponses()); LOGGER.error(error, exception); logger.log(error, Severity.WARNING); } catch (Exception exception) { updateFailureCount(instance); String error = String.format( "Unexpected Error %s encountered for Service ID %s Instance %s under Job ID %s. The number of Errors has been incremented (%s)", exception.getMessage(), instance.getServiceId(), instance.getInstanceId(), instance.getJobId(), instance.getNumberErrorResponses()); LOGGER.error(error, exception); logger.log(error, Severity.WARNING); } }