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

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

Introduction

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

Prototype

public static String trimToNull(final String str) 

Source Link

Document

Removes control characters (char <= 32) from both ends of this String returning null if the String is empty ("") after the trim or if it is null .

Usage

From source file:org.forgerock.cloudfoundry.Configuration.java

private String validateProperty(String value, String variableName) {
    if (StringUtils.trimToNull(value) == null) {
        throw new IllegalStateException("Required configuration missing: " + variableName);
    }//from   w  w  w .  j a v  a2s .  c o  m
    return value;
}

From source file:org.gbif.dwc.record.DarwinCoreTaxon.java

/**
 * The method tries to best assemble the most complete scientific name possible incl the name authorship.
 * It first tries to use scientificName and scientificNameAuthorship if existing.
 * Otherwise it uses the atomized name parts. Warning: this uses the genus property which might be wrong in case
 * of synonym names, see https://code.google.com/p/darwincore/issues/detail?id=151
 * Note also that the assembled name never includes a rank marker.
 *
 * @return the best guess of the full scientific name with authorship
 *///from ww w . ja v a2  s  .  co  m
protected String norm(String x) {
    x = StringUtils.trimToNull(x);
    if (x != null && (x.equalsIgnoreCase("\\N") || x.equalsIgnoreCase("NULL"))) {
        x = null;
    }
    return x;
}

From source file:org.gbif.dwc.text.ArchiveFile.java

public void setEncoding(String encoding) {
    this.encoding = StringUtils.trimToNull(encoding);
}

From source file:org.gbif.dwca.action.ValidateAction.java

/**
 * gets the row value or throws informative exception if the index does not exist
 *///  ww w.  j  a  v  a 2s .c o  m
private String getRowValue(String[] row, int column, String columnName) {
    try {
        return StringUtils.trimToNull(row[column]);
    } catch (Exception e) {
        valid = false;
        throw new IllegalArgumentException("Column " + columnName + " with index " + column + " not existing",
                e);
    }
}

From source file:org.gbif.ipt.action.manage.MappingAction.java

@Override
public void prepare() {
    super.prepare();

    // get mapping sequence id from parameters as setters are not called yet
    String midStr = StringUtils.trimToNull(req.getParameter("mid"));
    if (midStr != null) {
        mid = Integer.valueOf(midStr);
    }//from  w  w w  .j  a v a 2  s  . c om
    // id is rowtype
    if (id != null) {
        // mapping id, i.e. list index for the given rowtype, is given
        if (mid == null) {
            Extension ext = extensionManager.get(id);
            if (ext != null) {
                mapping = new ExtensionMapping();
                mapping.setExtension(ext);
            }
            // The extension could have been null if:
            // 1. The user tried to add a core mapping with the select help option, no extension would have been found
            // 2. No extension could be retrieved for the id (rowtype)
            // The result should be the user stays on the overview page, and displays a warning informing them that they
            // need to perform another selection.
            else {
                addActionError(getText("manage.overview.DwC.Mappings.select.invalid"));
                defaultResult = "error";
            }
        } else {
            List<ExtensionMapping> maps = resource.getMappings(id);
            mapping = maps.get(mid);
        }
    } else {
        // worst case, just redirect to resource not found page
        notFound = true;
    }

    if (mapping != null && mapping.getExtension() != null) {

        // is source assigned yet?
        if (mapping.getSource() == null) {
            // get source parameter as setters are not called yet
            String source = StringUtils.trimToNull(req.getParameter("source"));
            if (source != null) {
                Source src = resource.getSource(source);
                mapping.setSource(src);
            } else {
                // show set source form
                defaultResult = "source";
            }
        }
        // set empty filter if not existing
        if (mapping.getFilter() == null) {
            mapping.setFilter(new RecordFilter());
        }
        // determine the core row type
        String coreRowType = resource.getCoreRowType();
        if (coreRowType == null) {
            // not yet set, the current mapping must be the core type
            coreRowType = mapping.getExtension().getRowType();
        }
        LOG.info("Core row type: " + coreRowType);

        // setup the core record id term
        String coreIdTerm = AppConfig.coreIdTerm(coreRowType);

        coreid = extensionManager.get(coreRowType).getProperty(coreIdTerm);
        LOG.info("Field representing the id for the core: " + coreid);
        mappingCoreid = mapping.getField(coreid.getQualname());
        if (mappingCoreid == null) {
            // no, create bare mapping field
            mappingCoreid = new PropertyMapping();
            mappingCoreid.setTerm(coreid);
            mappingCoreid.setIndex(mapping.getIdColumn());
        }

        // inspect source
        readSource();

        LOG.info("Core ID field determined as " + coreid);

        // prepare all other fields
        fields = new ArrayList<PropertyMapping>(mapping.getExtension().getProperties().size());
        for (ExtensionProperty p : mapping.getExtension().getProperties()) {
            // ignore core id term
            if (p.equals(coreid)) {
                continue;
            }
            // uses a vocabulary?
            if (p.getVocabulary() != null) {
                vocabTerms.put(p.getVocabulary().getUriString(),
                        vocabManager.getI18nVocab(p.getVocabulary().getUriString(), getLocaleLanguage(), true));
            }
            // mapped already?
            PropertyMapping f = mapping.getField(p.getQualname());
            if (f == null) {
                // no, create bare mapping field
                f = new PropertyMapping();
            }
            f.setTerm(p);
            fields.add(f);
        }

        // finally do automapping if no fields are found
        if (mapping.getFields().isEmpty()) {
            int automapped = automap();
            if (automapped > 0) {
                addActionMessage(
                        getText("manage.mapping.automaped", new String[] { String.valueOf(automapped) }));
            }
        }

        if (!isHttpPost()) {
            // save, which does the validation, is not called for GET requests
            addWarnings();
        }
    }
}

From source file:org.gbif.ipt.action.manage.MappingAction.java

@Override
public String save() throws IOException {
    // a new mapping?
    if (resource.getMapping(id, mid) == null) {
        mid = resource.addMapping(mapping);
    } else {/*from   w  w w. j  av a  2  s. co  m*/
        // save field mappings
        Set<PropertyMapping> mappedFields = new TreeSet<PropertyMapping>();
        for (PropertyMapping f : fields) {
            if (f.getIndex() != null || StringUtils.trimToNull(f.getDefaultValue()) != null) {
                mappedFields.add(f);
            }
        }
        // save coreid field
        mappingCoreid.setIndex(mapping.getIdColumn());
        mappingCoreid.setDefaultValue(mapping.getIdSuffix());
        if (mappingCoreid.getIndex() != null
                || StringUtils.trimToNull(mappingCoreid.getDefaultValue()) != null) {
            mappedFields.add(mappingCoreid);
        }
        // back to mapping object
        mapping.setFields(mappedFields);

        // update core type
        updateResourceCoreType(mapping, mappedFields.size());
    }

    // set modified date
    resource.setModified(new Date());
    // save entire resource config
    saveResource();
    // report validation without skipping this save
    addWarnings();

    return defaultResult;
}

From source file:org.gbif.ipt.action.manage.MappingAction.java

/**
 * Update resource core type. This must be done every time the resource's core type mapping is being modified, or
 * deleted. If it is the 1st mapping of the core type, the core type won't have been set yet. Only if 1 or more
 * mapped fields were saved, can we consider the mapping to have been legitimate. Furthermore, if the
 * core type mapping is being deleted, then the resource must reset its core type to null.
 * /*w  w  w.  j  a v  a  2  s.  c  o m*/
 * @param mapping ExtensionMapping
 * @param mappedFields the number of mapped fields in the mapping - set to 0 if the mapping is to be deleted
 */
void updateResourceCoreType(ExtensionMapping mapping, int mappedFields) {
    // proceed only if we're dealing with the core type mapping
    if (mapping.isCore()) {
        // must be 1 or more mapped fields for mapping to be legitimate
        if (mappedFields > 0) {
            // set resource core type, based on core extension's coreRowType
            String coreRowType = StringUtils.trimToNull(mapping.getExtension().getRowType());
            if (Constants.DWC_ROWTYPE_TAXON.equalsIgnoreCase(coreRowType)) {
                resource.setCoreType(StringUtils.capitalize(CoreRowType.CHECKLIST.toString()));
            } else if (Constants.DWC_ROWTYPE_OCCURRENCE.equalsIgnoreCase(coreRowType)) {
                resource.setCoreType(StringUtils.capitalize(CoreRowType.OCCURRENCE.toString()));
            } else {
                resource.setCoreType(StringUtils.capitalize(CoreRowType.OTHER.toString()));
            }
        }
        // otherwise, reset core type!
        else {
            resource.setCoreType(null);
        }
    }
}

From source file:org.gbif.ipt.action.manage.OverviewAction.java

/**
 * Executes the instruction to publish the resource.
 * </br>//from  w w w .  ja  v a2 s  . c om
 * In addition, the method must check if resource has been configured to be auto-published.
 * </br>
 * In addition, the method must clear the processFailures for the resource being published. If a resource has
 * exceeded the maximum number of failed publish events during auto-publication, auto-publication for the resource is
 * suspended. By publishing the resource manually, it is assumed the manager is trying to debug the problem. Without
 * this safeguard in place, a resource can auto-publish in an endless number of failures.
 * 
 * @return Struts2 result string
 * @throws Exception if method fails
 */
public String publish() throws Exception {
    if (resource == null) {
        return NOT_FOUND;
    }

    // clear the processFailures for the resource, allowing auto-publication to proceed
    if (resourceManager.getProcessFailures().containsKey(resource.getShortname())) {
        logProcessFailures(resource);
        LOG.info("Clearing publish event failures for resource: " + resource.getTitleAndShortname());
        resourceManager.getProcessFailures().removeAll(resource.getShortname());
    }

    // look for parameters publication mode and publication frequency
    String pm = StringUtils.trimToNull(req.getParameter(Constants.REQ_PARAM_PUBLICATION_MODE));
    if (!Strings.isNullOrEmpty(pm)) {
        try {
            // auto-publishing being turned OFF
            if (PublicationMode.AUTO_PUBLISH_OFF == PublicationMode.valueOf(pm)
                    && resource.usesAutoPublishing()) {
                resourceManager.publicationModeToOff(resource);
            }
            // auto-publishing being turned ON, or auto-publishing settings being updated
            else {
                String pf = StringUtils.trimToNull(req.getParameter(Constants.REQ_PARAM_PUBLICATION_FREQUENCY));
                if (!Strings.isNullOrEmpty(pf)) {
                    resource.setUpdateFrequency(pf);
                    resource.setPublicationMode(PublicationMode.valueOf(pm));
                } else {
                    LOG.debug("No change to auto-publishing settings");
                }
            }
        } catch (IllegalArgumentException e) {
            LOG.error("Exception encountered while parsing parameters: " + e.getMessage(), e);
        } finally {
            // update frequencies map
            populateFrequencies();
        }
    }

    // increment version number - this will be the version of newly published resource (all of eml/rtf/dwca)
    int v = resource.getNextVersion();

    try {
        // publish a new version of the resource
        if (resourceManager.publish(resource, v, this)) {
            addActionMessage(
                    getText("publishing.started", new String[] { String.valueOf(v), resource.getShortname() }));
            return PUBLISHING;
        } else {
            // show action warning there is no source data and mapping, as long as resource isn't metadata-only
            if (!resource.getCoreType().equalsIgnoreCase(Constants.DATASET_TYPE_METADATA_IDENTIFIER)) {
                addActionWarning(getText("manage.overview.data.missing"));
            }
            missingRegistrationMetadata = !hasMinimumRegistryInfo(resource);
            return SUCCESS;
        }
    } catch (PublicationException e) {
        if (PublicationException.TYPE.LOCKED == e.getType()) {
            addActionError(getText("manage.overview.resource.being.published",
                    new String[] { resource.getTitleAndShortname() }));
        } else {
            // alert user publication failed
            addActionError(getText("publishing.failed",
                    new String[] { String.valueOf(v), resource.getShortname(), e.getMessage() }));
            // restore the previous version since publication was unsuccessful
            resourceManager.restoreVersion(resource, v - 1, this);
            // keep track of how many failures on auto publication have happened
            resourceManager.getProcessFailures().put(resource.getShortname(), new Date());
        }
    } catch (InvalidConfigException e) {
        // with this type of error, the version cannot be rolled back - just alert user publication failed
        String msg = getText("publishing.failed",
                new String[] { String.valueOf(v), resource.getShortname(), e.getMessage() });
        LOG.error(msg, e);
        addActionError(msg);
    }
    return ERROR;
}

From source file:org.gbif.ipt.action.manage.OverviewAction.java

public void setUnpublish(String unpublish) {
    this.unpublish = StringUtils.trimToNull(unpublish) != null;
}

From source file:org.gbif.ipt.action.manage.SourceAction.java

public void setAnalyze(String analyze) {
    if (StringUtils.trimToNull(analyze) != null) {
        this.analyze = true;
    }
}