Example usage for java.util Optional isPresent

List of usage examples for java.util Optional isPresent

Introduction

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

Prototype

public boolean isPresent() 

Source Link

Document

If a value is present, returns true , otherwise false .

Usage

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   ww  w  .jav a 2  s.  c  o m
    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: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>// w  w  w  . j a va2  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: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/*from w  ww  .j a va2  s .com*/
 */
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: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

/**
 * Method to find candidates for predecessors.
 * If segment was created at the time of creation of stream (= no predecessors)
 * it returns an empty list./*  w ww  .j  av a  2s . c o  m*/
 * <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:eu.mihosoft.vrl.v3d.Edge.java

private static List<Polygon> boundaryPolygonsOfPlaneGroup(List<Polygon> planeGroup) {

    List<Polygon> polygons = boundaryPathsWithHoles(boundaryPaths(boundaryEdgesOfPlaneGroup(planeGroup)));

    System.out.println("polygons: " + polygons.size());

    List<Polygon> result = new ArrayList<>(polygons.size());

    for (Polygon p : polygons) {

        Optional<List<Polygon>> holesOfPresult = p.getStorage().getValue(Edge.KEY_POLYGON_HOLES);

        if (!holesOfPresult.isPresent()) {
            result.add(p);/* w  w w. j a va2 s  . com*/
        } else {
            result.addAll(PolygonUtil.concaveToConvex(p));
        }
    }

    return result;
}

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);/*from   ww  w .  j a  v  a 2  s .  c o  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:net.sf.jabref.model.database.BibDatabase.java

/**
 * Returns the text stored in the given field of the given bibtex entry
 * which belongs to the given database.//from  w w  w .  jav a 2s . c  o  m
 * <p>
 * If a database is given, this function will try to resolve any string
 * references in the field-value.
 * Also, if a database is given, this function will try to find values for
 * unset fields in the entry linked by the "crossref" field, if any.
 *
 * @param field    The field to return the value of.
 * @param entry    maybenull
 *                 The bibtex entry which contains the field.
 * @param database maybenull
 *                 The database of the bibtex entry.
 * @return The resolved field value or null if not found.
 */
public static String getResolvedField(String field, BibEntry entry, BibDatabase database) {
    if ("bibtextype".equals(field)) {
        return EntryUtil.capitalizeFirst(entry.getType());
    }

    // TODO: Changed this to also consider alias fields, which is the expected
    // behavior for the preview layout and for the check whatever all fields are present.
    // But there might be unwanted side-effects?!
    Optional<String> result = entry.getFieldOrAlias(field);

    // If this field is not set, and the entry has a crossref, try to look up the
    // field in the referred entry: Do not do this for the bibtex key.
    if (!result.isPresent() && (database != null) && !field.equals(BibEntry.KEY_FIELD)) {
        Optional<String> crossrefKey = entry.getFieldOptional(FieldName.CROSSREF);
        if (crossrefKey.isPresent()) {
            Optional<BibEntry> referred = database.getEntryByKey(crossrefKey.get());
            if (referred.isPresent()) {
                // Ok, we found the referred entry. Get the field value from that
                // entry. If it is unset there, too, stop looking:
                result = referred.get().getFieldOptional(field);
            }
        }
    }

    return BibDatabase.getText(result.orElse(null), database);
}

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

private static Optional<HistoryRecord> findSegmentSealedEvent(final int lower, final int upper,
        final int segmentNumber, final byte[] indexTable, final byte[] historyTable) {

    if (lower > upper || historyTable.length == 0) {
        return Optional.empty();
    }/*  w w  w . j  a  va2s .c o  m*/

    final int offset = ((lower + upper) / 2) * IndexRecord.INDEX_RECORD_SIZE;

    final Optional<IndexRecord> indexRecord = IndexRecord.readRecord(indexTable, offset);

    final Optional<IndexRecord> previousIndex = indexRecord.isPresent()
            ? IndexRecord.fetchPrevious(indexTable, offset)
            : Optional.empty();

    final int historyTableOffset = indexRecord.isPresent() ? indexRecord.get().getHistoryOffset() : 0;
    final Optional<HistoryRecord> record = HistoryRecord.readRecord(historyTable, historyTableOffset, false);

    // if segment is not present in history record, check if it is present in previous
    // if yes, we have found the segment sealed event
    // else repeat binary searchIndex
    if (!record.get().getSegments().contains(segmentNumber)) {
        assert previousIndex.isPresent();

        final Optional<HistoryRecord> previousRecord = HistoryRecord.readRecord(historyTable,
                previousIndex.get().getHistoryOffset(), false);
        if (previousRecord.get().getSegments().contains(segmentNumber)) {
            return record; // search complete
        } else { // binary search lower
            return findSegmentSealedEvent(lower, (lower + upper) / 2 - 1, segmentNumber, indexTable,
                    historyTable);
        }
    } else { // binary search upper
        // not sealed in the current location: look in second half
        return findSegmentSealedEvent((lower + upper) / 2 + 1, upper, segmentNumber, indexTable, historyTable);
    }
}

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

/**
 * Method to compute segments created and deleted in latest scale event.
 *
 * @param historyTable history table// www .ja v  a 2s  .co m
 * @return pair of segments sealed and segments created in last scale event.
 */
public static Pair<List<Integer>, List<Integer>> getLatestScaleData(final byte[] historyTable) {
    final Optional<HistoryRecord> current = HistoryRecord.readLatestRecord(historyTable, false);
    ImmutablePair<List<Integer>, List<Integer>> result;
    if (current.isPresent()) {
        final Optional<HistoryRecord> previous = HistoryRecord.fetchPrevious(current.get(), historyTable);
        result = previous
                .map(historyRecord -> new ImmutablePair<>(
                        diff(historyRecord.getSegments(), current.get().getSegments()),
                        diff(current.get().getSegments(), historyRecord.getSegments())))
                .orElseGet(() -> new ImmutablePair<>(Collections.emptyList(), current.get().getSegments()));
    } else {
        result = new ImmutablePair<>(Collections.emptyList(), Collections.emptyList());
    }
    return result;
}