Example usage for org.apache.commons.lang StringUtils defaultIfBlank

List of usage examples for org.apache.commons.lang StringUtils defaultIfBlank

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils defaultIfBlank.

Prototype

public static String defaultIfBlank(String str, String defaultStr) 

Source Link

Document

Returns either the passed in String, or if the String is whitespace, empty ("") or null, the value of defaultStr.

Usage

From source file:com.microfocus.plugins.attribution.datamodel.services.impl.DependenciesServiceImpl.java

@Override
public List<ProjectDependency> getProjectDependencies(MavenProject project, Settings settings,
        ArtifactRepository localRepository, DependencyOverride[] dependencyOverrides) {
    List<ProjectDependency> projectDependencies = new ArrayList<ProjectDependency>();
    Map<String, DependencyOverride> projectDependencyOverrides = new HashMap<String, DependencyOverride>();

    if (dependencyOverrides != null) {
        for (DependencyOverride dependencyOverride : dependencyOverrides) {
            projectDependencyOverrides.put(dependencyOverride.getForDependency(), dependencyOverride);
        }/*  www.ja va 2 s . com*/
    }

    RepositoryUtils repoUtils = new RepositoryUtils(log, wagonManager, settings, mavenProjectBuilder, factory,
            resolver, project.getRemoteArtifactRepositories(), project.getPluginArtifactRepositories(),
            localRepository, repositoryMetadataManager);
    DependencyNode dependencyNode = resolveProject(project);
    Dependencies dependencies = new Dependencies(project, dependencyNode, classesAnalyzer);

    try {
        List<Artifact> alldeps = dependencies.getAllDependencies();

        if (log.isInfoEnabled()) {
            System.out.print("[INFO] Reading dependency information from available repositories.");
        }

        for (Artifact artifact : alldeps) {
            MavenProject pluginProject = mavenProjectBuilder.buildFromRepository(artifact,
                    project.getRemoteArtifactRepositories(), localRepository);
            MavenProject artifactProject = repoUtils.getMavenProjectFromRepository(artifact);

            String projectUrl = pluginProject.getUrl();
            List<ProjectDependencyLicense> licenses = DependencyUtils
                    .toProjectLicenses(artifactProject.getLicenses());
            List<String> downloadUrls = new ArrayList<String>();

            for (ArtifactRepository artifactRepository : artifactProject.getRemoteArtifactRepositories()) {
                String downloadUrl = repoUtils.getDependencyUrlFromRepository(artifact, artifactRepository);
                if (dependencyExistsInRepo(repoUtils, artifactRepository, artifact)) {
                    downloadUrls.add(downloadUrl);
                }

                if (log.isInfoEnabled()) {
                    System.out.print('.');
                }
            }

            DependencyOverride dependencyOverride = projectDependencyOverrides
                    .get(artifact.getGroupId() + ":" + artifact.getArtifactId());
            if (dependencyOverride != null) {
                if (StringUtils.isNotBlank(dependencyOverride.getProjectUrl())) {
                    projectUrl = dependencyOverride.getProjectUrl();
                }

                if (StringUtils.isNotBlank(dependencyOverride.getDownloadUrl())) {
                    downloadUrls = Arrays.asList(dependencyOverride.getDownloadUrl());
                }

                if (dependencyOverride.getLicense() != null) {
                    licenses = Arrays.asList(dependencyOverride.getLicense());
                }
            }

            String name = StringUtils.defaultIfBlank(artifactProject.getName(), artifact.getArtifactId());

            ProjectDependency dependency = new ProjectDependency();
            dependency.setGroupId(artifact.getGroupId());
            dependency.setArtifactId(artifact.getArtifactId());
            dependency.setVersion(artifact.getVersion());
            dependency.setProjectUrl(projectUrl);
            dependency.setType(artifact.getType());
            dependency.setLicenses(licenses);
            dependency.setName(name);
            dependency.setDownloadUrls(downloadUrls);

            projectDependencies.add(dependency);
        }

        System.out.println(); // End with a carriage return, so normal logging can continue
    } catch (ProjectBuildingException e) {
        throw new DataModelException("An error occurred building the list of project dependencies.", e);
    }

    Collections.sort(projectDependencies, byName());

    return projectDependencies;
}

From source file:com.openshift.internal.restclient.capability.resources.DockerRegistryImageStreamImportCapability.java

private DockerResponse retrieveMetaData(HttpClient client, String token, DockerImageURI uri) throws Exception {
    String regUri = String.format("%s/%s/%s/manifests/%s", DEFAULT_DOCKER_REGISTRY,
            StringUtils.defaultIfBlank(uri.getUserName(), "library"), uri.getName(), uri.getTag());
    Request request = client.newRequest(regUri);
    if (token != null) {
        request.header(PROPERTY_AUTHORIZATION, String.format("%s %s", AUTHORIZATION_BEARER, token));

    }/*  w  w  w  . ja v a  2 s .  c  om*/
    LOG.debug("retrieveMetaData uri: " + regUri);
    ContentResponse response = request.send();
    LOG.debug("retrieveMetaData response: " + response.toString());
    switch (response.getStatus()) {
    case STATUS_OK:
        return new DockerResponse(DockerResponse.DATA, response.getContentAsString());
    case STATUS_UNAUTHORIZED:
        return new DockerResponse(DockerResponse.AUTH, response.getHeaders().get(HttpHeader.WWW_AUTHENTICATE));
    }
    LOG.info("Unable to retrieve docker meta data: " + response.toString());
    return null;
}

From source file:net.di2e.ecdr.commons.query.CDRQueryImpl.java

protected void populateResponseFormat(MultivaluedMap<String, String> queryParameters) {
    String format = queryParameters.getFirst(SearchConstants.FORMAT_PARAMETER);
    responseFormat = StringUtils.defaultIfBlank(format,
            queryCriteria.getQueryConfiguration().getDefaultResponseFormat());
}

From source file:adalid.commons.velocity.VelocityEngineer.java

public static StringWriter merge(VelocityContext context, String tempname, String encoding) throws Exception {
    encoding = StringUtils.defaultIfBlank(encoding, getTemplateEncoding(tempname));
    Template template = Velocity.getTemplate(tempname, encoding);
    StringWriter sw = new StringWriter();
    template.merge(context, sw);//w  w w  . j  av  a2  s  .c o m
    return sw;
}

From source file:com.kibana.multitenancy.plugin.KibanaUserReindexFilter.java

private String getRequestedIndex(RestRequest request) {
    String uri = StringUtils.defaultIfBlank(request.uri(), "");
    String[] splitUri = uri.split("/");

    if (splitUri.length > 0)
        return uri.split("/")[1];
    else/*from   w  w w. jav  a 2  s .  co m*/
        return "";
}

From source file:net.grinder.console.ConsoleFoundationEx.java

private String getConsoleInfo() {
    ConsoleProperties consoleProperties = m_container.getComponent(ConsoleProperties.class);
    return StringUtils.defaultIfBlank(consoleProperties.getConsoleHost(), "localhost") + ":"
            + consoleProperties.getConsolePort();
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.legacyExcel.importer.ExcelImportUtilities.java

/**
 * Creates a NumberAV object from the attrValue for the given number attribute type.
 * @param at The attribute to which the created number should be linked.
 * @param attrValue Cell value holder which contains the relevant number value
 * @param valueOverride an override value for the actual cell content. If this String is non-null/empty and non-whitespace, it will used in the NumberAV, regardless of the cell content in attrValue!
 * @return A number attribute value object containing the value from attrValue or valueOverride, or <code>null</code> if no number could be parsed
 *///from   www  .j  ava 2 s .  com
@SuppressWarnings("boxing")
private static NumberAV createNumberAV(NumberAT at, CellValueHolder attrValue, String valueOverride) {
    NumberAV numberV = new NumberAV();
    Double cell = null;
    // if valueOverride is null, use attrValue as "default value"
    String value = StringUtils.defaultIfBlank(valueOverride, attrValue.getAttributeValue());

    try {
        cell = contentAsDouble(value);
    } catch (NumberFormatException ex) {
        String warnMessage = "Cell [" + getCellRef(attrValue.getOriginCell()) + "]  Ignoring value " + value
                + " for attribute type " + at.getName() + " due to error:" + ex.getMessage();
        getProcessingLog().warn(warnMessage);
        attrValue.addProblem(ProblemMarker.WARNING, warnMessage);
        throw new IllegalArgumentException("\"" + value + "\" is not a number", ex);
    } catch (IllegalStateException ex) {
        String warnMessage = "Cell [" + getCellRef(attrValue.getOriginCell()) + "]  Ignoring value " + value
                + " for attribute type " + at.getName() + " due to error:" + ex.getMessage();
        getProcessingLog().warn(warnMessage);
        attrValue.addProblem(ProblemMarker.WARNING, warnMessage);
        throw new IllegalArgumentException(ex);
    }

    if (cell != null) {
        try {
            BigDecimal v = BigDecimal.valueOf(cell);
            numberV.setValue(v);

            return numberV;
        } catch (NumberFormatException e) {
            LOGGER.warn("Couldn't translate a Double into a BigDecimal");
        }
    }
    return null;
}

From source file:io.fabric8.elasticsearch.plugin.kibana.KibanaUtils.java

/**
 * Gets the default index-pattern if not set or set on the wrong version of 
 * Kibana or empty if it doesnt need to be set
 * /*from  www .  j  a v a2s  .com*/
 * @param kibanaIndex The index to Check
 * @param defaultIfNotSet The value to use if not set
 * @return The default index-pattern
 */
public String getDefaultIndexPattern(String kibanaIndex, String defaultIfNotSet) {
    // default if config doesnt exist or is not set
    // the value if config doesnt exist but previous does
    try {
        SearchResponse response = pluginClient.search(kibanaIndex, "config");
        final long totalHits = response.getHits().getTotalHits();
        if (totalHits == 0) {
            return defaultIfNotSet;
        } else if (totalHits == 1) {
            try {
                return defaultPath.read(response.getHits().getHits()[0].getSourceAsString());
            } catch (PathNotFoundException e) {
                return defaultIfNotSet;
            }
        }
        Map<Version, String> patternMap = new HashMap<>();
        for (SearchHit hit : response.getHits().getHits()) {
            String source = hit.getSourceAsString();
            String defaultIndex = defaultIfNotSet;
            try {
                defaultIndex = defaultPath.read(source);
            } catch (PathNotFoundException e) {
                // skip
            }
            patternMap.put(Version.valueOf(hit.getId()), defaultIndex);
        }
        List<Version> versions = new ArrayList<>(patternMap.keySet());
        Collections.sort(versions);
        if (versions.contains(defaultVersion)) {
            return StringUtils.defaultIfBlank(patternMap.get(defaultVersion), "");
        } else {
            return patternMap.get(versions.get(versions.size() - 1));
        }
    } catch (IndexNotFoundException e) {
        return defaultIfNotSet;
    }
}

From source file:com.fortify.processrunner.cli.CLIOptionDefinition.java

public String getDefaultValueDescription() {
    return StringUtils.defaultIfBlank(defaultValueDescription, getValueDescription(getDefaultValue()));
}

From source file:jenkins.metrics.api.MetricsAccessKey.java

public boolean isOriginAllowed(String origin) {
    if (originRegexs == null) {
        // idempotent
        if (StringUtils.equals("*", StringUtils.defaultIfBlank(origins, "*").trim())) {
            originRegexs = new String[] { ".*" };
        } else {/*w  ww  . ja v  a2s.  c o m*/
            List<String> regexs = new ArrayList<String>();
            for (String pattern : StringUtils.split(origins, " ,")) {
                if (StringUtils.isBlank(pattern)) {
                    continue;
                }
                String[] parts = StringUtils.split(pattern, ":");
                if (parts.length > 3) {
                    regexs.add(
                            globToRegex(parts[0]) + ":" + globToRegex(parts[1]) + ":" + globToRegex(parts[2]));
                } else if (parts.length == 3) {
                    regexs.add(
                            globToRegex(parts[0]) + ":" + globToRegex(parts[1]) + ":" + globToRegex(parts[2]));
                } else if (parts.length == 2) {
                    if (parts[1].matches("^\\d{1,5}$")) {
                        // it's a port
                        regexs.add(".*:" + globToRegex(parts[0]) + ":" + parts[1]);
                    } else {
                        // it's a hostname
                        regexs.add(globToRegex(parts[0]) + ":" + globToRegex(parts[1]) + "(:.*)?");
                    }
                } else if (parts.length == 1) {
                    // assume it matches the host name only
                    regexs.add(".*:" + globToRegex(pattern) + "(:.*)?");
                }
            }
            originRegexs = regexs.toArray(new String[regexs.size()]);
        }

    }
    for (String regex : originRegexs) {
        if (origin.matches(regex)) {
            return true;
        }
    }
    return false;
}