Example usage for org.springframework.util StringUtils commaDelimitedListToStringArray

List of usage examples for org.springframework.util StringUtils commaDelimitedListToStringArray

Introduction

In this page you can find the example usage for org.springframework.util StringUtils commaDelimitedListToStringArray.

Prototype

public static String[] commaDelimitedListToStringArray(@Nullable String str) 

Source Link

Document

Convert a comma delimited list (e.g., a row from a CSV file) into an array of strings.

Usage

From source file:eap.config.TxAdviceBeanDefinitionParser.java

private void addRollbackRuleAttributesTo(List<RollbackRuleAttribute> rollbackRules, String rollbackForValue) {
    String[] exceptionTypeNames = StringUtils.commaDelimitedListToStringArray(rollbackForValue);
    for (String typeName : exceptionTypeNames) {
        rollbackRules.add(new RollbackRuleAttribute(StringUtils.trimWhitespace(typeName)));
    }//from   www. ja  v a  2  s.  com
}

From source file:eap.config.TxAdviceBeanDefinitionParser.java

private void addNoRollbackRuleAttributesTo(List<RollbackRuleAttribute> rollbackRules,
        String noRollbackForValue) {
    String[] exceptionTypeNames = StringUtils.commaDelimitedListToStringArray(noRollbackForValue);
    for (String typeName : exceptionTypeNames) {
        rollbackRules.add(new NoRollbackRuleAttribute(StringUtils.trimWhitespace(typeName)));
    }/*from  w w w .  ja  va  2s.  c o  m*/
}

From source file:net.sf.juffrou.reflect.JuffrouTypeConverterDelegate.java

/**
 * Convert the value to the required type (if necessary from a String), for the specified property.
 * //from ww  w  .  j a v a2s  .  c  o  m
 * @param propertyName
 *            name of the property
 * @param oldValue
 *            the previous value, if available (may be <code>null</code>)
 * @param newValue
 *            the proposed new value
 * @param requiredType
 *            the type we must convert to (or <code>null</code> if not known, for example in case of a collection
 *            element)
 * @param typeDescriptor
 *            the descriptor for the target property or field
 * @return the new value, possibly the result of type conversion
 * @throws IllegalArgumentException
 *             if type conversion failed
 */
@SuppressWarnings("unchecked")
public <T> T convertIfNecessary(String propertyName, Object oldValue, Object newValue, Class<T> requiredType,
        TypeDescriptor typeDescriptor) throws IllegalArgumentException {

    Object convertedValue = newValue;

    // Custom editor for this type?
    PropertyEditor editor = this.propertyEditorRegistry.findCustomEditor(requiredType, propertyName);

    ConversionFailedException firstAttemptEx = null;

    // No custom editor but custom ConversionService specified?
    ConversionService conversionService = this.propertyEditorRegistry.getConversionService();
    if (editor == null && conversionService != null && convertedValue != null && typeDescriptor != null) {
        TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue);
        TypeDescriptor targetTypeDesc = typeDescriptor;
        if (conversionService.canConvert(sourceTypeDesc, targetTypeDesc)) {
            try {
                return (T) conversionService.convert(convertedValue, sourceTypeDesc, targetTypeDesc);
            } catch (ConversionFailedException ex) {
                // fallback to default conversion logic below
                firstAttemptEx = ex;
            }
        }
    }

    // Value not of required type?
    if (editor != null
            || (requiredType != null && !ClassUtils.isAssignableValue(requiredType, convertedValue))) {
        if (requiredType != null && Collection.class.isAssignableFrom(requiredType)
                && convertedValue instanceof String) {
            TypeDescriptor elementType = typeDescriptor.getElementTypeDescriptor();
            if (elementType != null && Enum.class.isAssignableFrom(elementType.getType())) {
                convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue);
            }
        }
        if (editor == null) {
            editor = findDefaultEditor(requiredType);
        }
        convertedValue = doConvertValue(oldValue, convertedValue, requiredType, editor);
    }

    boolean standardConversion = false;

    if (requiredType != null) {
        // Try to apply some standard type conversion rules if appropriate.

        if (convertedValue != null) {
            if (requiredType.isArray()) {
                // Array required -> apply appropriate conversion of elements.
                if (convertedValue instanceof String
                        && Enum.class.isAssignableFrom(requiredType.getComponentType())) {
                    convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue);
                }
                return (T) convertToTypedArray(convertedValue, propertyName, requiredType.getComponentType());
            } else if (convertedValue instanceof Collection) {
                // Convert elements to target type, if determined.
                convertedValue = convertToTypedCollection((Collection) convertedValue, propertyName,
                        requiredType, typeDescriptor);
                standardConversion = true;
            } else if (convertedValue instanceof Map) {
                // Convert keys and values to respective target type, if determined.
                convertedValue = convertToTypedMap((Map) convertedValue, propertyName, requiredType,
                        typeDescriptor);
                standardConversion = true;
            }
            if (convertedValue.getClass().isArray() && Array.getLength(convertedValue) == 1) {
                convertedValue = Array.get(convertedValue, 0);
                standardConversion = true;
            }
            if (String.class.equals(requiredType)
                    && ClassUtils.isPrimitiveOrWrapper(convertedValue.getClass())) {
                // We can stringify any primitive value...
                return (T) convertedValue.toString();
            } else if (convertedValue instanceof String && !requiredType.isInstance(convertedValue)) {
                if (firstAttemptEx == null && !requiredType.isInterface() && !requiredType.isEnum()) {
                    try {
                        Constructor strCtor = requiredType.getConstructor(String.class);
                        return (T) BeanUtils.instantiateClass(strCtor, convertedValue);
                    } catch (NoSuchMethodException ex) {
                        // proceed with field lookup
                        if (logger.isTraceEnabled()) {
                            logger.trace("No String constructor found on type [" + requiredType.getName() + "]",
                                    ex);
                        }
                    } catch (Exception ex) {
                        if (logger.isDebugEnabled()) {
                            logger.debug(
                                    "Construction via String failed for type [" + requiredType.getName() + "]",
                                    ex);
                        }
                    }
                }
                String trimmedValue = ((String) convertedValue).trim();
                if (requiredType.isEnum() && "".equals(trimmedValue)) {
                    // It's an empty enum identifier: reset the enum value to null.
                    return null;
                }
                convertedValue = attemptToConvertStringToEnum(requiredType, trimmedValue, convertedValue);
                standardConversion = true;
            }
        }

        if (!ClassUtils.isAssignableValue(requiredType, convertedValue)) {
            if (firstAttemptEx != null) {
                throw firstAttemptEx;
            }
            // Definitely doesn't match: throw IllegalArgumentException/IllegalStateException
            StringBuilder msg = new StringBuilder();
            msg.append("Cannot convert value of type [").append(ClassUtils.getDescriptiveType(newValue));
            msg.append("] to required type [").append(ClassUtils.getQualifiedName(requiredType)).append("]");
            if (propertyName != null) {
                msg.append(" for property '").append(propertyName).append("'");
            }
            if (editor != null) {
                msg.append(": PropertyEditor [").append(editor.getClass().getName())
                        .append("] returned inappropriate value of type [")
                        .append(ClassUtils.getDescriptiveType(convertedValue)).append("]");
                throw new IllegalArgumentException(msg.toString());
            } else {
                msg.append(": no matching editors or conversion strategy found");
                throw new IllegalStateException(msg.toString());
            }
        }
    }

    if (firstAttemptEx != null) {
        if (editor == null && !standardConversion && requiredType != null
                && !Object.class.equals(requiredType)) {
            throw firstAttemptEx;
        }
        logger.debug("Original ConversionService attempt failed - ignored since "
                + "PropertyEditor based conversion eventually succeeded", firstAttemptEx);
    }

    return (T) convertedValue;
}

From source file:es.osoco.grails.plugins.otp.access.AbstractMultipleVoterFilterInvocationDefinition.java

protected List<String> split(final String value) {
    if (!value.startsWith("ROLE_") && !value.startsWith("IS_")) {
        // an expression
        return Collections.singletonList(value);
    }//from   ww w .j av a2  s  .  c  om

    String[] parts = StringUtils.commaDelimitedListToStringArray(value);
    List<String> cleaned = new ArrayList<String>();
    for (String part : parts) {
        part = part.trim();
        if (part.length() > 0) {
            cleaned.add(part);
        }
    }
    return cleaned;
}

From source file:org.eclipse.gemini.blueprint.test.AbstractDependencyManagerTests.java

/**
 * Locates (through the {@link ArtifactLocator}) an OSGi bundle given as a
 * String.//w  ww .j  a v  a2 s  .c om
 * 
 * The default implementation expects the argument to be in Comma Separated
 * Values (CSV) format which indicates an artifact group, id, version and
 * optionally the type.
 * 
 * @param bundleId the bundle identifier in CSV format
 * @return a resource pointing to the artifact location
 */
protected Resource locateBundle(String bundleId) {
    Assert.hasText(bundleId, "bundleId should not be empty");

    // parse the String
    String[] artifactId = StringUtils.commaDelimitedListToStringArray(bundleId);

    Assert.isTrue(artifactId.length >= 3, "the CSV string " + bundleId + " contains too few values");
    // TODO: add a smarter mechanism which can handle 1 or 2 values CSVs
    for (int i = 0; i < artifactId.length; i++) {
        artifactId[i] = StringUtils.trimWhitespace(artifactId[i]);
    }

    ArtifactLocator aLocator = getLocator();

    return (artifactId.length == 3 ? aLocator.locateArtifact(artifactId[0], artifactId[1], artifactId[2])
            : aLocator.locateArtifact(artifactId[0], artifactId[1], artifactId[2], artifactId[3]));
}

From source file:org.jlot.web.api.error.DefaultRestErrorResolver.java

protected RestError toRestError(String exceptionConfig) {
    String[] values = StringUtils.commaDelimitedListToStringArray(exceptionConfig);
    if (values == null || values.length == 0) {
        throw new IllegalStateException(
                "Invalid config mapping.  Exception names must map to a string configuration.");
    }//www  .java  2  s.  c  o m

    RestError restError = new RestError();

    boolean statusCodeSet = false;
    boolean msgSet = false;
    boolean devMsgSet = false;
    boolean moreInfoSet = false;

    for (String value : values) {

        String trimmedVal = StringUtils.trimWhitespace(value);

        // check to see if the value is an explicitly named key/value pair:
        String[] pair = StringUtils.split(trimmedVal, "=");
        if (pair != null) {
            // explicit attribute set:
            String pairKey = StringUtils.trimWhitespace(pair[0]);
            if (!StringUtils.hasText(pairKey)) {
                pairKey = null;
            }
            String pairValue = StringUtils.trimWhitespace(pair[1]);
            if (!StringUtils.hasText(pairValue)) {
                pairValue = null;
            }
            if ("statusCode".equalsIgnoreCase(pairKey)) {
                int statusCode = getRequiredInt(pairKey, pairValue);
                restError.setStatusCode(statusCode);
                statusCodeSet = true;
            } else if ("msg".equalsIgnoreCase(pairKey)) {
                restError.setMessage(pairValue);
                msgSet = true;
            } else if ("devMsg".equalsIgnoreCase(pairKey)) {
                restError.setDeveloperMessage(pairValue);
                devMsgSet = true;
            } else if ("infoUrl".equalsIgnoreCase(pairKey)) {
                restError.setMoreInfoUrl(pairValue);
                moreInfoSet = true;
            }
        } else {
            // not a key/value pair - use heuristics to determine what value
            // is being set:
            int val;
            if (!statusCodeSet) {
                val = getInt("statusCode", trimmedVal);
                if (val > 0) {
                    restError.setStatusCode(val);
                    statusCodeSet = true;
                    continue;
                }
            }
            if (!moreInfoSet && trimmedVal.toLowerCase().startsWith("http")) {
                restError.setMoreInfoUrl(trimmedVal);
                moreInfoSet = true;
                continue;
            }
            if (!msgSet) {
                restError.setMessage(trimmedVal);
                msgSet = true;
                continue;
            }
            if (!devMsgSet) {
                restError.setDeveloperMessage(trimmedVal);
                devMsgSet = true;
                continue;
            }
            if (!moreInfoSet) {
                restError.setMoreInfoUrl(trimmedVal);
                moreInfoSet = true;
                // noinspection UnnecessaryContinue
                continue;
            }
        }
    }

    return restError;
}

From source file:com.novation.eligibility.rest.spring.web.servlet.handler.DefaultRestErrorResolver.java

protected RestError toRestError(String exceptionConfig) {
    String[] values = StringUtils.commaDelimitedListToStringArray(exceptionConfig);
    if (values == null || values.length == 0) {
        throw new IllegalStateException(
                "Invalid config mapping.  Exception names must map to a string configuration.");
    }// w ww.j  av a 2 s  .c o m

    RestError.Builder builder = new RestError.Builder();

    boolean statusSet = false;
    boolean codeSet = false;
    boolean msgSet = false;
    boolean devMsgSet = false;
    boolean moreInfoSet = false;

    for (String value : values) {

        String trimmedVal = StringUtils.trimWhitespace(value);

        //check to see if the value is an explicitly named key/value pair:
        String[] pair = StringUtils.split(trimmedVal, "=");
        if (pair != null) {
            //explicit attribute set:
            String pairKey = StringUtils.trimWhitespace(pair[0]);
            if (!StringUtils.hasText(pairKey)) {
                pairKey = null;
            }
            String pairValue = StringUtils.trimWhitespace(pair[1]);
            if (!StringUtils.hasText(pairValue)) {
                pairValue = null;
            }
            if ("status".equalsIgnoreCase(pairKey)) {
                int statusCode = getRequiredInt(pairKey, pairValue);
                builder.setStatus(statusCode);
                statusSet = true;
            } else if ("code".equalsIgnoreCase(pairKey)) {
                int code = getRequiredInt(pairKey, pairValue);
                builder.setCode(code);
                codeSet = true;
            } else if ("msg".equalsIgnoreCase(pairKey)) {
                builder.setMessage(pairValue);
                msgSet = true;
            } else if ("devMsg".equalsIgnoreCase(pairKey)) {
                builder.setDeveloperMessage(pairValue);
                devMsgSet = true;
            } else if ("infoUrl".equalsIgnoreCase(pairKey)) {
                builder.setMoreInfoUrl(pairValue);
                moreInfoSet = true;
            }
        } else {
            //not a key/value pair - use heuristics to determine what value is being set:
            int val;
            if (!statusSet) {
                val = getInt("status", trimmedVal);
                if (val > 0) {
                    builder.setStatus(val);
                    statusSet = true;
                    continue;
                }
            }
            if (!codeSet) {
                val = getInt("code", trimmedVal);
                if (val > 0) {
                    builder.setCode(val);
                    codeSet = true;
                    continue;
                }
            }
            if (!moreInfoSet && trimmedVal.toLowerCase().startsWith("http")) {
                builder.setMoreInfoUrl(trimmedVal);
                moreInfoSet = true;
                continue;
            }
            if (!msgSet) {
                builder.setMessage(trimmedVal);
                msgSet = true;
                continue;
            }
            if (!devMsgSet) {
                builder.setDeveloperMessage(trimmedVal);
                devMsgSet = true;
                continue;
            }
            if (!moreInfoSet) {
                builder.setMoreInfoUrl(trimmedVal);
                moreInfoSet = true;
                //noinspection UnnecessaryContinue
                continue;
            }
        }
    }

    return builder.build();
}

From source file:com.breakidea.noah.web.velocity.VelocityEngineFactory.java

/**
 * Initialize a Velocity resource loader for the given VelocityEngine: either a standard Velocity FileResourceLoader
 * or a SpringResourceLoader./*from  ww w. j a va  2 s  . c  o  m*/
 * <p>
 * Called by {@code createVelocityEngine()}.
 * @param velocityEngine the VelocityEngine to configure
 * @param resourceLoaderPath the path to load Velocity resources from
 * @see org.apache.velocity.runtime.resource.loader.FileResourceLoader
 * @see SpringResourceLoader
 * @see #initSpringResourceLoader
 * @see #createVelocityEngine()
 */
protected void initVelocityResourceLoader(VelocityEngine velocityEngine, String resourceLoaderPath) {
    if (isPreferFileSystemAccess()) {
        // Try to load via the file system, fall back to SpringResourceLoader
        // (for hot detection of template changes, if possible).
        try {
            StringBuilder resolvedPath = new StringBuilder();
            String[] paths = StringUtils.commaDelimitedListToStringArray(resourceLoaderPath);
            for (int i = 0; i < paths.length; i++) {
                String path = paths[i];
                Resource resource = getResourceLoader().getResource(path);
                File file = resource.getFile(); // will fail if not resolvable in the file system
                if (logger.isDebugEnabled()) {
                    logger.debug("Resource loader path [" + path + "] resolved to file ["
                            + file.getAbsolutePath() + "]");
                }
                resolvedPath.append(file.getAbsolutePath());
                if (i < paths.length - 1) {
                    resolvedPath.append(',');
                }
            }

            velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, "true");
            velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, resolvedPath.toString());
        } catch (IOException ex) {
            if (logger.isDebugEnabled()) {
                logger.debug("Cannot resolve resource loader path [" + resourceLoaderPath
                        + "] to [java.io.File]: using SpringResourceLoader", ex);
            }
            initSpringResourceLoader(velocityEngine, resourceLoaderPath);
        }
    } else {
        // Always load via SpringResourceLoader
        // (without hot detection of template changes).
        if (logger.isDebugEnabled()) {
            logger.debug("File system access not preferred: using SpringResourceLoader");
        }
        initSpringResourceLoader(velocityEngine, resourceLoaderPath);
    }
}

From source file:org.springmodules.validation.bean.conf.loader.xml.handler.AbstractPropertyValidationElementHandler.java

/**
 * Extracts the names of the validation context in which the valiation rule is applicable. Expects a "contexts"
 * attribute to hold a comma-separated list of context names. If no such attribute exists or if it holds an empty
 * string, <code>null </code> is returned. As the contract of {@link AbstractValidationRule#setContextTokens(String[])}
 * defines <code>null</code> means that the rule always applies regardless of the context.
 *
 * @param element The element that represents the validation rule.
 * @return The names of the validation contexts in which the
 *//*from w  w  w  .ja v  a 2 s.  co  m*/
protected String[] extractApplicableContexts(Element element) {
    String contextString = element.getAttribute(CONTEXTS_ATTR);
    return (StringUtils.hasText(contextString)) ? StringUtils.commaDelimitedListToStringArray(contextString)
            : null;
}

From source file:net.alpha.velocity.spring.support.VelocityEngineFactory.java

/**
 * Initialize a Velocity resource loader for the given VelocityEngine:
 * either a standard Velocity FileResourceLoader or a SpringResourceLoader.
 * <p>Called by {@code createVelocityEngine()}.
 *
 * @param velocityEngine     the VelocityEngine to configure
 * @param resourceLoaderPath the path to load Velocity resources from
 * @see org.apache.velocity.runtime.resource.loader.FileResourceLoader
 * @see SpringResourceLoader/*  ww  w . j  av a2s  . c  o  m*/
 * @see #initSpringResourceLoader
 * @see #createVelocityEngine()
 */
protected void initVelocityResourceLoader(VelocityEngine velocityEngine, String resourceLoaderPath) {
    if (isPreferFileSystemAccess()) {
        // Try to load via the file system, fall back to SpringResourceLoader
        // (for hot detection of template changes, if possible).
        try {
            StringBuilder resolvedPath = new StringBuilder();
            String[] paths = StringUtils.commaDelimitedListToStringArray(resourceLoaderPath);
            for (int i = 0; i < paths.length; i++) {
                String path = paths[i];
                Resource resource = getResourceLoader().getResource(path);
                File file = resource.getFile(); // will fail if not resolvable in the file system
                if (logger.isDebugEnabled()) {
                    logger.debug("Resource loader path [" + path + "] resolved to file ["
                            + file.getAbsolutePath() + "]");
                }
                resolvedPath.append(file.getAbsolutePath());
                if (i < paths.length - 1) {
                    resolvedPath.append(',');
                }
            }
            velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, "true");
            velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, resolvedPath.toString());
        } catch (IOException ex) {
            if (logger.isDebugEnabled()) {
                logger.debug("Cannot resolve resource loader path [" + resourceLoaderPath
                        + "] to [java.io.File]: using SpringResourceLoader", ex);
            }
            initSpringResourceLoader(velocityEngine, resourceLoaderPath);
        }
    } else {
        // Always load via SpringResourceLoader
        // (without hot detection of template changes).
        if (logger.isDebugEnabled()) {
            logger.debug("File system access not preferred: using SpringResourceLoader");
        }
        initSpringResourceLoader(velocityEngine, resourceLoaderPath);
    }
}