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.culturegraph.mf.ide.domain.FluxCommandMetadata.java

private static Properties properties(ClassLoader loader) throws IOException {
    Properties commands = new Properties();
    String propertiesFileName = "flux-commands.properties";
    InputStream propertiesFile = loader.getResourceAsStream(propertiesFileName);
    try {/*from   ww  w.  j  a  v a 2s .co m*/
        if (propertiesFile == null)
            throw new FileNotFoundException("Could not find " + propertiesFileName);
        commands.load(propertiesFile);
        return commands;
    } finally {
        Closeables.closeQuietly(propertiesFile);
    }
}

From source file:com.xebialabs.overthere.Overthere.java

/**
* Creates a connection.// w ww .  j  av a2 s.  co  m
* 
* @param protocol
*            The protocol to use, e.g. "local".
* @param options
*            A set of options to use for the connection.
* @return the connection.
*/
public static OverthereConnection getConnection(String protocol, final ConnectionOptions options) {
    if (!protocols.get().containsKey(protocol)) {
        throw new IllegalArgumentException("Unknown connection protocol " + protocol);
    }

    logger.trace("Connection for protocol {} requested with the following connection options: {}", protocol,
            options);

    ConnectionOptions jumpstationOptions = options.get(JUMPSTATION, null);
    AddressPortMapper mapper = new DefaultAddressPortMapper();
    if (jumpstationOptions != null) {
        mapper = (SshTunnelConnection) Overthere.getConnection(SSH_PROTOCOL, jumpstationOptions);
    }
    try {
        return buildConnection(protocol, options, mapper);
    } catch (RuntimeException exc) {
        Closeables.closeQuietly(mapper);
        throw exc;
    }
}

From source file:com.google.android.dialer.util.HttpFetcher.java

public static byte[] getRequestAsByteArray(Context context, String url, List<Pair<String, String>> list)
        throws IOException, AuthException {
    Preconditions.checkNotNull(url);/*w  w w.  j  a va  2s .  c o  m*/
    String rewrittenUrl = reWriteUrl(context, url);

    if (rewrittenUrl == null) {
        if (Log.DEBUG) {
            Log.d(TAG, "url " + obfuscateUrl(url) + " is blocked.  Ignoring request.");
        }
        return null;
    } else {
        if (!rewrittenUrl.equals(url) && Log.DEBUG) {
            Log.d(TAG,
                    "Original url: " + obfuscateUrl(url) + ", after re-write: " + obfuscateUrl(rewrittenUrl));
        }
        if (Log.DEBUG) {
            Log.d(TAG, "fetching " + obfuscateUrl(rewrittenUrl));
        }

        byte[] byteArray = null;
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        boolean failed = false;
        long uptimeMillis = SystemClock.uptimeMillis();
        ;
        int responseCode = 0;
        ByteArrayOutputStream byteArrayOutputStream = null;

        try {
            connection = (HttpURLConnection) new URL(rewrittenUrl).openConnection();
            addHeaders(connection, list);
            responseCode = connection.getResponseCode();
            Log.d(TAG, "response code: " + responseCode);
            int n = responseCode / 100;
            if (n == 2) {
                inputStream = connection.getInputStream();
                byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] array = new byte[1024];
                while (true) {
                    int read = inputStream.read(array);
                    if (read == -1) {
                        break;
                    }
                    byteArrayOutputStream.write(array, 0, read);
                }
            } else {
                failed = true;
            }
        } finally {
            Closeables.closeQuietly(inputStream);
            if (connection != null) {
                connection.disconnect();
            }
        }

        if (failed) {
            handleBadResponse(rewrittenUrl, byteArrayOutputStream.toByteArray());
            if (responseCode == 401) {
                throw new AuthException("Auth error");
            }
            return null;
        } else {
            byteArray = byteArrayOutputStream.toByteArray();
            Log.d(TAG, "received " + byteArray.length + " bytes");
            Log.d(TAG, "fetch took " + (SystemClock.uptimeMillis() - uptimeMillis) + " ms");
            return byteArray;
        }
    }
}

From source file:org.apache.jackrabbit.oak.osgi.ObserverTracker.java

@Override
public void removedService(ServiceReference reference, Object service) {
    Closeable subscription = subscriptions.remove(reference);
    if (subscription != null) {
        Closeables.closeQuietly(subscription);
        bundleContext.ungetService(reference);
    }// w  w  w  .  j  a  v  a 2s .c  o  m
}

From source file:org.kohsuke.stapler.AbstractAPT6.java

/**
 * Stores the given content to a location under the class output directory.
 *///from  www.  j  av  a2 s. c o  m
protected final void store(final Content content) {
    OutputStream os = null;
    try {
        final String path = content.location();
        final FileObject f = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", path);
        content.store(os = f.openOutputStream());
    } catch (final FilerException e) {
        // someone else is already processing this file!
    } catch (final Exception e) {
        processingEnv.getMessager().printMessage(Kind.ERROR, e.toString());
    } finally {
        Closeables.closeQuietly(os);
    }
}

From source file:com.linecorp.armeria.common.util.Version.java

/**
 * Retrieves the version information of Armeria artifacts using the specified {@link ClassLoader}.
 *
 * @return A {@link Map} whose keys are Maven artifact IDs and whose values are {@link Version}s
 *//*from w  w  w.  j a v a  2 s  .  co  m*/
public static Map<String, Version> identify(ClassLoader classLoader) {
    if (classLoader == null) {
        classLoader = getContextClassLoader();
    }

    // Collect all properties.
    Properties props = new Properties();
    try {
        Enumeration<URL> resources = classLoader.getResources(PROP_RESOURCE_PATH);
        while (resources.hasMoreElements()) {
            URL url = resources.nextElement();
            InputStream in = url.openStream();
            try {
                props.load(in);
            } finally {
                Closeables.closeQuietly(in);
            }
        }
    } catch (Exception ignore) {
        // Not critical. Just ignore.
    }

    // Collect all artifactIds.
    Set<String> artifactIds = new HashSet<>();
    for (Object o : props.keySet()) {
        String k = (String) o;

        int dotIndex = k.indexOf('.');
        if (dotIndex <= 0) {
            continue;
        }

        String artifactId = k.substring(0, dotIndex);

        // Skip the entries without required information.
        if (!props.containsKey(artifactId + PROP_VERSION) || !props.containsKey(artifactId + PROP_COMMIT_DATE)
                || !props.containsKey(artifactId + PROP_SHORT_COMMIT_HASH)
                || !props.containsKey(artifactId + PROP_LONG_COMMIT_HASH)
                || !props.containsKey(artifactId + PROP_REPO_STATUS)) {
            continue;
        }

        artifactIds.add(artifactId);
    }

    Map<String, Version> versions = new HashMap<>();
    for (String artifactId : artifactIds) {
        versions.put(artifactId,
                new Version(artifactId, props.getProperty(artifactId + PROP_VERSION),
                        parseIso8601(props.getProperty(artifactId + PROP_COMMIT_DATE)),
                        props.getProperty(artifactId + PROP_SHORT_COMMIT_HASH),
                        props.getProperty(artifactId + PROP_LONG_COMMIT_HASH),
                        props.getProperty(artifactId + PROP_REPO_STATUS)));
    }

    return versions;
}

From source file:org.apache.mahout.clustering.spectral.common.VectorCache.java

/**
 * Loads a Vector from the specified path. Returns null if no vector exists.
 *///from  w  w  w .  ja va  2s .  c  o  m
public static Vector load(Configuration conf, Path input) throws IOException {
    log.info("Loading vector from: {}", input);
    SequenceFileValueIterator<VectorWritable> iterator = new SequenceFileValueIterator<VectorWritable>(input,
            true, conf);
    try {
        return iterator.next().get();
    } finally {
        Closeables.closeQuietly(iterator);
    }
}

From source file:com.silverpeas.lookV5.AjaxServletRSS.java

public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String enc = getEncodingParameter(req);
    res.setContentType("text/xml;charset=" + enc);
    String loadedUrl = EncodeHelper.transformHtmlCode(req.getParameter("loadedUrl"));
    InputStream rss = null;//from   w w  w.j a v  a 2 s.c om
    try {
        URL url = new URL(loadedUrl);
        rss = url.openStream();
        ByteStreams.copy(rss, res.getOutputStream());
    } finally {
        Closeables.closeQuietly(rss);
    }
}

From source file:com.github.fhirschmann.clozegen.lib.components.api.JCasFileWriter.java

@Override
public void collectionProcessComplete() {
    Closeables.closeQuietly(outputBuffer);
}

From source file:org.kitesdk.apps.spark.spi.streaming.SparkStreamingJobManager.java

public static StreamDescription loadDescription(FileSystem fs, Path appRoot, String jobName) {

    Path streamingJobPath = jobDescriptionFile(appRoot, jobName);

    StringBuilder builder = new StringBuilder();
    InputStream input = null;//from  ww w  .j  a  v a2  s  . com

    try {
        input = fs.open(streamingJobPath);

        InputStreamReader streamReader = new InputStreamReader(input);

        BufferedReader reader = new BufferedReader(streamReader);

        String line;

        while ((line = reader.readLine()) != null) {

            builder.append(line);
        }
    } catch (IOException e) {
        throw new AppException(e);
    } finally {
        Closeables.closeQuietly(input);
    }

    return StreamDescription.parseJson(builder.toString());
}