/** * Returns the first ancestor found of the specified type to the specified * document when walking up the tree. If there was no ancestor of the * specified type and the root was reached, an empty {@code Optional} is * returned. * * @param <E> ancestor type * @param document the starting point * @param clazz the ancestor type to look for * @return first ancestor found or empty */ public static <E extends Document> Optional<E> ancestor( final Document document, final Class<E> clazz) { requireNonNull(document); requireNonNull(clazz); return document.ancestors() .filter(clazz::isInstance) .map(clazz::cast) .findFirst(); }
/** * Returns {@code true} if the specified document and all its ancestors are * enabled. If at least one ancestor is not enabled, {@code false} is * returned. * * @param document the document to test * @return {@code true} if enabled, else {@code false} */ public static boolean isAllAncestorsEnabled(Document document) { return HasEnabled.test(document) && document.ancestors() .noneMatch(doc -> !HasEnabled.test(doc)); }
/** * Returns this node or one of the ancestor nodes if it matches the * specified {@code Class}. If no such node exists, an * {@code IllegalStateException} is thrown. * * @param <E> the type of the class to match * @param clazz the class to match * @return the node found */ private <E extends Document & HasMainInterface> Optional<E> documentOfType(Class<E> clazz) { requireNonNull(clazz); if (clazz.isAssignableFrom(document().mainInterface())) { @SuppressWarnings("unchecked") final E result = (E) document(); return Optional.of(result); } return document() .ancestors() .filter(clazz::isInstance) .map(clazz::cast) .findAny(); } }
/** * Returns this node or one of the ancestor nodes if it matches the * specified {@code Class}. If no * such node exists, an {@code Optional.empty()} is returned. * * @param <E> the type of the class to match * @param clazz the class to match * @return the node found */ default <E extends Document> Optional<E> getDocument(Class<E> clazz) { requireNonNull(clazz); if (clazz.isAssignableFrom(Translator.this.getDocument().mainInterface())) { @SuppressWarnings("unchecked") final E result = (E) Translator.this.getDocument(); return Optional.of(result); } return Translator.this.getDocument() .ancestors() .filter(clazz::isInstance) .map(clazz::cast) .findAny(); }
final List<HasAlias> ancestors = document.ancestors() .map(HasAlias::of) .collect(toList());