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:io.github.retz.mesosc.MesosHTTPFetcher.java

public static Optional<String> sandboxUri(String t, String master, String slaveId, String frameworkId,
        String executorId, String containerId) {
    Optional<String> slaveAddr = fetchSlaveAddr(master, slaveId); // get master:5050/slaves with slaves/pid, cut with '@'
    LOG.debug("Agent address of executor {}: {}", executorId, slaveAddr);

    if (!slaveAddr.isPresent()) {
        return Optional.empty();
    }/* w w  w .  ja va2s.  c o m*/

    Optional<String> dir = fetchDirectory(slaveAddr.get(), frameworkId, executorId, containerId);
    if (!dir.isPresent()) {
        return Optional.empty();
    }

    try {
        return Optional
                .of(String.format("http://%s/files/%s?path=%s", slaveAddr.get(), t, URLEncoder.encode(dir.get(), //builder.toString(),
                        UTF_8.toString())));
    } catch (UnsupportedEncodingException e) {
        LOG.error(e.toString(), e);
        return Optional.empty();
    }
}

From source file:com.ikanow.aleph2.aleph2_rest_utils.RestCrudFunctions.java

private static <T> Response handleUpdateRequest(final Optional<String> json, final ICrudService<T> crud_service,
        final Class<T> clazz)
        throws JsonParseException, JsonMappingException, IOException, InterruptedException, ExecutionException {
    //get id or a query object that was posted
    if (json.isPresent()) {
        _logger.debug("input: " + json.get());
        final Tuple2<QueryComponent<T>, UpdateComponent<T>> q_u = RestUtils
                .convertStringToUpdateComponent(json.get(), clazz);
        boolean upsert = false; //TODO get from url params
        boolean before_updated = false; //TODO get from url params
        return Response
                .ok(RestUtils//w  ww.  j  a  v a  2 s.  c  om
                        .convertObjectToJson(crud_service
                                .updateAndReturnObjectBySpec(q_u._1, Optional.of(upsert), q_u._2,
                                        Optional.of(before_updated), Collections.emptyList(), false)
                                .get().get())
                        .toString())
                .build();
    } else {
        return Response.status(Status.BAD_REQUEST).entity("PUT requires json in the body").build();
    }
}

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());//from  www  .  j  a va2  s .co m
    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:com.ikanow.aleph2.aleph2_rest_utils.RestCrudFunctions.java

private static <T> Response handleQueryRequest(final Optional<String> query_json,
        final Optional<String> query_id, final ICrudService<T> crud_service, final Class<T> clazz,
        Optional<Long> limit) {
    //get id or a query object that was posted
    //TODO switch to query_id.map().orElse() ... just making a quick swap for the moment
    if (query_id.isPresent()) {
        //ID query
        try {//from   w w  w.ja va  2s.  c  o m
            final String id = query_id.get();
            _logger.debug("id: " + id);
            return Response.ok(RestUtils.convertObjectToJson(crud_service.getObjectById(id).get()).toString())
                    .build();
        } catch (JsonProcessingException | InterruptedException | ExecutionException e) {
            return Response.status(Status.BAD_REQUEST)
                    .entity(ErrorUtils.getLongForm("Error converting input stream to string: {0}", e)).build();
        }
    } else if (query_json.isPresent()) {
        //Body Query
        try {
            final String json = query_json.get();
            _logger.debug("query: " + json);
            final QueryComponent<T> query = RestUtils.convertStringToQueryComponent(json, clazz, limit);
            return Response
                    .ok(RestUtils.convertCursorToJson(crud_service.getObjectsBySpec(query).get()).toString())
                    .build();
        } catch (Exception e) {
            return Response.status(Status.BAD_REQUEST)
                    .entity(ErrorUtils.getLongForm("Error converting input stream to string: {0}", e)).build();
        }
    } else {
        //empty query, does a getall using limit (or 10)
        try {
            _logger.debug("empty query, get all");
            final SingleQueryComponent<T> query = JsonNode.class.isAssignableFrom(clazz)
                    ? (SingleQueryComponent<T>) CrudUtils.allOf()
                    : CrudUtils.allOf(clazz);
            final Cursor<T> cursor = crud_service.getObjectsBySpec(query.limit(limit.orElse(10L))).get();
            return Response.ok(RestUtils.convertCursorToJson(cursor).toString()).build();
        } catch (JsonProcessingException | InterruptedException | ExecutionException e) {
            return Response.status(Status.BAD_REQUEST)
                    .entity(ErrorUtils.getLongForm("Error converting input stream to string: {0}", e)).build();
        }
    }
}

From source file:com.asakusafw.workflow.executor.TaskExecutors.java

/**
 * Returns the batch application installation base path.
 * @param environmentVariables the environment variables
 * @return the batch application installation base path
 *///  w w  w. ja  v  a 2  s  .  com
public static Optional<Path> findApplicationHome(Map<String, String> environmentVariables) {
    Optional<Path> batchapps = Optional.ofNullable(environmentVariables.get(ENV_BATCHAPPS_PATH))
            .map(Paths::get);
    if (batchapps.isPresent()) {
        return batchapps;
    }
    return findFrameworkHome(environmentVariables).map(it -> it.resolve(DEFAULT_BATCHAPPS_PATH));
}

From source file:com.kantenkugel.discordbot.commands.sections.ConfigCommand.java

private static void config(MessageEvent event, ServerConfig cfg, String[] args) {
    if (args.length == 1) {
        reply(event, cfg,/*from w  w w .ja va2 s.c om*/
                "Available subcommands: prefix, restrictTexts, leave, admins, mods, modules, allowEveryone\nTo get more details, run "
                        + cfg.getPrefix() + args[0] + " SUBCOMMAND");
    } else if (args.length > 1) {
        String key = null;
        if (args.length > 2) {
            key = args[2].toLowerCase();
        }
        switch (args[1].toLowerCase()) {
        case "prefix":
            if (args.length == 2) {
                reply(event, cfg,
                        "This command modifies the prefix used to call commands of this bot."
                                + "\nCurrent Prefix: `" + cfg.getPrefix() + "`\nTo change, call "
                                + cfg.getPrefix() + args[0] + " " + args[1] + " PREFIX");
            } else {
                String prefix = MessageUtil.getArgs(event, cfg, 3)[2].toLowerCase();
                cfg.setPrefix(prefix);
                reply(event, cfg, "Prefix changed to `" + prefix + '`');
            }
            break;
        case "restricttexts":
            if (args.length == 2) {
                reply(event, cfg, "This command changes the behavior of text-commands."
                        + "\nIf restrictTexts is set to true, only mods can call the text-commands"
                        + "\nIf set to false, everyone can (default)" + "\nrestrictTexts is currently set to: "
                        + cfg.isRestrictTexts() + "\nTo change, call " + cfg.getPrefix() + args[0] + " "
                        + args[1] + " true/false");
            } else {
                cfg.setRestrictTexts(Boolean.parseBoolean(args[2]));
                reply(event, cfg, "restrictTexts changed to " + cfg.isRestrictTexts());
            }
            break;
        case "alloweveryone":
            if (args.length == 2) {
                reply(event, cfg,
                        MessageUtil.strip("This config changes if the bot can ping @everyone in this guild "
                                + "(this affects primarily text-responses created by `addcom` and responses from the responder module)."
                                + "\nIf allowEveryone is set to true, this bot can do @everyone."
                                + "\nIf set to false, @everyone will always get escaped."
                                + "\nallowEveryone is currently set to: " + cfg.isAllowEveryone()
                                + "\nTo change, call " + cfg.getPrefix() + args[0] + " " + args[1]
                                + " true/false"));
            } else {
                cfg.setAllowEveryone(Boolean.parseBoolean(args[2]));
                reply(event, cfg, "allowEveryone changed to " + cfg.isAllowEveryone());
            }
            break;
        case "leave":
            if (args.length == 2) {
                reply(event, cfg, "This will make the bot leave this server!" + "\nTo leave, call "
                        + cfg.getPrefix() + args[0] + " " + args[1] + " YES");
            } else if (args[2].equals("YES")) {
                event.getGuild().getManager().leave();
            }
            break;
        case "admins":
            if (args.length < 4) {
                reply(event, cfg, "This will add/remove Users and/or Roles to the admin-set"
                        + "\nAdmins have access to everything mods can, + access to the clear command (may change)"
                        + "\nUsage: " + cfg.getPrefix() + args[0] + " " + args[1]
                        + " addUser/removeUser @MENTION" + "\nOr: " + cfg.getPrefix() + args[0] + " " + args[1]
                        + " addRole/removeRole ROLENAME");
                reply(event, cfg,
                        MessageUtil
                                .strip("Current Admins:\n\tUsers: "
                                        + (cfg.getAdmins().size() == 0 ? "None"
                                                : cfg.getAdmins().stream().map(User::getUsername)
                                                        .reduce((s1, s2) -> s1 + ", " + s2).get())
                                        + "\n\tRoles: "
                                        + (cfg.getAdminRoles().size() == 0 ? "None"
                                                : MessageUtil
                                                        .strip(cfg.getAdminRoles().stream().map(Role::getName)
                                                                .reduce((s1, s2) -> s1 + ", " + s2).get()))));
            } else {
                switch (key) {
                case "adduser":
                    event.getMessage().getMentionedUsers().forEach(cfg::addAdmin);
                    reply(event, cfg, "User(s) added as admin(s)");
                    break;
                case "removeuser":
                    event.getMessage().getMentionedUsers().forEach(cfg::removeAdmin);
                    reply(event, cfg, "User(s) removed from admin(s)");
                    break;
                case "addrole":
                    String name = StringUtils.join(args, ' ', 3, args.length);
                    Optional<Role> any = event.getGuild().getRoles().stream()
                            .filter(r -> r.getName().equalsIgnoreCase(name)).findAny();
                    if (any.isPresent()) {
                        cfg.addAdminRole(any.get());
                        reply(event, cfg,
                                MessageUtil.strip("Role " + any.get().getName() + " added as admin role"));
                    } else {
                        reply(event, cfg, "No role matching given name found");
                    }
                    break;
                case "removerole":
                    String name2 = StringUtils.join(args, ' ', 3, args.length);
                    Optional<Role> anyremove = event.getGuild().getRoles().stream()
                            .filter(r -> r.getName().equalsIgnoreCase(name2)).findAny();
                    if (anyremove.isPresent()) {
                        cfg.removeAdminRole(anyremove.get());
                        reply(event, cfg, MessageUtil
                                .strip("Role " + anyremove.get().getName() + " removed from admin roles"));
                    } else {
                        reply(event, cfg, "No role matching given name found");
                    }
                    break;
                default:
                    reply(event, cfg, "Invalid syntax");
                }
            }
            break;
        case "mods":
            if (args.length < 4) {
                reply(event, cfg, "This will add/remove Users and/or Roles to the mods-set"
                        + "\nMods have access to adding, removing and editing text-commands, and also calling them, when they were locked via the restrictTexts config"
                        + "\nUsage: " + cfg.getPrefix() + args[0] + " " + args[1]
                        + " addUser/removeUser @MENTION" + "\nOr: " + cfg.getPrefix() + args[0] + " " + args[1]
                        + " addRole/removeRole ROLENAME");
                reply(event, cfg,
                        MessageUtil
                                .strip("Current Mods:\n\tUsers: "
                                        + (cfg.getMods().size() == 0 ? "None"
                                                : cfg.getMods().stream().map(User::getUsername)
                                                        .reduce((s1, s2) -> s1 + ", " + s2).get())
                                        + "\n\tRoles: "
                                        + (cfg.getModRoles().size() == 0 ? "None"
                                                : MessageUtil
                                                        .strip(cfg.getModRoles().stream().map(Role::getName)
                                                                .reduce((s1, s2) -> s1 + ", " + s2).get()))));
            } else {
                switch (key) {
                case "adduser":
                    event.getMessage().getMentionedUsers().forEach(cfg::addMod);
                    reply(event, cfg, "User(s) added as mod(s)");
                    break;
                case "removeuser":
                    event.getMessage().getMentionedUsers().forEach(cfg::removeMod);
                    reply(event, cfg, "User(s) removed from mod(s)");
                    break;
                case "addrole":
                    String name = StringUtils.join(args, ' ', 3, args.length);
                    Optional<Role> any = event.getGuild().getRoles().stream()
                            .filter(r -> r.getName().equalsIgnoreCase(name)).findAny();
                    if (any.isPresent()) {
                        cfg.addModRole(any.get());
                        reply(event, cfg,
                                MessageUtil.strip("Role " + any.get().getName() + " added as mod role"));
                    } else {
                        reply(event, cfg, "No role matching given name found");
                    }
                    break;
                case "removerole":
                    String name2 = StringUtils.join(args, ' ', 3, args.length);
                    Optional<Role> anyremove = event.getGuild().getRoles().stream()
                            .filter(r -> r.getName().equalsIgnoreCase(name2)).findAny();
                    if (anyremove.isPresent()) {
                        cfg.removeModRole(anyremove.get());
                        reply(event, cfg, MessageUtil
                                .strip("Role " + anyremove.get().getName() + " removed from mod roles"));
                    } else {
                        reply(event, cfg, "No role matching given name found");
                    }
                    break;
                default:
                    reply(event, cfg, "Invalid syntax");
                }
            }
            break;
        case "modules":
            if (args.length < 4) {
                reply(event, cfg,
                        "This will add/remove/configure Modules on this Guild" + "\nUsage: " + cfg.getPrefix()
                                + args[0] + " " + args[1] + " enable/disable MODULE" + "\nOr: "
                                + cfg.getPrefix() + args[0] + " " + args[1] + " configure MODULE\n");
                reply(event, cfg,
                        "Currently enabled Modules:\n\t"
                                + (cfg.getModules().size() == 0
                                        ? "None"
                                        : cfg.getModules().keySet().stream().reduce((s1, s2) -> s1 + ", " + s2)
                                                .get())
                                + "\nAvailable Modules:\n\t"
                                + (Module.getModuleList().size() == 0 ? "None"
                                        : Module.getModuleList().stream().reduce((s1, s2) -> s1 + ", " + s2)
                                                .get()));
            } else {
                String val = null;
                if (args.length > 3) {
                    val = args[3].toLowerCase();
                }
                switch (key) {
                case "enable":
                    if (Module.getModules().containsKey(val)) {
                        if (!cfg.getModules().containsKey(val)) {
                            cfg.addModule(val);
                            reply(event, cfg, "Module enabled");
                        } else {
                            reply(event, cfg, "Module was already enabled!");
                        }
                    } else {
                        reply(event, cfg, "Module does not exist");
                    }
                    break;
                case "disable":
                    if (Module.getModules().containsKey(val)) {
                        if (cfg.getModules().containsKey(val)) {
                            cfg.removeModule(val);
                            reply(event, cfg, "Module disabled");
                        } else {
                            reply(event, cfg, "Module was not enabled!");
                        }
                    } else {
                        reply(event, cfg, "Module does not exist");
                    }
                    break;
                case "configure":
                    if (Module.getModules().containsKey(val)) {
                        if (cfg.getModules().containsKey(val)) {
                            String cfgString = args.length > 4 ? StringUtils.join(args, ' ', 4, args.length)
                                    : null;
                            cfg.getModules().get(val).configure(cfgString, event, cfg);
                        } else {
                            reply(event, cfg, "Module was not enabled!");
                        }
                    } else {
                        reply(event, cfg, "Module does not exist");
                    }
                    break;
                default:
                    reply(event, cfg, "Invalid syntax");
                }
            }
            break;
        default:
            reply(event, cfg, "Invalid syntax");
        }
    }
}

From source file:com.github.steveash.guavate.Guavate.java

/**
 * Converts an optional to a stream with zero or one elements.
 * @param <T> the type of optional element
 * @param optional the optional/* ww  w.j  ava2s  . c om*/
 * @return a stream containing a single value if the optional has a value, else a stream with no values.
 */
public static <T> Stream<T> stream(Optional<T> optional) {
    return optional.isPresent() ? Stream.of(optional.get()) : Stream.empty();
}

From source file:com.android.tools.idea.templates.RepositoryUrlManager.java

private static String findExistingExplicitVersion(@NotNull Collection<GradleCoordinate> dependencies) {
    Optional<GradleCoordinate> highest = dependencies.stream()
            .filter(coordinate -> ImportModule.SUPPORT_GROUP_ID.equals(coordinate.getGroupId()))
            .max(COMPARE_PLUS_LOWER);//from  w  w  w . j a v  a 2s . c  o  m
    if (!highest.isPresent()) {
        return null;
    }
    String version = highest.get().getRevision();
    if (version.endsWith("+")) {
        return version.length() > 1 ? version.substring(0, version.length() - 1) : null;
    }
    return version;
}

From source file:com.msd.gin.halyard.tools.HalyardExport.java

/**
 * Export function is called for the export execution with given arguments.
 * @param conf Hadoop Configuration instance
 * @param log StatusLog notification service implementation for back-calls
 * @param source String source HTable name
 * @param query String SPARQL Graph query
 * @param targetUrl String URL of the target system (+folder or schema, +table or file name)
 * @param driverClass String JDBC Driver class name (for JDBC export only)
 * @param driverClasspath Array of URLs with JDBC Driver classpath (for JDB export only)
 * @param jdbcProperties Arrays of String JDBC connection properties (for JDB export only)
 * @param trimTable boolean option to trim target JDBC table before export (for JDB export only)
 * @throws ExportException in case of an export problem
 *///  w  ww.j a v a2 s. c  o m
public static void export(Configuration conf, StatusLog log, String source, String query, String targetUrl,
        String driverClass, URL[] driverClasspath, String[] jdbcProperties, boolean trimTable)
        throws ExportException {
    try {
        QueryResultWriter writer = null;
        if (targetUrl.startsWith("file:") || targetUrl.startsWith("hdfs:")) {
            OutputStream out = FileSystem.get(URI.create(targetUrl), conf).create(new Path(targetUrl));
            try {
                if (targetUrl.endsWith(".bz2")) {
                    out = new CompressorStreamFactory()
                            .createCompressorOutputStream(CompressorStreamFactory.BZIP2, out);
                    targetUrl = targetUrl.substring(0, targetUrl.length() - 4);
                } else if (targetUrl.endsWith(".gz")) {
                    out = new CompressorStreamFactory()
                            .createCompressorOutputStream(CompressorStreamFactory.GZIP, out);
                    targetUrl = targetUrl.substring(0, targetUrl.length() - 3);
                }
            } catch (CompressorException e) {
                IOUtils.closeQuietly(out);
                throw new ExportException(e);
            }
            if (targetUrl.endsWith(".csv")) {
                writer = new CSVResultWriter(log, out);
            } else {
                Optional<RDFFormat> form = Rio.getWriterFormatForFileName(targetUrl);
                if (!form.isPresent())
                    throw new ExportException("Unsupported target file format extension: " + targetUrl);
                writer = new RIOResultWriter(log, form.get(), out);
            }
        } else if (targetUrl.startsWith("jdbc:")) {
            int i = targetUrl.lastIndexOf('/');
            if (i < 0)
                throw new ExportException("Taret URL does not end with /<table_name>");
            if (driverClass == null)
                throw new ExportException(
                        "Missing mandatory JDBC driver class name argument -c <driver_class>");
            writer = new JDBCResultWriter(log, targetUrl.substring(0, i), targetUrl.substring(i + 1),
                    jdbcProperties, driverClass, driverClasspath, trimTable);
        } else {
            throw new ExportException("Unsupported target URL protocol " + targetUrl);
        }
        new HalyardExport(source, query, writer, log).run(conf);
    } catch (IOException e) {
        throw new ExportException(e);
    }
}

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

public static void rescindGroupInvite(ItemStack stack) {
    Optional<String> zone = getZone(stack);
    for (Player aPlayer : Sponge.getServer().getOnlinePlayers()) {
        ItemStack[] itemStacks = tf(aPlayer).inventory.mainInventory;
        for (int i = 0; i < itemStacks.length; ++i) {
            if (hasSameZoneID(stack, itemStacks[i]) && isZoneSlaveItem(stack)) {
                if (!zone.isPresent()) {
                    aPlayer.sendMessage(
                            Text.of(TextColors.RED, "A group you were invited to has been destroyed."));
                } else {
                    aPlayer.sendMessage(Text.of(TextColors.RED,
                            "A " + zone.get() + " group you were invited to has been destroyed."));
                }/*from   w  ww.j  a  v  a 2  s  . c o m*/
                itemStacks[i] = null;
            }
        }
        tf(aPlayer).inventoryContainer.detectAndSendChanges();
    }
}