Example usage for java.lang StackTraceElement toString

List of usage examples for java.lang StackTraceElement toString

Introduction

In this page you can find the example usage for java.lang StackTraceElement toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of this stack trace element.

Usage

From source file:org.bonitasoft.engine.LocalServerTestsInitializer.java

private void printThread(final Thread thread) {
    System.out.println("\n");
    System.out.println("Thread is still alive:" + thread.getName());
    for (StackTraceElement stackTraceElement : thread.getStackTrace()) {
        System.out.println("        at " + stackTraceElement.toString());
    }/*from ww w . j  a v a  2s.  c  o  m*/
}

From source file:org.kepler.sms.SemanticType.java

private void tryWriteOutStackTrace() throws IOException {
    File file;//from  w  ww .ja  v  a  2  s .  c  om
    BufferedWriter writer;
    try {
        throw new Exception();
    } catch (Exception ex) {
        StackTraceElement[] stackTrace = ex.getStackTrace();
        if (!isGoodTrace(stackTrace)) {
            log.debug("Not writing out this trace");
            return;
        }
        file = File.createTempFile("exception", ".txt");
        writer = new BufferedWriter(new FileWriter(file));
        for (StackTraceElement element : ex.getStackTrace()) {
            writer.write(element.toString());
            writer.write("\n");
        }
    }
    writer.close();
    log.info("Wrote stack trace to: " + file.getAbsolutePath());
}

From source file:fr.paris.lutece.plugins.directory.web.action.DirectoryActionResult.java

/**
 * Build the error message for action results
 * @param e the exception/*from  w  w  w  . j  av  a2 s.  c  o  m*/
 * @return the error message
 */
private String buildErrorMessage(Exception e) {
    String strError = e.getMessage();

    if (StringUtils.isBlank(strError) && (e.getStackTrace() != null) && (e.getStackTrace().length > 0)) {
        StringBuilder sbError = new StringBuilder();

        for (StackTraceElement ele : e.getStackTrace()) {
            sbError.append(ele.toString());
            sbError.append("\n");
        }

        strError = sbError.toString();
    }

    return strError;
}

From source file:io.bitgrillr.gocddockerexecplugin.DockerExecPlugin.java

private void logException(Exception e) {
    JobConsoleLogger.getConsoleLogger().printLine(e.getMessage());
    for (StackTraceElement ste : e.getStackTrace()) {
        JobConsoleLogger.getConsoleLogger().printLine("\t" + ste.toString());
    }/*from  w  w w .j  a  v a  2  s . c om*/
}

From source file:com.google.step2.example.consumer.servlet.LoginServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    log.info("Login Servlet Post");

    // posted means they're sending us an OpenID4
    StringBuffer realmBuf = new StringBuffer(req.getScheme()).append("://").append(req.getServerName());

    if ((req.getScheme().equalsIgnoreCase("http") && req.getServerPort() != 80)
            || (req.getScheme().equalsIgnoreCase("https") && req.getServerPort() != 443)) {
        realmBuf.append(":").append(req.getServerPort());
    }/*from   w ww  .  ja  va2  s  .  c om*/

    String realm = realmBuf.toString();
    String returnToUrl = new StringBuffer(realm).append(req.getContextPath()).append(REDIRECT_PATH).toString();

    // this is magic - normally this would also fall out of the discovery:
    OAuthAccessor accessor = null;

    // Fetch an unauthorized OAuth request token to test authorizing
    if (YES_STRING.equals(req.getParameter("oauth"))) {
        try {
            accessor = providerStore.getOAuthAccessor("google");
            accessor = oauthConsumerUtil.getRequestToken(accessor);

            // TODO(sweis): Put this string contstant somewhere that makes sense
            String oauthTestEndpoint = (String) accessor.getProperty("oauthTestEndpoint");
            if (oauthTestEndpoint != null) {
                realm = oauthTestEndpoint;
                returnToUrl = oauthTestEndpoint;
            }
        } catch (ProviderInfoNotFoundException e) {
            throw new ServletException(e);
        } catch (OAuthException e) {
            throw new ServletException(e);
        } catch (URISyntaxException e) {
            throw new ServletException(e);
        }
    }

    // we assume that the user typed an identifier for an IdP, not for a user
    IdpIdentifier openId = new IdpIdentifier(req.getParameter("openid"));

    AuthRequestHelper helper = consumerHelper.getAuthRequestHelper(openId, returnToUrl.toString());

    helper.requestUxIcon(true);

    if (accessor != null) {
        log.debug("Requesting OAuth scope : " + (String) accessor.getProperty("scope"));
        helper.requestOauthAuthorization(accessor.consumer.consumerKey, (String) accessor.getProperty("scope"));
    }

    if (YES_STRING.equals(req.getParameter("email"))) {
        log.debug("Requesting AX email");
        helper.requestAxAttribute(Step2.AxSchema.EMAIL, true);
    }

    if (YES_STRING.equals(req.getParameter("country"))) {
        log.debug("Requesting AX country");
        helper.requestAxAttribute(Step2.AxSchema.COUNTRY, true);
    }

    if (YES_STRING.equals(req.getParameter("language"))) {
        log.debug("Requesting AX country");
        helper.requestAxAttribute(Step2.AxSchema.LANGUAGE, true);
    }

    if (YES_STRING.equals(req.getParameter("firstName"))) {
        log.debug("Requesting AX country");
        helper.requestAxAttribute(Step2.AxSchema.FIRST_NAME, true);
    }

    if (YES_STRING.equals(req.getParameter("lastName"))) {
        log.debug("Requesting AX country");
        helper.requestAxAttribute(Step2.AxSchema.LAST_NAME, true);
    }

    HttpSession session = req.getSession();
    AuthRequest authReq = null;
    try {
        authReq = helper.generateRequest();
        authReq.setRealm(realm);

        // add PAPE, if requested
        if (YES_STRING.equals(req.getParameter("reauth"))) {
            log.debug("Requesting PAPE reauth");
            PapeRequest pape = PapeRequest.createPapeRequest();
            pape.setMaxAuthAge(1);
            authReq.addExtension(pape);
        }

        session.setAttribute("discovered", helper.getDiscoveryInformation());
    } catch (DiscoveryException e) {
        StringBuffer errorMessage = new StringBuffer("Could not discover OpenID endpoint.");
        errorMessage.append("\n\n").append("Check if URL is valid: ");
        errorMessage.append(openId).append("\n\n");
        errorMessage.append("Stack Trace:\n");
        for (StackTraceElement s : e.getStackTrace()) {
            errorMessage.append(s.toString()).append('\n');
        }
        resp.sendError(400, errorMessage.toString());
        return;
    } catch (MessageException e) {
        throw new ServletException(e);
    } catch (ConsumerException e) {
        throw new ServletException(e);
    }
    if (YES_STRING.equals(req.getParameter("usePost"))) {
        // using POST
        req.setAttribute("message", authReq);
        RequestDispatcher d = req.getRequestDispatcher("/WEB-INF/formredirection.jsp");
        d.forward(req, resp);
    } else {
        // using GET
        resp.sendRedirect(authReq.getDestinationUrl(true));
    }
}

From source file:org.trianacode.TrianaCloud.Broker.Broker.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    logger.info("Broker received a request.");
    String pathInfo = isolatePath(request);
    String content = "";
    if (!pathInfo.equalsIgnoreCase("")) {
        logger.info("Unknown Endpoint");
        write404Error(response, "Unknown endpoint");
        return;/*from   w w w .j a va  2 s . c  om*/
    }

    try {
        byte[] data = null;
        String r_key = "";
        String fname = "";
        String name = "";
        int numTasks = 0;
        StringBuilder s = new StringBuilder();

        try {
            List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            for (FileItem item : items) {
                if (item.isFormField()) {
                    // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
                    String fieldname = item.getFieldName();
                    String fieldvalue = item.getString();
                    if (fieldname.equalsIgnoreCase("task")) {
                        s.append(fieldvalue);
                    }
                    if (fieldname.equalsIgnoreCase("routingkey")) {
                        r_key = fieldvalue;
                    }
                    if (fieldname.equalsIgnoreCase("numtasks")) {
                        numTasks = Integer.parseInt(fieldvalue);
                    }
                    if (fieldname.equalsIgnoreCase("name")) {
                        name = fieldvalue;
                    }
                } else {
                    // Process form file field (input type="file").
                    String fieldname = item.getFieldName();
                    String filename = FilenameUtils.getName(item.getName());
                    // ... (do your job here)

                    fname = filename;

                    InputStream is = item.getInputStream();

                    long length = item.getSize();

                    if (length > Integer.MAX_VALUE) {
                        // File is too large
                        throw new Exception("File too large");
                    }

                    // Create the byte array to hold the data
                    byte[] bytes = new byte[(int) length];

                    // Read in the bytes
                    int offset = 0;
                    int numRead = 0;
                    while (offset < bytes.length
                            && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
                        offset += numRead;
                    }

                    // Ensure all the bytes have been read in
                    if (offset < bytes.length) {
                        throw new IOException("Could not completely read file " + length);
                    }
                    data = bytes;
                }
            }
        } catch (FileUploadException e) {
            logger.error("Cannot parse multipart request.");
            throw new ServletException("Cannot parse multipart request.", e);
        }

        List<String> UUIDList = new ArrayList<String>();

        log.debug(content);
        for (int i = 0; i < numTasks; i++) {
            Task t = new Task();
            t.setData(data);
            t.setDataMD5(MD5.getMD5Hash(data));
            t.setDataType("binary");
            t.setName(name);
            t.setFileName(fname);
            t.setOrigin("Broker");
            t.setDispatchTime(System.currentTimeMillis());
            t.setRoutingKey(r_key);
            t.setUUID(UUID.randomUUID().toString());
            insertTask(t);
            UUIDList.add(t.getUUID());
        }

        StringBuilder sb = new StringBuilder();
        for (String id : UUIDList) {
            sb.append(id + "\n");
        }
        //String ret = "Ok; ///TODO:do some stuff here
        writeResponse(response, 200, "Success", sb.toString());

        List<Task> t = td.list();

        for (Task ta : t) {
            System.out.println(ta.getDispatchTime() + "  " + ta.getState());
        }

    } catch (Exception e) {
        e.printStackTrace();
        log.error(e);
        StringBuffer stack = new StringBuffer("Error: " + e.getMessage() + "<br/>");
        StackTraceElement[] trace = e.getStackTrace();
        for (StackTraceElement element : trace) {
            stack.append(element.toString()).append("<br/>");
        }
        writeError(response, 500, stack.toString());
    } catch (Throwable t) {
        writeThrowable(response, t);
    }
}

From source file:com.carvoyant.modularinput.Program.java

@Override
protected String stackTraceToLogEntry(Exception e) {
    // Concatenate all the lines of the exception's stack trace with \\ between them.
    StringBuilder sb = new StringBuilder();

    sb.append("\"");
    sb.append(e.getClass().getName());/*w w w .  j  av  a  2  s .  c  o m*/

    if (e.getMessage() != null) {
        sb.append(": ");
        sb.append(e.getMessage());
    }

    sb.append("\" at ");
    for (StackTraceElement s : e.getStackTrace()) {
        sb.append(s.toString());
        sb.append("\\\\");
    }
    return sb.toString();
}

From source file:luceneprueba.Reader.java

public void retriveReviewsByDate() {
    try {/*from ww w .  ja  va  2  s . c  om*/
        BufferedReader br = new BufferedReader(new FileReader("files/output/review_date.json"));
        JSONParser parser = new JSONParser();
        JSONArray datesReviews = (JSONArray) parser.parse(br.readLine());
        Iterator i = datesReviews.iterator();
        while (i.hasNext()) {
            JSONObject json = (JSONObject) i.next();
            System.out.println("Recuperando los top-60 reviews del da " + (String) json.get("date"));
            searchOnIndex((String) json.get("review"), (String) json.get("date"));
        }
        br.close();
        //indexReader.close();

    } catch (FileNotFoundException | org.json.simple.parser.ParseException ex) {
        for (StackTraceElement st : ex.getStackTrace()) {
            System.out.println(st.toString());
        }
        System.out.println(ex.getLocalizedMessage());
    } catch (IOException ex) {
        for (StackTraceElement st : ex.getStackTrace()) {
            System.out.println(st.toString());
        }
        System.out.println(ex.getLocalizedMessage());
    }
}

From source file:org.kew.rmf.matchconf.ConfigurationEngine.java

/**
 * Runs the deduplicator's CoreApp providing the path to the written config. In case of chained
 * configs it calls one after the other. Doing this it tries to collect as many Exception types
 * as possible and pipes them back to the UI-user.
 *
 * @param writeBefore/*  w w w.j  av a2s .c  om*/
 * @return
 */
public Map<String, List<String>> runConfiguration(boolean writeBefore) {
    @SuppressWarnings("serial")
    Map<String, List<String>> infoMap = new HashMap<String, List<String>>() {
        {
            put("messages", new ArrayList<String>());
            put("exception", new ArrayList<String>());
            put("stackTrace", new ArrayList<String>());
        }
    };
    try {
        if (writeBefore)
            this.write_to_filesystem();
        infoMap.get("messages").add(String.format("%s: Written config file to %s..", this.config.getName(),
                this.config.getWorkDirPath()));
        File workDir = new File(this.config.getWorkDirPath());
        assert workDir.exists();
        // assert the luceneDirectory does NOT exist (we want to overwrite the index for now!)
        File luceneDir = new File(this.luceneDirectory);
        if (luceneDir.exists())
            FileUtils.deleteDirectory(luceneDir);
        CoreApp.main(
                new String[] { "-d " + workDir.toString(), "-c config_" + this.config.getName() + ".xml" });
        infoMap.get("messages").add(String.format("%s: Ran without complains.", this.config.getName()));
        // Our super-sophisticated ETL functionality:
        String next = this.config.getNextConfig();
        if (!StringUtils.isBlank(this.config.getNextConfig())) {
            ConfigurationEngine nextEngine = new ConfigurationEngine(
                    Configuration.findConfigurationsByNameEquals(next).getSingleResult());
            Map<String, List<String>> nextInfoMap = nextEngine.runConfiguration();
            infoMap.get("exception").addAll(nextInfoMap.get("exception"));
            infoMap.get("stackTrace").addAll(nextInfoMap.get("stackTrace"));
            infoMap.get("messages").addAll(nextInfoMap.get("messages"));
        }
    } catch (Exception e) {
        infoMap.get("exception").add(e.toString());
        for (StackTraceElement ste : e.getStackTrace())
            infoMap.get("stackTrace").add(ste.toString());
    }
    File luceneDir = new File(this.luceneDirectory);
    try {
        if (luceneDir.exists())
            FileUtils.deleteDirectory(luceneDir);
    } catch (IOException e) {
        System.err.println("Error deleting lucine directory " + luceneDir);
    }
    return infoMap;
}

From source file:com.example.GWTOAuthLoginDemo.server.rpc.OAuthLoginServiceImpl.java

public static String stackTraceToString(Throwable caught) {
    StringBuilder sb = new StringBuilder();
    for (StackTraceElement e : caught.getStackTrace()) {
        sb.append(e.toString()).append("\n");
    }//w  w w  . j  av a 2  s. c om
    return sb.toString();
}