Java Code Examples for java.util.function.Function

The following are top voted examples for showing how to use java.util.function.Function. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: openjdk-jdk10   File: SortedOpTest.java   View source code 6 votes vote down vote up
@Test(groups = { "serialization-hostile" })
public void testIntSequentialShortCircuitTerminal() {
    int[] a = new int[]{5, 4, 3, 2, 1};

    Function<Integer, IntStream> knownSize = i -> assertNCallsOnly(
            Arrays.stream(a).sorted(), (s, c) -> s.peek(c::accept), i);
    Function<Integer, IntStream> unknownSize = i -> assertNCallsOnly
            (unknownSizeIntStream(a).sorted(), (s, c) -> s.peek(c::accept), i);

    // Find
    assertEquals(knownSize.apply(1).findFirst(), OptionalInt.of(1));
    assertEquals(knownSize.apply(1).findAny(), OptionalInt.of(1));
    assertEquals(unknownSize.apply(1).findFirst(), OptionalInt.of(1));
    assertEquals(unknownSize.apply(1).findAny(), OptionalInt.of(1));

    // Match
    assertEquals(knownSize.apply(2).anyMatch(i -> i == 2), true);
    assertEquals(knownSize.apply(2).noneMatch(i -> i == 2), false);
    assertEquals(knownSize.apply(2).allMatch(i -> i == 2), false);
    assertEquals(unknownSize.apply(2).anyMatch(i -> i == 2), true);
    assertEquals(unknownSize.apply(2).noneMatch(i -> i == 2), false);
    assertEquals(unknownSize.apply(2).allMatch(i -> i == 2), false);
}
 
Example 2
Project: verify-matching-service-adapter   File: IssueInstantValidatorTest.java   View source code 6 votes vote down vote up
@Test
public void validationDoesNotOccurWhenNoInstantIsProvided() {
    Messages messages = messages();
    Function<Object, Instant> instantProvider = context -> null;
    IssueInstantValidator<Object> validator = new IssueInstantValidator<>(
        TTL_MESSAGE,
        INSTANT_IN_FUTURE_MESSAGE,
        instantProvider,
        TTL,
        CLOCK_DELTA
    );

    Messages returnedMessages = validator.validate(new Object(), messages);

    assertThat(returnedMessages, sameInstance(messages));
    assertThat(validator.getCondition(), notNullValue());
    assertThat(validator.getCondition().test(new Object()), is(false));

    assertThat(returnedMessages.hasErrorLike(TTL_MESSAGE), is(false));
    assertThat(returnedMessages.hasErrorLike(INSTANT_IN_FUTURE_MESSAGE), is(false));
}
 
Example 3
Project: practical-functional-java   File: StreamTest.java   View source code 6 votes vote down vote up
@Test
public void testFlatMap1() {
    ImmutablePerson fred = ImmutablePerson.of("Fred", "Flintstone");
    fred = fred.withNickNames("The Fredmeister", "Yabba Dabba Dude");
    
    ImmutablePerson barney = ImmutablePerson.of("Barney",  "Rubble");
    barney = barney.withNickNames("The Barnster", "Little Buddy");

    String expectedAllNickNames = "The Fredmeister,Yabba Dabba Dude,"
            + "The Barnster,Little Buddy";
    
    // (not so good) map each ImmutablePerson to a Stream<String> of nicknames,
    // then use flatMap for flatten
    String allNickNames = Stream.of(fred, barney)  // Stream<ImmutablePerson>
            .map(ImmutablePerson::nickNames)  // Stream<Stream<String>>
            .flatMap(Function.identity()) // Stream<String>
            .collect(Collectors.joining(","));
    
    assertThat(allNickNames).isEqualTo(expectedAllNickNames);
}
 
Example 4
Project: travny   File: AnyTest.java   View source code 6 votes vote down vote up
@Test
public void shouldWriteReadAny() throws IOException {
    OtherRecWithId rec = new OtherRecWithId().setInField(234).setStrField("string456");
    RecWithAny r = new RecWithAny().setIntField(123).setStringField("string123").setAnyField(new Any(rec));

    byte[] data = BinaryWriter.toBytes(r);
    RecWithAny deserializedCustom = BinaryReader.fromBytes(data, RecWithAny.class);
    Assert.assertEquals(r, deserializedCustom);
    Record deserializedGeneric = BinaryReader.fromBytes(data, RecWithAny.getRecordSchema());
    Assert.assertEquals(r, deserializedGeneric);

    Assert.assertEquals(rec, deserializedCustom.getAnyField().getCustom((Function) ID_TO_CLZ));
    Assert.assertEquals(rec, ((Any) deserializedGeneric.get("anyField")).getGeneric(ID_TO_SCHEMA));

    String json = JsonWriter.toString(r);
    RecWithAny jsonCustom = JsonReader.fromString(json, RecWithAny.class);
    Assert.assertEquals(r, jsonCustom);
    Record jsonGen = JsonReader.fromString(json, RecWithAny.getRecordSchema());
    Assert.assertEquals(r, jsonGen);

    Assert.assertEquals(rec, jsonCustom.getAnyField().getCustom((Function) ID_TO_CLZ));
    Assert.assertEquals(rec, ((Any) jsonGen.get("anyField")).getGeneric(ID_TO_SCHEMA));

}
 
Example 5
Project: elasticsearch_my   File: DiffableTestUtils.java   View source code 6 votes vote down vote up
/**
 * Tests making random changes to an object, calculating diffs for these changes, sending this
 * diffs over the wire and appling these diffs on the other side.
 */
public static <T extends Diffable<T>> void testDiffableSerialization(Supplier<T> testInstance,
                                                                     Function<T, T> modifier,
                                                                     NamedWriteableRegistry namedWriteableRegistry,
                                                                     Reader<T> reader,
                                                                     Reader<Diff<T>> diffReader) throws IOException {
    T remoteInstance = testInstance.get();
    T localInstance = assertSerialization(remoteInstance, namedWriteableRegistry, reader);
    for (int runs = 0; runs < NUMBER_OF_DIFF_TEST_RUNS; runs++) {
        T remoteChanges = modifier.apply(remoteInstance);
        Diff<T> remoteDiffs = remoteChanges.diff(remoteInstance);
        Diff<T> localDiffs = copyInstance(remoteDiffs, namedWriteableRegistry, diffReader);
        localInstance = assertDiffApplication(remoteChanges, localInstance, localDiffs);
        remoteInstance = remoteChanges;
    }
}
 
Example 6
Project: 360w17g1   File: AbstractView.java   View source code 6 votes vote down vote up
/**
 * Displays a title for a numbered list of objects and prompts the user to make a selection from that list. Offers
 * alternative options.
 * 
 * @param theTitle the title of the list
 * @param thePrompt the prompt
 * @param theList the list
 * @param theToStringFunction a function that maps an object list to a string list
 * @param theAlternatives alternative options to the list (e.g. back)
 * @return the object selected from the array or null if an alternative option was chosen
 * @throws NullPointerException if any parameters are null
 */
protected <E> E getSelectionFromList(final String theTitle, final String thePrompt, final E[] theList,
		final Function<E, String> theToStringFunction, final String[] theAlternatives) {
	print(Objects.requireNonNull(theTitle));
	displayLine();
	final Stream<String> listAsStrings = Arrays.stream(Objects.requireNonNull(theList))
			.map(Objects.requireNonNull(theToStringFunction));
	displayNumberedList(Stream.concat(listAsStrings,
			Arrays.stream(Objects.requireNonNull(theAlternatives))).toArray(String[]::new));
	displayLine();
	final int index = getInteger(Objects.requireNonNull(thePrompt), 1, theList.length + 1);
	if (index == theList.length + 1) {
		return null;
	} else {
		return theList[index - 1];
	}
}
 
Example 7
Project: syndesis   File: ReflectiveSorterTest.java   View source code 6 votes vote down vote up
@Test
public void noParams() {
    ListResult<TestPersonInterface> toSort = new ListResult.Builder<TestPersonInterface>().items(getTestData()).totalCount(getTestData().size()).build();
    Function<ListResult<TestPersonInterface>, ListResult<TestPersonInterface>> operator =
        new ReflectiveSorter<>(TestPersonInterface.class, getOptions(null, null));
    ListResult<TestPersonInterface> sorted = operator.apply(toSort);

    String[] expectedNames = {
        "Schrödinger",
        "Heisenberg",
        "Feynman",
        "Maxwell",
    };

    for (int i = 0; i < expectedNames.length; i++) {
        assertEquals(sorted.getItems().get(i).getLastName(), expectedNames[i]);
    }
    assertEquals(getTestData().size(), sorted.getTotalCount());

}
 
Example 8
Project: spoj   File: MREPLBRC_Brute_Force.java   View source code 6 votes vote down vote up
public static void testManyCases(Function<String, Long> f) {
	test("()()()", f);
	test("()()?(", f);
	test("()()?)", f);
	test("()()??", f);
	test("(?([?)]?}?", f);
	test("(??)", f);
	test("????", f);
	test("??(?", f);
	test("?](?", f);
	test("{](?", f);
	test("((?)???)()", f);
	test("((?)???)?)", f);
	test("[(?)???)?)??", f);
	test("([{??}])", f);
	test("(((((??)))))", f);
	test("(((?((??))???)", f);
	test("?((?((???]})???)", f);
	test("?((?((???]})???)??())?", f);
}
 
Example 9
Project: diorite-configs-java8   File: ConfigPropertyTemplateImpl.java   View source code 6 votes vote down vote up
public ConfigPropertyTemplateImpl(ConfigTemplate<?> template, Class<T> rawType, Type genericType, String name, Function<Config, T> defaultValueSupplier,
                                  AnnotatedElement annotatedElement)
{
    this.template = template;
    this.rawType = rawType;
    this.genericType = genericType;
    this.defaultValueSupplier = defaultValueSupplier;
    this.annotatedElement = annotatedElement;
    this.originalName = name;
    Comment comment = this.annotatedElement.getAnnotation(Comment.class);
    if (this.annotatedElement.isAnnotationPresent(CustomKey.class))
    {
        this.name = this.annotatedElement.getAnnotation(CustomKey.class).value();
    }
    else if ((comment != null) && ! comment.name().isEmpty())
    {
        this.name = comment.name();
    }
    else
    {
        this.name = name;
    }
}
 
Example 10
Project: openjdk-jdk10   File: JdepsConfiguration.java   View source code 6 votes vote down vote up
/**
 * Returns the list of packages that split between resolved module and
 * unnamed module
 */
public Map<String, Set<String>> splitPackages() {
    Set<String> splitPkgs = packageToModule.keySet().stream()
                                   .filter(packageToUnnamedModule::containsKey)
                                   .collect(toSet());
    if (splitPkgs.isEmpty())
        return Collections.emptyMap();

    return splitPkgs.stream().collect(toMap(Function.identity(), (pn) -> {
        Set<String> sources = new LinkedHashSet<>();
        sources.add(packageToModule.get(pn).getModule().location().toString());
        packageToUnnamedModule.get(pn).stream()
            .map(Archive::getPathName)
            .forEach(sources::add);
        return sources;
    }));
}
 
Example 11
Project: Reinickendorf_SER316   File: ApiClient.java   View source code 6 votes vote down vote up
public <T> T sendRequest (Function <WebClient, T> request) {
	int retries = 0;
	do {
		try {
			WebClient webClientCopy = WebClient.fromClient(webClient);
			T response = request.apply(webClientCopy);
			webClientCopy.close();
			return response;
		}
		catch (NotAuthorizedException e) {
			if (retries < 5) {
				retries ++;
				authClient.refreshAuthenticationContext();
			}
			else throw e;
		}
	} 
	while (retries < 5);
	
	return null;
}
 
Example 12
Project: jspare-vertx-ms-blueprint   File: ConfigurationProviderVertxEBProxy.java   View source code 6 votes vote down vote up
private <T> List<T> convertList(List list) {
  if (list.isEmpty()) { 
        return (List<T>) list; 
      } 
   
  Object elem = list.get(0); 
  if (!(elem instanceof Map) && !(elem instanceof List)) { 
    return (List<T>) list; 
  } else { 
    Function<Object, T> converter; 
    if (elem instanceof List) { 
      converter = object -> (T) new JsonArray((List) object); 
    } else { 
      converter = object -> (T) new JsonObject((Map) object); 
    } 
    return (List<T>) list.stream().map(converter).collect(Collectors.toList()); 
  } 
}
 
Example 13
Project: datarouter   File: CollectorToolTests.java   View source code 6 votes vote down vote up
@Test
public void testToMap(){
	List<String> list = Arrays.asList("a2", "bb3", "bb9", "c", "ddd4", "eeee5");
	Function<String,String> keyMapper = key -> {
		return key.startsWith("e") ? null : key.charAt(0) + "";
	};
	Function<String,Integer> valueMapper = key -> {
		if(key.equals("c")){
			return null;
		}
		char lastChar = key.charAt(key.length() - 1);
		return Integer.parseInt(lastChar + "");
	};
	Map<String,Integer> map = list.stream().collect(CollectorTool.toMap(keyMapper, valueMapper));
	Iterator<Entry<String,Integer>> iterator = map.entrySet().iterator();
	Assert.assertEquals(nextIn(iterator), "a=2");
	Assert.assertEquals(nextIn(iterator), "b=9");
	Assert.assertEquals(nextIn(iterator), "c=null");
	Assert.assertEquals(nextIn(iterator), "d=4");
	Assert.assertEquals(nextIn(iterator), "null=5");
	Assert.assertFalse(iterator.hasNext());
}
 
Example 14
Project: openjdk-jdk10   File: NodeBuilderTest.java   View source code 6 votes vote down vote up
@Test(dataProvider = "Node.Builder<Double>")
public void testDoubleIteration(List<Double> l, Function<Integer, Node.Builder.OfDouble> m) {
    Node.Builder.OfDouble nb = m.apply(l.size());
    nb.begin(l.size());
    for (Double i : l) {
        nb.accept((double) i);
    }
    nb.end();

    Node.OfDouble n = nb.build();
    assertEquals(n.count(), l.size());

    {
        List<Double> _l = new ArrayList<>();
        n.forEach((DoubleConsumer) _l::add);

        assertContents(_l, l);
    }

}
 
Example 15
Project: openjdk-jdk10   File: ForEachOpTest.java   View source code 6 votes vote down vote up
@Test(groups = { "serialization-hostile" })
public void testIntForEachOrdered() {
    List<Integer> input = countTo(10000);
    TestData.OfInt data = TestData.Factory.ofIntSupplier("[1, 10000]",
                                                         () -> IntStream.range(1, 10001));

    Function<IntStream, List<Integer>> terminalFunc = s -> {
        List<Integer> l = new ArrayList<>();
        s.forEachOrdered(l::add);
        return l;
    };

    // Test head
    withData(data).
            terminal(terminalFunc).
            expectedResult(input).
            exercise();

    // Test multiple stages
    withData(data).
            terminal(s -> s.map(i -> i), terminalFunc).
            expectedResult(input).
            exercise();
}
 
Example 16
Project: collectors-utils   File: FlatMappingTest.java   View source code 6 votes vote down vote up
@Test
public void should_collect_flat_map_a_non_empty_stream_into_a_stream() {

    // Given
    Stream<String> strings = Stream.of("one", "two", "three");
    Function<String, Stream<Character>> streamMapper = string -> string.chars().mapToObj(letter -> (char)letter);

    Collector<String, ?, Stream<Character>> streamCollector = CollectorsUtils.flatMapping(streamMapper);

    // When
    List<Character> characters = strings.collect(streamCollector).collect(toList());

    // Then
    assertThat(characters.size()).isEqualTo(11);
    assertThat(characters).containsExactly('o', 'n', 'e', 't', 'w', 'o', 't', 'h', 'r', 'e', 'e');
}
 
Example 17
Project: wall-t   File: ApiModule.java   View source code 5 votes vote down vote up
@Provides
@Singleton
public Map<ApiVersion, Function<Build, BuildData>> buildByApiVersion( ) {
    return ImmutableMap.of(
            ApiVersion.API_6_0,
            build -> new BuildData( build.getId( ), build.getStatus( ),
                    build.isRunning( ) ? BuildState.running : BuildState.finished,
                    build.isRunning( ) ? build.getRunningInformation( ).getPercentageComplete( ) : 100,
                    Optional.ofNullable( build.getFinishDate( ) ),
                    build.isRunning( ) ? Duration.of( build.getRunningInformation( ).getEstimatedTotalTime( ) - build.getRunningInformation( ).getElapsedTime( ), ChronoUnit.SECONDS ) : Duration.ZERO ),


            ApiVersion.API_7_0,
            build -> new BuildData( build.getId( ), build.getStatus( ),
                    build.isRunning( ) ? BuildState.running : BuildState.finished,
                    build.isRunning( ) ? build.getRunningInformation( ).getPercentageComplete( ) : 100,
                    Optional.ofNullable( build.getFinishDate( ) ),
                    build.isRunning( ) ? Duration.of( build.getRunningInformation( ).getEstimatedTotalTime( ) - build.getRunningInformation( ).getElapsedTime( ), ChronoUnit.SECONDS ) : Duration.ZERO ),

            ApiVersion.API_8_0,
            build -> new BuildData( build.getId( ), build.getStatus( ),
                    build.isRunning( ) ? BuildState.running : BuildState.finished,
                    build.isRunning( ) ? build.getRunningInformation( ).getPercentageComplete( ) : 100,
                    Optional.ofNullable( build.getFinishDate( ) ),
                    build.isRunning( ) ? Duration.of( build.getRunningInformation( ).getEstimatedTotalTime( ) - build.getRunningInformation( ).getElapsedTime( ), ChronoUnit.SECONDS ) : Duration.ZERO ),

            ApiVersion.API_8_1,
            build -> new BuildData( build.getId( ), build.getStatus( ),
                    build.getState( ),
                    build.getState( ) == BuildState.running ? build.getRunningInformation( ).getPercentageComplete( ) : 100,
                    Optional.ofNullable( build.getFinishDate( ) ),
                    build.getState( ) == BuildState.running ? Duration.of( build.getRunningInformation( ).getEstimatedTotalTime( ) - build.getRunningInformation( ).getElapsedTime( ), ChronoUnit.SECONDS ) : Duration.ZERO )
    );
}
 
Example 18
Project: flux-capacitor-client   File: HandlerInspector.java   View source code 5 votes vote down vote up
private static <M> List<Function<M, Object>> getParameterSuppliers(Method method,
                                                                   List<ParameterResolver<M>> resolvers) {
    if (method.getParameterCount() == 0) {
        throw new IllegalStateException("Annotated method should contain at least one parameter");
    }
    return Arrays.stream(method.getParameters())
            .map(p -> resolvers.stream().map(r -> r.resolve(p)).filter(Objects::nonNull).findFirst()
                    .orElseThrow(() -> new IllegalStateException("Could not resolve parameter " + p)))
            .collect(toList());
}
 
Example 19
Project: generator-thundr-gae-react   File: ReferenceDataService.java   View source code 5 votes vote down vote up
@SuppressWarnings("unchecked")
private <T extends ReferenceData> Function<T, ReferenceDataDto> getTransformer(Class<T> referenceDataClass) {
    Optional transformer = customTransformers
        .entrySet()
        .stream()
        .filter(entry -> entry.getKey().isAssignableFrom(referenceDataClass))
        .map(Map.Entry::getValue)
        .findFirst();
    return (Function<T, ReferenceDataDto>) transformer.orElse(ReferenceData.TO_DTO_TRANSFORMER);
}
 
Example 20
Project: ytk-learn   File: DataUtils.java   View source code 5 votes vote down vote up
public static <T, R> void travel(Function<T, R> func, List<Iterator<T>> iterators) {
    for (Iterator<T> it : iterators) {
        while(it.hasNext()) {
            func.apply(it.next());
        }
    }

}
 
Example 21
Project: ReactPropTypes-Plugin   File: PropTypesHelper.java   View source code 5 votes vote down vote up
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
    Set<Object> seen = ConcurrentHashMap.newKeySet();
    return t -> seen.add(keyExtractor.apply(t));
}
 
Example 22
Project: log4j2-elasticsearch   File: BulkProcessorObjectFactory.java   View source code 5 votes vote down vote up
@Override
public Function<BulkRequest, Boolean> createFailureHandler(FailoverPolicy failover) {
    return new Function<BulkRequest, Boolean>() {

        private final BulkRequestIntrospector introspector = new BulkRequestIntrospector();

        @Override
        public Boolean apply(BulkRequest bulk) {
            introspector.items(bulk).forEach(failedItem -> failover.deliver(failedItem));
            return true;
        }

    };
}
 
Example 23
Project: pipelines   File: BeamFunctions.java   View source code 5 votes vote down vote up
/**
 * A wrapper to expose the given function suitable for a beam pipeline.
 * <em>It is the reponsibility of the user to ensure that appropriate serializers are registered in Beam</em>.
 *
 * @param source To wrap.
 * @param <IN> The type of input
 * @param <OUT> The type of output
 * @return A function suitable for calling in Beam.
 */
public static <IN,OUT> DoFn<IN, OUT> beamify(Function<IN, OUT> source) {
  return new DoFn<IN, OUT>() {

    @ProcessElement
    public void processElement(ProcessContext c)
      throws InvocationTargetException, IllegalAccessException, IntrospectionException {
      c.output(source.apply(c.element()));
    }
  };
}
 
Example 24
Project: otus_java_2017_10   File: DBServiceImpl.java   View source code 5 votes vote down vote up
private <R> R runInSession(Function<Session, R> function) {
    try (Session session = sessionFactory.openSession()) {
        Transaction transaction = session.beginTransaction();
        R result = function.apply(session);
        transaction.commit();
        return result;
    }
}
 
Example 25
Project: sporticus   File: LoggerImplLog4j.java   View source code 5 votes vote down vote up
private <T> void log(Level level, T[] items, Function<T, String> func) {
	try {
		if (logger.isEnabledFor(level)) {
			Arrays.stream(items).forEach(t -> logger.log(level, func.apply(t)));
		}
	} catch (Exception e) {
		logger.warn("log statement failed", e);
	}
}
 
Example 26
Project: pbt-junit-quickcheck   File: GreatestCommonDivisorCalculator.java   View source code 5 votes vote down vote up
public long primeFactors(final long a, final long b)
{
	final PrimeFactorCalculator pfc = new PrimeFactorCalculator();
	final Map<Long, Long> factorsA = pfc.factor(a).stream()
			.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
	final Map<Long, Long> factorsB = pfc.factor(b).stream()
			.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
	final Stream<Long> factorsBoth = factorsA.entrySet().stream().map(e -> e.getKey())
			.filter(k -> factorsB.containsKey(k));
	return factorsBoth.map(f -> (long) Math.pow(f, Math.min(factorsA.get(f), factorsB.get(f))))
			.reduce(1L, (f1, f2) -> f1 * f2);
}
 
Example 27
Project: streamingpool-core   File: ErrorDeflector.java   View source code 5 votes vote down vote up
public <S, T> io.reactivex.functions.Function<S, Optional<T>> emptyOnException(Function<S, T> function) {
    return val -> {
        try {
            return Optional.of(function.apply(val));
        } catch (Exception e) {
            deflectOperationIncomingError(function, val, e);
            return Optional.empty();
        }
    };
}
 
Example 28
Project: teemo   File: WebviewValueSwitcherTest.java   View source code 5 votes vote down vote up
private Function<IBasicContextSwitcher<Object>, String> getValueGetter() {
	return new Function<IBasicContextSwitcher<Object>, String>() {
		@Override
		public String apply(IBasicContextSwitcher<Object> t) {
			// current/url/current
			String c = t.currentContextOrWindow();
			return c + "/url/" + c;
		}
	};
}
 
Example 29
Project: Unified-World-Units   File: MassUnit.java   View source code 5 votes vote down vote up
public MassUnit(String symbol, String singularName, String pluralName,
		Function<BigDecimalAmount, BigDecimalAmount> translationToCanonical,
		Function<BigDecimalAmount, BigDecimalAmount> translationFromCanonical) {

	super(2, symbol, singularName, pluralName, translationToCanonical, translationFromCanonical);

	unitCounter = new UnitCounter(this);
}
 
Example 30
Project: jdk8u-jdk   File: LongNodeTest.java   View source code 5 votes vote down vote up
private Node.OfLong tree(List<Long> l, Function<List<Long>, Node.OfLong> m) {
    if (l.size() < 3) {
        return m.apply(l);
    }
    else {
        return new Nodes.ConcNode.OfLong(
                tree(l.subList(0, l.size() / 2), m),
                tree(l.subList(l.size() / 2, l.size()), m));
    }
}
 
Example 31
Project: qpp-conversion-tool   File: Registry.java   View source code 5 votes vote down vote up
/**
 * Creates a function that will return new instances of the handlerClass
 *
 * @param handlerClass The class of which to create new instances
 * @return A function that returns instances of the handlerClass when supplied with a context
 */
private Function<Context, Object> createHandler(Class<?> handlerClass) {
	try {
		return createHandlerConstructor(handlerClass);
	} catch (NoSuchMethodException | IllegalAccessException e) {
		DEV_LOG.warn("Unable to create constructor handle", e);
		return ignore -> null;
	}
}
 
Example 32
Project: tascalate-concurrent   File: CallbackRegistry.java   View source code 5 votes vote down vote up
@Override
protected State<S> addCallbacks(Function<? super Callable<?>, ? extends Runnable> targetSetup,
                                Function<? super S, ?> successCallback, 
                                Function<Throwable, ?> failureCallback, 
                                Executor executor) {
    
    callbacks.add(new CallbackHolder<>(targetSetup, successCallback, failureCallback, executor));
    return this;
}
 
Example 33
Project: soabase-stages   File: StagedFutureImpl.java   View source code 5 votes vote down vote up
@Override
public <U> StagedFutureTimeout<U> thenIf(Function<T, Optional<U>> proc) {
    Objects.requireNonNull(proc, "proc cannot be null");

    // don't burn a thread if the optional is empty
    CompletionStage<Optional<U>> nextStage = future.thenCompose(optional -> {
        if (optional.isPresent()) {
            Function<T, Optional<U>> tracedProc = tracingProc(tracing, proc);
            return future.thenApplyAsync(__ -> tracedProc.apply(optional.get()), executor);
        }
        return CompletableFuture.completedFuture(Optional.empty());
    });
    return new StagedFutureImpl<>(executor, nextStage, tracing);
}
 
Example 34
Project: stroom-stats   File: QueryApiHelper.java   View source code 5 votes vote down vote up
/**
 * Get all values for a named field, converted into the chosen type
 */
public static <T> List<T> getTypedFieldValues(final FlatResult flatResult,
                                              final String fieldName,
                                              final Class<T> valueType) {

    if (flatResult == null || flatResult.getValues() == null || flatResult.getValues().isEmpty()) {
        return Collections.emptyList();
    }

    int fieldIndex = getFieldIndex(flatResult.getStructure(), fieldName);
    if (fieldIndex == -1) {
        throw new RuntimeException(String.format("Field %s does not exist in the FlatResult, possible fields: %s",
                fieldName, flatResult.getStructure().stream().map(Field::getName).collect(Collectors.joining(","))));
    }

    Function<String, T> conversionFunc = str -> {
        Object val = conversionMap.get(valueType).apply(str);
        try {
            return (T) val;
        } catch (ClassCastException e) {
            throw new RuntimeException(String.format("Unable to cast field %s to type %s", fieldName, valueType.getName()), e);
        }
    };

    //
    return flatResult.getValues().stream()
            .map(values -> values.get(fieldIndex))
            .map(obj -> {
                if (obj.getClass().equals(valueType)) {
                    return (T) obj;
                } else {
                    return conversionFunc.apply(convertValueToStr(obj));
                }
            })
            .collect(Collectors.toList());
}
 
Example 35
Project: koryphe   File: FunctionTest.java   View source code 5 votes vote down vote up
@Test
public void shouldEqualsWhenSameObject() {
    // Given
    final Function instance = getInstance();

    // Then
    assertEquals(instance, instance);
    assertEquals(instance.hashCode(), instance.hashCode());
}
 
Example 36
Project: ARCLib   File: Utils.java   View source code 5 votes vote down vote up
public static <T, U> Set<U> map(Set<T> objects, Function<T, U> func) {
    if (objects != null) {
        return objects.stream()
                      .map(func)
                      .collect(Collectors.toSet());
    } else {
        return null;
    }
}
 
Example 37
Project: reasonml-idea-plugin   File: InferredTypes.java   View source code 5 votes vote down vote up
@NotNull
private static Function<PsiLet, LogicalPosition> letExpressionToLogicalPosition(Editor selectedTextEditor) {
    return letStatement -> {
        PsiElement letName = letStatement.getNameIdentifier();
        if (letName == null) {
            return null;
        }

        int nameOffset = letName.getTextOffset();
        return selectedTextEditor.offsetToLogicalPosition(nameOffset);
    };
}
 
Example 38
Project: openjdk-jdk10   File: ByteBufferViews.java   View source code 5 votes vote down vote up
@DataProvider
public static Object[][] shortViewProvider() {
    List<Map.Entry<String, Function<ByteBuffer, ShortBuffer>>> bfs = List.of(
            Map.entry("bb.asShortBuffer()",
                      bb -> bb.asShortBuffer()),
            Map.entry("bb.asShortBuffer().slice()",
                      bb -> bb.asShortBuffer().slice()),
            Map.entry("bb.asShortBuffer().slice().duplicate()",
                      bb -> bb.asShortBuffer().slice().duplicate())
    );

    return product(BYTE_BUFFER_FUNCTIONS, bfs);
}
 
Example 39
Project: vertx-jooq-async   File: AsyncJooqSQLClientImpl.java   View source code 5 votes vote down vote up
@Override
public <P> CompletableFuture<P> fetchOne(Query query, Function<JsonObject, P> mapper){
    return getConnection().thenCompose(sqlConnection -> {
        CompletableFuture<P> cf = new VertxCompletableFuture<P>(vertx);
        sqlConnection.queryWithParams(query.getSQL(), getBindValues(query), executeAndClose(rs -> {
            Optional<P> optional = rs.getRows().stream().findFirst().map(mapper);
            return optional.orElseGet(() -> null);
        }, sqlConnection, cf));
        return cf;
    });
}
 
Example 40
Project: springmock   File: MockAttachingTestExecutionListener.java   View source code 5 votes vote down vote up
private Optional<Object> tryToGetBean(ApplicationContext applicationContext, DoubleDefinition doubleDefinition) {
	final Function<String, String> beanNameResolver = isFactoryBean(doubleDefinition.getDoubleClass())
			? FactoryBeanRecognizer::getFactoryBeanName
			: Function.identity();

	return Stream
			.concat(
					Stream.of(doubleDefinition.getName()),
					doubleDefinition.getAliases().stream())
			.map(beanNameResolver)
			.map(nameOrAlias -> tryToGetBean(applicationContext, nameOrAlias))
			.filter(Optional::isPresent)
			.findFirst()
			.orElse(Optional.empty());
}