Example usage for org.springframework.util StringUtils toStringArray

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

Introduction

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

Prototype

public static String[] toStringArray(@Nullable Enumeration<String> enumeration) 

Source Link

Document

Copy the given Enumeration into a String array.

Usage

From source file:org.springframework.test.context.support.AbstractTestContextBootstrapper.java

/**
 * Build the {@link MergedContextConfiguration merged context configuration}
 * for the supplied {@link Class testClass}, context configuration attributes,
 * and parent context configuration./*from   ww  w.j av  a  2  s .  co  m*/
 * @param testClass the test class for which the {@code MergedContextConfiguration}
 * should be built (must not be {@code null})
 * @param configAttributesList the list of context configuration attributes for the
 * specified test class, ordered <em>bottom-up</em> (i.e., as if we were
 * traversing up the class hierarchy); never {@code null} or empty
 * @param parentConfig the merged context configuration for the parent application
 * context in a context hierarchy, or {@code null} if there is no parent
 * @param cacheAwareContextLoaderDelegate the cache-aware context loader delegate to
 * be passed to the {@code MergedContextConfiguration} constructor
 * @param requireLocationsClassesOrInitializers whether locations, classes, or
 * initializers are required; typically {@code true} but may be set to {@code false}
 * if the configured loader supports empty configuration
 * @return the merged context configuration
 * @see #resolveContextLoader
 * @see ContextLoaderUtils#resolveContextConfigurationAttributes
 * @see SmartContextLoader#processContextConfiguration
 * @see ContextLoader#processLocations
 * @see ActiveProfilesUtils#resolveActiveProfiles
 * @see ApplicationContextInitializerUtils#resolveInitializerClasses
 * @see MergedContextConfiguration
 */
private MergedContextConfiguration buildMergedContextConfiguration(Class<?> testClass,
        List<ContextConfigurationAttributes> configAttributesList,
        @Nullable MergedContextConfiguration parentConfig,
        CacheAwareContextLoaderDelegate cacheAwareContextLoaderDelegate,
        boolean requireLocationsClassesOrInitializers) {

    Assert.notEmpty(configAttributesList, "ContextConfigurationAttributes list must not be null or empty");

    ContextLoader contextLoader = resolveContextLoader(testClass, configAttributesList);
    List<String> locations = new ArrayList<>();
    List<Class<?>> classes = new ArrayList<>();
    List<Class<?>> initializers = new ArrayList<>();

    for (ContextConfigurationAttributes configAttributes : configAttributesList) {
        if (logger.isTraceEnabled()) {
            logger.trace(
                    String.format("Processing locations and classes for context configuration attributes %s",
                            configAttributes));
        }
        if (contextLoader instanceof SmartContextLoader) {
            SmartContextLoader smartContextLoader = (SmartContextLoader) contextLoader;
            smartContextLoader.processContextConfiguration(configAttributes);
            locations.addAll(0, Arrays.asList(configAttributes.getLocations()));
            classes.addAll(0, Arrays.asList(configAttributes.getClasses()));
        } else {
            String[] processedLocations = contextLoader.processLocations(configAttributes.getDeclaringClass(),
                    configAttributes.getLocations());
            locations.addAll(0, Arrays.asList(processedLocations));
            // Legacy ContextLoaders don't know how to process classes
        }
        initializers.addAll(0, Arrays.asList(configAttributes.getInitializers()));
        if (!configAttributes.isInheritLocations()) {
            break;
        }
    }

    Set<ContextCustomizer> contextCustomizers = getContextCustomizers(testClass,
            Collections.unmodifiableList(configAttributesList));

    Assert.state(
            !(requireLocationsClassesOrInitializers
                    && areAllEmpty(locations, classes, initializers, contextCustomizers)),
            () -> String.format(
                    "%s was unable to detect defaults, and no ApplicationContextInitializers "
                            + "or ContextCustomizers were declared for context configuration attributes %s",
                    contextLoader.getClass().getSimpleName(), configAttributesList));

    MergedTestPropertySources mergedTestPropertySources = TestPropertySourceUtils
            .buildMergedTestPropertySources(testClass);
    MergedContextConfiguration mergedConfig = new MergedContextConfiguration(testClass,
            StringUtils.toStringArray(locations), ClassUtils.toClassArray(classes),
            ApplicationContextInitializerUtils.resolveInitializerClasses(configAttributesList),
            ActiveProfilesUtils.resolveActiveProfiles(testClass), mergedTestPropertySources.getLocations(),
            mergedTestPropertySources.getProperties(), contextCustomizers, contextLoader,
            cacheAwareContextLoaderDelegate, parentConfig);

    return processMergedContextConfiguration(mergedConfig);
}

From source file:org.springframework.test.context.support.ActiveProfilesUtils.java

/**
 * Resolve <em>active bean definition profiles</em> for the supplied {@link Class}.
 * <p>Note that the {@link ActiveProfiles#inheritProfiles inheritProfiles} flag of
 * {@link ActiveProfiles @ActiveProfiles} will be taken into consideration.
 * Specifically, if the {@code inheritProfiles} flag is set to {@code true}, profiles
 * defined in the test class will be merged with those defined in superclasses.
 * @param testClass the class for which to resolve the active profiles (must not be
 * {@code null})//www .  j av a  2s  . c  om
 * @return the set of active profiles for the specified class, including active
 * profiles from superclasses if appropriate (never {@code null})
 * @see ActiveProfiles
 * @see ActiveProfilesResolver
 * @see org.springframework.context.annotation.Profile
 */
static String[] resolveActiveProfiles(Class<?> testClass) {
    Assert.notNull(testClass, "Class must not be null");

    final List<String[]> profileArrays = new ArrayList<>();

    Class<ActiveProfiles> annotationType = ActiveProfiles.class;
    AnnotationDescriptor<ActiveProfiles> descriptor = MetaAnnotationUtils.findAnnotationDescriptor(testClass,
            annotationType);
    if (descriptor == null && logger.isDebugEnabled()) {
        logger.debug(String.format(
                "Could not find an 'annotation declaring class' for annotation type [%s] and class [%s]",
                annotationType.getName(), testClass.getName()));
    }

    while (descriptor != null) {
        Class<?> rootDeclaringClass = descriptor.getRootDeclaringClass();
        Class<?> declaringClass = descriptor.getDeclaringClass();
        ActiveProfiles annotation = descriptor.synthesizeAnnotation();

        if (logger.isTraceEnabled()) {
            logger.trace(String.format("Retrieved @ActiveProfiles [%s] for declaring class [%s]", annotation,
                    declaringClass.getName()));
        }

        Class<? extends ActiveProfilesResolver> resolverClass = annotation.resolver();
        if (ActiveProfilesResolver.class == resolverClass) {
            resolverClass = DefaultActiveProfilesResolver.class;
        }

        ActiveProfilesResolver resolver;
        try {
            resolver = BeanUtils.instantiateClass(resolverClass, ActiveProfilesResolver.class);
        } catch (Exception ex) {
            String msg = String.format(
                    "Could not instantiate ActiveProfilesResolver of type [%s] " + "for test class [%s]",
                    resolverClass.getName(), rootDeclaringClass.getName());
            logger.error(msg);
            throw new IllegalStateException(msg, ex);
        }

        String[] profiles = resolver.resolve(rootDeclaringClass);
        if (!ObjectUtils.isEmpty(profiles)) {
            profileArrays.add(profiles);
        }

        descriptor = (annotation.inheritProfiles()
                ? MetaAnnotationUtils.findAnnotationDescriptor(rootDeclaringClass.getSuperclass(),
                        annotationType)
                : null);
    }

    // Reverse the list so that we can traverse "down" the hierarchy.
    Collections.reverse(profileArrays);

    final Set<String> activeProfiles = new LinkedHashSet<>();
    for (String[] profiles : profileArrays) {
        for (String profile : profiles) {
            if (StringUtils.hasText(profile)) {
                activeProfiles.add(profile.trim());
            }
        }
    }

    return StringUtils.toStringArray(activeProfiles);
}

From source file:org.springframework.test.context.support.DefaultActiveProfilesResolver.java

/**
 * Resolve the <em>bean definition profiles</em> for the given {@linkplain
 * Class test class} based on profiles configured declaratively via
 * {@link ActiveProfiles#profiles} or {@link ActiveProfiles#value}.
 * @param testClass the test class for which the profiles should be resolved;
 * never {@code null}//from   w  w w  .  j  av a 2s . c  o  m
 * @return the list of bean definition profiles to use when loading the
 * {@code ApplicationContext}; never {@code null}
 */
@Override
public String[] resolve(Class<?> testClass) {
    Assert.notNull(testClass, "Class must not be null");

    final Set<String> activeProfiles = new LinkedHashSet<>();

    Class<ActiveProfiles> annotationType = ActiveProfiles.class;
    AnnotationDescriptor<ActiveProfiles> descriptor = findAnnotationDescriptor(testClass, annotationType);

    if (descriptor == null) {
        if (logger.isDebugEnabled()) {
            logger.debug(String.format(
                    "Could not find an 'annotation declaring class' for annotation type [%s] and class [%s]",
                    annotationType.getName(), testClass.getName()));
        }
    } else {
        Class<?> declaringClass = descriptor.getDeclaringClass();
        ActiveProfiles annotation = descriptor.synthesizeAnnotation();

        if (logger.isTraceEnabled()) {
            logger.trace(String.format("Retrieved @ActiveProfiles [%s] for declaring class [%s].", annotation,
                    declaringClass.getName()));
        }

        for (String profile : annotation.profiles()) {
            if (StringUtils.hasText(profile)) {
                activeProfiles.add(profile.trim());
            }
        }
    }

    return StringUtils.toStringArray(activeProfiles);
}

From source file:org.springframework.test.context.support.TestPropertySourceUtils.java

private static String[] mergeLocations(List<TestPropertySourceAttributes> attributesList) {
    List<String> locations = new ArrayList<>();
    for (TestPropertySourceAttributes attrs : attributesList) {
        if (logger.isTraceEnabled()) {
            logger.trace(String.format("Processing locations for TestPropertySource attributes %s", attrs));
        }/*from   w w  w.ja v a  2  s.co m*/
        String[] locationsArray = TestContextResourceUtils
                .convertToClasspathResourcePaths(attrs.getDeclaringClass(), attrs.getLocations());
        locations.addAll(0, Arrays.asList(locationsArray));
        if (!attrs.isInheritLocations()) {
            break;
        }
    }
    return StringUtils.toStringArray(locations);
}

From source file:org.springframework.test.context.support.TestPropertySourceUtils.java

private static String[] mergeProperties(List<TestPropertySourceAttributes> attributesList) {
    List<String> properties = new ArrayList<>();
    for (TestPropertySourceAttributes attrs : attributesList) {
        if (logger.isTraceEnabled()) {
            logger.trace(/*from   w  ww.j  a  v  a 2s . com*/
                    String.format("Processing inlined properties for TestPropertySource attributes %s", attrs));
        }
        String[] attrProps = attrs.getProperties();
        if (attrProps != null) {
            properties.addAll(0, Arrays.asList(attrProps));
        }
        if (!attrs.isInheritProperties()) {
            break;
        }
    }
    return StringUtils.toStringArray(properties);
}

From source file:org.springframework.web.context.request.FacesRequestAttributes.java

@Override
public String[] getAttributeNames(int scope) {
    return StringUtils.toStringArray(getAttributeMap(scope).keySet());
}

From source file:org.springframework.web.context.request.ServletRequestAttributes.java

public String[] getAttributeNames(int scope) {
    if (scope == SCOPE_REQUEST) {
        return StringUtils.toStringArray(this.request.getAttributeNames());
    } else {/*ww w . j a v  a2  s  .c om*/
        HttpSession session = getSession(false);
        if (session != null) {
            return StringUtils.toStringArray(session.getAttributeNames());
        } else {
            return new String[0];
        }
    }
}

From source file:org.springframework.web.portlet.context.PortletRequestAttributes.java

public String[] getAttributeNames(int scope) {
    if (scope == SCOPE_REQUEST) {
        return StringUtils.toStringArray(this.request.getAttributeNames());
    } else {/*  www. j  ava 2 s .  c o m*/
        PortletSession session = getSession(false);
        if (session != null) {
            if (scope == SCOPE_GLOBAL_SESSION) {
                return StringUtils.toStringArray(session.getAttributeNames(PortletSession.APPLICATION_SCOPE));
            } else {
                return StringUtils.toStringArray(session.getAttributeNames());
            }
        } else {
            return new String[0];
        }
    }
}

From source file:org.tinygroup.weblayer.webcontext.parser.util.BeanWrapperImpl.java

/**
 * Parse the given property name into the corresponding property name tokens.
 * @param propertyName the property name to parse
 * @return representation of the parsed property tokens
 *///  w ww .  java2s .  c  o  m
private PropertyTokenHolder getPropertyNameTokens(String propertyName) {
    PropertyTokenHolder tokens = new PropertyTokenHolder();
    String actualName = null;
    List keys = new ArrayList(2);
    int searchIndex = 0;
    while (searchIndex != -1) {
        int keyStart = propertyName.indexOf(PROPERTY_KEY_PREFIX, searchIndex);
        searchIndex = -1;
        if (keyStart != -1) {
            int keyEnd = propertyName.indexOf(PROPERTY_KEY_SUFFIX, keyStart + PROPERTY_KEY_PREFIX.length());
            if (keyEnd != -1) {
                if (actualName == null) {
                    actualName = propertyName.substring(0, keyStart);
                }
                String key = propertyName.substring(keyStart + PROPERTY_KEY_PREFIX.length(), keyEnd);
                if ((key.startsWith("'") && key.endsWith("'"))
                        || (key.startsWith("\"") && key.endsWith("\""))) {
                    key = key.substring(1, key.length() - 1);
                }
                keys.add(key);
                searchIndex = keyEnd + PROPERTY_KEY_SUFFIX.length();
            }
        }
    }
    tokens.actualName = (actualName != null ? actualName : propertyName);
    tokens.canonicalName = tokens.actualName;
    if (!keys.isEmpty()) {
        tokens.canonicalName += PROPERTY_KEY_PREFIX
                + StringUtils.collectionToDelimitedString(keys, PROPERTY_KEY_SUFFIX + PROPERTY_KEY_PREFIX)
                + PROPERTY_KEY_SUFFIX;
        tokens.keys = StringUtils.toStringArray(keys);
    }
    return tokens;
}