Search in sources :

Example 21 with HttpField

use of org.eclipse.jetty.http.HttpField in project jetty.project by eclipse.

the class Request method getPushBuilder.

/* ------------------------------------------------------------ */
/** Get a PushBuilder associated with this request initialized as follows:<ul>
     * <li>The method is initialized to "GET"</li>
     * <li>The headers from this request are copied to the Builder, except for:<ul>
     *   <li>Conditional headers (eg. If-Modified-Since)
     *   <li>Range headers
     *   <li>Expect headers
     *   <li>Authorization headers
     *   <li>Referrer headers
     * </ul></li>
     * <li>If the request was Authenticated, an Authorization header will
     * be set with a container generated token that will result in equivalent
     * Authorization</li>
     * <li>The query string from {@link #getQueryString()}
     * <li>The {@link #getRequestedSessionId()} value, unless at the time
     * of the call {@link #getSession(boolean)}
     * has previously been called to create a new {@link HttpSession}, in
     * which case the new session ID will be used as the PushBuilders
     * requested session ID.</li>
     * <li>The source of the requested session id will be the same as for
     * this request</li>
     * <li>The builders Referer header will be set to {@link #getRequestURL()}
     * plus any {@link #getQueryString()} </li>
     * <li>If {@link HttpServletResponse#addCookie(Cookie)} has been called
     * on the associated response, then a corresponding Cookie header will be added
     * to the PushBuilder, unless the {@link Cookie#getMaxAge()} is &lt;=0, in which
     * case the Cookie will be removed from the builder.</li>
     * <li>If this request has has the conditional headers If-Modified-Since or
     * If-None-Match then the {@link PushBuilderImpl#isConditional()} header is set
     * to true.
     * </ul>
     *
     * <p>Each call to getPushBuilder() will return a new instance
     * of a PushBuilder based off this Request.  Any mutations to the
     * returned PushBuilder are not reflected on future returns.
     * @return A new PushBuilder or null if push is not supported
     */
public PushBuilder getPushBuilder() {
    if (!isPushSupported())
        throw new IllegalStateException(String.format("%s,push=%b,channel=%s", this, isPush(), getHttpChannel()));
    HttpFields fields = new HttpFields(getHttpFields().size() + 5);
    boolean conditional = false;
    for (HttpField field : getHttpFields()) {
        HttpHeader header = field.getHeader();
        if (header == null)
            fields.add(field);
        else {
            switch(header) {
                case IF_MATCH:
                case IF_RANGE:
                case IF_UNMODIFIED_SINCE:
                case RANGE:
                case EXPECT:
                case REFERER:
                case COOKIE:
                    continue;
                case AUTHORIZATION:
                    continue;
                case IF_NONE_MATCH:
                case IF_MODIFIED_SINCE:
                    conditional = true;
                    continue;
                default:
                    fields.add(field);
            }
        }
    }
    String id = null;
    try {
        HttpSession session = getSession();
        if (session != null) {
            // checks if session is valid
            session.getLastAccessedTime();
            id = session.getId();
        } else
            id = getRequestedSessionId();
    } catch (IllegalStateException e) {
        id = getRequestedSessionId();
    }
    PushBuilder builder = new PushBuilderImpl(this, fields, getMethod(), getQueryString(), id, conditional);
    builder.addHeader("referer", getRequestURL().toString());
    return builder;
}
Also used : HttpHeader(org.eclipse.jetty.http.HttpHeader) HostPortHttpField(org.eclipse.jetty.http.HostPortHttpField) HttpField(org.eclipse.jetty.http.HttpField) HttpSession(javax.servlet.http.HttpSession) HttpFields(org.eclipse.jetty.http.HttpFields)

Example 22 with HttpField

use of org.eclipse.jetty.http.HttpField in project jetty.project by eclipse.

the class ResourceService method passConditionalHeaders.

/* ------------------------------------------------------------ */
/* Check modification date headers.
     */
protected boolean passConditionalHeaders(HttpServletRequest request, HttpServletResponse response, HttpContent content) throws IOException {
    try {
        String ifm = null;
        String ifnm = null;
        String ifms = null;
        long ifums = -1;
        if (request instanceof Request) {
            // Find multiple fields by iteration as an optimization 
            HttpFields fields = ((Request) request).getHttpFields();
            for (int i = fields.size(); i-- > 0; ) {
                HttpField field = fields.getField(i);
                if (field.getHeader() != null) {
                    switch(field.getHeader()) {
                        case IF_MATCH:
                            ifm = field.getValue();
                            break;
                        case IF_NONE_MATCH:
                            ifnm = field.getValue();
                            break;
                        case IF_MODIFIED_SINCE:
                            ifms = field.getValue();
                            break;
                        case IF_UNMODIFIED_SINCE:
                            ifums = DateParser.parseDate(field.getValue());
                            break;
                        default:
                    }
                }
            }
        } else {
            ifm = request.getHeader(HttpHeader.IF_MATCH.asString());
            ifnm = request.getHeader(HttpHeader.IF_NONE_MATCH.asString());
            ifms = request.getHeader(HttpHeader.IF_MODIFIED_SINCE.asString());
            ifums = request.getDateHeader(HttpHeader.IF_UNMODIFIED_SINCE.asString());
        }
        if (!HttpMethod.HEAD.is(request.getMethod())) {
            if (_etags) {
                String etag = content.getETagValue();
                if (ifm != null) {
                    boolean match = false;
                    if (etag != null) {
                        QuotedCSV quoted = new QuotedCSV(true, ifm);
                        for (String tag : quoted) {
                            if (CompressedContentFormat.tagEquals(etag, tag)) {
                                match = true;
                                break;
                            }
                        }
                    }
                    if (!match) {
                        response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
                        return false;
                    }
                }
                if (ifnm != null && etag != null) {
                    // Handle special case of exact match OR gzip exact match
                    if (CompressedContentFormat.tagEquals(etag, ifnm) && ifnm.indexOf(',') < 0) {
                        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                        response.setHeader(HttpHeader.ETAG.asString(), ifnm);
                        return false;
                    }
                    // Handle list of tags
                    QuotedCSV quoted = new QuotedCSV(true, ifnm);
                    for (String tag : quoted) {
                        if (CompressedContentFormat.tagEquals(etag, tag)) {
                            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                            response.setHeader(HttpHeader.ETAG.asString(), tag);
                            return false;
                        }
                    }
                    // If etag requires content to be served, then do not check if-modified-since
                    return true;
                }
            }
            // Handle if modified since
            if (ifms != null) {
                //Get jetty's Response impl
                String mdlm = content.getLastModifiedValue();
                if (mdlm != null && ifms.equals(mdlm)) {
                    response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    if (_etags)
                        response.setHeader(HttpHeader.ETAG.asString(), content.getETagValue());
                    response.flushBuffer();
                    return false;
                }
                long ifmsl = request.getDateHeader(HttpHeader.IF_MODIFIED_SINCE.asString());
                if (ifmsl != -1 && content.getResource().lastModified() / 1000 <= ifmsl / 1000) {
                    response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    if (_etags)
                        response.setHeader(HttpHeader.ETAG.asString(), content.getETagValue());
                    response.flushBuffer();
                    return false;
                }
            }
            // Parse the if[un]modified dates and compare to resource
            if (ifums != -1 && content.getResource().lastModified() / 1000 > ifums / 1000) {
                response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                return false;
            }
        }
    } catch (IllegalArgumentException iae) {
        if (!response.isCommitted())
            response.sendError(400, iae.getMessage());
        throw iae;
    }
    return true;
}
Also used : HttpField(org.eclipse.jetty.http.HttpField) PreEncodedHttpField(org.eclipse.jetty.http.PreEncodedHttpField) HttpFields(org.eclipse.jetty.http.HttpFields) HttpServletRequest(javax.servlet.http.HttpServletRequest) QuotedCSV(org.eclipse.jetty.http.QuotedCSV)

Example 23 with HttpField

use of org.eclipse.jetty.http.HttpField in project jetty.project by eclipse.

the class ResponseNotifier method forwardSuccess.

public void forwardSuccess(List<Response.ResponseListener> listeners, Response response) {
    notifyBegin(listeners, response);
    for (Iterator<HttpField> iterator = response.getHeaders().iterator(); iterator.hasNext(); ) {
        HttpField field = iterator.next();
        if (!notifyHeader(listeners, response, field))
            iterator.remove();
    }
    notifyHeaders(listeners, response);
    if (response instanceof ContentResponse)
        notifyContent(listeners, response, ByteBuffer.wrap(((ContentResponse) response).getContent()), Callback.NOOP);
    notifySuccess(listeners, response);
}
Also used : ContentResponse(org.eclipse.jetty.client.api.ContentResponse) HttpField(org.eclipse.jetty.http.HttpField)

Example 24 with HttpField

use of org.eclipse.jetty.http.HttpField in project jetty.project by eclipse.

the class WebSocketUpgradeRequest method upgrade.

@Override
public void upgrade(HttpResponse response, HttpConnectionOverHTTP oldConn) {
    if (!this.getHeaders().get(HttpHeader.UPGRADE).equalsIgnoreCase("websocket")) {
        // Not my upgrade
        throw new HttpResponseException("Not WebSocket Upgrade", response);
    }
    // Check the Accept hash
    String reqKey = this.getHeaders().get(HttpHeader.SEC_WEBSOCKET_KEY);
    String expectedHash = AcceptHash.hashKey(reqKey);
    String respHash = response.getHeaders().get(HttpHeader.SEC_WEBSOCKET_ACCEPT);
    if (expectedHash.equalsIgnoreCase(respHash) == false) {
        throw new HttpResponseException("Invalid Sec-WebSocket-Accept hash", response);
    }
    // We can upgrade
    EndPoint endp = oldConn.getEndPoint();
    WebSocketClientConnection connection = new WebSocketClientConnection(endp, wsClient.getExecutor(), wsClient.getScheduler(), localEndpoint.getPolicy(), wsClient.getBufferPool());
    URI requestURI = this.getURI();
    WebSocketSession session = getSessionFactory().createSession(requestURI, localEndpoint, connection);
    session.setUpgradeRequest(new ClientUpgradeRequest(this));
    session.setUpgradeResponse(new ClientUpgradeResponse(response));
    connection.addListener(session);
    ExtensionStack extensionStack = new ExtensionStack(getExtensionFactory());
    List<ExtensionConfig> extensions = new ArrayList<>();
    HttpField extField = response.getHeaders().getField(HttpHeader.SEC_WEBSOCKET_EXTENSIONS);
    if (extField != null) {
        String[] extValues = extField.getValues();
        if (extValues != null) {
            for (String extVal : extValues) {
                QuotedStringTokenizer tok = new QuotedStringTokenizer(extVal, ",");
                while (tok.hasMoreTokens()) {
                    extensions.add(ExtensionConfig.parse(tok.nextToken()));
                }
            }
        }
    }
    extensionStack.negotiate(extensions);
    extensionStack.configure(connection.getParser());
    extensionStack.configure(connection.getGenerator());
    // Setup Incoming Routing
    connection.setNextIncomingFrames(extensionStack);
    extensionStack.setNextIncoming(session);
    // Setup Outgoing Routing
    session.setOutgoingHandler(extensionStack);
    extensionStack.setNextOutgoing(connection);
    session.addManaged(extensionStack);
    session.setFuture(fut);
    wsClient.addManaged(session);
    if (upgradeListener != null) {
        upgradeListener.onHandshakeResponse(new ClientUpgradeResponse(response));
    }
    // Now swap out the connection
    endp.upgrade(connection);
}
Also used : ArrayList(java.util.ArrayList) WebSocketClientConnection(org.eclipse.jetty.websocket.client.io.WebSocketClientConnection) HttpResponseException(org.eclipse.jetty.client.HttpResponseException) EndPoint(org.eclipse.jetty.io.EndPoint) URI(java.net.URI) ExtensionStack(org.eclipse.jetty.websocket.common.extensions.ExtensionStack) WebSocketSession(org.eclipse.jetty.websocket.common.WebSocketSession) QuotedStringTokenizer(org.eclipse.jetty.util.QuotedStringTokenizer) ExtensionConfig(org.eclipse.jetty.websocket.api.extensions.ExtensionConfig) HttpField(org.eclipse.jetty.http.HttpField)

Example 25 with HttpField

use of org.eclipse.jetty.http.HttpField in project jetty.project by eclipse.

the class HttpResponseAbortTest method testAbortOnHeader.

@Test
public void testAbortOnHeader() throws Exception {
    start(new EmptyServerHandler());
    final CountDownLatch latch = new CountDownLatch(1);
    client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).onResponseHeader(new Response.HeaderListener() {

        @Override
        public boolean onHeader(Response response, HttpField field) {
            response.abort(new Exception());
            return true;
        }
    }).send(new Response.CompleteListener() {

        @Override
        public void onComplete(Result result) {
            Assert.assertTrue(result.isFailed());
            latch.countDown();
        }
    });
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(org.eclipse.jetty.client.api.Response) HttpField(org.eclipse.jetty.http.HttpField) CountDownLatch(java.util.concurrent.CountDownLatch) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) Result(org.eclipse.jetty.client.api.Result) Test(org.junit.Test)

Aggregations

HttpField (org.eclipse.jetty.http.HttpField)57 Test (org.junit.Test)29 HttpFields (org.eclipse.jetty.http.HttpFields)19 ByteBuffer (java.nio.ByteBuffer)17 MetaData (org.eclipse.jetty.http.MetaData)16 HostPortHttpField (org.eclipse.jetty.http.HostPortHttpField)12 ArrayList (java.util.ArrayList)8 PreEncodedHttpField (org.eclipse.jetty.http.PreEncodedHttpField)7 Entry (org.eclipse.jetty.http2.hpack.HpackContext.Entry)7 ByteBufferPool (org.eclipse.jetty.io.ByteBufferPool)7 MappedByteBufferPool (org.eclipse.jetty.io.MappedByteBufferPool)7 HttpHeader (org.eclipse.jetty.http.HttpHeader)6 HttpServletResponse (javax.servlet.http.HttpServletResponse)5 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)5 HeaderGenerator (org.eclipse.jetty.http2.generator.HeaderGenerator)5 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 HpackEncoder (org.eclipse.jetty.http2.hpack.HpackEncoder)4 Parser (org.eclipse.jetty.http2.parser.Parser)4 CountDownLatch (java.util.concurrent.CountDownLatch)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)3