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:de.bayern.gdi.gui.Controller.java

private boolean validateInput() {
    final StringBuilder failed = new StringBuilder();

    Consumer<String> fail = s -> {
        if (failed.length() != 0) {
            failed.append(", ");
        }/*from w ww .  ja  v a 2  s . c o  m*/
        failed.append(s);
    };

    for (DataBean.Attribute attr : this.dataBean.getAttributes()) {
        if (!attr.getType().isEmpty() && !Validator.isValid(attr.getType(), attr.getValue())) {
            fail.accept(attr.getName());
        }
    }

    if (downloadConfig != null) {
        if (serviceTypeChooser.isVisible() && serviceTypeChooser.getValue() instanceof MiscItemModel) {
            fail.accept(I18n.format("gui.dataset"));
        }

        if (atomContainer.isVisible() && atomVariationChooser.getValue() instanceof MiscItemModel) {
            fail.accept(I18n.format("gui.variants"));
        }

        if (referenceSystemChooser.isVisible() && !referenceSystemChooser.getValue().isAvailable()) {
            fail.accept(I18n.format("gui.reference-system"));
        }

        if (basicWFSContainer.isVisible() && dataFormatChooser.isVisible()
                && !dataFormatChooser.getValue().isAvailable()) {
            fail.accept(I18n.format("gui.data-format"));
        }

        if (simpleWFSContainer.isVisible()) {
            ObservableList<Node> children = simpleWFSContainer.getChildren();
            for (Node node : children) {
                if (node instanceof HBox) {
                    HBox hb = (HBox) node;
                    Node n2 = hb.getChildren().get(1);
                    if (n2 instanceof ComboBox) {
                        ComboBox<OutputFormatModel> cb = (ComboBox<OutputFormatModel>) n2;
                        if (!cb.getValue().isAvailable()) {
                            fail.accept(I18n.format("gui.data-format"));
                            break;
                        }
                    }
                }
            }
        }
    }

    if (failed.length() == 0) {
        return true;
    }
    setStatusTextUI(I18n.format("status.validation-fail", failed.toString()));
    return false;
}

From source file:net.dv8tion.jda.core.entities.EntityBuilder.java

public void createGuildSecondPass(long guildId, List<JSONArray> memberChunks) {
    JSONObject guildJson = cachedGuildJsons.remove(guildId);
    Consumer<Guild> secondPassCallback = cachedGuildCallbacks.remove(guildId);
    GuildImpl guildObj = (GuildImpl) api.getGuildMap().get(guildId);

    if (guildObj == null)
        throw new IllegalStateException(
                "Attempted to perform a second pass on an unknown Guild. Guild not in JDA "
                        + "mapping. GuildId: " + guildId);
    if (guildJson == null)
        throw new IllegalStateException(
                "Attempted to perform a second pass on an unknown Guild. No cached Guild "
                        + "for second pass. GuildId: " + guildId);
    if (secondPassCallback == null)
        throw new IllegalArgumentException("No callback provided for the second pass on the Guild!");

    for (JSONArray chunk : memberChunks) {
        createGuildMemberPass(guildObj, chunk);
    }//from   w w  w  . j a va 2  s  .  co  m

    Member owner = guildObj.getMemberById(guildJson.getLong("owner_id"));
    if (owner != null)
        guildObj.setOwner(owner);

    if (guildObj.getOwner() == null)
        WebSocketClient.LOG.fatal("Never set the Owner of the Guild: " + guildObj.getId()
                + " because we don't have the owner User object! How?!");

    JSONArray channels = guildJson.getJSONArray("channels");
    createGuildChannelPass(guildObj, channels);

    JSONArray voiceStates = guildJson.getJSONArray("voice_states");
    createGuildVoiceStatePass(guildObj, voiceStates);

    secondPassCallback.accept(guildObj);
    api.getGuildLock().unlock(guildId);
}

From source file:org.kie.workbench.common.dmn.backend.DMNMarshallerTest.java

public void roundTripUnmarshalThenMarshalUnmarshal(InputStream dmnXmlInputStream,
        Consumer<Graph<?, Node<?, ?>>> checkGraphConsumer) throws IOException {
    DMNMarshaller m = getDMNMarshaller();

    // first unmarshal from DMN XML to Stunner DMN Graph
    @SuppressWarnings("unchecked")
    Graph<?, Node<?, ?>> g = m.unmarshall(null, dmnXmlInputStream);
    checkGraphConsumer.accept(g);

    // round trip to Stunner DMN Graph back to DMN XML
    DiagramImpl diagram = new DiagramImpl("", null);
    diagram.setGraph(g);//from  w w w .  j a  v  a 2 s .  co m

    String mString = m.marshall(diagram);
    LOG.debug(mString);

    // now unmarshal once more, from the marshalled just done above, back again to Stunner DMN Graph to complete check for round-trip
    @SuppressWarnings("unchecked")
    Graph<?, Node<?, ?>> g2 = m.unmarshall(null, new StringInputStream(mString));
    checkGraphConsumer.accept(g2);
}

From source file:blusunrize.immersiveengineering.api.ApiUtils.java

public static boolean raytraceAlongCatenaryRelative(Connection conn,
        Predicate<Triple<BlockPos, Vec3d, Vec3d>> shouldStop, Consumer<Triple<BlockPos, Vec3d, Vec3d>> close,
        Vec3d vStart, Vec3d vEnd) {//w w  w .  j  a va 2s  . c  o  m
    conn.getSubVertices(vStart, vEnd);
    HashMap<BlockPos, Vec3d> halfScanned = new HashMap<>();
    HashSet<BlockPos> done = new HashSet<>();
    HashSet<Triple<BlockPos, Vec3d, Vec3d>> near = new HashSet<>();
    Vec3d across = vEnd.subtract(vStart);
    across = new Vec3d(across.x, 0, across.z);
    double lengthHor = across.length();
    halfScanned.put(conn.start, vStart);
    halfScanned.put(conn.end, vEnd);
    //Raytrace X&Z
    for (int dim = 0; dim <= 2; dim += 2) {
        int start = (int) Math.ceil(Math.min(getDim(vStart, dim), getDim(vEnd, dim)));
        int end = (int) Math.ceil(Math.max(getDim(vStart, dim), getDim(vEnd, dim)));
        for (int i = start; i < end; i++) {
            double factor = (i - getDim(vStart, dim)) / getDim(across, dim);
            Vec3d pos = conn.getVecAt(factor);

            if (handleVec(pos, pos, 0, halfScanned, done, shouldStop, near, conn.start))
                return false;
        }
    }
    //Raytrace Y
    boolean vertical = vStart.x == vEnd.x && vStart.z == vEnd.z;
    if (vertical) {
        for (int y = (int) Math.ceil(Math.min(vStart.y, vEnd.y)); y <= Math
                .floor(Math.max(vStart.y, vEnd.y)); y++) {
            Vec3d pos = new Vec3d(vStart.x, y, vStart.z);
            if (handleVec(pos, pos, 0, halfScanned, done, shouldStop, near, conn.start))
                return false;
        }
    } else {
        double min = conn.catA + conn.catOffsetY + vStart.y;
        for (int i = 0; i < 2; i++) {
            double factor = i == 0 ? 1 : -1;
            double max = i == 0 ? vEnd.y : vStart.y;
            for (int y = (int) Math.ceil(min); y <= Math.floor(max); y++) {
                double yReal = y - vStart.y;
                double posRel;
                Vec3d pos;
                posRel = (factor * acosh((yReal - conn.catOffsetY) / conn.catA) * conn.catA + conn.catOffsetX)
                        / lengthHor;
                pos = new Vec3d(vStart.x + across.x * posRel, y, vStart.z + across.z * posRel);

                if (posRel >= 0 && posRel <= 1
                        && handleVec(pos, pos, 0, halfScanned, done, shouldStop, near, conn.start))
                    return false;
            }
        }
    }
    for (Triple<BlockPos, Vec3d, Vec3d> p : near)
        close.accept(p);
    for (Map.Entry<BlockPos, Vec3d> p : halfScanned.entrySet())
        if (shouldStop.test(new ImmutableTriple<>(p.getKey(), p.getValue(), p.getValue())))
            return false;
    return true;
}

From source file:org.opendaylight.controller.cluster.datastore.shardmanager.ShardManager.java

private void findLocalShard(final String shardName, final ActorRef sender,
        final Consumer<LocalShardFound> onLocalShardFound) {
    Timeout findLocalTimeout = new Timeout(datastoreContextFactory.getBaseDatastoreContext()
            .getShardInitializationTimeout().duration().$times(2));

    Future<Object> futureObj = ask(getSelf(), new FindLocalShard(shardName, true), findLocalTimeout);
    futureObj.onComplete(new OnComplete<Object>() {
        @Override//  www . j  ava 2s  .  com
        public void onComplete(Throwable failure, Object response) {
            if (failure != null) {
                LOG.debug("{}: Received failure from FindLocalShard for shard {}", persistenceId, shardName,
                        failure);
                sender.tell(new Status.Failure(new RuntimeException(
                        String.format("Failed to find local shard %s", shardName), failure)), self());
            } else {
                if (response instanceof LocalShardFound) {
                    getSelf().tell(new RunnableMessage() {
                        @Override
                        public void run() {
                            onLocalShardFound.accept((LocalShardFound) response);
                        }
                    }, sender);
                } else if (response instanceof LocalShardNotFound) {
                    String msg = String.format("Local shard %s does not exist", shardName);
                    LOG.debug("{}: {}", persistenceId, msg);
                    sender.tell(new Status.Failure(new IllegalArgumentException(msg)), self());
                } else {
                    String msg = String.format("Failed to find local shard %s: received response: %s",
                            shardName, response);
                    LOG.debug("{}: {}", persistenceId, msg);
                    sender.tell(new Status.Failure(
                            response instanceof Throwable ? (Throwable) response : new RuntimeException(msg)),
                            self());
                }
            }
        }
    }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
}

From source file:org.opencb.opencga.storage.mongodb.variant.VariantMongoDBAdaptor.java

@Override
public void forEach(Query query, Consumer<? super Variant> action, QueryOptions options) {
    Objects.requireNonNull(action);
    VariantDBIterator variantDBIterator = iterator(query, options);
    while (variantDBIterator.hasNext()) {
        action.accept(variantDBIterator.next());
    }//  www  .ja v  a2  s .  c  om
}

From source file:com.ikanow.aleph2.analytics.services.AnalyticsContext.java

/** Internal utility for completing job output
 *  NOTE IF THE JOB IS NOT TRANSIENT THEN IT SWITCHES THE ENTIRE BUFFER ACROSS
 *  (WHICH WON'T WORK IF THERE ARE >1 JOBS)
 * @param bucket/*from w ww .j  ava 2  s. co m*/
 * @param job
 */
private void switchJobOutputBuffer(final DataBucketBean bucket, final AnalyticThreadJobBean job) {
    final Optional<String> job_name = Optional.of(job)
            .filter(j -> Optionals.of(() -> j.output().is_transient()).orElse(false)).map(j -> j.name());
    final Consumer<IGenericDataService> switchPrimary = s -> {
        getSecondaryBuffer(bucket, Optional.of(job), true, s).ifPresent(curr_secondary -> {
            final CompletableFuture<BasicMessageBean> result = s.switchCrudServiceToPrimaryBuffer(bucket,
                    Optional.of(curr_secondary),
                    IGenericDataService.SECONDARY_PING.equals(curr_secondary)
                            ? Optional.of(IGenericDataService.SECONDARY_PONG) //(primary must have been ping)
                            : Optional.of(IGenericDataService.SECONDARY_PING),
                    job_name);

            // Log on error:
            result.thenAccept(res -> {
                if (!res.success()) {
                    _logger.warn(ErrorUtils.get("Bucket:job {0}:{1} service {2}: {3}", bucket.full_name(),
                            job.name(), s.getClass().getSimpleName(), res.message()));
                }
            });
        });
    };
    if (!_multi_writer.isSet()) {
        setupOutputs(bucket, job);
    }
    _multi_writer.optional().ifPresent(w -> w.getDataServices()
            .forEach(s -> s.getDataService().ifPresent(ss -> switchPrimary.accept(ss))));
}

From source file:org.cc86.MMC.modules.audio.SWTTYProvider.java

@Override
public void uartHandler(final Consumer<Byte[]> out, final BlockingQueue<byte[]> ctrl, final boolean addPrefix) {
    new Thread(() -> {
        InputStream fis = null;//from   w  w w . j  a  va2 s .  c  o  m
        OutputStream fos = null;

        try {
            //final Socket s = new Socket("127.0.0.1", 8888);
            //fis = new FileInputStream();
            if (!new File("/sys/class/softuart/softuart/data").exists()) {
                System.out.println("no running softuart driver, shutting down");
                System.exit(0);
            }

            setup();
            //("/home/pi/codestuff/uartdmp");//
            fos = new FileOutputStream("/sys/class/softuart/softuart/data");
            PrintStream ps = new PrintStream(fos);
            //fos = s.getOutputStream();/*new InputStreamReader(s.getInputStream()*/

            new Thread(() -> {
                FileInputStream br;
                try {
                    byte[] data = new byte[3192];
                    //br = 
                    //br.mark(4096);
                    ByteArrayOutputStream bs = new ByteArrayOutputStream();
                    while (true) {
                        List<Byte> bfr = new ArrayList<Byte>();
                        FileInputStream fi = new FileInputStream("/sys/class/softuart/softuart/data");
                        //Tools.runCmdWithPassthru(new PrintStream(bs), "cat","/sys/class/softuart/softuart/data");

                        int len = fi.read(data);
                        //bs.reset();
                        //int len=data.length;
                        if (len < 0) {
                            try {
                                Thread.sleep(10);
                            } catch (InterruptedException ex) {
                            }
                            continue;
                        }
                        l.trace("data rcvd, len={}" + len);
                        for (int i = 0; i < len; i += 2) {
                            int datapkg = ((data[i] & 0xF0) >>> 4) | ((data[i + 1] & 0xF0));
                            datapkg |= ((data[i + 1] & 0x08) << 5);
                            boolean parity = numberOfSetBits(datapkg) % 2 == 0;
                            l.trace(String.format("%03X", datapkg));
                            bytesReceived++;
                            if (parity) {
                                l.trace(datapkg);
                                bfr.add((byte) (datapkg & 0xff));

                            } else {
                                bytesErrored++;
                            }
                        }
                        out.accept(bfr.toArray(new Byte[0]));

                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException ex) {
                        }
                    }
                } /*catch (FileNotFoundException ex)
                  {
                  ex.printStackTrace();
                  } */catch (IOException ex) //noop-catch killme
                {
                    ex.printStackTrace();
                }
            }).start();//*/
            //BufferedReader bs = new BufferedReader(new InputStreamReader(ctrl));
            while (true) {
                //l.warn("d'arvit");
                byte[] thebyte = ctrl.take();//alphabet[new Random().nextInt(26)] + alphabet[new Random().nextInt(26)] + alphabet[new Random().nextInt(26)] + "\r\n";
                l.trace("SENT_UART:" + Arrays.toString(thebyte));
                StringBuilder sb = new StringBuilder();
                for (Byte pkgbyte : thebyte) {
                    sb.append("\\x").append(String.format("%02X", pkgbyte));
                }
                String echo = sb + "";
                l.trace(echo);
                Tools.runCmdWithPassthru(System.out, "/bin/bash", "-c",
                        "echo -ne '" + echo + "'>/sys/class/softuart/softuart/data");
                //ps.write(new byte[]{thebyte});
                //ps.flush();
                //fos.flush();
                //Thread.sleep(1000);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                //fis.close();
                fos.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }).start();
}

From source file:org.apache.nifi.reporting.util.provenance.ProvenanceEventConsumer.java

public void consumeEvents(final EventAccess eventAccess, final StateManager stateManager,
        final Consumer<List<ProvenanceEventRecord>> consumer) throws ProcessException {

    Long currMaxId = eventAccess.getProvenanceRepository().getMaxEventId();

    if (currMaxId == null) {
        logger.debug("No events to send because no events have been created yet.");
        return;/*w  w  w.jav  a 2s.c o  m*/
    }

    if (firstEventId < 0) {
        Map<String, String> state;
        try {
            state = stateManager.getState(Scope.LOCAL).toMap();
        } catch (IOException e) {
            logger.error("Failed to get state at start up due to:" + e.getMessage(), e);
            return;
        }

        if (state.containsKey(LAST_EVENT_ID_KEY)) {
            firstEventId = Long.parseLong(state.get(LAST_EVENT_ID_KEY)) + 1;
        } else {
            if (END_OF_STREAM.getValue().equals(startPositionValue)) {
                firstEventId = currMaxId;
            }
        }

        if (currMaxId < (firstEventId - 1)) {
            if (BEGINNING_OF_STREAM.getValue().equals(startPositionValue)) {
                logger.warn(
                        "Current provenance max id is {} which is less than what was stored in state as the last queried event, which was {}. This means the provenance restarted its "
                                + "ids. Restarting querying from the beginning.",
                        new Object[] { currMaxId, firstEventId });
                firstEventId = -1;
            } else {
                logger.warn(
                        "Current provenance max id is {} which is less than what was stored in state as the last queried event, which was {}. This means the provenance restarted its "
                                + "ids. Restarting querying from the latest event in the Provenance Repository.",
                        new Object[] { currMaxId, firstEventId });
                firstEventId = currMaxId;
            }
        }
    }

    if (currMaxId == (firstEventId - 1)) {
        logger.debug(
                "No events to send due to the current max id being equal to the last id that was queried.");
        return;
    }

    List<ProvenanceEventRecord> rawEvents;
    List<ProvenanceEventRecord> filteredEvents;
    try {
        rawEvents = eventAccess.getProvenanceEvents(firstEventId, batchSize);
        filteredEvents = filterEvents(rawEvents);
    } catch (final IOException ioe) {
        logger.error("Failed to retrieve Provenance Events from repository due to: " + ioe.getMessage(), ioe);
        return;
    }

    if (rawEvents == null || rawEvents.isEmpty()) {
        logger.debug("No events to send due to 'events' being null or empty.");
        return;
    }

    // Consume while there are more events and not stopped.
    while (rawEvents != null && !rawEvents.isEmpty() && isScheduled()) {

        if (!filteredEvents.isEmpty()) {
            // Executes callback.
            consumer.accept(filteredEvents);
        }

        firstEventId = updateLastEventId(rawEvents, stateManager);

        // Retrieve the next batch
        try {
            rawEvents = eventAccess.getProvenanceEvents(firstEventId, batchSize);
            filteredEvents = filterEvents(rawEvents);
        } catch (final IOException ioe) {
            logger.error("Failed to retrieve Provenance Events from repository due to: " + ioe.getMessage(),
                    ioe);
            return;
        }
    }

}