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:io.gravitee.management.service.impl.ApplicationServiceImpl.java

private static ApplicationEntity convert(Application application) {
    ApplicationEntity applicationEntity = new ApplicationEntity();

    applicationEntity.setId(application.getId());
    applicationEntity.setName(application.getName());
    applicationEntity.setDescription(application.getDescription());
    applicationEntity.setType(application.getType());

    applicationEntity.setCreatedAt(application.getCreatedAt());
    applicationEntity.setUpdatedAt(application.getUpdatedAt());

    if (application.getMembers() != null) {
        final Optional<Membership> member = application.getMembers().stream()
                .filter(membership -> MembershipType.PRIMARY_OWNER.equals(membership.getMembershipType()))
                .findFirst();//  ww w  . j a va 2s. co m
        if (member.isPresent()) {
            final User user = member.get().getUser();
            final PrimaryOwnerEntity primaryOwnerEntity = new PrimaryOwnerEntity();
            primaryOwnerEntity.setUsername(user.getUsername());
            primaryOwnerEntity.setLastname(user.getLastname());
            primaryOwnerEntity.setFirstname(user.getFirstname());
            primaryOwnerEntity.setEmail(user.getEmail());
            applicationEntity.setPrimaryOwner(primaryOwnerEntity);
        }
    }

    return applicationEntity;
}

From source file:de.hybris.platform.acceleratorstorefrontcommons.tags.Functions.java

public static boolean isQuoteUserSellerApprover() {
    final UserModel userModel = getQuoteUserIdentificationStrategy(getCurrentRequest()).getCurrentQuoteUser();
    final Optional<QuoteUserType> quoteUserTypeOptional = getQuoteUserTypeIdentificationStrategy(
            getCurrentRequest()).getCurrentQuoteUserType(userModel);
    return quoteUserTypeOptional.isPresent()
            && QuoteUserType.SELLERAPPROVER.equals(quoteUserTypeOptional.get());
}

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();
        }//ww  w . j  a  va  2s  .c om
        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:de.fosd.jdime.Main.java

/**
 * Parses command line arguments and initializes program.
 *
 * @param context//w  ww. ja v a  2 s.co  m
 *         merge context
 * @param args
 *         command line arguments
 * @return true if program should continue
 */
private static boolean parseCommandLineArgs(MergeContext context, String[] args) {
    JDimeConfig config;

    try {
        config = new JDimeConfig(args);
    } catch (ParseException e) {
        System.err.println("Failed to parse the command line arguments " + Arrays.toString(args));
        System.err.println(e.getMessage());
        System.exit(EXIT_FAILURE);
        return false;
    }

    Main.config = config;

    if (args.length == 0 || config.getBoolean(CLI_HELP).orElse(false)) {
        printCLIHelp();
        return false;
    }

    if (config.getBoolean(CLI_VERSION).orElse(false)) {
        Optional<String> commit = config.get(JDIME_COMMIT);

        if (commit.isPresent()) {
            System.out.printf("%s version %s commit %s%n", TOOLNAME, VERSION, commit.get());
        } else {
            System.out.printf("%s version %s%n", TOOLNAME, VERSION);
        }

        return false;
    }

    Optional<String> mode = config.get(CLI_MODE).map(String::toLowerCase);

    if (mode.isPresent() && MODE_LIST.equals(mode.get())) {
        printStrategies();
        return false;
    }

    context.configureFrom(config);
    return true;
}

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  w  w  . j  av  a2s  .  c  o  m
                        .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:lumbermill.internal.influxdb.InfluxDBClient.java

/**
 * Creates  Points based on the event and config
 *//*from  w  w w . j a  v  a2s  . c  o m*/
private static Observable<Point> buildPoint(MapWrap config, StringTemplate measurementTemplate,
        JsonEvent jsonEvent) {

    final MapWrap fieldsConfig = MapWrap.of(config.getObject("fields"));
    final List<String> excludeTags = config.getObject("excludeTags", DEFAULT_EXCLUDED_TAGS);

    // One field is required, otherwise the point will not be created
    boolean addedAtLeastOneField = false;
    Optional<String> measurementOptional = measurementTemplate.format(jsonEvent);
    if (!measurementOptional.isPresent()) {
        LOGGER.debug("Failed to extract measurement using {}, not points will be created",
                measurementTemplate.original());
        return Observable.empty();
    }
    Point.Builder pointBuilder = Point.measurement(measurementOptional.get());

    for (Object entry1 : fieldsConfig.toMap().entrySet()) {
        Map.Entry<String, String> entry = (Map.Entry) entry1;
        StringTemplate fieldName = StringTemplate.compile(entry.getKey());
        String valueField = entry.getValue();

        JsonNode node = jsonEvent.unsafe().get(valueField);
        if (node == null) {
            LOGGER.debug("Failed to extract any field for {}", valueField);
            continue;
        }

        Optional<String> formattedFieldNameOptional = fieldName.format(jsonEvent);
        if (!formattedFieldNameOptional.isPresent()) {
            LOGGER.debug("Failed to extract any field for {}", fieldName.original());
            continue;
        }

        addedAtLeastOneField = true;

        if (node.isNumber()) {
            pointBuilder.addField(formattedFieldNameOptional.get(), node.asDouble());
        } else if (node.isBoolean()) {
            pointBuilder.addField(formattedFieldNameOptional.get(), node.asBoolean());
        } else {
            pointBuilder.addField(formattedFieldNameOptional.get(), node.asText());
        }
    }

    Iterator<String> stringIterator = jsonEvent.unsafe().fieldNames();
    while (stringIterator.hasNext()) {
        String next = stringIterator.next();
        if (!excludeTags.contains(next)) {
            pointBuilder.tag(next, jsonEvent.valueAsString(next));
        }
    }

    Optional<String> timeField = config.exists("time") ? Optional.of(config.asString("time"))
            : Optional.empty();
    TimeUnit precision = config.getObject("precision", TimeUnit.MILLISECONDS);

    // Override @timestamp with a ISO_8601 String or a numerical value
    if (timeField.isPresent() && jsonEvent.has(config.asString("time"))) {

        if (jsonEvent.unsafe().get(timeField.get()).isTextual()) {
            pointBuilder.time(ZonedDateTime
                    .parse(jsonEvent.valueAsString("@timestamp"), DateTimeFormatter.ISO_OFFSET_DATE_TIME)
                    .toInstant().toEpochMilli(), precision);
        } else {
            pointBuilder.time(jsonEvent.asLong(timeField.get()), precision);
        }
    } else {
        // If not overriden, check if timestamp exists and use that
        if (jsonEvent.has("@timestamp")) {
            pointBuilder.time(ZonedDateTime
                    .parse(jsonEvent.valueAsString("@timestamp"), DateTimeFormatter.ISO_OFFSET_DATE_TIME)
                    .toInstant().toEpochMilli(), precision);
        }
    }

    if (!addedAtLeastOneField) {
        LOGGER.debug("Could not create a point since no fields where added");
        return Observable.empty();
    }

    Point point = pointBuilder.build();
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Point to be stored {}", point.toString());
    }
    return Observable.just(point);
}

From source file:io.github.retz.mesosc.MesosHTTPFetcher.java

public static Optional<String> sandboxDownloadUri(String master, String slaveId, String frameworkId,
        String executorId, String containerId, String path) {
    Optional<String> base = sandboxUri("download", master, slaveId, frameworkId, executorId, containerId,
            RETRY_LIMIT);//  w  ww. j  a  v a  2 s. com
    if (base.isPresent()) {
        try {
            String encodedPath = URLEncoder.encode(path, UTF_8.toString());
            return Optional.of(base.get() + encodedPath);
        } catch (UnsupportedEncodingException e) {
            return Optional.empty();
        }
    }
    return Optional.empty();
}

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/*from  ww  w.ja  va2s  . co m*/
 * @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: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();
    }/*from  ww w .j a  va  2s.co 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.kantenkugel.discordbot.commands.sections.ConfigCommand.java

private static void config(MessageEvent event, ServerConfig cfg, String[] args) {
    if (args.length == 1) {
        reply(event, cfg,//from www. j a  v  a2  s . co  m
                "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");
        }
    }
}