Example usage for java.lang Throwable getStackTrace

List of usage examples for java.lang Throwable getStackTrace

Introduction

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

Prototype

public StackTraceElement[] getStackTrace() 

Source Link

Document

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

Usage

From source file:org.evosuite.setup.TestClusterGenerator.java

private boolean addDependencyClass(GenericClass clazz, int recursionLevel) {
    if (recursionLevel > Properties.CLUSTER_RECURSION) {
        logger.debug("Maximum recursion level reached, not adding dependency {}", clazz.getClassName());
        return false;
    }//from w  ww  .ja va 2  s .c  o  m

    clazz = clazz.getRawGenericClass();

    if (analyzedClasses.contains(clazz.getRawClass())) {
        return true;
    }
    analyzedClasses.add(clazz.getRawClass());

    // We keep track of generic containers in case we find other concrete generic components during runtime
    if (clazz.isAssignableTo(Collection.class) || clazz.isAssignableTo(Map.class)) {
        if (clazz.getNumParameters() > 0) {
            containerClasses.add(clazz.getRawClass());
        }
    }

    if (clazz.equals(String.class)) {
        return false;
    }

    try {
        TestCluster cluster = TestCluster.getInstance();
        logger.debug("Adding dependency class {}", clazz.getClassName());

        // TODO: Should we include declared classes as well?

        if (!canUse(clazz.getRawClass())) {
            logger.info("*** Cannot use class: {}", clazz.getClassName());
            return false;
        }

        // Add all constructors
        for (Constructor<?> constructor : getConstructors(clazz.getRawClass())) {
            String name = "<init>" + org.objectweb.asm.Type.getConstructorDescriptor(constructor);

            if (Properties.TT) {
                String orig = name;
                name = BooleanTestabilityTransformation.getOriginalNameDesc(clazz.getClassName(), "<init>",
                        org.objectweb.asm.Type.getConstructorDescriptor(constructor));
                if (!orig.equals(name))
                    logger.info("TT name: {} -> {}", orig, name);

            }

            if (canUse(constructor)) {
                GenericConstructor genericConstructor = new GenericConstructor(constructor, clazz);
                try {
                    cluster.addGenerator(clazz.getWithWildcardTypes(), genericConstructor);
                    addDependencies(genericConstructor, recursionLevel + 1);
                    logger.debug("Keeping track of {}.{}{}", constructor.getDeclaringClass().getName(),
                            constructor.getName(), Type.getConstructorDescriptor(constructor));
                } catch (Throwable t) {
                    logger.info("Error adding constructor {}: {}", constructor.getName(), t.getMessage());
                }

            } else {
                logger.debug("Constructor cannot be used: {}", constructor);
            }

        }

        // Add all methods
        for (Method method : getMethods(clazz.getRawClass())) {
            String name = method.getName() + org.objectweb.asm.Type.getMethodDescriptor(method);

            if (Properties.TT) {
                String orig = name;
                name = BooleanTestabilityTransformation.getOriginalNameDesc(clazz.getClassName(),
                        method.getName(), org.objectweb.asm.Type.getMethodDescriptor(method));
                if (!orig.equals(name))
                    logger.info("TT name: {} -> {}", orig, name);
            }

            if (canUse(method, clazz.getRawClass()) && !method.getName().equals("hashCode")) {
                logger.debug("Adding method {}.{}{}", clazz.getClassName(), method.getName(),
                        Type.getMethodDescriptor(method));

                if (method.getTypeParameters().length > 0) {
                    logger.info("Type parameters in methods are not handled yet, skipping {}", method);
                    continue;
                }
                GenericMethod genericMethod = new GenericMethod(method, clazz);
                try {
                    addDependencies(genericMethod, recursionLevel + 1);
                    cluster.addModifier(clazz.getWithWildcardTypes(), genericMethod);
                    //               GenericClass retClass = new GenericClass(
                    //                       genericMethod.getReturnType(), method.getReturnType());
                    GenericClass retClass = new GenericClass(method.getReturnType());

                    if (!retClass.isPrimitive() && !retClass.isVoid() && !retClass.isObject()) {
                        cluster.addGenerator(retClass.getWithWildcardTypes(), genericMethod);
                    }
                } catch (Throwable t) {
                    logger.info("Error adding method {}: {}", method.getName(), t.getMessage());
                }
            } else {
                logger.debug("Method cannot be used: {}", method);
            }
        }

        // Add all fields
        for (Field field : getFields(clazz.getRawClass())) {
            logger.debug("Checking field {}", field);
            if (canUse(field, clazz.getRawClass())) {
                logger.debug("Adding field {} for class {}", field, clazz);
                try {
                    GenericField genericField = new GenericField(field, clazz);
                    cluster.addGenerator(new GenericClass(field.getGenericType()).getWithWildcardTypes(),
                            genericField);
                    if (!Modifier.isFinal(field.getModifiers())) {
                        cluster.addModifier(clazz.getWithWildcardTypes(), genericField);
                        addDependencies(genericField, recursionLevel + 1);
                    }
                } catch (Throwable t) {
                    logger.info("Error adding field {}: {}", field.getName(), t.getMessage());
                }

            } else {
                logger.debug("Field cannot be used: {}", field);
            }
        }
        logger.info("Finished analyzing {} at recursion level {}", clazz.getTypeName(), recursionLevel);
        cluster.getAnalyzedClasses().add(clazz.getRawClass());
    } catch (Throwable t) {
        /*
         * NOTE: this is a problem we know it can happen in some cases in SF110, but don't
         * have a real solution now. As it is bound to happen, we try to minimize the logging (eg no
         * stack trace), although we still need to log it
         */
        logger.error("Problem for {}. Failed to add dependencies for class {}: {}\n{}", Properties.TARGET_CLASS,
                clazz.getClassName(), t, Arrays.asList(t.getStackTrace()));

        return false;
    }
    return true;
}

From source file:com.crushpaper.Servlet.java

/**
 * Runs the server./*w ww .  jav a2s.  c  om*/
 * 
 * @throws IOException
 */
public boolean run() throws IOException {
    createTheUserForSingleUserMode();

    int numThreads = 8;
    if (httpsPort != null) {
        numThreads += 3;
    }

    final int idleTimeout = 60000;
    final BlockingQueue<Runnable> queue = new BlockingArrayQueue<>(10000);
    final Server server = new Server(new QueuedThreadPool(numThreads, numThreads, idleTimeout, queue));

    // HTTP Configuration
    final HttpConfiguration http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");
    if (httpsPort != null) {
        http_config.setSecurePort(httpsPort);
    }

    http_config.setOutputBufferSize(32768);

    // HTTP connector
    final ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(http_config));
    http.setPort(httpPort);
    http.setIdleTimeout(30000);

    final ArrayList<Connector> connectors = new ArrayList<Connector>();
    connectors.add(http);

    if (keyStorePath != null) {
        // SSL requires a certificate so we configure a factory for SSL
        // contents
        // with information pointing to what keystore the SSL connection
        // needs
        // to know about.
        final SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setKeyStorePath(keyStorePath.getAbsolutePath());
        if (keyStorePassword != null) {
            sslContextFactory.setKeyStorePassword(keyStorePassword);
        }

        if (keyManagerPassword != null) {
            sslContextFactory.setKeyManagerPassword(keyManagerPassword);
        }

        // HTTPS configuration.
        final HttpConfiguration https_config = new HttpConfiguration(http_config);
        https_config.addCustomizer(new SecureRequestCustomizer());

        // HTTPS connector.
        final ServerConnector https = new ServerConnector(server,
                new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
                new HttpConnectionFactory(https_config));
        https.setPort(httpsPort);
        https.setIdleTimeout(500000);

        connectors.add(https);
    }

    server.setConnectors(connectors.toArray(new Connector[connectors.size()]));

    final ContextHandlerCollection contexts = createContexts(temporaryDirectory, sessionStoreDirectory);

    // Set a handler
    if (logDirectory == null) {
        server.setHandler(contexts);
    } else {
        logDirectory.mkdirs();

        // Configure HTTP request logging.
        final HandlerCollection handlers = new HandlerCollection();

        final RequestLogHandler requestLogHandler = new RequestLogHandler();
        handlers.setHandlers(new Handler[] { contexts, requestLogHandler });
        server.setHandler(handlers);

        final NCSARequestLog requestLog = new NCSARequestLog(
                new File(logDirectory, "jetty-yyyy_mm_dd.request.log").getAbsolutePath());
        requestLog.setRetainDays(90);
        requestLog.setAppend(true);
        requestLog.setExtended(false);
        requestLog.setLogTimeZone("GMT");
        requestLog.setLogLatency(true);
        requestLogHandler.setRequestLog(requestLog);
    }

    // Start the server
    try {
        server.start();
        server.join();
    } catch (final Throwable t) {
        logger.log(Level.SEVERE, t.getStackTrace().toString());
    }

    return true;
}

From source file:com.chiorichan.http.HttpHandler.java

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    try {//from   w  w  w .  j a v  a2  s  . c  o  m
        if (request == null || response == null) {
            NetworkManager.getLogger().severe(EnumColor.NEGATIVE + "" + EnumColor.RED
                    + "We got an unexpected exception before the connection was processed:", cause);

            StringBuilder sb = new StringBuilder();
            sb.append("<h1>500 - Internal Server Error</h1>\n");
            sb.append(
                    "<p>The server had encountered an unexpected exception before it could fully process your request, so no extended debug information is or will be available.</p>\n");
            sb.append(
                    "<p>The exception has been logged to the console, so we can only hope the exception is noticed and resolved. We apoligize for any inconvenience.</p>\n");
            sb.append("<p><i>You have a good day now and we will see you again soon. :)</i></p>\n");
            sb.append("<hr>\n");
            sb.append(Versioning.getHTMLFooter());

            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.valueOf(500), Unpooled.wrappedBuffer(sb.toString().getBytes()));
            ctx.write(response);

            return;
        }

        String ip = request.getIpAddr();

        if (requestFinished && cause instanceof HttpError) {
            int code = ((HttpError) cause).getHttpCode();

            if (code >= 400 && code <= 499)
                NetworkSecurity.addStrikeToIp(ip, IpStrikeType.HTTP_ERROR_400);
            if (code >= 500 && code <= 599)
                NetworkSecurity.addStrikeToIp(ip, IpStrikeType.HTTP_ERROR_500);

            if (response.getStage() != HttpResponseStage.CLOSED)
                response.sendError((HttpError) cause);
            else
                NetworkManager.getLogger().severe(EnumColor.NEGATIVE + "" + EnumColor.RED + " [" + ip
                        + "] For reasons unknown, we caught the HttpError but the connection was already closed.",
                        cause);
            return;
        }

        if (requestFinished && "Connection reset by peer".equals(cause.getMessage())) {
            NetworkManager.getLogger().warning(EnumColor.NEGATIVE + "" + EnumColor.RED + " [" + ip
                    + "] The connection was closed before we could finish the request, if the IP continues to abuse the system it WILL BE BANNED!");
            NetworkSecurity.addStrikeToIp(ip, IpStrikeType.CLOSED_EARLY);
            return;
        }

        ScriptingException evalOrig = null;

        /*
         * Unpackage the EvalFactoryException.
         * Not sure if exceptions from the EvalFactory should be handled differently or not.
         * XXX Maybe skip generating exception pages for errors that were caused internally and report them to Chiori-chan unless the server is in development mode?
         */
        if (cause instanceof ScriptingException && cause.getCause() != null) {
            evalOrig = (ScriptingException) cause;
            cause = cause.getCause();
        }

        /*
         * Presently we can only send one exception to the client
         * So for now we only send the most severe one
         *
         * TODO Enhancement: Make it so each exception is printed out.
         */
        if (cause instanceof MultipleException) {
            IException most = null;

            // The lower the intValue() to more important it became
            for (IException e : ((MultipleException) cause).getExceptions())
                if (e instanceof Throwable
                        && (most == null || most.reportingLevel().intValue() > e.reportingLevel().intValue()))
                    most = e;

            if (most instanceof ScriptingException) {
                evalOrig = (ScriptingException) most;
                cause = most.getCause();
            } else
                cause = (Throwable) most;
        }

        /*
         * TODO Proper Exception Handling. Consider the ability to have these exceptions cached, then delivered by e-mail to chiori-chan and/or server administrator.
         */
        if (cause instanceof HttpError)
            response.sendError((HttpError) cause);
        else if (cause instanceof PermissionDeniedException) {
            PermissionDeniedException pde = (PermissionDeniedException) cause;

            if (pde.getReason() == PermissionDeniedReason.LOGIN_PAGE)
                response.sendLoginPage(pde.getReason().getMessage());
            else
                /*
                 * TODO generate a special permission denied page
                 */
                response.sendError(((PermissionDeniedException) cause).getHttpCode(), cause.getMessage());
        } else if (cause instanceof OutOfMemoryError) {
            log.log(Level.SEVERE,
                    EnumColor.NEGATIVE + "" + EnumColor.RED + "OutOfMemoryError! This is serious!!!");
            response.sendError(500, "We have encountered an internal server error");

            if (Versioning.isDevelopment())
                cause.printStackTrace();
        } else if (evalOrig == null) {
            // Was not caught by EvalFactory
            log.log(Level.SEVERE, "%s%sException %s thrown in file '%s' at line %s, message '%s'",
                    EnumColor.NEGATIVE, EnumColor.RED, cause.getClass().getName(),
                    cause.getStackTrace()[0].getFileName(), cause.getStackTrace()[0].getLineNumber(),
                    cause.getMessage());
            response.sendException(cause);

            if (Versioning.isDevelopment())
                cause.printStackTrace();
        } else {
            if (evalOrig.isScriptingException() && !evalOrig.hasScriptTrace()) {
                log.log(Level.WARNING,
                        "We caught an EvalException which was determined to be related to a scripting issue but the exception has no script trace, this might be a combined internal and external problem.",
                        EnumColor.NEGATIVE, EnumColor.RED);
                log.log(Level.SEVERE, "%s%sException %s thrown in file '%s' at line %s, message '%s'",
                        EnumColor.NEGATIVE, EnumColor.RED, cause.getClass().getName(),
                        cause.getStackTrace()[0].getFileName(), cause.getStackTrace()[0].getLineNumber(),
                        cause.getMessage());
            } else if (evalOrig.isScriptingException()) {
                ScriptTraceElement element = evalOrig.getScriptTrace()[0];
                log.log(Level.SEVERE, "%s%sException %s thrown in file '%s' at line %s:%s, message '%s'",
                        EnumColor.NEGATIVE, EnumColor.RED, cause.getClass().getName(),
                        element.context().filename(), element.getLineNumber(),
                        element.getColumnNumber() > 0 ? element.getColumnNumber() : 0, cause.getMessage());
            } else
                log.log(Level.SEVERE, "%s%sException %s thrown with message '%s'", EnumColor.NEGATIVE,
                        EnumColor.RED, cause.getClass().getName(), cause.getMessage());
            // log.log( Level.SEVERE, "%s%sException %s thrown in file '%s' at line %s, message '%s'", LogColor.NEGATIVE, LogColor.RED, cause.getClass().getName(), cause.getStackTrace()[0].getFileName(),
            // cause.getStackTrace()[0].getLineNumber(), cause.getMessage() );

            response.sendException(evalOrig);

            if (Versioning.isDevelopment())
                cause.printStackTrace();
        }

        finish();
    } catch (Throwable t) {
        NetworkManager.getLogger().severe(EnumColor.NEGATIVE + "" + EnumColor.RED
                + "This is an uncaught exception from the exceptionCaught() method:", t);
        // ctx.fireExceptionCaught( t );
    }
}