Example usage for org.apache.commons.collections4 MapUtils isNotEmpty

List of usage examples for org.apache.commons.collections4 MapUtils isNotEmpty

Introduction

In this page you can find the example usage for org.apache.commons.collections4 MapUtils isNotEmpty.

Prototype

public static boolean isNotEmpty(final Map<?, ?> map) 

Source Link

Document

Null-safe check if the specified map is not empty.

Usage

From source file:io.github.swagger2markup.internal.document.builder.PathsDocumentBuilder.java

private List<ObjectType> buildResponsesSection(PathOperation operation, MarkupDocBuilder docBuilder) {
    Map<String, Response> responses = operation.getOperation().getResponses();
    List<ObjectType> inlineDefinitions = new ArrayList<>();

    MarkupDocBuilder responsesBuilder = copyMarkupDocBuilder();
    applyPathsDocumentExtension(new Context(Position.OPERATION_RESPONSES_BEGIN, responsesBuilder, operation));
    if (MapUtils.isNotEmpty(responses)) {
        List<MarkupTableColumn> responseCols = Arrays.asList(
                new MarkupTableColumn(HTTP_CODE_COLUMN).withWidthRatio(1).withHeaderColumn(false)
                        .withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^1"),
                new MarkupTableColumn(DESCRIPTION_COLUMN).withWidthRatio(15)
                        .withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^15"),
                new MarkupTableColumn(SCHEMA_COLUMN).withWidthRatio(4)
                        .withMarkupSpecifiers(MarkupLanguage.ASCIIDOC, ".^4"));

        List<List<String>> cells = new ArrayList<>();

        Set<String> responseNames = toKeySet(responses, config.getResponseOrdering());
        for (String responseName : responseNames) {
            Response response = responses.get(responseName);

            String schemaContent = NO_CONTENT;
            if (response.getSchema() != null) {
                Property property = response.getSchema();
                Type type = PropertyUtils.getType(property, new DefinitionDocumentResolverFromOperation());

                type = createInlineType(type, RESPONSE + " " + responseName,
                        operation.getId() + " " + RESPONSE + " " + responseName, inlineDefinitions);

                schemaContent = type.displaySchema(markupDocBuilder);
            }/*  w w  w  .  jav  a2s . c om*/

            MarkupDocBuilder descriptionBuilder = copyMarkupDocBuilder();

            descriptionBuilder.text(defaultString(swaggerMarkupDescription(response.getDescription())));

            Map<String, Property> headers = response.getHeaders();
            if (MapUtils.isNotEmpty(headers)) {
                descriptionBuilder.newLine(true).boldText(HEADERS_COLUMN).text(COLON);
                for (Map.Entry<String, Property> header : headers.entrySet()) {
                    descriptionBuilder.newLine(true);
                    Property headerProperty = header.getValue();
                    Type propertyType = PropertyUtils.getType(headerProperty, null);
                    String headerDescription = defaultString(
                            swaggerMarkupDescription(headerProperty.getDescription()));
                    Object defaultValue = PropertyUtils.getDefaultValue(headerProperty);

                    descriptionBuilder.literalText(header.getKey())
                            .text(String.format(" (%s)", propertyType.displaySchema(markupDocBuilder)));

                    if (isNotBlank(headerDescription) || defaultValue != null) {
                        descriptionBuilder.text(COLON);

                        if (isNotBlank(headerDescription) && !headerDescription.endsWith("."))
                            headerDescription += ".";

                        descriptionBuilder.text(headerDescription);

                        if (defaultValue != null) {
                            descriptionBuilder.text(" ").boldText(DEFAULT_COLUMN).text(COLON)
                                    .literalText(Json.pretty(defaultValue));
                        }
                    }
                }
            }

            cells.add(Arrays.asList(boldText(responseName), descriptionBuilder.toString(), schemaContent));
        }

        responsesBuilder.tableWithColumnSpecs(responseCols, cells);
    }
    applyPathsDocumentExtension(new Context(Position.OPERATION_RESPONSES_END, responsesBuilder, operation));
    String responsesContent = responsesBuilder.toString();

    applyPathsDocumentExtension(new Context(Position.OPERATION_RESPONSES_BEFORE, docBuilder, operation));
    if (isNotBlank(responsesContent)) {
        buildSectionTitle(RESPONSES, docBuilder);
        docBuilder.text(responsesContent);
    }
    applyPathsDocumentExtension(new Context(Position.OPERATION_RESPONSES_AFTER, docBuilder, operation));

    return inlineDefinitions;
}

From source file:com.epam.catgenome.manager.GffManagerTest.java

public void checkGenesCorrectness(List<Gene> genes) {
    Assert.assertTrue(genes.stream().allMatch(g -> MapUtils.isNotEmpty(g.getAttributes())));
    Assert.assertTrue(//from   w w  w  .ja  v a  2s . c  o  m
            genes.stream().allMatch(g -> !GeneUtils.isGene(g) || CollectionUtils.isNotEmpty(g.getItems())));
    Assert.assertTrue(genes.stream().allMatch(g -> !GeneUtils.isGene(g)
            || g.getItems().stream().allMatch(i -> MapUtils.isNotEmpty(i.getAttributes()))));
    Assert.assertTrue(genes.stream().allMatch(g -> !GeneUtils.isGene(g)
            || g.getItems().stream().allMatch(i -> CollectionUtils.isNotEmpty(i.getItems()))));
}

From source file:io.cloudslang.lang.compiler.modeller.ExecutableBuilder.java

private String resolveDoReferenceId(String rawReferenceId, Map<String, String> imports, String namespace) {

    int numberOfDelimiters = StringUtils.countMatches(rawReferenceId, NAMESPACE_DELIMITER);
    String resolvedReferenceId;/*from   ww  w .  j  av a  2  s  . co m*/

    if (numberOfDelimiters == 0) {
        // implicit namespace
        resolvedReferenceId = namespace + NAMESPACE_DELIMITER + rawReferenceId;
    } else {
        String prefix = StringUtils.substringBefore(rawReferenceId, NAMESPACE_DELIMITER);
        String suffix = StringUtils.substringAfter(rawReferenceId, NAMESPACE_DELIMITER);
        if (MapUtils.isNotEmpty(imports) && imports.containsKey(prefix)) {
            // expand alias
            resolvedReferenceId = imports.get(prefix) + NAMESPACE_DELIMITER + suffix;
        } else {
            // full path without alias expanding
            resolvedReferenceId = rawReferenceId;
        }
    }

    return resolvedReferenceId;
}

From source file:com.jkoolcloud.tnt4j.streams.configure.sax.ConfigParserHandler.java

private void handleJavaObject(JavaObjectData javaObjectData) throws Exception {
    if (javaObjectData == null) {
        return;/* ww w  .  j ava  2 s  .com*/
    }

    Object obj = Utils.createInstance(javaObjectData.className, javaObjectData.getArgs(),
            javaObjectData.getTypes());

    javaObjectsMap.put(javaObjectData.name, obj);

    if (MapUtils.isNotEmpty(currProperties)) {
        if (obj instanceof TNTStreamOutput) {
            ((TNTStreamOutput<?>) obj).setProperties(currProperties.entrySet());
        }

        currProperties.clear();
    }
}

From source file:org.apache.metron.profiler.bolt.KafkaEmitter.java

@Override
public void emit(ProfileMeasurement measurement, OutputCollector collector) {

    // only need to emit, if there are triage values
    Map<String, Object> triageValues = measurement.getTriageValues();
    if (MapUtils.isNotEmpty(triageValues)) {

        JSONObject message = createMessage(measurement);
        appendTriageValues(measurement, message);
        collector.emit(getStreamId(), new Values(message));

        LOG.debug("Emitted measurement; stream={}, profile={}, entity={}, period={}, start={}, end={}",
                getStreamId(), measurement.getProfileName(), measurement.getEntity(),
                measurement.getPeriod().getPeriod(), measurement.getPeriod().getStartTimeMillis(),
                measurement.getPeriod().getEndTimeMillis());

    } else {//from w  w w.  j a  va  2s  .  c o  m

        LOG.debug(
                "No triage values, nothing to emit; stream={}, profile={}, entity={}, period={}, start={}, end={}",
                getStreamId(), measurement.getProfileName(), measurement.getEntity(),
                measurement.getPeriod().getPeriod(), measurement.getPeriod().getStartTimeMillis(),
                measurement.getPeriod().getEndTimeMillis());
    }
}

From source file:org.codice.ddf.opensearch.source.OpenSearchSource.java

@Override
public SourceResponse query(QueryRequest queryRequest) throws UnsupportedQueryException {
    String methodName = "query";
    LOGGER.trace(methodName);// w w  w.j  a va  2  s.c  o  m

    final SourceResponse response;

    Subject subject = null;
    if (queryRequest.hasProperties()) {
        Object subjectObj = queryRequest.getProperties().get(SecurityConstants.SECURITY_SUBJECT);
        subject = (Subject) subjectObj;
    }

    Query query = queryRequest.getQuery();
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Received query: {}", query);
        FilterTransformer transform = new FilterTransformer();
        transform.setIndentation(2);
        try {
            LOGGER.trace(transform.transform(query));
        } catch (TransformerException e) {
            LOGGER.debug("Error transforming query to XML", e);
        }
    }

    final OpenSearchFilterVisitorObject openSearchFilterVisitorObject = (OpenSearchFilterVisitorObject) query
            .accept(openSearchFilterVisitor, new OpenSearchFilterVisitorObject());

    final ContextualSearch contextualSearch = openSearchFilterVisitorObject.getContextualSearch();
    final SpatialSearch spatialSearch = createCombinedSpatialSearch(
            openSearchFilterVisitorObject.getPointRadiusSearches(),
            openSearchFilterVisitorObject.getGeometrySearches(), numMultiPointRadiusVertices,
            distanceTolerance);
    final TemporalFilter temporalSearch = openSearchFilterVisitorObject.getTemporalSearch();
    final String idSearch = StringUtils.defaultIfEmpty((String) queryRequest.getPropertyValue(Metacard.ID),
            openSearchFilterVisitorObject.getId());

    final Map<String, String> searchPhraseMap = contextualSearch == null ? new HashMap<>()
            : contextualSearch.getSearchPhraseMap();

    // OpenSearch endpoints only support certain keyword, temporal, and spatial searches. The
    // OpenSearchSource additionally supports an id search when no other search criteria is
    // specified.
    if (MapUtils.isNotEmpty(searchPhraseMap) || spatialSearch != null || temporalSearch != null) {
        if (StringUtils.isNotEmpty(idSearch)) {
            LOGGER.debug(
                    "Ignoring the id search {}. Querying the source with the keyword, temporal, and/or spatial OpenSearch parameters",
                    idSearch);
        }

        final WebClient restWebClient = factory.getWebClientForSubject(subject);
        if (restWebClient == null) {
            throw new UnsupportedQueryException("Unable to create restWebClient");
        }
        response = doOpenSearchQuery(queryRequest, subject, spatialSearch, temporalSearch, searchPhraseMap,
                restWebClient);
    } else if (StringUtils.isNotEmpty(idSearch)) {
        final WebClient restWebClient = newRestClient(query, idSearch, false, subject);
        if (restWebClient == null) {
            throw new UnsupportedQueryException("Unable to create restWebClient");
        }

        response = doQueryById(queryRequest, restWebClient);
    } else {
        LOGGER.debug(
                "The OpenSearch Source only supports id searches or searches with certain keyword, \"{}\" temporal, or \"{}\" spatial criteria, but the query was {}. See the documentation for more details about supported searches.",
                OpenSearchConstants.SUPPORTED_TEMPORAL_SEARCH_TERM,
                OpenSearchConstants.SUPPORTED_SPATIAL_SEARCH_TERM, query);
        throw new UnsupportedQueryException(
                "OpenSearch query parameters could not be created from the query criteria.");
    }

    setSourceId(response);

    LOGGER.trace(methodName);

    return response;
}

From source file:org.craftercms.commons.config.YamlConfiguration.java

protected void buildConfig(Map<String, Object> yamlObj) {
    ImmutableNode.Builder root = new ImmutableNode.Builder();

    if (MapUtils.isNotEmpty(yamlObj)) {
        buildConfigFromMap(yamlObj, root);
    }//from w  w  w . j  a v  a 2s. c  o  m

    addNodes(null, root.create().getChildren());
}

From source file:org.craftercms.commons.http.HttpUtils.java

/**
 * Builds a query string from the specified params. The param names are always encoded, but the values are only encoded
 * if {@code encodeValues} is true./*www. j a  v a  2s  .c o m*/
 *
 * @param queryParams   the params to build the query string with
 * @param charset       the charset to use for URL encoding
 * @param encodeValues  if the param values should be encoded
 *
 * @return the query string
 */
public static String getQueryStringFromParams(MultiValueMap<String, String> queryParams, String charset,
        boolean encodeValues) throws UnsupportedEncodingException {
    StringBuilder queryString = new StringBuilder();

    if (MapUtils.isNotEmpty(queryParams)) {
        for (Map.Entry<String, List<String>> entry : queryParams.entrySet()) {
            String paramName = URLEncoder.encode(entry.getKey(), charset);

            for (String paramValue : entry.getValue()) {
                if (queryString.length() > 0) {
                    queryString.append('&');
                }

                if (encodeValues) {
                    paramValue = URLEncoder.encode(paramValue, charset);
                }

                queryString.append(paramName).append('=').append(paramValue);
            }
        }

        queryString.insert(0, '?');
    }

    return queryString.toString();
}

From source file:org.craftercms.commons.jackson.JacksonUtils.java

/**
 * Creates a module from a set of serializers and deserializes.
 *
 * @param serializers   the serializers, can be null or empty
 * @param deserializers the deserializers, can be null or empty
 *
 * @return a non-reusable Jackson module composed of the specified serializers and deserializers
 *///  w w  w . j  a v a2  s  .  com
@SuppressWarnings("unchecked")
public static final Module createModule(List<JsonSerializer<?>> serializers,
        Map<Class<?>, JsonDeserializer<?>> deserializers) {
    SimpleModule module = new SimpleModule();

    if (CollectionUtils.isNotEmpty(serializers)) {
        for (JsonSerializer<?> serializer : serializers) {
            module.addSerializer(serializer);
        }
    }

    if (MapUtils.isNotEmpty(deserializers)) {
        for (Map.Entry<Class<?>, JsonDeserializer<?>> entry : deserializers.entrySet()) {
            Class<Object> type = (Class<Object>) entry.getKey();
            JsonDeserializer<Object> des = (JsonDeserializer<Object>) entry.getValue();

            module.addDeserializer(type, des);
        }
    }

    return module;
}

From source file:org.craftercms.commons.mongo.JongoFactoryBean.java

@Override
protected Jongo createInstance() throws Exception {
    DB db = mongo.getDB(dbName);//  w  ww  .  ja v  a 2 s.co m
    JacksonMapper.Builder builder = new JacksonMapper.Builder();
    builder.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
    if (CollectionUtils.isNotEmpty(serializers) || MapUtils.isNotEmpty(deserializers)) {
        builder.registerModule(JacksonUtils.createModule(serializers, deserializers));
    }
    return new Jongo(db, builder.build());
}