Search in sources :

Example 6 with Http2Header

use of com.webpieces.http2parser.api.dto.lib.Http2Header in project webpieces by deanhiller.

the class ResponseCreator method addCommonHeaders.

public void addCommonHeaders(Http2Request request, Http2Response response, boolean isInternalError, boolean isDynamicPartOfWebsite) {
    String connHeader = request.getSingleHeaderValue(Http2HeaderName.CONNECTION);
    DateTime now = DateTime.now().toDateTime(DateTimeZone.UTC);
    String dateStr = formatter.print(now) + " GMT";
    //in general, nearly all these headers are desired..
    Http2Header date = new Http2Header(Http2HeaderName.DATE, dateStr);
    response.addHeader(date);
    if (isDynamicPartOfWebsite) {
        List<RouterCookie> cookies = createCookies(isInternalError);
        for (RouterCookie c : cookies) {
            Http2Header cookieHeader = create(c);
            response.addHeader(cookieHeader);
        }
    }
    if (connHeader == null)
        return;
    else if (!"keep-alive".equals(connHeader))
        return;
    //just re-use the connHeader from the request...
    response.addHeader(request.getHeaderLookupStruct().getHeader(Http2HeaderName.CONNECTION));
}
Also used : Http2Header(com.webpieces.http2parser.api.dto.lib.Http2Header) RouterCookie(org.webpieces.ctx.api.RouterCookie) DateTime(org.joda.time.DateTime)

Example 7 with Http2Header

use of com.webpieces.http2parser.api.dto.lib.Http2Header in project webpieces by deanhiller.

the class ResponseCreator method createContentResponseImpl.

private ResponseEncodingTuple createContentResponseImpl(Http2Request request, int statusCode, String reason, boolean isDynamicPartOfWebsite, MimeTypeResult mimeType) {
    Http2Response response = new Http2Response();
    response.setEndOfStream(false);
    response.addHeader(new Http2Header(Http2HeaderName.STATUS, statusCode + ""));
    response.addHeader(new Http2Header("reason", reason));
    response.addHeader(new Http2Header(Http2HeaderName.CONTENT_TYPE, mimeType.mime));
    boolean isInternalError = false;
    if (statusCode == 500)
        isInternalError = true;
    addCommonHeaders(request, response, isInternalError, isDynamicPartOfWebsite);
    return new ResponseEncodingTuple(response, mimeType);
}
Also used : Http2Response(com.webpieces.hpack.api.dto.Http2Response) Http2Header(com.webpieces.http2parser.api.dto.lib.Http2Header)

Example 8 with Http2Header

use of com.webpieces.http2parser.api.dto.lib.Http2Header in project webpieces by deanhiller.

the class StaticFileReader method runAsyncFileRead.

private CompletableFuture<Void> runAsyncFileRead(RequestInfo info, RenderStaticResponse renderStatic) throws IOException {
    boolean isFile = true;
    String fullFilePath = renderStatic.getFilePath();
    if (fullFilePath == null) {
        isFile = false;
        fullFilePath = renderStatic.getDirectory() + renderStatic.getRelativePath();
    }
    String extension = null;
    int lastDirIndex = fullFilePath.lastIndexOf("/");
    int lastDot = fullFilePath.lastIndexOf(".");
    if (lastDot > lastDirIndex) {
        extension = fullFilePath.substring(lastDot + 1);
    }
    ResponseEncodingTuple tuple = responseCreator.createResponse(info.getRequest(), StatusCode.HTTP_200_OK, extension, "application/octet-stream", false);
    Http2Response response = tuple.response;
    //On startup, we protect developers from breaking clients.  In http, all files that change
    //must also change the hash automatically and the %%{ }%% tag generates those hashes so the
    //files loaded are always the latest
    Long timeMs = config.getStaticFileCacheTimeSeconds();
    if (timeMs != null)
        response.addHeader(new Http2Header(Http2HeaderName.CACHE_CONTROL, "max-age=" + timeMs));
    Path file;
    Compression compr = compressionLookup.createCompressionStream(info.getRouterRequest().encodings, extension, tuple.mimeType);
    //during startup as I don't feel like paying a cpu penalty for compressing while live
    if (compr != null && compr.getCompressionType().equals(routerConfig.getStartupCompression())) {
        response.addHeader(new Http2Header(Http2HeaderName.CONTENT_ENCODING, compr.getCompressionType()));
        File routesCache = renderStatic.getTargetCache();
        File fileReference;
        if (isFile) {
            String fileName = fullFilePath.substring(lastDirIndex + 1);
            fileReference = new File(routesCache, fileName);
        } else {
            fileReference = new File(routesCache, renderStatic.getRelativePath());
        }
        fullFilePath = fileReference.getAbsolutePath();
        file = fetchFile("Compressed File from cache=", fullFilePath + ".gz");
    } else {
        file = fetchFile("File=", fullFilePath);
    }
    AsynchronousFileChannel asyncFile = AsynchronousFileChannel.open(file, options, fileExecutor);
    CompletableFuture<StreamWriter> future;
    try {
        log.info(() -> "sending chunked file via async read=" + file);
        long length = file.toFile().length();
        AtomicLong remaining = new AtomicLong(length);
        future = info.getResponseSender().sendResponse(response).thenCompose(s -> readLoop(s, info.getPool(), file, asyncFile, 0, remaining));
    } catch (Throwable e) {
        future = new CompletableFuture<StreamWriter>();
        future.completeExceptionally(e);
    }
    return //our finally block for failures
    future.handle((s, exc) -> handleClose(info, s, exc)).thenAccept(s -> empty());
}
Also used : Path(java.nio.file.Path) BufferPool(org.webpieces.data.api.BufferPool) RouterConfig(org.webpieces.router.api.RouterConfig) AsynchronousFileChannel(java.nio.channels.AsynchronousFileChannel) CompletableFuture(java.util.concurrent.CompletableFuture) ResponseEncodingTuple(org.webpieces.webserver.impl.ResponseCreator.ResponseEncodingTuple) Singleton(javax.inject.Singleton) ByteBuffer(java.nio.ByteBuffer) HashSet(java.util.HashSet) Inject(javax.inject.Inject) DataWrapper(org.webpieces.data.api.DataWrapper) Named(javax.inject.Named) CompressionLookup(org.webpieces.router.impl.compression.CompressionLookup) Path(java.nio.file.Path) DataWrapperGeneratorFactory(org.webpieces.data.api.DataWrapperGeneratorFactory) ExecutorService(java.util.concurrent.ExecutorService) Logger(org.webpieces.util.logging.Logger) RenderStaticResponse(org.webpieces.router.api.dto.RenderStaticResponse) StatusCode(com.webpieces.http2parser.api.dto.StatusCode) OpenOption(java.nio.file.OpenOption) CompletionHandler(java.nio.channels.CompletionHandler) StandardOpenOption(java.nio.file.StandardOpenOption) Set(java.util.Set) HttpFrontendFactory(org.webpieces.frontend2.api.HttpFrontendFactory) Http2Header(com.webpieces.http2parser.api.dto.lib.Http2Header) IOException(java.io.IOException) File(java.io.File) Http2HeaderName(com.webpieces.http2parser.api.dto.lib.Http2HeaderName) AtomicLong(java.util.concurrent.atomic.AtomicLong) BufferCreationPool(org.webpieces.data.api.BufferCreationPool) WebServerConfig(org.webpieces.webserver.api.WebServerConfig) StreamWriter(com.webpieces.http2engine.api.StreamWriter) Paths(java.nio.file.Paths) NotFoundException(org.webpieces.router.api.exceptions.NotFoundException) DataWrapperGenerator(org.webpieces.data.api.DataWrapperGenerator) LoggerFactory(org.webpieces.util.logging.LoggerFactory) Http2Response(com.webpieces.hpack.api.dto.Http2Response) DataFrame(com.webpieces.http2parser.api.dto.DataFrame) Compression(org.webpieces.router.impl.compression.Compression) Http2Response(com.webpieces.hpack.api.dto.Http2Response) Compression(org.webpieces.router.impl.compression.Compression) Http2Header(com.webpieces.http2parser.api.dto.lib.Http2Header) StreamWriter(com.webpieces.http2engine.api.StreamWriter) AsynchronousFileChannel(java.nio.channels.AsynchronousFileChannel) AtomicLong(java.util.concurrent.atomic.AtomicLong) CompletableFuture(java.util.concurrent.CompletableFuture) ResponseEncodingTuple(org.webpieces.webserver.impl.ResponseCreator.ResponseEncodingTuple) AtomicLong(java.util.concurrent.atomic.AtomicLong) File(java.io.File)

Example 9 with Http2Header

use of com.webpieces.http2parser.api.dto.lib.Http2Header in project webpieces by deanhiller.

the class Http2Translations method translateResponse.

public static HttpResponse translateResponse(Http2Response headers) {
    HttpResponseStatus status = new HttpResponseStatus();
    HttpResponseStatusLine statusLine = new HttpResponseStatusLine();
    statusLine.setStatus(status);
    HttpResponse response = new HttpResponse();
    response.setStatusLine(statusLine);
    for (Http2Header header : headers.getHeaders()) {
        if (header.getKnownName() == Http2HeaderName.STATUS) {
            fillStatus(header, status);
        } else if ("reason".equals(header.getName())) {
            fillReason(header, status);
        } else if (header.getKnownName() == Http2HeaderName.SCHEME) {
        //do nothing and drop it
        } else {
            Header http1Header = convertHeader(header);
            response.addHeader(http1Header);
        }
    }
    if (headers.isEndOfStream() && headers.getHeaderLookupStruct().getHeader(Http2HeaderName.CONTENT_LENGTH) == null) {
        //firefox really needs content length
        response.addHeader(new Header(KnownHeaderName.CONTENT_LENGTH, "0"));
    }
    if (status.getCode() == null)
        throw new IllegalArgumentException("The header :status is required to send the response");
    return response;
}
Also used : Header(org.webpieces.httpparser.api.common.Header) Http2Header(com.webpieces.http2parser.api.dto.lib.Http2Header) HttpResponseStatus(org.webpieces.httpparser.api.dto.HttpResponseStatus) Http2Header(com.webpieces.http2parser.api.dto.lib.Http2Header) HttpResponse(org.webpieces.httpparser.api.dto.HttpResponse) HttpResponseStatusLine(org.webpieces.httpparser.api.dto.HttpResponseStatusLine)

Example 10 with Http2Header

use of com.webpieces.http2parser.api.dto.lib.Http2Header in project webpieces by deanhiller.

the class Http2Requests method createRequest.

public static Http2Request createRequest(int streamId, boolean eos) {
    List<Http2Header> headers = new ArrayList<>();
    headers.add(new Http2Header(Http2HeaderName.METHOD, "GET"));
    headers.add(new Http2Header(Http2HeaderName.AUTHORITY, "somehost.com"));
    headers.add(new Http2Header(Http2HeaderName.PATH, "/"));
    headers.add(new Http2Header(Http2HeaderName.SCHEME, "http"));
    headers.add(new Http2Header(Http2HeaderName.HOST, "somehost.com"));
    headers.add(new Http2Header(Http2HeaderName.ACCEPT, "*/*"));
    headers.add(new Http2Header(Http2HeaderName.ACCEPT_ENCODING, "gzip, deflate"));
    headers.add(new Http2Header(Http2HeaderName.USER_AGENT, "webpieces/1.15.0"));
    Http2Request request = new Http2Request(headers);
    request.setStreamId(streamId);
    request.setEndOfStream(eos);
    return request;
}
Also used : Http2Request(com.webpieces.hpack.api.dto.Http2Request) Http2Header(com.webpieces.http2parser.api.dto.lib.Http2Header) ArrayList(java.util.ArrayList)

Aggregations

Http2Header (com.webpieces.http2parser.api.dto.lib.Http2Header)36 ArrayList (java.util.ArrayList)16 Http2Response (com.webpieces.hpack.api.dto.Http2Response)13 Http2Request (com.webpieces.hpack.api.dto.Http2Request)6 Http2HeaderName (com.webpieces.http2parser.api.dto.lib.Http2HeaderName)6 Http2Push (com.webpieces.hpack.api.dto.Http2Push)5 StreamWriter (com.webpieces.http2engine.api.StreamWriter)4 Http2Frame (com.webpieces.http2parser.api.dto.lib.Http2Frame)4 CompletableFuture (java.util.concurrent.CompletableFuture)4 Header (org.webpieces.httpparser.api.common.Header)4 Logger (org.webpieces.util.logging.Logger)4 LoggerFactory (org.webpieces.util.logging.LoggerFactory)4 List (java.util.List)3 BufferPool (org.webpieces.data.api.BufferPool)3 Encoder (com.twitter.hpack.Encoder)2 Http2Headers (com.webpieces.hpack.api.dto.Http2Headers)2 Http2Trailers (com.webpieces.hpack.api.dto.Http2Trailers)2 HeaderEncoding (com.webpieces.hpack.impl.HeaderEncoding)2 PushPromiseListener (com.webpieces.http2engine.api.PushPromiseListener)2 PushStreamHandle (com.webpieces.http2engine.api.PushStreamHandle)2