Example usage for java.io DataInputStream readUnsignedByte

List of usage examples for java.io DataInputStream readUnsignedByte

Introduction

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

Prototype

public final int readUnsignedByte() throws IOException 

Source Link

Document

See the general contract of the readUnsignedByte method of DataInput.

Usage

From source file:bobs.is.compress.sevenzip.SevenZFile.java

private Archive readHeaders(final byte[] password) throws IOException {
    final byte[] signature = new byte[6];
    file.readFully(signature);/*w ww.j  a  v a 2s . co m*/
    if (!Arrays.equals(signature, sevenZSignature)) {
        throw new IOException("Bad 7z signature");
    }
    // 7zFormat.txt has it wrong - it's first major then minor
    final byte archiveVersionMajor = file.readByte();
    final byte archiveVersionMinor = file.readByte();
    if (archiveVersionMajor != 0) {
        throw new IOException(
                String.format("Unsupported 7z version (%d,%d)", archiveVersionMajor, archiveVersionMinor));
    }

    final long startHeaderCrc = 0xffffFFFFL & Integer.reverseBytes(file.readInt());
    final StartHeader startHeader = readStartHeader(startHeaderCrc);

    final int nextHeaderSizeInt = (int) startHeader.nextHeaderSize;
    if (nextHeaderSizeInt != startHeader.nextHeaderSize) {
        throw new IOException("cannot handle nextHeaderSize " + startHeader.nextHeaderSize);
    }
    file.seek(SIGNATURE_HEADER_SIZE + startHeader.nextHeaderOffset);
    final byte[] nextHeader = new byte[nextHeaderSizeInt];
    file.readFully(nextHeader);
    final CRC32 crc = new CRC32();
    crc.update(nextHeader);
    if (startHeader.nextHeaderCrc != crc.getValue()) {
        throw new IOException("NextHeader CRC mismatch");
    }

    final ByteArrayInputStream byteStream = new ByteArrayInputStream(nextHeader);
    DataInputStream nextHeaderInputStream = new DataInputStream(byteStream);
    Archive archive = new Archive();
    int nid = nextHeaderInputStream.readUnsignedByte();
    if (nid == NID.kEncodedHeader) {
        nextHeaderInputStream = readEncodedHeader(nextHeaderInputStream, archive, password);
        // Archive gets rebuilt with the new header
        archive = new Archive();
        nid = nextHeaderInputStream.readUnsignedByte();
    }
    if (nid == NID.kHeader) {
        readHeader(nextHeaderInputStream, archive);
        nextHeaderInputStream.close();
    } else {
        throw new IOException("Broken or unsupported archive: no Header");
    }
    return archive;
}

From source file:com.ocpsoft.pretty.faces.config.annotation.ByteCodeAnnotationFilter.java

/**
 * <p>//ww  w.  j a v a  2 s.c  om
 * Checks whether that supplied {@link InputStream} contains a Java class
 * file that might contain PrettyFaces annotations.
 * </p>
 * <p>
 * The caller of this method is responsible to close the supplied
 * {@link InputStream}. This method won't do it!
 * </p>
 * 
 * @param classFileStream
 *           The stream to read the class file from.
 * @return <code>true</code> for files that should be further checked for
 *         annotations
 * @throws IOException
 *            for any kind of IO problem
 */
@SuppressWarnings("unused")
public boolean accept(InputStream classFileStream) throws IOException {

    // open a DataInputStream
    DataInputStream in = new DataInputStream(classFileStream);

    // read magic and abort if it doesn't match
    int magic = in.readInt();
    if (magic != CLASS_FILE_MAGIC) {
        if (log.isDebugEnabled()) {
            log.debug("Magic not found! Not a valid class file!");
        }
        return false;
    }

    // check for at least JDK 1.5
    int minor = in.readUnsignedShort();
    int major = in.readUnsignedShort();
    if (major < 49) {
        // JDK 1.4 or less
        if (log.isTraceEnabled()) {
            log.trace("Not a JDK5 class! It cannot contain annotations!");
        }
        return false;
    }

    // this values is equal to the number entries in the constants pool + 1
    int constantPoolEntries = in.readUnsignedShort() - 1;

    // loop over all entries in the constants pool
    for (int i = 0; i < constantPoolEntries; i++) {

        // the tag to identify the record type
        int tag = in.readUnsignedByte();

        // process record according to its type
        switch (tag) {

        case CONSTANT_Class:
            /*
             * CONSTANT_Class_info { 
             *   u1 tag; 
             *   u2 name_index; 
             * }
             */
            in.readUnsignedShort();
            break;

        case CONSTANT_Fieldref:
        case CONSTANT_Methodref:
        case CONSTANT_InterfaceMethodref:
            /*
             * CONSTANT_[Fieldref|Methodref|InterfaceMethodref]_info { 
             *   u1 tag; 
             *   u2 class_index; 
             *   u2 name_and_type_index; 
             * }
             */
            in.readUnsignedShort();
            in.readUnsignedShort();
            break;

        case CONSTANT_String:
            /*
             * CONSTANT_String_info { 
             *   u1 tag; 
             *   u2 string_index; 
             * }
             */
            in.readUnsignedShort();
            break;

        case CONSTANT_Integer:
        case CONSTANT_Float:
            /*
             * CONSTANT_[Integer|Float]_info { 
             *   u1 tag; 
             *   u4 bytes; 
             * }
             */
            in.readInt();
            break;

        case CONSTANT_Long:
        case CONSTANT_Double:

            /*
             * CONSTANT_Long_info { 
             *   u1 tag; 
             *   u4 high_bytes; 
             *   u4 low_bytes; 
             * }
             */
            in.readLong();

            /*
             * We must increase the constant pool index because this tag
             * type takes two entries
             */
            i++;

            break;

        case CONSTANT_NameAndType:
            /*
             * CONSTANT_NameAndType_info { 
             *   u1 tag; 
             *   u2 name_index; 
             *   u2 descriptor_index; 
             * }
             */
            in.readUnsignedShort();
            in.readUnsignedShort();
            break;

        case CONSTANT_Utf8:
            /*
             * CONSTANT_Utf8_info { 
             *   u1 tag; 
             *   u2 length; 
             *   u1 bytes[length]; 
             * }
             */
            String str = in.readUTF();

            // check if this string sounds interesting
            if (str.contains(SEARCH_STRING)) {
                if (log.isTraceEnabled()) {
                    log.trace("Found PrettyFaces annotation reference in constant pool: " + str);
                }
                return true;
            }
            break;

        default:
            /*
             * Unknown tag! Should not happen! We will scan the class in this case.
             */
            if (log.isDebugEnabled()) {
                log.debug("Unknown constant pool tag found: " + tag);
            }
            return true;
        }
    }

    /*
     * We are finished with reading the interesting parts of the class file.
     * We stop here because the file doesn't seem to be interesting.
     */
    if (log.isTraceEnabled()) {
        log.trace("No reference to PrettyFaces annotations found!");
    }
    return false;

}

From source file:org.apache.fop.fonts.type1.PFBParser.java

/**
 * Parses a PFB file into a PFBData object.
 * @param in InputStream to load the PFB file from
 * @return PFBData memory representation of the font
 * @throws IOException In case of an I/O problem
 *///w  w  w . j  av a 2s. c  om
public PFBData parsePFB(InputStream in) throws IOException {
    PFBData pfb = new PFBData();
    BufferedInputStream bin = new BufferedInputStream(in);
    DataInputStream din = new DataInputStream(bin);
    din.mark(32);
    int firstByte = din.readUnsignedByte();
    din.reset();
    if (firstByte == 128) {
        pfb.setPFBFormat(PFBData.PFB_PC);
        parsePCFormat(pfb, din);
    } else {
        pfb.setPFBFormat(PFBData.PFB_RAW);
        parseRAWFormat(pfb, bin);
    }
    return pfb;
}

From source file:org.apache.fop.fonts.type1.PFBParser.java

private void parsePCFormat(PFBData pfb, DataInputStream din) throws IOException {
    int segmentHead;
    int segmentType;
    int bytesRead;

    //Read first segment
    segmentHead = din.readUnsignedByte();
    if (segmentHead != 128) {
        throw new IOException("Invalid file format. Expected ASCII 80hex");
    }//  www  .j  av a  2  s.  co  m
    segmentType = din.readUnsignedByte(); //Read
    int len1 = swapInteger(din.readInt());
    byte[] headerSegment = new byte[len1];
    din.readFully(headerSegment);
    pfb.setHeaderSegment(headerSegment);

    //Read second segment
    segmentHead = din.readUnsignedByte();
    if (segmentHead != 128) {
        throw new IOException("Invalid file format. Expected ASCII 80hex");
    }
    segmentType = din.readUnsignedByte();
    int len2 = swapInteger(din.readInt());
    byte[] encryptedSegment = new byte[len2];
    din.readFully(encryptedSegment);
    pfb.setEncryptedSegment(encryptedSegment);

    //Read third segment
    segmentHead = din.readUnsignedByte();
    if (segmentHead != 128) {
        throw new IOException("Invalid file format. Expected ASCII 80hex");
    }
    segmentType = din.readUnsignedByte();
    int len3 = swapInteger(din.readInt());
    byte[] trailerSegment = new byte[len3];
    din.readFully(trailerSegment);
    pfb.setTrailerSegment(trailerSegment);

    //Read EOF indicator
    segmentHead = din.readUnsignedByte();
    if (segmentHead != 128) {
        throw new IOException("Invalid file format. Expected ASCII 80hex");
    }
    segmentType = din.readUnsignedByte();
    if (segmentType != 3) {
        throw new IOException("Expected segment type 3, but found: " + segmentType);
    }
}

From source file:tor.TorCrypto.java

/**
 * Parses a public key encoded as ASN.1//  w w  w .ja  va2 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:ubic.gemma.analysis.preprocess.batcheffects.AffyScanDateExtractor.java

private int readUnsignedByteLittleEndian(DataInputStream dis) throws IOException {
    return dis.readUnsignedByte();
}

From source file:ubic.gemma.core.analysis.preprocess.batcheffects.AffyScanDateExtractor.java

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

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

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

From source file:ubic.gemma.image.aba.AllenBrainAtlasServiceImpl.java

private void transferData(DataInputStream in, OutputStream out) throws IOException {
    // This is whacked. There must be a better way than throwing an exception.
    boolean EOF = false;
    while (!EOF) {
        try {/*  www .j  ava 2  s  . c o  m*/
            out.write(in.readUnsignedByte());
        } catch (EOFException eof) {
            EOF = true;
        }
    }
}

From source file:VASSAL.tools.imports.adc2.MapBoard.java

/**
 * Read primary and secondary symbol information. Each hex may only have one of each. Additional symbols must
 * be tertiary attributes./* www .j  a  va2  s. co  m*/
 */
protected void readHexDataBlock(DataInputStream in) throws IOException {
    ADC2Utils.readBlockHeader(in, "Hex Data");

    int count = getNColumns() * getNRows();

    for (int i = 0; i < count; ++i) {
        // primary symbol
        int symbolIndex = ADC2Utils.readBase250Word(in);
        SymbolSet.SymbolData symbol = getSet().getMapBoardSymbol(symbolIndex);
        if (symbol != null)
            primaryMapBoardSymbols.add(new HexData(i, symbol));

        // secondary symbol
        symbolIndex = ADC2Utils.readBase250Word(in);
        symbol = getSet().getMapBoardSymbol(symbolIndex);
        if (symbol != null)
            secondaryMapBoardSymbols.add(new HexData(i, symbol));

        /* int elevation = */ ADC2Utils.readBase250Word(in);

        // flags for hexsides, lines, and placenames: completely ignored
        /* int additionalInformation = */ in.readUnsignedByte();
    }
}