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

The following examples show how to use java.util.function.Function#andThen() . 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
Source File: PathResourceLookupFunctionTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void composeResourceLookupFunction() throws Exception {
	ClassPathResource defaultResource = new ClassPathResource("response.txt", getClass());

	Function<ServerRequest, Optional<Resource>> lookupFunction =
			new PathResourceLookupFunction("/resources/**",
					new ClassPathResource("org/springframework/web/servlet/function/"));

	Function<ServerRequest, Optional<Resource>> customLookupFunction =
			lookupFunction.andThen((Optional<Resource> optionalResource) -> {
				if (optionalResource.isPresent()) {
					return optionalResource;
				}
				else {
					return Optional.of(defaultResource);
				}
			});

	MockHttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/resources/foo");
	ServerRequest request = new DefaultServerRequest(servletRequest, Collections.emptyList());

	Optional<Resource> result = customLookupFunction.apply(request);
	assertTrue(result.isPresent());

	assertEquals(defaultResource.getFile(), result.get().getFile());
}
 
Example 2
Source File: Chapter04Functional.java    From Java-11-Cookbook-Second-Edition with MIT License 6 votes vote down vote up
private static void compose2() {
    //Function<Integer, Double> multiplyBy30 = i -> i * 30d;
    Function<Integer, Double> multiplyBy30 = createMultiplyBy(30d);
    System.out.println(multiplyBy30.apply(1)); //prints: 30

    //Function<Double,Double> subtract7 = d-> d - 7.;
    Function<Double,Double> subtract7 = createSubtract(7.0);
    System.out.println(subtract7.apply(10.0));  //prints: 3.0

    Function<Integer, Double> multiplyBy30AndSubtract7 = subtract7.compose(multiplyBy30);
    System.out.println(multiplyBy30AndSubtract7.apply(1)); //prints: 23.0

    multiplyBy30AndSubtract7 = multiplyBy30.andThen(subtract7);
    System.out.println(multiplyBy30AndSubtract7.apply(1)); //prints: 23.0

    Function<Integer, Double> multiplyBy30Subtract7Twice = subtract7.compose(multiplyBy30).andThen(subtract7);
    System.out.println(multiplyBy30Subtract7Twice.apply(1));  //prints: 16

}
 
Example 3
Source File: Schedulers.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
/**
 * Add or replace a named scheduling {@link Function decorator}. With subsequent calls
 * to this method, the onScheduleHook hook can be a composite of several sub-hooks, each
 * with a different key.
 * <p>
 * The sub-hook is a {@link Function} taking the scheduled {@link Runnable}.
 * It returns the decorated {@link Runnable}.
 *
 * @param key the key under which to set up the onScheduleHook sub-hook
 * @param decorator the {@link Runnable} decorator to add (or replace, if key is already present)
 * @see #resetOnScheduleHook(String)
 * @see #resetOnScheduleHooks()
 */
public static void onScheduleHook(String key, Function<Runnable, Runnable> decorator) {
	synchronized (onScheduleHooks) {
		onScheduleHooks.put(key, decorator);
		Function<Runnable, Runnable> newHook = null;
		for (Function<Runnable, Runnable> function : onScheduleHooks.values()) {
			if (newHook == null) {
				newHook = function;
			}
			else {
				newHook = newHook.andThen(function);
			}
		}
		onScheduleHook = newHook;
	}
}
 
Example 4
Source File: JsonNodeConfigurationFactoryProvider.java    From bootique with Apache License 2.0 6 votes vote down vote up
protected JsonNode loadConfiguration(Map<String, String> properties) {

        // hopefully sharing the mapper between parsers is safe... Does it
        // change the state during parse?
        ObjectMapper textToJsonMapper = jacksonService.newObjectMapper();
        Map<ParserType, Function<InputStream, Optional<JsonNode>>> parsers = new EnumMap<>(ParserType.class);
        parsers.put(ParserType.YAML, new JsonNodeYamlParser(textToJsonMapper));
        parsers.put(ParserType.JSON, new JsonNodeJsonParser(textToJsonMapper));

        Function<URL, Optional<JsonNode>> parser = new MultiFormatJsonNodeParser(parsers, bootLogger);

        BinaryOperator<JsonNode> singleConfigMerger = new InPlaceLeftHandMerger(bootLogger);

        Function<JsonNode, JsonNode> overrider = andCliOptionOverrider(identity(), parser, singleConfigMerger);

        if (!properties.isEmpty()) {
            overrider = overrider.andThen(new InPlaceMapOverrider(properties));
        }

        return JsonNodeConfigurationBuilder.builder()
                .parser(parser)
                .merger(singleConfigMerger)
                .resources(configurationSource)
                .overrider(overrider)
                .build();
    }
 
Example 5
Source File: EitherInstances.java    From cyclops with Apache License 2.0 5 votes vote down vote up
@Override
public <T> Higher<Higher<either, L>, T> handleErrorWith(Function<? super L, ? extends Higher<Higher<either, L>, ? extends T>> fn, Higher<Higher<either, L>, T> ds) {
    Function<? super L, ? extends Either<L, T>> fn2 = fn.andThen(s -> {

        Higher<Higher<either, L>, T> x = (Higher<Higher<either, L>, T>) s;
        Either<L, T> r = narrowK(x);
        return r;
    });
    return narrowK(ds).flatMapLeftToRight(fn2);
}
 
Example 6
Source File: TestPublisher.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
@Nullable
private static <T> Function<Subscriber<? super T>, Subscriber<? super T>>
andThen(@Nullable final Function<Subscriber<? super T>, Subscriber<? super T>> first,
        @Nullable final Function<Subscriber<? super T>, Subscriber<? super T>> second) {
    if (first == null) {
        return second;
    }
    if (second == null) {
        return first;
    }
    return first.andThen(second);
}
 
Example 7
Source File: TestCompletable.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
@Nullable
private static Function<Subscriber, Subscriber>
andThen(@Nullable final Function<Subscriber, Subscriber> first,
        @Nullable final Function<Subscriber, Subscriber> second) {
    if (first == null) {
        return second;
    }
    if (second == null) {
        return first;
    }
    return first.andThen(second);
}
 
Example 8
Source File: LazyEitherInstances.java    From cyclops with Apache License 2.0 5 votes vote down vote up
@Override
public <T> Higher<Higher<either, L>, T> handleErrorWith(Function<? super L, ? extends Higher<Higher<either, L>, ? extends T>> fn, Higher<Higher<either, L>, T> ds) {
    Function<? super L, ? extends Either<L, T>> fn2 = fn.andThen(s -> {

        Higher<Higher<either, L>, T> x = (Higher<Higher<either, L>, T>)s;
        Either<L, T> r = narrowK(x);
        return r;
    });
    return narrowK(ds).flatMapLeftToRight(fn2);
}
 
Example 9
Source File: StandardFunctionalInterfaces.java    From Learn-Java-12-Programming with MIT License 5 votes vote down vote up
private static void function(){
    Function<Integer, Double> multiplyByTen = i -> i * 10.0;
    System.out.println(multiplyByTen.apply(1)); //prints: 10.0

    Supplier<Integer> supply7 = () -> 7;
    Function<Integer, Double> multiplyByFive = i -> i * 5.0;
    Consumer<String> printResult = printWithPrefixAndPostfix("Result: ", " Great!");
    printResult.accept(multiplyByFive.apply(supply7.get()).toString()); //prints: Result: 35.0 Great!

    Function<Double, Long> divideByTwo = d -> Double.valueOf(d / 2.).longValue();
    Function<Long, String> incrementAndCreateString = l -> String.valueOf(l + 1);
    Function<Double, String> divideByTwoIncrementAndCreateString = divideByTwo.andThen(incrementAndCreateString);
    printResult.accept(divideByTwoIncrementAndCreateString.apply(4.));     //prints: Result: 3 Great!

    divideByTwoIncrementAndCreateString = incrementAndCreateString.compose(divideByTwo);
    printResult.accept(divideByTwoIncrementAndCreateString.apply(4.));  //prints: Result: 3 Great!

    Function<Double, Double> multiplyByTwo = d -> d * 2.0;
    System.out.println(multiplyByTwo.apply(2.));  //prints: 4.0

    Function<Double, Long> subtract7 = d -> Math.round(d - 7);
    System.out.println(subtract7.apply(11.0));   //prints: 4

    long r = multiplyByTwo.andThen(subtract7).apply(2.);
    System.out.println(r);                          //prints: -3

    multiplyByTwo = Function.identity();
    System.out.println(multiplyByTwo.apply(2.));  //prints: 2.0

    r = multiplyByTwo.andThen(subtract7).apply(2.);
    System.out.println(r);                          //prints: -5
}
 
Example 10
Source File: TemplateBasedQueryParameterSetterFactory.java    From spring-data-jpa-extra with Apache License 2.0 5 votes vote down vote up
private static QueryParameterSetter createSetter(Function<Object[], Object> valueExtractor, StringQuery.ParameterBinding binding,
                                                 @Nullable JpaParameters.JpaParameter parameter) {

    TemporalType temporalType = parameter != null && parameter.isTemporalParameter() //
            ? parameter.getRequiredTemporalType() //
            : null;

    return new QueryParameterSetter.NamedOrIndexedQueryParameterSetter(valueExtractor.andThen(binding::prepare),
            ParameterImpl.of(parameter, binding), temporalType);
}
 
Example 11
Source File: SummaryBuilder.java    From PaySim with GNU General Public License v3.0 5 votes vote down vote up
private static double objectiveFunctionSteps(StepsProfiles targetStepsProfiles, StepsProfiles simulationStepsProfiles, StringBuilder summaryBuilder) {
    Map<String, Function<StepActionProfile, Double>> statExtractor = new HashMap<>();
    Function<StepActionProfile, Integer>  getCount = StepActionProfile::getCount;
    Function<StepActionProfile, Double> getCountDouble = getCount.andThen(Integer::doubleValue);

    statExtractor.put("Average amount", StepActionProfile::getAvgAmount);
    statExtractor.put("Std amount", StepActionProfile::getStdAmount);
    statExtractor.put("Count", getCountDouble);

    double totalNRMSE = 0;
    summaryBuilder.append(SEPARATOR);
    summaryBuilder.append(Output.EOL_CHAR);
    for (String estimator: statExtractor.keySet()) {
        Map<String, ArrayList<Double>> targetSeries = targetStepsProfiles.computeSeries(statExtractor.get(estimator));
        Map<String, ArrayList<Double>> simulationSeries = simulationStepsProfiles.computeSeries(statExtractor.get(estimator));
        for (String action : ActionTypes.getActions()) {
            ArrayList<Double> unitTarget = targetSeries.get(action);
            ArrayList<Double> unitSimulation = simulationSeries.get(action);
            double NRMSE = computeNRMSE(unitTarget, unitSimulation);

            ArrayList<String> errorLine = new ArrayList<>();
            errorLine.add(estimator);
            errorLine.add(action);
            errorLine.add(Output.fastFormatDouble(Output.PRECISION_OUTPUT, NRMSE));

            buildLineTable(errorLine, summaryBuilder);

            totalNRMSE += NRMSE;
        }
        summaryBuilder.append(SEPARATOR);
        summaryBuilder.append(Output.EOL_CHAR);
    }

    return totalNRMSE;
}
 
Example 12
Source File: PathResourceLookupFunctionTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void composeResourceLookupFunction() throws Exception {
	ClassPathResource defaultResource = new ClassPathResource("response.txt", getClass());

	Function<ServerRequest, Mono<Resource>> lookupFunction =
			new PathResourceLookupFunction("/resources/**",
					new ClassPathResource("org/springframework/web/reactive/function/server/"));

	Function<ServerRequest, Mono<Resource>> customLookupFunction =
			lookupFunction.andThen(resourceMono -> resourceMono
							.switchIfEmpty(Mono.just(defaultResource)));

	MockServerRequest request = MockServerRequest.builder()
			.uri(new URI("http://localhost/resources/foo"))
			.build();

	Mono<Resource> result = customLookupFunction.apply(request);
	StepVerifier.create(result)
			.expectNextMatches(resource -> {
				try {
					return defaultResource.getFile().equals(resource.getFile());
				}
				catch (IOException ex) {
					return false;
				}
			})
			.expectComplete()
			.verify();
}
 
Example 13
Source File: Hooks.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Nullable
@SuppressWarnings("unchecked")
static Function<Publisher, Publisher> createOrUpdateOpHook(Collection<Function<? super Publisher<Object>, ? extends Publisher<Object>>> hooks) {
	Function<Publisher, Publisher> composite = null;
	for (Function<? super Publisher<Object>, ? extends Publisher<Object>> function : hooks) {
		Function<? super Publisher, ? extends Publisher> op = (Function<? super Publisher, ? extends Publisher>) function;
		if (composite != null) {
			composite = composite.andThen(op);
		}
		else {
			composite = (Function<Publisher, Publisher>) op;
		}
	}
	return composite;
}
 
Example 14
Source File: AuthenticationClientDefinitions.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
static ResourceDefinition getAuthenticationContextDefinition() {
    AttributeDefinition[] attributes = new AttributeDefinition[] { CONTEXT_EXTENDS, MATCH_RULES };

    TrivialAddHandler<AuthenticationContext> add = new TrivialAddHandler<AuthenticationContext>(AuthenticationContext.class, attributes, AUTHENTICATION_CONTEXT_RUNTIME_CAPABILITY) {

        @Override
        protected ValueSupplier<AuthenticationContext> getValueSupplier(ServiceBuilder<AuthenticationContext> serviceBuilder, OperationContext context, ModelNode model)
                throws OperationFailedException {
            String parent = CONTEXT_EXTENDS.resolveModelAttribute(context, model).asStringOrNull();
            Supplier<AuthenticationContext> parentSupplier;
            if (parent != null) {
                InjectedValue<AuthenticationContext> parentInjector = new InjectedValue<>();

                serviceBuilder.addDependency(context.getCapabilityServiceName(
                        RuntimeCapability.buildDynamicCapabilityName(AUTHENTICATION_CONTEXT_CAPABILITY, parent), AuthenticationContext.class),
                        AuthenticationContext.class, parentInjector);

                parentSupplier = parentInjector::getValue;
            } else {
                parentSupplier = AuthenticationContext::empty;
            }

            Function<AuthenticationContext, AuthenticationContext> authContext = Function.identity();

            if (model.hasDefined(ElytronDescriptionConstants.MATCH_RULES)) {
                List<ModelNode> nodes = model.require(ElytronDescriptionConstants.MATCH_RULES).asList();
                for (ModelNode current : nodes) {
                    String authenticationConfiguration = AUTHENTICATION_CONFIGURATION.resolveModelAttribute(context, current).asStringOrNull();
                    String sslContext = SSL_CONTEXT.resolveModelAttribute(context, current).asStringOrNull();
                    if (authenticationConfiguration == null && sslContext == null) {
                        continue;
                    }

                    Function<MatchRule, MatchRule> matchRule = ignored -> MatchRule.ALL;

                    String abstractType = MATCH_ABSTRACT_TYPE.resolveModelAttribute(context, current).asStringOrNull();
                    String abstractTypeAuthority = MATCH_ABSTRACT_TYPE_AUTHORITY.resolveModelAttribute(context, current).asStringOrNull();
                    matchRule = abstractType != null || abstractTypeAuthority != null ? matchRule.andThen(m -> m.matchAbstractType(abstractType, abstractTypeAuthority))  : matchRule;

                    ModelNode host = MATCH_HOST.resolveModelAttribute(context, current);
                    matchRule = host.isDefined() ? matchRule.andThen(m -> m.matchHost(host.asString())) : matchRule;

                    ModelNode localSecurityDomain = MATCH_LOCAL_SECURITY_DOMAIN.resolveModelAttribute(context, current);
                    matchRule = localSecurityDomain.isDefined() ? matchRule.andThen(m -> m.matchLocalSecurityDomain(localSecurityDomain.asString())) : matchRule;

                    ModelNode matchNoUser = MATCH_NO_USER.resolveModelAttribute(context, current);
                    matchRule = matchNoUser.asBoolean() ? matchRule.andThen(m -> m.matchNoUser()) : matchRule;

                    ModelNode path = MATCH_PATH.resolveModelAttribute(context, current);
                    matchRule = path.isDefined() ? matchRule.andThen(m -> m.matchPath(path.asString())) : matchRule;

                    ModelNode port = MATCH_PORT.resolveModelAttribute(context, current);
                    matchRule = port.isDefined() ? matchRule.andThen(m -> m.matchPort(port.asInt())) : matchRule;

                    ModelNode protocol = MATCH_PROTOCOL.resolveModelAttribute(context, current);
                    matchRule = protocol.isDefined() ? matchRule.andThen(m -> m.matchProtocol(protocol.asString())) : matchRule;

                    ModelNode urn = MATCH_URN.resolveModelAttribute(context, current);
                    matchRule = urn.isDefined() ? matchRule.andThen(m -> m.matchUrnName(urn.asString())) : matchRule;

                    ModelNode user = MATCH_USER.resolveModelAttribute(context, current);
                    matchRule = user.isDefined() ? matchRule.andThen(m -> m.matchUser(user.asString())) : matchRule;

                    final Function<MatchRule, MatchRule> finalMatchRule = matchRule;
                    Supplier<MatchRule> matchRuleSuppler = new OneTimeSupplier<>(() -> finalMatchRule.apply(null));

                    if (authenticationConfiguration != null) {
                        InjectedValue<AuthenticationConfiguration> authenticationConfigurationInjector = new InjectedValue<>();

                        serviceBuilder.addDependency(context.getCapabilityServiceName(
                                RuntimeCapability.buildDynamicCapabilityName(AUTHENTICATION_CONFIGURATION_CAPABILITY, authenticationConfiguration), AuthenticationConfiguration.class),
                                AuthenticationConfiguration.class, authenticationConfigurationInjector);

                        authContext = authContext.andThen(a -> a.with(matchRuleSuppler.get(), authenticationConfigurationInjector.getValue()));
                    }

                    if (sslContext != null) {
                        InjectedValue<SSLContext> sslContextInjector = new InjectedValue<>();

                        serviceBuilder.addDependency(context.getCapabilityServiceName(
                                RuntimeCapability.buildDynamicCapabilityName(SSL_CONTEXT_CAPABILITY, sslContext), SSLContext.class),
                                SSLContext.class, sslContextInjector);

                        authContext = authContext.andThen(a -> a.withSsl(matchRuleSuppler.get(), sslContextInjector::getValue));
                    }
                }
            }

            final Function<AuthenticationContext, AuthenticationContext> finalContext = authContext;
            return () -> finalContext.apply(parentSupplier.get());
        }

    };

    return new TrivialResourceDefinition(ElytronDescriptionConstants.AUTHENTICATION_CONTEXT, add, attributes,
            AUTHENTICATION_CONTEXT_RUNTIME_CAPABILITY);
}
 
Example 15
Source File: SessionImpl.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
public List<Schema> getSchemas() {
    Function<Row, String> rowToName = r -> r.getValue(0, new StringValueFactory());
    Function<Row, Schema> rowToSchema = rowToName.andThen(n -> new SchemaImpl(this.session, this, n));
    return this.session.query(this.xbuilder.buildSqlStatement("select schema_name from information_schema.schemata"), null, rowToSchema,
            Collectors.toList());
}
 
Example 16
Source File: PortfolioEntity.java    From reactive-stock-trader with Apache License 2.0 4 votes vote down vote up
<E extends PortfolioEvent> void setEventHandlerChangingState(Class<E> event, Function<E, PortfolioState> handler) {
    Function<E, Behavior> stateHandler = handler.andThen(this::behaviourForState);
    builder.setEventHandlerChangingBehavior(event, stateHandler);
}
 
Example 17
Source File: JsonNodeConfigurationFactoryProvider.java    From bootique with Apache License 2.0 4 votes vote down vote up
private Function<JsonNode, JsonNode> andCliOptionOverrider(
        Function<JsonNode, JsonNode> overrider,
        Function<URL, Optional<JsonNode>> parser,
        BinaryOperator<JsonNode> singleConfigMerger) {

    if (optionMetadata.isEmpty()) {
        return overrider;
    }

    List<OptionSpec<?>> detectedOptions = cli.detectedOptions();
    if (detectedOptions.isEmpty()) {
        return overrider;
    }

    for (OptionSpec<?> cliOpt : detectedOptions) {

        OptionMetadata omd = findMetadata(cliOpt);

        if (omd == null) {
            continue;
        }

        // config decorators are loaded first, and then can be overridden from options...
        for (OptionRefWithConfig decorator : optionDecorators) {
            if (decorator.getOptionName().equals(omd.getName())) {
                overrider = overrider.andThen(new InPlaceResourceOverrider(decorator.getConfigResource().getUrl(),
                        parser, singleConfigMerger));
            }
        }

        for (OptionRefWithConfigPath pathDecorator : optionPathDecorators) {
            if (pathDecorator.getOptionName().equals(omd.getName())) {
                String cliValue = cli.optionString(omd.getName());
                overrider = overrider.andThen(new InPlaceMapOverrider(
                        singletonMap(pathDecorator.getConfigPath(), cliValue)
                ));
            }
        }
    }

    return overrider;
}
 
Example 18
Source File: MoreCollectors.java    From arctic-sea with Apache License 2.0 4 votes vote down vote up
protected <U> Collector<X, ?, Map<Chain<T>, U>> collector(Function<X, U> finisher) {
    Function<Entry<Chain<T>, X>, X> valueFunction = Entry::getValue;
    Function<Entry<Chain<T>, X>, U> finish = valueFunction.andThen(finisher);
    Function<X, Stream<Entry<Chain<T>, X>>> toIdentifierChain = this::toIdentifierChain;
    return flatMapping(toIdentifierChain, toMap(Entry::getKey, finish));
}
 
Example 19
Source File: TestFunctionComposition2.java    From mini-jvm with GNU Lesser General Public License v3.0 3 votes vote down vote up
public static void main(String[] args) {
  Function<Integer,Integer> f1 = it -> { return it + 1; };
  Function<Integer,Integer> f2 = it -> { return it - 10; };

  Function<Integer,Integer> f4 = f1.andThen(f2);

  int ret = f4.apply(0);

  System.out.println(ret);
}
 
Example 20
Source File: Maybe.java    From mug with Apache License 2.0 2 votes vote down vote up
/**
 * Wraps {@code function} that returns {@code Stream<T>} to one that returns
 * {@code Stream<Maybe<T, E>>} with exceptions of type {@code E} wrapped.
 *
 * <p>Useful to be passed to {@link Stream#flatMap}.
 *
 * <p>Unchecked exceptions will be immediately propagated without being wrapped.
 */
public static <F, T, E extends Throwable> Function<F, Stream<Maybe<T, E>>> maybeStream(
    CheckedFunction<? super F, ? extends Stream<? extends T>, E> function) {
  Function<F, Maybe<Stream<? extends T>, E>> wrapped = maybe(function);
  return wrapped.andThen(Maybe::maybeStream);
}