Example usage for java.io Closeable close

List of usage examples for java.io Closeable close

Introduction

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

Prototype

public void close() throws IOException;

Source Link

Document

Closes this stream and releases any system resources associated with it.

Usage

From source file:org.candlepin.util.CrlFileUtil.java

/**
 * Updates the specified CRL file by adding or removing entries. If both lists are either null
 * or empty, the CRL file will not be modified by this method. If the file does not exist or
 * appears to be empty, it will be initialized before processing the lists.
 *
 * @param file/*from   w ww.j a v a  2  s . c o m*/
 *  The CRL file to update
 *
 * @param revoke
 *  A collection of serials to revoke (add)
 *
 * @param unrevoke
 *  A collection of serials to unrevoke (remove)
 *
 * @throws IOException
 *  if an IO error occurs while updating the CRL file
 */
public void updateCRLFile(File file, final Collection<BigInteger> revoke, final Collection<BigInteger> unrevoke)
        throws IOException {

    if (!file.exists() || file.length() == 0) {
        this.initializeCRLFile(file, revoke);
        return;
    }

    File strippedFile = stripCRLFile(file);

    InputStream input = null;
    InputStream reaper = null;

    BufferedOutputStream output = null;
    OutputStream filter = null;
    OutputStream encoder = null;

    try {
        // Impl note:
        // Due to the way the X509CRLStreamWriter works (and the DER format in general), we have
        // to make two passes through the file.
        input = new Base64InputStream(new FileInputStream(strippedFile));
        reaper = new Base64InputStream(new FileInputStream(strippedFile));

        // Note: This will break if we ever stop using RSA keys
        PrivateKey key = this.pkiReader.getCaKey();
        X509CRLStreamWriter writer = new X509CRLStreamWriter(input, (RSAPrivateKey) key,
                this.pkiReader.getCACert());

        // Add new entries
        if (revoke != null) {
            Date now = new Date();
            for (BigInteger serial : revoke) {
                writer.add(serial, now, CRLReason.privilegeWithdrawn);
            }
        }

        // Unfortunately, we need to do the prescan before checking if we have changes queued,
        // or we could miss cases where we have entries to remove, but nothing to add.
        if (unrevoke != null && !unrevoke.isEmpty()) {
            writer.preScan(reaper, new CRLEntryValidator() {
                public boolean shouldDelete(X509CRLEntryObject entry) {
                    return unrevoke.contains(entry.getSerialNumber());
                }
            });
        } else {
            writer.preScan(reaper);
        }

        // Verify we actually have work to do now
        if (writer.hasChangesQueued()) {
            output = new BufferedOutputStream(new FileOutputStream(file));
            filter = new FilterOutputStream(output) {
                private boolean needsLineBreak = true;

                public void write(int b) throws IOException {
                    this.needsLineBreak = (b != (byte) '\n');
                    super.write(b);
                }

                public void write(byte[] buffer) throws IOException {
                    this.needsLineBreak = (buffer[buffer.length - 1] != (byte) '\n');
                    super.write(buffer);
                }

                public void write(byte[] buffer, int off, int len) throws IOException {
                    this.needsLineBreak = (buffer[off + len - 1] != (byte) '\n');
                    super.write(buffer, off, len);
                }

                public void close() throws IOException {
                    if (this.needsLineBreak) {
                        super.write((int) '\n');
                        this.needsLineBreak = false;
                    }

                    // Impl note:
                    // We're intentionally not propagating the call here.
                }
            };
            encoder = new Base64OutputStream(filter, true, 76, new byte[] { (byte) '\n' });

            output.write("-----BEGIN X509 CRL-----\n".getBytes());

            writer.lock();
            writer.write(encoder);
            encoder.close();
            filter.close();

            output.write("-----END X509 CRL-----\n".getBytes());
            output.close();
        }
    } catch (GeneralSecurityException e) {
        // This should never actually happen
        log.error("Unexpected security error occurred while retrieving CA key", e);
    } catch (CryptoException e) {
        // Something went horribly wrong with the stream writer
        log.error("Unexpected error occurred while writing new CRL file", e);
    } finally {
        for (Closeable stream : Arrays.asList(encoder, output, reaper, input)) {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    log.error("Unexpected exception occurred while closing stream: {}", stream, e);
                }
            }
        }

        if (!strippedFile.delete()) {
            log.error("Unable to delete temporary CRL file: {}", strippedFile);
        }
    }
}

From source file:org.mule.module.launcher.application.DefaultMuleApplication.java

@Override
public void dispose() {
    // moved wrapper logic into the actual implementation, as redeploy() invokes it directly, bypassing
    // classloader cleanup
    try {//from   w w  w.  j av a 2 s .c o m
        ClassLoader appCl = getDeploymentClassLoader();
        // if not initialized yet, it can be null
        if (appCl != null) {
            Thread.currentThread().setContextClassLoader(appCl);
        }

        doDispose();

        if (appCl != null) {
            // close classloader to release jar connections in lieu of Java 7's ClassLoader.close()
            if (appCl instanceof Closeable) {
                Closeable classLoader = (Closeable) appCl;
                try {
                    classLoader.close();
                } catch (IOException e) {
                    // Ignore
                }
            }
        }
    } finally {
        // kill any refs to the old classloader to avoid leaks
        Thread.currentThread().setContextClassLoader(null);
    }
}

From source file:com.ridgelineapps.wallpaper.photosite.FlickrUtils.java

/**
 * Closes the specified stream./*from ww w .j a  va  2 s  . c o  m*/
 *
 * @param stream The stream to close.
 */
static void closeStream(Closeable stream) {
    if (stream != null) {
        try {
            stream.close();
        } catch (IOException e) {
            android.util.Log.e(FlickrUtils.LOG_TAG, "Could not close stream", e);
        }
    }
}

From source file:com.aliyun.fs.oss.blk.JetOssFileSystemStore.java

private void closeQuietly(Closeable closeable) {
    if (closeable != null) {
        try {/*from   ww w. j  av  a 2  s .c o m*/
            closeable.close();
        } catch (IOException e) {
            // ignore
        }
    }
}

From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java

/**
 * Closes all the provided streams.//w  w w. ja  v  a 2  s  . com
 *
 * @param streams : One or more of streams.
 */
private void closeStreams(Closeable... streams) {

    try {
        for (Closeable stream : streams) {
            if (stream != null) {
                stream.close();
            }
        }
    } catch (IOException e) {
        log.error("Error closing the stream.", e);
    }
}

From source file:kornell.server.ProxyServlet.java

protected void closeQuietly(Closeable closeable) {
    try {//from ww  w .j a va 2s  .  co  m
        if (closeable != null)
            closeable.close();
    } catch (IOException e) {
        //TODO: Understand and solve log(e.getMessage(), e);
    }
}

From source file:org.bytesoft.bytetcc.work.CleanupWork.java

public void closeQuietly(Closeable closeable) {
    if (closeable != null) {
        try {//from   w w w  .j  a  v  a 2 s.c o  m
            closeable.close();
        } catch (IOException ex) {
            logger.debug(ex.getMessage());
        }
    }
}

From source file:org.apache.solr.handler.dataimport.FsMailEntityProcessor.java

private void close(Closeable c) {
    if (c != null) {
        try {//from   ww  w. j a va 2  s  .  co m
            c.close();
        } catch (IOException e) {
            LOG.warn("Error closing Closeable: " + e.getMessage(), e);
        }
    }
}

From source file:org.apache.bval.jsr.ApacheValidatorFactory.java

public void close() {
    try {/*from  w  ww  .  j  a  v  a 2  s .c o m*/
        for (final Closeable c : toClose) {
            c.close();
        }
        toClose.clear();
    } catch (final Exception e) {
        // no-op
    }
}

From source file:info.servertools.core.util.FileUtils.java

public static void zipDirectory(File directory, File zipfile, @Nullable Collection<String> fileBlacklist,
        @Nullable Collection<String> folderBlacklist) throws IOException {
    URI baseDir = directory.toURI();
    Deque<File> queue = new LinkedList<>();
    queue.push(directory);/*from   w  ww  . java  2s.  c  om*/
    OutputStream out = new FileOutputStream(zipfile);
    Closeable res = out;
    try {
        ZipOutputStream zout = new ZipOutputStream(out);
        res = zout;
        while (!queue.isEmpty()) {
            directory = queue.removeFirst();
            File[] dirFiles = directory.listFiles();
            if (dirFiles != null && dirFiles.length != 0) {
                for (File child : dirFiles) {
                    if (child != null) {
                        String name = baseDir.relativize(child.toURI()).getPath();
                        if (child.isDirectory()
                                && (folderBlacklist == null || !folderBlacklist.contains(child.getName()))) {
                            queue.push(child);
                            name = name.endsWith("/") ? name : name + "/";
                            zout.putNextEntry(new ZipEntry(name));
                        } else {
                            if (fileBlacklist != null && !fileBlacklist.contains(child.getName())) {
                                zout.putNextEntry(new ZipEntry(name));
                                copy(child, zout);
                                zout.closeEntry();
                            }
                        }
                    }
                }
            }
        }
    } finally {
        res.close();
    }
}