Example usage for org.springframework.util ObjectUtils nullSafeToString

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

Introduction

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

Prototype

public static String nullSafeToString(@Nullable short[] array) 

Source Link

Document

Return a String representation of the contents of the specified array.

Usage

From source file:org.springframework.test.AbstractSpringContextTests.java

private final String contextKey(String... locations) {
    return ObjectUtils.nullSafeToString(locations);
}

From source file:org.springframework.test.context.ContextConfigurationAttributes.java

/**
 * Construct a new {@link ContextConfigurationAttributes} instance for the
 * {@linkplain Class test class} that declared the
 * {@link ContextConfiguration @ContextConfiguration} annotation and its
 * corresponding attributes./*from   w w  w  .j  a va  2  s. com*/
 * @param declaringClass the test class that declared {@code @ContextConfiguration}
 * @param locations the resource locations declared via {@code @ContextConfiguration}
 * @param classes the annotated classes declared via {@code @ContextConfiguration}
 * @param inheritLocations the {@code inheritLocations} flag declared via {@code @ContextConfiguration}
 * @param initializers the context initializers declared via {@code @ContextConfiguration}
 * @param inheritInitializers the {@code inheritInitializers} flag declared via {@code @ContextConfiguration}
 * @param name the name of level in the context hierarchy, or {@code null} if not applicable
 * @param contextLoaderClass the {@code ContextLoader} class declared via {@code @ContextConfiguration}
 * @throws IllegalArgumentException if the {@code declaringClass} or {@code contextLoaderClass} is
 * {@code null}
 */
public ContextConfigurationAttributes(Class<?> declaringClass, String[] locations, Class<?>[] classes,
        boolean inheritLocations, Class<? extends ApplicationContextInitializer<?>>[] initializers,
        boolean inheritInitializers, @Nullable String name, Class<? extends ContextLoader> contextLoaderClass) {

    Assert.notNull(declaringClass, "'declaringClass' must not be null");
    Assert.notNull(contextLoaderClass, "'contextLoaderClass' must not be null");

    if (!ObjectUtils.isEmpty(locations) && !ObjectUtils.isEmpty(classes) && logger.isDebugEnabled()) {
        logger.debug(String.format(
                "Test class [%s] has been configured with @ContextConfiguration's 'locations' (or 'value') %s "
                        + "and 'classes' %s attributes. Most SmartContextLoader implementations support "
                        + "only one declaration of resources per @ContextConfiguration annotation.",
                declaringClass.getName(), ObjectUtils.nullSafeToString(locations),
                ObjectUtils.nullSafeToString(classes)));
    }

    this.declaringClass = declaringClass;
    this.locations = locations;
    this.classes = classes;
    this.inheritLocations = inheritLocations;
    this.initializers = initializers;
    this.inheritInitializers = inheritInitializers;
    this.name = (StringUtils.hasText(name) ? name : null);
    this.contextLoaderClass = contextLoaderClass;
}

From source file:org.springframework.test.context.ContextConfigurationAttributes.java

/**
 * Provide a String representation of the context configuration attributes
 * and declaring class./* w w w .  j av  a2s  .  c  o m*/
 */
@Override
public String toString() {
    return new ToStringCreator(this).append("declaringClass", this.declaringClass.getName())
            .append("classes", ObjectUtils.nullSafeToString(this.classes))
            .append("locations", ObjectUtils.nullSafeToString(this.locations))
            .append("inheritLocations", this.inheritLocations)
            .append("initializers", ObjectUtils.nullSafeToString(this.initializers))
            .append("inheritInitializers", this.inheritInitializers).append("name", this.name)
            .append("contextLoaderClass", this.contextLoaderClass.getName()).toString();
}

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.  ja  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 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

/**
 * Execute the SQL scripts configured via the supplied
 * {@link DatabaseInitializer @DatabaseInitializer} for the given
 * {@link ExecutionPhase} and {@link TestContext}.
 *
 * <p>Special care must be taken in order to properly support the
 * {@link DatabaseInitializer#requireNewTransaction requireNewTransaction}
 * flag./*from  ww w  .ja v  a  2s.  c o m*/
 *
 * @param databaseInitializer the {@code @DatabaseInitializer} to parse
 * @param executionPhase the current execution phase
 * @param testContext the current {@code TestContext}
 * @param classLevel {@code true} if {@link DatabaseInitializer @DatabaseInitializer}
 * was declared at the class level
 */
@SuppressWarnings("serial")
private void executeDatabaseInitializer(DatabaseInitializer databaseInitializer, ExecutionPhase executionPhase,
        TestContext testContext, boolean classLevel) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug(String.format("Processing %s for execution phase [%s] and test context %s.",
                databaseInitializer, executionPhase, testContext));
    }

    if (executionPhase != databaseInitializer.executionPhase()) {
        return;
    }

    final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.setSqlScriptEncoding(databaseInitializer.encoding());
    populator.setSeparator(databaseInitializer.separator());
    populator.setCommentPrefix(databaseInitializer.commentPrefix());
    populator.setBlockCommentStartDelimiter(databaseInitializer.blockCommentStartDelimiter());
    populator.setBlockCommentEndDelimiter(databaseInitializer.blockCommentEndDelimiter());
    populator.setContinueOnError(databaseInitializer.continueOnError());
    populator.setIgnoreFailedDrops(databaseInitializer.ignoreFailedDrops());

    String[] scripts = getScripts(databaseInitializer, testContext, classLevel);
    scripts = TestContextResourceUtils.convertToClasspathResourcePaths(testContext.getTestClass(), scripts);
    populator.setScripts(
            TestContextResourceUtils.convertToResources(testContext.getApplicationContext(), scripts));
    if (logger.isDebugEnabled()) {
        logger.debug("Executing SQL scripts: " + ObjectUtils.nullSafeToString(scripts));
    }

    final DataSource dataSource = TestContextTransactionUtils.retrieveDataSource(testContext,
            databaseInitializer.dataSource());
    final PlatformTransactionManager transactionManager = TestContextTransactionUtils
            .retrieveTransactionManager(testContext, databaseInitializer.transactionManager());

    int propagation = databaseInitializer.requireNewTransaction()
            ? TransactionDefinition.PROPAGATION_REQUIRES_NEW
            : TransactionDefinition.PROPAGATION_REQUIRED;

    TransactionAttribute transactionAttribute = TestContextTransactionUtils
            .createDelegatingTransactionAttribute(testContext, new DefaultTransactionAttribute(propagation));

    new TransactionTemplate(transactionManager, transactionAttribute)
            .execute(new TransactionCallbackWithoutResult() {

                @Override
                public void doInTransactionWithoutResult(TransactionStatus status) {
                    populator.execute(dataSource);
                };
            });
}

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 av  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

/**
 * Execute the SQL scripts configured via the supplied {@link Sql @Sql}
 * annotation for the given {@link ExecutionPhase} and {@link TestContext}.
 * <p>Special care must be taken in order to properly support the configured
 * {@link SqlConfig#transactionMode}./*from ww  w .  j a v a 2  s  . c om*/
 * @param sql the {@code @Sql} annotation to parse
 * @param executionPhase the current execution phase
 * @param testContext the current {@code TestContext}
 * @param classLevel {@code true} if {@link Sql @Sql} was declared at the class level
 */
private void executeSqlScripts(Sql sql, ExecutionPhase executionPhase, TestContext testContext,
        boolean classLevel) throws Exception {

    if (executionPhase != sql.executionPhase()) {
        return;
    }

    MergedSqlConfig mergedSqlConfig = new MergedSqlConfig(sql.config(), testContext.getTestClass());
    if (logger.isDebugEnabled()) {
        logger.debug(String.format("Processing %s for execution phase [%s] and test context %s.",
                mergedSqlConfig, executionPhase, testContext));
    }

    final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.setSqlScriptEncoding(mergedSqlConfig.getEncoding());
    populator.setSeparator(mergedSqlConfig.getSeparator());
    populator.setCommentPrefix(mergedSqlConfig.getCommentPrefix());
    populator.setBlockCommentStartDelimiter(mergedSqlConfig.getBlockCommentStartDelimiter());
    populator.setBlockCommentEndDelimiter(mergedSqlConfig.getBlockCommentEndDelimiter());
    populator.setContinueOnError(mergedSqlConfig.getErrorMode() == ErrorMode.CONTINUE_ON_ERROR);
    populator.setIgnoreFailedDrops(mergedSqlConfig.getErrorMode() == ErrorMode.IGNORE_FAILED_DROPS);

    String[] scripts = getScripts(sql, testContext, classLevel);
    scripts = TestContextResourceUtils.convertToClasspathResourcePaths(testContext.getTestClass(), scripts);
    List<Resource> scriptResources = TestContextResourceUtils
            .convertToResourceList(testContext.getApplicationContext(), scripts);
    for (String stmt : sql.statements()) {
        if (StringUtils.hasText(stmt)) {
            stmt = stmt.trim();
            scriptResources.add(new ByteArrayResource(stmt.getBytes(), "from inlined SQL statement: " + stmt));
        }
    }
    populator.setScripts(scriptResources.toArray(new Resource[scriptResources.size()]));
    if (logger.isDebugEnabled()) {
        logger.debug("Executing SQL scripts: " + ObjectUtils.nullSafeToString(scriptResources));
    }

    String dsName = mergedSqlConfig.getDataSource();
    String tmName = mergedSqlConfig.getTransactionManager();
    DataSource dataSource = TestContextTransactionUtils.retrieveDataSource(testContext, dsName);
    PlatformTransactionManager txMgr = TestContextTransactionUtils.retrieveTransactionManager(testContext,
            tmName);
    boolean newTxRequired = (mergedSqlConfig.getTransactionMode() == TransactionMode.ISOLATED);

    if (txMgr == null) {
        Assert.state(!newTxRequired,
                () -> String.format(
                        "Failed to execute SQL scripts for test context %s: "
                                + "cannot execute SQL scripts using Transaction Mode "
                                + "[%s] without a PlatformTransactionManager.",
                        testContext, TransactionMode.ISOLATED));
        Assert.state(dataSource != null,
                () -> String.format("Failed to execute SQL scripts for test context %s: "
                        + "supply at least a DataSource or PlatformTransactionManager.", testContext));
        // Execute scripts directly against the DataSource
        populator.execute(dataSource);
    } else {
        DataSource dataSourceFromTxMgr = getDataSourceFromTransactionManager(txMgr);
        // Ensure user configured an appropriate DataSource/TransactionManager pair.
        if (dataSource != null && dataSourceFromTxMgr != null && !dataSource.equals(dataSourceFromTxMgr)) {
            throw new IllegalStateException(String.format(
                    "Failed to execute SQL scripts for test context %s: "
                            + "the configured DataSource [%s] (named '%s') is not the one associated with "
                            + "transaction manager [%s] (named '%s').",
                    testContext, dataSource.getClass().getName(), dsName, txMgr.getClass().getName(), tmName));
        }
        if (dataSource == null) {
            dataSource = dataSourceFromTxMgr;
            Assert.state(dataSource != null, () -> String.format("Failed to execute SQL scripts for "
                    + "test context %s: could not obtain DataSource from transaction manager [%s] (named '%s').",
                    testContext, txMgr.getClass().getName(), tmName));
        }
        final DataSource finalDataSource = dataSource;
        int propagation = (newTxRequired ? TransactionDefinition.PROPAGATION_REQUIRES_NEW
                : TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionAttribute txAttr = TestContextTransactionUtils.createDelegatingTransactionAttribute(
                testContext, new DefaultTransactionAttribute(propagation));
        new TransactionTemplate(txMgr, txAttr).execute(status -> {
            populator.execute(finalDataSource);
            return null;
        });
    }
}

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

/**
 * Generate the default classpath resource locations array based on the
 * supplied class./*from ww w  . ja  v a 2  s.  c  om*/
 * <p>For example, if the supplied class is {@code com.example.MyTest},
 * the generated locations will contain a single string with a value of
 * {@code "classpath:com/example/MyTest<suffix>"}, where {@code <suffix>}
 * is the value of the first configured
 * {@linkplain #getResourceSuffixes() resource suffix} for which the
 * generated location actually exists in the classpath.
 * <p>As of Spring 3.1, the implementation of this method adheres to the
 * contract defined in the {@link SmartContextLoader} SPI. Specifically,
 * this method will <em>preemptively</em> verify that the generated default
 * location actually exists. If it does not exist, this method will log a
 * warning and return an empty array.
 * <p>Subclasses can override this method to implement a different
 * <em>default location generation</em> strategy.
 * @param clazz the class for which the default locations are to be generated
 * @return an array of default application context resource locations
 * @since 2.5
 * @see #getResourceSuffixes()
 */
protected String[] generateDefaultLocations(Class<?> clazz) {
    Assert.notNull(clazz, "Class must not be null");

    String[] suffixes = getResourceSuffixes();
    for (String suffix : suffixes) {
        Assert.hasText(suffix, "Resource suffix must not be empty");
        String resourcePath = ClassUtils.convertClassNameToResourcePath(clazz.getName()) + suffix;
        String prefixedResourcePath = ResourceUtils.CLASSPATH_URL_PREFIX + resourcePath;
        ClassPathResource classPathResource = new ClassPathResource(resourcePath);
        if (classPathResource.exists()) {
            if (logger.isInfoEnabled()) {
                logger.info(String.format("Detected default resource location \"%s\" for test class [%s]",
                        prefixedResourcePath, clazz.getName()));
            }
            return new String[] { prefixedResourcePath };
        } else if (logger.isDebugEnabled()) {
            logger.debug(String.format(
                    "Did not detect default resource location for test class [%s]: " + "%s does not exist",
                    clazz.getName(), classPathResource));
        }
    }

    if (logger.isInfoEnabled()) {
        logger.info(String.format(
                "Could not detect default resource locations for test class [%s]: "
                        + "no resource found for suffixes %s.",
                clazz.getName(), ObjectUtils.nullSafeToString(suffixes)));
    }

    return EMPTY_STRING_ARRAY;
}

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

/**
 * Ensure that the supplied {@link MergedContextConfiguration} does not
 * contain {@link MergedContextConfiguration#getLocations() locations}.
 * @since 4.0.4//from w w w . j  a  va2 s.  c o m
 * @see AbstractGenericContextLoader#validateMergedContextConfiguration
 */
@Override
protected void validateMergedContextConfiguration(MergedContextConfiguration mergedConfig) {
    if (mergedConfig.hasLocations()) {
        String msg = String.format(
                "Test class [%s] has been configured with @ContextConfiguration's 'locations' "
                        + "(or 'value') attribute %s, but %s does not support resource locations.",
                mergedConfig.getTestClass().getName(),
                ObjectUtils.nullSafeToString(mergedConfig.getLocations()), getClass().getSimpleName());
        logger.error(msg);
        throw new IllegalStateException(msg);
    }
}

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

/**
 * Register classes in the supplied {@link GenericApplicationContext context}
 * from the classes in the supplied {@link MergedContextConfiguration}.
 * <p>Each class must represent an <em>annotated class</em>. An
 * {@link AnnotatedBeanDefinitionReader} is used to register the appropriate
 * bean definitions.//from  w ww. j ava2 s .  c o m
 * <p>Note that this method does not call {@link #createBeanDefinitionReader}
 * since {@code AnnotatedBeanDefinitionReader} is not an instance of
 * {@link BeanDefinitionReader}.
 * @param context the context in which the annotated classes should be registered
 * @param mergedConfig the merged configuration from which the classes should be retrieved
 * @see AbstractGenericContextLoader#loadBeanDefinitions
 */
@Override
protected void loadBeanDefinitions(GenericApplicationContext context, MergedContextConfiguration mergedConfig) {
    Class<?>[] annotatedClasses = mergedConfig.getClasses();
    if (logger.isDebugEnabled()) {
        logger.debug("Registering annotated classes: " + ObjectUtils.nullSafeToString(annotatedClasses));
    }
    new AnnotatedBeanDefinitionReader(context).register(annotatedClasses);
}