Example usage for org.springframework.util ObjectUtils isEmpty

List of usage examples for org.springframework.util ObjectUtils isEmpty

Introduction

In this page you can find the example usage for org.springframework.util ObjectUtils isEmpty.

Prototype

@SuppressWarnings("rawtypes")
public static boolean isEmpty(@Nullable Object obj) 

Source Link

Document

Determine whether the given object is empty.

Usage

From source file:org.springframework.test.context.ContextLoaderUtils.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})//from   w  ww. j  av  a 2  s. c o m
 * @return the set of active profiles for the specified class, including active
 * profiles from superclasses if appropriate (never {@code null})
 * @see ActiveProfiles
 * @see org.springframework.context.annotation.Profile
 */
static String[] resolveActiveProfiles(Class<?> testClass) {
    Assert.notNull(testClass, "Class must not be null");

    Class<ActiveProfiles> annotationType = ActiveProfiles.class;
    Class<?> declaringClass = findAnnotationDeclaringClass(annotationType, testClass);

    if (declaringClass == 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()));
    }

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

    while (declaringClass != null) {
        ActiveProfiles annotation = declaringClass.getAnnotation(annotationType);

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

        String[] profiles = annotation.profiles();
        String[] valueProfiles = annotation.value();

        if (!ObjectUtils.isEmpty(valueProfiles) && !ObjectUtils.isEmpty(profiles)) {
            String msg = String.format(
                    "Test class [%s] has been configured with @ActiveProfiles' 'value' [%s] "
                            + "and 'profiles' [%s] attributes. Only one declaration of active bean "
                            + "definition profiles is permitted per @ActiveProfiles annotation.",
                    declaringClass.getName(), ObjectUtils.nullSafeToString(valueProfiles),
                    ObjectUtils.nullSafeToString(profiles));
            logger.error(msg);
            throw new IllegalStateException(msg);
        } else if (!ObjectUtils.isEmpty(valueProfiles)) {
            profiles = valueProfiles;
        }

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

        declaringClass = annotation.inheritProfiles()
                ? findAnnotationDeclaringClass(annotationType, declaringClass.getSuperclass())
                : null;
    }

    return StringUtils.toStringArray(activeProfiles);
}

From source file:org.springframework.test.context.jdbc.DatabaseInitializerTestExecutionListener.java

private String[] getScripts(DatabaseInitializer databaseInitializer, TestContext testContext,
        boolean classLevel) {
    String[] scripts = databaseInitializer.scripts();
    String[] value = databaseInitializer.value();
    boolean scriptsDeclared = !ObjectUtils.isEmpty(scripts);
    boolean valueDeclared = !ObjectUtils.isEmpty(value);

    if (valueDeclared && scriptsDeclared) {
        String elementType = (classLevel ? "class" : "method");
        String elementName = (classLevel ? testContext.getTestClass().getName()
                : testContext.getTestMethod().toString());
        String msg = String.format(
                "Test %s [%s] has been configured with @DatabaseInitializer's 'value' [%s] "
                        + "and 'scripts' [%s] attributes. Only one declaration of SQL script "
                        + "paths is permitted per @DatabaseInitializer annotation.",
                elementType, elementName, ObjectUtils.nullSafeToString(value),
                ObjectUtils.nullSafeToString(scripts));
        logger.error(msg);/*from   w w w  . j a  v a 2 s. c o m*/
        throw new IllegalStateException(msg);
    }
    if (valueDeclared) {
        scripts = value;
    }
    if (ObjectUtils.isEmpty(scripts)) {
        scripts = new String[] { detectDefaultScript(testContext, classLevel) };
    }
    return scripts;
}

From source file:org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.java

private String[] getScripts(Sql sql, TestContext testContext, boolean classLevel) {
    String[] scripts = sql.scripts();
    if (ObjectUtils.isEmpty(scripts) && ObjectUtils.isEmpty(sql.statements())) {
        scripts = new String[] { detectDefaultScript(testContext, classLevel) };
    }//from  w  w w  .  ja  v a2s  . c  o m
    return scripts;
}

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

/**
 * If the supplied {@code locations} are {@code null} or <em>empty</em>
 * and {@link #isGenerateDefaultLocations()} returns {@code true},
 * default locations will be {@link #generateDefaultLocations(Class)
 * generated} (i.e., detected) for the specified {@link Class class}
 * and the configured {@linkplain #getResourceSuffixes() resource suffixes};
 * otherwise, the supplied {@code locations} will be
 * {@linkplain #modifyLocations modified} if necessary and returned.
 * @param clazz the class with which the locations are associated: to be
 * used when generating default locations
 * @param locations the unmodified locations to use for loading the
 * application context (can be {@code null} or empty)
 * @return a processed array of application context resource locations
 * @since 2.5/*  w  ww.  j  a v  a  2s  . co m*/
 * @see #isGenerateDefaultLocations()
 * @see #generateDefaultLocations(Class)
 * @see #modifyLocations(Class, String...)
 * @see org.springframework.test.context.ContextLoader#processLocations(Class, String...)
 * @see #processContextConfiguration(ContextConfigurationAttributes)
 */
@Override
public final String[] processLocations(Class<?> clazz, String... locations) {
    return (ObjectUtils.isEmpty(locations) && isGenerateDefaultLocations()) ? generateDefaultLocations(clazz)
            : modifyLocations(clazz, locations);
}

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})/*w w w . j a v a 2 s . c o m*/
 * @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.DelegatingSmartContextLoader.java

private static boolean supports(SmartContextLoader loader, MergedContextConfiguration mergedConfig) {
    if (loader instanceof AnnotationConfigContextLoader) {
        return ObjectUtils.isEmpty(mergedConfig.getLocations())
                && !ObjectUtils.isEmpty(mergedConfig.getClasses());
    } else {/*from   w  w  w  . ja v  a  2 s. c  om*/
        return !ObjectUtils.isEmpty(mergedConfig.getLocations())
                && ObjectUtils.isEmpty(mergedConfig.getClasses());
    }
}

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

private TestPropertySourceAttributes(Class<?> declaringClass, String[] locations, boolean inheritLocations,
        String[] properties, boolean inheritProperties) {

    Assert.notNull(declaringClass, "declaringClass must not be null");
    if (ObjectUtils.isEmpty(locations) && ObjectUtils.isEmpty(properties)) {
        locations = new String[] { detectDefaultPropertiesFile(declaringClass) };
    }/*from  w ww.  j av a2s.c  om*/
    this.declaringClass = declaringClass;
    this.locations = locations;
    this.inheritLocations = inheritLocations;
    this.properties = properties;
    this.inheritProperties = inheritProperties;
}

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

/**
 * Add the given <em>inlined properties</em> (in the form of <em>key-value</em>
 * pairs) to the supplied {@link ConfigurableEnvironment environment}.
 * <p>All key-value pairs will be added to the {@code Environment} as a
 * single {@link MapPropertySource} with the highest precedence.
 * <p>For details on the parsing of <em>inlined properties</em>, consult the
 * Javadoc for {@link #convertInlinedPropertiesToMap}.
 * @param environment the environment to update; never {@code null}
 * @param inlinedProperties the inlined properties to add to the environment;
 * potentially empty but never {@code null}
 * @since 4.1.5//w  w  w. jav  a 2s. com
 * @see MapPropertySource
 * @see #INLINED_PROPERTIES_PROPERTY_SOURCE_NAME
 * @see TestPropertySource#properties
 * @see #convertInlinedPropertiesToMap
 */
public static void addInlinedPropertiesToEnvironment(ConfigurableEnvironment environment,
        String... inlinedProperties) {
    Assert.notNull(environment, "'environment' must not be null");
    Assert.notNull(inlinedProperties, "'inlinedProperties' must not be null");
    if (!ObjectUtils.isEmpty(inlinedProperties)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Adding inlined properties to environment: "
                    + ObjectUtils.nullSafeToString(inlinedProperties));
        }
        MapPropertySource ps = (MapPropertySource) environment.getPropertySources()
                .get(INLINED_PROPERTIES_PROPERTY_SOURCE_NAME);
        if (ps == null) {
            ps = new MapPropertySource(INLINED_PROPERTIES_PROPERTY_SOURCE_NAME, new LinkedHashMap<>());
            environment.getPropertySources().addFirst(ps);
        }
        ps.getSource().putAll(convertInlinedPropertiesToMap(inlinedProperties));
    }
}

From source file:org.springframework.validation.DataBinder.java

/**
 * Add a custom formatter for the field type specified in {@link Formatter} class,
 * applying it to the specified fields only, if any, or otherwise to all fields.
 * <p>Registers a corresponding {@link PropertyEditor} adapter underneath the covers.
 * @param formatter the formatter to add, generically declared for a specific type
 * @param fields the fields to apply the formatter to, or none if to be applied to all
 * @since 4.2//from w ww  .jav  a 2  s  .c  o  m
 * @see #registerCustomEditor(Class, String, PropertyEditor)
 */
public void addCustomFormatter(Formatter<?> formatter, String... fields) {
    FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter);
    Class<?> fieldType = adapter.getFieldType();
    if (ObjectUtils.isEmpty(fields)) {
        getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter);
    } else {
        for (String field : fields) {
            getPropertyEditorRegistry().registerCustomEditor(fieldType, field, adapter);
        }
    }
}

From source file:org.springframework.validation.DataBinder.java

/**
 * Add a custom formatter, applying it to the specified field types only, if any,
 * or otherwise to all fields matching the {@link Formatter}-declared type.
 * <p>Registers a corresponding {@link PropertyEditor} adapter underneath the covers.
 * @param formatter the formatter to add (does not need to generically declare a
 * field type if field types are explicitly specified as parameters)
 * @param fieldTypes the field types to apply the formatter to, or none if to be
 * derived from the given {@link Formatter} implementation class
 * @since 4.2//from   w  w  w. ja  v a2  s  .  com
 * @see #registerCustomEditor(Class, PropertyEditor)
 */
public void addCustomFormatter(Formatter<?> formatter, Class<?>... fieldTypes) {
    FormatterPropertyEditorAdapter adapter = new FormatterPropertyEditorAdapter(formatter);
    if (ObjectUtils.isEmpty(fieldTypes)) {
        getPropertyEditorRegistry().registerCustomEditor(adapter.getFieldType(), adapter);
    } else {
        for (Class<?> fieldType : fieldTypes) {
            getPropertyEditorRegistry().registerCustomEditor(fieldType, adapter);
        }
    }
}