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:com.netflix.exhibitor.core.controlpanel.FileBasedPreferences.java

@Override
protected void flushSpi() throws BackingStoreException {
    if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
        throw new BackingStoreException("Could not create parent directories for: " + file);
    }/* www.  ja v a2 s  .c  o  m*/

    OutputStream out = null;
    try {
        out = new BufferedOutputStream(new FileOutputStream(file));
        properties.store(out, "# Auto-generated by " + FileBasedPreferences.class.getName());
    } catch (IOException e) {
        throw new BackingStoreException(e);
    } finally {
        Closeables.closeQuietly(out);
    }
}

From source file:com.metamx.druid.realtime.RealtimeManager.java

@LifecycleStop
public void stop() {
    for (FireChief chief : chiefs.values()) {
        Closeables.closeQuietly(chief);
    }
}

From source file:com.atoito.jeauty.Beautifier.java

public EnhancementResult enhance(String sourceFilePath) {
    if (Strings.isNullOrEmpty(sourceFilePath)) {
        return EnhancementResult.fail("Invalid empty source file path");
    }/*ww  w  . j  a va  2s  .c  o  m*/
    Reader fr = null;
    try {
        fr = new InputStreamReader(new FileInputStream(sourceFilePath), runOptions.getCharset());
    } catch (FileNotFoundException e) {
        return EnhancementResult.fail(e);
    }
    BufferedReader br = new BufferedReader(fr);
    StringBuilder fmt = new StringBuilder();
    String s;
    boolean currentLineEmpty = false;
    boolean lastLineEmpty = false;
    try {
        while ((s = br.readLine()) != null) {
            currentLineEmpty = s.trim().isEmpty();
            if (currentLineEmpty && lastLineEmpty) {
                lastLineEmpty = currentLineEmpty;
            } else {
                fmt.append(spaceIndentation(s)).append(runOptions.getEol());
                lastLineEmpty = currentLineEmpty;
            }
        }
    } catch (IOException ioe) {
        return EnhancementResult.fail(ioe);
    } finally {
        Closeables.closeQuietly(fr);
        Closeables.closeQuietly(br);
    }
    String spacedSourceCode = fmt.toString();
    return beautify(spacedSourceCode);
}

From source file:com.metamx.druid.index.v1.CompressedObjectStrategy.java

@Override
public byte[] toBytes(ResourceHolder<T> holder) {
    T val = holder.get();
    ByteBuffer buf = ByteBuffer.allocate(converter.sizeOf(val.remaining())).order(order);
    converter.combine(buf, val);

    final ResourceHolder<ChunkEncoder> encoder = CompressedPools.getChunkEncoder();
    LZFChunk chunk = encoder.get().encodeChunk(buf.array(), 0, buf.array().length);
    Closeables.closeQuietly(encoder);

    return chunk.getData();
}

From source file:org.apache.mahout.df.DFUtils.java

public static void storeWritable(Configuration conf, Path path, Writable writable) throws IOException {
    FileSystem fs = path.getFileSystem(conf);

    FSDataOutputStream out = fs.create(path);
    try {/*from   www .ja v  a  2  s . co  m*/
        writable.write(out);
    } finally {
        Closeables.closeQuietly(out);
    }
}

From source file:com.netflix.exhibitor.core.index.IndexProcessor.java

private void addActive(IndexBuilder builder) throws Exception {
    ZooKeeperLogFiles zooKeeperLogFiles = new ZooKeeperLogFiles(exhibitor);
    List<File> paths = zooKeeperLogFiles.getPaths();
    Collections.sort(paths, new Comparator<File>() {
        @Override/*from ww w  . ja  v  a2  s .  com*/
        public int compare(File o1, File o2) {
            long diff = o1.lastModified() - o2.lastModified();
            return (diff < 0) ? -1 : ((diff > 0) ? 1 : 0);
        }
    });

    int index = 0;
    for (File f : paths) {
        exhibitor.getLog().add(ActivityLog.Type.INFO,
                String.format("Indexing active log %d of %d", ++index, paths.size()));

        if (f.exists()) {
            InputStream in = new BufferedInputStream(new FileInputStream(f));
            try {
                builder.add(in);
            } finally {
                Closeables.closeQuietly(in);
            }
        }
    }
}

From source file:org.jclouds.http.functions.ParseSax.java

public T apply(HttpResponse from) {
    try {//w w  w  .  j  a v a 2  s .  c  om
        checkNotNull(from, "http response");
        checkNotNull(from.getPayload(), "payload in " + from);
    } catch (NullPointerException e) {
        return addDetailsAndPropagate(from, e);
    }
    InputStream is = null;
    try {
        // debug is more normally set, so trace is more appropriate for
        // something heavy like this
        if (from.getStatusCode() >= 300 || logger.isTraceEnabled())
            return convertStreamToStringAndParse(from);
        is = from.getPayload().getInput();
        return parse(new InputSource(is));
    } catch (RuntimeException e) {
        return addDetailsAndPropagate(from, e);
    } finally {
        Closeables.closeQuietly(is);
        from.getPayload().release();
    }
}

From source file:co.cask.cdap.filetailer.state.FileTailerStateProcessorImpl.java

@Override
public FileTailerState loadState() throws FileTailerStateProcessorException {
    if (!stateFile.exists()) {
        LOG.info("Not found state file: {}", stateFile.getAbsolutePath());
        return null;
    }/*from w  ww. j  a v  a2 s . c o  m*/
    LOG.debug("Start loading File Tailer state ..");
    try {
        BufferedReader reader = Files.newReader(stateFile, UTF_8);
        try {
            FileTailerState state = GSON.fromJson(reader, FileTailerState.class);
            LOG.debug("File Tailer state loaded successfully");
            return state;
        } finally {
            Closeables.closeQuietly(reader);
        }
    } catch (IOException e) {
        LOG.error("Can not load File Tailer state: {}", e);
        throw new FileTailerStateProcessorException(e.getMessage());
    }
}

From source file:org.cogroo.gc.cmdline.grammarchecker.XMLRulesReportTool.java

public void run(String[] args) {
    Params params = validateAndParseParams(args, Params.class);

    String lang = params.getLang();
    CmdLineUtil.checkLanguageCode(lang);

    File outFile = params.getOutputFile();
    CmdLineUtil.checkOutputFile("report file", outFile);

    String country = params.getCountry();
    if (Strings.isNullOrEmpty(country)) {
        throw new TerminateToolException(1, "Country cannot be empty. Example country: BR");
    }/*from   w  w  w  .  j  a va 2 s . c  o  m*/

    ComponentFactory factory;
    try {
        factory = ComponentFactory.create(new Locale(lang, country));
    } catch (InitializationException e) {
        e.printStackTrace();
        throw new TerminateToolException(1, "Could not find configuration for " + lang + ". Only "
                + new Locale("pt", "BR") + " might be supported for now.");
    }
    GrammarChecker cogroo;
    try {
        cogroo = new GrammarChecker(factory.createPipe());
    } catch (IOException e) {
        e.printStackTrace();
        throw new TerminateToolException(1, "Could not create pipeline!");
    }

    try {
        CogrooHtml report = new CogrooHtml(outFile, cogroo);
        report.evaluate();

        File jsFile = new File(outFile.getParentFile(), "overlib.js");
        if (!jsFile.exists()) {
            InputStream is = this.getClass().getResourceAsStream("/org/cogroo/gc/htmlreport/overlib.js");
            OutputStream os = new FileOutputStream(jsFile);
            ByteStreams.copy(is, os);
            Closeables.closeQuietly(os);
            Closeables.closeQuietly(is);
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new TerminateToolException(1, "Failure during report build.");
    }

}

From source file:net.sourceforge.vaticanfetcher.model.index.outlook.AttachmentVisitor.java

public final void run() {
    int numberOfAttachments = email.getNumberOfAttachments();
    for (int i = 0; i < numberOfAttachments; i++) {
        String filename = null;//from  ww w.  j a v a 2  s.  com
        File tempFile = null;
        try {
            PSTAttachment attach = email.getAttachment(i);

            // Get the filename; both long and short filenames can be used for attachments
            filename = attach.getLongFilename();
            if (filename.isEmpty())
                filename = attach.getFilename();

            // Set up input and output stream
            tempFile = config.createDerivedTempFile(filename);
            InputStream in = attach.getFileInputStream();
            FileOutputStream out = new FileOutputStream(tempFile);

            /*
             * TODO post-release-1.1: Instead of writing to a temporary
             * file, we could directly give the input stream to the parse
             * service. (But temporary files would still be necessary for
             * archives.)
             */

            /*
             * Copy bytes from input stream to output stream
             * 
             * 8176 is the block size used internally and should give the
             * best performance.
             */
            int bufferSize = 8176;
            byte[] buffer = new byte[bufferSize];
            int count = in.read(buffer);
            while (count == bufferSize) {
                out.write(buffer);
                count = in.read(buffer);
            }
            byte[] endBuffer = new byte[count];
            System.arraycopy(buffer, 0, endBuffer, 0, count);
            out.write(endBuffer);
            Closeables.closeQuietly(out);
            Closeables.closeQuietly(in);

            handleAttachment(filename, tempFile);
        } catch (CheckedOutOfMemoryError e) {
            if (filename == null)
                filename = "???";
            handleException(filename, e.getCause());
        } catch (Exception e) {
            if (filename == null)
                filename = "???";
            if (e instanceof IndexingException)
                e = ((IndexingException) e).getIOException();
            handleException(filename, e);
        } finally {
            if (deleteTempFiles && tempFile != null)
                tempFile.delete();
        }
    }
    runFinally();
}