Example usage for java.util Optional get

List of usage examples for java.util Optional get

Introduction

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

Prototype

public T get() 

Source Link

Document

If a value is present, returns the value, otherwise throws NoSuchElementException .

Usage

From source file:info.archinnov.achilles.internals.parser.CodecFactory.java

public static CodecContext buildCodecContext(AptUtils aptUtils, String codecClassName) {

    final TypeMirror codecInterfaceType = aptUtils.erasure(aptUtils.elementUtils
            .getTypeElement(info.archinnov.achilles.type.codec.Codec.class.getCanonicalName()).asType());
    final Optional<? extends TypeMirror> foundCodecInterface = aptUtils.elementUtils
            .getTypeElement(codecClassName).getInterfaces().stream()
            .filter(x -> aptUtils.typeUtils.isSameType(aptUtils.erasure(x), codecInterfaceType)).findFirst();

    aptUtils.validateTrue(foundCodecInterface.isPresent(),
            "Codec class '%s' should implement the Codec<FROM, TO> interface", codecClassName);

    final TypeMirror typeMirror = foundCodecInterface.get();

    final List<TypeName> codecTypes = asDeclared(typeMirror).getTypeArguments().stream().map(TypeName::get)
            .collect(toList());// w  w  w  .  jav  a2 s  .c  om
    aptUtils.validateTrue(codecTypes.size() == 2, "Codec class '%s' should have 2 parameters: Codec<FROM, TO>",
            codecInterfaceType);

    final TypeMirror codecType = aptUtils.erasure(aptUtils.elementUtils.getTypeElement(codecClassName));

    return new CodecContext(TypeName.get(codecType), codecTypes.get(0), codecTypes.get(1));
}

From source file:io.pravega.controller.store.stream.tables.TableHelper.java

/**
 * Find history record from the event when the given segment was sealed.
 * If segment is never sealed this method returns an empty list.
 * If segment is yet to be created, this method still returns empty list.
 * <p>//from   ww w  .  j  a  v a2 s .com
 * Find index that corresponds to segment start event.
 * Perform binary search on index+history records to find segment seal event.
 * <p>
 * If index table is not up to date we may have two cases:
 * 1. Segment create time > highest event time in index
 * 2. Segment seal time > highest event time in index
 * <p>
 * For 1 we cant have any searches in index and will need to fall through
 * History table starting from last indexed record.
 * <p>
 * For 2, fall through History Table starting from last indexed record
 * to find segment sealed event in history table.
 *
 * @param segment      segment
 * @param indexTable   index table
 * @param historyTable history table
 * @return
 */
public static List<Integer> findSegmentSuccessorCandidates(final Segment segment, final byte[] indexTable,
        final byte[] historyTable) {
    // fetch segment start time from segment Is
    // fetch last index Ic
    // fetch record corresponding to Ic. If segment present in that history record, fall through history table
    // else perform binary searchIndex
    // Note: if segment is present at Ic, we will fall through in the history table one record at a time
    Pair<Integer, Optional<IndexRecord>> search = IndexRecord.search(segment.getStart(), indexTable);
    final Optional<IndexRecord> recordOpt = search.getValue();
    final int startingOffset = recordOpt.isPresent() ? recordOpt.get().getHistoryOffset() : 0;

    final Optional<HistoryRecord> historyRecordOpt = findSegmentCreatedEvent(startingOffset, segment,
            historyTable);

    // segment information not in history table
    if (!historyRecordOpt.isPresent()) {
        return new ArrayList<>();
    }

    final int lower = search.getKey() / IndexRecord.INDEX_RECORD_SIZE;

    final int upper = (indexTable.length - IndexRecord.INDEX_RECORD_SIZE) / IndexRecord.INDEX_RECORD_SIZE;

    // index table may be stale, whereby we may not find segment.start to match an entry in the index table
    final Optional<IndexRecord> indexRecord = IndexRecord.readLatestRecord(indexTable);
    // if nothing is indexed read the first record in history table, hence offset = 0
    final int lastIndexedRecordOffset = indexRecord.isPresent() ? indexRecord.get().getHistoryOffset() : 0;

    final Optional<HistoryRecord> lastIndexedRecord = HistoryRecord.readRecord(historyTable,
            lastIndexedRecordOffset, false);

    // if segment is present in history table but its offset is greater than last indexed record,
    // we cant do anything on index table, fall through. OR
    // if segment exists at the last indexed record in history table, fall through,
    // no binary search possible on index
    if (lastIndexedRecord.get().getScaleTime() < historyRecordOpt.get().getScaleTime()
            || lastIndexedRecord.get().getSegments().contains(segment.getNumber())) {
        // segment was sealed after the last index entry
        HistoryRecord startPoint = lastIndexedRecord.get().getScaleTime() < historyRecordOpt.get()
                .getScaleTime() ? historyRecordOpt.get() : lastIndexedRecord.get();
        Optional<HistoryRecord> next = HistoryRecord.fetchNext(startPoint, historyTable, false);

        while (next.isPresent() && next.get().getSegments().contains(segment.getNumber())) {
            startPoint = next.get();
            next = HistoryRecord.fetchNext(startPoint, historyTable, false);
        }

        if (next.isPresent()) {
            return next.get().getSegments();
        } else { // we have reached end of history table which means segment was never sealed
            return new ArrayList<>();
        }
    } else {
        // segment is definitely sealed and segment sealed event is also present in index table
        // we should be able to find it by doing binary search on Index table
        final Optional<HistoryRecord> record = findSegmentSealedEvent(lower, upper, segment.getNumber(),
                indexTable, historyTable);

        return record.isPresent() ? record.get().getSegments() : new ArrayList<>();
    }
}

From source file:io.github.benas.randombeans.util.ReflectionUtils.java

@SuppressWarnings("unchecked")
public static <T> Randomizer<T> newInstance(final Class<T> type,
        final RandomizerArgument[] randomizerArguments) {
    try {//www  .  j av  a2 s . co  m
        if (notEmpty(randomizerArguments)) {
            Optional<Constructor<?>> matchingConstructor = asList(type.getConstructors()).stream()
                    .filter(constructor -> hasSameArgumentNumber(constructor, randomizerArguments)
                            && hasSameArgumentTypes(constructor, randomizerArguments))
                    .findFirst();
            if (matchingConstructor.isPresent()) {
                return (Randomizer<T>) matchingConstructor.get()
                        .newInstance(convertArguments(randomizerArguments));
            }
        }
        return (Randomizer<T>) type.newInstance();
    } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) {
        throw new ObjectGenerationException(
                format("Could not create Randomizer of type: %s with constructor arguments: %s", type,
                        Arrays.toString(randomizerArguments)),
                e);
    }
}

From source file:io.pravega.controller.store.stream.tables.TableHelper.java

/**
 * Method to find candidates for predecessors.
 * If segment was created at the time of creation of stream (= no predecessors)
 * it returns an empty list.//from w  w w.  j  av  a2s  .  com
 * <p>
 * First find the segment start time entry in the history table by using a binary
 * search on index followed by fall through History table if index is not up to date.
 * <p>
 * Fetch the record in history table that immediately preceeds segment created entry.
 *
 * @param segment      segment
 * @param indexTable   index table
 * @param historyTable history table
 * @return
 */
public static List<Integer> findSegmentPredecessorCandidates(final Segment segment, final byte[] indexTable,
        final byte[] historyTable) {
    final Optional<IndexRecord> recordOpt = IndexRecord.search(segment.getStart(), indexTable).getValue();
    final int startingOffset = recordOpt.isPresent() ? recordOpt.get().getHistoryOffset() : 0;

    Optional<HistoryRecord> historyRecordOpt = findSegmentCreatedEvent(startingOffset, segment, historyTable);
    if (!historyRecordOpt.isPresent()) {
        // cant compute predecessors because the creation event is not present in history table yet.
        return new ArrayList<>();
    }

    final HistoryRecord record = historyRecordOpt.get();

    final Optional<HistoryRecord> previous = HistoryRecord.fetchPrevious(record, historyTable);

    if (!previous.isPresent()) {
        return new ArrayList<>();
    } else {
        assert !previous.get().getSegments().contains(segment.getNumber());
        return previous.get().getSegments();
    }
}

From source file:net.sf.jabref.model.DuplicateCheck.java

private static int compareSingleField(String field, BibEntry one, BibEntry two) {
    Optional<String> optionalStringOne = one.getFieldOptional(field);
    Optional<String> optionalStringTwo = two.getFieldOptional(field);
    if (!optionalStringOne.isPresent()) {
        if (!optionalStringTwo.isPresent()) {
            return EMPTY_IN_BOTH;
        }//from   www  . j  a v a 2 s . c  om
        return EMPTY_IN_ONE;
    } else if (!optionalStringTwo.isPresent()) {
        return EMPTY_IN_TWO;
    }

    // Both strings present
    String stringOne = optionalStringOne.get();
    String stringTwo = optionalStringTwo.get();

    if (InternalBibtexFields.getFieldExtras(field).contains(FieldProperties.PERSON_NAMES)) {
        // Specific for name fields.
        // Harmonise case:
        String authorOne = AuthorList.fixAuthorLastNameOnlyCommas(stringOne, false).replace(" and ", " ")
                .toLowerCase();
        String authorTwo = AuthorList.fixAuthorLastNameOnlyCommas(stringTwo, false).replace(" and ", " ")
                .toLowerCase();
        double similarity = DuplicateCheck.correlateByWords(authorOne, authorTwo);
        if (similarity > 0.8) {
            return EQUAL;
        }
        return NOT_EQUAL;
    } else if (FieldName.PAGES.equals(field)) {
        // Pages can be given with a variety of delimiters, "-", "--", " - ", " -- ".
        // We do a replace to harmonize these to a simple "-":
        // After this, a simple test for equality should be enough:
        stringOne = stringOne.replaceAll("[- ]+", "-");
        stringTwo = stringTwo.replaceAll("[- ]+", "-");
        if (stringOne.equals(stringTwo)) {
            return EQUAL;
        }
        return NOT_EQUAL;
    } else if (FieldName.JOURNAL.equals(field)) {
        // We do not attempt to harmonize abbreviation state of the journal names,
        // but we remove periods from the names in case they are abbreviated with
        // and without dots:
        stringOne = stringOne.replace(".", "").toLowerCase();
        stringTwo = stringTwo.replace(".", "").toLowerCase();
        double similarity = DuplicateCheck.correlateByWords(stringOne, stringTwo);
        if (similarity > 0.8) {
            return EQUAL;
        }
        return NOT_EQUAL;
    } else {
        stringOne = stringOne.toLowerCase();
        stringTwo = stringTwo.toLowerCase();
        double similarity = DuplicateCheck.correlateByWords(stringOne, stringTwo);
        if (similarity > 0.8) {
            return EQUAL;
        }
        return NOT_EQUAL;
    }
}

From source file:de.tu_dortmund.ub.data.dswarm.TaskProcessingUnit.java

private static boolean goMultiThreaded(final Optional<Boolean> optionalDoInit,
        final Optional<Boolean> optionalDoTransformations,
        final Optional<Boolean> optionalAllowMultipleDataModels,
        final Optional<Boolean> optionalDoIngestOnTheFly, final Optional<Boolean> optionalDoExportOnTheFly) {

    return optionalDoInit.isPresent() && optionalDoInit.get() && optionalAllowMultipleDataModels.isPresent()
            && optionalAllowMultipleDataModels.get() && optionalDoTransformations.isPresent()
            && optionalDoTransformations.get() && optionalDoIngestOnTheFly.isPresent()
            && optionalDoIngestOnTheFly.get() && optionalDoExportOnTheFly.isPresent()
            && optionalDoExportOnTheFly.get();
}

From source file:io.pravega.controller.store.stream.tables.TableHelper.java

private static Optional<HistoryRecord> findRecordInHistoryTable(final int startingOffset, final long timeStamp,
        final byte[] historyTable, final boolean ignorePartial) {
    final Optional<HistoryRecord> recordOpt = HistoryRecord.readRecord(historyTable, startingOffset,
            ignorePartial);//w w w. j a v a  2 s  . co m

    if (!recordOpt.isPresent() || recordOpt.get().getScaleTime() > timeStamp) {
        return Optional.empty();
    }

    HistoryRecord record = recordOpt.get();
    Optional<HistoryRecord> next = HistoryRecord.fetchNext(record, historyTable, ignorePartial);

    // check if current record is correct else we need to fall through
    // if timestamp is > record.timestamp and less than next.timestamp
    assert timeStamp >= record.getScaleTime();
    while (next.isPresent() && !next.get().isPartial() && timeStamp >= next.get().getScaleTime()) {
        record = next.get();
        next = HistoryRecord.fetchNext(record, historyTable, ignorePartial);
    }

    return Optional.of(record);
}

From source file:co.runrightfast.vertx.orientdb.verticle.OrientDBVerticleTest.java

private static void initDatabase() {
    Optional<OrientDBService> orientDBService = TypeSafeObjectRegistry.GLOBAL_OBJECT_REGISTRY
            .get(OrientDBService.ORIENTDB_SERVICE);
    while (!orientDBService.isPresent()) {
        log.log(Level.WARNING, "Waiting for OrientDBService ...");
        sleep(Duration.ofSeconds(2));
        orientDBService = TypeSafeObjectRegistry.GLOBAL_OBJECT_REGISTRY.get(OrientDBService.ORIENTDB_SERVICE);
    }//from  w w  w . j a va 2  s.  c om

    final OServerAdmin admin = orientDBService.get().getServerAdmin();
    try {
        OrientDBUtils.createDatabase(admin, EventLogRepository.DB);
    } catch (final Exception e) {
        e.printStackTrace();
    } finally {
        admin.close();
    }

    EventLogRepository.initDatabase(
            orientDBService.get().getODatabaseDocumentTxSupplier(EventLogRepository.DB).get().get());
}

From source file:com.uber.hoodie.common.util.CompactionUtils.java

/**
 * Generate compaction operation from file-slice
 *
 * @param partitionPath          Partition path
 * @param fileSlice              File Slice
 * @param metricsCaptureFunction Metrics Capture function
 * @return Compaction Operation/* ww w .  j  av  a 2 s . c om*/
 */
public static HoodieCompactionOperation buildFromFileSlice(String partitionPath, FileSlice fileSlice,
        Optional<Function<Pair<String, FileSlice>, Map<String, Double>>> metricsCaptureFunction) {
    HoodieCompactionOperation.Builder builder = HoodieCompactionOperation.newBuilder();
    builder.setPartitionPath(partitionPath);
    builder.setFileId(fileSlice.getFileId());
    builder.setBaseInstantTime(fileSlice.getBaseInstantTime());
    builder.setDeltaFilePaths(
            fileSlice.getLogFiles().map(lf -> lf.getPath().toString()).collect(Collectors.toList()));
    if (fileSlice.getDataFile().isPresent()) {
        builder.setDataFilePath(fileSlice.getDataFile().get().getPath());
    }

    if (metricsCaptureFunction.isPresent()) {
        builder.setMetrics(metricsCaptureFunction.get().apply(Pair.of(partitionPath, fileSlice)));
    }
    return builder.build();
}

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 w w .  ja v  a  2  s.  com
    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));
}