下面列出了怎么用java.util.function.Function的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Constructor
*/
public TreeMapStore() {
/*
* For the start times index, the "key comparator" will compare the
* start times as longs directly. This is the primary comparator for its
* tree map.
*
* The secondary "value" comparator will check the end times first, and
* in the event of a tie, defer to the ISegment's Comparable
* implementation, a.k.a. its natural ordering.
*/
fStartTimesIndex = TreeMultimap.create(Comparator.<Long>naturalOrder(),
Comparator.comparingLong(E::getEnd).thenComparing(Function.identity()));
fSize = 0;
}
public ChecksumData computeChecksum(ChunkBuffer data)
throws OzoneChecksumException {
if (checksumType == ChecksumType.NONE) {
// Since type is set to NONE, we do not need to compute the checksums
return new ChecksumData(checksumType, bytesPerChecksum);
}
final Function<ByteBuffer, ByteString> function;
try {
function = Algorithm.valueOf(checksumType).newChecksumFunction();
} catch (Exception e) {
throw new OzoneChecksumException(checksumType);
}
// Checksum is computed for each bytesPerChecksum number of bytes of data
// starting at offset 0. The last checksum might be computed for the
// remaining data with length less than bytesPerChecksum.
final List<ByteString> checksumList = new ArrayList<>();
for (ByteBuffer b : data.iterate(bytesPerChecksum)) {
checksumList.add(computeChecksum(b, function, bytesPerChecksum));
}
return new ChecksumData(checksumType, bytesPerChecksum, checksumList);
}
/**
* Generates random method descriptor
*
* @param executable executable used to generate descriptor
* @return MethodDescriptor instance
*/
public MethodDescriptor generateRandomDescriptor(Executable executable) {
Combination<PatternType> patterns =
Utils.getRandomElement(PATTERNS_LIST);
Combination<Separator> separators =
Utils.getRandomElement(SEPARATORS_LIST);
// Create simple mutators for signature generation
List<Function<String, String>> signMutators = new ArrayList<>();
signMutators.add(input -> input);
signMutators.add(input -> "");
Combination<Function<String, String>> mutators = new Combination<>(
Utils.getRandomElement(ELEMENT_MUTATORS),
Utils.getRandomElement(ELEMENT_MUTATORS),
// use only this type of mutators
Utils.getRandomElement(signMutators));
return makeMethodDescriptor(executable, patterns,
separators, mutators);
}
/**
* @param stringFilter
* @param adLanguage AD_Language (used to get the right row's string representation)
* @return true if the row is matching the string filter
*/
public boolean matchesStringFilter(final String stringFilter)
{
if (Check.isEmpty(stringFilter, true))
{
return true;
}
final String rowDisplayName = getSummary();
final Function<String, String> normalizer = s -> StringUtils.stripDiacritics(s.trim()).toLowerCase();
final String rowDisplayNameNorm = normalizer.apply(rowDisplayName);
final String stringFilterNorm = normalizer.apply(stringFilter);
return rowDisplayNameNorm.contains(stringFilterNorm);
}
public SingularityTestModule(
boolean useDbTests,
Function<SingularityConfiguration, Void> customConfigSetup
)
throws Exception {
this.useDBTests = useDbTests;
this.customConfigSetup = customConfigSetup;
dropwizardModule = new DropwizardModule(environment);
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
Logger rootLogger = context.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
rootLogger.setLevel(
Level.toLevel(System.getProperty("singularity.test.log.level", "WARN"))
);
Logger hsLogger = context.getLogger("com.hubspot");
hsLogger.setLevel(
Level.toLevel(
System.getProperty("singularity.test.log.level.for.com.hubspot", "WARN")
)
);
this.ts = new TestingServer();
}
@Test(dataProvider = "LongStreamTestData", dataProviderClass = LongStreamTestDataProvider.class)
public void testLongOps(String name, TestData.OfLong data) {
Function<LongStream, List<Long>> terminalFunc = s -> {
List<Long> l = Collections.synchronizedList(new ArrayList<Long>());
s.forEach(l::add);
return l;
};
// Test head
withData(data).
terminal(terminalFunc).
resultAsserter(resultAsserter()).
exercise();
// Test multiple stages
withData(data).
terminal(s -> s.map(i -> i), terminalFunc).
resultAsserter(resultAsserter()).
exercise();
}
public ImmutableMap<String, SourcePath> toNameMap(
BuildTarget buildTarget,
SourcePathResolverAdapter pathResolver,
String parameterName,
Predicate<SourcePath> filter,
Function<SourcePath, SourcePath> transform) {
ImmutableMap.Builder<String, SourcePath> sources = ImmutableMap.builder();
switch (getType()) {
case NAMED:
for (Map.Entry<String, SourcePath> ent : getNamedSources().get().entrySet()) {
if (filter.test(ent.getValue())) {
sources.put(ent.getKey(), transform.apply(ent.getValue()));
}
}
break;
case UNNAMED:
pathResolver
.getSourcePathNames(
buildTarget, parameterName, getUnnamedSources().get(), filter, transform)
.forEach((name, path) -> sources.put(name, transform.apply(path)));
break;
}
return sources.build();
}
public <R> Managed<R> flatMap(Function<? super T, cyclops.reactive.Managed<R>> f){
FluxManaged<T> m = this;
return new IO.SyncIO.SyncManaged<R>(){
@Override
public <R1> IO<R1> apply(Function<? super R, ? extends IO<R1>> fn) {
IO<R1> x = m.apply(r1 -> {
IO<R1> r = f.apply(r1).apply(r2 -> fn.apply(r2));
return r;
});
return x;
}
};
}
private void setupCommands(Function<PulsarAdminBuilder, ? extends PulsarAdmin> adminFactory) {
try {
adminBuilder.serviceHttpUrl(serviceUrl);
adminBuilder.authentication(authPluginClassName, authParams);
PulsarAdmin admin = adminFactory.apply(adminBuilder);
for (Map.Entry<String, Class<?>> c : commandMap.entrySet()) {
addCommand(c, admin);
}
} catch (Exception e) {
Throwable cause;
if (e instanceof InvocationTargetException && null != e.getCause()) {
cause = e.getCause();
} else {
cause = e;
}
System.err.println(cause.getClass() + ": " + cause.getMessage());
System.exit(1);
}
}
@Override
public Integer stream(Function<Stream<Emp>, Integer> mapper) {
SqlFileSelectQuery query = __support.getQueryImplementors().createSqlFileSelectQuery(method6);
query.setConfig(__support.getConfig());
query.setSqlFilePath(SqlFileUtil.buildPath("example.dao.EmpDao", "iterate"));
query.setCallerClassName("example.dao.EmpDao");
query.setCallerMethodName("iterate");
query.prepare();
SelectCommand<Integer> command =
__support
.getCommandImplementors()
.createSelectCommand(
method6,
query,
new EntityStreamHandler<Emp, Integer>(_Emp.getSingletonInternal(), mapper));
return command.execute();
}
@Override
public <T extends MetadataFacet> Stream<T> getMetadataFacetStream(RepositorySession session, String repositoryId, Class<T> facetClazz, QueryParameter queryParameter) throws MetadataRepositoryException {
final Session jcrSession = getSession(session);
final MetadataFacetFactory<T> factory = metadataService.getFactory(facetClazz);
final String facetId = factory.getFacetId();
final String facetPath = '/' + getFacetPath(repositoryId, facetId);
StringBuilder query = new StringBuilder("SELECT * FROM [");
query.append(FACET_NODE_TYPE).append("] AS facet WHERE ISDESCENDANTNODE(facet, [")
.append(facetPath).append("]) AND [facet].[archiva:name] IS NOT NULL");
appendQueryParams(query, "facet", "archiva:name", queryParameter);
String q = query.toString();
Map<String, String> params = new HashMap<>();
QueryResult result = runNativeJcrQuery(jcrSession, q, params, queryParameter.getOffset(), queryParameter.getLimit());
final Function<Row, Optional<T>> rowFunc = getFacetFromRowFunc(factory, repositoryId);
return StreamSupport.stream(createResultSpliterator(result, rowFunc), false).filter(Optional::isPresent).map(Optional::get);
}
@SuppressWarnings("unchecked")
@Override
public <M extends BaseMessage> boolean send(String hostAndPort, Function<Connection, M> creator, Consumer<M> sender) {
InetSocketAddress recipient = ip_address.get(hostAndPort);
if (recipient == null) return false;// gateway server 找不到,直接返回推送失败
M message = creator.apply(gatewayUDPConnector.getConnection());
message.setRecipient(recipient);
sender.accept(message);
return true;
}
void update(String key, Function<String, Subscriptions<?>> factory) {
Subscriptions<?> subs = this.oldMap.get(key);
if(subs == null) {
try {
subs = factory.apply(key);
} catch (Exception e) {
log.error("Can not update subscriptions for '{}' key, due to error:", key, e);
}
}
newMap.put(key, subs);
}
public HystrixMethodHandlerFactory(MethodHandlerFactory methodHandlerFactory,
CloudReactiveFeign.SetterFactory commandSetterFactory,
@Nullable Function<Throwable, Object> fallbackFactory) {
this.methodHandlerFactory = checkNotNull(methodHandlerFactory, "methodHandlerFactory must not be null");
this.commandSetterFactory = checkNotNull(commandSetterFactory, "hystrixObservableCommandSetter must not be null");
this.fallbackFactory = fallbackFactory;
}
/** Constructor. */
public <T> Read(String subscriptionName, Function<PubsubMessage, CompletableFuture<T>> output,
Function<Subscriber.Builder, Subscriber.Builder> config,
Function<PubsubMessage, PubsubMessage> decompress) {
ProjectSubscriptionName subscription = ProjectSubscriptionName.parse(subscriptionName);
subscriber = config.apply(Subscriber.newBuilder(subscription,
// Synchronous CompletableFuture methods are executed by the thread that completes the
// future, or the current thread if the future is already complete. Use that here to
// minimize memory usage by doing as much work as immediately possible.
(message, consumer) -> CompletableFuture.completedFuture(message).thenApply(decompress)
.thenCompose(output).whenComplete((result, exception) -> {
if (exception == null) {
consumer.ack();
} else {
// exception is always a CompletionException caused by another exception
if (exception.getCause() instanceof BatchException) {
// only log batch exception once
((BatchException) exception.getCause()).handle((batchExc) -> LOG.error(
String.format("failed to deliver %d messages", batchExc.size),
batchExc.getCause()));
} else {
// log exception specific to this message
LOG.error("failed to deliver message", exception.getCause());
}
consumer.nack();
}
})))
.build();
}
public Result<E, T> unsafePerform(final Function<Exception, E> f) {
try {
return run.get();
} catch (final InterruptedException | ExecutionException e) {
E error = f.apply(e);
return Result.failure(error);
}
}
protected CompletionStage<Result> handleRequest(
String operation,
JsonNode requestBodyJson,
Function requestValidatorFn,
Map<String, String> headers,
Request httpRequest) {
return handleRequest(
operation, requestBodyJson, requestValidatorFn, null, null, headers, true, httpRequest);
}
private static Object parseValue(final Field field, final Object value) {
final Function<Object, ?> parser = PARSERS.get(field.getType());
if (parser == null) {
throw new IllegalArgumentException("Unknown constant type: " + field.getType());
}
try {
return parser.apply(value);
} catch (final IllegalArgumentException e) {
throw new IllegalArgumentException(
"Failed to parse value '" + value + "' for constant '" + field.getName() + "'");
}
}
public <R2> ReaderWriterState<R,W,S,R2> flatMap(Function<? super T,? extends ReaderWriterState<R,W,S,R2>> f) {
return suspended((r,s) -> runState.apply(r, s)
.flatMap(result -> Free.done(f.apply(result._3())
.run(r, result._2())
.transform((w2,s2,r2)-> tuple(monoid.apply(w2,result._1()),s2,r2)
))),monoid);
}
private Function<String, PipelineElement> createReplacerFunction(final DittoHeaders dittoHeaders) {
return placeholderWithSpaces -> {
final String placeholder = placeholderWithSpaces.trim();
final Function<DittoHeaders, String> placeholderResolver = replacementDefinitions.get(placeholder);
if (placeholderResolver == null) {
throw GatewayPlaceholderNotResolvableException.newUnknownPlaceholderBuilder(placeholder,
knownPlaceHolders)
.dittoHeaders(dittoHeaders)
.build();
}
return Optional.ofNullable(placeholderResolver.apply(dittoHeaders))
.map(PipelineElement::resolved)
.orElse(PipelineElement.unresolved());
};
}
/**
* @param value The value to instantiate this {@code UInt32Value} with.
* @param ctor A constructor for the concrete type.
*/
protected BaseUInt32Value(UInt32 value, Function<UInt32, T> ctor) {
requireNonNull(value);
requireNonNull(ctor);
this.value = value;
this.ctor = ctor;
}
@SuppressWarnings("unchecked")
public CriteriaQuery<Long> resultCount(Function<CriteriaQuery<?>, CriteriaQuery<?>> extension) {
CriteriaQuery<Long> q = builder.createQuery(Long.class);
q.from(clazz).alias(alias);
q.where(predicates.toArray(new Predicate[0]));
if (q.isDistinct()) {
q.select(builder.countDistinct(root));
} else {
q.select(builder.count(root));
}
return (CriteriaQuery<Long>)extension.apply(q);
}
private void logSubmittedSteps(String clusterId, int n, Function<Integer, String> names, Function<Integer, String> ids)
{
logger.info("Submitted {} EMR step(s) to {}", n, clusterId);
for (int i = 0; i < n; i++) {
logger.info("Step {}/{}: {}: {}", i + 1, n, names.apply(i), ids.apply(i));
}
}
private static <T> T withNiceErrorMessage(
final String name, final String value, final Function<String, T> parser) {
try {
return parser.apply(value);
} catch (final IllegalArgumentException e) {
throw createInvalidBlockConfigException(name, value, e);
}
}
ClusterNode restartedNode(Function<MetaData, MetaData> adaptGlobalMetaData, Function<Long, Long> adaptCurrentTerm,
Settings nodeSettings) {
final TransportAddress address = randomBoolean() ? buildNewFakeTransportAddress() : localNode.getAddress();
final DiscoveryNode newLocalNode = new DiscoveryNode(localNode.getName(), localNode.getId(),
UUIDs.randomBase64UUID(random()), // generated deterministically for repeatable tests
address.address().getHostString(), address.getAddress(), address, Collections.emptyMap(),
localNode.isMasterNode() ? EnumSet.allOf(Role.class) : emptySet(), Version.CURRENT);
return new ClusterNode(nodeIndex, newLocalNode,
node -> new MockPersistedState(newLocalNode, persistedState, adaptGlobalMetaData, adaptCurrentTerm), nodeSettings);
}
static <T, R> O<R> m(O<T> source, Function<T, O<R>> mapper) {
return o -> {
class D {
class E {
}
E e = new E();
}
D d = new D();
return d.e;
};
}
CreateBaseVisitorClass(JDefinedClass visitor, Outline outline,
JPackage jPackage,
Function<String, String> visitMethodNamer) {
super(outline, jPackage);
this.visitor = visitor;
this.visitMethodNamer = visitMethodNamer;
}
private static void addNullableField(
FieldAssembler<Schema> builder,
String columnName,
Function<BaseTypeBuilder<UnionAccumulator<NullDefault<Schema>>>, UnionAccumulator<NullDefault<Schema>>> func
) {
final BaseTypeBuilder<UnionAccumulator<NullDefault<Schema>>> and = builder.name(columnName).type().unionOf().nullBuilder().endNull().and();
func.apply(and).endUnion().noDefault();
}
private ReadWriteLock updateCount(final File file, final Function<Integer, Integer> update) {
final String key = getMapKey(file);
boolean updated = false;
Tuple<ReadWriteLock, Integer> updatedTuple = null;
while (!updated) {
final Tuple<ReadWriteLock, Integer> tuple = lockMap.computeIfAbsent(key, k -> new Tuple<>(new ReentrantReadWriteLock(), 0));
final Integer updatedCount = update.apply(tuple.getValue());
updatedTuple = new Tuple<>(tuple.getKey(), updatedCount);
updated = lockMap.replace(key, tuple, updatedTuple);
}
return updatedTuple.getKey();
}
private static Stream<PlatformComponent<?>>
toPlatformComponentStream(PlatformMBeanProvider provider)
{
return provider.getPlatformComponentList()
.stream()
.collect(toMap(PlatformComponent::getObjectNamePattern,
Function.identity(),
(p1, p2) -> {
throw new InternalError(
p1.getObjectNamePattern() +
" has been used as key for " + p1 +
", it cannot be reused for " + p2);
}))
.values().stream();
}