Java Code Examples for org.springframework.util.StringUtils#getFilenameExtension()

The following examples show how to use org.springframework.util.StringUtils#getFilenameExtension() . These examples are extracted from open source projects. 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
@Nullable
protected ScriptEngine retrieveScriptEngine(ScriptSource scriptSource) {
	ScriptEngineManager scriptEngineManager = new ScriptEngineManager(this.beanClassLoader);

	if (this.scriptEngineName != null) {
		return StandardScriptUtils.retrieveEngineByName(scriptEngineManager, this.scriptEngineName);
	}

	if (scriptSource instanceof ResourceScriptSource) {
		String filename = ((ResourceScriptSource) scriptSource).getResource().getFilename();
		if (filename != null) {
			String extension = StringUtils.getFilenameExtension(filename);
			if (extension != null) {
				ScriptEngine engine = scriptEngineManager.getEngineByExtension(extension);
				if (engine != null) {
					return engine;
				}
			}
		}
	}

	return null;
}
 
Example 2
/**
 * A public method exposing the knowledge of the path extension strategy to
 * resolve file extensions to a {@link MediaType} in this case for a given
 * {@link Resource}. The method first looks up any explicitly registered
 * file extensions first and then falls back on JAF if available.
 * @param resource the resource to look up
 * @return the MediaType for the extension, or {@code null} if none found
 * @since 4.3
 */
public MediaType getMediaTypeForResource(Resource resource) {
	Assert.notNull(resource, "Resource must not be null");
	MediaType mediaType = null;
	String filename = resource.getFilename();
	String extension = StringUtils.getFilenameExtension(filename);
	if (extension != null) {
		mediaType = lookupMediaType(extension);
	}
	if (mediaType == null && JAF_PRESENT) {
		mediaType = ActivationMediaTypeFactory.getMediaType(filename);
	}
	if (MediaType.APPLICATION_OCTET_STREAM.equals(mediaType)) {
		mediaType = null;
	}
	return mediaType;
}
 
Example 3
@Nullable
protected ScriptEngine retrieveScriptEngine(ScriptSource scriptSource) {
	ScriptEngineManager scriptEngineManager = new ScriptEngineManager(this.beanClassLoader);

	if (this.scriptEngineName != null) {
		return StandardScriptUtils.retrieveEngineByName(scriptEngineManager, this.scriptEngineName);
	}

	if (scriptSource instanceof ResourceScriptSource) {
		String filename = ((ResourceScriptSource) scriptSource).getResource().getFilename();
		if (filename != null) {
			String extension = StringUtils.getFilenameExtension(filename);
			if (extension != null) {
				ScriptEngine engine = scriptEngineManager.getEngineByExtension(extension);
				if (engine != null) {
					return engine;
				}
			}
		}
	}

	return null;
}
 
Example 4
private Collection<String> getProfilePaths(String profiles, String path) {
	Set<String> paths = new LinkedHashSet<>();
	for (String profile : StringUtils.commaDelimitedListToSet(profiles)) {
		if (!StringUtils.hasText(profile) || "default".equals(profile)) {
			paths.add(path);
		}
		else {
			String ext = StringUtils.getFilenameExtension(path);
			String file = path;
			if (ext != null) {
				ext = "." + ext;
				file = StringUtils.stripFilenameExtension(path);
			}
			else {
				ext = "";
			}
			paths.add(file + "-" + profile + ext);
		}
	}
	paths.add(path);
	return paths;
}
 
Example 5
/**
 * Obtain the JSR-223 ScriptEngine to use for the given script.
 * @param script the script to evaluate
 * @return the ScriptEngine (never {@code null})
 */
protected ScriptEngine getScriptEngine(ScriptSource script) {
	if (this.scriptEngineManager == null) {
		this.scriptEngineManager = new ScriptEngineManager();
	}

	if (StringUtils.hasText(this.engineName)) {
		return StandardScriptUtils.retrieveEngineByName(this.scriptEngineManager, this.engineName);
	}
	else if (script instanceof ResourceScriptSource) {
		Resource resource = ((ResourceScriptSource) script).getResource();
		String extension = StringUtils.getFilenameExtension(resource.getFilename());
		if (extension == null) {
			throw new IllegalStateException(
					"No script language defined, and no file extension defined for resource: " + resource);
		}
		ScriptEngine engine = this.scriptEngineManager.getEngineByExtension(extension);
		if (engine == null) {
			throw new IllegalStateException("No matching engine found for file extension '" + extension + "'");
		}
		return engine;
	}
	else {
		throw new IllegalStateException(
				"No script language defined, and no resource associated with script: " + script);
	}
}
 
Example 6
/**
 * Check if the path has a file extension and whether the extension is
 * either {@link #WHITELISTED_EXTENSIONS whitelisted} or explicitly
 * {@link ContentNegotiationManager#getAllFileExtensions() registered}.
 * If not, and the status is in the 2xx range, a 'Content-Disposition'
 * header with a safe attachment file name ("f.txt") is added to prevent
 * RFD exploits.
 */
private void addContentDispositionHeader(ServletServerHttpRequest request, ServletServerHttpResponse response) {
	HttpHeaders headers = response.getHeaders();
	if (headers.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
		return;
	}

	try {
		int status = response.getServletResponse().getStatus();
		if (status < 200 || status > 299) {
			return;
		}
	}
	catch (Throwable ex) {
		// ignore
	}

	HttpServletRequest servletRequest = request.getServletRequest();
	String requestUri = rawUrlPathHelper.getOriginatingRequestUri(servletRequest);

	int index = requestUri.lastIndexOf('/') + 1;
	String filename = requestUri.substring(index);
	String pathParams = "";

	index = filename.indexOf(';');
	if (index != -1) {
		pathParams = filename.substring(index);
		filename = filename.substring(0, index);
	}

	filename = decodingUrlPathHelper.decodeRequestString(servletRequest, filename);
	String ext = StringUtils.getFilenameExtension(filename);

	pathParams = decodingUrlPathHelper.decodeRequestString(servletRequest, pathParams);
	String extInPathParams = StringUtils.getFilenameExtension(pathParams);

	if (!safeExtension(servletRequest, ext) || !safeExtension(servletRequest, extInPathParams)) {
		headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=f.txt");
	}
}
 
Example 7
synchronized String retrieve(ServletWebRequest request, String name, String profile,
		String label, String path, boolean resolvePlaceholders) throws IOException {
	name = Environment.normalize(name);
	label = Environment.normalize(label);
	Resource resource = this.resourceRepository.findOne(name, profile, label, path);
	if (checkNotModified(request, resource)) {
		// Content was not modified. Just return.
		return null;
	}
	// ensure InputStream will be closed to prevent file locks on Windows
	try (InputStream is = resource.getInputStream()) {
		String text = StreamUtils.copyToString(is, Charset.forName("UTF-8"));
		String ext = StringUtils.getFilenameExtension(resource.getFilename());
		if (ext != null) {
			ext = ext.toLowerCase();
		}
		Environment environment = this.environmentRepository.findOne(name, profile,
				label, false);
		if (resolvePlaceholders) {
			text = resolvePlaceholders(prepareEnvironment(environment), text);
		}
		if (ext != null && encryptEnabled && plainTextEncryptEnabled) {
			ResourceEncryptor re = this.resourceEncryptorMap.get(ext);
			if (re == null) {
				logger.warn("Cannot decrypt for extension " + ext);
			}
			else {
				text = re.decrypt(text, environment);
			}
		}
		return text;
	}
}
 
Example 8
@Override
@Nullable
public String getMimeType(String filePath) {
	String extension = StringUtils.getFilenameExtension(filePath);
	if (this.mimeTypes.containsKey(extension)) {
		return this.mimeTypes.get(extension).toString();
	}
	else {
		return MediaTypeFactory.getMediaType(filePath).
				map(MimeType::toString)
				.orElse(null);
	}
}
 
Example 9
@Override
protected String getMediaTypeKey(NativeWebRequest webRequest) {
	HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
	if (request == null) {
		logger.warn("An HttpServletRequest is required to determine the media type key");
		return null;
	}
	String path = PATH_HELPER.getLookupPathForRequest(request);
	String filename = WebUtils.extractFullFilenameFromUrlPath(path);
	String extension = StringUtils.getFilenameExtension(filename);
	return (StringUtils.hasText(extension)) ? extension.toLowerCase(Locale.ENGLISH) : null;
}
 
Example 10
/**
 * Check if the path has a file extension and whether the extension is
 * either {@link #WHITELISTED_EXTENSIONS whitelisted} or explicitly
 * {@link ContentNegotiationManager#getAllFileExtensions() registered}.
 * If not, and the status is in the 2xx range, a 'Content-Disposition'
 * header with a safe attachment file name ("f.txt") is added to prevent
 * RFD exploits.
 */
private void addContentDispositionHeader(ServletServerHttpRequest request, ServletServerHttpResponse response) {
	HttpHeaders headers = response.getHeaders();
	if (headers.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
		return;
	}

	try {
		int status = response.getServletResponse().getStatus();
		if (status < 200 || status > 299) {
			return;
		}
	}
	catch (Throwable ex) {
		// ignore
	}

	HttpServletRequest servletRequest = request.getServletRequest();
	String requestUri = rawUrlPathHelper.getOriginatingRequestUri(servletRequest);

	int index = requestUri.lastIndexOf('/') + 1;
	String filename = requestUri.substring(index);
	String pathParams = "";

	index = filename.indexOf(';');
	if (index != -1) {
		pathParams = filename.substring(index);
		filename = filename.substring(0, index);
	}

	filename = decodingUrlPathHelper.decodeRequestString(servletRequest, filename);
	String ext = StringUtils.getFilenameExtension(filename);

	pathParams = decodingUrlPathHelper.decodeRequestString(servletRequest, pathParams);
	String extInPathParams = StringUtils.getFilenameExtension(pathParams);

	if (!safeExtension(servletRequest, ext) || !safeExtension(servletRequest, extInPathParams)) {
		headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=f.txt");
	}
}
 
Example 11
/**
 * A public method exposing the knowledge of the path extension strategy to
 * resolve file extensions to a {@link MediaType} in this case for a given
 * {@link Resource}. The method first looks up any explicitly registered
 * file extensions first and then falls back on {@link MediaTypeFactory} if available.
 * @param resource the resource to look up
 * @return the MediaType for the extension, or {@code null} if none found
 * @since 4.3
 */
@Nullable
public MediaType getMediaTypeForResource(Resource resource) {
	Assert.notNull(resource, "Resource must not be null");
	MediaType mediaType = null;
	String filename = resource.getFilename();
	String extension = StringUtils.getFilenameExtension(filename);
	if (extension != null) {
		mediaType = lookupMediaType(extension);
	}
	if (mediaType == null) {
		mediaType = MediaTypeFactory.getMediaType(filename).orElse(null);
	}
	return mediaType;
}
 
Example 12
@Override
@Nullable
public String getMimeType(String filePath) {
	String extension = StringUtils.getFilenameExtension(filePath);
	if (this.mimeTypes.containsKey(extension)) {
		return this.mimeTypes.get(extension).toString();
	}
	else {
		return MediaTypeFactory.getMediaType(filePath).
				map(MimeType::toString)
				.orElse(null);
	}
}
 
Example 13
Source Project: gocd   File: MockServletContext.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String getMimeType(String filePath) {
	String extension = StringUtils.getFilenameExtension(filePath);
	if (this.mimeTypes.containsKey(extension)) {
		return this.mimeTypes.get(extension).toString();
	}
	else {
		try {
			return Optional.of(Files.probeContentType(Paths.get(filePath))).orElse("application/octet-stream");
		} catch (IOException e) {
			return "application/octet-stream";
		}
	}
}
 
Example 14
Source Project: oauth2-resource   File: FileStorageController.java    License: MIT License 5 votes vote down vote up
private Map<String, Object> saveToDisk(MultipartFile multipartFile, String publicStorageLocation) {
    Map<String, Object> result = new HashMap<>(16);
    List<String> fileNames = new LinkedList<>();
    String fileType = StringUtils.getFilenameExtension(multipartFile.getOriginalFilename());
    if (fileType == null || "".equals(fileType)) {
        String multipartFileContentType = multipartFile.getContentType();
        if (StringUtils.endsWithIgnoreCase("image/png", multipartFileContentType)) {
            fileType = "png";
        } else if (StringUtils.endsWithIgnoreCase("image/jpg", multipartFileContentType)) {
            fileType = "jpg";
        } else if (StringUtils.endsWithIgnoreCase("image/jpeg", multipartFileContentType)) {
            fileType = "jpg";
        } else if (StringUtils.endsWithIgnoreCase("application/pdf", multipartFileContentType)) {
            fileType = "pdf";
        } else if (StringUtils.endsWithIgnoreCase("application/msword", multipartFileContentType)) {
            fileType = "doc";
        }
    }
    if (whitelist.contains(StringUtils.trimAllWhitespace(fileType).toLowerCase())) {
        try {
            String newFileName = storageService.save(Paths.get(publicStorageLocation), multipartFile, fileType);
            fileNames.add(newFileName);
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error("上传文件异常", e);
            }
        }
    }
    if (fileNames.size() > 0) {
        result.put("status", 1);
    } else {
        result.put("status", 0);
    }
    result.put("files", fileNames);
    return result;
}
 
Example 15
@Override
public String getMimeType(String filePath) {
	String extension = StringUtils.getFilenameExtension(filePath);
	return getMimeTypes().get(extension);
}
 
Example 16
@Override
public String getMimeType(String filePath) {
	String extension = StringUtils.getFilenameExtension(filePath);
	return getMimeTypes().get(extension);
}
 
Example 17
@Override
public String addVersion(String requestPath, String version) {
	String baseFilename = StringUtils.stripFilenameExtension(requestPath);
	String extension = StringUtils.getFilenameExtension(requestPath);
	return (baseFilename + "-" + version + "." + extension);
}
 
Example 18
@Override
public String addVersion(String requestPath, String version) {
	String baseFilename = StringUtils.stripFilenameExtension(requestPath);
	String extension = StringUtils.getFilenameExtension(requestPath);
	return (baseFilename + '-' + version + '.' + extension);
}
 
Example 19
/**
 * Check if the path has a file extension and whether the extension is
 * either {@link #WHITELISTED_EXTENSIONS whitelisted} or explicitly
 * {@link ContentNegotiationManager#getAllFileExtensions() registered}.
 * If not, and the status is in the 2xx range, a 'Content-Disposition'
 * header with a safe attachment file name ("f.txt") is added to prevent
 * RFD exploits.
 */
private void addContentDispositionHeader(ServletServerHttpRequest request,
		ServletServerHttpResponse response) {

	HttpHeaders headers = response.getHeaders();
	if (headers.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
		return;
	}

	try {
		int status = response.getServletResponse().getStatus();
		if (status < 200 || status > 299) {
			return;
		}
	}
	catch (Throwable ex) {
		// Ignore
	}

	HttpServletRequest servletRequest = request.getServletRequest();
	String requestUri = RAW_URL_PATH_HELPER.getOriginatingRequestUri(servletRequest);

	int index = requestUri.lastIndexOf('/') + 1;
	String filename = requestUri.substring(index);
	String pathParams = "";

	index = filename.indexOf(';');
	if (index != -1) {
		pathParams = filename.substring(index);
		filename = filename.substring(0, index);
	}

	filename = DECODING_URL_PATH_HELPER.decodeRequestString(servletRequest, filename);
	String ext = StringUtils.getFilenameExtension(filename);

	pathParams = DECODING_URL_PATH_HELPER.decodeRequestString(servletRequest, pathParams);
	String extInPathParams = StringUtils.getFilenameExtension(pathParams);

	if (!safeExtension(servletRequest, ext) || !safeExtension(servletRequest, extInPathParams)) {
		headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=f.txt");
	}
}
 
Example 20
@Override
public String addVersion(String requestPath, String version) {
	String baseFilename = StringUtils.stripFilenameExtension(requestPath);
	String extension = StringUtils.getFilenameExtension(requestPath);
	return (baseFilename + '-' + version + '.' + extension);
}