Search in sources :

Example 41 with Servlet

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

the class DefaultGetServlet method doGet.

/**
     * @throws ResourceNotFoundException if the resource of the request is a non
     *             existing resource.
     */
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
    // cannot handle the request for missing resources
    if (ResourceUtil.isNonExistingResource(request.getResource())) {
        throw new ResourceNotFoundException(request.getResource().getPath(), "No resource found");
    }
    Servlet rendererServlet;
    String ext = request.getRequestPathInfo().getExtension();
    if (ext == null) {
        rendererServlet = streamerServlet;
    } else {
        rendererServlet = rendererMap.get(ext);
    }
    // fail if we should not just stream or we cannot support the ext.
    if (rendererServlet == null) {
        request.getRequestProgressTracker().log("No renderer for extension " + ext);
        // do nothing (but log an error message)
        if (response.isCommitted() || request.getAttribute(SlingConstants.ATTR_REQUEST_SERVLET) != null) {
            logger.error("No renderer for extension {}, cannot render resource {}", ext, request.getResource());
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
        return;
    }
    request.getRequestProgressTracker().log("Using " + rendererServlet.getClass().getName() + " to render for extension=" + ext);
    rendererServlet.service(request, response);
}
Also used : JsonRendererServlet(org.apache.sling.servlets.get.impl.helpers.JsonRendererServlet) StreamRendererServlet(org.apache.sling.servlets.get.impl.helpers.StreamRendererServlet) HtmlRendererServlet(org.apache.sling.servlets.get.impl.helpers.HtmlRendererServlet) Servlet(javax.servlet.Servlet) PlainTextRendererServlet(org.apache.sling.servlets.get.impl.helpers.PlainTextRendererServlet) SlingSafeMethodsServlet(org.apache.sling.api.servlets.SlingSafeMethodsServlet) XMLRendererServlet(org.apache.sling.servlets.get.impl.helpers.XMLRendererServlet) ResourceNotFoundException(org.apache.sling.api.resource.ResourceNotFoundException)

Example 42 with Servlet

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

the class SlingServletResolverTest method testAcceptsRequest.

@Test
public void testAcceptsRequest() {
    MockSlingHttpServletRequest secureRequest = new MockSlingHttpServletRequest(SERVLET_PATH, null, SERVLET_EXTENSION, null, null);
    secureRequest.setResourceResolver(mockResourceResolver);
    secureRequest.setSecure(true);
    Servlet result = servletResolver.resolveServlet(secureRequest);
    assertEquals("Did not resolve to correct servlet", servlet, result);
}
Also used : MockSlingHttpServletRequest(org.apache.sling.commons.testing.sling.MockSlingHttpServletRequest) HttpServlet(javax.servlet.http.HttpServlet) Servlet(javax.servlet.Servlet) OptingServlet(org.apache.sling.api.servlets.OptingServlet) Test(org.junit.Test)

Example 43 with Servlet

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

the class SlingServletDelegate method init.

/**
     * Initializes this servlet by loading the framework configuration
     * properties, starting the OSGi framework (Apache Felix) and exposing the
     * system bundle context and the <code>Felix</code> instance as servlet
     * context attributes.
     *
     * @throws ServletException if the framework cannot be initialized.
     */
@Override
public final void init() throws ServletException {
    // temporary holders control final setup and ensure proper
    // disposal in case of setup errors
    Sling tmpSling = null;
    Servlet tmpDelegatee = null;
    try {
        log("Starting Apache Sling in " + slingHome);
        // read the default parameters
        Map<String, String> props = loadConfigProperties(slingHome);
        Logger logger = new ServletContextLogger(getServletContext());
        LaunchpadContentProvider rp = new ServletContextResourceProvider(getServletContext());
        tmpSling = SlingBridge.getSlingBridge(notifiable, logger, rp, props, getServletContext());
        // set up the OSGi HttpService proxy servlet
        tmpDelegatee = new ProxyServlet();
        tmpDelegatee.init(getServletConfig());
        // them destroyed in the finally clause.
        if (servletDestroyed) {
            log("SlingServletDelegate destroyed while starting Apache Sling, shutting Apache Sling down");
        } else {
            // set the fields now
            sling = tmpSling;
            delegatee = tmpDelegatee;
            // reset temporary holders to prevent destroyal
            tmpSling = null;
            tmpDelegatee = null;
            log("Apache Sling successfully started in " + slingHome);
        }
    } catch (BundleException be) {
        throw new ServletException("Failed to start Apache Sling in " + slingHome, be);
    } catch (ServletException se) {
        throw new ServletException("Failed to start bridge servlet for Apache Sling", se);
    } catch (Throwable t) {
        throw new ServletException("Uncaught Failure starting Apache Sling", t);
    } finally {
        // clean up temporary fields
        if (tmpDelegatee != null) {
            tmpDelegatee.destroy();
        }
        if (tmpSling != null) {
            tmpSling.destroy();
        }
    }
}
Also used : ServletException(javax.servlet.ServletException) LaunchpadContentProvider(org.apache.sling.launchpad.api.LaunchpadContentProvider) ProxyServlet(org.apache.felix.http.proxy.ProxyServlet) ProxyServlet(org.apache.felix.http.proxy.ProxyServlet) Servlet(javax.servlet.Servlet) GenericServlet(javax.servlet.GenericServlet) BundleException(org.osgi.framework.BundleException) Logger(org.apache.felix.framework.Logger) Sling(org.apache.sling.launchpad.base.impl.Sling)

Example 44 with Servlet

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

the class SlingServlet method service.

/**
     * If Sling has already been started, the request is forwarded to the
     * started Sling framework. Otherwise the Sling framework is started unless
     * there were too many startup failures.
     * <p>
     * If the request is not forwarded to Sling, this method returns a 404/NOT
     * FOUND if the startup failure counter has exceeded or 503/SERVICE
     * UNAVAILABLE if the Sling framework is starting up.
     * <p>
     * If a request causes the framework to start, it is immediately terminated
     * with said response status and framework is started in a separate thread.
     */
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
    // delegate the request to the registered delegatee servlet
    Servlet delegatee = sling;
    if (delegatee != null) {
        // check for problematic application servers like WebSphere
        // where path info and servlet path is set wrong SLING-2410
        final HttpServletRequest request = (HttpServletRequest) req;
        if (request.getPathInfo() == null && request.getServletPath() != null && request.getServletPath().endsWith(".jsp")) {
            req = new HttpServletRequestWrapper(request) {

                @Override
                public String getPathInfo() {
                    return request.getServletPath();
                }

                @Override
                public String getServletPath() {
                    return "";
                }
            };
        }
        delegatee.service(req, res);
    } else if (startFailureCounter > MAX_START_FAILURES) {
        // too many startup retries, fail for ever
        ((HttpServletResponse) res).sendError(HttpServletResponse.SC_NOT_FOUND);
    } else {
        startSling(req);
        ((HttpServletResponse) res).sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Apache Sling is currently starting up, please try again");
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) Servlet(javax.servlet.Servlet) GenericServlet(javax.servlet.GenericServlet)

Example 45 with Servlet

use of javax.servlet.Servlet in project tomee by apache.

the class HttpUtil method addServlet.

public static boolean addServlet(final String classname, final WebContext wc, final String mapping) {
    final HttpListenerRegistry registry = SystemInstance.get().getComponent(HttpListenerRegistry.class);
    if (registry == null || mapping == null) {
        return false;
    }
    final ServletListener listener;
    try {
        ServletContext servletContext = wc.getServletContext();
        if (servletContext == null) {
            servletContext = SystemInstance.get().getComponent(ServletContext.class);
        }
        if ("javax.faces.webapp.FacesServlet".equals(classname)) {
            try {
                // faking it to let the FacesServlet starting
                // NOTE: needs myfaces-impl + tomcat-jasper (JspFactory)
                // TODO: handle the whole lifecycle (cleanup mainly) + use myfaces SPI to make scanning really faster (take care should work in tomee were we already have it impl)
                final Class<?> mfListenerClass = wc.getClassLoader().loadClass("org.apache.myfaces.webapp.StartupServletContextListener");
                final ServletContextListener servletContextListener = ServletContextListener.class.cast(mfListenerClass.newInstance());
                servletContext.setAttribute("javax.enterprise.inject.spi.BeanManager", new InjectableBeanManager(wc.getWebBeansContext().getBeanManagerImpl()));
                final Thread thread = Thread.currentThread();
                final ClassLoader old = setClassLoader(wc, thread);
                try {
                    servletContextListener.contextInitialized(new ServletContextEvent(servletContext));
                } finally {
                    thread.setContextClassLoader(old);
                }
                servletContext.removeAttribute("javax.enterprise.inject.spi.BeanManager");
            } catch (final Exception e) {
            // no-op
            }
        }
        final Thread thread = Thread.currentThread();
        final ClassLoader old = setClassLoader(wc, thread);
        try {
            listener = new ServletListener((Servlet) wc.newInstance(wc.getClassLoader().loadClass(classname)), wc.getContextRoot());
            final ServletContext sc = servletContext;
            listener.getDelegate().init(new ServletConfig() {

                @Override
                public String getServletName() {
                    return classname;
                }

                @Override
                public ServletContext getServletContext() {
                    return sc;
                }

                @Override
                public String getInitParameter(final String s) {
                    return sc.getInitParameter(s);
                }

                @Override
                public Enumeration<String> getInitParameterNames() {
                    final Enumeration<String> parameterNames = sc.getInitParameterNames();
                    return parameterNames == null ? Collections.<String>emptyEnumeration() : parameterNames;
                }
            });
        } finally {
            thread.setContextClassLoader(old);
        }
    } catch (final Exception e) {
        throw new OpenEJBRuntimeException(e);
    }
    registry.addHttpListener(listener, pattern(wc.getContextRoot(), "/".equals(mapping) ? "/*" : mapping));
    return true;
}
Also used : Enumeration(java.util.Enumeration) ServletContextListener(javax.servlet.ServletContextListener) InjectableBeanManager(org.apache.webbeans.container.InjectableBeanManager) ServletConfig(javax.servlet.ServletConfig) HttpListenerRegistry(org.apache.openejb.server.httpd.HttpListenerRegistry) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) ServletListener(org.apache.openejb.server.httpd.ServletListener) ServletContext(javax.servlet.ServletContext) Servlet(javax.servlet.Servlet) ServletContextEvent(javax.servlet.ServletContextEvent)

Aggregations

Servlet (javax.servlet.Servlet)86 Test (org.junit.Test)18 HttpServlet (javax.servlet.http.HttpServlet)16 ServletException (javax.servlet.ServletException)15 IOException (java.io.IOException)11 OptingServlet (org.apache.sling.api.servlets.OptingServlet)11 GenericServlet (javax.servlet.GenericServlet)10 DefaultErrorHandlerServlet (org.apache.sling.servlets.resolver.internal.defaults.DefaultErrorHandlerServlet)9 DefaultServlet (org.apache.sling.servlets.resolver.internal.defaults.DefaultServlet)9 ServletContext (javax.servlet.ServletContext)8 UnavailableException (javax.servlet.UnavailableException)8 Resource (org.apache.sling.api.resource.Resource)8 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)8 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)7 MockServletWebServerFactory (org.springframework.boot.web.servlet.server.MockServletWebServerFactory)7 ServletInfo (io.undertow.servlet.api.ServletInfo)6 ArrayList (java.util.ArrayList)5 Filter (javax.servlet.Filter)5 Context (org.apache.catalina.Context)5 SlingHttpServletResponse (org.apache.sling.api.SlingHttpServletResponse)5