Java Code Examples for java.util.function.Consumer#andThen()

The following examples show how to use java.util.function.Consumer#andThen() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public static void main(String[] args) {

        Supplier<Pessoa> banco = () -> Pessoa.builder()
                .withNome("Ada")
                .withCidade("Salvador")
                .withPais("Pais")
                .withRg("rg")
                .withCpf("cpf")
                .withEmail("meu-email")
                .build();


        Optional<Pessoa> cache = Optional.ofNullable(null);

        Consumer<Pessoa> println = System.out::println;
        Consumer<Pessoa> log = p -> LOGGER.info("Olha eu estou logando " + p);
        Consumer<Pessoa> auditoria = log.andThen(println);


        Pessoa pessoa = cache.orElseGet(banco);
        auditoria.accept(pessoa);
    }
 
Example 2
private static void consumer(){
    Consumer<String> printResult =
            s -> System.out.println("Result: " + s);
    printResult.accept("10.0");         //prints: Result: 10.0

    printWithPrefixAndPostfix("Result: ", " Great!")
            .accept("10.0");  //prints: Result: 10.0 Great!

    String externalData = "external data";
    Consumer<Person> setRecord =
            p -> p.setRecord(p.getFirstName() + " " +
                    p.getLastName() + ", " + p.getAge() + ", " + externalData);

    Consumer<Person> printRecord =
            p -> System.out.println(p.getRecord());

    Consumer<Person> setRecordThenPrint = setRecord.andThen(printRecord);

    setRecordThenPrint.accept(new Person(42, "Nick", "Samoylov"));
                                     //prints: Nick-Samoylov-42-externalData
}
 
Example 3
@Override
public void customize() {
    if (this.role == null) {
        return;
    }

    Consumer<Archive> keycloakPreparer = (archive) -> {
        archive.as(Secured.class)
                .protect()
                .withRole(this.role);
    };

    Consumer<Archive> preparer = this.jolokia.jolokiaWarPreparer();

    if (preparer == null) {
        preparer = keycloakPreparer;
    } else {
        preparer = preparer.andThen(keycloakPreparer);
    }

    this.jolokia.prepareJolokiaWar(preparer);
}
 
Example 4
@Produces
public Archive jolokiaWar() throws Exception {

    if (this.context == null) {
        this.context = this.fraction.context();
    }

    Archive deployment = this.lookup.artifact(DEPLOYMENT_GAV, DEPLOYMENT_NAME);

    deployment.as(WARArchive.class).setContextRoot(this.context);

    Consumer<Archive> preparer = new ConfigurationValueAccessPreparer(this.jolokiaAccessXML);
    if (this.fraction.jolokiaWarPreparer() != null) {
        preparer = preparer.andThen(this.fraction.jolokiaWarPreparer());
    }

    preparer.accept(deployment);

    return deployment;
}
 
Example 5
Source Project: packagedrone   File: RpmBuilder.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private <T> void addFile ( final String targetName, final T sourcePath, final Consumer<FileEntry> customizer, final int mode, final Instant fileModificationInstant, final RecorderFunction<T> func ) throws IOException
{
    final PathName pathName = PathName.parse ( targetName );

    final long mtime = fileModificationInstant.getEpochSecond ();
    final int inode = this.currentInode++;

    final short smode = (short) ( mode | CpioConstants.C_ISREG );

    final Result result = func.record ( this.recorder, "./" + pathName.toString (), sourcePath, cpioCustomizer ( mtime, inode, smode ) );

    Consumer<FileEntry> c = this::initEntry;
    c = c.andThen ( entry -> {
        entry.setModificationTime ( (int)mtime );
        entry.setInode ( inode );
        entry.setMode ( smode );
    } );

    if ( customizer != null )
    {
        c = c.andThen ( customizer );
    }

    addResult ( pathName, result, c );
}
 
Example 6
/**
 * Queue a username resolve with an asynchronous callback.
 *
 * @param id A {@link UUID} to resolve.
 * @param callback A callback to run after the username is resolved.
 */
public static void resolve(UUID id, @Nullable Consumer<String> callback) {
  final Consumer<String> existing = QUEUE.get(checkNotNull(id));
  if (callback == null) callback = i -> {};

  // If a callback already exists, chain the new one after the existing one
  if (existing != null && callback != existing) {
    callback = existing.andThen(callback);
  }

  QUEUE.put(id, callback);
}
 
Example 7
Source Project: joyrpc   File: Futures.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 把消费者和Future组合成链
 *
 * @param consumer 消费者
 * @param future   Future
 * @param <T>
 * @return 消费者
 */
public static <T> Consumer<AsyncResult<T>> chain(final Consumer<AsyncResult<T>> consumer, final CompletableFuture<T> future) {
    Consumer<AsyncResult<T>> c = consumer == null ? r -> {
    } : consumer;
    return future == null ? c : c.andThen(o -> {
        if (o.isSuccess()) {
            future.complete(o.getResult());
        } else {
            future.completeExceptionally(o.getThrowable());
        }
    });
}
 
Example 8
@Override
public Elevation getElevationForQuery(String queryString) {
  boolean hasExactMatchElevationRules = exactMatchElevationMap.size() != 0;
  if (subsetMatcher.getSubsetCount() == 0) {
    if (!hasExactMatchElevationRules) {
      return null;
    }
    return exactMatchElevationMap.get(analyzeQuery(queryString));
  }
  Collection<String> queryTerms = new ArrayList<>();
  Consumer<CharSequence> termsConsumer = term -> queryTerms.add(term.toString());
  StringBuilder concatTerms = null;
  if (hasExactMatchElevationRules) {
    concatTerms = new StringBuilder();
    termsConsumer = termsConsumer.andThen(concatTerms::append);
  }
  analyzeQuery(queryString, termsConsumer);
  Elevation mergedElevation = null;

  if (hasExactMatchElevationRules) {
    mergedElevation = exactMatchElevationMap.get(concatTerms.toString());
  }

  Iterator<Elevation> elevationIterator = subsetMatcher.findSubsetsMatching(queryTerms);
  while (elevationIterator.hasNext()) {
    Elevation elevation = elevationIterator.next();
    mergedElevation = mergedElevation == null ? elevation : mergedElevation.mergeWith(elevation);
  }

  return mergedElevation;
}
 
Example 9
Source Project: packagedrone   File: RpmBuilder.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private void addDirectory ( final String targetName, final int mode, final Instant modInstant, final Consumer<FileEntry> customizer ) throws IOException
{
    final PathName pathName = PathName.parse ( targetName );

    final long mtime = modInstant.getEpochSecond ();
    final int inode = this.currentInode++;

    final short smode = (short) ( mode | CpioConstants.C_ISDIR );

    final Result result = this.recorder.addDirectory ( "./" + pathName.toString (), cpioCustomizer ( mtime, inode, smode ) );

    Consumer<FileEntry> c = this::initEntry;
    c = c.andThen ( entry -> {
        entry.setModificationTime ( (int)mtime );
        entry.setInode ( inode );
        entry.setMode ( smode );
        entry.setSize ( 0 );
        entry.setTargetSize ( 4096 );
    } );

    if ( customizer != null )
    {
        c = c.andThen ( customizer );
    }

    addResult ( pathName, result, c );
}
 
Example 10
Source Project: packagedrone   File: RpmBuilder.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private void addSymbolicLink ( final String targetName, final String linkTo, final int mode, final Instant modInstant, final Consumer<FileEntry> customizer ) throws IOException
{
    final PathName pathName = PathName.parse ( targetName );

    final long mtime = modInstant.getEpochSecond ();
    final int inode = this.currentInode++;

    final short smode = (short) ( mode | CpioConstants.C_ISLNK );

    final Result result = this.recorder.addSymbolicLink ( "./" + pathName.toString (), linkTo, cpioCustomizer ( mtime, inode, smode ) );

    Consumer<FileEntry> c = this::initEntry;
    c = c.andThen ( entry -> {
        entry.setModificationTime ( (int)mtime );
        entry.setInode ( inode );
        entry.setMode ( smode );
        entry.setSize ( result.getSize () );
        entry.setTargetSize ( result.getSize () );
        entry.setLinkTo ( linkTo );
    } );

    if ( customizer != null )
    {
        c = c.andThen ( customizer );
    }

    addResult ( pathName, result, c );
}
 
Example 11
Source Project: j2objc   File: ConsumerTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testAndThen_null() throws Exception {
  Consumer<StringBuilder> one = s -> s.append("one");
  try {
    one.andThen(null);
    fail();
  } catch (NullPointerException expected) {}
}
 
Example 12
Source Project: jphp   File: DateTimeParser.java    License: Apache License 2.0 5 votes vote down vote up
private StringNode(String value, boolean caseSensitive, Consumer<DateTimeParserContext> applier) {
    super(DateTimeTokenizer.Symbol.STRING, value.length());
    this.value = value;
    this.matcher = caseSensitive ? String::equals : String::equalsIgnoreCase;
    this.applier = applier == empty() ?
            cursorIncrementer() :
            applier.andThen(cursorIncrementer());
}
 
Example 13
Source Project: reactor-netty   File: HttpClientConnect.java    License: Apache License 2.0 4 votes vote down vote up
Publisher<Void> requestWithBody(HttpClientOperations ch) {
	try {
		ch.resourceUrl = toURI.toExternalForm();

		UriEndpoint uri = toURI;
		HttpHeaders headers = ch.getNettyRequest()
		                        .setUri(uri.getPathAndQuery())
		                        .setMethod(method)
		                        .setProtocolVersion(HttpVersion.HTTP_1_1)
		                        .headers();

		ch.path = HttpOperations.resolvePath(ch.uri());

		if (defaultHeaders != null) {
			headers.set(defaultHeaders);
		}

		if (!headers.contains(HttpHeaderNames.USER_AGENT)) {
			headers.set(HttpHeaderNames.USER_AGENT, USER_AGENT);
		}

		SocketAddress remoteAddress = uri.getRemoteAddress();
		if (!headers.contains(HttpHeaderNames.HOST)) {
			headers.set(HttpHeaderNames.HOST, resolveHostHeaderValue(remoteAddress));
		}

		if (!headers.contains(HttpHeaderNames.ACCEPT)) {
			headers.set(HttpHeaderNames.ACCEPT, ALL);
		}

		ch.followRedirectPredicate(followRedirectPredicate);

		if (!Objects.equals(method, HttpMethod.GET) &&
					!Objects.equals(method, HttpMethod.HEAD) &&
					!Objects.equals(method, HttpMethod.DELETE) &&
					!headers.contains(HttpHeaderNames.CONTENT_LENGTH)) {
			ch.chunkedTransfer(true);
		}

		ch.listener().onStateChange(ch, HttpClientState.REQUEST_PREPARED);
		if (websocketClientSpec != null) {
			Mono<Void> result =
					Mono.fromRunnable(() -> ch.withWebsocketSupport(websocketClientSpec, compress));
			if (handler != null) {
				result = result.thenEmpty(Mono.fromRunnable(() -> Flux.concat(handler.apply(ch, ch))));
			}
			return result;
		}

		Consumer<HttpClientRequest> consumer = null;
		if (fromURI != null && !toURI.equals(fromURI)) {
			if (handler instanceof RedirectSendHandler) {
				headers.remove(HttpHeaderNames.EXPECT)
				       .remove(HttpHeaderNames.COOKIE)
				       .remove(HttpHeaderNames.AUTHORIZATION)
				       .remove(HttpHeaderNames.PROXY_AUTHORIZATION);
			}
			else {
				consumer = request ->
				        request.requestHeaders()
				               .remove(HttpHeaderNames.EXPECT)
				               .remove(HttpHeaderNames.COOKIE)
				               .remove(HttpHeaderNames.AUTHORIZATION)
				               .remove(HttpHeaderNames.PROXY_AUTHORIZATION);
			}
		}
		if (this.redirectRequestConsumer != null) {
			consumer = consumer != null ? consumer.andThen(this.redirectRequestConsumer) : this.redirectRequestConsumer;
		}
		ch.redirectRequestConsumer(consumer);
		return handler != null ? handler.apply(ch, ch) : ch.send();
	}
	catch (Throwable t) {
		return Mono.error(t);
	}
}
 
Example 14
Source Project: jeka   File: JkConsumers.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Chains this underlying {@link Consumer} with the specified one. The specified element will
 * be executed at the beginning.
 */
public JkConsumers<T, P> prepend(Consumer<T> appendedConsumer) {
    consumer = appendedConsumer.andThen(consumer);
    return this;
}
 
Example 15
Source Project: consulo   File: MapBasedTree.java    License: Apache License 2.0 4 votes vote down vote up
public void onRemove(@Nonnull Consumer<? super N> consumer) {
  Consumer old = nodeRemoved;
  nodeRemoved = old == null ? consumer : old.andThen(consumer);
}
 
Example 16
Source Project: consulo   File: MapBasedTree.java    License: Apache License 2.0 4 votes vote down vote up
public void onInsert(@Nonnull Consumer<? super N> consumer) {
  Consumer old = nodeInserted;
  nodeInserted = old == null ? consumer : old.andThen(consumer);
}
 
Example 17
/**
 * to perform when the document is loaded
 * 
 * @param onDescriptorLoaded
 */
public void addOnLoaded(Consumer<PdfDocumentDescriptor> onDescriptorLoaded) {
    this.onLoaded = onDescriptorLoaded.andThen(this.onLoaded);
}