Search in sources :

Example 71 with Servlet

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

the class SlingServletResolver method resolveServlet.

/**
     * @see org.apache.sling.api.servlets.ServletResolver#resolveServlet(org.apache.sling.api.resource.ResourceResolver, java.lang.String)
     */
@Override
public Servlet resolveServlet(final ResourceResolver resolver, final String scriptName) {
    if (resolver == null) {
        throw new IllegalArgumentException("Resource resolver must not be null");
    }
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("resolveServlet called for for script name {}", scriptName);
    }
    final ResourceResolver scriptResolver = this.getScriptResourceResolver();
    final Servlet servlet = resolveServletInternal(null, (Resource) null, scriptName, scriptResolver);
    // log the servlet found
    if (LOGGER.isDebugEnabled()) {
        if (servlet != null) {
            LOGGER.debug("Servlet {} found for script name {}", RequestUtil.getServletName(servlet), scriptName);
        } else {
            LOGGER.debug("No servlet found for script name {}", scriptName);
        }
    }
    return servlet;
}
Also used : ResourceResolver(org.apache.sling.api.resource.ResourceResolver) DefaultErrorHandlerServlet(org.apache.sling.servlets.resolver.internal.defaults.DefaultErrorHandlerServlet) HttpServlet(javax.servlet.http.HttpServlet) DefaultServlet(org.apache.sling.servlets.resolver.internal.defaults.DefaultServlet) Servlet(javax.servlet.Servlet) OptingServlet(org.apache.sling.api.servlets.OptingServlet)

Example 72 with Servlet

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

the class SlingServletResolver method handleError.

/**
     * @see org.apache.sling.engine.servlets.ErrorHandler#handleError(java.lang.Throwable, org.apache.sling.api.SlingHttpServletRequest, org.apache.sling.api.SlingHttpServletResponse)
     */
@Override
public void handleError(final Throwable throwable, final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws IOException {
    // do not handle, if already handling ....
    if (request.getAttribute(SlingConstants.ERROR_REQUEST_URI) != null) {
        LOGGER.error("handleError: Recursive invocation. Not further handling Throwable:", throwable);
        return;
    }
    // start tracker
    RequestProgressTracker tracker = request.getRequestProgressTracker();
    String timerName = "handleError:throwable=" + throwable.getClass().getName();
    tracker.startTimer(timerName);
    final ResourceResolver scriptResolver = this.getScriptResourceResolver();
    try {
        // find the error handler component
        Servlet servlet = null;
        Resource resource = getErrorResource(request);
        Class<?> tClass = throwable.getClass();
        while (servlet == null && tClass != Object.class) {
            // find a servlet for the simple class name as the method name
            ResourceCollector locationUtil = new ResourceCollector(tClass.getSimpleName(), DEFAULT_ERROR_HANDLER_RESOURCE_TYPE, resource, this.executionPaths);
            servlet = getServletInternal(locationUtil, request, scriptResolver);
            // go to the base class
            tClass = tClass.getSuperclass();
        }
        if (servlet == null) {
            servlet = getDefaultErrorServlet(request, resource, scriptResolver);
        }
        // set the message properties
        request.setAttribute(SlingConstants.ERROR_EXCEPTION, throwable);
        request.setAttribute(SlingConstants.ERROR_EXCEPTION_TYPE, throwable.getClass());
        request.setAttribute(SlingConstants.ERROR_MESSAGE, throwable.getMessage());
        // log a track entry after resolution before calling the handler
        tracker.logTimer(timerName, "Using handler {0}", RequestUtil.getServletName(servlet));
        handleError(servlet, request, response);
    } finally {
        tracker.logTimer(timerName, "Error handler finished");
    }
}
Also used : ResourceCollector(org.apache.sling.servlets.resolver.internal.helper.ResourceCollector) AbstractResourceCollector(org.apache.sling.servlets.resolver.internal.helper.AbstractResourceCollector) NamedScriptResourceCollector(org.apache.sling.servlets.resolver.internal.helper.NamedScriptResourceCollector) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) Resource(org.apache.sling.api.resource.Resource) SyntheticResource(org.apache.sling.api.resource.SyntheticResource) DefaultErrorHandlerServlet(org.apache.sling.servlets.resolver.internal.defaults.DefaultErrorHandlerServlet) HttpServlet(javax.servlet.http.HttpServlet) DefaultServlet(org.apache.sling.servlets.resolver.internal.defaults.DefaultServlet) Servlet(javax.servlet.Servlet) OptingServlet(org.apache.sling.api.servlets.OptingServlet) RequestProgressTracker(org.apache.sling.api.request.RequestProgressTracker)

Example 73 with Servlet

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

the class SlingServletResolverTest method testIgnoreRequest.

@Test
public void testIgnoreRequest() {
    MockSlingHttpServletRequest insecureRequest = new MockSlingHttpServletRequest(SERVLET_PATH, null, SERVLET_EXTENSION, null, null);
    insecureRequest.setResourceResolver(mockResourceResolver);
    insecureRequest.setSecure(false);
    Servlet result = servletResolver.resolveServlet(insecureRequest);
    assertTrue("Did not ignore unwanted request", result.getClass() != MockSlingRequestHandlerServlet.class);
}
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 74 with Servlet

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

the class SlingMainServlet method activate.

// ---------- Property Setter for SCR --------------------------------------
@Activate
protected void activate(final BundleContext bundleContext, final Map<String, Object> componentConfig, final Config config) {
    final String[] props = config.sling_additional_response_headers();
    if (props != null) {
        final ArrayList<StaticResponseHeader> mappings = new ArrayList<>(props.length);
        for (final String prop : props) {
            if (prop != null && prop.trim().length() > 0) {
                try {
                    final StaticResponseHeader mapping = new StaticResponseHeader(prop.trim());
                    mappings.add(mapping);
                } catch (final IllegalArgumentException iae) {
                    log.info("configure: Ignoring '{}': {}", prop, iae.getMessage());
                }
            }
        }
        RequestData.setAdditionalResponseHeaders(mappings);
    }
    configuredServerInfo = config.sling_serverinfo();
    // setup server info
    setProductInfo(bundleContext);
    // prepare the servlet configuration from the component config
    final Hashtable<String, Object> configuration = new Hashtable<>(componentConfig);
    // ensure the servlet name
    if (!(configuration.get("servlet-name") instanceof String)) {
        configuration.put("servlet-name", this.productInfo);
    }
    // configure method filter
    allowTrace = config.sling_trace_allow();
    // configure the request limits
    RequestData.setMaxIncludeCounter(config.sling_max_inclusions());
    RequestData.setMaxCallCounter(config.sling_max_calls());
    RequestData.setSlingMainServlet(this);
    // Warn about the obsolete parameter encoding configuration
    if (componentConfig.get(DEPRECATED_ENCODING_PROPERTY) != null) {
        log.warn("Please configure the default request parameter encoding using " + "the 'org.apache.sling.engine.parameters' configuration PID; the property " + DEPRECATED_ENCODING_PROPERTY + "=" + componentConfig.get(DEPRECATED_ENCODING_PROPERTY) + " is obsolete and ignored");
    }
    // register the servlet context
    final Dictionary<String, String> contextProperties = new Hashtable<>();
    contextProperties.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME, SERVLET_CONTEXT_NAME);
    contextProperties.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_PATH, SLING_ROOT);
    contextProperties.put(Constants.SERVICE_DESCRIPTION, "Apache Sling Engine Servlet Context Helper");
    contextProperties.put(Constants.SERVICE_VENDOR, "The Apache Software Foundation");
    this.contextRegistration = bundleContext.registerService(ServletContextHelper.class, this.slingHttpContext, contextProperties);
    // register the servlet
    final Dictionary<String, String> servletConfig = toStringConfig(configuration);
    servletConfig.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_SELECT, "(" + HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME + "=" + SERVLET_CONTEXT_NAME + ")");
    servletConfig.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, SLING_ROOT);
    servletConfig.put(Constants.SERVICE_DESCRIPTION, "Apache Sling Engine Main Servlet");
    servletConfig.put(Constants.SERVICE_VENDOR, "The Apache Software Foundation");
    this.servletRegistration = bundleContext.registerService(Servlet.class, this, servletConfig);
    log.info("{} ready to serve requests", this.getServerInfo());
    // now that the sling main servlet is registered with the HttpService
    // and initialized we can register the servlet context
    slingServletContext = new SlingServletContext(bundleContext, this);
    // register render filters already registered after registration with
    // the HttpService as filter initialization may cause the servlet
    // context to be required (see SLING-42)
    filterManager = new ServletFilterManager(bundleContext, slingServletContext);
    filterManager.open();
    requestProcessor.setFilterManager(filterManager);
    // initialize requestListenerManager
    requestListenerManager = new RequestListenerManager(bundleContext, slingServletContext);
    // Setup configuration printer
    this.printerRegistration = WebConsoleConfigPrinter.register(bundleContext, filterManager);
    // setup the request info recorder
    try {
        int maxRequests = config.sling_max_record_requests();
        String[] patterns = config.sling_store_pattern_requests();
        if (patterns == null)
            patterns = new String[0];
        List<Pattern> compiledPatterns = new ArrayList<>(patterns.length);
        for (String pattern : patterns) {
            if (pattern != null && pattern.trim().length() > 0) {
                compiledPatterns.add(Pattern.compile(pattern));
            }
        }
        RequestHistoryConsolePlugin.initPlugin(bundleContext, maxRequests, compiledPatterns);
    } catch (Throwable t) {
        log.debug("Unable to register web console request recorder plugin.", t);
    }
    try {
        Dictionary<String, String> mbeanProps = new Hashtable<>();
        mbeanProps.put("jmx.objectname", "org.apache.sling:type=engine,service=RequestProcessor");
        RequestProcessorMBeanImpl mbean = new RequestProcessorMBeanImpl();
        requestProcessorMBeanRegistration = bundleContext.registerService(RequestProcessorMBean.class, mbean, mbeanProps);
        requestProcessor.setMBean(mbean);
    } catch (Throwable t) {
        log.debug("Unable to register mbean");
    }
    // provide the SlingRequestProcessor service
    Hashtable<String, String> srpProps = new Hashtable<>();
    srpProps.put(Constants.SERVICE_VENDOR, "The Apache Software Foundation");
    srpProps.put(Constants.SERVICE_DESCRIPTION, "Sling Request Processor");
    requestProcessorRegistration = bundleContext.registerService(SlingRequestProcessor.class, requestProcessor, srpProps);
}
Also used : Pattern(java.util.regex.Pattern) Hashtable(java.util.Hashtable) ArrayList(java.util.ArrayList) SlingRequestProcessor(org.apache.sling.engine.SlingRequestProcessor) SlingServletContext(org.apache.sling.engine.impl.helper.SlingServletContext) ServletContextHelper(org.osgi.service.http.context.ServletContextHelper) RequestProcessorMBean(org.apache.sling.engine.jmx.RequestProcessorMBean) RequestListenerManager(org.apache.sling.engine.impl.helper.RequestListenerManager) ServletFilterManager(org.apache.sling.engine.impl.filter.ServletFilterManager) Servlet(javax.servlet.Servlet) GenericServlet(javax.servlet.GenericServlet) Activate(org.osgi.service.component.annotations.Activate)

Example 75 with Servlet

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

the class SlingRequestProcessorImpl method dispatchRequest.

// ---------- Generic Content Request processor ----------------------------
/**
     * Dispatches the request on behalf of the
     * {@link org.apache.sling.engine.impl.request.SlingRequestDispatcher}.
     */
public void dispatchRequest(ServletRequest request, ServletResponse response, Resource resource, RequestPathInfo resolvedURL, boolean include) throws IOException, ServletException {
    // we need a SlingHttpServletRequest/SlingHttpServletResponse tupel
    // to continue
    SlingHttpServletRequest cRequest = RequestData.toSlingHttpServletRequest(request);
    SlingHttpServletResponse cResponse = RequestData.toSlingHttpServletResponse(response);
    // get the request data (and btw check the correct type)
    final RequestData requestData = RequestData.getRequestData(cRequest);
    final ContentData oldContentData = requestData.getContentData();
    final ContentData contentData = requestData.setContent(resource, resolvedURL);
    try {
        // resolve the servlet
        Servlet servlet = servletResolver.resolveServlet(cRequest);
        contentData.setServlet(servlet);
        FilterChainType type = include ? FilterChainType.INCLUDE : FilterChainType.FORWARD;
        processComponent(cRequest, cResponse, type);
    } finally {
        requestData.resetContent(oldContentData);
    }
}
Also used : SlingHttpServletResponse(org.apache.sling.api.SlingHttpServletResponse) ContentData(org.apache.sling.engine.impl.request.ContentData) RequestData(org.apache.sling.engine.impl.request.RequestData) Servlet(javax.servlet.Servlet) SlingHttpServletRequest(org.apache.sling.api.SlingHttpServletRequest) FilterChainType(org.apache.sling.engine.impl.filter.ServletFilterManager.FilterChainType)

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