Search in sources :

Example 21 with XFuture

use of org.webpieces.util.futures.XFuture in project webpieces by deanhiller.

the class CompressionChunkingHandle method process.

@Override
public XFuture<StreamWriter> process(Http2Response response) {
    if (lastResponseSent != null)
        throw new IllegalStateException("You already sent a response.  " + "do not call Actions.redirect or Actions.render more than once.  previous response=" + lastResponseSent + " 2nd response=" + response);
    lastResponseSent = response;
    Compression compression = checkForCompression(response);
    ChunkedStream chunkedStream = new ChunkedStream(webSettings.getMaxBodySizeToSend());
    Http2Response finalResp = response;
    if (Current.isContextSet()) {
        // in some exceptional cases like incoming cookies failing to parse, there will be no context
        List<OverwritePlatformResponse> callbacks = Current.getContext().getCallbacks();
        for (OverwritePlatformResponse callback : callbacks) {
            finalResp = (Http2Response) callback.modifyOrReplace(finalResp);
        }
    }
    boolean closeAfterResponding = false;
    if (closeAfterResponding(originalRequest))
        closeAfterResponding = true;
    boolean shouldClose = closeAfterResponding;
    return handler.process(response).thenApply(w -> possiblyClose(shouldClose, response, w)).thenApply(w -> new ProxyStreamWriter(shouldClose, compression, chunkedStream, w));
}
Also used : SneakyThrow(org.webpieces.util.exceptions.SneakyThrow) Http2Request(com.webpieces.http2.api.dto.highlevel.Http2Request) Inject(javax.inject.Inject) RouterRequest(org.webpieces.ctx.api.RouterRequest) StreamMsg(com.webpieces.http2.api.dto.lowlevel.lib.StreamMsg) Map(java.util.Map) DataWrapper(org.webpieces.data.api.DataWrapper) CompressionLookup(org.webpieces.router.impl.compression.CompressionLookup) OutputStream(java.io.OutputStream) WebSettings(org.webpieces.router.impl.routeinvoker.WebSettings) CancelReason(com.webpieces.http2.api.dto.lowlevel.CancelReason) IOException(java.io.IOException) List(java.util.List) DataFrame(com.webpieces.http2.api.dto.lowlevel.DataFrame) XFuture(org.webpieces.util.futures.XFuture) OverwritePlatformResponse(org.webpieces.ctx.api.OverwritePlatformResponse) MimeTypes(org.webpieces.router.impl.compression.MimeTypes) RouterResponseHandler(org.webpieces.router.api.RouterResponseHandler) Http2MsgType(com.webpieces.http2.api.dto.lowlevel.lib.Http2MsgType) Http2Header(com.webpieces.http2.api.dto.lowlevel.lib.Http2Header) StreamWriter(com.webpieces.http2.api.streaming.StreamWriter) Http2HeaderName(com.webpieces.http2.api.dto.lowlevel.lib.Http2HeaderName) PushStreamHandle(com.webpieces.http2.api.streaming.PushStreamHandle) Current(org.webpieces.ctx.api.Current) Http2Headers(com.webpieces.http2.api.dto.highlevel.Http2Headers) Http2Response(com.webpieces.http2.api.dto.highlevel.Http2Response) Compression(org.webpieces.router.impl.compression.Compression) Http2Response(com.webpieces.http2.api.dto.highlevel.Http2Response) Compression(org.webpieces.router.impl.compression.Compression) OverwritePlatformResponse(org.webpieces.ctx.api.OverwritePlatformResponse)

Example 22 with XFuture

use of org.webpieces.util.futures.XFuture in project webpieces by deanhiller.

the class IntegTestClientToEchoServer method write.

private void write(Channel channel, String reason) {
    // counter++;
    // if(counter % 100000 == 0)
    // log.info("counter="+counter);
    byte[] data = new byte[10240];
    ByteBuffer buffer = ByteBuffer.wrap(data);
    XFuture<Void> write = channel.write(buffer);
    write.thenAccept(p -> write(channel, "wrote data from client")).whenComplete((r, e) -> finished(r, e)).exceptionally(e -> {
        logIt(e);
        return null;
    });
}
Also used : Channel(org.webpieces.nio.api.channels.Channel) DataListener(org.webpieces.nio.api.handlers.DataListener) BufferPool(org.webpieces.data.api.BufferPool) SimpleMeterRegistry(io.micrometer.core.instrument.simple.SimpleMeterRegistry) Logger(org.slf4j.Logger) Executor(java.util.concurrent.Executor) IntegTestLocalhostThroughput(org.webpieces.nio.api.throughput.IntegTestLocalhostThroughput) NamedThreadFactory(org.webpieces.util.threading.NamedThreadFactory) ClientDataListener(org.webpieces.nio.api.throughput.ClientDataListener) LoggerFactory(org.slf4j.LoggerFactory) BackpressureConfig(org.webpieces.nio.api.BackpressureConfig) InetSocketAddress(java.net.InetSocketAddress) ByteBuffer(java.nio.ByteBuffer) Executors(java.util.concurrent.Executors) ChannelManager(org.webpieces.nio.api.ChannelManager) Metrics(io.micrometer.core.instrument.Metrics) BytesRecorder(org.webpieces.nio.api.throughput.BytesRecorder) ChannelManagerFactory(org.webpieces.nio.api.ChannelManagerFactory) XFuture(org.webpieces.util.futures.XFuture) TwoPools(org.webpieces.data.api.TwoPools) TCPChannel(org.webpieces.nio.api.channels.TCPChannel) ByteBuffer(java.nio.ByteBuffer)

Example 23 with XFuture

use of org.webpieces.util.futures.XFuture in project webpieces by deanhiller.

the class BasTCPServerChannel method accept.

/* (non-Javadoc)
	 * @see api.biz.xsoftware.nio.TCPServerChannel#accept()
	 */
public boolean accept(int newSocketNum) throws IOException {
    XFuture<Void> future;
    try {
        // special code...see information in close() method
        if (isClosed())
            return false;
        JdkSocketChannel newChan = channel.accept();
        if (newChan == null)
            return false;
        newChan.configureBlocking(false);
        SocketAddress remoteAddress = newChan.getRemoteAddress();
        String serverSocketId = id + "." + newSocketNum;
        BasTCPChannel tcpChan = new BasTCPChannel(serverSocketId, newChan, remoteAddress, selMgr, router, pool, config);
        if (log.isTraceEnabled())
            log.trace(tcpChan + "Accepted new incoming connection");
        XFuture<DataListener> connectFuture = connectionListener.connected(tcpChan, true);
        future = connectFuture.thenCompose(l -> tcpChan.registerForReads(l)).thenApply(c -> null);
    } catch (Throwable e) {
        future = new XFuture<Void>();
        future.completeExceptionally(e);
    }
    future.exceptionally(t -> {
        log.error(this + "Failed to connect", t);
        connectionListener.failed(this, t);
        return null;
    });
    return true;
}
Also used : DataListener(org.webpieces.nio.api.handlers.DataListener) BufferPool(org.webpieces.data.api.BufferPool) Logger(org.slf4j.Logger) SocketAddress(java.net.SocketAddress) ClosedChannelException(java.nio.channels.ClosedChannelException) SelectionKey(java.nio.channels.SelectionKey) NioException(org.webpieces.util.exceptions.NioException) SneakyThrow(org.webpieces.util.exceptions.SneakyThrow) LoggerFactory(org.slf4j.LoggerFactory) TCPServerChannel(org.webpieces.nio.api.channels.TCPServerChannel) IOException(java.io.IOException) BackpressureConfig(org.webpieces.nio.api.BackpressureConfig) BindException(java.net.BindException) ConnectionListener(org.webpieces.nio.api.handlers.ConnectionListener) ConsumerFunc(org.webpieces.nio.api.handlers.ConsumerFunc) InetSocketAddress(java.net.InetSocketAddress) ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketException(java.net.SocketException) JdkSelect(org.webpieces.nio.api.jdk.JdkSelect) XFuture(org.webpieces.util.futures.XFuture) NioClosedChannelException(org.webpieces.util.exceptions.NioClosedChannelException) JdkSocketChannel(org.webpieces.nio.api.jdk.JdkSocketChannel) XFuture(org.webpieces.util.futures.XFuture) DataListener(org.webpieces.nio.api.handlers.DataListener) JdkSocketChannel(org.webpieces.nio.api.jdk.JdkSocketChannel) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress)

Example 24 with XFuture

use of org.webpieces.util.futures.XFuture in project webpieces by deanhiller.

the class TestPermitQueue method testReducePermits.

@Test
public void testReducePermits() throws InterruptedException {
    PermitQueue queue = new PermitQueue(2);
    XFuture<Long> future1 = new XFuture<Long>();
    svc.addToReturn(future1);
    svc.addToReturn(future1);
    svc.addToReturn(future1);
    svc.addToReturn(future1);
    queue.runRequest(() -> svc.runFunction(1));
    queue.runRequest(() -> svc.runFunction(2));
    queue.runRequest(() -> svc.runFunction(3));
    queue.runRequest(() -> svc.runFunction(4));
    List<Integer> results = svc.getAndClear();
    Assert.assertEquals(2, results.size());
    Assert.assertEquals(1, results.get(0).intValue());
    Assert.assertEquals(2, results.get(1).intValue());
    queue.modifyPermitPoolSize(-1);
    // release two
    queue.releasePermit();
    queue.releasePermit();
    // only one will run
    List<Integer> results2 = svc.getAndClear();
    Assert.assertEquals(1, results2.size());
    Assert.assertEquals(3, results2.get(0).intValue());
    queue.releasePermit();
    List<Integer> results3 = svc.getAndClear();
    Assert.assertEquals(1, results3.size());
    Assert.assertEquals(4, results3.get(0).intValue());
}
Also used : FuturePermitQueue(org.webpieces.util.locking.FuturePermitQueue) PermitQueue(org.webpieces.util.locking.PermitQueue) XFuture(org.webpieces.util.futures.XFuture) Test(org.junit.Test)

Example 25 with XFuture

use of org.webpieces.util.futures.XFuture in project webpieces by deanhiller.

the class MockChannel method write.

@SuppressWarnings("unchecked")
@Override
public XFuture<Void> write(ByteBuffer b) {
    DataWrapper wrapper = dataGen.wrapByteBuffer(b);
    List<HttpPayload> parsedData = parser.parse(wrapper);
    if (parsedData.size() != 1)
        throw new IllegalArgumentException("The impl should be writing out full single payloads each write call");
    HttpPayload payload = parsedData.get(0);
    return (XFuture<Void>) super.calledMethod(Method.WRITE, payload);
}
Also used : DataWrapper(org.webpieces.data.api.DataWrapper) HttpPayload(org.webpieces.httpparser.api.dto.HttpPayload) XFuture(org.webpieces.util.futures.XFuture)

Aggregations

XFuture (org.webpieces.util.futures.XFuture)71 Test (org.junit.Test)21 StreamWriter (com.webpieces.http2.api.streaming.StreamWriter)20 ByteBuffer (java.nio.ByteBuffer)16 Logger (org.slf4j.Logger)15 LoggerFactory (org.slf4j.LoggerFactory)15 ArrayList (java.util.ArrayList)14 List (java.util.List)13 Map (java.util.Map)12 DataWrapper (org.webpieces.data.api.DataWrapper)12 HttpFullRequest (org.webpieces.httpclient11.api.HttpFullRequest)12 HttpFullResponse (org.webpieces.httpclient11.api.HttpFullResponse)12 NotFoundException (org.webpieces.http.exception.NotFoundException)11 AbstractWebpiecesTest (org.webpieces.webserver.test.AbstractWebpiecesTest)11 ResponseWrapper (org.webpieces.webserver.test.ResponseWrapper)11 Http2Request (com.webpieces.http2.api.dto.highlevel.Http2Request)10 PrivateWebserverForTest (org.webpieces.webserver.PrivateWebserverForTest)10 StreamRef (com.webpieces.http2.api.streaming.StreamRef)9 RequestContext (org.webpieces.ctx.api.RequestContext)9 Http2Response (com.webpieces.http2.api.dto.highlevel.Http2Response)8