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));
}
}
}
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());
}
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));
}
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);
}
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;
}
Aggregations