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

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

Introduction

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

Prototype

public static String trimToNull(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:mitm.application.djigzo.tools.CLITool.java

private void handleCommandline(String[] args) throws Exception {
    CommandLineParser parser = new PosixParser();

    Options options = createCommandLineOptions();

    HelpFormatter formatter = new HelpFormatter();

    CommandLine commandLine;// ww  w. j a  v  a2  s.  c o m

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException e) {
        formatter.printHelp(COMMAND_NAME, options, true);

        throw e;
    }

    initLogging(commandLine.hasOption(loggingOption.getLongOpt()));

    soapUser = soapUserOption.getValue();

    soapPassword = soapPasswordOption.getValue();

    encrypt = commandLine.hasOption(encryptOption.getLongOpt());

    value = valueOption.getValue();

    email = StringUtils.trimToNull(emailOption.getValue());

    domain = StringUtils.trimToNull(domainOption.getValue());

    global = commandLine.hasOption(globalOption.getLongOpt());

    salt = StringUtils.trimToNull(saltOption.getValue());

    if (commandLine.getOptions().length == 0 || commandLine.hasOption(helpOption.getLongOpt())) {
        formatter.printHelp(COMMAND_NAME, options, true);

        System.exit(1);

        return;
    }

    if (commandLine.hasOption(setPropertyOption.getLongOpt())) {
        setProperty();
    } else if (commandLine.hasOption(getPropertyOption.getLongOpt())) {
        getProperty();
    } else if (commandLine.hasOption(addUserOption.getLongOpt())) {
        addUser();
    } else if (commandLine.hasOption(deleteUserOption.getLongOpt())) {
        deleteUser();
    } else if (commandLine.hasOption(addDomainOption.getLongOpt())) {
        addDomain();
    } else if (commandLine.hasOption(deleteDomainOption.getLongOpt())) {
        deleteDomain();
    } else if (commandLine.hasOption(importXMLOption.getLongOpt())) {
        importXML();
    } else if (commandLine.hasOption(encodePasswordOption.getLongOpt())) {
        encodePassword();
    }
}

From source file:com.egt.web.configuracion.basica.FragmentoFiltro.java

public String getUrlImagenTextoFiltro2() {
    String nx = this.getRecursoDataProvider().getNombreFuncionSelect();
    nx = StringUtils.trimToNull(nx);
    return this.getRecursoDataProvider().isNombreFuncionSelectModificado() ? URL_IMAGEN_WARNING
            : nx == null ? URL_IMAGEN_OK_DIMMED : URL_IMAGEN_OK;
}

From source file:com.haulmont.cuba.gui.components.filter.Param.java

protected Component createTextField(final ValueProperty valueProperty) {
    if (inExpr) {
        ListEditor listEditor = componentsFactory.createComponent(ListEditor.class);
        listEditor.setItemType(ListEditor.ItemType.STRING);
        initListEditor(listEditor, valueProperty);
        return listEditor;
    }//from w  ww .  j ava 2 s .  c  o m

    TextField field = componentsFactory.createComponent(TextField.class);
    field.setWidth(theme.get("cuba.gui.filter.Param.textComponent.width"));

    field.addValueChangeListener(e -> {
        Object paramValue = null;
        if (!StringUtils.isBlank((String) e.getValue())) {
            paramValue = e.getValue();
        }
        if (paramValue instanceof String) {
            Configuration configuration = AppBeans.get(Configuration.NAME);
            if (configuration.getConfig(ClientConfig.class).getGenericFilterTrimParamValues()) {
                _setValue(StringUtils.trimToNull((String) paramValue), valueProperty);
            } else {
                _setValue(paramValue, valueProperty);
            }
        } else {
            _setValue(paramValue, valueProperty);
        }
    });

    Object _value = valueProperty == ValueProperty.DEFAULT_VALUE ? defaultValue : value;

    if (_value instanceof List) {
        field.setValue(StringUtils.join((Collection) _value, ","));
    } else if (_value instanceof String) {
        field.setValue(_value);
    } else {
        field.setValue("");
    }

    return field;
}

From source file:com.bluexml.xforms.controller.mapping.MappingToolAlfrescoToClassForms.java

/**
 * Fill x forms attribute. Creates the attribute node and sets the value in the instance.
 * Priority order: value from the uri; if none, the attribute's default; if none, a default
 * value for the type is created./*from  w w w  .  j  a v a  2 s. c o m*/
 * 
 * @param xformsDoc
 *            the xforms document
 * @param containerElement
 *            the container element
 * @param attrType
 *            the attribute
 * @param attributes
 *            the attributes
 * @param initParams
 *            the init params
 * @param isServletRequest
 */
private void fillXFormsAttribute(Document xformsDoc, Element containerElement, AttributeType attrType,
        List<GenericAttribute> attributes, Map<String, String> initParams, boolean formIsReadOnly,
        boolean isServletRequest) {

    Element attrElt = xformsDoc.createElement(attrType.getName());
    // the value to set eventually
    String textualValue = null;
    // there may be a default value
    String defaultValue = getDefault(attrType);
    // #999: enums may be dynamic so don't treat them all as static
    String staticEnumName = isDynamicEnum(attrType) ? null : attrType.getEnumQName();

    GenericAttribute alfAttribute = findAttribute(attributes, attrType);
    String type = attrType.getType();
    if (attrType.getName().equals(MsgId.INT_INSTANCE_SIDEID.getText())) {
        if (alfAttribute != null) {
            textualValue = alfAttribute.getValue().get(0).getValue();
        }
    } else {
        if (alfAttribute == null) {
            String initialValue = safeMapGet(initParams, attrType.getName());
            // setting the value from the uri
            if (StringUtils.trimToNull(initialValue) != null) {
                textualValue = convertAlfrescoAttributeToXforms(initialValue, type, staticEnumName, initParams);
            } else { // empty form (but we want to include default values)
                textualValue = createXFormsInitialValue(type, defaultValue, staticEnumName, initParams);
            }
        } else {
            textualValue = convertAlfrescoAttributeToXforms(alfAttribute.getValue(), type, staticEnumName,
                    initParams);
        }
    }

    // we set the text content depending on the data type, with user format if applicable
    final boolean applyUserFormat = (isServletRequest == false) && (formIsReadOnly || isReadOnly(attrType));
    if (type.equals("DateTime")) {
        String timeValue = getTimeFromDateTime(textualValue);
        String dateValue = getDateFromDateTime(textualValue);
        if (applyUserFormat) {
            dateValue = transformDateValueForDisplay(dateValue);
            timeValue = transformTimeValueForDisplay(timeValue);
            attrElt.setTextContent(dateValue + " " + timeValue);
        } else {
            Element dateField = xformsDoc.createElement("date");
            dateField.setTextContent(dateValue);
            attrElt.appendChild(dateField);
            Element timeField = xformsDoc.createElement("time");
            timeField.setTextContent(timeValue);
            attrElt.appendChild(timeField);
        }
    } else if (type.equals("Date")) {
        String dateValue = textualValue;
        if (applyUserFormat) {
            transformDateValueForDisplay(textualValue);
        }
        attrElt.setTextContent(dateValue);
    } else if (type.equals("Time")) {
        String timeValue = textualValue;
        if (applyUserFormat) {
            timeValue = transformTimeValueForDisplay(textualValue);
        }
        attrElt.setTextContent(timeValue);
        // } else if (isMultiple(attrType) && (attrType.getEnumQName() == null)) {
        // // ** #1420: support for text fields with 'multiple' property set to 'true'
        // Element input =
        // xformsDoc.createElement(MsgId.INT_INSTANCE_INPUT_MULT_INPUT.getText());
        // attrElt.appendChild(input);
        //
        // // add legitimate multiple values
        // if (alfAttribute != null) {
        // for (ValueType valueType : alfAttribute.getValue()) {
        // Element item = getInputMultipleItemWithValue(xformsDoc, valueType.getValue());
        // attrElt.appendChild(item);
        // }
        // }
        //
        // // add ghost
        // Element ghostItem = getInputMultipleItemWithValue(xformsDoc, "");
        // attrElt.appendChild(ghostItem);
        // // ** #1420
    } else {
        attrElt.setTextContent(textualValue);
    }

    if (isFileField(attrType)) {
        attrElt.setAttribute("file", "");
        attrElt.setAttribute("type", "");
    }

    containerElement.appendChild(attrElt);
}

From source file:adalid.core.programmers.AbstractSqlProgrammer.java

protected String getSortCriteriaString(SortCriteria criteria) {
    String columna = StringUtils.trimToNull(criteria.getColumna());
    if (columna == null) {
        return null;
    }//from w  w  w .  j  av a  2 s.co m
    if (SortOption.DESC.equals(criteria.getOrden())) {
        return columna + SPC$ + getDescending();
    } else {
        //          return columna + SPC$ + getAscending();
        return columna;
    }
}

From source file:com.cloudbees.hudson.plugins.folder.AbstractFolder.java

/**
 * Loads all the child {@link Item}s./*www . j a v  a2  s . c o  m*/
 *
 * @param modulesDir Directory that contains sub-directories for each child item.
 */
// TODO replace with ItemGroupMixIn.loadChildren once baseline core has JENKINS-41222 merged
public static <K, V extends TopLevelItem> Map<K, V> loadChildren(AbstractFolder<V> parent, File modulesDir,
        Function1<? extends K, ? super V> key) {
    CopyOnWriteMap.Tree<K, V> configurations = new CopyOnWriteMap.Tree<K, V>();
    if (!modulesDir.isDirectory() && !modulesDir.mkdirs()) { // make sure it exists
        LOGGER.log(Level.SEVERE, "Could not create {0} for folder {1}",
                new Object[] { modulesDir, parent.getFullName() });
        return configurations;
    }

    File[] subdirs = modulesDir.listFiles(new FileFilter() {
        public boolean accept(File child) {
            return child.isDirectory();
        }
    });
    if (subdirs == null) {
        return configurations;
    }
    final ChildNameGenerator<AbstractFolder<V>, V> childNameGenerator = parent.childNameGenerator();
    Map<String, V> byDirName = new HashMap<String, V>();
    if (parent.items != null) {
        if (childNameGenerator == null) {
            for (V item : parent.items.values()) {
                byDirName.put(item.getName(), item);
            }
        } else {
            for (V item : parent.items.values()) {
                String itemName = childNameGenerator.dirNameFromItem(parent, item);
                if (itemName == null) {
                    itemName = childNameGenerator.dirNameFromLegacy(parent, item.getName());
                }
                byDirName.put(itemName, item);
            }
        }
    }
    for (File subdir : subdirs) {
        try {
            boolean legacy;
            String childName;
            if (childNameGenerator == null) {
                // the directory name is the item name
                childName = subdir.getName();
                legacy = false;
            } else {
                File nameFile = new File(subdir, ChildNameGenerator.CHILD_NAME_FILE);
                if (nameFile.isFile()) {
                    childName = StringUtils.trimToNull(FileUtils.readFileToString(nameFile, "UTF-8"));
                    if (childName == null) {
                        LOGGER.log(Level.WARNING, "{0} was empty, assuming child name is {1}",
                                new Object[] { nameFile, subdir.getName() });
                        legacy = true;
                        childName = subdir.getName();
                    } else {
                        legacy = false;
                    }
                } else {
                    // this is a legacy name
                    legacy = true;
                    childName = subdir.getName();
                }
            }
            // Try to retain the identity of an existing child object if we can.
            V item = byDirName.get(childName);
            boolean itemNeedsSave = false;
            if (item == null) {
                XmlFile xmlFile = Items.getConfigFile(subdir);
                if (xmlFile.exists()) {
                    item = (V) xmlFile.read();
                    String name;
                    if (childNameGenerator == null) {
                        name = subdir.getName();
                    } else {
                        String dirName = childNameGenerator.dirNameFromItem(parent, item);
                        if (dirName == null) {
                            dirName = childNameGenerator.dirNameFromLegacy(parent, childName);
                            BulkChange bc = new BulkChange(item); // suppress any attempt to save as parent not set
                            try {
                                childNameGenerator.recordLegacyName(parent, item, childName);
                                itemNeedsSave = true;
                            } catch (IOException e) {
                                LOGGER.log(Level.WARNING, "Ignoring {0} as could not record legacy name",
                                        subdir);
                                continue;
                            } finally {
                                bc.abort();
                            }
                        }
                        if (!subdir.getName().equals(dirName)) {
                            File newSubdir = parent.getRootDirFor(dirName);
                            if (newSubdir.exists()) {
                                LOGGER.log(Level.WARNING,
                                        "Ignoring {0} as folder naming rules collide with {1}",
                                        new Object[] { subdir, newSubdir });
                                continue;

                            }
                            LOGGER.log(Level.INFO, "Moving {0} to {1} in accordance with folder naming rules",
                                    new Object[] { subdir, newSubdir });
                            if (!subdir.renameTo(newSubdir)) {
                                LOGGER.log(Level.WARNING, "Failed to move {0} to {1}. Ignoring this item",
                                        new Object[] { subdir, newSubdir });
                                continue;
                            }
                        }
                        File nameFile = new File(parent.getRootDirFor(dirName),
                                ChildNameGenerator.CHILD_NAME_FILE);
                        name = childNameGenerator.itemNameFromItem(parent, item);
                        if (name == null) {
                            name = childNameGenerator.itemNameFromLegacy(parent, childName);
                            FileUtils.writeStringToFile(nameFile, name, "UTF-8");
                            BulkChange bc = new BulkChange(item); // suppress any attempt to save as parent not set
                            try {
                                childNameGenerator.recordLegacyName(parent, item, childName);
                                itemNeedsSave = true;
                            } catch (IOException e) {
                                LOGGER.log(Level.WARNING, "Ignoring {0} as could not record legacy name",
                                        subdir);
                                continue;
                            } finally {
                                bc.abort();
                            }
                        } else if (!childName.equals(name) || legacy) {
                            FileUtils.writeStringToFile(nameFile, name, "UTF-8");
                        }
                    }
                    item.onLoad(parent, name);
                } else {
                    LOGGER.log(Level.WARNING, "could not find file " + xmlFile.getFile());
                    continue;
                }
            } else {
                String name;
                if (childNameGenerator == null) {
                    name = subdir.getName();
                } else {
                    File nameFile = new File(subdir, ChildNameGenerator.CHILD_NAME_FILE);
                    name = childNameGenerator.itemNameFromItem(parent, item);
                    if (name == null) {
                        name = childNameGenerator.itemNameFromLegacy(parent, childName);
                        FileUtils.writeStringToFile(nameFile, name, "UTF-8");
                        BulkChange bc = new BulkChange(item); // suppress any attempt to save as parent not set
                        try {
                            childNameGenerator.recordLegacyName(parent, item, childName);
                            itemNeedsSave = true;
                        } catch (IOException e) {
                            LOGGER.log(Level.WARNING, "Ignoring {0} as could not record legacy name", subdir);
                            continue;
                        } finally {
                            bc.abort();
                        }
                    } else if (!childName.equals(name) || legacy) {
                        FileUtils.writeStringToFile(nameFile, name, "UTF-8");
                    }
                    if (!subdir.getName().equals(name) && item instanceof AbstractItem
                            && ((AbstractItem) item).getDisplayNameOrNull() == null) {
                        BulkChange bc = new BulkChange(item);
                        try {
                            ((AbstractItem) item).setDisplayName(childName);
                        } finally {
                            bc.abort();
                        }
                    }
                }
                item.onLoad(parent, name);
            }
            if (itemNeedsSave) {
                try {
                    item.save();
                } catch (IOException e) {
                    LOGGER.log(Level.WARNING, "Could not update {0} after applying folder naming rules",
                            item.getFullName());
                }
            }
            configurations.put(key.call(item), item);
        } catch (Exception e) {
            Logger.getLogger(ItemGroupMixIn.class.getName()).log(Level.WARNING, "could not load " + subdir, e);
        }
    }

    return configurations;
}

From source file:adalid.core.AbstractPersistentEntity.java

private void annotateDiscriminatorValue(Class<?> type) {
    /*/*ww  w . j a  v  a 2 s .c  om*/
     * DiscriminatorValue annotation cannot be "inherited"
     */
    _annotatedWithDiscriminatorValue = type.isAnnotationPresent(DiscriminatorValue.class);
    if (_annotatedWithDiscriminatorValue) {
        DiscriminatorValue annotation = type.getAnnotation(DiscriminatorValue.class);
        _discriminatorValue = StringUtils.trimToNull(annotation.value());
    }
}

From source file:com.haulmont.cuba.gui.xml.layout.loaders.AbstractComponentLoader.java

protected Action loadDeclarativeActionDefault(Component.ActionsHolder actionsHolder, Element element) {
    String id = element.attributeValue("id");
    if (id == null) {
        Element component = element;
        for (int i = 0; i < 2; i++) {
            if (component.getParent() != null)
                component = component.getParent();
            else//from  w  w  w  .j a  va  2  s .c om
                throw new GuiDevelopmentException("No action ID provided", context.getFullFrameId());
        }
        throw new GuiDevelopmentException("No action ID provided", context.getFullFrameId(), "Component ID",
                component.attributeValue("id"));
    }

    String trackSelection = element.attributeValue("trackSelection");

    String shortcut = StringUtils.trimToNull(element.attributeValue("shortcut"));
    shortcut = loadShortcut(shortcut);

    if (Boolean.parseBoolean(trackSelection)) {
        DeclarativeTrackingAction action = new DeclarativeTrackingAction(id,
                loadResourceString(element.attributeValue("caption")),
                loadResourceString(element.attributeValue("description")),
                getIconPath(element.attributeValue("icon")), element.attributeValue("enable"),
                element.attributeValue("visible"), element.attributeValue("invoke"), shortcut, actionsHolder);

        loadActionConstraint(action, element);

        return action;
    } else {
        return new DeclarativeAction(id, loadResourceString(element.attributeValue("caption")),
                loadResourceString(element.attributeValue("description")),
                getIconPath(element.attributeValue("icon")), element.attributeValue("enable"),
                element.attributeValue("visible"), element.attributeValue("invoke"), shortcut, actionsHolder);
    }
}

From source file:net.sourceforge.fenixedu.domain.Person.java

public void setIdentification(String documentIdNumber, final IDDocumentType idDocumentType) {
    documentIdNumber = StringUtils.trimToNull(documentIdNumber);
    if (documentIdNumber != null && idDocumentType != null
            && checkIfDocumentNumberIdAndDocumentIdTypeExists(documentIdNumber, idDocumentType)) {
        throw new DomainException("error.person.existent.docIdAndType");
    }/*from   www .  ja v  a2 s  . c  o m*/
    setDocumentIdNumber(documentIdNumber);
    setIdDocumentType(idDocumentType);
}

From source file:com.bluexml.xforms.generator.forms.XFormsGenerator.java

/**
 * Writes the description files into the directories of each form type that's been generated.
 *///from  ww  w . j  a  v a  2s.c o  m
private void renderDescriptionFiles() {
    Element root = new Element("root");
    Document doc = new Document(root);

    Element labelElt = new Element("label");
    root.addContent(labelElt);
    Element descrElt = new Element("description");
    root.addContent(descrElt);

    for (FormTypeRendered formType : formTypesToDescribe) {
        StringBuffer fileName = new StringBuffer(outputXForms.getAbsolutePath());
        fileName.append(File.separatorChar);
        fileName.append(formType.getFolder());
        if (StringUtils.trimToNull(formType.getFolder()) != null) {
            fileName.append(File.separatorChar);
        }
        fileName.append("descr.xml");
        File descrFile = new File(fileName.toString());

        if (StringUtils.trimToNull(formType.getLabel()) != null) {
            labelElt.setText(formType.getLabel());
            descrElt.setText(formType.getDescription());

            try {
                FileOutputStream fos = new FileOutputStream(descrFile);
                outputter.output(doc, fos);
                fos.close();
            } catch (Exception ex) {
                monitor.addErrorTextAndLog(
                        "Could not write folder description file " + descrFile.getAbsolutePath(), null, null);
            }
        }
    }

}