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:com.github.davidcarboni.encryptedfileupload.StreamingTest.java

/**
 * Tests, whether an IOException is properly delegated.
 *//*from w  w  w.  ja v a2s  .  c  om*/
public void testIOException() throws IOException {
    byte[] request = newRequest();
    InputStream stream = new FilterInputStream(new ByteArrayInputStream(request)) {
        private int num;

        @Override
        public int read() throws IOException {
            if (++num > 123) {
                throw new IOException("123");
            }
            return super.read();
        }

        @Override
        public int read(byte[] pB, int pOff, int pLen) throws IOException {
            for (int i = 0; i < pLen; i++) {
                int res = read();
                if (res == -1) {
                    return i == 0 ? -1 : i;
                }
                pB[pOff + i] = (byte) res;
            }
            return pLen;
        }
    };
    try {
        parseUpload(stream, request.length);
        fail("Expected IOException");
    } catch (FileUploadException e) {
        assertTrue(e.getCause() instanceof IOException);
        assertEquals("123", e.getCause().getMessage());
    }
}

From source file:com.datos.vfs.provider.http.HttpRandomAccessContent.java

@Override
protected DataInputStream getDataInputStream() throws IOException {
    if (dis != null) {
        return dis;
    }//from   w w w  .  j a  va2  s. c  om

    final GetMethod getMethod = new GetMethod();
    fileObject.setupMethod(getMethod);
    getMethod.setRequestHeader("Range", "bytes=" + filePointer + "-");
    final int status = fileSystem.getClient().executeMethod(getMethod);
    if (status != HttpURLConnection.HTTP_PARTIAL && status != HttpURLConnection.HTTP_OK) {
        throw new FileSystemException("vfs.provider.http/get-range.error", fileObject.getName(),
                Long.valueOf(filePointer), Integer.valueOf(status));
    }

    mis = new HttpFileObject.HttpInputStream(getMethod);
    // If the range request was ignored
    if (status == HttpURLConnection.HTTP_OK) {
        final long skipped = mis.skip(filePointer);
        if (skipped != filePointer) {
            throw new FileSystemException("vfs.provider.http/get-range.error", fileObject.getName(),
                    Long.valueOf(filePointer), Integer.valueOf(status));
        }
    }
    dis = new DataInputStream(new FilterInputStream(mis) {
        @Override
        public int read() throws IOException {
            final int ret = super.read();
            if (ret > -1) {
                filePointer++;
            }
            return ret;
        }

        @Override
        public int read(final byte[] b) throws IOException {
            final int ret = super.read(b);
            if (ret > -1) {
                filePointer += ret;
            }
            return ret;
        }

        @Override
        public int read(final byte[] b, final int off, final int len) throws IOException {
            final int ret = super.read(b, off, len);
            if (ret > -1) {
                filePointer += ret;
            }
            return ret;
        }
    });

    return dis;
}

From source file:davmail.exchange.dav.ExchangeDavMethod.java

@Override
protected void processResponseBody(HttpState httpState, HttpConnection httpConnection) {
    Header contentTypeHeader = getResponseHeader("Content-Type");
    if (contentTypeHeader != null && "text/xml".equals(contentTypeHeader.getValue())) {
        responses = new ArrayList<MultiStatusResponse>();
        XMLStreamReader reader;/*from   w w w . j av  a2  s  .  c  o m*/
        try {
            reader = XMLStreamUtil.createXMLStreamReader(new FilterInputStream(getResponseBodyAsStream()) {
                final byte[] lastbytes = new byte[3];

                @Override
                public int read(byte[] bytes, int off, int len) throws IOException {
                    int count = in.read(bytes, off, len);
                    // patch invalid element name
                    for (int i = 0; i < count; i++) {
                        byte currentByte = bytes[off + i];
                        if ((lastbytes[0] == '<') && (currentByte >= '0' && currentByte <= '9')) {
                            // move invalid first tag char to valid range
                            bytes[off + i] = (byte) (currentByte + 49);
                        }
                        lastbytes[0] = lastbytes[1];
                        lastbytes[1] = lastbytes[2];
                        lastbytes[2] = currentByte;
                    }
                    return count;
                }

            });
            while (reader.hasNext()) {
                reader.next();
                if (XMLStreamUtil.isStartTag(reader, "response")) {
                    handleResponse(reader);
                }
            }

        } catch (IOException e) {
            LOGGER.error("Error while parsing soap response: " + e, e);
        } catch (XMLStreamException e) {
            LOGGER.error("Error while parsing soap response: " + e, e);
        }
    }
}

From source file:org.callimachusproject.io.CarInputStream.java

private ZipArchiveEntry next() throws IOException {
    if (Thread.interrupted())
        throw new InterruptedIOException();
    entry = zipStream.getNextZipEntry();
    if (entry == null) {
        entryStream = null;//w ww.  j a v a  2 s  . co  m
        entryMetaType = null;
        return null;
    }
    final ZipArchiveEntry openEntry = entry;
    entryStream = new LatencyInputStream(new FilterInputStream(zipStream) {
        public void close() throws IOException {
            if (openEntry == entry) {
                entry = null;
                entryStream = null;
                entryMetaType = null;
            }
        }
    }, RDFS_PEEK_SIZE);
    entryType = readEntryType(entry, entryStream);
    entryMetaType = MetaTypeExtraField.parseExtraField(entry);
    if (entryMetaType == null) {
        if (entry.isDirectory()) {
            entryMetaType = MetaTypeExtraField.FOLDER;
        } else if (FILE_NAME.matcher(entry.getName()).find()) {
            entryMetaType = MetaTypeExtraField.FILE;
        } else if (scanForClass(entryStream, entryType)) {
            entryMetaType = MetaTypeExtraField.RDFS;
        } else {
            entryMetaType = MetaTypeExtraField.RDF;
        }
    }
    return entry;
}

From source file:org.apache.ant.compress.resources.ZipResource.java

/**
 * Return an InputStream for reading the contents of this Resource.
 * @return an InputStream object./*  w  w  w  . j a  v a2 s  . c  om*/
 * @throws IOException if the zip file cannot be opened,
 *         or the entry cannot be read.
 */
public InputStream getInputStream() throws IOException {
    if (isReference()) {
        return ((Resource) getCheckedRef()).getInputStream();
    }
    File f = getZipfile();
    if (f == null) {
        return super.getInputStream();
    }

    final ZipFile z = new ZipFile(f, getEncoding());
    ZipArchiveEntry ze = z.getEntry(getName());
    if (ze == null) {
        z.close();
        throw new BuildException("no entry " + getName() + " in " + getArchive());
    }
    return new FilterInputStream(z.getInputStream(ze)) {
        public void close() throws IOException {
            FileUtils.close(in);
            z.close();
        }

        protected void finalize() throws Throwable {
            try {
                close();
            } finally {
                super.finalize();
            }
        }
    };
}

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

private String parseContent(ZipEntry ze, ZipInputStream zis, ArrayList outlinks) throws Exception {
    StringBuffer res = new StringBuffer();
    FilterInputStream fis = new FilterInputStream(zis) {
        public void close() {
        };//from  ww  w. ja v a  2  s.  c  om
    };
    SAXBuilder builder = new SAXBuilder();
    Document doc = builder.build(fis);
    Element root = doc.getRootElement();
    // XXX this is expensive for very large documents. In those cases another
    // XXX method (direct processing of SAX events, or XMLPull) should be used.
    XPath path = new JDOMXPath("//text:span | //text:p | //text:tab | //text:tab-stop | //text:a");
    path.addNamespace("text", root.getNamespace("text").getURI());
    Namespace xlink = Namespace.getNamespace("xlink", "http://www.w3.org/1999/xlink");
    List list = path.selectNodes(doc);
    boolean lastp = true;
    for (int i = 0; i < list.size(); i++) {
        Element el = (Element) list.get(i);
        String text = el.getText();
        if (el.getName().equals("p")) {
            // skip empty paragraphs
            if (!text.equals("")) {
                if (!lastp)
                    res.append("\n");
                res.append(text + "\n");
                lastp = true;
            }
        } else if (el.getName().startsWith("tab")) {
            res.append("\t");
            lastp = false;
        } else if (el.getName().equals("a")) {
            List nl = el.getChildren();
            String a = null;
            for (int k = 0; k < nl.size(); k++) {
                Element anchor = (Element) nl.get(k);
                String nsName = anchor.getNamespacePrefix() + ":" + anchor.getName();
                if (!nsName.equals("text:span"))
                    continue;
                a = anchor.getText();
                break;
            }
            String u = el.getAttributeValue("href", xlink);
            if (u == null)
                u = a; // often anchors are URLs
            try {
                Outlink o = new Outlink(u, a);
                outlinks.add(o);
            } catch (MalformedURLException mue) {
                // skip
            }
            if (a != null && !a.equals("")) {
                if (!lastp)
                    res.append(' ');
                res.append(a);
                lastp = false;
            }
        } else {
            if (!text.equals("")) {
                if (!lastp)
                    res.append(' ');
                res.append(text);
            }
            lastp = false;
        }
    }
    return res.toString();
}

From source file:org.apache.felix.webconsole.internal.misc.LicenseServlet.java

private void findResource(JSONWriter jsonWriter, Bundle bundle, String[] patterns)
        throws IOException, JSONException {
    jsonWriter.key("Bundle Resources"); // aka the bundle files
    jsonWriter.array();/*from  w  w  w.  java  2s  .co m*/
    for (int i = 0; i < patterns.length; i++) {
        Enumeration getEntries = bundle.findEntries("/", patterns[i] + "*", true);
        if (getEntries != null) {
            while (getEntries.hasMoreElements()) {
                URL nextURL = (URL) getEntries.nextElement();
                jsonWriter.object();
                jsonWriter.key("url");
                jsonWriter.value(getName(nextURL.getPath()));
                jsonWriter.key("data");
                jsonWriter.value(readResourceFromURL(nextURL));
                jsonWriter.endObject();
            }
        }
    }
    jsonWriter.endArray();

    Enumeration jarEntries = bundle.findEntries("/", "*.jar", true);
    if (jarEntries != null) {
        while (jarEntries.hasMoreElements()) {
            URL nextURL = (URL) jarEntries.nextElement();

            jsonWriter.key("Embedded " + getName(nextURL.getPath()));
            jsonWriter.array();

            for (int i = 0; i < patterns.length; i++) {
                String patternStuff = ".*/" + patterns[i] + "[^/]*$";

                InputStream tmpInput = null;
                try {
                    tmpInput = nextURL.openStream();
                    ZipInputStream zipInput = new ZipInputStream(tmpInput);
                    ZipEntry zipEntry = zipInput.getNextEntry();
                    while (zipEntry != null) {
                        String name = zipEntry.getName();
                        if (!name.endsWith("/") && "/".concat(name).matches(patternStuff)) {
                            jsonWriter.object();
                            jsonWriter.key("url");
                            jsonWriter.value(getName(name));
                            jsonWriter.key("data");
                            jsonWriter.value(readResourceFromStream(new FilterInputStream(zipInput) {
                                public void close() {
                                }
                            }));
                            jsonWriter.endObject();
                        }

                        zipEntry = zipInput.getNextEntry();
                    }
                } finally {
                    if (tmpInput != null) {
                        try {
                            tmpInput.close();
                        } catch (IOException ignore) {
                        }
                    }
                }
            }

            jsonWriter.endArray();
        }
    }
}

From source file:com.adaptris.core.common.PayloadStreamOutputParameterTest.java

@Test(expected = CoreException.class)
public void testInsert_BrokenInput() throws Exception {
    PayloadStreamOutputParameter p = new PayloadStreamOutputParameter();
    p.setContentEncoding(UTF_8);/* w w  w  .  j  a v a  2 s.com*/
    AdaptrisMessage msg = AdaptrisMessageFactory.getDefaultInstance().newMessage();
    FilterInputStream in = new FilterInputStream(new ByteArrayInputStream(new byte[0])) {
        @Override
        public int read() throws IOException {
            throw new IOException("Failed to read");
        }

        @Override
        public int read(byte[] b) throws IOException {
            throw new IOException("Failed to read");
        }

        @Override
        public int read(byte[] b, int off, int len) throws IOException {
            throw new IOException("Failed to read");
        }
    };
    p.insert(new InputStreamWithEncoding(in, UTF_8), msg);
}

From source file:com.adaptris.core.common.PayloadStreamOutputParameterTest.java

@Test(expected = CoreException.class)
public void testInsert_Broken_BinaryInput() throws Exception {
    PayloadStreamOutputParameter p = new PayloadStreamOutputParameter();
    AdaptrisMessage msg = AdaptrisMessageFactory.getDefaultInstance().newMessage();
    FilterInputStream in = new FilterInputStream(new ByteArrayInputStream(new byte[0])) {
        @Override/*from   ww w  .j av  a 2  s . c o m*/
        public int read() throws IOException {
            throw new IOException("Failed to read");
        }

        @Override
        public int read(byte[] b) throws IOException {
            throw new IOException("Failed to read");
        }

        @Override
        public int read(byte[] b, int off, int len) throws IOException {
            throw new IOException("Failed to read");
        }
    };
    p.insert(new InputStreamWithEncoding(in, null), msg);
}