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:runtime.intrinsic.demo._writefile.java

public static boolean invoke(final String path, final String contents) {
    final File file = new File(path);

    FileWriter fw = null;/*w w w.  java 2s .  co  m*/
    try {
        fw = new FileWriter(file, false);
        fw.write(contents);
    } catch (IOException ignore) {
        return false;
    } finally {
        Closeables.closeQuietly(fw);
    }

    return true;
}

From source file:runtime.intrinsic.demo._appendfile.java

public static boolean invoke(final String path, final String contents) {
    final File file = new File(path);

    FileWriter fw = null;/*  w  w w  .j  av a 2s  . c o m*/
    try {
        fw = new FileWriter(file, true);
        fw.write(contents);
    } catch (IOException ignore) {
        return false;
    } finally {
        Closeables.closeQuietly(fw);
    }

    return true;
}

From source file:org.kitesdk.apps.spi.PropertyFiles.java

public static Map<String, String> load(File input) {

    FileInputStream stream = null;

    try {//from   ww  w.ja  v a  2s.co m
        stream = new FileInputStream(input);
        return load(stream);
    } catch (FileNotFoundException e) {
        throw new AppException(e);
    } finally {
        Closeables.closeQuietly(stream);
    }
}

From source file:net.awired.visuwall.plugin.bamboo.BambooVersionExtractor.java

static String extractVersion(URL url) throws BambooVersionNotFoundException {
    InputStream stream = null;/*from   w  w w . j a  va  2s.  c o m*/
    try {
        stream = url.openStream();
        byte[] bytes = ByteStreams.toByteArray(stream);
        String page = new String(bytes);
        return extractVersion(page);
    } catch (IOException e) {
        throw new BambooVersionNotFoundException("Can't extract version from url:" + url, e);
    } finally {
        Closeables.closeQuietly(stream);
    }
}

From source file:org.apache.mahout.classifier.bayes.WikipediaXmlSplitter.java

public static void main(String[] args) throws IOException {
    DefaultOptionBuilder obuilder = new DefaultOptionBuilder();
    ArgumentBuilder abuilder = new ArgumentBuilder();
    GroupBuilder gbuilder = new GroupBuilder();

    Option dumpFileOpt = obuilder.withLongName("dumpFile").withRequired(true)
            .withArgument(abuilder.withName("dumpFile").withMinimum(1).withMaximum(1).create())
            .withDescription("The path to the wikipedia dump file (.bz2 or uncompressed)").withShortName("d")
            .create();//w w  w.j  a v  a 2s  .c o m

    Option outputDirOpt = obuilder.withLongName("outputDir").withRequired(true)
            .withArgument(abuilder.withName("outputDir").withMinimum(1).withMaximum(1).create())
            .withDescription("The output directory to place the splits in:\n"
                    + "local files:\n\t/var/data/wikipedia-xml-chunks or\n\tfile:///var/data/wikipedia-xml-chunks\n"
                    + "Hadoop DFS:\n\thdfs://wikipedia-xml-chunks\n"
                    + "AWS S3 (blocks):\n\ts3://bucket-name/wikipedia-xml-chunks\n"
                    + "AWS S3 (native files):\n\ts3n://bucket-name/wikipedia-xml-chunks\n")

            .withShortName("o").create();

    Option s3IdOpt = obuilder.withLongName("s3ID").withRequired(false)
            .withArgument(abuilder.withName("s3Id").withMinimum(1).withMaximum(1).create())
            .withDescription("Amazon S3 ID key").withShortName("i").create();
    Option s3SecretOpt = obuilder.withLongName("s3Secret").withRequired(false)
            .withArgument(abuilder.withName("s3Secret").withMinimum(1).withMaximum(1).create())
            .withDescription("Amazon S3 secret key").withShortName("s").create();

    Option chunkSizeOpt = obuilder.withLongName("chunkSize").withRequired(true)
            .withArgument(abuilder.withName("chunkSize").withMinimum(1).withMaximum(1).create())
            .withDescription("The Size of the chunk, in megabytes").withShortName("c").create();
    Option numChunksOpt = obuilder.withLongName("numChunks").withRequired(false)
            .withArgument(abuilder.withName("numChunks").withMinimum(1).withMaximum(1).create())
            .withDescription(
                    "The maximum number of chunks to create.  If specified, program will only create a subset of the chunks")
            .withShortName("n").create();
    Group group = gbuilder.withName("Options").withOption(dumpFileOpt).withOption(outputDirOpt)
            .withOption(chunkSizeOpt).withOption(numChunksOpt).withOption(s3IdOpt).withOption(s3SecretOpt)
            .create();

    Parser parser = new Parser();
    parser.setGroup(group);
    CommandLine cmdLine;
    try {
        cmdLine = parser.parse(args);
    } catch (OptionException e) {
        log.error("Error while parsing options", e);
        CommandLineUtil.printHelp(group);
        return;
    }

    Configuration conf = new Configuration();
    String dumpFilePath = (String) cmdLine.getValue(dumpFileOpt);
    String outputDirPath = (String) cmdLine.getValue(outputDirOpt);

    if (cmdLine.hasOption(s3IdOpt)) {
        String id = (String) cmdLine.getValue(s3IdOpt);
        conf.set("fs.s3n.awsAccessKeyId", id);
        conf.set("fs.s3.awsAccessKeyId", id);
    }
    if (cmdLine.hasOption(s3SecretOpt)) {
        String secret = (String) cmdLine.getValue(s3SecretOpt);
        conf.set("fs.s3n.awsSecretAccessKey", secret);
        conf.set("fs.s3.awsSecretAccessKey", secret);
    }
    // do not compute crc file when using local FS
    conf.set("fs.file.impl", "org.apache.hadoop.fs.RawLocalFileSystem");
    FileSystem fs = FileSystem.get(URI.create(outputDirPath), conf);

    int chunkSize = 1024 * 1024 * Integer.parseInt((String) cmdLine.getValue(chunkSizeOpt));

    int numChunks = Integer.MAX_VALUE;
    if (cmdLine.hasOption(numChunksOpt)) {
        numChunks = Integer.parseInt((String) cmdLine.getValue(numChunksOpt));
    }

    String header = "<mediawiki xmlns=\"http://www.mediawiki.org/xml/export-0.3/\" "
            + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
            + "xsi:schemaLocation=\"http://www.mediawiki.org/xml/export-0.3/ "
            + "http://www.mediawiki.org/xml/export-0.3.xsd\" " + "version=\"0.3\" " + "xml:lang=\"en\">\n"
            + "  <siteinfo>\n" + "<sitename>Wikipedia</sitename>\n"
            + "    <base>http://en.wikipedia.org/wiki/Main_Page</base>\n"
            + "    <generator>MediaWiki 1.13alpha</generator>\n" + "    <case>first-letter</case>\n"
            + "    <namespaces>\n" + "      <namespace key=\"-2\">Media</namespace>\n"
            + "      <namespace key=\"-1\">Special</namespace>\n" + "      <namespace key=\"0\" />\n"
            + "      <namespace key=\"1\">Talk</namespace>\n" + "      <namespace key=\"2\">User</namespace>\n"
            + "      <namespace key=\"3\">User talk</namespace>\n"
            + "      <namespace key=\"4\">Wikipedia</namespace>\n"
            + "      <namespace key=\"5\">Wikipedia talk</namespace>\n"
            + "      <namespace key=\"6\">Image</namespace>\n"
            + "      <namespace key=\"7\">Image talk</namespace>\n"
            + "      <namespace key=\"8\">MediaWiki</namespace>\n"
            + "      <namespace key=\"9\">MediaWiki talk</namespace>\n"
            + "      <namespace key=\"10\">Template</namespace>\n"
            + "      <namespace key=\"11\">Template talk</namespace>\n"
            + "      <namespace key=\"12\">Help</namespace>\n"
            + "      <namespace key=\"13\">Help talk</namespace>\n"
            + "      <namespace key=\"14\">Category</namespace>\n"
            + "      <namespace key=\"15\">Category talk</namespace>\n"
            + "      <namespace key=\"100\">Portal</namespace>\n"
            + "      <namespace key=\"101\">Portal talk</namespace>\n" + "    </namespaces>\n"
            + "  </siteinfo>\n";

    StringBuilder content = new StringBuilder();
    content.append(header);
    NumberFormat decimalFormatter = new DecimalFormat("0000");
    File dumpFile = new File(dumpFilePath);
    FileLineIterator it;
    if (dumpFilePath.endsWith(".bz2")) {
        // default compression format from http://download.wikimedia.org
        CompressionCodec codec = new BZip2Codec();
        it = new FileLineIterator(codec.createInputStream(new FileInputStream(dumpFile)));
    } else {
        // assume the user has previously de-compressed the dump file
        it = new FileLineIterator(dumpFile);
    }
    int filenumber = 0;
    while (it.hasNext()) {
        String thisLine = it.next();
        if (thisLine.trim().startsWith("<page>")) {
            boolean end = false;
            while (!thisLine.trim().startsWith("</page>")) {
                content.append(thisLine).append('\n');
                if (it.hasNext()) {
                    thisLine = it.next();
                } else {
                    end = true;
                    break;
                }
            }
            content.append(thisLine).append('\n');

            if (content.length() > chunkSize || end) {
                content.append("</mediawiki>");
                filenumber++;
                String filename = outputDirPath + "/chunk-" + decimalFormatter.format(filenumber) + ".xml";
                BufferedWriter chunkWriter = new BufferedWriter(
                        new OutputStreamWriter(fs.create(new Path(filename)), "UTF-8"));
                try {
                    chunkWriter.write(content.toString(), 0, content.length());
                } finally {
                    Closeables.closeQuietly(chunkWriter);
                }
                if (filenumber >= numChunks) {
                    break;
                }
                content = new StringBuilder();
                content.append(header);
            }
        }
    }
}

From source file:org.trancecode.io.TcByteStreams.java

public static long copy(final InputStream in, final OutputStream out, final boolean close) {
    try {//from  w  ww  .j  av a 2 s.c  o m
        final long bytes = ByteStreams.copy(in, out);
        Closeables.close(in, false);
        Closeables.close(out, false);
        return bytes;
    } catch (final IOException e) {
        throw new RuntimeIOException(e);
    } finally {
        if (close) {
            Closeables.closeQuietly(in);
            Closeables.closeQuietly(out);
        }
    }
}

From source file:org.sonar.plugins.pmd.PmdVersion.java

public static String getVersion() {
    Properties properties = new Properties();

    InputStream input = null;/*from ww w  . j  a v a 2 s.  c o  m*/
    try {
        input = PmdVersion.class.getResourceAsStream(PROPERTIES_PATH);
        properties.load(input);
    } catch (IOException e) {
        LoggerFactory.getLogger(PmdVersion.class)
                .warn("Can not load the PMD version from the file " + PROPERTIES_PATH, e);
    } finally {
        Closeables.closeQuietly(input);
    }

    return properties.getProperty("pmd.version", "");
}

From source file:org.jclouds.demo.tweetstore.config.util.PropertiesLoader.java

private static Properties loadJcloudsProperties(ServletContext context) {
    InputStream input = context.getResourceAsStream(PROPERTIES_FILE);
    Properties props = new Properties();
    try {//from  w w  w  .  j a  va 2s.  c om
        props.load(input);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        Closeables.closeQuietly(input);
    }
    return props;
}

From source file:org.cogroo.config.LanguageConfigurationUtil.java

/**
 * //  w  w w. j  ava2 s  .  c o  m
 * @param locale
 *          contains the language to be used
 * @throws InitializationException
 * @return the file .xml converted to Java, it contains which analyzers to add
 *         into the pipe according to the language to be used
 */
public static LanguageConfiguration get(Locale locale) {

    String file = generateName(locale);

    InputStream in = LanguageConfigurationUtil.class.getClassLoader().getResourceAsStream(file);

    if (in != null) {
        LanguageConfiguration lc = get(in);
        Closeables.closeQuietly(in);
        return lc;
    } else
        throw new InitializationException(
                "Couldn't locate configuration for locale: " + locale + " The expected file was: " + file);
}

From source file:com.mdrsolutions.external.xml.XmlCalls.java

public static final String getXml(String filePath, boolean notClassPath) {

    String xml = "";
    InputStream is;/*from w  w w.  j  a va 2  s .com*/

    if (!notClassPath) {
        return getXml(filePath);
    }

    try {
        File f = new File(filePath);
        is = new FileInputStream(f);
        xml = CharStreams.toString(new InputStreamReader(is));
        if (null == xml || xml.isEmpty()) {

            Closeables.closeQuietly(is);
            throw new IOException("File path to SQL file could not be read!");
        } else {
            Closeables.closeQuietly(is);
            return xml;
        }
    } catch (IOException ex) {
        logger.error("Could not read the sql file specified!", ex);
    }
    return xml;
}