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.hhscyber.nl.tweets.url.URLUnshortener.java

/**
 * Expand the given short {@link URL}//from   ww w .  j a  v  a  2s .c om
 * @param address
 * @return
 */
public URL expand(URL address) {

    //Check cache
    URL inCache = cache.get(address);
    if (inCache != null) {
        return inCache;
    }

    //Connect & check for the location field
    HttpURLConnection connection = null;
    try {
        connection = (HttpURLConnection) address.openConnection(Proxy.NO_PROXY);
        connection.setConnectTimeout(connectTimeout);
        connection.setInstanceFollowRedirects(false);
        connection.setReadTimeout(readTimeout);
        connection.connect();
        String expandedURL = connection.getHeaderField("Location");
        if (expandedURL != null) {
            URL expanded = new URL(expandedURL);
            cache.put(address, expanded);
            return expanded;
        }
    } catch (Throwable e) {
        LOGGER.warn("Problem while expanding {}", address, e);
    } finally {
        try {
            if (connection != null) {
                Closeables.closeQuietly(connection.getInputStream());
            }
        } catch (IOException e) {
            LOGGER.warn("Unable to close connection stream", e);
        }
    }

    return address;
}

From source file:org.plista.kornakapi.web.servlets.BatchSetPreferencesServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    int batchSize = getParameterAsInt(request, Parameters.BATCH_SIZE, Parameters.DEFAULT_BATCH_SIZE);

    ServletFileUpload upload = new ServletFileUpload();

    FileItemIterator fileItems;//ww  w  .  j a v  a2 s  .com
    InputStream in = null;

    boolean fileProcessed = false;

    Storage storage = this.getDomainIndependetStorage();

    try {
        fileItems = upload.getItemIterator(request);
        while (fileItems.hasNext()) {

            FileItemStream item = fileItems.next();

            if (Parameters.FILE.equals(item.getFieldName()) && !item.isFormField()) {

                in = item.openStream();
                Iterator<Preference> preferences = new CSVPreferenceFileIterator(in);

                storage.batchSetPreferences(preferences, batchSize);

                fileProcessed = true;

                break;
            }
        }
    } catch (FileUploadException e) {
        throw new IOException(e);
    } finally {
        Closeables.closeQuietly(in);
    }

    if (!fileProcessed) {
        throw new IllegalStateException("Unable to find supplied data file!");
    }
}

From source file:org.plista.kornakapi.web.servlets.BatchDeleteCandidatesServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    int batchSize = getParameterAsInt(request, Parameters.BATCH_SIZE, Parameters.DEFAULT_BATCH_SIZE);

    ServletFileUpload upload = new ServletFileUpload();

    FileItemIterator fileItems;/*from  w ww.jav a2s . com*/
    InputStream in = null;

    boolean fileProcessed = false;

    Storage storage = this.getDomainIndependetStorage();
    try {
        fileItems = upload.getItemIterator(request);
        while (fileItems.hasNext()) {

            FileItemStream item = fileItems.next();

            if (Parameters.FILE.equals(item.getFieldName()) && !item.isFormField()) {

                in = item.openStream();
                Iterator<Candidate> candidates = new CSVCandidateFileIterator(in);

                storage.batchDeleteCandidates(candidates, batchSize);

                fileProcessed = true;

                break;
            }
        }
    } catch (FileUploadException e) {
        throw new IOException(e);
    } finally {
        Closeables.closeQuietly(in);
    }

    if (!fileProcessed) {
        throw new IllegalStateException("Unable to find supplied data file!");
    }
}

From source file:org.locationtech.geogig.cli.plumbing.VerifyPatch.java

@Override
public void runInternal(GeogigCLI cli) throws IOException {
    checkParameter(patchFiles.size() < 2, "Only one single patch file accepted");
    checkParameter(!patchFiles.isEmpty(), "No patch file specified");

    ConsoleReader console = cli.getConsole();

    File patchFile = new File(patchFiles.get(0));
    checkParameter(patchFile.exists(), "Patch file cannot be found");
    FileInputStream stream;/*from   w ww . j a v a2 s . com*/
    try {
        stream = new FileInputStream(patchFile);
    } catch (FileNotFoundException e1) {
        throw new IllegalStateException("Can't open patch file " + patchFile);
    }
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        Closeables.closeQuietly(reader);
        Closeables.closeQuietly(stream);
        throw new IllegalStateException("Error reading patch file " + patchFile, e);
    }
    Patch patch = PatchSerializer.read(reader);
    Closeables.closeQuietly(reader);
    Closeables.closeQuietly(stream);

    VerifyPatchResults verify = cli.getGeogig().command(VerifyPatchOp.class).setPatch(patch).setReverse(reverse)
            .call();
    Patch toReject = verify.getToReject();
    Patch toApply = verify.getToApply();
    if (toReject.isEmpty()) {
        console.println("Patch can be applied.");
    } else {
        console.println("Error: Patch cannot be applied\n");
        console.println("Applicable entries:\n");
        console.println(toApply.toString());
        console.println("\nConflicting entries:\n");
        console.println(toReject.toString());
    }

}

From source file:org.renyan.leveldb.impl.FileChannelLogWriter.java

@Override
public synchronized void delete() {
    closed.set(true);/*  w  ww. j  a v  a 2  s  .co m*/

    // close the channel
    Closeables.closeQuietly(fileChannel);

    // try to delete the file
    file.delete();
}

From source file:org.wso2.msf4j.internal.router.SSLHandlerFactory.java

private static KeyStore getKeyStore(File keyStore, String keyStorePassword) throws IOException {
    KeyStore ks = null;/*www.  ja  v a2s  .  c o  m*/
    InputStream is = new FileInputStream(keyStore);
    try {
        ks = KeyStore.getInstance("JKS");
        ks.load(is, keyStorePassword.toCharArray());
    } catch (Exception ex) {
        if (ex instanceof RuntimeException) {
            throw ((RuntimeException) ex);
        }
        throw new IOException(ex);
    } finally {
        Closeables.closeQuietly(is);
    }
    return ks;
}

From source file:org.apache.drill.exec.rpc.control.ControllerImpl.java

public void close() {
    Closeables.closeQuietly(server);
    for (ControlConnectionManager bt : connectionRegistry) {
        bt.close();
    }
}

From source file:org.apache.provisionr.api.util.BuilderWithOptions.java

/**
 * Load options from a properties file available as a resource on the classpath
 */// www .j a va 2 s .  c om
public P optionsFromResource(String resource) {
    Properties properties = new Properties();
    ByteArrayInputStream in = null;
    try {
        in = new ByteArrayInputStream(Resources.toByteArray(Resources.getResource(resource)));
        properties.load(in);
        return options(properties);

    } catch (IOException e) {
        throw Throwables.propagate(e);
    } finally {
        Closeables.closeQuietly(in);
    }
}

From source file:net.sourceforge.vaticanfetcher.model.index.IndexWriterAdapter.java

private void reopenWriterAndThrow(@NotNull OutOfMemoryError e) throws IOException, CheckedOutOfMemoryError {
    /*/*from www .j  a  v a  2s.c  o  m*/
     * According to the IndexWriter javadoc, we're supposed to immediately close the IndexWriter if 
     * IndexWriter.addDocument(...) or IndexWriter.updateDocument(...) hit OutOfMemoryErrors.
     */
    Directory indexDir = writer.getDirectory();
    Closeables.closeQuietly(writer);
    writer = new IndexWriter(indexDir, IndexRegistry.analyzer, MaxFieldLength.UNLIMITED);
    throw new CheckedOutOfMemoryError(e);
}

From source file:io.fabric8.process.manager.GenerateControllerKinds.java

public void run() throws Exception {
    File baseDir = new File(System.getProperty("basedir", "."));
    File srcDir = new File(baseDir, "src/main/resources");
    assertTrue("source dir doesn't exist! " + srcDir, srcDir.exists());
    assertTrue("source folder is not a directory " + srcDir, srcDir.isDirectory());

    File classesDir = new File(baseDir, "target/classes");
    File outFile = new File(classesDir, "io/fabric8/process/manager/controllerKinds");
    outFile.getParentFile().mkdirs();/*from w  w w  . j a  v a2  s  . c  o  m*/

    System.out.println("Generating controller kinds file: " + outFile);
    FileWriter writer = null;
    try {
        writer = new FileWriter(outFile);

        File[] list = srcDir.listFiles();
        String postfix = ".json";
        List<String> kinds = Lists.newArrayList();
        assertNotNull("No JSON files found in source dir: " + srcDir, list);
        for (File file : list) {
            if (!file.isFile())
                continue;
            String name = file.getName();
            if (name.endsWith(postfix)) {
                String kind = name.substring(0, name.length() - postfix.length());
                kinds.add(kind);
                writer.write(kind + "\n");
            }
        }

        System.out.println("Found controller kinds: " + kinds);
    } finally {
        Closeables.closeQuietly(writer);
    }

    // lets try find the process tarball
    String groupId = System.getProperty("groupId", "io.fabric8.process");
    String artifactId = "process-launcher";
    String version = System.getProperty("version", "1.1.0-SNAPSHOT");
    String classifier = "bin";
    String extension = "tar.gz";

    String name = groupId + "/" + artifactId + "/" + version;
    System.out.println("Loading bundle: " + name);

    File file = new File(baseDir + "/../process-launcher/target/" + artifactId + "-" + version + "-bin.tar.gz");

    assertNotNull("Cannot find the file for " + name + " using " + file.getPath(), file);
    File newFile = new File(classesDir, "process-launcher.tar.gz");
    Files.copy(file, newFile); // lets leave a copy there though so the next build works

    System.out.println("Copied process launch tarball to " + newFile);
}