Example usage for java.lang RuntimeException getStackTrace

List of usage examples for java.lang RuntimeException getStackTrace

Introduction

In this page you can find the example usage for java.lang RuntimeException getStackTrace.

Prototype

public StackTraceElement[] getStackTrace() 

Source Link

Document

Provides programmatic access to the stack trace information printed by #printStackTrace() .

Usage

From source file:org.nuxeo.binary.metadata.test.MetadataReaderTest.java

protected String getCurrentMethodName(RuntimeException e) {
    StackTraceElement currentElement = e.getStackTrace()[0];
    return currentElement.getMethodName();
}

From source file:org.seadva.metadatagen.service.MetadataGenerator.java

@POST
@Path("/oremap")
@Consumes(MediaType.APPLICATION_JSON)//from www .j a v  a 2s. c o  m
@Produces(MediaType.APPLICATION_JSON)
public Response putOreMap(String publicationRequestString, @QueryParam("requestUrl") String requestURL)
        throws JSONException {
    try {
        String messageString = "";
        Document request = Document.parse(publicationRequestString);
        Document content = (Document) request.get("Aggregation");
        if (content == null) {
            messageString += "Missing Aggregation";
        }

        if (messageString.equals("")) {
            // Get organization from profile(s)
            // Add to base document
            String ID = (String) content.get("Identifier");

            // retrieve OREMap
            Document aggregation = (Document) request.get("Aggregation");
            Client client = Client.create();
            WebResource webResource;

            webResource = client.resource(aggregation.get("@id").toString());
            webResource.addFilter(new RedirectFilter());

            ClientResponse response = null;
            try {
                response = webResource.accept("application/json").get(ClientResponse.class);
                if (response.getStatus() != 200) {
                    String message = "Error while retrieving OREMap from Project Space - Response : "
                            + response.getStatus();
                    System.out.println(MetadataGenerator.class.getName() + " - " + message);
                    return Response.status(ClientResponse.Status.BAD_REQUEST).entity(message).build();
                }
            } catch (RuntimeException e) {
                String message = "Error while retrieving OREMap from Project Space - Response : "
                        + e.getMessage();
                System.out.println(MetadataGenerator.class.getName() + " - " + message);
                return Response.status(ClientResponse.Status.BAD_REQUEST).entity(message).build();
            }

            String oreString = response.getEntity(String.class);

            OREMetadataGen oreMetadataGen = new OREMetadataGen();
            if (!oreMetadataGen.hasValidOREMetadata(oreString)) {
                String message = "Error occurred while validating OREMap : " + oreMetadataGen.getErrorMsg();
                System.out.println(MetadataGenerator.class.getName() + " - " + message);
                return Response.status(ClientResponse.Status.BAD_REQUEST).entity(message).build();
            }

            Document oreMapDocument = Document.parse(oreString);
            ObjectId mapId = new ObjectId();
            //oreMapDocument.put("_id", mapId);

            //Update 'actionable' identifiers for map and aggregation:
            //Note these changes retain the tag-style identifier for the aggregation created by the space
            //These changes essentially work like ARKs/ARTs and represent the <aggId> moving from the custodianship of the space <SpaceURL>/<aggId>
            // to that of the CP services <servicesURL>/<aggId>
            String newMapURL = requestURL + "/" + ID + "/oremap";

            //@id of the map in the map
            oreMapDocument.put("@id", newMapURL);

            //@id of describes object (the aggregation)  in map
            ((Document) oreMapDocument.get("describes")).put("@id", newMapURL + "#aggregation");

            ClientResponse postResponse = pdtWebService.path("researchobjects").path("/oremap")
                    .queryParam("objectId", mapId.toString()).accept("application/json")
                    .type("application/json").post(ClientResponse.class, oreMapDocument.toJson().toString());

            if (postResponse.getStatus() == 200 && !oreMetadataGen.getSkipValidation()) {
                return Response.ok(new JSONObject().put("id", mapId).toString()).build();
            } else if (postResponse.getStatus() == 200 && oreMetadataGen.getSkipValidation()) {
                try {
                    return Response.created(new URI(newMapURL)).entity(new JSONObject().put("id", mapId)
                            .put("warning", oreMetadataGen.getErrorMsg()).toString()).build();
                } catch (URISyntaxException e) {
                    System.out.println(MetadataGenerator.class.getName() + ": Error while persisting OREMap : "
                            + e.getMessage());
                    return Response.serverError().build();
                }
            } else {
                System.out.println(MetadataGenerator.class.getName()
                        + ": Error while persisting OREMap in PDT - Response : " + postResponse.getStatus());
                return Response.serverError().build();
            }
        } else {
            System.out.println(MetadataGenerator.class.getName() + ": Bad Request : " + messageString);
            return Response.status(ClientResponse.Status.BAD_REQUEST).entity(messageString).build();
        }
    } catch (Exception e) {
        System.out.println(e.getStackTrace());
        System.out.println(e.getMessage());
        e.printStackTrace();
        return Response.status(ClientResponse.Status.BAD_REQUEST)
                .entity("Exception thrown when persisting OREMap" + e.getMessage()).build();
    }
}

From source file:smilehouse.opensyncro.pipes.Pipe.java

private void addLogEntry(LogEntry logEntry, int statusCode) {
    if (this.log == null)
        this.log = new HashSet();

    logEntry.setStatusCode(statusCode);//w  ww. j a  v  a 2  s.co  m
    logEntry.setTime(new Date());

    // The LogEntry is not explicitly added to the Pipe's log Set, since it causes
    // Hibernate to query all LogEntries from the database and thus consume
    // ever-increasing amount of server resources.

    //this.log.add(logEntry);
    String status = getStatusString(statusCode);

    Persister persister = new Persister(database);

    try {
        persister.update(logEntry);

        List messages;

        boolean mailAddressNotSet = ((getMailHost() == null || getRecipientAddress() == null)
                || (getMailHost().length() == 0 || getRecipientAddress().length() == 0));

        // Notification via email only if host and email address are present
        if (!mailAddressNotSet && !(getTransferLogNotificationLevel() == MessageLogger.MAIL_NONE)) {

            String date = dateFormat.format(new Date());
            String subject = this.getName() + " " + status + " " + date + " (" + database + ")";
            String message = "";

            // Get number of log messages at or below transferLogNotificationLevel.  

            int entries = persister.getLogMessageEntries(logEntry.getId(), getTransferLogNotificationLevel())
                    .size();

            //Generate mail message
            if (entries > 0) {

                messages = persister.getLogMessageEntries(logEntry.getId(), getLoggingVerbosityLevel());
                for (Iterator m = messages.iterator(); m.hasNext();) {
                    LogMessageEntry messageEntry = (LogMessageEntry) m.next();
                    message += (messageEntry.getMessage()) + "\n";
                }
            } else {
                message += MAIL_MESSAGE_NO_ENTRIES;
            }

            // Send notification email except when the message is
            // MAIL_MESSAGE_NO_ENTRIES or the pipe has aborted and 
            // isAbortMailEnabled()==true 
            if (!message.equals(MAIL_MESSAGE_NO_ENTRIES)
                    || (statusCode == LogEntry.STATUS_ABORTED && isAbortMailEnabled())) {
                try {

                    Properties props = new Properties();
                    props.put("mail.host", getMailHost());

                    Session mailConnection = Session.getInstance(props, null);
                    Message msg = new MimeMessage(mailConnection);
                    Address sender = new InternetAddress(MAIL_SENDER + "@" + getMailHost(), MAIL_SENDER);
                    Address[] receivers = receiverAddresses(getRecipientAddress());

                    // Set mail content and subject
                    msg.setContent(message, "text/plain");
                    msg.setFrom(sender);
                    msg.setRecipients(Message.RecipientType.TO, receivers);
                    msg.setSubject(subject);

                    // Send the mail
                    Transport.send(msg);

                } catch (MessagingException e) {
                    String error = "An error occurred when sending mail report from " + MAIL_SENDER + "@"
                            + getMailHost() + " to " + getRecipientAddress() + ":\n" + e.getMessage();
                    Environment.getInstance().log(error);
                    logEntry.logMessage(error, this, MessageLogger.ERROR);
                    persister.update(logEntry);
                } catch (RuntimeException ex) {
                    Environment.getInstance().log("A RuntimeException has occurred: " + ex.getMessage()
                            + ex.getStackTrace().toString());
                }
            }
        }
        // Remove unnecessary (debug level) messages from the LogEntry if Transfer log
        // verbosity level is set to DYNAMIC and the current LogEntry's status is either
        // OK or ABORTED
        if (getLoggingVerbosityLevel() == MessageLogger.LOG_DYNAMIC
                && (statusCode == LogEntry.STATUS_OK || statusCode == LogEntry.STATUS_ABORTED)) {
            messages = persister.getLogMessageEntries(logEntry.getId(), MessageLogger.DEBUG);
            if (messages.size() > 0) {
                for (Iterator m = messages.iterator(); m.hasNext();) {
                    LogMessageEntry messageEntry = (LogMessageEntry) m.next();
                    if (messageEntry.getMessageType() == MessageLogger.DEBUG) {
                        persister.delete(messageEntry);

                    }
                }
            }
        }
    } catch (Exception e) {
        Environment.getInstance().log(e.getMessage());
    } finally {
        persister.close();
    }
}

From source file:za.co.eon.econtentsolutions.component.abstractlticomponent.AbstractLTIComponentServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  w  ww .jav  a 2 s.  c om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try (PrintWriter out = response.getWriter()) {
        Launch launch = tsugi.getLaunch(request, response);
        if (launch.isComplete()) {
            launch.getOutput().flashSuccess("LTI Launch validated and redirected");
            log.info("LTI Launch validated and redirected...");
            return;
        }
        if (!launch.isValid()) {
            out.println("<pre>");
            out.println("Launch is not valid but nowhere to redirect");
            out.println(launch.getErrorMessage());
            out.println("Base String:");
            out.println(launch.getBaseString());
            out.println("</pre>");
            out.close();

            throw new RuntimeException(launch.getErrorMessage());
        }

        HttpSession session = request.getSession();
        Output o = launch.getOutput();

        Properties versions = o.header(out);
        o.bodyStart(out);
        o.flashMessages(out);

        //
        out.println("<pre>");

        // Dump out some stuff from the Request Object
        out.println("");
        out.println(
                "<a href=\"http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html\" target=\"_blank\">HttpServletRequest</a> data:");
        out.println("req.getRequestURL()=" + request.getRequestURL());
        out.println("req.getMethod()=" + request.getMethod());
        out.println("req.getServletPath()=" + request.getServletPath());
        out.println("req.getPathInfo()=" + request.getPathInfo());
        out.println("req.getQueryString()=" + request.getQueryString());

        out.println("");
        out.print("<a href=\"");
        out.print(launch.getGetUrl(null) + "/zap");
        out.println("\">Click here to see if we stay logged in with a GET</a>");

        out.println("");
        out.println(
                "Using the <a href=\"http://csev.github.io/tsugi-java/apidocs/index.html\" target=\"_blank\">Tsugi API</a>:");
        out.println("Content Title: " + launch.getContext().getTitle());
        out.println("Context Settings: " + launch.getContext().getSettings().getSettingsJson());
        out.println("User Email: " + launch.getUser().getEmail());
        out.println("isInstructor()=" + launch.getUser().isInstructor());
        out.println("isTenantAdmin()=" + launch.getUser().isTenantAdmin());
        out.println("Link Title: " + launch.getLink().getTitle());
        out.println("Link Settings: " + launch.getLink().getSettings().getSettingsJson());
        out.println("Sourcedid: " + launch.getResult().getSourceDID());
        out.println("Service URL: " + launch.getService().getURL());
        out.println("");
        out.println("JavaScript library versions:");
        out.println(TsugiUtils.dumpProperties(versions));

        out.println("");
        out.println("Using the provided JDBC connection:");
        Connection c = null;
        try {
            c = launch.getConnection();
            out.println("Connection: " + c);
            DatabaseMetaData meta = c.getMetaData();
            String productName = meta.getDatabaseProductName();
            String productVersion = meta.getDatabaseProductVersion();
            String URL = meta.getURL();
            out.println("Connection product=" + productName + " version=" + productVersion);
            out.println("Connection URL=" + URL);
        } catch (Exception ex) {
            log.error("Unable to get connection metadata", ex);
            out.println("Unable to get connection metadata:" + ex.getMessage());
        }

        // Do a simple query just to see how it is done
        if (c != null) {
            Statement stmt = null;
            String query = "SELECT plugin_id, plugin_path FROM lms_plugins;";

            try {
                stmt = c.createStatement();
                ResultSet rs = stmt.executeQuery(query);
                int num = 0;
                while (rs.next()) {
                    String plugin_path = rs.getString("plugin_path");
                    out.println("plugin_path=" + plugin_path);
                    num++;
                }
                out.println("Successfully read " + num + " rows from the database");
            } catch (SQLException e) {
                out.println("Problems reading database");
                out.println("INSERT INTO mjjs (name) VALUES ('tsugi');");
                e.printStackTrace();
            }
        }

        // Cheat and look at the internal data Tsugi maintains - this depends on
        // the JDBC implementation
        Properties sess_row = (Properties) session.getAttribute("lti_row");
        if (sess_row != null) {
            out.println("");
            out.println("Tsugi-managed internal session data (Warning: org.tsugi.impl.jdbc.Tsugi_JDBC only)");
            String x = TsugiUtils.dumpProperties(sess_row);
            out.println(x);
        }

        out.println("</pre>");

        // Do the Footer
        o.footerStart(out);
        out.println("<!-- App footer stuff goes here -->");
        o.footerEnd(out);

        out.close();
    } catch (RuntimeException re) {
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>AbstractLTIComponentServlet Error</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>AbstractLTIComponentServlet</h1>");
            out.println("<h3 style=\"color: red;\">Error</h3>");
            out.println("<p>Servlet AbstractLTIComponentServlet at " + request.getContextPath()
                    + " threw an exception.</p>");
            out.println("<p>Exception: " + re.toString() + "<br />");
            out.println("Message: " + re.getMessage() + "<br />");
            out.println("Stacktrace:</p>");
            out.println("<p>" + re.getStackTrace().toString() + "</p>");
            out.println("</body>");
            out.println("</html>");
        }
    }
}