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

The following examples show how to use org.springframework.util.FileCopyUtils#copyToByteArray() . 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: 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 2
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 3
Source File: AppCacheManifestTransformerTests.java    From java-technology-stack 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: ShadowingClassLoader.java    From java-technology-stack 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 5
Source File: AppCacheManifestTransformerTests.java    From spring-analysis-note 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 6
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 7
Source File: Jaxb2Marshaller.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public byte[] getAttachmentAsByteArray(String cid) {
	try {
		DataHandler dataHandler = getAttachmentAsDataHandler(cid);
		return FileCopyUtils.copyToByteArray(dataHandler.getInputStream());
	}
	catch (IOException ex) {
		throw new UnmarshallingFailureException("Couldn't read attachment", ex);
	}
}
 
Example 8
Source File: RequestLoggingFilterTests.java    From java-technology-stack with MIT License 5 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("UTF-8");
	request.setContent(requestBody);

	FilterChain filterChain = new FilterChain() {
		@Override
		public void doFilter(ServletRequest filterRequest, ServletResponse filterResponse)
				throws IOException, ServletException {
			((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("UTF-8"), wrapper.getContentAsByteArray());
		}
	};

	filter.doFilter(request, response, filterChain);

	assertNotNull(filter.afterRequestMessage);
	assertTrue(filter.afterRequestMessage.contains("Hel"));
	assertFalse(filter.afterRequestMessage.contains("Hello World"));
}
 
Example 9
Source File: ResourceHttpMessageConverterTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void shouldReadImageResource() throws IOException {
	byte[] body = FileCopyUtils.copyToByteArray(getClass().getResourceAsStream("logo.jpg"));
	MockHttpInputMessage inputMessage = new MockHttpInputMessage(body);
	inputMessage.getHeaders().setContentType(MediaType.IMAGE_JPEG);
	inputMessage.getHeaders().setContentDisposition(
			ContentDisposition.builder("attachment").filename("yourlogo.jpg").build());
	Resource actualResource = converter.read(Resource.class, inputMessage);
	assertThat(FileCopyUtils.copyToByteArray(actualResource.getInputStream()), is(body));
	assertEquals("yourlogo.jpg", actualResource.getFilename());
}
 
Example 10
Source File: RestResponseErrorHandler.java    From mPaaS with Apache License 2.0 5 votes vote down vote up
protected byte[] getResponseBody(ClientHttpResponse response) {
    try {
        return FileCopyUtils.copyToByteArray(response.getBody());
    }
    catch (IOException ex) {
        throw new KmssServiceException("errors.unkown", ex);
    }
}
 
Example 11
Source File: ContentCachingRequestWrapperTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void cachedContent() throws Exception {
	this.request.setMethod("GET");
	this.request.setCharacterEncoding(CHARSET);
	this.request.setContent("Hello World".getBytes(CHARSET));

	ContentCachingRequestWrapper wrapper = new ContentCachingRequestWrapper(this.request);
	byte[] response = FileCopyUtils.copyToByteArray(wrapper.getInputStream());
	assertArrayEquals(response, wrapper.getContentAsByteArray());
}
 
Example 12
Source File: ContentCachingRequestWrapperTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void cachedContentWithLimit() throws Exception {
	this.request.setMethod("GET");
	this.request.setCharacterEncoding(CHARSET);
	this.request.setContent("Hello World".getBytes(CHARSET));

	ContentCachingRequestWrapper wrapper = new ContentCachingRequestWrapper(this.request, 3);
	byte[] response = FileCopyUtils.copyToByteArray(wrapper.getInputStream());
	assertArrayEquals("Hello World".getBytes(CHARSET), response);
	assertArrayEquals("Hel".getBytes(CHARSET), wrapper.getContentAsByteArray());
}
 
Example 13
Source File: BufferedImageHttpMessageConverterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void read() throws IOException {
	Resource logo = new ClassPathResource("logo.jpg", BufferedImageHttpMessageConverterTests.class);
	byte[] body = FileCopyUtils.copyToByteArray(logo.getInputStream());
	MockHttpInputMessage inputMessage = new MockHttpInputMessage(body);
	inputMessage.getHeaders().setContentType(new MediaType("image", "jpeg"));
	BufferedImage result = converter.read(BufferedImage.class, inputMessage);
	assertEquals("Invalid height", 500, result.getHeight());
	assertEquals("Invalid width", 750, result.getWidth());
}
 
Example 14
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 15
Source File: Jaxb2Marshaller.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public byte[] getAttachmentAsByteArray(String cid) {
	try {
		DataHandler dataHandler = getAttachmentAsDataHandler(cid);
		return FileCopyUtils.copyToByteArray(dataHandler.getInputStream());
	}
	catch (IOException ex) {
		throw new UnmarshallingFailureException("Couldn't read attachment", ex);
	}
}
 
Example 16
Source File: RequestPartServletServerHttpRequestTests.java    From java-technology-stack 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 17
Source File: RequestPartServletServerHttpRequestTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void getBody() throws Exception {
	byte[] bytes = "content".getBytes("UTF-8");
	MultipartFile part = new MockMultipartFile("part", "", "application/json", bytes);
	this.mockRequest.addFile(part);
	ServerHttpRequest request = new RequestPartServletServerHttpRequest(this.mockRequest, "part");

	byte[] result = FileCopyUtils.copyToByteArray(request.getBody());
	assertArrayEquals(bytes, result);
}
 
Example 18
Source File: CssLinkResourceTransformer.java    From java-technology-stack with MIT License 4 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public Resource transform(HttpServletRequest request, Resource resource, ResourceTransformerChain transformerChain)
		throws IOException {

	resource = transformerChain.transform(request, resource);

	String filename = resource.getFilename();
	if (!"css".equals(StringUtils.getFilenameExtension(filename)) ||
			resource instanceof EncodedResourceResolver.EncodedResource ||
			resource instanceof GzipResourceResolver.GzippedResource) {
		return resource;
	}

	byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream());
	String content = new String(bytes, DEFAULT_CHARSET);

	SortedSet<ContentChunkInfo> links = new TreeSet<>();
	for (LinkParser parser : this.linkParsers) {
		parser.parse(content, links);
	}

	if (links.isEmpty()) {
		return resource;
	}

	int index = 0;
	StringWriter writer = new StringWriter();
	for (ContentChunkInfo linkContentChunkInfo : links) {
		writer.write(content.substring(index, linkContentChunkInfo.getStart()));
		String link = content.substring(linkContentChunkInfo.getStart(), linkContentChunkInfo.getEnd());
		String newLink = null;
		if (!hasScheme(link)) {
			String absolutePath = toAbsolutePath(link, request);
			newLink = resolveUrlPath(absolutePath, request, resource, transformerChain);
		}
		writer.write(newLink != null ? newLink : link);
		index = linkContentChunkInfo.getEnd();
	}
	writer.write(content.substring(index));

	return new TransformedResource(resource, writer.toString().getBytes(DEFAULT_CHARSET));
}
 
Example 19
Source File: PathResourceTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Test
public void getInputStream() throws IOException {
	PathResource resource = new PathResource(TEST_FILE);
	byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream());
	assertThat(bytes.length, greaterThan(0));
}
 
Example 20
Source File: CommAreaRecord.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
public void read(InputStream in) throws IOException {
	this.bytes = FileCopyUtils.copyToByteArray(in);
}