Search in sources :

Example 26 with XFuture

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

the class MockHttp1Channel method write.

@SuppressWarnings("unchecked")
@Override
public XFuture<Void> write(ByteBuffer b) {
    DataWrapper data = dataGen.wrapByteBuffer(b);
    parser.parse(memento, data);
    List<HttpPayload> payloads = memento.getParsedMessages();
    return (XFuture<Void>) super.calledMethod(Method.INCOMING_FRAME, payloads);
}
Also used : DataWrapper(org.webpieces.data.api.DataWrapper) HttpPayload(org.webpieces.httpparser.api.dto.HttpPayload) XFuture(org.webpieces.util.futures.XFuture)

Example 27 with XFuture

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

the class TestLesson3Errors method testRemoteSystemDown.

/**
 * Tests a remote asynchronous system fails and a 500 error page is rendered
 */
@Test
public void testRemoteSystemDown() {
    XFuture<FetchValueResponse> future = new XFuture<FetchValueResponse>();
    mockRemote.addValueToReturn(future);
    HttpFullRequest req = TestLesson2Html.createRequest("/async");
    XFuture<HttpFullResponse> respFuture = http11Socket.send(req);
    Assert.assertFalse(respFuture.isDone());
    // notice that the thread returned but there is no response back to browser yet such that thread can do more work.
    // next, simulate remote system returning a value..
    future.completeExceptionally(new RuntimeException("complete future with exception"));
    ResponseWrapper response = ResponseExtract.waitResponseAndWrap(respFuture);
    response.assertStatusCode(KnownStatusCode.HTTP_500_INTERNAL_SVR_ERROR);
    response.assertContains("You encountered a Bug in our web software");
}
Also used : HttpFullResponse(org.webpieces.httpclient11.api.HttpFullResponse) HttpFullRequest(org.webpieces.httpclient11.api.HttpFullRequest) XFuture(org.webpieces.util.futures.XFuture) ResponseWrapper(org.webpieces.webserver.test.ResponseWrapper) FetchValueResponse(webpiecesxxxxxpackage.service.FetchValueResponse) AbstractWebpiecesTest(org.webpieces.webserver.test.AbstractWebpiecesTest) Test(org.junit.Test)

Example 28 with XFuture

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

the class AsyncSSLEngine2Impl method sendHandshakeMessageImpl.

private XFuture<Void> sendHandshakeMessageImpl() throws SSLException {
    SSLEngine sslEngine = mem.getEngine();
    if (log.isTraceEnabled())
        log.trace(mem + "sending handshake message");
    // HELPER.eraseBuffer(empty);
    HandshakeStatus hsStatus = sslEngine.getHandshakeStatus();
    if (hsStatus != HandshakeStatus.NEED_WRAP)
        throw new IllegalStateException("we should only be calling this method when hsStatus=NEED_WRAP.  hsStatus=" + hsStatus);
    List<XFuture<Void>> futures = new ArrayList<>();
    while (hsStatus == HandshakeStatus.NEED_WRAP) {
        ByteBuffer engineToSocketData = pool.nextBuffer(sslEngine.getSession().getPacketBufferSize());
        Status lastStatus = null;
        synchronized (wrapLock) {
            // KEEEEEP This very small.  wrap and then listener.packetEncrypted
            SSLEngineResult result = sslEngine.wrap(EMPTY, engineToSocketData);
            lastStatus = result.getStatus();
            hsStatus = result.getHandshakeStatus();
            final Status lastStatus2 = lastStatus;
            final HandshakeStatus hsStatus2 = hsStatus;
            if (log.isTraceEnabled())
                log.trace(mem + "write packet pos=" + engineToSocketData.position() + " lim=" + engineToSocketData.limit() + " status=" + lastStatus2 + " hs=" + hsStatus2);
            if (lastStatus == Status.BUFFER_OVERFLOW || lastStatus == Status.BUFFER_UNDERFLOW)
                throw new RuntimeException("status not right, status=" + lastStatus + " even though we sized the buffer to consume all?");
            engineToSocketData.flip();
            XFuture<Void> fut = listener.sendEncryptedHandshakeData(engineToSocketData);
            futures.add(fut);
        }
        if (lastStatus == Status.CLOSED && !clientInitiated) {
            fireClose();
        }
    }
    if (hsStatus == HandshakeStatus.NEED_WRAP || hsStatus == HandshakeStatus.NEED_TASK)
        throw new RuntimeException(mem + "BUG, need to implement more here status=" + hsStatus);
    final HandshakeStatus hsStatus2 = hsStatus;
    if (log.isTraceEnabled())
        log.trace(mem + "status=" + hsStatus2 + " isConn=" + mem.getConnectionState());
    if (hsStatus == HandshakeStatus.FINISHED) {
        fireLinkEstablished();
    }
    XFuture<Void> futureAll = XFuture.allOf(futures.toArray(new XFuture[futures.size()]));
    return futureAll;
}
Also used : HandshakeStatus(javax.net.ssl.SSLEngineResult.HandshakeStatus) Status(javax.net.ssl.SSLEngineResult.Status) SSLEngineResult(javax.net.ssl.SSLEngineResult) XFuture(org.webpieces.util.futures.XFuture) SSLEngine(javax.net.ssl.SSLEngine) AsyncSSLEngine(org.webpieces.ssl.api.AsyncSSLEngine) ArrayList(java.util.ArrayList) ByteBuffer(java.nio.ByteBuffer) HandshakeStatus(javax.net.ssl.SSLEngineResult.HandshakeStatus)

Example 29 with XFuture

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

the class AsyncSSLEngine2Impl method feedEncryptedPacketImpl.

private XFuture<Void> feedEncryptedPacketImpl(ByteBuffer encryptedInData, XFuture<Void> byteAcker) {
    SSLEngine sslEngine = mem.getEngine();
    HandshakeStatus hsStatus = sslEngine.getHandshakeStatus();
    Status status = null;
    logTrace1(encryptedInData, hsStatus);
    ByteBuffer encryptedData = encryptedInData;
    ByteBuffer cached = mem.getCachedToProcess();
    if (cached != null) {
        encryptedData = combine(cached, encryptedData);
        mem.setCachedEncryptedData(null);
    }
    int i = 0;
    // stay in loop while we
    // 1. need unwrap or not_handshaking or need_task AND
    // 2. have data in buffer
    // 3. have enough data in buffer(ie. not underflow)
    int totalToAck = 0;
    while (encryptedData.hasRemaining() && status != Status.BUFFER_UNDERFLOW && status != Status.CLOSED) {
        i++;
        SSLEngineResult result;
        ByteBuffer outBuffer = mem.getCachedOut();
        int remainBeforeDecrypt = encryptedData.remaining();
        try {
            result = sslEngine.unwrap(encryptedData, outBuffer);
            status = result.getStatus();
        } catch (SSLException e) {
            AsyncSSLEngineException ee = new AsyncSSLEngineException("status=" + status + " hsStatus=" + hsStatus + " b=" + encryptedData, e);
            throw ee;
        } finally {
            int totalBytesToAck = remainBeforeDecrypt - encryptedData.remaining();
            if (outBuffer.position() != 0) {
                outBuffer.flip();
                listener.packetUnencrypted(outBuffer).handle((v, t) -> {
                    if (t != null)
                        log.error("Exception in ssl listener", t);
                    decryptionTracker.ackBytes(totalBytesToAck);
                    return null;
                });
                // frequently the out buffer is not used so we only ask the pool for buffers AFTER it has been consumed/used
                ByteBuffer newCachedOut = pool.nextBuffer(sslEngine.getSession().getApplicationBufferSize());
                mem.setCachedOut(newCachedOut);
            } else {
                totalToAck += totalBytesToAck;
            }
        }
        status = result.getStatus();
        hsStatus = result.getHandshakeStatus();
        if (hsStatus == HandshakeStatus.NEED_TASK || hsStatus == HandshakeStatus.NEED_WRAP) {
            // handshake as well
            break;
        }
        logAndCheck(encryptedData, result, outBuffer, status, hsStatus, i);
    }
    if (encryptedData.hasRemaining()) {
        mem.setCachedEncryptedData(encryptedData);
    }
    logTrace(encryptedData, status, hsStatus);
    if (!encryptedData.hasRemaining())
        pool.releaseBuffer(encryptedData);
    int bytesToAck = totalToAck;
    return cleanAndFire(hsStatus, status).thenApply(v -> {
        decryptionTracker.ackBytes(bytesToAck);
        return null;
    }).thenCompose(v -> byteAcker);
}
Also used : HandshakeStatus(javax.net.ssl.SSLEngineResult.HandshakeStatus) Status(javax.net.ssl.SSLEngineResult.Status) BufferPool(org.webpieces.data.api.BufferPool) Logger(org.slf4j.Logger) HandshakeStatus(javax.net.ssl.SSLEngineResult.HandshakeStatus) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Status(javax.net.ssl.SSLEngineResult.Status) ByteBuffer(java.nio.ByteBuffer) ArrayList(java.util.ArrayList) SSLEngine(javax.net.ssl.SSLEngine) AsyncSSLEngine(org.webpieces.ssl.api.AsyncSSLEngine) ByteAckTracker(org.webpieces.util.acking.ByteAckTracker) List(java.util.List) SSLEngineResult(javax.net.ssl.SSLEngineResult) SSLException(javax.net.ssl.SSLException) XFuture(org.webpieces.util.futures.XFuture) AsyncSSLEngineException(org.webpieces.ssl.api.AsyncSSLEngineException) SslListener(org.webpieces.ssl.api.SslListener) ConnectionState(org.webpieces.ssl.api.ConnectionState) SSLEngineResult(javax.net.ssl.SSLEngineResult) SSLEngine(javax.net.ssl.SSLEngine) AsyncSSLEngine(org.webpieces.ssl.api.AsyncSSLEngine) AsyncSSLEngineException(org.webpieces.ssl.api.AsyncSSLEngineException) ByteBuffer(java.nio.ByteBuffer) SSLException(javax.net.ssl.SSLException) HandshakeStatus(javax.net.ssl.SSLEngineResult.HandshakeStatus)

Example 30 with XFuture

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

the class Level5AStates method fireToStateMachine.

private XFuture<Void> fireToStateMachine(Http2SendRecieve type, Stream stream, Http2Msg payload, boolean keepDelayedState) {
    Http2Event event = translate(type, payload);
    XFuture<Void> future = stream.getLock().synchronizeD(() -> {
        fireToStatemachineImpl(stream, event);
        return checkForClosedState(stream, payload, keepDelayedState);
    }).thenApply(isReleased -> {
        release(isReleased, stream, payload);
        return null;
    });
    return future.handle((v, e) -> {
        if (e == null) {
            return XFuture.completedFuture(v);
        } else {
            return translateException(stream, e);
        }
    }).thenCompose(Function.identity());
}
Also used : NoTransitionConnectionError(com.webpieces.http2engine.impl.shared.data.NoTransitionConnectionError) SENT_DATA_EOS(com.webpieces.http2engine.impl.shared.data.Http2Event.SENT_DATA_EOS) RECV_RST(com.webpieces.http2engine.impl.shared.data.Http2Event.RECV_RST) NoTransitionListener(org.webpieces.javasm.api.NoTransitionListener) Http2Msg(com.webpieces.http2.api.dto.lowlevel.lib.Http2Msg) RECV_DATA_EOS(com.webpieces.http2engine.impl.shared.data.Http2Event.RECV_DATA_EOS) LoggerFactory(org.slf4j.LoggerFactory) NoTransitionStreamError(com.webpieces.http2engine.impl.shared.data.NoTransitionStreamError) Function(java.util.function.Function) Supplier(java.util.function.Supplier) RECV_HEADERS_EOS(com.webpieces.http2engine.impl.shared.data.Http2Event.RECV_HEADERS_EOS) Http2SendRecieve(com.webpieces.http2engine.impl.shared.data.Http2Event.Http2SendRecieve) StateMachineFactory(org.webpieces.javasm.api.StateMachineFactory) Http2Event(com.webpieces.http2engine.impl.shared.data.Http2Event) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) State(org.webpieces.javasm.api.State) ConnectionException(com.webpieces.http2.api.dto.error.ConnectionException) StateMachine(org.webpieces.javasm.api.StateMachine) PermitQueue(org.webpieces.util.locking.PermitQueue) Stream(com.webpieces.http2engine.impl.shared.data.Stream) SENT_RST(com.webpieces.http2engine.impl.shared.data.Http2Event.SENT_RST) Memento(org.webpieces.javasm.api.Memento) Logger(org.slf4j.Logger) AsyncLock(org.webpieces.util.locking.AsyncLock) CancelReason(com.webpieces.http2.api.dto.lowlevel.CancelReason) Http2Push(com.webpieces.http2.api.dto.highlevel.Http2Push) SENT_HEADERS_EOS(com.webpieces.http2engine.impl.shared.data.Http2Event.SENT_HEADERS_EOS) CancelReasonCode(com.webpieces.http2.api.dto.error.CancelReasonCode) StreamException(com.webpieces.http2.api.dto.error.StreamException) DataFrame(com.webpieces.http2.api.dto.lowlevel.DataFrame) XFuture(org.webpieces.util.futures.XFuture) Http2PayloadType(com.webpieces.http2engine.impl.shared.data.Http2PayloadType) Http2Headers(com.webpieces.http2.api.dto.highlevel.Http2Headers) Http2Event(com.webpieces.http2engine.impl.shared.data.Http2Event)

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