Example usage for com.google.common.io Closeables closeQuietly

List of usage examples for com.google.common.io Closeables closeQuietly

Introduction

In this page you can find the example usage for com.google.common.io Closeables closeQuietly.

Prototype

public static void closeQuietly(@Nullable Reader reader) 

Source Link

Document

Closes the given Reader , logging any IOException that's thrown rather than propagating it.

Usage

From source file:org.sonatype.nexus.client.internal.util.Version.java

/**
 * Reads the version from a properties file, the one embedded by Maven into Jar during build.
 * //  w  w w  .  j  a  v a 2s .c o m
 * @param cl the class loader to be used to load the properties file.
 * @param path the binary path of the properties file to read from (might have more in case of shaded JAR).
 * @param defaultVersion the version string to return in case of unsuccessful read of the properties file.
 * @return the version from the Maven properties file on given path, embedded into JAR.
 * @since 2.4.1
 */
public static String readVersion(final ClassLoader cl, final String path, final String defaultVersion) {
    String version = defaultVersion;
    InputStream is = null;
    try {
        final Properties props = new Properties();
        is = cl.getResourceAsStream(path);
        if (is != null) {
            props.load(is);
            version = props.getProperty("version");
        }
    } catch (IOException e) {
        LOG.error("Could not load/read version from " + path, e);
    } finally {
        Closeables.closeQuietly(is);
    }
    return version;
}

From source file:org.cleansvg.SVGModule.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static Map<String, String> loadProperties(final String resource) {
    final String fileName = resource + ".properties";
    final File file = new File(fileName);
    final Reader reader;
    try {/*from   w ww.  jav  a2 s. com*/
        reader = Files.newReader(file, Charsets.UTF_8);
    } catch (final FileNotFoundException e) {
        // logger.log(Level.SEVERE, "Cannot open " + fileName + ".", e);
        throw new RuntimeException(e);
    }
    final Properties properties = new Properties();
    // boolean thrown = true;
    try {
        properties.load(reader);
        // thrown = false;
    } catch (final IOException e) {
        // logger.log(Level.SEVERE, "Cannot read " + fileName + ".", e);
    } finally {
        // Closeables.close(reader, thrown);
        Closeables.closeQuietly(reader);
    }
    return (Map) properties;
}

From source file:org.codehaus.httpcache4j.payload.ByteArrayPayload.java

public ByteArrayPayload(InputStream stream, MIMEType type) throws IOException {
    try {/*  w w w.  ja  v a 2 s.com*/
        this.bytes = ByteStreams.toByteArray(stream);
    } finally {
        Closeables.closeQuietly(stream);
    }
    length = bytes.length;
    this.type = type;
}

From source file:co.cask.cdap.explore.service.FileWriterHelper.java

/**
 * Generate an Avro file of schema (key String, value String) containing the records ("<prefix>i", "#i")
 * for start <= i < end. The file is written using the passed-in output stream.
 *///from  w ww . j a  v  a 2  s  . c  o m
public static void generateAvroFile(OutputStream out, String prefix, int start, int end) throws IOException {
    Schema schema = Schema.createRecord("kv", null, null, false);
    schema.setFields(ImmutableList.of(new Schema.Field("key", Schema.create(Schema.Type.STRING), null, null),
            new Schema.Field("value", Schema.create(Schema.Type.STRING), null, null)));

    DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>(schema);
    DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(datumWriter);
    dataFileWriter.create(schema, out);
    try {
        for (int i = start; i < end; i++) {
            GenericRecord kv = new GenericData.Record(schema);
            kv.put("key", prefix + i);
            kv.put("value", "#" + i);
            dataFileWriter.append(kv);
        }
    } finally {
        Closeables.closeQuietly(dataFileWriter);
        Closeables.closeQuietly(out);
    }
}

From source file:org.apache.mahout.graph.preprocessing.GraphUtils.java

public static int indexVertices(Configuration conf, Path verticesPath, Path indexPath) throws IOException {
    FileSystem fs = FileSystem.get(verticesPath.toUri(), conf);
    SequenceFile.Writer writer = SequenceFile.createWriter(fs, conf, indexPath, IntWritable.class,
            Vertex.class);
    int index = 0;

    try {/*from   w w w . j a va2s.c om*/
        for (FileStatus fileStatus : fs.listStatus(verticesPath)) {
            InputStream in = HadoopUtil.openStream(fileStatus.getPath(), conf);
            try {
                for (String line : new FileLineIterable(in)) {
                    writer.append(new IntWritable(index++), new Vertex(Long.parseLong(line)));
                }
            } finally {
                Closeables.closeQuietly(in);
            }
        }
    } finally {
        Closeables.closeQuietly(writer);
    }

    return index;
}

From source file:com.axemblr.service.cm.util.StreamGobbler.java

public void run() {
    try {/*from   w ww .  j  ava2 s  .c o  m*/
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line = null;
        while ((line = br.readLine()) != null)
            out.println(type + ">" + line);
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        Closeables.closeQuietly(is);
    }
}

From source file:org.eclipse.recommenders.utils.Zips.java

public static void unzip(File zipFile, File destFolder) throws IOException {
    ZipInputStream zis = null;//from  w w w  .ja  v  a 2  s  .  co m
    try {
        InputSupplier<FileInputStream> fis = Files.newInputStreamSupplier(zipFile);
        zis = new ZipInputStream(fis.getInput());
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            if (!entry.isDirectory()) {
                final File file = new File(destFolder, entry.getName());
                Files.createParentDirs(file);
                Files.write(ByteStreams.toByteArray(zis), file);
            }
        }
    } finally {
        Closeables.closeQuietly(zis);
    }
}

From source file:org.sonar.test.i18n.RuleRepositoryTestHelper.java

private static Properties loadProperties(String resourcePath) {
    Properties properties = new Properties();

    InputStream input = null;//from   w  w  w .  j  a  va  2  s.c  o m
    try {
        input = TestUtils.class.getResourceAsStream(resourcePath);
        properties.load(input);
        return properties;
    } catch (IOException e) {
        throw new SonarException("Unable to read properties " + resourcePath, e);
    } finally {
        Closeables.closeQuietly(input);
    }
}

From source file:com.github.zhongl.io.FileChannels.java

private static <T> T read(FileChannel channel, FileChannelFunction<T> function) throws IOException {
    try {/* ww w . jav  a2  s .c  o  m*/
        return function.apply(channel);
    } finally {
        Closeables.closeQuietly(channel);
    }
}

From source file:com.android.providers.contacts.debug.DataExporter.java

/**
 * Compress all files under the app data dir into a single zip file, and return the content://
 * URI to the file, which can be read via {@link DumpFileProvider}.
 *///from   w  w w  .j  a  v a  2 s  .co  m
public static Uri exportData(Context context) throws IOException {
    final String fileName = generateRandomName() + OUT_FILE_SUFFIX;
    final File outFile = getOutputFile(context, fileName);

    // Remove all existing ones.
    removeDumpFiles(context);

    Log.i(TAG, "Dump started...");

    ensureOutputDirectory(context);
    final ZipOutputStream os = new ZipOutputStream(new FileOutputStream(outFile));
    os.setLevel(Deflater.BEST_COMPRESSION);
    try {
        addDirectory(context, os, context.getFilesDir().getParentFile(), "contacts-files");
    } finally {
        Closeables.closeQuietly(os);
    }
    Log.i(TAG, "Dump finished.");
    return DumpFileProvider.AUTHORITY_URI.buildUpon().appendPath(fileName).build();
}