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.sonar.batch.scan.DeprecatedJsonReport.java

private void exportResults(Collection<Resource> resources) {
    File exportFile = new File(fileSystem.workingDir(), settings.getString("sonar.dryRun.export.path"));

    LOG.info("Export (deprecated) dry run results to " + exportFile.getAbsolutePath());
    Writer output = null;/*w w  w  .j av  a  2 s .co m*/
    try {
        output = new BufferedWriter(new FileWriter(exportFile));
        writeJson(resources, output);
    } catch (IOException e) {
        throw new SonarException("Unable to write DryRun results in file " + exportFile.getAbsolutePath(), e);
    } finally {
        Closeables.closeQuietly(output);
    }
}

From source file:org.apache.crunch.io.text.csv.CSVRecordIterator.java

@Override
public boolean hasNext() {
    if (!(currentLine == null)) {
        return true;
    }//from ww w  .  jav a  2s  . co  m
    Closeables.closeQuietly(this);
    return false;
}

From source file:org.stjs.testing.driver.DriverConfiguration.java

public DriverConfiguration(Class<?> klass) {

    InputStream in = null;/*ww w .j a  va2 s .  c  om*/
    props = new Properties();
    try {
        in = klass.getResourceAsStream(getConfigFileLocation());
        if (in != null) {
            props.load(in);
        }
    } catch (IOException e) {
        // silent
    } finally {
        Closeables.closeQuietly(in);
    }

    // system properties take precedence
    props.putAll(System.getProperties());
    if (props.get(PROP_PORT) != null) {
        port = Integer.parseInt(props.getProperty(PROP_PORT));
    }
    if (props.get(PROP_WAIT_FOR_BROWSER) != null) {
        waitForBrowser = Integer.parseInt(props.getProperty(PROP_WAIT_FOR_BROWSER));
    }
    if (props.get(PROP_SKIP_IF_NO_BROWSER) != null) {
        skipIfNoBrowser = Boolean.parseBoolean(props.getProperty(PROP_SKIP_IF_NO_BROWSER));
    }
    if (props.get(PROP_START_BROWSER) != null) {
        startBrowser = Boolean.parseBoolean(props.getProperty(PROP_START_BROWSER));
    }
    if (props.get(PROP_TEST_TIMEOUT) != null) {
        testTimeout = Integer.parseInt(props.getProperty(PROP_TEST_TIMEOUT));
    }
    if (props.get(PROP_BROWSER_COUNT) != null) {
        System.out.println("Configuration property " + PROP_BROWSER_COUNT + " is now ignored, use "
                + PROP_BROWSERS + " instead");
    }
    if (props.get(PROP_DEBUG) != null) {
        debugEnabled = Boolean.parseBoolean(props.getProperty(PROP_DEBUG));
    }
    classLoader = new WebAppClassLoader(new URL[] {}, klass.getClassLoader(), debugEnabled);
    stjsClassResolver = new DefaultClassResolver(classLoader);
    resourceResolver = new TestResourceResolver(classLoader);
    dependencyCollector = new DependencyCollector();

    // load browsers last
    browsers = instantiateBrowsers();
}

From source file:org.sonar.batch.scan.JsonReport.java

private void exportResults() {
    File exportFile = new File(fileSystem.workingDir(), settings.getString("sonar.report.export.path"));

    LOG.info("Export results to " + exportFile.getAbsolutePath());
    Writer output = null;/*from  w w  w .  ja  v  a 2 s.c om*/
    try {
        output = new BufferedWriter(new FileWriter(exportFile));
        writeJson(output);

    } catch (IOException e) {
        throw new SonarException("Unable to write report results in file " + exportFile.getAbsolutePath(), e);
    } finally {
        Closeables.closeQuietly(output);
    }
}

From source file:co.cask.cdap.internal.app.runtime.service.InMemoryProgramRuntimeService.java

@Override
public synchronized RuntimeInfo run(Program program, ProgramOptions options) {
    try {/* w  w w .  j  av  a 2 s .c o  m*/
        File tmpDir = new File(cConf.get(Constants.CFG_LOCAL_DATA_DIR),
                cConf.get(Constants.AppFabric.TEMP_DIR));
        final File destinationUnpackedJarDir = new File(tmpDir,
                String.format("%s.%s", program.getName(), UUID.randomUUID().toString()));
        Preconditions.checkState(!destinationUnpackedJarDir.exists());
        destinationUnpackedJarDir.mkdirs();

        final Program bundleJarProgram = Programs.createWithUnpack(program.getJarLocation(),
                destinationUnpackedJarDir);
        RuntimeInfo info = super.run(bundleJarProgram, options);
        final ProgramController controller = info.getController();
        controller.addListener(new AbstractListener() {

            @Override
            public void killed() {
                try {
                    Closeables.closeQuietly(bundleJarProgram);
                    FileUtils.deleteDirectory(destinationUnpackedJarDir);
                } catch (IOException e) {
                    LOG.warn("Failed to cleanup temporary program directory {}.", destinationUnpackedJarDir, e);
                }
            }

            @Override
            public void completed() {
                try {
                    Closeables.closeQuietly(bundleJarProgram);
                    FileUtils.deleteDirectory(destinationUnpackedJarDir);
                } catch (IOException e) {
                    LOG.warn("Failed to cleanup temporary program directory {}.", destinationUnpackedJarDir, e);
                }
            }

            @Override
            public void error(Throwable cause) {
                try {
                    Closeables.closeQuietly(bundleJarProgram);
                    FileUtils.deleteDirectory(destinationUnpackedJarDir);
                } catch (IOException e) {
                    LOG.warn("Failed to cleanup temporary program directory {}.", destinationUnpackedJarDir, e);
                }
            }
        }, ExecutorUtils.newThreadExecutor(Threads.createDaemonThreadFactory("program-clean-up-%d")));

        return info;

    } catch (IOException e) {
        throw new RuntimeException("Error unpackaging program " + program.getName());
    }
}

From source file:com.netflix.exhibitor.core.processes.ProcessMonitor.java

private void closeHolder(ProcessHolder previousHolder) {
    if (previousHolder != null) {
        previousHolder.isBeingClosed.set(true);

        Closeables.closeQuietly(previousHolder.process.getErrorStream());
        Closeables.closeQuietly(previousHolder.process.getInputStream());
        Closeables.closeQuietly(previousHolder.process.getOutputStream());

        previousHolder.process.destroy();
    }//from  ww  w . j a va  2s  .  com
}

From source file:com.silverpeas.util.ZipManager.java

/**
 * Mthode compressant au format zip un fichier ou un dossier de faon rcursive au format zip
 *
 * @param filename    - fichier ou dossier  compresser
 * @param outfilename - fichier zip  creer
 * @return la taille du fichier zip gnr en octets
 * @throws FileNotFoundException//from w  w w .  j  a  v a 2s  .co m
 * @throws IOException
 */
public static long compressPathToZip(String filename, String outfilename)
        throws FileNotFoundException, IOException {
    ZipArchiveOutputStream zos = null;
    File file = new File(filename);
    try {
        // cration du flux zip
        zos = new ZipArchiveOutputStream(new FileOutputStream(outfilename));
        zos.setFallbackToUTF8(true);
        zos.setCreateUnicodeExtraFields(NOT_ENCODEABLE);
        zos.setEncoding(CharEncoding.UTF_8);
        @SuppressWarnings("unchecked")
        Collection<File> listcontenuPath = FileUtils.listFiles(file, null, true);
        for (File content : listcontenuPath) {
            String entryName = content.getPath().substring(file.getParent().length() + 1);
            entryName = entryName.replace(File.separatorChar, '/');
            zos.putArchiveEntry(new ZipArchiveEntry(entryName));
            InputStream in = new FileInputStream(content);
            IOUtils.copy(in, zos);
            zos.closeArchiveEntry();
            IOUtils.closeQuietly(in);
        }
        zos.close();
        File fileZip = new File(outfilename);
        return fileZip.length();
    } finally {
        if (zos != null) {
            Closeables.closeQuietly(zos);
        }
    }
}

From source file:com.nesscomputing.httpclient.response.NumberContentConverter.java

@Override
public T convert(HttpClientResponse httpClientResponse, InputStream inputStream) throws IOException {
    final int responseCode = httpClientResponse.getStatusCode();
    switch (responseCode) {
    case 200:/*from w  w  w  .  j  a v a  2 s. co  m*/
    case 201:
        final Charset charset = Charset.forName(Objects.firstNonNull(httpClientResponse.getCharset(), "UTF-8"));
        final InputStreamReader reader = new InputStreamReader(inputStream, charset);

        try {
            final String data = CharStreams.toString(reader);
            final T result = numberClass.cast(safeInvoke(data));
            if (result == null) {
                // 201 may or may not return a body. Try parsing the body, return the empty value if
                // none is there (same as 204).
                if (responseCode == 201) {
                    return emptyValue;
                }
                throw new IllegalArgumentException(format("Could not parse result '%s'", data));
            }
            return result;
        } finally {
            Closeables.closeQuietly(reader);
        }

    case 204:
        return emptyValue;

    case 404:
        if (ignore404) {
            return emptyValue;
        }
        throw throwHttpResponseException(httpClientResponse);

    default:
        throw throwHttpResponseException(httpClientResponse);
    }
}

From source file:eu.operando.pq.PrivacyQuestionsService.java

public List<AccessReason> getReasonsFromFile(String filename) {
    InputStream fis = null;//from w w w  .  j ava 2 s  .  co  m
    try {
        fis = this.getClass().getClassLoader().getResourceAsStream(filename);
        String content = CharStreams.toString(new InputStreamReader(fis, Charsets.UTF_8));
        Closeables.closeQuietly(fis);

        ObjectMapper mapper = new ObjectMapper();

        //JSON from String to Object
        return mapper.readValue(content, new TypeReference<List<AccessReason>>() {
        });

    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.codehaus.httpcache4j.cache.PersistentCacheStorage2.java

private void writeItem(Key key, SerializableCacheItem item) throws IOException {
    File metadata = new File(fileManager.resolve(key).getAbsolutePath() + ".metadata");
    if (!metadata.getParentFile().exists()) {
        fileManager.ensureDirectoryExists(metadata.getParentFile());
    }//from  w  w w. jav a 2  s .  c o m
    FileWriter writer = null;
    try {
        Properties properties = new Properties();
        properties.putAll(key.toProperties());
        properties.putAll(item.toProperties());
        writer = new FileWriter(metadata);
        properties.store(writer, null);
    } finally {
        Closeables.closeQuietly(writer);
    }
}