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.neo4j.helpers.HostnamePort.java

public HostnamePort(String hostnamePort) throws IllegalArgumentException {
    Objects.requireNonNull(hostnamePort);

    String[] parts = splitHostAndPort(hostnamePort);
    if (parts.length == 1) {
        host = StringUtils.defaultIfBlank(parts[0], null);
        ports = new int[] { 0, 0 };
    } else if (parts.length == 2) {
        host = StringUtils.defaultIfBlank(parts[0], null);

        String[] portStrings = parts[1].split("-");
        ports = new int[2];

        if (portStrings.length == 1) {
            ports[0] = ports[1] = Integer.parseInt(portStrings[0]);
        } else if (portStrings.length == 2) {
            ports[0] = Integer.parseInt(portStrings[0]);
            ports[1] = Integer.parseInt(portStrings[1]);
        } else {/*  w w w  .  ja  v  a 2  s .  co m*/
            throw new IllegalArgumentException(
                    format("Cannot have more than two port ranges: %s", hostnamePort));
        }
    } else {
        throw new IllegalArgumentException(hostnamePort);
    }
}

From source file:org.openestate.io.is24_csv.Is24CsvRecord.java

public void setKontaktLand(String value) {
    this.set(FIELD_KONTAKT_LAND,
            StringUtils.defaultIfBlank(Is24CsvFormat.getCountryCode(value), Locale.GERMANY.getISO3Country()));
}

From source file:org.openestate.io.is24_csv.Is24CsvRecord.java

public void setObjektLand(String value) {
    this.set(FIELD_OBJEKT_LAND,
            StringUtils.defaultIfBlank(Is24CsvFormat.getCountryCode(value), Locale.GERMANY.getISO3Country()));
}

From source file:org.openestate.is24.restapi.utils.Resource.java

/**
 * Load resource informations from the response {@link Message} of a created
 * object./*from   www  .j a va  2s . co  m*/
 *
 * @param message
 * message from the body of the HTTP response
 *
 * @return
 * resource informations
 */
public static Resource getCreatedResource(Message message) {
    if (message == null)
        return null;
    if (!MessageCode.MESSAGE_RESOURCE_CREATED.equals(message.getMessageCode()))
        return null;

    String txt = StringUtils.trimToNull(message.getMessage());
    if (txt == null)
        return null;

    //LOGGER.debug( "Parse response message after creation." );
    //LOGGER.debug( "> " + txt );

    // parse resource type and ID from a text like:
    // Resource [REALESTATE] with id [123456] has been created.
    if (CREATED_PATTERN == null)
        CREATED_PATTERN = Pattern.compile("^.*\\[([\\w]+)\\].*\\[([\\d]+)\\].*");
    Matcher m = CREATED_PATTERN.matcher(txt);
    if (!m.find())
        return null;
    return new Resource(StringUtils.trimToNull(m.group(1)),
            Long.parseLong(StringUtils.defaultIfBlank(StringUtils.trimToNull(m.group(2)), "0")));
}

From source file:org.openestate.is24.restapi.utils.Resource.java

/**
 * Load resource informations from the response {@link Message}.
 *
 * @param message//from w ww. ja v  a  2  s  . c  om
 * message from the body of the HTTP response
 *
 * @return
 * resource informations
 */
public static Resource getMessageResource(Message message) {
    if (message == null)
        return null;
    //if (!MessageCode.MESSAGE_RESOURCE_CREATED.equals( message.getMessageCode() ))
    //  return null;

    String txt = StringUtils.trimToNull(message.getMessage());
    if (txt == null)
        return null;

    //LOGGER.debug( "Parse response message after creation." );
    //LOGGER.debug( "> " + txt );

    // parse resource type and ID from a text like:
    // The operation for your request causes a conflict. [MESSAGE: duplicated contactDetails:59476923]
    if (MESSAGE_PATTERN == null)
        MESSAGE_PATTERN = Pattern.compile("^.*\\[MESSAGE:([^\\]]*):([\\d]+)\\].*");
    Matcher m = MESSAGE_PATTERN.matcher(txt);
    if (!m.find())
        return null;
    return new Resource(StringUtils.trimToNull(m.group(1)),
            Long.parseLong(StringUtils.defaultIfBlank(StringUtils.trimToNull(m.group(2)), "0")));
}

From source file:org.phenotips.configuration.internal.global.GlobalRecordConfiguration.java

@Override
public DocumentReference getPhenotypeMapping() {
    try {/*  w  ww.  j ava  2s .c om*/
        String mapping = "PhenoTips.PhenotypeMapping";
        BaseObject settings = getGlobalConfigurationObject();
        mapping = StringUtils.defaultIfBlank(settings.getStringValue("phenotypeMapping"), mapping);
        DocumentReferenceResolver<String> resolver = ComponentManagerRegistry.getContextComponentManager()
                .getInstance(DocumentReferenceResolver.TYPE_STRING, "current");
        return resolver.resolve(mapping);
    } catch (NullPointerException ex) {
        // No value set, return the default
    } catch (ComponentLookupException e) {
        // Shouldn't happen, base components must be available
    }
    return null;
}

From source file:org.phenotips.configuration.internal.global.GlobalRecordConfiguration.java

@Override
public String getDateOfBirthFormat() {
    String result = getISODateFormat();
    try {/*from  w ww  .  j a v a2  s .c o  m*/
        BaseObject settings = getGlobalConfigurationObject();
        result = StringUtils.defaultIfBlank(settings.getStringValue("dateOfBirthFormat"), result);
    } catch (NullPointerException ex) {
        // No value set, return the default
    }
    return result;
}

From source file:org.phenotips.data.internal.PhenoTipsFeature.java

/**
 * Constructor that copies the data from an XProperty value.
 *
 * @param doc the XDocument representing the described patient in XWiki
 * @param property the feature category XProperty
 * @param value the specific value from the property represented by this object
 */// w  ww.jav  a  2  s.  co  m
public PhenoTipsFeature(XWikiDocument doc, ListProperty property, String value) {
    super(value);
    this.propertyName = property.getName();
    Matcher nameMatch = NEGATIVE_PREFIX.matcher(this.propertyName);
    this.present = !nameMatch.lookingAt();
    this.type = nameMatch.replaceFirst("");

    this.metadata = new TreeMap<>();
    String metadataNotes = "";
    try {
        BaseObject metadataObject = findMetadataObject(doc);
        if (metadataObject != null) {
            for (FeatureMetadatum.Type metadataType : FeatureMetadatum.Type.values()) {
                StringProperty metadataProp = (StringProperty) metadataObject.get(metadataType.toString());
                if (metadataProp != null && StringUtils.isNotBlank(metadataProp.getValue())) {
                    this.metadata.put(metadataType.toString(), new PhenoTipsFeatureMetadatum(metadataProp));
                }
            }
            metadataNotes = metadataObject.getLargeStringValue("comments");
        }
    } catch (XWikiException ex) {
        // Cannot access metadata, simply ignore
        this.logger.info("Failed to retrieve phenotype metadata: {}", ex.getMessage());
    }
    this.notes = StringUtils.defaultIfBlank(metadataNotes, "");
    // Readonly from now on
    this.metadata = Collections.unmodifiableMap(this.metadata);

    List<String> categoriesList = Collections.emptyList();
    try {
        BaseObject categoriesObject = findCategoriesObject(doc);
        if (categoriesObject != null && categoriesObject.getListValue(META_PROPERTY_CATEGORIES) != null) {
            @SuppressWarnings("unchecked")
            List<String> originalCategories = categoriesObject.getListValue(META_PROPERTY_CATEGORIES);
            categoriesList = Collections.unmodifiableList(originalCategories);
        }
    } catch (XWikiException ex) {
        // Cannot access metadata, simply ignore
        this.logger.info("Failed to retrieve phenotype categories: {}", ex.getMessage());
    }
    this.categories = categoriesList;
}

From source file:org.phenotips.data.internal.R71490PhenoTips1280DataMigration.java

private void migrateGenes(XWikiDocument doc, XWikiContext context, List<String> geneList, String status)
        throws HibernateException, XWikiException {
    DocumentReference oldGenesClassReference = CANDIDATE_NAME.equals(status) ? this.investigationClassReference
            : this.rejectedGenesClassReference;
    StringBuilder freeComments = new StringBuilder("");

    List<BaseObject> genes = doc.getXObjects(oldGenesClassReference);
    if (genes == null) {
        return;//from w w w.j av a  2  s  . c o  m
    }

    for (BaseObject gene : genes) {
        if (gene == null) {
            continue;
        }

        StringProperty oldGeneNameProp = (StringProperty) gene.get(GENE_NAME);
        LargeStringProperty oldGeneCommentsProp = (LargeStringProperty) gene.get(COMMENTS_NAME);

        if (oldGeneNameProp == null || StringUtils.isBlank(oldGeneNameProp.getValue())) {
            // fix for PT-3033: users occasionally used the "rejected genes" section in 1.2 only for comments
            if (oldGeneCommentsProp != null && StringUtils.isNotBlank(oldGeneCommentsProp.getValue())) {
                freeComments.append(" - " + oldGeneCommentsProp.getValue() + "\n");
            }
            continue;
        }

        String geneName = oldGeneNameProp.getValue();
        String geneComments = null;
        if (oldGeneCommentsProp != null) {
            geneComments = StringUtils.defaultIfBlank(oldGeneCommentsProp.getValue(), null);
        }
        // check if we already have migrated this gene
        if (!geneList.contains(geneName)) {
            BaseObject newgene = doc.newXObject(this.geneClassReference, context);
            newgene.setStringValue(GENE_NAME, geneName);
            newgene.setStringValue(STATUS_NAME, status);
            if (geneComments != null) {
                newgene.setLargeStringValue(COMMENTS_NAME, geneComments);
            }
            geneList.add(geneName);
        } else if (geneComments != null) {
            String commentAppend = "Automatic migration: \ngene was duplicated in the " + status
                    + " gene section.";
            commentAppend += "\nOriginal comment: \n" + geneComments;
            updateComment(geneName, doc, commentAppend, this.geneClassReference);
        }
    }
    doc.removeXObjects(oldGenesClassReference);

    // fix for PT-3033: users occasionally used the "rejected genes" section in 1.2 only for comments
    if (StringUtils.isNotBlank(freeComments.toString())) {
        this.commentsFromEmptyGenes += (CANDIDATE_NAME.equals(status) ? CANDIDATE_COMMENT_START
                : REJECTED_COMMENT_START) + freeComments.toString();
    }
}

From source file:org.phenotips.data.Medication.java

/**
 * Constructor parsing back a JSON, in the same format as {@link #toJSON()} produces.
 *
 * @param json a JSON object in the format produced by {@link #toJSON()}; must not be {@code null}
 * @throws IllegalArgumentException if {@code json} is {@code null}
 *//*from w  w  w.  j  a va  2 s  . c o  m*/
public Medication(JSONObject json) {
    if (json == null) {
        throw new IllegalArgumentException("The json parameter must not be null");
    }
    this.name = StringUtils.defaultIfBlank(json.optString(NAME), null);
    this.genericName = StringUtils.defaultIfBlank(json.optString(GENERIC_NAME), null);
    this.dose = StringUtils.defaultIfBlank(json.optString(DOSE), null);
    this.frequency = StringUtils.defaultIfBlank(json.optString(FREQUENCY), null);
    String effectStr = json.optString(EFFECT);
    if (StringUtils.isBlank(effectStr)) {
        this.effect = null;
    } else {
        MedicationEffect e = null;
        try {
            e = MedicationEffect.fromString(effectStr);
        } catch (IllegalArgumentException ex) {
            // Shouldn't happen
            this.logger.info("Unknown medication effect: {}", effectStr);
        }
        this.effect = e;
    }
    String durationStr = json.optString(DURATION);
    if (StringUtils.isBlank(durationStr)) {
        this.duration = null;
    } else {
        this.duration = ISOPeriodFormat.standard().parsePeriod("P" + durationStr);
    }
    this.notes = StringUtils.defaultIfBlank(json.optString(NOTES), null);
}