Example usage for java.util.function Supplier get

List of usage examples for java.util.function Supplier get

Introduction

In this page you can find the example usage for java.util.function Supplier get.

Prototype

T get();

Source Link

Document

Gets a result.

Usage

From source file:com.evolveum.midpoint.schema.SelectorOptions.java

public static <T> Collection<SelectorOptions<T>> set(Collection<SelectorOptions<T>> options, ItemPath path,
        Supplier<T> constructor, Consumer<T> setter) {
    if (options == null) {
        options = new ArrayList<>();
    }/*from   w w  w. j a va 2 s.  c  o m*/
    Collection<T> optionsForPath = findOptionsForPath(options, path);
    T option;
    if (optionsForPath.isEmpty()) {
        option = constructor.get();
        options.add(SelectorOptions.create(path, option));
    } else {
        option = optionsForPath.iterator().next();
    }
    setter.accept(option);
    return options;
}

From source file:net.openhft.chronicle.timeseries.Columns.java

public static <T> void setAll(LongColumn col, Supplier<T> perThread,
        LongColumnIndexObjectConsumer<T> consumer) {
    long length = col.length();
    int chunks = Math.toIntExact((length - 1) / CHUNK_SIZE + 1);
    ForkJoinPool fjp = ForkJoinPool.commonPool();
    int procs = Runtime.getRuntime().availableProcessors();
    List<ForkJoinTask> tasks = new ArrayList<>(procs);
    int chunksPerTask = (chunks - 1) / procs + 1;
    for (int i = 0; i < procs; i++) {
        int si = i * chunksPerTask;
        int ei = Math.min(chunks, si + chunksPerTask);
        tasks.add(fjp.submit(() -> {/*from   w  w w.  ja va 2  s  . c  o  m*/
            T t = perThread.get();
            long first = (long) si * CHUNK_SIZE;
            int max = (int) Math.min((ei - si) * CHUNK_SIZE, length - first);
            for (int j = 0; j < max; j++) {
                consumer.apply(col, first + j, t);
            }
        }));
    }
    for (ForkJoinTask task : tasks) {
        task.join();
    }
}

From source file:me.rojo8399.placeholderapi.impl.utils.TypeUtils.java

@SuppressWarnings("unchecked")
public static <T> Optional<T> tryCast(Object val, final Class<T> expected) {
    if (val == null) {
        return Optional.empty();
    }//from w ww  .j  av a2s. c om
    if (expected == null) {
        throw new IllegalArgumentException("Must provide an expected class!");
    }
    if (val instanceof BaseValue<?> && !BaseValue.class.isAssignableFrom(expected)) {
        return tryCast(((BaseValue<?>) val).get(), expected);
    }
    if (val instanceof Supplier) {
        Supplier<?> fun = (Supplier<?>) val;
        return tryCast(fun.get(), expected);
    }
    if (Text.class.isAssignableFrom(expected)) {
        if (val instanceof Text) {
            return TypeUtils.tryOptional(() -> expected.cast(val));
        } else {
            if (val instanceof ItemStack) {
                return TypeUtils.tryOptional(() -> expected.cast(TextUtils.ofItem((ItemStack) val)));
            }
            if (val instanceof Instant) {
                return TypeUtils.tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE
                        .deserialize(PlaceholderAPIPlugin.getInstance().formatter()
                                .format(LocalDateTime.ofInstant((Instant) val, ZoneId.systemDefault())))));
            }
            if (val instanceof Duration) {
                String dur = formatDuration((Duration) val);
                return TypeUtils
                        .tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE.deserialize(dur)));
            }
            if (val instanceof LocalDateTime) {
                return TypeUtils.tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE.deserialize(
                        PlaceholderAPIPlugin.getInstance().formatter().format((LocalDateTime) val))));
            }
            if (val instanceof CommandSource) {
                return TypeUtils.tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE
                        .deserialize(String.valueOf(((CommandSource) val).getName()))));
            }
            if (val.getClass().isArray()) {
                List<Text> l2 = unboxPrimitiveArray(val).stream()
                        .map(o -> tryCast(o, (Class<? extends Text>) expected)).flatMap(unmapOptional())
                        .collect(Collectors.toList());
                return TypeUtils.tryOptional(() -> expected.cast(Text.joinWith(Text.of(", "), l2)));
            }
            if (val instanceof Iterable) {
                Iterable<?> l = (Iterable<?>) val;
                // should be safe cause we already checked assignability
                @SuppressWarnings("serial")
                final List<Text> l2 = new ArrayList<Object>() {
                    {
                        for (Object o : l) {
                            add(o);
                        }
                    }
                }.stream().map(o -> tryCast(o, (Class<? extends Text>) expected)).flatMap(unmapOptional())
                        .collect(Collectors.toList());
                return TypeUtils.tryOptional(() -> expected.cast(Text.joinWith(Text.of(", "), l2)));
            }
            return TypeUtils.tryOptional(
                    () -> expected.cast(TextSerializers.FORMATTING_CODE.deserialize(String.valueOf(val))));
        }
    }
    if (val instanceof String) {
        if (String.class.isAssignableFrom(expected)) {
            return tryOptional(() -> expected.cast(val));
        }
        if (expected.isArray() && String.class.isAssignableFrom(expected.getComponentType())) {
            String v = (String) val;
            if (v.isEmpty()) {
                return Optional.empty();
            }
            if (!v.contains("_")) {
                return tryOptional(() -> expected.cast(new String[] { v }));
            }
            String[] x = v.split("_");
            if (x.length == 0) {
                return Optional.empty();
            }
            boolean ne = false;
            for (String s : x) {
                ne = ne || !s.isEmpty();
            }
            if (!ne) {
                return Optional.empty();
            }
            return tryOptional(() -> expected.cast(x));
        }
        if (List.class.isAssignableFrom(expected)
                && String.class.isAssignableFrom(expected.getTypeParameters()[0].getGenericDeclaration())) {
            String v = (String) val;
            if (v.isEmpty()) {
                return Optional.empty();
            }
            if (!v.contains("_")) {
                return tryOptional(() -> expected.cast(Collections.singletonList(v)));
            }
            String[] x = v.split("_");
            if (x.length == 0) {
                return Optional.empty();
            }
            boolean ne = false;
            for (String s : x) {
                ne = ne || !s.isEmpty();
            }
            if (!ne) {
                return Optional.empty();
            }
            return tryOptional(() -> expected.cast(Arrays.asList(x)));
        }
        Optional<T> opt = tryOptional(() -> convertPrimitive((String) val, expected));
        if (opt.isPresent()) {
            return opt;
        }
        opt = deserializers.entrySet().stream()
                .filter(e -> e.getKey().isSubtypeOf(expected) || e.getKey().getRawType().equals(expected))
                .map(Map.Entry::getValue).map(f -> tryOptional(() -> f.apply((String) val)))
                .flatMap(unmapOptional()).findAny().flatMap(o -> tryOptional(() -> expected.cast(o)));
        if (opt.isPresent()) {
            return opt;
        }
        try {
            // should theoretically match any string -> object conversions, such as deser

            // for now im filtering against method names as well just to avoid issues where
            // expected result is not obtained due to weird methods, might change in future
            Method method = Arrays.stream(expected.getDeclaredMethods())
                    .filter(m -> Modifier.isStatic(m.getModifiers()) && Modifier.isPublic(m.getModifiers()))
                    .filter(m -> Arrays.stream(m.getParameterTypes()).anyMatch(c -> c.equals(String.class)))
                    .filter(m -> m.getReturnType().equals(expected) || m.getReturnType().equals(Optional.class))
                    .filter(m -> STRING_TO_VAL_PATTERN.matcher(m.getName()).find()).findAny().get(); // error if no
            Object valout = method.invoke(null, (String) val);
            if (valout == null) {
                return Optional.empty();
            }
            if (expected.isInstance(valout)) {
                // Register a new deserializer once we confirm it works. Should prevent
                // extremely long parsing from happening multiple times.
                final MethodHandle mh = MethodHandles.publicLookup().unreflect(method);
                PlaceholderServiceImpl.get().registerTypeDeserializer(TypeToken.of(expected), str -> {
                    try {
                        return expected.cast(mh.invokeExact((String) val));
                    } catch (Throwable e1) {
                        throw new RuntimeException(e1);
                    }
                });
                return tryOptional(() -> expected.cast(valout));
            }
            if (valout instanceof Optional) {
                Optional<?> valopt = (Optional<?>) valout;
                if (!valopt.isPresent()) {
                    return Optional.empty();
                }
                Object v = valopt.get();
                if (expected.isInstance(v)) {
                    // Register a new deserializer once we confirm it works. Should prevent
                    // extremely long parsing from happening multiple times.
                    final MethodHandle mh = MethodHandles.publicLookup().unreflect(method);
                    PlaceholderServiceImpl.get().registerTypeDeserializer(TypeToken.of(expected), str -> {
                        try {
                            Optional<?> optx = (Optional<?>) mh.invokeExact((String) val);
                            return expected.cast(optx.get());
                        } catch (Throwable e1) {
                            throw new RuntimeException(e1);
                        }
                    });
                    return tryOptional(() -> expected.cast(v));
                } else {
                    return Optional.empty();
                }
            }
            return Optional.empty();
        } catch (Exception e) {
            // fires if no method found, if invoke throws, if something else goes wrong
            return Optional.empty();
        }
    }
    return TypeUtils.tryOptional(() -> expected.cast(val));
}

From source file:hudson.XmlFile.java

/**
 * Provides an XStream replacement for an object unless a call to {@link #write} is currently in progress.
 * As per JENKINS-45892 this may be used by any class which expects to be written at top level to an XML file
 * but which cannot safely be serialized as a nested object (for example, because it expects some {@code onLoad} hook):
 * implement a {@code writeReplace} method delegating to this method.
 * The replacement need not be {@link Serializable} since it is only necessary for use from XStream.
 * @param o an object ({@code this} from {@code writeReplace})
 * @param replacement a supplier of a safely serializable replacement object with a {@code readResolve} method
 * @return {@code o}, if {@link #write} is being called on it, else the replacement
 * @since 2.74//from  w ww.ja  v  a 2 s .c o m
 */
public static Object replaceIfNotAtTopLevel(Object o, Supplier<Object> replacement) {
    File currentlyWriting = writing.get();
    if (beingWritten.containsKey(o) || currentlyWriting == null) {
        return o;
    } else {
        LOGGER.log(Level.WARNING,
                "JENKINS-45892: reference to " + o + " being saved from unexpected " + currentlyWriting,
                new IllegalStateException());
        return replacement.get();
    }
}

From source file:com.vmware.photon.controller.common.dcp.ServiceHostUtils.java

/**
 * Generic wait function./* w ww . j a v a  2 s  .c  o  m*/
 */
public static <T> T waitForState(Supplier<T> supplier, Predicate<T> predicate, long waitIterationSleep,
        long waitIterationCount, Runnable cleanup) throws Throwable {
    for (int i = 0; i < waitIterationCount; i++) {
        T t = supplier.get();
        if (predicate.test(t)) {
            return t;
        }
        Thread.sleep(waitIterationSleep);
    }

    if (cleanup != null) {
        cleanup.run();
    }
    throw new TimeoutException("timeout waiting for state transition.");
}

From source file:cz.lbenda.gui.controls.TextAreaFrmController.java

/** Create button which can open text editor */
public static Button createOpenButton(String windowTitle, @Nonnull Supplier<String> oldValueSupplier,
        @Nonnull Consumer<String> newValueConsumer) {
    String title = windowTitle == null ? msgDefaultWindowTitle : windowTitle;
    Button result = new Button(null, new ImageView(BUTTON_IMAGE));
    result.setTooltip(new Tooltip(msgBtnOpenInEditor_tooltip));
    BorderPane.setAlignment(result, Pos.TOP_RIGHT);
    result.setOnAction(event -> {//  w  w w .  jav  a  2 s  .  c  o  m
        Tuple2<Parent, TextAreaFrmController> tuple2 = TextAreaFrmController.createNewInstance();
        tuple2.get2().textProperty().setValue(oldValueSupplier.get());
        tuple2.get2().textProperty()
                .addListener((observable, oldValue, newValue) -> newValueConsumer.accept(newValue));
        Stage stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
        DialogHelper.getInstance().openWindowInCenterOfStage(stage, tuple2.get2().getMainPane(), title);
    });
    return result;
}

From source file:fr.landel.utils.commons.MapUtils2.java

/**
 * Create a new {@link HashMap} from the {@code objects}. Each objects are
 * checked and only added to the map if key and value are assignable from
 * classes./* w  w  w .j av  a2s . c  om*/
 * 
 * <p>
 * precondition: {@code mapProvider}, {@code keyClass}, {@code keyValue} and
 * {@code objects} cannot be {@code null}
 * </p>
 * 
 * <pre>
 * Map&lt;String, String&gt; map = MapUtils2.newHashMap(TreeMap::new, String.class, String.class, "key1", "value1", "key2", "value2");
 * 
 * // equivalent
 * Map&lt;String, String&gt; map = new TreeMap&lt;&gt;();
 * map.put("key1", "value1");
 * map.put("key2", "value2");
 * </pre>
 * 
 * @param mapProvider
 *            map constructor supplier
 * @param keyClass
 *            the class of key
 * @param valueClass
 *            the class of value
 * @param objects
 *            objects pair to put in the new {@link Map}
 * @param <K>
 *            the type of map key
 * @param <V>
 *            the type of map value
 * @param <M>
 *            the type of map
 * @return the new {@link Map}
 * @throws NullPointerException
 *             if {@code mapProvider}, {@code keyClass} or
 *             {@code valueClass} are {@code null}
 * @throws IllegalArgumentException
 *             if {@code objects} is {@code null} or empty or if
 *             {@code objects} length is even
 */
@SuppressWarnings("unchecked")
public static <K, V, M extends Map<K, V>> M newMap(final Supplier<M> mapProvider, final Class<K> keyClass,
        final Class<V> valueClass, Object... objects) {
    Objects.requireNonNull(mapProvider);
    Objects.requireNonNull(keyClass);
    Objects.requireNonNull(valueClass);
    if (objects == null || objects.length % 2 != 0) {
        throw new IllegalArgumentException(ERROR_OBJECTS_ODD);
    }

    final M map = mapProvider.get();

    int j;
    for (int i = 0; i < objects.length; i += 2) {
        j = i + 1;
        if ((objects[i] == null || keyClass.isAssignableFrom(objects[i].getClass()))
                && (objects[j] == null || valueClass.isAssignableFrom(objects[j].getClass()))) {
            map.put((K) objects[i], (V) objects[j]);
        }
    }

    return map;
}

From source file:fr.landel.utils.commons.ObjectUtils.java

/**
 * Check if the {@code object} is not {@code null}, otherwise throws the
 * {@code throwableSupplier}.//  w w  w. ja va  2  s.c  om
 * 
 * <p>
 * precondition: {@code throwableSupplier} cannot be {@code null}
 * </p>
 * 
 * <pre>
 * String object1 = ObjectUtils.requireNonNull("test", Exception::new);
 * // -&gt; set object
 * String object2 = ObjectUtils.requireNonNull(null, Exception::new);
 * // -&gt; throws an exception
 * String object3 = ObjectUtils.requireNonNull("test", null);
 * // -&gt; throws a NullPointerException
 * </pre>
 * 
 * @param object
 *            the object to check
 * @param throwableSupplier
 *            the throwable supplier
 * @param <T>
 *            the object type
 * @param <E>
 *            the throwable type
 * @return the object if not {@code null}
 * @throws E
 *             exception thrown if object is {@code null}
 * @throws NullPointerException
 *             if throwable supplier is {@code null}
 */
public static <T, E extends Throwable> T requireNonNull(final T object, final Supplier<E> throwableSupplier)
        throws E {
    Objects.requireNonNull(throwableSupplier, THROWABLE_SUPPLIER_ERROR);
    if (object == null) {
        throw throwableSupplier.get();
    }
    return object;
}

From source file:fr.landel.utils.commons.ObjectUtils.java

/**
 * Returns a default value if the object passed is {@code null}.
 *
 * <pre>/*from   www .j a v a 2  s  . c o  m*/
 * ObjectUtils.defaultIfNull(null, () -&gt; null)          = null
 * ObjectUtils.defaultIfNull(null, () -&gt; "")            = ""
 * ObjectUtils.defaultIfNull(null, () -&gt; "zz")          = "zz"
 * ObjectUtils.defaultIfNull("abc", () -&gt; *)            = "abc"
 * ObjectUtils.defaultIfNull(Boolean.TRUE, () -&gt; *)     = Boolean.TRUE
 * </pre>
 *
 * @param object
 *            the {@code Object} to test, may be {@code null}
 * @param defaultValueSupplier
 *            the default value supplier, cannot be {@code null}, may supply
 *            {@code null}
 * @param <T>
 *            the type of the object
 * @return {@code object} if it is not {@code null}, defaultValue otherwise
 * @throws NullPointerException
 *             if supplier is {@code null}
 */
public static <T> T defaultIfNull(final T object, final Supplier<? extends T> defaultValueSupplier) {
    Objects.requireNonNull(defaultValueSupplier, "The parameter defaultValueSupplier cannot be null");

    return object != null ? object : defaultValueSupplier.get();
}

From source file:ee.ria.xroad.proxy.util.MetaserviceTestUtil.java

/** Try to extract a single element of type T from the Soap Body, of class clazz.
 * @param body the {@link SOAPBody}//from   w  w w  .  j  a  v a 2s.c  o  m
 * @param clazz the class of type T
 * @param unmarshallerSupplier a {@link Supplier} for the unmarshaller. Needed if this util class does not
 *                             know of the class you want to unmarshall
 * @param <T> the {@link JAXBElement} value to extract, like {@link ee.ria.xroad.common.metadata.MethodListType}
 * @return the resulting element of type T
 * @throws JAXBException if unexpected errors occur during unmarshalling
 */
public static <T> T verifyAndGetSingleBodyElementOfType(SOAPBody body, Class<T> clazz,
        Supplier<Unmarshaller> unmarshallerSupplier) throws JAXBException {

    NodeList list = body.getChildNodes();

    List<Element> elements = new ArrayList<>();
    for (int i = 0; i < list.getLength(); i++) {
        Node node = list.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            elements.add((Element) node);
        }
    }

    assertThat("Was expecting a single element", elements.size(), is(1));
    JAXBElement<T> element = unmarshallerSupplier.get().unmarshal(elements.get(0), clazz);
    return element.getValue();
}