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.apache.jackrabbit.core.fs.mem.MemoryFileSystem.java

public OutputStream getOutputStream(String filePath) throws FileSystemException {
    if (isFolder(filePath)) {
        throw new FileSystemException("path denotes folder: " + filePath);
    }//  w  w w .  j ava2 s.  co m

    String folderPath = filePath;
    if (filePath.lastIndexOf(FileSystem.SEPARATOR) > 0) {
        folderPath = filePath.substring(0, filePath.lastIndexOf("/"));
    } else {
        folderPath = "/";
    }
    assertIsFolder(folderPath);

    final MemoryFile file = new MemoryFile();
    entries.put(filePath, file);
    return new FilterOutputStream(new ByteArrayOutputStream()) {
        public void write(byte[] bytes, int off, int len) throws IOException {
            out.write(bytes, off, len);
        }

        public void close() throws IOException {
            out.close();
            file.setData(((ByteArrayOutputStream) out).toByteArray());
        }
    };
}

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

@Override
public OutputStream createFile(final S3Object f) throws FileSystemException, IOException {
    String fileName = FileUtils.getTempDirectory().getAbsolutePath() + "tempFile";

    final File file = new File(fileName);
    final FileOutputStream fos = new FileOutputStream(file);
    final BufferedOutputStream bos = new BufferedOutputStream(fos);

    FilterOutputStream filterOutputStream = new FilterOutputStream(bos) {
        @Override/*w  w w  .  ja va 2 s  . com*/
        public void close() throws IOException {
            super.close();
            bos.close();

            FileInputStream fis = new FileInputStream(file);
            ObjectMetadata metaData = new ObjectMetadata();
            metaData.setContentLength(file.length());

            s3Client.putObject(bucketName, f.getKey(), fis, metaData);

            fis.close();
            file.delete();
        }
    };
    return filterOutputStream;
}

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

@Override
public OutputStream getOutputStream() {
    if (DEBUG) {//from w  ww. j av a 2 s  .  c o  m
        return new FilterOutputStream(process.getOutputStream()) {
            @Override
            public void write(int b) throws IOException {
                System.err.print((char) b);
                super.write(b);
            }

            @Override
            public void write(byte[] b) throws IOException {
                System.err.print(new String(b));
                super.write(b);
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
                byte[] actual = new byte[len];
                System.arraycopy(b, off, actual, 0, len);
                System.err.print(new String(actual));
                super.write(b, off, len);
            }
        };
    } else {
        return process.getOutputStream();
    }
}

From source file:org.apache.xmlrpc.client.XmlRpcCommonsTransport.java

protected void writeRequest(final ReqWriter pWriter) throws XmlRpcException {
    method.setRequestEntity(new RequestEntity() {
        public boolean isRepeatable() {
            return true;
        }//from   w  w  w  . ja  v a  2 s .c om

        public void writeRequest(OutputStream pOut) throws IOException {
            try {
                /* Make sure, that the socket is not closed by replacing it with our
                 * own BufferedOutputStream.
                 */
                OutputStream ostream;
                if (isUsingByteArrayOutput(config)) {
                    // No need to buffer the output.
                    ostream = new FilterOutputStream(pOut) {
                        public void close() throws IOException {
                            flush();
                        }

                        // See XMLRPC-173
                        public void write(byte[] b, int off, int len) throws IOException {
                            out.write(b, off, len);
                        }

                        // See XMLRPC-173
                        public void write(byte[] b) throws IOException {
                            out.write(b);
                        }
                    };
                } else {
                    ostream = new BufferedOutputStream(pOut) {
                        public void close() throws IOException {
                            flush();
                        }
                    };
                }
                pWriter.write(ostream);
            } catch (XmlRpcException e) {
                throw new XmlRpcIOException(e);
            } catch (SAXException e) {
                throw new XmlRpcIOException(e);
            }
        }

        public long getContentLength() {
            return contentLength;
        }

        public String getContentType() {
            return "text/xml";
        }
    });
    try {
        int redirectAttempts = 0;
        for (;;) {
            client.executeMethod(method);
            if (!isRedirectRequired()) {
                break;
            }
            if (redirectAttempts++ > MAX_REDIRECT_ATTEMPTS) {
                throw new XmlRpcException("Too many redirects.");
            }
            resetClientForRedirect();
        }
    } catch (XmlRpcIOException e) {
        Throwable t = e.getLinkedException();
        if (t instanceof XmlRpcException) {
            throw (XmlRpcException) t;
        } else {
            throw new XmlRpcException("Unexpected exception: " + t.getMessage(), t);
        }
    } catch (IOException e) {
        throw new XmlRpcException("I/O error while communicating with HTTP server: " + e.getMessage(), e);
    }
}

From source file:edu.ucsd.xmlrpc.xmlrpc.client.XmlRpcCommonsTransport.java

protected void writeRequest(final ReqWriter pWriter) throws XmlRpcException {
    method.setRequestEntity(new RequestEntity() {
        public boolean isRepeatable() {
            return true;
        }/*from w  ww.  j av  a 2s.  co m*/

        public void writeRequest(OutputStream pOut) throws IOException {
            try {
                /* Make sure, that the socket is not closed by replacing it with our
                 * own BufferedOutputStream.
                 */
                OutputStream ostream;
                if (isUsingByteArrayOutput(config)) {
                    // No need to buffer the output.
                    ostream = new FilterOutputStream(pOut) {
                        public void close() throws IOException {
                            flush();
                        }
                    };
                } else {
                    ostream = new BufferedOutputStream(pOut) {
                        public void close() throws IOException {
                            flush();
                        }
                    };
                }
                pWriter.write(ostream);
            } catch (XmlRpcException e) {
                throw new XmlRpcIOException(e);
            } catch (SAXException e) {
                throw new XmlRpcIOException(e);
            }
        }

        public long getContentLength() {
            return contentLength;
        }

        public String getContentType() {
            return "text/xml";
        }
    });
    try {
        int redirectAttempts = 0;
        for (;;) {
            client.executeMethod(method);
            if (!isRedirectRequired()) {
                break;
            }
            if (redirectAttempts++ > MAX_REDIRECT_ATTEMPTS) {
                throw new XmlRpcException("Too many redirects.");
            }
            resetClientForRedirect();
        }
    } catch (XmlRpcIOException e) {
        Throwable t = e.getLinkedException();
        if (t instanceof XmlRpcException) {
            throw (XmlRpcException) t;
        } else {
            throw new XmlRpcException("Unexpected exception: " + t.getMessage(), t);
        }
    } catch (IOException e) {
        throw new XmlRpcException("I/O error while communicating with HTTP server: " + e.getMessage(), e);
    }
}

From source file:org.ScripterRon.BitcoinMonitor.Request.java

/**
 * Issue the Bitcoin RPC request and return the parsed JSON response
 *
 * @param       requestType             Request type
 * @param       requestParams           Request parameters in JSON format or null if no parameters
 * @return                              Parsed JSON response
 * @throws      IOException             Unable to issue Bitcoin RPC request
 * @throws      ParseException          Unable to parse the Bitcoin RPC response
 *//*from  w w  w  .  j av a  2  s .  c o  m*/
private static Response issueRequest(String requestType, String requestParams)
        throws IOException, ParseException {
    long id = requestId.incrementAndGet();
    Response response = null;
    try {
        URL url = new URL(String.format("http://%s:%d/", Main.rpcHost, Main.rpcPort));
        String request;
        if (requestParams != null) {
            request = String.format("{\"jsonrpc\": \"2.0\", \"method\": \"%s\", \"params\": %s, \"id\": %d}",
                    requestType, requestParams, id);
        } else {
            request = String.format("{\"jsonrpc\": \"2.0\", \"method\": \"%s\", \"id\": %d}", requestType, id);
        }
        log.debug(String.format("Issue HTTP request to %s:%d: %s", Main.rpcHost, Main.rpcPort, request));
        byte[] requestBytes = request.getBytes("UTF-8");
        //
        // Issue the request
        //
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json-rpc");
        conn.setRequestProperty("Cache-Control", "no-cache, no-store");
        conn.setRequestProperty("Content-Length", String.format("%d", requestBytes.length));
        conn.setRequestProperty("Accept", "application/json-rpc");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setConnectTimeout(nodeConnectTimeout);
        conn.setReadTimeout(nodeReadTimeout);
        conn.connect();
        try (FilterOutputStream out = new FilterOutputStream(conn.getOutputStream())) {
            out.write(requestBytes);
            out.flush();
            int code = conn.getResponseCode();
            if (code != HttpURLConnection.HTTP_OK) {
                String errorText = String.format("Response code %d for %s request\n  %s", code, requestType,
                        conn.getResponseMessage());
                log.error(errorText);
                throw new IOException(errorText);
            }
        }
        //
        // Parse the response
        //
        try (InputStreamReader in = new InputStreamReader(conn.getInputStream(), "UTF-8")) {
            JSONParser parser = new JSONParser();
            response = (Response) parser.parse(in, containerFactory);
            Response errorResponse = (Response) response.getObject("error");
            if (errorResponse != null) {
                String errorText = String.format("Error %d returned for %s request\n  %s",
                        errorResponse.getInt("code"), requestType, errorResponse.getString("message"));
                log.error(errorText);
                throw new IOException(errorText);
            }
        }
        if (log.isDebugEnabled())
            log.debug(String.format("Request complete\n%s", Utils.formatJSON(response)));
    } catch (MalformedURLException exc) {
        throw new IOException("Malformed Bitcoin RPC URL", exc);
    } catch (org.json.simple.parser.ParseException exc) {
        String errorText = String.format("JSON parse exception for %s request: Position %d, Code %d",
                requestType, exc.getPosition(), exc.getErrorType());
        log.error(errorText);
        throw new ParseException(errorText, exc.getPosition(), exc.getErrorType());
    } catch (IOException exc) {
        String errorText = String.format("I/O error on %s request", requestType);
        log.error(errorText, exc);
        throw new IOException(errorText);
    }
    return response;
}

From source file:net.solarnetwork.node.backup.FileSystemBackupService.java

@Override
public Backup performBackup(final Iterable<BackupResource> resources) {
    if (resources == null) {
        return null;
    }//from w ww  .j ava2s .  c  o m
    final Iterator<BackupResource> itr = resources.iterator();
    if (!itr.hasNext()) {
        log.debug("No resources provided, nothing to backup");
        return null;
    }
    BackupStatus status = setStatusIf(RunningBackup, Configured);
    if (status != RunningBackup) {
        return null;
    }
    final Calendar now = new GregorianCalendar();
    now.set(Calendar.MILLISECOND, 0);
    final String archiveName = String.format(ARCHIVE_NAME_FORMAT, now);
    final File archiveFile = new File(backupDir, archiveName);
    final String archiveKey = getArchiveKey(archiveName);
    log.info("Starting backup to archive {}", archiveName);
    log.trace("Backup archive: {}", archiveFile.getAbsolutePath());
    Backup backup = null;
    ZipOutputStream zos = null;
    try {
        zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(archiveFile)));
        while (itr.hasNext()) {
            BackupResource r = itr.next();
            log.debug("Backup up resource {} to archive {}", r.getBackupPath(), archiveName);
            zos.putNextEntry(new ZipEntry(r.getBackupPath()));
            FileCopyUtils.copy(r.getInputStream(), new FilterOutputStream(zos) {

                @Override
                public void close() throws IOException {
                    // FileCopyUtils closes the stream, which we don't want
                }

            });
        }
        zos.flush();
        zos.finish();
        log.info("Backup complete to archive {}", archiveName);
        backup = new SimpleBackup(now.getTime(), archiveKey, archiveFile.length(), true);

        // clean out older backups
        File[] backupFiles = getAvailableBackupFiles();
        if (backupFiles != null && backupFiles.length > additionalBackupCount + 1) {
            // delete older files
            for (int i = additionalBackupCount + 1; i < backupFiles.length; i++) {
                log.info("Deleting old backup archive {}", backupFiles[i].getName());
                if (!backupFiles[i].delete()) {
                    log.warn("Unable to delete backup archive {}", backupFiles[i].getAbsolutePath());
                }
            }
        }
    } catch (IOException e) {
        log.error("IO error creating backup: {}", e.getMessage());
        setStatus(Error);
    } catch (RuntimeException e) {
        log.error("Error creating backup: {}", e.getMessage());
        setStatus(Error);
    } finally {
        if (zos != null) {
            try {
                zos.close();
            } catch (IOException e) {
                // ignore this
            }
        }
        status = setStatusIf(Configured, RunningBackup);
        if (status != Configured) {
            // clean up if we encountered an error
            if (archiveFile.exists()) {
                archiveFile.delete();
            }
        }
    }
    return backup;
}

From source file:org.candlepin.util.CrlFileUtil.java

/**
 * Updates the specified CRL file by adding or removing entries. If both lists are either null
 * or empty, the CRL file will not be modified by this method. If the file does not exist or
 * appears to be empty, it will be initialized before processing the lists.
 *
 * @param file/*  w  ww . j  a va2s  . c  o m*/
 *  The CRL file to update
 *
 * @param revoke
 *  A collection of serials to revoke (add)
 *
 * @param unrevoke
 *  A collection of serials to unrevoke (remove)
 *
 * @throws IOException
 *  if an IO error occurs while updating the CRL file
 */
public void updateCRLFile(File file, final Collection<BigInteger> revoke, final Collection<BigInteger> unrevoke)
        throws IOException {

    if (!file.exists() || file.length() == 0) {
        this.initializeCRLFile(file, revoke);
        return;
    }

    File strippedFile = stripCRLFile(file);

    InputStream input = null;
    InputStream reaper = null;

    BufferedOutputStream output = null;
    OutputStream filter = null;
    OutputStream encoder = null;

    try {
        // Impl note:
        // Due to the way the X509CRLStreamWriter works (and the DER format in general), we have
        // to make two passes through the file.
        input = new Base64InputStream(new FileInputStream(strippedFile));
        reaper = new Base64InputStream(new FileInputStream(strippedFile));

        // Note: This will break if we ever stop using RSA keys
        PrivateKey key = this.pkiReader.getCaKey();
        X509CRLStreamWriter writer = new X509CRLStreamWriter(input, (RSAPrivateKey) key,
                this.pkiReader.getCACert());

        // Add new entries
        if (revoke != null) {
            Date now = new Date();
            for (BigInteger serial : revoke) {
                writer.add(serial, now, CRLReason.privilegeWithdrawn);
            }
        }

        // Unfortunately, we need to do the prescan before checking if we have changes queued,
        // or we could miss cases where we have entries to remove, but nothing to add.
        if (unrevoke != null && !unrevoke.isEmpty()) {
            writer.preScan(reaper, new CRLEntryValidator() {
                public boolean shouldDelete(X509CRLEntryObject entry) {
                    return unrevoke.contains(entry.getSerialNumber());
                }
            });
        } else {
            writer.preScan(reaper);
        }

        // Verify we actually have work to do now
        if (writer.hasChangesQueued()) {
            output = new BufferedOutputStream(new FileOutputStream(file));
            filter = new FilterOutputStream(output) {
                private boolean needsLineBreak = true;

                public void write(int b) throws IOException {
                    this.needsLineBreak = (b != (byte) '\n');
                    super.write(b);
                }

                public void write(byte[] buffer) throws IOException {
                    this.needsLineBreak = (buffer[buffer.length - 1] != (byte) '\n');
                    super.write(buffer);
                }

                public void write(byte[] buffer, int off, int len) throws IOException {
                    this.needsLineBreak = (buffer[off + len - 1] != (byte) '\n');
                    super.write(buffer, off, len);
                }

                public void close() throws IOException {
                    if (this.needsLineBreak) {
                        super.write((int) '\n');
                        this.needsLineBreak = false;
                    }

                    // Impl note:
                    // We're intentionally not propagating the call here.
                }
            };
            encoder = new Base64OutputStream(filter, true, 76, new byte[] { (byte) '\n' });

            output.write("-----BEGIN X509 CRL-----\n".getBytes());

            writer.lock();
            writer.write(encoder);
            encoder.close();
            filter.close();

            output.write("-----END X509 CRL-----\n".getBytes());
            output.close();
        }
    } catch (GeneralSecurityException e) {
        // This should never actually happen
        log.error("Unexpected security error occurred while retrieving CA key", e);
    } catch (CryptoException e) {
        // Something went horribly wrong with the stream writer
        log.error("Unexpected error occurred while writing new CRL file", e);
    } finally {
        for (Closeable stream : Arrays.asList(encoder, output, reaper, input)) {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    log.error("Unexpected exception occurred while closing stream: {}", stream, e);
                }
            }
        }

        if (!strippedFile.delete()) {
            log.error("Unable to delete temporary CRL file: {}", strippedFile);
        }
    }
}

From source file:net.solarnetwork.node.backup.DefaultBackupManager.java

@Override
public void exportBackupArchive(String backupKey, OutputStream out) throws IOException {
    final BackupService service = activeBackupService();
    if (service == null) {
        return;/*ww  w  . j  a  v a 2 s.  com*/
    }

    final Backup backup = service.backupForKey(backupKey);
    if (backup == null) {
        return;
    }

    // create the zip archive for the backup files
    ZipOutputStream zos = new ZipOutputStream(out);
    try {
        BackupResourceIterable resources = service.getBackupResources(backup);
        for (BackupResource r : resources) {
            zos.putNextEntry(new ZipEntry(r.getBackupPath()));
            FileCopyUtils.copy(r.getInputStream(), new FilterOutputStream(zos) {

                @Override
                public void close() throws IOException {
                    // FileCopyUtils closed the stream, which we don't want here
                }

            });
        }
        resources.close();
    } finally {
        zos.flush();
        zos.finish();
        zos.close();
    }
}

From source file:com.netscape.cms.logging.LogFile.java

public static String base64Encode(byte[] bytes) throws IOException {
    // All this streaming is lame, but Base64OutputStream needs a
    // PrintStream
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    try (Base64OutputStream b64 = new Base64OutputStream(new PrintStream(new FilterOutputStream(output)))) {
        b64.write(bytes);/*  www .ja v  a  2 s.c o  m*/
        b64.flush();

        // This is internationally safe because Base64 chars are
        // contained within 8859_1
        return output.toString("8859_1");
    }
}