Java Code Examples for org.springframework.core.io.FileSystemResource

The following examples show how to use org.springframework.core.io.FileSystemResource. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: tutorials   Source File: EmailServiceImpl.java    License: MIT License 7 votes vote down vote up
@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 Project: agent   Source File: ServerClient.java    License: MIT License 7 votes vote down vote up
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 3
Source Project: SpringBoot-Course   Source File: MailService.java    License: MIT License 6 votes vote down vote up
/**
 * 发送带附件的邮件
 * @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 4
@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 5
Source Project: super-cloudops   Source File: HostServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
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 6
Source Project: spring-batch   Source File: CapitalizeNamesJobConfig.java    License: MIT License 6 votes vote down vote up
@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 7
@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 8
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 9
Source Project: cougar   Source File: TlsNioConfigTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 10
Source Project: seppb   Source File: JavaMailUtils.java    License: MIT License 6 votes vote down vote up
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 11
@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 12
Source Project: spring-boot-demo   Source File: MailServiceImpl.java    License: MIT License 6 votes vote down vote up
/**
 * 发送正文中有静态资源的邮件
 *
 * @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 13
/**
 * 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 14
Source Project: cougar   Source File: TlsNioConfigTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 15
@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 16
/**
 * 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 17
@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 18
Source Project: xmanager   Source File: BaseController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 下载
 * @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 19
Source Project: SpringAll   Source File: EmailController.java    License: MIT License 6 votes vote down vote up
@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 20
Source Project: FastBootWeixin   Source File: WxVideoMessageProcessor.java    License: Apache License 2.0 6 votes vote down vote up
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 21
@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 22
Source Project: servicecomb-java-chassis   Source File: TestUpload.java    License: Apache License 2.0 6 votes vote down vote up
@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 23
Source Project: xmanager   Source File: BaseController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 下载
 * @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 24
@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 25
Source Project: spring-vault   Source File: Settings.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @return the vault properties.
 */
public static SslConfiguration createSslConfiguration() {

	File workDir = findWorkDir();

	return SslConfiguration.forTrustStore(new FileSystemResource(new File(workDir, "keystore.jks")),
			"changeit".toCharArray());
}
 
Example 26
Source Project: servicecomb-java-chassis   Source File: TestUpload.java    License: Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example 27
Source Project: rice   Source File: LocationXmlDoc.java    License: Educational Community License v2.0 5 votes vote down vote up
static Resource getResource(String location) {
    if (isExistingFile(location)) {
        return new FileSystemResource(location);
    } else {
        ResourceLoader loader = new DefaultResourceLoader();
        return loader.getResource(location);
    }
}
 
Example 28
@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();
}
 
Example 29
Source Project: servicecomb-java-chassis   Source File: TestUpload.java    License: Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example 30
@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();
}