Example usage for com.google.common.io ByteSource openBufferedStream

List of usage examples for com.google.common.io ByteSource openBufferedStream

Introduction

In this page you can find the example usage for com.google.common.io ByteSource openBufferedStream.

Prototype

public InputStream openBufferedStream() throws IOException 

Source Link

Document

Opens a new buffered InputStream for reading from this source.

Usage

From source file:com.google.devtools.build.lib.vfs.FileSystemUtils.java

/**
 * Reads at most {@code limit} bytes from {@code inputFile} and returns it as a byte array.
 *
 * @throws IOException if there was an error.
 */// w w w .  java2  s  .c  o m
public static byte[] readContentWithLimit(Path inputFile, int limit) throws IOException {
    Preconditions.checkArgument(limit >= 0, "limit needs to be >=0, but it is %s", limit);
    ByteSource byteSource = asByteSource(inputFile);
    byte[] buffer = new byte[limit];
    try (InputStream inputStream = byteSource.openBufferedStream()) {
        int read = ByteStreams.read(inputStream, buffer, 0, limit);
        return read == limit ? buffer : Arrays.copyOf(buffer, read);
    }
}

From source file:org.asoem.greyfish.utils.persistence.JavaPersister.java

private <T> T deserialize(final ByteSource byteSource, final Class<T> clazz)
        throws IOException, ClassNotFoundException {
    final InputStream input = byteSource.openBufferedStream();
    boolean threw = true;
    try {/* w  ww.j  a  va2s . com*/
        final T object = deserialize(input, clazz);
        threw = false;
        return object;
    } finally {
        Closeables.close(input, threw);
    }
}

From source file:com.zxy.commons.hystrix.web.HystrixInitializer.java

/**
 * webspringproperties??/*w ww .  ja v  a  2s  .  c om*/
 * 
 * @return Properties
*/
private Properties load() {
    Properties properties = new Properties();
    InputStream inputStream = null;
    try {
        final URL url = Resources.getResource("hystrix.properties");
        final ByteSource byteSource = Resources.asByteSource(url);

        inputStream = byteSource.openBufferedStream();
        properties.load(inputStream);
        // properties.list(System.out);
    } catch (Exception e) {
        // do nothing
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException ioException) {
                // do nothing
            }
        }
    }
    return properties;
}

From source file:de.l3s.concatgz.io.FileBackedBytesWritable.java

@Override
public void write(DataOutput dataOutput) throws IOException {
    if (stream == null)
        return;//w  ww  .jav a  2s .  c o  m
    ByteSource bytes = stream.asByteSource();
    long size = bytes.size();
    dataOutput.writeLong(size);
    byte[] buffer = new byte[BUFFER_SIZE];
    InputStream stream = bytes.openBufferedStream();
    int read = stream.read(buffer);
    while (read != -1) {
        if (read > 0)
            dataOutput.write(buffer, 0, read);
        read = stream.read(buffer);
    }
    stream.close();
}

From source file:com.zenika.doclipser.api.DockerConfig.java

private Properties readPropertyFile(URL url) {
    final ByteSource byteSource = Resources.asByteSource(url);
    final Properties properties = new Properties();
    InputStream inputStream = null;
    try {//w ww  .ja  v  a 2s. co m
        inputStream = byteSource.openBufferedStream();
        properties.load(inputStream);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (final IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }
    return properties;
}

From source file:com.fasterxml.jackson.tools.Jackson.java

private void run() {
    ByteSource inputSource = Files.asByteSource(inputFile);
    ByteSink outputSink = Files.asByteSink(outputFile);
    InputStream input;/*from   ww  w . j a  v a  2 s .  c  o m*/
    OutputStream output;
    try {
        input = inputSource.openBufferedStream();
        output = outputSink.openBufferedStream();
        convert(input, output);
    } catch (IOException e) {
        System.err.format("Exception in conversion %s%n", e.getMessage());
        System.exit(1);
    }
}

From source file:com.zxy.commons.lang.conf.AbstractConfigProperties.java

/**
 * ?Properties/*from w w w.j  a  va  2s  .  co m*/
 * 
 * @return Properties
 * @throws IOException
 */
@SuppressWarnings("PMD.EmptyCatchBlock")
private Properties load() throws IOException {
    //      final URL url = Resources.getResource(resource);
    final URL url = getPath();
    final ByteSource byteSource = Resources.asByteSource(url);
    final Properties properties = new Properties();
    InputStream inputStream = null;
    try {
        inputStream = byteSource.openBufferedStream();
        properties.load(inputStream);
        //         properties.list(System.out);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException ioException) {
                // do nothing
            }
        }
    }
    return properties;
}

From source file:org.codice.ddf.spatial.geocoding.extract.GeoNamesFileExtractor.java

/**
 * Download a GeoNames .zip file from a remote location
 *
 * @param resource         - the name of the zip file to download ( ex. AD )
 * @param response         - the response from the get request
 * @param inputStream      - the InputStream from the web connection
 * @param progressCallback -  the callback to receive updates about the progress, may be
 *                         null if you don't want any updates
 * @throws GeoNamesRemoteDownloadException when the connection could not be established or the
 *                                         file could not be downloaded.
 *//*from  w w w.jav a2  s.co m*/
private InputStream getInputStreamFromUrl(String resource, Response response, InputStream inputStream,
        ProgressCallback progressCallback) throws GeoNamesRemoteDownloadException {
    int responseCode = 0;

    try (FileBackedOutputStream fileOutputStream = new FileBackedOutputStream(BUFFER_SIZE);) {

        responseCode = response.getStatus();

        int totalFileSize = response.getLength();

        if (inputStream == null) {
            throw new GeoNamesRemoteDownloadException(
                    "Unable to get input stream from " + url + ".  Server responded with : " + responseCode);
        }

        double totalBytesRead = 0.0;
        int bytesRead = -1;
        byte[] buffer = new byte[BUFFER_SIZE];

        while ((bytesRead = inputStream.read(buffer)) != -1) {
            fileOutputStream.write(buffer, 0, bytesRead);
            totalBytesRead += bytesRead;
            if (progressCallback != null) {
                progressCallback.updateProgress((int) ((totalBytesRead / totalFileSize) * 50));
            }
        }

        if (progressCallback != null) {
            progressCallback.updateProgress(50);
        }

        ByteSource byteSource = fileOutputStream.asByteSource();
        fileOutputStream.flush();
        inputStream.close();
        closeConnection();

        return byteSource.openBufferedStream();

    } catch (IOException e) {
        throw new GeoNamesRemoteDownloadException("Unable to download " + resource + " from " + url
                + ".  Server responded with : " + responseCode, e);
    }
}

From source file:org.codice.ddf.spatial.geocoding.extract.GeoNamesFileExtractor.java

/**
 * Unzips a file and returns the output as a new InputStream
 *
 * @param resource    - the name of the resource file to be unzipped
 * @param inputStream - the InputStream for the file to be unzipped
 * @return - the unzipped file as an InputStream
 * @throws GeoEntryExtractionException when the given file fails to be unzipped.
 *///from w w w . j  a v  a2s.com
private InputStream unZipInputStream(String resource, InputStream inputStream)
        throws GeoEntryExtractionException {
    try (FileBackedOutputStream bufferedOutputStream = new FileBackedOutputStream(BUFFER_SIZE);
            ZipInputStream zipInputStream = new ZipInputStream(inputStream);) {

        ZipEntry zipEntry;
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {

            // GeoNames <filename>.zip files will contain <filename>.txt and readme.txt
            if (!zipEntry.getName().equals("readme.txt")) {

                byte data[] = new byte[BUFFER_SIZE];
                int bytesRead;
                while ((bytesRead = zipInputStream.read(data, 0, BUFFER_SIZE)) != -1) {
                    bufferedOutputStream.write(data, 0, bytesRead);
                }

                ByteSource zipByteSource = bufferedOutputStream.asByteSource();
                bufferedOutputStream.flush();
                fileSize = zipByteSource.size();
                return zipByteSource.openBufferedStream();
            }
        }

    } catch (IOException e) {
        throw new GeoEntryExtractionException("Unable to unzip " + resource, e);
    }

    throw new GeoEntryExtractionException("Unable to unzip " + resource);
}

From source file:de.nx42.maps4cim.header.HeaderEditor.java

public void writeChanges(File dest) throws IOException {

    /*/*  ww w.  j a  v  a 2  s  .  com*/
     * - Find header end of old file
     * - write new header to byte array
     * - create new writer, append new header & main part of old file
     */

    // write to temp, rename if successful (useful if src == dest and errors occur...)
    File tmp = new File(dest.getParentFile(), dest.getName() + ".tmp");

    // create streams
    InputStream is = null;
    FileOutputStream fos = null;

    try {
        // open the source file and find the end of the header
        ByteSource source = Files.asByteSource(mapFile);
        int headerEnd = HeaderParser.findEndOfHeader(source);

        // open the destination file
        fos = new FileOutputStream(tmp);

        // write the header
        fos.write(header.generateHeader());

        // copy the contents (without header) from the source file to the destination
        is = source.openBufferedStream();
        long skipped = is.skip(headerEnd);
        if (skipped != headerEnd) {
            throw new IOException("Could not read from existing map file!");
        }
        ByteStreams.copy(is, fos);

        // move tmp file
        fos.close();
        if (dest.exists()) {
            dest.delete();
        }
        Files.move(tmp, dest);
    } finally {
        // close streams
        if (is != null) {
            is.close();
        }
        if (fos != null) {
            fos.close();
        }
    }
}