Search in sources :

Example 86 with Consumer

use of java.util.function.Consumer in project xtext-core by eclipse.

the class CommandServiceTest method testExecute.

@Test
public void testExecute() {
    final Procedure1<InitializeParams> _function = (InitializeParams it) -> {
        ClientCapabilities _clientCapabilities = new ClientCapabilities();
        final Procedure1<ClientCapabilities> _function_1 = (ClientCapabilities it_1) -> {
            WorkspaceClientCapabilities _workspaceClientCapabilities = new WorkspaceClientCapabilities();
            final Procedure1<WorkspaceClientCapabilities> _function_2 = (WorkspaceClientCapabilities it_2) -> {
                ExecuteCommandCapabilities _executeCommandCapabilities = new ExecuteCommandCapabilities();
                final Procedure1<ExecuteCommandCapabilities> _function_3 = (ExecuteCommandCapabilities it_3) -> {
                    it_3.setDynamicRegistration(Boolean.valueOf(true));
                };
                ExecuteCommandCapabilities _doubleArrow = ObjectExtensions.<ExecuteCommandCapabilities>operator_doubleArrow(_executeCommandCapabilities, _function_3);
                it_2.setExecuteCommand(_doubleArrow);
            };
            WorkspaceClientCapabilities _doubleArrow = ObjectExtensions.<WorkspaceClientCapabilities>operator_doubleArrow(_workspaceClientCapabilities, _function_2);
            it_1.setWorkspace(_doubleArrow);
        };
        ClientCapabilities _doubleArrow = ObjectExtensions.<ClientCapabilities>operator_doubleArrow(_clientCapabilities, _function_1);
        it.setCapabilities(_doubleArrow);
    };
    this.initialize(_function);
    final Procedure1<CommandServiceTest.TestExecuteCommandConfiguration> _function_1 = (CommandServiceTest.TestExecuteCommandConfiguration it) -> {
        it.command = "testlang.a";
        final Consumer<Object> _function_2 = (Object it_1) -> {
            if ((it_1 instanceof String)) {
                this.assertEquals("a", ((String) it_1));
            } else {
                Assert.fail("no string");
            }
        };
        it.assertCommandResult = _function_2;
    };
    this.testExecuteCommand(_function_1);
    final Procedure1<CommandServiceTest.TestExecuteCommandConfiguration> _function_2 = (CommandServiceTest.TestExecuteCommandConfiguration it) -> {
        it.command = "testlang.b";
        final Consumer<Object> _function_3 = (Object it_1) -> {
            if ((it_1 instanceof String)) {
                this.assertEquals("b", ((String) it_1));
            } else {
                Assert.fail("no string");
            }
        };
        it.assertCommandResult = _function_3;
    };
    this.testExecuteCommand(_function_2);
    final Procedure1<CommandServiceTest.TestExecuteCommandConfiguration> _function_3 = (CommandServiceTest.TestExecuteCommandConfiguration it) -> {
        it.command = "doesnotexist.c";
        final Consumer<Object> _function_4 = (Object it_1) -> {
            Assert.assertNull(it_1);
        };
        it.assertCommandResult = _function_4;
    };
    this.testExecuteCommand(_function_3);
}
Also used : WorkspaceClientCapabilities(org.eclipse.lsp4j.WorkspaceClientCapabilities) ClientCapabilities(org.eclipse.lsp4j.ClientCapabilities) InitializeParams(org.eclipse.lsp4j.InitializeParams) WorkspaceClientCapabilities(org.eclipse.lsp4j.WorkspaceClientCapabilities) Consumer(java.util.function.Consumer) Procedure1(org.eclipse.xtext.xbase.lib.Procedures.Procedure1) ExecuteCommandCapabilities(org.eclipse.lsp4j.ExecuteCommandCapabilities) Test(org.junit.Test) AbstractTestLangLanguageServerTest(org.eclipse.xtext.ide.tests.server.AbstractTestLangLanguageServerTest)

Example 87 with Consumer

use of java.util.function.Consumer in project hono by eclipse.

the class ClientTestBase method testSendingMessages.

/**
 * Verifies that a number of messages uploaded to Hono's Telemetry or Event API can be successfully
 * consumed via the AMQP Messaging Network.
 *
 * @param ctx The test context.
 * @throws InterruptedException if test execution is interrupted.
 */
@Test
public void testSendingMessages(final TestContext ctx) throws InterruptedException {
    final CountDownLatch received = new CountDownLatch(IntegrationTestSupport.MSG_COUNT);
    final Async setup = ctx.async();
    final AtomicReference<String> registrationAssertion = new AtomicReference<>();
    registrationClient.register(DEVICE_ID, null).compose(ok -> registrationClient.assertRegistration(DEVICE_ID)).compose(result -> {
        registrationAssertion.set(result.getString(RegistrationConstants.FIELD_ASSERTION));
        return createConsumer(TEST_TENANT_ID, msg -> {
            LOGGER.trace("received {}", msg);
            assertMessageProperties(ctx, msg);
            assertAdditionalMessageProperties(ctx, msg);
            received.countDown();
            if (received.getCount() % 200 == 0) {
                LOGGER.info("messages received: {}", IntegrationTestSupport.MSG_COUNT - received.getCount());
            }
        });
    }).map(c -> {
        consumer = c;
        setup.complete();
        return null;
    });
    setup.await(1000);
    long start = System.currentTimeMillis();
    final AtomicInteger messagesSent = new AtomicInteger();
    while (messagesSent.get() < IntegrationTestSupport.MSG_COUNT) {
        final Async sending = ctx.async();
        sender.send(DEVICE_ID, "payload_" + messagesSent.getAndIncrement(), CONTENT_TYPE_TEXT_PLAIN, registrationAssertion.get(), creditAvailable -> sending.complete());
        if (messagesSent.get() % 200 == 0) {
            LOGGER.info("messages sent: " + messagesSent.get());
        }
        sending.await();
    }
    long timeToWait = Math.max(DEFAULT_TEST_TIMEOUT, Math.round(IntegrationTestSupport.MSG_COUNT * 1.2));
    if (!received.await(timeToWait, TimeUnit.MILLISECONDS)) {
        LOGGER.info("sent {} and received {} messages after {} milliseconds", messagesSent.get(), IntegrationTestSupport.MSG_COUNT - received.getCount(), System.currentTimeMillis() - start);
        ctx.fail("did not receive all messages sent");
    } else {
        LOGGER.info("sent {} and received {} messages after {} milliseconds", messagesSent.get(), IntegrationTestSupport.MSG_COUNT - received.getCount(), System.currentTimeMillis() - start);
    }
}
Also used : TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) LoggerFactory(org.slf4j.LoggerFactory) MessageConsumer(org.eclipse.hono.client.MessageConsumer) AtomicReference(java.util.concurrent.atomic.AtomicReference) Constants(org.eclipse.hono.util.Constants) CompositeFuture(io.vertx.core.CompositeFuture) ProtonClientOptions(io.vertx.proton.ProtonClientOptions) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ConnectionFactoryBuilder(org.eclipse.hono.connection.ConnectionFactoryImpl.ConnectionFactoryBuilder) MessageSender(org.eclipse.hono.client.MessageSender) After(org.junit.After) Message(org.apache.qpid.proton.message.Message) RegistrationClient(org.eclipse.hono.client.RegistrationClient) HonoClient(org.eclipse.hono.client.HonoClient) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) Before(org.junit.Before) Logger(org.slf4j.Logger) Vertx(io.vertx.core.Vertx) RegistrationConstants(org.eclipse.hono.util.RegistrationConstants) Test(org.junit.Test) HonoClientImpl(org.eclipse.hono.client.impl.HonoClientImpl) MessageHelper(org.eclipse.hono.util.MessageHelper) Future(io.vertx.core.Future) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Async(io.vertx.ext.unit.Async) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 88 with Consumer

use of java.util.function.Consumer in project riposte by Nike-Inc.

the class StreamingAsyncHttpClient method prepChannelForDownstreamCall.

protected void prepChannelForDownstreamCall(ChannelPool pool, Channel ch, StreamingCallback callback, Deque<Span> distributedSpanStackToUse, Map<String, String> mdcContextToUse, boolean isSecureHttpsCall, boolean relaxedHttpsValidation, boolean performSubSpanAroundDownstreamCalls, long downstreamCallTimeoutMillis, ObjectHolder<Boolean> callActiveHolder, ObjectHolder<Boolean> lastChunkSentDownstreamHolder) throws SSLException, NoSuchAlgorithmException, KeyStoreException {
    ChannelHandler chunkSenderHandler = new SimpleChannelInboundHandler<HttpObject>() {

        @Override
        protected void channelRead0(ChannelHandlerContext downstreamCallCtx, HttpObject msg) throws Exception {
            try {
                // the call is fully processed should not trigger the behavior a second time.
                if (callActiveHolder.heldObject) {
                    if (msg instanceof LastHttpContent) {
                        lastChunkSentDownstreamHolder.heldObject = true;
                        if (performSubSpanAroundDownstreamCalls) {
                            // Complete the subspan.
                            runnableWithTracingAndMdc(() -> {
                                if (distributedSpanStackToUse == null || distributedSpanStackToUse.size() < 2)
                                    Tracer.getInstance().completeRequestSpan();
                                else
                                    Tracer.getInstance().completeSubSpan();
                            }, distributedSpanStackToUse, mdcContextToUse).run();
                        }
                    }
                    HttpObject msgToPass = msg;
                    if (msg instanceof HttpResponse) {
                        // We can't pass the original HttpResponse back to the callback due to intricacies of how
                        // Netty handles determining the last chunk. If we do, and the callback ends up writing
                        // the message out to the client (which happens during proxy routing for example), then
                        // msg's headers might get modified - potentially causing this channel pipeline to
                        // never send a LastHttpContent, which will in turn cause an indefinite hang.
                        HttpResponse origHttpResponse = (HttpResponse) msg;
                        HttpResponse httpResponse = (msg instanceof FullHttpResponse) ? new DefaultFullHttpResponse(origHttpResponse.getProtocolVersion(), origHttpResponse.getStatus(), ((FullHttpResponse) msg).content()) : new DefaultHttpResponse(origHttpResponse.getProtocolVersion(), origHttpResponse.getStatus());
                        httpResponse.headers().add(origHttpResponse.headers());
                        msgToPass = httpResponse;
                    }
                    callback.messageReceived(msgToPass);
                } else {
                    if (shouldLogBadMessagesAfterRequestFinishes) {
                        runnableWithTracingAndMdc(() -> logger.warn("Received HttpObject msg when call was not active: {}", String.valueOf(msg)), distributedSpanStackToUse, mdcContextToUse).run();
                    }
                }
            } finally {
                if (msg instanceof LastHttpContent) {
                    releaseChannelBackToPoolIfCallIsActive(ch, pool, callActiveHolder, "last content chunk sent", distributedSpanStackToUse, mdcContextToUse);
                }
            }
        }
    };
    Consumer<Throwable> doErrorHandlingConsumer = (cause) -> {
        Pair<Deque<Span>, Map<String, String>> originalThreadInfo = null;
        try {
            // Setup tracing and MDC so our log messages have the correct distributed trace info, etc.
            originalThreadInfo = linkTracingAndMdcToCurrentThread(distributedSpanStackToUse, mdcContextToUse);
            // call is fully processed should not trigger the behavior a second time.
            if (callActiveHolder.heldObject) {
                if (performSubSpanAroundDownstreamCalls) {
                    if (distributedSpanStackToUse == null || distributedSpanStackToUse.size() < 2)
                        Tracer.getInstance().completeRequestSpan();
                    else
                        Tracer.getInstance().completeSubSpan();
                }
                Tracer.getInstance().unregisterFromThread();
                if (cause instanceof Errors.NativeIoException) {
                    // NativeIoExceptions are often setup to not have stack traces which is bad for debugging.
                    // Wrap it in a NativeIoExceptionWrapper that maps to a 503 since this is likely a busted
                    // connection and a second attempt should work.
                    cause = new NativeIoExceptionWrapper("Caught a NativeIoException in the downstream streaming call pipeline. Wrapped it in a " + "NativeIoExceptionWrapper so that it maps to a 503 and provides a usable stack trace " + "in the logs.", (Errors.NativeIoException) cause);
                }
                callback.unrecoverableErrorOccurred(cause, true);
            } else {
                if (cause instanceof DownstreamIdleChannelTimeoutException) {
                    logger.debug("A channel used for downstream calls will be closed because it was idle too long. " + "This is normal behavior and does not indicate a downstream call failure: {}", cause.toString());
                } else {
                    logger.warn("Received exception in downstream call pipeline after the call was finished. " + "Not necessarily anything to worry about but in case it helps debugging the " + "exception was: {}", cause.toString());
                }
            }
        } finally {
            // Mark the channel as broken so it will be closed and removed from the pool when it is returned.
            markChannelAsBroken(ch);
            // Release it back to the pool if possible/necessary so the pool can do its usual cleanup.
            releaseChannelBackToPoolIfCallIsActive(ch, pool, callActiveHolder, "error received in downstream pipeline: " + cause.toString(), distributedSpanStackToUse, mdcContextToUse);
            // No matter what the cause is we want to make sure the channel is closed. Doing this raw ch.close()
            // here will catch the cases where this channel does not have an active call but still needs to be
            // closed (e.g. an idle channel timeout that happens in-between calls).
            ch.close();
            // Unhook the tracing and MDC stuff from this thread now that we're done.
            unlinkTracingAndMdcFromCurrentThread(originalThreadInfo);
        }
    };
    ChannelHandler errorHandler = new ChannelInboundHandlerAdapter() {

        @Override
        public void exceptionCaught(ChannelHandlerContext downstreamCallCtx, Throwable cause) throws Exception {
            doErrorHandlingConsumer.accept(cause);
        }

        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            if (logger.isDebugEnabled()) {
                runnableWithTracingAndMdc(() -> logger.debug("Downstream channel closing. call_active={}, last_chunk_sent_downstream={}, channel_id={}", callActiveHolder.heldObject, lastChunkSentDownstreamHolder.heldObject, ctx.channel().toString()), distributedSpanStackToUse, mdcContextToUse).run();
            }
            // We only care if the channel was closed while the call was active.
            if (callActiveHolder.heldObject)
                doErrorHandlingConsumer.accept(new DownstreamChannelClosedUnexpectedlyException(ch));
            super.channelInactive(ctx);
        }
    };
    // Set up the HTTP client pipeline.
    ChannelPipeline p = ch.pipeline();
    List<String> registeredHandlerNames = p.names();
    // couldn't be removed at that time because it wasn't in the channel's eventLoop.
    if (registeredHandlerNames.contains(DOWNSTREAM_IDLE_CHANNEL_TIMEOUT_HANDLER_NAME)) {
        ChannelHandler idleHandler = p.get(DOWNSTREAM_IDLE_CHANNEL_TIMEOUT_HANDLER_NAME);
        if (idleHandler != null)
            p.remove(idleHandler);
    }
    if (debugChannelLifecycleLoggingEnabled && !registeredHandlerNames.contains(DEBUG_LOGGER_HANDLER_NAME)) {
        // Add the channel debug logger if desired.
        p.addFirst(DEBUG_LOGGER_HANDLER_NAME, new LoggingHandler(DOWNSTREAM_CLIENT_CHANNEL_DEBUG_LOGGER_NAME, LogLevel.DEBUG));
    }
    // Add/replace a downstream call timeout detector.
    addOrReplacePipelineHandler(new DownstreamIdleChannelTimeoutHandler(downstreamCallTimeoutMillis, () -> callActiveHolder.heldObject, true, "StreamingAsyncHttpClientChannel-call-timeout", distributedSpanStackToUse, mdcContextToUse), DOWNSTREAM_CALL_TIMEOUT_HANDLER_NAME, p, registeredHandlerNames);
    if (isSecureHttpsCall) {
        // SSL call. Make sure we add the SSL handler if necessary.
        if (!registeredHandlerNames.contains(SSL_HANDLER_NAME)) {
            if (clientSslCtx == null) {
                if (relaxedHttpsValidation) {
                    clientSslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
                } else {
                    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                    tmf.init((KeyStore) null);
                    clientSslCtx = SslContextBuilder.forClient().trustManager(tmf).build();
                }
            }
            p.addAfter(DOWNSTREAM_CALL_TIMEOUT_HANDLER_NAME, SSL_HANDLER_NAME, clientSslCtx.newHandler(ch.alloc()));
        }
    } else {
        // Not an SSL call. Remove the SSL handler if it's there.
        if (registeredHandlerNames.contains(SSL_HANDLER_NAME))
            p.remove(SSL_HANDLER_NAME);
    }
    // The HttpClientCodec handler deals with HTTP codec stuff so you don't have to. Set it up if it hasn't already
    // been setup, and inspect it to make sure it's in a "ready to handle a new request" state. Some rare
    // and currently unknown edgecases can cause us to hit this point with the HttpClientCodec in an unclean
    // state, and if we barrel forward without cleaning this up the call will fail.
    boolean pipelineContainsHttpClientCodec = registeredHandlerNames.contains(HTTP_CLIENT_CODEC_HANDLER_NAME);
    boolean existingHttpClientCodecIsInBadState = false;
    if (pipelineContainsHttpClientCodec) {
        HttpClientCodec currentCodec = (HttpClientCodec) p.get(HTTP_CLIENT_CODEC_HANDLER_NAME);
        int currentHttpClientCodecInboundState = determineHttpClientCodecInboundState(currentCodec);
        if (currentHttpClientCodecInboundState != 0) {
            runnableWithTracingAndMdc(() -> logger.warn("HttpClientCodec inbound state was not 0. It will be replaced with a fresh HttpClientCodec. " + "bad_httpclientcodec_inbound_state={}", currentHttpClientCodecInboundState), distributedSpanStackToUse, mdcContextToUse).run();
            existingHttpClientCodecIsInBadState = true;
        } else {
            int currentHttpClientCodecOutboundState = determineHttpClientCodecOutboundState(currentCodec);
            if (currentHttpClientCodecOutboundState != 0) {
                runnableWithTracingAndMdc(() -> logger.warn("HttpClientCodec outbound state was not 0. It will be replaced with a fresh HttpClientCodec. " + "bad_httpclientcodec_outbound_state={}", currentHttpClientCodecOutboundState), distributedSpanStackToUse, mdcContextToUse).run();
                existingHttpClientCodecIsInBadState = true;
            }
        }
    }
    // or replace it if it was in a bad state.
    if (!pipelineContainsHttpClientCodec || existingHttpClientCodecIsInBadState) {
        addOrReplacePipelineHandler(new HttpClientCodec(4096, 8192, 8192, true), HTTP_CLIENT_CODEC_HANDLER_NAME, p, registeredHandlerNames);
    }
    // Update the chunk sender handler and error handler to the newly created versions that know about the correct
    // callback, dtrace info, etc to use for this request.
    addOrReplacePipelineHandler(chunkSenderHandler, CHUNK_SENDER_HANDLER_NAME, p, registeredHandlerNames);
    addOrReplacePipelineHandler(errorHandler, ERROR_HANDLER_NAME, p, registeredHandlerNames);
}
Also used : AttributeKey(io.netty.util.AttributeKey) Span(com.nike.wingtips.Span) HttpHeaders(io.netty.handler.codec.http.HttpHeaders) DefaultThreadFactory(io.netty.util.concurrent.DefaultThreadFactory) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) LoggerFactory(org.slf4j.LoggerFactory) Random(java.util.Random) KeyStoreException(java.security.KeyStoreException) AsyncNettyHelper.unlinkTracingAndMdcFromCurrentThread(com.nike.riposte.util.AsyncNettyHelper.unlinkTracingAndMdcFromCurrentThread) HttpObject(io.netty.handler.codec.http.HttpObject) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) InetAddress(java.net.InetAddress) ChannelPromise(io.netty.channel.ChannelPromise) Map(java.util.Map) ThreadFactory(java.util.concurrent.ThreadFactory) SocketChannel(io.netty.channel.socket.SocketChannel) HttpObjectDecoder(io.netty.handler.codec.http.HttpObjectDecoder) HttpRequest(io.netty.handler.codec.http.HttpRequest) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) DOWNSTREAM_CALL_CONNECTION_SETUP_TIME_NANOS_REQUEST_ATTR_KEY(com.nike.riposte.server.handler.ProxyRouterEndpointExecutionHandler.DOWNSTREAM_CALL_CONNECTION_SETUP_TIME_NANOS_REQUEST_ATTR_KEY) DownstreamIdleChannelTimeoutException(com.nike.riposte.server.error.exception.DownstreamIdleChannelTimeoutException) ChannelHealthChecker(io.netty.channel.pool.ChannelHealthChecker) DownstreamChannelClosedUnexpectedlyException(com.nike.riposte.server.error.exception.DownstreamChannelClosedUnexpectedlyException) KeyStore(java.security.KeyStore) ChannelPipeline(io.netty.channel.ChannelPipeline) InetSocketAddress(java.net.InetSocketAddress) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) List(java.util.List) SSLException(javax.net.ssl.SSLException) AbstractChannelPoolHandler(io.netty.channel.pool.AbstractChannelPoolHandler) LogLevel(io.netty.handler.logging.LogLevel) ChannelAttributes(com.nike.riposte.server.channelpipeline.ChannelAttributes) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) HttpObjectEncoder(io.netty.handler.codec.http.HttpObjectEncoder) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) ChannelPoolMap(io.netty.channel.pool.ChannelPoolMap) HttpProcessingState(com.nike.riposte.server.http.HttpProcessingState) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) HttpRequestEncoder(io.netty.handler.codec.http.HttpRequestEncoder) DownstreamIdleChannelTimeoutHandler(com.nike.riposte.client.asynchttp.netty.downstreampipeline.DownstreamIdleChannelTimeoutHandler) RequestInfo(com.nike.riposte.server.http.RequestInfo) ChannelOption(io.netty.channel.ChannelOption) LoggingHandler(io.netty.handler.logging.LoggingHandler) Tracer(com.nike.wingtips.Tracer) CompletableFuture(java.util.concurrent.CompletableFuture) Errors(io.netty.channel.unix.Errors) Deque(java.util.Deque) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) AsyncNettyHelper.linkTracingAndMdcToCurrentThread(com.nike.riposte.util.AsyncNettyHelper.linkTracingAndMdcToCurrentThread) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) HttpRequestTracingUtils(com.nike.wingtips.http.HttpRequestTracingUtils) BiConsumer(java.util.function.BiConsumer) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) HttpContent(io.netty.handler.codec.http.HttpContent) Attribute(io.netty.util.Attribute) Logger(org.slf4j.Logger) EventLoopGroup(io.netty.channel.EventLoopGroup) CombinedChannelDuplexHandler(io.netty.channel.CombinedChannelDuplexHandler) SslContext(io.netty.handler.ssl.SslContext) Promise(io.netty.util.concurrent.Promise) HostnameResolutionException(com.nike.riposte.server.error.exception.HostnameResolutionException) Field(java.lang.reflect.Field) UnknownHostException(java.net.UnknownHostException) ChannelFuture(io.netty.channel.ChannelFuture) Epoll(io.netty.channel.epoll.Epoll) Consumer(java.util.function.Consumer) Channel(io.netty.channel.Channel) SimpleChannelPool(io.netty.channel.pool.SimpleChannelPool) Bootstrap(io.netty.bootstrap.Bootstrap) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) WrapperException(com.nike.backstopper.exception.WrapperException) MDC(org.slf4j.MDC) SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) NativeIoExceptionWrapper(com.nike.riposte.server.error.exception.NativeIoExceptionWrapper) AsyncNettyHelper.runnableWithTracingAndMdc(com.nike.riposte.util.AsyncNettyHelper.runnableWithTracingAndMdc) ChannelPool(io.netty.channel.pool.ChannelPool) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) ChannelHandler(io.netty.channel.ChannelHandler) Pair(com.nike.internal.util.Pair) AbstractChannelPoolMap(io.netty.channel.pool.AbstractChannelPoolMap) Future(io.netty.util.concurrent.Future) DownstreamIdleChannelTimeoutHandler(com.nike.riposte.client.asynchttp.netty.downstreampipeline.DownstreamIdleChannelTimeoutHandler) LoggingHandler(io.netty.handler.logging.LoggingHandler) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelHandler(io.netty.channel.ChannelHandler) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) Span(com.nike.wingtips.Span) HttpObject(io.netty.handler.codec.http.HttpObject) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) Pair(com.nike.internal.util.Pair) SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) NativeIoExceptionWrapper(com.nike.riposte.server.error.exception.NativeIoExceptionWrapper) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) LastHttpContent(io.netty.handler.codec.http.LastHttpContent) ChannelPipeline(io.netty.channel.ChannelPipeline) Errors(io.netty.channel.unix.Errors) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) InsecureTrustManagerFactory(io.netty.handler.ssl.util.InsecureTrustManagerFactory) DownstreamChannelClosedUnexpectedlyException(com.nike.riposte.server.error.exception.DownstreamChannelClosedUnexpectedlyException) DownstreamIdleChannelTimeoutException(com.nike.riposte.server.error.exception.DownstreamIdleChannelTimeoutException) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 89 with Consumer

use of java.util.function.Consumer in project flow by vaadin.

the class StateNodeTest method assertCollectChanges_initiallyInactive.

private void assertCollectChanges_initiallyInactive(StateNode stateNode, ElementPropertyMap properties, Consumer<Boolean> activityUpdater) {
    VisibilityData visibility = stateNode.getFeature(VisibilityData.class);
    activityUpdater.accept(false);
    // activity updater may modify visibility of the node itself or its
    // ancestor. The number of changes will depend on whether the subject
    // node is visible or not
    boolean visibilityChanged = !visibility.isVisible();
    properties.setProperty("foo", "bar");
    TestStateTree tree = (TestStateTree) stateNode.getOwner();
    tree.dirtyNodes.clear();
    List<NodeChange> changes = new ArrayList<>();
    stateNode.collectChanges(changes::add);
    if (visibilityChanged) {
        Assert.assertEquals(0, tree.dirtyNodes.size());
    } else {
        // the target node should be marked as dirty because it's visible
        // but its parent is inactive
        Assert.assertEquals(1, tree.dirtyNodes.size());
        tree.dirtyNodes.contains(stateNode);
    }
    Assert.assertEquals(visibilityChanged ? 3 : 2, changes.size());
    // node is attached event
    Assert.assertThat(changes.get(0), CoreMatchers.instanceOf(NodeAttachChange.class));
    // tag update (ElementData is reported feature) and possible visibility
    // update
    Assert.assertThat(changes.get(1), CoreMatchers.instanceOf(MapPutChange.class));
    MapPutChange change = (MapPutChange) changes.get(1);
    MapPutChange tagChange;
    if (visibilityChanged) {
        Assert.assertThat(changes.get(2), CoreMatchers.instanceOf(MapPutChange.class));
        tagChange = change.getFeature().equals(ElementData.class) ? change : (MapPutChange) changes.get(2);
        change = tagChange.equals(change) ? (MapPutChange) changes.get(2) : change;
    } else {
        tagChange = (MapPutChange) changes.get(1);
    }
    Assert.assertEquals(Element.get(stateNode).getTag(), tagChange.getValue());
    if (visibilityChanged) {
        Assert.assertEquals(Boolean.FALSE, change.getValue());
    }
    changes.clear();
    // now the node becomes active and should send all values from all
    // features (including values that has not been sent previously).
    activityUpdater.accept(true);
    properties.setProperty("baz", "foo");
    stateNode.collectChanges(changes::add);
    Assert.assertEquals(visibilityChanged ? 3 : 2, changes.size());
    // node is attached event
    // property updates and possible visibility update
    Assert.assertThat(changes.get(1), CoreMatchers.instanceOf(MapPutChange.class));
    Optional<MapPutChange> visibilityChange = changes.stream().filter(MapPutChange.class::isInstance).map(MapPutChange.class::cast).filter(chang -> chang.getFeature().equals(VisibilityData.class)).findFirst();
    if (visibilityChanged) {
        Assert.assertTrue(visibilityChange.isPresent());
        Assert.assertTrue((Boolean) visibilityChange.get().getValue());
        changes.remove(visibilityChange.get());
    }
    Optional<MapPutChange> fooUpdate = changes.stream().filter(MapPutChange.class::isInstance).map(MapPutChange.class::cast).filter(chang -> chang.getKey().equals("foo")).findFirst();
    Assert.assertTrue(fooUpdate.isPresent());
    Assert.assertEquals("bar", fooUpdate.get().getValue());
    changes.remove(fooUpdate.get());
    change = (MapPutChange) changes.get(0);
    Assert.assertEquals("foo", change.getValue());
    Assert.assertEquals("baz", change.getKey());
    // Don't make any changes, check that there are no changes collected
    changes.clear();
    stateNode.collectChanges(changes::add);
    Assert.assertEquals(0, changes.size());
}
Also used : MapPutChange(com.vaadin.flow.internal.change.MapPutChange) IntStream(java.util.stream.IntStream) CoreMatchers(org.hamcrest.CoreMatchers) Arrays(java.util.Arrays) VisibilityData(com.vaadin.flow.internal.nodefeature.VisibilityData) NodeAttachChange(com.vaadin.flow.internal.change.NodeAttachChange) Registration(com.vaadin.flow.shared.Registration) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) NodeFeature(com.vaadin.flow.internal.nodefeature.NodeFeature) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Element(com.vaadin.flow.dom.Element) UI(com.vaadin.flow.component.UI) LinkedList(java.util.LinkedList) ElementAttributeMap(com.vaadin.flow.internal.nodefeature.ElementAttributeMap) NodeDetachChange(com.vaadin.flow.internal.change.NodeDetachChange) ElementFactory(com.vaadin.flow.dom.ElementFactory) ElementClassList(com.vaadin.flow.internal.nodefeature.ElementClassList) Set(java.util.Set) Test(org.junit.Test) Collectors(java.util.stream.Collectors) ElementData(com.vaadin.flow.internal.nodefeature.ElementData) Consumer(java.util.function.Consumer) NodeChange(com.vaadin.flow.internal.change.NodeChange) ElementPropertyMap(com.vaadin.flow.internal.nodefeature.ElementPropertyMap) List(java.util.List) MapPutChange(com.vaadin.flow.internal.change.MapPutChange) ElementChildrenList(com.vaadin.flow.internal.nodefeature.ElementChildrenList) Optional(java.util.Optional) Assert(org.junit.Assert) NodeChange(com.vaadin.flow.internal.change.NodeChange) NodeAttachChange(com.vaadin.flow.internal.change.NodeAttachChange) ArrayList(java.util.ArrayList) VisibilityData(com.vaadin.flow.internal.nodefeature.VisibilityData)

Example 90 with Consumer

use of java.util.function.Consumer in project riposte by Nike-Inc.

the class AsyncNettyHelperTest method consumerWithTracingAndMdc_pair_works_as_expected.

@Test
public void consumerWithTracingAndMdc_pair_works_as_expected() {
    // given
    Pair<Deque<Span>, Map<String, String>> setupInfo = generateTracingAndMdcInfo();
    // when
    Consumer result = AsyncNettyHelper.consumerWithTracingAndMdc(consumerMock, setupInfo);
    // then
    verifyConsumerWithTracingAndMdcSupport(result, consumerMock, setupInfo.getLeft(), setupInfo.getRight());
}
Also used : BiConsumer(java.util.function.BiConsumer) Consumer(java.util.function.Consumer) Deque(java.util.Deque) Map(java.util.Map) HashMap(java.util.HashMap) Test(org.junit.Test)

Aggregations

Consumer (java.util.function.Consumer)908 List (java.util.List)445 ArrayList (java.util.ArrayList)288 Test (org.junit.Test)250 Map (java.util.Map)228 IOException (java.io.IOException)223 Collectors (java.util.stream.Collectors)205 Collections (java.util.Collections)185 Arrays (java.util.Arrays)181 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)163 TimeUnit (java.util.concurrent.TimeUnit)157 HashMap (java.util.HashMap)152 Set (java.util.Set)149 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)146 Optional (java.util.Optional)132 Collection (java.util.Collection)127 Function (java.util.function.Function)119 CountDownLatch (java.util.concurrent.CountDownLatch)116 File (java.io.File)112 AtomicReference (java.util.concurrent.atomic.AtomicReference)111