org.springframework.util.ResourceUtils Java Examples

The following examples show how to use org.springframework.util.ResourceUtils. 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: FileRefreshableDataSourceFactoryBeanTests.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #2
Source File: AbstractRenditionIntegrationTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #3
Source File: CSSReverter.java    From BlogManagePlatform with Apache License 2.0 6 votes vote down vote up
/**
 * 将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;
	}
}
 
Example #4
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 #5
Source File: ThemeController.java    From blog-sharon with Apache License 2.0 6 votes vote down vote up
/**
 * 更新主题
 *
 * @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"));
}
 
Example #6
Source File: AuditAppTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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();
}
 
Example #7
Source File: UrlResource.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * 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;
	}
}
 
Example #8
Source File: ContractIT.java    From restful-booker-platform with GNU General Public License v3.0 6 votes vote down vote up
@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);
}
 
Example #9
Source File: DkesService.java    From dk-fitting with Apache License 2.0 6 votes vote down vote up
/**
 * 将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;
}
 
Example #10
Source File: ThemeController.java    From blog-sharon with Apache License 2.0 6 votes vote down vote up
/**
 * 获取模板文件内容
 *
 * @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;
}
 
Example #11
Source File: ContractServiceImpl.java    From springboot-learn with MIT License 6 votes vote down vote up
@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;
}
 
Example #12
Source File: ProxyClientUtil.java    From secrets-proxy with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example #13
Source File: UrlJarLoader.java    From alchemy with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #14
Source File: IndexController.java    From kbase-doc with Apache License 2.0 6 votes vote down vote up
/**
 * 文件列表
 * @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;
}
 
Example #15
Source File: MySqlMybatisGenerator.java    From java-master with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #16
Source File: BackupController.java    From stone with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 备份资源文件 重要
 *
 * @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"));
    }
}
 
Example #17
Source File: PathUtil.java    From mica with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example #18
Source File: ServletContextResource.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
	}
}
 
Example #19
Source File: HaloUtils.java    From stone with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 获取所有主题
 *
 * @return List
 */
public static List<Theme> getThemes() {
    final List<Theme> themes = new ArrayList<>();
    try {
        // 获取项目根路径
        final File basePath = new File(ResourceUtils.getURL("classpath:").getPath());
        // 获取主题路径
        final File themesPath = new File(basePath.getAbsolutePath(), "templates/themes");
        final File[] files = themesPath.listFiles();
        if (null != files) {
            Theme theme = null;
            for (File file : files) {
                if (file.isDirectory()) {
                    if (StrUtil.equals("__MACOSX", file.getName())) {
                        continue;
                    }
                    theme = new Theme();
                    theme.setThemeName(file.getName());
                    File optionsPath = new File(themesPath.getAbsolutePath(),
                            file.getName() + "/module/options.ftl");
                    if (optionsPath.exists()) {
                        theme.setHasOptions(true);
                    } else {
                        theme.setHasOptions(false);
                    }
                    File gitPath = new File(themesPath.getAbsolutePath(), file.getName() + "/.git");
                    if (gitPath.exists()) {
                        theme.setHasUpdate(true);
                    } else {
                        theme.setHasUpdate(false);
                    }
                    themes.add(theme);
                }
            }
        }
    } catch (Exception e) {
        log.error("Themes scan failed:{}", e.getMessage());
    }
    return themes;
}
 
Example #20
Source File: CommonsUtilsTest.java    From rebuild with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void zip() throws Exception {
 File file = ResourceUtils.getFile("classpath:metadata-conf.xml");
 File dest = SysConfiguration.getFileOfTemp(file.getName() + ".zip");
 CommonsUtils.zip(file, dest);
 System.out.println("Zip to : " + dest);
}
 
Example #21
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 #22
Source File: FileUtil.java    From jeesupport with MIT License 5 votes vote down vote up
private static File _try_clspath_loader( String _path ){
    File file = null;
    if ( _path.startsWith( "classpath:" ) ){
        try{
            file = ResourceUtils.getFile( _path );
        }catch( FileNotFoundException e ){
        }
    }

    return file;
}
 
Example #23
Source File: WebConfig.java    From taoshop with Apache License 2.0 5 votes vote down vote up
@Override  
public void addResourceHandlers(ResourceHandlerRegistry registry) {
  
    registry.addResourceHandler("/templates/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/templates/");
    registry.addResourceHandler("/static/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/static/");
    registry.addResourceHandler("/plugins/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/static/");
    super.addResourceHandlers(registry);
}
 
Example #24
Source File: Installer.java    From rebuild with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @return
 * @throws IOException
 */
protected String[] getDbInitScript() throws IOException {
    File script = ResourceUtils.getFile("classpath:scripts/db-init.sql");
    List<?> LS = FileUtils.readLines(script, "utf-8");

    List<String> SQLS = new ArrayList<>();
    StringBuilder SQL = new StringBuilder();
    boolean ignoreTerms = false;
    for (Object L : LS) {
        String L2 = L.toString().trim();

        // NOTE double 字段也不支持
        boolean H2Unsupported = quickMode
                && (L2.startsWith("fulltext ") || L2.startsWith("unique ") || L2.startsWith("index "));

        // Ignore comments and line of blank
        if (StringUtils.isEmpty(L2) || L2.startsWith("--") || H2Unsupported) {
            continue;
        }
        if (L2.startsWith("/*") || L2.endsWith("*/")) {
            ignoreTerms = L2.startsWith("/*");
            continue;
        } else if (ignoreTerms) {
            continue;
        }

        SQL.append(L2);
        if (L2.endsWith(";")) {  // SQL ends
            SQLS.add(SQL.toString().replace(",\n)Engine=", "\n)Engine="));
            SQL = new StringBuilder();
        } else {
            SQL.append('\n');
        }
    }
    return SQLS.toArray(new String[0]);
}
 
Example #25
Source File: WatermarkController.java    From kbase-doc with Apache License 2.0 5 votes vote down vote up
/**
 * 输出文件demo https://o7planning.org/en/11765/spring-boot-file-download-example
 * @author eko.zhan at 2018年9月2日 下午4:26:10
 * @param file
 * @param text
 * @param color
 * @return
 * @throws IOException
 */
@ApiOperation(value="传入文件并返回水印文件", response=ResponseMessage.class)
@ApiImplicitParams({
        @ApiImplicitParam(name="file", value="待添加水印的文件", dataType="__file", required=true, paramType="form"),
        @ApiImplicitParam(name="text", value="水印内容", dataType="string", required=false, paramType="form"),
        @ApiImplicitParam(name="color", value="颜色码,以#开头", dataType="string", required=false, paramType="form")
})
@PostMapping("/handle")
public ResponseEntity<ByteArrayResource> handle(@RequestParam("file") MultipartFile file, @RequestParam(value="text", required=false) String text, @RequestParam(value="color", required=false) String color) throws IOException {
	if (!file.getOriginalFilename().toLowerCase().endsWith(".docx")) {
		log.error("上传的文件必须是 docx 类型");
	}
	File dir = ResourceUtils.getFile("classpath:static/DATAS");
	String pardir = DateFormatUtils.format(new Date(), "yyyyMMdd");
	String filename = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + "." + FilenameUtils.getExtension(file.getOriginalFilename());
	File originFile = new File(dir + "/" + pardir + "/" + filename);
	FileUtils.copyInputStreamToFile(file.getInputStream(), originFile);
	byte[] bytes = watermarkService.handle(originFile, text, color);
	ByteArrayResource resource = new ByteArrayResource(bytes);
	return ResponseEntity.ok()
			// Content-Disposition
			.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + originFile.getName())
			// Content-Type
			.contentType(getMediaType(originFile.getName()))
			// Contet-Length
			.contentLength(bytes.length)
			.body(resource);
}
 
Example #26
Source File: VersionServiceTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldReturnSpecificZoweVersion() throws FileNotFoundException {
    File file = ResourceUtils.getFile(CLASSPATH_URL_PREFIX + "zowe.version/zowe-manifest.json");
    ReflectionTestUtils.setField(versionService, ZOWE_MANIFEST_FIELD, file.getAbsolutePath());

    VersionInfo version = versionService.getVersion();
    assertNotNull(version.getZowe());
    assertEquals("1.8.0", version.getZowe().getVersion());
    assertEquals("802", version.getZowe().getBuildNumber());
    assertEquals("397a4365056685d639810a077a58b736db9f018b", version.getZowe().getCommitHash());
}
 
Example #27
Source File: ClassificationFileImporterTest.java    From rebuild with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void exec() throws Exception {
    ID newClass = ClassificationImporterTest.getClassification();
    File file = ResourceUtils.getFile("classpath:classification-demo.xlsx");

    ClassificationFileImporter importer = new ClassificationFileImporter(newClass, file);
    TaskExecutors.run(importer.setUser(UserService.SYSTEM_USER));
    System.out.println("ClassificationFileImporter : " + importer.getSucceeded());
}
 
Example #28
Source File: DefaultConfigurationTest.java    From elasticactors with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadComplexObject() throws IOException {
    File configFile = ResourceUtils.getFile("classpath:ea-test.yaml");

    // yaml mapper
    ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
    DefaultConfiguration configuration = objectMapper.readValue(new FileInputStream(configFile), DefaultConfiguration.class);

    assertFalse(configuration.getProperty(
            TestActor.class,
            "pushConfigurations",
            List.class,
            Collections.emptyList()).isEmpty());
}
 
Example #29
Source File: PathMatchingResourcePatternResolver.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
	}
}
 
Example #30
Source File: PDFConverter.java    From BlogManagePlatform with Apache License 2.0 5 votes vote down vote up
/**
 * 添加字体
 * @author Frodez
 * @date 2019-05-19
 */
@SneakyThrows
public static void addFont(String alias, String fileName) {
	FontProperties properties = ContextUtil.bean(FontProperties.class);
	fontCache.put(alias, FontProgramFactory.createFont(FileUtil.readBytes(ResourceUtils.getFile(StrUtil.concat(properties.getPath(), fileName))),
		false));
}