Search in sources :

Example 16 with BiConsumer

use of java.util.function.BiConsumer in project Gargoyle by callakrsos.

the class CommonsSqllPan method queryAll.

/**
	 * @inheritDoc
	 */
@Override
public void queryAll(List<String> queryArray, Consumer<Integer> onSuccess, BiConsumer<Exception, Boolean> exceptionHandler) {
    int result = -1;
    Connection con = null;
    try {
        con = connectionSupplier.get();
        // List<List<String>> collect = Stream.of(queryArray).filter(str ->
        // ValueUtil.isNotEmpty(str)).map(str ->
        // str).collect(Collectors.toList());
        result = DbUtil.getTransactionedScope(con, queryArray, arr -> {
            List<String> collect = arr.stream().filter(str -> ValueUtil.isNotEmpty(str)).collect(Collectors.toList());
            return collect;
        }, ex -> {
            LOGGER.error(ValueUtil.toString(ex));
            exceptionHandler.accept(ex, true);
        });
        onSuccess.accept(result);
    } catch (SQLException e) {
        boolean showDialog = true;
        // 사용자가 SQL을 잘못입력한경우 처리할 내용. [크리틱컬하지않는 에러... 처리.]
        if ("42P01".equals(e.getSQLState())) {
            LOGGER.error(ValueUtil.toString(e));
            showDialog = false;
        } else if ("42S02".equals(e.getSQLState())) {
            LOGGER.error(ValueUtil.toString(e));
            showDialog = false;
        } else /* Postgre sql */
        if ("42601".equals(e.getSQLState())) {
            LOGGER.error(ValueUtil.toString(e));
            showDialog = false;
        }
        exceptionHandler.accept(e, showDialog);
    } catch (Exception e) {
        LOGGER.error(ValueUtil.toString(e));
        exceptionHandler.accept(e, true);
    } finally /* 2015.11.12 finnaly문 추가. */
    {
        try {
            if (con != null)
                con.close();
        } catch (SQLException e) {
            LOGGER.error(ValueUtil.toString(e));
        }
    }
}
Also used : Connection(java.sql.Connection) DbUtil(com.kyj.fx.voeditor.visual.util.DbUtil) LoggerFactory(org.slf4j.LoggerFactory) StringUtils(org.apache.commons.lang3.StringUtils) SchemaItemTree(com.kyj.fx.voeditor.visual.component.sql.dbtree.commons.SchemaItemTree) Map(java.util.Map) ColumnItemTree(com.kyj.fx.voeditor.visual.component.sql.dbtree.commons.ColumnItemTree) TableInformationUserMetadataVO(com.kyj.fx.voeditor.visual.component.sql.table.TableInformationUserMetadataVO) Pair(javafx.util.Pair) DatabaseTreeNode(com.kyj.fx.voeditor.visual.component.sql.dbtree.DatabaseTreeNode) Set(java.util.Set) KeyEvent(javafx.scene.input.KeyEvent) SimpleTextView(com.kyj.fx.voeditor.visual.component.text.SimpleTextView) ConfigResourceLoader(com.kyj.fx.voeditor.visual.momory.ConfigResourceLoader) Collectors(java.util.stream.Collectors) TreeView(javafx.scene.control.TreeView) TableInformationFrameView(com.kyj.fx.voeditor.visual.component.sql.table.TableInformationFrameView) FxUtil(com.kyj.fx.voeditor.visual.util.FxUtil) List(java.util.List) ResourceLoader(com.kyj.fx.voeditor.visual.momory.ResourceLoader) DatabaseItemTree(com.kyj.fx.voeditor.visual.component.sql.dbtree.commons.DatabaseItemTree) Optional(java.util.Optional) ObservableList(javafx.collections.ObservableList) Scene(javafx.scene.Scene) GargoyleConnectionFailException(com.kyj.fx.voeditor.visual.exceptions.GargoyleConnectionFailException) ResultSetToMapConverter(com.kyj.fx.voeditor.visual.functions.ResultSetToMapConverter) TreeItem(javafx.scene.control.TreeItem) MouseEvent(javafx.scene.input.MouseEvent) HashMap(java.util.HashMap) DialogUtil(com.kyj.fx.voeditor.visual.util.DialogUtil) Constructor(java.lang.reflect.Constructor) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) SQLException(java.sql.SQLException) TableItemTree(com.kyj.fx.voeditor.visual.component.sql.dbtree.commons.TableItemTree) BiConsumer(java.util.function.BiConsumer) KeyCode(javafx.scene.input.KeyCode) Properties(java.util.Properties) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) FxClipboardUtil(com.kyj.fx.voeditor.visual.util.FxClipboardUtil) IOException(java.io.IOException) ValueUtil(com.kyj.fx.voeditor.visual.util.ValueUtil) GagoyleParamEmptyException(com.kyj.fx.voeditor.visual.exceptions.GagoyleParamEmptyException) Consumer(java.util.function.Consumer) ActionEvent(javafx.event.ActionEvent) Stage(javafx.stage.Stage) NotYetSupportException(com.kyj.fx.voeditor.visual.exceptions.NotYetSupportException) DatabaseTreeCallback(com.kyj.fx.voeditor.visual.component.sql.dbtree.DatabaseTreeCallback) Collections(java.util.Collections) SQLException(java.sql.SQLException) Connection(java.sql.Connection) List(java.util.List) ObservableList(javafx.collections.ObservableList) ArrayList(java.util.ArrayList) GargoyleConnectionFailException(com.kyj.fx.voeditor.visual.exceptions.GargoyleConnectionFailException) SQLException(java.sql.SQLException) IOException(java.io.IOException) GagoyleParamEmptyException(com.kyj.fx.voeditor.visual.exceptions.GagoyleParamEmptyException) NotYetSupportException(com.kyj.fx.voeditor.visual.exceptions.NotYetSupportException)

Example 17 with BiConsumer

use of java.util.function.BiConsumer in project knime-core by knime.

the class NodeRecommendationManager method loadRecommendations.

/**
 * (Re-)Loads the recommendations for the node recommendation engine from the currently active node triple providers.
 *
 * @throws Exception if something went wrong while loading the statistics (e.g. a corrupt file)
 * @see #getNodeTripleProviders()
 */
public void loadRecommendations() throws Exception {
    // read from multiple frequency sources
    List<NodeTripleProvider> providers = getNodeTripleProviders();
    List<Map<String, List<NodeRecommendation>>> recommendations = new ArrayList<>(providers.size());
    for (NodeTripleProvider provider : providers) {
        if (provider.isEnabled() && !updateRequired(provider)) {
            Map<String, List<NodeRecommendation>> recommendationMap = new HashMap<>();
            recommendations.add(recommendationMap);
            provider.getNodeTriples().forEach(nf -> fillRecommendationsMap(recommendationMap, nf));
            // aggregate multiple occurring id's
            // but apply a different aggregation method to source nodes
            BiConsumer<NodeRecommendation, NodeRecommendation> avgAggr = (np1, np2) -> {
                np1.increaseFrequency(np2.getFrequency(), 1);
            };
            BiConsumer<NodeRecommendation, NodeRecommendation> sumAggr = (np1, np2) -> {
                np1.increaseFrequency(np2.getFrequency(), 0);
            };
            recommendationMap.keySet().stream().forEach(s -> {
                if (s.equals(SOURCE_NODES_KEY)) {
                    aggregate(recommendationMap.get(s), sumAggr);
                } else {
                    aggregate(recommendationMap.get(s), avgAggr);
                }
            });
        }
    }
    // end for
    m_recommendations = recommendations;
    m_listeners.stream().forEach(l -> l.updated());
}
Also used : NativeNodeContainer(org.knime.core.node.workflow.NativeNodeContainer) NodeType(org.knime.core.node.NodeFactory.NodeType) NodeTripleProvider(org.knime.workbench.workflowcoach.data.NodeTripleProvider) HashMap(java.util.HashMap) CoreException(org.eclipse.core.runtime.CoreException) NodeTripleProviderFactory(org.knime.workbench.workflowcoach.data.NodeTripleProviderFactory) ConnectionType(org.knime.core.node.workflow.ConnectionContainer.ConnectionType) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) NodeContainer(org.knime.core.node.workflow.NodeContainer) UpdatableNodeTripleProvider(org.knime.workbench.workflowcoach.data.UpdatableNodeTripleProvider) NodeLogger(org.knime.core.node.NodeLogger) Map(java.util.Map) IConfigurationElement(org.eclipse.core.runtime.IConfigurationElement) BiConsumer(java.util.function.BiConsumer) IExtensionPoint(org.eclipse.core.runtime.IExtensionPoint) IExtension(org.eclipse.core.runtime.IExtension) IPreferenceChangeListener(org.eclipse.core.runtime.preferences.IEclipsePreferences.IPreferenceChangeListener) NodeTriple(org.knime.core.node.NodeTriple) Set(java.util.Set) Collectors(java.util.stream.Collectors) WorkflowCoachPreferenceInitializer(org.knime.workbench.workflowcoach.prefs.WorkflowCoachPreferenceInitializer) RepositoryManager(org.knime.workbench.repository.RepositoryManager) NodeInfo(org.knime.core.node.NodeInfo) Objects(java.util.Objects) DefaultScope(org.eclipse.core.runtime.preferences.DefaultScope) ConnectionContainer(org.knime.core.node.workflow.ConnectionContainer) List(java.util.List) NodeTemplate(org.knime.workbench.repository.model.NodeTemplate) InstanceScope(org.eclipse.core.runtime.preferences.InstanceScope) Platform(org.eclipse.core.runtime.Platform) Collections(java.util.Collections) HashMap(java.util.HashMap) NodeTripleProvider(org.knime.workbench.workflowcoach.data.NodeTripleProvider) UpdatableNodeTripleProvider(org.knime.workbench.workflowcoach.data.UpdatableNodeTripleProvider) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map)

Example 18 with BiConsumer

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

the class EventConsumerImplTest method testCreateRegistersBiConsumerAsMessageHandler.

/**
 * Verifies that the message delivery for a received event is forwarded to the
 * registered event consumer.
 *
 * @param ctx The test context.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testCreateRegistersBiConsumerAsMessageHandler(final TestContext ctx) {
    // GIVEN an event consumer that releases all messages
    final Async consumerCreation = ctx.async();
    final BiConsumer<ProtonDelivery, Message> eventConsumer = (delivery, message) -> {
        ProtonHelper.released(delivery, true);
    };
    final RecordImpl attachments = new RecordImpl();
    final Source source = mock(Source.class);
    when(source.toString()).thenReturn("event/tenant");
    final ProtonReceiver receiver = mock(ProtonReceiver.class);
    when(receiver.getSource()).thenReturn(source);
    when(receiver.attachments()).thenReturn(attachments);
    when(receiver.getRemoteQoS()).thenReturn(ProtonQoS.AT_LEAST_ONCE);
    when(receiver.open()).then(answer -> {
        consumerCreation.complete();
        return receiver;
    });
    final ProtonConnection con = mock(ProtonConnection.class);
    when(con.createReceiver(anyString())).thenReturn(receiver);
    when(receiver.openHandler(any(Handler.class))).thenAnswer(invocation -> {
        final Handler handler = invocation.getArgument(0);
        handler.handle(Future.succeededFuture(receiver));
        return receiver;
    });
    final ArgumentCaptor<ProtonMessageHandler> messageHandler = ArgumentCaptor.forClass(ProtonMessageHandler.class);
    EventConsumerImpl.create(vertx.getOrCreateContext(), new ClientConfigProperties(), con, "tenant", eventConsumer, open -> {
    }, remoteDetach -> {
    });
    consumerCreation.await();
    verify(receiver).handler(messageHandler.capture());
    // WHEN an event is received
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    final Message msg = mock(Message.class);
    messageHandler.getValue().handle(delivery, msg);
    // THEN the message is released and settled
    verify(delivery).disposition(any(Released.class), eq(Boolean.TRUE));
}
Also used : TestContext(io.vertx.ext.unit.TestContext) ProtonConnection(io.vertx.proton.ProtonConnection) ProtonReceiver(io.vertx.proton.ProtonReceiver) Async(io.vertx.ext.unit.Async) ProtonDelivery(io.vertx.proton.ProtonDelivery) RunWith(org.junit.runner.RunWith) Timeout(io.vertx.ext.unit.junit.Timeout) ArgumentCaptor(org.mockito.ArgumentCaptor) ProtonMessageHandler(io.vertx.proton.ProtonMessageHandler) RecordImpl(org.apache.qpid.proton.engine.impl.RecordImpl) After(org.junit.After) BiConsumer(java.util.function.BiConsumer) Message(org.apache.qpid.proton.message.Message) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) Before(org.junit.Before) Vertx(io.vertx.core.Vertx) Test(org.junit.Test) ProtonHelper(io.vertx.proton.ProtonHelper) ProtonQoS(io.vertx.proton.ProtonQoS) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) Released(org.apache.qpid.proton.amqp.messaging.Released) Future(io.vertx.core.Future) Mockito(org.mockito.Mockito) Source(org.apache.qpid.proton.amqp.transport.Source) Rule(org.junit.Rule) Handler(io.vertx.core.Handler) ProtonReceiver(io.vertx.proton.ProtonReceiver) Released(org.apache.qpid.proton.amqp.messaging.Released) ProtonDelivery(io.vertx.proton.ProtonDelivery) Message(org.apache.qpid.proton.message.Message) ProtonMessageHandler(io.vertx.proton.ProtonMessageHandler) Handler(io.vertx.core.Handler) RecordImpl(org.apache.qpid.proton.engine.impl.RecordImpl) Source(org.apache.qpid.proton.amqp.transport.Source) ProtonConnection(io.vertx.proton.ProtonConnection) ProtonMessageHandler(io.vertx.proton.ProtonMessageHandler) Async(io.vertx.ext.unit.Async) ClientConfigProperties(org.eclipse.hono.config.ClientConfigProperties) Test(org.junit.Test)

Example 19 with BiConsumer

use of java.util.function.BiConsumer in project eclipse.platform.swt by eclipse.

the class MJ_Table method ownerDrawn_cheese_multiple_col.

@Test
public void ownerDrawn_cheese_multiple_col() {
    final Shell shell = mkShell("Expected: No cheese in multiple column, also mouse move over no cheese.");
    shell.setLayout(new FillLayout(SWT.VERTICAL));
    final Table table = new Table(shell, SWT.VIRTUAL | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
    AtomicBoolean packpending = new AtomicBoolean(true);
    table.setData(packpending);
    table.addListener(SWT.EraseItem, ownerDrawnListener);
    table.addListener(SWT.SetData, ownerDrawnListener);
    table.addListener(SWT.MeasureItem, ownerDrawnListener);
    table.addListener(SWT.PaintItem, ownerDrawnListener);
    BiConsumer<Integer, String> createColCons = (colStyle, colName) -> {
        final TableColumn tableColumn = new TableColumn(table, colStyle);
        tableColumn.setText(colName);
        tableColumn.setMoveable(true);
    };
    createColCons.accept(SWT.LEFT, "LEFT");
    createColCons.accept(SWT.CENTER, "CENTER");
    createColCons.accept(SWT.RIGHT, "RIGHT");
    int ItemCount = 1000;
    table.setItemCount(ItemCount);
    table.setHeaderVisible(true);
    shell.setSize(SWIDTH, SHEIGHT);
    shell.open();
    mainLoop(shell);
}
Also used : TableEditor(org.eclipse.swt.custom.TableEditor) MethodSorters(org.junit.runners.MethodSorters) Arrays(java.util.Arrays) BiFunction(java.util.function.BiFunction) TableColumn(org.eclipse.swt.widgets.TableColumn) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) FontMetrics(org.eclipse.swt.graphics.FontMetrics) Image(org.eclipse.swt.graphics.Image) Rectangle(org.eclipse.swt.graphics.Rectangle) Random(java.util.Random) ControlListener(org.eclipse.swt.events.ControlListener) TextLayout(org.eclipse.swt.graphics.TextLayout) TextStyle(org.eclipse.swt.graphics.TextStyle) Table(org.eclipse.swt.widgets.Table) GC(org.eclipse.swt.graphics.GC) Point(org.eclipse.swt.graphics.Point) Event(org.eclipse.swt.widgets.Event) ControlEvent(org.eclipse.swt.events.ControlEvent) Locale(java.util.Locale) Composite(org.eclipse.swt.widgets.Composite) Listener(org.eclipse.swt.widgets.Listener) BiConsumer(java.util.function.BiConsumer) Font(org.eclipse.swt.graphics.Font) GridData(org.eclipse.swt.layout.GridData) FillLayout(org.eclipse.swt.layout.FillLayout) RowData(org.eclipse.swt.layout.RowData) Collator(java.text.Collator) TableItem(org.eclipse.swt.widgets.TableItem) Text(org.eclipse.swt.widgets.Text) Shell(org.eclipse.swt.widgets.Shell) Button(org.eclipse.swt.widgets.Button) ShellEvent(org.eclipse.swt.events.ShellEvent) Test(org.junit.Test) ShellAdapter(org.eclipse.swt.events.ShellAdapter) Consumer(java.util.function.Consumer) RowLayout(org.eclipse.swt.layout.RowLayout) Color(org.eclipse.swt.graphics.Color) ControlAdapter(org.eclipse.swt.events.ControlAdapter) SWT(org.eclipse.swt.SWT) SelectionEvent(org.eclipse.swt.events.SelectionEvent) ScrollBar(org.eclipse.swt.widgets.ScrollBar) FixMethodOrder(org.junit.FixMethodOrder) Label(org.eclipse.swt.widgets.Label) SelectionListener(org.eclipse.swt.events.SelectionListener) GridLayout(org.eclipse.swt.layout.GridLayout) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Shell(org.eclipse.swt.widgets.Shell) Table(org.eclipse.swt.widgets.Table) FillLayout(org.eclipse.swt.layout.FillLayout) TableColumn(org.eclipse.swt.widgets.TableColumn) Point(org.eclipse.swt.graphics.Point) Test(org.junit.Test)

Example 20 with BiConsumer

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

the class StreamingAsyncHttpClient method streamDownstreamCall.

/**
 * TODO: Fully document me.
 * <br/>
 * NOTE: The returned CompletableFuture will only be completed successfully if the connection to the downstream
 * server was successful and the initialRequestChunk was successfully written out. This has implications for
 * initialRequestChunk regarding releasing its reference count (i.e. calling {@link
 * io.netty.util.ReferenceCountUtil#release(Object)} and passing in initialRequestChunk). If the returned
 * CompletableFuture is successful it means initialRequestChunk's reference count will already be reduced by one
 * relative to when this method was called because it will have been passed to a successful {@link
 * ChannelHandlerContext#writeAndFlush(Object)} method call.
 * <p/>
 * Long story short - assume initialRequestChunk is an object with a reference count of x:
 * <ul>
 *     <li>
 *         If the returned CompletableFuture is successful, then when it completes successfully
 *         initialRequestChunk's reference count will be x - 1
 *     </li>
 *     <li>
 *         If the returned CompletableFuture is *NOT* successful, then when it completes initialRequestChunk's
 *         reference count will still be x
 *     </li>
 * </ul>
 */
public CompletableFuture<StreamingChannel> streamDownstreamCall(String downstreamHost, int downstreamPort, HttpRequest initialRequestChunk, boolean isSecureHttpsCall, boolean relaxedHttpsValidation, StreamingCallback callback, long downstreamCallTimeoutMillis, boolean performSubSpanAroundDownstreamCalls, boolean addTracingHeadersToDownstreamCall, ChannelHandlerContext ctx) {
    CompletableFuture<StreamingChannel> streamingChannel = new CompletableFuture<>();
    // set host header. include port in value when it is a non-default port
    boolean isDefaultPort = (downstreamPort == 80 && !isSecureHttpsCall) || (downstreamPort == 443 && isSecureHttpsCall);
    String hostHeaderValue = (isDefaultPort) ? downstreamHost : downstreamHost + ":" + downstreamPort;
    initialRequestChunk.headers().set(HttpHeaders.Names.HOST, hostHeaderValue);
    long beforeConnectionStartTimeNanos = System.nanoTime();
    // Create a connection to the downstream server.
    ChannelPool pool = getPooledChannelFuture(downstreamHost, downstreamPort);
    Future<Channel> channelFuture = pool.acquire();
    // Add a listener that kicks off the downstream call once the connection is completed.
    channelFuture.addListener(future -> {
        Pair<Deque<Span>, Map<String, String>> originalThreadInfo = null;
        try {
            long connectionSetupTimeNanos = System.nanoTime() - beforeConnectionStartTimeNanos;
            HttpProcessingState httpProcessingState = ChannelAttributes.getHttpProcessingStateForChannel(ctx).get();
            if (httpProcessingState != null) {
                RequestInfo<?> requestInfo = httpProcessingState.getRequestInfo();
                if (requestInfo != null) {
                    requestInfo.addRequestAttribute(DOWNSTREAM_CALL_CONNECTION_SETUP_TIME_NANOS_REQUEST_ATTR_KEY, connectionSetupTimeNanos);
                }
            }
            // Setup tracing and MDC so our log messages have the correct distributed trace info, etc.
            originalThreadInfo = linkTracingAndMdcToCurrentThread(ctx);
            if (logger.isDebugEnabled()) {
                logger.debug("CONNECTION SETUP TIME NANOS: {}", connectionSetupTimeNanos);
            }
            if (!future.isSuccess()) {
                try {
                    // We did not connect to the downstream host successfully. Notify the callback.
                    streamingChannel.completeExceptionally(new WrapperException("Unable to connect to downstream host: " + downstreamHost, future.cause()));
                } finally {
                    Channel ch = channelFuture.getNow();
                    if (ch != null) {
                        // We likely will never reach here since the channel future was not successful, however if
                        // we *do* manage to get here somehow, then mark the channel broken and release it back
                        // to the pool.
                        markChannelAsBroken(ch);
                        pool.release(ch);
                    }
                }
                return;
            }
            // noinspection ConstantConditions
            if (performSubSpanAroundDownstreamCalls) {
                // Add the subspan.
                String spanName = getSubspanSpanName(initialRequestChunk.getMethod().name(), downstreamHost + ":" + downstreamPort + initialRequestChunk.getUri());
                if (Tracer.getInstance().getCurrentSpan() == null) {
                    // There is no parent span to start a subspan from, so we have to start a new span for this call
                    // rather than a subspan.
                    // TODO: Set this to CLIENT once we have that ability in the wingtips API for request root spans
                    Tracer.getInstance().startRequestWithRootSpan(spanName);
                } else {
                    // There was at least one span on the stack, so we can start a subspan for this call.
                    Tracer.getInstance().startSubSpan(spanName, Span.SpanPurpose.CLIENT);
                }
            }
            Deque<Span> distributedSpanStackToUse = Tracer.getInstance().getCurrentSpanStackCopy();
            Map<String, String> mdcContextToUse = MDC.getCopyOfContextMap();
            Span spanForDownstreamCall = (distributedSpanStackToUse == null) ? null : distributedSpanStackToUse.peek();
            // Add distributed trace headers to the downstream call if desired and we have a current span.
            if (addTracingHeadersToDownstreamCall && spanForDownstreamCall != null) {
                HttpRequestTracingUtils.propagateTracingHeaders((headerKey, headerValue) -> {
                    if (headerValue != null) {
                        initialRequestChunk.headers().set(headerKey, headerValue);
                    }
                }, spanForDownstreamCall);
            }
            Channel ch = channelFuture.getNow();
            if (logger.isDebugEnabled())
                logger.debug("Channel ID of the Channel pulled from the pool: {}", ch.toString());
            // We may not be in the right thread to modify the channel pipeline and write data. If we're in the
            // wrong thread we can get deadlock type situations. By running the relevant bits in the channel's
            // event loop we're guaranteed it will be run in the correct thread.
            ch.eventLoop().execute(runnableWithTracingAndMdc(() -> {
                BiConsumer<String, Throwable> prepChannelErrorHandler = (errorMessage, cause) -> {
                    try {
                        streamingChannel.completeExceptionally(new WrapperException(errorMessage, cause));
                    } finally {
                        // This channel may be permanently busted depending on the error, so mark it broken and let
                        // the pool close it and clean it up.
                        markChannelAsBroken(ch);
                        pool.release(ch);
                    }
                };
                try {
                    ObjectHolder<Boolean> callActiveHolder = new ObjectHolder<>();
                    callActiveHolder.heldObject = true;
                    ObjectHolder<Boolean> lastChunkSentDownstreamHolder = new ObjectHolder<>();
                    lastChunkSentDownstreamHolder.heldObject = false;
                    // noinspection ConstantConditions
                    prepChannelForDownstreamCall(pool, ch, callback, distributedSpanStackToUse, mdcContextToUse, isSecureHttpsCall, relaxedHttpsValidation, performSubSpanAroundDownstreamCalls, downstreamCallTimeoutMillis, callActiveHolder, lastChunkSentDownstreamHolder);
                    logInitialRequestChunk(initialRequestChunk, downstreamHost, downstreamPort);
                    // Send the HTTP request.
                    ChannelFuture writeFuture = ch.writeAndFlush(initialRequestChunk);
                    // After the initial chunk has been sent we'll open the floodgates
                    // for any further chunk streaming
                    writeFuture.addListener(completedWriteFuture -> {
                        if (completedWriteFuture.isSuccess())
                            streamingChannel.complete(new StreamingChannel(ch, pool, callActiveHolder, lastChunkSentDownstreamHolder, distributedSpanStackToUse, mdcContextToUse));
                        else {
                            prepChannelErrorHandler.accept("Writing the first HttpRequest chunk to the downstream service failed.", completedWriteFuture.cause());
                            // noinspection UnnecessaryReturnStatement
                            return;
                        }
                    });
                } catch (SSLException | NoSuchAlgorithmException | KeyStoreException ex) {
                    prepChannelErrorHandler.accept("Error setting up SSL context for downstream call", ex);
                    // noinspection UnnecessaryReturnStatement
                    return;
                } catch (Throwable t) {
                    // If we don't catch and handle this here it gets swallowed since we're in a Runnable
                    prepChannelErrorHandler.accept("An unexpected error occurred while prepping the channel pipeline for the downstream call", t);
                    // noinspection UnnecessaryReturnStatement
                    return;
                }
            }, ctx));
        } catch (Throwable ex) {
            try {
                String errorMsg = "Error occurred attempting to send first chunk (headers/etc) downstream";
                Exception errorToFire = new WrapperException(errorMsg, ex);
                logger.warn(errorMsg, errorToFire);
                streamingChannel.completeExceptionally(errorToFire);
            } finally {
                Channel ch = channelFuture.getNow();
                if (ch != null) {
                    // Depending on where the error was thrown the channel may or may not exist. If it does exist,
                    // then assume it's unusable, mark it as broken, and let the pool close it and remove it.
                    markChannelAsBroken(ch);
                    pool.release(ch);
                }
            }
        } finally {
            // Unhook the tracing and MDC stuff from this thread now that we're done.
            unlinkTracingAndMdcFromCurrentThread(originalThreadInfo);
        }
    });
    return streamingChannel;
}
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) HttpProcessingState(com.nike.riposte.server.http.HttpProcessingState) Span(com.nike.wingtips.Span) WrapperException(com.nike.backstopper.exception.WrapperException) CompletableFuture(java.util.concurrent.CompletableFuture) ChannelFuture(io.netty.channel.ChannelFuture) SimpleChannelPool(io.netty.channel.pool.SimpleChannelPool) ChannelPool(io.netty.channel.pool.ChannelPool) SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) Channel(io.netty.channel.Channel) Deque(java.util.Deque) KeyStoreException(java.security.KeyStoreException) DownstreamIdleChannelTimeoutException(com.nike.riposte.server.error.exception.DownstreamIdleChannelTimeoutException) DownstreamChannelClosedUnexpectedlyException(com.nike.riposte.server.error.exception.DownstreamChannelClosedUnexpectedlyException) SSLException(javax.net.ssl.SSLException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) HostnameResolutionException(com.nike.riposte.server.error.exception.HostnameResolutionException) UnknownHostException(java.net.UnknownHostException) WrapperException(com.nike.backstopper.exception.WrapperException) Map(java.util.Map) ChannelPoolMap(io.netty.channel.pool.ChannelPoolMap) AbstractChannelPoolMap(io.netty.channel.pool.AbstractChannelPoolMap) BiConsumer(java.util.function.BiConsumer)

Aggregations

BiConsumer (java.util.function.BiConsumer)264 Test (org.junit.Test)111 List (java.util.List)109 Map (java.util.Map)79 IOException (java.io.IOException)78 ArrayList (java.util.ArrayList)74 Consumer (java.util.function.Consumer)71 HashMap (java.util.HashMap)66 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)54 Collectors (java.util.stream.Collectors)53 CountDownLatch (java.util.concurrent.CountDownLatch)52 Collections (java.util.Collections)46 Set (java.util.Set)46 Collection (java.util.Collection)45 Arrays (java.util.Arrays)44 TimeUnit (java.util.concurrent.TimeUnit)43 Function (java.util.function.Function)43 Assert (org.junit.Assert)43 Optional (java.util.Optional)41 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)35