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

The following examples show how to use org.springframework.util.StreamUtils#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: SourceHttpMessageConverter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@SuppressWarnings("deprecation")  // on JDK 9
private SAXSource readSAXSource(InputStream body, HttpInputMessage inputMessage) throws IOException {
	try {
		XMLReader xmlReader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader();
		xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", !isSupportDtd());
		xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", isProcessExternalEntities());
		if (!isProcessExternalEntities()) {
			xmlReader.setEntityResolver(NO_OP_ENTITY_RESOLVER);
		}
		byte[] bytes = StreamUtils.copyToByteArray(body);
		return new SAXSource(xmlReader, new InputSource(new ByteArrayInputStream(bytes)));
	}
	catch (SAXException ex) {
		throw new HttpMessageNotReadableException(
				"Could not parse document: " + ex.getMessage(), ex, inputMessage);
	}
}
 
Example 2
Source File: TestAttestationUtil.java    From webauthn4j with Apache License 2.0 5 votes vote down vote up
public static PrivateKey loadPrivateKeyFromResource(Resource resource) {
    try {
        InputStream inputStream = resource.getInputStream();
        byte[] data = StreamUtils.copyToByteArray(inputStream);
        return loadECPrivateKey(data);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 3
Source File: WxMediaResource.java    From FastBootWeixin with Apache License 2.0 5 votes vote down vote up
/**
 * body只在
 *
 * @return the result
 */
public byte[] getBody() {
    if (this.body == null && this.file != null) {
        try (InputStream is = new BufferedInputStream(new FileInputStream(file))) {
            this.body = StreamUtils.copyToByteArray(is);
        } catch (Exception e) {
            throw new WxAppException(e);
        }
    }
    return body;
}
 
Example 4
Source File: FunctionArchiveDeployer.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
@Override
protected ClassLoader createClassLoader(URL[] urls) throws Exception {
	String classAsPath = DeployerContextUtils.class.getName().replace('.', '/') + ".class";
	byte[] deployerContextUtilsBytes = StreamUtils
			.copyToByteArray(DeployerContextUtils.class.getClassLoader().getResourceAsStream(classAsPath));
	/*
	 * While LaunchedURLClassLoader is completely disconnected with the current
	 * class loader, this will ensure that certain classes (e.g., org.reactivestreams.* see #shouldLoadViaDeployerLoader() )
	 * are shared across two class loaders.
	 */
	final ClassLoader deployerClassLoader = getClass().getClassLoader();
	this.archiveLoader = new LaunchedURLClassLoader(urls, deployerClassLoader.getParent()) {
		@Override
		public Class<?> loadClass(String name) throws ClassNotFoundException {
			Class<?> clazz = null;
			if (shouldLoadViaDeployerLoader(name)) {
				clazz = deployerClassLoader.loadClass(name);
			}
			else if (name.equals(DeployerContextUtils.class.getName())) {
				/*
				 * This will ensure that `DeployerContextUtils` is available to
				 * foreign class loader for cases where foreign JAR does not
				 * have SCF dependencies.
				 */
				try {
					clazz = super.loadClass(name, false);
				}
				catch (Exception e) {
					clazz = defineClass(name, deployerContextUtilsBytes, 0, deployerContextUtilsBytes.length);
				}
			}
			else {
				clazz = super.loadClass(name, false);
			}
			return clazz;
		}
	};
	return this.archiveLoader;
}
 
Example 5
Source File: BufferingClientHttpResponseWrapper.java    From teiid-spring-boot with Apache License 2.0 5 votes vote down vote up
@Override
public InputStream getBody() throws IOException {
  if (this.body == null) {
    this.body = StreamUtils.copyToByteArray(this.response.getBody());
  }
  return new ByteArrayInputStream(this.body);
}
 
Example 6
Source File: ImageRecognitionTensorflowProcessorIntegrationTests.java    From tensorflow with Apache License 2.0 5 votes vote down vote up
@Test
public void testEvaluationPositive() throws IOException {
	try (InputStream is = new ClassPathResource("/images/panda.jpeg").getInputStream()) {

		byte[] image = StreamUtils.copyToByteArray(is);

		testEvaluationWithOutputInHeader(
				image, "{\"labels\":[{\"giant panda\":0.9864928}]}");
	}
}
 
Example 7
Source File: ImageRecognitionTensorflowProcessorIntegrationTests.java    From tensorflow with Apache License 2.0 5 votes vote down vote up
@Test
public void testEvaluationPositive() throws IOException {
	try (InputStream is = new ClassPathResource("/images/panda.jpeg").getInputStream()) {

		byte[] image = StreamUtils.copyToByteArray(is);

		channels.input().send(MessageBuilder.withPayload(image).build());

		Message<byte[]> received = (Message<byte[]>) messageCollector.forChannel(channels.output()).poll();

		Assert.assertThat(received.getPayload(),
				equalTo("{\"labels\":[{\"giant panda\":0.9864928}]}"));
	}
}
 
Example 8
Source File: SpringExampleAppTests.java    From spring-qrcode-example with Apache License 2.0 5 votes vote down vote up
@Test
public void testQrCodeControllerSuccess() throws Exception {
	byte[] testImage = StreamUtils.copyToByteArray(getClass().getResourceAsStream("/test.png"));
	webClient.get().uri(SpringExampleApp.QRCODE_ENDPOINT + "?text=This is a test")
		.exchange().expectStatus().isOk()
		.expectHeader().contentType(MediaType.IMAGE_PNG)
		.expectHeader().cacheControl(CacheControl.maxAge(1800, TimeUnit.SECONDS))
		.expectBody(byte[].class).isEqualTo(testImage);
}
 
Example 9
Source File: JsonNodeSerdeTest.java    From football-events with MIT License 5 votes vote down vote up
@Test
public void deserialize() throws Exception {
    byte[] json = StreamUtils.copyToByteArray(getClass().getResourceAsStream("JsonNodeSerdeTest.json"));
    JsonNode node = new JsonNodeSerde().deserialize(null, json);

    assertThat(node.get("schema").get("name").textValue()).isEqualTo("fb-connect.public.players.Envelope");
    assertThat(node.get("payload").get("before").textValue()).isNull();
    assertThat(node.get("payload").get("after").get("id").intValue()).isEqualTo(1);
    assertThat(node.get("payload").get("after").get("name").textValue()).isEqualTo("Player One");
    assertThat(node.get("payload").get("op").textValue()).isEqualTo("c");
}
 
Example 10
Source File: FileProcessorImpl.java    From accelerator-initializer with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public byte[] fileToByteArray(File file) {
    try(InputStream is = new FileInputStream(file)) {
        return StreamUtils.copyToByteArray(is);
    } catch (IOException e) {
        throw new InitializerException("It was not possible to generate project {}", file.getName(), e);
    }
}
 
Example 11
Source File: Ip2regionSearcherImpl.java    From mica with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
	DbConfig config = new DbConfig();
	Resource resource = resourceLoader.getResource(properties.getDbFileLocation());
	try (InputStream inputStream = resource.getInputStream()) {
		this.searcher = new DbSearcher(config, new ByteArrayDBReader(StreamUtils.copyToByteArray(inputStream)));
	}
}
 
Example 12
Source File: BufferingClientHttpResponseWrapper.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public InputStream getBody() throws IOException {
	if (this.body == null) {
		this.body = StreamUtils.copyToByteArray(this.response.getBody());
	}
	return new ByteArrayInputStream(this.body);
}
 
Example 13
Source File: BodyReaderWrapper.java    From spring-boot-start-current with Apache License 2.0 5 votes vote down vote up
public BodyReaderWrapper ( HttpServletRequest request ) throws IOException {
    super( request );
    if ( RequestUtils.isApplicationJsonHeader( request ) ) {
        body = StreamUtils.copyToByteArray( request.getInputStream() );
    } else {
        body = null;
    }
}
 
Example 14
Source File: ServiceMetadata.java    From spring-cloud-open-service-broker with Apache License 2.0 5 votes vote down vote up
private String base64EncodeImageData(String filename) {
	String formattedImageData = null;
	ClassPathResource resource = new ClassPathResource(filename);
	try (InputStream stream = resource.getInputStream()) {
		byte[] imageBytes = StreamUtils.copyToByteArray(stream);
		String imageData = Base64Utils.encodeToString(imageBytes);
		formattedImageData = String.format(IMAGE_DATA_FORMAT, imageData);
	}
	catch (IOException e) {
		LOG.warn("Error converting image file to byte array", e);
	}
	return formattedImageData;
}
 
Example 15
Source File: ResourceHttpMessageConverter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected Resource readInternal(Class<? extends Resource> clazz, HttpInputMessage inputMessage)
		throws IOException, HttpMessageNotReadableException {

	if (this.supportsReadStreaming && InputStreamResource.class == clazz) {
		return new InputStreamResource(inputMessage.getBody()) {
			@Override
			public String getFilename() {
				return inputMessage.getHeaders().getContentDisposition().getFilename();
			}
		};
	}
	else if (Resource.class == clazz || ByteArrayResource.class.isAssignableFrom(clazz)) {
		byte[] body = StreamUtils.copyToByteArray(inputMessage.getBody());
		return new ByteArrayResource(body) {
			@Override
			@Nullable
			public String getFilename() {
				return inputMessage.getHeaders().getContentDisposition().getFilename();
			}
		};
	}
	else {
		throw new HttpMessageNotReadableException("Unsupported resource class: " + clazz, inputMessage);
	}
}
 
Example 16
Source File: DubboGatewayServlet.java    From spring-cloud-alibaba with Apache License 2.0 4 votes vote down vote up
private byte[] getRequestBody(HttpServletRequest request) throws IOException {
	ServletInputStream inputStream = request.getInputStream();
	return StreamUtils.copyToByteArray(inputStream);
}
 
Example 17
Source File: VaultPkiTemplateIntegrationTests.java    From spring-vault with Apache License 2.0 4 votes vote down vote up
@Test
void shouldReturnCrl() throws Exception {

	try (InputStream in = this.pkiOperations.getCrl(Encoding.DER)) {

		CertificateFactory cf = CertificateFactory.getInstance("X.509");

		assertThat(cf.generateCRL(in)).isInstanceOf(X509CRL.class);
	}

	try (InputStream crl = this.pkiOperations.getCrl(Encoding.PEM)) {

		byte[] bytes = StreamUtils.copyToByteArray(crl);
		assertThat(bytes).isNotEmpty();
	}
}
 
Example 18
Source File: OssKeyLoader.java    From daming with Apache License 2.0 4 votes vote down vote up
@Override
@SneakyThrows
public byte[] getBytes() {
    OSSObject ossObject = ossClient.getObject(bucketName, objectName);
    return StreamUtils.copyToByteArray(ossObject.getObjectContent());
}
 
Example 19
Source File: BodyReaderHttpServletRequestWrapper.java    From bird-java with MIT License 4 votes vote down vote up
public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
    super(request);
    requestBody = StreamUtils.copyToByteArray(request.getInputStream());
}
 
Example 20
Source File: SourceHttpMessageConverter.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private StreamSource readStreamSource(InputStream body) throws IOException {
	byte[] bytes = StreamUtils.copyToByteArray(body);
	return new StreamSource(new ByteArrayInputStream(bytes));
}