java.util.function.Function#andThen ( )源码实例Demo

下面列出了java.util.function.Function#andThen ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@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());
}
 
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();
    }
 
源代码3 项目: reactor-core   文件: Schedulers.java
/**
 * 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;
	}
}
 
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

}
 
@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();
}
 
源代码6 项目: cyclops   文件: EitherInstances.java
@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);
}
 
源代码7 项目: servicetalk   文件: TestPublisher.java
@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);
}
 
源代码8 项目: servicetalk   文件: TestCompletable.java
@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);
}
 
源代码9 项目: cyclops   文件: LazyEitherInstances.java
@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);
}
 
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
}
 
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);
}
 
源代码12 项目: PaySim   文件: SummaryBuilder.java
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;
}
 
源代码13 项目: reactor-core   文件: Hooks.java
@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;
}
 
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;
}
 
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);
}
 
源代码16 项目: FoxTelem   文件: SessionImpl.java
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());
}
 
源代码17 项目: reactive-stock-trader   文件: PortfolioEntity.java
<E extends PortfolioEvent> void setEventHandlerChangingState(Class<E> event, Function<E, PortfolioState> handler) {
    Function<E, Behavior> stateHandler = handler.andThen(this::behaviourForState);
    builder.setEventHandlerChangingBehavior(event, stateHandler);
}
 
源代码18 项目: arctic-sea   文件: MoreCollectors.java
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));
}
 
源代码19 项目: mini-jvm   文件: TestFunctionComposition2.java
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);
}
 
源代码20 项目: mug   文件: Maybe.java
/**
 * 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);
}