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:org.apache.eagle.alert.engine.utils.CompressionUtils.java

public static byte[] compress(byte[] source) throws IOException {
    if (source == null || source.length == 0) {
        return source;
    }/*from   www .  ja va 2 s  .c o  m*/
    ByteArrayInputStream sourceStream = new ByteArrayInputStream(source);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream(source.length / 2);
    try (OutputStream compressor = new GZIPOutputStream(outputStream)) {
        ByteStreams.copy(sourceStream, compressor);
        compressor.close();
    }
    try {
        return outputStream.toByteArray();
    } finally {
        sourceStream.close();
        outputStream.close();
    }
}

From source file:org.haiku.haikudepotserver.support.FileHelper.java

/**
 * <p>This method will stream the data from the supplied URL into the file.  If it is a suitable
 * URL (http / https) then it is possible to provide a timeout and that will be observed when
 * connecting and retreiving data.</p>
 *///ww w . jav a  2  s . c o  m

public static void streamUrlDataToFile(URL url, File file, long timeoutMillis) throws IOException {
    switch (url.getProtocol()) {

    case "http":
    case "https":
        HttpURLConnection connection = null;

        try {
            connection = (HttpURLConnection) url.openConnection();

            connection.setConnectTimeout((int) timeoutMillis);
            connection.setReadTimeout((int) timeoutMillis);
            connection.setRequestMethod(HttpMethod.GET.name());
            connection.connect();

            int responseCode = connection.getResponseCode();

            if (responseCode == HttpStatus.OK.value()) {
                try (InputStream inputStream = connection.getInputStream();
                        OutputStream outputStream = new FileOutputStream(file)) {
                    ByteStreams.copy(inputStream, outputStream);
                }
            } else {
                throw new IOException("url request returned " + responseCode);
            }

        } finally {
            if (null != connection) {
                connection.disconnect();
            }
        }
        break;

    case "file":
        Files.copy(new File(url.getFile()), file);
        break;

    default:
        throw new IllegalStateException("the url scheme of " + url.getProtocol() + " is unsupported.");

    }

}

From source file:org.sonatype.nexus.common.hash.Hashes.java

/**
 * Computes the hash of the given stream using the given algorithm.
 *//*from w w w .  j a  v a 2  s  . co  m*/
public static HashCode hash(final HashAlgorithm algorithm, final InputStream inputStream) throws IOException {
    checkNotNull(algorithm);
    checkNotNull(inputStream);

    try (HashingInputStream hashingStream = new HashingInputStream(algorithm.function(), inputStream)) {
        ByteStreams.copy(hashingStream, ByteStreams.nullOutputStream());
        return hashingStream.hash();
    }
}

From source file:org.caleydo.core.view.opengl.layout2.internal.SandBoxLibraryLoader.java

/**
 * extract the given library of the classpath and put it to a temporary file
 *///from ww  w  .j  a v a  2 s . c  o  m
public static File toTemporaryFile(String libName) throws IOException {
    // convert to native library name
    libName = System.mapLibraryName(libName);
    if (SystemUtils.IS_OS_MAC_OSX)
        libName = StringUtils.replace(libName, ".dylib", ".jnilib");

    // create
    String extension = Files.getFileExtension(libName);
    File file = File.createTempFile(StringUtils.removeEnd(libName, extension), "." + extension);
    file.deleteOnExit();

    URL res = SandBoxLibraryLoader.class.getResource("/" + libName);
    if (res == null)
        throw new FileNotFoundException("can't extract: " + libName);
    try (InputStream in = res.openStream();
            OutputStream to = new BufferedOutputStream(new FileOutputStream(file))) {
        ByteStreams.copy(in, to);
    } catch (IOException e) {
        System.err.println("can't extract: " + libName);
        e.printStackTrace();
        throw new FileNotFoundException("can't extract: " + libName);
    }
    return file;
}

From source file:org.jclouds.vagrant.util.VagrantUtils.java

public static void write(File file, InputStream in) throws IOException {
    OutputStream out = new FileOutputStream(file);
    try {/*from  w  w w .ja  v a  2  s .  c  o  m*/
        ByteStreams.copy(in, out);
    } finally {
        Closeables2.closeQuietly(out);
        Closeables2.closeQuietly(in);
    }
}

From source file:com.docdoku.server.rest.file.util.BinaryResourceUpload.java

/**
 * Upload a form file in a specific output
 * @param outputStream BinaryResource output stream (in server vault repository)
 * @param formPart The form part list//w  ww .  j a  v a2 s.  com
 * @return The length of the file uploaded
 */
public static long uploadBinary(OutputStream outputStream, Part formPart) throws IOException {
    long length;
    try (InputStream in = formPart.getInputStream(); OutputStream out = outputStream) {
        length = ByteStreams.copy(in, out);
    }
    return length;
}

From source file:com.palantir.giraffe.file.base.CrossSystemTransfers.java

public static void copyFile(Path source, Path target, CopyFlags flags) throws IOException {
    checkPaths(source, target, flags);//from w  ww .  j a va2 s  . c  om

    try (ReadableByteChannel sourceChannel = openSourceChannel(source);
            WritableByteChannel targetChannel = openTargetChannel(target, flags)) {
        ByteStreams.copy(sourceChannel, targetChannel);
    }

    if (flags.copyAttributes) {
        LinkOption[] options = LinkOptions.toArray(flags.followLinks);
        PosixFileAttributeViews.copyAttributes(source, target, options);
    }
}

From source file:com.netflix.servo.example.EchoHandler.java

protected void handleImpl(HttpExchange exchange) throws IOException {
    exchange.sendResponseHeaders(200, 0);
    ByteStreams.copy(exchange.getRequestBody(), exchange.getResponseBody());
    exchange.close();//  w w  w .  j a  va 2s.c om
}

From source file:nbm.center.App.java

private static File extractDefaultConfiguration() throws IOException {
    InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("default.yml");
    File tempConfigFile = File.createTempFile("default", ".yml");
    tempConfigFile.deleteOnExit();/*w w w.j  a v  a  2s.c  om*/
    FileOutputStream output = new FileOutputStream(tempConfigFile);
    try {
        ByteStreams.copy(input, output);
    } finally {
        output.close();
    }
    return tempConfigFile;
}

From source file:com.cloudbees.clickstack.util.HttpUtils.java

/**
 * Save the content of the given {@code url} to the given {@code destFile}.
 *
 * @param url/*from ww  w. j a  v  a  2  s .c o  m*/
 * @param destFile
 * @throws RuntimeIOException
 */
public static void get(@Nonnull URL url, @Nonnull Path destFile) throws RuntimeIOException {
    try {
        HttpURLConnection cnn = (HttpURLConnection) url.openConnection();
        int responseCode = cnn.getResponseCode();
        Preconditions.checkState(responseCode == HttpURLConnection.HTTP_OK,
                "Unexpected response code {}for {}", responseCode, url);
        InputStream in = cnn.getInputStream();
        OutputStream out = Files.newOutputStream(destFile);
        long length = ByteStreams.copy(in, out);
        logger.debug("Copied {} in {}: {}bytes", url, destFile, length);
    } catch (IOException e) {
        throw new RuntimeIOException("Exception downloading the content of '" + url + "' to '" + destFile + "'",
                e);
    }
}