Example usage for java.io DataOutputStream writeShort

List of usage examples for java.io DataOutputStream writeShort

Introduction

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

Prototype

public final void writeShort(int v) throws IOException 

Source Link

Document

Writes a short to the underlying output stream as two bytes, high byte first.

Usage

From source file:org.jboss.as.test.integration.security.loginmodules.negotiation.Krb5ConfServerSetupTask.java

/**
 * Creates a keytab file for given principal.
 * /*from   www.ja  v  a  2  s.co m*/
 * @param principalName
 * @param passPhrase
 * @param keytabFile
 * @throws IOException
 */
public static void createKeytab(final String principalName, final String passPhrase, final File keytabFile)
        throws IOException {
    LOGGER.info("Principal name: " + principalName);
    final KerberosTime timeStamp = new KerberosTime();

    DataOutputStream dos = null;
    try {
        dos = new DataOutputStream(new FileOutputStream(keytabFile));
        dos.write(Keytab.VERSION_0X502_BYTES);

        for (Map.Entry<EncryptionType, EncryptionKey> keyEntry : KerberosKeyFactory
                .getKerberosKeys(principalName, passPhrase).entrySet()) {
            final EncryptionKey key = keyEntry.getValue();
            final byte keyVersion = (byte) key.getKeyVersion();
            // entries.add(new KeytabEntry(principalName, principalType, timeStamp, keyVersion, key));

            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DataOutputStream entryDos = new DataOutputStream(baos);
            // handle principal name
            String[] spnSplit = principalName.split("@");
            String nameComponent = spnSplit[0];
            String realm = spnSplit[1];

            String[] nameComponents = nameComponent.split("/");
            try {
                // increment for v1
                entryDos.writeShort((short) nameComponents.length);
                entryDos.writeUTF(realm);
                // write components
                for (String component : nameComponents) {
                    entryDos.writeUTF(component);
                }

                entryDos.writeInt(1); // principal type: KRB5_NT_PRINCIPAL
                entryDos.writeInt((int) (timeStamp.getTime() / 1000));
                entryDos.write(keyVersion);

                entryDos.writeShort((short) key.getKeyType().getValue());

                byte[] data = key.getKeyValue();
                entryDos.writeShort((short) data.length);
                entryDos.write(data);
            } finally {
                IOUtils.closeQuietly(entryDos);
            }
            final byte[] entryBytes = baos.toByteArray();
            dos.writeInt(entryBytes.length);
            dos.write(entryBytes);
        }
        // } catch (IOException ioe) {
    } finally {
        IOUtils.closeQuietly(dos);
    }
}

From source file:com.dbay.apns4j.tools.ApnsTools.java

public final static byte[] generateData(List<FrameItem> list) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream os = new DataOutputStream(bos);
    int frameLength = 0;
    for (FrameItem item : list) {
        // itemId length = 1, itemDataLength = 2
        frameLength += 1 + 2 + item.getItemLength();
    }/*from  w ww  .j  av a 2s  .c om*/
    try {
        os.writeByte(Command.SEND_V2);
        os.writeInt(frameLength);
        for (FrameItem item : list) {
            os.writeByte(item.getItemId());
            os.writeShort(item.getItemLength());
            os.write(item.getItemData());
        }
        return bos.toByteArray();
    } catch (IOException e) {
        e.printStackTrace();
    }
    throw new RuntimeException();
}

From source file:marytts.util.io.FileUtils.java

public static void writeBinaryFile(short[] x, DataOutputStream d) throws IOException {
    for (int i = 0; i < x.length; i++)
        d.writeShort(x[i]);
}

From source file:org.apache.hadoop.raid.BlockFixer.java

/**
 * Reads data from the data stream provided and computes metadata.
 *//*from  w  w  w  .jav  a  2 s  . c o  m*/
static DataInputStream computeMetadata(Configuration conf, InputStream dataStream) throws IOException {
    ByteArrayOutputStream mdOutBase = new ByteArrayOutputStream(1024 * 1024);
    DataOutputStream mdOut = new DataOutputStream(mdOutBase);

    // First, write out the version.
    mdOut.writeShort(FSDataset.METADATA_VERSION);

    // Create a summer and write out its header.
    int bytesPerChecksum = conf.getInt("io.bytes.per.checksum", 512);
    DataChecksum sum = DataChecksum.newDataChecksum(DataChecksum.CHECKSUM_CRC32, bytesPerChecksum);
    sum.writeHeader(mdOut);

    // Buffer to read in a chunk of data.
    byte[] buf = new byte[bytesPerChecksum];
    // Buffer to store the checksum bytes.
    byte[] chk = new byte[sum.getChecksumSize()];

    // Read data till we reach the end of the input stream.
    int bytesSinceFlush = 0;
    while (true) {
        // Read some bytes.
        int bytesRead = dataStream.read(buf, bytesSinceFlush, bytesPerChecksum - bytesSinceFlush);
        if (bytesRead == -1) {
            if (bytesSinceFlush > 0) {
                boolean reset = true;
                sum.writeValue(chk, 0, reset); // This also resets the sum.
                // Write the checksum to the stream.
                mdOut.write(chk, 0, chk.length);
                bytesSinceFlush = 0;
            }
            break;
        }
        // Update the checksum.
        sum.update(buf, bytesSinceFlush, bytesRead);
        bytesSinceFlush += bytesRead;

        // Flush the checksum if necessary.
        if (bytesSinceFlush == bytesPerChecksum) {
            boolean reset = true;
            sum.writeValue(chk, 0, reset); // This also resets the sum.
            // Write the checksum to the stream.
            mdOut.write(chk, 0, chk.length);
            bytesSinceFlush = 0;
        }
    }

    byte[] mdBytes = mdOutBase.toByteArray();
    return new DataInputStream(new ByteArrayInputStream(mdBytes));
}

From source file:org.apache.hadoop.hdfs.server.namenode.FSImageSerialization.java

static void writeINodeUnderConstruction(DataOutputStream out, INodeFileUnderConstruction cons, String path)
        throws IOException {
    writeString(path, out);//  w ww. j a v a2 s. c o m
    out.writeLong(cons.getId());
    out.writeShort(cons.getFileReplication());
    out.writeLong(cons.getModificationTime());
    out.writeLong(cons.getPreferredBlockSize());

    writeBlocks(cons.getBlocks(), out);
    cons.getPermissionStatus().write(out);

    writeString(cons.getClientName(), out);
    writeString(cons.getClientMachine(), out);

    out.writeInt(0); //  do not store locations of last block
}

From source file:com.ebay.nest.io.sede.lazy.LazyUtils.java

/**
 * Write out a binary representation of a PrimitiveObject to a byte stream.
 *
 * @param out ByteStream.Output, an unsynchronized version of ByteArrayOutputStream, used as a
 *            backing buffer for the the DataOutputStream
 * @param o the PrimitiveObject//w  ww .  j a v a 2  s  .c  om
 * @param oi the PrimitiveObjectInspector
 * @throws IOException on error during the write operation
 */
public static void writePrimitive(OutputStream out, Object o, PrimitiveObjectInspector oi) throws IOException {

    DataOutputStream dos = new DataOutputStream(out);

    try {
        switch (oi.getPrimitiveCategory()) {
        case BOOLEAN:
            boolean b = ((BooleanObjectInspector) oi).get(o);
            dos.writeBoolean(b);
            break;

        case BYTE:
            byte bt = ((ByteObjectInspector) oi).get(o);
            dos.writeByte(bt);
            break;

        case SHORT:
            short s = ((ShortObjectInspector) oi).get(o);
            dos.writeShort(s);
            break;

        case INT:
            int i = ((IntObjectInspector) oi).get(o);
            dos.writeInt(i);
            break;

        case LONG:
            long l = ((LongObjectInspector) oi).get(o);
            dos.writeLong(l);
            break;

        case FLOAT:
            float f = ((FloatObjectInspector) oi).get(o);
            dos.writeFloat(f);
            break;

        case DOUBLE:
            double d = ((DoubleObjectInspector) oi).get(o);
            dos.writeDouble(d);
            break;

        default:
            throw new RuntimeException("Hive internal error.");
        }
    } finally {
        // closing the underlying ByteStream should have no effect, the data should still be
        // accessible
        dos.close();
    }
}

From source file:org.apache.jackrabbit.core.persistence.util.Serializer.java

/**
 * Serializes the specified <code>NodeState</code> object to the given
 * binary <code>stream</code>.
 *
 * @param state  <code>state</code> to serialize
 * @param stream the stream where the <code>state</code> should be
 *               serialized to//w ww.  j  ava  2s. co  m
 * @throws Exception if an error occurs during the serialization
 * @see #deserialize(NodeState, InputStream)
 */
public static void serialize(NodeState state, OutputStream stream) throws Exception {
    DataOutputStream out = new DataOutputStream(stream);

    // primaryType
    out.writeUTF(state.getNodeTypeName().toString());
    // parentUUID
    if (state.getParentId() == null) {
        out.write(NULL_UUID_PLACEHOLDER_BYTES);
    } else {
        out.write(state.getParentId().getRawBytes());
    }
    // definitionId
    out.writeUTF("");
    // mixin types
    Collection<Name> c = state.getMixinTypeNames();
    out.writeInt(c.size()); // count
    for (Iterator<Name> iter = c.iterator(); iter.hasNext();) {
        out.writeUTF(iter.next().toString()); // name
    }
    // modCount
    out.writeShort(state.getModCount());
    // properties (names)
    c = state.getPropertyNames();
    out.writeInt(c.size()); // count
    for (Iterator<Name> iter = c.iterator(); iter.hasNext();) {
        Name propName = iter.next();
        out.writeUTF(propName.toString()); // name
    }
    // child nodes (list of name/uuid pairs)
    Collection<ChildNodeEntry> collChildren = state.getChildNodeEntries();
    out.writeInt(collChildren.size()); // count
    for (Iterator<ChildNodeEntry> iter = collChildren.iterator(); iter.hasNext();) {
        ChildNodeEntry entry = iter.next();
        out.writeUTF(entry.getName().toString()); // name
        out.write(entry.getId().getRawBytes()); // uuid
    }
}

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

private static void writeUint16(DataOutputStream dos, int i) throws IOException {
    dos.writeShort(i);
}

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

private static void writeSint16(DataOutputStream dos, short i) throws IOException {
    dos.writeShort(i);
}

From source file:org.apache.hadoop.hive.serde2.lazy.LazyUtils.java

/**
 * Write out a binary representation of a PrimitiveObject to a byte stream.
 *
 * @param out ByteStream.Output, an unsynchronized version of ByteArrayOutputStream, used as a
 *            backing buffer for the the DataOutputStream
 * @param o the PrimitiveObject//from   w  w w  . j  ava  2s .co  m
 * @param oi the PrimitiveObjectInspector
 * @throws IOException on error during the write operation
 */
public static void writePrimitive(OutputStream out, Object o, PrimitiveObjectInspector oi) throws IOException {

    DataOutputStream dos = new DataOutputStream(out);

    try {
        switch (oi.getPrimitiveCategory()) {
        case BOOLEAN:
            boolean b = ((BooleanObjectInspector) oi).get(o);
            dos.writeBoolean(b);
            break;

        case BYTE:
            byte bt = ((ByteObjectInspector) oi).get(o);
            dos.writeByte(bt);
            break;

        case SHORT:
            short s = ((ShortObjectInspector) oi).get(o);
            dos.writeShort(s);
            break;

        case INT:
            int i = ((IntObjectInspector) oi).get(o);
            dos.writeInt(i);
            break;

        case LONG:
            long l = ((LongObjectInspector) oi).get(o);
            dos.writeLong(l);
            break;

        case FLOAT:
            float f = ((FloatObjectInspector) oi).get(o);
            dos.writeFloat(f);
            break;

        case DOUBLE:
            double d = ((DoubleObjectInspector) oi).get(o);
            dos.writeDouble(d);
            break;

        case BINARY: {
            BytesWritable bw = ((BinaryObjectInspector) oi).getPrimitiveWritableObject(o);
            out.write(bw.getBytes(), 0, bw.getLength());
            break;
        }

        default:
            throw new RuntimeException("Hive internal error.");
        }
    } finally {
        // closing the underlying ByteStream should have no effect, the data should still be
        // accessible
        dos.close();
    }
}