java.util.function.Function Java Examples
The following examples show how to use
java.util.function.Function.
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: SingularityTestModule.java From Singularity with Apache License 2.0 | 6 votes |
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(); }
Example #2
Source File: SourceSet.java From buck with Apache License 2.0 | 6 votes |
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(); }
Example #3
Source File: Checksum.java From hadoop-ozone with Apache License 2.0 | 6 votes |
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); }
Example #4
Source File: MethodGenerator.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * 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); }
Example #5
Source File: HUEditorRow.java From metasfresh-webui-api-legacy with GNU General Public License v3.0 | 6 votes |
/** * @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); }
Example #6
Source File: ForEachOpTest.java From openjdk-8-source with GNU General Public License v2.0 | 6 votes |
@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(); }
Example #7
Source File: FluxManaged.java From cyclops with Apache License 2.0 | 6 votes |
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; } }; }
Example #8
Source File: PulsarAdminTool.java From pulsar with Apache License 2.0 | 6 votes |
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); } }
Example #9
Source File: TreeMapStore.java From tracecompass with Eclipse Public License 2.0 | 6 votes |
/** * 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; }
Example #10
Source File: EmpDaoImpl.java From doma with Apache License 2.0 | 6 votes |
@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(); }
Example #11
Source File: JcrMetadataRepository.java From archiva with Apache License 2.0 | 6 votes |
@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); }
Example #12
Source File: ConstantsReader.java From teku with Apache License 2.0 | 5 votes |
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() + "'"); } }
Example #13
Source File: Esuc.java From haven-platform with Apache License 2.0 | 5 votes |
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); }
Example #14
Source File: ReaderWriterState.java From cyclops with Apache License 2.0 | 5 votes |
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); }
Example #15
Source File: HeaderBasedPlaceholderSubstitutionAlgorithm.java From ditto with Eclipse Public License 2.0 | 5 votes |
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()); }; }
Example #16
Source File: BaseController.java From sunbird-lms-service with MIT License | 5 votes |
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); }
Example #17
Source File: BaseUInt32Value.java From incubator-tuweni with Apache License 2.0 | 5 votes |
/** * @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; }
Example #18
Source File: ThingsAggregatorProxyActor.java From ditto with Eclipse Public License 2.0 | 5 votes |
private Function<List<PlainJson>, CommandResponse<?>> supplyRetrieveThingsResponse( final DittoHeaders dittoHeaders, @Nullable final String namespace) { return plainJsonThings -> RetrieveThingsResponse.of(plainJsonThings.stream() .map(PlainJson::getJson) .collect(Collectors.toList()), namespace, dittoHeaders); }
Example #19
Source File: OrmCriteria.java From sample-boot-micro with MIT License | 5 votes |
@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); }
Example #20
Source File: EmrOperatorFactory.java From digdag with Apache License 2.0 | 5 votes |
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)); } }
Example #21
Source File: GenesisState.java From besu with Apache License 2.0 | 5 votes |
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); } }
Example #22
Source File: CoordinatorTests.java From crate with Apache License 2.0 | 5 votes |
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); }
Example #23
Source File: A.java From akarnokd-misc with Apache License 2.0 | 5 votes |
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; }; }
Example #24
Source File: CreateBaseVisitorClass.java From jaxb-visitor with Apache License 2.0 | 5 votes |
CreateBaseVisitorClass(JDefinedClass visitor, Outline outline, JPackage jPackage, Function<String, String> visitMethodNamer) { super(outline, jPackage); this.visitor = visitor; this.visitMethodNamer = visitMethodNamer; }
Example #25
Source File: JdbcCommon.java From nifi with Apache License 2.0 | 5 votes |
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(); }
Example #26
Source File: EventFileManager.java From localization_nifi with Apache License 2.0 | 5 votes |
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(); }
Example #27
Source File: ManagementFactory.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
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(); }
Example #28
Source File: DocumentCollection.java From metasfresh-webui-api-legacy with GNU General Public License v3.0 | 5 votes |
public <R> R forDocumentWritable( @NonNull final DocumentPath documentPath, @NonNull final IDocumentChangesCollector changesCollector, @NonNull final Function<Document, R> documentProcessor) { final DocumentPath rootDocumentPath = documentPath.getRootDocumentPath(); return forRootDocumentWritable( rootDocumentPath, changesCollector, rootDocument -> { final Document document; if (documentPath.isRootDocument()) { document = rootDocument; } else if (documentPath.isSingleNewIncludedDocument()) { document = rootDocument.createIncludedDocument(documentPath.getDetailId()); } else { document = rootDocument.getIncludedDocument(documentPath.getDetailId(), documentPath.getSingleRowId()); DocumentPermissionsHelper.assertCanEdit(rootDocument); } return documentProcessor.apply(document); }); }
Example #29
Source File: BKAbstractLogWriter.java From distributedlog with Apache License 2.0 | 5 votes |
protected synchronized CompletableFuture<BKLogSegmentWriter> rollLogSegmentIfNecessary( final BKLogSegmentWriter segmentWriter, long startTxId, boolean bestEffort, boolean allowMaxTxID) { final BKLogWriteHandler writeHandler; try { writeHandler = getWriteHandler(); } catch (IOException e) { return FutureUtils.exception(e); } CompletableFuture<BKLogSegmentWriter> rollPromise; if (null != segmentWriter && (writeHandler.shouldStartNewSegment(segmentWriter) || forceRolling)) { rollPromise = closeOldLogSegmentAndStartNewOneWithPermit( segmentWriter, writeHandler, startTxId, bestEffort, allowMaxTxID); } else if (null == segmentWriter) { rollPromise = asyncStartNewLogSegment(writeHandler, startTxId, allowMaxTxID); } else { rollPromise = FutureUtils.value(segmentWriter); } return rollPromise.thenApply(new Function<BKLogSegmentWriter, BKLogSegmentWriter>() { @Override public BKLogSegmentWriter apply(BKLogSegmentWriter newSegmentWriter) { if (segmentWriter == newSegmentWriter) { return newSegmentWriter; } truncateLogSegmentsIfNecessary(writeHandler); return newSegmentWriter; } }); }
Example #30
Source File: StreamExTest.java From streamex with Apache License 2.0 | 5 votes |
@Test public void testMapPartial() { Function<Integer, Optional<String>> literalOf = num -> num == 1 ? Optional.of("one") : Optional.empty(); List<Integer> original = asList(1, 2, 3, 4); List<String> expected = asList("one"); streamEx(original::stream, s -> assertEquals(expected, s.get().mapPartial(literalOf).toList())); }