Example usage for java.util Optional map

List of usage examples for java.util Optional map

Introduction

In this page you can find the example usage for java.util Optional map.

Prototype

public <U> Optional<U> map(Function<? super T, ? extends U> mapper) 

Source Link

Document

If a value is present, returns an Optional describing (as if by #ofNullable ) the result of applying the given mapping function to the value, otherwise returns an empty Optional .

Usage

From source file:com.ikanow.aleph2.search_service.elasticsearch.utils.ElasticsearchIndexUtils.java

/** Utility to build a lookup map based on a columnar schema
 * @param columnar_schema//from w ww  .  j a va2 s.c om
 * @return
 */
protected static Map<Either<String, Tuple2<String, String>>, JsonNode> createComplexStringLookups(
        final Optional<DataSchemaBean.SearchIndexSchemaBean> maybe_search_index_schema,
        final SearchIndexSchemaDefaultBean search_index_schema_override, final ObjectMapper mapper) {
    // (see similar code in parseDefaultMapping)
    final boolean tokenize_by_default = maybe_search_index_schema.map(s -> s.tokenize_by_default())
            .orElse(true);
    final boolean dual_tokenize_by_default = Optional
            .ofNullable(search_index_schema_override.dual_tokenize_by_default()).orElse(false);

    // Start with streams of tokenized, non-tokenized, and dual fields
    return Stream
            .of(maybe_search_index_schema.map(s -> s.tokenization_override())
                    .map(m -> m.get(DEFAULT_TOKENIZATION_TYPE))
                    .map(columnar_schema -> createComplexStringLookups_partial(columnar_schema))
                    .orElse(Collections.emptyMap()).entrySet().stream()
                    .<Tuple3<Either<String, Tuple2<String, String>>, Boolean, Boolean>>map(
                            kv -> Tuples._3T(kv.getKey(), kv.getValue(), null)),
                    maybe_search_index_schema.map(s -> s.tokenization_override())
                            .map(m -> m.get(NO_TOKENIZATION_TYPE))
                            .map(columnar_schema -> createComplexStringLookups_partial(columnar_schema))
                            .orElse(Collections.emptyMap()).entrySet().stream()
                            .<Tuple3<Either<String, Tuple2<String, String>>, Boolean, Boolean>>map(
                                    kv -> Tuples._3T(kv.getKey(), !kv.getValue(), null)),
                    Optional.ofNullable(search_index_schema_override.dual_tokenization_override())
                            .map(columnar_schema -> createComplexStringLookups_partial(columnar_schema))
                            .orElse(Collections.emptyMap()).entrySet().stream()
                            .<Tuple3<Either<String, Tuple2<String, String>>, Boolean, Boolean>>map(
                                    kv -> Tuples._3T(kv.getKey(), null, kv.getValue())))
            .flatMap(__ -> __)
            // Merge the map
            .collect(Collectors.toMap(t3 -> t3._1(), t3 -> Tuples._2T(t3._2(), t3._3()),
                    // use the existing value, unless it's null in which case overwrite it
                    (t2_1, t2_2) -> Tuples._2T(Optional.ofNullable(t2_1._1()).orElse(t2_2._1()),
                            Optional.ofNullable(t2_2._1()).orElse(t2_2._2()))))
            .entrySet()
            // Now convert to the JSON mapping
            .stream()
            .map(kv -> Tuples._2T(kv.getKey(),
                    getMapping(
                            Tuples._2T(Optional.ofNullable(kv.getValue()._1()).orElse(tokenize_by_default),
                                    Optional.ofNullable(kv.getValue()._2()).orElse(dual_tokenize_by_default)),
                            search_index_schema_override, mapper, kv.getKey().isRight())))
            .collect(Collectors.toMap(t2 -> t2._1(), t2 -> t2._2()));
}

From source file:net.sf.jabref.logic.groups.KeywordGroup.java

@Override
public boolean contains(BibEntry entry) {
    if (regExp) {
        Optional<String> content = entry.getFieldOptional(searchField);
        return content.map(value -> pattern.matcher(value).find()).orElse(false);
    }/* ww  w . j  av a2s  .  co m*/

    Set<String> words = entry.getFieldAsWords(searchField);
    if (words.isEmpty()) {
        return false;
    }

    if (caseSensitive) {
        return words.containsAll(searchWords);
    }
    return containsCaseInsensitive(searchWords, words);
}

From source file:com.ikanow.aleph2.management_db.services.DataBucketCrudService.java

/** Check if bucket exists (or the path within the bucket if "file" optional specified
 * @param to_check/* w  ww. j  av a 2 s  . c om*/
 * @param storage_service
 * @param file - the file path in the bucket (checks bucket root path if left blank)
 * @return
 * @throws Exception
 */
public static boolean doesBucketPathExist(final DataBucketBean to_check, final IStorageService storage_service,
        final Optional<String> file) throws Exception {
    final FileContext dfs = storage_service.getUnderlyingPlatformDriver(FileContext.class, Optional.empty())
            .get();
    final String bucket_root = storage_service.getBucketRootPath() + "/" + to_check.full_name()
            + IStorageService.BUCKET_SUFFIX;

    try {
        dfs.getFileStatus(new Path(bucket_root + file.map(s -> "/" + s).orElse("")));
        return true;
    } catch (FileNotFoundException fe) {
        return false;
    }

}

From source file:com.example.app.repository.model.RepositoryDAO.java

/**
 * Get boolean flag.  If true, the given user can perform the given MembershipOperation on the given Repository
 *
 * @param user the User to check//from  ww  w  .  j a v  a2 s . co m
 * @param repository the Repository to check for permission
 * @param timeZone the timezone.
 * @param operation the Operation the User wishes to perform
 *
 * @return boolean flag
 */
public boolean canOperate(@Nonnull User user, @Nonnull Repository repository, TimeZone timeZone,
        @Nonnull MembershipOperation operation) {
    Optional<Profile> owner = getOwnerOfRepository(repository);
    return owner.map(ownerProfile -> _profileDAO.canOperate(user, ownerProfile, timeZone, operation))
            .orElse(false);
}

From source file:com.ikanow.aleph2.management_db.mongodb.services.IkanowV1SyncService_LibraryJars.java

/** Builds a V2 library bean out of a V1 share
 * @param src_json/*ww w.  j  av a2  s .co m*/
 * @return
 * @throws JsonParseException
 * @throws JsonMappingException
 * @throws IOException
 * @throws ParseException
 */
protected static SharedLibraryBean getLibraryBeanFromV1Share(final JsonNode src_json)
        throws JsonParseException, JsonMappingException, IOException, ParseException {

    final String[] description_lines = Optional.ofNullable(safeJsonGet("description", src_json).asText())
            .orElse("unknown").split("\r\n?|\n");

    final String _id = "v1_" + safeJsonGet(JsonUtils._ID, src_json).asText();
    final String created = safeJsonGet("created", src_json).asText();
    final String modified = safeJsonGet("modified", src_json).asText();
    final String display_name = safeJsonGet("title", src_json).asText();
    final String path_name = display_name;

    final List<String> description_lines_list = Arrays.asList(description_lines);

    // Find possible JSON config
    Optional<Tuple2<Integer, Integer>> json_config = IntStream.range(1, description_lines.length).boxed()
            .filter(i -> description_lines[i].trim().startsWith("{")).findFirst()
            .<Tuple2<Integer, Integer>>map(start -> {
                return IntStream.range(start + 1, description_lines.length).boxed()
                        .filter(i -> !description_lines[i].matches("^\\s*[{}\"'].*")).findFirst()
                        .<Tuple2<Integer, Integer>>map(end -> Tuples._2T(start, end))
                        .orElse(Tuples._2T(start, description_lines.length));
            });

    @SuppressWarnings("unchecked")
    final Optional<Map<String, Object>> json = json_config
            .map(t2 -> description_lines_list.stream().limit(t2._2()).skip(t2._1())
                    .collect(Collectors.joining("\n")))
            .map(Lambdas.wrap_u(s -> _mapper.readTree(s)))
            .<Map<String, Object>>map(j -> (Map<String, Object>) _mapper.convertValue(j, Map.class));
    ;

    final Set<String> tags = safeTruncate(description_lines[description_lines.length - 1], 5).toLowerCase()
            .startsWith("tags:")
                    ? new HashSet<String>(Arrays.asList(description_lines[description_lines.length - 1]
                            .replaceFirst("(?i)tags:\\s*", "").split("\\s*,\\s*")))
                    : Collections.emptySet();

    final String description = description_lines_list.stream()
            .limit(Optional.of(description_lines.length).map(n -> tags.isEmpty() ? n : n - 1) // skip over the tags if any
                    .get())
            .skip(json_config.map(Tuple2::_2).orElse(1)).collect(Collectors.joining("\n"));

    final LibraryType type = LibraryType.misc_archive;
    final String owner_id = safeJsonGet(JsonUtils._ID, safeJsonGet("owner", src_json)).asText();
    //final JsonNode comm_objs = safeJsonGet("communities", src_json); // collection of { _id: $oid } types
    final String misc_entry_point = description_lines[0];

    final SharedLibraryBean bean = BeanTemplateUtils.build(SharedLibraryBean.class)
            .with(SharedLibraryBean::_id, _id).with(SharedLibraryBean::created, parseJavaDate(created))
            .with(SharedLibraryBean::modified, parseJavaDate(modified))
            .with(SharedLibraryBean::display_name, display_name).with(SharedLibraryBean::path_name, path_name)
            .with(SharedLibraryBean::description, description).with(SharedLibraryBean::tags, tags)
            .with(SharedLibraryBean::type, type).with(SharedLibraryBean::misc_entry_point, misc_entry_point)
            .with(SharedLibraryBean::owner_id, owner_id)
            .with(SharedLibraryBean::library_config, json.orElse(null)).done().get();

    return bean;
}

From source file:alfio.manager.PaypalManager.java

public boolean refund(alfio.model.transaction.Transaction transaction, Event event, Optional<Integer> amount) {
    String captureId = transaction.getTransactionId();
    try {/*from w ww .j ava2 s  .c  om*/
        APIContext apiContext = getApiContext(event);
        String amountOrFull = amount.map(MonetaryUtil::formatCents).orElse("full");
        log.info("Paypal: trying to do a refund for payment {} with amount: {}", captureId, amountOrFull);
        Capture capture = Capture.get(apiContext, captureId);
        RefundRequest refundRequest = new RefundRequest();
        amount.ifPresent(
                a -> refundRequest.setAmount(new Amount(capture.getAmount().getCurrency(), formatCents(a))));
        DetailedRefund res = capture.refund(apiContext, refundRequest);
        log.info("Paypal: refund for payment {} executed with success for amount: {}", captureId, amountOrFull);
        return true;
    } catch (PayPalRESTException ex) {
        log.warn("Paypal: was not able to refund payment with id " + captureId, ex);
        return false;
    }
}

From source file:com.ikanow.aleph2.example.flume_harvester.services.FlumeHarvestTechnology.java

/** Starts/restarts a flume agent by creating a per-bucket config for that element
 *  TODO (ALEPH-10): NOTE: currently only one config is allowed per agent - I didn't realize you needed one jvm per agent ...
 *  the only way of having multiple configs per JVM is to generate multiple sources and sinks, ie merge all the config elements into 1
 *  I'll leave it like this for the moment, in case the plan later is to spawn multiple processes from the one harvester
 *  (which would have the advantage of not having to alter unaffected agents, which might be tricky to calculate of course) 
 * @param agent_num/*w  w  w  .ja  v a  2s  .  c  o m*/
 * @param bucket
 * @param config
 * @param context
 * @throws IOException
 */
protected Tuple2<String, File> updateAgentConfig(final int agent_num, final DataBucketBean bucket,
        final FlumeBucketConfigBean config, final IHarvestContext context, final boolean test_mode)
        throws IOException {
    //TODO (ALEPH-10): unit test for this 

    final String agent_name = FlumeUtils.getConfigName(bucket.full_name(),
            Optional.of(Integer.toString(agent_num)));

    // Is morphlines configured?
    final Optional<String> morphlines_file = Optional.ofNullable(config.morphlines_config())
            .flatMap(Lambdas.wrap_u(m_cfg -> {
                final File tmp_morph = createTempFile("aleph2_morph_", agent_name);
                final Optional<String> morph_cfg = FlumeUtils.createMorphlinesConfig(config);
                return morph_cfg.map(Lambdas.wrap_u(mcfg -> {
                    FileUtils.writeStringToFile(tmp_morph, mcfg);
                    return tmp_morph.toString();
                }));

            }));
    final File tmp_flume = createTempFile("aleph2_flume_", agent_name);
    final String flume_config = FlumeUtils
            .createFlumeConfig(agent_name, bucket, config,
                    context.getHarvestContextSignature(Optional.of(bucket),
                            FlumeLaunchUtils.getContextLibraries(Optional.of(config))),
                    morphlines_file, test_mode);
    FileUtils.writeStringToFile(tmp_flume, flume_config);

    return Tuples._2T(agent_name, tmp_flume);
}

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

public TypeName determineTargetCQLType(AnnotationTree annotationTree, TypeName parentType, TypeName sourceType,
        String methodName, String paramName, Optional<CodecInfo> codecFromRegistry) {
    TypeName targetType = sourceType;/*  ww w  .  j  a v a2 s .c  om*/
    TypeMirror typeMirror = annotationTree.getCurrentType();

    final Optional<TypedMap> jsonTransform = extractTypedMap(annotationTree, JSON.class);
    final Optional<TypedMap> enumerated = extractTypedMap(annotationTree, Enumerated.class);
    final Optional<TypedMap> codecFromType = extractTypedMap(annotationTree, Codec.class);
    final Optional<TypedMap> runtimeCodec = extractTypedMap(annotationTree, RuntimeCodec.class);
    final Optional<TypedMap> computed = extractTypedMap(annotationTree, Computed.class);
    final Optional<TypeName> computedCQLClass = computed.map(x -> x.<Class<?>>getTyped("cqlClass"))
            .map(ClassName::get);
    final boolean isCounter = extractTypedMap(annotationTree, Counter.class).isPresent();

    if (jsonTransform.isPresent()) {
        return ClassName.get(String.class);
    } else if (codecFromType.isPresent()) {
        final CodecContext codecContext = codecFromType.get().getTyped("codecContext");
        validateCodec(aptUtils, codecContext, sourceType, computedCQLClass, isCounter);
        return codecContext.targetType.box();
    } else if (runtimeCodec.isPresent()) {
        final RuntimeCodecContext runtimeCodecContext = runtimeCodec.get().getTyped("runtimeCodecContext");
        validateCodec(aptUtils, runtimeCodecContext, runtimeCodecContext.sourceType, computedCQLClass,
                isCounter);
        return runtimeCodecContext.targetType.box();
    } else if (enumerated.isPresent()) {
        final TypedMap typedMap = enumerated.get();
        final Object value = typedMap.getTyped("value");
        aptUtils.validateTrue(isAnEnum(value),
                "The type '%s' on param '%s' of method '%s' in class '%s' is not a java.lang.Enum type",
                sourceType.toString(), paramName, methodName, parentType);
        final Encoding encoding = typedMap.getTyped("value");
        if (encoding == Encoding.NAME) {
            return STRING;

        } else {
            return OBJECT_INT;
        }
    } else if (typeMirror.getKind() == TypeKind.ARRAY && typeMirror.toString().equals("byte[]")) {
        if (codecFromRegistry.isPresent()) {
            return codecFromRegistry.get().targetType.box();
        } else {
            return BYTE_BUFFER;
        }
    } else if (typeMirror.getKind() == TypeKind.ARRAY && typeMirror.toString().equals("java.lang.Byte[]")) {
        if (codecFromRegistry.isPresent()) {
            return codecFromRegistry.get().targetType.box();
        } else {
            return BYTE_BUFFER;
        }
    } else {
        if (codecFromRegistry.isPresent()) {
            return codecFromRegistry.get().targetType.box();
        } else {
            TypeValidator.validateAllowedTypesForFunction(aptUtils, parentType.toString(), methodName,
                    sourceType);
            return targetType;
        }
    }
}

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

/**
 * Returns an instance of CrudUtils.allOf(clazz), if clazz is a JsonNode returns CrudUtils.allOf().
 * /*from  ww w.  j  a  v a2  s  . c  om*/
 * If the object is not a bean, this will exception out.
 * @param clazz
 * @return
 */
@SuppressWarnings("unchecked")
private static <T> SingleQueryComponent<T> getSingleQueryComponent(final QueryComponentBean toConvert,
        final Class<T> clazz, Optional<Long> limit) {
    final SingleQueryComponent<T> query = JsonNode.class.isAssignableFrom(clazz)
            ? (SingleQueryComponent<T>) CrudUtils.allOf()
            : CrudUtils.allOf(clazz);

    //add all the possible ops
    toConvert.when().entrySet().stream().forEach(e -> query.when(e.getKey(), e.getValue())); //equals
    toConvert.whenNot().entrySet().stream().forEach(e -> query.whenNot(e.getKey(), e.getValue())); //not equals

    toConvert.withAll().entrySet().stream().forEach(e -> query.withAll(e.getKey(), e.getValue())); //equals all
    toConvert.withAny().entrySet().stream().forEach(e -> query.withAny(e.getKey(), e.getValue())); //equals any      
    toConvert.withPresent().stream().forEach(e -> query.withPresent(e)); //exists
    toConvert.withNotPresent().stream().forEach(e -> query.withNotPresent(e)); //not exists

    toConvert.rangeAbove().entrySet().stream()
            .forEach(e -> query.rangeAbove(e.getKey(), e.getValue()._1, e.getValue()._2)); // >=
    toConvert.rangeBelow().entrySet().stream()
            .forEach(e -> query.rangeAbove(e.getKey(), e.getValue()._1, e.getValue()._2)); // <=
    toConvert.rangeIn().entrySet().stream().forEach(e -> query.rangeIn(e.getKey(), e.getValue()._1._1,
            e.getValue()._1._2, e.getValue()._2._1, e.getValue()._2._2)); //>= AND <=

    limit.map(l -> query.limit(l));

    return query;
}

From source file:com.ikanow.aleph2.example.flume_harvester.services.FlumeHarvestTechnology.java

@Override
public CompletableFuture<BasicMessageBean> onPeriodicPoll(DataBucketBean polled_bucket,
        IHarvestContext context) {/*  ww w.ja  va  2s .c o  m*/

    // (If we're here then we're not suspended by definition)

    // Check if it's running
    final Optional<String> maybe_pid = Optional.ofNullable(FlumeLaunchUtils.getPid(polled_bucket));
    final boolean is_running = maybe_pid.map(Lambdas.wrap_u(pid -> FlumeLaunchUtils.isRunning(pid)))
            .orElse(false);
    if (!is_running) { // restart it if not
        return onNewSource(polled_bucket, context, true);
    } else {
        return CompletableFuture.completedFuture(new BasicMessageBean(new Date(), true, "onPeriodicPoll",
                "onPeriodicPoll", null, "No action taken", null));
    }
}