Here are the examples of the java api org.springframework.util.StreamUtils.copy() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
78 Examples
19
Source : ByteArrayHttpMessageConverter.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Override
protected void writeInternal(byte[] bytes, HttpOutputMessage outputMessage) throws IOException {
StreamUtils.copy(bytes, outputMessage.getBody());
}
19
Source : XpathResultMatchersTests.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Test
public void stringEncodingDetection() throws Exception {
String content = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" + "<person><name>Jürgen</name></person>";
byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
MockHttpServletResponse response = new MockHttpServletResponse();
response.addHeader("Content-Type", "application/xml");
StreamUtils.copy(bytes, response.getOutputStream());
StubMvcResult result = new StubMvcResult(null, null, null, null, null, null, response);
new XpathResultMatchers("/person/name", null).string("Jürgen").match(result);
}
19
Source : ProjectGenerator.java
with MIT License
from microsoft
with MIT License
from microsoft
private void writeBinary(File target, byte[] body) {
try (OutputStream stream = new FileOutputStream(target)) {
StreamUtils.copy(body, stream);
} catch (Exception e) {
throw new IllegalStateException("Cannot write file " + target, e);
}
}
19
Source : XpathResultMatchersTests.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
@Test
public void stringEncodingDetection() throws Exception {
String content = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" + "<person><name>Jürgen</name></person>";
byte[] bytes = content.getBytes(Charset.forName("UTF-8"));
MockHttpServletResponse response = new MockHttpServletResponse();
response.addHeader("Content-Type", "application/xml");
StreamUtils.copy(bytes, response.getOutputStream());
StubMvcResult result = new StubMvcResult(null, null, null, null, null, null, response);
new XpathResultMatchers("/person/name", null).string("Jürgen").match(result);
}
19
Source : CloudEventHttpMessageConverter.java
with Apache License 2.0
from cloudevents
with Apache License 2.0
from cloudevents
private void copy(byte[] body, HttpOutputMessage outputMessage) {
try {
StreamUtils.copy(body, outputMessage.getBody());
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
19
Source : AuthenticationServiceJwtImpl.java
with Apache License 2.0
from alibaba
with Apache License 2.0
from alibaba
public byte[] toBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
StreamUtils.copy(inputStream, buffer);
byte[] bytes = buffer.toByteArray();
inputStream.close();
buffer.close();
return bytes;
}
18
Source : JarFileTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
@Test
public void jarFileWithScriptAtTheStart() throws Exception {
File file = this.temporaryFolder.newFile();
InputStream sourceJarContent = new FileInputStream(this.rootJarFile);
FileOutputStream outputStream = new FileOutputStream(file);
StreamUtils.copy("#/bin/bash", Charset.defaultCharset(), outputStream);
FileCopyUtils.copy(sourceJarContent, outputStream);
this.rootJarFile = file;
this.jarFile = new JarFile(file);
// Call some other tests to verify
getEntries();
getNestedJarFile();
}
18
Source : ResourceHttpMessageConverter.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
protected void writeContent(Resource resource, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
try {
InputStream in = resource.getInputStream();
try {
StreamUtils.copy(in, outputMessage.getBody());
} catch (NullPointerException ex) {
// ignore, see SPR-13620
} finally {
try {
in.close();
} catch (Throwable ex) {
// ignore, see SPR-12999
}
}
} catch (FileNotFoundException ex) {
// ignore, see SPR-12999
}
}
18
Source : BufferingClientHttpRequestWrapper.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@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);
}
18
Source : SourceFiles.java
with Apache License 2.0
from spring-projects-experimental
with Apache License 2.0
from spring-projects-experimental
/**
* Create a {@link SourceFile} from an {@link InputStream}, usually replacedociated
* with a static resource on disk.
* @param packageName the package name
* @param clreplacedName the clreplaced name
* @param staticFile the static file
* @return the source file
*/
public static SourceFile fromStaticFile(String packageName, String clreplacedName, InputStream staticFile) {
return rootPath -> {
Path packagePath = rootPath;
for (String segment : packageName.split(("\\."))) {
packagePath = packagePath.resolve(segment);
}
Files.createDirectories(packagePath);
Path outputPath = packagePath.resolve(Paths.get(clreplacedName + ".java"));
StreamUtils.copy(staticFile, Files.newOutputStream(outputPath));
};
}
18
Source : Request.java
with Apache License 2.0
from otaviof
with Apache License 2.0
from otaviof
/**
* Time body bytes to the same size declared on header.
*
* @param req servlet request;
* @param body body bytes;
* @return trimmed body bytes;
* @throws IOException on buffer copy error;
*/
private byte[] trimBody(HttpServletRequest req, byte[] body) throws IOException {
var length = req.getContentLength();
var bos = new ByteArrayOutputStream(length >= 0 ? length : StreamUtils.BUFFER_SIZE);
StreamUtils.copy(body, bos);
return bos.toByteArray();
}
18
Source : NacosConfigHttpHandler.java
with Apache License 2.0
from nacos-group
with Apache License 2.0
from nacos-group
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();
}
18
Source : ProjectGenerator.java
with MIT License
from microsoft
with MIT License
from microsoft
private void writeText(File target, String body) {
try (OutputStream stream = new FileOutputStream(target)) {
StreamUtils.copy(body, Charset.forName("UTF-8"), stream);
} catch (Exception e) {
throw new IllegalStateException("Cannot write file " + target, e);
}
}
18
Source : ResourceHttpMessageConverter.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
@Override
protected void writeInternal(Resource resource, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
InputStream in = resource.getInputStream();
try {
StreamUtils.copy(in, outputMessage.getBody());
} finally {
try {
in.close();
} catch (IOException ex) {
}
}
outputMessage.getBody().flush();
}
18
Source : OssController.java
with Apache License 2.0
from alibaba
with Apache License 2.0
from alibaba
@GetMapping("/upload2")
public String uploadWithOutputStream() {
try {
try (OutputStream outputStream = ((WritableResource) this.remoteFile).getOutputStream();
InputStream inputStream = localFile.getInputStream()) {
StreamUtils.copy(inputStream, outputStream);
}
} catch (Exception ex) {
ex.printStackTrace();
return "upload with outputStream failed";
}
return "upload success";
}
17
Source : TokenValidatorTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
private byte[] dotConcat(byte[]... bytes) throws IOException {
ByteArrayOutputStream result = new ByteArrayOutputStream();
for (int i = 0; i < bytes.length; i++) {
if (i > 0) {
StreamUtils.copy(DOT, result);
}
StreamUtils.copy(bytes[i], result);
}
return result.toByteArray();
}
17
Source : AbstractAsyncHttpRequestFactoryTestCase.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Test
public void multipleWrites() throws Exception {
AsyncClientHttpRequest request = this.factory.createAsyncRequest(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));
} else {
StreamUtils.copy(body, request.getBody());
}
Future<ClientHttpResponse> futureResponse = request.executeAsync();
ClientHttpResponse response = futureResponse.get();
try {
FileCopyUtils.copy(body, request.getBody());
fail("IllegalStateException expected");
} catch (IllegalStateException ex) {
// expected
} finally {
response.close();
}
}
17
Source : KubernetesShellClient.java
with Apache License 2.0
from ThalesGroup
with Apache License 2.0
from ThalesGroup
String copyResourceToPath(Resource resource, String path) throws IOException {
long contentLength = resource.contentLength();
String finalPath = path + (path.endsWith("/") ? Strings.EMPTY : "/") + resource.getFilename();
String[] command = new String[] { "dd", "if=/dev/stdin", "of=" + finalPath, "bs=" + contentLength, "count=1" };
log.debug("Transferring {} to {}/{} in path {}", resource, namespace, podName, path);
Process proc = null;
try {
proc = getExec().exec(namespace, podName, command, containerName, true, false);
try (OutputStream os = proc.getOutputStream()) {
try (InputStream is = resource.getInputStream()) {
StreamUtils.copy(is, os);
}
}
if (!proc.waitFor(5000, TimeUnit.MILLISECONDS)) {
throw new ChaosException(KubernetesChaosErrorCode.K8S_SHELL_TRANSFER_TIMEOUT);
}
int i = proc.exitValue();
if (i == 0) {
String command1 = "chmod 755 " + finalPath;
runCommand(command1);
return finalPath;
}
throw new ChaosException(KubernetesChaosErrorCode.K8S_SHELL_TRANSFER_FAIL);
} catch (ApiException e) {
throw new ChaosException(KubernetesChaosErrorCode.K8S_SHELL_TRANSFER_FAIL, e);
} catch (InterruptedException e) {
log.error("Interrupted while processing, throwing Interrupt up thread", e);
Thread.currentThread().interrupt();
return Strings.EMPTY;
} finally {
if (proc != null)
proc.destroy();
}
}
17
Source : FunctionInvoker.java
with Apache License 2.0
from spring-cloud
with Apache License 2.0
from spring-cloud
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void handleRequest(InputStream input, OutputStream output, Context context) throws IOException {
final byte[] payload = StreamUtils.copyToByteArray(input);
Message requestMessage = AWSLambdaUtils.generateMessage(payload, new MessageHeaders(Collections.emptyMap()), function.getInputType(), this.objectMapper, context);
Message<byte[]> responseMessage = (Message<byte[]>) this.function.apply(requestMessage);
byte[] responseBytes = AWSLambdaUtils.generateOutput(requestMessage, responseMessage, this.objectMapper);
StreamUtils.copy(responseBytes, output);
}
17
Source : FileProcessorImpl.java
with Mozilla Public License 2.0
from scotiabank
with Mozilla Public License 2.0
from scotiabank
@Override
public void copy(InputStream from, File to) {
try (OutputStream os = new FileOutputStream(to);
InputStream fromWrapper = from) {
StreamUtils.copy(fromWrapper, os);
} catch (IOException e) {
throw new InitializerException("It was not possible to copy file {}", e);
}
}
17
Source : JsonContentReader.java
with Apache License 2.0
from Open-MBEE
with Apache License 2.0
from Open-MBEE
public void getStreamContent(OutputStream os) {
try {
StreamUtils.copy(new ByteArrayInputStream(this.json), os);
} catch (IOException e) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to copy content to output stream:" + System.lineSeparator() + "accessor: " + this, e);
}
}
}
17
Source : UnpackJar.java
with Apache License 2.0
from open-hand
with Apache License 2.0
from open-hand
/**
* 从jar包输入流解压需要的文件到目标目录
*
* @param inputStream jar包输入流
* @param dir 目标目录
* @param dep 是否是Spring Boot依赖包的解压, 只有为false时
* @throws IOException 出现IO错误
*/
private void extraJarStream(InputStream inputStream, String dir, boolean dep, boolean jarInit) throws IOException {
JarEntry entry = null;
JarInputStream jarInputStream = new JarInputStream(inputStream);
while ((entry = jarInputStream.getNextJarEntry()) != null) {
String name = entry.getName();
if (((name.endsWith(SUFFIX_GROOVY) || name.endsWith(SUFFIX_XML) || name.endsWith(SUFFIX_XLSX) || name.endsWith(SUFFIX_SQL)) && name.contains(PREFIX_SCRIPT_DB))) {
if (name.startsWith(PREFIX_SPRING_BOOT_CLreplacedES)) {
name = name.substring(PREFIX_SPRING_BOOT_CLreplacedES.length());
}
File file = new File(dir + name);
if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
throw new IOException("create dir fail: " + file.getParentFile().getAbsolutePath());
}
try (FileOutputStream outputStream = new FileOutputStream(file)) {
StreamUtils.copy(jarInputStream, outputStream);
}
} else if (name.endsWith(SUFFIX_JAR) && jarInit) {
extraJarStream(jarInputStream, dir, true, true);
}
}
}
17
Source : StringHttpMessageConverter.java
with MIT License
from mindcarver
with MIT License
from mindcarver
@Override
protected void writeInternal(String str, HttpOutputMessage outputMessage) throws IOException {
if (this.writeAcceptCharset) {
outputMessage.getHeaders().setAcceptCharset(getAcceptedCharsets());
}
Charset charset = getContentTypeCharset(outputMessage.getHeaders().getContentType());
StreamUtils.copy(str, charset, outputMessage.getBody());
}
17
Source : URLBootstrap.java
with Apache License 2.0
from mercyblitz
with Apache License 2.0
from mercyblitz
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);
}
}
17
Source : ResourceHttpRequestHandler.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
/**
* Write the actual content out to the given servlet response,
* streaming the resource's content.
* @param response current servlet response
* @param resource the identified resource (never {@code null})
* @throws IOException in case of errors while writing the content
*/
protected void writeContent(HttpServletResponse response, Resource resource) throws IOException {
try {
InputStream in = resource.getInputStream();
try {
StreamUtils.copy(in, response.getOutputStream());
} catch (NullPointerException ex) {
// ignore, see SPR-13620
} finally {
try {
in.close();
} catch (Throwable ex) {
// ignore, see SPR-12999
}
}
} catch (FileNotFoundException ex) {
// ignore, see SPR-12999
}
}
17
Source : TRImageUtil.java
with Apache License 2.0
from ijazfx
with Apache License 2.0
from ijazfx
public static void compressImage(InputStream sourceStream, File targetFile) {
boolean compressed = false;
try {
String mimeType = TRFileContentUtil.getMimeType(targetFile.getName());
if (mimeType != null) {
Iterator<ImageWriter> writers = ImageIO.getImageWritersByMIMEType(mimeType);
if (writers.hasNext()) {
ImageWriter writer = writers.next();
FileOutputStream targetStream = new FileOutputStream(targetFile);
compressImage(sourceStream, targetStream, writer);
compressed = true;
}
}
} catch (Exception ex) {
L.warn("Compression Failed:", ex);
}
if (!compressed) {
try {
StreamUtils.copy(sourceStream, new FileOutputStream(targetFile));
} catch (IOException ex) {
L.warn("Compression Failed:", ex);
}
}
}
17
Source : TRImageUtil.java
with Apache License 2.0
from ijazfx
with Apache License 2.0
from ijazfx
public static void compressImage(File sourceFile, OutputStream targetStream) {
boolean compressed = false;
try {
String mimeType = TRFileContentUtil.getMimeType(sourceFile.getName());
if (mimeType != null) {
Iterator<ImageWriter> writers = ImageIO.getImageWritersByMIMEType(mimeType);
if (writers.hasNext()) {
ImageWriter writer = writers.next();
FileInputStream sourceStream = new FileInputStream(sourceFile);
compressImage(sourceStream, targetStream, writer);
compressed = true;
}
}
} catch (Exception ex) {
L.warn("Compression Failed:", ex);
}
if (!compressed) {
try {
StreamUtils.copy(new FileInputStream(sourceFile), targetStream);
} catch (IOException ex) {
L.warn("Compression Failed:", ex);
}
}
}
17
Source : WxHttpInputMessageConverter.java
with Apache License 2.0
from FastBootWeixin
with Apache License 2.0
from FastBootWeixin
@Override
protected void writeInternal(HttpInputMessage httpInputMessage, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
StreamUtils.copy(httpInputMessage.getBody(), outputMessage.getBody());
}
17
Source : InboxController.java
with Apache License 2.0
from adorsys
with Apache License 2.0
from adorsys
/**
* Sends file to multiple users' INBOX.
*/
@SneakyThrows
@PutMapping(value = "/inbox/doreplacedent/{path:.*}", consumes = MULTIPART_FORM_DATA_VALUE)
@ApiOperation("Send doreplacedent to inbox")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Doreplacedent was successfully sent"), @ApiResponse(code = 403, message = "Access denied") })
public void writeToInbox(@RequestHeader Set<String> users, @PathVariable String path, @RequestParam("file") MultipartFile file) {
Set<UserID> toUsers = users.stream().map(UserID::new).collect(Collectors.toSet());
try (OutputStream os = dataSafeService.inboxService().write(WriteRequest.forDefaultPublic(toUsers, path));
InputStream is = file.getInputStream()) {
StreamUtils.copy(is, os);
}
log.debug("Users {}, write to INBOX file: {}", toUsers, path);
}
17
Source : DocumentController.java
with Apache License 2.0
from adorsys
with Apache License 2.0
from adorsys
/**
* Writes file to user's private space.
*/
@SneakyThrows
@PutMapping(value = "/doreplacedent/{path:.*}", consumes = MULTIPART_FORM_DATA_VALUE)
@ApiOperation("Write doreplacedent to user's private space")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Doreplacedent was successfully written") })
public void writeDoreplacedent(@RequestHeader String user, @RequestHeader String preplacedword, @RequestHeader(defaultValue = StorageIdentifier.DEFAULT_ID) String storageId, @PathVariable String path, @RequestParam("file") MultipartFile file) {
UserIDAuth userIDAuth = new UserIDAuth(new UserID(user), ReadKeyPreplacedwordHelper.getForString(preplacedword));
WriteRequest<UserIDAuth, PrivateResource> request = WriteRequest.forPrivate(userIDAuth, new StorageIdentifier(storageId), path);
try (OutputStream os = datasafeService.privateService().write(request);
InputStream is = file.getInputStream()) {
StreamUtils.copy(is, os);
}
log.debug("User: {}, write private file to: {}", user, path);
}
16
Source : ExampleServlet.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
@Override
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
String content = "Hello World";
if (this.ecreplacedquestInfo) {
content += " scheme=" + request.getScheme();
content += " remoteaddr=" + request.getRemoteAddr();
}
if (this.writeWithoutContentLength) {
response.setContentType("text/plain");
ServletOutputStream outputStream = response.getOutputStream();
StreamUtils.copy(content.getBytes(), outputStream);
outputStream.flush();
} else {
response.getWriter().write(content);
}
}
16
Source : AbstractHttpRequestFactoryTestCase.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Test(expected = IllegalStateException.clreplaced)
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());
}
16
Source : PathResolver.java
with Apache License 2.0
from spring-projects-experimental
with Apache License 2.0
from spring-projects-experimental
private void maybeCopyToRoot(String root, File repo, List<Dependency> clreplacedPathArchives) {
if (root == null || !this.preferLocalSnapshots) {
return;
}
// Otherwise copy any locally installed snapshots with the same version to the
// root
File dir = new File(root, "repository");
if (!dir.exists() && !dir.mkdirs() || !dir.isDirectory()) {
throw new IllegalStateException("Cannot create root directory: " + root);
}
try {
String parent = dir.getCanonicalPath();
for (Dependency archive : clreplacedPathArchives) {
if (!archive.getArtifact().isSnapshot()) {
continue;
}
File file = archive.getArtifact().getFile();
String path = file.getCanonicalPath();
if (!path.endsWith(".jar")) {
continue;
}
if (!path.startsWith(parent)) {
throw new IllegalStateException("Not in thin root repository: " + path);
}
String jar = path.substring(parent.length());
File source = new File(repo, jar);
File target = file;
if (source.exists() && !FileUtils.contentEquals(source, target)) {
log.info("Preferring local snapshot: " + archive);
FileUtils.deleteDirectory(target.getParentFile());
target.getParentFile().mkdirs();
StreamUtils.copy(new FileInputStream(source), new FileOutputStream(target));
String pom = jar.substring(0, jar.length() - 4) + ".pom";
file = new File(repo, pom);
if (file.exists()) {
StreamUtils.copy(new FileInputStream(file), new FileOutputStream(new File(dir, pom)));
}
}
}
} catch (Exception e) {
throw new IllegalStateException("Cannot copy jar files", e);
}
}
16
Source : PackageMetadataService.java
with Apache License 2.0
from spring-cloud
with Apache License 2.0
from spring-cloud
/**
* Download package metadata from all repositories.
* @return A list of package metadata, not yet persisted in the PackageMetadataRepository.
*/
@Transactional
public List<PackageMetadata> downloadPackageMetadata() {
List<PackageMetadata> finalMetadataList = new ArrayList<>();
Path targetPath = null;
try {
targetPath = TempFileUtils.createTempDirectory("skipperIndex");
for (Repository packageRepository : this.repositoryRepository.findAll()) {
try {
if (!packageRepository.isLocal()) {
Resource resource = resourceLoader.getResource(packageRepository.getUrl() + "/index.yml");
if (resource.exists()) {
logger.info("Downloading package metadata from " + resource);
File downloadedFile = new File(targetPath.toFile(), computeFilename(resource));
StreamUtils.copy(resource.getInputStream(), new FileOutputStream(downloadedFile));
List<File> downloadedFileAsList = new ArrayList<>();
downloadedFileAsList.add(downloadedFile);
List<PackageMetadata> downloadedPackageMetadata = deserializeFromIndexFiles(downloadedFileAsList);
for (PackageMetadata packageMetadata : downloadedPackageMetadata) {
packageMetadata.setRepositoryId(packageRepository.getId());
packageMetadata.setRepositoryName(packageRepository.getName());
}
finalMetadataList.addAll(downloadedPackageMetadata);
} else {
logger.info("Package metadata index resource does not exist: " + resource.getDescription());
}
}
} catch (Exception e) {
logger.warn("Could not process package file from " + packageRepository.getName(), e.getMessage());
}
}
} finally {
if (targetPath != null && !FileSystemUtils.deleteRecursively(targetPath.toFile())) {
logger.warn("Temporary directory can not be deleted: " + targetPath);
}
}
return finalMetadataList;
}
16
Source : BigQueryTemplate.java
with Apache License 2.0
from spring-cloud
with Apache License 2.0
from spring-cloud
@Override
public ListenableFuture<Job> writeDataToTable(String tableName, InputStream inputStream, FormatOptions dataFormatOptions, Schema schema) {
TableId tableId = TableId.of(datasetName, tableName);
WriteChannelConfiguration.Builder writeChannelConfiguration = WriteChannelConfiguration.newBuilder(tableId).setFormatOptions(dataFormatOptions).setWriteDisposition(this.writeDisposition).setAutodetect(this.autoDetectSchema);
if (schema != null) {
writeChannelConfiguration.setSchema(schema);
}
TableDataWriteChannel writer = bigQuery.writer(writeChannelConfiguration.build());
try (OutputStream sink = Channels.newOutputStream(writer)) {
// Write data from data input file to BigQuery
StreamUtils.copy(inputStream, sink);
} catch (IOException e) {
throw new BigQueryException("Failed to write data to BigQuery tables.", e);
}
if (writer.getJob() == null) {
throw new BigQueryException("Failed to initialize the BigQuery write job.");
}
return createJobFuture(writer.getJob());
}
16
Source : AbstractAsyncHttpRequestFactoryTests.java
with Apache License 2.0
from SourceHot
with Apache License 2.0
from SourceHot
@Test
public void multipleWrites() throws Exception {
AsyncClientHttpRequest request = this.factory.createAsyncRequest(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));
} else {
StreamUtils.copy(body, request.getBody());
}
Future<ClientHttpResponse> futureResponse = request.executeAsync();
ClientHttpResponse response = futureResponse.get();
try {
replacedertThatIllegalStateException().isThrownBy(() -> FileCopyUtils.copy(body, request.getBody()));
} finally {
response.close();
}
}
16
Source : ExtensionFormHttpMessageConverter.java
with Apache License 2.0
from NotFound403
with Apache License 2.0
from NotFound403
/**
* Write form.
*
* @param formData the form data
* @param contentType the content type
* @param outputMessage the output message
* @throws IOException the io exception
*/
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();
// should never occur
replacedert.notNull(charset, "No charset");
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());
}
}
16
Source : AbstractHttpRequestFactoryTestCase.java
with Apache License 2.0
from langtianya
with Apache License 2.0
from langtianya
@Test(expected = IllegalStateException.clreplaced)
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(new StreamingHttpOutputMessage.Body() {
@Override
public void writeTo(OutputStream outputStream) throws IOException {
StreamUtils.copy(body, outputStream);
}
});
} else {
StreamUtils.copy(body, request.getBody());
}
ClientHttpResponse response = request.execute();
try {
FileCopyUtils.copy(body, request.getBody());
} finally {
response.close();
}
}
16
Source : VersionController.java
with Apache License 2.0
from adorsys
with Apache License 2.0
from adorsys
/**
* writes latest version of file to user's private space.
*/
@SneakyThrows
@PutMapping(value = "/versioned/{path:.*}", consumes = MULTIPART_FORM_DATA_VALUE)
@ApiOperation("Write latest doreplacedent to user's private space")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Doreplacedent was successfully written") })
public void writeVersionedDoreplacedent(@RequestHeader String user, @RequestHeader String preplacedword, @RequestHeader(defaultValue = StorageIdentifier.DEFAULT_ID) String storageId, @PathVariable String path, @RequestParam("file") MultipartFile file) {
UserIDAuth userIDAuth = new UserIDAuth(new UserID(user), ReadKeyPreplacedwordHelper.getForString(preplacedword));
WriteRequest<UserIDAuth, PrivateResource> request = WriteRequest.forPrivate(userIDAuth, new StorageIdentifier(storageId), path);
try (OutputStream os = versionedDatasafeServices.latestPrivate().write(request);
InputStream is = file.getInputStream()) {
StreamUtils.copy(is, os);
}
log.debug("User: {}, write private file to: {}", user, path);
}
15
Source : RestartClassLoaderTests.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
private File createSampleJarFile() throws IOException {
File file = this.temp.newFile("sample.jar");
JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(file));
jarOutputStream.putNextEntry(new ZipEntry(PACKAGE_PATH + "/Sample.clreplaced"));
StreamUtils.copy(getClreplaced().getResourcereplacedtream("Sample.clreplaced"), jarOutputStream);
jarOutputStream.closeEntry();
jarOutputStream.putNextEntry(new ZipEntry(PACKAGE_PATH + "/Sample.txt"));
StreamUtils.copy("fromchild", StandardCharsets.UTF_8, jarOutputStream);
jarOutputStream.closeEntry();
jarOutputStream.close();
return file;
}
15
Source : MultipartMixedConverter.java
with Apache License 2.0
from xm-online
with Apache License 2.0
from xm-online
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.defaultCharset;
} else {
outputMessage.getHeaders().setContentType(MediaType.APPLICATION_FORM_URLENCODED);
charset = this.defaultCharset;
}
StringBuilder builder = new StringBuilder();
buildByNames(form, charset, builder);
final byte[] bytes = builder.toString().getBytes(charset.name());
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());
}
}
15
Source : AbstractAsyncHttpRequestFactoryTestCase.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Test
public void echo() throws Exception {
AsyncClientHttpRequest request = this.factory.createAsyncRequest(new URI(baseUrl + "/echo"), HttpMethod.PUT);
replacedertEquals("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 {
replacedertEquals("Invalid status code", HttpStatus.OK, response.getStatusCode());
replacedertTrue("Header not found", response.getHeaders().containsKey(headerName));
replacedertEquals("Header value not found", Arrays.asList(headerValue1, headerValue2), response.getHeaders().get(headerName));
byte[] result = FileCopyUtils.copyToByteArray(response.getBody());
replacedertTrue("Invalid body", Arrays.equals(body, result));
} finally {
response.close();
}
}
15
Source : FormHttpMessageConverter.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
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();
// should never occur
replacedert.notNull(charset, "No charset");
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());
}
}
15
Source : ByteArrayHttpMessageConverter.java
with MIT License
from Vip-Augus
with MIT License
from Vip-Augus
@Override
public byte[] readInternal(Clreplaced<? extends byte[]> clazz, HttpInputMessage inputMessage) throws IOException {
long contentLength = inputMessage.getHeaders().getContentLength();
ByteArrayOutputStream bos = new ByteArrayOutputStream(contentLength >= 0 ? (int) contentLength : StreamUtils.BUFFER_SIZE);
StreamUtils.copy(inputMessage.getBody(), bos);
return bos.toByteArray();
}
15
Source : AbstractHttpRequestFactoryTests.java
with Apache License 2.0
from SourceHot
with Apache License 2.0
from SourceHot
@Test
public void multipleWrites() throws Exception {
ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.POST);
final byte[] body = "Hello World".getBytes(StandardCharsets.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();
replacedertThatIllegalStateException().isThrownBy(() -> FileCopyUtils.copy(body, request.getBody()));
}
15
Source : FormHttpMessageConverter.java
with Apache License 2.0
from SourceHot
with Apache License 2.0
from SourceHot
private void writeForm(MultiValueMap<String, Object> formData, @Nullable MediaType contentType, HttpOutputMessage outputMessage) throws IOException {
contentType = getFormContentType(contentType);
outputMessage.getHeaders().setContentType(contentType);
Charset charset = contentType.getCharset();
// should never occur
replacedert.notNull(charset, "No charset");
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());
}
}
15
Source : FullScanDataToZipOutputSupport.java
with MIT License
from Daimler
with MIT License
from Daimler
private void writeStringAsZipFileEntry(ZipOutputStream zippedOut, String string, String wantedFileName, List<String> fileNamesAlreadyUsed) throws UnsupportedEncodingException, IOException {
/* prevent duplicated filenames*/
String fileName = wantedFileName;
int index = 0;
while (fileNamesAlreadyUsed.contains(fileName)) {
index++;
fileName = wantedFileName + "[" + index + "]";
}
fileNamesAlreadyUsed.add(fileName);
String fileEnding = "txt";
if (string.startsWith("{")) {
fileEnding = "json";
} else if (string.startsWith("<")) {
fileEnding = "xml";
}
byte[] asArray = string.getBytes("UTF-8");
ByteArrayInputStream bais = new ByteArrayInputStream(asArray);
ZipEntry e = new ZipEntry(fileName + "." + fileEnding);
e.setSize(asArray.length);
e.setTime(System.currentTimeMillis());
zippedOut.putNextEntry(e);
StreamUtils.copy(bais, zippedOut);
}
15
Source : DocumentController.java
with Apache License 2.0
from adorsys
with Apache License 2.0
from adorsys
/**
* Reads user's private file.
*/
@SneakyThrows
@GetMapping(value = "/doreplacedent/{path:.*}", produces = APPLICATION_OCTET_STREAM_VALUE)
@ApiOperation("Read doreplacedent from user's private space")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Doreplacedent was successfully read"), @ApiResponse(code = 401, message = "Doreplacedent not found") })
public void readDoreplacedent(@RequestHeader String user, @RequestHeader String preplacedword, @RequestHeader(defaultValue = StorageIdentifier.DEFAULT_ID) String storageId, @PathVariable String path, HttpServletResponse response) {
UserIDAuth userIDAuth = new UserIDAuth(new UserID(user), ReadKeyPreplacedwordHelper.getForString(preplacedword));
ReadRequest<UserIDAuth, PrivateResource> request = ReadRequest.forPrivate(userIDAuth, new StorageIdentifier(storageId), path);
// this is needed for swagger, produces is just a directive:
response.addHeader(CONTENT_TYPE, APPLICATION_OCTET_STREAM_VALUE);
try (InputStream is = datasafeService.privateService().read(request);
OutputStream os = response.getOutputStream()) {
StreamUtils.copy(is, os);
}
log.debug("User: {}, read private file from: {}", user, preplacedword);
}
14
Source : JarFileRemoteApplicationLauncher.java
with Apache License 2.0
from yuanmabiji
with Apache License 2.0
from yuanmabiji
private void addToJar(JarOutputStream output, File root, File current) throws IOException {
for (File file : current.listFiles()) {
if (file.isDirectory()) {
addToJar(output, root, file);
}
output.putNextEntry(new ZipEntry(file.getAbsolutePath().substring(root.getAbsolutePath().length() + 1).replace("\\", "/") + (file.isDirectory() ? "/" : "")));
if (file.isFile()) {
try (FileInputStream input = new FileInputStream(file)) {
StreamUtils.copy(input, output);
}
}
output.closeEntry();
}
}
14
Source : RequestLogFilter.java
with Apache License 2.0
from wengwh
with Apache License 2.0
from wengwh
private void updateResponse(String requestUri, ContentCachingResponseWrapper responseWrapper) {
try {
HttpServletResponse rawResponse = (HttpServletResponse) responseWrapper.getResponse();
byte[] body = responseWrapper.getContentAsByteArray();
ServletOutputStream outputStream = rawResponse.getOutputStream();
if (rawResponse.isCommitted()) {
if (body.length > 0) {
StreamUtils.copy(body, outputStream);
}
} else {
if (body.length > 0) {
rawResponse.setContentLength(body.length);
StreamUtils.copy(body, rawResponse.getOutputStream());
}
}
finishResponse(outputStream, body);
} catch (Exception ex) {
log.error("请求地址为" + requestUri + "的连接返回报文失败,原因是{}", ex.getMessage());
}
}
See More Examples