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

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

Introduction

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

Prototype

public static <T extends CharSequence> T defaultIfBlank(final T str, final T defaultStr) 

Source Link

Document

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

 StringUtils.defaultIfBlank(null, "NULL")  = "NULL" StringUtils.defaultIfBlank("", "NULL")    = "NULL" StringUtils.defaultIfBlank(" ", "NULL")   = "NULL" StringUtils.defaultIfBlank("bat", "NULL") = "bat" StringUtils.defaultIfBlank("", null)      = null 

Usage

From source file:org.phenotips.data.permissions.internal.DefaultPermissionsConfiguration.java

@Override
public String getDefaultVisibility() {
    DocumentReference preferencesDocument = this.resolver.resolve(TEMPLATE_DOCUMENT);
    DocumentReference configurationClassDocument = this.resolver.resolve(Visibility.CLASS_REFERENCE);
    String visibilityName = (String) this.dab.getProperty(new ObjectPropertyReference("visibility",
            new BaseObjectReference(configurationClassDocument, 0, preferencesDocument)));
    return StringUtils.defaultIfBlank(visibilityName, null);
}

From source file:org.phenotips.data.permissions.internal.RightsUpdateEventListener.java

private Visibility getVisibility(XWikiDocument doc) {
    String visibility = null;/*from   ww w . jav  a2 s . c om*/
    BaseObject visibilityObj = doc.getXObject(Visibility.CLASS_REFERENCE);
    if (visibilityObj != null) {
        visibility = visibilityObj.getStringValue("visibility");
    }
    return this.manager.resolveVisibility(StringUtils.defaultIfBlank(visibility, "private"));
}

From source file:org.phenotips.ontology.internal.solr.AbstractOBOSolrOntologyService.java

/**
 * Add an ontology to the index./*w ww  .ja v  a2s . c o  m*/
 *
 * @param ontologyUrl the address from where to get the ontology file
 * @return {@code 0} if the indexing succeeded, {@code 1} if writing to the Solr server failed, {@code 2} if the
 *         specified URL is invalid
 */
protected int index(String ontologyUrl) {
    String realOntologyUrl = StringUtils.defaultIfBlank(ontologyUrl, getDefaultOntologyLocation());

    SolrUpdateGenerator generator = new SolrUpdateGenerator();
    Map<String, Double> fieldSelection = new HashMap<String, Double>();
    Map<String, TermData> data = generator.transform(realOntologyUrl, fieldSelection);
    if (data == null) {
        return 2;
    }
    try {
        Collection<SolrInputDocument> termBatch = new HashSet<SolrInputDocument>();
        Iterator<Map.Entry<String, TermData>> dataIterator = data.entrySet().iterator();
        int batchCounter = 0;
        while (dataIterator.hasNext()) {
            /* Resetting when the batch fills */
            if (batchCounter == getSolrDocsPerBatch()) {
                commitTerms(termBatch);
                termBatch = new HashSet<>();
                batchCounter = 0;
            }
            Map.Entry<String, TermData> item = dataIterator.next();
            SolrInputDocument doc = new SolrInputDocument();
            for (Map.Entry<String, Collection<String>> property : item.getValue().entrySet()) {
                String name = property.getKey();
                for (String value : property.getValue()) {
                    doc.addField(name, value, ParameterPreparer.DEFAULT_BOOST.floatValue());
                }
            }
            termBatch.add(doc);
            batchCounter++;
        }
        commitTerms(termBatch);
        return 0;
    } catch (SolrServerException ex) {
        this.logger.warn("Failed to index ontology: {}", ex.getMessage());
    } catch (IOException ex) {
        this.logger.warn("Failed to communicate with the Solr server while indexing ontology: {}",
                ex.getMessage());
    } catch (OutOfMemoryError ex) {
        this.logger.warn("Failed to add terms to the Solr. Ran out of memory. {}", ex.getMessage());
    }
    return 1;
}

From source file:org.phenotips.ontology.internal.solr.HumanPhenotypeOntology.java

/**
 * Add an ontology to the index.//w w w .j av  a2s. c o  m
 *
 * @param ontologyUrl the address from where to get the ontology file
 * @return {@code 0} if the indexing succeeded, {@code 1} if writing to the Solr server failed, {@code 2} if the
 *         specified URL is invalid
 */
protected int index(String ontologyUrl) {
    String realOntologyUrl = StringUtils.defaultIfBlank(ontologyUrl, getDefaultOntologyLocation());

    SolrUpdateGenerator generator = new SolrUpdateGenerator();
    Map<String, Double> fieldSelection = new HashMap<String, Double>();
    Map<String, TermData> data = generator.transform(realOntologyUrl, fieldSelection);
    if (data == null) {
        return 2;
    }
    Collection<SolrInputDocument> allTerms = new HashSet<SolrInputDocument>();
    for (Map.Entry<String, TermData> item : data.entrySet()) {
        SolrInputDocument doc = new SolrInputDocument();
        for (Map.Entry<String, Collection<String>> property : item.getValue().entrySet()) {
            String name = property.getKey();
            for (String value : property.getValue()) {
                doc.addField(name, value, ParameterPreparer.DEFAULT_BOOST.floatValue());
            }
        }
        allTerms.add(doc);
    }
    try {
        this.externalServicesAccess.getServer().add(allTerms);
        this.externalServicesAccess.getServer().commit();
        this.externalServicesAccess.getCache().removeAll();
        return 0;
    } catch (SolrServerException ex) {
        this.logger.warn("Failed to index ontology: {}", ex.getMessage());
    } catch (IOException ex) {
        this.logger.warn("Failed to communicate with the Solr server while indexing ontology: {}",
                ex.getMessage());
    }
    return 1;
}

From source file:org.phenotips.tool.xarimporter.ImportMojo.java

private void toExtension(DefaultLocalExtension extension, Model model, ComponentManager componentManager)
        throws ComponentLookupException {
    extension.setName(getPropertyString(model, MPNAME_NAME, model.getName()));
    extension.setSummary(getPropertyString(model, MPNAME_SUMMARY, model.getDescription()));
    extension.setWebsite(getPropertyString(model, MPNAME_WEBSITE, model.getUrl()));

    // authors/*from   ww w  . j a v a 2 s . c o  m*/
    for (Developer developer : model.getDevelopers()) {
        URL authorURL = null;
        if (developer.getUrl() != null) {
            try {
                authorURL = new URL(developer.getUrl());
            } catch (MalformedURLException e) {
                this.getLog().warn(
                        "Invalid URL for developer [" + developer.getId() + "]: [" + developer.getUrl() + "]");
            }
        }

        extension.addAuthor(new DefaultExtensionAuthor(
                StringUtils.defaultIfBlank(developer.getName(), developer.getId()), authorURL));
    }

    // licenses
    ExtensionLicenseManager licenseManager = componentManager.getInstance(ExtensionLicenseManager.class);
    for (License license : model.getLicenses()) {
        extension.addLicense(getExtensionLicense(license, licenseManager));
    }

    // features
    String featuresString = getProperty(model, MPNAME_FEATURES);
    if (StringUtils.isNotBlank(featuresString)) {
        featuresString = featuresString.replaceAll("[\r\n]", "");
        ConverterManager converter = componentManager.getInstance(ConverterManager.class);
        extension.setFeatures(converter.<Collection<String>>convert(List.class, featuresString));
    }

    // dependencies
    for (Dependency mavenDependency : model.getDependencies()) {
        if (!mavenDependency.isOptional() && (mavenDependency.getScope().equals("compile")
                || mavenDependency.getScope().equals("runtime"))) {
            extension.addDependency(new DefaultExtensionDependency(
                    mavenDependency.getGroupId() + ':' + mavenDependency.getArtifactId(),
                    new DefaultVersionConstraint(mavenDependency.getVersion())));
        }
    }
}

From source file:org.phenotips.vocabulary.internal.GeneNomenclature.java

private SolrQuery produceDynamicSolrParams(Map<String, String> staticOptions, String originalQuery,
        Integer rows, String sort, String customFilter) {
    String escapedQuery = ClientUtils.escapeQueryChars(originalQuery.trim());

    SolrQuery params = new SolrQuery(escapedQuery);
    for (Map.Entry<String, String> option : staticOptions.entrySet()) {
        params.set(option.getKey(), option.getValue());
    }/*ww w  .j  a  va2  s.  c  o m*/
    params.setRows(rows);
    if (StringUtils.isNotBlank(sort)) {
        params.add(CommonParams.SORT, sort);
    }
    params.add(CommonParams.FQ, StringUtils.defaultIfBlank(customFilter, "status:Approved"));
    return params;
}

From source file:org.phenotips.vocabulary.internal.solr.AbstractCSVSolrVocabulary.java

/**
 * Add a vocabulary to the index.//from   ww w  . j a va2 s .  com
 *
 * @param sourceUrl the URL to be indexed
 * @return {@code 0} if the indexing succeeded, {@code 1} if writing to the Solr server failed, {@code 2} if the
 *         specified URL is invalid
 */
protected int index(String sourceUrl) {
    String url = StringUtils.defaultIfBlank(sourceUrl, getDefaultSourceLocation());
    Collection<SolrInputDocument> data = null;
    try {
        data = load(new URL(url));
    } catch (MalformedURLException e) {
        return 2;
    }
    if (data == null) {
        return 2;
    }
    try {
        Collection<SolrInputDocument> termBatch = new HashSet<>();
        Iterator<SolrInputDocument> dataIterator = data.iterator();
        int batchCounter = 0;
        while (dataIterator.hasNext()) {
            /* Resetting when the batch fills */
            if (batchCounter == getSolrDocsPerBatch()) {
                commitTerms(termBatch);
                termBatch = new HashSet<>();
                batchCounter = 0;
            }
            SolrInputDocument item = dataIterator.next();
            extendTerm(new SolrVocabularyInputTerm(item, this));
            termBatch.add(item);
            batchCounter++;
        }
        commitTerms(termBatch);
        return 0;
    } catch (SolrServerException ex) {
        this.logger.warn("Failed to index vocabulary: {}", ex.getMessage());
    } catch (IOException ex) {
        this.logger.warn("Failed to communicate with the Solr server while indexing vocabulary: {}",
                ex.getMessage());
    } catch (OutOfMemoryError ex) {
        this.logger.warn("Failed to add terms to the Solr. Ran out of memory. {}", ex.getMessage());
    }
    return 1;
}

From source file:org.phenotips.vocabulary.internal.solr.AbstractOBOSolrVocabulary.java

/**
 * Load vocabulary data from a provided source url.
 *
 * @param sourceUrl the address from where to get the vocabulary source file
 * @return vocabulary data, if exists/*w  ww.  j a  v  a 2s  . c o  m*/
 */
protected Map<String, TermData> load(final String sourceUrl) {
    String realOntologyUrl = StringUtils.defaultIfBlank(sourceUrl, getDefaultSourceLocation());

    SolrUpdateGenerator generator = new SolrUpdateGenerator();
    Map<String, Double> fieldSelection = new HashMap<>();
    return generator.transform(realOntologyUrl, fieldSelection);
}

From source file:org.phenotips.vocabulary.internal.solr.HumanPhenotypeOntology.java

private SolrQuery addDynamicQueryParameters(String originalQuery, Integer rows, String sort, String customFq,
        boolean isId, SolrQuery query) {
    String queryString = originalQuery.trim();
    String escapedQuery = ClientUtils.escapeQueryChars(queryString);
    if (isId) {/*  w  w w.  j av a  2s . co  m*/
        query.setFilterQueries(StringUtils.defaultIfBlank(customFq,
                new MessageFormat("id:{0} alt_id:{0}").format(new String[] { escapedQuery })));
    } else {
        query.setFilterQueries(StringUtils.defaultIfBlank(customFq, "term_category:HP\\:0000118"));
    }
    query.setQuery(escapedQuery);
    query.set(SpellingParams.SPELLCHECK_Q, queryString);
    query.setRows(rows);
    if (StringUtils.isNotBlank(sort)) {
        for (String sortItem : sort.split("\\s*,\\s*")) {
            query.addSort(StringUtils.substringBefore(sortItem, " "),
                    sortItem.endsWith(" desc") || sortItem.startsWith("-") ? ORDER.desc : ORDER.asc);
        }
    }
    return query;
}

From source file:org.phenotips.vocabulary.internal.solr.MendelianInheritanceInMan.java

private SolrQuery addDynamicQueryParameters(String originalQuery, Integer rows, String sort, String customFq,
        SolrQuery query) {/*from   w  w  w .j av  a2 s  .  c  om*/
    String queryString = originalQuery.trim();
    String escapedQuery = ClientUtils.escapeQueryChars(queryString);
    query.setFilterQueries(StringUtils.defaultIfBlank(customFq, "+type:disorder"));
    query.setQuery(escapedQuery);
    query.set(SpellingParams.SPELLCHECK_Q, queryString);
    String lastWord = StringUtils.substringAfterLast(escapedQuery, " ");
    if (StringUtils.isBlank(lastWord)) {
        lastWord = escapedQuery;
    }
    lastWord += "*";
    query.set(DisMaxParams.BQ,
            String.format(
                    "nameSpell:%1$s^20 short_name:%1$s^20 synonymSpell:%1$s^12 text:%1$s^1 textSpell:%1$s^2",
                    lastWord));
    query.setRows(rows);
    if (StringUtils.isNotBlank(sort)) {
        for (String sortItem : sort.split("\\s*,\\s*")) {
            query.addSort(StringUtils.substringBefore(sortItem, " "),
                    sortItem.endsWith(" desc") || sortItem.startsWith("-") ? ORDER.desc : ORDER.asc);
        }
    }
    return query;
}