Example usage for java.io FilterOutputStream FilterOutputStream

List of usage examples for java.io FilterOutputStream FilterOutputStream

Introduction

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

Prototype

public FilterOutputStream(OutputStream out) 

Source Link

Document

Creates an output stream filter built on top of the specified underlying output stream.

Usage

From source file:org.sample.interceptor.MyClientWriterInterceptor.java

@Override
public void aroundWriteTo(WriterInterceptorContext wic) throws IOException, WebApplicationException {

    System.out.println("MyClientWriterInterceptor");
    wic.setOutputStream(new FilterOutputStream(wic.getOutputStream()) {

        final ByteArrayOutputStream baos = new ByteArrayOutputStream();

        @Override/*from w ww.ja  va2s .  c o  m*/
        public void write(int b) throws IOException {
            baos.write(b);
            super.write(b);
        }

        @Override
        public void close() throws IOException {
            System.out.println("MyClientWriterInterceptor --> " + baos.toString());
            super.close();
        }
    });

    //        wic.setOutputStream(new FilterOutputStream(wic.getOutputStream()) {
    //            
    //            @Override
    //            public void write(int b) throws IOException {
    //                System.out.println("**** "  + (char)b);
    //                super.write(b);
    //            }
    //            
    //        });

    wic.proceed();
}

From source file:com.cedarsoft.serialization.jackson.NumberSerializerTest.java

@Test
public void testNotClose() throws Exception {
    final boolean[] shallAcceptClose = { false };

    JsonFactory jsonFactory = JacksonSupport.getJsonFactory();
    OutputStream out = new FilterOutputStream(new ByteArrayOutputStream()) {
        private boolean closed;

        @Override/*from   w  w  w  .java2  s .c o m*/
        public void close() throws IOException {
            if (!shallAcceptClose[0]) {
                fail("Unacceptable close!");
            }

            super.close();
            closed = true;
        }
    };

    getSerializer().serialize(123, out);
    shallAcceptClose[0] = true;
    out.close();
}

From source file:com.cedarsoft.serialization.jackson.StringSerializerTest.java

License:asdf

@Test
public void testNotClose() throws Exception {
    final boolean[] shallAcceptClose = { false };
    final boolean[] closed = new boolean[1];

    OutputStream out = new FilterOutputStream(new ByteArrayOutputStream()) {

        @Override/*w w  w .  j ava  2 s  .  co m*/
        public void close() throws IOException {
            if (!shallAcceptClose[0]) {
                fail("Unacceptable close!");
            }

            super.close();
            closed[0] = true;
        }
    };

    getSerializer().serialize("daString", out);
    shallAcceptClose[0] = true;
    out.close();
    assertThat(closed[0]).isTrue();
}

From source file:com.cedarsoft.serialization.jackson.IntegerSerializerTest.java

@Test
public void testNotClose() throws Exception {
    final boolean[] shallAcceptClose = { false };
    final boolean[] closed = new boolean[1];

    OutputStream out = new FilterOutputStream(new ByteArrayOutputStream()) {

        @Override//from  w  w  w  .ja v a  2s  . c  o  m
        public void close() throws IOException {
            if (!shallAcceptClose[0]) {
                fail("Unacceptable close!");
            }

            super.close();
            closed[0] = true;
        }
    };

    getSerializer().serialize(12, out);
    shallAcceptClose[0] = true;
    out.close();
    assertThat(closed[0]).isTrue();
}

From source file:nl.nn.adapterframework.filesystem.FtpFileSystem.java

private FilterOutputStream completePendingCommand(OutputStream os) {
    FilterOutputStream fos = new FilterOutputStream(os) {
        @Override/*from   ww w .  j a v a2 s  .  c  o m*/
        public void close() throws IOException {
            super.close();
            ftpClient.completePendingCommand();
        }
    };
    return fos;
}

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

private FilterOutputStream openEntryStream() {
    return new FilterOutputStream(zipStream) {
        private boolean closed;

        public void close() throws IOException {
            if (!closed) {
                closed = true;/* www  .j  a v  a2  s .co m*/
                zipStream.closeArchiveEntry();
            }
        }
    };
}

From source file:org.esxx.Response.java

public static void writeObject(Object object, ContentType ct, OutputStream out) throws IOException {

    if (object == null) {
        return;/*w  w  w  . ja v a  2  s .c om*/
    }

    // Unwrap wrapped objects
    object = JS.toJavaObject(object);

    // Convert complex types to primitive types
    if (object instanceof Node) {
        ESXX esxx = ESXX.getInstance();

        if (ct.match("message/rfc822")) {
            try {
                String xml = esxx.serializeNode((Node) object);
                org.esxx.xmtp.XMTPParser xmtpp = new org.esxx.xmtp.XMTPParser();
                javax.mail.Message msg = xmtpp.convertMessage(new StringReader(xml));
                object = new ByteArrayOutputStream();
                msg.writeTo(new FilterOutputStream((OutputStream) object) {
                    @Override
                    public void write(int b) throws IOException {
                        if (b == '\r') {
                            return;
                        } else if (b == '\n') {
                            out.write('\r');
                            out.write('\n');
                        } else {
                            out.write(b);
                        }
                    }
                });
            } catch (javax.xml.stream.XMLStreamException ex) {
                throw new ESXXException("Failed to serialize Node as message/rfc822:" + ex.getMessage(), ex);
            } catch (javax.mail.MessagingException ex) {
                throw new ESXXException("Failed to serialize Node as message/rfc822:" + ex.getMessage(), ex);
            }
        } else {
            object = esxx.serializeNode((Node) object);
        }
    } else if (object instanceof Scriptable) {
        if (ct.match("application/x-www-form-urlencoded")) {
            String cs = Parsers.getParameter(ct, "charset", "UTF-8");

            object = StringUtil.encodeFormVariables(cs, (Scriptable) object);
        } else if (ct.match("text/csv")) {
            object = jsToCSV(ct, (Scriptable) object);
        } else {
            object = jsToJSON(object).toString();
        }
    } else if (object instanceof byte[]) {
        object = new ByteArrayInputStream((byte[]) object);
    } else if (object instanceof File) {
        object = new FileInputStream((File) object);
    }

    // Serialize primitive types
    if (object instanceof ByteArrayOutputStream) {
        ByteArrayOutputStream bos = (ByteArrayOutputStream) object;

        bos.writeTo(out);
    } else if (object instanceof ByteBuffer) {
        // Write result as-is to output stream
        WritableByteChannel wbc = Channels.newChannel(out);
        ByteBuffer bb = (ByteBuffer) object;

        bb.rewind();

        while (bb.hasRemaining()) {
            wbc.write(bb);
        }

        wbc.close();
    } else if (object instanceof InputStream) {
        IO.copyStream((InputStream) object, out);
    } else if (object instanceof Reader) {
        // Write stream as-is, using the specified charset (if present)
        String cs = Parsers.getParameter(ct, "charset", "UTF-8");
        Writer ow = new OutputStreamWriter(out, cs);

        IO.copyReader((Reader) object, ow);
    } else if (object instanceof String) {
        // Write string as-is, using the specified charset (if present)
        String cs = Parsers.getParameter(ct, "charset", "UTF-8");
        Writer ow = new OutputStreamWriter(out, cs);
        ow.write((String) object);
        ow.flush();
    } else if (object instanceof RenderedImage) {
        Iterator<ImageWriter> i = ImageIO.getImageWritersByMIMEType(ct.getBaseType());

        if (!i.hasNext()) {
            throw new ESXXException("No ImageWriter available for " + ct.getBaseType());
        }

        ImageWriter writer = i.next();

        writer.setOutput(ImageIO.createImageOutputStream(out));
        writer.write((RenderedImage) object);
    } else {
        throw new UnsupportedOperationException("Unsupported object class type: " + object.getClass());
    }
}

From source file:org.zuinnote.hadoop.office.format.common.writer.msexcel.internal.EncryptedZipEntrySource.java

public void setInputStream(InputStream is) throws IOException {
    this.tmpFile = TempFile.createTempFile("hadoopoffice-protected", ".zip");

    ZipArchiveInputStream zis = new ZipArchiveInputStream(is);
    FileOutputStream fos = new FileOutputStream(tmpFile);
    ZipArchiveOutputStream zos = new ZipArchiveOutputStream(fos);
    ZipArchiveEntry ze;//from   w w  w  .j a  v  a  2 s  . c  o m
    while ((ze = (ZipArchiveEntry) zis.getNextEntry()) != null) {
        // rewrite zip entries to match the size of the encrypted data (with padding)
        ZipArchiveEntry zeNew = new ZipArchiveEntry(ze.getName());
        zeNew.setComment(ze.getComment());
        zeNew.setExtra(ze.getExtra());
        zeNew.setTime(ze.getTime());
        zos.putArchiveEntry(zeNew);
        FilterOutputStream fos2 = new FilterOutputStream(zos) {
            // do not close underlyzing ZipOutputStream
            @Override
            public void close() {
            }
        };
        OutputStream nos;
        if (this.ciEncoder != null) { // encrypt if needed
            nos = new CipherOutputStream(fos2, this.ciEncoder);
        } else { // do not encrypt
            nos = fos2;
        }
        IOUtils.copy(zis, nos);
        nos.close();
        if (fos2 != null) {
            fos2.close();
        }
        zos.closeArchiveEntry();

    }
    zos.close();
    fos.close();
    zis.close();
    IOUtils.closeQuietly(is);
    this.zipFile = new ZipFile(this.tmpFile);

}

From source file:de.tud.inf.db.sparqlytics.model.Session.java

/**
 * Creates a new output writer.//  w w w  .j av  a  2 s.  c o m
 *
 * @return a new output writer
 * @throws IOException if an error occurs
 *
 * @see #setSink
 */
public OutputStream getOutput() throws IOException {
    if (sink == null) {
        //System.out must not be closed
        return new FilterOutputStream(System.out) {
            @Override
            public void close() {
            }
        };
    } else if (sink.isFile()) {
        return new BufferedOutputStream(new FileOutputStream(sink, true));
    } else {
        ResultsFormat format = getResultsFormat();
        if (format == null) {
            format = ResultsFormat.FMT_RDF_XML;
        }
        Lang lang = ResultsFormat.convert(format);
        if (lang == null) {
            lang = RDFLanguages.contentTypeToLang(format.getSymbol());
        }
        List<String> extensions = lang.getFileExtensions();
        StringBuilder name = new StringBuilder(dateFormat.format(new Date()));
        if (!extensions.isEmpty()) {
            name.append('.').append(extensions.get(0));
        }
        return new BufferedOutputStream(new FileOutputStream(new File(sink, name.toString())));
    }
}

From source file:org.apache.sis.internal.maven.Assembler.java

/**
 * Creates the distribution file.//from www . j  a  v a 2 s  .c  om
 *
 * @throws MojoExecutionException if the plugin execution failed.
 */
@Override
public void execute() throws MojoExecutionException {
    final File sourceDirectory = new File(rootDirectory, ARTIFACT_PATH);
    if (!sourceDirectory.isDirectory()) {
        throw new MojoExecutionException("Directory not found: " + sourceDirectory);
    }
    final File targetDirectory = new File(rootDirectory, TARGET_DIRECTORY);
    final String version = project.getVersion();
    final String artifactBase = FINALNAME_PREFIX + version;
    try {
        final File targetFile = new File(distributionDirectory(targetDirectory), artifactBase + ".zip");
        final ZipArchiveOutputStream zip = new ZipArchiveOutputStream(targetFile);
        try {
            zip.setLevel(9);
            appendRecursively(sourceDirectory, artifactBase, zip, new byte[8192]);
            /*
             * At this point, all the "application/sis-console/src/main/artifact" and sub-directories
             * have been zipped.  Now generate the Pack200 file and zip it directly (without creating
             * a temporary "sis.pack.gz" file).
             */
            final Packer packer = new Packer(project.getName(), project.getUrl(), version, targetDirectory);
            final ZipArchiveEntry entry = new ZipArchiveEntry(
                    artifactBase + '/' + LIB_DIRECTORY + '/' + FATJAR_FILE + PACK_EXTENSION);
            entry.setMethod(ZipArchiveEntry.STORED);
            zip.putArchiveEntry(entry);
            packer.preparePack200(FATJAR_FILE + ".jar").pack(new FilterOutputStream(zip) {
                /*
                 * Closes the archive entry, not the ZIP file.
                 */
                @Override
                public void close() throws IOException {
                    zip.closeArchiveEntry();
                }
            });
        } finally {
            zip.close();
        }
    } catch (IOException e) {
        throw new MojoExecutionException(e.getLocalizedMessage(), e);
    }
}