Example usage for org.apache.commons.io HexDump dump

List of usage examples for org.apache.commons.io HexDump dump

Introduction

In this page you can find the example usage for org.apache.commons.io HexDump dump.

Prototype


public static void dump(byte[] data, long offset, OutputStream stream, int index)
        throws IOException, ArrayIndexOutOfBoundsException, IllegalArgumentException 

Source Link

Document

Dump an array of bytes to an OutputStream.

Usage

From source file:de.griffel.confluence.plugins.plantuml.PlantUmlMacro.java

private String render(final String umlBlock, final PageContext pageContext,
        final PlantUmlMacroParams macroParams, final PlantUmlPreprocessor preprocessor)
        throws IOException, UnauthorizedDownloadResourceException, DownloadResourceNotFoundException {

    final FileFormat fileFormat = macroParams.getFileFormat(pageContext);

    final List<String> config = new PlantUmlConfigBuilder().build(macroParams);
    final MySourceStringReader reader = new MySourceStringReader(new Defines(), umlBlock, config);

    final StringBuilder sb = new StringBuilder();

    if (preprocessor.hasExceptions()) {
        sb.append("<span class=\"error\">");
        for (PreprocessingException exception : preprocessor.getExceptions()) {
            sb.append("<span class=\"error\">");
            sb.append("plantuml: ");
            sb.append(exception.getDetails());
            sb.append("</span><br/>");
        }//w w w  .  ja  v a2 s . co  m
        sb.append("</span>");
    }

    while (reader.hasNext()) {
        final DownloadResourceWriter resourceWriter = writeableDownloadResourceManager.getResourceWriter(
                AuthenticatedUserThreadLocal.getUsername(), "plantuml", fileFormat.getFileSuffix());

        final ImageInfo imageInfo = reader.renderImage(resourceWriter.getStreamForWriting(), fileFormat);
        final ImageMap cmap = imageInfo.getImageMap();

        if (cmap.isValid()) {
            sb.append(cmap.toHtmlString());
        }

        if (umlBlock.matches(PlantUmlPluginInfo.PLANTUML_VERSION_INFO_REGEX)) {
            sb.append(new PlantUmlPluginInfo(pluginAccessor, i18NBeanFactory.getI18NBean()).toHtmlString());
        }

        final DownloadResourceInfo resourceInfo;
        if (macroParams.getExportName() != null && !preprocessor.hasExceptions()) {
            resourceInfo = attachImage(pageContext.getEntity(), macroParams, imageInfo, fileFormat,
                    resourceWriter);
        } else {
            resourceInfo = new DefaultDownloadResourceInfo(writeableDownloadResourceManager, resourceWriter);
        }

        if (FileFormat.SVG == fileFormat) {
            final StringWriter sw = new StringWriter();
            IOUtils.copy(resourceInfo.getStreamForReading(), sw);
            sb.append(sw.getBuffer());
        } else /* PNG */ {
            sb.append("<span class=\"image-wrap\" style=\"").append(macroParams.getAlignment().getCssStyle())
                    .append("\">");
            sb.append("<img");
            if (cmap.isValid()) {
                sb.append(" usemap=\"#");
                sb.append(cmap.getId());
                sb.append("\"");
            }
            sb.append(" src='");
            sb.append(resourceInfo.getDownloadPath());
            sb.append("'");
            sb.append(macroParams.getImageStyle());
            sb.append("/>");
            sb.append("</span>");
        }

    }

    if (macroParams.isDebug()) {
        sb.append("<div class=\"puml-debug\">");
        sb.append("<pre>");
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        HexDump.dump(umlBlock.getBytes("UTF-8"), 0, baos, 0);
        sb.append(baos.toString()); // HexDump class writer bytes with JVM default encoding
        sb.append("</pre>");
        sb.append("</div>");
    }

    return sb.toString();
}

From source file:com.jkoolcloud.tnt4j.streams.utils.Utils.java

/**
 * Makes a HEX dump string representation of provided bytes array.
 *
 * @param b/*  w  ww  .j  a v  a 2s.c  o  m*/
 *            bytes array make HEX dump
 * @param offset
 *            offset at which to start dumping bytes
 * @param len
 *            maximum number of bytes to dump
 * @return returns HEX dump representation of provided bytes array
 */
public static String toHexDump(byte[] b, int offset, int len) {
    if (b == null) {
        return "<EMPTY>"; // NON-NLS
    }

    String hexStr;
    ByteArrayOutputStream bos = new ByteArrayOutputStream(b.length * 2);
    try {
        if (len > 0 && len < b.length) {
            byte[] bc = Arrays.copyOfRange(b, offset, offset + len);
            HexDump.dump(bc, 0, bos, offset);
        } else {
            HexDump.dump(b, 0, bos, offset);
        }
        hexStr = NEW_LINE + bos.toString(UTF8);
        bos.close();
    } catch (Exception exc) {
        hexStr = "HEX FAIL: " + exc.getLocalizedMessage(); // NON-NLS
    }

    return hexStr;
}

From source file:org.apache.bookkeeper.util.HexDumpEntryFormatter.java

@Override
public void formatEntry(byte[] data) {
    try {//from   ww w  . j  a v  a2  s.  c  o  m
        HexDump.dump(data, 0, System.out, 0);
    } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("Warn: Index is outside the data array's bounds : " + e.getMessage());
    } catch (IllegalArgumentException e) {
        System.out.println("Warn: The output stream is null : " + e.getMessage());
    } catch (IOException e) {
        System.out.println("Warn: Something has gone wrong writing the data to stream : " + e.getMessage());
    }
}

From source file:org.apache.flume.event.EventHelper.java

public static String dumpEvent(Event event, int maxBytes) {
    StringBuilder buffer = new StringBuilder();
    if (event == null || event.getBody() == null) {
        buffer.append("null");
    } else if (event.getBody().length == 0) {
        // do nothing... in this case, HexDump.dump() will throw an exception
    } else {/*from  w ww  . j  a  v a 2 s.  co  m*/
        byte[] body = event.getBody();
        byte[] data = Arrays.copyOf(body, Math.min(body.length, maxBytes));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            HexDump.dump(data, 0, out, 0);
            String hexDump = new String(out.toByteArray());
            // remove offset since it's not relevant for such a small dataset
            if (hexDump.startsWith(HEXDUMP_OFFSET)) {
                hexDump = hexDump.substring(HEXDUMP_OFFSET.length());
            }
            buffer.append(hexDump);
        } catch (Exception e) {
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("Exception while dumping event", e);
            }
            buffer.append("...Exception while dumping: ").append(e.getMessage());
        }
        String result = buffer.toString();
        if (result.endsWith(EOL) && buffer.length() > EOL.length()) {
            buffer.delete(buffer.length() - EOL.length(), buffer.length()).toString();
        }
    }
    return "{ headers:" + event.getHeaders() + " body:" + buffer + " }";
}

From source file:org.apache.fop.afp.apps.FontPatternExtractor.java

/**
 * Extracts the Type1 PFB file from the given AFP outline font.
 * @param file the AFP file to read from
 * @param targetDir the target directory where the PFB file is to be placed.
 * @throws IOException if an I/O error occurs
 *///from  w  w  w.  jav a2 s  . c o  m
public void extract(File file, File targetDir) throws IOException {
    InputStream in = new java.io.FileInputStream(file);
    try {
        MODCAParser parser = new MODCAParser(in);
        ByteArrayOutputStream baout = new ByteArrayOutputStream();
        UnparsedStructuredField strucField;
        while ((strucField = parser.readNextStructuredField()) != null) {
            if (strucField.getSfTypeID() == 0xD3EE89) {
                byte[] sfData = strucField.getData();
                println(strucField.toString());
                HexDump.dump(sfData, 0, printStream, 0);
                baout.write(sfData);
            }
        }

        ByteArrayInputStream bin = new ByteArrayInputStream(baout.toByteArray());
        DataInputStream din = new DataInputStream(bin);
        long len = din.readInt() & 0xFFFFFFFFL;
        println("Length: " + len);
        din.skip(4); //checksum
        int tidLen = din.readUnsignedShort() - 2;
        byte[] tid = new byte[tidLen];
        din.readFully(tid);
        String filename = new String(tid, "ISO-8859-1");
        int asciiCount1 = countUSAsciiCharacters(filename);
        String filenameEBCDIC = new String(tid, "Cp1146");
        int asciiCount2 = countUSAsciiCharacters(filenameEBCDIC);
        println("TID: " + filename + " " + filenameEBCDIC);

        if (asciiCount2 > asciiCount1) {
            //Haven't found an indicator if the name is encoded in EBCDIC or not
            //so we use a trick.
            filename = filenameEBCDIC;
        }
        if (!filename.toLowerCase().endsWith(".pfb")) {
            filename = filename + ".pfb";
        }
        println("Output filename: " + filename);
        File out = new File(targetDir, filename);

        OutputStream fout = new java.io.FileOutputStream(out);
        try {
            IOUtils.copyLarge(din, fout);
        } finally {
            IOUtils.closeQuietly(fout);
        }

    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:org.apache.jackrabbit.oak.plugins.segment.Segment.java

private static String toHex(byte[] bytes) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {//from ww  w.ja  v  a 2  s . c  o  m
        HexDump.dump(bytes, 0, out, 0);
        return out.toString(Charsets.UTF_8.name());
    } catch (IOException e) {
        return "Error dumping segment: " + e.getMessage();
    } finally {
        closeQuietly(out);
    }
}

From source file:org.javaweb.utils.HexUtils.java

/**
 * Hexdump ??ASCII?//from  w  w w  . j a v  a 2s .c o m
 *
 * @param data
 * @return
 */
public static byte[] hexDump(byte[] data) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {
        HexDump.dump(data, data.length, baos, 0);
    } catch (ArrayIndexOutOfBoundsException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return baos.toByteArray();
}

From source file:org.jnotary.client.DvcsCheck.java

private static void verifyAndDump(byte[] hash, DVCSResponse response) throws Exception {
    if (Arrays.equals(hash, response.getDvCertInfo().getMessageImprint().getDigest())) {
        System.out.println("Message imprint is successfully verified");
    } else {//w  w w .j  av  a2s  . c om
        System.out.println("Message imprint verification is FAILED");

        System.out.println("Message imprint of source file:");
        HexDump.dump(hash, 0, System.out, 0);
        System.out.println("\nMessage imprint from dvcs-response file:");
        HexDump.dump(response.getDvCertInfo().getMessageImprint().getDigest(), 0, System.out, 0);
    }

    System.out.println("DVCS-response information");
    if (response.getDvCertInfo() != null) {
        System.out.println("Service type:"
                + ServiceType.toString(response.getDvCertInfo().getRequestInformation().getService()));
        System.out.println("Nonce: "
                + response.getDvCertInfo().getRequestInformation().getNonce().getPositiveValue().toString(16));
        System.out.println(
                "Response time: " + response.getDvCertInfo().getResponseTime().getGenTime().getTimeString());
    }

    PKIStatusInfo statusInfo = null;
    if (response.getDvErrorNote() != null)
        statusInfo = response.getDvErrorNote().getTransactionStatus();
    else if (response.getDvCertInfo() != null && response.getDvCertInfo().getDvStatus() != null)
        statusInfo = response.getDvCertInfo().getDvStatus();
    if (statusInfo == null)
        throw new Exception("Status info is not present");

    java.lang.StringBuilder sb = new StringBuilder("PKIStatus: ");
    sb.append(statusInfo.getStatus());
    if (statusInfo.getStatusString() != null) {
        sb.append("; FreeText: ");
        sb.append(statusInfo.getStatusString().getStringAt(0).getString());
    }
    if (statusInfo.getFailInfo() != null) {
        sb.append("; PKIFailerInfo: ");
        sb.append(statusInfo.getFailInfo().intValue());
    }
    System.out.println(sb.toString());
}

From source file:org.jopenray.client.RendererListener.java

private void handlePacket() throws IOException {
    byteCount += dataLength;/*w w  w .j a  v  a  2 s  .c  o  m*/
    packetCount++;

    PrintStream out = System.out;
    boolean dump = false;
    ByteArrayInputStream bIn = new ByteArrayInputStream(udpData, 0, this.dataLength);
    int r = readInt16(bIn);
    if (r == 1) {
        out.println("===================================================================================");
    }
    out.print("Seq number:" + r);
    int flag = readInt16(bIn);
    out.print(" Flag:" + flag);
    int type = readInt16(bIn);
    out.print(" Type:" + type);
    int dir = readInt16(bIn);
    out.println(" Dir:" + dir + " dataSize:" + udpData.length);
    if (dir != 2000) {

        // Server -> Sunray
        int a = readInt16(bIn);
        int b = readInt16(bIn);
        int c = readInt16(bIn);
        int d = readInt16(bIn);
        out.println("Server -> Sunray:" + a + "," + b + "," + c + "," + d);
        boolean endOfFrame = false;
        while (bIn.available() > 0 && !endOfFrame) {
            String opCodeHeader = "";
            int opcode = bIn.read();
            opCodeHeader += "[ Opcode: " + opcode;
            int f = bIn.read();
            opCodeHeader += " Flag" + f;
            int oseq = readInt16(bIn);
            opCodeHeader += " OpcodeSeq:" + oseq;
            int x = readInt16(bIn);
            int y = readInt16(bIn);

            int w = readInt16(bIn);
            int h = readInt16(bIn);

            opCodeHeader += " x,y: " + x + "," + y + " w:" + w + " h:" + h + " ]";

            switch (opcode) {
            case 0x0: {
                endOfFrame = true;
                break;
            }
            case 0x03:
                out.println("0x03 Strange opcode " + opCodeHeader);
                break;
            case 0xA1:
                int ap1 = bIn.read();
                int ap2 = bIn.read();
                int ap3 = bIn.read();
                int ap4 = bIn.read();
                out.println("0xA1:" + ap1 + "," + ap2 + "," + ap3 + "," + ap4 + opCodeHeader);
                break;
            case 0xA2:
                // out.println("FillRect");
                int a2p1 = bIn.read();
                int a2p2 = bIn.read();
                int a2p3 = bIn.read();
                int a2p4 = bIn.read();
                out.println("FillRect: Color:" + a2p1 + "," + a2p2 + "," + a2p3 + "," + a2p4 + opCodeHeader);
                break;
            case 0xA3: {

                int a3p1 = bIn.read();
                int a3p2 = bIn.read();
                int a3p3 = bIn.read();
                int a3p4 = bIn.read();
                int nbBytesPerRow = round(w, 8) / 8;
                int nbBytes = round(nbBytesPerRow * h, 4);
                byte[] unkuonw = new byte[nbBytes];
                try {
                    int lRead = bIn.read(unkuonw);
                    out.println("FillRectBitmap: Color:" + a3p1 + "," + a3p2 + "," + a3p3 + "," + a3p4
                            + " | bytes/row:" + nbBytesPerRow + "l:" + nbBytes + " lRead:" + lRead
                            + opCodeHeader);

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                break;
            }
            case 0xA4:
                int xsrc = readInt16(bIn);
                int ysrc = readInt16(bIn);
                out.println("CopyRect from : " + xsrc + "," + ysrc + opCodeHeader);

                break;
            case 0xA5: {
                // out.println("SetRectBitmap");
                // err.println("SetRectBitmap not yet implemented");
                try {
                    Color c1 = readColor(bIn);
                    Color c2 = readColor(bIn);
                    int nbBytesPerRow = round(w, 8) / 8;
                    int nbBytes = round(nbBytesPerRow * h, 4);
                    byte[] unkuonw = new byte[nbBytes];

                    int lRead = bIn.read(unkuonw);

                    out.println("SetRectBitmap: " + w + "x" + h + " at " + x + "," + y + " Color:" + c1 + " / "
                            + c2 + " | bytes/row:" + nbBytesPerRow + " l:" + nbBytes + " lRead:" + lRead
                            + opCodeHeader);
                    if (nbBytes > 1024) {
                        out.println("! data too long:" + nbBytes);
                    } else {
                        HexDump.dump(unkuonw, 0, System.err, 0);
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    dump = true;
                }

                break;
            }
            case 0xA6: {

                out.println("SetRect:" + opCodeHeader);
                int nbBytesPerRow = round(w * 3, 4);
                int nbBytes = round(nbBytesPerRow * h, 4);
                // int nbBytes=w*h;
                if (nbBytes > 1000000) {
                    System.out.println("Bad length:" + nbBytes);
                } else {
                    byte[] colors = new byte[nbBytes];

                    int lRead = bIn.read(colors);
                    if (lRead != nbBytes) {
                        System.out.println("Bad length:" + nbBytes + " != " + lRead);
                    }
                    // colors contains colors (r,g,b)
                }
                break;
            }
            case 0xA8: {
                int xbound = readInt16(bIn);
                int ybound = readInt16(bIn);
                int wbound = readInt16(bIn);
                int hbound = readInt16(bIn);
                out.println("SetMouseBound to: " + xbound + "," + ybound + " w:" + wbound + " h:" + hbound + " "
                        + opCodeHeader + opCodeHeader);

                break;
            }
            case 0xA9: {

                Color c1 = readColor(bIn);
                Color c2 = readColor(bIn);
                out.println("SetMousePointer pos:" + x + "," + y + " size:" + w + "x" + h + " Color:" + c1
                        + " , " + c2 + opCodeHeader);
                int l = (w * h) / 8;
                byte[] b1 = new byte[l];
                bIn.read(b1);
                out.println("Bitmap");
                // printBits(w, h, b1);

                byte[] b2 = new byte[l];
                bIn.read(b2);
                out.println("Mask");
                // printBits(w, h, b2);
                break;
            }
            case 0xAA:
                int aap1 = bIn.read();
                int aap2 = bIn.read();
                int aap3 = bIn.read();
                int aap4 = bIn.read();
                out.println("SetMousePosition: " + aap1 + "," + aap2 + "," + aap3 + "," + aap4 + opCodeHeader);
                break;
            case 0xAB:
                int ab1 = readInt16(bIn);
                int ab2 = readInt16(bIn);
                out.println("SetKeyLock: " + ab1 + " " + ab2 + opCodeHeader);

                break;
            case 0xAC:

                int ac1 = readInt16(bIn);
                int ac2 = readInt16(bIn);
                int ac3 = readInt16(bIn);
                int ac4 = readInt16(bIn);
                out.println(
                        "0xAC : " + ac1 + " , " + ac2 + "," + ac3 + " , " + ac4 + opCodeHeader + opCodeHeader);
                break;
            case 0xAD:
                out.println("0xAD" + opCodeHeader);

                int l = readInt16(bIn);
                // l = (l & 0xfffc) + 2;

                out.println("l: " + l);
                out.println("(l & 0xfffc) + 2 :" + (l & 0xfffc) + 2);
                byte[] unkuonwn = new byte[l];
                dump = true;
                try {
                    int lRead = bIn.read(unkuonwn);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                break;
            case 0xAF: {

                int p1 = bIn.read();
                int p2 = bIn.read();
                int p3 = bIn.read();
                int p4 = bIn.read();
                for (int i = 0; i < 8; i++) {
                    bIn.read();
                }
                if (p1 != 255 && p2 != 255 && p3 != 255 && p4 != 255) {
                    out.println("PAD:" + p1 + "," + p2 + "," + p3 + "," + p4 + opCodeHeader);
                } else {
                    out.println("PAD " + opCodeHeader);
                }
                break;
            }
            case 0xB1:

                out.println("AUDIO:" + r + "|" + flag + "|" + type + "|" + dir + " l:" + udpData.length + " "
                        + opCodeHeader);
                // outTest.print("AUDIO:"+r+"|"+flag+"|"+type+"|"+dir+" " +
                // opCodeHeader);
                /*
                 * int xbound = readInt16(bIn); int ybound = readInt16(bIn);
                 * int wbound = readInt16(bIn); int hbound = readInt16(bIn);
                 * out.println(" to: " + xbound + "," + ybound + " w:" +
                 * wbound + " h:" + hbound + " " + opCodeHeader +
                 * opCodeHeader); dump=true;
                 */

                int v1 = 0;
                int v2 = 0;
                int totalv1et2 = 0;
                int bigTotal = 0;
                while (bIn.available() >= 0) {
                    int b1 = bIn.read();
                    int b2 = bIn.read();
                    if (b1 == -1 && b2 == -1) {
                        // outTest.print(totalv1et2+" : big total: "+bigTotal);
                        break;
                    }
                    // soundOut.write(b2);
                    // soundOut.write(b1);

                    if (b1 == 0x7F && b2 == 0xFF) {
                        v1++;
                        bigTotal++;
                        totalv1et2++;
                        if (v2 > 0)
                            out.println("v2=" + v2);
                        v2 = 0;
                    } else if (b1 == 0x80 && b2 == 0x01) {
                        v2++;
                        totalv1et2++;
                        bigTotal++;
                        if (v1 > 0)
                            out.println("v1=" + v1);
                        v1 = 0;
                    } else {
                        if (v2 > 0)
                            out.println("v2=" + v2);
                        if (v1 > 0)
                            out.println("v1=" + v1);
                        out.println("Unknwon:" + b1 + " et " + b2 + "[" + (b1 * 256 + b2) + "] total v1+v2:"
                                + totalv1et2);
                        // if(totalv1et2>0)
                        // outTest.print(totalv1et2+",");
                        v1 = 0;
                        v2 = 0;
                        totalv1et2 = 0;
                    }
                    /*
                     * bIn.read(); bIn.read(); for (int j = 0; j < 8; j++) {
                     * for (int i = 0; i < 12; i++) {
                     * 
                     * int aaa1 = bIn.read(); int aaa2 = bIn.read(); if (i %
                     * 2 == 0) { soundOut.write(aaa2); soundOut.write(aaa1);
                     * } } }
                     */

                }
                // outTest.println();

                break;
            case 0xD1:
                out.println("0xD1 " + opCodeHeader + opCodeHeader);
                break;
            case 0xD8:
                out.println("0xD8 " + opCodeHeader + opCodeHeader);
                break;
            case 0xB0: {
                out.println("0xB0 " + opCodeHeader + opCodeHeader);
                int p1 = readInt16(bIn);

                int p2 = readInt16(bIn);
                int p3 = readInt16(bIn);
                int nb = readInt16(bIn);
                out.println(p1 + " ; " + p2 + " ; " + p3);
                for (int i = 0; i < nb; i++) {
                    int xx = readInt16(bIn);
                    int yy = readInt16(bIn);
                    int ww = readInt16(bIn);
                    int hh = readInt16(bIn);
                    out.println("[" + xx + "," + yy + " " + ww + "x" + hh + "]");
                }
                break;
            }
            case 0xB4: {
                // ??
                out.println("0xB4 " + opCodeHeader + opCodeHeader);

                for (int i = 0; i < 19; i++) {
                    int p1 = readInt16(bIn);
                    out.print(p1 + ",");
                }
                int end = readInt16(bIn);
                out.println(end);
                break;
            }
            case 0xB9: {
                // ??
                out.println("0xB9 " + opCodeHeader + opCodeHeader);
                break;
            }
            case 0xBF: {
                int le = readInt16(bIn);
                out.println("0xBF " + le + " bytes " + opCodeHeader);

                byte[] unknown = new byte[le];

                try {
                    int lRead = bIn.read(unknown);
                    if (lRead != le) {
                        out.println("Bad length:" + lRead + " / " + le);
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                break;
            }
            default:
                out.println("Unknown opcode:" + opcode + opCodeHeader);
                dump = true;
                endOfFrame = true;
                break;
            }
        }

    } else {
        out.println("Unknown packet direction:" + dir);
        if (dir != 0)
            dump = true;
    }
    if (dump) {
        HexDump.dump(udpData, 0, System.err, 0);
    }
}

From source file:org.jopenray.operation.SetMouseCursorOperation.java

private void init(int offsetX, int offsetY, int width, int height, Color c0, Color c1, byte[] bitmap,
        byte[] mask) {
    final int expectedLength = (height * width) / 8;
    if (bitmap.length != expectedLength) {

        throw new IllegalArgumentException("Bad bitmap length:" + bitmap.length + " must be " + expectedLength
                + "(" + width + "x" + height + ")");
    }//from  www.java2  s. c  o m
    if (mask.length != expectedLength) {
        try {
            HexDump.dump(bitmap, 0, System.err, 0);
            HexDump.dump(mask, 0, System.err, 0);
        } catch (Exception ignr) {

        }

        throw new IllegalArgumentException("Bad mask length:" + mask.length + " must be " + expectedLength + "("
                + width + "x" + height + ")");
    }

    allocate(12 + 8 + bitmap.length + mask.length);
    setHeader(0xA9, offsetX, offsetY, width, height);

    buffer.addColor(c0);
    buffer.addColor(c1);
    buffer.addBytes(bitmap);
    buffer.addBytes(mask);
}