@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); }
@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)); }
@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); }
@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)); }
/** * 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; } }
/** * 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]; } }
@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()); }
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); }
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; } }
/** * 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; })); }
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; }
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()); } }
@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()); }
@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); } }
@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(); }
@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'); }
@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 ) ); }
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()); }
@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); }
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()); } } }
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) { Set<Object> seen = ConcurrentHashMap.newKeySet(); return t -> seen.add(keyExtractor.apply(t)); }
@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; } }; }
/** * 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())); } }; }
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; } }
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); } }
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); }
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(); } }; }
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; } }; }
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); }
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)); } }
/** * 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; } }
@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; }
@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); }
/** * 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()); }
@Test public void shouldEqualsWhenSameObject() { // Given final Function instance = getInstance(); // Then assertEquals(instance, instance); assertEquals(instance.hashCode(), instance.hashCode()); }
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; } }
@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); }; }
@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); }
@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; }); }
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()); }