Example usage for com.google.common.io ByteStreams copy

List of usage examples for com.google.common.io ByteStreams copy

Introduction

In this page you can find the example usage for com.google.common.io ByteStreams copy.

Prototype

public static long copy(ReadableByteChannel from, WritableByteChannel to) throws IOException 

Source Link

Document

Copies all bytes from the readable channel to the writable channel.

Usage

From source file:com.google.devtools.build.android.ResourcesZip.java

/** Creates a ResourcesZip from an archive by expanding into the workingDirectory. */
public static ResourcesZip createFrom(Path resourcesZip, Path workingDirectory) throws IOException {
    // Expand resource files zip into working directory.
    final ZipFile zipFile = new ZipFile(resourcesZip.toFile());

    zipFile.stream().filter(not(ZipEntry::isDirectory)).forEach(entry -> {
        Path output = workingDirectory.resolve(entry.getName());
        try {/*  w  ww.  j  a  v a 2  s  .c  o m*/
            Files.createDirectories(output.getParent());
            try (FileOutputStream fos = new FileOutputStream(output.toFile())) {
                ByteStreams.copy(zipFile.getInputStream(entry), fos);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });
    return from(Files.createDirectories(workingDirectory.resolve("res")),
            Files.createDirectories(workingDirectory.resolve("assets")), workingDirectory.resolve("ids.txt"));
}

From source file:com.facebook.buck.artifact_cache.ThriftArtifactCacheProtocol.java

private static String computeHash(ByteSource source, HashFunction hashFunction) throws IOException {
    try (InputStream inputStream = source.openStream();
            HashingOutputStream outputStream = new HashingOutputStream(hashFunction, new OutputStream() {
                @Override// ww w  . j  a  va  2s. c om
                public void write(int b) throws IOException {
                    // Do nothing.
                }
            })) {
        ByteStreams.copy(inputStream, outputStream);
        return outputStream.hash().toString();
    }
}

From source file:com.epam.ta.reportportal.commons.exception.forwarding.ClientResponseForwardingExceptionHandler.java

@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
        Exception ex) {/*  ww  w . ja v a 2s .c o m*/
    /* just forward upstream */
    if (ResponseForwardingException.class.isAssignableFrom(ex.getClass())) {
        ResponseForwardingException forwardingException = ((ResponseForwardingException) ex);
        try (ByteArrayInputStream dataStream = new ByteArrayInputStream(forwardingException.getBody())) {

            //copy status
            response.setStatus(forwardingException.getStatus().value());

            //copy headers
            response.setContentType(forwardingException.getHeaders().getContentType().toString());

            //copy body
            ByteStreams.copy(dataStream, response.getOutputStream());

            // return empty model and view to short circuit the
            // iteration and to let
            // Spring know that we've rendered the view ourselves:
            return new ModelAndView();

        } catch (IOException e) {
            LOGGER.error("Cannot forward exception", e);
            return null;
        }
    }

    return null;
}

From source file:com.hortonworks.streamline.common.util.HdfsFileStorage.java

@Override
public String uploadFile(InputStream inputStream, String name) throws IOException {
    Path jarPath = new Path(directory, name);

    try (FSDataOutputStream outputStream = hdfsFileSystem.create(jarPath, false)) {
        ByteStreams.copy(inputStream, outputStream);
    }/*  w w  w  . j a  v  a  2 s. com*/

    return jarPath.toString();
}

From source file:de.uniulm.omi.cloudiator.sword.remote.overthere.OverthereWinRMConnection.java

@Override
public File downloadFile(String path) throws RemoteException {
    OverthereFile overthereFile = this.delegate.getFile(path);
    //todo refactor, is duplicate of unix logic.
    try {//from w  ww . ja  v  a  2 s .c  om
        File tempFile = File.createTempFile("sword.overthere", "tmp");
        tempFile.deleteOnExit();
        ByteStreams.copy(overthereFile.getInputStream(), new FileOutputStream(tempFile));
        return tempFile;
    } catch (IOException e) {
        throw new RemoteException(e);
    }
}

From source file:de.dentrassi.pm.storage.service.util.DownloadHelper.java

public static void streamArtifact(final HttpServletResponse response, final Artifact artifact,
        final String mimetype, final boolean download, final Function<ArtifactInformation, String> nameProvider)
        throws IOException {
    artifact.streamData((info, stream) -> {

        String mt = mimetype;/*from   w ww .  j av  a2s.co  m*/
        if (mt == null) {
            mt = getMimeType(artifact);
        }

        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType(mt);
        response.setDateHeader("Last-Modified", info.getCreationTimestamp().getTime());

        try {
            response.setContentLengthLong(info.getSize());
            if (download) {
                response.setHeader("Content-Disposition",
                        String.format("attachment; filename=%s", info.getName()));
            }
            final long size = ByteStreams.copy(stream, response.getOutputStream());
            logger.debug("Copyied {} bytes", size);
        } catch (final Exception e) {
            throw new RuntimeException(e);
        }
    });
}

From source file:io.kubernetes.client.util.WebSocketStreamHandler.java

@Override
public void textMessage(Reader in) {
    try {// ww w  .  j  av a2  s.  c  om
        OutputStream out = getSocketInputOutputStream(in.read());
        InputStream inStream = new ByteArrayInputStream(CharStreams.toString(in).getBytes(Charsets.UTF_8));
        ByteStreams.copy(inStream, out);
    } catch (IOException ex) {
        log.error("Error writing message", ex);
    }
}

From source file:org.richfaces.cdk.resource.writer.impl.JavaScriptPackagingProcessor.java

@Override
public void process(String resourceName, InputStream in, OutputStream out, boolean closeAtFinish)
        throws IOException {

    Reader reader = null;//from  www.j a  v  a 2  s  .  c om
    Writer writer = null;

    try {
        reader = new InputStreamReader(in, charset);
        writer = new OutputStreamWriter(out, charset);

        ByteStreams.copy(in, out);
        if (!closeAtFinish) {
            // add semicolon to satisfy end of context of each script when packing files
            writer.write(";");
            writer.flush();
        }
    } finally {
        Closeables.closeQuietly(reader);
        if (closeAtFinish) {
            Closeables.closeQuietly(writer);
        } else {
            writer.flush();
        }
    }
}

From source file:at.pcgamingfreaks.MarriageMaster.Bungee.Database.Language.java

private void ExtractLangFile(File file) {
    try {//  ww w  . j  av  a 2  s  .c  o  m
        if (file.exists()) {
            file.delete();
        }
        file.createNewFile();
        try (InputStream is = plugin.getResourceAsStream("Lang/bungee_" + plugin.config.getLanguage() + ".yml");
                OutputStream os = new FileOutputStream(file)) {
            ByteStreams.copy(is, os);
        } catch (Exception e) {
            try (InputStream is = plugin.getResourceAsStream("Lang/bungee_en.yml");
                    OutputStream os = new FileOutputStream(file)) {
                ByteStreams.copy(is, os);
            }
        }
        plugin.log.info("Lang extracted successfully!");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.google.devtools.build.lib.server.RPCTestingClient.java

public ServerResponse sendRequest(String request) throws Exception {
    LocalClientSocket connection = new LocalClientSocket();
    connection.connect(new LocalSocketAddress(socketFile.getPathFile()));
    try {//from  w w w . java 2s . co m
        OutputStream out = connection.getOutputStream();
        out.write(request.getBytes(UTF_8));
        out.flush();
        connection.shutdownOutput();

        OutputStream stdout = outErr.getOutputStream();
        OutputStream stderr = outErr.getErrorStream();
        ByteArrayOutputStream control = new ByteArrayOutputStream();
        StreamDemultiplexer demux = new StreamDemultiplexer((byte) '1', stdout, stderr, control);
        ByteStreams.copy(connection.getInputStream(), demux);
        demux.flush();

        return ServerResponse.parseFrom(control);
    } finally {
        connection.close();
    }
}