Search in sources :

Example 46 with ServletRequestContext

use of io.undertow.servlet.handlers.ServletRequestContext in project undertow by undertow-io.

the class HttpServletRequestImpl method verifyMultipartServlet.

private void verifyMultipartServlet() {
    ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    MultipartConfigElement multipart = src.getServletPathMatch().getServletChain().getManagedServlet().getMultipartConfig();
    if (multipart == null) {
        throw UndertowServletMessages.MESSAGES.multipartConfigNotPresent();
    }
}
Also used : MultipartConfigElement(javax.servlet.MultipartConfigElement) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext)

Example 47 with ServletRequestContext

use of io.undertow.servlet.handlers.ServletRequestContext in project undertow by undertow-io.

the class HttpServletResponseImpl method doErrorDispatch.

public void doErrorDispatch(int sc, String error) throws IOException {
    writer = null;
    responseState = ResponseState.NONE;
    resetBuffer();
    treatAsCommitted = false;
    final String location = servletContext.getDeployment().getErrorPages().getErrorLocation(sc);
    if (location != null) {
        RequestDispatcherImpl requestDispatcher = new RequestDispatcherImpl(location, servletContext);
        final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
        try {
            requestDispatcher.error(servletRequestContext, servletRequestContext.getServletRequest(), servletRequestContext.getServletResponse(), exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY).getCurrentServlet().getManagedServlet().getServletInfo().getName(), error);
        } catch (ServletException e) {
            throw new RuntimeException(e);
        }
    } else if (error != null) {
        setContentType("text/html");
        setCharacterEncoding("UTF-8");
        if (servletContext.getDeployment().getDeploymentInfo().isEscapeErrorMessage()) {
            getWriter().write("<html><head><title>Error</title></head><body>" + escapeHtml(error) + "</body></html>");
        } else {
            getWriter().write("<html><head><title>Error</title></head><body>" + error + "</body></html>");
        }
        getWriter().close();
    }
    responseDone();
}
Also used : ServletException(javax.servlet.ServletException) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext) HttpString(io.undertow.util.HttpString)

Example 48 with ServletRequestContext

use of io.undertow.servlet.handlers.ServletRequestContext in project undertow by undertow-io.

the class HttpServletRequestImpl method startAsync.

@Override
public AsyncContext startAsync(final ServletRequest servletRequest, final ServletResponse servletResponse) throws IllegalStateException {
    final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
    if (!servletContext.getDeployment().getDeploymentInfo().isAllowNonStandardWrappers()) {
        if (servletRequestContext.getOriginalRequest() != servletRequest) {
            if (!(servletRequest instanceof ServletRequestWrapper)) {
                throw UndertowServletMessages.MESSAGES.requestWasNotOriginalOrWrapper(servletRequest);
            }
        }
        if (servletRequestContext.getOriginalResponse() != servletResponse) {
            if (!(servletResponse instanceof ServletResponseWrapper)) {
                throw UndertowServletMessages.MESSAGES.responseWasNotOriginalOrWrapper(servletResponse);
            }
        }
    }
    if (!isAsyncSupported()) {
        throw UndertowServletMessages.MESSAGES.startAsyncNotAllowed();
    } else if (asyncStarted) {
        throw UndertowServletMessages.MESSAGES.asyncAlreadyStarted();
    }
    asyncStarted = true;
    servletRequestContext.setServletRequest(servletRequest);
    servletRequestContext.setServletResponse(servletResponse);
    return asyncContext = new AsyncContextImpl(exchange, servletRequest, servletResponse, servletRequestContext, true, asyncContext);
}
Also used : ServletRequestWrapper(javax.servlet.ServletRequestWrapper) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext) ServletResponseWrapper(javax.servlet.ServletResponseWrapper)

Example 49 with ServletRequestContext

use of io.undertow.servlet.handlers.ServletRequestContext in project undertow by undertow-io.

the class EndpointSessionHandler method onConnect.

@Override
public void onConnect(WebSocketHttpExchange exchange, WebSocketChannel channel) {
    ConfiguredServerEndpoint config = HandshakeUtil.getConfig(channel);
    try {
        if (container.isClosed()) {
            // if the underlying container is closed we just reject
            channel.sendClose();
            channel.resumeReceives();
            return;
        }
        InstanceFactory<?> endpointFactory = config.getEndpointFactory();
        ServerEndpointConfig.Configurator configurator = config.getEndpointConfiguration().getConfigurator();
        final InstanceHandle<?> instance;
        DefaultContainerConfigurator.setCurrentInstanceFactory(endpointFactory);
        final Object instanceFromConfigurator = configurator.getEndpointInstance(config.getEndpointConfiguration().getEndpointClass());
        final InstanceHandle<?> factoryInstance = DefaultContainerConfigurator.clearCurrentInstanceFactory();
        if (factoryInstance == null) {
            instance = new ImmediateInstanceHandle<>(instanceFromConfigurator);
        } else if (factoryInstance.getInstance() == instanceFromConfigurator) {
            instance = factoryInstance;
        } else {
            // the default instance has been wrapped
            instance = new InstanceHandle<Object>() {

                @Override
                public Object getInstance() {
                    return instanceFromConfigurator;
                }

                @Override
                public void release() {
                    factoryInstance.release();
                }
            };
        }
        ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
        Principal principal = exchange.getAttachment(HandshakeUtil.PRINCIPAL);
        if (principal == null) {
            if (src.getServletRequest() instanceof HttpServletRequest) {
                principal = ((HttpServletRequest) src.getServletRequest()).getUserPrincipal();
            } else {
                principal = src.getOriginalRequest().getUserPrincipal();
            }
        }
        final InstanceHandle<Endpoint> endpointInstance;
        if (config.getAnnotatedEndpointFactory() != null) {
            final AnnotatedEndpoint annotated = config.getAnnotatedEndpointFactory().createInstance(instance);
            endpointInstance = new InstanceHandle<Endpoint>() {

                @Override
                public Endpoint getInstance() {
                    return annotated;
                }

                @Override
                public void release() {
                    instance.release();
                }
            };
        } else {
            endpointInstance = (InstanceHandle<Endpoint>) instance;
        }
        UndertowSession session = new UndertowSession(channel, URI.create(exchange.getRequestURI()), exchange.getAttachment(HandshakeUtil.PATH_PARAMS), exchange.getRequestParameters(), this, principal, endpointInstance, config.getEndpointConfiguration(), exchange.getQueryString(), config.getEncodingFactory().createEncoding(config.getEndpointConfiguration()), config, channel.getSubProtocol(), Collections.<Extension>emptyList(), null);
        config.addOpenSession(session);
        session.setMaxBinaryMessageBufferSize(getContainer().getDefaultMaxBinaryMessageBufferSize());
        session.setMaxTextMessageBufferSize(getContainer().getDefaultMaxTextMessageBufferSize());
        session.setMaxIdleTimeout(getContainer().getDefaultMaxSessionIdleTimeout());
        session.getAsyncRemote().setSendTimeout(getContainer().getDefaultAsyncSendTimeout());
        try {
            endpointInstance.getInstance().onOpen(session, config.getEndpointConfiguration());
        } catch (Exception e) {
            endpointInstance.getInstance().onError(session, e);
            IoUtils.safeClose(session);
        }
        channel.resumeReceives();
    } catch (Exception e) {
        JsrWebSocketLogger.REQUEST_LOGGER.endpointCreationFailed(e);
        IoUtils.safeClose(channel);
    }
}
Also used : ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext) AnnotatedEndpoint(io.undertow.websockets.jsr.annotated.AnnotatedEndpoint) HttpServletRequest(javax.servlet.http.HttpServletRequest) AnnotatedEndpoint(io.undertow.websockets.jsr.annotated.AnnotatedEndpoint) Endpoint(javax.websocket.Endpoint) InstanceHandle(io.undertow.servlet.api.InstanceHandle) ImmediateInstanceHandle(io.undertow.servlet.util.ImmediateInstanceHandle) Principal(java.security.Principal)

Example 50 with ServletRequestContext

use of io.undertow.servlet.handlers.ServletRequestContext in project undertow by undertow-io.

the class JsrWebSocketFilter method doFilter.

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;
    if (req.getHeader(Headers.UPGRADE_STRING) != null) {
        final ServletWebSocketHttpExchange facade = new ServletWebSocketHttpExchange(req, resp, peerConnections);
        String path;
        if (req.getPathInfo() == null) {
            path = req.getServletPath();
        } else {
            path = req.getServletPath() + req.getPathInfo();
        }
        if (!path.startsWith("/")) {
            path = "/" + path;
        }
        PathTemplateMatcher.PathMatchResult<WebSocketHandshakeHolder> matchResult = pathTemplateMatcher.match(path);
        if (matchResult != null) {
            Handshake handshaker = null;
            for (Handshake method : matchResult.getValue().handshakes) {
                if (method.matches(facade)) {
                    handshaker = method;
                    break;
                }
            }
            if (handshaker != null) {
                if (container.isClosed()) {
                    resp.sendError(StatusCodes.SERVICE_UNAVAILABLE);
                    return;
                }
                facade.putAttachment(HandshakeUtil.PATH_PARAMS, matchResult.getParameters());
                facade.putAttachment(HandshakeUtil.PRINCIPAL, req.getUserPrincipal());
                final Handshake selected = handshaker;
                ServletRequestContext src = ServletRequestContext.requireCurrent();
                final HttpSessionImpl session = src.getCurrentServletContext().getSession(src.getExchange(), false);
                facade.upgradeChannel(new HttpUpgradeListener() {

                    @Override
                    public void handleUpgrade(StreamConnection streamConnection, HttpServerExchange exchange) {
                        WebSocketChannel channel = selected.createChannel(facade, streamConnection, facade.getBufferPool());
                        peerConnections.add(channel);
                        if (session != null) {
                            final Session underlying;
                            if (System.getSecurityManager() == null) {
                                underlying = session.getSession();
                            } else {
                                underlying = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(session));
                            }
                            List<WebSocketChannel> connections;
                            synchronized (underlying) {
                                connections = (List<WebSocketChannel>) underlying.getAttribute(SESSION_ATTRIBUTE);
                                if (connections == null) {
                                    underlying.setAttribute(SESSION_ATTRIBUTE, connections = new ArrayList<>());
                                }
                                connections.add(channel);
                            }
                            final List<WebSocketChannel> finalConnections = connections;
                            channel.addCloseTask(new ChannelListener<WebSocketChannel>() {

                                @Override
                                public void handleEvent(WebSocketChannel channel) {
                                    synchronized (underlying) {
                                        finalConnections.remove(channel);
                                    }
                                }
                            });
                        }
                        callback.onConnect(facade, channel);
                    }
                });
                handshaker.handshake(facade);
                return;
            }
        }
    }
    chain.doFilter(request, response);
}
Also used : ChannelListener(org.xnio.ChannelListener) WebSocketHandshakeHolder(io.undertow.websockets.jsr.ServerWebSocketContainer.WebSocketHandshakeHolder) WebSocketChannel(io.undertow.websockets.core.WebSocketChannel) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletRequestContext(io.undertow.servlet.handlers.ServletRequestContext) StreamConnection(org.xnio.StreamConnection) ServletWebSocketHttpExchange(io.undertow.servlet.websockets.ServletWebSocketHttpExchange) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServerExchange(io.undertow.server.HttpServerExchange) PathTemplateMatcher(io.undertow.util.PathTemplateMatcher) HttpSessionImpl(io.undertow.servlet.spec.HttpSessionImpl) ArrayList(java.util.ArrayList) List(java.util.List) HttpUpgradeListener(io.undertow.server.HttpUpgradeListener) Handshake(io.undertow.websockets.core.protocol.Handshake) Session(io.undertow.server.session.Session)

Aggregations

ServletRequestContext (io.undertow.servlet.handlers.ServletRequestContext)68 IOException (java.io.IOException)12 HttpSessionImpl (io.undertow.servlet.spec.HttpSessionImpl)11 HttpServerExchange (io.undertow.server.HttpServerExchange)10 Session (io.undertow.server.session.Session)10 HttpServletRequest (javax.servlet.http.HttpServletRequest)9 ServletException (javax.servlet.ServletException)8 ServletRequest (javax.servlet.ServletRequest)8 HttpServletRequestImpl (io.undertow.servlet.spec.HttpServletRequestImpl)6 Account (io.undertow.security.idm.Account)5 HttpServletResponseImpl (io.undertow.servlet.spec.HttpServletResponseImpl)5 HttpString (io.undertow.util.HttpString)5 HttpServletResponse (javax.servlet.http.HttpServletResponse)5 HttpSession (javax.servlet.http.HttpSession)5 SecurityContext (io.undertow.security.api.SecurityContext)4 SessionManager (io.undertow.server.session.SessionManager)4 ServletResponse (javax.servlet.ServletResponse)4 ArrayList (java.util.ArrayList)3 GenericMessageInfo (org.jboss.security.auth.message.GenericMessageInfo)3 Sender (io.undertow.io.Sender)2