Search in sources :

Example 46 with NonBlockingByteArrayOutputStream

use of com.helger.commons.io.stream.NonBlockingByteArrayOutputStream in project ph-commons by phax.

the class XMLMapHandlerTest method testWriteInvalid.

@Test
public void testWriteInvalid() {
    final ICommonsMap<String, String> aMap = new CommonsHashMap<>();
    try {
        XMLMapHandler.writeMap(aMap, (IHasOutputStream) null);
        fail();
    } catch (final NullPointerException ex) {
    }
    try {
        XMLMapHandler.writeMap(null, new ByteArrayOutputStreamProvider());
        fail();
    } catch (final NullPointerException ex) {
    }
    try {
        XMLMapHandler.writeMap(aMap, (OutputStream) null);
        fail();
    } catch (final NullPointerException ex) {
    }
    try {
        XMLMapHandler.writeMap(null, new NonBlockingByteArrayOutputStream());
        fail();
    } catch (final NullPointerException ex) {
    }
}
Also used : ByteArrayOutputStreamProvider(com.helger.commons.io.streamprovider.ByteArrayOutputStreamProvider) CommonsHashMap(com.helger.commons.collection.impl.CommonsHashMap) NonBlockingByteArrayOutputStream(com.helger.commons.io.stream.NonBlockingByteArrayOutputStream) Test(org.junit.Test)

Example 47 with NonBlockingByteArrayOutputStream

use of com.helger.commons.io.stream.NonBlockingByteArrayOutputStream in project ph-commons by phax.

the class MicroReaderTest method testNamespaces2.

/**
 * Test: Use 2 different namespaces and use them both more than once
 */
@Test
public void testNamespaces2() {
    final XMLWriterSettings xs = new XMLWriterSettings();
    xs.setIndent(EXMLSerializeIndent.NONE);
    final String s = "<?xml version=\"1.0\"?>" + "<verrryoot xmlns='uri1'>" + "<root>" + "<child xmlns='uri2'>" + "<child2>Value text - no entities!</child2>" + "</child>" + "</root>" + "</verrryoot>";
    final IMicroDocument aDoc = MicroReader.readMicroXML(s);
    assertNotNull(aDoc);
    final NonBlockingByteArrayOutputStream baos = new NonBlockingByteArrayOutputStream();
    new MicroSerializer(xs).write(aDoc, baos);
    final String sXML = baos.getAsString(StandardCharsets.UTF_8);
    assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<verrryoot xmlns=\"uri1\">" + "<root>" + "<ns0:child xmlns:ns0=\"uri2\">" + "<ns0:child2>Value text - no entities!</ns0:child2>" + "</ns0:child>" + "</root>" + "</verrryoot>", sXML);
}
Also used : XMLWriterSettings(com.helger.xml.serialize.write.XMLWriterSettings) NonBlockingByteArrayOutputStream(com.helger.commons.io.stream.NonBlockingByteArrayOutputStream) IMicroDocument(com.helger.xml.microdom.IMicroDocument) Test(org.junit.Test)

Example 48 with NonBlockingByteArrayOutputStream

use of com.helger.commons.io.stream.NonBlockingByteArrayOutputStream in project ph-commons by phax.

the class GraphVizHelper method getGraphAsImageWithGraphVizNeato.

/**
 * Invoked the external process "neato" from the GraphViz package. Attention:
 * this spans a sub-process!
 *
 * @param sFileType
 *        The file type to be generated. E.g. "png" - see neato help for
 *        details. May neither be <code>null</code> nor empty.
 * @param sDOT
 *        The DOT file to be converted to an image. May neither be
 *        <code>null</code> nor empty.
 * @return The byte buffer that keeps the converted image. Never
 *         <code>null</code>.
 * @throws IOException
 *         In case some IO error occurs
 * @throws InterruptedException
 *         If the sub-process did not terminate correctly!
 */
@Nonnull
public static NonBlockingByteArrayOutputStream getGraphAsImageWithGraphVizNeato(@Nonnull @Nonempty final String sFileType, @Nonnull final String sDOT) throws IOException, InterruptedException {
    ValueEnforcer.notEmpty(sFileType, "FileType");
    ValueEnforcer.notEmpty(sDOT, "DOT");
    final ProcessBuilder aPB = new ProcessBuilder("neato", "-T" + sFileType).redirectErrorStream(false);
    final Process p = aPB.start();
    // Set neato stdin
    p.getOutputStream().write(sDOT.getBytes(StandardCharsets.UTF_8));
    p.getOutputStream().close();
    // Read neato stdout
    final NonBlockingByteArrayOutputStream aBAOS = new NonBlockingByteArrayOutputStream();
    StreamHelper.copyInputStreamToOutputStream(p.getInputStream(), aBAOS);
    p.waitFor();
    return aBAOS;
}
Also used : NonBlockingByteArrayOutputStream(com.helger.commons.io.stream.NonBlockingByteArrayOutputStream) Nonnull(javax.annotation.Nonnull)

Example 49 with NonBlockingByteArrayOutputStream

use of com.helger.commons.io.stream.NonBlockingByteArrayOutputStream in project ph-commons by phax.

the class XMLWriter method getNodeAsBytes.

/**
 * Convert the passed DOM node to an XML byte array using the provided XML
 * writer settings.
 *
 * @param aNode
 *        The node to be converted to a byte array. May not be
 *        <code>null</code>.
 * @param aSettings
 *        The XML writer settings to be used. May not be <code>null</code>.
 * @return The byte array representation of the passed node.
 * @since 8.6.3
 */
@Nullable
public static byte[] getNodeAsBytes(@Nonnull final Node aNode, @Nonnull final IXMLWriterSettings aSettings) {
    ValueEnforcer.notNull(aNode, "Node");
    ValueEnforcer.notNull(aSettings, "Settings");
    try (final NonBlockingByteArrayOutputStream aBAOS = new NonBlockingByteArrayOutputStream(50 * CGlobal.BYTES_PER_KILOBYTE)) {
        // start serializing
        if (writeToStream(aNode, aBAOS, aSettings).isSuccess())
            return aBAOS.toByteArray();
    } catch (final Exception ex) {
        if (LOGGER.isErrorEnabled())
            LOGGER.error("Error serializing DOM node with settings " + aSettings.toString(), ex);
    }
    return null;
}
Also used : NonBlockingByteArrayOutputStream(com.helger.commons.io.stream.NonBlockingByteArrayOutputStream) Nullable(javax.annotation.Nullable)

Example 50 with NonBlockingByteArrayOutputStream

use of com.helger.commons.io.stream.NonBlockingByteArrayOutputStream in project ph-commons by phax.

the class Base64 method encodeBytesToBytes.

/**
 * Similar to {@link #encodeBytes(byte[], int, int, int)} but returns a byte
 * array instead of instantiating a String. This is more efficient if you're
 * working with I/O streams and have large data sets to encode.
 *
 * @param aSource
 *        The data to convert
 * @param nOfs
 *        Offset in array where conversion should begin
 * @param nLen
 *        Length of data to convert
 * @param nOptions
 *        Specified options
 * @return The Base64-encoded data as a String
 * @see Base64#GZIP
 * @see Base64#DO_BREAK_LINES
 * @throws IOException
 *         if there is an error
 * @throws NullPointerException
 *         if source array is null
 * @throws IllegalArgumentException
 *         if source array, offset, or length are invalid
 * @since 2.3.1
 */
@Nonnull
@ReturnsMutableCopy
public static byte[] encodeBytesToBytes(@Nonnull final byte[] aSource, @Nonnegative final int nOfs, @Nonnegative final int nLen, final int nOptions) throws IOException {
    ValueEnforcer.isArrayOfsLen(aSource, nOfs, nLen);
    // Compress?
    if ((nOptions & GZIP) != 0) {
        // GZip -> Base64 -> ByteArray
        try (final NonBlockingByteArrayOutputStream baos = new NonBlockingByteArrayOutputStream()) {
            try (final Base64OutputStream b64os = new Base64OutputStream(baos, ENCODE | nOptions);
                final GZIPOutputStream gzos = new GZIPOutputStream(b64os)) {
                gzos.write(aSource, nOfs, nLen);
            }
            return baos.toByteArray();
        }
    }
    // Else, don't compress. Better not to use streams at all then.
    {
        final boolean bBreakLines = (nOptions & DO_BREAK_LINES) != 0;
        final boolean bUseCRLF = (nOptions & DO_NEWLINE_CRLF) != 0;
        // int len43 = len * 4 / 3;
        // byte[] outBuff = new byte[ ( len43 )
        // Main 4:3
        // + ( (len % 3) > 0 ? 4 : 0 )
        // Account for padding
        // + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ];
        // New lines
        // Try to determine more precisely how big the array needs to be.
        // If we get it right, we don't have to do an array copy, and
        // we save a bunch of memory.
        // Bytes needed for actual encoding
        int nEncLen = (nLen / 3) * 4 + (nLen % 3 > 0 ? 4 : 0);
        if (bBreakLines) {
            // Plus extra newline characters
            final int nLinesAdded = nEncLen / MAX_LINE_LENGTH;
            if (bUseCRLF)
                nEncLen += nLinesAdded * NEW_LINE_CRLF.length;
            else
                nEncLen += nLinesAdded;
        }
        final byte[] outBuff = new byte[nEncLen];
        int d = 0;
        int e = 0;
        final int len2 = nLen - 2;
        int lineLength = 0;
        for (; d < len2; d += 3, e += 4) {
            _encode3to4(aSource, d + nOfs, 3, outBuff, e, nOptions);
            lineLength += 4;
            if (bBreakLines && lineLength >= MAX_LINE_LENGTH) {
                if (bUseCRLF) {
                    for (final byte b : NEW_LINE_CRLF) {
                        outBuff[e + 4] = b;
                        e++;
                    }
                } else {
                    outBuff[e + 4] = NEW_LINE;
                    e++;
                }
                lineLength = 0;
            }
        }
        if (d < nLen) {
            _encode3to4(aSource, d + nOfs, nLen - d, outBuff, e, nOptions);
            e += 4;
        }
        // Only resize array if we didn't guess it right.
        if (e <= outBuff.length - 1) {
            // If breaking lines and the last byte falls right at
            // the line length (76 bytes per line), there will be
            // one extra byte, and the array will need to be resized.
            // Not too bad of an estimate on array size, I'd say.
            final byte[] finalOut = new byte[e];
            System.arraycopy(outBuff, 0, finalOut, 0, e);
            // " to " + e );
            return finalOut;
        }
        // System.err.println("No need to resize array.");
        return outBuff;
    }
}
Also used : GZIPOutputStream(java.util.zip.GZIPOutputStream) NonBlockingByteArrayOutputStream(com.helger.commons.io.stream.NonBlockingByteArrayOutputStream) ReturnsMutableCopy(com.helger.commons.annotation.ReturnsMutableCopy) Nonnull(javax.annotation.Nonnull)

Aggregations

NonBlockingByteArrayOutputStream (com.helger.commons.io.stream.NonBlockingByteArrayOutputStream)55 Test (org.junit.Test)30 IOException (java.io.IOException)12 MimeBodyPart (javax.mail.internet.MimeBodyPart)12 NonBlockingByteArrayInputStream (com.helger.commons.io.stream.NonBlockingByteArrayInputStream)8 InputStream (java.io.InputStream)7 Nonnull (javax.annotation.Nonnull)7 MessagingException (javax.mail.MessagingException)7 IMicroDocument (com.helger.xml.microdom.IMicroDocument)4 AS2Exception (com.helger.as2lib.exception.AS2Exception)3 IMessageMDN (com.helger.as2lib.message.IMessageMDN)3 CommonsArrayList (com.helger.commons.collection.impl.CommonsArrayList)3 ByteArrayOutputStreamProvider (com.helger.commons.io.streamprovider.ByteArrayOutputStreamProvider)3 MockMarshallerExternal (com.helger.jaxb.mock.MockMarshallerExternal)3 MockJAXBArchive (com.helger.jaxb.mock.external.MockJAXBArchive)3 XMLWriterSettings (com.helger.xml.serialize.write.XMLWriterSettings)3 Nullable (javax.annotation.Nullable)3 SMIMEException (org.bouncycastle.mail.smime.SMIMEException)3 AS2DispositionException (com.helger.as2lib.disposition.AS2DispositionException)2 WrappedAS2Exception (com.helger.as2lib.exception.WrappedAS2Exception)2