org.springframework.core.io.FileSystemResource Java Examples
The following examples show how to use
org.springframework.core.io.FileSystemResource.
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: EmailServiceImpl.java From tutorials with MIT License | 8 votes |
@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(); } }
Example #2
Source File: MailService.java From SpringBoot-Course with MIT License | 7 votes |
/** * 发送带附件的邮件 * @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); }
Example #3
Source File: PropertiesConfiguration.java From gravitee-management-rest-api with Apache License 2.0 | 7 votes |
@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; }
Example #4
Source File: ServerClient.java From agent with MIT License | 7 votes |
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()); } }
Example #5
Source File: CloudFoundryAppDeployerTest.java From spring-cloud-app-broker with Apache License 2.0 | 6 votes |
@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); }
Example #6
Source File: ThemeFingerprintRegistryTest.java From molgenis with GNU Lesser General Public License v3.0 | 6 votes |
@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); }
Example #7
Source File: CapitalizeNamesJobConfig.java From spring-batch with MIT License | 6 votes |
@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; }
Example #8
Source File: WxVideoMessageProcessor.java From FastBootWeixin with Apache License 2.0 | 6 votes |
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; }
Example #9
Source File: AddressImportJobConfiguration.java From spring-batch-lightmin with Apache License 2.0 | 6 votes |
@Bean @JobScope public FlatFileItemReader<BatchTaskAddress> fileItemReader(@Value("#{jobParameters['fileSource']}") final String pathToFile, final LineMapper<BatchTaskAddress> lineMapper) throws Exception { final FlatFileItemReader<BatchTaskAddress> reader = new FlatFileItemReader<>(); reader.setEncoding("utf-8"); reader.setLineMapper(lineMapper); reader.setLinesToSkip(1); reader.setResource(new FileSystemResource(pathToFile)); reader.afterPropertiesSet(); return reader; }
Example #10
Source File: TestUpload.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@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)); }
Example #11
Source File: HostServiceImpl.java From super-cloudops with Apache License 2.0 | 6 votes |
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)); }
Example #12
Source File: BaseController.java From xmanager with Apache License 2.0 | 6 votes |
/** * 下载 * @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); }
Example #13
Source File: TlsNioConfigTest.java From cougar with Apache License 2.0 | 6 votes |
@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(); } }
Example #14
Source File: EmailServiceImpl.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
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; }
Example #15
Source File: EmailController.java From SpringAll with MIT License | 6 votes |
@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(); } }
Example #16
Source File: BaseController.java From xmanager with Apache License 2.0 | 6 votes |
/** * 下载 * @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); }
Example #17
Source File: TlsNioConfigTest.java From cougar with Apache License 2.0 | 6 votes |
@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(); } }
Example #18
Source File: JavaMailUtils.java From seppb with MIT License | 6 votes |
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); } }
Example #19
Source File: ReloadingDataDictionary.java From rice with Educational Community License v2.0 | 6 votes |
/** * 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); } }
Example #20
Source File: CloudFoundryAppSchedulerTests.java From spring-cloud-deployer-cloudfoundry with Apache License 2.0 | 6 votes |
@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(); }
Example #21
Source File: MailServiceImpl.java From spring-boot-demo with MIT License | 6 votes |
/** * 发送正文中有静态资源的邮件 * * @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); }
Example #22
Source File: CRLDistributionPointRevocationCheckerTests.java From springboot-shiro-cas-mybatis with MIT License | 6 votes |
/** * 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); }
Example #23
Source File: SpringMvcIntegrationTestBase.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
@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()); } }
Example #24
Source File: ClassPathXmlApplicationContextTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void testResourceArrayPropertyEditor() throws IOException { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(CONTEXT_WILDCARD); Service service = (Service) ctx.getBean("service"); assertEquals(3, service.getResources().length); List<Resource> resources = Arrays.asList(service.getResources()); assertTrue(resources.contains(new FileSystemResource(new ClassPathResource(FQ_CONTEXT_A).getFile()))); assertTrue(resources.contains(new FileSystemResource(new ClassPathResource(FQ_CONTEXT_B).getFile()))); assertTrue(resources.contains(new FileSystemResource(new ClassPathResource(FQ_CONTEXT_C).getFile()))); ctx.close(); }
Example #25
Source File: CollectionToCollectionConverterTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void differentImpls() throws Exception { List<Resource> resources = new ArrayList<Resource>(); resources.add(new ClassPathResource("test")); resources.add(new FileSystemResource("test")); resources.add(new TestResource()); TypeDescriptor sourceType = TypeDescriptor.forObject(resources); assertSame(resources, conversionService.convert(resources, sourceType, new TypeDescriptor(getClass().getField("resources")))); }
Example #26
Source File: HttpsClientConfiguration.java From pulsar-manager with Apache License 2.0 | 5 votes |
@Bean public CloseableHttpClient httpClient() throws Exception { if (tlsEnabled) { Resource resource = new FileSystemResource(tlsKeystore); File trustStoreFile = resource.getFile(); SSLContext sslcontext = SSLContexts.custom() .loadTrustMaterial(trustStoreFile, tlsKeystorePassword.toCharArray(), new TrustSelfSignedStrategy()) .build(); HostnameVerifier hostnameVerifier = (s, sslSession) -> { // Custom logic to verify host name, tlsHostnameVerifier is false for test if (!tlsHostnameVerifier) { return true; } else { HostnameVerifier hv= HttpsURLConnection.getDefaultHostnameVerifier(); return hv.verify(s, sslSession); } }; SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslcontext, hostnameVerifier); return HttpClients.custom() .setSSLSocketFactory(sslsf) .build(); } return HttpClients.custom().build(); }
Example #27
Source File: FlatFileItemWriterAutoConfigurationTests.java From spring-cloud-task with Apache License 2.0 | 5 votes |
@Test public void testCustomLineAggregatorFileGeneration() { ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() .withUserConfiguration(LineAggregatorConfiguration.class) .withConfiguration( AutoConfigurations.of(PropertyPlaceholderAutoConfiguration.class, BatchAutoConfiguration.class, SingleStepJobAutoConfiguration.class, FlatFileItemWriterAutoConfiguration.class)) .withPropertyValues("spring.batch.job.jobName=job", "spring.batch.job.stepName=step1", "spring.batch.job.chunkSize=5", "spring.batch.job.flatfilewriter.name=fooWriter", String.format( "spring.batch.job.flatfilewriter.resource=file://%s", this.outputFile.getAbsolutePath()), "spring.batch.job.flatfilewriter.encoding=UTF-8"); applicationContextRunner.run((context) -> { JobLauncher jobLauncher = context.getBean(JobLauncher.class); Job job = context.getBean(Job.class); JobExecution jobExecution = jobLauncher.run(job, new JobParameters()); JobExplorer jobExplorer = context.getBean(JobExplorer.class); while (jobExplorer.getJobExecution(jobExecution.getJobId()).isRunning()) { Thread.sleep(1000); } AssertFile.assertLineCount(3, this.outputFile); String results = FileCopyUtils.copyToString(new InputStreamReader( new FileSystemResource(this.outputFile).getInputStream())); assertThat(results).isEqualTo("{item=foo}\n{item=bar}\n{item=baz}\n"); }); }
Example #28
Source File: PersonPhotoRestController.java From building-microservices with Apache License 2.0 | 5 votes |
@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); }
Example #29
Source File: PetApi.java From openapi-generator with Apache License 2.0 | 5 votes |
/** * uploads an image * * <p><b>200</b> - successful operation * @param petId ID of pet to update * @param additionalMetadata Additional data to pass to server * @param file file to upload * @return ModelApiResponse * @throws WebClientResponseException if an error occurs while attempting to invoke the API */ public Mono<ModelApiResponse> uploadFile(Long petId, String additionalMetadata, File file) throws WebClientResponseException { Object postBody = null; // verify the required parameter 'petId' is set if (petId == null) { throw new WebClientResponseException("Missing the required parameter 'petId' when calling uploadFile", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); } // create path and map variables final Map<String, Object> pathParams = new HashMap<String, Object>(); pathParams.put("petId", petId); final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>(); final HttpHeaders headerParams = new HttpHeaders(); final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>(); final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>(); if (additionalMetadata != null) formParams.add("additionalMetadata", additionalMetadata); if (file != null) formParams.add("file", new FileSystemResource(file)); final String[] localVarAccepts = { "application/json" }; final List<MediaType> localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] localVarContentTypes = { "multipart/form-data" }; final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); String[] localVarAuthNames = new String[] { "petstore_auth" }; ParameterizedTypeReference<ModelApiResponse> localVarReturnType = new ParameterizedTypeReference<ModelApiResponse>() {}; return apiClient.invokeAPI("/pet/{petId}/uploadImage", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); }
Example #30
Source File: BeanDefinitionWriterServiceTest.java From geomajas-project-server with GNU Affero General Public License v3.0 | 5 votes |
@Test public void testWriteAndBack() throws NoSuchBeanDefinitionException, RuntimeConfigException, IllegalStateException, IOException { BeanDefinitionWriterServiceImpl service = new BeanDefinitionWriterServiceImpl(); String basePath = File.createTempFile("tmp", "tmp").getParentFile().getAbsolutePath() + File.separator; service.setBaseResource(new FileSystemResource(basePath)); List<BeanDefinitionHolder> beans = new ArrayList<BeanDefinitionHolder>(); beans.add(new BeanDefinitionHolder(context.getBeanFactory().getBeanDefinition("beanA"), "beanA")); beans.add(new BeanDefinitionHolder(context.getBeanFactory().getBeanDefinition("beanB"), "beanB")); service.persist("test", beans); GenericXmlApplicationContext generic = new GenericXmlApplicationContext(service.getBaseResource().createRelative("test.xml")); Assert.assertEquals(context.getBean("beanA"), generic.getBean("beanA")); Assert.assertEquals(context.getBean("beanB"), generic.getBean("beanB")); }