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:Main.java

public static byte[] getBodyBytes(String ip, String port, String key)
        throws NumberFormatException, IOException {

    String[] ipArr = ip.split("\\.");
    byte[] ipByte = new byte[4];
    ipByte[0] = (byte) (Integer.parseInt(ipArr[0]) & 0xFF);
    ipByte[1] = (byte) (Integer.parseInt(ipArr[1]) & 0xFF);
    ipByte[2] = (byte) (Integer.parseInt(ipArr[2]) & 0xFF);
    ipByte[3] = (byte) (Integer.parseInt(ipArr[3]) & 0xFF);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);
    dos.write(ipByte);//from   w  w w  .ja  v  a2  s.com
    dos.writeShort(Short.parseShort(port));
    dos.writeByte(key.getBytes().length);
    dos.write(key.getBytes());
    byte[] bs = baos.toByteArray();
    baos.close();
    dos.close();

    return bs;
}

From source file:org.apache.hadoop.hdfs.server.datanode.BlockMetadataHeader.java

/**
 * This writes all the fields till the beginning of checksum.
 * @param out DataOutputStream// w w  w . jav a 2  s. co  m
 * @throws IOException
 */
@VisibleForTesting
public static void writeHeader(DataOutputStream out, BlockMetadataHeader header) throws IOException {
    out.writeShort(header.getVersion());
    header.getChecksum().writeHeader(out);
}

From source file:com.fullhousedev.globalchat.bukkit.PluginMessageManager.java

public static void sendRawMessage(String subChannel, String serverName, byte[] message, Plugin pl) {
    ByteArrayOutputStream b = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(b);

    try {//ww w .ja v  a2 s  .c  om
        out.writeUTF("Forward");
        out.writeUTF(serverName);
        out.writeUTF(subChannel);

        out.writeShort(message.length);
        out.write(message);
    } catch (IOException ex) {
        Logger.getLogger(GlobalChat.class.getName()).log(Level.SEVERE, null, ex);
    }

    Player p = Bukkit.getOnlinePlayers()[0];

    p.sendPluginMessage(pl, "BungeeCord", b.toByteArray());
}

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

@Deprecated
public final static byte[] generateData(int id, int expire, byte[] token, byte[] payload) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream os = new DataOutputStream(bos);
    try {/*from  w  w w  . j  a va  2  s  .c o  m*/
        os.writeByte(Command.SEND);
        os.writeInt(id);
        os.writeInt(expire);
        os.writeShort(token.length);
        os.write(token);
        os.writeShort(payload.length);
        os.write(payload);
        os.flush();
        return bos.toByteArray();
    } catch (IOException e) {
        e.printStackTrace();
    }
    throw new RuntimeException();
}

From source file:Main.java

protected static void serialiseLength(DataOutputStream os, int len, int max_length)

        throws IOException {
    if (len > max_length) {

        throw (new IOException("Invalid DHT data length: max=" + max_length + ",actual=" + len));
    }// w  w w  .  j  ava 2s. c  o  m

    if (max_length < 256) {

        os.writeByte(len);

    } else if (max_length < 65536) {

        os.writeShort(len);

    } else {

        os.writeInt(len);
    }
}

From source file:net.datenwerke.transloader.primitive.WrapperConverter.java

private static void write(Object wrapper, DataOutputStream dataStream) throws IOException {
    char typeCode = getTypeCode(wrapper);
    switch (typeCode) {
    case 'B':
        dataStream.writeByte(intValue(wrapper));
        break;/*from   w  ww  . j  a va2s .c  o  m*/
    case 'C':
        dataStream.writeChar(charValue(wrapper));
        break;
    case 'S':
        dataStream.writeShort(intValue(wrapper));
        break;
    case 'I':
        dataStream.writeInt(intValue(wrapper));
        break;
    case 'J':
        dataStream.writeLong(number(wrapper).longValue());
        break;
    case 'F':
        dataStream.writeFloat(number(wrapper).floatValue());
        break;
    case 'D':
        dataStream.writeDouble(number(wrapper).doubleValue());
        break;
    case 'Z':
        dataStream.writeBoolean(booleanValue(wrapper));
    }
}

From source file:Messenger.TorLib.java

/**
 *  This method Creates a socket, then sends the inital SOCKS request info
 *  It stops before reading so that other methods may
 *  differently interpret the results.  It returns the open socket.
 *
 * @param targetHostname The hostname of the destination host.
 * @param targetPort The port to connect to
 * @param req SOCKS/TOR request code/*w w w .ja  v  a2  s. c  om*/
 * @return An open Socket that has been sent the SOCK4a init codes.
 * @throws IOException from any Socket problems
 */
static Socket TorSocketPre(String targetHostname, int targetPort, byte req) throws IOException {

    Socket s;
    //      System.out.println("Opening connection to "+targetHostname+":"+targetPort+
    //            " via proxy "+proxyAddr+":"+proxyPort+" of type "+req);
    s = new Socket(proxyAddr, proxyPort);
    DataOutputStream os = new DataOutputStream(s.getOutputStream());
    os.writeByte(SOCKS_VERSION);
    os.writeByte(req);
    // 2 bytes
    os.writeShort(targetPort);
    // 4 bytes, high byte first
    os.writeInt(SOCKS4A_FAKEIP);
    os.writeByte(SOCKS_DELIM);
    os.writeBytes(targetHostname);
    os.writeByte(SOCKS_DELIM);
    return (s);
}

From source file:HexUtil.java

/**
  * Write a (reasonably short) BigInteger to a stream.
  * @param integer the BigInteger to write
  * @param out the stream to write it to
  *//*from   w w  w.j a va 2s  .  c o  m*/
public static void writeBigInteger(BigInteger integer, DataOutputStream out) throws IOException {
    if (integer.signum() == -1) {
        //dump("Negative BigInteger", Logger.ERROR, true);
        throw new IllegalStateException("Negative BigInteger!");
    }
    byte[] buf = integer.toByteArray();
    if (buf.length > Short.MAX_VALUE)
        throw new IllegalStateException("Too long: " + buf.length);
    out.writeShort((short) buf.length);
    out.write(buf);
}

From source file:truelauncher.client.auth.Type2.java

protected static void writeAuthPacket(DataOutputStream dos, PlayerAuthData padata) throws IOException {
    ///*w  w  w .  j  ava 2s .  c  o m*/
    //fake 1.7.2 handshake packet format.
    //host = authpacket(AuthConnector + nick + token + password)
    //

    //create frame buffer
    ByteArrayOutputStream frame = new ByteArrayOutputStream();
    DataOutputStream frameOut = new DataOutputStream(frame);
    String authpacket = "AuthConnector|" + padata.getNick() + "|" + padata.getToken() + "|"
            + padata.getPassword();
    //write handshake packet to frame
    //write packet id
    writeVarInt(frameOut, 0x00);
    //write protocolVersion
    writeVarInt(frameOut, padata.getProtocolVersion());
    //write authpacket instead of hostname
    writeString(frameOut, authpacket);
    //write port
    frameOut.writeShort(padata.getPort());
    //write state
    writeVarInt(frameOut, 2);
    //now write frame to real socket
    //write length
    writeVarInt(dos, frame.size());
    //write packet
    frame.writeTo(dos);
    frame.reset();
    //close frames
    frameOut.close();
    frame.close();
}

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

/**
 * Serializes the specified <code>PropertyState</code> object to the given
 * binary <code>stream</code>. Binary values are stored in the specified
 * <code>BLOBStore</code>./*from  w  w w .j  av  a 2s .co  m*/
 *
 * @param state     <code>state</code> to serialize
 * @param stream    the stream where the <code>state</code> should be
 *                  serialized to
 * @param blobStore handler for BLOB data
 * @throws Exception if an error occurs during the serialization
 * @see #deserialize(PropertyState, InputStream,BLOBStore)
 */
public static void serialize(PropertyState state, OutputStream stream, BLOBStore blobStore) throws Exception {
    DataOutputStream out = new DataOutputStream(stream);

    // type
    out.writeInt(state.getType());
    // multiValued
    out.writeBoolean(state.isMultiValued());
    // definitionId
    out.writeUTF("");
    // modCount
    out.writeShort(state.getModCount());
    // values
    InternalValue[] values = state.getValues();
    out.writeInt(values.length); // count
    for (int i = 0; i < values.length; i++) {
        InternalValue val = values[i];
        if (state.getType() == PropertyType.BINARY) {
            // special handling required for binary value:
            // put binary value in BLOB store
            InputStream in = val.getStream();
            String blobId = blobStore.createId(state.getPropertyId(), i);
            try {
                blobStore.put(blobId, in, val.getLength());
            } finally {
                IOUtils.closeQuietly(in);
            }
            // store id of BLOB as property value
            out.writeUTF(blobId); // value
            // replace value instance with value backed by resource
            // in BLOB store and discard old value instance (e.g. temp file)
            if (blobStore instanceof ResourceBasedBLOBStore) {
                // optimization: if the BLOB store is resource-based
                // retrieve the resource directly rather than having
                // to read the BLOB from an input stream
                FileSystemResource fsRes = ((ResourceBasedBLOBStore) blobStore).getResource(blobId);
                values[i] = InternalValue.create(fsRes);
            } else {
                in = blobStore.get(blobId);
                try {
                    values[i] = InternalValue.create(in);
                } finally {
                    IOUtils.closeQuietly(in);
                }
            }
            val.discard();
        } else {
            /**
             * because writeUTF(String) has a size limit of 65k,
             * Strings are serialized as <length><byte[]>
             */
            //out.writeUTF(val.toString());   // value
            byte[] bytes = val.toString().getBytes(ENCODING);
            out.writeInt(bytes.length); // lenght of byte[]
            out.write(bytes); // byte[]
        }
    }
}