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:com.docd.purefm.test.CommandLineFileTest.java

private String md5sum(final File file) {
    try {//from   w ww.  j a v a  2  s . co  m
        final InputStream fis = new AutoCloseInputStream(new FileInputStream(file));
        return new String(Hex.encodeHex(DigestUtils.md5(fis)));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.norconex.commons.lang.url.URLStreamer.java

private static InputStream responseInputStream(URLConnection conn) throws IOException {
    conn.connect();//from w  w  w  .j a  va 2s. c om
    return new AutoCloseInputStream(conn.getInputStream());
}

From source file:com.yenlo.synapse.transport.vfs.VFSTransportListener.java

/**
 * Process a single file through Axis2//w w  w  . j a  v a 2 s. c om
 * @param entry the PollTableEntry for the file (or its parent directory or archive)
 * @param file the file that contains the actual message pumped into Axis2
 * @throws AxisFault on error
 */
private void processFile(PollTableEntry entry, FileObject file) throws AxisFault {

    try {
        FileContent content = file.getContent();
        String fileName = file.getName().getBaseName();
        String filePath = file.getName().getPath();
        String fileURI = file.getName().getURI();

        metrics.incrementBytesReceived(content.getSize());

        Map<String, Object> transportHeaders = new HashMap<String, Object>();
        transportHeaders.put(VFSConstants.FILE_PATH, filePath);
        transportHeaders.put(VFSConstants.FILE_NAME, fileName);
        transportHeaders.put(VFSConstants.FILE_URI, fileURI);

        try {
            transportHeaders.put(VFSConstants.FILE_LENGTH, content.getSize());
            transportHeaders.put(VFSConstants.LAST_MODIFIED, content.getLastModifiedTime());
        } catch (FileSystemException ignore) {
        }

        MessageContext msgContext = entry.createMessageContext();

        String contentType = entry.getContentType();
        if (BaseUtils.isBlank(contentType)) {
            if (file.getName().getExtension().toLowerCase().endsWith(".xml")) {
                contentType = "text/xml";
            } else if (file.getName().getExtension().toLowerCase().endsWith(".txt")) {
                contentType = "text/plain";
            }
        } else {
            // Extract the charset encoding from the configured content type and
            // set the CHARACTER_SET_ENCODING property as e.g. SOAPBuilder relies on this.
            String charSetEnc = null;
            try {
                if (contentType != null) {
                    charSetEnc = new ContentType(contentType).getParameter("charset");
                }
            } catch (ParseException ex) {
                // ignore
            }
            msgContext.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc);
        }

        // if the content type was not found, but the service defined it.. use it
        if (contentType == null) {
            if (entry.getContentType() != null) {
                contentType = entry.getContentType();
            } else if (VFSUtils.getProperty(content, BaseConstants.CONTENT_TYPE) != null) {
                contentType = VFSUtils.getProperty(content, BaseConstants.CONTENT_TYPE);
            }
        }

        // does the service specify a default reply file URI ?
        String replyFileURI = entry.getReplyFileURI();
        if (replyFileURI != null) {
            msgContext.setProperty(Constants.OUT_TRANSPORT_INFO,
                    new VFSOutTransportInfo(replyFileURI, entry.isFileLockingEnabled()));
        }

        // Determine the message builder to use
        Builder builder;
        if (contentType == null) {
            log.debug("No content type specified. Using SOAP builder.");
            builder = new SOAPBuilder();
        } else {
            int index = contentType.indexOf(';');
            String type = index > 0 ? contentType.substring(0, index) : contentType;
            builder = BuilderUtil.getBuilderFromSelector(type, msgContext);
            if (builder == null) {
                if (log.isDebugEnabled()) {
                    log.debug("No message builder found for type '" + type + "'. Falling back to SOAP.");
                }
                builder = new SOAPBuilder();
            }
        }

        // set the message payload to the message context
        InputStream in;
        ManagedDataSource dataSource;
        if (builder instanceof DataSourceMessageBuilder && entry.isStreaming()) {
            in = null;
            dataSource = ManagedDataSourceFactory.create(new FileObjectDataSource(file, contentType));
        } else {
            in = new AutoCloseInputStream(content.getInputStream());
            dataSource = null;
        }

        try {
            OMElement documentElement;
            if (in != null) {
                documentElement = builder.processDocument(in, contentType, msgContext);
            } else {
                documentElement = ((DataSourceMessageBuilder) builder).processDocument(dataSource, contentType,
                        msgContext);
            }
            msgContext.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement));

            handleIncomingMessage(msgContext, transportHeaders, null, //* SOAP Action - not applicable *//
                    contentType);
        } finally {
            if (dataSource != null) {
                dataSource.destroy();
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("Processed file : " + file + " of Content-type : " + contentType);
        }

    } catch (FileSystemException e) {
        handleException("Error reading file content or attributes : " + file, e);

    } finally {
        try {
            file.close();
        } catch (FileSystemException warn) {
            //  log.warn("Cannot close file after processing : " + file.getName().getPath(), warn);
            // ignore the warning, since we handed over the stream close job to AutocloseInputstream..
        }
    }
}

From source file:org.apache.jackrabbit.core.PropertyImpl.java

/** Wrapper around {@link #getValue()} */
public InputStream getStream() throws RepositoryException {
    final Binary binary = getValue().getBinary();
    // make sure binary is disposed after stream had been consumed
    return new AutoCloseInputStream(binary.getStream()) {
        @Override//from  w  w  w.  j  a va 2s . c om
        public void close() throws IOException {
            super.close();
            binary.dispose();
        }
    };
}

From source file:org.apache.synapse.transport.vfs.VFSTransportListener.java

/**
 * Process a single file through Axis2/*www  . java2s  .co m*/
 * @param entry the PollTableEntry for the file (or its parent directory or archive)
 * @param file the file that contains the actual message pumped into Axis2
 * @throws AxisFault on error
 */
private void processFile(PollTableEntry entry, FileObject file) throws AxisFault {

    try {
        FileContent content = file.getContent();
        String fileName = file.getName().getBaseName();
        String filePath = file.getName().getPath();
        String fileURI = file.getName().getURI();

        metrics.incrementBytesReceived(content.getSize());

        Map<String, Object> transportHeaders = new HashMap<String, Object>();
        transportHeaders.put(VFSConstants.FILE_PATH, filePath);
        transportHeaders.put(VFSConstants.FILE_NAME, fileName);
        transportHeaders.put(VFSConstants.FILE_URI, fileURI);

        try {
            transportHeaders.put(VFSConstants.FILE_LENGTH, content.getSize());
            transportHeaders.put(VFSConstants.LAST_MODIFIED, content.getLastModifiedTime());
        } catch (FileSystemException ignore) {
        }

        MessageContext msgContext = entry.createMessageContext();

        String contentType = entry.getContentType();
        if (BaseUtils.isBlank(contentType)) {
            if (file.getName().getExtension().toLowerCase().endsWith(".xml")) {
                contentType = "text/xml";
            } else if (file.getName().getExtension().toLowerCase().endsWith(".txt")) {
                contentType = "text/plain";
            }
        } else {
            // Extract the charset encoding from the configured content type and
            // set the CHARACTER_SET_ENCODING property as e.g. SOAPBuilder relies on this.
            String charSetEnc = null;
            try {
                if (contentType != null) {
                    charSetEnc = new ContentType(contentType).getParameter("charset");
                }
            } catch (ParseException ex) {
                // ignore
            }
            msgContext.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, charSetEnc);
        }

        // if the content type was not found, but the service defined it.. use it
        if (contentType == null) {
            if (entry.getContentType() != null) {
                contentType = entry.getContentType();
            } else if (VFSUtils.getProperty(content, BaseConstants.CONTENT_TYPE) != null) {
                contentType = VFSUtils.getProperty(content, BaseConstants.CONTENT_TYPE);
            }
        }

        // does the service specify a default reply file URI ?
        String replyFileURI = entry.getReplyFileURI();
        if (replyFileURI != null) {
            msgContext.setProperty(Constants.OUT_TRANSPORT_INFO,
                    new VFSOutTransportInfo(replyFileURI, entry.isFileLockingEnabled()));
        }

        // Determine the message builder to use
        Builder builder;
        if (contentType == null) {
            log.debug("No content type specified. Using SOAP builder.");
            builder = new SOAPBuilder();
        } else {
            int index = contentType.indexOf(';');
            String type = index > 0 ? contentType.substring(0, index) : contentType;
            builder = BuilderUtil.getBuilderFromSelector(type, msgContext);
            if (builder == null) {
                if (log.isDebugEnabled()) {
                    log.debug("No message builder found for type '" + type + "'. Falling back to SOAP.");
                }
                builder = new SOAPBuilder();
            }
        }

        // set the message payload to the message context
        InputStream in;
        ManagedDataSource dataSource;
        if (builder instanceof DataSourceMessageBuilder && entry.isStreaming()) {
            in = null;
            dataSource = ManagedDataSourceFactory.create(new FileObjectDataSource(file, contentType));
        } else {
            in = new AutoCloseInputStream(content.getInputStream());
            dataSource = null;
        }

        try {
            OMElement documentElement;
            if (in != null) {
                documentElement = builder.processDocument(in, contentType, msgContext);
            } else {
                documentElement = ((DataSourceMessageBuilder) builder).processDocument(dataSource, contentType,
                        msgContext);
            }
            msgContext.setEnvelope(TransportUtils.createSOAPEnvelope(documentElement));

            handleIncomingMessage(msgContext, transportHeaders, null, //* SOAP Action - not applicable *//
                    contentType);
        } finally {
            if (dataSource != null) {
                dataSource.destroy();
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("Processed file : " + VFSUtils.maskURLPassword(file.toString()) + " of Content-type : "
                    + contentType);
        }

    } catch (FileSystemException e) {
        handleException(
                "Error reading file content or attributes : " + VFSUtils.maskURLPassword(file.toString()), e);

    } finally {
        try {
            if (file != null) {
                file.close();
            }
        } catch (FileSystemException warn) {
            // ignore the warning,  since we handed over the stream close job to
            // AutocloseInputstream..
        }
    }
}

From source file:org.artifactory.bintray.BintrayServiceImpl.java

private void pushArtifactsToVersion(BintrayUploadInfo uploadInfo, List<FileInfo> artifactsToPush,
        BasicStatusHolder status, VersionHandle bintrayVersionHandle) throws MultipleBintrayCallException {
    List<RepoPath> artifactPaths = Lists.newArrayList();
    Map<String, InputStream> streamMap = Maps.newHashMap();
    try {//from   w w  w .  jav  a 2s .c  o  m
        for (FileInfo fileInfo : artifactsToPush) {
            artifactPaths.add(fileInfo.getRepoPath());
            ResourceStreamHandle handle = repoService.getResourceStreamHandle(fileInfo.getRepoPath());
            streamMap.put(fileInfo.getRelPath(), new AutoCloseInputStream(handle.getInputStream()));
        }
        status.status(
                "Starting to push the requested files to " + String.format("into %s/%s/%s/%s: ",
                        uploadInfo.getPackageDetails().getSubject(), uploadInfo.getPackageDetails().getRepo(),
                        uploadInfo.getPackageDetails().getName(), uploadInfo.getVersionDetails().getName()),
                log);

        log.info("Pushing {} files...", streamMap.keySet().size());
        log.debug("Pushing the following files into Bintray: {}", Arrays.toString(artifactPaths.toArray()));
        bintrayVersionHandle.upload(streamMap);
    } catch (MultipleBintrayCallException mbce) {
        for (BintrayCallException bce : mbce.getExceptions()) {
            status.error(bce.toString(), bce.getStatusCode(), log);
        }
        throw mbce;
    } finally {
        for (InputStream stream : streamMap.values()) {
            IOUtils.closeQuietly(stream);
        }
    }
}

From source file:org.duracloud.chunk.FileChunker.java

private InputStream getInputStream(InputStream stream) {
    return new AutoCloseInputStream(stream);
}

From source file:org.duracloud.chunk.FileChunkerDriver.java

private static InputStream getInputStream(File file) {
    try {/*w w  w  . j a  v a2 s  . com*/
        return new AutoCloseInputStream(new FileInputStream(file));
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.duracloud.client.util.ContentStoreUtil.java

public InputStream getContentStream(String spaceId, String contentId) {
    Content content = getContent(spaceId, contentId);
    if (null == content) {
        StringBuilder sb = new StringBuilder("Error: content is null: ");
        sb.append(spaceId);/*from   w w  w.  j av a2  s.com*/
        sb.append("/");
        sb.append(contentId);
        log.error(sb.toString());
        throw new DuraCloudRuntimeException(sb.toString());
    }
    return new AutoCloseInputStream(content.getStream());
}

From source file:org.duracloud.common.util.ApplicationConfig.java

public static Properties getPropsFromResource(String resourceName) {
    Properties props = new Properties();
    AutoCloseInputStream in = new AutoCloseInputStream(
            ApplicationConfig.class.getClassLoader().getResourceAsStream(resourceName));
    try {/*from www  . j  a v a 2s.c om*/
        props.load(in);
    } catch (Exception e) {
        String error = "Unable to find resource: '" + resourceName + "': " + e.getMessage();
        throw new RuntimeException(error, e);
    }
    return props;
}