Search in sources :

Example 1 with ResponseEncodingTuple

use of org.webpieces.webserver.impl.ResponseCreator.ResponseEncodingTuple 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 2 with ResponseEncodingTuple

use of org.webpieces.webserver.impl.ResponseCreator.ResponseEncodingTuple in project webpieces by deanhiller.

the class ProxyResponse method createResponseAndSend.

private CompletableFuture<Void> createResponseAndSend(StatusCode statusCode, String content, String extension, String defaultMime) {
    if (content == null)
        throw new IllegalArgumentException("content cannot be null");
    ResponseEncodingTuple tuple = responseCreator.createResponse(request, statusCode, extension, defaultMime, true);
    log.debug(() -> "content about to be sent back=" + content);
    Charset encoding = tuple.mimeType.htmlResponsePayloadEncoding;
    byte[] bytes = content.getBytes(encoding);
    return maybeCompressAndSend(extension, tuple, bytes);
}
Also used : ResponseEncodingTuple(org.webpieces.webserver.impl.ResponseCreator.ResponseEncodingTuple) Charset(java.nio.charset.Charset)

Aggregations

ResponseEncodingTuple (org.webpieces.webserver.impl.ResponseCreator.ResponseEncodingTuple)2 Http2Response (com.webpieces.hpack.api.dto.Http2Response)1 StreamWriter (com.webpieces.http2engine.api.StreamWriter)1 DataFrame (com.webpieces.http2parser.api.dto.DataFrame)1 StatusCode (com.webpieces.http2parser.api.dto.StatusCode)1 Http2Header (com.webpieces.http2parser.api.dto.lib.Http2Header)1 Http2HeaderName (com.webpieces.http2parser.api.dto.lib.Http2HeaderName)1 File (java.io.File)1 IOException (java.io.IOException)1 ByteBuffer (java.nio.ByteBuffer)1 AsynchronousFileChannel (java.nio.channels.AsynchronousFileChannel)1 CompletionHandler (java.nio.channels.CompletionHandler)1 Charset (java.nio.charset.Charset)1 OpenOption (java.nio.file.OpenOption)1 Path (java.nio.file.Path)1 Paths (java.nio.file.Paths)1 StandardOpenOption (java.nio.file.StandardOpenOption)1 HashSet (java.util.HashSet)1 Set (java.util.Set)1 CompletableFuture (java.util.concurrent.CompletableFuture)1