Java Code Examples for org.springframework.util.FileCopyUtils#copy()

The following examples show how to use org.springframework.util.FileCopyUtils#copy() . 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: ShallowEtagHeaderFilterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test  // SPR-12960
public void filterWriterWithDisabledCaching() throws Exception {
	final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels");
	MockHttpServletResponse response = new MockHttpServletResponse();

	final byte[] responseBody = "Hello World".getBytes("UTF-8");
	FilterChain filterChain = (filterRequest, filterResponse) -> {
		assertEquals("Invalid request passed", request, filterRequest);
		((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK);
		FileCopyUtils.copy(responseBody, filterResponse.getOutputStream());
	};

	ShallowEtagHeaderFilter.disableContentCaching(request);
	this.filter.doFilter(request, response, filterChain);

	assertEquals(200, response.getStatus());
	assertNull(response.getHeader("ETag"));
	assertArrayEquals(responseBody, response.getContentAsByteArray());
}
 
Example 2
Source File: ShallowEtagHeaderFilterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void filterSendRedirect() throws Exception {
	final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels");
	MockHttpServletResponse response = new MockHttpServletResponse();

	final byte[] responseBody = "Hello World".getBytes("UTF-8");
	FilterChain filterChain = (filterRequest, filterResponse) -> {
		assertEquals("Invalid request passed", request, filterRequest);
		response.setContentLength(100);
		FileCopyUtils.copy(responseBody, filterResponse.getOutputStream());
		((HttpServletResponse) filterResponse).sendRedirect("http://www.google.com");
	};
	filter.doFilter(request, response, filterChain);

	assertEquals("Invalid status", 302, response.getStatus());
	assertNull("Invalid ETag header", response.getHeader("ETag"));
	assertEquals("Invalid Content-Length header", 100, response.getContentLength());
	assertArrayEquals("Invalid content", responseBody, response.getContentAsByteArray());
	assertEquals("Invalid redirect URL", "http://www.google.com", response.getRedirectedUrl());
}
 
Example 3
Source File: TemporaryLobCreator.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public void setBlobAsBinaryStream(
		PreparedStatement ps, int paramIndex, @Nullable InputStream binaryStream, int contentLength)
		throws SQLException {

	if (binaryStream != null) {
		Blob blob = ps.getConnection().createBlob();
		try {
			FileCopyUtils.copy(binaryStream, blob.setBinaryStream(1));
		}
		catch (IOException ex) {
			throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex);
		}
		this.temporaryBlobs.add(blob);
		ps.setBlob(paramIndex, blob);
	}
	else {
		ps.setBlob(paramIndex, (Blob) null);
	}

	if (logger.isDebugEnabled()) {
		logger.debug(binaryStream != null ?
				"Copied binary stream into temporary BLOB with length " + contentLength :
				"Set BLOB to null");
	}
}
 
Example 4
Source File: AbstractAsyncHttpRequestFactoryTestCase.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void headersAfterExecute() throws Exception {
	AsyncClientHttpRequest request = this.factory.createAsyncRequest(new URI(baseUrl + "/echo"), HttpMethod.POST);
	request.getHeaders().add("MyHeader", "value");
	byte[] body = "Hello World".getBytes("UTF-8");
	FileCopyUtils.copy(body, request.getBody());

	Future<ClientHttpResponse> futureResponse = request.executeAsync();
	ClientHttpResponse response = futureResponse.get();
	try {
		request.getHeaders().add("MyHeader", "value");
		fail("UnsupportedOperationException expected");
	}
	catch (UnsupportedOperationException ex) {
		// expected
	}
	finally {
		response.close();
	}
}
 
Example 5
Source File: AbstractHttpRequestFactoryTestCase.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void multipleWrites() throws Exception {
	ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.POST);

	final byte[] body = "Hello World".getBytes("UTF-8");
	if (request instanceof StreamingHttpOutputMessage) {
		StreamingHttpOutputMessage streamingRequest = (StreamingHttpOutputMessage) request;
		streamingRequest.setBody(outputStream -> {
			StreamUtils.copy(body, outputStream);
			outputStream.flush();
			outputStream.close();
		});
	}
	else {
		StreamUtils.copy(body, request.getBody());
	}

	request.execute();
	FileCopyUtils.copy(body, request.getBody());
}
 
Example 6
Source File: ShallowEtagHeaderFilterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void filterWriter() throws Exception {
	final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels");
	String etag = "\"0b10a8db164e0754105b7a99be72e3fe5\"";
	request.addHeader("If-None-Match", etag);
	MockHttpServletResponse response = new MockHttpServletResponse();

	FilterChain filterChain = (filterRequest, filterResponse) -> {
		assertEquals("Invalid request passed", request, filterRequest);
		((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK);
		String responseBody = "Hello World";
		FileCopyUtils.copy(responseBody, filterResponse.getWriter());
	};
	filter.doFilter(request, response, filterChain);

	assertEquals("Invalid status", 304, response.getStatus());
	assertEquals("Invalid ETag header", "\"0b10a8db164e0754105b7a99be72e3fe5\"", response.getHeader("ETag"));
	assertFalse("Response has Content-Length header", response.containsHeader("Content-Length"));
	assertArrayEquals("Invalid content", new byte[0], response.getContentAsByteArray());
}
 
Example 7
Source File: ShallowEtagHeaderFilterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void filterSendError() throws Exception {
	final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels");
	MockHttpServletResponse response = new MockHttpServletResponse();

	final byte[] responseBody = "Hello World".getBytes("UTF-8");
	FilterChain filterChain = (filterRequest, filterResponse) -> {
		assertEquals("Invalid request passed", request, filterRequest);
		response.setContentLength(100);
		FileCopyUtils.copy(responseBody, filterResponse.getOutputStream());
		((HttpServletResponse) filterResponse).sendError(HttpServletResponse.SC_FORBIDDEN);
	};
	filter.doFilter(request, response, filterChain);

	assertEquals("Invalid status", 403, response.getStatus());
	assertNull("Invalid ETag header", response.getHeader("ETag"));
	assertEquals("Invalid Content-Length header", 100, response.getContentLength());
	assertArrayEquals("Invalid content", responseBody, response.getContentAsByteArray());
}
 
Example 8
Source File: ShallowEtagHeaderFilterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void filterFlushResponse() throws Exception {
	final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels");
	MockHttpServletResponse response = new MockHttpServletResponse();

	final byte[] responseBody = "Hello World".getBytes("UTF-8");
	FilterChain filterChain = (filterRequest, filterResponse) -> {
		assertEquals("Invalid request passed", request, filterRequest);
		((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK);
		FileCopyUtils.copy(responseBody, filterResponse.getOutputStream());
		filterResponse.flushBuffer();
	};
	filter.doFilter(request, response, filterChain);

	assertEquals("Invalid status", 200, response.getStatus());
	assertEquals("Invalid ETag header", "\"0b10a8db164e0754105b7a99be72e3fe5\"", response.getHeader("ETag"));
	assertTrue("Invalid Content-Length header", response.getContentLength() > 0);
	assertArrayEquals("Invalid content", responseBody, response.getContentAsByteArray());
}
 
Example 9
Source File: ShallowEtagHeaderFilterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void filterNoMatch() throws Exception {
	final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels");
	MockHttpServletResponse response = new MockHttpServletResponse();

	final byte[] responseBody = "Hello World".getBytes("UTF-8");
	FilterChain filterChain = (filterRequest, filterResponse) -> {
		assertEquals("Invalid request passed", request, filterRequest);
		((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK);
		FileCopyUtils.copy(responseBody, filterResponse.getOutputStream());
	};
	filter.doFilter(request, response, filterChain);

	assertEquals("Invalid status", 200, response.getStatus());
	assertEquals("Invalid ETag header", "\"0b10a8db164e0754105b7a99be72e3fe5\"", response.getHeader("ETag"));
	assertTrue("Invalid Content-Length header", response.getContentLength() > 0);
	assertArrayEquals("Invalid content", responseBody, response.getContentAsByteArray());
}
 
Example 10
Source File: ExcelController.java    From jframework with Apache License 2.0 5 votes vote down vote up
@GetMapping("/export1")
public void exportCsv(HttpServletResponse response, HttpServletRequest request) throws IOException {
    // csv文件名字,为了方便默认给个名字,当然名字可以自定义,看实际需求了
    String fileName = "csv文件.csv";
    // 解决不同浏览器出现的乱码
    fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
    response.setContentType(MediaType.APPLICATION_OCTET_STREAM.toString());
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"; filename*=utf-8''" + fileName);
    FileCopyUtils.copy(genCsvUserDto(), response.getOutputStream());
}
 
Example 11
Source File: EncodedResourceResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
static void createGzippedFile(String filePath) throws IOException {
	Resource location = new ClassPathResource("test/", EncodedResourceResolverTests.class);
	Resource resource = new FileSystemResource(location.createRelative(filePath).getFile());

	Path gzFilePath = Paths.get(resource.getFile().getAbsolutePath() + ".gz");
	Files.deleteIfExists(gzFilePath);

	File gzFile = Files.createFile(gzFilePath).toFile();
	GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(gzFile));
	FileCopyUtils.copy(resource.getInputStream(), out);
	gzFile.deleteOnExit();
}
 
Example 12
Source File: TenantController.java    From youkefu with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/save")
  @Menu(type = "apps" , subtype = "tenant")
  public ModelAndView save(HttpServletRequest request ,@Valid Tenant tenant, @RequestParam(value = "tenantpic", required = false) MultipartFile tenantpic,@Valid String skills) throws NoSuchAlgorithmException, IOException {
  	Tenant tenanttemp = tenantRes.findByOrgidAndTenantname(super.getOrgid(request),tenant.getTenantname());
  	if(tenanttemp!=null) {
  		return request(super.createRequestPageTempletResponse("redirect:/apps/tenant/index.html?msg=tenantexist"));
  	}
  	tenantRes.save(tenant) ;
  	if(tenantpic!=null && tenantpic.getOriginalFilename().lastIndexOf(".") > 0){
  		File logoDir = new File(path , "tenantpic");
  		if(!logoDir.exists()){
  			logoDir.mkdirs() ;
  		}
  		String fileName = "tenantpic/"+tenant.getId()+tenantpic.getOriginalFilename().substring(tenantpic.getOriginalFilename().lastIndexOf(".")) ;
  		FileCopyUtils.copy(tenantpic.getBytes(), new File(path , fileName));
  		tenant.setTenantlogo(fileName);
  	}
  	String tenantid = tenant.getId();
  	List<OrgiSkillRel>  orgiSkillRelList = orgiSkillRelRes.findByOrgi(tenantid) ;
  	orgiSkillRelRes.delete(orgiSkillRelList);
  	if(!StringUtils.isBlank(skills)){
  		String[] skillsarray = skills.split(",") ;
  		for(String skill : skillsarray){
  			OrgiSkillRel rel = new OrgiSkillRel();
  			rel.setOrgi(tenant.getId());
  			rel.setSkillid(skill);
  			rel.setCreater(super.getUser(request).getId());
  			rel.setCreatetime(new Date());
  			orgiSkillRelRes.save(rel) ;
  		}
  	}
  	if(!StringUtils.isBlank(super.getUser(request).getOrgid())) {
  		tenant.setOrgid(super.getUser(request).getOrgid());
}else {
	tenant.setOrgid(UKDataContext.SYSTEM_ORGI);
}
  	tenantRes.save(tenant) ;
  	OnlineUserUtils.clean(tenantid);
  	return request(super.createRequestPageTempletResponse("redirect:/apps/tenant/index"));
  }
 
Example 13
Source File: StandardMultipartHttpServletRequest.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void transferTo(File dest) throws IOException, IllegalStateException {
	this.part.write(dest.getPath());
	if (dest.isAbsolute() && !dest.exists()) {
		// Servlet 3.0 Part.write is not guaranteed to support absolute file paths:
		// may translate the given path to a relative location within a temp dir
		// (e.g. on Jetty whereas Tomcat and Undertow detect absolute paths).
		// At least we offloaded the file from memory storage; it'll get deleted
		// from the temp dir eventually in any case. And for our user's purposes,
		// we can manually copy it to the requested location as a fallback.
		FileCopyUtils.copy(this.part.getInputStream(), Files.newOutputStream(dest.toPath()));
	}
}
 
Example 14
Source File: EncodedResourceResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
static void createGzippedFile(String filePath) throws IOException {
	Resource location = new ClassPathResource("test/", EncodedResourceResolverTests.class);
	Resource resource = new FileSystemResource(location.createRelative(filePath).getFile());

	Path gzFilePath = Paths.get(resource.getFile().getAbsolutePath() + ".gz");
	Files.deleteIfExists(gzFilePath);

	File gzFile = Files.createFile(gzFilePath).toFile();
	GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(gzFile));
	FileCopyUtils.copy(resource.getInputStream(), out);
	gzFile.deleteOnExit();
}
 
Example 15
Source File: PathResourceTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void doesNotExistOutputStream() throws IOException {
	File file = temporaryFolder.newFile("test");
	file.delete();
	PathResource resource = new PathResource(file.toPath());
	FileCopyUtils.copy("test".getBytes(), resource.getOutputStream());
	assertThat(resource.contentLength(), equalTo(4L));
}
 
Example 16
Source File: ServletServerHttpResponseTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void getBody() throws Exception {
	byte[] content = "Hello World".getBytes("UTF-8");
	FileCopyUtils.copy(content, response.getBody());

	assertArrayEquals("Invalid content written", content, mockResponse.getContentAsByteArray());
}
 
Example 17
Source File: CallCenterMediaController.java    From youkefu with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/media/update")
  @Menu(type = "callcenter" , subtype = "media" , access = false , admin = true)
  public ModelAndView pbxhostupdate(ModelMap map , HttpServletRequest request , @RequestParam(value = "mediafile", required = false) MultipartFile mediafile) throws IOException {
Media media = new Media();
media.setName(request.getParameter("name"));
media.setHostid(request.getParameter("hostid"));
media.setId(request.getParameter("id"));
if(!StringUtils.isBlank(media.getId())){
	Media oldMedia = mediaRes.findByIdAndOrgi(media.getId(), super.getOrgi(request)) ;
	if(oldMedia!=null){
		if(mediafile!=null && mediafile.getSize() > 0){
			File wavFile = new File(path , oldMedia.getFilename());
    		if(!wavFile.exists()){
    			wavFile.deleteOnExit();
    		}
			
			String fileName = "media/"+media.getId()+mediafile.getOriginalFilename().substring(mediafile.getOriginalFilename().lastIndexOf(".")) ;
			oldMedia.setFilename(fileName);
			
			if(mediafile!=null && mediafile.getOriginalFilename().lastIndexOf(".") > 0){
	    		File mediaDir = new File(path , "media");
	    		if(!mediaDir.exists()){
	    			mediaDir.mkdirs() ;
	    		}
	    		FileCopyUtils.copy(mediafile.getBytes(), new File(path , fileName));
	    	}
		}
		oldMedia.setName(media.getName());
		mediaRes.save(oldMedia);
	}
}
return request(super.createRequestPageTempletResponse("redirect:/admin/callcenter/media.html?hostid="+media.getHostid()));
  }
 
Example 18
Source File: CallCenterMediaController.java    From youkefu with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/media/save")
  @Menu(type = "callcenter" , subtype = "media" , access = false , admin = true)
  public ModelAndView mediasave(ModelMap map , HttpServletRequest request , @RequestParam(value = "mediafile", required = false) MultipartFile mediafile) throws IOException {
Media media = new Media();
media.setName(request.getParameter("name"));
media.setHostid(request.getParameter("hostid"));
if(!StringUtils.isBlank(media.getName())){
	int count = mediaRes.countByNameAndOrgi(media.getName(), super.getOrgi(request)) ;
	if(count == 0){
		String fileName = "media/"+media.getId()+ mediafile.getOriginalFilename().substring(mediafile.getOriginalFilename().lastIndexOf(".")) ;
		
		media.setOrgi(super.getOrgi(request));
		media.setCreater(super.getUser(request).getId());
		media.setFilelength((int) mediafile.getSize());
		media.setContent(mediafile.getContentType());
		media.setFilename(fileName);
		
		if(mediafile!=null && mediafile.getOriginalFilename().lastIndexOf(".") > 0){
    		File logoDir = new File(path , "media");
    		if(!logoDir.exists()){
    			logoDir.mkdirs() ;
    		}
    		FileCopyUtils.copy(mediafile.getBytes(), new File(path , fileName));
    	}
		
		mediaRes.save(media) ;
	}
}
return request(super.createRequestPageTempletResponse("redirect:/admin/callcenter/media.html?hostid="+media.getHostid()));
  }
 
Example 19
Source File: IMAgentController.java    From youkefu with Apache License 2.0 4 votes vote down vote up
@RequestMapping("/agent/sessionconfig/save")
  @Menu(type = "setting" , subtype = "sessionconfig" , admin= false)
  public ModelAndView sessionconfig(ModelMap map , HttpServletRequest request , @Valid SessionConfig sessionConfig,BindingResult result,  @RequestParam(value = "tipagenticon", required = false) MultipartFile tipagenticon) throws IOException{
  	SessionConfig tempSessionConfig = sessionConfigRes.findByOrgi(super.getOrgi(request)) ;
  	if(tempSessionConfig == null){
  		tempSessionConfig = sessionConfig;
  		tempSessionConfig.setCreater(super.getUser(request).getId());
  	}else{
  		UKTools.copyProperties(sessionConfig, tempSessionConfig);
  	}
  	if(sessionConfig.getWorkinghours() != null){
  		List<SessionConfigItem> sessionConfigList = new ArrayList<SessionConfigItem>();
  		String[] wk = sessionConfig.getWorkinghours().split(",");
  		for(String worktime : wk){
  			SessionConfigItem session = new SessionConfigItem();
  			String[] items = worktime.split(":", 3) ;
  			session.setType(items[0]);
  			session.setWorktype(items[1]);
  			session.setWorkinghours(items[2]);
  			sessionConfigList.add(session);
  		}
  		tempSessionConfig.setWorkinghours(objectMapper.writeValueAsString(sessionConfigList));
  	}else{
  		tempSessionConfig.setWorkinghours(null);
  	}
  	
  	tempSessionConfig.setOrgi(super.getOrgi(request));
  	
  	if(tipagenticon!=null && !StringUtils.isBlank(tipagenticon.getName()) && tipagenticon.getBytes()!=null && tipagenticon.getBytes().length >0){
	String fileName = "logo/"+UKTools.md5("tipagenticon_"+tempSessionConfig.getOrgi())+tipagenticon.getOriginalFilename().substring(tipagenticon.getOriginalFilename().lastIndexOf(".")) ;
	File file = new File(path , fileName) ;
	if(!file.getParentFile().exists()){
		file.getParentFile().mkdirs();
	}
  		FileCopyUtils.copy(tipagenticon.getBytes(), file);
  		tempSessionConfig.setTipagenticon(fileName);
}
  	sessionConfigRes.save(tempSessionConfig) ;
  	
  	CacheHelper.getSystemCacheBean().put(UKDataContext.SYSTEM_CACHE_SESSION_CONFIG+"_"+super.getOrgi(request),tempSessionConfig, super.getOrgi(request)) ;
  	
  	CacheHelper.getSystemCacheBean().delete(UKDataContext.SYSTEM_CACHE_SESSION_CONFIG_LIST , UKDataContext.SYSTEM_ORGI) ;
  	
  	ServiceQuene.initSessionConfigList() ;
  	map.put("sessionConfig", tempSessionConfig) ;
  	
  	
      return request(super.createRequestPageTempletResponse("redirect:/setting/agent/index.html"));
  }
 
Example 20
Source File: PathResourceTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Test
public void outputStream() throws IOException {
	PathResource resource = new PathResource(temporaryFolder.newFile("test").toPath());
	FileCopyUtils.copy("test".getBytes(StandardCharsets.UTF_8), resource.getOutputStream());
	assertThat(resource.contentLength(), equalTo(4L));
}