Java Code Examples for org.springframework.util.ResourceUtils#CLASSPATH_URL_PREFIX

The following examples show how to use org.springframework.util.ResourceUtils#CLASSPATH_URL_PREFIX . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestPropertySourceAttributes.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Detect a default properties file for the supplied class, as specified
 * in the class-level Javadoc for {@link TestPropertySource}.
 */
private static String detectDefaultPropertiesFile(Class<?> testClass) {
	String resourcePath = ClassUtils.convertClassNameToResourcePath(testClass.getName()) + ".properties";
	String prefixedResourcePath = ResourceUtils.CLASSPATH_URL_PREFIX + resourcePath;
	ClassPathResource classPathResource = new ClassPathResource(resourcePath);

	if (classPathResource.exists()) {
		if (logger.isInfoEnabled()) {
			logger.info(String.format("Detected default properties file \"%s\" for test class [%s]",
				prefixedResourcePath, testClass.getName()));
		}
		return prefixedResourcePath;
	}
	else {
		String msg = String.format("Could not detect default properties file for test [%s]: " +
				"%s does not exist. Either declare the 'locations' or 'properties' attributes " +
				"of @TestPropertySource or make the default properties file available.", testClass.getName(),
				classPathResource);
		logger.error(msg);
		throw new IllegalStateException(msg);
	}
}
 
Example 2
Source File: TestPropertySourceAttributes.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Detect a default properties file for the supplied class, as specified
 * in the class-level Javadoc for {@link TestPropertySource}.
 */
private static String detectDefaultPropertiesFile(Class<?> testClass) {
	String resourcePath = ClassUtils.convertClassNameToResourcePath(testClass.getName()) + ".properties";
	String prefixedResourcePath = ResourceUtils.CLASSPATH_URL_PREFIX + resourcePath;
	ClassPathResource classPathResource = new ClassPathResource(resourcePath);

	if (classPathResource.exists()) {
		if (logger.isInfoEnabled()) {
			logger.info(String.format("Detected default properties file \"%s\" for test class [%s]",
				prefixedResourcePath, testClass.getName()));
		}
		return prefixedResourcePath;
	}
	else {
		String msg = String.format("Could not detect default properties file for test [%s]: " +
				"%s does not exist. Either declare the 'locations' or 'properties' attributes " +
				"of @TestPropertySource or make the default properties file available.", testClass.getName(),
				classPathResource);
		logger.error(msg);
		throw new IllegalStateException(msg);
	}
}
 
Example 3
Source File: AbstractSingleSpringContextTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Subclasses can override this method to return the locations of their
 * config files.
 * <p>A plain path will be treated as class path location, e.g.:
 * "org/springframework/whatever/foo.xml". Note however that you may prefix
 * path locations with standard Spring resource prefixes. Therefore, a
 * config location path prefixed with "classpath:" with behave the same as a
 * plain path, but a config location such as
 * "file:/some/path/path/location/appContext.xml" will be treated as a
 * filesystem location.
 * <p>The default implementation builds config locations for the config paths
 * specified through {@link #getConfigPaths()}.
 * @return an array of config locations
 * @see #getConfigPaths()
 * @see org.springframework.core.io.ResourceLoader#getResource(String)
 */
protected final String[] getConfigLocations() {
	String[] paths = getConfigPaths();
	String[] convertedPaths = new String[paths.length];
	for (int i = 0; i < paths.length; i++) {
		String path = paths[i];
		if (path.startsWith(SLASH)) {
			convertedPaths[i] = ResourceUtils.CLASSPATH_URL_PREFIX + path;
		}
		else if (!ResourcePatternUtils.isUrl(path)) {
			convertedPaths[i] = ResourceUtils.CLASSPATH_URL_PREFIX + SLASH
					+ StringUtils.cleanPath(ClassUtils.classPackageAsResourcePath(getClass()) + SLASH + path);
		}
		else {
			convertedPaths[i] = StringUtils.cleanPath(path);
		}
	}
	return convertedPaths;
}
 
Example 4
Source File: TestPropertySourceAttributes.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Detect a default properties file for the supplied class, as specified
 * in the class-level Javadoc for {@link TestPropertySource}.
 */
private static String detectDefaultPropertiesFile(Class<?> testClass) {
	String resourcePath = ClassUtils.convertClassNameToResourcePath(testClass.getName()) + ".properties";
	String prefixedResourcePath = ResourceUtils.CLASSPATH_URL_PREFIX + resourcePath;
	ClassPathResource classPathResource = new ClassPathResource(resourcePath);

	if (classPathResource.exists()) {
		if (logger.isInfoEnabled()) {
			logger.info(String.format("Detected default properties file \"%s\" for test class [%s]",
				prefixedResourcePath, testClass.getName()));
		}
		return prefixedResourcePath;
	}
	else {
		String msg = String.format("Could not detect default properties file for test [%s]: "
				+ "%s does not exist. Either declare the 'locations' or 'properties' attributes "
				+ "of @TestPropertySource or make the default properties file available.", testClass.getName(),
			classPathResource);
		logger.error(msg);
		throw new IllegalStateException(msg);
	}
}
 
Example 5
Source File: SqlScriptsTestExecutionListener.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Detect a default SQL script by implementing the algorithm defined in
 * {@link Sql#scripts}.
 */
private String detectDefaultScript(TestContext testContext, boolean classLevel) {
	Class<?> clazz = testContext.getTestClass();
	Method method = testContext.getTestMethod();
	String elementType = (classLevel ? "class" : "method");
	String elementName = (classLevel ? clazz.getName() : method.toString());

	String resourcePath = ClassUtils.convertClassNameToResourcePath(clazz.getName());
	if (!classLevel) {
		resourcePath += "." + method.getName();
	}
	resourcePath += ".sql";

	String prefixedResourcePath = ResourceUtils.CLASSPATH_URL_PREFIX + resourcePath;
	ClassPathResource classPathResource = new ClassPathResource(resourcePath);

	if (classPathResource.exists()) {
		if (logger.isInfoEnabled()) {
			logger.info(String.format("Detected default SQL script \"%s\" for test %s [%s]",
					prefixedResourcePath, elementType, elementName));
		}
		return prefixedResourcePath;
	}
	else {
		String msg = String.format("Could not detect default SQL script for test %s [%s]: " +
				"%s does not exist. Either declare statements or scripts via @Sql or make the " +
				"default SQL script available.", elementType, elementName, classPathResource);
		logger.error(msg);
		throw new IllegalStateException(msg);
	}
}
 
Example 6
Source File: AbstractContextLoader.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Generate the default classpath resource locations array based on the
 * supplied class.
 * <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;
}
 
Example 7
Source File: SqlScriptsTestExecutionListener.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Detect a default SQL script by implementing the algorithm defined in
 * {@link Sql#scripts}.
 */
private String detectDefaultScript(TestContext testContext, boolean classLevel) {
	Class<?> clazz = testContext.getTestClass();
	Method method = testContext.getTestMethod();
	String elementType = (classLevel ? "class" : "method");
	String elementName = (classLevel ? clazz.getName() : method.toString());

	String resourcePath = ClassUtils.convertClassNameToResourcePath(clazz.getName());
	if (!classLevel) {
		resourcePath += "." + method.getName();
	}
	resourcePath += ".sql";

	String prefixedResourcePath = ResourceUtils.CLASSPATH_URL_PREFIX + resourcePath;
	ClassPathResource classPathResource = new ClassPathResource(resourcePath);

	if (classPathResource.exists()) {
		if (logger.isInfoEnabled()) {
			logger.info(String.format("Detected default SQL script \"%s\" for test %s [%s]",
					prefixedResourcePath, elementType, elementName));
		}
		return prefixedResourcePath;
	}
	else {
		String msg = String.format("Could not detect default SQL script for test %s [%s]: " +
				"%s does not exist. Either declare statements or scripts via @Sql or make the " +
				"default SQL script available.", elementType, elementName, classPathResource);
		logger.error(msg);
		throw new IllegalStateException(msg);
	}
}
 
Example 8
Source File: AbstractContextLoader.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Generate the default classpath resource locations array based on the
 * supplied class.
 * <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;
}
 
Example 9
Source File: StartedListener.java    From halo with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Init internal themes
 */
private void initThemes() {
    // Whether the blog has initialized
    Boolean isInstalled = optionService.getByPropertyOrDefault(PrimaryProperties.IS_INSTALLED, Boolean.class, false);
    try {
        String themeClassPath = ResourceUtils.CLASSPATH_URL_PREFIX + ThemeService.THEME_FOLDER;

        URI themeUri = ResourceUtils.getURL(themeClassPath).toURI();

        log.debug("Theme uri: [{}]", themeUri);

        Path source;

        if ("jar".equalsIgnoreCase(themeUri.getScheme())) {

            // Create new file system for jar
            FileSystem fileSystem = getFileSystem(themeUri);
            source = fileSystem.getPath("/BOOT-INF/classes/" + ThemeService.THEME_FOLDER);
        } else {
            source = Paths.get(themeUri);
        }

        // Create theme folder
        Path themePath = themeService.getBasePath();

        // Fix the problem that the project cannot start after moving to a new server
        if (!haloProperties.isProductionEnv() || Files.notExists(themePath) || !isInstalled) {
            FileUtils.copyFolder(source, themePath);
            log.debug("Copied theme folder from [{}] to [{}]", source, themePath);
        } else {
            log.debug("Skipped copying theme folder due to existence of theme folder");
        }
    } catch (Exception e) {
        log.error("Initialize internal theme to user path error!", e);
    }
}
 
Example 10
Source File: SqlScriptsTestExecutionListener.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Detect a default SQL script by implementing the algorithm defined in
 * {@link Sql#scripts}.
 */
private String detectDefaultScript(TestContext testContext, boolean classLevel) {
	Class<?> clazz = testContext.getTestClass();
	Method method = testContext.getTestMethod();
	String elementType = (classLevel ? "class" : "method");
	String elementName = (classLevel ? clazz.getName() : method.toString());

	String resourcePath = ClassUtils.convertClassNameToResourcePath(clazz.getName());
	if (!classLevel) {
		resourcePath += "." + method.getName();
	}
	resourcePath += ".sql";

	String prefixedResourcePath = ResourceUtils.CLASSPATH_URL_PREFIX + resourcePath;
	ClassPathResource classPathResource = new ClassPathResource(resourcePath);

	if (classPathResource.exists()) {
		if (logger.isInfoEnabled()) {
			logger.info(String.format("Detected default SQL script \"%s\" for test %s [%s]", prefixedResourcePath,
				elementType, elementName));
		}
		return prefixedResourcePath;
	}
	else {
		String msg = String.format("Could not detect default SQL script for test %s [%s]: "
				+ "%s does not exist. Either declare statements or scripts via @Sql or make the "
				+ "default SQL script available.", elementType, elementName, classPathResource);
		logger.error(msg);
		throw new IllegalStateException(msg);
	}
}
 
Example 11
Source File: AbstractContextLoader.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Generate the default classpath resource locations array based on the
 * supplied class.
 *
 * <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;
}
 
Example 12
Source File: TestContextResourceUtils.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * Convert the supplied paths to classpath resource paths.
 *
 * <p>For each of the supplied paths:
 * <ul>
 * <li>A plain path &mdash; for example, {@code "context.xml"} &mdash; will
 * be treated as a classpath resource that is relative to the package in
 * which the specified class is defined.
 * <li>A path starting with a slash will be treated as an absolute path
 * within the classpath, for example: {@code "/org/example/schema.sql"}.
 * <li>A path which is prefixed with a URL protocol (e.g.,
 * {@link ResourceUtils#CLASSPATH_URL_PREFIX classpath:},
 * {@link ResourceUtils#FILE_URL_PREFIX file:}, {@code http:}, etc.) will be
 * {@link StringUtils#cleanPath cleaned} but otherwise unmodified.
 * </ul>
 * @param clazz the class with which the paths are associated
 * @param paths the paths to be converted
 * @return a new array of converted resource paths
 * @see #convertToResources
 */
public static String[] convertToClasspathResourcePaths(Class<?> clazz, String... paths) {
	String[] convertedPaths = new String[paths.length];
	for (int i = 0; i < paths.length; i++) {
		String path = paths[i];
		if (path.startsWith(SLASH)) {
			convertedPaths[i] = ResourceUtils.CLASSPATH_URL_PREFIX + path;
		}
		else if (!ResourcePatternUtils.isUrl(path)) {
			convertedPaths[i] = ResourceUtils.CLASSPATH_URL_PREFIX + SLASH +
					StringUtils.cleanPath(ClassUtils.classPackageAsResourcePath(clazz) + SLASH + path);
		}
		else {
			convertedPaths[i] = StringUtils.cleanPath(path);
		}
	}
	return convertedPaths;
}
 
Example 13
Source File: TestContextResourceUtils.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * Convert the supplied paths to classpath resource paths.
 *
 * <p>For each of the supplied paths:
 * <ul>
 * <li>A plain path &mdash; for example, {@code "context.xml"} &mdash; will
 * be treated as a classpath resource that is relative to the package in
 * which the specified class is defined.
 * <li>A path starting with a slash will be treated as an absolute path
 * within the classpath, for example: {@code "/org/example/schema.sql"}.
 * <li>A path which is prefixed with a URL protocol (e.g.,
 * {@link ResourceUtils#CLASSPATH_URL_PREFIX classpath:},
 * {@link ResourceUtils#FILE_URL_PREFIX file:}, {@code http:}, etc.) will be
 * {@link StringUtils#cleanPath cleaned} but otherwise unmodified.
 * </ul>
 * @param clazz the class with which the paths are associated
 * @param paths the paths to be converted
 * @return a new array of converted resource paths
 * @see #convertToResources
 */
public static String[] convertToClasspathResourcePaths(Class<?> clazz, String... paths) {
	String[] convertedPaths = new String[paths.length];
	for (int i = 0; i < paths.length; i++) {
		String path = paths[i];
		if (path.startsWith(SLASH)) {
			convertedPaths[i] = ResourceUtils.CLASSPATH_URL_PREFIX + path;
		}
		else if (!ResourcePatternUtils.isUrl(path)) {
			convertedPaths[i] = ResourceUtils.CLASSPATH_URL_PREFIX + SLASH +
					StringUtils.cleanPath(ClassUtils.classPackageAsResourcePath(clazz) + SLASH + path);
		}
		else {
			convertedPaths[i] = StringUtils.cleanPath(path);
		}
	}
	return convertedPaths;
}
 
Example 14
Source File: TestContextResourceUtils.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Convert the supplied paths to classpath resource paths.
 *
 * <p>For each of the supplied paths:
 * <ul>
 * <li>A plain path &mdash; for example, {@code "context.xml"} &mdash; will
 * be treated as a classpath resource that is relative to the package in
 * which the specified class is defined.
 * <li>A path starting with a slash will be treated as an absolute path
 * within the classpath, for example: {@code "/org/example/schema.sql"}.
 * <li>A path which is prefixed with a URL protocol (e.g.,
 * {@link ResourceUtils#CLASSPATH_URL_PREFIX classpath:},
 * {@link ResourceUtils#FILE_URL_PREFIX file:}, {@code http:}, etc.) will be
 * {@link StringUtils#cleanPath cleaned} but otherwise unmodified.
 *
 * @param clazz the class with which the paths are associated
 * @param paths the paths to be converted
 * @return a new array of converted resource paths
 * @see #convertToResources
 */
public static String[] convertToClasspathResourcePaths(Class<?> clazz, String... paths) {
	String[] convertedPaths = new String[paths.length];
	for (int i = 0; i < paths.length; i++) {
		String path = paths[i];
		if (path.startsWith(SLASH)) {
			convertedPaths[i] = ResourceUtils.CLASSPATH_URL_PREFIX + path;
		}
		else if (!ResourcePatternUtils.isUrl(path)) {
			convertedPaths[i] = ResourceUtils.CLASSPATH_URL_PREFIX + SLASH
					+ StringUtils.cleanPath(ClassUtils.classPackageAsResourcePath(clazz) + SLASH + path);
		}
		else {
			convertedPaths[i] = StringUtils.cleanPath(path);
		}
	}
	return convertedPaths;
}