Example usage for java.io DataInputStream readShort

List of usage examples for java.io DataInputStream readShort

Introduction

In this page you can find the example usage for java.io DataInputStream readShort.

Prototype

public final short readShort() throws IOException 

Source Link

Document

See the general contract of the readShort method of DataInput.

Usage

From source file:com.zack6849.alphabot.api.Utils.java

public static String checkServerStatus(InetAddress i, int port) {
    String returns = "Error.";
    try {/*from ww w .j ava2  s.c o m*/
        //wow...i never actually used the port argument?
        Socket s = new Socket(i, port);
        DataInputStream SS_BF = new DataInputStream(s.getInputStream());
        DataOutputStream d = new DataOutputStream(s.getOutputStream());
        d.write(new byte[] { (byte) 0xFE, (byte) 0x01 });
        SS_BF.readByte();
        short length = SS_BF.readShort();
        StringBuilder sb = new StringBuilder();
        for (int in = 0; in < length; in++) {
            char ch = SS_BF.readChar();
            sb.append(ch);
        }
        String all = sb.toString().trim();
        System.out.println(all);
        String[] args1 = all.split("\u0000");
        if (args1[3].contains("")) {
            returns = "MOTD: " + args1[3].replaceAll("[a-m]", "").replaceAll("[1234567890]", "")
                    + "   players: [" + args1[4] + "/" + args1[5] + "]";
        } else {
            returns = "MOTD: " + args1[3] + "   players: [" + args1[4] + "/" + args1[5] + "]";
        }
    } catch (UnknownHostException e1) {
        returns = "the host you specified is unknown. check your settings.";
    } catch (IOException e1) {
        returns = "sorry, we couldn't reach this server, make sure that the server is up and has query enabled.";
    }
    return returns;
}

From source file:ubic.gemma.core.loader.expression.arrayDesign.AffyChipTypeExtractor.java

private static int readShort(DataInputStream dis) throws IOException {
    return dis.readShort();
}

From source file:ClassFileUtilities.java

/**
 * Returns the dependencies of the given class.
 * @return a list of strings representing the used classes.
 *//*  w w  w  . ja v a  2s . c o m*/
public static Set getClassDependencies(InputStream is) throws IOException {
    DataInputStream dis = new DataInputStream(is);

    if (dis.readInt() != 0xcafebabe) {
        throw new IOException("Invalid classfile");
    }

    dis.readInt();

    int len = dis.readShort();
    String[] strs = new String[len];
    Set classes = new HashSet();
    Set desc = new HashSet();

    for (int i = 1; i < len; i++) {
        int constCode = dis.readByte() & 0xff;
        switch (constCode) {
        case CONSTANT_LONG_INFO:
        case CONSTANT_DOUBLE_INFO:
            dis.readLong();
            i++;
            break;

        case CONSTANT_FIELDREF_INFO:
        case CONSTANT_METHODREF_INFO:
        case CONSTANT_INTERFACEMETHODREF_INFO:
        case CONSTANT_INTEGER_INFO:
        case CONSTANT_FLOAT_INFO:
            dis.readInt();
            break;

        case CONSTANT_CLASS_INFO:
            classes.add(new Integer(dis.readShort() & 0xffff));
            break;

        case CONSTANT_STRING_INFO:
            dis.readShort();
            break;

        case CONSTANT_NAMEANDTYPE_INFO:
            dis.readShort();
            desc.add(new Integer(dis.readShort() & 0xffff));
            break;

        case CONSTANT_UTF8_INFO:
            strs[i] = dis.readUTF();
            break;

        default:
            throw new RuntimeException("unexpected data in constant-pool:" + constCode);
        }
    }

    Set result = new HashSet();

    Iterator it = classes.iterator();
    while (it.hasNext()) {
        result.add(strs[((Integer) it.next()).intValue()]);
    }

    it = desc.iterator();
    while (it.hasNext()) {
        result.addAll(getDescriptorClasses(strs[((Integer) it.next()).intValue()]));
    }

    return result;
}

From source file:Messenger.TorLib.java

/**
 * This method opens a TOR socket, and does an anonymous DNS resolve through it.
 * Since Tor caches things, this is a very fast lookup if we've already connected there
 * The resolve does a gethostbyname() on the exit node.
 * @param targetHostname String containing the hostname to look up.
 * @return String representation of the IP address: "x.x.x.x"
 *//*from  ww w  . j  a  va2  s .  c  o  m*/
static String TorResolve(String targetHostname) {
    int targetPort = 0; // we dont need a port to resolve

    try {
        Socket s = TorSocketPre(targetHostname, targetPort, TOR_RESOLVE);
        DataInputStream is = new DataInputStream(s.getInputStream());

        byte version = is.readByte();
        byte status = is.readByte();
        if (status != (byte) 90) {
            //failed for some reason, return useful exception
            throw (new IOException(ParseSOCKSStatus(status)));
        }
        int port = is.readShort();
        byte[] ipAddrBytes = new byte[4];
        is.read(ipAddrBytes);
        InetAddress ia = InetAddress.getByAddress(ipAddrBytes);
        //System.out.println("Resolved into:"+ia);
        is.close();
        String addr = ia.toString().substring(1); // clip off the "/"
        return (addr);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return (null);
}

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

/**
 * Deserializes a <code>PropertyState</code> object from the given binary
 * <code>stream</code>. Binary values are retrieved from the specified
 * <code>BLOBStore</code>./*from  ww w  .ja  v a2s.c  o  m*/
 *
 * @param state     <code>state</code> to deserialize
 * @param stream    the stream where the <code>state</code> should be
 *                  deserialized from
 * @param blobStore handler for BLOB data
 * @throws Exception if an error occurs during the deserialization
 * @see #serialize(PropertyState, OutputStream, BLOBStore)
 */
public static void deserialize(PropertyState state, InputStream stream, BLOBStore blobStore) throws Exception {
    DataInputStream in = new DataInputStream(stream);

    // type
    int type = in.readInt();
    state.setType(type);
    // multiValued
    boolean multiValued = in.readBoolean();
    state.setMultiValued(multiValued);
    // definitionId
    in.readUTF();
    // modCount
    short modCount = in.readShort();
    state.setModCount(modCount);
    // values
    int count = in.readInt(); // count
    InternalValue[] values = new InternalValue[count];
    for (int i = 0; i < count; i++) {
        InternalValue val;
        if (type == PropertyType.BINARY) {
            String s = in.readUTF(); // value (i.e. blobId)
            // special handling required for binary value:
            // the value stores the id of the BLOB data
            // in the BLOB store
            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(s);
                val = InternalValue.create(fsRes);
            } else {
                InputStream is = blobStore.get(s);
                try {
                    val = InternalValue.create(is);
                } finally {
                    try {
                        is.close();
                    } catch (IOException e) {
                        // ignore
                    }
                }
            }
        } else {
            /**
             * because writeUTF(String) has a size limit of 65k,
             * Strings are serialized as <length><byte[]>
             */
            //s = in.readUTF();   // value
            int len = in.readInt(); // lenght of byte[]
            byte[] bytes = new byte[len];
            in.readFully(bytes); // byte[]
            String s = new String(bytes, ENCODING);
            val = InternalValue.valueOf(s, type);
        }
        values[i] = val;
    }
    state.setValues(values);
}

From source file:Messenger.TorLib.java

/**
 * This method creates a socket to the target host and port using TorSocketPre, then reads
 * the SOCKS information./*from w  ww  . j  a v a 2  s .  c om*/
 * @param targetHostname Hostname of destination host.
 * @param targetPort Port on remote destination host.
 * @return Fully initialized TCP Socket that tunnels to the target Host/Port via the Tor Proxy host/port.
 * @throws IOException when Socket and Read/Write exceptions occur.
 */
static Socket TorSocket(String targetHostname, int targetPort) throws IOException {
    Socket s = TorSocketPre(targetHostname, targetPort, TOR_CONNECT);
    DataInputStream is = new DataInputStream(s.getInputStream());

    // only the status is useful on a TOR CONNECT
    byte version = is.readByte();
    byte status = is.readByte();
    if (status != (byte) 90) {
        //failed for some reason, return useful exception
        throw (new IOException(ParseSOCKSStatus(status)));
    }
    //      System.out.println("status: "+ParseSOCKSStatus(status));
    int port = is.readShort();
    int ipAddr = is.readInt();
    return (s);
}

From source file:dualcontrol.CryptoClientDemo.java

private void call(Properties properties, MockableConsole console, String hostAddress, int port, byte[] data)
        throws Exception {
    Socket socket = SSLContexts.create(false, "cryptoclient.ssl", properties, console).getSocketFactory()
            .createSocket(hostAddress, port);
    DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
    dos.writeShort(data.length);// w  w  w.j  a v a  2 s . co  m
    dos.write(data);
    dos.flush();
    DataInputStream dis = new DataInputStream(socket.getInputStream());
    byte[] ivBytes = new byte[dis.readShort()];
    dis.readFully(ivBytes);
    byte[] bytes = new byte[dis.readShort()];
    dis.readFully(bytes);
    if (new String(data).contains("DECRYPT")) {
        System.err.printf("INFO CryptoClientDemo decrypted %s\n", new String(bytes));
    } else {
        System.out.printf("%s:%s\n", Base64.encodeBase64String(ivBytes), Base64.encodeBase64String(bytes));
    }
    socket.close();
}

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

/**
 * Deserializes a <code>NodeState</code> object from the given binary
 * <code>stream</code>.// ww  w  .  ja  v  a2 s .  co  m
 *
 * @param state  <code>state</code> to deserialize
 * @param stream the stream where the <code>state</code> should be deserialized from
 * @throws Exception if an error occurs during the deserialization
 * @see #serialize(NodeState, OutputStream)
 */
public static void deserialize(NodeState state, InputStream stream) throws Exception {
    DataInputStream in = new DataInputStream(stream);

    // primaryType
    String s = in.readUTF();
    state.setNodeTypeName(NameFactoryImpl.getInstance().create(s));
    // parentUUID (may be null)
    byte[] uuidBytes = new byte[NodeId.UUID_BYTE_LENGTH];
    in.readFully(uuidBytes);
    if (!Arrays.equals(uuidBytes, NULL_UUID_PLACEHOLDER_BYTES)) {
        state.setParentId(new NodeId(uuidBytes));
    }
    // definitionId
    in.readUTF();
    // mixin types
    int count = in.readInt(); // count
    Set<Name> set = new HashSet<Name>(count);
    for (int i = 0; i < count; i++) {
        set.add(NameFactoryImpl.getInstance().create(in.readUTF()));
    }
    if (set.size() > 0) {
        state.setMixinTypeNames(set);
    }
    // modCount
    short modCount = in.readShort();
    state.setModCount(modCount);
    // properties (names)
    count = in.readInt(); // count
    for (int i = 0; i < count; i++) {
        state.addPropertyName(NameFactoryImpl.getInstance().create(in.readUTF())); // name
    }
    // child nodes (list of name/uuid pairs)
    count = in.readInt(); // count
    for (int i = 0; i < count; i++) {
        Name name = NameFactoryImpl.getInstance().create(in.readUTF()); // name
        // uuid
        in.readFully(uuidBytes);
        state.addChildNodeEntry(name, new NodeId(uuidBytes));
    }
}

From source file:dualcontrol.CryptoHandler.java

public void handle(DualControlKeyStoreSession dualControl, Socket socket) throws Exception {
    try {/*  w w w  .  j a  v a 2 s .c o  m*/
        this.dualControl = dualControl;
        DataInputStream dis = new DataInputStream(socket.getInputStream());
        int length = dis.readShort();
        byte[] bytes = new byte[length];
        dis.readFully(bytes);
        String data = new String(bytes);
        String[] fields = data.split(":");
        String mode = fields[0];
        String alias = fields[1];
        this.dos = new DataOutputStream(socket.getOutputStream());
        if (mode.equals("GETKEY")) {
            if (enableGetKey) {
                SecretKey key = dualControl.loadKey(alias);
                dos.writeUTF(key.getAlgorithm());
                write(key.getEncoded());
            }
        } else {
            cipher(mode, alias, fields[2], fields[3], fields[4]);
        }
    } finally {
        dos.close();
    }
}

From source file:com.github.ambry.commons.BlobId.java

/**
 * Re-constructs existing blobId by deserializing from data input stream
 *
 * @param stream from which to deserialize the blobid
 * @param clusterMap of the cluster that the blob id belongs to
 * @throws IOException//from  w  ww .java  2s  .com
 */
public BlobId(DataInputStream stream, ClusterMap clusterMap) throws IOException {
    this.version = stream.readShort();
    if (version == 1) {
        this.partitionId = clusterMap.getPartitionIdFromStream(stream);
        uuid = Utils.readIntString(stream);
    } else {
        throw new IllegalArgumentException("version " + version + " not supported for blob id");
    }
}