Example usage for java.io DataOutputStream write

List of usage examples for java.io DataOutputStream write

Introduction

In this page you can find the example usage for java.io DataOutputStream write.

Prototype

public synchronized void write(int b) throws IOException 

Source Link

Document

Writes the specified byte (the low eight bits of the argument b) to the underlying output stream.

Usage

From source file:org.apache.fontbox.ttf.TTFSubFont.java

private byte[] buildOS2Table() throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bos);
    OS2WindowsMetricsTable os2 = this.baseTTF.getOS2Windows();
    if (os2 == null) {
        // sometimes there is no OS2 table in an embedded subfonts
        // create a dummy
        os2 = new OS2WindowsMetricsTable();
    }/*from  w ww  .j  a  v a2s.c o m*/

    LOG.debug("Building table [OS/2]...");

    writeUint16(dos, 0);
    writeSint16(dos, os2.getAverageCharWidth());
    writeUint16(dos, os2.getWeightClass());
    writeUint16(dos, os2.getWidthClass());

    writeSint16(dos, os2.getFsType());

    writeSint16(dos, os2.getSubscriptXSize());
    writeSint16(dos, os2.getSubscriptYSize());
    writeSint16(dos, os2.getSubscriptXOffset());
    writeSint16(dos, os2.getSubscriptYOffset());

    writeSint16(dos, os2.getSuperscriptXSize());
    writeSint16(dos, os2.getSuperscriptYSize());
    writeSint16(dos, os2.getSuperscriptXOffset());
    writeSint16(dos, os2.getSuperscriptYOffset());

    writeSint16(dos, os2.getStrikeoutSize());
    writeSint16(dos, os2.getStrikeoutPosition());
    writeUint8(dos, os2.getFamilyClass());
    writeUint8(dos, os2.getFamilySubClass());
    dos.write(os2.getPanose());

    writeUint32(dos, 0);
    writeUint32(dos, 0);
    writeUint32(dos, 0);
    writeUint32(dos, 0);

    dos.write(os2.getAchVendId().getBytes("ISO-8859-1"));

    Iterator<Entry<Integer, Integer>> it = characters.entrySet().iterator();
    it.next();
    Entry<Integer, Integer> first = it.next();

    writeUint16(dos, os2.getFsSelection());
    writeUint16(dos, first.getKey());
    writeUint16(dos, characters.lastKey());
    /*
     * The mysterious Microsoft additions.
     *
     * SHORT    sTypoAscender    
     * SHORT    sTypoDescender    
     * SHORT    sTypoLineGap
     * USHORT    usWinAscent
     * USHORT    usWinDescent
     */
    writeUint16(dos, os2.getTypoAscender());
    writeUint16(dos, os2.getTypoDescender());
    writeUint16(dos, os2.getTypeLineGap());
    writeUint16(dos, os2.getWinAscent());
    writeUint16(dos, os2.getWinDescent());

    dos.flush();
    LOG.debug("Finished table [OS/2].");
    return bos.toByteArray();
}

From source file:com.stratuscom.harvester.codebase.ClassServer.java

private boolean processRequest(Socket sock) {
    try {//from  ww w . ja v  a2s .c om
        DataOutputStream out = new DataOutputStream(sock.getOutputStream());
        String req;
        try {
            req = getInput(sock, true);
        } catch (Exception e) {
            logger.log(Level.FINE, "reading request", e);
            return true;
        }
        if (req == null) {
            return true;
        }
        String[] args = new String[3];
        boolean get = req.startsWith("GET ");
        if (!get && !req.startsWith("HEAD ")) {
            processBadRequest(args, out);
        }
        String path = parsePathFromRequest(req, get);
        if (path == null) {
            return processBadRequest(args, out);
        }
        if (args != null) {
            args[0] = path;
        }
        args[1] = sock.getInetAddress().getHostName();
        args[2] = Integer.toString(sock.getPort());

        logger.log(Level.FINER,
                get ? MessageNames.CLASS_SERVER_RECEIVED_REQUEST : MessageNames.CLASS_SERVER_RECEIVED_PROBE,
                args);
        byte[] bytes;
        try {
            bytes = getBytes(path);
        } catch (Exception e) {
            logger.log(Level.WARNING, MessageNames.CLASS_SERVER_EXCEPTION_GETTING_BYTES, e);
            out.writeBytes("HTTP/1.0 500 Internal Error\r\n\r\n");
            out.flush();
            return true;
        }
        if (bytes == null) {
            logger.log(Level.FINE, MessageNames.CLASS_SERVER_NO_CONTENT_FOUND, path);
            out.writeBytes("HTTP/1.0 404 Not Found\r\n\r\n");
            out.flush();
            return true;
        }
        writeHeader(out, bytes);
        if (get) {
            out.write(bytes);
        }
        out.flush();
        return false;
    } catch (Exception e) {
        logger.log(Level.FINE, MessageNames.CLASS_SERVER_EXCEPTION_WRITING_RESPONSE, e);
    } finally {
        try {
            sock.close();
        } catch (IOException e) {
        }
    }
    return false;
}

From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java

/**
 * This method writes what readCredential() method expects to read. (Note the use of singular
 * credential). It is similar to writeCredentials(), except that it doesn't write
 * credential-properties./*w w  w  .j  av a 2s.co m*/
 */
public byte writeCredential(DataOutputStream dos, DataInputStream dis, String authInit, boolean isNotification,
        DistributedMember member, HeapDataOutputStream heapdos) throws IOException, GemFireSecurityException {

    if (!this.multiuserSecureMode && (authInit == null || authInit.length() == 0)) {
        // No credentials indicator
        heapdos.writeByte(CREDENTIALS_NONE);
        heapdos.flush();
        dos.write(heapdos.toByteArray());
        dos.flush();
        return -1;
    }

    if (dhSKAlgo == null || dhSKAlgo.length() == 0) {
        // Normal credentials without encryption indicator
        heapdos.writeByte(CREDENTIALS_NORMAL);
        this.appSecureMode = CREDENTIALS_NORMAL;
        // DataSerializer.writeProperties(p_credentials, heapdos);
        heapdos.flush();
        dos.write(heapdos.toByteArray());
        dos.flush();
        return -1;
    }
    byte acceptanceCode = -1;
    try {
        InternalLogWriter securityLogWriter = (InternalLogWriter) this.system.getSecurityLogWriter();
        securityLogWriter.fine("HandShake: using Diffie-Hellman key exchange with algo " + dhSKAlgo);
        boolean requireAuthentication = (certificateFilePath != null && certificateFilePath.length() > 0);
        if (requireAuthentication) {
            securityLogWriter.fine("HandShake: server authentication using digital " + "signature required");
        }
        // Credentials with encryption indicator
        heapdos.writeByte(CREDENTIALS_DHENCRYPT);
        this.appSecureMode = CREDENTIALS_DHENCRYPT;
        heapdos.writeBoolean(requireAuthentication);
        // Send the symmetric encryption algorithm name
        DataSerializer.writeString(dhSKAlgo, heapdos);
        // Send the DH public key
        byte[] keyBytes = dhPublicKey.getEncoded();
        DataSerializer.writeByteArray(keyBytes, heapdos);
        byte[] clientChallenge = null;
        if (requireAuthentication) {
            // Authentication of server should be with the client supplied
            // challenge
            clientChallenge = new byte[64];
            random.nextBytes(clientChallenge);
            DataSerializer.writeByteArray(clientChallenge, heapdos);
        }
        heapdos.flush();
        dos.write(heapdos.toByteArray());
        dos.flush();

        // Expect the alias and signature in the reply
        acceptanceCode = dis.readByte();
        if (acceptanceCode != REPLY_OK && acceptanceCode != REPLY_AUTH_NOT_REQUIRED) {
            // Ignore the useless data
            dis.readByte();
            dis.readInt();
            if (!isNotification) {
                DataSerializer.readByteArray(dis);
            }
            readMessage(dis, dos, acceptanceCode, member);
        } else if (acceptanceCode == REPLY_OK) {
            // Get the public key of the other side
            keyBytes = DataSerializer.readByteArray(dis);
            if (requireAuthentication) {
                String subject = DataSerializer.readString(dis);
                byte[] signatureBytes = DataSerializer.readByteArray(dis);
                if (!certificateMap.containsKey(subject)) {
                    throw new AuthenticationFailedException(
                            LocalizedStrings.HandShake_HANDSHAKE_FAILED_TO_FIND_PUBLIC_KEY_FOR_SERVER_WITH_SUBJECT_0
                                    .toLocalizedString(subject));
                }

                // Check the signature with the public key
                X509Certificate cert = (X509Certificate) certificateMap.get(subject);
                Signature sig = Signature.getInstance(cert.getSigAlgName());
                sig.initVerify(cert);
                sig.update(clientChallenge);
                // Check the challenge string
                if (!sig.verify(signatureBytes)) {
                    throw new AuthenticationFailedException(
                            "Mismatch in client " + "challenge bytes. Malicious server?");
                }
                securityLogWriter
                        .fine("HandShake: Successfully verified the " + "digital signature from server");
            }

            // Read server challenge bytes
            byte[] serverChallenge = DataSerializer.readByteArray(dis);
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFact = KeyFactory.getInstance("DH");
            // PublicKey pubKey = keyFact.generatePublic(x509KeySpec);
            this.clientPublicKey = keyFact.generatePublic(x509KeySpec);

            HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT);
            try {
                // Add the challenge string
                DataSerializer.writeByteArray(serverChallenge, hdos);
                // byte[] encBytes = encrypt.doFinal(hdos.toByteArray());
                byte[] encBytes = encryptBytes(hdos.toByteArray(),
                        getEncryptCipher(dhSKAlgo, this.clientPublicKey));
                DataSerializer.writeByteArray(encBytes, dos);
            } finally {
                hdos.close();
            }
        }
    } catch (IOException ex) {
        throw ex;
    } catch (GemFireSecurityException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new AuthenticationFailedException("HandShake failed in Diffie-Hellman key exchange", ex);
    }
    dos.flush();
    return acceptanceCode;
}

From source file:com.linkedin.pinot.common.utils.DataTable.java

/**
 * Serialize the data table into a byte-array, as per the specified serialization.
 *
 * @param version Format version to use for serialization.
 * @return Serialized byte-array// w  w  w . j  a v  a  2s  .  co m
 * @throws Exception
 */
public byte[] toBytes(Version version) throws Exception {
    final byte[] dictionaryBytes = serializeDictionary();
    final byte[] metadataBytes = serializeMetadata();
    byte[] schemaBytes = new byte[0];
    if (schema != null) {
        schemaBytes = schema.toBytes();
    }
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final DataOutputStream out = new DataOutputStream(baos);
    // TODO: convert this format into a proper class
    // VERSION|NUM_ROW|NUM_COL|(START|SIZE) -- START|SIZE 5 PAIRS FOR
    // DICTIONARY, METADATA,
    // SCHEMA, DATATABLE, VARIABLE DATA BUFFER --> 4 + 4 + 4 + 5*8 = 52
    // bytes

    out.writeInt(version.getValue());
    out.writeInt(numRows);
    out.writeInt(numCols);
    // dictionary
    int baseOffset = 52;
    out.writeInt(baseOffset);
    out.writeInt(dictionaryBytes.length);
    baseOffset += dictionaryBytes.length;

    // metadata
    out.writeInt(baseOffset);
    out.writeInt(metadataBytes.length);
    baseOffset += metadataBytes.length;

    // schema
    out.writeInt(baseOffset);
    out.writeInt(schemaBytes.length);
    baseOffset += schemaBytes.length;

    // datatable
    out.writeInt(baseOffset);
    if (fixedSizeDataBytes == null) {
        out.writeInt(0);
    } else {
        out.writeInt(fixedSizeDataBytes.length);
        baseOffset += fixedSizeDataBytes.length;
    }

    // variable data
    out.writeInt(baseOffset);
    if (variableSizeDataBytes == null) {
        out.writeInt(0);
    } else {
        out.writeInt(variableSizeDataBytes.length);
    }

    // write them
    out.write(dictionaryBytes);
    out.write(metadataBytes);
    out.write(schemaBytes);
    if (fixedSizeDataBytes != null) {
        out.write(fixedSizeDataBytes);
    }
    if (variableSizeDataBytes != null) {
        out.write(variableSizeDataBytes);
    }
    byte[] byteArray = baos.toByteArray();
    long end = System.currentTimeMillis();
    return byteArray;
}

From source file:org.apache.jmeter.protocol.mqtt.client.MqttPublisher.java

public byte[] createPayload(String message, String useTimeStamp, String useNumSeq, String type_value,
        String format, String charset) throws IOException, NumberFormatException {
    ByteArrayOutputStream b = new ByteArrayOutputStream();
    DataOutputStream d = new DataOutputStream(b);
    // flags     
    byte flags = 0x00;
    if ("TRUE".equals(useTimeStamp))
        flags |= 0x80;/*from   ww w  .  j  a  va  2 s .co m*/
    if ("TRUE".equals(useNumSeq))
        flags |= 0x40;
    if (MQTTPublisherGui.INT.equals(type_value))
        flags |= 0x20;
    if (MQTTPublisherGui.LONG.equals(type_value))
        flags |= 0x10;
    if (MQTTPublisherGui.FLOAT.equals(type_value))
        flags |= 0x08;
    if (MQTTPublisherGui.DOUBLE.equals(type_value))
        flags |= 0x04;
    if (MQTTPublisherGui.STRING.equals(type_value))
        flags |= 0x02;
    if (!"TEXT".equals(type_value)) {
        d.writeByte(flags);
    }
    // TimeStamp
    if ("TRUE".equals(useTimeStamp)) {
        Date date = new java.util.Date();
        d.writeLong(date.getTime());
    }
    // Number Sequence
    if ("TRUE".equals(useNumSeq)) {
        d.writeInt(numSeq++);

    }
    // Value            
    if (MQTTPublisherGui.INT.equals(type_value)) {
        d.writeInt(Integer.parseInt(message));
    } else if (MQTTPublisherGui.LONG.equals(type_value)) {
        d.writeLong(Long.parseLong(message));
    } else if (MQTTPublisherGui.DOUBLE.equals(type_value)) {
        d.writeDouble(Double.parseDouble(message));
    } else if (MQTTPublisherGui.FLOAT.equals(type_value)) {
        d.writeDouble(Float.parseFloat(message));
    } else if (MQTTPublisherGui.STRING.equals(type_value)) {
        d.write(message.getBytes());
    } else if ("TEXT".equals(type_value)) {
        d.write(message.getBytes());
    }

    // Format: Encoding        
    if (MQTTPublisherGui.BINARY.equals(format)) {
        BinaryCodec encoder = new BinaryCodec();
        return encoder.encode(b.toByteArray());
    } else if (MQTTPublisherGui.BASE64.equals(format)) {
        return Base64.encodeBase64(b.toByteArray());
    } else if (MQTTPublisherGui.BINHEX.equals(format)) {
        Hex encoder = new Hex();
        return encoder.encode(b.toByteArray());
    } else if (MQTTPublisherGui.PLAIN_TEXT.equals(format)) {
        String s = new String(b.toByteArray(), charset);
        return s.getBytes();

    } else
        return b.toByteArray();
}

From source file:org.apache.hadoop.hive.ql.metadata.formatting.TextMetaDataFormatter.java

@Override
public void showTableStatus(DataOutputStream outStream, Hive db, HiveConf conf, List<Table> tbls,
        Map<String, String> part, Partition par) throws HiveException {
    try {/*w w  w  . j av a  2s  . c  o  m*/
        Iterator<Table> iterTables = tbls.iterator();
        while (iterTables.hasNext()) {
            // create a row per table name
            Table tbl = iterTables.next();
            String tableName = tbl.getTableName();
            String tblLoc = null;
            String inputFormattCls = null;
            String outputFormattCls = null;
            if (part != null) {
                if (par != null) {
                    if (par.getLocation() != null) {
                        tblLoc = par.getDataLocation().toString();
                    }
                    inputFormattCls = par.getInputFormatClass().getName();
                    outputFormattCls = par.getOutputFormatClass().getName();
                }
            } else {
                if (tbl.getPath() != null) {
                    tblLoc = tbl.getDataLocation().toString();
                }
                inputFormattCls = tbl.getInputFormatClass().getName();
                outputFormattCls = tbl.getOutputFormatClass().getName();
            }

            String owner = tbl.getOwner();
            List<FieldSchema> cols = tbl.getCols();
            String ddlCols = MetaStoreUtils.getDDLFromFieldSchema("columns", cols);
            boolean isPartitioned = tbl.isPartitioned();
            String partitionCols = "";
            if (isPartitioned) {
                partitionCols = MetaStoreUtils.getDDLFromFieldSchema("partition_columns", tbl.getPartCols());
            }

            outStream.write(("tableName:" + tableName).getBytes("UTF-8"));
            outStream.write(terminator);
            outStream.write(("owner:" + owner).getBytes("UTF-8"));
            outStream.write(terminator);
            outStream.write(("location:" + tblLoc).getBytes("UTF-8"));
            outStream.write(terminator);
            outStream.write(("inputformat:" + inputFormattCls).getBytes("UTF-8"));
            outStream.write(terminator);
            outStream.write(("outputformat:" + outputFormattCls).getBytes("UTF-8"));
            outStream.write(terminator);
            outStream.write(("columns:" + ddlCols).getBytes("UTF-8"));
            outStream.write(terminator);
            outStream.write(("partitioned:" + isPartitioned).getBytes("UTF-8"));
            outStream.write(terminator);
            outStream.write(("partitionColumns:" + partitionCols).getBytes("UTF-8"));
            outStream.write(terminator);
            // output file system information
            Path tblPath = tbl.getPath();
            List<Path> locations = new ArrayList<Path>();
            if (isPartitioned) {
                if (par == null) {
                    for (Partition curPart : db.getPartitions(tbl)) {
                        if (curPart.getLocation() != null) {
                            locations.add(new Path(curPart.getLocation()));
                        }
                    }
                } else {
                    if (par.getLocation() != null) {
                        locations.add(new Path(par.getLocation()));
                    }
                }
            } else {
                if (tblPath != null) {
                    locations.add(tblPath);
                }
            }
            if (!locations.isEmpty()) {
                writeFileSystemStats(outStream, conf, locations, tblPath, false, 0);
            }

            outStream.write(terminator);
        }
    } catch (IOException e) {
        throw new HiveException(e);
    }
}

From source file:TModem.java

public boolean receive(String tfile) throws IOException, InterruptedException {
    char checksum, index, blocknumber, errorcount;
    byte character;
    byte[] sector = new byte[SECSIZE];
    DataOutputStream foo;

    foo = new DataOutputStream(new FileOutputStream(tfile));

    System.out.println("you have " + SLEEP + " seconds...");

    /* wait for the user or remote to get his act together */
    gotChar = false;//from w w w  .j  av a 2 s .  co m
    new IOTimer(SLEEP, "receive from remote").start();

    errStream.println("Starting receive...");
    putchar(NAK);
    errorcount = 0;
    blocknumber = 1;
    rxLoop: do {
        character = getchar();
        gotChar = true;
        if (character != EOT) {
            try {
                byte not_ch;
                if (character != SOH) {
                    errStream.println("Not SOH");
                    if (++errorcount < MAXERRORS)
                        continue rxLoop;
                    else
                        xerror();
                }
                character = getchar();
                not_ch = (byte) (~getchar());
                errStream.println("[" + character + "] ");
                if (character != not_ch) {
                    errStream.println("Blockcounts not ~");
                    ++errorcount;
                    continue rxLoop;
                }
                if (character != blocknumber) {
                    errStream.println("Wrong blocknumber");
                    ++errorcount;
                    continue rxLoop;
                }
                checksum = 0;
                for (index = 0; index < SECSIZE; index++) {
                    sector[index] = getchar();
                    checksum += sector[index];
                }
                if (checksum != getchar()) {
                    errStream.println("Bad checksum");
                    errorcount++;
                    continue rxLoop;
                }
                putchar(ACK);
                blocknumber++;
                try {
                    foo.write(sector);
                } catch (IOException e) {
                    errStream.println("write failed, blocknumber " + blocknumber);
                }
            } finally {
                if (errorcount != 0)
                    putchar(NAK);
            }
        }
    } while (character != EOT);

    foo.close();

    putchar(ACK); /* tell the other end we accepted his EOT    */
    putchar(ACK);
    putchar(ACK);

    errStream.println("Receive Completed.");
    return true;
}

From source file:com.curso.listadapter.net.RESTClient.java

/**
 * upload multipart/*ww  w.  ja  va  2s.com*/
 * this method receive the file to be uploaded
 * */
@SuppressWarnings("deprecation")
public String uploadMultiPart(Map<String, File> files) throws Exception {
    disableSSLCertificateChecking();
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    DataInputStream inStream = null;
    try {
        URL endpoint = new URL(url);
        conn = (HttpURLConnection) endpoint.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

        dos = new DataOutputStream(conn.getOutputStream());
        String post = "";

        //WRITE ALL THE PARAMS
        for (NameValuePair p : params)
            post += writeMultipartParam(p);
        dos.flush();
        //END WRITE ALL THE PARAMS

        //BEGIN THE UPLOAD
        ArrayList<FileInputStream> inputStreams = new ArrayList<FileInputStream>();
        for (Entry<String, File> entry : files.entrySet()) {
            post += lineEnd;
            post += twoHyphens + boundary + lineEnd;
            String NameParamImage = entry.getKey();
            File file = entry.getValue();
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1 * 1024 * 1024;
            FileInputStream fileInputStream = new FileInputStream(file);

            post += "Content-Disposition: attachment; name=\"" + NameParamImage + "\"; filename=\""
                    + file.getName() + "\"" + lineEnd;
            String mimetype = getMimeType(file.getName());
            post += "Content-Type: " + mimetype + lineEnd;
            post += "Content-Transfer-Encoding: binary" + lineEnd + lineEnd;

            dos.write(post.toString().getBytes("UTF-8"));

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            while (bytesRead > 0) {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                inputStreams.add(fileInputStream);
            }

            Log.d("Test", post);
            dos.flush();
            post = "";
        }

        //END THE UPLOAD

        dos.writeBytes(lineEnd);

        dos.writeBytes(twoHyphens + boundary + twoHyphens);
        //            for(FileInputStream inputStream: inputStreams){
        //               inputStream.close();
        //            }
        dos.flush();
        dos.close();
        conn.connect();
        Log.d("upload", "finish flush:" + conn.getResponseCode());
    } catch (MalformedURLException ex) {
        Log.e("Debug", "error: " + ex.getMessage(), ex);
    } catch (IOException ioe) {
        Log.e("Debug", "error: " + ioe.getMessage(), ioe);
    }
    try {
        String response_data = "";
        inStream = new DataInputStream(conn.getInputStream());
        String str;
        while ((str = inStream.readLine()) != null) {
            response_data += str;
        }
        inStream.close();
        return response_data;
    } catch (IOException ioex) {
        Log.e("Debug", "error: " + ioex.getMessage(), ioex);
    }
    return null;
}

From source file:org.apache.fontbox.ttf.TTFSubsetter.java

private byte[] buildPostTable() throws IOException {
    PostScriptTable post = ttf.getPostScript();
    if (post == null || keepTables != null && !keepTables.contains("post")) {
        return null;
    }/*from w ww.  j ava  2s. c  o m*/

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(bos);

    writeFixed(out, 2.0); // version
    writeFixed(out, post.getItalicAngle());
    writeSInt16(out, post.getUnderlinePosition());
    writeSInt16(out, post.getUnderlineThickness());
    writeUint32(out, post.getIsFixedPitch());
    writeUint32(out, post.getMinMemType42());
    writeUint32(out, post.getMaxMemType42());
    writeUint32(out, post.getMinMemType1());
    writeUint32(out, post.getMaxMemType1());

    // version 2.0

    // numberOfGlyphs
    writeUint16(out, glyphIds.size());

    // glyphNameIndex[numGlyphs]
    Map<String, Integer> names = new TreeMap<String, Integer>();
    for (int gid : glyphIds) {
        String name = post.getName(gid);
        Integer macId = WGL4Names.MAC_GLYPH_NAMES_INDICES.get(name);
        if (macId != null) {
            // the name is implicit, as it's from MacRoman
            writeUint16(out, macId);
        } else {
            // the name will be written explicitly
            Integer ordinal = names.get(name);
            if (ordinal == null) {
                ordinal = names.size();
                names.put(name, ordinal);
            }
            writeUint16(out, 258 + ordinal);
        }
    }

    // names[numberNewGlyphs]
    for (String name : names.keySet()) {
        byte[] buf = name.getBytes(Charset.forName("US-ASCII"));
        writeUint8(out, buf.length);
        out.write(buf);
    }

    out.flush();
    return bos.toByteArray();
}

From source file:com.linkedin.pinot.core.common.datatable.DataTableImplV2.java

@Nonnull
@Override/*  www  .  j a  v a 2s. c  om*/
public byte[] toBytes() throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);
    dataOutputStream.writeInt(VERSION);
    dataOutputStream.writeInt(_numRows);
    dataOutputStream.writeInt(_numColumns);
    int dataOffset = HEADER_SIZE;

    // Write dictionary.
    dataOutputStream.writeInt(dataOffset);
    byte[] dictionaryMapBytes = null;
    if (_dictionaryMap != null) {
        dictionaryMapBytes = serializeDictionaryMap();
        dataOutputStream.writeInt(dictionaryMapBytes.length);
        dataOffset += dictionaryMapBytes.length;
    } else {
        dataOutputStream.writeInt(0);
    }

    // Write metadata.
    dataOutputStream.writeInt(dataOffset);
    byte[] metadataBytes = serializeMetadata();
    dataOutputStream.writeInt(metadataBytes.length);
    dataOffset += metadataBytes.length;

    // Write data schema.
    dataOutputStream.writeInt(dataOffset);
    byte[] dataSchemaBytes = null;
    if (_dataSchema != null) {
        dataSchemaBytes = _dataSchema.toBytes();
        dataOutputStream.writeInt(dataSchemaBytes.length);
        dataOffset += dataSchemaBytes.length;
    } else {
        dataOutputStream.writeInt(0);
    }

    // Write fixed size data.
    dataOutputStream.writeInt(dataOffset);
    if (_fixedSizeDataBytes != null) {
        dataOutputStream.writeInt(_fixedSizeDataBytes.length);
        dataOffset += _fixedSizeDataBytes.length;
    } else {
        dataOutputStream.writeInt(0);
    }

    // Write variable size data.
    dataOutputStream.writeInt(dataOffset);
    if (_variableSizeDataBytes != null) {
        dataOutputStream.writeInt(_variableSizeDataBytes.length);
    } else {
        dataOutputStream.writeInt(0);
    }

    // Write actual data.
    if (dictionaryMapBytes != null) {
        dataOutputStream.write(dictionaryMapBytes);
    }
    dataOutputStream.write(metadataBytes);
    if (dataSchemaBytes != null) {
        dataOutputStream.write(dataSchemaBytes);
    }
    if (_fixedSizeDataBytes != null) {
        dataOutputStream.write(_fixedSizeDataBytes);
    }
    if (_variableSizeDataBytes != null) {
        dataOutputStream.write(_variableSizeDataBytes);
    }

    return byteArrayOutputStream.toByteArray();
}