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.lxgaming.teleportbow.managers.CommandManager.java

public static boolean registerCommand(AbstractCommand parentCommand,
        Class<? extends AbstractCommand> commandClass) {
    if (parentCommand.getClass() == commandClass) {
        TeleportBow.getInstance().getLogger().warn("{} attempted to register itself",
                parentCommand.getClass().getSimpleName());
        return false;
    }/* www .  jav  a  2s. c  o m*/

    if (getCommandClasses().contains(commandClass)) {
        TeleportBow.getInstance().getLogger().warn("{} has already been registered",
                commandClass.getSimpleName());
        return false;
    }

    getCommandClasses().add(commandClass);
    Optional<AbstractCommand> command = Toolbox.newInstance(commandClass);
    if (!command.isPresent()) {
        TeleportBow.getInstance().getLogger().error("{} failed to initialize", commandClass.getSimpleName());
        return false;
    }

    parentCommand.getChildren().add(command.get());
    TeleportBow.getInstance().getLogger().debug("{} registered for {}", commandClass.getSimpleName(),
            parentCommand.getClass().getSimpleName());
    return true;
}

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

private static Pair<Integer, Optional<IndexRecord>> binarySearchIndex(final int lower, final int upper,
        final long timestamp, final byte[] indexTable) {
    if (upper < lower || indexTable.length == 0) {
        return new ImmutablePair<>(0, Optional.empty());
    }//www . j av  a  2 s.c  om

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

    final IndexRecord record = IndexRecord.readRecord(indexTable, offset).get();

    final Optional<IndexRecord> next = IndexRecord.fetchNext(indexTable, offset);

    if (record.getEventTime() <= timestamp) {
        if (!next.isPresent() || (next.get().getEventTime() > timestamp)) {
            return new ImmutablePair<>(offset, Optional.of(record));
        } else {
            return binarySearchIndex((lower + upper) / 2 + 1, upper, timestamp, indexTable);
        }
    } else {
        return binarySearchIndex(lower, (lower + upper) / 2 - 1, timestamp, indexTable);
    }
}

From source file:com.ikanow.aleph2.data_model.utils.PropertiesUtils.java

/**
 * Reads in the config file and sends back a list of a config data service entries based on the
 * given configPrefix.  This is used by the ModuleUtils to get the requested modules to load.
 * /*from w w w  . j  av  a 2  s.c  o m*/
 * @param config
 * @param configPrefix
 * @return
 * @throws IOException 
 * @throws JsonMappingException 
 * @throws JsonParseException 
 */
public static List<ConfigDataServiceEntry> getDataServiceProperties(final Config config,
        final String configPrefix) {
    Optional<ConfigObject> sub_config = getSubConfigObject(config, configPrefix);
    if (sub_config.isPresent()) {
        final ConfigObject dataServiceConfig = sub_config.get(); //config.getObject(configPrefix);         
        List<ConfigDataServiceEntry> toReturn = dataServiceConfig.entrySet().stream()
                .map(entry -> new ConfigDataServiceEntry(entry.getKey(),
                        Optional.ofNullable(PropertiesUtils.getConfigValue(config,
                                configPrefix + "." + entry.getKey() + ".interface", null)),
                        PropertiesUtils.getConfigValue(config, configPrefix + "." + entry.getKey() + ".service",
                                null),
                        PropertiesUtils.getConfigValue(config, configPrefix + "." + entry.getKey() + ".default",
                                false)))
                .collect(Collectors.toList());
        return toReturn;
    } else {
        return Collections.emptyList();
    }
}

From source file:io.github.retz.web.AppRequestHandler.java

static String getApp(Request req, Response res) throws JsonProcessingException {
    LOG.debug(LoadAppRequest.resourcePattern());
    Optional<AuthHeader> authHeaderValue = getAuthInfo(req);

    String appname = req.params(":name");
    LOG.debug("deleting app {} requested by {}", appname, authHeaderValue.get().key());
    Optional<Application> maybeApp = Applications.get(appname);
    res.type("application/json");
    if (maybeApp.isPresent()) {
        // Compare application owner and requester
        validateOwner(req, maybeApp.get());

        res.status(200);//from  w  w w  . ja  v a2  s  .c o  m
        GetAppResponse getAppResponse = new GetAppResponse(maybeApp.get());
        getAppResponse.ok();
        String r = MAPPER.writeValueAsString(getAppResponse);
        LOG.info(r);
        return r;

    } else {
        ErrorResponse response = new ErrorResponse("No such application: " + appname);
        res.status(404);
        return MAPPER.writeValueAsString(response);
    }
}

From source file:com.netflix.spinnaker.halyard.config.model.v1.security.AuthnMethod.java

public static Class<? extends AuthnMethod> translateAuthnMethodName(String authnMethodName) {
    Optional<? extends Class<?>> res = Arrays.stream(Authn.class.getDeclaredFields())
            .filter(f -> f.getName().equals(authnMethodName)).map(Field::getType).findFirst();

    if (res.isPresent()) {
        return (Class<? extends AuthnMethod>) res.get();
    } else {/*  w w w  . j  av a  2s. c  o m*/
        throw new IllegalArgumentException(
                "No authn method with name \"" + authnMethodName + "\" handled by halyard");
    }
}

From source file:io.github.lxgaming.teleportbow.util.Toolbox.java

public static boolean isValidBow(ItemStack itemStack) {
    if (itemStack == null || itemStack.getType() != ItemTypes.BOW) {
        return false;
    }/*from www. ja  va2  s.  c  o m*/

    Optional<List<Enchantment>> enchantments = itemStack.get(Keys.ITEM_ENCHANTMENTS);
    if (!enchantments.isPresent() || enchantments.get().isEmpty()) {
        return false;
    }

    for (Enchantment enchantment : enchantments.get()) {
        if (enchantment.getType() == EnchantmentTypes.INFINITY && enchantment.getLevel() == 10) {
            return true;
        }
    }

    return false;
}

From source file:io.github.lxgaming.teleportbow.managers.CommandManager.java

public static CommandResult process(AbstractCommand abstractCommand, CommandSource commandSource,
        String message) {//from   w w w .ja v a 2s .c om
    Optional<List<String>> arguments = getArguments(message).map(Toolbox::newArrayList);
    if (!arguments.isPresent()) {
        commandSource
                .sendMessage(Text.of(Toolbox.getTextPrefix(), TextColors.RED, "Failed to collect arguments"));
        return CommandResult.empty();
    }

    Optional<AbstractCommand> command = getCommand(abstractCommand, arguments.get());
    if (!command.isPresent()) {
        return CommandResult.empty();
    }

    if (!command.get().testPermission(commandSource)) {
        commandSource.sendMessage(Text.of(Toolbox.getTextPrefix(), TextColors.RED,
                "You do not have permission to execute this command"));
        return CommandResult.empty();
    }

    TeleportBow.getInstance().getLogger().debug("Processing {} for {}",
            command.get().getPrimaryAlias().orElse("Unknown"), commandSource.getName());
    return command.get().execute(commandSource, arguments.get());
}

From source file:io.syndesis.rest.v1.handler.connection.ConnectionActionHandler.java

static boolean shouldEnrichDataShape(final Optional<DataShape> maybeExistingDataShape,
        final Object received) {
    if (maybeExistingDataShape.isPresent() && received != null) {
        final DataShape existingDataShape = maybeExistingDataShape.get();

        return "json-schema".equals(existingDataShape.getKind())
                && existingDataShape.getSpecification() == null;
    }//from w ww  .  j a va 2s . c om

    return false;
}

From source file:com.facebook.buck.testutil.integration.TarInspector.java

private static TarArchiveInputStream getArchiveInputStream(Optional<String> compressorType, Path tar)
        throws IOException, CompressorException {
    BufferedInputStream inputStream = new BufferedInputStream(Files.newInputStream(tar));
    if (compressorType.isPresent()) {
        return new TarArchiveInputStream(
                new CompressorStreamFactory().createCompressorInputStream(compressorType.get(), inputStream));
    }/*  www .  j a va 2  s .  com*/
    return new TarArchiveInputStream(inputStream);
}

From source file:io.github.retz.web.AppRequestHandler.java

static String loadApp(Request req, Response res) throws JsonProcessingException, IOException {
    LOG.debug(LoadAppRequest.resourcePattern());
    Optional<AuthHeader> authHeaderValue = getAuthInfo(req);
    res.type("application/json");

    // TODO: check key from Authorization header matches a key in Application object
    LoadAppRequest loadAppRequest = MAPPER.readValue(req.bodyAsBytes(), LoadAppRequest.class);
    LOG.debug("app (id={}, owner={}), requested by {}", loadAppRequest.application().getAppid(),
            loadAppRequest.application().getOwner(), authHeaderValue.get().key());

    // Compare application owner and requester
    validateOwner(req, loadAppRequest.application());

    Optional<Application> tmp = Applications.get(loadAppRequest.application().getAppid());
    if (tmp.isPresent()) {
        if (!tmp.get().getOwner().equals(loadAppRequest.application().getOwner())) {
            res.status(403);//  w  w  w . ja va  2  s.  c om
            LOG.error("Application {} is already owned by ", loadAppRequest.application().getAppid(),
                    tmp.get().getOwner());
            return MAPPER.writeValueAsString(
                    new ErrorResponse("The application name is already used by other user"));
        }
    }

    if (!(loadAppRequest.application().container() instanceof DockerContainer)) {
        if (loadAppRequest.application().getUser().isPresent()
                && loadAppRequest.application().getUser().get().equals("root")) {
            res.status(400);
            return MAPPER
                    .writeValueAsString(new ErrorResponse("root user is only allowed with Docker container"));
        }
    }

    Application app = loadAppRequest.application();
    LOG.info("Registering application name={} owner={}", app.getAppid(), app.getOwner());
    boolean result = Applications.load(app);

    if (result) {
        res.status(200);
        LoadAppResponse response = new LoadAppResponse();
        response.ok();
        return MAPPER.writeValueAsString(response);
    } else {

        res.status(400);
        return MAPPER.writeValueAsString(new ErrorResponse("cannot load application"));
    }

}