下面列出了怎么用org.springframework.core.io.FileSystemResource的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void sendMessageWithAttachment(String to,
String subject,
String text,
String pathToAttachment) {
try {
MimeMessage message = emailSender.createMimeMessage();
// pass 'true' to the constructor to create a multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(NOREPLY_ADDRESS);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text);
FileSystemResource file = new FileSystemResource(new File(pathToAttachment));
helper.addAttachment("Invoice", file);
emailSender.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
/**
* 发送带附件的邮件
* @param to
* @param subject
* @param content
* @param filePathList
* @throws MessagingException
*/
public void sendAttachmentMail(String to, String subject, String content, String[] filePathList) throws MessagingException {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
for (String filePath: filePathList) {
System.out.println(filePath);
FileSystemResource fileSystemResource = new FileSystemResource(new File(filePath));
String fileName = fileSystemResource.getFilename();
helper.addAttachment(fileName, fileSystemResource);
}
javaMailSender.send(message);
}
@Test
void getFingerprint() throws IOException {
String theme = "bootstrap-theme-name.min.css";
String version = "bootstrap-3";
String themeUri = "css/theme/" + version + "/" + theme;
FileSystemResource themeFile = mock(FileSystemResource.class);
InputStream themeDataStream = IOUtils.toInputStream("yo yo yo data");
when(themeFile.getInputStream()).thenReturn(themeDataStream);
when(styleService.getThemeData(theme, BootstrapVersion.BOOTSTRAP_VERSION_3))
.thenReturn(themeFile);
// first call
String firstResult = themeFingerprintRegistry.getFingerprint(themeUri);
assertNotNull(firstResult);
verify(styleService).getThemeData(theme, BootstrapVersion.BOOTSTRAP_VERSION_3);
// second call
String secondResult = themeFingerprintRegistry.getFingerprint(themeUri);
verifyNoMoreInteractions(styleService);
// verify stable key
assertEquals(secondResult, firstResult);
}
private ResponseEntity<FileSystemResource> downloadFile(File file) {
if (file == null) {
return null;
}
if (!file.exists()) {
return null;
}
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
String suffixName = file.getName().substring(file.getName().lastIndexOf("."));// 后缀名
headers.add("Content-Disposition", "attachment; filename=" + System.currentTimeMillis() + suffixName);
headers.add("Pragma", "no-cache");
headers.add("Access-Control-Expose-Headers", "Content-Disposition");
headers.add("Expires", "0");
headers.add("Last-Modified", new Date().toString());
headers.add("ETag", String.valueOf(System.currentTimeMillis()));
return ResponseEntity.ok().headers(headers).contentLength(file.length())
.contentType(MediaType.parseMediaType("application/octet-stream")).body(new FileSystemResource(file));
}
@Bean
public FlatFileItemWriter<Person> itemWriter() {
BeanWrapperFieldExtractor<Person> fieldExtractor =
new BeanWrapperFieldExtractor<>();
fieldExtractor.setNames(new String[] {"firstName", "lastName"});
fieldExtractor.afterPropertiesSet();
DelimitedLineAggregator<Person> lineAggregator =
new DelimitedLineAggregator<>();
lineAggregator.setDelimiter(",");
lineAggregator.setFieldExtractor(fieldExtractor);
FlatFileItemWriter<Person> flatFileItemWriter =
new FlatFileItemWriter<>();
flatFileItemWriter.setName("personItemWriter");
flatFileItemWriter.setResource(
new FileSystemResource("target/test-outputs/persons.txt"));
flatFileItemWriter.setLineAggregator(lineAggregator);
return flatFileItemWriter;
}
@BeforeEach
void setUp() {
deploymentProperties = new CloudFoundryDeploymentProperties();
CloudFoundryTargetProperties targetProperties = new CloudFoundryTargetProperties();
targetProperties.setDefaultOrg("default-org");
targetProperties.setDefaultSpace("default-space");
given(operationsApplications.pushManifest(any())).willReturn(Mono.empty());
given(resourceLoader.getResource(APP_PATH)).willReturn(new FileSystemResource(APP_PATH));
given(cloudFoundryOperations.spaces()).willReturn(operationsSpaces);
given(cloudFoundryOperations.applications()).willReturn(operationsApplications);
given(cloudFoundryOperations.services()).willReturn(operationsServices);
given(cloudFoundryOperations.organizations()).willReturn(operationsOrganizations);
given(cloudFoundryClient.serviceInstances()).willReturn(clientServiceInstances);
given(cloudFoundryClient.spaces()).willReturn(clientSpaces);
given(cloudFoundryClient.organizations()).willReturn(clientOrganizations);
given(cloudFoundryClient.applicationsV2()).willReturn(clientApplications);
given(operationsUtils.getOperations(anyMap())).willReturn(Mono.just(cloudFoundryOperations));
given(operationsUtils.getOperationsForSpace(anyString())).willReturn(Mono.just(cloudFoundryOperations));
given(operationsUtils.getOperationsForOrgAndSpace(anyString(), anyString()))
.willReturn(Mono.just(cloudFoundryOperations));
appDeployer = new CloudFoundryAppDeployer(deploymentProperties, cloudFoundryOperations, cloudFoundryClient,
operationsUtils, targetProperties, resourceLoader);
}
private String addResourcesInMessage(final MimeMessageHelper mailMessage, final String htmlText) throws Exception {
final Document document = Jsoup.parse(htmlText);
final List<String> resources = new ArrayList<>();
final Elements imageElements = document.getElementsByTag("img");
resources.addAll(imageElements.stream()
.filter(imageElement -> imageElement.hasAttr("src"))
.filter(imageElement -> !imageElement.attr("src").startsWith("http"))
.map(imageElement -> {
final String src = imageElement.attr("src");
imageElement.attr("src", "cid:" + src);
return src;
})
.collect(Collectors.toList()));
final String html = document.html();
mailMessage.setText(html, true);
for (final String res : resources) {
final FileSystemResource templateResource = new FileSystemResource(new File(templatesPath, res));
mailMessage.addInline(res, templateResource, getContentTypeByFileName(res));
}
return html;
}
@Test(expected = IllegalStateException.class)
public void secureServerSupportsTlsNeedsClientAuthKeystoreProvidedTruststoreNotProvided() throws Throwable {
try {
TlsNioConfig config = new TlsNioConfig();
config.setNioLogger(logger);
config.setMbeanServer(mbeanServer);
config.setTruststoreType("JKS");
config.setKeystore(new FileSystemResource(getServerKeystorePath()));
config.setKeystorePassword("password");
config.setKeystoreType("JKS");
config.setWantClientAuth(true);
config.setNeedClientAuth(false);
config.setRequiresTls(false);
config.setSupportsTls(true);
config.setTruststoreType("JKS");
config.configureProtocol(minaConfig, true);
fail("Expected an exception");
}
catch (IOException ioe) {
throw ioe.getCause();
}
}
private static void buildMimeMessage(MailDTO mailDTO, MimeMessage mimeMessage) throws MessagingException {
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(verifyNotNull(mailDTO.getFrom(), "邮件发送人不能为空"));
helper.setTo(verifyNotNull(mailDTO.getTo(), "邮件接收人不能为空"));
helper.setText(mailDTO.getContent(), mailDTO.isHtml());
helper.setSubject(mailDTO.getSubject());
if (!isEmpty(mailDTO.getTocc()) && isNotBlank(mailDTO.getTocc()[0])) {
helper.setCc(mailDTO.getTocc());
}
if (mailDTO.isHasImage()) {
helper.addInline(mailDTO.getImageId(), mailDTO.ResourceImage());
}
if (mailDTO.isHasAttachment()) {
FileSystemResource docx = new FileSystemResource(new File(mailDTO.getAttachmentPath()));
helper.addAttachment(mailDTO.getAttachmentName(), docx);
}
}
@Test
public void testInvalidCron() {
thrown.expect(CreateScheduleException.class);
thrown.expectMessage("Illegal characters for this position: 'FOO'");
Resource resource = new FileSystemResource("src/test/resources/demo-0.0.1-SNAPSHOT.jar");
mockAppResultsInAppList();
AppDefinition definition = new AppDefinition("test-application-1", null);
Map badCronMap = new HashMap<String, String>();
badCronMap.put(CRON_EXPRESSION, BAD_CRON_EXPRESSION);
ScheduleRequest request = new ScheduleRequest(definition, badCronMap, null, "test-schedule", resource);
this.cloudFoundryAppScheduler.schedule(request);
assertThat(((TestJobs) this.client.jobs()).getCreateJobResponse()).isNull();
}
/**
* 发送正文中有静态资源的邮件
*
* @param to 收件人地址
* @param subject 邮件主题
* @param content 邮件内容
* @param rscPath 静态资源地址
* @param rscId 静态资源id
* @param cc 抄送地址
* @throws MessagingException 邮件发送异常
*/
@Override
public void sendResourceMail(String to, String subject, String content, String rscPath, String rscId, String... cc) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
if (ArrayUtil.isNotEmpty(cc)) {
helper.setCc(cc);
}
FileSystemResource res = new FileSystemResource(new File(rscPath));
helper.addInline(rscId, res);
mailSender.send(message);
}
/**
* Creates a new test instance with given parameters.
*
* @param checker Revocation checker instance.
* @param expiredCRLPolicy Policy instance for handling expired CRL data.
* @param certFiles File names of certificates to check.
* @param crlFile File name of CRL file to serve out.
* @param expected Expected result of check; null to indicate expected success.
*/
public CRLDistributionPointRevocationCheckerTests(
final CRLDistributionPointRevocationChecker checker,
final RevocationPolicy<X509CRL> expiredCRLPolicy,
final String[] certFiles,
final String crlFile,
final GeneralSecurityException expected) throws Exception {
super(certFiles, expected);
final File file = new File(System.getProperty("java.io.tmpdir"), "ca.crl");
if (file.exists()) {
file.delete();
}
final OutputStream out = new FileOutputStream(file);
IOUtils.copy(new ClassPathResource(crlFile).getInputStream(), out);
this.checker = checker;
this.checker.setExpiredCRLPolicy(expiredCRLPolicy);
this.webServer = new MockWebServer(8085, new FileSystemResource(file), "text/plain");
logger.debug("Web server listening on port 8085 serving file {}", crlFile);
}
@Test(expected = IllegalStateException.class)
public void secureServerSupportsTlsWantsClientAuthKeystoreProvidedTruststoreNotProvided() throws Throwable {
try {
TlsNioConfig config = new TlsNioConfig();
config.setNioLogger(logger);
config.setMbeanServer(mbeanServer);
config.setTruststoreType("JKS");
config.setKeystore(new FileSystemResource(getServerKeystorePath()));
config.setKeystorePassword("password");
config.setKeystoreType("JKS");
config.setWantClientAuth(true);
config.setNeedClientAuth(false);
config.setRequiresTls(false);
config.setSupportsTls(true);
config.setTruststoreType("JKS");
config.configureProtocol(minaConfig, true);
fail("Expected an exception");
}
catch (IOException ioe) {
throw ioe.getCause();
}
}
@Test
public void blowsUpWhenFileNameDoesNotMatch() throws Exception {
String file1Content = "hello world";
String file2Content = "bonjour";
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("file1", new FileSystemResource(newFile(file1Content).getAbsolutePath()));
map.add("unmatched name", new FileSystemResource(newFile(file2Content).getAbsolutePath()));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
ResponseEntity<String> response = null;
try {
response = restTemplate
.postForEntity(codeFirstUrl + "uploadWithoutAnnotation", new HttpEntity<>(map, headers), String.class);
assertEquals("required is true, throw exception", "but not throw exception");
} catch (HttpClientErrorException e) {
assertEquals(400, e.getRawStatusCode());
assertEquals("Bad Request", e.getStatusCode().getReasonPhrase());
}
}
/**
* Call back when a dictionary file is changed. Calls the spring bean reader
* to reload the file (which will override beans as necessary and destroy
* singletons) and runs the indexer
*
* @see no.geosoft.cc.io.FileListener#fileChanged(java.io.File)
*/
public void fileChanged(File file) {
LOG.info("reloading dictionary configuration for " + file.getName());
try {
List<String> beforeReloadBeanNames = Arrays.asList(ddBeans.getBeanDefinitionNames());
Resource resource = new FileSystemResource(file);
xmlReader.loadBeanDefinitions(resource);
List<String> afterReloadBeanNames = Arrays.asList(ddBeans.getBeanDefinitionNames());
List<String> addedBeanNames = ListUtils.removeAll(afterReloadBeanNames, beforeReloadBeanNames);
String namespace = KRADConstants.DEFAULT_NAMESPACE;
if (fileToNamespaceMapping.containsKey(file.getAbsolutePath())) {
namespace = fileToNamespaceMapping.get(file.getAbsolutePath());
}
ddIndex.addBeanNamesToNamespace(namespace, addedBeanNames);
performDictionaryPostProcessing(true);
} catch (Exception e) {
LOG.info("Exception in dictionary hot deploy: " + e.getMessage(), e);
}
}
@Bean(name = "graviteeProperties")
public static Properties graviteeProperties() throws IOException {
LOGGER.info("Loading Gravitee Management configuration.");
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
String yamlConfiguration = System.getProperty(GRAVITEE_CONFIGURATION);
Resource yamlResource = new FileSystemResource(yamlConfiguration);
LOGGER.info("\tGravitee Management configuration loaded from {}", yamlResource.getURL().getPath());
yaml.setResources(yamlResource);
Properties properties = yaml.getObject();
LOGGER.info("Loading Gravitee Management configuration. DONE");
return properties;
}
/**
* 下载
* @param file 文件
* @param fileName 生成的文件名
* @return {ResponseEntity}
*/
protected ResponseEntity<Resource> download(File file, String fileName) {
Resource resource = new FileSystemResource(file);
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();
String header = request.getHeader("User-Agent");
// 避免空指针
header = header == null ? "" : header.toUpperCase();
HttpStatus status;
if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
fileName = URLUtils.encodeURL(fileName, Charsets.UTF_8);
status = HttpStatus.OK;
} else {
fileName = new String(fileName.getBytes(Charsets.UTF_8), Charsets.ISO_8859_1);
status = HttpStatus.CREATED;
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", fileName);
return new ResponseEntity<Resource>(resource, headers, status);
}
@RequestMapping("sendInlineMail")
public String sendInlineMail() {
MimeMessage message = null;
try {
message = jms.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo("[email protected]"); // 接收地址
helper.setSubject("一封带静态资源的邮件"); // 标题
helper.setText("<html><body>博客图:<img src='cid:img'/></body></html>", true); // 内容
// 传入附件
FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/img/sunshine.png"));
helper.addInline("img", file);
jms.send(message);
return "发送成功";
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
protected WxMessageBody.Video processVideoBody(WxMessageParameter wxMessageParameter, WxMessageBody.Video body) {
if (body.getThumbMediaId() == null) {
String thumbMediaId = null;
// 优先使用path
if (body.getMediaResource() != null) {
thumbMediaId = wxMediaManager.addTempMedia(WxMedia.Type.THUMB, body.getThumbMediaResource());
} else if (body.getThumbMediaPath() != null) {
thumbMediaId = wxMediaManager.addTempMedia(WxMedia.Type.THUMB, new FileSystemResource(body.getThumbMediaPath()));
} else if (body.getThumbMediaUrl() != null) {
String url = WxUrlUtils.absoluteUrl(wxMessageParameter.getRequestUrl(), body.getThumbMediaUrl());
thumbMediaId = wxMediaManager.addTempMediaByUrl(WxMedia.Type.THUMB, url);
}
body.setThumbMediaId(thumbMediaId);
}
return body;
}
public UploadFile uploadFile(File file, Integer fileType) {
MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>();
multiValueMap.add("file", new FileSystemResource(file));
Response<UploadFile> response = restTemplate.exchange(uploadFileUrl,
HttpMethod.POST,
new HttpEntity<>(multiValueMap),
new ParameterizedTypeReference<Response<UploadFile>>() {
},
fileType).getBody();
if (response.isSuccess()) {
return response.getData();
} else {
throw new RuntimeException(response.getMsg());
}
}
@Test
public void testFileUploadList() {
Map<String, Object> map = new HashMap<>();
List<FileSystemResource> list1 = new ArrayList<>();
List<FileSystemResource> list2 = new ArrayList<>();
list1.add(fileSystemResource1);
list1.add(fileSystemResource2);
list2.add(fileSystemResource3);
list2.add(fileSystemResource4);
map.put("file1", list1);
map.put("file2", list2);
map.put("name", message);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
String result = consumersSpringmvc.getSCBRestTemplate()
.postForObject("/uploadList", new HttpEntity<>(map, headers), String.class);
Assert.assertTrue(containsAll(result, "hello1", "cse4", "cse3", "中文 2", message));
}
/**
* 下载
* @param file 文件
* @param fileName 生成的文件名
* @return {ResponseEntity}
*/
protected ResponseEntity<Resource> download(File file, String fileName) {
Resource resource = new FileSystemResource(file);
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();
String header = request.getHeader("User-Agent");
// 避免空指针
header = header == null ? "" : header.toUpperCase();
HttpStatus status;
if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
fileName = URLUtils.encodeURL(fileName, Charsets.UTF_8);
status = HttpStatus.OK;
} else {
fileName = new String(fileName.getBytes(Charsets.UTF_8), Charsets.ISO_8859_1);
status = HttpStatus.CREATED;
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", fileName);
return new ResponseEntity<Resource>(resource, headers, status);
}
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Resource> read(@PathVariable Long id) throws Exception {
Person person = this.personRepository.findOne(id);
File file = fileFor(person);
if (!file.exists()) {
throw new FileNotFoundException(file.getAbsolutePath());
}
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.IMAGE_JPEG);
Resource resource = new FileSystemResource(file);
return new ResponseEntity<>(resource, httpHeaders, HttpStatus.OK);
}
/**
* @return the vault properties.
*/
public static SslConfiguration createSslConfiguration() {
File workDir = findWorkDir();
return SslConfiguration.forTrustStore(new FileSystemResource(new File(workDir, "keystore.jks")),
"changeit".toCharArray());
}
@Test
public void testFileUploadArray() {
Map<String, Object> map = new HashMap<>();
FileSystemResource[] array1 = {fileSystemResource1, fileSystemResource2};
FileSystemResource[] array2 = {fileSystemResource3, fileSystemResource4};
map.put("file1", array1);
map.put("file2", array2);
map.put("name", message);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
String result = consumersSpringmvc.getSCBRestTemplate()
.postForObject("/uploadArray", new HttpEntity<>(map, headers), String.class);
Assert.assertTrue(containsAll(result, "hello1", "cse4", "cse3", "中文 2", message));
}
static Resource getResource(String location) {
if (isExistingFile(location)) {
return new FileSystemResource(location);
} else {
ResourceLoader loader = new DefaultResourceLoader();
return loader.getResource(location);
}
}
@Test
public void testNameTooLong() {
thrown.expect(CreateScheduleException.class);
thrown.expectMessage("Schedule can not be created because its name " +
"'j1-scdf-itcouldbesaidthatthisislongtoowaytoo-oopsitcouldbesaidthatthisis" +
"longtoowaytoo-oopsitcouldbesaidthatthisislongtoowaytoo-oopsitcouldbe" +
"saidthatthisislongtoowaytoo-oopsitcouldbesaidthatthisislongtoowaytoo-" +
"oopsitcouldbesaidthatthisislongtoowaytoo-oops12' has too many characters. " +
"Schedule name length must be 255 characters or less");
Resource resource = new FileSystemResource("src/test/resources/demo-0.0.1-SNAPSHOT.jar");
mockAppResultsInAppList();
AppDefinition definition = new AppDefinition("test-application-1", null);
Map cronMap = new HashMap<String, String>();
cronMap.put(CRON_EXPRESSION, DEFAULT_CRON_EXPRESSION);
ScheduleRequest request = new ScheduleRequest(definition, cronMap, null,
"j1-scdf-itcouldbesaidthatthisislongtoowaytoo-oopsitcouldbesaidthatthisis" +
"longtoowaytoo-oopsitcouldbesaidthatthisislongtoowaytoo-oopsitcouldbe" +
"saidthatthisislongtoowaytoo-oopsitcouldbesaidthatthisislongtoowaytoo-" +
"oopsitcouldbesaidthatthisislongtoowaytoo-oops12", resource);
this.cloudFoundryAppScheduler.schedule(request);
assertThat(((TestJobs) this.client.jobs()).getCreateJobResponse()).isNull();
}
@Test
public void testFileUploadArrayWithoutAnnotation() {
Map<String, Object> map = new HashMap<>();
FileSystemResource[] array1 = {fileSystemResource1, fileSystemResource2};
FileSystemResource[] array2 = {fileSystemResource3, fileSystemResource4};
map.put("file1", array1);
map.put("file2", array2);
map.put("name", message);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
String result = consumersSpringmvc.getSCBRestTemplate()
.postForObject("/uploadArrayWithoutAnnotation", new HttpEntity<>(map, headers), String.class);
Assert.assertTrue(containsAll(result, "hello1", "cse4", "cse3", "中文 2", message));
}
@Test(expected = IOException.class)
public void freeMarkerConfigurationFactoryBeanWithConfigLocation() throws Exception {
FreeMarkerConfigurationFactoryBean fcfb = new FreeMarkerConfigurationFactoryBean();
fcfb.setConfigLocation(new FileSystemResource("myprops.properties"));
Properties props = new Properties();
props.setProperty("myprop", "/mydir");
fcfb.setFreemarkerSettings(props);
fcfb.afterPropertiesSet();
}
@Before
public void setUp() throws Exception {
this.deploymentProperties = new HashMap<>();
this.deploymentRequest = new AppDeploymentRequest(new AppDefinition("foo", Collections.emptyMap()), new FileSystemResource(""), deploymentProperties);
this.kubernetesDeployerProperties = new KubernetesDeployerProperties();
this.deploymentPropertiesResolver = new DeploymentPropertiesResolver(
KubernetesDeployerProperties.KUBERNETES_DEPLOYER_PROPERTIES_PREFIX, this.kubernetesDeployerProperties);
}