Example usage for org.apache.commons.io.input AutoCloseInputStream AutoCloseInputStream

List of usage examples for org.apache.commons.io.input AutoCloseInputStream AutoCloseInputStream

Introduction

In this page you can find the example usage for org.apache.commons.io.input AutoCloseInputStream AutoCloseInputStream.

Prototype

public AutoCloseInputStream(InputStream in) 

Source Link

Document

Creates an automatically closing proxy for the given input stream.

Usage

From source file:eu.annocultor.utils.OntologySubtractor.java

public static void main(String[] args) throws Exception {

    boolean copy = checkNoCopyOption(args);

    if (args.length == 2 || args.length == 3) {

        File sourceDir = new File(args[0]);
        File destinationDir = new File(args[1]);

        checkSrcAndDstDirs(sourceDir, destinationDir);

        Collection<String> filesWithDeletedStatements = listNameStamsForFilesWithDeletedStatements(sourceDir);

        if (filesWithDeletedStatements.isEmpty()) {
            System.out.println(//from w w w.j  a va2  s. c  o  m
                    "Did not found any file *.*.*.deleted.rdf with statements to be deleted. Do nothing and exit.");
        } else {

            System.out.println(
                    "Found " + filesWithDeletedStatements.size() + " files with statements to be deleted");
            System.out.println(
                    "Copying all RDF files from " + sourceDir.getName() + " to " + destinationDir.getName());

            if (copy) {
                copyRdfFiles(sourceDir, destinationDir);
            }

            sutractAll(sourceDir, destinationDir, filesWithDeletedStatements);
        }
    } else {
        for (Object string : IOUtils.readLines(new AutoCloseInputStream(
                OntologySubtractor.class.getResourceAsStream("/subtractor/readme.txt")))) {
            System.out.println(string.toString());
        }
    }
}

From source file:com.anjlab.tapestry5.services.ConfigHelper.java

public static ConfigHelper fromClasspathResource(String resourceName) throws IOException {
    logger.info("Reading config from classpath: {}", resourceName);
    InputStream input = ConfigHelper.class.getClassLoader().getResourceAsStream(resourceName);
    if (input == null) {
        throw new IOException("Classpath resource not found: " + resourceName);
    }/*from w ww  .j  av  a  2 s.  c o m*/
    return new ConfigHelper(new AutoCloseInputStream(input));
}

From source file:guru.nidi.loader.url.SimpleUrlFetcher.java

@Override
public InputStream fetchFromUrl(CloseableHttpClient client, String base, String name, long ifModifiedSince)
        throws IOException {
    final String suffix = (name == null || name.length() == 0) ? "" : ("/" + encodeUrl(name));
    final HttpGet get = postProcessGet(new HttpGet(base + suffix));
    if (ifModifiedSince > 0) {
        get.addHeader("if-modified-since", httpDate(ifModifiedSince));
    }//ww  w.j  av a  2  s . c  o  m
    final CloseableHttpResponse getResult = client.execute(get);
    switch (getResult.getStatusLine().getStatusCode()) {
    case HttpStatus.SC_OK:
        // remove AutoCloseInputStream as soon as
        // https://github.com/raml-org/raml-java-parser/issues/72 is fixed
        return new AutoCloseInputStream(getResult.getEntity().getContent());
    case HttpStatus.SC_NOT_MODIFIED:
        EntityUtils.consume(getResult.getEntity());
        return null;
    default:
        throw new IOException("Http response status not ok: " + getResult.getStatusLine().toString());
    }
}

From source file:com.bittorrent.mpetazzoni.bencode.BDecoder.java

/**
 * Decode a B-encoded byte buffer./*from   www .  j  a  v  a  2  s.co  m*/
 *
 * <p>
 * Automatically instantiates a new BDecoder for the provided buffer and
 * decodes its root member.
 * </p>
 *
 * @param data The {@link ByteBuffer} to read from.
 */
public static BEValue bdecode(ByteBuffer data) throws IOException {
    return BDecoder.bdecode(new AutoCloseInputStream(new ByteArrayInputStream(data.array())));
}

From source file:com.github.neio.filesystem.paths.FilePath.java

@Override
public BigInteger sha1Hash() throws NeIOException, FilesystemException {
    try {//from w w  w  .j av a2 s .  c  om
        MessageDigest hash = MessageDigest.getInstance("SHA1");
        DigestOutputStream digestOutputStream = new DigestOutputStream(new NullOutputStream(), hash);

        IOUtils.copy(new AutoCloseInputStream(new FileInputStream(new java.io.File(super.path))),
                digestOutputStream);

        return new BigInteger(hash.digest());
    } catch (NoSuchAlgorithmException e) {
        throw new NeIOException("Unable calculate hash due to SHA1 Algorithm not being found", e);
    } catch (FileNotFoundException e) {
        throw new FilesystemException("File pointed at by this path [" + super.path + "] does not exist", e);
    } catch (IOException e) {
        throw new NeIOException(e);
    }
}

From source file:eu.annocultor.tools.GeneratorOfXmlSchemaForConvertersDoclet.java

public static boolean start(RootDoc root) {
    Logger log = Logger.getLogger("DocletGenerator");

    if (destination == null) {
        try {/*w  ww  .j av  a  2  s  .c om*/
            // loaded from RuleListenersFragment
            ruleListenerDef = IOUtils.toString(GeneratorOfXmlSchemaForConvertersDoclet.class
                    .getResourceAsStream("/RuleListenersFragment.xsd"), "UTF-8");

            String fn = System.getenv("annocultor.xconverter.destination.file.name");
            fn = (fn == null) ? "./../../../src/site/resources/schema/XConverterInclude.xsd" : fn;

            destination = new File(fn);
            if (destination.exists()) {
                destination.delete();
            }

            // initial copy of the template and include
            FileOutputStream os;
            os = new FileOutputStream(new File(destination.getParentFile(), "XConverter.xsd"));
            IOUtils.copy(new AutoCloseInputStream(GeneratorOfXmlSchemaForConvertersDoclet.class
                    .getResourceAsStream("/XConverterTemplate.xsd")), os);
            os.close();
            os = new FileOutputStream(destination);
            IOUtils.copy(new AutoCloseInputStream(GeneratorOfXmlSchemaForConvertersDoclet.class
                    .getResourceAsStream("/XConverterInclude.xsd")), os);
            os.close();
        } catch (Exception e) {
            try {
                throw new RuntimeException("On destination " + destination.getCanonicalPath(), e);
            } catch (IOException e1) {
                // too bad
                throw new RuntimeException(e1);
            }
        }
    }

    try {
        String s = Utils.loadFileToString(destination.getCanonicalPath(), "\n");
        int breakPoint = s.indexOf(XSD_TEXT_TO_REPLACED_WITH_GENERATED_XML_SIGNATURES);
        if (breakPoint < 0) {
            throw new Exception(
                    "Signature not found in XSD: " + XSD_TEXT_TO_REPLACED_WITH_GENERATED_XML_SIGNATURES);
        }
        String preambula = s.substring(0, breakPoint);
        String appendix = s.substring(breakPoint);

        destination.delete();

        PrintWriter schemaWriter = new PrintWriter(destination);
        schemaWriter.print(preambula);

        ClassDoc[] classes = root.classes();
        for (int i = 0; i < classes.length; ++i) {
            ClassDoc cd = classes[i];
            PrintWriter documentationWriter = null;
            if (getSuperClasses(cd).contains(Rule.class.getName())) {
                for (ConstructorDoc constructorDoc : cd.constructors()) {
                    if (constructorDoc.isPublic()) {
                        if (isMeantForXMLAccess(constructorDoc)) {
                            // dump APT doc
                            if (documentationWriter == null) {
                                // Create APT file and write the rule description
                                File file = new File("./../../../src/site/xdoc/rules." + cd.name() + ".xml");
                                documentationWriter = new PrintWriter(file);
                                log.info("Generating doc for rule " + file.getCanonicalPath());
                                printRuleDocStart(cd, documentationWriter);
                            }

                            // create XSD 

                            // check for the init() method
                            boolean initFound = false;
                            for (MethodDoc methodDoc : cd.methods()) {
                                if ("init".equals(methodDoc.name())) {
                                    if (methodDoc.parameters().length == 0) {
                                        initFound = true;
                                        break;
                                    }
                                }
                            }
                            if (!initFound) {
                                //                           throw new Exception("Method init() is required. Please make sure NOW that it is called in constructor " + cd.name());
                            }

                            printConstructorSchema(constructorDoc, schemaWriter);

                            if (documentationWriter != null) {
                                printConstructorDoc(constructorDoc, documentationWriter);
                            }
                        }
                    }
                }
            }

            if (documentationWriter != null) {
                printRuleDocEnd(documentationWriter);
            }
        }

        schemaWriter.print(appendix);
        schemaWriter.close();
        log.info("Saved to " + destination.getCanonicalPath());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return true;
}

From source file:com.xpn.xwiki.doc.FilesystemAttachmentContent.java

@Override
public InputStream getContentInputStream() {
    /** An InputStream which locks a lock while it is being read. */
    final class LockingFileInputStream extends FileInputStream {
        /** The lock to lock while reading the file. */
        private Lock lock;

        /**//from   www . j  a  va2 s  . co  m
         * The Constructor.
         *
         * @param toRead the file for this stream to read.
         * @param lock the lock to lock on creation of the stream and unlock when it is closed.
         * @throws IOException if the extended FileInputStream throws one.
         */
        public LockingFileInputStream(final File toRead, final Lock lock) throws IOException {
            super(toRead);
            this.lock = lock;
            lock.lock();
        }

        /** {@inheritDoc} */
        public void close() throws IOException {
            // Make sure this only happens once.
            if (this.lock != null) {
                super.close();
                this.lock.unlock();
                this.lock = null;
            }
        }
    }

    try {
        return new AutoCloseInputStream(new LockingFileInputStream(this.storageFile, this.lock.readLock()));
    } catch (IOException e) {
        throw new RuntimeException("Failed to get InputStream", e);
    }
}

From source file:com.xpn.xwiki.doc.XWikiAttachmentContent.java

/**
 * @return an InputStream to read the binary content of this attachment.
 * @since 2.3M2//from   w w  w .j a v a2  s.c  o m
 */
public InputStream getContentInputStream() {
    try {
        return new AutoCloseInputStream(this.file.getInputStream());
    } catch (IOException e) {
        throw new RuntimeException("Failed to get InputStream", e);
    }
}

From source file:gov.nih.nci.caarray.dataStorage.database.DatabaseMultipartBlobDataStorage.java

/**
 * {@inheritDoc}/*from  ww  w  .j  a va2s .  c om*/
 */
@Override
public InputStream openInputStream(URI handle, boolean compressed) throws DataStoreException {
    checkScheme(handle);
    try {
        return new AutoCloseInputStream(FileUtils.openInputStream(openFile(handle, compressed)));
    } catch (final IOException e) {
        throw new DataStoreException("Could not open input stream for data: ", e);
    }
}

From source file:gov.nih.nci.caarray.application.fileaccess.FileAccessServiceStub.java

@Override
public InputStream openInputStream(URI handle, boolean compressed) throws DataStoreException {
    checkScheme(handle);//from ww w. j av a2 s. c  o  m
    try {
        return new AutoCloseInputStream(FileUtils.openInputStream(openFile(handle, compressed)));
    } catch (final IOException e) {
        throw new DataStoreException("Could not open input stream for data " + handle + ":", e);
    }
}