Search in sources :

Example 1 with SingleThreadModel

use of javax.servlet.SingleThreadModel in project Payara by payara.

the class StandardWrapper method loadServlet.

/**
 * Creates an instance of the servlet, if there is not already
 * at least one initialized instance.
 */
private synchronized Servlet loadServlet() throws ServletException {
    // Nothing to do if we already have an instance or an instance pool
    if (!singleThreadModel && instance != null) {
        return instance;
    }
    long t1 = System.currentTimeMillis();
    loadServletClass();
    // Instantiate the servlet class
    Servlet servlet = null;
    try {
        servlet = ((StandardContext) getParent()).createServletInstance(servletClass);
    } catch (ClassCastException e) {
        unavailable(null);
        // Restore the context ClassLoader
        throw new ServletException(createMsg(CLASS_IS_NOT_SERVLET_EXCEPTION, servletClass.getName()), e);
    } catch (Throwable e) {
        unavailable(null);
        // Restore the context ClassLoader
        throw new ServletException(createMsg(ERROR_INSTANTIATE_SERVLET_CLASS_EXCEPTION, servletClass.getName()), e);
    }
    // Check if loading the servlet in this web application should be allowed
    if (!isServletAllowed(servlet)) {
        throw new SecurityException(createMsg(PRIVILEGED_SERVLET_CANNOT_BE_LOADED_EXCEPTION, servletClass.getName()));
    }
    // Special handling for ContainerServlet instances
    if ((servlet instanceof ContainerServlet) && (isContainerProvidedServlet(servletClass.getName()) || ((Context) getParent()).getPrivileged())) {
        ((ContainerServlet) servlet).setWrapper(this);
    }
    classLoadTime = (int) (System.currentTimeMillis() - t1);
    // Register our newly initialized instance
    singleThreadModel = servlet instanceof SingleThreadModel;
    if (singleThreadModel) {
        if (instancePool == null)
            instancePool = new Stack<Servlet>();
    }
    if (notifyContainerListeners) {
        fireContainerEvent("load", this);
    }
    loadTime = System.currentTimeMillis() - t1;
    return servlet;
}
Also used : ServletException(javax.servlet.ServletException) HttpServlet(javax.servlet.http.HttpServlet) Servlet(javax.servlet.Servlet) ContainerServlet(org.apache.catalina.ContainerServlet) ContainerServlet(org.apache.catalina.ContainerServlet) SingleThreadModel(javax.servlet.SingleThreadModel) Stack(java.util.Stack)

Example 2 with SingleThreadModel

use of javax.servlet.SingleThreadModel in project Payara by payara.

the class StandardContext method addServlet.

/**
 * Adds the given servlet instance with the given name and URL patterns
 * to this servlet context, and initializes it.
 *
 * @param servletName the servlet name
 * @param servlet the servlet instance
 * @param initParams Map containing the initialization parameters for
 * the servlet
 * @param urlPatterns the URL patterns that will be mapped to the servlet
 *
 * @return the ServletRegistration through which the servlet may be
 * further configured
 */
@Override
public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet, Map<String, String> initParams, String... urlPatterns) {
    if (isContextInitializedCalled) {
        String msg = MessageFormat.format(rb.getString(LogFacade.SERVLET_CONTEXT_ALREADY_INIT_EXCEPTION), new Object[] { "addServlet", getName() });
        throw new IllegalStateException(msg);
    }
    if (servletName == null || servletName.length() == 0) {
        throw new IllegalArgumentException(rb.getString(LogFacade.NULL_EMPTY_SERVLET_NAME_EXCEPTION));
    }
    if (servlet == null) {
        throw new NullPointerException(rb.getString(LogFacade.NULL_SERVLET_INSTANCE_EXCEPTION));
    }
    if (servlet instanceof SingleThreadModel) {
        throw new IllegalArgumentException("Servlet implements " + SingleThreadModel.class.getName());
    }
    /*
         * Make sure the given Servlet instance is unique across all deployed
         * contexts
         */
    Container host = getParent();
    if (host != null) {
        for (Container child : host.findChildren()) {
            if (child == this) {
                // Our own context will be checked further down
                continue;
            }
            if (((StandardContext) child).hasServlet(servlet)) {
                return null;
            }
        }
    }
    /*
         * Make sure the given Servlet name and instance are unique within
         * this context
         */
    synchronized (children) {
        for (Map.Entry<String, Container> e : children.entrySet()) {
            if (servletName.equals(e.getKey()) || servlet == ((StandardWrapper) e.getValue()).getServlet()) {
                return null;
            }
        }
        DynamicServletRegistrationImpl regis = (DynamicServletRegistrationImpl) servletRegisMap.get(servletName);
        StandardWrapper wrapper = null;
        if (regis == null) {
            wrapper = (StandardWrapper) createWrapper();
        } else {
            // Complete preliminary servlet registration
            wrapper = regis.getWrapper();
        }
        wrapper.setName(servletName);
        wrapper.setServlet(servlet);
        if (initParams != null) {
            for (Map.Entry<String, String> e : initParams.entrySet()) {
                wrapper.addInitParameter(e.getKey(), e.getValue());
            }
        }
        addChild(wrapper, true, (null == regis));
        if (null == regis) {
            regis = (DynamicServletRegistrationImpl) servletRegisMap.get(servletName);
        }
        if (urlPatterns != null) {
            for (String urlPattern : urlPatterns) {
                addServletMapping(urlPattern, servletName, false);
            }
        }
        return regis;
    }
}
Also used : Container(org.apache.catalina.Container) SingleThreadModel(javax.servlet.SingleThreadModel) FilterMap(org.apache.catalina.deploy.FilterMap) ServletMap(org.apache.catalina.deploy.ServletMap) Map(java.util.Map) TreeMap(java.util.TreeMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap)

Example 3 with SingleThreadModel

use of javax.servlet.SingleThreadModel in project sling by apache.

the class ServletWrapper method service.

/**
     * Call the servlet.
     * @param request The current request.
     * @param response The current response.
     * @throws Exception
     */
public void service(HttpServletRequest request, HttpServletResponse response) throws Exception {
    try {
        if ((available > 0L) && (available < Long.MAX_VALUE)) {
            if (available > System.currentTimeMillis()) {
                response.setDateHeader("Retry-After", available);
                response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Servlet unavailable.");
                logger.error("Java servlet {} is unavailable.", this.sourcePath);
                return;
            }
            // Wait period has expired. Reset.
            available = 0;
        }
        final Servlet servlet = this.getServlet();
        // invoke the servlet
        if (servlet instanceof SingleThreadModel) {
            // of the page is determined right before servicing
            synchronized (this) {
                servlet.service(request, response);
            }
        } else {
            servlet.service(request, response);
        }
    } catch (final UnavailableException ex) {
        int unavailableSeconds = ex.getUnavailableSeconds();
        if (unavailableSeconds <= 0) {
            // Arbitrary default
            unavailableSeconds = 60;
        }
        available = System.currentTimeMillis() + (unavailableSeconds * 1000L);
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex.getMessage());
        logger.error("Java servlet {} is unavailable.", this.sourcePath);
    }
}
Also used : UnavailableException(javax.servlet.UnavailableException) Servlet(javax.servlet.Servlet) SingleThreadModel(javax.servlet.SingleThreadModel)

Example 4 with SingleThreadModel

use of javax.servlet.SingleThreadModel in project tomcat70 by apache.

the class StandardWrapper method loadServlet.

/**
 * Load and initialize an instance of this servlet, if there is not already
 * at least one initialized instance.  This can be used, for example, to
 * load servlets that are marked in the deployment descriptor to be loaded
 * at server startup time.
 */
public synchronized Servlet loadServlet() throws ServletException {
    if (unloading) {
        throw new ServletException(sm.getString("standardWrapper.unloading", getName()));
    }
    // Nothing to do if we already have an instance or an instance pool
    if (!singleThreadModel && (instance != null))
        return instance;
    PrintStream out = System.out;
    if (swallowOutput) {
        SystemLogHandler.startCapture();
    }
    Servlet servlet;
    try {
        long t1 = System.currentTimeMillis();
        // Complain if no servlet class has been specified
        if (servletClass == null) {
            unavailable(null);
            throw new ServletException(sm.getString("standardWrapper.notClass", getName()));
        }
        InstanceManager instanceManager = ((StandardContext) getParent()).getInstanceManager();
        try {
            servlet = (Servlet) instanceManager.newInstance(servletClass);
        } catch (ClassCastException e) {
            unavailable(null);
            // Restore the context ClassLoader
            throw new ServletException(sm.getString("standardWrapper.notServlet", servletClass), e);
        } catch (Throwable e) {
            e = ExceptionUtils.unwrapInvocationTargetException(e);
            ExceptionUtils.handleThrowable(e);
            unavailable(null);
            // http://bz.apache.org/bugzilla/show_bug.cgi?id=36630
            if (log.isDebugEnabled()) {
                log.debug(sm.getString("standardWrapper.instantiate", servletClass), e);
            }
            // Restore the context ClassLoader
            throw new ServletException(sm.getString("standardWrapper.instantiate", servletClass), e);
        }
        if (multipartConfigElement == null) {
            MultipartConfig annotation = servlet.getClass().getAnnotation(MultipartConfig.class);
            if (annotation != null) {
                multipartConfigElement = new MultipartConfigElement(annotation);
            }
        }
        // Special handling for ContainerServlet instances
        if ((servlet instanceof ContainerServlet) && (isContainerProvidedServlet(servletClass) || ((Context) getParent()).getPrivileged())) {
            ((ContainerServlet) servlet).setWrapper(this);
        }
        classLoadTime = (int) (System.currentTimeMillis() - t1);
        if (servlet instanceof SingleThreadModel) {
            if (instancePool == null) {
                instancePool = new Stack<Servlet>();
            }
            singleThreadModel = true;
        }
        initServlet(servlet);
        fireContainerEvent("load", this);
        loadTime = System.currentTimeMillis() - t1;
    } finally {
        if (swallowOutput) {
            String log = SystemLogHandler.stopCapture();
            if (log != null && log.length() > 0) {
                if (getServletContext() != null) {
                    getServletContext().log(log);
                } else {
                    out.println(log);
                }
            }
        }
    }
    return servlet;
}
Also used : PrintStream(java.io.PrintStream) InstanceManager(org.apache.tomcat.InstanceManager) ContainerServlet(org.apache.catalina.ContainerServlet) ServletException(javax.servlet.ServletException) MultipartConfigElement(javax.servlet.MultipartConfigElement) MultipartConfig(javax.servlet.annotation.MultipartConfig) Servlet(javax.servlet.Servlet) ContainerServlet(org.apache.catalina.ContainerServlet) SingleThreadModel(javax.servlet.SingleThreadModel)

Example 5 with SingleThreadModel

use of javax.servlet.SingleThreadModel in project tomcat70 by apache.

the class JspServletWrapper method service.

public void service(HttpServletRequest request, HttpServletResponse response, boolean precompile) throws ServletException, IOException, FileNotFoundException {
    Servlet servlet;
    try {
        if (ctxt.isRemoved()) {
            throw new FileNotFoundException(jspUri);
        }
        if ((available > 0L) && (available < Long.MAX_VALUE)) {
            if (available > System.currentTimeMillis()) {
                response.setDateHeader("Retry-After", available);
                response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, Localizer.getMessage("jsp.error.unavailable"));
                return;
            }
            // Wait period has expired. Reset.
            available = 0;
        }
        /*
             * (1) Compile
             */
        if (options.getDevelopment() || firstTime) {
            synchronized (this) {
                firstTime = false;
                // The following sets reload to true, if necessary
                ctxt.compile();
            }
        } else {
            if (compileException != null) {
                // Throw cached compilation exception
                throw compileException;
            }
        }
        /*
             * (2) (Re)load servlet class file
             */
        servlet = getServlet();
        // If a page is to be precompiled only, return.
        if (precompile) {
            return;
        }
    } catch (ServletException ex) {
        if (options.getDevelopment()) {
            throw handleJspException(ex);
        }
        throw ex;
    } catch (FileNotFoundException fnfe) {
        // File has been removed. Let caller handle this.
        throw fnfe;
    } catch (IOException ex) {
        if (options.getDevelopment()) {
            throw handleJspException(ex);
        }
        throw ex;
    } catch (IllegalStateException ex) {
        if (options.getDevelopment()) {
            throw handleJspException(ex);
        }
        throw ex;
    } catch (Exception ex) {
        if (options.getDevelopment()) {
            throw handleJspException(ex);
        }
        throw new JasperException(ex);
    }
    try {
        /*
             * (3) Handle limitation of number of loaded Jsps
             */
        if (unloadAllowed) {
            synchronized (this) {
                if (unloadByCount) {
                    if (unloadHandle == null) {
                        unloadHandle = ctxt.getRuntimeContext().push(this);
                    } else if (lastUsageTime < ctxt.getRuntimeContext().getLastJspQueueUpdate()) {
                        ctxt.getRuntimeContext().makeYoungest(unloadHandle);
                        lastUsageTime = System.currentTimeMillis();
                    }
                } else {
                    if (lastUsageTime < ctxt.getRuntimeContext().getLastJspQueueUpdate()) {
                        lastUsageTime = System.currentTimeMillis();
                    }
                }
            }
        }
        /*
             * (4) Service request
             */
        if (servlet instanceof SingleThreadModel) {
            // of the page is determined right before servicing
            synchronized (this) {
                servlet.service(request, response);
            }
        } else {
            servlet.service(request, response);
        }
    } catch (UnavailableException ex) {
        String includeRequestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI);
        if (includeRequestUri != null) {
            // servlet engine.
            throw ex;
        }
        int unavailableSeconds = ex.getUnavailableSeconds();
        if (unavailableSeconds <= 0) {
            // Arbitrary default
            unavailableSeconds = 60;
        }
        available = System.currentTimeMillis() + (unavailableSeconds * 1000L);
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, ex.getMessage());
    } catch (ServletException ex) {
        if (options.getDevelopment()) {
            throw handleJspException(ex);
        }
        throw ex;
    } catch (IOException ex) {
        if (options.getDevelopment()) {
            throw new IOException(handleJspException(ex).getMessage(), ex);
        }
        throw ex;
    } catch (IllegalStateException ex) {
        if (options.getDevelopment()) {
            throw handleJspException(ex);
        }
        throw ex;
    } catch (Exception ex) {
        if (options.getDevelopment()) {
            throw handleJspException(ex);
        }
        throw new JasperException(ex);
    }
}
Also used : ServletException(javax.servlet.ServletException) JasperException(org.apache.jasper.JasperException) FileNotFoundException(java.io.FileNotFoundException) UnavailableException(javax.servlet.UnavailableException) Servlet(javax.servlet.Servlet) IOException(java.io.IOException) SingleThreadModel(javax.servlet.SingleThreadModel) ServletException(javax.servlet.ServletException) JasperException(org.apache.jasper.JasperException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) UnavailableException(javax.servlet.UnavailableException)

Aggregations

SingleThreadModel (javax.servlet.SingleThreadModel)5 Servlet (javax.servlet.Servlet)4 ServletException (javax.servlet.ServletException)3 UnavailableException (javax.servlet.UnavailableException)2 ContainerServlet (org.apache.catalina.ContainerServlet)2 FileNotFoundException (java.io.FileNotFoundException)1 IOException (java.io.IOException)1 PrintStream (java.io.PrintStream)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 Stack (java.util.Stack)1 TreeMap (java.util.TreeMap)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 ConcurrentMap (java.util.concurrent.ConcurrentMap)1 MultipartConfigElement (javax.servlet.MultipartConfigElement)1 MultipartConfig (javax.servlet.annotation.MultipartConfig)1 HttpServlet (javax.servlet.http.HttpServlet)1 Container (org.apache.catalina.Container)1 FilterMap (org.apache.catalina.deploy.FilterMap)1 ServletMap (org.apache.catalina.deploy.ServletMap)1