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

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

Introduction

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

Prototype

@Override
public String getMessage() 

Source Link

Document

Default method overridden so that we can add location information

Usage

From source file:controllers.core.OrgUnitController.java

/**
 * Display the gantt of actors' allocations of the org unit.
 * /*from   w ww  .  j a  v  a2s.  c o m*/
 * @param id
 *            the org unit id
 */
@With(CheckOrgUnitExists.class)
@Dynamic(IMafConstants.ORG_UNIT_VIEW_DYNAMIC_PERMISSION)
public Result allocation(Long id) {

    // get the org unit
    OrgUnit orgUnit = OrgUnitDao.getOrgUnitById(id);

    // prepare the data (to order them)
    SortableCollection<DateSortableObject> sortableCollection = new SortableCollection<>();
    for (PortfolioEntryResourcePlanAllocatedActor allocatedActor : PortfolioEntryResourcePlanDAO
            .getPEPlanAllocatedActorAsListByOrgUnitAndActive(id, true)) {
        if (allocatedActor.endDate != null) {
            sortableCollection.addObject(new DateSortableObject(allocatedActor.endDate, allocatedActor));
        }
    }
    for (TimesheetActivityAllocatedActor allocatedActivity : TimesheetDao
            .getTimesheetActivityAllocatedActorAsListByOrgUnit(id, true)) {
        if (allocatedActivity.endDate != null) {
            sortableCollection.addObject(new DateSortableObject(allocatedActivity.endDate, allocatedActivity));
        }
    }

    // construct the gantt

    List<SourceItem> items = new ArrayList<SourceItem>();

    for (DateSortableObject dateSortableObject : sortableCollection.getSorted()) {

        if (dateSortableObject.getObject() instanceof PortfolioEntryResourcePlanAllocatedActor) {

            PortfolioEntryResourcePlanAllocatedActor allocatedActor = (PortfolioEntryResourcePlanAllocatedActor) dateSortableObject
                    .getObject();

            // get the from date
            Date from = allocatedActor.startDate;

            // get the to date
            Date to = allocatedActor.endDate;

            // get the portfolio entry
            Long portfolioEntryId = allocatedActor.portfolioEntryResourcePlan.lifeCycleInstancePlannings
                    .get(0).lifeCycleInstance.portfolioEntry.id;
            PortfolioEntry portfolioEntry = PortfolioEntryDao.getPEById(portfolioEntryId);

            String packageName = allocatedActor.portfolioEntryPlanningPackage != null
                    ? allocatedActor.portfolioEntryPlanningPackage.getName() + " / "
                    : "";

            SourceItem item = new SourceItem(allocatedActor.actor.getNameHumanReadable(),
                    portfolioEntry.getName());

            String cssClass = null;

            if (from != null) {

                to = JqueryGantt.cleanToDate(from, to);
                cssClass = "";

            } else {

                from = to;
                cssClass = "diamond diamond-";

            }

            if (allocatedActor.isConfirmed) {
                cssClass += "success";
            } else {
                cssClass += "warning";
            }

            SourceDataValue dataValue = new SourceDataValue(
                    controllers.core.routes.PortfolioEntryPlanningController.resources(portfolioEntry.id).url(),
                    null, null, null, null);

            item.values.add(new SourceValue(from, to, "",
                    packageName + views.html.framework_views.parts.formats.display_number
                            .render(allocatedActor.days, null, false).body(),
                    cssClass, dataValue));

            items.add(item);

        }

        if (dateSortableObject.getObject() instanceof TimesheetActivityAllocatedActor) {

            TimesheetActivityAllocatedActor allocatedActivity = (TimesheetActivityAllocatedActor) dateSortableObject
                    .getObject();

            // get the from date
            Date from = allocatedActivity.startDate;

            // get the to date
            Date to = allocatedActivity.endDate;

            SourceItem item = new SourceItem(allocatedActivity.actor.getNameHumanReadable(),
                    allocatedActivity.timesheetActivity.getName());

            String cssClass = null;

            if (from != null) {

                to = JqueryGantt.cleanToDate(from, to);
                cssClass = "";

            } else {

                from = to;
                cssClass = "diamond diamond-";

            }

            cssClass += "info";

            SourceDataValue dataValue = new SourceDataValue(
                    controllers.core.routes.ActorController
                            .allocationDetails(allocatedActivity.actor.id, 0, 0, false).url(),
                    null, null, null, null);

            item.values
                    .add(new SourceValue(from, to, "", views.html.framework_views.parts.formats.display_number
                            .render(allocatedActivity.days, null, false).body(), cssClass, dataValue));

            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.orgunit.org_unit_allocation.render(orgUnit, ganttSource));

}

From source file:org.apache.unomi.services.services.SegmentServiceImpl.java

private void getAutoGeneratedRules(Metadata metadata, Condition condition, Condition parentCondition,
        List<Rule> rules) {
    Set<String> tags = condition.getConditionType().getMetadata().getTags();
    if (tags.contains("eventCondition") && !tags.contains("profileCondition")) {
        try {/*from  w  w  w. ja va 2s  . c o  m*/
            Map<String, Object> m = new HashMap<>(3);
            m.put("scope", metadata.getScope());
            m.put("condition", condition);
            m.put("numberOfDays", parentCondition.getParameter("numberOfDays"));
            String key = CustomObjectMapper.getObjectMapper().writeValueAsString(m);
            key = "eventTriggered" + getMD5(key);
            parentCondition.setParameter("generatedPropertyKey", key);
            Rule rule = rulesService.getRule(key);
            if (rule == null) {
                rule = new Rule(new Metadata(metadata.getScope(), key,
                        "Auto generated rule for " + metadata.getName(), ""));
                rule.setCondition(condition);
                rule.getMetadata().setHidden(true);
                final Action action = new Action();
                action.setActionType(definitionsService.getActionType("setEventOccurenceCountAction"));
                action.setParameter("pastEventCondition", parentCondition);

                rule.setActions(Arrays.asList(action));
                rule.setLinkedItems(Arrays.asList(metadata.getId()));
                rules.add(rule);

                updateExistingProfilesForPastEventCondition(condition, parentCondition);
            } else {
                rule.getLinkedItems().add(metadata.getId());
                rules.add(rule);
            }
        } catch (JsonProcessingException e) {
            logger.error(e.getMessage(), e);
        }
    } else {
        Collection<Object> values = new ArrayList<>(condition.getParameterValues().values());
        for (Object parameterValue : values) {
            if (parameterValue instanceof Condition) {
                getAutoGeneratedRules(metadata, (Condition) parameterValue, condition, rules);
            } else if (parameterValue instanceof Collection) {
                for (Object subCondition : (Collection<?>) parameterValue) {
                    if (subCondition instanceof Condition) {
                        getAutoGeneratedRules(metadata, (Condition) subCondition, condition, rules);
                    }
                }
            }
        }
    }
}

From source file:controllers.core.ActorController.java

/**
 * Display the gantt of allocations of the actor.
 * //from   w  w w  .j  av  a2s  .  c  om
 * @param id
 *            the actor id
 */
@With(CheckActorExists.class)
@Dynamic(IMafConstants.ACTOR_VIEW_DYNAMIC_PERMISSION)
public Result allocation(Long id) {

    // get the actor
    Actor actor = ActorDao.getActorById(id);

    // prepare the data (to order them)
    SortableCollection<DateSortableObject> sortableCollection = new SortableCollection<>();
    for (PortfolioEntryResourcePlanAllocatedActor allocatedActor : PortfolioEntryResourcePlanDAO
            .getPEPlanAllocatedActorAsListByActorAndActive(id, true)) {
        if (allocatedActor.endDate != null) {
            sortableCollection.addObject(new DateSortableObject(allocatedActor.endDate, allocatedActor));
        }
    }
    for (TimesheetActivityAllocatedActor allocatedActivity : TimesheetDao
            .getTimesheetActivityAllocatedActorAsListByActor(id, true)) {
        if (allocatedActivity.endDate != null) {
            sortableCollection.addObject(new DateSortableObject(allocatedActivity.endDate, allocatedActivity));
        }
    }

    // construct the gantt

    List<SourceItem> items = new ArrayList<SourceItem>();

    for (DateSortableObject dateSortableObject : sortableCollection.getSorted()) {

        if (dateSortableObject.getObject() instanceof PortfolioEntryResourcePlanAllocatedActor) {

            PortfolioEntryResourcePlanAllocatedActor allocatedActor = (PortfolioEntryResourcePlanAllocatedActor) dateSortableObject
                    .getObject();

            // get the from date
            Date from = allocatedActor.startDate;

            // get the to date
            Date to = allocatedActor.endDate;

            // get the portfolio entry
            Long portfolioEntryId = allocatedActor.portfolioEntryResourcePlan.lifeCycleInstancePlannings
                    .get(0).lifeCycleInstance.portfolioEntry.id;
            PortfolioEntry portfolioEntry = PortfolioEntryDao.getPEById(portfolioEntryId);

            String packageName = allocatedActor.portfolioEntryPlanningPackage != null
                    ? allocatedActor.portfolioEntryPlanningPackage.getName()
                    : "";

            SourceItem item = new SourceItem(portfolioEntry.getName(), packageName);

            String cssClass = null;

            if (from != null) {

                to = JqueryGantt.cleanToDate(from, to);
                cssClass = "";

            } else {

                from = to;
                cssClass = "diamond diamond-";

            }

            if (allocatedActor.isConfirmed) {
                cssClass += "success";
            } else {
                cssClass += "warning";
            }

            SourceDataValue dataValue = new SourceDataValue(
                    controllers.core.routes.PortfolioEntryPlanningController.resources(portfolioEntry.id).url(),
                    null, null, null, null);

            item.values
                    .add(new SourceValue(from, to, "", views.html.framework_views.parts.formats.display_number
                            .render(allocatedActor.days, null, false).body(), cssClass, dataValue));

            items.add(item);

        }

        if (dateSortableObject.getObject() instanceof TimesheetActivityAllocatedActor) {

            TimesheetActivityAllocatedActor allocatedActivity = (TimesheetActivityAllocatedActor) dateSortableObject
                    .getObject();

            // get the from date
            Date from = allocatedActivity.startDate;

            // get the to date
            Date to = allocatedActivity.endDate;

            SourceItem item = new SourceItem(allocatedActivity.timesheetActivity.getName(), "");

            String cssClass = null;

            if (from != null) {

                to = JqueryGantt.cleanToDate(from, to);
                cssClass = "";

            } else {

                from = to;
                cssClass = "diamond diamond-";

            }

            cssClass += "info";

            SourceDataValue dataValue = new SourceDataValue(
                    controllers.core.routes.ActorController.allocationDetails(actor.id, 0, 0, false).url(),
                    null, null, null, null);

            item.values
                    .add(new SourceValue(from, to, "", views.html.framework_views.parts.formats.display_number
                            .render(allocatedActivity.days, null, false).body(), cssClass, dataValue));

            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.actor.actor_allocation.render(actor, ganttSource));
}

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

/**
 * Get a badge data with specific ID from database
 * @param appId applicationId//from  ww  w.  ja  v a  2  s. c  om
 * @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:edu.cmu.cs.lti.discoursedb.github.converter.GithubConverterService.java

public void addCrossrefs(String refinfo, String source, Discourse discourse, User actor) {
    if (refinfo.length() == 0) {
        return;// w  w  w. j av a 2s.co  m
    }
    try {
        JsonNode node = new ObjectMapper().readValue(new JsonFactory().createParser(refinfo), JsonNode.class);
        for (JsonNode reference : node) {
            JsonNode parts = reference.get("parts");
            String owner = parts.get(0).toString();
            String project = parts.get(1).toString();
            String issueNumString = parts.get(2).toString().replaceAll("[^0-9]+", "");
            String rev = parts.get(3).toString();

            long issuenum = Long.parseLong(issueNumString);

            String issueIdentifier = GithubConverterUtil.standardIssueIdentifier(owner + "/" + project,
                    issuenum);
            DiscoursePart issueDP = getDiscoursePart(discourse, issueIdentifier,
                    DiscoursePartTypes.GITHUB_ISSUE);
            DiscoursePartInteraction dpi = userService.createDiscoursePartInteraction(actor, issueDP,
                    DiscoursePartInteractionTypes.REFER);

            AnnotationInstance crossref = annotationService.createTypedAnnotation("CrossrefFrom");
            annotationService.addAnnotation(dpi, crossref);
            annotationService.addFeature(crossref, annotationService.createTypedFeature(source, "Source"));
        }
    } catch (JsonProcessingException je) {
        logger.error("Could not parse " + refinfo + " from " + source + ": " + je.getMessage());
    } catch (IOException e) {
        logger.error("Could not parse " + refinfo + " from " + source + ": " + e.getMessage());
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

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 w  w. jav  a 2 s  .c  o m*/

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

/**
 * Get all application list separated into two categories. All apps registered for the member and other apps.
 * /*from  ww  w.  j  a va  2 s  . com*/
 * 
 * @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:ac.ucy.cs.spdx.service.Compatibility.java

@POST
@Path("/edge/")
@Consumes(MediaType.TEXT_PLAIN)/*from ww  w .  j  a v  a  2s. c om*/
@Produces(MediaType.APPLICATION_JSON)
public String addEdge(String jsonString) {

    ObjectMapper mapper = new ObjectMapper();
    JsonNode licenseEdge = null;
    try {
        licenseEdge = mapper.readTree(jsonString);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    ArrayList<String> licenseNodes = new ArrayList<String>();
    String nodeIdentifier = licenseEdge.get("nodeIdentifier").toString();
    nodeIdentifier = nodeIdentifier.substring(1, nodeIdentifier.length() - 1);

    String transitivity = licenseEdge.get("transitivity").toString();
    transitivity = transitivity.substring(1, transitivity.length() - 1);
    Boolean isTransitive = Boolean.parseBoolean(transitivity);

    JsonNode nodesJSON = licenseEdge.get("nodeIdentifiers");

    for (int i = 0; i < nodesJSON.size(); i++) {
        String node = nodesJSON.get(i).get("identifier").toString();
        node = node.substring(1, node.length() - 1);
        licenseNodes.add(node);
    }

    try {
        LicenseGraph.connectNode(isTransitive, nodeIdentifier,
                licenseNodes.toArray(new String[licenseNodes.size()]));
    } catch (LicenseEdgeAlreadyExistsException e) {
        e.printStackTrace();
        return "{\"status\":\"failure\",\"message\":\"" + e.getMessage() + "\"}";
    }

    LicenseGraph.exportGraph();

    return "{\"status\":\"success\",\"message\":\"" + nodeIdentifier + " -> " + licenseNodes.toString()
            + " added in the system.\"}";// {"nodeIdentifier":"Caldera","transitivity":"true","nodeIdentifiers":[{"identifier":"Apache-2.0"}]}
}

From source file:org.mayocat.theme.internal.DefaultThemeManager.java

private Theme getTheme(String themeId, Optional<Tenant> tenant, List<Level> ignore) {
    Level level = Level.TENANT_DIRECTORY;
    JsonNode node;//from   w w  w. ja v a 2 s  .c  o m

    Path themeDirectory = null;

    if (tenant.isPresent() && !ignore.contains(Level.TENANT_DIRECTORY)) {
        themeDirectory = getTenantThemeDirectory(tenant.get().getSlug(), themeId);
    }

    if ((themeDirectory == null || !themeDirectory.toFile().exists())
            && !ignore.contains(Level.THEME_DIRECTORY)) {
        level = Level.THEME_DIRECTORY;
        themeDirectory = getGlobalThemeDirectory(themeId);
    }

    if (themeDirectory == null || !themeDirectory.toFile().exists()) {
        Optional<Path> path = getClasspathThemePath(themeId);
        if (path.isPresent() && !ignore.contains(Level.CLASSPATH)) {
            try {
                node = mapper.readTree(Resources.getResource(path.get().resolve(THEME_YML).toString()));
                ThemeDefinition definition = mapper.readValue(new TreeTraversingParser(node),
                        ThemeDefinition.class);

                return new Theme(path.get(), definition, null, Theme.Type.CLASSPATH);
            } catch (JsonProcessingException e) {
                Theme theme = new Theme(path.get(), null, null, Theme.Type.CLASSPATH, false);
            } catch (IOException e) {
                // Surrender
                logger.error("Could not resolve theme", e);
                return null;
            }
        } else {
            // Here there is nothing more we can do ; surrender
            return null;
        }
    }

    if (themeDirectory == null || !themeDirectory.resolve("theme.yml").toFile().isFile()) {
        // Theme not found
        return null;
    }

    ThemeDefinition definition = null;
    Theme parent = null;
    boolean definitionValid = true;
    logger.debug("Theme directory resolved to [{}]", themeDirectory.toString());
    try {
        node = mapper.readTree(themeDirectory.resolve("theme.yml").toFile());
        definition = mapper.readValue(new TreeTraversingParser(node), ThemeDefinition.class);
    } catch (JsonProcessingException e) {
        definition = null;
        definitionValid = false;
        logger.warn("Trying to load invalid theme. Error: {}", e.getMessage());
    } catch (IOException e) {
        logger.error("I/O exception parsing theme", e);
        // theme.yml file not found -> theme might have a parent
        if (tenant.isPresent()) {
            parent = getTheme(themeId, Optional.<Tenant>absent(), Arrays.asList(level));
        }
    }

    Theme theme = new Theme(themeDirectory, definition, parent, Theme.Type.FILE_SYSTEM, definitionValid);
    if (!level.equals(Level.THEME_DIRECTORY)) {
        // The theme lives in the tenant directory
        theme.setTenantOwnTheme(true);
    }

    return theme;
}