Java Code Examples for org.apache.tomcat.util.ExceptionUtils#handleThrowable()

The following examples show how to use org.apache.tomcat.util.ExceptionUtils#handleThrowable() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestApplicationHttpRequest.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    Map map = req.getParameterMap();

    boolean insertWorks;
    try {
        map.put("test", new Integer[] { Integer.valueOf(0) });
        insertWorks = true;
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        insertWorks = false;
    }

    resp.setContentType("text/plain");
    resp.setCharacterEncoding("UTF-8");
    PrintWriter pw = resp.getWriter();
    if (insertWorks) {
        pw.print("FAIL");
    } else {
        pw.print("OK");
    }
}
 
Example 2
Source File: HostManagerServlet.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize this servlet.
 */
@Override
public void init() throws ServletException {

    // Ensure that our ContainerServlet properties have been set
    if ((wrapper == null) || (context == null))
        throw new UnavailableException
            (sm.getString("hostManagerServlet.noWrapper"));

    // Set our properties from the initialization parameters
    String value = null;
    try {
        value = getServletConfig().getInitParameter("debug");
        debug = Integer.parseInt(value);
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
    }

}
 
Example 3
Source File: ContainerBase.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
protected void processChildren(Container container, ClassLoader cl) {
    try {
        if (container.getLoader() != null) {
            Thread.currentThread().setContextClassLoader
                (container.getLoader().getClassLoader());
        }
        container.backgroundProcess();
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        log.error("Exception invoking periodic operation: ", t);
    } finally {
        Thread.currentThread().setContextClassLoader(cl);
    }
    Container[] children = container.findChildren();
    for (int i = 0; i < children.length; i++) {
        if (children[i].getBackgroundProcessorDelay() <= 0) {
            processChildren(children[i], cl);
        }
    }
}
 
Example 4
Source File: TestApplicationHttpRequest.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    Map map = req.getParameterMap();

    boolean insertWorks;
    try {
        map.put("test", new Integer[] { Integer.valueOf(0) });
        insertWorks = true;
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        insertWorks = false;
    }

    resp.setContentType("text/plain");
    resp.setCharacterEncoding("UTF-8");
    PrintWriter pw = resp.getWriter();
    if (insertWorks) {
        pw.print("FAIL");
    } else {
        pw.print("OK");
    }
}
 
Example 5
Source File: ResponseIncludeWrapper.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@Override
public void setHeader(String name, String value) {
    super.setHeader(name, value);
    String lname = name.toLowerCase(Locale.ENGLISH);
    if (lname.equals(LAST_MODIFIED)) {
        try {
            synchronized(RFC1123_FORMAT) {
                lastModified = RFC1123_FORMAT.parse(value).getTime();
            }
        } catch (Throwable ignore) {
            ExceptionUtils.handleThrowable(ignore);
        }
    }
    else if (lname.equals(CONTENT_TYPE))
    {
        contentType = value;
    }
}
 
Example 6
Source File: JasperListener.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Primary entry point for startup and shutdown events.
 *
 * @param event The event that has occurred
 */
@Override
public void lifecycleEvent(LifecycleEvent event) {

    if (Lifecycle.BEFORE_INIT_EVENT.equals(event.getType())) {
        try {
            // Set JSP factory
            Class.forName("org.apache.jasper.compiler.JspRuntimeContext",
                          true,
                          this.getClass().getClassLoader());
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
            // Should not occur, obviously
            log.warn("Couldn't initialize Jasper", t);
        }
        // Another possibility is to do directly:
        // JspFactory.setDefaultFactory(new JspFactoryImpl());
    }

}
 
Example 7
Source File: StandardSession.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Perform the internal processing required to passivate
 * this session.
 */
public void passivate() {

    // Notify interested session event listeners
    fireSessionEvent(Session.SESSION_PASSIVATED_EVENT, null);

    // Notify ActivationListeners
    HttpSessionEvent event = null;
    String keys[] = keys();
    for (int i = 0; i < keys.length; i++) {
        Object attribute = attributes.get(keys[i]);
        if (attribute instanceof HttpSessionActivationListener) {
            if (event == null)
                event = new HttpSessionEvent(getSession());
            try {
                ((HttpSessionActivationListener)attribute)
                    .sessionWillPassivate(event);
            } catch (Throwable t) {
                ExceptionUtils.handleThrowable(t);
                manager.getContainer().getLogger().error
                    (sm.getString("standardSession.attributeEvent"), t);
            }
        }
    }

}
 
Example 8
Source File: Request.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Notify interested listeners that attribute has been removed.
 */
private void notifyAttributeRemoved(String name, Object value) {
    Object listeners[] = context.getApplicationEventListeners();
    if ((listeners == null) || (listeners.length == 0)) {
        return;
    }
    ServletRequestAttributeEvent event =
      new ServletRequestAttributeEvent(context.getServletContext(),
                                       getRequest(), name, value);
    for (int i = 0; i < listeners.length; i++) {
        if (!(listeners[i] instanceof ServletRequestAttributeListener)) {
            continue;
        }
        ServletRequestAttributeListener listener =
            (ServletRequestAttributeListener) listeners[i];
        try {
            listener.attributeRemoved(event);
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
            context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t);
            // Error valve will pick this exception up and display it to user
            attributes.put(RequestDispatcher.ERROR_EXCEPTION, t);
        }
    }
}
 
Example 9
Source File: StandardSession.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Perform internal processing required to activate this
 * session.
 */
public void activate() {

    // Initialize access count
    if (ACTIVITY_CHECK) {
        accessCount = new AtomicInteger();
    }

    // Notify interested session event listeners
    fireSessionEvent(Session.SESSION_ACTIVATED_EVENT, null);

    // Notify ActivationListeners
    HttpSessionEvent event = null;
    String keys[] = keys();
    for (int i = 0; i < keys.length; i++) {
        Object attribute = attributes.get(keys[i]);
        if (attribute instanceof HttpSessionActivationListener) {
            if (event == null)
                event = new HttpSessionEvent(getSession());
            try {
                ((HttpSessionActivationListener)attribute)
                    .sessionDidActivate(event);
            } catch (Throwable t) {
                ExceptionUtils.handleThrowable(t);
                manager.getContainer().getLogger().error
                    (sm.getString("standardSession.attributeEvent"), t);
            }
        }
    }

}
 
Example 10
Source File: ResponseIncludeWrapper.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void setHeader(String name, String value) {
    super.setHeader(name, value);
    String lname = name.toLowerCase(Locale.ENGLISH);
    if (lname.equals(LAST_MODIFIED)) {
        try {
            synchronized(RFC1123_FORMAT) {
                lastModified = RFC1123_FORMAT.parse(value).getTime();
            }
        } catch (Throwable ignore) {
            ExceptionUtils.handleThrowable(ignore);
        }
    }
}
 
Example 11
Source File: CharsetMapper.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Construct a new CharsetMapper using the specified properties resource.
 *
 * @param name Name of a properties resource to be loaded
 *
 * @exception IllegalArgumentException if the specified properties
 *  resource could not be loaded for any reason.
 */
public CharsetMapper(String name) {
    try (InputStream stream = this.getClass().getResourceAsStream(name)) {
        map.load(stream);
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        throw new IllegalArgumentException(t.toString());
    }
}
 
Example 12
Source File: WsSession.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
private void fireEndpointOnClose(CloseReason closeReason) {

        // Fire the onClose event
        Throwable throwable = null;
        InstanceManager instanceManager = webSocketContainer.getInstanceManager();
        Thread t = Thread.currentThread();
        ClassLoader cl = t.getContextClassLoader();
        t.setContextClassLoader(applicationClassLoader);
        try {
            localEndpoint.onClose(this, closeReason);
        } catch (Throwable t1) {
            ExceptionUtils.handleThrowable(t1);
            throwable = t1;
        } finally {
            if (instanceManager != null) {
                try {
                    instanceManager.destroyInstance(localEndpoint);
                } catch (Throwable t2) {
                    ExceptionUtils.handleThrowable(t2);
                    if (throwable == null) {
                        throwable = t2;
                    }
                }
            }
            t.setContextClassLoader(cl);
        }

        if (throwable != null) {
            fireEndpointOnError(throwable);
        }
    }
 
Example 13
Source File: AprEndpoint.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Process given socket. This is called when the socket has been
 * accepted.
 * @param socket The socket
 * @return <code>true</code> if the socket was correctly configured
 *  and processing may continue, <code>false</code> if the socket needs to be
 *  close immediately
 */
protected boolean processSocketWithOptions(long socket) {
    try {
        // During shutdown, executor may be null - avoid NPE
        if (running) {
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("endpoint.debug.socket",
                        Long.valueOf(socket)));
            }
            AprSocketWrapper wrapper = new AprSocketWrapper(Long.valueOf(socket), this);
            wrapper.setKeepAliveLeft(getMaxKeepAliveRequests());
            wrapper.setSecure(isSSLEnabled());
            wrapper.setReadTimeout(getConnectionTimeout());
            wrapper.setWriteTimeout(getConnectionTimeout());
            connections.put(Long.valueOf(socket), wrapper);
            getExecutor().execute(new SocketWithOptionsProcessor(wrapper));
        }
    } catch (RejectedExecutionException x) {
        log.warn("Socket processing request was rejected for:"+socket,x);
        return false;
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        // This means we got an OOM or similar creating a thread, or that
        // the pool and its queue are full
        log.error(sm.getString("endpoint.process.fail"), t);
        return false;
    }
    return true;
}
 
Example 14
Source File: StandardSession.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Inform the listeners about the new session.
 *
 */
public void tellNew() {

    // Notify interested session event listeners
    fireSessionEvent(Session.SESSION_CREATED_EVENT, null);

    // Notify interested application event listeners
    Context context = manager.getContext();
    Object listeners[] = context.getApplicationLifecycleListeners();
    if (listeners != null && listeners.length > 0) {
        HttpSessionEvent event =
            new HttpSessionEvent(getSession());
        for (int i = 0; i < listeners.length; i++) {
            if (!(listeners[i] instanceof HttpSessionListener))
                continue;
            HttpSessionListener listener =
                (HttpSessionListener) listeners[i];
            try {
                context.fireContainerEvent("beforeSessionCreated",
                        listener);
                listener.sessionCreated(event);
                context.fireContainerEvent("afterSessionCreated", listener);
            } catch (Throwable t) {
                ExceptionUtils.handleThrowable(t);
                try {
                    context.fireContainerEvent("afterSessionCreated",
                            listener);
                } catch (Exception e) {
                    // Ignore
                }
                manager.getContext().getLogger().error
                    (sm.getString("standardSession.sessionEvent"), t);
            }
        }
    }

}
 
Example 15
Source File: WebappClassLoaderBase.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
private void nullInstance(Object instance) {
    if (instance == null) {
        return;
    }
    Field[] fields = instance.getClass().getDeclaredFields();
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        int mods = field.getModifiers();
        if (field.getType().isPrimitive()
                || (field.getName().indexOf('$') != -1)) {
            continue;
        }
        try {
            field.setAccessible(true);
            if (Modifier.isStatic(mods) && Modifier.isFinal(mods)) {
                // Doing something recursively is too risky
                continue;
            }
            Object value = field.get(instance);
            if (null != value) {
                Class<? extends Object> valueClass = value.getClass();
                if (!loadedByThisOrChild(valueClass)) {
                    if (log.isDebugEnabled()) {
                        log.debug("Not setting field " + field.getName() +
                                " to null in object of class " +
                                instance.getClass().getName() +
                                " because the referenced object was of type " +
                                valueClass.getName() +
                                " which was not loaded by this web application class loader.");
                    }
                } else {
                    field.set(instance, null);
                    if (log.isDebugEnabled()) {
                        log.debug("Set field " + field.getName()
                                + " to null in class " + instance.getClass().getName());
                    }
                }
            }
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
            if (log.isDebugEnabled()) {
                log.debug("Could not set field " + field.getName()
                        + " to null in object instance of class "
                        + instance.getClass().getName(), t);
            }
        }
    }
}
 
Example 16
Source File: NioEndpoint.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 *
 * 处理特别的连接。
 * Process the specified connection.
 * @param socket The socket channel
 * @return <code>true</code> if the socket was correctly configured
 *  and processing may continue, <code>false</code> if the socket needs to be
 *  close immediately
 *  true 和 false 取决于socket是否能够正确的执行。
 *
 *
 *  在这里的意图:将SocketChannel 转换成 NioChannel.
 *                然后将NioChannel注册到轮询器。
 *  1.设置SocketChannel属性和对应的Socket并转换为NioChannel。
 *  2.将NioChannel注册到Poller上去。
 */
protected boolean setSocketOptions(SocketChannel socket) {
    // Process the connection
    try {
        //disable blocking, APR style, we are gonna be polling it
        //禁止用阻塞,ARP的风格。我门要轮询他。
        socket.configureBlocking(false);
        Socket sock = socket.socket();
        socketProperties.setProperties(sock);

        NioChannel channel = nioChannels.pop();
        if (channel == null) {
            /**
             * 初始化SocketBufferHandler。
             */
            SocketBufferHandler bufhandler = new SocketBufferHandler(
                    socketProperties.getAppReadBufSize(),
                    socketProperties.getAppWriteBufSize(),
                    socketProperties.getDirectBuffer());
            /**
             * 创建Channel对象。
             */
            if (isSSLEnabled()) {
                channel = new SecureNioChannel(socket, bufhandler, selectorPool, this);
            } else {
                channel = new NioChannel(socket, bufhandler);
            }
        } else {
            channel.setIOChannel(socket);
            channel.reset();
        }
        /**
         * 将NioChannel注册到Poller内。
         */
        getPoller0().register(channel);
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        try {
            log.error("",t);
        } catch (Throwable tt) {
            ExceptionUtils.handleThrowable(tt);
        }
        // Tell to close the socket
        return false;
    }
    return true;
}
 
Example 17
Source File: WebappClassLoaderBase.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
private void clearReferencesStopTimerThread(Thread thread) {

        // Need to get references to:
        // in Sun/Oracle JDK:
        // - newTasksMayBeScheduled field (in java.util.TimerThread)
        // - queue field
        // - queue.clear()
        // in IBM JDK, Apache Harmony:
        // - cancel() method (in java.util.Timer$TimerImpl)

        try {

            try {
                Field newTasksMayBeScheduledField =
                    thread.getClass().getDeclaredField("newTasksMayBeScheduled");
                newTasksMayBeScheduledField.setAccessible(true);
                Field queueField = thread.getClass().getDeclaredField("queue");
                queueField.setAccessible(true);

                Object queue = queueField.get(thread);

                Method clearMethod = queue.getClass().getDeclaredMethod("clear");
                clearMethod.setAccessible(true);

                synchronized(queue) {
                    newTasksMayBeScheduledField.setBoolean(thread, false);
                    clearMethod.invoke(queue);
                    // In case queue was already empty. Should only be one
                    // thread waiting but use notifyAll() to be safe.
                    queue.notifyAll();
                }

            }catch (NoSuchFieldException nfe){
                Method cancelMethod = thread.getClass().getDeclaredMethod("cancel");
                synchronized(thread) {
                    cancelMethod.setAccessible(true);
                    cancelMethod.invoke(thread);
                }
            }

            log.warn(sm.getString("webappClassLoader.warnTimerThread",
                    getContextName(), thread.getName()));

        } catch (Exception e) {
            // So many things to go wrong above...
            Throwable t = ExceptionUtils.unwrapInvocationTargetException(e);
            ExceptionUtils.handleThrowable(t);
            log.warn(sm.getString(
                    "webappClassLoader.stopTimerThreadFail",
                    thread.getName(), getContextName()), t);
        }
    }
 
Example 18
Source File: LifecycleBase.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public final synchronized void stop() throws LifecycleException {

    if (LifecycleState.STOPPING_PREP.equals(state) || LifecycleState.STOPPING.equals(state) ||
            LifecycleState.STOPPED.equals(state)) {

        if (log.isDebugEnabled()) {
            Exception e = new LifecycleException();
            log.debug(sm.getString("lifecycleBase.alreadyStopped", toString()), e);
        } else if (log.isInfoEnabled()) {
            log.info(sm.getString("lifecycleBase.alreadyStopped", toString()));
        }

        return;
    }

    if (state.equals(LifecycleState.NEW)) {
        state = LifecycleState.STOPPED;
        return;
    }

    if (!state.equals(LifecycleState.STARTED) && !state.equals(LifecycleState.FAILED)) {
        invalidTransition(Lifecycle.BEFORE_STOP_EVENT);
    }

    try {
        if (state.equals(LifecycleState.FAILED)) {
            // Don't transition to STOPPING_PREP as that would briefly mark the
            // component as available but do ensure the BEFORE_STOP_EVENT is
            // fired
            fireLifecycleEvent(BEFORE_STOP_EVENT, null);
        } else {
            setStateInternal(LifecycleState.STOPPING_PREP, null, false);
        }

        // 模板方法
        stopInternal();

        // Shouldn't be necessary but acts as a check that sub-classes are
        // doing what they are supposed to.
        if (!state.equals(LifecycleState.STOPPING) && !state.equals(LifecycleState.FAILED)) {
            invalidTransition(Lifecycle.AFTER_STOP_EVENT);
        }

        setStateInternal(LifecycleState.STOPPED, null, false);
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        setStateInternal(LifecycleState.FAILED, null, false);
        throw new LifecycleException(sm.getString("lifecycleBase.stopFail",toString()), t);
    } finally {
        if (this instanceof Lifecycle.SingleUse) {
            // Complete stop process first
            setStateInternal(LifecycleState.STOPPED, null, false);
            destroy();
        }
    }
}
 
Example 19
Source File: TldConfig.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
private void tldScanResourcePaths(String startPath) {

        if (log.isTraceEnabled()) {
            log.trace(sm.getString("tldConfig.webinfScan", startPath));
        }

        ServletContext ctxt = context.getServletContext();

        Set<String> dirList = ctxt.getResourcePaths(startPath);
        if (dirList != null) {
            Iterator<String> it = dirList.iterator();
            while (it.hasNext()) {
                String path = it.next();
                if (!path.endsWith(TLD_EXT)
                        && (path.startsWith(WEB_INF_LIB)
                                || path.startsWith("/WEB-INF/classes/"))) {
                    continue;
                }
                if (path.endsWith(TLD_EXT)) {
                    if (path.startsWith("/WEB-INF/tags/") &&
                            !path.endsWith("implicit.tld")) {
                        continue;
                    }
                    InputStream stream = ctxt.getResourceAsStream(path);
                    try {
                        XmlErrorHandler handler = tldScanStream(stream);
                        handler.logFindings(log, path);
                    } catch (IOException ioe) {
                        log.warn(sm.getString("tldConfig.webinfFail", path),
                                ioe);
                    } finally {
                        if (stream != null) {
                            try {
                                stream.close();
                            } catch (Throwable t) {
                                ExceptionUtils.handleThrowable(t);
                            }
                        }
                    }
                } else {
                    tldScanResourcePaths(path);
                }
            }
        }
    }
 
Example 20
Source File: Nio2Endpoint.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Override
protected void doRun() {
    boolean launch = false;
    try {
        int handshake = -1;

        try {
            if (socketWrapper.getSocket().isHandshakeComplete()) {
                // No TLS handshaking required. Let the handler
                // process this socket / event combination.
                handshake = 0;
            } else if (event == SocketEvent.STOP || event == SocketEvent.DISCONNECT ||
                    event == SocketEvent.ERROR) {
                // Unable to complete the TLS handshake. Treat it as
                // if the handshake failed.
                handshake = -1;
            } else {
                handshake = socketWrapper.getSocket().handshake();
                // The handshake process reads/writes from/to the
                // socket. status may therefore be OPEN_WRITE once
                // the handshake completes. However, the handshake
                // happens when the socket is opened so the status
                // must always be OPEN_READ after it completes. It
                // is OK to always set this as it is only used if
                // the handshake completes.
                event = SocketEvent.OPEN_READ;
            }
        } catch (IOException x) {
            handshake = -1;
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("endpoint.err.handshake"), x);
            }
        }
        if (handshake == 0) {
            SocketState state = SocketState.OPEN;
            // Process the request from this socket
            if (event == null) {
                state = getHandler().process(socketWrapper, SocketEvent.OPEN_READ);
            } else {
                state = getHandler().process(socketWrapper, event);
            }
            if (state == SocketState.CLOSED) {
                // Close socket and pool
                socketWrapper.close();
                if (running && !paused) {
                    if (!nioChannels.push(socketWrapper.getSocket())) {
                        socketWrapper.getSocket().free();
                    }
                }
            } else if (state == SocketState.UPGRADING) {
                launch = true;
            }
        } else if (handshake == -1 ) {
            getHandler().process(socketWrapper, SocketEvent.CONNECT_FAIL);
            socketWrapper.close();
            if (running && !paused) {
                if (!nioChannels.push(socketWrapper.getSocket())) {
                    socketWrapper.getSocket().free();
                }
            }
        }
    } catch (VirtualMachineError vme) {
        ExceptionUtils.handleThrowable(vme);
    } catch (Throwable t) {
        log.error(sm.getString("endpoint.processing.fail"), t);
        if (socketWrapper != null) {
            ((Nio2SocketWrapper) socketWrapper).close();
        }
    } finally {
        if (launch) {
            try {
                getExecutor().execute(new SocketProcessor(socketWrapper, SocketEvent.OPEN_READ));
            } catch (NullPointerException npe) {
                if (running) {
                    log.error(sm.getString("endpoint.launch.fail"),
                            npe);
                }
            }
        }
        socketWrapper = null;
        event = null;
        //return to cache
        if (running && !paused) {
            processorCache.push(this);
        }
    }
}