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:com.formkiq.core.form.FormFinder.java

/**
 * Find {@link FormJSONField}./*from www .  ja va  2s  .  co m*/
 * @param archive {@link ArchiveDTO}
 * @param documentfieldname {@link String}
 * @return {@link Optional} {@link FormJSONField}
 */
public static Optional<FormJSONField> findField(final ArchiveDTO archive, final String documentfieldname) {

    Optional<FormJSONField> op = Optional.empty();
    List<WorkflowOutputFormField> fields = stream(archive.getWorkflow());
    Optional<WorkflowOutputFormField> o = fields.stream()
            .filter(s -> s.getDocumentfieldname().equals(documentfieldname)).findFirst();

    if (o.isPresent()) {
        String fuuid = extractLabelAndValue(o.get().getForm()).getRight();
        String fid = extractLabelAndValue(o.get().getField()).getRight();

        FormJSON form = archive.getForm(fuuid);
        op = FormFinder.findField(form, NumberUtils.toInt(fid, -1));
    }

    return op;
}

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

public static boolean playerAlreadyHasInvite(ItemStack stack, Player target) {
    UUID zoneID = getZoneID(stack).orElseThrow(() -> new IllegalArgumentException("Illegal zone ItemStack"));
    ItemStack[] inv = tf(target).inventory.mainInventory;
    for (ItemStack aStack : inv) {
        Optional<UUID> optZoneID = getZoneID(aStack);
        if (optZoneID.isPresent()) {
            if (zoneID.equals(optZoneID.get())) {
                return true;
            }/*from ww w  .  j  a v  a 2 s. c o m*/
        }
    }
    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.
 * //w  w  w . j  a v a  2  s .co m
 * @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:com.skelril.skree.content.registry.item.zone.ZoneItemUtil.java

public static boolean notifyGroupOwner(ItemStack stack, Player holder, boolean joined) {
    Validate.isTrue(isZoneSlaveItem(stack));
    Optional<Player> optPlayer = getGroupOwner(stack);
    if (optPlayer.isPresent()) {
        Player player = optPlayer.get();
        if (joined) {
            if (incrementCount(stack, player)) {
                player.sendMessage(/* w  w  w. jav  a2s . c om*/
                        Text.of(TextColors.GOLD, holder.getName() + " has accepted your invitation."));
            }
        } else {
            if (!isAttuned(stack) || decrementCount(stack, player)) {
                player.sendMessage(
                        Text.of(TextColors.RED, holder.getName() + " has declined your invitation."));
            }
        }
        return true;
    }
    return false;
}

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

public static <T> BoundValuesWrapper extractPartitionKeysAndStaticValues(T instance,
        AbstractEntityProperty<T> entityProperty, Options options) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(format("Extract partition key values and static columns from entity %s of type %",
                instance, entityProperty.entityClass.getCanonicalName()));
    }/*from www .  ja  v a  2 s  .  c  o m*/

    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()));

    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.ikanow.aleph2.data_model.utils.ProcessUtils.java

/**
 * Starts the given process by calling process_builder.start();
 * Records the started processes pid and start date.
 *  /* ww  w.  java2  s .  c om*/
 * @param process_builder
 * @throws IOException 
 * @return returns any error in _1(), the pid in _2()
 */
public static Tuple2<String, String> launchProcess(final ProcessBuilder process_builder,
        final String application_name, final DataBucketBean bucket, final String aleph_root_path,
        final Optional<Tuple2<Long, Integer>> timeout_kill) {
    try {
        if (timeout_kill.isPresent()) {
            final Stream<String> timeout_stream = Stream.of("timeout", "-s", timeout_kill.get()._2.toString(),
                    timeout_kill.get()._1.toString());
            process_builder.command(Stream.concat(timeout_stream, process_builder.command().stream())
                    .collect(Collectors.toList()));
        }

        //starts the process, get pid back
        logger.debug("Starting process: " + process_builder.command().toString());
        final Process px = process_builder.start();
        String err = null;
        String pid = null;
        if (!px.isAlive()) {
            err = "Unknown error: " + px.exitValue() + ": "
                    + process_builder.command().stream().collect(Collectors.joining(" "));
            // (since not capturing output)
        } else {
            pid = getPid(px);
            //get the date on the pid file from /proc/<pid>
            final long date = getDateOfPid(pid);
            //record pid=date to aleph_root_path/pid_manager/bucket._id/application_name
            storePid(application_name, bucket, aleph_root_path, pid, date);
        }
        return Tuples._2T(err, pid);

    } catch (Throwable t) {
        return Tuples._2T(ErrorUtils.getLongForm("{0}", t), null);
    }
}

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

public static CodecContext buildCodecContext(AptUtils aptUtils, AnnotationMirror codecFromType) {
    Optional<Class<Codec>> codecClassO = getElementValueClass(codecFromType, "value", false);
    if (codecClassO.isPresent()) {
        Class<Codec> codecClass = codecClassO.get();
        List<Type> genericTypes = Arrays.asList(codecClass.getGenericInterfaces());

        final List<TypeName> codecTypes = genericTypes.stream().filter(x -> x instanceof ParameterizedType)
                .map(x -> (ParameterizedType) x)
                .filter(x -> x.getRawType().getTypeName()
                        .equals(info.archinnov.achilles.type.codec.Codec.class.getCanonicalName()))
                .flatMap(x -> Arrays.asList(x.getActualTypeArguments()).stream()).map(TypeName::get)
                .collect(Collectors.toList());
        aptUtils.validateTrue(codecTypes.size() == 2,
                "Codec class '%s' should have 2 parameters: Codec<FROM, TO>", codecClass);
        return new CodecContext(ClassName.get(codecClass), codecTypes.get(0), codecTypes.get(1));
    } else {//from w  ww.  j av  a 2  s  .  c o  m
        return buildCodecContext(aptUtils, getElementValueClassName(codecFromType, "value", false).toString());
    }
}

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

public static <T> BoundValuesWrapper extractAllValues(T instance, AbstractEntityProperty<T> entityProperty,
        Options options) {//from  w ww.j  a  v 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:net.sf.jabref.gui.desktop.JabRefDesktop.java

/**
 * Open an external file, attempting to use the correct viewer for it.
 *
 * @param databaseContext/*from w  ww . j a va 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: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.  j  a v  a2 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);
}