Example usage for java.io Closeable Closeable

List of usage examples for java.io Closeable Closeable

Introduction

In this page you can find the example usage for java.io Closeable Closeable.

Prototype

Closeable

Source Link

Usage

From source file:com.tinspx.util.io.callbacks.FileTests.java

public static Closeable teardownTestDir(@NonNull final File testDir) throws IOException {
    return new Closeable() {
        @Override//from   w w w.  jav a2  s.co m
        public void close() throws IOException {
            FileUtils.deleteDirectory(testDir);
        }
    };
}

From source file:org.apache.jackrabbit.oak.upgrade.cli.node.Jackrabbit2Factory.java

private static Closeable asCloseable(final RepositoryContext context) {
    return new Closeable() {
        @Override//from w ww  .  j a v  a 2 s.c om
        public void close() throws IOException {
            context.getRepository().shutdown();
        }
    };
}

From source file:org.ow2.chameleon.core.utils.BundleHelper.java

/**
 * Checks whether the given file is a bundle or not.
 * The check is based on the {@literal Bundle-ManifestVersion} header.
 * If the file is a directory this method checks if the directory is an exploded bundle.
 * If the file is a jar file, it checks the manifest.
 *
 * @param file the file.//from  ww w.  java 2  s .com
 * @return {@literal true} if it's a bundle, {@literal false} otherwise.
 */
public static boolean isBundle(File file) {

    if (file.isFile() && file.getName().endsWith(".jar")) {
        JarFile jar = null;
        try {
            jar = new JarFile(file);
            return jar.getManifest() != null && jar.getManifest().getMainAttributes() != null
                    && jar.getManifest().getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME) != null;
            // We check the symbolic name because it's the only mandatory header
            // see http://wiki.osgi.org/wiki/Bundle-SymbolicName.
        } catch (IOException e) {
            LoggerFactory.getLogger(BundleHelper.class)
                    .error("Cannot check if the file {} is a bundle, " + "cannot open it", file.getName(), e);
            return false;
        } finally {
            final JarFile finalJar = jar;
            IOUtils.closeQuietly(new Closeable() {
                @Override
                public void close() throws IOException {
                    if (finalJar != null) {
                        finalJar.close();
                    }
                }
            });
        }
    }

    return isExplodedBundle(file);

}

From source file:org.apache.jackrabbit.oak.upgrade.cli.blob.S3DataStoreFactory.java

private static Closeable asCloseable(final CachingDataStore store, final File tempHomeDir) {
    return new Closeable() {
        @Override// w  w w  . j  av  a  2  s  .c  o m
        public void close() throws IOException {
            try {
                while (!store.getPendingUploads().isEmpty()) {
                    log.info("Waiting for following uploads to finish: " + store.getPendingUploads());
                    Thread.sleep(1000);
                }
                store.close();
                FileUtils.deleteDirectory(tempHomeDir);
            } catch (DataStoreException e) {
                throw new IOException(e);
            } catch (InterruptedException e) {
                throw new IOException(e);
            }
        }
    };
}

From source file:org.callimachusproject.client.AutoClosingHttpClient.java

@Override
protected CloseableHttpResponse doExecute(final HttpHost host, final HttpRequest request, HttpContext ctx)
        throws IOException, ClientProtocolException {
    if (++numberOfClientCalls % 100 == 0) {
        // Deletes the (no longer used) temporary cache files from disk.
        cleanResources();//from w  w w  .j  a va  2s  . c om
    }
    CloseableHttpResponse resp = client.execute(host, request, ctx);
    HttpEntity entity = resp.getEntity();
    if (entity != null) {
        resp.setEntity(new CloseableEntity(entity, new Closeable() {
            public void close() throws IOException {
                // this also keeps this object from being finalized
                // until all its response entities are consumed
                String uri = request.getRequestLine().getUri();
                logger.debug("Remote {}{} closed", host, uri);
            }
        }));
    }
    return resp;
}

From source file:org.flowerplatform.communication.public_resources.PublicResourcesServlet.java

protected Pair<InputStream, Closeable> getInputStreamForFileWithinZip(final InputStream fileInputStream,
        String fileWithinZip) throws IOException {
    final BufferedInputStream bis = new BufferedInputStream(fileInputStream, DEFAULT_BUFFER_SIZE);
    final ZipInputStream zis = new ZipInputStream(bis);

    Closeable closeable = new Closeable() {

        @Override/*from w  w w .ja v a2s  .  c  o m*/
        public void close() throws IOException {
            zis.close();
            bis.close();
            fileInputStream.close();
        }
    };

    for (ZipEntry ze = zis.getNextEntry(); ze != null; ze = zis.getNextEntry()) {
        if (fileWithinZip.equals(ze.getName())) {
            return new Pair<InputStream, Closeable>(zis, closeable);
        }
    }

    closeable.close();
    return null;
}

From source file:org.callimachusproject.server.helpers.AutoClosingAsyncClient.java

private FutureCallback<HttpResponse> track(FutureCallback<HttpResponse> callback) {
    return new ResponseCallback(callback) {
        public void completed(HttpResponse result) {
            try {
                HttpEntity entity = result.getEntity();
                if (entity != null) {
                    result.setEntity(new CloseableEntity(entity, new Closeable() {
                        public void close() throws IOException {
                            // this also keeps this object from being finalized
                            // until all its response entities are consumed
                            if (++numberOfClientCalls % 100 == 0) {
                                cleanResources();
                            }//from w w w .j  a  v a2 s.  c om
                        }
                    }));
                }
                super.completed(result);
            } catch (RuntimeException ex) {
                super.failed(ex);
            }
        }
    };
}

From source file:mil.nga.giat.geowave.datastore.accumulo.query.AccumuloConstraintsDelete.java

@Override
protected CloseableIterator<Object> initCloseableIterator(ScannerBase scanner, Iterator it) {
    return new CloseableIteratorWrapper(new Closeable() {
        boolean closed = false;

        @Override/*from ww  w  .ja  va2 s.  co  m*/
        public void close() throws IOException {
            if (!closed) {
                if (scanner instanceof BatchDeleter) {
                    try {
                        ((BatchDeleter) scanner).delete();
                    } catch (MutationsRejectedException | TableNotFoundException e) {
                        LOGGER.warn("Unable to delete rows by query constraints", e);
                    }
                }
                scanner.close();
            }
            closed = true;
        }
    }, it);
}

From source file:com.microsoft.services.orc.http.impl.AndroidNetworkRunnable.java

@Override
public void run() {
    AndroidHttpClient client = null;// www.j  av  a  2  s. c  o m
    try {

        String userAgent = mRequest.getHeaders().get(Constants.USER_AGENT_HEADER);

        if (userAgent == null) {
            userAgent = "";
        }

        client = AndroidHttpClient.newInstance(userAgent);

        BasicHttpEntityEnclosingRequest realRequest = new BasicHttpEntityEnclosingRequest(
                mRequest.getVerb().toString(), mRequest.getUrl().toString());
        EntityEnclosingRequestWrapper wrapper = new EntityEnclosingRequestWrapper(realRequest);

        Map<String, String> headers = mRequest.getHeaders();
        for (String key : headers.keySet()) {
            wrapper.addHeader(key, headers.get(key));
        }

        if (mRequest.getContent() != null) {
            ByteArrayEntity entity = new ByteArrayEntity(mRequest.getContent());
            wrapper.setEntity(entity);
        } else if (mRequest.getStreamedContent() != null) {
            InputStream stream = mRequest.getStreamedContent();
            InputStreamEntity entity = new InputStreamEntity(stream, mRequest.getStreamedContentSize());
            wrapper.setEntity(entity);
        }

        HttpResponse realResponse = client.execute(wrapper);
        int status = realResponse.getStatusLine().getStatusCode();

        Map<String, List<String>> responseHeaders = new HashMap<String, List<String>>();
        for (Header header : realResponse.getAllHeaders()) {
            List<String> headerValues = new ArrayList<String>();
            for (HeaderElement element : header.getElements()) {
                headerValues.add(element.getValue());
            }
            responseHeaders.put(header.getName(), headerValues);
        }

        HttpEntity entity = realResponse.getEntity();
        InputStream stream = null;

        if (entity != null) {
            stream = entity.getContent();
        }

        if (stream != null) {
            final AndroidHttpClient finalClient = client;
            Closeable closeable = new Closeable() {
                @Override
                public void close() throws IOException {
                    finalClient.close();
                }
            };

            Response response = new ResponseImpl(stream, status, responseHeaders, closeable);

            mFuture.set(response);
        } else {
            client.close();
            mFuture.set(new EmptyResponse(status, responseHeaders));
        }

    } catch (Throwable t) {
        if (client != null) {
            client.close();
        }

        mFuture.setException(t);
    }
}

From source file:org.sonar.api.utils.System2Test.java

@Test
public void close_throws_exception_on_error() {
    Closeable closeable = new Closeable() {
        @Override/*from  w w w .ja v  a 2 s  .c  o  m*/
        public void close() throws IOException {
            throw new IOException("expected");
        }
    };
    try {
        System2.INSTANCE.close(closeable);
        fail();
    } catch (IllegalStateException e) {
        assertThat(e.getCause().getMessage()).isEqualTo("expected");
    }
}