Example usage for java.lang RuntimeException printStackTrace

List of usage examples for java.lang RuntimeException printStackTrace

Introduction

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

Prototype

public void printStackTrace(PrintStream s) 

Source Link

Document

Prints this throwable and its backtrace to the specified print stream.

Usage

From source file:org.jspresso.framework.util.resources.server.ResourceProviderServlet.java

/**
 * {@inheritDoc}//from  w ww  .ja v  a 2s  .co m
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    try {
        HttpRequestHolder.setServletRequest(request);
        String localUrlSpec = request.getParameter(LOCAL_URL_PARAMETER);
        String imageUrlSpec = request.getParameter(IMAGE_URL_PARAMETER);
        String id = request.getParameter(ID_PARAMETER);
        boolean ommitFileName = Boolean.parseBoolean(request.getParameter(OMIT_FILE_NAME_PARAMETER));

        if (id == null && localUrlSpec == null && imageUrlSpec == null) {
            throw new ServletException("No resource id nor local URL specified.");
        }

        BufferedInputStream inputStream = null;
        if (id != null) {
            IResourceBase resource = ResourceManager.getInstance().getRegistered(id);
            if (resource == null) {
                throw new ServletException("Bad resource id : " + id);
            }

            response.setContentType(resource.getMimeType());
            if (!ommitFileName) {
                completeFileName(response, resource.getName());
            }
            long resourceLength = resource.getSize();
            if (resourceLength > 0) {
                response.setContentLength((int) resourceLength);
            }

            if (resource instanceof IResource) {
                inputStream = new BufferedInputStream(((IResource) resource).getContent());
            } else if (resource instanceof IActiveResource) {
                OutputStream outputStream = response.getOutputStream();
                try {
                    writeActiveResource((IActiveResource) resource, outputStream);
                } catch (RuntimeException ex) {
                    try (PrintStream ps = new PrintStream(outputStream)) {
                        ex.printStackTrace(new PrintWriter(ps, true));
                    }
                    throw ex;
                }
            }
        } else if (localUrlSpec != null) {
            if (!UrlHelper.isClasspathUrl(localUrlSpec)) {
                // we must append parameters that are passed AFTER the localUrl
                // parameter as they must be considered as part of the localUrl.
                String queryString = request.getQueryString();
                localUrlSpec = queryString.substring(
                        queryString.indexOf(LOCAL_URL_PARAMETER) + LOCAL_URL_PARAMETER.length() + 1,
                        queryString.length());
            }
            if (isLocalUrlAllowed(localUrlSpec)) {
                URL localUrl = UrlHelper.createURL(localUrlSpec);
                if (localUrl == null) {
                    throw new ServletException("Bad local URL : " + localUrlSpec);
                }
                if (!ommitFileName) {
                    completeFileName(response, localUrl.getFile());
                }
                inputStream = new BufferedInputStream(localUrl.openStream());
            } else {
                LOG.warn(
                        "The resource provider servlet filtered a forbidden local URL request ({}). You can adapt the regex "
                                + "security filtering options by modifying the [{}] init parameter on the servlet.",
                        localUrlSpec, ALLOWED_LOCAL_URL_REGEX_KEY);
                LOG.warn("Current value is {} = {}", ALLOWED_LOCAL_URL_REGEX_KEY,
                        allowedLocalUrlPattern.pattern());
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
            }
        } else {
            if (isLocalUrlAllowed(imageUrlSpec)) {
                URL imageUrl = UrlHelper.createURL(imageUrlSpec);
                if (imageUrl == null) {
                    throw new ServletException("Bad image URL : " + imageUrlSpec);
                }
                if (!ommitFileName) {
                    completeFileName(response, imageUrl.getFile());
                }
                String width = request.getParameter(IMAGE_WIDTH_PARAMETER);
                String height = request.getParameter(IMAGE_HEIGHT_PARAMETER);
                if (width != null && height != null) {
                    inputStream = new BufferedInputStream(new ByteArrayInputStream(ImageHelper
                            .scaleImage(imageUrl, Integer.parseInt(width), Integer.parseInt(height), "PNG")));
                } else {
                    inputStream = new BufferedInputStream(imageUrl.openStream());
                }
            } else {
                LOG.warn(
                        "The resource provider servlet filtered a forbidden image URL request ({}). You can adapt the regex "
                                + "security filtering options by modifying the [{}] init parameter on the servlet.",
                        imageUrlSpec, ALLOWED_LOCAL_URL_REGEX_KEY);
                LOG.warn("Current value is {} = {}", ALLOWED_LOCAL_URL_REGEX_KEY,
                        allowedLocalUrlPattern.pattern());
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
            }
        }
        if (inputStream != null) {
            BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());

            IoHelper.copyStream(inputStream, outputStream);

            inputStream.close();
            outputStream.close();
        }
    } catch (ServletException | IOException ex) {
        LOG.error("An exception occurred when dealing with the following request : [{}]",
                request.getRequestURL(), ex);
        try {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } catch (IOException ioe) {
            throw new NestedRuntimeException(ioe, "An exception occurred while sending back a "
                    + HttpServletResponse.SC_NOT_FOUND + "error.");
        }
    } finally {
        HttpRequestHolder.setServletRequest(null);
    }
}

From source file:daikon.dcomp.StackVer.java

/**
 * Implements the pass 3b data flow analysis as described in the
 * Java Virtual Machine Specification, Second Edition.  As it is doing
 * so it keeps track of the stack and local variables at each instruction.
 *
 * @see org.apache.commons.bcel6.verifier.statics.Pass2Verifier#getLocalVariablesInfo(int)
 *///  w  w w .j  a v a 2s  . c  o  m
public VerificationResult do_stack_ver(MethodGen mg) {

    /*
      if (! myOwner.doPass3a(method_no).equals(VerificationResult.VR_OK)){
          return VerificationResult.VR_NOTYET;
      }
    */
    // Pass 3a ran before, so it's safe to assume the JavaClass object is
    // in the BCEL repository.
    // JavaClass jc = Repository.lookupClass(myOwner.getClassName());

    ConstantPoolGen constantPoolGen = mg.getConstantPool();
    // Init Visitors
    InstConstraintVisitor icv = new LimitedConstraintVisitor();
    icv.setConstantPoolGen(constantPoolGen);

    ExecutionVisitor ev = new ExecutionVisitor();
    ev.setConstantPoolGen(constantPoolGen);

    try {
        stack_types = new StackTypes(mg);

        icv.setMethodGen(mg);

        ////////////// DFA BEGINS HERE ////////////////
        if (!(mg.isAbstract() || mg.isNative())) { // IF mg HAS CODE (See pass 2)

            // false says don't check if jsr subroutine is covered by exception handler
            ControlFlowGraph cfg = new ControlFlowGraph(mg, false);

            // Build the initial frame situation for this method.
            Frame f = new Frame(mg.getMaxLocals(), mg.getMaxStack());
            if (!mg.isStatic()) {
                if (mg.getName().equals(Const.CONSTRUCTOR_NAME)) {
                    Frame.setThis(new UninitializedObjectType(new ObjectType(mg.getClassName())));
                    f.getLocals().set(0, Frame.getThis());
                } else {
                    @SuppressWarnings("nullness")
                    // unannotated: org.apache.commons.bcel6.verifier.structurals.Frame is not yet annotated
                    /*@NonNull*/ UninitializedObjectType dummy = null;
                    Frame.setThis(dummy);
                    f.getLocals().set(0, new ObjectType(mg.getClassName()));
                }
            }
            Type[] argtypes = mg.getArgumentTypes();
            int twoslotoffset = 0;
            for (int j = 0; j < argtypes.length; j++) {
                if (argtypes[j] == Type.SHORT || argtypes[j] == Type.BYTE || argtypes[j] == Type.CHAR
                        || argtypes[j] == Type.BOOLEAN) {
                    argtypes[j] = Type.INT;
                }
                f.getLocals().set(twoslotoffset + j + (mg.isStatic() ? 0 : 1), argtypes[j]);
                if (argtypes[j].getSize() == 2) {
                    twoslotoffset++;
                    f.getLocals().set(twoslotoffset + j + (mg.isStatic() ? 0 : 1), Type.UNKNOWN);
                }
            }
            circulationPump(cfg, cfg.contextOf(mg.getInstructionList().getStart()), f, icv, ev);
        }
    } catch (VerifierConstraintViolatedException ce) {
        ce.extendMessage("Constraint violated in method '" + mg + "':\n", "");
        return new VerificationResult(VerificationResult.VERIFIED_REJECTED, ce.getMessage());
    } catch (RuntimeException re) {
        // These are internal errors

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        re.printStackTrace(pw);

        throw new AssertionViolatedException(
                "Some RuntimeException occured while verify()ing class '" + mg.getClassName() + "', method '"
                        + mg + "'. Original RuntimeException's stack trace:\n---\n" + sw + "---\n");
    }
    return VerificationResult.VR_OK;
}

From source file:net.sourceforge.msscodefactory.cflib.v2_1.CFLib.Tip.CFTipEnvelopeHandler.java

public void parseStringContents(String str) {
    setResponse("");
    try {/* w w  w. j  ava2 s .  c o  m*/
        super.parseStringContents(str);
    } catch (RuntimeException e) {
        ICFLibMessageLog log = getLog();
        if (log != null) {
            PrintStream printStream = log.getPrintStream();
            log.message("Caught " + e.getClass().getName() + " -- " + e.getMessage());
            e.printStackTrace(printStream);
        } else {
            e.printStackTrace();
        }
        setResponse("");
    } catch (Error e) {
        ICFLibMessageLog log = getLog();
        if (log != null) {
            PrintStream printStream = log.getPrintStream();
            log.message("Caught " + e.getClass().getName() + " -- " + e.getMessage());
            e.printStackTrace(printStream);
        } else {
            e.printStackTrace();
        }
        setResponse("");
    }
}

From source file:net.sourceforge.msscodefactory.cflib.v2_1.CFLib.Tip.CFTipEnvelopeHandler.java

public void parse(String url) {
    setResponse("");
    try {/*from  w  w w.jav a2s. c o m*/
        super.parse(url);
    } catch (RuntimeException e) {
        ICFLibMessageLog log = getLog();
        if (log != null) {
            PrintStream printStream = log.getPrintStream();
            log.message("Caught " + e.getClass().getName() + " -- " + e.getMessage());
            e.printStackTrace(printStream);
        } else {
            e.printStackTrace();
        }
        setResponse("");
    } catch (Error e) {
        ICFLibMessageLog log = getLog();
        if (log != null) {
            PrintStream printStream = log.getPrintStream();
            log.message("Caught " + e.getClass().getName() + " -- " + e.getMessage());
            e.printStackTrace(printStream);
        } else {
            e.printStackTrace();
        }
        setResponse("");
    }
}

From source file:net.sourceforge.msscodefactory.cflib.v2_1.CFLib.Tip.CFTipEnvelopeHandler.java

public void parseFile(String url) {
    setResponse("");
    try {/*from w  ww .  jav  a  2  s  .  c om*/
        super.parse(url);
    } catch (RuntimeException e) {
        ICFLibMessageLog log = getLog();
        if (log != null) {
            PrintStream printStream = log.getPrintStream();
            log.message("Caught " + e.getClass().getName() + " -- " + e.getMessage());
            e.printStackTrace(printStream);
        } else {
            e.printStackTrace();
        }
        setResponse("");
    } catch (Error e) {
        ICFLibMessageLog log = getLog();
        if (log != null) {
            PrintStream printStream = log.getPrintStream();
            log.message("Caught " + e.getClass().getName() + " -- " + e.getMessage());
            e.printStackTrace(printStream);
        } else {
            e.printStackTrace();
        }
        setResponse("");
    }
}

From source file:hudson.plugins.sshslaves.SSHLauncher.java

/**
 * {@inheritDoc}//from  w  w  w  .  java  2 s . c o m
 */
@Override
public synchronized void launch(final SlaveComputer computer, final TaskListener listener)
        throws InterruptedException {
    connection = new Connection(host, port);
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    Set<Callable<Boolean>> callables = new HashSet<Callable<Boolean>>();
    callables.add(new Callable<Boolean>() {
        public Boolean call() throws InterruptedException {
            Boolean rval = Boolean.FALSE;
            try {

                openConnection(listener);

                verifyNoHeaderJunk(listener);
                reportEnvironment(listener);

                String java = resolveJava(computer, listener);

                final String workingDirectory = getWorkingDirectory(computer);
                if (workingDirectory == null) {
                    listener.error("Cannot get the working directory for " + computer);
                    return Boolean.FALSE;
                }
                copySlaveJar(listener, workingDirectory);

                startSlave(computer, listener, java, workingDirectory);

                PluginImpl.register(connection);
                rval = Boolean.TRUE;
            } catch (RuntimeException e) {
                e.printStackTrace(listener.error(Messages.SSHLauncher_UnexpectedError()));
            } catch (Error e) {
                e.printStackTrace(listener.error(Messages.SSHLauncher_UnexpectedError()));
            } catch (IOException e) {
                e.printStackTrace(listener.getLogger());
            } finally {
                return rval;
            }
        }
    });

    final Node node = computer.getNode();
    final String nodeName = node != null ? node.getNodeName() : "unknown";
    try {
        long time = System.currentTimeMillis();
        List<Future<Boolean>> results;
        if (this.getLaunchTimeoutMillis() > 0) {
            results = executorService.invokeAll(callables, this.getLaunchTimeoutMillis(),
                    TimeUnit.MILLISECONDS);
        } else {
            results = executorService.invokeAll(callables);
        }
        long duration = System.currentTimeMillis() - time;
        Boolean res;
        try {
            res = results.get(0).get();
        } catch (ExecutionException e) {
            res = Boolean.FALSE;
        }
        if (!res) {
            System.out.println(
                    Messages.SSHLauncher_LaunchFailedDuration(getTimestamp(), nodeName, host, duration));
            listener.getLogger().println(getTimestamp() + " Launch failed - cleaning up connection");
            cleanupConnection(listener);
        } else {
            System.out.println(
                    Messages.SSHLauncher_LaunchCompletedDuration(getTimestamp(), nodeName, host, duration));
        }
        executorService.shutdown();
    } catch (InterruptedException e) {
        System.out.println(Messages.SSHLauncher_LaunchFailed(getTimestamp(), nodeName, host));
    }

}

From source file:com.palantir.atlasdb.keyvalue.partition.map.DynamicPartitionMapImpl.java

/**
 * Before://ww  w  .  j av  a 2 s  . c o  m
 *
 * ranges operated by E:
 * A     B     C     D     E     F     G     H     I
 * |     |-----|-----|-----|     |     |     |     |
 *
 * ranges operated by F
 * A     B     C     D     E     F     G     H     I
 * |     |     |-----|-----|-----|     |     |     |
 *
 * ranges operated by G
 * A     B     C     D     E     F     G     H     I
 * |     |     |     |-----|-----|-----|     |     |
 *
 * ranges operated by H
 * A     B     C     D     E     F     G     H     I
 * |     |     |     |     |-----|-----|-----|     |
 *
 *
 * Removing E:
 *
 * ranges operated by F
 * A     B     C     D     *     F     G     H     I
 * |     |-----|-----|-----------|     |     |     |
 *
 * ranges operated by G
 * A     B     C     D     *     F     G     H     I
 * |     |     |-----|-----------|-----|     |     |
 *
 * ranges operated by H
 * A     B     C     D     *     F     G     H     I
 * |     |     |     |-----------|-----|-----|     |
 *
 *
 * Idea: add one lower range to REPF higher endpoints.
 * In case of the last one (H) I only need to add part
 * of the new range that this endpoint did not have
 * previously ([DE]).
 *
 *
 */
@Override
public synchronized void promoteRemovedEndpoint(byte[] key) {
    Preconditions.checkArgument(ring.get(key) instanceof EndpointWithLeavingStatus);
    Preconditions.checkState(operationsInProgress == 1);
    EndpointWithLeavingStatus ews = (EndpointWithLeavingStatus) ring.get(key);
    Preconditions.checkArgument(ews.backfilled());

    KeyValueEndpoint kve = ring.get(key).get();
    KeyValueService kvs = kve.keyValueService();

    // Finalize
    ring.remove(key);
    version.increment();
    operationsInProgress = 0;

    byte[] otherKey = key;
    try {
        // TODO: Shouldn't this be +1, or filter based on normal status?
        for (int i = 0; i < quorumParameters.getReplicationFactor(); ++i) {
            otherKey = ring.nextKey(otherKey);
            ring.get(otherKey).get().partitionMapService().updateMap(this);
        }
    } catch (RuntimeException e) {
        ring.put(key, ews);
        version.decrement();
        operationsInProgress = 1;
        throw e;
    }

    // Delegates are transient
    delegates.remove(kvs);

    // Now we can safely remove data from the endpoint.
    // If this fails... I don't care.
    try {
        kve.partitionMapService().updateMap(this);
        for (String table : kvs.getAllTableNames()) {
            kvs.dropTable(table);
        }
    } catch (RuntimeException e) {
        log.warn("Error while removing data from removed endpoint. Ignoring.");
        e.printStackTrace(System.out);
    }
}

From source file:net.sf.joost.stx.Processor.java

/**
 * Emits an <code>endDocument</code> event to an external handler
 * (in {@link Context#targetHandler}), preceded by all necessary
 * namespace undeclarations (<code>endPrefixMapping</code> events).
 *//*w  ww. j av a  2 s . co  m*/
private void endExternDocument() throws SAXException {
    try {
        // undeclare current namespaces
        for (Enumeration e = inScopeNamespaces.keys(); e.hasMoreElements();) {
            String prefix = (String) e.nextElement();
            if (!prefix.equals("xml"))
                context.targetHandler.endPrefixMapping(prefix);
        }

        // If the Map interface would be used
        //
        //           Map.Entry[] nsEntries = new Map.Entry[inScopeNamespaces.size()];
        //           inScopeNamespaces.entrySet().toArray(nsEntries);
        //           for (int i=0; i<nsEntries.length; i++) {
        //              String prefix = (String)nsEntries[i].getKey();
        //              if (!prefix.equals("xml"))
        //                 context.targetHandler.endPrefixMapping(prefix);
        //           }

        context.targetHandler.endDocument();
        context.targetHandler = null;
    } catch (RuntimeException e) {
        // wrap exception
        java.io.StringWriter sw = null;
        sw = new java.io.StringWriter();
        e.printStackTrace(new java.io.PrintWriter(sw));
        NodeBase nb = context.currentInstruction;
        context.errorHandler.fatalError("External processing failed: " + sw, nb.publicId, nb.systemId,
                nb.lineNo, nb.colNo, e);
    }
}

From source file:net.sf.joost.stx.Processor.java

/**
 * Emits a <code>startDocument</code> event to an external handler
 * (in {@link Context#targetHandler}), followed by all necessary
 * namespace declarations (<code>startPrefixMapping</code> events).
 *//* www.j  a  v a 2s . c o  m*/
private void startExternDocument() throws SAXException {
    try {
        context.targetHandler.startDocument();

        // declare current namespaces
        for (Enumeration e = inScopeNamespaces.keys(); e.hasMoreElements();) {
            String prefix = (String) e.nextElement();
            if (!prefix.equals("xml"))
                context.targetHandler.startPrefixMapping(prefix, (String) inScopeNamespaces.get(prefix));
        }

        // If the Map interface would be used:
        //
        //           Map.Entry[] nsEntries = new Map.Entry[inScopeNamespaces.size()];
        //           inScopeNamespaces.entrySet().toArray(nsEntries);
        //           for (int i=0; i<nsEntries.length; i++) {
        //              String prefix = (String)nsEntries[i].getKey();
        //              if (!prefix.equals("xml"))
        //                 context.targetHandler.startPrefixMapping(
        //                    prefix, (String)nsEntries[i].getValue());
        //           }

    } catch (RuntimeException e) {
        // wrap exception
        java.io.StringWriter sw = null;
        sw = new java.io.StringWriter();
        e.printStackTrace(new java.io.PrintWriter(sw));
        NodeBase nb = context.currentInstruction;
        context.errorHandler.fatalError("External processing failed: " + sw, nb.publicId, nb.systemId,
                nb.lineNo, nb.colNo, e);
    }
}