下面列出了怎么用org.springframework.util.ResourceUtils的API类实例代码及写法,或者点击链接到github查看源代码。
@Nullable
public static String toFilePath(@Nullable URL url) {
if (url == null) { return null; }
String protocol = url.getProtocol();
String file = UrlUtil.decode(url.getPath(), Charsets.UTF_8);
if (ResourceUtils.URL_PROTOCOL_FILE.equals(protocol)) {
return new File(file).getParentFile().getParentFile().getAbsolutePath();
} else if (ResourceUtils.URL_PROTOCOL_JAR.equals(protocol)
|| ResourceUtils.URL_PROTOCOL_ZIP.equals(protocol)) {
int ipos = file.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
if (ipos > 0) {
file = file.substring(0, ipos);
}
if (file.startsWith(ResourceUtils.FILE_URL_PREFIX)) {
file = file.substring(ResourceUtils.FILE_URL_PREFIX.length());
}
return new File(file).getParentFile().getAbsolutePath();
}
return file;
}
@Before
public void setup() throws Exception
{
super.setup();
permissionService = applicationContext.getBean("permissionService", PermissionService.class);
authorityService = (AuthorityService) applicationContext.getBean("AuthorityService");
auditService = applicationContext.getBean("AuditService", AuditService.class);
AuditModelRegistryImpl auditModelRegistry = (AuditModelRegistryImpl) applicationContext.getBean("auditModel.modelRegistry");
// Register the test model
URL testModelUrl = ResourceUtils.getURL("classpath:alfresco/audit/alfresco-audit-access.xml");
auditModelRegistry.registerModel(testModelUrl);
auditModelRegistry.loadAuditModels();
}
NodeRef createContentNodeFromQuickFile(String fileName) throws FileNotFoundException
{
NodeRef rootNodeRef = nodeService.getRootNode(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
NodeRef folderNodeRef = nodeService.createNode(
rootNodeRef,
ContentModel.ASSOC_CHILDREN,
QName.createQName(getName() + GUID.generate()),
ContentModel.TYPE_FOLDER).getChildRef();
File file = ResourceUtils.getFile("classpath:quick/" + fileName);
NodeRef contentRef = nodeService.createNode(
folderNodeRef,
ContentModel.ASSOC_CONTAINS,
ContentModel.ASSOC_CONTAINS,
ContentModel.TYPE_CONTENT,
Collections.singletonMap(ContentModel.PROP_NAME, fileName))
.getChildRef();
ContentWriter contentWriter = contentService.getWriter(contentRef, ContentModel.PROP_CONTENT, true);
contentWriter.setMimetype(mimetypeService.guessMimetype(fileName));
contentWriter.putContent(file);
return contentRef;
}
/**
* 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;
}
/**
* 更新主题
*
* @param themeName 主题名
* @return JsonResult
*/
@GetMapping(value = "/pull")
@ResponseBody
public JsonResult pullFromRemote(@RequestParam(value = "themeName") String themeName) {
try {
File basePath = new File(ResourceUtils.getURL("classpath:").getPath());
File themePath = new File(basePath.getAbsolutePath(), "templates/themes");
String cmdResult = RuntimeUtil.execForStr("cd " + themePath.getAbsolutePath() + "/" + themeName + " && git pull");
if (NOT_FOUND_GIT.equals(cmdResult)) {
return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.theme.no-git"));
}
HaloConst.THEMES.clear();
HaloConst.THEMES = HaloUtils.getThemes();
} catch (Exception e) {
log.error("Update theme failed: {}", e.getMessage());
return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.theme.update-theme-failed") + e.getMessage());
}
return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.common.update-success"));
}
/**
* This implementation opens an InputStream for the given URL.
* <p>It sets the {@code useCaches} flag to {@code false},
* mainly to avoid jar file locking on Windows.
* @see java.net.URL#openConnection()
* @see java.net.URLConnection#setUseCaches(boolean)
* @see java.net.URLConnection#getInputStream()
*/
@Override
public InputStream getInputStream() throws IOException {
URLConnection con = this.url.openConnection();
ResourceUtils.useCachesIfNecessary(con);
try {
return con.getInputStream();
}
catch (IOException ex) {
// Close the HTTP connection (if applicable).
if (con instanceof HttpURLConnection) {
((HttpURLConnection) con).disconnect();
}
throw ex;
}
}
@Test
public void checkAuthContract() throws JSONException, FileNotFoundException, URISyntaxException {
// First we make an HTTP request to get the Booking from Booking API
Response response = given()
.get("http://localhost:3000/booking/1");
// Next we take the body of the HTTP response and convert it into a JSONObject
JSONObject parsedResponse = new JSONObject(response.body().prettyPrint());
// Then we import our expected JSON contract from the contract folder
// and store in a string
File file = ResourceUtils.getFile(this.getClass().getResource("/contract.json"));
String testObject = new Scanner(file).useDelimiter("\\Z").next();
// Finally we compare the contract string and the JSONObject to compare
// and pass if they match
JSONAssert.assertEquals(testObject, parsedResponse, true);
}
/**
* 将resultList 保存进文件,selectResult.txt
*
* @param resultList
* @return
*/
public JSONObject saveResult(List resultList, String sql) {
JSONObject jsonObject = new JSONObject();
try {
File file = ResourceUtils.getFile("classpath:selectResult.txt");
FileUtils.writeLines(file, "utf-8", resultList, "\n");
jsonObject.put("isWrite", true);
jsonObject.put("msg", "结果保存成功!");
} catch (IOException e) {
e.printStackTrace();
jsonObject.put("isWrite", false);
jsonObject.put("msg", "结果保存失败!");
}
return jsonObject;
}
/**
* 获取模板文件内容
*
* @param tplName 模板文件名
* @return 模板内容
*/
@GetMapping(value = "/getTpl", produces = "text/text;charset=UTF-8")
@ResponseBody
public String getTplContent(@RequestParam("tplName") String tplName) {
String tplContent = "";
try {
//获取项目根路径
File basePath = new File(ResourceUtils.getURL("classpath:").getPath());
//获取主题路径
File themesPath = new File(basePath.getAbsolutePath(), new StringBuffer("templates/themes/").append(BaseController.THEME).append("/").append(tplName).toString());
FileReader fileReader = new FileReader(themesPath);
tplContent = fileReader.readString();
} catch (Exception e) {
log.error("Get template file error: {}", e.getMessage());
}
return tplContent;
}
@Override
public File download() {
File htmlFile;
File pdfFile;
String htmlFilePath;
try {
//读取html页面
htmlFile = ResourceUtils.getFile("classpath:templates/index.html");
htmlFilePath = "classpath:templates/index.html";
// 中文字体存储路径
String chineseFontPath = "classpath:Fonts/simsun.ttc";
// html转pdf
PdfUtil.html2pdf(htmlFilePath,"classpath:templates/index.html.pdf", chineseFontPath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//将html转换为pdf文件并保存
//将pdf文件返回
return null;
}
@Bean
public FileRefreshableDataSourceFactoryBean fileBean() {
FileRefreshableDataSourceFactoryBean factoryBean = new FileRefreshableDataSourceFactoryBean();
factoryBean.setBufSize(1024);
factoryBean.setCharset("utf-8");
factoryBean.setRecommendRefreshMs(2000);
try {
factoryBean.setFile(ResourceUtils.getFile("classpath:flowrule.json")
.getAbsolutePath());
}
catch (FileNotFoundException e) {
// ignore
}
factoryBean.setConverter(buildConverter());
return factoryBean;
}
/**
* 备份资源文件 重要
*
* @return JsonResult
*/
public JsonResult backupResources() {
try {
if (HaloUtils.getBackUps(BackupTypeEnum.RESOURCES.getDesc()).size() > CommonParamsEnum.TEN.getValue()) {
FileUtil.del(System.getProperties().getProperty("user.home") + "/halo/backup/resources/");
}
final File path = new File(ResourceUtils.getURL("classpath:").getPath());
final String srcPath = path.getAbsolutePath();
final String distName = "resources_backup_" + DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
//执行打包
ZipUtil.zip(srcPath, System.getProperties().getProperty("user.home") + "/halo/backup/resources/" + distName + ".zip");
log.info("Current time: {}, the resource file backup was performed.", DateUtil.now());
return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.backup.backup-success"));
} catch (Exception e) {
log.error("Backup resource file failed: {}", e.getMessage());
return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.backup.backup-failed"));
}
}
public static void generator() throws Exception {
List<String> warnings = new ArrayList<>();
File propFile = ResourceUtils.getFile("classpath:generatorConfig.properties");
Properties properties = new Properties();
properties.load(new FileInputStream(propFile));
String projectPath = new File("").getAbsolutePath();
properties.put("project.path", projectPath);
InputStream inputStream = addTableToXml(properties.getProperty("tables"));
ConfigurationParser cp = new ConfigurationParser(properties, warnings);
Configuration config = cp.parseConfiguration(inputStream);
DefaultShellCallback callback = new DefaultShellCallback(true);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
inputStream.close();
logger.info("generated warnings:" + warnings);
}
/**
* 文件列表
* @author eko.zhan at 2017年8月9日 下午8:32:19
* @return
* @throws FileNotFoundException
*/
@ApiOperation(value="获取文件数据列表", notes="获取固定路径下的文件,并返回文件名,文件所在路径和文件大小")
@RequestMapping(value="getDataList", method=RequestMethod.POST)
public JSONArray getDataList() throws FileNotFoundException{
JSONArray arr = new JSONArray();
File dir = ResourceUtils.getFile("classpath:static/DATAS");
File[] files = dir.listFiles();
for (File file : files){
if (file.isFile()){
JSONObject json = new JSONObject();
json.put("path", file.getPath());
json.put("name", file.getName());
json.put("size", file.length());
arr.add(json);
}
}
return arr;
}
private File toFile(String path) throws FileNotFoundException {
File file;
if (path.startsWith("/")) {
file = createProgramFile(path);
} else if (path.startsWith("classpath:") || path.startsWith("file:")) {
file = ResourceUtils.getFile(path);
} else if (path.startsWith("hdfs:")) {
throw new UnsupportedOperationException();
} else if (path.startsWith("http:")) {
throw new UnsupportedOperationException();
} else if (path.startsWith("https:")) {
throw new UnsupportedOperationException();
} else {
//default download from nexus
MavenLoaderInfo mavenLoaderInfo = MavenJarUtil.forAvg(releaseRepositoryUrl, snapRepositoryUrl, path);
file = mavenLoaderInfo.getJarFile();
}
return file;
}
@Nullable
private static KeyStore keyStoreFromResource(OneOpsConfig.TrustStore config) {
try {
try (InputStream ins = new FileInputStream(ResourceUtils.getFile(config.getPath()))) {
log.info("Loading the trust-store: " + config.getPath());
if (ins == null) {
throw new IllegalStateException("Can't find the trust-store.");
}
KeyStore ks = KeyStore.getInstance(config.getType());
ks.load(ins, config.getStorePassword());
return ks;
}
} catch (IOException | GeneralSecurityException ex) {
throw new IllegalStateException("Can't load the trust-store (" + config.getPath() + ").", ex);
}
}
/**
* 将html中外联的css变成内联,并去掉外联样式
* @author Frodez
* @date 2019-03-21
*/
@Override
public String revert(String html) {
Assert.notNull(html, "html must not be null");
try {
Document document = Jsoup.parse(html);
Elements links = document.select("link[href]");
Elements htmlElement = document.select("html");
for (Element iter : links) {
String path = iter.attr("href");
if (!path.endsWith(".css")) {
continue;
}
htmlElement.prepend(StrUtil.concat("<style type=\"text/css\">", FileUtil.readString(ResourceUtils
.getFile(StrUtil.concat(FreemarkerRender.getLoaderPath(), path))), "</style>"));
}
links.remove();
return document.html();
} catch (Exception e) {
log.error("[frodez.util.renderer.reverter.CSSReverter.revert]", e);
return html;
}
}
/**
* 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);
}
}
/**
* Resolve the given jar file URL into a JarFile object.
*/
protected JarFile getJarFile(String jarFileUrl) throws IOException {
if (jarFileUrl.startsWith(ResourceUtils.FILE_URL_PREFIX)) {
try {
return new JarFile(ResourceUtils.toURI(jarFileUrl).getSchemeSpecificPart());
}
catch (URISyntaxException ex) {
// Fallback for URLs that are not valid URIs (should hardly ever happen).
return new JarFile(jarFileUrl.substring(ResourceUtils.FILE_URL_PREFIX.length()));
}
}
else {
return new JarFile(jarFileUrl);
}
}
/**
* For replaceExisting = true, the title must be taken from the metadata and not overridden by the actual filename.
*
* @throws Throwable
*/
@Test
public void testMNT8470() throws Throwable
{
txn = transactionService.getUserTransaction();
txn.begin();
NodeRef folderNode = topLevelFolder.getNodeRef();
try
{
NodeImporter nodeImporter = streamingNodeImporterFactory.getNodeImporter(ResourceUtils.getFile("classpath:bulkimport1"));
BulkImportParameters bulkImportParameters = new BulkImportParameters();
bulkImportParameters.setTarget(folderNode);
bulkImportParameters.setReplaceExisting(true);
bulkImportParameters.setDisableRulesService(true);
bulkImportParameters.setBatchSize(40);
bulkImporter.bulkImport(bulkImportParameters, nodeImporter);
}
catch(Throwable e)
{
fail(e.getMessage());
}
System.out.println(bulkImporter.getStatus());
assertEquals(false, bulkImporter.getStatus().inProgress());
List<FileInfo> folders = getFolders(folderNode, null);
assertEquals(1, folders.size());
FileInfo folder1 = folders.get(0);
assertEquals("folder1", folder1.getName());
// title should be taken from the metadata file
assertEquals("", folder1.getProperties().get(ContentModel.PROP_TITLE));
}
/**
* Determine the persistence unit root URL based on the given resource
* (which points to the {@code persistence.xml} file we're reading).
* @param resource the resource to check
* @return the corresponding persistence unit root URL
* @throws IOException if the checking failed
*/
protected URL determinePersistenceUnitRootUrl(Resource resource) throws IOException {
URL originalURL = resource.getURL();
// If we get an archive, simply return the jar URL (section 6.2 from the JPA spec)
if (ResourceUtils.isJarURL(originalURL)) {
return ResourceUtils.extractJarFileURL(originalURL);
}
// check META-INF folder
String urlToString = originalURL.toExternalForm();
if (!urlToString.contains(META_INF)) {
if (logger.isInfoEnabled()) {
logger.info(resource.getFilename() +
" should be located inside META-INF directory; cannot determine persistence unit root URL for " +
resource);
}
return null;
}
if (urlToString.lastIndexOf(META_INF) == urlToString.lastIndexOf('/') - (1 + META_INF.length())) {
if (logger.isInfoEnabled()) {
logger.info(resource.getFilename() +
" is not located in the root of META-INF directory; cannot determine persistence unit root URL for " +
resource);
}
return null;
}
String persistenceUnitRoot = urlToString.substring(0, urlToString.lastIndexOf(META_INF));
if (persistenceUnitRoot.endsWith("/")) {
persistenceUnitRoot = persistenceUnitRoot.substring(0, persistenceUnitRoot.length() - 1);
}
return new URL(persistenceUnitRoot);
}
@Test
public void testLoadIntoMap() throws IOException {
File configFile = ResourceUtils.getFile("classpath:ea-default.yaml");
// get the yaml resource
// yaml mapper
ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
Map configuration = objectMapper.readValue(new FileInputStream(configFile), Map.class);
assertNotNull(configuration);
}
/**
* This implementation returns a File reference for the given URI-identified
* resource, provided that it refers to a file in the file system.
* @see org.springframework.util.ResourceUtils#getFile(java.net.URI, String)
*/
protected File getFile(URI uri) throws IOException {
if (uri.getScheme().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) {
return VfsResourceDelegate.getResource(uri).getFile();
}
return ResourceUtils.getFile(uri, getDescription());
}
@Override
public void setUp() throws Exception
{
auditModelRegistry = (AuditModelRegistryImpl) ctx.getBean("auditModel.modelRegistry");
auditModelRegistry.setProperty(AuditModelRegistryImpl.PROPERTY_AUDIT_CONFIG_STRICT, Boolean.TRUE.toString());
// Register a new model
URL testModelUrl = ResourceUtils.getURL("classpath:alfresco/testaudit/alfresco-audit-test.xml");
auditModelRegistry.registerModel(testModelUrl);
auditModelRegistry.loadAuditModels();
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
if (!StringUtils.hasText(text)) {
setValue(null);
return;
}
// Check whether we got an absolute file path without "file:" prefix.
// For backwards compatibility, we'll consider those as straight file path.
if (!ResourceUtils.isUrl(text)) {
File file = new File(text);
if (file.isAbsolute()) {
setValue(file);
return;
}
}
// Proceed with standard resource location parsing.
this.resourceEditor.setAsText(text);
Resource resource = (Resource) this.resourceEditor.getValue();
// If it's a URL or a path pointing to an existing resource, use it as-is.
if (ResourceUtils.isUrl(text) || resource.exists()) {
try {
setValue(resource.getFile());
}
catch (IOException ex) {
throw new IllegalArgumentException(
"Could not retrieve File for " + resource + ": " + ex.getMessage());
}
}
else {
// Create a relative File reference and hope for the best.
setValue(new File(text));
}
}
/**
* Try to determine the persistence unit root URL based on the given
* "defaultPersistenceUnitRootLocation".
* @return the persistence unit root URL to pass to the JPA PersistenceProvider
* @see #setDefaultPersistenceUnitRootLocation
*/
private URL determineDefaultPersistenceUnitRootUrl() {
if (this.defaultPersistenceUnitRootLocation == null) {
return null;
}
try {
URL url = this.resourcePatternResolver.getResource(this.defaultPersistenceUnitRootLocation).getURL();
return (ResourceUtils.isJarURL(url) ? ResourceUtils.extractJarFileURL(url) : url);
}
catch (IOException ex) {
throw new PersistenceException("Unable to resolve persistence unit root URL", ex);
}
}
/**
* This implementation builds a URI based on the URL returned
* by {@link #getURL()}.
*/
@Override
public URI getURI() throws IOException {
URL url = getURL();
try {
return ResourceUtils.toURI(url);
}
catch (URISyntaxException ex) {
throw new NestedIOException("Invalid URI [" + url + "]", ex);
}
}
private String getArtifactPath(String hostMachine, String artifact) throws Exception {
String path;
if (!isCloud(hostMachine) && !isLocalhost(hostMachine) && !ResourceUtils.isUrl(artifact)) {
path = uploadFile(hostMachine, artifact);
} else {
path = artifact;
}
return path;
}
/**
* This implementation resolves "file:" URLs or alternatively delegates to
* {@code ServletContext.getRealPath}, throwing a FileNotFoundException
* if not found or not resolvable.
* @see javax.servlet.ServletContext#getResource(String)
* @see javax.servlet.ServletContext#getRealPath(String)
*/
@Override
public File getFile() throws IOException {
URL url = this.servletContext.getResource(this.path);
if (url != null && ResourceUtils.isFileURL(url)) {
// Proceed with file system resolution...
return super.getFile();
}
else {
String realPath = WebUtils.getRealPath(this.servletContext, this.path);
return new File(realPath);
}
}
/**
* Extract entries from the given jar by pattern.
* @param jarFilePath the path to the jar file
* @param entryPattern the pattern for jar entries to match
* @param result the Set of matching Resources to add to
*/
private void doRetrieveMatchingJarEntries(String jarFilePath, String entryPattern, Set<Resource> result) {
if (logger.isDebugEnabled()) {
logger.debug("Searching jar file [" + jarFilePath + "] for entries matching [" + entryPattern + "]");
}
try {
JarFile jarFile = new JarFile(jarFilePath);
try {
for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements();) {
JarEntry entry = entries.nextElement();
String entryPath = entry.getName();
if (getPathMatcher().match(entryPattern, entryPath)) {
result.add(new UrlResource(
ResourceUtils.URL_PROTOCOL_JAR,
ResourceUtils.FILE_URL_PREFIX + jarFilePath + ResourceUtils.JAR_URL_SEPARATOR + entryPath));
}
}
}
finally {
jarFile.close();
}
}
catch (IOException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Cannot search for matching resources in jar file [" + jarFilePath +
"] because the jar cannot be opened through the file system", ex);
}
}
}