List of usage examples for org.apache.commons.codec.binary Base64OutputStream Base64OutputStream
public Base64OutputStream(OutputStream out, boolean doEncode, int lineLength, byte[] lineSeparator)
From source file:com.opengamma.web.analytics.json.Compressor.java
static void compressStream(InputStream inputStream, OutputStream outputStream) throws IOException { InputStream iStream = new BufferedInputStream(inputStream); GZIPOutputStream oStream = new GZIPOutputStream( new Base64OutputStream(new BufferedOutputStream(outputStream), true, -1, null), 2048); byte[] buffer = new byte[2048]; int bytesRead; while ((bytesRead = iStream.read(buffer)) != -1) { oStream.write(buffer, 0, bytesRead); }/*www. ja v a2s . c o m*/ oStream.close(); // this is necessary for the gzip and base64 streams }
From source file:cloudeventbus.codec.Encoder.java
@Override public void encode(ChannelHandlerContext ctx, Frame frame, ByteBuf out) throws Exception { LOGGER.debug("Encoding frame {}", frame); switch (frame.getFrameType()) { case AUTHENTICATE: final AuthenticationRequestFrame authenticationRequestFrame = (AuthenticationRequestFrame) frame; out.writeByte(FrameType.AUTHENTICATE.getOpcode()); out.writeByte(' '); final String challenge = Base64.encodeBase64String(authenticationRequestFrame.getChallenge()); writeString(out, challenge);/*from w w w .j a va2 s . co m*/ break; case AUTH_RESPONSE: final AuthenticationResponseFrame authenticationResponseFrame = (AuthenticationResponseFrame) frame; out.writeByte(FrameType.AUTH_RESPONSE.getOpcode()); out.writeByte(' '); // Write certificate chain final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final OutputStream base64Out = new Base64OutputStream(outputStream, true, Integer.MAX_VALUE, new byte[0]); CertificateStoreLoader.store(base64Out, authenticationResponseFrame.getCertificates()); out.writeBytes(outputStream.toByteArray()); out.writeByte(' '); // Write salt final byte[] encodedSalt = Base64.encodeBase64(authenticationResponseFrame.getSalt()); out.writeBytes(encodedSalt); out.writeByte(' '); // Write signature final byte[] encodedDigitalSignature = Base64 .encodeBase64(authenticationResponseFrame.getDigitalSignature()); out.writeBytes(encodedDigitalSignature); break; case ERROR: final ErrorFrame errorFrame = (ErrorFrame) frame; out.writeByte(FrameType.ERROR.getOpcode()); out.writeByte(' '); writeString(out, Integer.toString(errorFrame.getCode().getErrorNumber())); if (errorFrame.getMessage() != null) { out.writeByte(' '); writeString(out, errorFrame.getMessage()); } break; case GREETING: final GreetingFrame greetingFrame = (GreetingFrame) frame; out.writeByte(FrameType.GREETING.getOpcode()); out.writeByte(' '); writeString(out, Integer.toString(greetingFrame.getVersion())); out.writeByte(' '); writeString(out, greetingFrame.getAgent()); out.writeByte(' '); writeString(out, Long.toString(greetingFrame.getId())); break; case PING: out.writeByte(FrameType.PING.getOpcode()); break; case PONG: out.writeByte(FrameType.PONG.getOpcode()); break; case PUBLISH: final PublishFrame publishFrame = (PublishFrame) frame; out.writeByte(FrameType.PUBLISH.getOpcode()); out.writeByte(' '); writeString(out, publishFrame.getSubject().toString()); if (publishFrame.getReplySubject() != null) { out.writeByte(' '); writeString(out, publishFrame.getReplySubject().toString()); } out.writeByte(' '); final ByteBuf body = Unpooled.wrappedBuffer(publishFrame.getBody().getBytes(CharsetUtil.UTF_8)); writeString(out, Integer.toString(body.readableBytes())); out.writeBytes(Codec.DELIMITER); out.writeBytes(body); break; case SERVER_READY: out.writeByte(FrameType.SERVER_READY.getOpcode()); break; case SUBSCRIBE: final SubscribeFrame subscribeFrame = (SubscribeFrame) frame; out.writeByte(FrameType.SUBSCRIBE.getOpcode()); out.writeByte(' '); writeString(out, subscribeFrame.getSubject().toString()); break; case UNSUBSCRIBE: final UnsubscribeFrame unsubscribeFrame = (UnsubscribeFrame) frame; out.writeByte(FrameType.UNSUBSCRIBE.getOpcode()); out.writeByte(' '); writeString(out, unsubscribeFrame.getSubject().toString()); break; default: throw new EncodingException("Don't know how to encode message of type " + frame.getClass().getName()); } out.writeBytes(Codec.DELIMITER); }
From source file:gobblin.codec.Base64Codec.java
private OutputStream encodeOutputStreamWithApache(OutputStream origStream) { return new Base64OutputStream(origStream, true, 0, null); }
From source file:com.twentyn.patentExtractor.Util.java
public static byte[] compressXMLDocument(Document doc) throws IOException, TransformerConfigurationException, TransformerException { Transformer transformer = getTransformerFactory().newTransformer(); // The OutputKeys.INDENT configuration key determines whether the output is indented. DOMSource w3DomSource = new DOMSource(doc); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Writer w = new BufferedWriter(new OutputStreamWriter( new GZIPOutputStream(new Base64OutputStream(baos, true, 0, new byte[] { '\n' })))); StreamResult sResult = new StreamResult(w); transformer.transform(w3DomSource, sResult); w.close();/*w w w . j a v a 2 s. c o m*/ return baos.toByteArray(); }
From source file:com.xpn.xwiki.internal.xml.DOMXMLWriter.java
/** * {@inheritDoc}// w ww . jav a 2 s . c om * <p> * Add the element into the <code>{@link Document}</code> as a children of the element at the top of the stack of * opened elements, putting the whole stream content as Base64 text in the content of the * <code>{@link Element}</code>. * * @see com.xpn.xwiki.internal.xml.XMLWriter#writeBase64(org.dom4j.Element, java.io.InputStream) */ @Override public void writeBase64(Element element, InputStream is) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Base64OutputStream out = new Base64OutputStream(baos, true, 0, null); IOUtils.copy(is, out); out.close(); element.addText(baos.toString(this.format.getEncoding())); write(element); }
From source file:hudson.console.ConsoleNote.java
private ByteArrayOutputStream encodeToBytes() throws IOException { ByteArrayOutputStream buf = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(new GZIPOutputStream(buf)); try {// www . j av a 2 s. c o m oos.writeObject(this); } finally { oos.close(); } ByteArrayOutputStream buf2 = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(new Base64OutputStream(buf2, true, -1, null)); try { buf2.write(PREAMBLE); dos.writeInt(buf.size()); buf.writeTo(dos); } finally { dos.close(); } buf2.write(POSTAMBLE); return buf2; }
From source file:com.googlecode.jdeltasync.DeltaSyncClient.java
private void downloadMessageContent(final IDeltaSyncSession session, final String messageId, final OutputStream output, final boolean raw) throws DeltaSyncException, IOException { String request = "<ItemOperations xmlns=\"ItemOperations:\" xmlns:A=\"HMMAIL:\">" + "<Fetch>" + "<Class>Email</Class>" + "<A:ServerId>" + messageId + "</A:ServerId>" + "<A:Compression>hm-compression</A:Compression>" + "<A:ResponseContentType>mtom</A:ResponseContentType>" + "</Fetch>" + "</ItemOperations>"; Document response = itemOperations(session, request, new UriCapturingResponseHandler<Document>() { public Document handle(URI uri, HttpResponse response) throws DeltaSyncException, IOException { session.setBaseUri(uri.getScheme() + "://" + uri.getHost()); Header contentType = response.getFirstHeader("Content-Type"); if (contentType == null || !contentType.getValue().equals("application/xop+xml")) { if (contentType != null && contentType.getValue().equals("text/xml")) { // If we receive a text/xml response it means an error has occurred return XmlUtil.parse(response.getEntity().getContent()); }//from ww w .j a v a 2s. c o m throw new DeltaSyncException("Unexpected Content-Type received: " + contentType); } final Object[] result = new Object[1]; MimeStreamParser parser = new MimeStreamParser(); parser.setContentHandler(new SimpleContentHandler() { @Override public void headers(org.apache.james.mime4j.message.Header header) { } @Override public void bodyDecoded(BodyDescriptor bd, InputStream is) throws IOException { if ("application/xop+xml".equals(bd.getMimeType())) { try { result[0] = XmlUtil.parse(is); } catch (XmlException e) { result[0] = e; } } else if ("application/octet-stream".equals(bd.getMimeType())) { OutputStream out = output; if (!raw) { out = new HU01DecompressorOutputStream(output); } byte[] buffer = new byte[4096]; int n; while ((n = is.read(buffer)) != -1) { out.write(buffer, 0, n); } out.flush(); } } }); try { parser.parse(response.getEntity().getContent()); } catch (MimeException e) { throw new DeltaSyncException("Failed to parse multipart xop+xml response", e); } catch (IOException e) { if (e.getCause() != null && (e.getCause() instanceof HU01Exception)) { session.getLogger().error("HU01 decompression failed: ", e.getCause()); session.getLogger().error("Dumping HU01 stream as BASE64 for message {}", messageId); session.getLogger().error("Please submit the BASE64 encoded message content"); session.getLogger().error("and the plain text message content to the JDeltaSync"); session.getLogger().error("issue tracker. The plain text message content can"); session.getLogger().error("be retrieved by clicking \"View message source\" in"); session.getLogger().error("the Hotmail web UI."); ByteArrayOutputStream baos = new ByteArrayOutputStream(8192); Base64OutputStream base64Out = new Base64OutputStream(baos, true, 72, LINE_SEPARATOR); try { downloadRawMessageContent(session, messageId, base64Out); base64Out.close(); session.getLogger().error(new String(baos.toByteArray(), "ASCII")); } catch (Throwable t) { session.getLogger().error("Failed to dump HU01 stream", t); } throw (HU01Exception) e.getCause(); } throw e; } if (result[0] instanceof DeltaSyncException) { throw (DeltaSyncException) result[0]; } return (Document) result[0]; } }); if (session.getLogger().isDebugEnabled()) { session.getLogger().debug("Received ItemOperations response: {}", XmlUtil.toString(response, false)); } checkStatus(response); // No general error in the response. Check for a specific <Fetch> error. Element elStatus = XmlUtil.getElement(response, "/itemop:ItemOperations/itemop:Responses/itemop:Fetch/itemop:Status"); if (elStatus == null) { throw new DeltaSyncException( "No <Status> element found in <Fetch> response: " + XmlUtil.toString(response, true)); } int code = Integer.parseInt(elStatus.getTextContent().trim()); if (code == 4403) { throw new NoSuchMessageException(messageId); } else if (code != 1) { throw new UnrecognizedErrorCodeException(code, "Unrecognized error code in response for <Fetch> request. Response was: " + XmlUtil.toString(response, true)); } }
From source file:org.apache.camel.dataformat.base64.Base64DataFormat.java
private void marshalStreaming(Exchange exchange, Object graph, OutputStream stream) throws Exception { InputStream decoded = ExchangeHelper.convertToMandatoryType(exchange, InputStream.class, graph); Base64OutputStream base64Output = new Base64OutputStream(stream, true, lineLength, lineSeparator); try {//from ww w .j a v a 2 s .c om IOHelper.copy(decoded, base64Output); } finally { IOHelper.close(decoded, base64Output); } }
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/*from ww w. j a v a 2s. c om*/ * 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:org.springframework.cloud.aws.messaging.support.converter.ObjectMessageConverter.java
@Override public Object convertToInternal(Object payload, MessageHeaders headers) { if (!(payload instanceof Serializable)) { throw new IllegalArgumentException("Can't convert payload, it must be of type Serializable"); }/*ww w . j a va 2s. com*/ ByteArrayOutputStream content = new ByteArrayOutputStream(); Base64OutputStream base64OutputStream = new Base64OutputStream(content, true, 0, null); ObjectOutputStream objectOutputStream = null; try { objectOutputStream = new ObjectOutputStream(base64OutputStream); objectOutputStream.writeObject(payload); objectOutputStream.flush(); } catch (IOException e) { throw new MessageConversionException("Error converting payload into binary representation", e); } finally { if (objectOutputStream != null) { try { objectOutputStream.close(); } catch (IOException e) { LOGGER.warn("Error closing object output stream while writing message payload", e); } } } return new String(content.toByteArray(), 0, content.size(), this.encoding); }