org.springframework.util.FileCopyUtils Java Examples

The following examples show how to use org.springframework.util.FileCopyUtils. 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: SimpleBufferingClientHttpRequest.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] bufferedOutput) throws IOException {
	addHeaders(this.connection, headers);
	// JDK <1.8 doesn't support getOutputStream with HTTP DELETE
	if (getMethod() == HttpMethod.DELETE && bufferedOutput.length == 0) {
		this.connection.setDoOutput(false);
	}
	if (this.connection.getDoOutput() && this.outputStreaming) {
		this.connection.setFixedLengthStreamingMode(bufferedOutput.length);
	}
	this.connection.connect();
	if (this.connection.getDoOutput()) {
		FileCopyUtils.copy(bufferedOutput, this.connection.getOutputStream());
	}
	else {
		// Immediately trigger the request in a no-output scenario as well
		this.connection.getResponseCode();
	}
	return new SimpleClientHttpResponse(this.connection);
}
 
Example #2
Source File: AbstractHttpRequestFactoryTestCase.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test(expected = UnsupportedOperationException.class)
public void headersAfterExecute() throws Exception {
	ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/status/ok"), HttpMethod.POST);

	request.getHeaders().add("MyHeader", "value");
	byte[] body = "Hello World".getBytes("UTF-8");
	FileCopyUtils.copy(body, request.getBody());

	ClientHttpResponse response = request.execute();
	try {
		request.getHeaders().add("MyHeader", "value");
	}
	finally {
		response.close();
	}
}
 
Example #3
Source File: AppCacheManifestTransformerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void transformManifest() throws Exception {
	MockServerWebExchange exchange = MockServerWebExchange.from(get("/static/test.appcache"));
	Resource resource = getResource("test.appcache");
	Resource actual = this.transformer.transform(exchange, resource, this.chain).block(TIMEOUT);

	assertNotNull(actual);
	byte[] bytes = FileCopyUtils.copyToByteArray(actual.getInputStream());
	String content = new String(bytes, "UTF-8");

	assertThat("should rewrite resource links", content,
			containsString("/static/foo-e36d2e05253c6c7085a91522ce43a0b4.css"));
	assertThat("should rewrite resource links", content,
			containsString("/static/bar-11e16cf79faee7ac698c805cf28248d2.css"));
	assertThat("should rewrite resource links", content,
			containsString("/static/js/bar-bd508c62235b832d960298ca6c0b7645.js"));

	assertThat("should not rewrite external resources", content, containsString("//example.org/style.css"));
	assertThat("should not rewrite external resources", content, containsString("http://example.org/image.png"));

	// Not the same hash as Spring MVC
	// Hash is computed from links, and not from the linked content

	assertThat("should generate fingerprint", content,
			containsString("# Hash: 8eefc904df3bd46537fa7bdbbc5ab9fb"));
}
 
Example #4
Source File: IMAgentController.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/adv/save")
  @Menu(type = "setting" , subtype = "adv" , admin= false)
  public ModelAndView advsave(ModelMap map , HttpServletRequest request , @Valid AdType adv , @Valid String advtype , @RequestParam(value = "imgfile", required = false) MultipartFile imgfile) throws IOException {
  	adv.setOrgi(super.getOrgi(request));
adv.setCreater(super.getUser(request).getId());
if(!StringUtils.isBlank(adv.getContent())){
	adv.setContent(adv.getContent().replaceAll("\"", "'"));
}
adv.setCreatetime(new Date());
if(imgfile!=null && imgfile.getSize() > 0){
	File adDir = new File(path , "adv");
  		if(!adDir.exists()){
  			adDir.mkdirs() ;
  		}
  		String fileName = "adv/"+UKTools.getUUID()+imgfile.getOriginalFilename().substring(imgfile.getOriginalFilename().lastIndexOf(".")) ;
  		FileCopyUtils.copy(imgfile.getBytes(), new File(path , fileName));
  		adv.setImgurl("/res/image.html?id="+java.net.URLEncoder.encode(fileName , "UTF-8"));
}
adTypeRes.save(adv) ;

UKTools.initAdv(super.getOrgi(request));

      return request(super.createRequestPageTempletResponse("redirect:/setting/adv.html?adpos="+adv.getAdpos()));
  }
 
Example #5
Source File: ShadowingClassLoader.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private Class<?> doLoadClass(String name) throws ClassNotFoundException {
	String internalName = StringUtils.replace(name, ".", "/") + ".class";
	InputStream is = this.enclosingClassLoader.getResourceAsStream(internalName);
	if (is == null) {
		throw new ClassNotFoundException(name);
	}
	try {
		byte[] bytes = FileCopyUtils.copyToByteArray(is);
		bytes = applyTransformers(name, bytes);
		Class<?> cls = defineClass(name, bytes, 0, bytes.length);
		// Additional check for defining the package, if not defined yet.
		if (cls.getPackage() == null) {
			int packageSeparator = name.lastIndexOf('.');
			if (packageSeparator != -1) {
				String packageName = name.substring(0, packageSeparator);
				definePackage(packageName, null, null, null, null, null, null, null);
			}
		}
		this.classCache.put(name, cls);
		return cls;
	}
	catch (IOException ex) {
		throw new ClassNotFoundException("Cannot load resource for class [" + name + "]", ex);
	}
}
 
Example #6
Source File: ContentCachingRequestWrapperTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void cachedContentWithOverflow() throws Exception {
	this.request.setMethod("GET");
	this.request.setCharacterEncoding(CHARSET);
	this.request.setContent("Hello World".getBytes(CHARSET));

	ContentCachingRequestWrapper wrapper = new ContentCachingRequestWrapper(this.request, 3) {
		@Override
		protected void handleContentOverflow(int contentCacheLimit) {
			throw new IllegalStateException(String.valueOf(contentCacheLimit));
		}
	};

	try {
		FileCopyUtils.copyToByteArray(wrapper.getInputStream());
		fail("Should have thrown IllegalStateException");
	}
	catch (IllegalStateException ex) {
		assertEquals("3", ex.getMessage());
	}
}
 
Example #7
Source File: ApplicationContextExpressionTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void resourceInjection() throws IOException {
	System.setProperty("logfile", "do_not_delete_me.txt");
	try (AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(ResourceInjectionBean.class)) {
		ResourceInjectionBean resourceInjectionBean = ac.getBean(ResourceInjectionBean.class);
		Resource resource = new ClassPathResource("do_not_delete_me.txt");
		assertEquals(resource, resourceInjectionBean.resource);
		assertEquals(resource.getURL(), resourceInjectionBean.url);
		assertEquals(resource.getURI(), resourceInjectionBean.uri);
		assertEquals(resource.getFile(), resourceInjectionBean.file);
		assertArrayEquals(FileCopyUtils.copyToByteArray(resource.getInputStream()),
				FileCopyUtils.copyToByteArray(resourceInjectionBean.inputStream));
		assertEquals(FileCopyUtils.copyToString(new EncodedResource(resource).getReader()),
				FileCopyUtils.copyToString(resourceInjectionBean.reader));
	}
	finally {
		System.getProperties().remove("logfile");
	}
}
 
Example #8
Source File: AppCacheManifestTransformerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void transformManifest() throws Exception {
	this.request = new MockHttpServletRequest("GET", "/static/test.appcache");
	Resource resource = getResource("test.appcache");
	Resource actual = this.transformer.transform(this.request, resource, this.chain);

	byte[] bytes = FileCopyUtils.copyToByteArray(actual.getInputStream());
	String content = new String(bytes, "UTF-8");

	assertThat("should rewrite resource links", content,
			containsString("/static/foo-e36d2e05253c6c7085a91522ce43a0b4.css"));
	assertThat("should rewrite resource links", content,
			containsString("/static/bar-11e16cf79faee7ac698c805cf28248d2.css"));
	assertThat("should rewrite resource links", content,
			containsString("/static/js/bar-bd508c62235b832d960298ca6c0b7645.js"));

	assertThat("should not rewrite external resources", content, containsString("//example.org/style.css"));
	assertThat("should not rewrite external resources", content, containsString("http://example.org/image.png"));

	assertThat("should generate fingerprint", content,
			containsString("# Hash: 4bf0338bcbeb0a5b3a4ec9ed8864107d"));
}
 
Example #9
Source File: RequestLoggingFilterTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void payloadMaxLength() throws Exception {
	filter.setIncludePayload(true);
	filter.setMaxPayloadLength(3);

	final MockHttpServletRequest request = new MockHttpServletRequest("POST", "/hotels");
	MockHttpServletResponse response = new MockHttpServletResponse();

	final byte[] requestBody = "Hello World".getBytes(StandardCharsets.UTF_8);
	request.setContent(requestBody);

	FilterChain filterChain = (filterRequest, filterResponse) -> {
		((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK);
		byte[] buf = FileCopyUtils.copyToByteArray(filterRequest.getInputStream());
		assertArrayEquals(requestBody, buf);
		ContentCachingRequestWrapper wrapper =
				WebUtils.getNativeRequest(filterRequest, ContentCachingRequestWrapper.class);
		assertArrayEquals("Hel".getBytes(StandardCharsets.UTF_8), wrapper.getContentAsByteArray());
	};

	filter.doFilter(request, response, filterChain);

	assertNotNull(filter.afterRequestMessage);
	assertTrue(filter.afterRequestMessage.contains("Hel"));
	assertFalse(filter.afterRequestMessage.contains("Hello World"));
}
 
Example #10
Source File: RequestLoggingFilterTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void payloadReader() throws Exception {
	filter.setIncludePayload(true);

	final MockHttpServletRequest request = new MockHttpServletRequest("POST", "/hotels");
	MockHttpServletResponse response = new MockHttpServletResponse();

	final String requestBody = "Hello World";
	request.setContent(requestBody.getBytes(StandardCharsets.UTF_8));

	FilterChain filterChain = (filterRequest, filterResponse) -> {
		((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK);
		String buf = FileCopyUtils.copyToString(filterRequest.getReader());
		assertEquals(requestBody, buf);
	};

	filter.doFilter(request, response, filterChain);

	assertNotNull(filter.afterRequestMessage);
	assertTrue(filter.afterRequestMessage.contains(requestBody));
}
 
Example #11
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 #12
Source File: ShallowEtagHeaderFilterTests.java    From spring-analysis-note 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 #13
Source File: ShallowEtagHeaderFilterTests.java    From spring-analysis-note 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 #14
Source File: ShallowEtagHeaderFilterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void filterSendErrorMessage() 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, "ERROR");
	};
	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());
	assertEquals("Invalid error message", "ERROR", response.getErrorMessage());
}
 
Example #15
Source File: MyProxy.java    From code with Apache License 2.0 6 votes vote down vote up
/**
 * @param proxyClassString 代理类的代码
 * @param myProxyFile 代理类的Java文件
 * @throws IOException
 */
private static void compile(StringBuffer proxyClassString, File myProxyFile) throws IOException {
    // in out
    FileCopyUtils.copy(proxyClassString.toString().getBytes(), myProxyFile);
    // 调用系统编译器
    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();

    StandardJavaFileManager standardJavaFileManager = javaCompiler.getStandardFileManager(null, null, null);

    Iterable javaFileObjects = standardJavaFileManager.getJavaFileObjects(myProxyFile);

    JavaCompiler.CompilationTask task = javaCompiler.getTask(null, standardJavaFileManager, null, null, null, javaFileObjects);

    task.call();

    standardJavaFileManager.close();
}
 
Example #16
Source File: TemporaryLobCreator.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public void setClobAsCharacterStream(
		PreparedStatement ps, int paramIndex, @Nullable Reader characterStream, int contentLength)
		throws SQLException {

	if (characterStream != null) {
		Clob clob = ps.getConnection().createClob();
		try {
			FileCopyUtils.copy(characterStream, clob.setCharacterStream(1));
		}
		catch (IOException ex) {
			throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex);
		}
		this.temporaryClobs.add(clob);
		ps.setClob(paramIndex, clob);
	}
	else {
		ps.setClob(paramIndex, (Clob) null);
	}

	if (logger.isDebugEnabled()) {
		logger.debug(characterStream != null ?
				"Copied character stream into temporary CLOB with length " + contentLength :
				"Set CLOB to null");
	}
}
 
Example #17
Source File: RequestPartServletServerHttpRequestTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void getBodyViaRequestParameterWithRequestEncoding() throws Exception {
	MockMultipartHttpServletRequest mockRequest = new MockMultipartHttpServletRequest() {
		@Override
		public HttpHeaders getMultipartHeaders(String paramOrFileName) {
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			return headers;
		}
	};

	byte[] bytes = {(byte) 0xC4};
	mockRequest.setParameter("part", new String(bytes, StandardCharsets.ISO_8859_1));
	mockRequest.setCharacterEncoding("iso-8859-1");
	ServerHttpRequest request = new RequestPartServletServerHttpRequest(mockRequest, "part");
	byte[] result = FileCopyUtils.copyToByteArray(request.getBody());
	assertArrayEquals(bytes, result);
}
 
Example #18
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 #19
Source File: RequestLoggingFilterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void payloadReader() throws Exception {
	filter.setIncludePayload(true);

	final MockHttpServletRequest request = new MockHttpServletRequest("POST", "/hotels");
	MockHttpServletResponse response = new MockHttpServletResponse();

	final String requestBody = "Hello World";
	request.setContent(requestBody.getBytes("UTF-8"));

	FilterChain filterChain = new FilterChain() {
		@Override
		public void doFilter(ServletRequest filterRequest, ServletResponse filterResponse)
				throws IOException, ServletException {
			((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK);
			String buf = FileCopyUtils.copyToString(filterRequest.getReader());
			assertEquals(requestBody, buf);
		}
	};

	filter.doFilter(request, response, filterChain);

	assertNotNull(filter.afterRequestMessage);
	assertTrue(filter.afterRequestMessage.contains(requestBody));
}
 
Example #20
Source File: PassThroughClob.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public InputStream getAsciiStream() throws SQLException {
	try {
		if (this.content != null) {
			return new ByteArrayInputStream(this.content.getBytes(StandardCharsets.US_ASCII));
		}
		else if (this.characterStream != null) {
			String tempContent = FileCopyUtils.copyToString(this.characterStream);
			return new ByteArrayInputStream(tempContent.getBytes(StandardCharsets.US_ASCII));
		}
		else {
			return (this.asciiStream != null ? this.asciiStream : StreamUtils.emptyInput());
		}
	}
	catch (IOException ex) {
		throw new SQLException("Failed to read stream content: " + ex);
	}
}
 
Example #21
Source File: PassThroughClob.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public InputStream getAsciiStream() throws SQLException {
	try {
		if (this.content != null) {
			return new ByteArrayInputStream(this.content.getBytes(StandardCharsets.US_ASCII));
		}
		else if (this.characterStream != null) {
			String tempContent = FileCopyUtils.copyToString(this.characterStream);
			return new ByteArrayInputStream(tempContent.getBytes(StandardCharsets.US_ASCII));
		}
		else {
			return (this.asciiStream != null ? this.asciiStream : StreamUtils.emptyInput());
		}
	}
	catch (IOException ex) {
		throw new SQLException("Failed to read stream content: " + ex);
	}
}
 
Example #22
Source File: ShallowEtagHeaderFilterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void filterMatch() 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);
		byte[] responseBody = "Hello World".getBytes("UTF-8");
		FileCopyUtils.copy(responseBody, filterResponse.getOutputStream());
		filterResponse.setContentLength(responseBody.length);
	};
	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 #23
Source File: ShallowEtagHeaderFilterTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void filterMatch() 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);
		byte[] responseBody = "Hello World".getBytes("UTF-8");
		FileCopyUtils.copy(responseBody, filterResponse.getOutputStream());
		filterResponse.setContentLength(responseBody.length);
	};
	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 #24
Source File: FileServiceQiNiuYun.java    From smart-admin with MIT License 5 votes vote down vote up
/**
 * 获取文件
 */
public File getFile(String key, String fileName) {
    String finalUrl = getDownloadUrl(key);
    OkHttpClient client = new OkHttpClient();
    Request req = new Request.Builder().url(finalUrl).build();
    okhttp3.Response resp = null;
    File file = new File(fileName);
    try {
        resp = client.newCall(req).execute();
        if (resp.isSuccessful()) {
            ResponseBody body = resp.body();
            InputStream objectContent = body.byteStream();
            // 输入流转换为字节流
            byte[] buffer = FileCopyUtils.copyToByteArray(objectContent);
            // 字节流写入文件
            FileCopyUtils.copy(buffer, file);
            // 关闭输入流
            objectContent.close();
        }

    } catch (IOException e) {
        log.error("文件获取失败:" + e);
        return null;
    } finally {
    }
    return file;
}
 
Example #25
Source File: FreeMarkerMacroTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private String fetchMacro(String name) throws Exception {
	ClassPathResource resource = new ClassPathResource("test.ftl", getClass());
	assertTrue(resource.exists());
	String all = FileCopyUtils.copyToString(new InputStreamReader(resource.getInputStream()));
	all = all.replace("\r\n", "\n");
	String[] macros = StringUtils.delimitedListToStringArray(all, "\n\n");
	for (String macro : macros) {
		if (macro.startsWith(name)) {
			return macro.substring(macro.indexOf("\n")).trim();
		}
	}
	return null;
}
 
Example #26
Source File: AbstractAsyncHttpRequestFactoryTestCase.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void echo() throws Exception {
	AsyncClientHttpRequest request = this.factory.createAsyncRequest(new URI(baseUrl + "/echo"), HttpMethod.PUT);
	assertEquals("Invalid HTTP method", HttpMethod.PUT, request.getMethod());
	String headerName = "MyHeader";
	String headerValue1 = "value1";
	request.getHeaders().add(headerName, headerValue1);
	String headerValue2 = "value2";
	request.getHeaders().add(headerName, headerValue2);
	final byte[] body = "Hello World".getBytes("UTF-8");
	request.getHeaders().setContentLength(body.length);

	if (request instanceof StreamingHttpOutputMessage) {
		StreamingHttpOutputMessage streamingRequest = (StreamingHttpOutputMessage) request;
		streamingRequest.setBody(outputStream -> StreamUtils.copy(body, outputStream));
	}
	else {
		StreamUtils.copy(body, request.getBody());
	}

	Future<ClientHttpResponse> futureResponse = request.executeAsync();
	ClientHttpResponse response = futureResponse.get();
	try {
		assertEquals("Invalid status code", HttpStatus.OK, response.getStatusCode());
		assertTrue("Header not found", response.getHeaders().containsKey(headerName));
		assertEquals("Header value not found", Arrays.asList(headerValue1, headerValue2),
				response.getHeaders().get(headerName));
		byte[] result = FileCopyUtils.copyToByteArray(response.getBody());
		assertTrue("Invalid body", Arrays.equals(body, result));
	}
	finally {
		response.close();
	}
}
 
Example #27
Source File: ServletServerHttpResponseTests.java    From spring-analysis-note 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 #28
Source File: RequestPartServletServerHttpRequestTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test  // SPR-13317
public void getBodyWithWrappedRequest() throws Exception {
	byte[] bytes = "content".getBytes("UTF-8");
	MultipartFile part = new MockMultipartFile("part", "", "application/json", bytes);
	this.mockRequest.addFile(part);
	HttpServletRequest wrapped = new HttpServletRequestWrapper(this.mockRequest);
	ServerHttpRequest request = new RequestPartServletServerHttpRequest(wrapped, "part");

	byte[] result = FileCopyUtils.copyToByteArray(request.getBody());
	assertArrayEquals(bytes, result);
}
 
Example #29
Source File: SimpleBufferingAsyncClientHttpRequest.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected ListenableFuture<ClientHttpResponse> executeInternal(
		final HttpHeaders headers, final byte[] bufferedOutput) throws IOException {

	return this.taskExecutor.submitListenable(new Callable<ClientHttpResponse>() {
		@Override
		public ClientHttpResponse call() throws Exception {
			SimpleBufferingClientHttpRequest.addHeaders(connection, headers);
			// JDK <1.8 doesn't support getOutputStream with HTTP DELETE
			if (getMethod() == HttpMethod.DELETE && bufferedOutput.length == 0) {
				connection.setDoOutput(false);
			}
			if (connection.getDoOutput() && outputStreaming) {
				connection.setFixedLengthStreamingMode(bufferedOutput.length);
			}
			connection.connect();
			if (connection.getDoOutput()) {
				FileCopyUtils.copy(bufferedOutput, connection.getOutputStream());
			}
			else {
				// Immediately trigger the request in a no-output scenario as well
				connection.getResponseCode();
			}
			return new SimpleClientHttpResponse(connection);
		}
	});
}
 
Example #30
Source File: ServletServerHttpRequestTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void getBody() throws IOException {
	byte[] content = "Hello World".getBytes("UTF-8");
	mockRequest.setContent(content);

	byte[] result = FileCopyUtils.copyToByteArray(request.getBody());
	assertArrayEquals("Invalid content returned", content, result);
}