Java Code Examples for java.util.function.Function

The following examples show how to use java.util.function.Function. 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
Source Project: tracecompass   Source File: TreeMapStore.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * 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 2
Source Project: hadoop-ozone   Source File: Checksum.java    License: Apache License 2.0 6 votes vote down vote up
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 3
Source Project: openjdk-jdk9   Source File: MethodGenerator.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 4
/**
 * @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 5
Source Project: Singularity   Source File: SingularityTestModule.java    License: Apache License 2.0 6 votes vote down vote up
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 6
@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 Project: buck   Source File: SourceSet.java    License: Apache License 2.0 6 votes vote down vote up
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 8
Source Project: cyclops   Source File: FluxManaged.java    License: Apache License 2.0 6 votes vote down vote up
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 9
Source Project: pulsar   Source File: PulsarAdminTool.java    License: Apache License 2.0 6 votes vote down vote up
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 10
Source Project: doma   Source File: EmpDaoImpl.java    License: Apache License 2.0 6 votes vote down vote up
@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 Project: archiva   Source File: JcrMetadataRepository.java    License: Apache License 2.0 6 votes vote down vote up
@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 Project: mpush   Source File: GatewayUDPConnectionFactory.java    License: Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 13
Source Project: haven-platform   Source File: Esuc.java    License: Apache License 2.0 5 votes vote down vote up
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
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;
}
 
Example 15
Source Project: gcp-ingestion   Source File: Pubsub.java    License: Mozilla Public License 2.0 5 votes vote down vote up
/** 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();
}
 
Example 16
Source Project: simplesource   Source File: FutureResult.java    License: Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 17
Source Project: sunbird-lms-service   Source File: BaseController.java    License: MIT License 5 votes vote down vote up
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 18
Source Project: teku   Source File: ConstantsReader.java    License: Apache License 2.0 5 votes vote down vote up
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 19
Source Project: cyclops   Source File: ReaderWriterState.java    License: Apache License 2.0 5 votes vote down vote up
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 20
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 21
Source Project: incubator-tuweni   Source File: BaseUInt32Value.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @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 22
Source Project: sample-boot-micro   Source File: OrmCriteria.java    License: MIT License 5 votes vote down vote up
@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 23
Source Project: digdag   Source File: EmrOperatorFactory.java    License: Apache License 2.0 5 votes vote down vote up
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 24
Source Project: besu   Source File: GenesisState.java    License: Apache License 2.0 5 votes vote down vote up
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 25
Source Project: crate   Source File: CoordinatorTests.java    License: Apache License 2.0 5 votes vote down vote up
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 26
Source Project: akarnokd-misc   Source File: A.java    License: Apache License 2.0 5 votes vote down vote up
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 27
Source Project: jaxb-visitor   Source File: CreateBaseVisitorClass.java    License: Apache License 2.0 5 votes vote down vote up
CreateBaseVisitorClass(JDefinedClass visitor, Outline outline,
                       JPackage jPackage,
                       Function<String, String> visitMethodNamer) {
    super(outline, jPackage);
    this.visitor = visitor;
    this.visitMethodNamer = visitMethodNamer;
}
 
Example 28
Source Project: nifi   Source File: JdbcCommon.java    License: Apache License 2.0 5 votes vote down vote up
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 29
Source Project: localization_nifi   Source File: EventFileManager.java    License: Apache License 2.0 5 votes vote down vote up
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 30
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();
}