Search in sources :

Example 31 with DispatcherType

use of javax.servlet.DispatcherType in project jetty.project by eclipse.

the class StandardDescriptorProcessor method addFilterMapping.

public void addFilterMapping(String filterName, XmlParser.Node node, WebAppContext context, Descriptor descriptor) {
    FilterMapping mapping = new FilterMapping();
    mapping.setFilterName(filterName);
    List<String> paths = new ArrayList<String>();
    Iterator<XmlParser.Node> iter = node.iterator("url-pattern");
    while (iter.hasNext()) {
        String p = iter.next().toString(false, true);
        p = ServletPathSpec.normalize(p);
        paths.add(p);
        context.getMetaData().setOrigin(filterName + ".filter.mapping." + p, descriptor);
    }
    mapping.setPathSpecs((String[]) paths.toArray(new String[paths.size()]));
    List<String> names = new ArrayList<String>();
    iter = node.iterator("servlet-name");
    while (iter.hasNext()) {
        String n = ((XmlParser.Node) iter.next()).toString(false, true);
        names.add(n);
    }
    mapping.setServletNames((String[]) names.toArray(new String[names.size()]));
    List<DispatcherType> dispatches = new ArrayList<DispatcherType>();
    iter = node.iterator("dispatcher");
    while (iter.hasNext()) {
        String d = ((XmlParser.Node) iter.next()).toString(false, true);
        dispatches.add(FilterMapping.dispatch(d));
    }
    if (dispatches.size() > 0)
        mapping.setDispatcherTypes(EnumSet.copyOf(dispatches));
    _filterMappings.add(mapping);
}
Also used : Node(org.eclipse.jetty.xml.XmlParser.Node) ArrayList(java.util.ArrayList) FilterMapping(org.eclipse.jetty.servlet.FilterMapping) DispatcherType(javax.servlet.DispatcherType)

Example 32 with DispatcherType

use of javax.servlet.DispatcherType in project jetty.project by eclipse.

the class ContextHandler method doScope.

/* ------------------------------------------------------------ */
/**
     * @see org.eclipse.jetty.server.handler.ScopedHandler#doScope(java.lang.String, org.eclipse.jetty.server.Request, javax.servlet.http.HttpServletRequest,
     *      javax.servlet.http.HttpServletResponse)
     */
@Override
public void doScope(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    if (LOG.isDebugEnabled())
        LOG.debug("scope {}|{}|{} @ {}", baseRequest.getContextPath(), baseRequest.getServletPath(), baseRequest.getPathInfo(), this);
    Context old_context = null;
    String old_context_path = null;
    String old_servlet_path = null;
    String old_path_info = null;
    ClassLoader old_classloader = null;
    Thread current_thread = null;
    String pathInfo = target;
    DispatcherType dispatch = baseRequest.getDispatcherType();
    old_context = baseRequest.getContext();
    // Are we already in this context?
    if (old_context != _scontext) {
        // check the target.
        if (DispatcherType.REQUEST.equals(dispatch) || DispatcherType.ASYNC.equals(dispatch) || DispatcherType.ERROR.equals(dispatch) && baseRequest.getHttpChannelState().isAsync()) {
            if (_compactPath)
                target = URIUtil.compactPath(target);
            if (!checkContext(target, baseRequest, response))
                return;
            if (target.length() > _contextPath.length()) {
                if (_contextPath.length() > 1)
                    target = target.substring(_contextPath.length());
                pathInfo = target;
            } else if (_contextPath.length() == 1) {
                target = URIUtil.SLASH;
                pathInfo = URIUtil.SLASH;
            } else {
                target = URIUtil.SLASH;
                pathInfo = null;
            }
        }
        // Set the classloader
        if (_classLoader != null) {
            current_thread = Thread.currentThread();
            old_classloader = current_thread.getContextClassLoader();
            current_thread.setContextClassLoader(_classLoader);
        }
    }
    try {
        old_context_path = baseRequest.getContextPath();
        old_servlet_path = baseRequest.getServletPath();
        old_path_info = baseRequest.getPathInfo();
        // Update the paths
        baseRequest.setContext(_scontext);
        __context.set(_scontext);
        if (!DispatcherType.INCLUDE.equals(dispatch) && target.startsWith("/")) {
            if (_contextPath.length() == 1)
                baseRequest.setContextPath("");
            else
                baseRequest.setContextPath(_contextPathEncoded);
            baseRequest.setServletPath(null);
            baseRequest.setPathInfo(pathInfo);
        }
        if (old_context != _scontext)
            enterScope(baseRequest, dispatch);
        if (LOG.isDebugEnabled())
            LOG.debug("context={}|{}|{} @ {}", baseRequest.getContextPath(), baseRequest.getServletPath(), baseRequest.getPathInfo(), this);
        nextScope(target, baseRequest, request, response);
    } finally {
        if (old_context != _scontext) {
            exitScope(baseRequest);
            // reset the classloader
            if (_classLoader != null && current_thread != null) {
                current_thread.setContextClassLoader(old_classloader);
            }
            // reset the context and servlet path.
            baseRequest.setContext(old_context);
            __context.set(old_context);
            baseRequest.setContextPath(old_context_path);
            baseRequest.setServletPath(old_servlet_path);
            baseRequest.setPathInfo(old_path_info);
        }
    }
}
Also used : ServletContext(javax.servlet.ServletContext) URLClassLoader(java.net.URLClassLoader) DispatcherType(javax.servlet.DispatcherType)

Example 33 with DispatcherType

use of javax.servlet.DispatcherType in project jetty.project by eclipse.

the class WebSocketUpgradeFilter method configureContext.

public static WebSocketUpgradeFilter configureContext(ServletContextHandler context) throws ServletException {
    // Prevent double configure
    WebSocketUpgradeFilter filter = (WebSocketUpgradeFilter) context.getAttribute(WebSocketUpgradeFilter.class.getName());
    if (filter != null) {
        return filter;
    }
    // Dynamically add filter
    NativeWebSocketConfiguration configuration = NativeWebSocketServletContainerInitializer.getDefaultFrom(context.getServletContext());
    filter = new WebSocketUpgradeFilter(configuration);
    filter.setToAttribute(context, WebSocketUpgradeFilter.class.getName());
    String name = "Jetty_WebSocketUpgradeFilter";
    String pathSpec = "/*";
    EnumSet<DispatcherType> dispatcherTypes = EnumSet.of(DispatcherType.REQUEST);
    FilterHolder fholder = new FilterHolder(filter);
    fholder.setName(name);
    fholder.setAsyncSupported(true);
    fholder.setInitParameter(CONTEXT_ATTRIBUTE_KEY, WebSocketUpgradeFilter.class.getName());
    context.addFilter(fholder, pathSpec, dispatcherTypes);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Adding [{}] {} mapped to {} to {}", name, filter, pathSpec, context);
    }
    return filter;
}
Also used : FilterHolder(org.eclipse.jetty.servlet.FilterHolder) DispatcherType(javax.servlet.DispatcherType)

Example 34 with DispatcherType

use of javax.servlet.DispatcherType in project spring-boot by spring-projects.

the class SecurityAutoConfigurationTests method defaultFilterDispatcherTypes.

@Test
public void defaultFilterDispatcherTypes() {
    this.context = new AnnotationConfigWebApplicationContext();
    this.context.setServletContext(new MockServletContext());
    this.context.register(SecurityAutoConfiguration.class, SecurityFilterAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class);
    this.context.refresh();
    DelegatingFilterProxyRegistrationBean bean = this.context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class);
    @SuppressWarnings("unchecked") EnumSet<DispatcherType> dispatcherTypes = (EnumSet<DispatcherType>) ReflectionTestUtils.getField(bean, "dispatcherTypes");
    assertThat(dispatcherTypes).containsOnly(DispatcherType.ASYNC, DispatcherType.ERROR, DispatcherType.REQUEST);
}
Also used : DelegatingFilterProxyRegistrationBean(org.springframework.boot.web.servlet.DelegatingFilterProxyRegistrationBean) EnumSet(java.util.EnumSet) DispatcherType(javax.servlet.DispatcherType) AnnotationConfigWebApplicationContext(org.springframework.web.context.support.AnnotationConfigWebApplicationContext) MockServletContext(org.springframework.mock.web.MockServletContext) Test(org.junit.Test)

Example 35 with DispatcherType

use of javax.servlet.DispatcherType in project nifi by apache.

the class HandleHttpRequest method onTrigger.

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    try {
        if (!initialized.get()) {
            initializeServer(context);
        }
    } catch (Exception e) {
        context.yield();
        try {
            // shutdown to release any resources allocated during the failed initialization
            shutdown();
        } catch (final Exception shutdownException) {
            getLogger().debug("Failed to shutdown following a failed initialization: " + shutdownException);
        }
        throw new ProcessException("Failed to initialize the server", e);
    }
    HttpRequestContainer container;
    try {
        container = containerQueue.poll(2, TimeUnit.MILLISECONDS);
    } catch (final InterruptedException e1) {
        Thread.currentThread().interrupt();
        return;
    }
    if (container == null) {
        return;
    }
    final long start = System.nanoTime();
    final HttpServletRequest request = container.getRequest();
    FlowFile flowFile = session.create();
    try (OutputStream flowFileOut = session.write(flowFile)) {
        StreamUtils.copy(request.getInputStream(), flowFileOut);
    } catch (final IOException e) {
        // There may be many reasons which can produce an IOException on the HTTP stream and in some of them, eg.
        // bad requests, the connection to the client is not closed. In order to address also these cases, we try
        // and answer with a BAD_REQUEST, which lets the client know that the request has not been correctly
        // processed and makes it aware that the connection can be closed.
        getLogger().error("Failed to receive content from HTTP Request from {} due to {}", new Object[] { request.getRemoteAddr(), e });
        session.remove(flowFile);
        try {
            HttpServletResponse response = container.getResponse();
            response.sendError(Status.BAD_REQUEST.getStatusCode());
            response.flushBuffer();
            container.getContext().complete();
        } catch (final IOException ioe) {
            getLogger().warn("Failed to send HTTP response to {} due to {}", new Object[] { request.getRemoteAddr(), ioe });
        }
        return;
    }
    final String charset = request.getCharacterEncoding() == null ? context.getProperty(URL_CHARACTER_SET).getValue() : request.getCharacterEncoding();
    final String contextIdentifier = UUID.randomUUID().toString();
    final Map<String, String> attributes = new HashMap<>();
    try {
        putAttribute(attributes, HTTPUtils.HTTP_CONTEXT_ID, contextIdentifier);
        putAttribute(attributes, "mime.type", request.getContentType());
        putAttribute(attributes, "http.servlet.path", request.getServletPath());
        putAttribute(attributes, "http.context.path", request.getContextPath());
        putAttribute(attributes, "http.method", request.getMethod());
        putAttribute(attributes, "http.local.addr", request.getLocalAddr());
        putAttribute(attributes, HTTPUtils.HTTP_LOCAL_NAME, request.getLocalName());
        final String queryString = request.getQueryString();
        if (queryString != null) {
            putAttribute(attributes, "http.query.string", URLDecoder.decode(queryString, charset));
        }
        putAttribute(attributes, HTTPUtils.HTTP_REMOTE_HOST, request.getRemoteHost());
        putAttribute(attributes, "http.remote.addr", request.getRemoteAddr());
        putAttribute(attributes, "http.remote.user", request.getRemoteUser());
        putAttribute(attributes, "http.protocol", request.getProtocol());
        putAttribute(attributes, HTTPUtils.HTTP_REQUEST_URI, request.getRequestURI());
        putAttribute(attributes, "http.request.url", request.getRequestURL().toString());
        putAttribute(attributes, "http.auth.type", request.getAuthType());
        putAttribute(attributes, "http.requested.session.id", request.getRequestedSessionId());
        final DispatcherType dispatcherType = request.getDispatcherType();
        if (dispatcherType != null) {
            putAttribute(attributes, "http.dispatcher.type", dispatcherType.name());
        }
        putAttribute(attributes, "http.character.encoding", request.getCharacterEncoding());
        putAttribute(attributes, "http.locale", request.getLocale());
        putAttribute(attributes, "http.server.name", request.getServerName());
        putAttribute(attributes, HTTPUtils.HTTP_PORT, request.getServerPort());
        final Enumeration<String> paramEnumeration = request.getParameterNames();
        while (paramEnumeration.hasMoreElements()) {
            final String paramName = paramEnumeration.nextElement();
            final String value = request.getParameter(paramName);
            attributes.put("http.param." + paramName, value);
        }
        final Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (final Cookie cookie : cookies) {
                final String name = cookie.getName();
                final String cookiePrefix = "http.cookie." + name + ".";
                attributes.put(cookiePrefix + "value", cookie.getValue());
                attributes.put(cookiePrefix + "domain", cookie.getDomain());
                attributes.put(cookiePrefix + "path", cookie.getPath());
                attributes.put(cookiePrefix + "max.age", String.valueOf(cookie.getMaxAge()));
                attributes.put(cookiePrefix + "version", String.valueOf(cookie.getVersion()));
                attributes.put(cookiePrefix + "secure", String.valueOf(cookie.getSecure()));
            }
        }
        if (queryString != null) {
            final String[] params = URL_QUERY_PARAM_DELIMITER.split(queryString);
            for (final String keyValueString : params) {
                final int indexOf = keyValueString.indexOf("=");
                if (indexOf < 0) {
                    // no =, then it's just a key with no value
                    attributes.put("http.query.param." + URLDecoder.decode(keyValueString, charset), "");
                } else {
                    final String key = keyValueString.substring(0, indexOf);
                    final String value;
                    if (indexOf == keyValueString.length() - 1) {
                        value = "";
                    } else {
                        value = keyValueString.substring(indexOf + 1);
                    }
                    attributes.put("http.query.param." + URLDecoder.decode(key, charset), URLDecoder.decode(value, charset));
                }
            }
        }
    } catch (final UnsupportedEncodingException uee) {
        // won't happen because charset has been validated
        throw new ProcessException("Invalid character encoding", uee);
    }
    final Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        final String headerName = headerNames.nextElement();
        final String headerValue = request.getHeader(headerName);
        putAttribute(attributes, "http.headers." + headerName, headerValue);
    }
    final Principal principal = request.getUserPrincipal();
    if (principal != null) {
        putAttribute(attributes, "http.principal.name", principal.getName());
    }
    final X509Certificate[] certs = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
    final String subjectDn;
    if (certs != null && certs.length > 0) {
        final X509Certificate cert = certs[0];
        subjectDn = cert.getSubjectDN().getName();
        final String issuerDn = cert.getIssuerDN().getName();
        putAttribute(attributes, HTTPUtils.HTTP_SSL_CERT, subjectDn);
        putAttribute(attributes, "http.issuer.dn", issuerDn);
    } else {
        subjectDn = null;
    }
    flowFile = session.putAllAttributes(flowFile, attributes);
    final HttpContextMap contextMap = context.getProperty(HTTP_CONTEXT_MAP).asControllerService(HttpContextMap.class);
    final boolean registered = contextMap.register(contextIdentifier, request, container.getResponse(), container.getContext());
    if (!registered) {
        getLogger().warn("Received request from {} but could not process it because too many requests are already outstanding; responding with SERVICE_UNAVAILABLE", new Object[] { request.getRemoteAddr() });
        try {
            container.getResponse().setStatus(Status.SERVICE_UNAVAILABLE.getStatusCode());
            container.getResponse().flushBuffer();
            container.getContext().complete();
        } catch (final Exception e) {
            getLogger().warn("Failed to respond with SERVICE_UNAVAILABLE message to {} due to {}", new Object[] { request.getRemoteAddr(), e });
        }
        session.remove(flowFile);
        return;
    }
    final long receiveMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
    session.getProvenanceReporter().receive(flowFile, HTTPUtils.getURI(attributes), "Received from " + request.getRemoteAddr() + (subjectDn == null ? "" : " with DN=" + subjectDn), receiveMillis);
    session.transfer(flowFile, REL_SUCCESS);
    getLogger().info("Transferring {} to 'success'; received from {}", new Object[] { flowFile, request.getRemoteAddr() });
}
Also used : HashMap(java.util.HashMap) HttpContextMap(org.apache.nifi.http.HttpContextMap) OutputStream(java.io.OutputStream) HttpServletRequest(javax.servlet.http.HttpServletRequest) DispatcherType(javax.servlet.DispatcherType) Cookie(javax.servlet.http.Cookie) FlowFile(org.apache.nifi.flowfile.FlowFile) HttpServletResponse(javax.servlet.http.HttpServletResponse) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) URISyntaxException(java.net.URISyntaxException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ProcessException(org.apache.nifi.processor.exception.ProcessException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) ProcessException(org.apache.nifi.processor.exception.ProcessException) Principal(java.security.Principal)

Aggregations

DispatcherType (javax.servlet.DispatcherType)45 ServletContext (javax.servlet.ServletContext)6 ServletRequest (javax.servlet.ServletRequest)6 IOException (java.io.IOException)5 FilterMap (org.apache.catalina.deploy.FilterMap)5 ServletResponse (javax.servlet.ServletResponse)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 HttpServletResponse (javax.servlet.http.HttpServletResponse)4 Server (org.eclipse.jetty.server.Server)4 FilterHolder (org.eclipse.jetty.servlet.FilterHolder)4 AnnotationConfigWebApplicationContext (org.springframework.web.context.support.AnnotationConfigWebApplicationContext)4 DeploymentInfo (io.undertow.servlet.api.DeploymentInfo)3 File (java.io.File)3 WebInitParam (javax.servlet.annotation.WebInitParam)3 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)3 Test (org.junit.Test)3 ServletFilterMapping (com.sun.enterprise.deployment.web.ServletFilterMapping)2 ServletContainer (com.sun.jersey.spi.container.servlet.ServletContainer)2 ManagedFilter (io.undertow.servlet.core.ManagedFilter)2 ArrayList (java.util.ArrayList)2