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:net.sf.jabref.gui.desktop.JabRefDesktop.java

private static void openExternalFilePlatformIndependent(Optional<ExternalFileType> fileType, String filePath)
        throws IOException {
    if (fileType.isPresent()) {
        String application = fileType.get().getOpenWithApplication();

        if (application.isEmpty()) {
            NATIVE_DESKTOP.openFile(filePath, fileType.get().getExtension());
        } else {/* w ww .  jav a 2s  .  c  om*/
            NATIVE_DESKTOP.openFileWithApplication(filePath, application);
        }
    }
}

From source file:net.sf.jabref.gui.desktop.JabRefDesktop.java

/**
 * Open an external file, attempting to use the correct viewer for it.
 *
 * @param databaseContext/*from  w  w  w .j a v a 2  s .  co  m*/
 *            The database this file belongs to.
 * @param link
 *            The filename.
 * @return false if the link couldn't be resolved, true otherwise.
 */
public static boolean openExternalFileAnyFormat(final BibDatabaseContext databaseContext, String link,
        final Optional<ExternalFileType> type) throws IOException {
    boolean httpLink = false;

    if (REMOTE_LINK_PATTERN.matcher(link.toLowerCase()).matches()) {
        httpLink = true;
    }

    // For other platforms we'll try to find the file type:
    File file = new File(link);

    if (!httpLink) {
        Optional<File> tmp = FileUtil.expandFilename(databaseContext, link);
        if (tmp.isPresent()) {
            file = tmp.get();
        }
    }

    // Check if we have arrived at a file type, and either an http link or an existing file:
    if ((httpLink || file.exists()) && (type.isPresent())) {
        // Open the file:
        String filePath = httpLink ? link : file.getPath();
        openExternalFilePlatformIndependent(type, filePath);
        return true;
    } else {
        // No file matched the name, or we didn't know the file type.
        return false;
    }
}

From source file:nu.yona.server.subscriptions.entities.Buddy.java

/**
 * Determines the name of the user (first or last) through an algorithm that ensures the best possible value is returned, but
 * never null. It first tries calling the getter that is supposed to take it from the buddy entity or message. If that returns
 * null and a user is given and that user is not yet migrated (i.e. the name is not removed from it), it tries to get that. If
 * that doesn't return anything either, it builds a string based on the given nickname.
 * /* www. jav  a2s. c  om*/
 * @param buddyUserNameGetter Getter to fetch the name from the buddy entity or a message
 * @param user Optional user entity
 * @param userNameGetter Getter to fetch the name (first or last) from the user entity
 * @param fallbackMessageId The ID of the translatable message to build the fallback string
 * @param nickname The nickname to include in the fallback string
 * @return The name or a substitute for it (never null)
 */
public static String determineName(Supplier<String> buddyUserNameGetter, Optional<User> user,
        Function<User, String> userNameGetter, String fallbackMessageId, String nickname) {
    String name = buddyUserNameGetter.get();
    if (name != null) {
        return name;
    }
    if ((user.isPresent()) && (user.get().getPrivateDataMigrationVersion() < VERSION_OF_NAME_MIGRATION)) {
        // User is not deleted yet and not yet migrated, so get the name from the user entity
        name = userNameGetter.apply(user.get());
    }
    if (name != null) {
        return name;
    }
    // We're apparently in a migration process to move first and last name to the private data
    // The app will fetch the message, causing processing of all unprocessed messages. That'll fill in the first and last
    // name in the buddy entity, so from then onward, the user will see the right data
    return Translator.getInstance().getLocalizedMessage(fallbackMessageId, nickname);
}

From source file:net.sf.jabref.logic.util.io.FileUtil.java

/**
 * Converts a relative filename to an absolute one, if necessary. Returns
 * null if the file does not exist.//  w  ww  .  j  a v  a  2s .c  o m
 * <p>
 * Will look in each of the given dirs starting from the beginning and
 * returning the first found file to match if any.
 */
public static Optional<File> expandFilename(String name, List<String> directories) {
    for (String dir : directories) {
        if (dir != null) {
            Optional<File> result = expandFilename(name, dir);
            if (result.isPresent()) {
                return result;
            }
        }
    }

    return Optional.empty();
}

From source file:com.wrmsr.wava.TestWhatever.java

public static Stream<BasicSet> collapseIfOr(BasicSet basics, Basic basic) {
    return matchBoolean(basic).flatMap(m1 -> {
        Basic or = basics.get(m1.ifFalse);
        if (!or.getBody().isEmpty() || !basics.getInputs(or).equals(ImmutableSet.of(basic.getName()))) {
            return Stream.empty();
        }//www . java 2  s .co m
        Basic then = basics.get(m1.ifTrue);
        if (!basics.getInputs(then).equals(ImmutableSet.of(basic.getName(), or.getName()))) {
            return Stream.empty();
        }
        Optional<Name> after = getUnconditionalTarget(then.getBreakTable());
        if (!after.isPresent()) {
            return Stream.empty();
        }
        return matchBoolean(or).flatMap(m2 -> {
            if (!m2.ifTrue.equals(then.getName()) || !m2.ifFalse.equals(after.get())) {
                return Stream.empty();
            }
            Basic newBasic = new Basic(basic.getName(),
                    ImmutableList.<Node>builder().addAll(basic.getBody())
                            .add(new If(new Binary(BinaryOp.CondOr, Type.I32, m1.condition, m2.condition),
                                    nodify(then.getBody()), new Nop()))
                            .build(),
                    new BreakTable(ImmutableList.of(), after.get(), new Nop()), minBasicIndex(basic, or, then));
            return Stream.of(basics.replace(newBasic).remove(or).remove(then));
        });
    });
}

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

public static List<FunctionSignature> parseFunctionRegistryAndValidateTypes(AptUtils aptUtils, TypeElement elm,
        GlobalParsingContext context) {//from  w ww. j a v  a 2s .  co  m
    final List<ExecutableElement> methods = ElementFilter.methodsIn(elm.getEnclosedElements());
    final Optional<String> keyspace = AnnotationTree.findKeyspaceForFunctionRegistry(aptUtils, elm);
    final FunctionParamParser paramParser = new FunctionParamParser(aptUtils);

    final TypeName parentType = TypeName.get(aptUtils.erasure(elm));

    //Not allow to declare function in system keyspaces
    if (keyspace.isPresent()) {
        final String keyspaceName = keyspace.get();
        aptUtils.validateFalse(
                FORBIDDEN_KEYSPACES.contains(keyspaceName)
                        || FORBIDDEN_KEYSPACES.contains(keyspaceName.toLowerCase()),
                "The provided keyspace '%s' on function registry class '%s' is forbidden because it is a system keyspace",
                keyspaceName, parentType);
    }

    aptUtils.validateFalse(keyspace.isPresent() && isBlank(keyspace.get()),
            "The declared keyspace for function registry '%s' should not be blank",
            elm.getSimpleName().toString());

    return methods.stream().map(method -> {
        final String methodName = method.getSimpleName().toString();
        final List<AnnotationTree> annotationTrees = AnnotationTree.buildFromMethodForParam(aptUtils, method);
        final List<? extends VariableElement> parameters = method.getParameters();
        final List<FunctionParamSignature> parameterSignatures = new ArrayList<>(parameters.size());
        for (int i = 0; i < parameters.size(); i++) {
            final VariableElement parameter = parameters.get(i);
            context.nestedTypesStrategy.validate(aptUtils, annotationTrees.get(i), method.toString(),
                    parentType);
            final FunctionParamSignature functionParamSignature = paramParser.parseParam(context,
                    annotationTrees.get(i), parentType, methodName, parameter.getSimpleName().toString());
            parameterSignatures.add(functionParamSignature);
        }

        //Validate return type
        final TypeMirror returnType = method.getReturnType();
        aptUtils.validateFalse(returnType.getKind() == TypeKind.VOID,
                "The return type for the method '%s' on class '%s' should not be VOID", method.toString(),
                elm.getSimpleName().toString());

        aptUtils.validateFalse(returnType.getKind().isPrimitive(),
                "Due to internal JDK API limitations, UDF/UDA return types cannot be primitive. "
                        + "Use their Object counterpart instead for method '%s' " + "in function registry '%s'",
                method.toString(), elm.getQualifiedName());

        final FunctionParamSignature returnTypeSignature = paramParser.parseParam(context,
                AnnotationTree.buildFromMethodForReturnType(aptUtils, method), parentType, methodName,
                "returnType");

        // Validate NOT system function comparing only name lowercase
        aptUtils.validateFalse(SYSTEM_FUNCTIONS_NAME.contains(methodName.toLowerCase()),
                "The name of the function '%s' in class '%s' is reserved for system functions", method,
                parentType);

        return new FunctionSignature(keyspace, parentType, methodName, returnTypeSignature,
                parameterSignatures);
    }).collect(toList());
}

From source file:com.skelril.skree.content.registry.item.zone.ZoneItemUtil.java

public static void setMasterToZone(ItemStack stack, String zone) {
    Optional<ZoneService> optService = Sponge.getServiceManager().provide(ZoneService.class);

    if (optService.isPresent()) {
        ZoneService service = optService.get();

        if (stack.getTagCompound() == null) {
            stack.setTagCompound(new NBTTagCompound());
        }//from   w  ww  . ja va 2 s  .  com

        if (!stack.getTagCompound().hasKey("skree_zone_data")) {
            stack.getTagCompound().setTag("skree_zone_data", new NBTTagCompound());
        }

        NBTTagCompound tag = stack.getTagCompound().getCompoundTag("skree_zone_data");
        tag.setString("zone", zone);
        tag.setInteger("zone_player_count", 1);
        tag.setInteger("zone_max_players", service.getMaxGroupSize(zone).orElse(-1));
        tag.setString("zone_id", UUID.randomUUID().toString());

        attune(stack);
    }
}

From source file:com.skelril.skree.content.registry.item.zone.ZoneItemUtil.java

public static boolean hasSameZoneID(ItemStack stackA, ItemStack stackB) {
    if (isZoneItem(stackA) && isZoneItem(stackB)) {
        Optional<UUID> zoneIDA = getZoneID(stackA);
        Optional<UUID> zoneIDB = getZoneID(stackB);
        return zoneIDA.isPresent() && zoneIDB.isPresent() && zoneIDA.get().equals(zoneIDB.get());
    }/*from  w  w  w.  j av a  2s .c  o m*/
    return false;
}

From source file:net.sf.jabref.exporter.BibDatabaseWriter.java

private static List<FieldChange> applySaveActions(List<BibEntry> toChange, MetaData metaData) {
    List<FieldChange> changes = new ArrayList<>();

    Optional<FieldFormatterCleanups> saveActions = metaData.getSaveActions();
    if (saveActions.isPresent()) {
        // save actions defined -> apply for every entry
        for (BibEntry entry : toChange) {
            changes.addAll(saveActions.get().applySaveActions(entry));
        }//w  w w. ja v a 2s  . co  m
    }

    return changes;
}

From source file:com.hurence.logisland.plugin.PluginManager.java

private static void installPlugin(String artifact, String logislandHome) {
    Optional<ModuleInfo> moduleInfo = findPluginMeta().entrySet().stream()
            .filter(e -> artifact.equals(e.getKey().getArtifact())).map(Map.Entry::getKey).findFirst();
    if (moduleInfo.isPresent()) {
        System.err/*from w w  w .  j ava 2  s.co  m*/
                .println("A component already matches the artifact " + artifact + ". Please remove it first.");
        System.exit(-1);
    }

    try {

        IvySettings settings = new IvySettings();
        settings.load(new File(logislandHome, "conf/ivy.xml"));

        Ivy ivy = Ivy.newInstance(settings);
        ivy.bind();

        System.out.println("\nDownloading dependencies. Please hold on...\n");

        String parts[] = Arrays.stream(artifact.split(":")).map(String::trim).toArray(a -> new String[a]);
        if (parts.length != 3) {
            throw new IllegalArgumentException(
                    "Unrecognized artifact format. It should be groupId:artifactId:version");
        }
        ModuleRevisionId revisionId = new ModuleRevisionId(new ModuleId(parts[0], parts[1]), parts[2]);
        Set<ArtifactDownloadReport> toBePackaged = downloadArtifacts(ivy, revisionId,
                new String[] { "default", "compile", "runtime" });

        ArtifactDownloadReport artifactJar = toBePackaged.stream()
                .filter(a -> a.getArtifact().getModuleRevisionId().equals(revisionId)).findFirst()
                .orElseThrow(() -> new IllegalStateException("Unable to find artifact " + artifact
                        + ". Please check the name is correct and the repositories on ivy.xml are correctly configured"));

        Manifest manifest = new JarFile(artifactJar.getLocalFile()).getManifest();
        File libDir = new File(logislandHome, "lib");

        if (manifest.getMainAttributes().containsKey(ManifestAttributes.MODULE_ARTIFACT)) {
            org.apache.commons.io.FileUtils.copyFileToDirectory(artifactJar.getLocalFile(), libDir);
            //we have a logisland plugin. Just copy it
            System.out.println(String.format("Found logisland plugin %s version %s\n" + "It will provide:",
                    manifest.getMainAttributes().getValue(ManifestAttributes.MODULE_NAME),
                    manifest.getMainAttributes().getValue(ManifestAttributes.MODULE_VERSION)));
            Arrays.stream(manifest.getMainAttributes().getValue(ManifestAttributes.MODULE_EXPORTS).split(","))
                    .map(String::trim).forEach(s -> System.out.println("\t" + s));

        } else {
            System.out.println("Repackaging artifact and its dependencies");
            Set<ArtifactDownloadReport> environment = downloadArtifacts(ivy, revisionId,
                    new String[] { "provided" });
            Set<ArtifactDownloadReport> excluded = toBePackaged.stream()
                    .filter(adr -> excludeGroupIds.stream()
                            .anyMatch(s -> s.matches(adr.getArtifact().getModuleRevisionId().getOrganisation()))
                            || excludedArtifactsId.stream().anyMatch(
                                    s -> s.matches(adr.getArtifact().getModuleRevisionId().getName())))
                    .collect(Collectors.toSet());

            toBePackaged.removeAll(excluded);
            environment.addAll(excluded);

            Repackager rep = new Repackager(artifactJar.getLocalFile(), new LogislandPluginLayoutFactory());
            rep.setMainClass("");
            File destFile = new File(libDir, "logisland-component-" + artifactJar.getLocalFile().getName());
            rep.repackage(destFile, callback -> toBePackaged.stream().filter(adr -> adr.getLocalFile() != null)
                    .filter(adr -> !adr.getArtifact().getModuleRevisionId().equals(revisionId))
                    .map(adr -> new Library(adr.getLocalFile(), LibraryScope.COMPILE)).forEach(library -> {
                        try {
                            callback.library(library);
                        } catch (IOException e) {
                            throw new UncheckedIOException(e);
                        }
                    }));
            Thread.currentThread().setContextClassLoader(new URLClassLoader(
                    environment.stream().filter(adr -> adr.getLocalFile() != null).map(adr -> {
                        try {
                            return adr.getLocalFile().toURI().toURL();
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }).toArray(a -> new URL[a]), Thread.currentThread().getContextClassLoader()));
            //now clean up package and write the manifest
            String newArtifact = "com.hurence.logisland.repackaged:" + parts[1] + ":" + parts[2];
            LogislandRepackager.execute(destFile.getAbsolutePath(), "BOOT-INF/lib-provided", parts[2],
                    newArtifact, "Logisland Component for " + artifact, "Logisland Component for " + artifact,
                    new String[] { "org.apache.kafka.*" }, new String[0],
                    "org.apache.kafka.connect.connector.Connector");
        }
        System.out.println("Install done!");
    } catch (Exception e) {
        System.err.println("Unable to install artifact " + artifact);
        e.printStackTrace();
        System.exit(-1);
    }

}