Example usage for java.io DataInputStream readByte

List of usage examples for java.io DataInputStream readByte

Introduction

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

Prototype

public final byte readByte() throws IOException 

Source Link

Document

See the general contract of the readByte method of DataInput.

Usage

From source file:org.apache.hadoop.hdfs.qjournal.client.URLLogInputStream.java

/**
 * Read the header of fsedit log/* w  w w . j  a  v  a  2  s  .c o m*/
 * @param in fsedit stream
 * @return the edit log version number
 * @throws IOException if error occurs
 */
static int readLogVersion(DataInputStream in) throws IOException, LogHeaderCorruptException {
    int logVersion = 0;
    // Read log file version. Could be missing.
    in.mark(4);
    // If edits log is greater than 2G, available method will return negative
    // numbers, so we avoid having to call available
    boolean available = true;
    try {
        logVersion = in.readByte();
    } catch (EOFException e) {
        available = false;
    }

    if (available) {
        in.reset();
        logVersion = in.readInt();
        if (logVersion < FSConstants.LAYOUT_VERSION) { // future version
            throw new LogHeaderCorruptException("Unexpected version of the file system log file: " + logVersion
                    + ". Current version = " + FSConstants.LAYOUT_VERSION + ".");
        }
    }
    return logVersion;
}

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

/**
 * @return A UNICODE string. A string object is stored as an INT (to store the string length) followed by the WCHAR
 *         array/*from w w  w  . j av  a2s.com*/
 *         (to store the string contents).
 *         (http://media.affymetrix.com/support/developer/powertools/changelog/gcos-agcc/generic.html)
 */
private static String readUnicodeString(DataInputStream str) throws IOException {
    int fieldLength = readIntBigEndian(str);

    // log.info( fieldLength );

    byte[] buf = new byte[fieldLength * 2];

    // StringBuilder buf = new StringBuilder();
    for (int i = 0; i < fieldLength * 2; i++) {
        buf[i] = str.readByte();
    }

    return new String(buf, "UTF-16");
}

From source file:tor.TorCrypto.java

/**
 * Parses a public key encoded as ASN.1//ww w  . j  a  v  a2  s .  c  o  m
 *
 * @param rsapublickey ASN.1 Encoded public key
 * @return PublicKey
 */
public static PublicKey asn1GetPublicKey(byte[] rsapublickey) {
    int blobsize = rsapublickey.length;
    DataInputStream dis = null;
    int jint = 0; // int to represent unsigned byte or unsigned short
    int datacount = 0;

    try {
        // --- Try to read the ANS.1 encoded RSAPublicKey blob -------------
        ByteArrayInputStream bis = new ByteArrayInputStream(rsapublickey);
        dis = new DataInputStream(bis);

        if (dis.readByte() != 0x30) // asn.1 encoded starts with 0x30
            return null;

        jint = dis.readUnsignedByte(); // asn.1 is 0x80 plus number of bytes
        // representing data count
        if (jint == 0x81)
            datacount = dis.readUnsignedByte(); // datalength is specified
        // in next byte.
        else if (jint == 0x82) // bytes count for any supported keysize
            // would be at most 2 bytes
            datacount = dis.readUnsignedShort(); // datalength is specified
        // in next 2 bytes
        else
            return null; // all supported publickey byte-sizes can be
        // specified in at most 2 bytes

        if ((jint - 0x80 + 2 + datacount) != blobsize) // sanity check for
            // correct number of
            // remaining bytes
            return null;

        //      System.out
        //         .println("\nRead outer sequence bytes; validated outer asn.1 consistency ");

        // ------- Next attempt to read Integer sequence for modulus ------
        if (dis.readUnsignedByte() != 0x02) // next byte read must be
            // Integer asn.1 specifier
            return null;
        jint = dis.readUnsignedByte(); // asn.1 is 0x80 plus number of bytes
        // representing data count
        if (jint == 0x81)
            datacount = dis.readUnsignedByte(); // datalength is specified
        // in next byte.
        else if (jint == 0x82) // bytes count for any supported keysize
            // would be at most 2 bytes
            datacount = dis.readUnsignedShort(); // datalength is specified
        // in next 2 bytes
        else
            return null; // all supported publickey modulus byte-sizes can
        // be specified in at most 2 bytes

        // ---- next bytes are big-endian ordered modulus -----
        byte[] modulus = new byte[datacount];
        int modbytes = dis.read(modulus);
        if (modbytes != datacount) // if we can read enought modulus bytes
            // ...
            return null;

        //System.out.println("Read modulus");

        // ------- Next attempt to read Integer sequence for public exponent
        // ------
        if (dis.readUnsignedByte() != 0x02) // next byte read must be
            // Integer asn.1 specifier
            return null;
        datacount = dis.readUnsignedByte(); // size of modulus is specified
        // in one byte
        byte[] exponent = new byte[datacount];
        int expbytes = dis.read(exponent);
        if (expbytes != datacount)
            return null;
        //System.out.println("Read exponent");

        // ----- Finally, create the PublicKey object from modulus and
        // public exponent --------
        RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(1, modulus),
                new BigInteger(1, exponent));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
        return pubKey;
    } catch (Exception exc) {
        return null;
    } finally {
        try {
            dis.close();
        } catch (Exception exc) {
            /* ignore */
            ;
        }
    }
}

From source file:r.base.Connections.java

public static byte[] decompress3(byte buffer[]) throws IOException, DataFormatException {
    DataInputStream in = new DataInputStream(new ByteArrayInputStream(buffer));
    int outlen = in.readInt();
    byte type = in.readByte();

    if (type == 'Z') {
        byte[] properties = Arrays.copyOfRange(buffer, 5, 10);
        ByteArrayInputStream bais = new ByteArrayInputStream(buffer, 10, buffer.length - 5);
        ByteArrayOutputStream baos = new ByteArrayOutputStream(outlen);
        LzmaDecoder decoder = new LzmaDecoder();

        decoder.SetDecoderProperties(properties);
        if (!decoder.Code(bais, baos, outlen)) {
            throw new IOException("LZMA decompression error");
        }/*from   w  w  w. ja v a2  s . c om*/

        return baos.toByteArray();
    }

    throw new EvalException("decompres3: type = " + (char) type);
    //
    // if (type == 'Z') {
    // lzma_stream strm = LZMA_STREAM_INIT;
    // lzma_ret ret;
    // init_filters();
    // ret = lzma_raw_decoder(&strm, filters);
    // if (ret != LZMA_OK) error("internal error %d in R_decompress3", ret);
    // strm.next_in = p + 5;
    // strm.avail_in = inlen - 5;
    // strm.next_out = buf;
    // strm.avail_out = outlen;
    // ret = lzma_code(&strm, LZMA_RUN);
    // if (ret != LZMA_OK && (strm.avail_in > 0))
    // error("internal error %d in R_decompress3 %d",
    // ret, strm.avail_in);
    // lzma_end(&strm);
    // } else if (type == '2') {
    // int res;
    // res = BZ2_bzBuffToBuffDecompress((char *)buf, &outlen,
    // (char *)(p + 5), inlen - 5, 0, 0);
    // if(res != BZ_OK) error("internal error %d in R_decompress2", res);
    // } else if (type == '1') {
    // uLong outl; int res;
    // res = uncompress(buf, &outl, (Bytef *)(p + 5), inlen - 5);
    // if(res != Z_OK) error("internal error %d in R_decompress1");
    // } else if (type == '0') {
    // buf = p + 5;
    // } else error("unknown type in R_decompress3");
    //

}

From source file:RealFunctionValidation.java

public static Object readAndWritePrimitiveValue(final DataInputStream in, final DataOutputStream out,
        final Class<?> type) throws IOException {

    if (!type.isPrimitive()) {
        throw new IllegalArgumentException("type must be primitive");
    }/*from  www.j  a  v a  2s. c  o m*/
    if (type.equals(Boolean.TYPE)) {
        final boolean x = in.readBoolean();
        out.writeBoolean(x);
        return Boolean.valueOf(x);
    } else if (type.equals(Byte.TYPE)) {
        final byte x = in.readByte();
        out.writeByte(x);
        return Byte.valueOf(x);
    } else if (type.equals(Character.TYPE)) {
        final char x = in.readChar();
        out.writeChar(x);
        return Character.valueOf(x);
    } else if (type.equals(Double.TYPE)) {
        final double x = in.readDouble();
        out.writeDouble(x);
        return Double.valueOf(x);
    } else if (type.equals(Float.TYPE)) {
        final float x = in.readFloat();
        out.writeFloat(x);
        return Float.valueOf(x);
    } else if (type.equals(Integer.TYPE)) {
        final int x = in.readInt();
        out.writeInt(x);
        return Integer.valueOf(x);
    } else if (type.equals(Long.TYPE)) {
        final long x = in.readLong();
        out.writeLong(x);
        return Long.valueOf(x);
    } else if (type.equals(Short.TYPE)) {
        final short x = in.readShort();
        out.writeShort(x);
        return Short.valueOf(x);
    } else {
        // This should never occur.
        throw new IllegalStateException();
    }
}

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

/**
 * The data is stored as a int, then the array of bytes.
 *//*from   ww  w.j  av  a2 s  .c  o  m*/
private static byte[] readBytes(DataInputStream str) throws IOException {
    int fieldLength = readIntBigEndian(str);

    byte[] result = new byte[fieldLength];
    for (int i = 0; i < fieldLength; i++) {
        if (str.available() == 0)
            throw new IOException("Reached end of file without string end");
        result[i] = str.readByte();
    }

    return result;
}

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

/**
 * @return A 1 byte character string. A string object is stored as an INT (to store the string length) followed by
 *         the CHAR/*  ww w. ja  v a 2 s .c om*/
 *         array (to store the string contents).
 */
private static String readString(DataInputStream str) throws IOException {
    int fieldLength = readIntBigEndian(str);
    StringBuilder buf = new StringBuilder();
    for (int i = 0; i < fieldLength; i++) {
        if (str.available() == 0)
            throw new IOException("Reached end of file without string end");
        buf.append(new String(new byte[] { str.readByte() }));
    }
    return buf.toString();
}

From source file:ClassFileUtilities.java

/**
 * Returns the dependencies of the given class.
 * @return a list of strings representing the used classes.
 *//*from w  w w.j  a  va2 s . com*/
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:clueweb09.WarcRecord.java

private static String readLineFromInputStream(DataInputStream in) throws IOException {
    StringBuilder retString = new StringBuilder();
    boolean found_cr = false;
    boolean keepReading = true;
    try {/* ww w . j  ava2s . co  m*/
        do {
            char thisChar = 0;
            byte readByte = in.readByte();
            // check to see if it's a multibyte character
            if ((readByte & MASK_THREE_BYTE_CHAR) == MASK_THREE_BYTE_CHAR) {
                found_cr = false;
                // need to read the next 2 bytes
                if (in.available() < 2) {
                    // treat these all as individual characters
                    retString.append((char) readByte);
                    int numAvailable = in.available();
                    for (int i = 0; i < numAvailable; i++) {
                        retString.append((char) (in.readByte()));
                    }
                    continue;
                }
                byte secondByte = in.readByte();
                byte thirdByte = in.readByte();
                // ensure the topmost bit is set
                if (((secondByte & MASK_TOPMOST_BIT) != MASK_TOPMOST_BIT)
                        || ((thirdByte & MASK_TOPMOST_BIT) != MASK_TOPMOST_BIT)) {
                    //treat these as individual characters
                    retString.append((char) readByte);
                    retString.append((char) secondByte);
                    retString.append((char) thirdByte);
                    continue;
                }
                int finalVal = (thirdByte & MASK_BOTTOM_FIVE_BITS) + 64 * (secondByte & MASK_BOTTOM_FIVE_BITS)
                        + 4096 * (readByte & MASK_BOTTOM_FOUR_BITS);
                thisChar = (char) finalVal;
            } else if ((readByte & MASK_TWO_BYTE_CHAR) == MASK_TWO_BYTE_CHAR) {
                found_cr = false;

                // need to read next byte
                if (in.available() < 1) {
                    // treat this as individual characters
                    retString.append((char) readByte);
                    continue;
                }
                byte secondByte = in.readByte();
                if ((secondByte & MASK_TOPMOST_BIT) != MASK_TOPMOST_BIT) {
                    retString.append((char) readByte);
                    retString.append((char) secondByte);
                    continue;
                }
                int finalVal = (secondByte & MASK_BOTTOM_FIVE_BITS) + 64 * (readByte & MASK_BOTTOM_SIX_BITS);
                thisChar = (char) finalVal;
            } else {
                // interpret it as a single byte
                thisChar = (char) readByte;
            }
            // Look for carriage return; if found set a flag
            if (thisChar == '\r') {
                found_cr = true;
            }
            if (thisChar == '\n') {
                // if the linefeed is the next character after the carriage return
                if (found_cr) {
                    LINE_ENDING = CR_NEWLINE;
                } else {
                    LINE_ENDING = NEWLINE;
                }
                keepReading = false;
            } else {
                retString.append(thisChar);
            }
        } while (keepReading);
    } catch (EOFException eofEx) {
        return null;
    }

    if (retString.length() == 0) {
        return "";
    }

    return retString.toString();
}

From source file:cwru.mjq.WarcRecord.java

private static String readLineFromInputStream(DataInputStream in) throws IOException {
    StringBuilder retString = new StringBuilder();
    boolean found_cr = false;
    boolean keepReading = true;
    try {//from w w w.  j  a va 2 s  .  c  o  m
        do {
            char thisChar;
            byte readByte = in.readByte();
            // check to see if it's a multibyte character
            if ((readByte & MASK_THREE_BYTE_CHAR) == MASK_THREE_BYTE_CHAR) {
                found_cr = false;
                // need to read the next 2 bytes
                if (in.available() < 2) {
                    // treat these all as individual characters
                    retString.append((char) readByte);
                    int numAvailable = in.available();
                    for (int i = 0; i < numAvailable; i++) {
                        retString.append((char) (in.readByte()));
                    }
                    continue;
                }
                byte secondByte = in.readByte();
                byte thirdByte = in.readByte();
                // ensure the topmost bit is set
                if (((secondByte & MASK_TOPMOST_BIT) != MASK_TOPMOST_BIT)
                        || ((thirdByte & MASK_TOPMOST_BIT) != MASK_TOPMOST_BIT)) {
                    // treat these as individual characters
                    retString.append((char) readByte);
                    retString.append((char) secondByte);
                    retString.append((char) thirdByte);
                    continue;
                }
                int finalVal = (thirdByte & MASK_BOTTOM_FIVE_BITS) + 64 * (secondByte & MASK_BOTTOM_FIVE_BITS)
                        + 4096 * (readByte & MASK_BOTTOM_FOUR_BITS);
                thisChar = (char) finalVal;
            } else if ((readByte & MASK_TWO_BYTE_CHAR) == MASK_TWO_BYTE_CHAR) {
                found_cr = false;

                // need to read next byte
                if (in.available() < 1) {
                    // treat this as individual characters
                    retString.append((char) readByte);
                    continue;
                }
                byte secondByte = in.readByte();
                if ((secondByte & MASK_TOPMOST_BIT) != MASK_TOPMOST_BIT) {
                    retString.append((char) readByte);
                    retString.append((char) secondByte);
                    continue;
                }
                int finalVal = (secondByte & MASK_BOTTOM_FIVE_BITS) + 64 * (readByte & MASK_BOTTOM_SIX_BITS);
                thisChar = (char) finalVal;
            } else {
                // interpret it as a single byte
                thisChar = (char) readByte;
            }
            // Look for carriage return; if found set a flag
            if (thisChar == '\r') {
                found_cr = true;
            }
            if (thisChar == '\n') {
                // if the linefeed is the next character after the carriage
                // return
                if (found_cr) {
                    LINE_ENDING = CR_NEWLINE;
                } else {
                    LINE_ENDING = NEWLINE;
                }
                keepReading = false;
            } else {
                retString.append(thisChar);
            }
        } while (keepReading);
    } catch (EOFException eofEx) {
        return null;
    }

    if (retString.length() == 0) {
        return "";
    }

    return retString.toString();
}