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

The following examples show how to use java.util.function.Function#identity() . 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: FluxDistinctUntilChangedTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void doesntRetainObjectsWithForcedCancelOnSubscriber_conditional() {
	RetainedDetector retainedDetector = new RetainedDetector();
	AtomicReference<DistinctDefaultCancel> fooRef = new AtomicReference<>(retainedDetector.tracked(new DistinctDefaultCancel(0)));

	DistinctUntilChangedConditionalSubscriber<DistinctDefaultCancel, DistinctDefaultCancel> sub = new DistinctUntilChangedConditionalSubscriber<>(
			Operators.toConditionalSubscriber(new BaseSubscriber<DistinctDefaultCancel>() {}), Function.identity(), Objects::equals);
	sub.onSubscribe(Operators.emptySubscription());
	sub.onNext(fooRef.getAndSet(null));

	assertThat(retainedDetector.finalizedCount()).isZero();
	assertThat(retainedDetector.trackedTotal()).isOne();

	sub.cancel();
	System.gc();

	await()
			.atMost(2, TimeUnit.SECONDS)
			.untilAsserted(retainedDetector::assertAllFinalized);
}
 
Example 2
Source File: Internals.java    From streamex with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
static <K, D, A, M extends Map<K, D>> PartialCollector<Map<K, A>, M> grouping(Supplier<M> mapFactory,
        Collector<?, A, D> downstream) {
    BinaryOperator<A> downstreamMerger = downstream.combiner();
    BiConsumer<Map<K, A>, Map<K, A>> merger = (map1, map2) -> {
        for (Map.Entry<K, A> e : map2.entrySet())
            map1.merge(e.getKey(), e.getValue(), downstreamMerger);
    };

    if (downstream.characteristics().contains(Collector.Characteristics.IDENTITY_FINISH)) {
        return (PartialCollector<Map<K, A>, M>) new PartialCollector<>((Supplier<Map<K, A>>) mapFactory,
                merger, Function.identity(), ID_CHARACTERISTICS);
    }
    Function<A, D> downstreamFinisher = downstream.finisher();
    return new PartialCollector<>((Supplier<Map<K, A>>) mapFactory, merger, map -> {
        map.replaceAll((k, v) -> ((Function<A, A>) downstreamFinisher).apply(v));
        return (M) map;
    }, NO_CHARACTERISTICS);
}
 
Example 3
Source File: MessageBatcherTest.java    From data-highway with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 1000)
public void batcher_blocks_when_queue_is_full() throws Exception {
  Function<List<Integer>, List<Integer>> batchHandler = Function.identity();
  AtomicReference<Runnable> processQueue = new AtomicReference<>();
  ThreadFactory factory = r -> {
    processQueue.set(r);
    return new Thread();
  };

  CountDownLatch latch = new CountDownLatch(1);

  Thread thread = null;
  try (MessageBatcher<Integer, Integer> batcher = new MessageBatcher<>(4, 2, EnqueueBehaviour.BLOCK_AND_WAIT,
      batchHandler, factory)) {
    thread = new Thread(() -> {
      batcher.apply(1);
      batcher.apply(2);
      batcher.apply(3);
      batcher.apply(4);
      latch.countDown();
      batcher.apply(5);
    });
    thread.start();
    latch.await();

    while (thread.getState() != State.WAITING) {}
  } finally {
    if (thread != null) {
      thread.interrupt();
      thread.join();
    }
  }
}
 
Example 4
Source File: PropertyStatisticsTest.java    From warnings-ng-plugin with MIT License 5 votes vote down vote up
/**
 * Verifies that getNormalCount() returns the number of issues with Severity#NORMAL.
 */
@Test
void shouldReturnNormalCountOne() {
    Report issues = new Report();
    IssueBuilder builder = new IssueBuilder();
    issues.add(builder.setSeverity(Severity.WARNING_NORMAL).setCategory(KEY).build());
    PropertyStatistics statistics = new PropertyStatistics(issues, "category", Function.identity());

    long value = statistics.getNormalCount(KEY);

    assertThat(value).isEqualTo(1);
}
 
Example 5
Source File: DataObjectTypesTest.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
private <P, V> void testGet(TestContext ctx, String sqlType, P param, V value, String column, Function<TestDataObject, V> getter) {
  super.testGet(
    ctx,
    sqlType,
    TestDataObjectRowMapper.INSTANCE,
    Function.identity(),
    "value",
    Collections.singletonMap("value", param),
    value,
    getter,
    column);
}
 
Example 6
Source File: ReadStreamSubscriberTest.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
@Override
protected Sender sender() {
  return new Sender() {

    private ReadStreamSubscriber<String, String> subscriber = new ReadStreamSubscriber<>(Function.identity());

    {
      stream = subscriber;
      subscriber.onSubscribe(new Subscription() {
        @Override
        public void request(long n) {
          requested += n;
        }
        @Override
        public void cancel() {
        }
      });
    }

    protected void emit() {
      subscriber.onNext("" + seq++);
    }

    protected void complete() {
      subscriber.onComplete();
    }

    protected void fail(Throwable cause) {
      subscriber.onError(cause);
    }

  };
}
 
Example 7
Source File: PropertyStatisticsTest.java    From warnings-ng-plugin with MIT License 5 votes vote down vote up
/**
 * Verifies that getNormalCount() returns zero if there are not issues with Severity#NORMAL.
 */
@Test
void shouldReturnNormalCountZero() {
    Report issues = new Report();
    IssueBuilder builder = new IssueBuilder();
    issues.add(builder.setSeverity(Severity.WARNING_LOW).setCategory(KEY).build());
    PropertyStatistics statistics = new PropertyStatistics(issues, "category", Function.identity());

    long value = statistics.getNormalCount(KEY);

    assertThat(value).isEqualTo(0);
}
 
Example 8
Source File: BaseJdbcClient.java    From presto with Apache License 2.0 5 votes vote down vote up
protected Function<String, String> tryApplyLimit(OptionalLong limit)
{
    if (limit.isEmpty()) {
        return Function.identity();
    }
    return limitFunction()
            .map(limitFunction -> (Function<String, String>) sql -> limitFunction.apply(sql, limit.getAsLong()))
            .orElseGet(Function::identity);
}
 
Example 9
Source File: DefaultCommonSqlCodeGeneratorCallback.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
private Function<String, String> getDateTransformFunction(CodeFragment fragment, EqlDateFormat dateFormat) {
	if (fragment.evaluatesToType(DataType.DATE)) {
		return x -> this.sqlDialect.dateToString(x, dateFormat);
	}

	if (fragment.evaluatesToType(DataType.TEXT)) {
		return x -> normalizeDateValue(dateFormat, x);
	}

	return Function.identity();
}
 
Example 10
Source File: MessageBatcherTest.java    From data-highway with Apache License 2.0 5 votes vote down vote up
@Test
public void messages_fail_when_buffer_full() throws Exception {
  Function<List<Integer>, List<Integer>> batchHandler = Function.identity();
  AtomicReference<Runnable> processQueue = new AtomicReference<>();
  ThreadFactory factory = r -> {
    processQueue.set(r);
    return new Thread();
  };
  Thread t = null;
  try (MessageBatcher<Integer, Integer> batcher = new MessageBatcher<>(4, 2, EnqueueBehaviour.COMPLETE_EXCEPTIONALLY,
      batchHandler, factory)) {
    CompletableFuture<Integer> result1 = batcher.apply(1);
    CompletableFuture<Integer> result2 = batcher.apply(2);
    CompletableFuture<Integer> result3 = batcher.apply(3);
    CompletableFuture<Integer> result4 = batcher.apply(4);
    CompletableFuture<Integer> result5 = batcher.apply(5);

    t = new Thread(processQueue.get());
    t.start();

    assertThat(result1.get(), is(1));
    assertThat(result2.get(), is(2));
    assertThat(result3.get(), is(3));
    assertThat(result4.get(), is(4));

    try {
      result5.get();
      fail();
    } catch (ExecutionException e) {
      assertTrue(e.getCause() instanceof IllegalStateException);
    }
  }
  t.join();
}
 
Example 11
Source File: MarkSweepPruner.java    From besu with Apache License 2.0 5 votes vote down vote up
private MerklePatriciaTrie<Bytes32, Bytes> createStateTrie(final Bytes32 rootHash) {
  return new StoredMerklePatriciaTrie<>(
      worldStateStorage::getAccountStateTrieNode,
      rootHash,
      Function.identity(),
      Function.identity());
}
 
Example 12
Source File: MarkSweepPruner.java    From besu with Apache License 2.0 5 votes vote down vote up
private MerklePatriciaTrie<Bytes32, Bytes> createStorageTrie(final Bytes32 rootHash) {
  return new StoredMerklePatriciaTrie<>(
      worldStateStorage::getAccountStorageTrieNode,
      rootHash,
      Function.identity(),
      Function.identity());
}
 
Example 13
Source File: JsonbParser.java    From typescript-generator with MIT License 5 votes vote down vote up
public PropertyNamingStrategy create() {
    if (String.class.isInstance(value)) {
        final String val = value.toString();
        switch (val) {
            case PropertyNamingStrategy.IDENTITY:
                return propertyName -> propertyName;
            case PropertyNamingStrategy.LOWER_CASE_WITH_DASHES:
                return new ConfigurableNamingStrategy(Character::toLowerCase, '-');
            case PropertyNamingStrategy.LOWER_CASE_WITH_UNDERSCORES:
                return new ConfigurableNamingStrategy(Character::toLowerCase, '_');
            case PropertyNamingStrategy.UPPER_CAMEL_CASE:
                return camelCaseStrategy();
            case PropertyNamingStrategy.UPPER_CAMEL_CASE_WITH_SPACES:
                final PropertyNamingStrategy camelCase = camelCaseStrategy();
                final PropertyNamingStrategy space = new ConfigurableNamingStrategy(Function.identity(), ' ');
                return propertyName -> camelCase.translateName(space.translateName(propertyName));
            case PropertyNamingStrategy.CASE_INSENSITIVE:
                return propertyName -> propertyName;
            default:
                throw new IllegalArgumentException(val + " unknown as PropertyNamingStrategy");
        }
    }
    if (PropertyNamingStrategy.class.isInstance(value)) {
        return PropertyNamingStrategy.class.cast(value);
    }
    throw new IllegalArgumentException(value + " not supported as PropertyNamingStrategy");
}
 
Example 14
Source File: ModelCollector.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public Function<Model, Model> finisher() {
	return Function.identity();
}
 
Example 15
Source File: TestHashJoinOperator.java    From presto with Apache License 2.0 4 votes vote down vote up
private BuildSideSetup setupBuildSide(
        boolean parallelBuild,
        TaskContext taskContext,
        List<Integer> hashChannels,
        RowPagesBuilder buildPages,
        Optional<InternalJoinFilterFunction> filterFunction,
        boolean spillEnabled,
        SingleStreamSpillerFactory singleStreamSpillerFactory)
{
    Optional<JoinFilterFunctionFactory> filterFunctionFactory = filterFunction
            .map(function -> (session, addresses, pages) -> new StandardJoinFilterFunction(function, addresses, pages));

    int partitionCount = parallelBuild ? PARTITION_COUNT : 1;
    LocalExchangeFactory localExchangeFactory = new LocalExchangeFactory(
            FIXED_HASH_DISTRIBUTION,
            partitionCount,
            buildPages.getTypes(),
            hashChannels,
            buildPages.getHashChannel(),
            UNGROUPED_EXECUTION,
            DataSize.of(32, DataSize.Unit.MEGABYTE));
    LocalExchangeSinkFactoryId localExchangeSinkFactoryId = localExchangeFactory.newSinkFactoryId();
    localExchangeFactory.noMoreSinkFactories();

    // collect input data into the partitioned exchange
    DriverContext collectDriverContext = taskContext.addPipelineContext(0, true, true, false).addDriverContext();
    ValuesOperatorFactory valuesOperatorFactory = new ValuesOperatorFactory(0, new PlanNodeId("values"), buildPages.build());
    LocalExchangeSinkOperatorFactory sinkOperatorFactory = new LocalExchangeSinkOperatorFactory(localExchangeFactory, 1, new PlanNodeId("sink"), localExchangeSinkFactoryId, Function.identity());
    Driver sourceDriver = Driver.createDriver(collectDriverContext,
            valuesOperatorFactory.createOperator(collectDriverContext),
            sinkOperatorFactory.createOperator(collectDriverContext));
    valuesOperatorFactory.noMoreOperators();
    sinkOperatorFactory.noMoreOperators();

    while (!sourceDriver.isFinished()) {
        sourceDriver.process();
    }

    // build side operator factories
    LocalExchangeSourceOperatorFactory sourceOperatorFactory = new LocalExchangeSourceOperatorFactory(0, new PlanNodeId("source"), localExchangeFactory);
    JoinBridgeManager<PartitionedLookupSourceFactory> lookupSourceFactoryManager = JoinBridgeManager.lookupAllAtOnce(new PartitionedLookupSourceFactory(
            buildPages.getTypes(),
            rangeList(buildPages.getTypes().size()).stream()
                    .map(buildPages.getTypes()::get)
                    .collect(toImmutableList()),
            hashChannels.stream()
                    .map(buildPages.getTypes()::get)
                    .collect(toImmutableList()),
            partitionCount,
            false));

    HashBuilderOperatorFactory buildOperatorFactory = new HashBuilderOperatorFactory(
            1,
            new PlanNodeId("build"),
            lookupSourceFactoryManager,
            rangeList(buildPages.getTypes().size()),
            hashChannels,
            buildPages.getHashChannel()
                    .map(OptionalInt::of).orElse(OptionalInt.empty()),
            filterFunctionFactory,
            Optional.empty(),
            ImmutableList.of(),
            100,
            new PagesIndex.TestingFactory(false),
            spillEnabled,
            singleStreamSpillerFactory);
    return new BuildSideSetup(lookupSourceFactoryManager, buildOperatorFactory, sourceOperatorFactory, partitionCount);
}
 
Example 16
Source File: BoundedLocalCache.java    From caffeine with Apache License 2.0 4 votes vote down vote up
@Override
public Policy<K, V> policy() {
  return (policy == null)
      ? (policy = new BoundedPolicy<>(cache, Function.identity(), isWeighted))
      : policy;
}
 
Example 17
Source File: ReadFamily.java    From simple-bigtable with Apache License 2.0 4 votes vote down vote up
@Override
protected Function<List<Row>, List<Row>> parentTypeToCurrentType() {
  return Function.identity();
}
 
Example 18
Source File: ReadRow.java    From simple-bigtable with Apache License 2.0 4 votes vote down vote up
@Override
protected Function<List<Row>, List<Row>> parentTypeToCurrentType() {
  return Function.identity();
}
 
Example 19
Source File: InMemoryPlaintextSecret.java    From strongbox with Apache License 2.0 4 votes vote down vote up
public InMemoryPlaintextSecret(SecretsGroup secretsGroup, SecretIdentifier secretIdentifier) {
    super(secretsGroup, secretIdentifier, Function.identity());
}
 
Example 20
Source File: StreamMapperTest.java    From datakernel with Apache License 2.0 4 votes vote down vote up
@Test
public void testIdentity() {
	Function<String, String> function1 = Function.identity();
	Function<Integer, Integer> function2 = Function.identity();
	assertSame(function1, function2);
}