Example usage for java.util.function Consumer accept

List of usage examples for java.util.function Consumer accept

Introduction

In this page you can find the example usage for java.util.function Consumer accept.

Prototype

void accept(T t);

Source Link

Document

Performs this operation on the given argument.

Usage

From source file:at.gridtec.lambda4j.function.tri.obj.BiObjShortFunction.java

/**
 * Returns a composed {@link BiObjShortConsumer} that fist applies this function to its input, and then consumes the
 * result using the given {@link Consumer}. If evaluation of either operation throws an exception, it is relayed to
 * the caller of the composed operation.
 *
 * @param consumer The operation which consumes the result from this operation
 * @return A composed {@code BiObjShortConsumer} that first applies this function to its input, and then consumes
 * the result using the given {@code Consumer}.
 * @throws NullPointerException If given argument is {@code null}
 *//*w w  w  .  j a v  a2s . c  om*/
@Nonnull
default BiObjShortConsumer<T, U> consume(@Nonnull final Consumer<? super R> consumer) {
    Objects.requireNonNull(consumer);
    return (t, u, value) -> consumer.accept(apply(t, u, value));
}

From source file:at.gridtec.lambda4j.function.tri.obj.BiObjDoubleFunction.java

/**
 * Returns a composed {@link BiObjDoubleConsumer} that fist applies this function to its input, and then consumes
 * the result using the given {@link Consumer}. If evaluation of either operation throws an exception, it is relayed
 * to the caller of the composed operation.
 *
 * @param consumer The operation which consumes the result from this operation
 * @return A composed {@code BiObjDoubleConsumer} that first applies this function to its input, and then consumes
 * the result using the given {@code Consumer}.
 * @throws NullPointerException If given argument is {@code null}
 *//*from ww w .j a v  a  2  s . c om*/
@Nonnull
default BiObjDoubleConsumer<T, U> consume(@Nonnull final Consumer<? super R> consumer) {
    Objects.requireNonNull(consumer);
    return (t, u, value) -> consumer.accept(apply(t, u, value));
}

From source file:at.gridtec.lambda4j.function.tri.obj.BiObjLongFunction.java

/**
 * Returns a composed {@link BiObjLongConsumer} that fist applies this function to its input, and then consumes the
 * result using the given {@link Consumer}. If evaluation of either operation throws an exception, it is relayed to
 * the caller of the composed operation.
 *
 * @param consumer The operation which consumes the result from this operation
 * @return A composed {@code BiObjLongConsumer} that first applies this function to its input, and then consumes the
 * result using the given {@code Consumer}.
 * @throws NullPointerException If given argument is {@code null}
 *//*from   w  w  w.j ava2  s .c om*/
@Nonnull
default BiObjLongConsumer<T, U> consume(@Nonnull final Consumer<? super R> consumer) {
    Objects.requireNonNull(consumer);
    return (t, u, value) -> consumer.accept(apply(t, u, value));
}

From source file:com.diversityarrays.util.ClassPathExtender.java

public static void addDirectoryJarsToClassPath(Log logger, Consumer<File> jarChecker, File... dirs) {
    if (dirs == null || dirs.length <= 0) {
        if (logger != null) {
            logger.info("No directories provided for class path");
        }/*from  www .  ja va 2s  . c  o  m*/
        return;
    }

    ClassLoader ccl = Thread.currentThread().getContextClassLoader();
    if (ccl instanceof java.net.URLClassLoader) {
        try {
            Method m = java.net.URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
            m.setAccessible(true);

            Set<URL> currentUrls = new HashSet<URL>(Arrays.asList(((URLClassLoader) ccl).getURLs()));
            if (VERBOSE) {
                info(logger, "=== Current URLS in ClassLoader: " + currentUrls.size());
                for (URL u : currentUrls) {
                    info(logger, "\t" + u.toString());
                }
            }

            for (File dir : dirs) {
                if (dir.isDirectory()) {
                    for (File f : dir.listFiles(JAR_OR_PROPERTIES)) {
                        try {
                            URL u = f.toURI().toURL();
                            if (!currentUrls.contains(u)) {
                                m.invoke(ccl, u);
                                if (VERBOSE) {
                                    info(logger, "[Added " + u + "] to CLASSPATH");
                                }
                                if (jarChecker != null) {
                                    jarChecker.accept(f);
                                }
                            }
                        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
                                | MalformedURLException e) {
                            warn(logger,
                                    "%Unable to add " + f.getPath() + " to CLASSPATH (" + e.getMessage() + ")");
                        }
                    }
                }
            }
        } catch (NoSuchMethodException e) {
            warn(logger, "%No method: " + java.net.URLClassLoader.class.getName() + ".addURL(URL)");
        }

    } else {
        warn(logger, "%currentThread.contextClassLoader is not an instance of "
                + java.net.URLClassLoader.class.getName());
    }
}

From source file:com.github.erchu.beancp.DeclarativeMapImpl.java

@Override
public DeclarativeMap<S, D> beforeMap(final Consumer<Mapper> action) {
    if (mode == MapMode.CONFIGURATION) {
        if (_useConventionExecuted || _bindBindConstantOrMapExecuted || _afterMapExecuted) {
            throw new MapperConfigurationException(INVALID_STATEMENT_ORDER_MESSAGE);
        }/* w w w .  j  a v  a 2  s .  c o  m*/

        _beforeMapExecuted = true;
    }

    if (mode == MapMode.EXECUTION) {
        action.accept(_executionPhaseMapper);
    }

    return this;
}

From source file:local.laer.app.knapsack.support.OffsetBinaryMatrix.java

public void consume(Consumer<Cell<Integer>> callback) {
    SimpleCell<Integer> cell = new SimpleCell<>();

    for (int row = 0; row < rows(); row++) {
        for (int col = 0; col < cols(); col++) {
            cell.col = col + colOffset;//from   w w w .  java  2s  .  c o m
            cell.row = row + rowOffset;
            cell.value = convertToInt(value[row][col]);

            callback.accept(cell);
        }
    }
}

From source file:org.hawkular.inventory.impl.tinkerpop.spi.GraphProviderTest.java

@Test
public void testConcurrentTransactionsAllowed() throws Exception {
    //lock the commits of the 2 concurrent threads on this latch to ensure that we
    //truly do have 2 concurrent transactions on a single graph
    final CountDownLatch startLatch = new CountDownLatch(2);
    final CountDownLatch finishLatch = new CountDownLatch(1);

    boolean[] statuses = new boolean[2];

    GraphProvider gp = new DummyGraphProvider();
    Graph g = gp.instantiateGraph(null);

    Consumer<Integer> payload = (idx) -> {
        gp.startTransaction(g);/*  w  w w .ja  v  a2  s .com*/
        startLatch.countDown();
        try {
            finishLatch.await();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new IllegalStateException("The test graph should not be forcefully interrupted during test.");
        }
        gp.commit(g);

        statuses[idx] = true;
    };

    Thread t1 = new Thread(() -> payload.accept(0));
    Thread t2 = new Thread(() -> payload.accept(1));

    t1.start();
    t2.start();

    startLatch.await();
    finishLatch.countDown();

    t1.join();
    t2.join();

    Assert.assertTrue(statuses[0]);
    Assert.assertTrue(statuses[1]);
}

From source file:org.mimacom.sample.integration.patterns.user.service.integration.AsyncSearchServiceIntegration.java

public void indexUser(User user, Consumer<Void> successConsumer, Consumer<Throwable> failureConsumer) {
    LOG.info("going to send request to index user '{}' '{}'", user.getFirstName(), user.getLastName());

    HttpEntity<User> requestEntity = new HttpEntity<>(user);
    ListenableFuture<ResponseEntity<String>> listenableFuture = this.asyncRestTemplate
            .postForEntity(this.searchServiceUrl + "/index", requestEntity, String.class);

    listenableFuture.addCallback(result -> {
        LOG.info("user '{}' '{}' was indexed and response status code was '{}'", user.getFirstName(),
                user.getLastName(), result.getStatusCode());
        successConsumer.accept(null);
    }, failureConsumer::accept);/*from   w w w. j  a  v a 2s .  c  om*/

}

From source file:org.onosproject.store.cluster.messaging.impl.NettyMessagingManager.java

private void dispatchLocally(InternalMessage message) throws IOException {
    if (message.preamble() != preamble) {
        log.debug("Received {} with invalid preamble from {}", message.type(), message.sender());
        sendReply(message, Status.PROTOCOL_EXCEPTION, Optional.empty());
    }//from   w ww.j  a va 2 s  .  co  m
    clockService.recordEventTime(message.time());
    String type = message.type();
    if (REPLY_MESSAGE_TYPE.equals(type)) {
        try {
            Callback callback = callbacks.getIfPresent(message.id());
            if (callback != null) {
                if (message.status() == Status.OK) {
                    callback.complete(message.payload());
                } else if (message.status() == Status.ERROR_NO_HANDLER) {
                    callback.completeExceptionally(new MessagingException.NoRemoteHandler());
                } else if (message.status() == Status.ERROR_HANDLER_EXCEPTION) {
                    callback.completeExceptionally(new MessagingException.RemoteHandlerFailure());
                } else if (message.status() == Status.PROTOCOL_EXCEPTION) {
                    callback.completeExceptionally(new MessagingException.ProtocolException());
                }
            } else {
                log.debug("Received a reply for message id:[{}]. " + " from {}. But was unable to locate the"
                        + " request handle", message.id(), message.sender());
            }
        } finally {
            callbacks.invalidate(message.id());
        }
        return;
    }
    Consumer<InternalMessage> handler = handlers.get(type);
    if (handler != null) {
        handler.accept(message);
    } else {
        log.debug("No handler for message type {}", message.type(), message.sender());
        sendReply(message, Status.ERROR_NO_HANDLER, Optional.empty());
    }
}

From source file:org.everit.json.schema.loader.SchemaLoader.java

private <E> void ifPresent(final String key, final Class<E> expectedType, final Consumer<E> consumer) {
    if (schemaJson.has(key)) {
        @SuppressWarnings("unchecked")
        E value = (E) schemaJson.get(key);
        try {//ww  w.  j  a va  2  s  .com
            consumer.accept(value);
        } catch (ClassCastException e) {
            throw new SchemaException(key, expectedType, value);
        }
    }
}