Example usage for java.util LinkedHashMap getOrDefault

List of usage examples for java.util LinkedHashMap getOrDefault

Introduction

In this page you can find the example usage for java.util LinkedHashMap getOrDefault.

Prototype

public V getOrDefault(Object key, V defaultValue) 

Source Link

Usage

From source file:io.syndesis.verifier.LocalProcessVerifier.java

private ImmutableResult createResult(Verifier.Scope scope, Verifier.Result.Status status, Properties response) {
    ImmutableResult.Builder builder = ImmutableResult.builder().scope(scope).status(status);
    if (response != null) {
        LinkedHashMap<String, ImmutableError.Builder> errors = new LinkedHashMap<>();
        for (Map.Entry<Object, Object> entry : response.entrySet()) {
            String key = (String) entry.getKey();
            if (key.startsWith("error.")) {
                String errorId = key.substring("error.".length()).replaceFirst("\\..*", "");
                ImmutableError.Builder error = errors.getOrDefault(errorId, ImmutableError.builder());
                String value = (String) entry.getValue();
                if (key.endsWith(".code")) {
                    error.code(value);//from w  w w .j  a va  2 s. c  o m
                }
                if (key.endsWith(".description")) {
                    error.description(value);
                }
                errors.put(errorId, error);
            }
        }
        builder.addAllErrors(
                errors.values().stream().map(ImmutableError.Builder::build).collect(Collectors.toList()));
    }
    return builder.build();
}

From source file:io.stallion.restfulEndpoints.QueryToPager.java

protected void process() {
    // ?filters=&search=&page=&sort=&filter_by...
    Map<String, String> params = this.request.getQueryParams();
    String search = params.getOrDefault("search", null);
    if (!empty(search)) {
        if (!empty(_searchFields)) {
            this.chain = chain.search(search, asArray(_searchFields, String.class));
        } else {/*from  ww  w. ja  va 2s .  c o m*/
            Log.warn("Search included, but no search fields defined");
        }
    }
    String filters = params.getOrDefault("filters", null);
    if (!empty(filters)) {
        List<LinkedHashMap> filterObjects = JSON.parseList(filters);
        for (LinkedHashMap<String, Object> o : filterObjects) {
            String field = o.get("name").toString();
            if (!_allFilters && !_allowedFilters.contains(field)) {
                Log.warn("Filter not allowed: " + field);
                continue;
            }

            Object value = o.get("value");
            if (value instanceof Collection) {
                value = new ArrayList((Collection) value);
            }
            String operation = (String) o.getOrDefault("op", "=");
            this.chain = chain.filter(field, value, operation);
        }
    }
    String sort = or(params.getOrDefault("sort", null), defaultSort);
    if (!empty(sort)) {
        SortDirection dir = SortDirection.ASC;
        if (sort.startsWith("-")) {
            sort = sort.substring(1);
            dir = SortDirection.DESC;
        }
        if (!_allSorts && !_allowedSortable.contains(sort)) {
            Log.warn("Sort not allowed: " + sort);
        } else {
            this.chain = chain.sortBy(sort, dir);
        }
    }

    for (String filter : request.getQueryParamAsList("filter_by")) {
        if (empty(filter) || !filter.contains(":")) {
            continue;
        }
        String[] parts = StringUtils.split(filter, ":", 3);
        String key = parts[0];
        if (_allFilters && !_allowedFilters.contains(key)) {
            Log.warn("Filter not allowed: " + key);
            continue;
        }
        String val;
        String op = "eq";
        if (parts.length > 2) {
            op = parts[1];
            val = parts[2];
        } else {
            val = parts[1];
        }
        this.chain = chain.filter(key, val, op);

    }

}

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

/** Creates a mapping for the bucket - columnar elements
 *  ALSO INCLUDES THE PER-FIELD CONFIGURATION FROM THE SEARCH_INDEX_SCHEMA AND TEMPORAL_SCHMEA
 * @param bucket// w  w  w.ja v a  2 s.c  o m
 * @return
 * @throws IOException 
 */
public static XContentBuilder getColumnarMapping(final DataBucketBean bucket,
        Optional<XContentBuilder> to_embed,
        final LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> field_lookups,
        final JsonNode enabled_not_analyzed, final JsonNode enabled_analyzed,
        final JsonNode default_not_analyzed, final JsonNode default_analyzed,
        final Optional<JsonNode> doc_schema, final SearchIndexSchemaDefaultBean search_index_schema_override,
        final ObjectMapper mapper, final String index_type) {
    try {
        final XContentBuilder start = to_embed.orElse(XContentFactory.jsonBuilder().startObject());
        final boolean columnar_enabled = Optional.ofNullable(bucket.data_schema())
                .map(DataSchemaBean::columnar_schema).filter(s -> Optional.ofNullable(s.enabled()).orElse(true))
                .isPresent();

        final Map<Either<String, Tuple2<String, String>>, String> type_override = Optionals
                .of(() -> bucket.data_schema().search_index_schema().type_override()).map(m -> buildTypeMap(m))
                .orElse(Collections.emptyMap());

        // If no columnar settings are specified then go with a sensible default
        final Optional<DataSchemaBean.ColumnarSchemaBean> maybe_user_columnar_schema = Optionals
                .of(() -> bucket.data_schema().columnar_schema());
        final DataSchemaBean.ColumnarSchemaBean columnar_schema = maybe_user_columnar_schema
                .filter(__ -> columnar_enabled).filter(schema -> (null == schema.field_include_list()) && // ie the entire thing is empty
                        (null == schema.field_exclude_list()) && (null == schema.field_include_pattern_list())
                        && (null == schema.field_type_include_list())
                        && (null == schema.field_exclude_pattern_list())
                        && (null == schema.field_type_exclude_list()))
                .map(schema -> BeanTemplateUtils.clone(schema)
                        .with(DataSchemaBean.ColumnarSchemaBean::field_type_include_list,
                                Arrays.asList("string", "number", "date"))
                        .done())
                .orElseGet(() -> maybe_user_columnar_schema.orElse(null)) // (NOTE: can only be null if columnar_enabled is false)
        ;

        final LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> column_lookups_pretypes = Stream
                .of(columnar_enabled
                        ? createFieldIncludeLookups(
                                Optionals.ofNullable(columnar_schema.field_include_list()).stream(),
                                fn -> getKey(fn), field_lookups, enabled_not_analyzed, enabled_analyzed, true,
                                search_index_schema_override, type_override, mapper, index_type)
                        : Stream.<Tuple2<Either<String, Tuple2<String, String>>, JsonNode>>empty(),
                        columnar_enabled
                                ? createFieldExcludeLookups(
                                        Optionals.ofNullable(columnar_schema.field_exclude_list()).stream(),
                                        fn -> getKey(fn), field_lookups, search_index_schema_override,
                                        type_override, mapper, index_type)
                                : Stream.<Tuple2<Either<String, Tuple2<String, String>>, JsonNode>>empty(),
                        columnar_enabled
                                ? createFieldIncludeLookups(
                                        Optionals.ofNullable(columnar_schema.field_include_pattern_list())
                                                .stream(),
                                        fn -> Either.right(Tuples._2T(fn, "*")), field_lookups,
                                        enabled_not_analyzed, enabled_analyzed, true,
                                        search_index_schema_override, type_override, mapper, index_type)
                                : Stream.<Tuple2<Either<String, Tuple2<String, String>>, JsonNode>>empty(),
                        columnar_enabled
                                ? createFieldIncludeLookups(
                                        Optionals.ofNullable(columnar_schema.field_type_include_list())
                                                .stream(),
                                        fn -> Either.right(Tuples._2T("*", fn)), field_lookups,
                                        enabled_not_analyzed, enabled_analyzed, true,
                                        search_index_schema_override, type_override, mapper, index_type)
                                : Stream.<Tuple2<Either<String, Tuple2<String, String>>, JsonNode>>empty(),
                        columnar_enabled
                                ? createFieldExcludeLookups(
                                        Optionals.ofNullable(columnar_schema.field_exclude_pattern_list())
                                                .stream(),
                                        fn -> Either.right(Tuples._2T(fn, "*")), field_lookups,
                                        search_index_schema_override, type_override, mapper, index_type)
                                : Stream.<Tuple2<Either<String, Tuple2<String, String>>, JsonNode>>empty(),
                        columnar_enabled
                                ? createFieldExcludeLookups(
                                        Optionals.ofNullable(columnar_schema.field_type_exclude_list())
                                                .stream(),
                                        fn -> Either.right(Tuples._2T("*", fn)), field_lookups,
                                        search_index_schema_override, type_override, mapper, index_type)
                                : Stream.<Tuple2<Either<String, Tuple2<String, String>>, JsonNode>>empty(),

                        // Finally add the default columnar lookups to the unmentioned strings (ensures that *_* is at the end)

                        field_lookups.entrySet().stream()
                                .flatMap(kv -> createFieldIncludeLookups(Stream.of(kv.getKey().toString()),
                                        __ -> kv.getKey(), field_lookups, default_not_analyzed,
                                        default_analyzed, false, search_index_schema_override, type_override,
                                        mapper, index_type)))
                .flatMap(x -> x).collect(Collectors.toMap(t2 -> t2._1(), t2 -> t2._2(), (v1, v2) -> v1, // (ie ignore duplicates)
                        () -> new LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode>()));
        ;

        // Also any types that didn't map onto one of the fields or tokens:
        final LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> column_lookups_types = type_override
                .entrySet().stream()
                // (filter - convert name/* to name/type and check if I've already created such an entry using the type map)
                .filter(kv -> !column_lookups_pretypes
                        .containsKey(kv.getKey().either(s -> s, t2 -> Tuples._2T(t2._1(), kv.getValue()))))
                .flatMap(kv -> createFieldIncludeLookups(Stream.of(kv.getKey().toString()),
                        __ -> kv.getKey().<Either<String, Tuple2<String, String>>>either(s -> Either.left(s),
                                t2 -> Either.right(Tuples._2T(t2._1(), kv.getValue()))),
                        field_lookups, default_not_analyzed, default_analyzed, false,
                        search_index_schema_override, type_override, mapper, index_type))
                .collect(Collectors.toMap(t2 -> t2._1(), t2 -> t2._2(), (v1, v2) -> v1,
                        () -> new LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode>()));

        final LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> column_lookups = Stream
                .concat(column_lookups_pretypes.entrySet().stream(), column_lookups_types.entrySet().stream())
                .sorted((a, b) -> Integer.compare(sortKey(a.getKey()), sortKey(b.getKey())))
                .collect(Collectors.toMap(t2 -> t2.getKey(), t2 -> t2.getValue(), (v1, v2) -> v1,
                        () -> new LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode>()));

        final XContentBuilder properties = column_lookups.entrySet().stream()
                // properties not dynamic_templates
                .filter(kv -> kv.getKey().isLeft())
                // overwrite with version built using columns if it exists
                .map(kv -> Tuples._2T(kv.getKey(),
                        column_lookups.getOrDefault(kv.getKey(), kv.getValue())))
                .reduce(Optional.of(start.startObject("properties")) // add doc_schema if it exists
                        .map(props -> doc_schema
                                .map(ds -> Optionals.streamOf(ds.fields(), false)
                                        .reduce(props,
                                                Lambdas.wrap_u((acc, kv) -> acc.rawField(kv.getKey(),
                                                        kv.getValue().toString().getBytes())),
                                                (acc1, acc2) -> acc1 // shouldn't be possible
                                )).orElse(props)).get(),
                        Lambdas.wrap_u((acc, t2) -> acc.rawField(t2._1().left().value(),
                                t2._2().toString().getBytes())), // (left by construction) 
                        (acc1, acc2) -> acc1) // (not actually possible)
                .endObject();

        final XContentBuilder templates = column_lookups.entrySet().stream()
                // properties not dynamic_templates
                .filter(kv -> kv.getKey().isRight())
                // overwrite with version built using columns if it exists
                .map(kv -> Tuples._2T(kv.getKey(), column_lookups.getOrDefault(kv.getKey(), kv.getValue())))
                .reduce(properties.startArray("dynamic_templates"),
                        Lambdas.wrap_u((acc, t2) -> acc.startObject()
                                .rawField(getFieldNameFromMatchPair(t2._1().right().value()),
                                        t2._2().toString().getBytes()) // (right by construction)
                                .endObject()),
                        (acc1, acc2) -> acc1) // (not actually possible)
                .endArray();

        return templates;
    } catch (IOException e) {
        //Handle in-practice-impossible "IOException"
        return null;
    }
}