Package org.glassfish.grizzly.http

Examples of org.glassfish.grizzly.http.HttpContent



    @Override
    public NextAction handleRead(final FilterChainContext ctx) throws IOException {
        final Connection connection = ctx.getConnection();
        final HttpContent httpContent = ctx.getMessage();

        final HttpRequestPacket request = (HttpRequestPacket) httpContent.getHttpHeader();
        final URI requestURI;
        try {
            final String uri = request.getQueryString() == null ?
                    request.getRequestURI() :
                    request.getRequestURI() + "?" + request.getQueryString();
View Full Code Here


     */
    @Override
    @SuppressWarnings("unchecked")
    public NextAction handleRead(FilterChainContext ctx) throws IOException {
        // Get the parsed HttpContent (we assume prev. filter was HTTP)
        final HttpContent message = ctx.getMessage();

        final Connection grizzlyConnection = ctx.getConnection();
        final org.glassfish.tyrus.spi.Connection tyrusConnection = TYRUS_CONNECTION.get(grizzlyConnection);

        // Get the HTTP header
        final HttpHeader header = message.getHttpHeader();

        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, "handleRead websocket: {0} content-size={1} headers=\n{2}",
                    new Object[]{tyrusConnection, message.getContent().remaining(), header});
        }

        // client
        if (tyrusConnection != null) {
            // this is websocket with completed handshake
            if (message.getContent().hasRemaining()) {

                // get the frame(s) content
                Buffer buffer = message.getContent();
                final ByteBuffer webSocketBuffer = buffer.toByteBuffer();
                message.recycle();
                final ReadHandler readHandler = tyrusConnection.getReadHandler();

                TaskProcessor taskProcessor = TASK_PROCESSOR.get(ctx.getConnection());
                taskProcessor.processTask(new ProcessTask(webSocketBuffer, readHandler));
            }
            return ctx.getStopAction();
        }

        // tyrusConnection == null

        // proxy
        final HttpStatus httpStatus = ((HttpResponsePacket) message.getHttpHeader()).getHttpStatus();

        if (httpStatus.getStatusCode() != 101) {
            if (proxy && !PROXY_CONNECTED.get(grizzlyConnection)) {
                if (httpStatus == HttpStatus.OK_200) {

                    PROXY_CONNECTED.set(grizzlyConnection, true);

                    // TYRUS-221: Proxy handshake is complete, we need to enable SSL layer for secure ("wss")
                    // connections now.
                    if (sslFilter != null) {
                        ((GrizzlyClientSocket.FilterWrapper) sslFilter).enable();
                    }

                    httpCodecFilter.resetResponseProcessing(grizzlyConnection);

                    final UpgradeRequest upgradeRequest = UPGRADE_REQUEST.get(grizzlyConnection);
                    ctx.write(getHttpContent(upgradeRequest));
                    UPGRADE_REQUEST.remove(grizzlyConnection);
                } else {
                    throw new IOException(String.format("Proxy error. %s: %s", httpStatus.getStatusCode(),
                            new String(httpStatus.getReasonPhraseBytes(), "UTF-8")));
                }

                return ctx.getInvokeAction();
            }
        }

        // If websocket is null - it means either non-websocket Connection
        if (!UpgradeRequest.WEBSOCKET.equalsIgnoreCase(header.getUpgrade()) && message.getHttpHeader().isRequest()) {
            // if it's not a websocket connection - pass the processing to the next filter
            return ctx.getInvokeAction();
        }

        // Handle handshake
View Full Code Here

     */
    @Override
    @SuppressWarnings("unchecked")
    public NextAction handleRead(FilterChainContext ctx) throws IOException {
        // Get the parsed HttpContent (we assume prev. filter was HTTP)
        final HttpContent message = ctx.getMessage();

        final org.glassfish.tyrus.spi.Connection tyrusConnection = getConnection(ctx);

        if (logger.isLoggable(Level.FINE)) {
            logger.log(Level.FINE, "handleRead websocket: {0} content-size={1} headers=\n{2}",
                    new Object[]{tyrusConnection, message.getContent().remaining(), message.getHttpHeader()});
        }

        if (tyrusConnection == null) {
            // Get the HTTP header
            final HttpHeader header = message.getHttpHeader();

            // If websocket is null - it means either non-websocket Connection
            if (!UpgradeRequest.WEBSOCKET.equalsIgnoreCase(header.getUpgrade()) && message.getHttpHeader().isRequest()) {
                // if it's not a websocket connection - pass the processing to the next filter
                return ctx.getInvokeAction();
            }

            final String ATTR_NAME = "org.glassfish.tyrus.container.grizzly.WebSocketFilter.HANDSHAKE_PROCESSED";

            final AttributeHolder attributeHolder = ctx.getAttributes();
            if (attributeHolder != null) {
                final Object attribute = attributeHolder.getAttribute(ATTR_NAME);
                if (attribute != null) {
                    // handshake was already performed on this context.
                    return ctx.getInvokeAction();
                } else {
                    attributeHolder.setAttribute(ATTR_NAME, true);
                }
            }
            // Handle handshake
            return handleHandshake(ctx, message);
        }

        // tyrusConnection is not null
        // this is websocket with the completed handshake
        if (message.getContent().hasRemaining()) {
            // get the frame(s) content

            Buffer buffer = message.getContent();
            message.recycle();
            final ReadHandler readHandler = tyrusConnection.getReadHandler();
            TaskProcessor taskProcessor = getTaskProcessor(ctx);
            if (!buffer.isComposite()) {
                taskProcessor.processTask(new ProcessTask(buffer.toByteBuffer(), readHandler));
            } else {
View Full Code Here


    @Override
    public NextAction handleRead(final FilterChainContext ctx) throws IOException {

        final HttpContent requestContent = ctx.getMessage();
        final HttpRequestPacket request = (HttpRequestPacket) requestContent.getHttpHeader();

        if (fileCache.isEnabled() && Method.GET.equals(request.getMethod())) {
            final FileCacheEntry cacheEntry = fileCache.get(request);
            if (cacheEntry != null) {
                final HttpResponsePacket response = request.getResponse();
View Full Code Here

       
        this.ctx = ctx;
        connection = ctx.getConnection();
        final Object message = ctx.getMessage();
        if (message instanceof HttpContent) {
            final HttpContent content = (HttpContent) message;
           
            // Check if HttpContent is chunked message trailer w/ headers
            checkHttpTrailer(content);
            updateInputContentBuffer(content.getContent());
            contentRead = content.isLast();
            content.recycle();
           
            if (LOGGER.isLoggable(LOGGER_LEVEL)) {
                log("InputBuffer %s initialize with ready content: %s",
                        this, inputContentBuffer);
            }
View Full Code Here

     * @return {@link HttpContent}
     * @throws IOException
     */
    protected HttpContent blockingRead() throws IOException {
        final ReadResult rr = ctx.read();
        final HttpContent c = (HttpContent) rr.getMessage();
        rr.recycle();
        return c;
    }
View Full Code Here

        int read = 0;
        while ((requestedLen == -1 || read < requestedLen) &&
                httpHeader.isExpectContent()) {
           
            final HttpContent c = blockingRead();
           
            final boolean isLast = c.isLast();
            // Check if HttpContent is chunked message trailer w/ headers
            checkHttpTrailer(c);
           
            final Buffer b;
            try {
                b = c.getContent();
            } catch (HttpBrokenContentException e) {
                final Throwable cause = e.getCause();
                throw Exceptions.makeIOException(cause != null ? cause : e);
            }
           
            read += b.remaining();
            updateInputContentBuffer(b);
            c.recycle();
           
            if (isLast) {
                finished();
                break;
            }
View Full Code Here

        boolean last = false;

        while (read < requestedLen && httpHeader.isExpectContent()) {

            if (isNeedMoreInput || !inputContentBuffer.hasRemaining()) {
                final HttpContent c = blockingRead();
                updateInputContentBuffer(c.getContent());
                last = c.isLast();

                c.recycle();
                isNeedMoreInput = false;
            }

            final ByteBuffer bytes = inputContentBuffer.toByteBuffer();
View Full Code Here

     * This is service method, usually users don't have to call it explicitly.
     */
    @Override
    public void initiateAsyncronousDataReceiving() {
        if (!checkChunkedMaxPostSize()) {
            final HttpContent brokenContent =
                    HttpBrokenContent.builder(serverRequest.getRequest())
                    .error(new IOException("The HTTP request content exceeds max post size"))
                    .build();
            try {
                append(brokenContent);
View Full Code Here

        final Connection connection = ctx.getConnection();

        if (HttpPacket.isHttp(message)) {

            // Otherwise cast message to a HttpContent
            final HttpContent httpContent = (HttpContent) message;
            final HttpContext context = httpContent.getHttpHeader()
                    .getProcessingState().getHttpContext();
            Request handlerRequest = httpRequestInProgress.get(context);

            if (handlerRequest == null) {
                // It's a new HTTP request
                final HttpRequestPacket request = (HttpRequestPacket) httpContent.getHttpHeader();
                final HttpResponsePacket response = request.getResponse();
               
                handlerRequest = Request.create();
                handlerRequest.parameters.setLimit(config.getMaxRequestParameters());
                httpRequestInProgress.set(context, handlerRequest);
                final Response handlerResponse = handlerRequest.getResponse();

                handlerRequest.initialize(request, ctx, this);
                handlerResponse.initialize(handlerRequest, response,
                        ctx, suspendedResponseQueue, this);

                if (config.isGracefulShutdownSupported()) {
                    activeRequestsCounter.incrementAndGet();
                    handlerRequest.addAfterServiceListener(flushResponseHandler);
                }
               
                HttpServerProbeNotifier.notifyRequestReceive(this, connection,
                        handlerRequest);

                boolean wasSuspended = false;
               
                try {
                    ctx.setMessage(handlerResponse);

                    if (isShuttingDown) { // if we're in the shutting down phase - serve shutdown page and exit
                        handlerResponse.getResponse().getProcessingState().setError(true);
                        HtmlHelper.setErrorAndSendErrorPage(
                                handlerRequest, handlerResponse,
                                config.getDefaultErrorPageGenerator(),
                                503, HttpStatus.SERVICE_UNAVAILABLE_503.getReasonPhrase(),
                                "The server is being shutting down...", null);
                    } else if (!config.isPassTraceRequest()
                            && request.getMethod() == Method.TRACE) {
                        onTraceRequest(handlerRequest, handlerResponse);
                    } else if (!checkMaxPostSize(request.getContentLength())) {
                        handlerResponse.getResponse().getProcessingState().setError(true);
                        HtmlHelper.setErrorAndSendErrorPage(
                                handlerRequest, handlerResponse,
                                config.getDefaultErrorPageGenerator(),
                                400, HttpStatus.BAD_REQUEST_400.getReasonPhrase(),
                                "The request payload size exceeds the max post size limitation", null);
                    } else {
                        final HttpHandler httpHandlerLocal = httpHandler;
                        if (httpHandlerLocal != null) {
                            wasSuspended = !httpHandlerLocal.doHandle(
                                    handlerRequest, handlerResponse);
                        }
                    }
                } catch (Exception t) {
                    LOGGER.log(Level.WARNING,
                            LogMessages.WARNING_GRIZZLY_HTTP_SERVER_FILTER_HTTPHANDLER_INVOCATION_ERROR(), t);
                   
                    request.getProcessingState().setError(true);
                   
                    if (!response.isCommitted()) {
                            HtmlHelper.setErrorAndSendErrorPage(
                                    handlerRequest, handlerResponse,
                                    config.getDefaultErrorPageGenerator(),
                                    500, HttpStatus.INTERNAL_SERVER_ERROR_500.getReasonPhrase(),
                                    HttpStatus.INTERNAL_SERVER_ERROR_500.getReasonPhrase(),
                                    t);
                    }
                } catch (Throwable t) {
                    LOGGER.log(Level.WARNING,
                            LogMessages.WARNING_GRIZZLY_HTTP_SERVER_FILTER_UNEXPECTED(), t);
                    throw new IllegalStateException(t);
                }
               
                if (!wasSuspended) {
                    return afterService(ctx, connection,
                            handlerRequest, handlerResponse);
                } else {
                    return ctx.getSuspendAction();
                }
            } else {
                // We're working with suspended HTTP request
                try {
                    ctx.suspend();
                    final NextAction action = ctx.getSuspendAction();
                   
                    if (!handlerRequest.getInputBuffer().append(httpContent)) {
                        // we don't want this thread/context to reset
                        // OP_READ on Connection

                        // we have enough data? - terminate filter chain execution
                        ctx.completeAndRecycle();
                    } else {
                        ctx.resume(ctx.getStopAction());
                    }
                   
                    return action;
                } finally {
                    httpContent.recycle();
                }
            }
        } else { // this code will be run, when we resume the context
            // We're finishing the request processing
            final Response response = (Response) message;
View Full Code Here

TOP

Related Classes of org.glassfish.grizzly.http.HttpContent

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.