List of usage examples for java.util.function Consumer accept
void accept(T t);
From source file:org.openstreetmap.josm.tools.Utils.java
/** * Helper method to replace the "<code>instanceof</code>-check and cast" pattern. * Checks if an object is instance of class T and performs an action if that * is the case./*w ww . jav a 2 s .c o m*/ * Syntactic sugar to avoid typing the class name two times, when one time * would suffice. * @param <T> the type for the instanceof check and cast * @param o the object to check and cast * @param klass the class T * @param consumer action to take when o is and instance of T * @since 12604 */ @SuppressWarnings("unchecked") public static <T> void instanceOfThen(Object o, Class<T> klass, Consumer<? super T> consumer) { if (klass.isInstance(o)) { consumer.accept((T) o); } }
From source file:org.codice.alliance.libs.mpegts.MpegTsDecoderImpl.java
private void handleElementaryStream(MTSPacket mtsPacket, int pid, Consumer<PESPacket> callback) { if (mtsPacket.isContainsPayload()) { final PMTSection.PMTStream stream = programElementaryStreams.get(pid); final byte[] currentPacketBytes = currentPacketBytesByStream.get(pid); final boolean startingNewPacket = mtsPacket.isPayloadUnitStartIndicator(); final boolean currentPacketToHandle = currentPacketBytes != null; final boolean reachedEndOfCurrentPacket = startingNewPacket && currentPacketToHandle; final byte[] payloadBytes = getByteBufferAsBytes(mtsPacket.getPayload()); if (reachedEndOfCurrentPacket) { callback.accept( new PESPacket(currentPacketBytes, MpegStreamType.lookup(stream.getStreamType()), pid)); currentPacketBytesByStream.put(pid, payloadBytes); } else if (startingNewPacket) { currentPacketBytesByStream.put(pid, payloadBytes); } else if (currentPacketToHandle) { final byte[] concatenatedPacket = ArrayUtils.addAll(currentPacketBytes, payloadBytes); currentPacketBytesByStream.put(pid, concatenatedPacket); }/* w w w . j av a 2 s . c o m*/ } }
From source file:org.ligoj.app.plugin.vm.aws.VmAwsSnapshotResourceTest.java
private VmSnapshotStatus mockStatus() { final VmSnapshotStatus status = new VmSnapshotStatus(); status.setAuthor("ligoj-admin"); status.setStop(true);/*from www .jav a 2s . c o m*/ status.setStart(DateUtils.newCalendar().getTime()); status.setLocked(subscriptionRepository.findOneExpected(subscription)); status.setOperation(SnapshotOperation.CREATE); Mockito.when(resource.snapshotResource.getTask(subscription)).thenReturn(status); Mockito.when(resource.snapshotResource.nextStep(ArgumentMatchers.eq(subscription), ArgumentMatchers.argThat(new ArgumentMatcher<Consumer<VmSnapshotStatus>>() { @Override public boolean matches(final Consumer<VmSnapshotStatus> f) { f.accept(status); return true; } }))).thenReturn(null); Mockito.when(resource.snapshotResource.endTask(ArgumentMatchers.eq(subscription), ArgumentMatchers.eq(true), ArgumentMatchers.argThat(new ArgumentMatcher<Consumer<VmSnapshotStatus>>() { @Override public boolean matches(final Consumer<VmSnapshotStatus> f) { f.accept(status); status.setFailed(true); status.setEnd(new Date()); return true; } }))).thenReturn(null); Mockito.when( resource.snapshotResource.endTask(ArgumentMatchers.eq(subscription), ArgumentMatchers.eq(false), ArgumentMatchers.argThat(new ArgumentMatcher<Consumer<VmSnapshotStatus>>() { @Override public boolean matches(final Consumer<VmSnapshotStatus> f) { f.accept(status); status.setEnd(new Date()); return true; } }))) .thenReturn(null); return status; }
From source file:org.mimacom.sample.integration.patterns.user.service.integration.BulkHeadedSearchServiceIntegration.java
public void indexUserSlow(User user, int waitTime, Consumer<Void> successConsumer, Consumer<Throwable> failureConsumer) { LOG.info("[SLOW!] going to send request to index user '{}' '{}'", user.getFirstName(), user.getLastName()); HttpEntity<User> requestEntity = new HttpEntity<>(user); ListenableFuture<ResponseEntity<String>> listenableFuture = this.asyncIndexRestTemplate.postForEntity( this.searchServiceUrl + "/index?waitTime={waitTime}", requestEntity, String.class, waitTime); listenableFuture.addCallback(result -> { LOG.info("[SLOW!] 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 a2 s . co m*/ }
From source file:io.github.valters.xsdiff.format.SemanticDiffFormatter.java
private void printAttributeHighlights(final String text, final Set<String> fragments, final Consumer<String> toPrint) { final TrieBuilder trie = Trie.builder().removeOverlaps(); for (final String part : fragments) { trie.addKeyword(part);// w w w.j a v a2s . com } final Collection<Emit> emits = trie.build().parseText(text); int prevFragment = 0; for (final Emit emit : emits) { final String clearPartBefore = text.substring(prevFragment, emit.getStart()); output.clearPart(clearPartBefore); final String fragText = emit.getKeyword(); toPrint.accept(fragText); prevFragment = emit.getEnd() + 1; } final String clearPartAfter = text.substring(prevFragment, text.length()); output.clearPart(clearPartAfter); }
From source file:com.antonjohansson.svncommit.core.utils.Bash.java
/** {@inheritDoc} */ @Override/*from ww w. j a v a 2 s. co m*/ public void executeAndPipeOutput(Consumer<String> onData, Consumer<String> onError, Consumer<Boolean> onComplete, String... commandLines) { File scriptFile = getTemporaryScriptFile(asList(commandLines)); Process process = execute(path, scriptFile); try (InputStream logStream = process.getInputStream(); InputStream errorStream = process.getErrorStream()) { while (isAvailable(process, logStream, errorStream)) { if (logStream.available() > 0) { accept(onData, logStream); } if (errorStream.available() > 0) { accept(onError, errorStream); } } int exitValue = process.exitValue(); onComplete.accept(exitValue == 0); } catch (IOException e) { throw new RuntimeException("Could not execute temporary bash script", e); } }
From source file:edu.wustl.lookingglass.community.CommunityRepository.java
public Future<?> sync(Consumer<CommunityRepositorySyncStatus> runWhenDone) { return ThreadHelper.runInBackground(() -> { CommunityRepositorySyncStatus status = this.syncRepo(); if (runWhenDone != null) { runWhenDone.accept(status); }/*w w w . j a va 2s . c om*/ }); }
From source file:de.pixida.logtest.designer.automaton.AutomatonEdge.java
private Node createCheckBoxInput(final String propertyName, final Boolean initialValue, final Consumer<Boolean> applyValue) { final CheckBox result = new CheckBox(propertyName); result.setSelected(BooleanUtils.isTrue(initialValue)); result.setOnAction(event -> {/*from w ww .j av a2 s. c o m*/ applyValue.accept(result.isSelected()); this.getGraph().handleChange(); }); return result; }
From source file:org.pac4j.vertx.StatelessPac4jAuthHandlerIntegrationTest.java
private void testResourceAccess(final String url, final Optional<String> credentialsHeader, final int expectedHttpStatus, final Consumer<String> bodyValidator) throws Exception { startWebServer();// w w w . ja v a 2 s .c o m HttpClient client = vertx.createHttpClient(); // Attempt to get a private url final HttpClientRequest request = client.get(8080, "localhost", url); credentialsHeader.ifPresent(header -> request.putHeader(AUTH_HEADER_NAME, header)); // This should get the desired result straight away rather than operating through redirects request.handler(response -> { assertEquals(expectedHttpStatus, response.statusCode()); response.bodyHandler(body -> { final String bodyContent = body.toString(); bodyValidator.accept(bodyContent); testComplete(); }); }); request.end(); await(1, TimeUnit.SECONDS); }
From source file:org.eclipse.jgit.attributes.merge.MergeGitAttributeTest.java
public Git createRepositoryBinaryConflict(Consumer<Git> initialCommit, Consumer<Git> leftCommit, Consumer<Git> rightCommit) throws NoFilepatternException, GitAPIException, NoWorkTreeException, IOException { // Set up a git whith conflict commits on images Git git = new Git(db); // First commit initialCommit.accept(git); git.add().addFilepattern(".").call(); RevCommit firstCommit = git.commit().setAll(true).setMessage("initial commit adding git attribute file") .call();/*from w w w .ja va 2 s .c om*/ // Create branch and add an icon Checked_Boxe (enabled_checked) createBranch(firstCommit, REFS_HEADS_LEFT); checkoutBranch(REFS_HEADS_LEFT); leftCommit.accept(git); git.add().addFilepattern(".").call(); git.commit().setMessage("Left").call(); // Create a second branch from master Unchecked_Boxe checkoutBranch(REFS_HEADS_MASTER); createBranch(firstCommit, REFS_HEADS_RIGHT); checkoutBranch(REFS_HEADS_RIGHT); rightCommit.accept(git); git.add().addFilepattern(".").call(); git.commit().setMessage("Right").call(); checkoutBranch(REFS_HEADS_LEFT); return git; }