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:com.ikanow.aleph2.graph.titan.services.TitanGraphBuilderEnrichmentService.java

protected void tryRecoverableTransaction(final Consumer<TitanTransaction> transaction,
        final Runnable on_success) {
    final Random random_generator = new Random(java.util.UUID.randomUUID().getMostSignificantBits());
    IntStream.range(0, 1 + _MAX_ATTEMPT_NUM).boxed().filter(i -> { //(at most 5 attempts)
        try {//from  w  w w  . java 2  s  .c o  m
            // Create transaction

            /**/
            //TRACE
            System.err.println(new java.util.Date().toString() + ": GRABBING TRANS " + i);

            final TitanTransaction mutable_tx = _titan.get().newTransaction();

            /**/
            //TRACE
            System.err.println(
                    new java.util.Date().toString() + ": GRABBED TRANS " + i + " toS=" + mutable_tx.toString());

            try {
                transaction.accept(mutable_tx);
            } catch (Exception e) { //(close the transaction without saving)
                /**/
                //TRACE
                System.err.println(new java.util.Date().toString() + ": (ERROR) ROLLING BACK TRANS " + i);

                mutable_tx.rollback();
                throw e;
            }

            /**/
            //TRACE
            System.err.println(new java.util.Date().toString() + ": COMMITTING TRANS " + i + " tx="
                    + mutable_tx.hasModifications() + " open=" + mutable_tx.isOpen() + " toS="
                    + mutable_tx.toString());

            // Attempt to commit
            mutable_tx.commit();

            /**/
            //TRACE
            System.err.println(new java.util.Date().toString() + ": COMMITTED TRANS " + i);

            on_success.run();

            return true; // (ie ends the loop)
        } catch (TitanException e) {
            if ((i >= _MAX_ATTEMPT_NUM) || !isRecoverableError(e)) {

                /**/
                //DEBUG
                System.err.println(new java.util.Date().toString() + ": HERE2 NON_RECOV: " + i + " vs "
                        + _MAX_ATTEMPT_NUM + ErrorUtils.getLongForm(" error={0}", e));
                //e.printStackTrace();               

                _logger.optional().ifPresent(logger -> {
                    logger.log(Level.ERROR, ErrorUtils.lazyBuildMessage(false,
                            () -> "GraphBuilderEnrichmentService", () -> "system.onStageComplete", () -> null,
                            () -> ErrorUtils.getLongForm(
                                    "Failed to commit transaction due to local conflicts, attempt_num={1} error={0} (uuid={2})",
                                    e, i, UUID),
                            () -> null));
                });
                throw e;
            }

            // If we're here, we're going to retry the transaction

            /**/
            //DEBUG
            System.err.println(new java.util.Date().toString() + ": HERE3 RECOVERABLE"
                    + ErrorUtils.getLongForm(" error={0}", e));

            final int min_sleep_time = _BACKOFF_TIMES_MS[i] / 2;
            final int sleep_time = min_sleep_time + random_generator.nextInt(min_sleep_time);

            _logger.optional().ifPresent(logger -> {
                logger.log(Level.DEBUG, ErrorUtils.lazyBuildMessage(false,
                        () -> "GraphBuilderEnrichmentService", () -> "system.onStageComplete", () -> null,
                        () -> ErrorUtils.get(
                                "Failed to commit transaction due to local conflicts, attempt_num={0} (uuid={1} sleep_ms={2})",
                                i, UUID, sleep_time),
                        () -> null));
            });

            try {
                Thread.sleep(sleep_time);
            } catch (Exception interrupted) {
            }
            return false;

            // (If it's a versioning conflict then try again)
        }
        /**/
        //TRACE:
        catch (Throwable x) {
            System.err.println(new java.util.Date().toString() + ": HERE1 OTHER ERR"
                    + ErrorUtils.getLongForm(" error={0}", x));
            //x.printStackTrace();
            throw x;
        }
    }).findFirst() // ie stop as soon as we have successfully transacted
    ;
}

From source file:org.onosproject.store.primitives.impl.CopycatTransportServer.java

private void listen(Address address, Consumer<Connection> listener, ThreadContext context) {
    messagingService.registerHandler(messageSubject, (sender, payload) -> {
        try (DataInputStream input = new DataInputStream(new ByteArrayInputStream(payload))) {
            long connectionId = input.readLong();
            AtomicBoolean newConnectionCreated = new AtomicBoolean(false);
            CopycatTransportConnection connection = connections.computeIfAbsent(connectionId, k -> {
                newConnectionCreated.set(true);
                CopycatTransportConnection newConnection = new CopycatTransportConnection(connectionId,
                        CopycatTransport.Mode.SERVER, partitionId, CopycatTransport.toAddress(sender),
                        messagingService, getOrCreateContext(context));
                log.debug("Created new incoming connection {}", connectionId);
                newConnection.closeListener(c -> connections.remove(connectionId, c));
                return newConnection;
            });//w w w.  j  a  v a  2  s  .  c o m
            byte[] request = IOUtils.toByteArray(input);
            return CompletableFuture.supplyAsync(() -> {
                if (newConnectionCreated.get()) {
                    listener.accept(connection);
                }
                return connection;
            }, context.executor()).thenCompose(c -> c.handle(request));
        } catch (IOException e) {
            return Tools.exceptionalFuture(e);
        }
    });
    context.execute(() -> {
        listenFuture.complete(null);
    });
}

From source file:org.kie.server.services.impl.KieServerImpl.java

/**
 * Persists updated KieServer state./*  w w w  . ja  va 2 s. c  o m*/
 * @param kieServerStateConsumer
 */
private void storeServerState(Consumer<KieServerState> kieServerStateConsumer) {
    KieServerState currentState = repository.load(KieServerEnvironment.getServerId());
    kieServerStateConsumer.accept(currentState);
    repository.store(KieServerEnvironment.getServerId(), currentState);
}

From source file:org.elasticsearch.client.RequestConvertersTests.java

private static void setRandomRefreshPolicy(Consumer<WriteRequest.RefreshPolicy> setter,
        Map<String, String> expectedParams) {
    if (randomBoolean()) {
        WriteRequest.RefreshPolicy refreshPolicy = randomFrom(WriteRequest.RefreshPolicy.values());
        setter.accept(refreshPolicy);
        if (refreshPolicy != WriteRequest.RefreshPolicy.NONE) {
            expectedParams.put("refresh", refreshPolicy.getValue());
        }/*from ww w  .j a v a 2 s .  co m*/
    }
}

From source file:org.elasticsearch.client.RequestConvertersTests.java

/**
 * Randomize the {@link FetchSourceContext} request parameters.
 *///w  w  w.ja  v  a 2  s.  c om
private static void randomizeFetchSourceContextParams(Consumer<FetchSourceContext> consumer,
        Map<String, String> expectedParams) {
    if (randomBoolean()) {
        if (randomBoolean()) {
            boolean fetchSource = randomBoolean();
            consumer.accept(new FetchSourceContext(fetchSource));
            if (fetchSource == false) {
                expectedParams.put("_source", "false");
            }
        } else {
            int numIncludes = randomIntBetween(0, 5);
            String[] includes = new String[numIncludes];
            String includesParam = randomFields(includes);
            if (numIncludes > 0) {
                expectedParams.put("_source_include", includesParam);
            }
            int numExcludes = randomIntBetween(0, 5);
            String[] excludes = new String[numExcludes];
            String excludesParam = randomFields(excludes);
            if (numExcludes > 0) {
                expectedParams.put("_source_exclude", excludesParam);
            }
            consumer.accept(new FetchSourceContext(true, includes, excludes));
        }
    }
}

From source file:acmi.l2.clientmod.l2smr.Controller.java

protected void longTask(Task task, Consumer<Throwable> exceptionHandler) {
    executor.execute(() -> {/*from   w w w .j ava 2s. c o  m*/
        Platform.runLater(() -> {
            progress.setProgress(-1);
            progress.setVisible(true);
        });

        try {
            task.run(value -> Platform.runLater(() -> progress.setProgress(value)));
        } catch (Throwable t) {
            exceptionHandler.accept(t);
        } finally {
            Platform.runLater(() -> progress.setVisible(false));
        }
    });
}

From source file:org.diorite.impl.CoreMain.java

public static OptionSet main(final String[] args, final boolean client, final Consumer<OptionParser> addon) {
    final OptionParser parser = new OptionParser() {
        {/*from  w  ww.  j av  a  2s  .c o m*/
            this.acceptsAll(Collections.singletonList("?"), "Print help");
            this.acceptsAll(Arrays.asList("v", "version"), "Print version");
            this.acceptsAll(Collections.singletonList("debug"), "Enable debug mode");
            this.acceptsAll(Arrays.asList("resourceleakdetector", "rld"),
                    "ResourceLeakDetector level, disabled by default").withRequiredArg().ofType(String.class)
                    .describedAs("rld").defaultsTo(ResourceLeakDetector.Level.DISABLED.name());
            this.acceptsAll(Arrays.asList("p", "port", "server-port"), "Port to listen on").withRequiredArg()
                    .ofType(Integer.class).describedAs("port").defaultsTo(Core.DEFAULT_PORT);
            this.acceptsAll(Arrays.asList("hostname", "h"), "hostname to listen on").withRequiredArg()
                    .ofType(String.class).describedAs("hostname").defaultsTo("localhost");
            this.acceptsAll(Arrays.asList("online-mode", "online", "o"), "is server should be in online-mode")
                    .withRequiredArg().ofType(Boolean.class).describedAs("online").defaultsTo(true);
            this.acceptsAll(Collections.singletonList("config"), "Configuration file to use.").withRequiredArg()
                    .ofType(File.class).describedAs("config").defaultsTo(new File("diorite.yml"));
            this.acceptsAll(Arrays.asList("keepalivetimer", "keep-alive-timer", "kat"),
                    "Each x seconds server will send keep alive packet to players").withRequiredArg()
                    .ofType(Integer.class).describedAs("keepalivetimer").defaultsTo(10);
            this.acceptsAll(Arrays.asList("netty", "netty-threads"), "Amount of netty event loop threads.")
                    .withRequiredArg().ofType(Integer.class).describedAs("netty").defaultsTo(4);
            this.acceptsAll(Collections.singletonList("noconsole"), "Disables the console");
        }
    };
    if (addon != null) {
        addon.accept(parser);
    }
    OptionSet options;
    try {
        options = parser.parse(args);
    } catch (final Exception e) {
        e.printStackTrace();
        options = parser.parse(ArrayUtils.EMPTY_STRING_ARRAY);
    }
    final InitResult result = init(options, client);
    switch (result) {
    case HELP:
        try {
            parser.printHelpOn(System.out);
        } catch (final IOException e) {
            e.printStackTrace();
        }
        return null;
    case VERSION:
        System.out.println("Diorite version: " + DioriteCore.class.getPackage().getImplementationVersion()
                + " (MC: " + Core.getMinecraftVersion() + ")");
        return null;
    case RUN:
        return options;
    default:
        return null;
    }
}

From source file:org.eclipse.packagedrone.utils.rpm.build.RpmBuilder.java

private void addResult(final PathName targetName, final Result result, final Consumer<FileEntry> customizer) {
    final FileEntry entry = new FileEntry();

    // set basic file attributes

    entry.setSize(result.getSize());//w  w w. j  a  v a2 s . co m
    entry.setTargetSize(result.getSize());
    entry.setDigest(result.getSha1() != null ? Rpms.toHex(result.getSha1()).toLowerCase() : "");
    entry.setTargetName(targetName);

    // run customizer

    if (customizer != null) {
        customizer.accept(entry);
    }

    // record file entry

    this.files.put(targetName.toString(), entry);
}

From source file:de.fosd.jdime.artifact.file.FileArtifact.java

/**
 * Uses {@link #getJavaFiles()} and applies the given <code>Consumer</code> to every resulting
 * <code>FileArtifact</code> after it being parsed to an <code>ASTNodeArtifact</code>. If an
 * <code>IOException</code> occurs getting the files the method will immediately return. If an
 * <code>IOException</code> occurs parsing a file to an <code>ASTNodeArtifact</code> it will be skipped.
 *
 * @param cons/*  w  ww.j a  v a  2  s  .  co  m*/
 *         the <code>Consumer</code> to apply
 */
private void forAllJavaFiles(Consumer<ASTNodeArtifact> cons) {

    for (FileArtifact child : getJavaFiles()) {
        ASTNodeArtifact childAST;

        try {
            childAST = new ASTNodeArtifact(child);
        } catch (RuntimeException e) {
            LOG.log(Level.WARNING, e, () -> {
                String format = "Could not construct an ASTNodeArtifact from %s. No statistics will be collected for it.";
                return String.format(format, child);
            });

            continue;
        }

        cons.accept(childAST);
    }
}

From source file:org.geoserver.opensearch.rest.AbstractOpenSearchController.java

protected SimpleFeature mapFeatureToSimple(Feature f, SimpleFeatureType targetSchema,
        Consumer<SimpleFeatureBuilder> extraValueBuilder) {
    SimpleFeatureBuilder fb = new SimpleFeatureBuilder(targetSchema);
    List<AttributeDescriptor> attributeDescriptors = targetSchema.getAttributeDescriptors();
    String identifier = f.getIdentifier().getID();
    for (AttributeDescriptor ad : attributeDescriptors) {
        Name sourceName = (Name) ad.getUserData().get(SOURCE_NAME);
        Property p = f.getProperty(sourceName);
        if (p != null) {
            Object value = p.getValue();
            if (value != null) {
                fb.set(ad.getLocalName(), value);
                if (("eo:identifier".equals(ad.getLocalName()) || "eop:identifier".equals(ad.getLocalName()))
                        && value instanceof String) {
                    identifier = (String) value;
                }/*  ww  w  . j a v  a  2s.  c  o  m*/
            }
        }
    }
    extraValueBuilder.accept(fb);

    return fb.buildFeature(identifier);
}