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:i5.las2peer.services.gamificationApplicationService.GamificationApplicationService.java

/**
 * Get all application list separated into two categories. All apps registered for the member and other apps.
 * /*from  w  w w  .j ava  2 s. c o  m*/
 * 
 * @return HttpResponse with the returnString
 */
@GET
@Path("/list/separated")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "getSeparateApplicationInfo", notes = "Get all application list separated into two categories. All apps registered for the member and other apps.")
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "List of apps"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Database error"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "JsonProcessingException") })
public HttpResponse getSeparateApplicationInfo() {
    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99,
            "GET " + "gamification/applications/list/separated");

    JSONObject objResponse = new JSONObject();
    Connection conn = null;

    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    String name = userAgent.getLoginName();
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }
    ObjectMapper objectMapper = new ObjectMapper();
    //Set pretty printing of json
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    try {
        conn = dbm.getConnection();
        List<List<ApplicationModel>> allApps = applicationAccess.getSeparateApplicationsWithMemberId(conn,
                name);

        try {
            String response = objectMapper.writeValueAsString(allApps);
            allApps.clear();
            L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_11, "" + name);

            return new HttpResponse(response, HttpURLConnection.HTTP_OK);

        } catch (JsonProcessingException e) {
            e.printStackTrace();

            allApps.clear();
            // return HTTP Response on error
            objResponse.put("message", "Cannot delete Application. JsonProcessingException." + e.getMessage());
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
        }
    } catch (SQLException e) {

        e.printStackTrace();
        objResponse.put("message", "Database error");
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    }
    // always close connections
    finally {
        try {
            conn.close();
        } catch (SQLException e) {
            logger.printStackTrace(e);
        }
    }

}

From source file:i5.las2peer.services.gamificationBadgeService.GamificationBadgeService.java

/**
 * Get a badge data with specific ID from database
 * @param appId applicationId//from   ww w.  j a  v  a2s .  c o m
 * @param badgeId badge id
 * @return HttpResponse returned as JSON object
 */
@GET
@Path("/{appId}/{badgeId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Found a badges"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Error"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
@ApiOperation(value = "Find point for specific App ID and badge ID", notes = "Returns a badge", response = BadgeModel.class, responseContainer = "List", authorizations = @Authorization(value = "api_key"))
public HttpResponse getBadgeWithId(@ApiParam(value = "Application ID") @PathParam("appId") String appId,
        @ApiParam(value = "Badge ID") @PathParam("badgeId") String badgeId) {

    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99,
            "GET " + "gamification/badges/" + appId + "/" + badgeId);
    long randomLong = new Random().nextLong(); //To be able to match 

    BadgeModel badge = null;
    Connection conn = null;

    JSONObject objResponse = new JSONObject();
    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    String name = userAgent.getLoginName();
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }
    try {
        conn = dbm.getConnection();
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_16, "" + randomLong);

        try {
            if (!badgeAccess.isAppIdExist(conn, appId)) {
                objResponse.put("message", "Cannot get badge. App not found");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
            }
        } catch (SQLException e1) {
            e1.printStackTrace();
            objResponse.put("message",
                    "Cannot get badge. Cannot check whether application ID exist or not. Database error. "
                            + e1.getMessage());
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
        }
        badge = badgeAccess.getBadgeWithId(conn, appId, badgeId);
        if (badge == null) {
            objResponse.put("message", "Cannot get badge. Badge model is null.");
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
        }
        ObjectMapper objectMapper = new ObjectMapper();
        //Set pretty printing of json
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

        String badgeString = objectMapper.writeValueAsString(badge);
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_17, "" + randomLong);
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_26, "" + name);
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_27, "" + appId);
        return new HttpResponse(badgeString, HttpURLConnection.HTTP_OK);

    } catch (JsonProcessingException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot get badge. Cannot process JSON." + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(e.getMessage(), HttpURLConnection.HTTP_INTERNAL_ERROR);

    } catch (SQLException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot get badge. Database Error. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    }
    // always close connections
    finally {
        try {
            conn.close();
        } catch (SQLException e) {
            logger.printStackTrace(e);
        }
    }
}

From source file:com.msopentech.thali.relay.RelayWebServer.java

@Override
public Response serve(IHTTPSession session) {
    Method method = session.getMethod();
    String queryString = session.getQueryParameterString();
    String path = session.getUri();
    Map<String, String> headers = session.getHeaders();

    LOG.info("URI + Query: " + path + (queryString == null ? "" : "?" + queryString));
    LOG.info("METHOD: " + method.toString());
    LOG.info("ORIGIN: " + headers.get("origin"));

    // Handle an OPTIONS request without relaying anything for now
    // TODO: Relay OPTIONS properly, but manage the CORS aspects so
    // we don't introduce dependencies on couch CORS configuration
    if (method.name().equalsIgnoreCase("OPTIONS")) {
        Response optionsResponse = new Response("OK");
        AppendCorsHeaders(optionsResponse, headers);
        optionsResponse.setStatus(Response.Status.OK);
        return optionsResponse;
    }/*from w  ww . j  a v a  2  s .  c  om*/

    // Handle request for local HTTP Key URL
    // TODO: Temporary fake values, need to build hook to handle magic URLs and generate proper HTTPKey
    if (path.equalsIgnoreCase("/_relayutility/localhttpkeys")) {
        ObjectMapper mapper = new ObjectMapper();
        String responseBody = null;
        try {
            responseBody = mapper.writeValueAsString(httpKeyTypes);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Could not generate localhttpkeys output", e);
        }
        Response httpKeyResponse = new Response(responseBody);
        AppendCorsHeaders(httpKeyResponse, headers);
        httpKeyResponse.setMimeType("application/json");
        httpKeyResponse.setStatus(Response.Status.OK);
        return httpKeyResponse;
    }

    // Get the body of the request if appropriate
    byte[] requestBody = new byte[0];
    if (method.equals(Method.PUT) || method.equals(Method.POST)) {
        try {
            ByteBuffer bodyBuffer = ((HTTPSession) session).getBody();
            if (bodyBuffer != null) {
                requestBody = new byte[bodyBuffer.remaining()];
                bodyBuffer.get(requestBody);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return GenerateErrorResponse(e.getMessage());
        }
    }

    // Make a new request which we will prepare for relaying to TDH
    BasicHttpEntityEnclosingRequest basicHttpRequest = null;
    try {
        basicHttpRequest = buildRelayRequest(method, path, queryString, headers, requestBody);
    } catch (UnsupportedEncodingException e) {
        String message = "Unable to translate body to new request.\n" + ExceptionUtils.getStackTrace(e);
        return GenerateErrorResponse(message);
    } catch (URISyntaxException e) {
        return GenerateErrorResponse(
                "Unable to generate the URL for the local TDH.\n" + ExceptionUtils.getStackTrace(e));
    }

    // Actually make the relayed call
    HttpResponse tdhResponse = null;
    InputStream tdhResponseContent = null;
    Response clientResponse = null;
    try {
        LOG.info("Relaying call to TDH: " + httpHost.toURI());
        tdhResponse = httpClient.execute(httpHost, basicHttpRequest);
        tdhResponseContent = tdhResponse.getEntity().getContent();

        // Create response and set status and body
        // default the MIME_TYPE for now and we'll set it later when we enumerate the headers
        if (tdhResponse != null) {

            // This is horrible awful evil code to deal with CouchBase note properly sending CouchDB responses
            // for some errors. We must fix this in CouchBase - https://github.com/thaliproject/thali/issues/30
            String responseBodyString = null;
            if (tdhResponse.containsHeader("content-type") && tdhResponse.getFirstHeader("content-type")
                    .getValue().equalsIgnoreCase("application/json")) {
                if (tdhResponse.getStatusLine().getStatusCode() == 404) {
                    responseBodyString = "{\"error\":\"not_found\"}";
                }
                if (tdhResponse.getStatusLine().getStatusCode() == 412) {
                    responseBodyString = "{\"error\":\"missing_id\"}";
                }
            }

            clientResponse = new Response(new RelayStatus(tdhResponse.getStatusLine()),
                    NanoHTTPD.MIME_PLAINTEXT,
                    responseBodyString != null ? IOUtils.toInputStream(responseBodyString)
                            : IOUtils.toBufferedInputStream(tdhResponseContent));
            // If there is a response body we want to send it chunked to enable streaming
            clientResponse.setChunkedTransfer(true);
        }
    } catch (IOException e) {
        String message = "Reading response failed!\n" + ExceptionUtils.getStackTrace(e);
        return GenerateErrorResponse(message);
    } finally {
        // Make sure the read stream is closed so we don't exhaust our pool
        if (tdhResponseContent != null)
            try {
                tdhResponseContent.close();
            } catch (IOException e) {
                LOG.error(e.getMessage());
            }
    }

    // Prep all headers for our final response
    AppendCorsHeaders(clientResponse, headers);
    copyHeadersToResponse(clientResponse, tdhResponse.getAllHeaders());

    return clientResponse;
}

From source file:org.apache.asterix.test.common.TestExecutor.java

protected HttpUriRequest constructPostMethodJson(String statement, URI uri, String stmtParam,
        List<CompilationUnit.Parameter> otherParams) {
    if (stmtParam == null) {
        throw new NullPointerException("Statement parameter required.");
    }//  w  w  w  .j  av  a 2s . c om
    RequestBuilder builder = RequestBuilder.post(uri);
    ObjectMapper om = new ObjectMapper();
    ObjectNode content = om.createObjectNode();
    for (CompilationUnit.Parameter param : upsertParam(otherParams, stmtParam, statement)) {
        content.put(param.getName(), param.getValue());
    }
    try {
        builder.setEntity(new StringEntity(om.writeValueAsString(content), ContentType.APPLICATION_JSON));
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    builder.setCharset(StandardCharsets.UTF_8);
    return builder.build();
}

From source file:edu.cmu.cs.lti.discoursedb.api.browsing.controller.BrowsingRestController.java

@RequestMapping(value = "/prop_list", method = RequestMethod.GET)
@ResponseBody/*from w  ww.j  a  va2 s.co m*/
String prop_list(@RequestParam(value = "ptype", defaultValue = "*") String ptype, HttpServletRequest hsr,
        HttpSession session) {
    logger.info("Authenticating /prop_list");
    securityUtils.authenticate(hsr, session);
    logger.info("Authenticated /prop_list");

    logger.info("Requested property list of type " + ptype + " for user "
            + SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());

    List<SystemUserProperty> props = systemUserService.getPropertyList(ptype);
    ObjectMapper mapper = new ObjectMapper();
    try {
        return mapper.writeValueAsString(props);
    } catch (JsonProcessingException e) {
        // TODO Auto-generated catch block
        logger.info("Could not output property list!");
        e.printStackTrace();
        return "";
    }
}

From source file:webServices.RestServiceImpl.java

@GET
@Path("/findTwittsRest")
@Produces({ MediaType.TEXT_PLAIN })/*w w  w .  j  a  v a2s.  c  o  m*/
public String twitterSearchRest(@QueryParam("keys") String searchKeys, @QueryParam("sinceId") long sinceId,
        @QueryParam("maxId") long maxId, @QueryParam("update") boolean update,
        @QueryParam("location") String location) {

    final Vector<String> results = new Vector<String>();
    String output = "";
    long higherStatusId = Long.MIN_VALUE;
    long lowerStatusId = Long.MAX_VALUE;

    Query searchQuery = new Query(searchKeys);
    searchQuery.setCount(50);
    searchQuery.setResultType(Query.ResultType.recent);

    if (sinceId != 0) {
        if (update) {
            searchQuery.setSinceId(sinceId);
        }
        higherStatusId = sinceId;
    }
    if (maxId != 0) {
        if (!update) {
            searchQuery.setMaxId(maxId);
        }
        lowerStatusId = maxId;
    }
    if (location != null) {
        double lat = Double.parseDouble(location.substring(0, location.indexOf(",")));
        double lon = Double.parseDouble(location.substring(location.indexOf(",") + 1, location.length()));

        searchQuery.setGeoCode(new GeoLocation(lat, lon), 10, Query.KILOMETERS);
    }

    try {
        QueryResult qResult = twitter.search(searchQuery);

        for (Status status : qResult.getTweets()) {
            //System.out.println(Long.toString(status.getId())+"  ***  "+Long.toString(status.getUser().getId())+"  ***  "+status.isRetweet()+"  ***  "+status.isRetweeted());

            higherStatusId = Math.max(status.getId(), higherStatusId);
            lowerStatusId = Math.min(status.getId(), lowerStatusId);

            if (!status.isRetweet()) {
                if (status.getGeoLocation() != null) {
                    System.out.println(Long.toString(status.getId()) + "@"
                            + Double.toString(status.getGeoLocation().getLatitude()) + ","
                            + Double.toString(status.getGeoLocation().getLongitude()));
                    results.add(Long.toString(status.getId()) + "@"
                            + Double.toString(status.getGeoLocation().getLatitude()) + ","
                            + Double.toString(status.getGeoLocation().getLongitude()));
                } else {
                    results.add(Long.toString(status.getId()) + "@null");
                }
            }
        }

    } catch (TwitterException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    TwitterResults resultsObj = new TwitterResults(results.toString(), higherStatusId, lowerStatusId);
    ObjectMapper mapper = new ObjectMapper();
    try {
        output = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(resultsObj);
    } catch (JsonProcessingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return output;
}

From source file:org.o3project.ocnrm.odenos.linklayerizer.LinkLayerizer.java

private String getFlows() {
    logger.info("getFlows Start");

    String rtnJsonVal = "";
    try {// w w  w.  j  a  v  a 2s.  c o m
        ObjectMapper mapper = new ObjectMapper();
        rtnJsonVal = mapper.writeValueAsString(lowerflows);
        logger.debug("jsonFlows:" + rtnJsonVal);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
        logger.error("** Failed to getFlows {}", lowerflows);
    }

    logger.info("getFlows End");
    return rtnJsonVal;
}

From source file:org.o3project.ocnrm.odenos.linklayerizer.LinkLayerizer.java

private String getLinks() {
    logger.info("getLinks Start");

    String rtnJsonVal = "";
    try {//from   ww  w  . j  a  va  2 s.  com
        ObjectMapper mapper = new ObjectMapper();
        rtnJsonVal = mapper.writeValueAsString(layerizedlinks);
        logger.debug("jsonLinks:" + rtnJsonVal);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
        logger.error("** Failed to getLinks {}", layerizedlinks);
    }

    logger.info("getLinks End");
    return rtnJsonVal;
}