List of usage examples for java.io FilterOutputStream FilterOutputStream
public FilterOutputStream(OutputStream out)
From source file:com.netscape.cms.publish.publishers.FileBasedPublisher.java
/** * Publishes a object to the ldap directory. * * @param conn a Ldap connection/*from w w w .ja v a 2s. co m*/ * (null if LDAP publishing is not enabled) * @param dn dn of the ldap entry to publish cert * (null if LDAP publishing is not enabled) * @param object object to publish * (java.security.cert.X509Certificate or, * java.security.cert.X509CRL) */ public void publish(LDAPConnection conn, String dn, Object object) throws ELdapException { CMS.debug("FileBasedPublisher: publish"); try { if (object instanceof X509Certificate) { X509Certificate cert = (X509Certificate) object; BigInteger sno = cert.getSerialNumber(); String name = mDir + File.separator + "cert-" + sno.toString(); if (mDerAttr) { FileOutputStream fos = null; try { String fileName = name + ".der"; fos = new FileOutputStream(fileName); fos.write(cert.getEncoded()); } finally { if (fos != null) fos.close(); } } if (mB64Attr) { String fileName = name + ".b64"; PrintStream ps = null; Base64OutputStream b64 = null; FileOutputStream fos = null; try { fos = new FileOutputStream(fileName); ByteArrayOutputStream output = new ByteArrayOutputStream(); b64 = new Base64OutputStream(new PrintStream(new FilterOutputStream(output))); b64.write(cert.getEncoded()); b64.flush(); ps = new PrintStream(fos); ps.print(output.toString("8859_1")); } finally { if (ps != null) { ps.close(); } if (b64 != null) { b64.close(); } if (fos != null) fos.close(); } } } else if (object instanceof X509CRL) { X509CRL crl = (X509CRL) object; String[] namePrefix = getCrlNamePrefix(crl, mTimeStamp.equals("GMT")); String baseName = mDir + File.separator + namePrefix[0]; String tempFile = baseName + ".temp"; ZipOutputStream zos = null; byte[] encodedArray = null; File destFile = null; String destName = null; File renameFile = null; if (mDerAttr) { FileOutputStream fos = null; try { fos = new FileOutputStream(tempFile); encodedArray = crl.getEncoded(); fos.write(encodedArray); } finally { if (fos != null) fos.close(); } if (mZipCRL) { try { zos = new ZipOutputStream(new FileOutputStream(baseName + ".zip")); zos.setLevel(mZipLevel); zos.putNextEntry(new ZipEntry(baseName + ".der")); zos.write(encodedArray, 0, encodedArray.length); zos.closeEntry(); } finally { if (zos != null) zos.close(); } } destName = baseName + ".der"; destFile = new File(destName); if (destFile.exists()) { destFile.delete(); } renameFile = new File(tempFile); renameFile.renameTo(destFile); if (mLatestCRL) { String linkExt = "."; if (mLinkExt != null && mLinkExt.length() > 0) { linkExt += mLinkExt; } else { linkExt += "der"; } String linkName = mDir + File.separator + namePrefix[1] + linkExt; createLink(linkName, destName); if (mZipCRL) { linkName = mDir + File.separator + namePrefix[1] + ".zip"; createLink(linkName, baseName + ".zip"); } } } // output base64 file if (mB64Attr == true) { if (encodedArray == null) encodedArray = crl.getEncoded(); FileOutputStream fos = null; try { fos = new FileOutputStream(tempFile); fos.write(Utils.base64encode(encodedArray, true).getBytes()); } finally { if (fos != null) fos.close(); } destName = baseName + ".b64"; destFile = new File(destName); if (destFile.exists()) { destFile.delete(); } renameFile = new File(tempFile); renameFile.renameTo(destFile); } purgeExpiredFiles(); purgeExcessFiles(); } } catch (IOException e) { mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_FILE_PUBLISHER_ERROR", e.toString())); } catch (CertificateEncodingException e) { mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_FILE_PUBLISHER_ERROR", e.toString())); } catch (CRLException e) { mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER, ILogger.LL_FAILURE, CMS.getLogMessage("PUBLISH_FILE_PUBLISHER_ERROR", e.toString())); } }
From source file:org.apache.jackrabbit.core.fs.db.OracleFileSystem.java
/** * {@inheritDoc}/* w ww . j ava 2 s.c om*/ * <p/> * Overridden because we need to use <code>oracle.sql.BLOB</code> * and <code>PreparedStatement#setBlob</code> instead of just * <code>PreparedStatement#setBinaryStream</code>. */ public OutputStream getOutputStream(final String filePath) throws FileSystemException { if (!initialized) { throw new IllegalStateException("not initialized"); } FileSystemPathUtil.checkFormat(filePath); final String parentDir = FileSystemPathUtil.getParentDir(filePath); final String name = FileSystemPathUtil.getName(filePath); if (!isFolder(parentDir)) { throw new FileSystemException("path not found: " + parentDir); } if (isFolder(filePath)) { throw new FileSystemException("path denotes folder: " + filePath); } try { TransientFileFactory fileFactory = TransientFileFactory.getInstance(); final File tmpFile = fileFactory.createTransientFile("bin", null, null); return new FilterOutputStream(new FileOutputStream(tmpFile)) { public void write(byte[] bytes, int off, int len) throws IOException { out.write(bytes, off, len); } public void close() throws IOException { out.flush(); ((FileOutputStream) out).getFD().sync(); out.close(); InputStream in = null; Blob blob = null; try { if (isFile(filePath)) { synchronized (updateDataSQL) { long length = tmpFile.length(); in = new FileInputStream(tmpFile); blob = createTemporaryBlob(in); executeStmt(updateDataSQL, new Object[] { blob, new Long(System.currentTimeMillis()), new Long(length), parentDir, name }); } } else { synchronized (insertFileSQL) { long length = tmpFile.length(); in = new FileInputStream(tmpFile); blob = createTemporaryBlob(in); executeStmt(insertFileSQL, new Object[] { parentDir, name, blob, new Long(System.currentTimeMillis()), new Long(length) }); } } } catch (Exception e) { IOException ioe = new IOException(e.getMessage()); ioe.initCause(e); throw ioe; } finally { if (blob != null) { try { freeTemporaryBlob(blob); } catch (Exception e1) { } } IOUtils.closeQuietly(in); // temp file can now safely be removed tmpFile.delete(); } } }; } catch (Exception e) { String msg = "failed to open output stream to file: " + filePath; log.error(msg, e); throw new FileSystemException(msg, e); } }
From source file:sit.web.client.HttpHelper.java
public HTTPResponse doHttpUrlConnectionRequest(URL url, String method, String contentType, byte[] payload, String unamePword64) throws MalformedURLException, ProtocolException, IOException, URISyntaxException { if (payload == null) { //make sure payload is initialized payload = new byte[0]; }//from ww w .j a va 2 s .co m boolean isHTTPS = url.getProtocol().equalsIgnoreCase("https"); HttpURLConnection connection; if (isHTTPS) { connection = (HttpsURLConnection) url.openConnection(); } else { connection = (HttpURLConnection) url.openConnection(); } connection.setRequestMethod(method); connection.setRequestProperty("Host", url.getHost()); connection.setRequestProperty("Content-Type", contentType); connection.setRequestProperty("Content-Length", String.valueOf(payload.length)); if (isHTTPS) { connection.setRequestProperty("Authorization", "Basic " + unamePword64); } Logger.getLogger(HttpHelper.class.getName()).log(Level.FINER, "trying to connect:\n" + method + " " + url + "\nhttps:" + isHTTPS + "\nContentType:" + contentType + "\nContent-Length:" + String.valueOf(payload.length)); connection.setDoInput(true); if (payload.length > 0) { // open up the output stream of the connection connection.setDoOutput(true); FilterOutputStream output = new FilterOutputStream(connection.getOutputStream()); // write out the data output.write(payload); output.close(); } HTTPResponse response = new HTTPResponse(method + " " + url.toString(), payload, Charset.defaultCharset()); //TODO forward charset ot this method response.code = connection.getResponseCode(); response.message = connection.getResponseMessage(); Logger.getLogger(HttpHelper.class.getName()).log(Level.FINE, "received response: " + response.message + " with code: " + response.code); if (response.code != 500) { byte[] buffer = new byte[20480]; ByteBuilder bytes = new ByteBuilder(); // get ready to read the response from the cgi script DataInputStream input = new DataInputStream(connection.getInputStream()); boolean done = false; while (!done) { int readBytes = input.read(buffer); done = (readBytes == -1); if (!done) { bytes.append(buffer, readBytes); } } input.close(); response.reply = bytes.toString(Charset.defaultCharset()); } return response; }
From source file:io.druid.java.util.common.CompressionUtilsTest.java
@Test public void testGoodGzipWithException() throws Exception { final AtomicLong flushes = new AtomicLong(0); final File tmpDir = temporaryFolder.newFolder("testGoodGzipByteSource"); final File gzFile = new File(tmpDir, testFile.getName() + ".gz"); Assert.assertFalse(gzFile.exists()); CompressionUtils.gzip(Files.asByteSource(testFile), new ByteSink() { @Override//from w ww. j av a2 s .co m public OutputStream openStream() throws IOException { return new FilterOutputStream(new FileOutputStream(gzFile)) { @Override public void flush() throws IOException { if (flushes.getAndIncrement() > 0) { super.flush(); } else { throw new IOException("Haven't flushed enough"); } } }; } }, Predicates.<Throwable>alwaysTrue()); Assert.assertTrue(gzFile.exists()); try (final InputStream inputStream = CompressionUtils.decompress(new FileInputStream(gzFile), "file.gz")) { assertGoodDataStream(inputStream); } if (!testFile.delete()) { throw new IOE("Unable to delete file [%s]", testFile.getAbsolutePath()); } Assert.assertFalse(testFile.exists()); CompressionUtils.gunzip(Files.asByteSource(gzFile), testFile); Assert.assertTrue(testFile.exists()); try (final InputStream inputStream = new FileInputStream(testFile)) { assertGoodDataStream(inputStream); } Assert.assertEquals(4, flushes.get()); // 2 for suppressed closes, 2 for manual calls to shake out errors }
From source file:org.apache.druid.java.util.common.CompressionUtilsTest.java
@Test public void testGoodGzipWithException() throws Exception { final AtomicLong flushes = new AtomicLong(0); final File tmpDir = temporaryFolder.newFolder("testGoodGzipByteSource"); final File gzFile = new File(tmpDir, testFile.getName() + ".gz"); Assert.assertFalse(gzFile.exists()); CompressionUtils.gzip(Files.asByteSource(testFile), new ByteSink() { @Override/*from w ww.jav a 2 s .c om*/ public OutputStream openStream() throws IOException { return new FilterOutputStream(new FileOutputStream(gzFile)) { @Override public void flush() throws IOException { if (flushes.getAndIncrement() > 0) { super.flush(); } else { throw new IOException("Haven't flushed enough"); } } }; } }, Predicates.alwaysTrue()); Assert.assertTrue(gzFile.exists()); try (final InputStream inputStream = CompressionUtils.decompress(new FileInputStream(gzFile), "file.gz")) { assertGoodDataStream(inputStream); } if (!testFile.delete()) { throw new IOE("Unable to delete file [%s]", testFile.getAbsolutePath()); } Assert.assertFalse(testFile.exists()); CompressionUtils.gunzip(Files.asByteSource(gzFile), testFile); Assert.assertTrue(testFile.exists()); try (final InputStream inputStream = new FileInputStream(testFile)) { assertGoodDataStream(inputStream); } Assert.assertEquals(4, flushes.get()); // 2 for suppressed closes, 2 for manual calls to shake out errors }
From source file:org.kie.commons.java.nio.fs.jgit.JGitFileSystemProvider.java
@Override public OutputStream newOutputStream(final Path path, final OpenOption... options) throws IllegalArgumentException, UnsupportedOperationException, IOException, SecurityException { checkNotNull("path", path); final JGitPathImpl gPath = toPathImpl(path); final Pair<PathType, ObjectId> result = checkPath(gPath.getFileSystem().gitRepo(), gPath.getRefTree(), gPath.getPath());/*from www . jav a 2 s . co m*/ if (result.getK1().equals(PathType.DIRECTORY)) { throw new IOException(); } try { final File file = File.createTempFile("gitz", "woot"); return new FilterOutputStream(new FileOutputStream(file)) { public void close() throws java.io.IOException { super.close(); String name = null; String email = null; String message = null; TimeZone timeZone = null; Date when = null; if (options != null && options.length > 0) { for (final OpenOption option : options) { if (option instanceof CommentedOption) { final CommentedOption op = (CommentedOption) option; name = op.getName(); email = op.getEmail(); message = op.getMessage(); timeZone = op.getTimeZone(); when = op.getWhen(); break; } } } commit(gPath.getFileSystem().gitRepo(), gPath.getRefTree(), name, email, message, timeZone, when, new HashMap<String, File>() { { put(gPath.getPath(), file); } }); } }; } catch (java.io.IOException e) { throw new IOException(e); } }
From source file:io.druid.java.util.common.CompressionUtilsTest.java
@Test(expected = IOException.class) public void testStreamErrorGunzip() throws Exception { final File tmpDir = temporaryFolder.newFolder("testGoodGzipByteSource"); final File gzFile = new File(tmpDir, testFile.getName() + ".gz"); Assert.assertFalse(gzFile.exists()); CompressionUtils.gzip(Files.asByteSource(testFile), Files.asByteSink(gzFile), Predicates.<Throwable>alwaysTrue()); Assert.assertTrue(gzFile.exists());/*from w w w .j a va 2s .com*/ try (final InputStream inputStream = CompressionUtils.decompress(new FileInputStream(gzFile), "file.gz")) { assertGoodDataStream(inputStream); } if (testFile.exists() && !testFile.delete()) { throw new RE("Unable to delete file [%s]", testFile.getAbsolutePath()); } Assert.assertFalse(testFile.exists()); final AtomicLong flushes = new AtomicLong(0L); CompressionUtils.gunzip(new FileInputStream(gzFile), new FilterOutputStream(new FileOutputStream(testFile) { @Override public void flush() throws IOException { if (flushes.getAndIncrement() > 0) { super.flush(); } else { throw new IOException("Test exception"); } } })); }
From source file:org.apache.jackrabbit.core.fs.db.DatabaseFileSystem.java
/** * {@inheritDoc}/*from ww w . j a v a 2 s . c o m*/ */ public OutputStream getOutputStream(final String filePath) throws FileSystemException { if (!initialized) { throw new IllegalStateException("not initialized"); } FileSystemPathUtil.checkFormat(filePath); final String parentDir = FileSystemPathUtil.getParentDir(filePath); final String name = FileSystemPathUtil.getName(filePath); if (!isFolder(parentDir)) { throw new FileSystemException("path not found: " + parentDir); } if (isFolder(filePath)) { throw new FileSystemException("path denotes folder: " + filePath); } try { TransientFileFactory fileFactory = TransientFileFactory.getInstance(); final File tmpFile = fileFactory.createTransientFile("bin", null, null); return new FilterOutputStream(new FileOutputStream(tmpFile)) { public void write(byte[] bytes, int off, int len) throws IOException { out.write(bytes, off, len); } public void close() throws IOException { out.flush(); ((FileOutputStream) out).getFD().sync(); out.close(); InputStream in = null; try { if (isFile(filePath)) { synchronized (updateDataSQL) { long length = tmpFile.length(); in = new FileInputStream(tmpFile); executeStmt(updateDataSQL, new Object[] { new SizedInputStream(in, length), new Long(System.currentTimeMillis()), new Long(length), parentDir, name }); } } else { synchronized (insertFileSQL) { long length = tmpFile.length(); in = new FileInputStream(tmpFile); executeStmt(insertFileSQL, new Object[] { parentDir, name, new SizedInputStream(in, length), new Long(System.currentTimeMillis()), new Long(length) }); } } } catch (Exception e) { IOException ioe = new IOException(e.getMessage()); ioe.initCause(e); throw ioe; } finally { if (in != null) { in.close(); } // temp file can now safely be removed tmpFile.delete(); } } }; } catch (Exception e) { String msg = "failed to open output stream to file: " + filePath; log.error(msg, e); throw new FileSystemException(msg, e); } }
From source file:org.apache.druid.java.util.common.CompressionUtilsTest.java
@Test(expected = IOException.class) public void testStreamErrorGunzip() throws Exception { final File tmpDir = temporaryFolder.newFolder("testGoodGzipByteSource"); final File gzFile = new File(tmpDir, testFile.getName() + ".gz"); Assert.assertFalse(gzFile.exists()); CompressionUtils.gzip(Files.asByteSource(testFile), Files.asByteSink(gzFile), Predicates.alwaysTrue()); Assert.assertTrue(gzFile.exists());//from ww w . ja va 2 s .c om try (final InputStream inputStream = CompressionUtils.decompress(new FileInputStream(gzFile), "file.gz")) { assertGoodDataStream(inputStream); } if (testFile.exists() && !testFile.delete()) { throw new RE("Unable to delete file [%s]", testFile.getAbsolutePath()); } Assert.assertFalse(testFile.exists()); final AtomicLong flushes = new AtomicLong(0L); CompressionUtils.gunzip(new FileInputStream(gzFile), new FilterOutputStream(new FileOutputStream(testFile) { @Override public void flush() throws IOException { if (flushes.getAndIncrement() > 0) { super.flush(); } else { throw new IOException("Test exception"); } } })); }
From source file:org.sakaiproject.nakamura.email.outgoing.LiteOutgoingEmailMessageListener.java
private void logEmail(MultiPartEmail multiPartMessage) { if (multiPartMessage != null) { MimeMessage mimeMessage = multiPartMessage.getMimeMessage(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try {//from w w w .j a v a 2 s . c o m mimeMessage.writeTo(new FilterOutputStream(baos)); LOGGER.debug("Email content = \n" + baos.toString()); } catch (IOException e) { LOGGER.error("failed to log email", e); } catch (MessagingException e) { LOGGER.error("failed to log email", e); } } else { LOGGER.error("Email is null"); } }