Example usage for org.apache.commons.codec.binary Base64OutputStream Base64OutputStream

List of usage examples for org.apache.commons.codec.binary Base64OutputStream Base64OutputStream

Introduction

In this page you can find the example usage for org.apache.commons.codec.binary Base64OutputStream Base64OutputStream.

Prototype

public Base64OutputStream(OutputStream out, boolean doEncode) 

Source Link

Usage

From source file:com.github.tell.codec.Base64Serializer.java

public byte[] encode(final Serializable o) throws IOException {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final Base64OutputStream b64os = new Base64OutputStream(baos, true);
    final ObjectOutputStream oos = new ObjectOutputStream(b64os);
    oos.writeObject(o);//from www.ja  v a  2s.c  o m
    oos.close();
    return baos.toByteArray();
}

From source file:com.mirth.connect.donkey.util.Base64Util.java

/**
 * Decodes base64 data.//from w w w  . ja v  a2 s.c om
 * This method sets the initial output buffer to a value that is "guaranteed" to be slightly
 * larger than necessary.
 * Therefore the buffer should never need to be expanded, making the maximum memory requirements
 * much lower than
 * using Base64.decodeBase64.
 * 
 * @param bytes
 * @return
 * @throws IOException
 */
public static byte[] decodeBase64(byte[] bytes) throws IOException {
    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    // Set the size of the buffer to minimize peak memory usage
    // A binary message takes roughly .75 times the memory of the Base64 encoded message, so use 0.8 to be safe.
    ByteArrayOutputStream baos = new ByteArrayOutputStream((int) (bytes.length * 0.8));
    Base64OutputStream b64os = new Base64OutputStream(baos, false);

    // Perform the encoding
    IOUtils.copy(bais, b64os);

    // Free up any memory from the input
    b64os.close();

    return baos.toByteArray();
}

From source file:eu.peppol.document.AsicFilterInputStreamTest.java

/**
 * Takes a file holding an SBD/SBDH with an ASiC archive in base64 as payload and extracts the ASiC archive in binary format, while
 * calculating the message digest.//from   w w  w  . j a v a  2 s  . co m
 *
 * @throws Exception
 */
@Test
public void parseSampleSbdWithAsic() throws Exception {
    InputStream resourceAsStream = AsicFilterInputStreamTest.class.getClassLoader()
            .getResourceAsStream("sample-sbd-with-asic.xml");

    AsicFilterInputStream asicFilterInputStream = new AsicFilterInputStream(resourceAsStream);

    Path asicFile = Files.createTempFile("unit-test", ".asice");
    OutputStream asicOutputStream = Files.newOutputStream(asicFile);
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");

    DigestOutputStream digestOutputStream = new DigestOutputStream(asicOutputStream, messageDigest);
    Base64OutputStream base64OutputStream = new Base64OutputStream(digestOutputStream, false);

    IOUtils.copy(asicFilterInputStream, base64OutputStream);
    log.debug("Wrote ASiC to:" + asicFile);
    log.debug("Digest: " + new String(Base64.getEncoder().encode(messageDigest.digest())));

}

From source file:eu.peppol.document.PayloadParserTest.java

/**
 * Takes a file holding an SBD/SBDH with an ASiC archive in base64 as payload and extracts the ASiC archive in binary format, while
 * calculating the message digest.//from  w ww  .  j av  a2 s.c om
 *
 * @throws Exception
 */
@Test
public void parseSampleSbdWithAsic() throws Exception {

    InputStream resourceAsStream = PayloadParserTest.class.getClassLoader()
            .getResourceAsStream("sample-sbd-with-asic.xml");
    assertNotNull(resourceAsStream);

    Path xmlFile = Files.createTempFile("unit-test", ".xml");

    XMLEventReader xmlEventReader = XMLInputFactory.newInstance().createXMLEventReader(resourceAsStream,
            "UTF-8");
    FileOutputStream outputStream = new FileOutputStream(xmlFile.toFile());
    XMLEventWriter xmlEventWriter = XMLOutputFactory.newInstance().createXMLEventWriter(outputStream, "UTF-8");

    Path asicFile = Files.createTempFile("unit-test", ".asice");
    OutputStream asicOutputStream = Files.newOutputStream(asicFile);
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");

    DigestOutputStream digestOutputStream = new DigestOutputStream(asicOutputStream, messageDigest);
    Base64OutputStream base64OutputStream = new Base64OutputStream(digestOutputStream, false);

    boolean insideAsicElement = false;

    while (xmlEventReader.hasNext()) {
        XMLEvent xmlEvent = xmlEventReader.nextEvent();

        switch (xmlEvent.getEventType()) {
        case XMLEvent.START_ELEMENT:
            String localPart = xmlEvent.asStartElement().getName().getLocalPart();
            if ("asic".equals(localPart)) {
                insideAsicElement = true;
            }
            break;
        case XMLEvent.END_ELEMENT:
            localPart = xmlEvent.asEndElement().getName().getLocalPart();
            if ("asic".equals(localPart)) {
                insideAsicElement = false;
            }
            break;

        case XMLEvent.CHARACTERS:
            // Whenever we are inside the ASiC XML element, spit
            // out the base64 encoded data into the base64 decoding output stream.
            if (insideAsicElement) {
                Characters characters = xmlEvent.asCharacters();
                base64OutputStream.write(characters.getData().getBytes("UTF-8"));
            }
            break;
        }
        xmlEventWriter.add(xmlEvent);
    }

    asicOutputStream.close();
    outputStream.close();
    log.debug("Wrote xml output to: " + xmlFile);
    log.debug("Wrote ASiC to:" + asicFile);
    log.debug("Digest: " + new String(Base64.getEncoder().encode(messageDigest.digest())));
}

From source file:org.apache.vxquery.runtime.functions.cast.CastToBase64BinaryOperation.java

@Override
public void convertString(UTF8StringPointable stringp, DataOutput dOut) throws SystemException, IOException {
    baaos.reset();/*from   ww  w.j  a  v a 2s .  com*/
    Base64OutputStream b64os = new Base64OutputStream(baaos, false);
    b64os.write(stringp.getByteArray(), stringp.getStartOffset() + 2, stringp.getLength() - 2);

    dOut.write(ValueTag.XS_BASE64_BINARY_TAG);
    dOut.write((byte) ((baaos.size() >>> 8) & 0xFF));
    dOut.write((byte) ((baaos.size() >>> 0) & 0xFF));
    dOut.write(baaos.getByteArray(), 0, baaos.size());
}

From source file:org.apache.vxquery.runtime.functions.cast.CastToStringOperation.java

@Override
public void convertBase64Binary(XSBinaryPointable binaryp, DataOutput dOut)
        throws SystemException, IOException {
    baaos.reset();//  w w  w.ja  v a 2 s.  c  o  m
    @SuppressWarnings("resource")
    Base64OutputStream b64os = new Base64OutputStream(baaos, true);
    b64os.write(binaryp.getByteArray(), binaryp.getStartOffset() + 2, binaryp.getLength() - 2);

    dOut.write(returnTag);
    dOut.write((byte) ((baaos.size() >>> 8) & 0xFF));
    dOut.write((byte) ((baaos.size() >>> 0) & 0xFF));
    dOut.write(baaos.getByteArray(), 0, baaos.size());
}

From source file:org.apache.xml.security.stax.impl.transformer.TransformBase64Decode.java

@Override
public void setOutputStream(OutputStream outputStream) throws XMLSecurityException {
    super.setOutputStream(new Base64OutputStream(new FilterOutputStream(outputStream) {
        @Override//from  w  ww  . j av  a2 s  .  co m
        public void close() throws IOException {
            //do not close the parent output stream!
            super.flush();
        }
    }, false));
}

From source file:org.apache.xml.security.stax.impl.transformer.TransformBase64Decode.java

@Override
public void transform(XMLSecEvent xmlSecEvent) throws XMLStreamException {
    int eventType = xmlSecEvent.getEventType();
    switch (eventType) {
    case XMLStreamConstants.CHARACTERS:
        if (getOutputStream() != null) {
            //we have an output stream
            //encoding shouldn't matter here, because the data is Base64 encoded and is therefore in the ASCII range.
            try {
                getOutputStream().write(xmlSecEvent.asCharacters().getData().getBytes());
            } catch (IOException e) {
                throw new XMLStreamException(e);
            }//from   w  w w  . ja  v  a 2 s.c  om
        } else {
            //we have a child transformer
            if (childOutputMethod == null) {

                final XMLSecurityConstants.TransformMethod preferredChildTransformMethod = getTransformer()
                        .getPreferredTransformMethod(XMLSecurityConstants.TransformMethod.XMLSecEvent);

                switch (preferredChildTransformMethod) {
                case XMLSecEvent: {
                    childOutputMethod = new ChildOutputMethod() {

                        private UnsynchronizedByteArrayOutputStream byteArrayOutputStream;
                        private Base64OutputStream base64OutputStream;

                        @Override
                        public void transform(Object object) throws XMLStreamException {
                            if (base64OutputStream == null) {
                                byteArrayOutputStream = new UnsynchronizedByteArrayOutputStream();
                                base64OutputStream = new Base64OutputStream(byteArrayOutputStream, false);
                            }
                            try {
                                base64OutputStream.write(((byte[]) object));
                            } catch (IOException e) {
                                throw new XMLStreamException(e);
                            }
                        }

                        @Override
                        public void doFinal() throws XMLStreamException {
                            try {
                                base64OutputStream.close();
                            } catch (IOException e) {
                                throw new XMLStreamException(e);
                            }
                            XMLEventReaderInputProcessor xmlEventReaderInputProcessor = new XMLEventReaderInputProcessor(
                                    null,
                                    getXmlInputFactory()
                                            .createXMLStreamReader(new UnsynchronizedByteArrayInputStream(
                                                    byteArrayOutputStream.toByteArray())));

                            try {
                                XMLSecEvent xmlSecEvent;
                                do {
                                    xmlSecEvent = xmlEventReaderInputProcessor.processNextEvent(null);
                                    getTransformer().transform(xmlSecEvent);
                                } while (xmlSecEvent.getEventType() != XMLStreamConstants.END_DOCUMENT);
                            } catch (XMLSecurityException e) {
                                throw new XMLStreamException(e);
                            }
                            getTransformer().doFinal();
                        }
                    };
                    break;
                }
                case InputStream: {
                    childOutputMethod = new ChildOutputMethod() {

                        private UnsynchronizedByteArrayOutputStream byteArrayOutputStream;
                        private Base64OutputStream base64OutputStream;

                        @Override
                        public void transform(Object object) throws XMLStreamException {
                            if (base64OutputStream == null) {
                                byteArrayOutputStream = new UnsynchronizedByteArrayOutputStream();
                                base64OutputStream = new Base64OutputStream(byteArrayOutputStream, false);
                            }
                            try {
                                base64OutputStream.write(((byte[]) object));
                            } catch (IOException e) {
                                throw new XMLStreamException(e);
                            }
                        }

                        @Override
                        public void doFinal() throws XMLStreamException {
                            try {
                                base64OutputStream.close();
                            } catch (IOException e) {
                                throw new XMLStreamException(e);
                            }
                            getTransformer().transform(new UnsynchronizedByteArrayInputStream(
                                    byteArrayOutputStream.toByteArray()));
                            getTransformer().doFinal();
                        }
                    };
                    break;
                }
                }
            }
            childOutputMethod.transform(xmlSecEvent.asCharacters().getData().getBytes());
        }
        break;
    }
}

From source file:org.bimserver.collada.OpenGLTransmissionFormatSerializer.java

public void encodeFileToBase64Stream(Path file, OutputStream base64OutputStream) throws IOException {
    InputStream inputStream = Files.newInputStream(file);
    OutputStream out = new Base64OutputStream(base64OutputStream, true);
    IOUtils.copy(inputStream, out);/*from   w ww.j a  va  2s. com*/
    inputStream.close();
    out.close();
}

From source file:org.expath.servlex.processors.saxon.SaxonSerializer.java

private void serialize(XdmValue sequence, OutputStream out) throws TechnicalException {
    String method = methodFromMime(myMediaType);
    // TODO: @method could also contain "base64" or "hex".  Take it into account!
    // TODO: Can I use Saxon extension methods here?  Like "saxon:base64Binary"
    // or "saxon:hexBinary"...
    // See http://saxonica.com/documentation/#!extensions/output-extras.
    // TODO: What if myMethod is set?  We don't take it into account here...?
    if ("binary".equals(method)) {
        method = "text";
        out = new Base64OutputStream(out, false);
    }// w  ww  . j  a  v a 2s.c  o m
    net.sf.saxon.s9api.Serializer serial = new net.sf.saxon.s9api.Serializer();
    serial.setOutputStream(out);
    if (myMethod == null && myMediaType != null) {
        myMethod = method;
    }

    setOutputProperty(serial, Property.METHOD, myMethod);
    setOutputProperty(serial, Property.MEDIA_TYPE, myMediaType);
    setOutputProperty(serial, Property.ENCODING, myEncoding);
    setOutputProperty(serial, Property.BYTE_ORDER_MARK, myByteOrderMark);
    setOutputProperty(serial, Property.CDATA_SECTION_ELEMENTS, myCdataSectionElements);
    setOutputProperty(serial, Property.DOCTYPE_PUBLIC, myDoctypePublic);
    setOutputProperty(serial, Property.DOCTYPE_SYSTEM, myDoctypeSystem);
    setOutputProperty(serial, Property.ESCAPE_URI_ATTRIBUTES, myEscapeUriAttributes);
    setOutputProperty(serial, Property.INCLUDE_CONTENT_TYPE, myIncludeContentType);
    setOutputProperty(serial, Property.INDENT, myIndent);
    setOutputProperty(serial, Property.NORMALIZATION_FORM, myNormalizationForm);
    setOutputProperty(serial, Property.OMIT_XML_DECLARATION, myOmitXmlDeclaration);
    setOutputProperty(serial, Property.STANDALONE, myStandalone);
    setOutputProperty(serial, Property.UNDECLARE_PREFIXES, myUndeclarePrefixes);
    setOutputProperty(serial, Property.USE_CHARACTER_MAPS, myUseCharacterMaps);
    setOutputProperty(serial, Property.VERSION, myVersion);

    setOutputProperty(serial, Property.SAXON_CHARACTER_REPRESENTATION, mySaxonCharacterRepresentation);
    setOutputProperty(serial, Property.SAXON_DOUBLE_SPACE, mySaxonDoubleSpace);
    setOutputProperty(serial, Property.SAXON_INDENT_SPACES, mySaxonIndentSpaces);
    setOutputProperty(serial, Property.SAXON_LINE_LENGTH, mySaxonLineLength);
    setOutputProperty(serial, Property.SAXON_RECOGNIZE_BINARY, mySaxonRecognizeBinary);
    setOutputProperty(serial, Property.SAXON_REQUIRE_WELL_FORMED, mySaxonRequireWellFormed);
    setOutputProperty(serial, Property.SAXON_STYLESHEET_VERSION, mySaxonStylesheetVersion);
    setOutputProperty(serial, Property.SAXON_SUPPRESS_INDENTATION, mySaxonSuppressIndentation);
    setOutputProperty(serial, Property.SAXON_WRAP, mySaxonWrap);

    try {
        mySaxon.writeXdmValue(sequence, serial);
    } catch (SaxonApiException ex) {
        throw new TechnicalException("Error serializing sequence to the output stream", ex);
    }
}