Example usage for java.io FilterInputStream FilterInputStream

List of usage examples for java.io FilterInputStream FilterInputStream

Introduction

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

Prototype

protected FilterInputStream(InputStream in) 

Source Link

Document

Creates a FilterInputStream by assigning the argument in to the field this.in so as to remember it for later use.

Usage

From source file:org.sonatype.nexus.test.utils.hc4client.Hc4MethodCall.java

@Override
public InputStream getResponseEntityStream(long size) {
    InputStream result = null;/*from   w  w w. j  ava2 s  .c om*/

    try {
        if (getHttpResponse() != null && getHttpResponse().getEntity() != null) {
            final InputStream responseBodyAsStream = getHttpResponse().getEntity().getContent();
            if (responseBodyAsStream != null) {
                result = new FilterInputStream(responseBodyAsStream) {
                    @Override
                    public void close() throws IOException {
                        super.close();
                        getHttpMethod().releaseConnection();
                    }
                };
            }
        }
    } catch (IOException ioe) {
        this.clientHelper.getLogger().log(Level.WARNING,
                "An error occurred during the communication with the remote HTTP server.", ioe);
    }

    return result;
}

From source file:org.eclipse.acute.OmnisharpStreamConnectionProvider.java

@Override
public InputStream getInputStream() {
    if (DEBUG) {//  w  ww  . j  av a  2  s.co  m
        return new FilterInputStream(process.getInputStream()) {
            @Override
            public int read() throws IOException {
                int res = super.read();
                System.err.print((char) res);
                return res;
            }

            @Override
            public int read(byte[] b, int off, int len) throws IOException {
                int bytes = super.read(b, off, len);
                byte[] payload = new byte[bytes];
                System.arraycopy(b, off, payload, 0, bytes);
                System.err.print(new String(payload));
                return bytes;
            }

            @Override
            public int read(byte[] b) throws IOException {
                int bytes = super.read(b);
                byte[] payload = new byte[bytes];
                System.arraycopy(b, 0, payload, 0, bytes);
                System.err.print(new String(payload));
                return bytes;
            }
        };
    } else {
        return process.getInputStream();
    }
}

From source file:org.apache.nutch.parse.oo.OOParser.java

private void parseMeta(ZipEntry ze, ZipInputStream zis, Metadata metadata) throws Exception {
    FilterInputStream fis = new FilterInputStream(zis) {
        public void close() {
        };//from www . j av a 2 s .  c  o m
    };
    SAXBuilder builder = new SAXBuilder();
    Document doc = builder.build(fis);
    XPath path = new JDOMXPath("/office:document-meta/office:meta/*");
    Element root = doc.getRootElement();
    path.addNamespace("office", root.getNamespace("office").getURI());
    List list = path.selectNodes(doc);
    for (int i = 0; i < list.size(); i++) {
        Element n = (Element) list.get(i);
        String text = n.getText();
        if (text.trim().equals(""))
            continue;
        String name = n.getName();
        if (name.equals("title"))
            metadata.add(Metadata.TITLE, text);
        else if (name.equals("language"))
            metadata.add(Metadata.LANGUAGE, text);
        else if (name.equals("creation-date"))
            metadata.add(Metadata.DATE, text);
        else if (name.equals("print-date"))
            metadata.add(Metadata.LAST_PRINTED, text);
        else if (name.equals("generator"))
            metadata.add(Metadata.APPLICATION_NAME, text);
        else if (name.equals("creator"))
            metadata.add(Metadata.CREATOR, text);
    }
}

From source file:com.pmi.restlet.ext.httpclient.internal.HttpMethodCall.java

@Override
public InputStream getResponseEntityStream(long size) {
    InputStream result = null;//  w w w . ja  v a  2s  .  c  o  m

    try {
        // Return a wrapper filter that will release the connection when
        // needed
        InputStream responseStream = (getHttpResponse() == null) ? null
                : (getHttpResponse().getEntity() == null) ? null : getHttpResponse().getEntity().getContent();
        if (responseStream != null) {
            result = new FilterInputStream(responseStream) {
                @Override
                public void close() throws IOException {
                    super.close();
                    getHttpResponse().getEntity().consumeContent();
                }
            };
        }
    } catch (IOException ioe) {
    }

    return result;
}

From source file:com.noelios.restlet.ext.httpclient.HttpMethodCall.java

@Override
public InputStream getResponseEntityStream(long size) {
    InputStream result = null;/*from  w w w .j  a  va2s .c o  m*/

    try {
        // Return a wrapper filter that will release the connection when
        // needed
        final InputStream responseBodyAsStream = getHttpMethod().getResponseBodyAsStream();
        if (responseBodyAsStream != null) {
            result = new FilterInputStream(responseBodyAsStream) {
                @Override
                public void close() throws IOException {
                    super.close();
                    getHttpMethod().releaseConnection();
                }
            };
        }
    } catch (IOException ioe) {
    }

    return result;
}

From source file:org.eclipse.orion.internal.server.servlets.xfer.ClientImport.java

/**
 * Unzips the transferred file. Returns <code>true</code> if the unzip was
 * successful, and <code>false</code> otherwise. In case of failure, this method
 * handles setting an appropriate response.
 *///w w  w  .j  a v a2 s.  c  o m
private boolean completeUnzip(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
    IPath destPath = new Path(getPath());
    boolean force = false;
    List<String> filesFailed = new ArrayList<String>();
    if (req.getParameter("force") != null) {
        force = req.getParameter("force").equals("true");
    }
    List<String> excludedFiles = new ArrayList<String>();
    if (req.getParameter(ProtocolConstants.PARAM_EXCLUDE) != null) {
        excludedFiles = Arrays.asList(req.getParameter(ProtocolConstants.PARAM_EXCLUDE).split(","));
    }
    try {
        ZipFile source = new ZipFile(new File(getStorageDirectory(), FILE_DATA));
        IFileStore destinationRoot = NewFileServlet.getFileStore(req, destPath);
        Enumeration<? extends ZipEntry> entries = source.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            IFileStore destination = destinationRoot.getChild(entry.getName());
            if (!destinationRoot.isParentOf(destination)
                    || hasExcludedParent(destination, destinationRoot, excludedFiles)) {
                //file should not be imported
                continue;
            }
            if (entry.isDirectory())
                destination.mkdir(EFS.NONE, null);
            else {
                if (!force && destination.fetchInfo().exists()) {
                    filesFailed.add(entry.getName());
                    continue;
                }
                destination.getParent().mkdir(EFS.NONE, null);
                // this filter will throw an IOException if a zip entry is larger than 100MB
                FilterInputStream maxBytesReadInputStream = new FilterInputStream(
                        source.getInputStream(entry)) {
                    private static final int maxBytes = 0x6400000; // 100MB
                    private int totalBytes;

                    private void addByteCount(int count) throws IOException {
                        totalBytes += count;
                        if (totalBytes > maxBytes) {
                            throw new IOException("Zip file entry too large");
                        }
                    }

                    @Override
                    public int read() throws IOException {
                        int c = super.read();
                        if (c != -1) {
                            addByteCount(1);
                        }
                        return c;
                    }

                    @Override
                    public int read(byte[] b, int off, int len) throws IOException {
                        int read = super.read(b, off, len);
                        if (read != -1) {
                            addByteCount(read);
                        }
                        return read;
                    }
                };
                boolean fileWritten = false;
                try {
                    IOUtilities.pipe(maxBytesReadInputStream, destination.openOutputStream(EFS.NONE, null),
                            false, true);
                    fileWritten = true;
                } finally {
                    if (!fileWritten) {
                        try {
                            destination.delete(EFS.NONE, null);
                        } catch (CoreException ce) {
                            // best effort
                        }
                    }
                }
            }
        }
        source.close();

        if (!filesFailed.isEmpty()) {
            String failedFilesList = "";
            for (String file : filesFailed) {
                if (failedFilesList.length() > 0) {
                    failedFilesList += ", ";
                }
                failedFilesList += file;
            }
            String msg = NLS.bind(
                    "Failed to transfer all files to {0}, the following files could not be overwritten {1}",
                    destPath.toString(), failedFilesList);
            JSONObject jsonData = new JSONObject();
            jsonData.put("ExistingFiles", filesFailed);
            statusHandler.handleRequest(req, resp,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, jsonData, null));
            return false;
        }

    } catch (ZipException e) {
        //zip exception implies client sent us invalid input
        String msg = NLS.bind("Failed to complete file transfer on {0}", destPath.toString());
        statusHandler.handleRequest(req, resp,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, e));
        return false;
    } catch (Exception e) {
        //other failures should be considered server errors
        String msg = NLS.bind("Failed to complete file transfer on {0}", destPath.toString());
        statusHandler.handleRequest(req, resp,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e));
        return false;
    }
    return true;
}

From source file:org.apache.druid.storage.s3.S3DataSegmentPuller.java

private FileObject buildFileObject(final URI uri) throws AmazonServiceException {
    final S3Coords coords = new S3Coords(checkURI(uri));
    final S3ObjectSummary objectSummary = S3Utils.getSingleObjectSummary(s3Client, coords.bucket, coords.path);
    final String path = uri.getPath();

    return new FileObject() {
        S3Object s3Object = null;

        @Override/*from  www .  ja  v a  2 s .  c o  m*/
        public URI toUri() {
            return uri;
        }

        @Override
        public String getName() {
            final String ext = Files.getFileExtension(path);
            return Files.getNameWithoutExtension(path) + (Strings.isNullOrEmpty(ext) ? "" : ("." + ext));
        }

        /**
         * Returns an input stream for a s3 object. The returned input stream is not thread-safe.
         */
        @Override
        public InputStream openInputStream() throws IOException {
            try {
                if (s3Object == null) {
                    // lazily promote to full GET
                    s3Object = s3Client.getObject(objectSummary.getBucketName(), objectSummary.getKey());
                }

                final InputStream in = s3Object.getObjectContent();
                final Closer closer = Closer.create();
                closer.register(in);
                closer.register(s3Object);

                return new FilterInputStream(in) {
                    @Override
                    public void close() throws IOException {
                        closer.close();
                    }
                };
            } catch (AmazonServiceException e) {
                throw new IOE(e, "Could not load S3 URI [%s]", uri);
            }
        }

        @Override
        public OutputStream openOutputStream() {
            throw new UOE("Cannot stream S3 output");
        }

        @Override
        public Reader openReader(boolean ignoreEncodingErrors) {
            throw new UOE("Cannot open reader");
        }

        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            throw new UOE("Cannot open character sequence");
        }

        @Override
        public Writer openWriter() {
            throw new UOE("Cannot open writer");
        }

        @Override
        public long getLastModified() {
            return objectSummary.getLastModified().getTime();
        }

        @Override
        public boolean delete() {
            throw new UOE(
                    "Cannot delete S3 items anonymously. jetS3t doesn't support authenticated deletes easily.");
        }
    };
}

From source file:dk.netarkivet.common.distribute.arcrepository.BitarchiveRecord.java

/**
 * Retrieve the data in the record./*from w w  w  .  ja  v  a 2s.c o  m*/
 * If data is in RemoteFile, this operation deletes the RemoteFile.
 * @throws IllegalState if remotefile already deleted
 * @return the data from the ARCRecord as an InputStream.
 */
public InputStream getData() {
    InputStream result = null;
    if (isStoredAsRemoteFile) {
        if (hasRemoteFileBeenDeleted) {
            throw new IllegalState("RemoteFile has already been deleted");
        }
        log.info("Reading " + length + " bytes from RemoteFile");
        InputStream rfInputStream = objectAsRemoteFile.getInputStream();
        result = new FilterInputStream(rfInputStream) {
            public void close() throws IOException {
                super.close();
                objectAsRemoteFile.cleanup();
                hasRemoteFileBeenDeleted = true;
            }
        };
    } else {
        log.debug("Reading " + length + " bytes from objectBuffer");
        result = new ByteArrayInputStream(objectBuffer);
    }
    return result;
}

From source file:org.eclipse.mylyn.internal.context.core.InteractionContextExternalizer.java

public InputStream getAdditionalInformation(File file, String contributorIdentifier) throws IOException {
    if (!file.exists()) {
        return null;
    }//  w  ww. j  av a2  s.  c o m
    final ZipFile zipFile = new ZipFile(file);
    ZipEntry entry = findFileInZip(zipFile, contributorIdentifier);
    if (entry == null) {
        return null;
    }

    return new FilterInputStream(zipFile.getInputStream(entry)) {
        @Override
        public void close() throws IOException {
            super.close();
            zipFile.close();
        }
    };
}

From source file:dk.netarkivet.common.distribute.HTTPRemoteFile.java

/** Get an input stream representing the remote file.
 * If the file resides on the current machine, the input stream is to the
 * local file. Otherwise, the remote file is transferred over http.
 * The close method of the input stream will cleanup this handle, and if
 * checksums are requested, will check the checksums on close.
 * If the file is not set to be able to be transferred multiple times, it is
 * cleaned up after the transfer.// www.  j  a v  a 2s .  co  m
 * @return An input stream for the remote file.
 * @throws IOFailure on I/O trouble generating inputstream for remote file.
 * Also, the returned remote file will throw IOFailure on close, if
 * checksums are requested, but do not match.
 */
public InputStream getInputStream() {
    if (filesize == 0) {
        return new ByteArrayInputStream(new byte[] {});
    }
    try {
        InputStream is = null;
        if (isLocal()) {
            is = new FileInputStream(file);
        } else {
            URLConnection urlConnection = getRegistry().openConnection(url);
            //ensure not getting some cached version
            urlConnection.setUseCaches(false);
            is = urlConnection.getInputStream();
        }
        if (useChecksums) {
            is = new DigestInputStream(is, ChecksumCalculator.getMessageDigest(ChecksumCalculator.MD5));
        }
        return new FilterInputStream(is) {
            public void close() {
                if (useChecksums) {
                    String newChecksum = ChecksumCalculator
                            .toHex(((DigestInputStream) in).getMessageDigest().digest());
                    if (!newChecksum.equals(checksum)) {
                        throw new IOFailure(
                                "Checksum mismatch! Expected '" + checksum + "' but was '" + newChecksum + "'");
                    }
                }
                if (!multipleDownloads) {
                    cleanup();
                }
            }
        };
    } catch (IOException e) {
        throw new IOFailure("Unable to get inputstream for '" + file + "' from '" + url + "'", e);
    }
}