List of usage examples for com.fasterxml.jackson.core JsonProcessingException getMessage
@Override
public String getMessage()
From source file:ch.icclab.cyclops.resource.impl.RateResource.java
/** * Construct the JSON response consisting of the meter and the usage values * * Pseudo Code/*from w w w .j ava2s . c o m*/ * 1. Create the HasMap consisting of time range * 2. Create the response POJO * 3. Convert the POJO to JSON * 4. Return the JSON string * * @param rateArr An arraylist consisting of metername and corresponding usage * @param fromDate DateTime from usage data needs to be calculated * @param toDate DateTime upto which the usage data needs to be calculated * @return responseJson The response object in the JSON format */ private Representation constructGetRateResponse(HashMap rateArr, String fromDate, String toDate) { String jsonStr = null; JsonRepresentation responseJson = null; RateResponse responseObj = new RateResponse(); HashMap time = new HashMap(); ObjectMapper mapper = new ObjectMapper(); time.put("from", reformatDate(fromDate)); time.put("to", reformatDate(toDate)); //Build the response POJO responseObj.setTime(time); responseObj.setRate(rateArr); //Convert the POJO to a JSON string try { jsonStr = mapper.writeValueAsString(responseObj); responseJson = new JsonRepresentation(jsonStr); } catch (JsonProcessingException e) { logger.error("Error while constructing the response: " + e.getMessage()); e.printStackTrace(); } return responseJson; }
From source file:com.flipkart.foxtrot.core.datastore.impl.hbase.HBaseDataStore.java
@Override @Timed/*from ww w . ja v a 2 s . com*/ public List<Document> saveAll(final Table table, List<Document> documents) throws DataStoreException { if (documents == null || documents.isEmpty()) { throw new DataStoreException(DataStoreException.ErrorCode.STORE_INVALID_REQUEST, "Invalid Documents List"); } List<Put> puts = new Vector<Put>(); ImmutableList.Builder<Document> translatedDocuments = ImmutableList.builder(); try { for (Document document : documents) { if (document == null || document.getData() == null || document.getId() == null) { throw new DataStoreException(DataStoreException.ErrorCode.STORE_INVALID_REQUEST, "Invalid Document"); } Document translatedDocument = translator.translate(table, document); puts.add(getPutForDocument(table, translatedDocument)); translatedDocuments.add(translatedDocument); } } catch (JsonProcessingException e) { throw new DataStoreException(DataStoreException.ErrorCode.STORE_INVALID_REQUEST, e.getMessage(), e); } HTableInterface hTable = null; try { hTable = tableWrapper.getTable(table); hTable.put(puts); } catch (IOException e) { throw new DataStoreException(DataStoreException.ErrorCode.STORE_MULTI_SAVE, e.getMessage(), e); } catch (Exception e) { throw new DataStoreException(DataStoreException.ErrorCode.STORE_MULTI_SAVE, e.getMessage(), e); } finally { if (null != hTable) { try { hTable.close(); } catch (IOException e) { logger.error("Error closing table: ", e); } } } return translatedDocuments.build(); }
From source file:com.sugaronrest.SugarRestClient.java
/** * Sets response if an error occurs.//w ww. ja v a 2s . c o m * * @param request The request object. * @param response The response object. */ private void setErrorResponse(SugarRestRequest request, SugarRestResponse response) { ObjectMapper mapper = JsonObjectMapper.getMapper(); String jsonRequest = StringUtils.EMPTY; String jsonResponse = StringUtils.EMPTY; try { jsonRequest = mapper.writeValueAsString(request); jsonResponse = mapper.writeValueAsString(response); } catch (JsonProcessingException exception) { ErrorResponse errorResponse = ErrorResponse.format(exception, exception.getMessage()); errorResponse.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); response.setError(errorResponse); } response.setData(null); response.setJData(StringUtils.EMPTY); response.setJsonRawRequest(jsonRequest); response.setJsonRawResponse(jsonResponse); }
From source file:alluxio.underfs.swift.KeystoneV3AccessProvider.java
@Override public Access authenticate() { try {//ww w .j a va 2 s . c o m String requestBody; try { // Construct request body KeystoneV3Request request = new KeystoneV3Request( new Auth( new Identity(Arrays.asList(AUTH_METHOD), new Password(new User(mAccountConfig.getUsername(), mAccountConfig.getPassword()))), new Scope(new Project(mAccountConfig.getTenantName())))); requestBody = new ObjectMapper().writeValueAsString(request); } catch (JsonProcessingException e) { LOG.error("Error processing JSON request: {}", e.getMessage()); return null; } try (CloseableHttpClient client = HttpClients.createDefault()) { // Send request HttpPost post = new HttpPost(mAccountConfig.getAuthUrl()); post.addHeader("Accept", "application/json"); post.addHeader("Content-Type", "application/json"); post.setEntity(new ByteArrayEntity(requestBody.toString().getBytes())); try (CloseableHttpResponse httpResponse = client.execute(post)) { // Parse response int responseCode = httpResponse.getStatusLine().getStatusCode(); if (responseCode != RESPONSE_OK) { LOG.error("Error with response code {} ", responseCode); return null; } String token = httpResponse.getFirstHeader("X-Subject-Token").getValue(); // Parse response body try (BufferedReader bufReader = new BufferedReader( new InputStreamReader(httpResponse.getEntity().getContent()))) { String responseBody = bufReader.readLine(); KeystoneV3Response response; try { response = new ObjectMapper().readerFor(KeystoneV3Response.class) .readValue(responseBody); // Find endpoints String internalURL = null; String publicURL = null; for (Catalog catalog : response.mToken.mCatalog) { if (catalog.mName.equals("swift") && catalog.mType.equals("object-store")) { for (Endpoint endpoint : catalog.mEndpoints) { if (endpoint.mRegion.equals(mAccountConfig.getPreferredRegion())) { if (endpoint.mInterface.equals("public")) { publicURL = endpoint.mUrl; } else if (endpoint.mInterface.equals("internal")) { internalURL = endpoint.mUrl; } } } } } // Construct access object KeystoneV3Access access = new KeystoneV3Access(internalURL, mAccountConfig.getPreferredRegion(), publicURL, token); return access; } catch (JsonProcessingException e) { LOG.error("Error processing JSON response: {}", e.getMessage()); return null; } } } } } catch (IOException e) { // Unable to authenticate LOG.error("Exception authenticating using KeystoneV3 {}", e.getMessage()); return null; } }
From source file:com.ottogroup.bi.spqr.metrics.kafka.KafkaReporter.java
/** * @see com.codahale.metrics.ScheduledReporter#report() *///ww w.j av a2 s .co m public void report() { synchronized (this) { // exec async kafkaExecutor.submit(new Runnable() { public void run() { try { kafkaProducer.send( new KeyedMessage<byte[], byte[]>(topicId, jsonMapper.writeValueAsBytes(registry))); } catch (JsonProcessingException e) { logger.error("Failed to send message to kafka [topic=" + topicId + "]. Reason: " + e.getMessage(), e); } } }); } }
From source file:com.flipkart.foxtrot.core.datastore.impl.hbase.HBaseDataStore.java
@Override @Timed/* w w w . j a va 2 s .c o m*/ public List<Document> getAll(final Table table, List<String> ids) throws DataStoreException { if (ids == null) { throw new DataStoreException(DataStoreException.ErrorCode.STORE_INVALID_REQUEST, "Invalid Request IDs"); } HTableInterface hTable = null; try { List<Get> gets = new ArrayList<Get>(ids.size()); for (String id : ids) { Get get = new Get(Bytes.toBytes(translator.rawStorageIdFromDocumentId(table, id))) .addColumn(COLUMN_FAMILY, DOCUMENT_FIELD_NAME) .addColumn(COLUMN_FAMILY, DOCUMENT_META_FIELD_NAME) .addColumn(COLUMN_FAMILY, TIMESTAMP_FIELD_NAME).setMaxVersions(1); gets.add(get); } hTable = tableWrapper.getTable(table); Result[] getResults = hTable.get(gets); List<Document> results = new ArrayList<Document>(ids.size()); for (int index = 0; index < getResults.length; index++) { Result getResult = getResults[index]; if (!getResult.isEmpty()) { byte[] data = getResult.getValue(COLUMN_FAMILY, DOCUMENT_FIELD_NAME); byte[] metadata = getResult.getValue(COLUMN_FAMILY, DOCUMENT_META_FIELD_NAME); byte[] timestamp = getResult.getValue(COLUMN_FAMILY, TIMESTAMP_FIELD_NAME); long time = Bytes.toLong(timestamp); DocumentMetadata documentMetadata = (null != metadata) ? mapper.readValue(metadata, DocumentMetadata.class) : null; final String docId = (null == metadata) ? Bytes.toString(getResult.getRow()).split(":")[0] : documentMetadata.getRawStorageId(); results.add(translator .translateBack(new Document(docId, time, documentMetadata, mapper.readTree(data)))); } else { throw new DataStoreException(DataStoreException.ErrorCode.STORE_NO_DATA_FOUND_FOR_IDS, String.format("No data found for ID: %s", ids.get(index))); } } return results; } catch (DataStoreException ex) { throw ex; } catch (JsonProcessingException e) { throw new DataStoreException(DataStoreException.ErrorCode.STORE_INVALID_REQUEST, e.getMessage(), e); } catch (IOException e) { throw new DataStoreException(DataStoreException.ErrorCode.STORE_MULTI_GET, e.getMessage(), e); } catch (Exception ex) { throw new DataStoreException(DataStoreException.ErrorCode.STORE_MULTI_GET, ex.getMessage(), ex); } finally { if (null != hTable) { try { hTable.close(); } catch (IOException e) { logger.error("Error closing table: ", e); } } } }
From source file:org.graylog2.alarmcallbacks.HTTPAlarmCallback.java
@Override public void call(final Stream stream, final AlertCondition.CheckResult result) throws AlarmCallbackException { final Map<String, Object> event = Maps.newHashMap(); event.put("stream", stream); event.put("check_result", result); final Response r; try {/*from w w w. ja v a 2 s.c o m*/ final byte[] body = objectMapper.writeValueAsBytes(event); final URL url = new URL(configuration.getString(CK_URL)); final Request request = new Request.Builder().url(url).header("charset", "utf-8") .header("content-type", "application/json").post(RequestBody.create(CONTENT_TYPE, body)) .build(); r = httpClient.newCall(request).execute(); } catch (JsonProcessingException e) { throw new AlarmCallbackException("Unable to serialize alarm", e); } catch (MalformedURLException e) { throw new AlarmCallbackException("Malformed URL", e); } catch (IOException e) { throw new AlarmCallbackException(e.getMessage(), e); } if (!r.isSuccessful()) { throw new AlarmCallbackException("Expected successful HTTP response [2xx] but got [" + r.code() + "]."); } }
From source file:org.commonjava.maven.galley.transport.htcli.internal.AbstractHttpJob.java
private void writeMetadata(final Transfer target, final ObjectMapper mapper) { if (target == null || request == null || response == null) { logger.trace("Cannot write HTTP exchange metadata. Request: {}. Response: {}. Transfer: {}", request, response, target);/*w w w .j av a 2 s. c o m*/ return; } logger.trace("Writing HTTP exchange metadata. Request: {}. Response: {}", request, response); Transfer metaTxfr = target.getSiblingMeta(HttpExchangeMetadata.FILE_EXTENSION); if (metaTxfr == null) { if (target.isDirectory()) { logger.trace("DIRECTORY. Using HTTP exchange metadata file INSIDE directory called: {}", HttpExchangeMetadata.FILE_EXTENSION); metaTxfr = target.getChild(HttpExchangeMetadata.FILE_EXTENSION); } else { logger.trace("SKIP: Cannot retrieve HTTP exchange metadata Transfer instance for: {}", target); return; } } final HttpExchangeMetadata metadata = new HttpExchangeMetadata(request, response); OutputStream out = null; try { final Transfer finalMeta = metaTxfr; out = metaTxfr.openOutputStream(TransferOperation.GENERATE, false); logger.trace("Writing HTTP exchange metadata:\n\n{}\n\n", new Object() { @Override public String toString() { try { return mapper.writeValueAsString(metadata); } catch (final JsonProcessingException e) { logger.warn(String.format("Failed to write HTTP exchange metadata: %s. Reason: %s", finalMeta, e.getMessage()), e); } return "ERROR RENDERING METADATA"; } }); out.write(mapper.writeValueAsBytes(metadata)); } catch (final IOException e) { if (logger.isTraceEnabled()) { logger.trace(String.format("Failed to write metadata for HTTP exchange to: %s. Reason: %s", metaTxfr, e.getMessage()), e); } else { logger.warn("Failed to write metadata for HTTP exchange to: {}. Reason: {}", metaTxfr, e.getMessage()); } } finally { IOUtils.closeQuietly(out); } }
From source file:com.auditbucket.search.dao.TrackDaoES.java
private String makeIndexJson(SearchChange searchChange) { ObjectMapper mapper = new ObjectMapper(); Map<String, Object> index = makeIndexDocument(searchChange); try {/* w w w . j a v a 2s . c om*/ return mapper.writeValueAsString(index); } catch (JsonProcessingException e) { logger.error(e.getMessage()); } return null; }