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

The following examples show how to use org.springframework.util.StreamUtils#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: FormHttpMessageConverter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private void writeForm(MultiValueMap<String, Object> formData, @Nullable MediaType contentType,
		HttpOutputMessage outputMessage) throws IOException {

	contentType = getMediaType(contentType);
	outputMessage.getHeaders().setContentType(contentType);

	Charset charset = contentType.getCharset();
	Assert.notNull(charset, "No charset"); // should never occur

	final byte[] bytes = serializeForm(formData, charset).getBytes(charset);
	outputMessage.getHeaders().setContentLength(bytes.length);

	if (outputMessage instanceof StreamingHttpOutputMessage) {
		StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage;
		streamingOutputMessage.setBody(outputStream -> StreamUtils.copy(bytes, outputStream));
	}
	else {
		StreamUtils.copy(bytes, outputMessage.getBody());
	}
}
 
Example 2
Source File: InterceptingAsyncClientHttpRequest.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public ListenableFuture<ClientHttpResponse> executeAsync(HttpRequest request, byte[] body)
		throws IOException {

	if (this.iterator.hasNext()) {
		AsyncClientHttpRequestInterceptor interceptor = this.iterator.next();
		return interceptor.intercept(request, body, this);
	}
	else {
		URI uri = request.getURI();
		HttpMethod method = request.getMethod();
		HttpHeaders headers = request.getHeaders();

		Assert.state(method != null, "No standard HTTP method");
		AsyncClientHttpRequest delegate = requestFactory.createAsyncRequest(uri, method);
		delegate.getHeaders().putAll(headers);
		if (body.length > 0) {
			StreamUtils.copy(body, delegate.getBody());
		}

		return delegate.executeAsync();
	}
}
 
Example 3
Source File: InterceptingClientHttpRequest.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public ClientHttpResponse execute(HttpRequest request, byte[] body) throws IOException {
	if (this.iterator.hasNext()) {
		ClientHttpRequestInterceptor nextInterceptor = this.iterator.next();
		return nextInterceptor.intercept(request, body, this);
	}
	else {
		ClientHttpRequest delegate = requestFactory.createRequest(request.getURI(), request.getMethod());
		for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()) {
			List<String> values = entry.getValue();
			for (String value : values) {
				delegate.getHeaders().add(entry.getKey(), value);
			}
		}
		if (body.length > 0) {
			StreamUtils.copy(body, delegate.getBody());
		}
		return delegate.execute();
	}
}
 
Example 4
Source File: InterceptingAsyncClientHttpRequest.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public ListenableFuture<ClientHttpResponse> executeAsync(HttpRequest request, byte[] body)
		throws IOException {

	if (this.iterator.hasNext()) {
		AsyncClientHttpRequestInterceptor interceptor = this.iterator.next();
		return interceptor.intercept(request, body, this);
	}
	else {
		URI uri = request.getURI();
		HttpMethod method = request.getMethod();
		HttpHeaders headers = request.getHeaders();

		Assert.state(method != null, "No standard HTTP method");
		AsyncClientHttpRequest delegate = requestFactory.createAsyncRequest(uri, method);
		delegate.getHeaders().putAll(headers);
		if (body.length > 0) {
			StreamUtils.copy(body, delegate.getBody());
		}

		return delegate.executeAsync();
	}
}
 
Example 5
Source File: AbstractHttpRequestFactoryTestCase.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void echo() throws Exception {
	ClientHttpRequest request = factory.createRequest(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());
	}

	ClientHttpResponse response = request.execute();
	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 6
Source File: InterceptingClientHttpRequest.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public ClientHttpResponse execute(HttpRequest request, byte[] body) throws IOException {
	if (this.iterator.hasNext()) {
		ClientHttpRequestInterceptor nextInterceptor = this.iterator.next();
		return nextInterceptor.intercept(request, body, this);
	}
	else {
		ClientHttpRequest delegate = requestFactory.createRequest(request.getURI(), request.getMethod());
		delegate.getHeaders().putAll(request.getHeaders());
		if (body.length > 0) {
			StreamUtils.copy(body, delegate.getBody());
		}
		return delegate.execute();
	}
}
 
Example 7
Source File: SerializableObjectHttpMessageConverter.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
@Override
protected void writeInternal(final Serializable serializableObject, final HttpOutputMessage outputMessage)
  throws IOException, HttpMessageNotWritableException
{
  final byte[] messageBody = IOUtils.serializeObject(serializableObject);
  setContentLength(outputMessage, messageBody);
  StreamUtils.copy(messageBody, outputMessage.getBody());
}
 
Example 8
Source File: NacosConfigHttpHandler.java    From nacos-spring-project with Apache License 2.0 5 votes vote down vote up
private void write(HttpExchange httpExchange, String content) throws IOException {
	if (content != null) {
		OutputStream outputStream = httpExchange.getResponseBody();
		httpExchange.sendResponseHeaders(200, content.length());
		StreamUtils.copy(URLDecoder.decode(content, "UTF-8"), forName("UTF-8"),
				outputStream);
	}
	httpExchange.close();
}
 
Example 9
Source File: TestController.java    From jframework with Apache License 2.0 5 votes vote down vote up
@GetMapping(value = "/image", produces = MediaType.IMAGE_PNG_VALUE)
public void getImage(HttpServletResponse response) throws IOException {
    try (FileInputStream fileInputStream = new FileInputStream(new File("src/main/resources/1.png"))) {
        response.setContentType(MediaType.IMAGE_PNG_VALUE);
        StreamUtils.copy(fileInputStream, response.getOutputStream());
    }
}
 
Example 10
Source File: URLBootstrap.java    From thinking-in-spring-boot-samples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // 构建 URL 对象
    URL url = new URL("https://github.com/mercyblitz");
    // 获取 URLConnection 对象
    URLConnection urlConnection = url.openConnection();
    try (InputStream inputStream = urlConnection.getInputStream()) { // 自动关闭 InputStream
        // 复制 资源流 到 标准输出流
        StreamUtils.copy(inputStream, System.out);
    }
}
 
Example 11
Source File: SoapTransportCommandProcessor.java    From cougar with Apache License 2.0 5 votes vote down vote up
@Override
public void onCougarStart() {
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    for (ServiceBindingDescriptor sd : getServiceBindingDescriptors()) {
        SoapServiceBindingDescriptor soapServiceDesc = (SoapServiceBindingDescriptor) sd;
        try {
            // we'll load the schema content and create a Schema object once, as this is threadsafe and so can be reused
            // this should cut down on some memory usage and remove schema parsing from the critical path when validating
            try (InputStream is = soapServiceDesc.getClass().getClassLoader().getResourceAsStream(soapServiceDesc.getSchemaPath())) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                StreamUtils.copy(is, baos);
                String schemaContent = baos.toString();
                Schema schema = schemaFactory.newSchema(new StreamSource(new StringReader(schemaContent)));
                String uriVersionStripped = stripMinorVersionFromUri(soapServiceDesc.getServiceContextPath() + soapServiceDesc.getServiceVersion());
                for (OperationBindingDescriptor desc : soapServiceDesc.getOperationBindings()) {
                    SoapOperationBindingDescriptor soapOpDesc = (SoapOperationBindingDescriptor) desc;
                    OperationDefinition opDef = getOperationDefinition(soapOpDesc.getOperationKey());
                    String operationName = uriVersionStripped + "/" + soapOpDesc.getRequestName().toLowerCase();
                    bindings.put(operationName,
                            new SoapOperationBinding(opDef, soapOpDesc,
                                    soapServiceDesc, schema));
                }
            }
        }
        catch (IOException | SAXException e) {
            throw new CougarFrameworkException("Error loading schema", e);
        }
    }
}
 
Example 12
Source File: BufferingClientHttpRequestWrapper.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] bufferedOutput) throws IOException {
	this.request.getHeaders().putAll(headers);
	StreamUtils.copy(bufferedOutput, this.request.getBody());
	ClientHttpResponse response = this.request.execute();
	return new BufferingClientHttpResponseWrapper(response);
}
 
Example 13
Source File: RichMenuImageDownloadCommand.java    From line-bot-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
public void execute() throws IOException {
    final String richMenuId = checkNotNull(arguments.getRichMenuId(), "--rich-menu-id= is not set.");
    final String out = checkNotNull(arguments.getOut(), "--out= is not set.");
    final MessageContentResponse messageContentResponse =
            getUnchecked(lineBlobClient.getRichMenuImage(richMenuId));

    log.info("Request Successfully finished. {}", messageContentResponse);

    try (OutputStream os = new FileOutputStream(out)) {
        StreamUtils.copy(messageContentResponse.getStream(), os);
    }

    log.info("Successfully finished. Output = {}", out);
}
 
Example 14
Source File: FdfsFileService.java    From hsweb-framework with Apache License 2.0 5 votes vote down vote up
@Override
public void writeFile(String fileId, OutputStream out, long skip) throws IOException {
    try (InputStream inputStream = readFile(fileId)) {
        if (skip > 0) {
            long len = inputStream.skip(skip);
            log.info("skip write {} len:{}", skip, len);
        }
        StreamUtils.copy(inputStream, out);
    }
}
 
Example 15
Source File: StringHttpMessageConverter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected void writeInternal(String str, HttpOutputMessage outputMessage) throws IOException {
	HttpHeaders headers = outputMessage.getHeaders();
	if (this.writeAcceptCharset && headers.get(HttpHeaders.ACCEPT_CHARSET) == null) {
		headers.setAcceptCharset(getAcceptedCharsets());
	}
	Charset charset = getContentTypeCharset(headers.getContentType());
	StreamUtils.copy(str, charset, outputMessage.getBody());
}
 
Example 16
Source File: OAuth2FileService.java    From hsweb-framework with Apache License 2.0 5 votes vote down vote up
@Override
public void writeFile(String fileId, OutputStream out, long skip) throws IOException {
    try (InputStream stream = createRequest("/download/" + fileId)
            .header("Range", "bytes=" + skip)
            .get().asStream()) {
        StreamUtils.copy(stream, out);
    }
}
 
Example 17
Source File: RangeAwareResourceRegionHttpMessageConverter.java    From engine with GNU General Public License v3.0 4 votes vote down vote up
protected void writeResourceRegionCollection(Collection<ResourceRegion> resourceRegions,
                                             HttpOutputMessage outputMessage) throws IOException {
    Assert.notNull(resourceRegions, "Collection of ResourceRegion should not be null");
    HttpHeaders responseHeaders = outputMessage.getHeaders();

    MediaType contentType = responseHeaders.getContentType();
    String boundaryString = MimeTypeUtils.generateMultipartBoundaryString();
    responseHeaders.set(HttpHeaders.CONTENT_TYPE, "multipart/byteranges; boundary=" + boundaryString);
    OutputStream out = outputMessage.getBody();

    for (ResourceRegion region : resourceRegions) {
        long start = region.getPosition();
        long end = start + region.getCount() - 1;
        InputStream in = null;
        try {
            // Writing MIME header.
            println(out);
            print(out, "--" + boundaryString);
            println(out);
            if (contentType != null) {
                print(out, "Content-Type: " + contentType.toString());
                println(out);
            }
            Long resourceLength = region.getResource().contentLength();
            end = Math.min(end, resourceLength - 1);
            print(out, "Content-Range: bytes " + start + '-' + end + '/' + resourceLength);
            println(out);
            println(out);

            // Printing content
            Resource resource = region.getResource();
            if (resource instanceof RangeAwareResource) {
                in = ((RangeAwareResource) resource).getInputStream(start, end);
                StreamUtils.copy(in, out);
            } else {
                in = resource.getInputStream();
                StreamUtils.copyRange(in, out, start, end);
            }
        } finally {
            IOUtils.closeQuietly(in);
        }
    }

    println(out);
    print(out, "--" + boundaryString + "--");
}
 
Example 18
Source File: AppController.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@RequestMapping( value = "/{app}/**", method = RequestMethod.GET )
public void renderApp( @PathVariable( "app" ) String app,
    HttpServletRequest request, HttpServletResponse response )
    throws IOException, WebMessageException
{
    App application = appManager.getApp( app );

    if ( application == null )
    {
        throw new WebMessageException( WebMessageUtils.notFound( "App '" + app + "' not found." ) );
    }

    if ( !appManager.isAccessible( application ) )
    {
        throw new ReadAccessDeniedException( "You don't have access to application " + app + "." );
    }

    if ( application.getAppState() == AppStatus.DELETION_IN_PROGRESS )
    {
        throw new WebMessageException( WebMessageUtils.conflict( "App '" + app + "' deletion is still in progress." ) );
    }

    // Get page requested
    String pageName = getUrl( request.getPathInfo(), app );

    log.debug( String.format( "App page name: '%s'", pageName ) );

    // Handling of 'manifest.webapp'
    if ( "manifest.webapp".equals( pageName ) )
    {
        // If request was for manifest.webapp, check for * and replace with host
        if ( "*".equals( application.getActivities().getDhis().getHref() ) )
        {
            String contextPath = ContextUtils.getContextPath( request );

            log.debug( String.format( "Manifest context path: '%s'", contextPath ) );

            application.getActivities().getDhis().setHref( contextPath );
        }

        jsonMapper.writeValue( response.getOutputStream(), application );
    }
    // Any other page
    else
    {
        // Retrieve file
        Resource resource = appManager.getAppResource( application, pageName );

        if ( resource == null )
        {
            response.sendError( HttpServletResponse.SC_NOT_FOUND );
            return;
        }

        String filename = resource.getFilename();
        log.debug( String.format( "App filename: '%s'", filename ) );

        if ( new ServletWebRequest( request, response ).checkNotModified( resource.lastModified() ) )
        {
            response.setStatus( HttpServletResponse.SC_NOT_MODIFIED );
            return;
        }

        String mimeType = request.getSession().getServletContext().getMimeType( filename );

        if ( mimeType != null )
        {
            response.setContentType( mimeType );
        }

        response.setContentLength( (int) resource.contentLength() );
        response.setHeader( "Last-Modified", DateUtils.getHttpDateString( new Date( resource.lastModified() ) ) );
        StreamUtils.copy( resource.getInputStream(), response.getOutputStream() );
    }
}
 
Example 19
Source File: ByteArrayHttpMessageConverter.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
protected void writeInternal(byte[] bytes, HttpOutputMessage outputMessage) throws IOException {
	StreamUtils.copy(bytes, outputMessage.getBody());
}
 
Example 20
Source File: FormHttpMessageConverter.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private void writeForm(MultiValueMap<String, String> form, MediaType contentType,
		HttpOutputMessage outputMessage) throws IOException {

	Charset charset;
	if (contentType != null) {
		outputMessage.getHeaders().setContentType(contentType);
		charset = (contentType.getCharset() != null ? contentType.getCharset() : this.charset);
	}
	else {
		outputMessage.getHeaders().setContentType(MediaType.APPLICATION_FORM_URLENCODED);
		charset = this.charset;
	}
	StringBuilder builder = new StringBuilder();
	for (Iterator<String> nameIterator = form.keySet().iterator(); nameIterator.hasNext();) {
		String name = nameIterator.next();
		for (Iterator<String> valueIterator = form.get(name).iterator(); valueIterator.hasNext();) {
			String value = valueIterator.next();
			builder.append(URLEncoder.encode(name, charset.name()));
			if (value != null) {
				builder.append('=');
				builder.append(URLEncoder.encode(value, charset.name()));
				if (valueIterator.hasNext()) {
					builder.append('&');
				}
			}
		}
		if (nameIterator.hasNext()) {
			builder.append('&');
		}
	}
	final byte[] bytes = builder.toString().getBytes(charset.name());
	outputMessage.getHeaders().setContentLength(bytes.length);

	if (outputMessage instanceof StreamingHttpOutputMessage) {
		StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage;
		streamingOutputMessage.setBody(new StreamingHttpOutputMessage.Body() {
			@Override
			public void writeTo(OutputStream outputStream) throws IOException {
				StreamUtils.copy(bytes, outputStream);
			}
		});
	}
	else {
		StreamUtils.copy(bytes, outputMessage.getBody());
	}
}