Java Examples for java.util.function.Supplier

The following java examples will help you to understand the usage of java.util.function.Supplier. These source code samples are taken from different open source projects.

Example 1
Project: checker-framework-master  File: Issue436.java View source code
public void makeALongFormConditionalLambdaReturningGenerics(boolean makeAll) {
    // TypeArgInferenceUtil.assignedTo used to try to use the method return rather than the lambda return
    // for those return statements below
    Supplier<List<String>> supplier = () -> {
        if (makeAll) {
            return asList("beer", "peanuts");
        } else {
            return asList("cheese", "wine");
        }
    };
}
Example 2
Project: intellij-community-master  File: ImportTestOutputExtension.java View source code
@NotNull
static DefaultHandler findHandler(final Supplier<Reader> readerSupplier, GeneralTestEventsProcessor processor) {
    for (ImportTestOutputExtension extension : Extensions.getExtensions(EP_NAME)) {
        Reader reader = readerSupplier.get();
        if (reader == null)
            continue;
        try {
            DefaultHandler handler = extension.createHandler(reader, processor);
            if (handler != null)
                return handler;
        } catch (IOException ignored) {
        }
    }
    return new ImportedTestContentHandler(processor);
}
Example 3
Project: NOVA-Core-master  File: SupplierModule.java View source code
@Override
public java.util.function.Supplier<?> supply(Dependency<? super java.util.function.Supplier<?>> dependency, Injector injector) {
    Dependency<?> providedType = dependency.onTypeParameter();
    if (!dependency.getName().isDefault()) {
        providedType = providedType.named(dependency.getName());
    }
    final Dependency<?> finalProvidedType = providedType;
    return () -> SuppliedBy.lazyProvider(finalProvidedType.uninject().ignoredExpiry(), injector).provide();
}
Example 4
Project: java8-the-missing-tutorial-master  File: Example3_Functionalnterfaces.java View source code
public static void main(String[] args) {
    Predicate<String> nameStartWithS =  name -> name.startsWith("s");
    Consumer<String> sendEmail =  message -> System.out.println("Sending email >> " + message);
    Function<String, Integer> stringToLength =  name -> name.length();
    Supplier<String> uuidSupplier = () -> UUID.randomUUID().toString();
}
Example 5
Project: jena-sparql-api-master  File: JenaExtensionBatch.java View source code
public static void initJenaExtensions(ApplicationContext context) {
    //ApplicationContext baseContext = initBaseContext();
    @SuppressWarnings("unchecked") Supplier<HttpClient> httpClientSupplier = (Supplier<HttpClient>) context.getBean("httpClientSupplier");
    JenaExtensionJson.register();
    JenaExtensionHttp.register(httpClientSupplier);
    JenaExtensionTerm.register();
}
Example 6
Project: checkstyle-master  File: InputMethodReferences.java View source code
public void main(String[] args) {
    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
    numbers.forEach(String.CASE_INSENSITIVE_ORDER::equals);
    InputMethodReferences tl = new InputMethodReferences();
    String roster = new String();
    Supplier<InputMethodReferences> supplier = InputMethodReferences<String>::new;
    numbers.forEach(this::println);
    numbers.forEach(super::println);
    Supplier<InputMethodReferences2> supplier2 = InputMethodReferences2::new;
    Supplier<InputMethodReferences2> suppl = InputMethodReferences2::<Integer>new;
    Function<Integer, String[]> messageArrayFactory = String[]::new;
}
Example 7
Project: infinispan-master  File: TxDistributedLongCacheStream.java View source code
@Override
protected Supplier<Stream<CacheEntry>> supplierForSegments(ConsistentHash ch, Set<Integer> targetSegments, Set<Object> excludedKeys, boolean primaryOnly) {
    return () -> {
        Supplier<Stream<CacheEntry>> supplier = super.supplierForSegments(ch, targetSegments, excludedKeys, primaryOnly);
        Set<CacheEntry> set = ctx.getLookedUpEntries().values().stream().filter( e -> !isPrimaryOwner(ch, e)).collect(Collectors.toSet());
        Stream<CacheEntry> suppliedStream = supplier.get();
        if (!set.isEmpty()) {
            return Stream.concat(set.stream(), suppliedStream);
        }
        return suppliedStream;
    };
}
Example 8
Project: kludje-master  File: AltIterators.java View source code
public static <E> Iterator<E> iterateUntil(Supplier<? extends E> supplier, Predicate<? super E> stop) {
    Ensure.that(supplier != null, "supplier != null");
    Ensure.that(stop != null, "stop != null");
    class UntilIterator implements Iterator<E> {

        E next = supplier.get();

        @Override
        public boolean hasNext() {
            return stop.test(next);
        }

        @Override
        public E next() {
            if (!hasNext()) {
                throw new NoSuchElementException("Stopped on value '" + next + "'");
            }
            try {
                return next;
            } finally {
                next = supplier.get();
            }
        }
    }
    return new UntilIterator();
}
Example 9
Project: MicroBench-master  File: RandomSorter.java View source code
public static void main(String[] args) {
    Random random = new Random();
    final int[] data = IntStream.generate(random::nextInt).limit(10000).toArray();
    final int[] sorted = Arrays.stream(data).sorted().toArray();
    Predicate<int[]> validate =  v -> Arrays.equals(v, sorted);
    Supplier<int[]> stream = () -> Arrays.stream(data).sorted().toArray();
    Supplier<int[]> trad = () -> {
        int[] copy = Arrays.copyOf(data, data.length);
        Arrays.sort(copy);
        return copy;
    };
    new UBench("Sort Algorithms").addTask("Functional", stream, validate).addTask("Traditional", trad, validate).press(10000).report("With Warmup");
}
Example 10
Project: phantom-pojos-master  File: PhantomBuilderProxy.java View source code
private Object reify(Object arg, Type targetType) {
    if (arg == null) {
        return null;
    }
    if (arg instanceof Collection) {
        return reifyStream(targetType, ((Collection<Object>) arg).stream());
    }
    if (arg.getClass().isArray()) {
        return reifyStream(targetType, Stream.of(ReflectionUtils.toObjectArray(arg)));
    }
    return arg instanceof Supplier ? ((Supplier<?>) arg).get() : arg;
}
Example 11
Project: requery-master  File: BaseScalar.java View source code
@Override
public CompletableFuture<E> toCompletableFuture(Executor executor) {
    final java.util.function.Supplier<E> supplier = new java.util.function.Supplier<E>() {

        @Override
        public E get() {
            return BaseScalar.this.value();
        }
    };
    return executor == null ? CompletableFuture.supplyAsync(supplier) : CompletableFuture.supplyAsync(supplier, executor);
}
Example 12
Project: blobkeeper-master  File: Streams.java View source code
@NotNull
public static <T> Stream<ResultWrapper<T>> parallelize(int n, @NotNull Supplier<T> supplier) {
    // operations will be executed in parallel
    List<CompletableFuture<ResultWrapper<T>>> results = IntStream.iterate(0,  i -> i + 1).limit(n).boxed().map( ignored -> CompletableFuture.supplyAsync(new ResultSupplier<>(supplier), parallelExecutor)).collect(toImmutableList());
    return collect(results);
}
Example 13
Project: AsciidocFX-master  File: FxCompletableFeature.java View source code
public <U> FxCompletableFeature<U> supplyAsyncFx(Supplier<U> supplier) {
    FxCompletableFeature<U> fxCompletableFeature = new FxCompletableFeature<>();
    super.supplyAsync(() -> {
        Platform.runLater(() -> {
            try {
                U u = supplier.get();
                fxCompletableFeature.complete(u);
            } catch (Exception ex) {
                fxCompletableFeature.completeExceptionally(ex);
            }
        });
        return (U) fxCompletableFeature.join();
    });
    return fxCompletableFeature;
}
Example 14
Project: com.packtpub.e4-master  File: TimeZonesProvider.java View source code
public Map<String, Set<ZoneId>> getTimeZones() {
    Supplier<Set<ZoneId>> sortedZones = () -> new TreeSet<>(new TimeZoneComparator());
    Map<String, Set<ZoneId>> timeZones = // stream
    ZoneId.getAvailableZoneIds().stream().filter(// with / in them
     s -> s.contains("/")).limit(// return this many only
    max).map(// convert to ZoneId
    ZoneId::of).collect(// and group by
    Collectors.groupingBy(// first part
     z -> z.getId().split("/")[0], TreeMap::new, Collectors.toCollection(sortedZones)));
    if (logService != null) {
        logService.log(LogService.LOG_INFO, "Time zones loaded with " + timeZones.size());
    }
    return timeZones;
}
Example 15
Project: Consent2Share-master  File: JRDataSourceFactoryTest.java View source code
@Test
public void testNewJRDataSource() throws JRException {
    // Arrange
    final DataRow dataRow = new DataRow("col1", "col2");
    @SuppressWarnings({ "rawtypes", "unchecked" }) final Supplier dataProvider = () -> {
        final List l = new ArrayList();
        l.add(dataRow);
        return l;
    };
    // Act
    @SuppressWarnings("unchecked") final JRDataSource newJRDataSource = JRDataSourceFactory.newJRDataSource(dataProvider);
    // Assert
    assertNotNull(newJRDataSource);
    assertTrue(newJRDataSource.next());
}
Example 16
Project: esper-master  File: TestKafkaInputMsgTimestampBeanSerValue.java View source code
public void testInput() {
    Properties pluginProperties = SupportConstants.getInputPluginProps(TOPIC, SupportBeanFromByteArrayDeserializer.class.getName(), EsperIOKafkaInputTimestampExtractorConsumerRecord.class.getName());
    EPServiceProvider epService = SupportConstants.getEngineWKafkaInput(this.getClass().getSimpleName(), pluginProperties);
    epService.getEPAdministrator().getConfiguration().addEventType(SupportBean.class);
    epService.getEPRuntime().sendEvent(new CurrentTimeEvent(0));
    EPStatement stmt = epService.getEPAdministrator().createEPL("select * from SupportBean");
    SupportListener listener = new SupportListener();
    stmt.addListener(listener);
    // send single message with Java serialization (Java serialization is used for testing here and may not be the best choice)
    Properties producerProperties = SupportConstants.getProducerProps(org.apache.kafka.common.serialization.ByteArraySerializer.class.getName());
    KafkaProducer<String, byte[]> producer = new KafkaProducer<>(producerProperties);
    String generatedUUID = UUID.randomUUID().toString();
    int randomNumber = (int) (Math.random() * 100000000);
    long timestamp = 100000;
    byte[] serializedEvent = SerializerUtil.objectToByteArr(new SupportBean(generatedUUID, randomNumber));
    producer.send(new ProducerRecord<>(TOPIC, 0, timestamp, "key", serializedEvent));
    SupportAwaitUtil.awaitOrFail(10, TimeUnit.SECONDS, "failed to receive expected event", (Supplier<Object>) () -> {
        for (EventBean[] events : listener.getEvents()) {
            for (EventBean event : events) {
                SupportBean bean = (SupportBean) event.getUnderlying();
                if (bean.getStringProp().equals(generatedUUID) && bean.getIntProp() == randomNumber) {
                    return true;
                }
            }
        }
        return null;
    });
    assertEquals(timestamp, epService.getEPRuntime().getCurrentTime());
    producer.close();
    epService.destroy();
}
Example 17
Project: FluentLenium-master  File: FluentLeniumWaitIgnoringTest.java View source code
@Test
public void testIgnoring1Positive() {
    try {
        await().atMost(1, TimeUnit.NANOSECONDS).ignoring(CustomException.class).ignoring(CustomException2.class).until(new Supplier<Boolean>() {

            @Override
            public Boolean get() {
                throw new CustomException();
            }
        });
        throw new AssertionError();
    } catch (// NOPMD EmptyCatchBlock
    TimeoutException // NOPMD EmptyCatchBlock
    e) {
    }
}
Example 18
Project: java-8-lambdas-exercises-master  File: RefactorTest.java View source code
@Test
public void allStringJoins() {
    List<Supplier<Refactor.LongTrackFinder>> finders = Arrays.<Supplier<Refactor.LongTrackFinder>>asList(Refactor.Step0::new, Refactor.Step1::new, Refactor.Step2::new, Refactor.Step3::new, Refactor.Step4::new);
    List<Album> albums = unmodifiableList(asList(SampleData.aLoveSupreme, SampleData.sampleShortAlbum));
    List<Album> noTracks = unmodifiableList(asList(SampleData.sampleShortAlbum));
    finders.forEach( finder -> {
        System.out.println("Testing: " + finder.toString());
        Refactor.LongTrackFinder longTrackFinder = finder.get();
        Set<String> longTracks = longTrackFinder.findLongTracks(albums);
        assertEquals("[Acknowledgement, Resolution]", longTracks.toString());
        longTracks = longTrackFinder.findLongTracks(noTracks);
        assertTrue(longTracks.isEmpty());
    });
}
Example 19
Project: loadr-master  File: HttpService.java View source code
public static HttpServer startServer(String path, Supplier<String> request, Consumer<String> response) throws IOException {
    HttpServer httpServer = HttpServer.create(new InetSocketAddress(4221), 0);
    HttpContext context = httpServer.createContext(path);
    context.setHandler(( he) -> {
        final byte[] bytes = request.get().getBytes();
        he.sendResponseHeaders(200, bytes.length);
        final OutputStream output = he.getResponseBody();
        InputStream input = he.getRequestBody();
        response.accept(read(input));
        output.write(bytes);
        output.flush();
        he.close();
    });
    httpServer.start();
    return httpServer;
}
Example 20
Project: micro-server-master  File: AsyncDataWriter.java View source code
@Override
public Future<T> loadAndGet() {
    String correlationId = "" + System.currentTimeMillis() + ":" + r.nextLong();
    Supplier<MapX<String, String>> dataMap = () -> MapX.fromMap(HashMapBuilder.map(MANIFEST_COMPARATOR_DATA_LOADER_KEY, comparator.toString()).build());
    return Future.ofSupplier(() -> Tuple.tuple(comparator.load(), comparator.getData()), executorService).peek( t -> bus.post(SystemData.<String, String>builder().correlationId(correlationId).dataMap(dataMap.get()).errors(0).processed(t.v1 ? 1 : 0).build())).map(// 1.0.0-final
     t -> t.v2);
}
Example 21
Project: nanobot-master  File: MainScreenSteps.java View source code
private TreeSet<Point> searchPointset(final Supplier<Point> pointSupplier, final int markRGB) {
    final TreeSet<Point> pointset = new TreeSet<>();
    while (true) {
        final Point point = pointSupplier.get();
        if (point == null) {
            break;
        }
        pointset.add(point);
        final BufferedImage screenshot = ScenarioContext.get("screenshot", BufferedImage.class);
        final int x = point.x();
        final int y = point.y();
        screenshot.setRGB(x, y, markRGB);
        screenshot.setRGB(x - 1, y - 1, markRGB);
        screenshot.setRGB(x - 2, y - 2, markRGB);
        screenshot.setRGB(x - 1, y + 1, markRGB);
        screenshot.setRGB(x - 2, y + 2, markRGB);
        screenshot.setRGB(x + 1, y - 1, markRGB);
        screenshot.setRGB(x + 2, y - 2, markRGB);
        screenshot.setRGB(x + 1, y + 1, markRGB);
        screenshot.setRGB(x + 2, y + 2, markRGB);
    }
    return pointset;
}
Example 22
Project: od_7guis-master  File: ODListViews.java View source code
void bindSelectedPmId(ListView<PresentationModel> listView, Supplier<Attribute> attributeSupplier) {
    listView.getSelectionModel().selectedItemProperty().addListener(( s,  o,  n) -> {
        if (n != null) {
            attributeSupplier.get().setValue(n.getId());
        }
    });
    // maintain PMid to idx map:
    if (1 > 2) {
        listView.getItems().addListener(new ListChangeListener<PresentationModel>() {

            @Override
            public void onChanged(Change change) {
                System.out.println("Detected a change! " + change);
                while (change.next()) {
                    if (change.wasAdded()) {
                        System.out.println("added");
                    } else if (change.wasRemoved()) {
                        System.out.println("removed");
                    } else if (change.wasReplaced()) {
                        System.out.println("replaced");
                    } else if (change.wasPermutated()) {
                        System.out.println("permutated");
                    }
                }
            }
        });
    }
}
Example 23
Project: ovirt-engine-master  File: CompatibilityVersionUtils.java View source code
public static Version getEffective(Version vmCustomCompatibilityVersion, Supplier<Version> clusterCompatibilityVersionSupplier) {
    if (vmCustomCompatibilityVersion != null) {
        return vmCustomCompatibilityVersion;
    }
    if (clusterCompatibilityVersionSupplier != null) {
        Version clusterCompatibilityVersion = clusterCompatibilityVersionSupplier.get();
        if (clusterCompatibilityVersion != null) {
            return clusterCompatibilityVersion;
        }
    }
    return Version.getLast();
}
Example 24
Project: rakam-master  File: ClientMessageAutomationAction.java View source code
public String process(String project, Supplier<User> user, Template data) {
    StringTemplate template = new StringTemplate(data.template);
    return template.format(( query) -> {
        Object val = user.get().properties.get(query);
        if (val == null || !(val instanceof String)) {
            return data.variables.get(query);
        }
        return val.toString();
    });
}
Example 25
Project: tjungblut-online-ml-master  File: AbstractOnlineLearner.java View source code
/**
   * Peeks for the feature and outcome dimensions.
   * 
   * @param streamSupplier the supplier that gets streams.
   */
@VisibleForTesting
protected void peekDimensions(Supplier<Stream<FeatureOutcomePair>> streamSupplier) {
    Stream<FeatureOutcomePair> stream = Preconditions.checkNotNull(streamSupplier.get(), "Supplied a null stream!");
    Optional<FeatureOutcomePair> first = stream.findFirst();
    if (!first.isPresent()) {
        throw new IllegalArgumentException("Supplied an empty stream!");
    }
    FeatureOutcomePair firstExample = first.get();
    this.featureDimension = firstExample.getFeature().getDimension();
    this.outcomeDimension = firstExample.getOutcome().getDimension();
    this.numOutcomeClasses = Math.max(2, this.outcomeDimension);
}
Example 26
Project: vertx-unit-master  File: Helper.java View source code
public static Handler<TestContext> invoker(Method method, Supplier<?> instance) {
    Class<?>[] paramTypes = method.getParameterTypes();
    if (!(paramTypes.length == 0 || (paramTypes.length == 1 && paramTypes[0].equals(TestContext.class)))) {
        throw new IllegalArgumentException("Incorrect method handler mapping " + method);
    }
    return  context -> {
        try {
            Object o = instance.get();
            if (paramTypes.length == 0) {
                method.invoke(o);
            } else {
                method.invoke(o, context);
            }
        } catch (IllegalAccessException e) {
            Helper.uncheckedThrow(e);
        } catch (InvocationTargetException e) {
            Helper.uncheckedThrow(e.getCause());
        }
    };
}
Example 27
Project: vorlesung-se2-dhbw-master  File: Scenario.java View source code
public static OverallResult runFor(int iterations, Supplier<? extends Scenario> scenario) {
    OverallResult result = new OverallResult();
    for (int i = 0; i < iterations; i++) {
        Scenario run = scenario.get();
        List<Thread> threads = run.prepare();
        Collections.shuffle(threads);
        RunResult localResult = run.run(threads);
        result.consider(localResult);
        if (0 == i % (iterations / 10)) {
            System.out.print(".");
        }
    }
    return result;
}
Example 28
Project: widow-master  File: Retry.java View source code
public static <T> T retry(Supplier<T> tryMe, int times) throws InterruptedException, RetryFailedException {
    Throwable latestError = null;
    for (int i = 1; i <= times; i++) {
        try {
            logger.info("Trying time " + i);
            return tryMe.get();
        } catch (Throwable t) {
            logger.error("Error while (re)trying ", t);
            latestError = t;
        }
        if (i < times) {
            int sleepTime = random.nextInt(VARIANCE) + (i * i * 1000);
            logger.info("Sleeping for " + sleepTime + "ms");
            Thread.sleep(sleepTime);
        }
    }
    throw new RetryFailedException("Retry could not complete the operation", latestError);
}
Example 29
Project: xapi-master  File: ModelReference.java View source code
@Override
public ModelBuilder<ModelContent> get() {
    return ModelBuilder.build(CONTENT_KEY_BUILDER.get(), new Supplier<ModelContent>() {

        @Override
        public ModelContent get() {
            return X_Model.create(ModelContent.class);
        }
    }).withProperty("related", new ModelContent[0]).withProperty("children", new ModelContent[0]);
}
Example 30
Project: openjdk-master  File: ModuleUtils.java View source code
/**
     * Returns a ModuleFinder that finds modules with the given module
     * descriptors.
     */
static ModuleFinder finderOf(ModuleDescriptor... descriptors) {
    // Create a ModuleReference for each module
    Map<String, ModuleReference> namesToReference = new HashMap<>();
    for (ModuleDescriptor descriptor : descriptors) {
        String name = descriptor.name();
        URI uri = URI.create("module:/" + name);
        Supplier<ModuleReader> supplier = () -> {
            throw new UnsupportedOperationException();
        };
        ModuleReference mref = new ModuleReference(descriptor, uri, supplier);
        namesToReference.put(name, mref);
    }
    return new ModuleFinder() {

        @Override
        public Optional<ModuleReference> find(String name) {
            Objects.requireNonNull(name);
            return Optional.ofNullable(namesToReference.get(name));
        }

        @Override
        public Set<ModuleReference> findAll() {
            return new HashSet<>(namesToReference.values());
        }
    };
}
Example 31
Project: tinkerpop-master  File: TraversalSideEffects.java View source code
/**
     * If the sideEffect contains an object associated with the key, return it.
     * Else if a "with" supplier exists for the key, generate the object, store it in the sideEffects and return the object.
     * Else use the provided supplier to generate the object, store it in the sideEffects and return the object.
     * Note that if the orCreate supplier is used, it is NOT registered as a {@link java.util.function.Supplier}.
     *
     * @param key      the key of the object to get
     * @param orCreate if the object doesn't exist as an object or suppliable object, then generate it with the specified supplier
     * @param <V>      the return type of the object
     * @return the object that is either retrieved, generated, or supplier via orCreate
     * @deprecated As of release 3.2.0, replaced by {@link TraversalSideEffects#register(String, Supplier, BinaryOperator)} to register side-effects.
     */
@Deprecated
public default <V> V getOrCreate(final String key, final Supplier<V> orCreate) {
    final V value = this.exists(key) ? this.get(key) : null;
    if (null != value)
        return value;
    final Optional<Supplier<V>> with = this.getRegisteredSupplier(key);
    if (with.isPresent()) {
        final V v = with.get().get();
        this.set(key, v);
        return v;
    } else {
        final V v = orCreate.get();
        this.set(key, v);
        return v;
    }
}
Example 32
Project: accumulo-master  File: CompletableFutureUtil.java View source code
// create a binary tree of completable future operations, where each node in the tree merges the results of their children when complete
public static <T> CompletableFuture<T> merge(List<CompletableFuture<T>> futures, BiFunction<T, T, T> mergeFunc, Supplier<T> nothing) {
    if (futures.size() == 0) {
        return CompletableFuture.completedFuture(nothing.get());
    }
    while (futures.size() > 1) {
        ArrayList<CompletableFuture<T>> mergedFutures = new ArrayList<>(futures.size() / 2);
        for (int i = 0; i < futures.size(); i += 2) {
            if (i + 1 == futures.size()) {
                mergedFutures.add(futures.get(i));
            } else {
                mergedFutures.add(futures.get(i).thenCombine(futures.get(i + 1), mergeFunc));
            }
        }
        futures = mergedFutures;
    }
    return futures.get(0);
}
Example 33
Project: async-google-pubsub-client-master  File: AssertWithTimeout.java View source code
static <T> void assertThatWithin(final long timeout, final TimeUnit unit, final Supplier<T> actual, final Matcher<? super T> matcher) {
    final long start = System.nanoTime();
    final long deadline = start + unit.toNanos(timeout);
    while (true) {
        if (System.nanoTime() > deadline) {
            assertThat(actual.get(), matcher);
            return;
        }
        if (matcher.matches(actual.get())) {
            return;
        }
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return;
        }
    }
}
Example 34
Project: autopsy-master  File: FilterCheckBoxCellFactory.java View source code
@Override
protected void configureCell(IndexedCell<? extends X> cell, X item, boolean empty, Supplier<X> supplier) {
    if (selectedProperty != null) {
        checkBox.selectedProperty().unbindBidirectional(selectedProperty);
    }
    if (disabledProperty != null) {
        checkBox.disableProperty().unbind();
    }
    if (item == null) {
        cell.setGraphic(null);
    } else {
        checkBox.setText(item.getDisplayName());
        //            cell.setText(item.getDisplayName());
        selectedProperty = item.selectedProperty();
        checkBox.selectedProperty().bindBidirectional(selectedProperty);
        disabledProperty = item.disabledProperty();
        checkBox.disableProperty().bind(disabledProperty);
        cell.setGraphic(checkBox);
    }
}
Example 35
Project: AxonFramework-master  File: CollectionUtils.java View source code
/**
     * Merge two collections into a new collection instance. The new collection is created using the given {@code
     * factoryMethod}.
     * <p>
     * If any of the two inputs collections is {@code null} or empty the other input collection is returned (even if
     * that one is {@code null} as well).
     *
     * @param collection1 the first collection
     * @param collection2 the second collection
     * @param factoryMethod function to initialize the new collection
     * @param <S> the type of elements in the collections
     * @param <T> the type of collection
     * @return a collection that combines both collections
     */
public static <S, T extends Collection<S>> T merge(T collection1, T collection2, Supplier<T> factoryMethod) {
    if (collection1 == null || collection1.isEmpty()) {
        return collection2;
    }
    if (collection2 == null || collection2.isEmpty()) {
        return collection1;
    }
    T combined = factoryMethod.get();
    combined.addAll(collection1);
    combined.addAll(collection2);
    return combined;
}
Example 36
Project: bergamot-master  File: Matchers.java View source code
@SuppressWarnings({ "rawtypes", "unchecked" })
public Matcher<?> buildMatcher(MatchOn match) {
    if (match == null)
        return null;
    // find a factory
    Supplier<Matcher<?>> matcherFactory = this.matchers.get(match.getClass());
    if (matcherFactory == null)
        return null;
    // create the matcher
    Matcher<?> matcher = matcherFactory.get();
    if (!((Matcher) matcher).build(this, match))
        return null;
    return matcher;
}
Example 37
Project: brave-master  File: BraveRunnableTest.java View source code
Span attachesSpanInRunnable(Supplier<Span> createSpan, Supplier<Span> currentSpan) throws Exception {
    Span span = createSpan.get();
    Runnable runnable = BraveRunnable.wrap(() -> assertThat(currentSpan.get()).isEqualTo(span), brave);
    // create another span between the time the task was made and executed.
    Span nextSpan = createSpan.get();
    // runs assertion
    runnable.run();
    return nextSpan;
}
Example 38
Project: cf-java-client-master  File: LastOperationUtils.java View source code
public static Mono<Void> waitForCompletion(Duration completionTimeout, Supplier<Mono<LastOperation>> lastOperationSupplier) {
    return lastOperationSupplier.get().map(LastOperation::getState).filter( state -> !IN_PROGRESS.equals(state)).repeatWhenEmpty(DelayUtils.exponentialBackOff(Duration.ofSeconds(1), Duration.ofSeconds(15), completionTimeout)).onErrorResume( t -> t instanceof ClientV2Exception && ((ClientV2Exception) t).getStatusCode() == 404,  t -> Mono.empty()).then();
}
Example 39
Project: chaos-lemur-master  File: Precedence.java View source code
<U> U get(Function<T, U> f) {
    synchronized (this.monitor) {
        for (Supplier<T> supplier : this.suppliers) {
            T value = supplier.get();
            if (value != null) {
                return f.apply(value);
            }
        }
        throw new IllegalStateException("No non-null values supplied");
    }
}
Example 40
Project: dragome-sdk-master  File: Collectors.java View source code
public static <T> Collector<T, ?, List<T>> toList() {
    return new Collector<T, Object, List<T>>() {

        List<Object> result = new ArrayList<Object>();

        public Supplier<Object> supplier() {
            return null;
        }

        public BiConsumer<Object, T> accumulator() {
            return ( o,  t) -> result.add(t);
        }

        public BinaryOperator<Object> combiner() {
            return null;
        }

        public Function<Object, List<T>> finisher() {
            return  o -> (List) result;
        }

        public Set<Characteristics> characteristics() {
            return null;
        }
    };
}
Example 41
Project: guide-master  File: Lambda3.java View source code
public static void main(String[] args) throws Exception {
    // Predicates
    Predicate<String> predicate = ( s) -> s.length() > 0;
    // true
    predicate.test("foo");
    // false
    predicate.negate().test("foo");
    Predicate<Boolean> nonNull = Objects::nonNull;
    Predicate<Boolean> isNull = Objects::isNull;
    Predicate<String> isEmpty = String::isEmpty;
    Predicate<String> isNotEmpty = isEmpty.negate();
    // Functions
    Function<String, Integer> toInteger = Integer::valueOf;
    Function<String, String> backToString = toInteger.andThen(String::valueOf);
    // "123"
    backToString.apply("123");
    // Suppliers
    Supplier<Person> personSupplier = Person::new;
    // new Person
    personSupplier.get();
    // Consumers
    Consumer<Person> greeter = ( p) -> System.out.println("Hello, " + p.firstName);
    greeter.accept(new Person("Luke", "Skywalker"));
    // Comparators
    Comparator<Person> comparator = ( p1,  p2) -> p1.firstName.compareTo(p2.firstName);
    Person p1 = new Person("John", "Doe");
    Person p2 = new Person("Alice", "Wonderland");
    // > 0
    comparator.compare(p1, p2);
    // < 0
    comparator.reversed().compare(p1, p2);
    // Runnables
    Runnable runnable = () -> System.out.println(UUID.randomUUID());
    runnable.run();
    // Callables
    Callable<UUID> callable = UUID::randomUUID;
    callable.call();
}
Example 42
Project: haogrgr-test-master  File: JDK8GroupByTest.java View source code
public static <T> Collector<? super T, ?, T> reducing(BinaryOperator<T> op) {
    Supplier<SettableValue<T>> supplier = SettableValue::new;
    BiConsumer<SettableValue<T>, T> accumulator = ( box,  ele) -> box.set(ele);
    BinaryOperator<SettableValue<T>> combiner = SettableValue::merge;
    Function<SettableValue<T>, T> finisher = SettableValue::get;
    return Collector.of(supplier, accumulator, combiner, finisher);
}
Example 43
Project: idnadrev-master  File: CreateTask.java View source code
@FXML
public void save() {
    CreateTaskDS datasource = (CreateTaskDS) store.getDatasource();
    TaskState state = mainInfoController.getState();
    if (datasource.isFromThought() && mainInfoController.isProject() && (state == TaskState.NONE || state == TaskState.ASAP)) {
        controller.save();
        ActivityHint hint = new ActivityHint(CreateTaskActivity.class);
        hint.setReturnToActivity(ViewThoughtsActivity.class.getSimpleName());
        Task parent = store.getModel();
        Supplier supplier = () -> {
            Task child = new Task("");
            child.setParent(parent);
            child.setContext(parent.getContext());
            return child;
        };
        hint.setDataSourceHint(supplier);
        controller.stopCurrentStartNew(hint);
    } else {
        controller.save();
        controller.stopCurrent();
    }
}
Example 44
Project: java-learning-master  File: ConstructorReference.java View source code
public static void main(String[] args) {
    //Apple()的构造函数
    Supplier<Apple> c1 = Apple::new;
    Apple a1 = c1.get();
    System.out.println(a1);
    //Apple(int weight)的构造函数
    Function<Integer, Apple> c2 = Apple::new;
    Apple a2 = c2.apply(110);
    System.out.println(a2);
    List<Integer> weights = Arrays.asList(7, 3, 4, 10);
    List<Apple> apples = map(weights, Apple::new);
    System.out.println("list of weights:");
    apples.stream().forEach(System.out::println);
    //Apple(int weight, String color)的构造函数
    BiFunction<String, Integer, Apple> c3 = Apple::new;
    Apple a3 = c3.apply("green", 110);
    System.out.println(a3);
}
Example 45
Project: java8-playground-master  File: MethodReferencesGuessGameSolution.java View source code
public static void main(String[] args) {
    Consumer<Object> c = System.out::println;
    BiFunction<Integer, Integer, Integer> b = Math::min;
    Function<Integer, Float> f = Integer::floatValue;
    Function<Double, Boolean> finite = Double::isFinite;
    Predicate<Double> finite2 = Double::isFinite;
    Supplier<Double> r = Math::random;
    Supplier<String> ss = String::new;
}
Example 46
Project: java8-tutorial-master  File: Lambda3.java View source code
public static void main(String[] args) throws Exception {
    // Predicates
    Predicate<String> predicate = ( s) -> s.length() > 0;
    // true
    predicate.test("foo");
    // false
    predicate.negate().test("foo");
    Predicate<Boolean> nonNull = Objects::nonNull;
    Predicate<Boolean> isNull = Objects::isNull;
    Predicate<String> isEmpty = String::isEmpty;
    Predicate<String> isNotEmpty = isEmpty.negate();
    // Functions
    Function<String, Integer> toInteger = Integer::valueOf;
    Function<String, String> backToString = toInteger.andThen(String::valueOf);
    // "123"
    backToString.apply("123");
    // Suppliers
    Supplier<Person> personSupplier = Person::new;
    // new Person
    personSupplier.get();
    // Consumers
    Consumer<Person> greeter = ( p) -> System.out.println("Hello, " + p.firstName);
    greeter.accept(new Person("Luke", "Skywalker"));
    // Comparators
    Comparator<Person> comparator = ( p1,  p2) -> p1.firstName.compareTo(p2.firstName);
    Person p1 = new Person("John", "Doe");
    Person p2 = new Person("Alice", "Wonderland");
    // > 0
    comparator.compare(p1, p2);
    // < 0
    comparator.reversed().compare(p1, p2);
    // Runnables
    Runnable runnable = () -> System.out.println(UUID.randomUUID());
    runnable.run();
    // Callables
    Callable<UUID> callable = UUID::randomUUID;
    callable.call();
}
Example 47
Project: javacuriosities-master  File: Lesson05ExternalVariables.java View source code
public static void main(String[] args) {
    String message = "Hello World";
    // Aca creamos un lambda que esta referenciando a la variable externa
    // message
    Supplier<String> messageProvider = () -> message;
    System.out.println(messageProvider.get());
    List<String> words = Arrays.asList("Welcome", "Lambdas", "to", "Java");
    WordCounter wordCounter = new WordCounter();
    wordCounter.count(words);
    System.out.println(wordCounter.getCounter());
}
Example 48
Project: jfastnet-master  File: CompressedMessageTest.java View source code
private void testWithMessage(Supplier<Message> messageSupplier) {
    received = 0;
    Message msg;
    msg = messageSupplier.get();
    server.send(msg);
    log.info("Payload length uncompressed message: {}", msg.payloadLength());
    waitForCondition("message not received.", 1, () -> received == 1);
    msg = CompressedMessage.createFrom(server.getState(), messageSupplier.get());
    server.send(msg);
    log.info("Payload length compressed message: {}", msg.payloadLength());
    waitForCondition("message not received.", 1, () -> received == 2);
}
Example 49
Project: jooby-master  File: JoobyRunTest.java View source code
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void runSupplier() throws Exception {
    String[] args = {};
    new MockUnit(Supplier.class, Jooby.class).expect( unit -> {
        Supplier supplier = unit.get(Supplier.class);
        expect(supplier.get()).andReturn(unit.get(Jooby.class));
    }).expect( unit -> {
        Jooby jooby = unit.get(Jooby.class);
        jooby.start(args);
    }).run( unit -> {
        Jooby.run(unit.get(Supplier.class), args);
    });
}
Example 50
Project: joyrest-master  File: SerializationUtils.java View source code
public static void writeEntity(InternalRoute route, InternalRequest<?> request, InternalResponse<?> response, MediaType fallback) {
    if (!response.isEntityWritten() && response.getEntity().isPresent()) {
        MediaType accept = request.getMatchedAccept();
        Optional<Writer> optWriter = route.getWriter(accept);
        Writer writer;
        if (!optWriter.isPresent()) {
            Supplier<RestException> restExceptionSupplier = notAcceptableSupplier(String.format("No suitable Writer for accept header [%s] is registered.", accept));
            if (fallback == null) {
                throw restExceptionSupplier.get();
            } else {
                writer = route.getWriter(fallback).orElseThrow(restExceptionSupplier);
                response.header(HeaderName.CONTENT_TYPE, fallback.get());
            }
        } else {
            writer = optWriter.get();
            response.header(HeaderName.CONTENT_TYPE, accept.get());
        }
        writer.writeTo(response, request);
        response.setEntityWritten(true);
    }
}
Example 51
Project: levelup-java-examples-master  File: OptionalExample.java View source code
@Test
public void optional_orElseGet() {
    Optional<Framework> optionalFramework = Optional.empty();
    Supplier<Framework> defaulFramework = new Supplier<OptionalExample.Framework>() {

        @Override
        public Framework get() {
            Framework framework = new Framework();
            framework.communityUsers = 200000;
            framework.name = "Java";
            return framework;
        }
    };
    Framework framework = optionalFramework.orElseGet(defaulFramework);
    assertEquals("Java", framework.name);
}
Example 52
Project: MHFC-master  File: RegistryWrapper.java View source code
public static <T, A, Z> IServiceKey<T> registerService(String name, Supplier<T> newRegistry, Consumer<T> softFinalizeHook, IPhaseKey<A, Z> phase) {
    IServiceAccess<RegistryWrapper<T>> serviceAccess = Services.instance.registerService(name, IServiceHandle.noInit(), () -> new RegistryWrapper<>(newRegistry, softFinalizeHook));
    serviceAccess.addTo(phase, new IServicePhaseHandle<RegistryWrapper<T>, A, Z>() {

        @Override
        public void onPhaseStart(RegistryWrapper<T> service, A startupContext) {
            service.register();
        }

        @Override
        public void onPhaseEnd(RegistryWrapper<T> service, Z shutdownContext) {
            service.unregister();
        }
    });
    return serviceAccess.withIndirection(RegistryWrapper::getRegistry);
}
Example 53
Project: POL-POM-5-master  File: UiMessageSenderJavaFXImplementation.java View source code
@Override
public <R> R run(Supplier<R> function) {
    // runBackground synchronously on JavaFX thread
    if (Platform.isFxApplicationThread()) {
        return function.get();
    }
    // queue on JavaFX thread and wait for completion
    final CountDownLatch doneLatch = new CountDownLatch(1);
    final MutableObject result = new MutableObject();
    Platform.runLater(() -> {
        try {
            result.setValue(function.get());
        } finally {
            doneLatch.countDown();
        }
    });
    try {
        doneLatch.await();
    } catch (InterruptedException e) {
    }
    return (R) result.getValue();
}
Example 54
Project: ProjectAres-master  File: MethodHandleInvoker.java View source code
public static MethodHandleInvoker caching(Supplier<?> targeter) {
    return new MethodHandleInvoker() {

        @Nullable
        private Object cache;

        @Override
        protected Object targetFor(Method method) {
            if (cache == null) {
                cache = targeter.get();
            }
            return cache;
        }
    };
}
Example 55
Project: protonpack-master  File: InterleavingSpliterator.java View source code
public static <T> Spliterator<T> interleaving(Spliterator<T>[] spliterators, Function<T[], Integer> selector) {
    Supplier<T[]> bufferedValues = () -> {
        T[] values = (T[]) new Object[spliterators.length];
        for (int i = 0; i < spliterators.length; i++) {
            final int stableIndex = i;
            spliterators[i].tryAdvance( t -> values[stableIndex] = t);
        }
        return values;
    };
    return new InterleavingSpliterator<>(spliterators, bufferedValues, selector);
}
Example 56
Project: reactive-audit-master  File: ScatteringByteChannelTest.java View source code
@Parameterized.Parameters
public static Collection data() throws IOException {
    Supplier<?>[][] data = new Supplier<?>[][] { //Java8 {IOTestTools::getInputFileChannel},
    { new Supplier<Object>() {

        @Override
        public Object get() {
            return IOTestTools.getInputFileChannel();
        }
    } }, //Java8 {IOTestTools::getSocketChannel},
    { new Supplier<Object>() {

        @Override
        public Object get() {
            return IOTestTools.getSocketChannel();
        }
    } } };
    return Arrays.asList(data);
}
Example 57
Project: reactor-core-master  File: ParallelCollectTest.java View source code
@Test
public void collect() {
    Supplier<List<Integer>> as = () -> new ArrayList<>();
    AssertSubscriber<Integer> ts = AssertSubscriber.create();
    Flux.range(1, 10).parallel().collect(as, ( a,  b) -> a.add(b)).sequential().flatMapIterable( v -> v).log().subscribe(ts);
    ts.assertContainValues(new HashSet<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))).assertNoError().assertComplete();
}
Example 58
Project: reactor-master  File: LastOperationUtils.java View source code
public static Mono<Void> waitForCompletion(Duration completionTimeout, Supplier<Mono<LastOperation>> lastOperationSupplier) {
    return lastOperationSupplier.get().map(LastOperation::getState).filter( state -> !IN_PROGRESS.equals(state)).repeatWhenEmpty(DelayUtils.exponentialBackOff(Duration.ofSeconds(1), Duration.ofSeconds(15), completionTimeout)).onErrorResume( t -> t instanceof ClientV2Exception && ((ClientV2Exception) t).getStatusCode() == 404,  t -> Mono.empty()).then();
}
Example 59
Project: riptide-master  File: OriginalStackTracePlugin.java View source code
@Override
public RequestExecution prepare(final RequestArguments arguments, final RequestExecution execution) {
    return () -> {
        final CompletableFuture<ClientHttpResponse> future = execution.execute();
        // let's do the "heavy" stack trace work while the request is already on its way
        final Supplier<StackTraceElement[]> original = keepOriginalStackTrace();
        return future.exceptionally(throwingFunction( cause -> {
            cause.setStackTrace(concat(cause.getStackTrace(), original.get(), StackTraceElement.class));
            throw cause;
        }));
    };
}
Example 60
Project: sample-boot-hibernate-master  File: IdLockHandler.java View source code
public <T> T call(Serializable id, LockType lockType, final Supplier<T> callable) {
    if (lockType.isWrite()) {
        writeLock(id);
    } else {
        readLock(id);
    }
    try {
        return callable.get();
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new InvocationException("error.Exception", e);
    } finally {
        unlock(id);
    }
}
Example 61
Project: sandbox-master  File: MenuAnimationSystems.java View source code
public static MenuAnimationSystem createDefaultSwipeAnimation() {
    RenderingConfig config = CoreRegistry.get(Config.class).getRendering();
    MenuAnimationSystem swipe = new SwipeMenuAnimationSystem(0.25f, Direction.LEFT_TO_RIGHT);
    MenuAnimationSystem instant = new MenuAnimationSystemStub();
    Supplier<MenuAnimationSystem> provider = () -> config.isAnimatedMenu() ? swipe : instant;
    return new DeferredMenuAnimationSystem(provider);
}
Example 62
Project: scotch-lang-master  File: IntermediateApply.java View source code
@Override
public CodeBlock generateBytecode(BytecodeGenerator generator) {
    return new CodeBlock() {

        {
            newobj(p(SuppliedThunk.class));
            dup();
            captures.forEach( capture -> aload(generator.offsetOf(capture)));
            lambda(generator.currentClass(), new LambdaBlock(generator.reserveApply()) {

                {
                    function(p(Supplier.class), "get", sig(Object.class));
                    specialize(sig(Callable.class));
                    capture(getCaptureTypes());
                    delegateTo(ACC_STATIC, sig(Callable.class, getCaptureTypes()), new CodeBlock() {

                        {
                            generator.beginMethod(captures);
                            append(function.generateBytecode(generator));
                            invokeinterface(p(Callable.class), "call", sig(Object.class));
                            checkcast(p(Applicable.class));
                            append(argument.generateBytecode(generator));
                            invokeinterface(p(Applicable.class), "apply", sig(Callable.class, Callable.class));
                            areturn();
                            generator.endMethod();
                        }
                    });
                }
            });
            invokespecial(p(SuppliedThunk.class), "<init>", sig(void.class, Supplier.class));
        }
    };
}
Example 63
Project: seleniumcapsules-master  File: MouseOverLocator.java View source code
public Element locate(Page page) {
    return new ElementLocator<Page>(MAIN_NAV).andThen(new ElementLocator<>(SF_JS_ENABLED)).andThen(elements(LI)).andThen(new FirstMatch<>(NOT_NULL.and(DISPLAYED).and(TEXT.and(new Equals(menuGroup))))).andThen(GET).andThen(page.mouseOver()).andThen(new ElementLocator<>(UL)).andThen(new ElementLocator<>((Supplier<By>) () -> linkText(menuItem))).locate(page);
}
Example 64
Project: sonar-java-master  File: ObjectsMethodsTest.java View source code
public void testRequireNull(Supplier<String> supplier) {
    Object x = checkForNullMethod();
    Objects.requireNonNull(x);
    // Compliant: x was checked for non null
    x.toString();
    Object y = checkForNullMethod();
    Objects.requireNonNull(y, "Should not be null!");
    // Compliant: y was checked for non null
    y.toString();
    Object z = checkForNullMethod();
    Objects.requireNonNull(z, supplier);
    // Compliant: z was checked for non null
    z.toString();
    Object v = checkForNullMethod();
    requireNonNull(v);
    // Compliant
    v.toString();
    Object w = checkForNullMethod();
    // Noncompliant
    w.toString();
}
Example 65
Project: speedment-master  File: DefaultCollectSupplierAccumulatorCombinerTerminator.java View source code
@Override
public <T, R> R apply(final SqlStreamOptimizerInfo<ENTITY> info, final SqlStreamTerminator<ENTITY> sqlStreamTerminator, final ReferencePipeline<T> pipeline, final Supplier<R> supplier, final BiConsumer<R, ? super T> accumulator, final BiConsumer<R, R> combiner) {
    requireNonNull(info);
    requireNonNull(sqlStreamTerminator);
    requireNonNull(pipeline);
    requireNonNull(supplier);
    requireNonNull(accumulator);
    requireNonNull(combiner);
    return sqlStreamTerminator.optimize(pipeline).getAsReferenceStream().collect(supplier, accumulator, combiner);
}
Example 66
Project: streamex-master  File: ZipSpliteratorTest.java View source code
@Test
public void testEven() {
    List<String> expected = IntStreamEx.range(200).mapToObj( x -> x + ":" + (x + 1)).toList();
    int[] nums = IntStreamEx.range(200).toArray();
    Supplier<Spliterator<String>> s = () -> new ZipSpliterator<>(IntStreamEx.range(200).spliterator(), IntStreamEx.range(1, 201).spliterator(), ( x,  y) -> x + ":" + y, true);
    checkSpliterator("even", expected, s);
    s = () -> new ZipSpliterator<>(IntStreamEx.range(200).spliterator(), IntStreamEx.range(2, 202).parallel().map( x -> x - 1).spliterator(), ( x,  y) -> x + ":" + y, true);
    checkSpliterator("evenMap", expected, s);
    s = () -> new ZipSpliterator<>(IntStreamEx.of(nums).spliterator(), IntStreamEx.range(2, 202).parallel().map( x -> x - 1).spliterator(), ( x,  y) -> x + ":" + y, true);
    checkSpliterator("evenArray", expected, s);
}
Example 67
Project: Terasology-master  File: MenuAnimationSystems.java View source code
public static MenuAnimationSystem createDefaultSwipeAnimation() {
    RenderingConfig config = CoreRegistry.get(Config.class).getRendering();
    MenuAnimationSystem swipe = new SwipeMenuAnimationSystem(0.25f, Direction.LEFT_TO_RIGHT);
    MenuAnimationSystem instant = new MenuAnimationSystemStub();
    Supplier<MenuAnimationSystem> provider = () -> config.isAnimatedMenu() ? swipe : instant;
    return new DeferredMenuAnimationSystem(provider);
}
Example 68
Project: termd-master  File: Wait.java View source code
public static void forCondition(Supplier<Boolean> evaluationSupplier, long timeout, TemporalUnit timeUnit, String failedMessage) throws InterruptedException, TimeoutException {
    LocalDateTime started = LocalDateTime.now();
    while (true) {
        if (started.plus(timeout, timeUnit).isBefore(LocalDateTime.now())) {
            throw new TimeoutException(failedMessage + " Reached timeout " + timeout + " " + timeUnit);
        }
        if (evaluationSupplier.get()) {
            break;
        } else {
            Thread.sleep(100);
        }
    }
}
Example 69
Project: thrift-pool-client-master  File: TestThriftPoolClient.java View source code
@Test
public void testEcho() throws InterruptedException {
    // define serverList provider, you can use dynamic provider here to impl on the fly changing...
    Supplier<List<ThriftServerInfo>> serverListProvider = () -> //
    Arrays.asList(//
    ThriftServerInfo.of("127.0.0.1", 9092), //
    ThriftServerInfo.of("127.0.0.1", 9091), ThriftServerInfo.of("127.0.0.1", 9090));
    // init pool client
    ThriftClientImpl client = new ThriftClientImpl(serverListProvider);
    ExecutorService executorService = Executors.newFixedThreadPool(10);
    for (int i = 0; i < 100; i++) {
        int counter = i;
        executorService.submit(() -> {
            try {
                String result = client.iface(Client.class).echo("hi " + counter + "!");
                logger.info("get result: {}", result);
            } catch (Throwable e) {
                logger.error("get client fail", e);
            }
        });
    }
    MoreExecutors.shutdownAndAwaitTermination(executorService, 1, MINUTES);
}
Example 70
Project: VirtualSlideViewer-master  File: BackgroundOperationUtil.java View source code
public static <T extends ProgressView> void startBackgroundOperation(Supplier<T> progressViewFactory, Consumer<T> operation) {
    T progressView = progressViewFactory.get();
    Thread operationThread = new Thread(() -> {
        try {
            operation.accept(progressView);
        } finally {
            SwingUtilities.invokeLater(() -> progressView.hide());
        }
    });
    progressView.addCancelListener(() -> {
        operationThread.interrupt();
    });
    operationThread.start();
}
Example 71
Project: jersey-master  File: SupplierInstanceBindingTest.java View source code
@Test
public void testSupplierSingletonInstancePerLookup() {
    BindingTestHelper.bind(injectionManager,  binder -> {
        binder.bindFactory(new SupplierGreeting()).to(Greeting.class);
        binder.bindAsContract(Conversation.class);
    });
    Greeting greeting1 = injectionManager.getInstance(Conversation.class).greeting;
    Greeting greeting2 = injectionManager.getInstance(Conversation.class).greeting;
    Greeting greeting3 = injectionManager.getInstance(Conversation.class).greeting;
    assertNotSame(greeting1, greeting2);
    assertNotSame(greeting2, greeting3);
    Supplier<Greeting> supplier1 = injectionManager.getInstance(Conversation.class).greetingSupplier;
    Supplier<Greeting> supplier2 = injectionManager.getInstance(Conversation.class).greetingSupplier;
    Supplier<Greeting> supplier3 = injectionManager.getInstance(Conversation.class).greetingSupplier;
    assertSame(supplier1, supplier2);
    assertSame(supplier2, supplier3);
}
Example 72
Project: astrix-master  File: DropwizardMetricsTest.java View source code
@Test
public void timeObservable() throws Throwable {
    TimerSpi timer = dropwizardMetrics.createTimer();
    Supplier<Observable<String>> observable = timer.timeObservable(() -> Observable.create( subscriber -> {
        try {
            Thread.sleep(10);
            subscriber.onNext("foo");
            subscriber.onCompleted();
        } catch (InterruptedException e) {
            subscriber.onError(e);
        }
    }));
    assertEquals("foo", observable.get().toBlocking().first());
    TimerSnaphot timerSnapshot = timer.getSnapshot();
    assertEquals(1, timerSnapshot.getCount());
    // Should meassure execution time roughly equal to 10 ms
    assertThat(timerSnapshot.getMax(), greaterThan(8D));
}
Example 73
Project: breakout-master  File: RTraversal.java View source code
public static <R, T, V> V traverse(RNode<R, T> node, Predicate<RNode<R, T>> onNodes, Function<RLeaf<R, T>, V> onLeaves, Supplier<V> initialValue, BinaryOperator<V> combiner) {
    if (onNodes.test(node)) {
        if (node instanceof RBranch) {
            RBranch<R, T> branch = (RBranch<R, T>) node;
            V value = initialValue.get();
            for (int i = 0; i < branch.numChildren(); i++) {
                V childValue = traverse(branch.childAt(i), onNodes, onLeaves, initialValue, combiner);
                value = combiner.apply(value, childValue);
            }
            return value;
        } else if (node instanceof RLeaf) {
            return onLeaves.apply((RLeaf<R, T>) node);
        }
    }
    return initialValue.get();
}
Example 74
Project: caffeine-master  File: CacheManagerTest.java View source code
private void checkConfigurationJmx(Supplier<Cache<?, ?>> cacheSupplier) throws Exception {
    Cache<?, ?> cache = cacheSupplier.get();
    @SuppressWarnings("unchecked") CompleteConfiguration<?, ?> configuration = cache.getConfiguration(CompleteConfiguration.class);
    assertThat(configuration.isManagementEnabled(), is(true));
    assertThat(configuration.isStatisticsEnabled(), is(true));
    String name = "javax.cache:Cache=%s,CacheManager=%s,type=CacheStatistics";
    ManagementFactory.getPlatformMBeanServer().getObjectInstance(new ObjectName(String.format(name, cache.getName(), PROVIDER_NAME)));
}
Example 75
Project: camel-master  File: Suppliers.java View source code
public static <T> Supplier<T> memorize(Supplier<T> supplier) {
    final AtomicReference<T> valueHolder = new AtomicReference<>();
    return () -> {
        T supplied = valueHolder.get();
        if (supplied == null) {
            synchronized (valueHolder) {
                supplied = valueHolder.get();
                if (supplied == null) {
                    supplied = Objects.requireNonNull(supplier.get(), "Supplier should not return null");
                    valueHolder.lazySet(supplied);
                }
            }
        }
        return supplied;
    };
}
Example 76
Project: circuitbreaker-master  File: VertxCircuitBreaker.java View source code
/**
     * Returns a Future which is decorated by a CircuitBreaker.
     *
     * @param circuitBreaker the CircuitBreaker
     * @param supplier the Future supplier
     * @param <T> the type of the returned Future's result
     * @return a future which is decorated by a CircuitBreaker.
     */
static <T> Supplier<Future<T>> decorateFuture(CircuitBreaker circuitBreaker, Supplier<Future<T>> supplier) {
    return () -> {
        final Future<T> future = Future.future();
        if (!circuitBreaker.isCallPermitted()) {
            future.fail(new CircuitBreakerOpenException(String.format("CircuitBreaker '%s' is open", circuitBreaker.getName())));
        } else {
            long start = System.nanoTime();
            try {
                supplier.get().setHandler( result -> {
                    long durationInNanos = System.nanoTime() - start;
                    if (result.failed()) {
                        circuitBreaker.onError(durationInNanos, result.cause());
                        future.fail(result.cause());
                    } else {
                        circuitBreaker.onSuccess(durationInNanos);
                        future.complete(result.result());
                    }
                });
            } catch (Throwable throwable) {
                long durationInNanos = System.nanoTime() - start;
                circuitBreaker.onError(durationInNanos, throwable);
                future.fail(throwable);
            }
        }
        return future;
    };
}
Example 77
Project: common-chicken-runtime-engine-master  File: PoultryInspector.java View source code
/**
     * The main method of the Poultry Inspector.
     *
     * @param args the unused program arguments.
     */
public static void main(String args[]) {
    TrafficCounting.setCountingEnabled(true);
    NetworkAutologger.register();
    FileLogger.register();
    Supplier<SuperCanvasComponent> popup = (Supplier<SuperCanvasComponent>Serializable & ) () -> {
        return new TopLevelPaletteComponent(200, 200, WebcamComponent.class, HighlightComponent.class, LoggingComponent.class, NetworkPaletteComponent.class, ListPaletteComponent.class, FolderComponent.class, TrashComponent.class, TextComponent.class, TopLevelRConfComponent.class);
    };
    Supplier<SuperCanvasComponent> popupNet = (Supplier<SuperCanvasComponent>Serializable & ) () -> {
        return new NetworkPaletteComponent(200, 200);
    };
    SuperCanvasComponent[] components = new SuperCanvasComponent[] { new LoggingComponent(312, 300), new CluckNetworkingComponent(), new EditModeComponent(), new StartComponent(popup, "PALETTE", 0), new StartComponent(popupNet, "NETWORK", 1), new SaveLoadComponent(0, 0) };
    new SuperCanvasFrame("Poultry Inspector", popup, components).start();
}
Example 78
Project: crate-master  File: DMLProjector.java View source code
@Override
public BatchIterator apply(BatchIterator batchIterator) {
    Supplier<ShardRequest.Item> updateItemSupplier = () -> {
        BytesRef id = (BytesRef) collectIdExpression.value();
        return itemFactory.apply(id.utf8ToString());
    };
    return IndexWriterCountBatchIterator.newShardInstance(batchIterator, shardId, Collections.singletonList(collectIdExpression), bulkShardProcessor, updateItemSupplier);
}
Example 79
Project: diqube-master  File: Waiter.java View source code
/**
   * Block this thread until the checkFn returns true.
   * 
   * @param waitFor
   *          Strign describing what we wait for.
   * @param timeoutSeconds
   *          Number of seconds after which we timeout.
   * @param retryMs
   *          Number of milliseconds to wait between calling the checkFn.
   * @param checkFn
   *          The function which returns true if the expected circumstance is true.
   * @throws RuntimeException
   *           If interrupted.
   * @throws WaitTimeoutException
   *           If after the timeout is done the function still returns false.
   */
public void waitUntil(String waitFor, int timeoutSeconds, int retryMs, Supplier<Boolean> checkFn) throws WaitTimeoutException {
    if (checkFn.get())
        return;
    Object sync = new Object();
    int maxRetries = (int) Math.ceil(timeoutSeconds * 1000. / retryMs);
    for (int i = 0; i < maxRetries; i++) {
        synchronized (sync) {
            try {
                sync.wait(retryMs);
            } catch (InterruptedException e) {
                throw new RuntimeException("Interrupted while waiting for: " + waitFor);
            }
        }
        logger.trace("Retry {} for '{}'.", i, waitFor);
        if (checkFn.get())
            return;
    }
    throw new WaitTimeoutException("Timed out (" + timeoutSeconds + " sec) waiting for: " + waitFor);
}
Example 80
Project: elasticsearch-master  File: MustachePlugin.java View source code
@Override
public List<RestHandler> getRestHandlers(Settings settings, RestController restController, ClusterSettings clusterSettings, IndexScopedSettings indexScopedSettings, SettingsFilter settingsFilter, IndexNameExpressionResolver indexNameExpressionResolver, Supplier<DiscoveryNodes> nodesInCluster) {
    return Arrays.asList(new RestSearchTemplateAction(settings, restController), new RestMultiSearchTemplateAction(settings, restController), new RestGetSearchTemplateAction(settings, restController), new RestPutSearchTemplateAction(settings, restController), new RestDeleteSearchTemplateAction(settings, restController), new RestRenderSearchTemplateAction(settings, restController));
}
Example 81
Project: Flapi-master  File: CalculatorBuilderExample.java View source code
@Test
public void factoryUsage() {
    CalculatorFactory factory = CalculatorGenerator.factory(new Supplier<Calculator>() {

        @Override
        public Calculator get() {
            return new CalculatorHelperImpl();
        }
    });
    Result result = factory.begin().$(0).plus(10).minus(5).equals();
    assertEquals(5, result.get().intValue());
}
Example 82
Project: gga-selenium-framework-master  File: ActionScenrios.java View source code
public <TResult> TResult resultScenario(String actionName, Supplier<TResult> jAction, Function<TResult, String> logResult, LogLevels level) {
    element.logAction(actionName);
    Timer timer = new Timer();
    TResult result = new Timer(timeouts.currentTimeoutSec).getResultByCondition(jAction::get,  res -> true);
    if (result == null)
        throw asserter.exception("Do action %s failed. Can't got result", actionName);
    String stringResult = (logResult == null) ? result.toString() : JDISettings.asserter.silent(() -> logResult.apply(result));
    Long timePassed = timer.timePassedInMSec();
    addStatistic(timer.timePassedInMSec());
    toLog(format("Get result '%s' in %s seconds", stringResult, format("%.2f", (double) timePassed / 1000)), level);
    return result;
}
Example 83
Project: git-as-svn-master  File: Context.java View source code
@NotNull
public <T extends S> T getOrCreate(@NotNull Class<T> type, @NotNull Supplier<T> supplier) {
    final T result = get(type);
    if (result == null) {
        final T newObj = supplier.get();
        final S oldObj = map.putIfAbsent(type, newObj);
        if (oldObj != null) {
            //noinspection unchecked
            return (T) oldObj;
        }
        return newObj;
    }
    return result;
}
Example 84
Project: hazelcast-examples-master  File: HazelcastInterpreterSupport.java View source code
protected void readConsoleWhile(HazelcastInstance hazelcast, String name, Supplier<Void> showAll, Supplier<Integer> counter) {
    Console console = System.console();
    String line;
    while ((line = console.readLine("> ")) != null) {
        if (line.isEmpty()) {
            continue;
        }
        String[] tokens = line.split("\\s+", -1);
        String command = tokens[0];
        boolean stop = false;
        switch(command) {
            case "all":
                showAll.get();
                break;
            case "locate":
                if (tokens.length > 1) {
                    String key = tokens[1];
                    Partition partition = hazelcast.getPartitionService().getPartition(key);
                    show("Locate key = %s, partitionId = %s, owner = %s.", key, partition.getPartitionId(), partition.getOwner());
                } else {
                    show("Locate, required key.");
                }
                break;
            case "self":
                show("Self = %s.", hazelcast.getCluster().getLocalMember());
                break;
            case "name":
                PartitionService partitionService = hazelcast.getPartitionService();
                SerializationService serializationService = ((HazelcastInstanceProxy) hazelcast).getSerializationService();
                Data key = serializationService.toData(name, StringPartitioningStrategy.INSTANCE);
                Partition partition = partitionService.getPartition(key);
                show("Partition by name = %s, partitionId = %s, owner = %s.", name, partition.getPartitionId(), partition.getOwner());
                break;
            case "size":
                show("This data set size = %d.", counter.get());
                break;
            case "exit":
                stop = true;
                break;
            default:
                show("Unknown command = %s.", command);
                break;
        }
        if (stop) {
            break;
        }
    }
}
Example 85
Project: hbase-master  File: TestAsyncTableScanAll.java View source code
@Parameters(name = "{index}: table={0}, scan={2}")
public static List<Object[]> params() {
    Supplier<AsyncTableBase> rawTable = TestAsyncTableScanAll::getRawTable;
    Supplier<AsyncTableBase> normalTable = TestAsyncTableScanAll::getTable;
    return getScanCreater().stream().flatMap( p -> Arrays.asList(new Object[] { "raw", rawTable, p.getFirst(), p.getSecond() }, new Object[] { "normal", normalTable, p.getFirst(), p.getSecond() }).stream()).collect(Collectors.toList());
}
Example 86
Project: heroic-master  File: MemoryQueryCache.java View source code
@Override
public AsyncFuture<QueryResult> load(FullQuery.Request request, Supplier<AsyncFuture<QueryResult>> loader) {
    final AggregationInstance aggregation = request.getAggregation();
    /* can't be cached :( */
    if (aggregation.cadence() <= 0) {
        return loader.get();
    }
    final AsyncFuture<QueryResult> result = cache.get(request);
    if (result != null) {
        return result;
    }
    synchronized (lock) {
        final AsyncFuture<QueryResult> candidate = cache.get(request);
        if (candidate != null) {
            return candidate;
        }
        final AsyncFuture<QueryResult> next = loader.get();
        cache.put(request, next, ExpirationPolicy.ACCESSED, aggregation.cadence(), TimeUnit.MILLISECONDS);
        return next;
    }
}
Example 87
Project: hsweb-framework-master  File: CoreAutoConfiguration.java View source code
private void initScript() {
    Map<String, Object> vars = new HashMap<>(expressionScopeBeanMap);
    vars.put("LoginUser", (Supplier<User>) WebUtil::getLoginUser);
    vars.put("StringUtils", StringUtils.class);
    vars.put("User", User.class);
    initScript("js", vars);
    initScript("groovy", vars);
    initScript("java", vars);
    initScript("spel", vars);
    initScript("ognl", vars);
    initScript("ruby", vars);
    initScript("python", vars);
//执行脚本
}
Example 88
Project: JALSE-master  File: GetEntitiesMethod.java View source code
private Predicate<Entity> newIDFilter() {
    return  e -> {
        if (idSuppliers.isEmpty()) {
            return true;
        }
        boolean found = false;
        for (final Supplier<UUID> idSupplier : idSuppliers) {
            if (e.getID().equals(idSupplier.get())) {
                found = true;
                break;
            }
        }
        return found;
    };
}
Example 89
Project: java-design-patterns-master  File: Java8HolderTest.java View source code
@Override
Heavy getInternalHeavyValue() throws Exception {
    final Field holderField = Java8Holder.class.getDeclaredField("heavy");
    holderField.setAccessible(true);
    final Supplier<Heavy> supplier = (Supplier<Heavy>) holderField.get(this.holder);
    final Class<? extends Supplier> supplierClass = supplier.getClass();
    // The lazy holder is at first a lambda, but gets replaced with a new supplier after loading ...
    if (supplierClass.isLocalClass()) {
        final Field instanceField = supplierClass.getDeclaredField("heavyInstance");
        instanceField.setAccessible(true);
        return (Heavy) instanceField.get(supplier);
    } else {
        return null;
    }
}
Example 90
Project: jbosstools-openshift-master  File: DockerConfigMetaData.java View source code
/**
	 * Select info from either config or container config and provides a
	 * default non null value if nothing is found.
	 * 
	 * @param config the image config object
	 * @param containerConfig the image container config object
	 * @param accessor the accessor for the target property
	 * @param defaultFactory the factory for the default value
	 * @return the mapped value
	 */
private <C extends Collection<String>> C select(IDockerContainerConfig config, IDockerContainerConfig containerConfig, Function<IDockerContainerConfig, C> accessor, Supplier<C> defaultFactory) {
    C result = null;
    if (config != null) {
        result = accessor.apply(config);
    }
    if (((result == null) || result.isEmpty()) && (containerConfig != null)) {
        result = accessor.apply(containerConfig);
    }
    if (result == null) {
        result = defaultFactory.get();
    }
    return result;
}
Example 91
Project: jenetics-master  File: factories.java View source code
/**
	 * Return an integer factory which creates an integer sequence starting with
	 * {@code start} an with the given {@code step}.
	 *
	 * @param step the gap between the generated integers.
	 * @return an integer factory.
	 */
public static Supplier<Integer> Int(final int start, final int step) {
    return new Supplier<Integer>() {

        private int _value = start;

        @Override
        public Integer get() {
            return next();
        }

        private int next() {
            final int next = _value;
            _value += step;
            return next;
        }
    };
}
Example 92
Project: mockneat-master  File: Ints.java View source code
public MockUnitInt range(int lowerBound, int upperBound) {
    notNull(lowerBound, "lowerBound");
    notNull(upperBound, "upperBound");
    isTrue(lowerBound >= 0, LOWER_BOUND_BIGGER_THAN_ZERO);
    isTrue(upperBound > 0, UPPER_BOUND_BIGGER_THAN_ZERO);
    isTrue(upperBound > lowerBound, UPPER_BOUND_BIGGER_LOWER_BOUND);
    Supplier<Integer> supp = () -> random.nextInt(upperBound - lowerBound) + lowerBound;
    return () -> supp;
}
Example 93
Project: nifi-master  File: ClusterUtils.java View source code
public static void waitUntilConditionMet(final long time, final TimeUnit timeUnit, final BooleanSupplier test, final Supplier<String> errorMessageSupplier) {
    final long nanosToWait = timeUnit.toNanos(time);
    final long start = System.nanoTime();
    final long maxTime = start + nanosToWait;
    while (!test.getAsBoolean()) {
        if (System.nanoTime() > maxTime) {
            if (errorMessageSupplier == null) {
                throw new AssertionError("Condition never occurred after waiting " + time + " " + timeUnit);
            } else {
                throw new AssertionError("Condition never occurred after waiting " + time + " " + timeUnit + " : " + errorMessageSupplier.get());
            }
        }
    }
}
Example 94
Project: onos-master  File: HybridLogicalClockManagerTest.java View source code
@Test
public void testLocalEvents() {
    AtomicLong ticker = new AtomicLong();
    Supplier<Long> ptSource = ticker::get;
    HybridLogicalClockManager clockManager = new HybridLogicalClockManager();
    clockManager.physicalTimeSource = ptSource;
    HybridLogicalTime time1 = clockManager.timeNow();
    Assert.assertEquals(0, time1.logicalTime());
    Assert.assertEquals(1, time1.logicalCounter());
    HybridLogicalTime time2 = clockManager.timeNow();
    Assert.assertEquals(0, time2.logicalTime());
    Assert.assertEquals(2, time2.logicalCounter());
    ticker.incrementAndGet();
    HybridLogicalTime time3 = clockManager.timeNow();
    Assert.assertEquals(1, time3.logicalTime());
    Assert.assertEquals(0, time3.logicalCounter());
    HybridLogicalTime time4 = clockManager.timeNow();
    Assert.assertEquals(1, time4.logicalTime());
    Assert.assertEquals(1, time4.logicalCounter());
}
Example 95
Project: presto-master  File: BackupOperationStats.java View source code
public <V> V run(Supplier<V> supplier) {
    try (TimeStat.BlockTimer ignored = time.time()) {
        V value = supplier.get();
        successes.update(1);
        return value;
    } catch (PrestoException e) {
        if (e.getErrorCode().equals(RAPTOR_BACKUP_NOT_FOUND.toErrorCode())) {
            successes.update(1);
        } else if (e.getErrorCode().equals(RAPTOR_BACKUP_TIMEOUT.toErrorCode())) {
            timeouts.update(1);
        } else {
            failures.update(1);
        }
        throw e;
    }
}
Example 96
Project: radargun-master  File: Request.java View source code
public <T> T exec(Operation operation, Supplier<T> supplier, Predicate<T> predicate) {
    T value;
    try {
        value = supplier.get();
    } catch (Throwable t) {
        failed(operation);
        throw t;
    }
    responseCompleteTime = TimeService.nanoTime();
    try {
        successful = predicate.test(value);
    } catch (Throwable t) {
        successful = false;
        throw t;
    } finally {
        statistics.record(this, operation);
    }
    return value;
}
Example 97
Project: reactor-spring-master  File: ReactorBeanDefinitionRegistrar.java View source code
protected <T> void registerReactorBean(BeanDefinitionRegistry registry, String attrValue, String name, Class<T> tClass, Supplier<Supplier<T>> supplier) {
    // Create a root Enivronment
    if (!registry.containsBeanDefinition(name)) {
        BeanDefinitionBuilder envBeanDef = BeanDefinitionBuilder.rootBeanDefinition(CreateOrReuseFactoryBean.class);
        envBeanDef.addConstructorArgValue(name);
        envBeanDef.addConstructorArgValue(tClass);
        if (StringUtils.hasText(attrValue)) {
            envBeanDef.addConstructorArgReference(attrValue);
        } else {
            envBeanDef.addConstructorArgValue(supplier.get());
        }
        registry.registerBeanDefinition(name, envBeanDef.getBeanDefinition());
    }
}
Example 98
Project: reveno-master  File: ClusterTestUtils.java View source code
public static List<ClusterEngineWrapper> createClusterEngines(int count, List<File> dir, Consumer<ClusterEngineWrapper> forEach, Supplier<ClusterProvider> provider) {
    List<ClusterEngineWrapper> result = new ArrayList<>();
    int[] ports = Utils.getFreePorts(count * 2);
    for (int i = 0, p = 0; i < count; i++, p += 2) {
        ClusterEngineWrapper engine = new ClusterEngineWrapper(dir.get(i), ClusterTestUtils.class.getClassLoader(), provider.get());
        engine.setSequence(i);
        Address address = new InetAddress("127.0.0.1:" + ports[p], IOMode.ASYNC);
        engine.clusterConfiguration().currentNodeAddress(address);
        engine.clusterConfiguration().priorityInCluster(count - i);
        engine.clusterConfiguration().dataSync().port(ports[p + 1]);
        engine.clusterConfiguration().dataSync().mode(SyncMode.SNAPSHOT);
        forEach.accept(engine);
        result.add(engine);
    }
    for (ClusterEngineWrapper engine : result) {
        List<Address> nodes = result.stream().filter( subEngine -> engine != subEngine).map(ClusterEngineWrapper::getCurrentAddress).collect(Collectors.toList());
        engine.clusterConfiguration().nodesAddresses(nodes);
    }
    return result;
}
Example 99
Project: simplelenium-master  File: Retry.java View source code
<T> void execute(Supplier<Optional<T>> target, Consumer<T> action) {
    WebDriverException lastError = null;
    boolean retried = false;
    long start = System.currentTimeMillis();
    while ((System.currentTimeMillis() - start) < timeoutInMs) {
        try {
            Optional<T> targetElement = target.get();
            if (targetElement.isPresent()) {
                action.accept(targetElement.get());
                if (retried) {
                    System.out.println();
                }
                return;
            }
        } catch (StaleElementReferenceException e) {
        } catch (WebDriverException e) {
            lastError = e;
        }
        retried = true;
        System.out.print(".");
    }
    if (retried) {
        System.out.println();
    }
    if (lastError != null) {
        throw lastError;
    }
    throw new NoSuchElementException("Not found");
}
Example 100
Project: spectator-master  File: TagFactory.java View source code
/**
   * Helper method for creating a tag factory that uses a lambda to supply
   * the value.
   *
   * @param name
   *     Key to use for the returned tag value.
   * @param value
   *     Supplier used to retrieve the value for the tag. If the return
   *     value is null, then a null tag is returned an the dimension will
   *     be suppressed.
   * @return
   *     Factory for producing tags using the value supplier.
   */
static TagFactory from(String name, Supplier<String> value) {
    return new TagFactory() {

        @Override
        public String name() {
            return name;
        }

        @Override
        public Tag createTag() {
            final String v = value.get();
            return (v == null) ? null : new BasicTag(name, v);
        }
    };
}
Example 101
Project: sw360portal-master  File: DatabaseSettings.java View source code
public static Supplier<HttpClient> getConfiguredHttpClient() throws MalformedURLException {
    StdHttpClient.Builder httpClientBuilder = new StdHttpClient.Builder().url(COUCH_DB_URL);
    if (!"".equals(COUCH_DB_USERNAME)) {
        httpClientBuilder.username(COUCH_DB_USERNAME);
    }
    if (!"".equals(COUCH_DB_PASSWORD)) {
        httpClientBuilder.password(COUCH_DB_PASSWORD);
    }
    return httpClientBuilder::build;
}