Example usage for com.fasterxml.jackson.core JsonProcessingException printStackTrace

List of usage examples for com.fasterxml.jackson.core JsonProcessingException printStackTrace

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonProcessingException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:org.o3project.ocnrm.rest.GUIRestApi.java

/**
 * Data acquisition API of NW component.
 * Flow information, topology information,
 * and boundary information (Layerized nw is only specified) are acquired.
 *
 * GET /demo/info?NWCID=\<NW component name\>
 * <br>Example<br>//from www.  j  a  v a 2 s. co  m
 * http://localhost:44444/demo/info?NWCID=networkcomponent012,networkcomponent01
 * @return Representation
 */
@Get
public Representation getNWComponentInfo() {
    seqNo = SEQNO_PREFIX + mf.requestNoToString();

    logger.info(seqNo + "\t" + "getNWComponentInfo Start");
    logger.info(seqNo + "\t" + "getQueryValue(\"NWCID\") : " + getQueryValue("NWCID"));
    JSONObject result = new JSONObject();

    String nwcIdQuery = getQueryValue("NWCID");
    if (nwcIdQuery == null) {
        return new JsonRepresentation(result);
    }

    String[] nwcIds = getQueryValue("NWCID").split(",");

    try {
        for (String nwcId : nwcIds) {
            JSONObject json = new JSONObject();

            json.put("flow", makeFlows(nwcId));
            json.put("topology", makeTopology(nwcId));

            String objectId = sender.getConnections(nwcId);
            if (objectId != null) {
                json.put("boundaries", makeBoundary(nwcId, objectId));
            }
            result.put(nwcId, json);
        }
    } catch (JsonProcessingException e) {
        logger.error(seqNo + "\t" + "JsonProcessingException is occured: " + e.getMessage());
        e.printStackTrace();
    } catch (JSONException e) {
        logger.error(seqNo + "\t" + "JSONException is occured: " + e.getMessage());
        e.printStackTrace();
    } catch (ParseBodyException e) {
        logger.error(seqNo + "\t" + "ParseBodyException is occured: " + e.getMessage());
        e.printStackTrace();
    }
    logger.debug(seqNo + "\t" + "response to GUI : " + result);
    logger.info(seqNo + "\t" + "getNWComponentInfo End");
    return new JsonRepresentation(result);
}

From source file:ch.icclab.cyclops.persistence.impl.TSDBResource.java

/**
 * Receives the usage data array and the gauge meter name. The usage data is transformed
 * to a json data and saved into the the InfluxDB
 *
 * Pseudo Code/*www.j a  va  2 s.  co  m*/
 * 1. Iterate through the data array to save the data into an ArraList of objects
 * 2. Save the data into the TSDB POJO class
 * 3. Convert the POJO class to a JSON obj
 * 4. Invoke the InfluxDb client to save the data
 *
 * @param dataArr An array list consisting of usage data
 * @param meterName Name of the Gauge Meter
 * @return result A boolean output as a result of saving the meter data into the db
 */
public boolean saveCumulativeMeterData(ArrayList<CumulativeMeterData> dataArr, String meterName) {
    String jsonData;
    boolean result = true;
    ArrayList<Object> samplesArr;
    CumulativeMeterData cMeterData;
    DateTimeUtil time = new DateTimeUtil();
    TSDBData dbData = new TSDBData();
    ObjectMapper mapper = new ObjectMapper();
    ArrayList<String> columnNameArr = new ArrayList<String>();
    ArrayList<ArrayList<Object>> samplesConsolidatedArr = new ArrayList<ArrayList<Object>>();
    InfluxDBClient dbClient = new InfluxDBClient();

    // Build the array with column names for the time series
    columnNameArr.add("time");
    columnNameArr.add("userid");
    columnNameArr.add("resourceid");
    columnNameArr.add("volume");
    columnNameArr.add("usage");
    columnNameArr.add("source");
    columnNameArr.add("project_id");
    columnNameArr.add("type");
    columnNameArr.add("id");
    columnNameArr.add("unit");
    columnNameArr.add("instance_id");
    columnNameArr.add("instance_type");
    columnNameArr.add("mac");
    columnNameArr.add("fref");
    columnNameArr.add("name");
    //Build an array consisting of samples
    for (int i = 0; i < dataArr.size(); i++) {
        cMeterData = dataArr.get(i);
        samplesArr = new ArrayList<Object>();
        samplesArr.add(time.getEpoch(cMeterData.getRecorded_at()));
        samplesArr.add(cMeterData.getUser_id());
        samplesArr.add(cMeterData.getResource_id());
        samplesArr.add(cMeterData.getVolume());
        samplesArr.add(cMeterData.getUsage());
        samplesArr.add(cMeterData.getSource());
        samplesArr.add(cMeterData.getProject_id());
        samplesArr.add(cMeterData.getType());
        samplesArr.add(cMeterData.getId());
        samplesArr.add(cMeterData.getUnit());
        samplesArr.add(cMeterData.getMetadata().getInstance_id());
        samplesArr.add(cMeterData.getMetadata().getInstance_type());
        samplesArr.add(cMeterData.getMetadata().getMac());
        samplesArr.add(cMeterData.getMetadata().getFref());
        samplesArr.add(cMeterData.getMetadata().getName());
        // Build an array which contains all the sample arrays.
        samplesConsolidatedArr.add(samplesArr);
    }
    // Set the data object to be converted into a JSON request string
    dbData.setName(meterName);
    dbData.setColumns(columnNameArr);
    dbData.setPoints(samplesConsolidatedArr);
    // Convert the data object into a JSON string
    try {
        jsonData = mapper.writeValueAsString(dbData);
        // Write the JSON string to the DB
        dbClient.saveData(jsonData);
    } catch (JsonProcessingException e) {
        System.out.println("Saved to TSDB : False");
        e.printStackTrace();
        return false;
    }

    System.out.println("Saved to TSDB " + result);
    return result;
}

From source file:cc.arduino.packages.discoverers.PluggableDiscovery.java

private BoardPort mapJsonNodeToBoardPort(ObjectMapper mapper, JsonNode node) {
    try {/*w w w.  ja v a  2 s  .  co m*/
        BoardPort port = mapper.treeToValue(node.get("port"), BoardPort.class);
        // if no label, use address
        if (port.getLabel() == null || port.getLabel().isEmpty()) {
            port.setLabel(port.getAddress());
        }
        port.searchMatchingBoard();
        return port;
    } catch (JsonProcessingException e) {
        System.err.println(format("{0}: Invalid BoardPort message", discoveryName));
        e.printStackTrace();
        return null;
    }
}

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 www .  j  av a2  s  .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.jci.job.api.req.PrepareBatchInsertReq.java

/**
 * Prepare req./* w w w .j  a  v  a  2  s .c o  m*/
 *
 * @param responseBody the response body
 * @return the batch insert req
 */
public static BatchInsertReq preparePoReq(PoDetailsRes responseBody) {

    List<PoDetails> poList = responseBody.getPoList();

    ObjectMapper mapper = new ObjectMapper();
    List<TableEntity> poDetailsList = new ArrayList<>();
    List<TableEntity> poItemDetailsList = new ArrayList<>();

    PoBody prepareReq = null;
    List<Object> req = new ArrayList<>();

    List<String> rowKeyList = new ArrayList<>();
    BatchInsertReq res = null;
    String erpName = "";

    if (poList == null || poList.size() < 1) {
        return res;
    }

    LOG.info("poList size--->" + poList.size());

    for (PoDetails po : poList) {

        erpName = po.getErp().toUpperCase();

        String partitionKey = po.getErp().toUpperCase();
        //String orderNumber = po.getOrderNumber();

        String orderNumber = po.getOrderNumber();
        ;
        PoEntity poEntity = new PoEntity(partitionKey, orderNumber);
        rowKeyList.add(orderNumber);
        prepareReq = new PoBody();
        prepareReq.setErp(po.getErp());
        prepareReq.setOrderNumber(orderNumber);
        prepareReq.setPlant(po.getPlant());
        prepareReq.setRegion(po.getRegion());
        req.add(prepareReq);

        if (CommonUtils.isBlank(orderNumber) || CommonUtils.isBlank(po.getPlant())
                || CommonUtils.isBlank(po.getRegion()) || CommonUtils.isBlank(po.getErp())) {
            continue;
        }
        List<Object> itemList = po.getItemList();
        PoItemsEntity itemEntity = null;

        for (Object item : itemList) {
            itemEntity = new PoItemsEntity(partitionKey, orderNumber);//item.getOrderNumber()+"_"+item.getLineID()+"_"+item.getRequestID()
            if (poItemDetailsList.contains(itemEntity)) {
                continue;
            }

            try {
                itemEntity.setJsonString(mapper.writeValueAsString(item));
            } catch (JsonProcessingException e) {
                LOG.error("### Exception in PrepareBatchInsertReq.preparePoReq ###" + e);
            }

            if (itemEntity != null) {
                itemEntity.setOrderNumber(orderNumber);
                poItemDetailsList.add(itemEntity);
            }
        }

        if (!poDetailsList.contains(poEntity)) {
            poEntity.setRegion(po.getRegion());
            poEntity.setPlant(po.getPlant());

            poEntity.setOrderCreationDate(CommonUtils.stringToDate(po.getOrderCreationDate()));
            poEntity.setSupplierDeliveryState(Constants.STATUS_IN_TRANSIT);
            poEntity.setSuppType(po.getSupplierType());

            po.setItemList(null);
            try {
                poEntity.setJsonString(mapper.writeValueAsString(po));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            poDetailsList.add(poEntity);
        }
    }

    HashMap<String, List<TableEntity>> tableNameToEntityMap = new HashMap<>();
    tableNameToEntityMap.put(Constants.TABLE_PO_DETAILS, poDetailsList);
    tableNameToEntityMap.put(Constants.TABLE_PO_ITEM_DETAILS, poItemDetailsList);

    Map<String, List<String>> tableNameToRowkeyListMap = new HashMap<>();
    tableNameToRowkeyListMap.put(Constants.TABLE_PO_DETAILS, rowKeyList);
    res = new BatchInsertReq();
    res.setErpName(erpName);
    res.setTableNameToEntityMap(tableNameToEntityMap);
    res.setReq(req);
    res.setTableNameToRowkeyListMap(tableNameToRowkeyListMap);
    return res;
}

From source file:i5.las2peer.services.loadStoreGraphService.LoadStoreGraphService.java

/**
 * /*from  www.  j a  v a  2s.  co m*/
 * Returns the API documentation of all annotated resources for purposes of Swagger documentation.
 * 
 * @return The resource's documentation
 * 
 */
@GET
@Path("/swagger.json")
@Produces(MediaType.APPLICATION_JSON)
public HttpResponse getSwaggerJSON() {
    Swagger swagger = new Reader(new Swagger()).read(this.getClass());
    if (swagger == null) {
        return new HttpResponse("Swagger API declaration not available!", HttpURLConnection.HTTP_NOT_FOUND);
    }
    try {
        return new HttpResponse(Json.mapper().writeValueAsString(swagger), HttpURLConnection.HTTP_OK);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
        return new HttpResponse(e.getMessage(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    }
}

From source file:org.venice.piazza.servicecontroller.messaging.handlers.ExecuteServiceHandlerTest.java

/**
 * Tests executing web service with GET method
 *///w ww  . j  a v  a2  s  .  c o  m
@Test
public void testHandleWithMapInputsGet() {
    ExecuteServiceData edata = new ExecuteServiceData();
    String serviceId = "a842aae2-bd74-4c4b-9a65-c45e8cd9060f";
    edata.setServiceId(serviceId);
    HashMap<String, DataType> dataInputs = new HashMap<String, DataType>();
    URLParameterDataType tdt = new URLParameterDataType();
    tdt.content = "Marge";

    dataInputs.put("name", tdt);
    edata.setDataInputs(dataInputs);

    ObjectMapper mapper = new ObjectMapper();
    try {
        String tsvc = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(edata);
        System.out.println(tsvc);
    } catch (JsonProcessingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    URI uri = URI.create("http://localhost:8087/jumpstart/moviequotewelcome?name=Marge");
    Mockito.when(serviceMock.getUrl()).thenReturn(uri.toString());
    Mockito.when(accessorMock.getServiceById(serviceId)).thenReturn(movieService);
    Mockito.doNothing().when(loggerMock).log(Mockito.anyString(), Mockito.anyString());
    Mockito.when(restTemplateMock.getForEntity(Mockito.eq(uri), Mockito.eq(String.class)))
            .thenReturn(new ResponseEntity<String>("testExecuteService", HttpStatus.FOUND));

    when(accessorMock.getServiceById(serviceId)).thenReturn(movieService);

    ResponseEntity<String> retVal = executeServiceHandler.handle(edata);
    assertTrue(retVal.getBody().contains("testExecuteService"));
}

From source file:org.craftercms.studio.controller.services.rest.AbstractControllerTest.java

protected String generateRequestBody(Object jsonObject) {
    ObjectMapper mapper = new ObjectMapper();

    String toRet = "";
    try {/*from   w w w.ja  v  a 2  s . c o  m*/
        toRet = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
    } catch (JsonProcessingException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
    return toRet;
}

From source file:com.acentera.utils.ProjectsHelpers.java

public static String getProjectProvidersAsJson(ProjectProviders prov) {

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    ObjectWriter ow = mapper.writer();//from  w  w w . j  a  v  a  2  s .c  om
    JSONObject jso = new JSONObject();
    try {
        Logger.debug("PROVIDER IS : " + prov.getId());
        jso.put("provider", ow.writeValueAsString(prov));
        return jso.toString();
    } catch (JsonProcessingException e) {
        e.printStackTrace();
        return null;
    }

}

From source file:AdminCollectionDropFunctionalTest.java

@Test
public void testDropCollectionCreate() throws Exception {

    running(getFakeApplication(), new Runnable() {
        public void run() {
            try {
                String sFakeCollection = getRouteAddress();
                FakeRequest requestCreation = new FakeRequest(POST, sFakeCollection);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
                Result result = route(requestCreation);
                assertRoute(result, "testDropCollection.create", Status.CREATED, null, true);

                //Insert some object in there
                String sFakeInsertObjects = getRouteForObjects();
                JsonNode payload = (new ObjectMapper()).readTree("{\"test\":\"testvalue\"}");
                int cont = 15;
                for (int i = 0; i < cont; i++) {
                    requestCreation = new FakeRequest(POST, sFakeInsertObjects);
                    requestCreation = requestCreation.withHeader(TestConfig.KEY_APPCODE,
                            TestConfig.VALUE_APPCODE);
                    requestCreation = requestCreation.withHeader(TestConfig.KEY_AUTH,
                            TestConfig.AUTH_ADMIN_ENC);
                    requestCreation = requestCreation.withJsonBody(payload, POST);
                    Result result1 = route(requestCreation);
                    assertRoute(result1, "testDropCollection.populate", Status.OK, null, true);
                }/*from   w  ww .j  a va 2 s  . c om*/

                //check if the collection is full
                String sFakeCollectionCount = getRouteForCount();
                requestCreation = new FakeRequest(GET, sFakeCollectionCount);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
                result = route(requestCreation);
                assertRoute(result, "routeDropCollection.count", Status.OK, "\"count\":" + cont, true);

                //drop the collection
                requestCreation = new FakeRequest(DELETE, sFakeCollection);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
                result = route(requestCreation);
                assertRoute(result, "routeDropCollection.drop", Status.OK, null, false);

                //check the collection does not exist
                requestCreation = new FakeRequest(GET, sFakeCollectionCount);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
                result = route(requestCreation);
                assertRoute(result, "routeDropCollection.count_not_found", Status.NOT_FOUND, null, false);

                //try to recreate the same
                requestCreation = new FakeRequest(POST, sFakeCollection);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
                result = route(requestCreation);
                assertRoute(result, "testDropCollection.create_the_same", Status.CREATED, null, true);

                //check the collection is empty
                requestCreation = new FakeRequest(GET, sFakeCollectionCount);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
                result = route(requestCreation);
                assertRoute(result, "routeDropCollection.count_must_be_empty", Status.OK, "\"count\":0", true);

                //finally... drop
                requestCreation = new FakeRequest(DELETE, sFakeCollection);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
                requestCreation = requestCreation.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
                result = route(requestCreation);
                assertRoute(result, "routeDropCollection.drop_final", Status.OK, null, false);

            } catch (JsonProcessingException e) {
                fail();
            } catch (IOException e) {
                fail();
            } catch (Exception e) {
                e.printStackTrace();
                fail();
            }
        }
    });
}