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:ch.entwine.weblounge.kernel.security.SystemAdminDirectoryProvider.java

/**
 * {@inheritDoc}/* w w  w . j a  v  a2 s. c  o m*/
 * 
 * @see org.osgi.service.cm.ManagedService#updated(java.util.Dictionary)
 */
@SuppressWarnings("rawtypes")
public void updated(Dictionary properties) throws ConfigurationException {
    String login = null;
    String pass = "";
    String digest = null;
    String name = null;
    String email = null;

    if (properties != null) {
        login = StringUtils.trimToNull((String) properties.get(OPT_ADMIN_LOGIN));
        pass = StringUtils.trimToEmpty((String) properties.get(OPT_ADMIN_PASSWORD));
        digest = StringUtils.trimToEmpty((String) properties.get(OPT_ADMIN_DIGEST));
        name = StringUtils.trimToEmpty((String) properties.get(OPT_ADMIN_NAME));
        email = StringUtils.trimToEmpty((String) properties.get(OPT_ADMIN_EMAIL));
    }

    // If no user can be found
    if (login == null || "".equals(pass)) {
        logger.info("No system accounts have been defined");
        if (administrator != null)
            logger.info("Deactivating system admin account");
        administrator = null;
        return;
    }

    // Register the new one
    logger.info("Activating system admin user '{}'", login);
    administrator = new WebloungeUserImpl(login, Security.SYSTEM_CONTEXT);
    if (StringUtils.isNotBlank(name))
        administrator.setName(name);
    if (StringUtils.isNotBlank(email))
        administrator.setEmail(email);

    DigestType digestType = DigestType.plain;
    if (StringUtils.isNotBlank(digest)) {
        try {
            digestType = DigestType.valueOf(digest);
        } catch (IllegalArgumentException e) {
            logger.error("Digest type '{}' is unknown", digest);
            throw new ConfigurationException(OPT_ADMIN_DIGEST, digest);
        }
    }

    if (StringUtils.isNotBlank(pass)) {
        Password password = new PasswordImpl(StringUtils.trimToEmpty(pass), digestType);
        administrator.addPrivateCredentials(password);
    }

    // Add the roles
    for (Role role : SystemRole.SYSTEMADMIN.getClosure()) {
        administrator.addPublicCredentials(role);
    }
}

From source file:com.bluexml.xforms.demo.Util.java

/**
 * Calls the XForms webapp with initialization values.
 * //from   w  ww.j  av  a2 s  . c  om
 * @param alfrescohost
 *            the address (protocol, host name, port number) to the Alfresco instance, with NO
 *            trailing slash. e.g. http://www.bluexml.com/alfresco
 * @param xformshost
 *            the address (including context) of the xforms webapp host, with NO trailing slash.
 *            e.g: http://localhost:8081/myforms
 * @param formsproperties
 *            the path to the forms.properties file
 * @param redirectxml
 *            the path to the redirect.xml file
 * @return
 */
public static boolean initWebApp(String alfrescohost, String xformshost, String formsproperties,
        String redirectxml) {
    if (StringUtils.trimToNull(xformshost) == null) {
        return false;
    }
    String serviceURL = xformshost + "/xforms?init=true";

    serviceURL += "&alfrescoHost=" + alfrescohost;
    serviceURL += "&redirectXmlFile=" + redirectxml;
    serviceURL += "&formsPropertiesFile=" + formsproperties;

    GetMethod get = new GetMethod(serviceURL);
    HttpClient client = new HttpClient();
    try {
        client.executeMethod(get);
    } catch (HttpException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
    String result;
    try {
        result = get.getResponseBodyAsString();
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
    if (result == null) {
        return false;
    }
    result = result.trim();
    return result.equals("success");
}

From source file:com.google.code.configprocessor.processing.AddAction.java

public String getInside() {
    return StringUtils.trimToNull(inside);
}

From source file:com.hand.hap.mybatis.util.OGNL.java

/**
 * FOR INTERNAL USE ONLY/*from w w w  .  j  a v a2s .  co m*/
 * 
 * @param parameter
 * @return
 */
public static String getOrderByClause(Object parameter) {
    if (parameter == null) {
        return null;
    }
    StringBuilder sb = new StringBuilder(64);
    if (parameter instanceof BaseDTO) {
        String sortName = ((BaseDTO) parameter).getSortname();
        Field[] ids = DTOClassInfo.getIdFields(parameter.getClass());
        if (StringUtil.isNotEmpty(sortName)) {
            if (!COL_PATTERN.matcher(sortName).matches()) {
                throw new RuntimeException("Invalid sortname:" + sortName);
            }
            String order = ((BaseDTO) parameter).getSortorder();
            if (!("ASC".equalsIgnoreCase(order) || "DESC".equalsIgnoreCase(order) || order == null)) {
                throw new RuntimeException("Invalid sortorder:" + order);
            }
            String columnName = unCamel(sortName);

            sb.append(columnName).append(" ");
            sb.append(StringUtils.defaultIfEmpty(order, "ASC"));

            if (ids.length > 0 && !ids[0].getName().equals(sortName)) {
                sb.append(",").append(DTOClassInfo.getColumnName(ids[0])).append(" ASC");
            }
        } else {
            if (ids.length > 0) {
                sb.append(DTOClassInfo.getColumnName(ids[0])).append(" ASC");
            }
        }
    }
    return StringUtils.trimToNull(sb.toString());
}

From source file:com.eyeq.pivot4j.ui.property.PropertySupport.java

/**
 * @param name//from   w w w.j a va2s . co m
 * @param defaultValue
 * @param context
 * @return
 */
public String getString(String name, String defaultValue, RenderContext context) {
    if (name == null) {
        throw new NullArgumentException("name");
    }

    if (context == null) {
        throw new NullArgumentException("context");
    }

    String value = null;

    Property property = properties.get(name);

    if (property != null) {
        value = StringUtils.trimToNull(property.getValue(context));
    }

    if (value == null) {
        value = defaultValue;
    }

    return value;
}

From source file:nc.noumea.mairie.organigramme.dto.FichePosteDto.java

@JSON(include = false)
public String getLibelleGradeCategorie() {
    String suffixe = StringUtils.isNotBlank(this.categorie) ? " (" + this.categorie + ")" : "";
    return StringUtils.trimToNull(StringUtils.trimToEmpty(this.gradePoste) + suffixe);
}

From source file:com.openmeap.services.ApplicationManagementServiceImpl.java

public ConnectionOpenResponse connectionOpen(ConnectionOpenRequest request) throws WebServiceException {

    String reqAppArchHashVal = StringUtils.trimToNull(request.getApplication().getHashValue());
    String reqAppVerId = StringUtils.trimToNull(request.getApplication().getVersionId());
    String reqAppName = StringUtils.trimToNull(request.getApplication().getName());

    ConnectionOpenResponse response = new ConnectionOpenResponse();

    GlobalSettings settings = modelManager.getGlobalSettings();
    if (StringUtils.isBlank(settings.getExternalServiceUrlPrefix()) && logger.isWarnEnabled()) {
        logger.warn("The external service url prefix configured in the admin interface is blank.  "
                + "This will probably cause issues downloading application archives.");
    }/*from ww  w. j a  v  a2 s .co  m*/

    Application application = getApplication(reqAppName, reqAppVerId);

    // Generate a new auth token for the device to present to the proxy
    String authToken;
    try {
        authToken = AuthTokenProvider.newAuthToken(application.getProxyAuthSalt());
    } catch (DigestException e) {
        throw new GenericRuntimeException(e);
    }
    response.setAuthToken(authToken);

    // If there is a deployment, 
    // and the version of that deployment differs in hash value or identifier
    // then return an update in the response
    Deployment lastDeployment = modelManager.getModelService().getLastDeployment(application);
    Boolean reqAppVerDiffers = lastDeployment != null
            && !lastDeployment.getVersionIdentifier().equals(reqAppVerId);
    Boolean reqAppArchHashValDiffers = lastDeployment != null && reqAppArchHashVal != null
            && !lastDeployment.getApplicationArchive().getHash().equals(reqAppArchHashVal);

    // we only send an update if 
    //   a deployment has been made
    // and one of the following is true
    //   the app version is different than reported
    //   the app hash value is different than reported
    if (reqAppVerDiffers || reqAppArchHashValDiffers) {

        // TODO: I'm not happy with the discrepancies between the model and schema
        // ...besides, this update header should be encapsulated somewhere else
        ApplicationArchive currentVersionArchive = lastDeployment.getApplicationArchive();
        UpdateHeader uh = new UpdateHeader();

        uh.setVersionIdentifier(lastDeployment.getVersionIdentifier());
        uh.setInstallNeeds(Long.valueOf(
                currentVersionArchive.getBytesLength() + currentVersionArchive.getBytesLengthUncompressed()));
        uh.setStorageNeeds(Long.valueOf(currentVersionArchive.getBytesLengthUncompressed()));
        uh.setType(UpdateType.fromValue(lastDeployment.getType().toString()));
        uh.setUpdateUrl(currentVersionArchive.getDownloadUrl(settings));
        uh.setHash(new Hash());
        uh.getHash().setAlgorithm(HashAlgorithm.fromValue(currentVersionArchive.getHashAlgorithm()));
        uh.getHash().setValue(currentVersionArchive.getHash());

        response.setUpdate(uh);
    }

    return response;
}

From source file:ch.entwine.weblounge.common.impl.util.xml.XPathHelper.java

/**
 * Returns the query result or <code>null</code>.
 * /*ww w . ja  va  2  s . c om*/
 * @param node
 *          the context node
 * @param xpathExpression
 *          the xpath expression
 * @param defaultValue
 *          the default value
 * @param processor
 *          the xpath engine
 * 
 * @return the selected string or <code>defaultValue</code> if the query
 *         didn't yield a result
 */
public static String valueOf(Node node, String xpathExpression, String defaultValue, XPath processor) {

    if (node == null || processor == null)
        return null;

    try {
        String value = StringUtils.trimToNull(processor.evaluate(xpathExpression, node));

        // If we are running in test mode, we may neglect namespaces
        if (value == null) {
            NamespaceContext ctx = processor.getNamespaceContext();
            if (ctx instanceof XPathNamespaceContext && ((XPathNamespaceContext) ctx).isTest()) {
                if (xpathExpression.matches("(.*)[a-zA-Z0-9]+\\:[a-zA-Z0-9]+(.*)")) {
                    String xpNs = xpathExpression.replaceAll("[a-zA-Z0-9]+\\:", "");
                    value = StringUtils.trimToNull(processor.evaluate(xpNs, node));
                }
            }
        }
        return (value != null) ? value : defaultValue;
    } catch (XPathExpressionException e) {
        logger.warn("Error when selecting '{}': {}", xpathExpression, e.getMessage());
        return null;
    }
}

From source file:net.sf.firemox.clickable.ability.Ability.java

/**
 * Create an instance of Ability/* ww w .  j a v  a  2 s.c om*/
 * <ul>
 * Structure of InputStream : Data[size]
 * <li>name name [String]</li>
 * <li>priority [Priority]</li>
 * <li>optimization [Optimization]</li>
 * <li>play-as-spell [TrueFalseAuto]</li>
 * </ul>
 * 
 * @param inputFile
 *          file containing this ability
 * @throws IOException
 *           if error occurred during the reading process from the specified
 *           input stream
 */
protected Ability(InputStream inputFile) throws IOException {
    // name of this ability
    this.name = StringUtils.trimToNull(MToolKit.readString(inputFile).intern());

    // To enable recursive ability dependencies
    AbilityFactory.lastInstance = this;

    /**
     * We read the ability tag. If this ability has 'isHidden' tag, it would be
     * considered as abstract and no picture would be used to represent it, so
     * it would be played immediately without player intervention. If this
     * ability has this tag and requires player intervention the play would
     * crash.
     */
    priority = Priority.valueOf(inputFile);
    optimizer = Optimization.valueOf(inputFile);
    if (isHidden()) {
        pictureName = null;
    } else {
        pictureName = StringUtils.trimToNull(MToolKit.readString(inputFile));
    }
    playAsSpell = TrueFalseAuto.deserialize(inputFile);
}

From source file:com.hmsinc.epicenter.integrator.service.PatientService.java

private Patient parsePatient(final HL7Message message) throws InvalidMessageException, HL7Exception {

    final Facility facility = providerRepository
            .getFacilityByIdentifier(message.getDataSource().getSendingFacility());
    if (facility == null) {
        throw new InvalidMessageException("Facility not found: " + message.getDataSource().toString());
    }// ww  w.  j av a2 s  . c  o m

    Patient patient = null;
    final Terser t = message.getTerser();

    // See if this Patient is already in the database..
    final String patientID = StringUtils.trimToNull(t.get("/PID-3"));

    if (patientID == null) {
        logger.warn("No patient ID set in message");
    } else {
        patient = healthRepository.getPatient(patientID, facility);
    }

    if (patient == null) {

        logger.debug("Creating new patient record");
        patient = new Patient(patientID, facility);

    } else {

        logger.debug("Found existing patient record: {}", patient.getId());
    }

    return patient;
}