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:info.archinnov.achilles.internals.schema.SchemaValidator.java

public static void validateDefaultTTL(AbstractTableMetadata metadata, Optional<Integer> staticTTL,
        Class<?> entityClass) {
    if (staticTTL.isPresent()) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(format("Validating table %s default TTL value", metadata.getName()));
        }//from  w w w  .j  a  va 2  s . c o  m
        final int defaultTimeToLive = metadata.getOptions().getDefaultTimeToLive();
        validateBeanMappingTrue(staticTTL.get().equals(defaultTimeToLive),
                "Default TTL '%s' declared on entity '%s' does not match detected default TTL '%s' in live schema",
                staticTTL.get(), entityClass.getCanonicalName(), defaultTimeToLive);
    }
}

From source file:com.helion3.prism.api.query.QueryBuilder.java

/**
 * Parses a flag argument./*w  w w.  j a  v  a 2  s. c  om*/
 *
 * @param session QuerySession current session.
 * @param query Query query being built.
 * @param parameter String argument which should be a parameter
 * @return Optional<ListenableFuture<?>>
 */
private static Optional<ListenableFuture<?>> parseFlagFromArgument(QuerySession session, Query query,
        String flag) throws ParameterException {
    flag = flag.substring(1);

    // Determine the true alias and value
    Optional<String> optionalValue = Optional.empty();
    if (flag.contains("=")) {
        // Split the parameter: values
        String[] split = flag.split("=");
        flag = split[0];
        if (!split[1].trim().isEmpty()) {
            optionalValue = Optional.of(split[1]);
        }
    }

    // Find a handler
    Optional<FlagHandler> optionalHandler = Prism.getFlagHandler(flag);
    if (!optionalHandler.isPresent()) {
        throw new ParameterException("\"" + flag + "\" is not a valid flag. No handler found.");
    }

    FlagHandler handler = optionalHandler.get();

    // Allows this command source?
    if (!handler.acceptsSource(session.getCommandSource().get())) {
        throw new ParameterException("This command source may not use the \"" + flag + "\" flag.");
    }

    // Validate value
    if (optionalValue.isPresent() && !handler.acceptsValue(optionalValue.get())) {
        throw new ParameterException(
                "Invalid value \"" + optionalValue.get() + "\" for parameter \"" + flag + "\".");
    }

    return handler.process(session, flag, optionalValue, query);
}

From source file:cz.lbenda.rcp.DialogHelper.java

/** Open dialog with chooser when user can choose single option
 * @param question question which is show to user
 * @param items list of items which user can choose
 * @param <T> type of item//from ww  w  . j  a  v  a 2s.co  m
 * @return null if user click on cancel or don't choose anything, elsewhere choosed item */
@SuppressWarnings("unchecked")
public static <T> T chooseSingOption(String question, T... items) {
    if (items.length == 0) {
        return null;
    }
    Dialog<T> dialog = new Dialog<>();
    dialog.setResizable(false);
    dialog.setTitle(chooseSingleOption_title);
    dialog.setHeaderText(question);

    ComboBox<T> comboBox = new ComboBox<>();
    comboBox.getItems().addAll(items);
    dialog.getDialogPane().setContent(comboBox);

    ButtonType btCancel = ButtonType.CANCEL;
    ButtonType btOk = ButtonType.OK;
    dialog.getDialogPane().getButtonTypes().addAll(btCancel, btOk);

    Optional<T> result = dialog.showAndWait();
    if (result.isPresent()) {
        if (btCancel == result.get()) {
            return null;
        }
        if (btOk == result.get()) {
            return comboBox.getSelectionModel().getSelectedItem();
        }
    } else {
        return null;
    }
    return result.get();
}

From source file:info.archinnov.achilles.internals.runtime.BeanValueExtractor.java

public static <T> BoundValuesWrapper extractAllValues(T instance, AbstractEntityProperty<T> entityProperty,
        Options options) {/*from  w w  w . j av a 2s  .c om*/
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(format("Extract values from entity %s of type %s", instance,
                entityProperty.entityClass.getCanonicalName()));
    }

    final List<BoundValueInfo> boundValues = new ArrayList<>();
    final List<BoundValueInfo> partitionKeys = entityProperty.partitionKeys.stream().map(x -> {
        final AbstractProperty x1 = (AbstractProperty) x;
        final BiConsumer<Object, SettableData> lambda = x1::encodeToSettable;
        return BoundValueInfo.of(lambda, x.getFieldValue(instance), x.encodeField(instance));
    }).collect(toList());

    boundValues.addAll(partitionKeys);

    boundValues.addAll(entityProperty.staticColumns.stream().map(x -> {
        final AbstractProperty x1 = (AbstractProperty) x;
        return BoundValueInfo.of(x1::encodeToSettable, x.getFieldValue(instance), x.encodeField(instance));
    }).collect(toList()));

    boundValues.addAll(entityProperty.clusteringColumns.stream().map(x -> {
        final AbstractProperty x1 = (AbstractProperty) x;
        return BoundValueInfo.of(x1::encodeToSettable, x.getFieldValue(instance), x.encodeField(instance));
    }).collect(toList()));

    boundValues.addAll(entityProperty.normalColumns.stream().map(x -> {
        final AbstractProperty x1 = (AbstractProperty) x;
        return BoundValueInfo.of(x1::encodeToSettable, x.getFieldValue(instance), x.encodeField(instance));
    }).collect(toList()));

    boundValues.addAll(entityProperty.counterColumns.stream().map(x -> {
        final AbstractProperty x1 = (AbstractProperty) x;
        return BoundValueInfo.of(x1::encodeToSettable, x.getFieldValue(instance), x.encodeField(instance));
    }).collect(toList()));

    final Optional<Integer> ttl = OverridingOptional.from(options.getTimeToLive())
            .andThen(entityProperty.staticTTL).getOptional();

    boundValues.add(ttl.isPresent()
            ? BoundValueInfo.of(
                    (Object value, SettableData settableData) -> settableData.setInt("ttl", ttl.get()),
                    ttl.get(), ttl.get())
            : BoundValueInfo.of((Object value, SettableData settableData) -> settableData.setInt("ttl", 0), 0,
                    0));

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(format("Extracted encoded bound values : %s", boundValues));
    }
    return new BoundValuesWrapper(entityProperty, boundValues);
}

From source file:com.taobao.android.builder.dependency.parser.DependencyLocationManager.java

private static boolean shouldUseBuildCache(Project project, MavenCoordinates mavenCoordinates, File bundle,
        Optional<FileCache> buildCache) {
    if (!PrepareLibraryTask.shouldUseBuildCache(buildCache.isPresent(), mavenCoordinates)) {
        return false;
    }//from  ww  w.j  av a2s .  c o m

    if (!bundle.exists()) {
        return false;
    }

    if (StringUtils.isEmpty(mavenCoordinates.getGroupId())) {
        return true;
    }

    return !isProjectLibrary(project, bundle);
}

From source file:alfio.util.Validator.java

private static boolean containsAllRequiredTranslations(EventModification eventModification,
        List<EventModification.AdditionalServiceText> descriptions) {
    Optional<EventModification> optional = Optional.ofNullable(eventModification);
    return !optional.isPresent() || optional.map(e -> ContentLanguage.findAllFor(e.getLocales()))
            .filter(l -> l.stream().allMatch(
                    l1 -> descriptions.stream().anyMatch(d -> d.getLocale().equals(l1.getLanguage()))))
            .isPresent();/*from ww w .  ja v  a 2  s.co m*/
}

From source file:io.github.retz.scheduler.Launcher.java

public static int run(String... argv) {

    Configuration conf;/*from  www .j a va2  s.c  om*/
    try {
        conf = parseConfiguration(argv);
        if (conf.fileConfig.isTLS()) {
            LOG.warn("Make sure a valid certificate is being used or RetzExecutor may not work.");
        }
        Database.getInstance().init(conf.getServerConfig());
        if (conf.getServerConfig().getGc()) {
            GarbageJobCollector.start(conf.getServerConfig().getGcLeeway(),
                    conf.getServerConfig().getGcInterval());
        } else {
            LOG.info("Automatic garbage collection is turned off; use retz-admin gc to collect old jobs");
        }
    } catch (ParseException e) {
        LOG.error(e.toString());
        return -1;
    } catch (URISyntaxException e) {
        LOG.error(e.toString());
        return -1;
    } catch (SQLException e) {
        LOG.error(e.toString());
        return -1;
    } catch (IOException e) {
        LOG.error(e.toString());
        return -1;
    }

    Optional<JmxServer> maybeJmxServer = AdminConsole.startJmxServer(conf.getServerConfig());
    if (!maybeJmxServer.isPresent()) {
        LOG.error("Failed to start JMX Server");
        return -1;
    }
    JmxServer jmxServer = maybeJmxServer.get();

    Protos.FrameworkInfo fw = buildFrameworkInfo(conf);

    // Retz must do all recovery process before launching scheduler;
    // This is because running scheduler changes state of any jobs if it
    // has successfully connected to Mesos master.
    // By hitting HTTP endpoints and comparing with database job states,
    // Retz can decide whether to re-run it or just finish it.
    // BTW after connecting to Mesos it looks like re-sending unacked messages.
    maybeRequeueRunningJobs(conf.getMesosMaster(), fw.getId().getValue(), Database.getInstance().getRunning());

    RetzScheduler scheduler;
    try {
        scheduler = new RetzScheduler(conf, fw);
    } catch (Throwable t) {
        LOG.error("Cannot initialize scheduler", t);
        return -1;
    }
    SchedulerDriver driver = SchedulerDriverFactory.create(scheduler, conf, fw);

    Protos.Status status = driver.start();

    if (status != Protos.Status.DRIVER_RUNNING) {
        LOG.error("Cannot start Mesos scheduler: {}", status.name());
        System.exit(-1);
        //} else if (status == Protos.Status.DRIVER_ABORTED) {
        //} else if (status == Protos.Status.DRIVER_NOT_STARTED) {
        //} else if (status == Protos.Status.DRIVER_STOPPED) {
    }

    LOG.info("Mesos scheduler started: {}", status.name());

    // Start web server
    WebConsole.start(conf.fileConfig);
    WebConsole.set(scheduler, driver);
    LOG.info("Web console has started with port {}", conf.getPort());

    java.lang.Runtime.getRuntime().addShutdownHook(new ShutdownThread(driver));

    // Stop them all, usually don't come here
    // Wait for Mesos framework stop
    status = driver.join();
    LOG.info("{} has been stopped: {}", RetzScheduler.FRAMEWORK_NAME, status.name());

    WebConsole.stop(); // Stop web server
    GarbageJobCollector.stop();
    Database.getInstance().stop();
    jmxServer.stop();

    return (status == Protos.Status.DRIVER_STOPPED ? 0 : 255);
}

From source file:com.helion3.prism.api.query.QueryBuilder.java

/**
 * Parses a parameter argument./*from  www.  j  av a2s . co m*/
 *
 * @param session QuerySession current session.
 * @param query Query query being built.
 * @param parameter String argument which should be a parameter
 * @return Optional<ListenableFuture<?>>
 * @throws ParameterException
 */
private static Optional<ListenableFuture<?>> parseParameterFromArgument(QuerySession session, Query query,
        Pair<String, String> parameter) throws ParameterException {
    // Simple validation
    if (parameter.getKey().length() <= 0 || parameter.getValue().length() <= 0) {
        throw new ParameterException("Invalid empty value for parameter \"" + parameter.getKey() + "\".");
    }

    // Find a handler
    Optional<ParameterHandler> optionalHandler = Prism.getParameterHandler(parameter.getKey());
    if (!optionalHandler.isPresent()) {
        throw new ParameterException(
                "\"" + parameter.getKey() + "\" is not a valid parameter. No handler found.");
    }

    ParameterHandler handler = optionalHandler.get();

    // Allows this command source?
    if (!handler.acceptsSource(session.getCommandSource().get())) {
        throw new ParameterException(
                "This command source may not use the \"" + parameter.getKey() + "\" parameter.");
    }

    // Validate value
    if (!handler.acceptsValue(parameter.getValue())) {
        throw new ParameterException(
                "Invalid value \"" + parameter.getValue() + "\" for parameter \"" + parameter.getKey() + "\".");
    }

    return handler.process(session, parameter.getKey(), parameter.getValue(), query);
}

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

public static List<UDFSignature> parseFunctionRegistryAndValidateTypes(AptUtils aptUtils, TypeElement elm) {
    final List<ExecutableElement> methods = ElementFilter.methodsIn(elm.getEnclosedElements());
    final Optional<String> keyspace = AnnotationTree.findKeyspaceForFunctionRegistry(aptUtils, elm);

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

    //Not allow to declare function in system keyspaces
    if (keyspace.isPresent()) {
        final String keyspaceName = keyspace.get();
        aptUtils.validateFalse(// ww w. j a v a2s.  c o m
                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, sourceClass);
    }

    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 List<TypeName> parametersType = method.getParameters().stream().map(VariableElement::asType)
                .map(TypeName::get).collect(toList());
        final String methodName = method.getSimpleName().toString();
        final List<UDFParamSignature> parameterSignatures = method.getParameters().stream()
                .map(x -> new UDFParamSignature(TypeName.get(x.asType()).box(), x.getSimpleName().toString()))
                .collect(toList());

        //Validate parameter types
        for (TypeName param : parametersType) {
            TypeValidator.validateNativeTypesForFunction(aptUtils, method, param, "argument");
        }

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

        final TypeName returnType = TypeName.get(returnTypeMirror).box();
        TypeValidator.validateNativeTypesForFunction(aptUtils, method, returnType, "return type");

        // 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,
                sourceClass);

        return new UDFSignature(keyspace, sourceClass, methodName, returnType, parametersType,
                parameterSignatures);
    }).collect(toList());
}

From source file:alfio.util.Validator.java

public static ValidationResult validateTicketAssignment(UpdateTicketOwnerForm form,
        List<TicketFieldConfiguration> additionalFieldsForEvent, Optional<Errors> errorsOptional, Event event) {
    if (!errorsOptional.isPresent()) {
        return ValidationResult.success();//already validated
    }//  w  w w  . ja  va  2  s .  c  o  m
    Errors errors = errorsOptional.get();
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "error.email");
    String email = form.getEmail();
    if (!isEmailValid(email)) {
        errors.rejectValue("email", "error.email");
    }

    if (event.mustUseFirstAndLastName()) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", ErrorsCode.STEP_2_EMPTY_FIRSTNAME);
        validateMaxLength(form.getFirstName(), "firstName", ErrorsCode.STEP_2_MAX_LENGTH_FIRSTNAME, 255,
                errors);

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", ErrorsCode.STEP_2_EMPTY_LASTNAME);
        validateMaxLength(form.getLastName(), "lastName", ErrorsCode.STEP_2_MAX_LENGTH_LASTNAME, 255, errors);
    } else {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "fullName", ErrorsCode.STEP_2_EMPTY_FULLNAME);
        validateMaxLength(form.getFullName(), "fullName", ErrorsCode.STEP_2_MAX_LENGTH_FULLNAME, 255, errors);
    }

    //
    for (TicketFieldConfiguration fieldConf : additionalFieldsForEvent) {

        boolean isField = form.getAdditional() != null && form.getAdditional().containsKey(fieldConf.getName());

        if (!isField) {
            continue;
        }

        form.getAdditional().get(fieldConf.getName()).forEach(formValue -> {
            if (fieldConf.isMaxLengthDefined()) {
                validateMaxLength(formValue, "additional['" + fieldConf.getName() + "']",
                        "error." + fieldConf.getName(), fieldConf.getMaxLength(), errors);
            }

            if (!fieldConf.getRestrictedValues().isEmpty()) {
                validateRestrictedValue(formValue, "additional['" + fieldConf.getName() + "']",
                        "error." + fieldConf.getName(), fieldConf.getRestrictedValues(), errors);
            }

            if (fieldConf.isRequired() && StringUtils.isBlank(formValue)) {
                errors.rejectValue("additional['" + fieldConf.getName() + "']", "error." + fieldConf.getName());
            }
        });

        //TODO: complete checks: min length
    }

    return evaluateValidationResult(errors);
}