Example usage for java.io DataInputStream readInt

List of usage examples for java.io DataInputStream readInt

Introduction

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

Prototype

public final int readInt() throws IOException 

Source Link

Document

See the general contract of the readInt method of DataInput.

Usage

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

/**
 * <p>//from  w ww  .  j a  v  a2 s.co m
 * 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:edu.cornell.med.icb.goby.alignments.perms.PermutationReader.java

private void makeIndex(FastBufferedInputStream inputStream) throws IOException {
    input.position(0);/*from w  ww.  j  a  v  a 2s.  c  o  m*/
    final ObjectArrayList<Block> blocks = new ObjectArrayList<Block>();

    final DataInputStream dataInput = new DataInputStream(
            new FastBufferedInputStream(new FileInputStream(basename + ".perm")));
    try {
        long offset = 0;

        while (dataInput.available() > 0) {

            final Block block = new Block();
            block.offset = offset;
            block.n = dataInput.readInt();
            block.firstSmallIndex = dataInput.readInt();
            dataInput.skip(block.n * 4L);
            blocks.add(block);
            offset += block.n * 4L + 8L;
        }
        Collections.sort(blocks, SMALL_INDEX_COMPARATOR);
        indexBlocks = blocks.toArray(new Block[blocks.size()]);
    } finally {
        dataInput.close();
    }
}

From source file:org.carbondata.query.util.CacheUtil.java

public static int getMaxValueFromLevelFile(String filesLocaton) {
    if (null == filesLocaton) {
        return 0;
    }//  www  .j  a  v  a  2 s  .  c  o m
    DataInputStream fileChannel = null;
    try {
        if (!FileFactory.isFileExist(filesLocaton, FileFactory.getFileType(filesLocaton))) {
            return 0;
        }
        fileChannel = new DataInputStream(
                FileFactory.getDataInputStream(filesLocaton, FileFactory.getFileType(filesLocaton), 10240));
        CarbonFile memberFile = FileFactory.getCarbonFile(filesLocaton, FileFactory.getFileType(filesLocaton));
        long size = memberFile.getSize() - 4;
        long skipSize = size;
        long actualSkipSize = 0;
        while (actualSkipSize != size) {
            actualSkipSize += fileChannel.skip(skipSize);
            skipSize = skipSize - actualSkipSize;
        }
        LOGGER.debug("Bytes skipped " + skipSize);
        int maxVal = fileChannel.readInt();
        return maxVal;

    } catch (IOException e) {
        //            e.printStackTrace();
        LOGGER.error(e, e.getMessage());
    } finally {
        CarbonUtil.closeStreams(fileChannel);
    }
    return 0;
}

From source file:org.apache.hadoop.yarn.server.timeline.recovery.LeveldbTimelineStateStore.java

private void loadLatestSequenceNumber(TimelineServiceState state) throws IOException {
    byte[] data = null;
    try {/*from   w w w  .  j  a v a 2  s .  c o  m*/
        data = db.get(LATEST_SEQUENCE_NUMBER_KEY);
    } catch (DBException e) {
        throw new IOException(e);
    }
    if (data != null) {
        DataInputStream in = new DataInputStream(new ByteArrayInputStream(data));
        try {
            state.latestSequenceNumber = in.readInt();
        } finally {
            IOUtils.cleanup(LOG, in);
        }
    }
}

From source file:org.openxdata.server.servlet.WMDownloadServlet.java

private void downloadStudies(HttpServletResponse response) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);
    formDownloadService.downloadStudies(dos, "", "");
    baos.flush();/*from  www .ja v a2 s.  c o m*/
    dos.flush();
    byte[] data = baos.toByteArray();
    baos.close();
    dos.close();

    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));

    PrintWriter out = response.getWriter();
    out.println("<StudyList>");

    try {
        @SuppressWarnings("unused")
        byte size = dis.readByte(); //reads the size of the studies

        while (true) {
            String value = "<study id=\"" + dis.readInt() + "\" name=\"" + dis.readUTF() + "\"/>";
            out.println(value);
        }
    } catch (EOFException exe) {
        //exe.printStackTrace();
    }
    out.println("</StudyList>");
    out.flush();
    dis.close();
}

From source file:org.openamf.io.AMFDeserializer.java

/**
 * This is a hacked verison of Java's DataInputStream.readUTF(), which only
 * supports Strings <= 65535 UTF-8-encoded characters
 *///w w w.ja  v  a 2s  .  c  om
private Object readLongUTF(DataInputStream in) throws IOException {
    int utflen = in.readInt();
    StringBuffer str = new StringBuffer(utflen);
    byte bytearr[] = new byte[utflen];
    int c, char2, char3;
    int count = 0;

    in.readFully(bytearr, 0, utflen);

    while (count < utflen) {
        c = (int) bytearr[count] & 0xff;
        switch (c >> 4) {
        case 0:
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
            /* 0xxxxxxx*/
            count++;
            str.append((char) c);
            break;
        case 12:
        case 13:
            /* 110x xxxx   10xx xxxx*/
            count += 2;
            if (count > utflen)
                throw new UTFDataFormatException();
            char2 = (int) bytearr[count - 1];
            if ((char2 & 0xC0) != 0x80)
                throw new UTFDataFormatException();
            str.append((char) (((c & 0x1F) << 6) | (char2 & 0x3F)));
            break;
        case 14:
            /* 1110 xxxx  10xx xxxx  10xx xxxx */
            count += 3;
            if (count > utflen)
                throw new UTFDataFormatException();
            char2 = (int) bytearr[count - 2];
            char3 = (int) bytearr[count - 1];
            if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80))
                throw new UTFDataFormatException();
            str.append((char) (((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0)));
            break;
        default:
            /* 10xx xxxx,  1111 xxxx */
            throw new UTFDataFormatException();
        }
    }

    // The number of chars produced may be less than utflen
    return new String(str);
}

From source file:org.apache.cassandra.db.SuperColumn.java

private void fillSuperColumn(IColumn superColumn, DataInputStream dis) throws IOException {
    assert dis.available() != 0;

    /* read the number of columns */
    int size = dis.readInt();
    /* read the size of all columns */
    dis.readInt();//w  ww.j  a v a  2  s  .  c  o  m
    for (int i = 0; i < size; ++i) {
        IColumn subColumn = Column.serializer().deserialize(dis);
        superColumn.addColumn(subColumn.name(), subColumn);
    }
}

From source file:org.apache.xmlgraphics.image.loader.impl.ImageLoaderRawJPEG.java

/** {@inheritDoc} */
public Image loadImage(ImageInfo info, Map hints, ImageSessionContext session)
        throws ImageException, IOException {
    if (!MimeConstants.MIME_JPEG.equals(info.getMimeType())) {
        throw new IllegalArgumentException(
                "ImageInfo must be from a image with MIME type: " + MimeConstants.MIME_JPEG);
    }/*from  w  ww.  j av  a 2 s .co m*/

    ColorSpace colorSpace = null;
    boolean appeFound = false;
    int sofType = 0;
    ByteArrayOutputStream iccStream = null;

    Source src = session.needSource(info.getOriginalURI());
    ImageInputStream in = ImageUtil.needImageInputStream(src);
    JPEGFile jpeg = new JPEGFile(in);
    in.mark();
    try {
        outer: while (true) {
            int reclen;
            int segID = jpeg.readMarkerSegment();
            if (log.isTraceEnabled()) {
                log.trace("Seg Marker: " + Integer.toHexString(segID));
            }
            switch (segID) {
            case EOI:
                log.trace("EOI found. Stopping.");
                break outer;
            case SOS:
                log.trace("SOS found. Stopping early."); //TODO Not sure if this is safe
                break outer;
            case SOI:
            case NULL:
                break;
            case SOF0: //baseline
            case SOF1: //extended sequential DCT
            case SOF2: //progressive (since PDF 1.3)
            case SOFA: //progressive (since PDF 1.3)
                sofType = segID;
                if (log.isTraceEnabled()) {
                    log.trace("SOF: " + Integer.toHexString(sofType));
                }
                in.mark();
                try {
                    reclen = jpeg.readSegmentLength();
                    in.skipBytes(1); //data precision
                    in.skipBytes(2); //height
                    in.skipBytes(2); //width
                    int numComponents = in.readUnsignedByte();
                    if (numComponents == 1) {
                        colorSpace = ColorSpace.getInstance(ColorSpace.CS_GRAY);
                    } else if (numComponents == 3) {
                        colorSpace = ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB);
                    } else if (numComponents == 4) {
                        colorSpace = DeviceCMYKColorSpace.getInstance();
                    } else {
                        throw new ImageException("Unsupported ColorSpace for image " + info
                                + ". The number of components supported are 1, 3 and 4.");
                    }
                } finally {
                    in.reset();
                }
                in.skipBytes(reclen);
                break;
            case APP2: //ICC (see ICC1V42.pdf)
                in.mark();
                try {
                    reclen = jpeg.readSegmentLength();
                    // Check for ICC profile
                    byte[] iccString = new byte[11];
                    in.readFully(iccString);
                    in.skipBytes(1); //string terminator (null byte)

                    if ("ICC_PROFILE".equals(new String(iccString, "US-ASCII"))) {
                        in.skipBytes(2); //chunk sequence number and total number of chunks
                        int payloadSize = reclen - 2 - 12 - 2;
                        if (ignoreColorProfile(hints)) {
                            log.debug("Ignoring ICC profile data in JPEG");
                            in.skipBytes(payloadSize);
                        } else {
                            byte[] buf = new byte[payloadSize];
                            in.readFully(buf);
                            if (iccStream == null) {
                                if (log.isDebugEnabled()) {
                                    log.debug("JPEG has an ICC profile");
                                    DataInputStream din = new DataInputStream(new ByteArrayInputStream(buf));
                                    log.debug("Declared ICC profile size: " + din.readInt());
                                }
                                //ICC profiles can be split into several chunks
                                //so collect in a byte array output stream
                                iccStream = new ByteArrayOutputStream();
                            }
                            iccStream.write(buf);
                        }
                    }
                } finally {
                    in.reset();
                }
                in.skipBytes(reclen);
                break;
            case APPE: //Adobe-specific (see 5116.DCT_Filter.pdf)
                in.mark();
                try {
                    reclen = jpeg.readSegmentLength();
                    // Check for Adobe header
                    byte[] adobeHeader = new byte[5];
                    in.readFully(adobeHeader);

                    if ("Adobe".equals(new String(adobeHeader, "US-ASCII"))) {
                        // The reason for reading the APPE marker is that Adobe Photoshop
                        // generates CMYK JPEGs with inverted values. The correct thing
                        // to do would be to interpret the values in the marker, but for now
                        // only assume that if APPE marker is present and colorspace is CMYK,
                        // the image is inverted.
                        appeFound = true;
                    }
                } finally {
                    in.reset();
                }
                in.skipBytes(reclen);
                break;
            default:
                jpeg.skipCurrentMarkerSegment();
            }
        }
    } finally {
        in.reset();
    }

    ICC_Profile iccProfile = buildICCProfile(info, colorSpace, iccStream);
    if (iccProfile == null && colorSpace == null) {
        throw new ImageException("ColorSpace could not be identified for JPEG image " + info);
    }

    boolean invertImage = false;
    if (appeFound && colorSpace.getType() == ColorSpace.TYPE_CMYK) {
        if (log.isDebugEnabled()) {
            log.debug("JPEG has an Adobe APPE marker. Note: CMYK Image will be inverted. ("
                    + info.getOriginalURI() + ")");
        }
        invertImage = true;
    }

    ImageRawJPEG rawImage = new ImageRawJPEG(info, ImageUtil.needInputStream(src), sofType, colorSpace,
            iccProfile, invertImage);
    return rawImage;
}

From source file:com.exadel.flamingo.flex.messaging.amf.io.AMF0Deserializer.java

/**
 * This is a hacked verison of Java's DataInputStream.readUTF(), which only
 * supports Strings <= 65535 UTF-8-encoded characters
 *///from   w  w  w . jav  a  2s.  co m
private Object readLongUTF(DataInputStream in) throws IOException {
    int utflen = in.readInt();
    StringBuffer str = new StringBuffer(utflen);
    byte bytearr[] = new byte[utflen];
    int c, char2, char3;
    int count = 0;

    in.readFully(bytearr, 0, utflen);

    while (count < utflen) {
        c = bytearr[count] & 0xff;
        switch (c >> 4) {
        case 0:
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
            /* 0xxxxxxx*/
            count++;
            str.append((char) c);
            break;
        case 12:
        case 13:
            /* 110x xxxx   10xx xxxx*/
            count += 2;
            if (count > utflen)
                throw new UTFDataFormatException();
            char2 = bytearr[count - 1];
            if ((char2 & 0xC0) != 0x80)
                throw new UTFDataFormatException();
            str.append((char) (((c & 0x1F) << 6) | (char2 & 0x3F)));
            break;
        case 14:
            /* 1110 xxxx  10xx xxxx  10xx xxxx */
            count += 3;
            if (count > utflen)
                throw new UTFDataFormatException();
            char2 = bytearr[count - 2];
            char3 = bytearr[count - 1];
            if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80))
                throw new UTFDataFormatException();
            str.append((char) (((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0)));
            break;
        default:
            /* 10xx xxxx,  1111 xxxx */
            throw new UTFDataFormatException();
        }
    }

    // The number of chars produced may be less than utflen
    return new String(str);
}

From source file:com.sky.drovik.player.media.DiskCache.java

private void loadIndex() {
    final String indexFilePath = getIndexFilePath();
    try {// w  w w  .jav a2 s .  co  m
        // Open the input stream.
        final FileInputStream fileInput = new FileInputStream(indexFilePath);
        final BufferedInputStream bufferedInput = new BufferedInputStream(fileInput, 1024);
        final DataInputStream dataInput = new DataInputStream(bufferedInput);

        // Read the header.
        final int magic = dataInput.readInt();
        final int version = dataInput.readInt();
        boolean valid = true;
        if (magic != INDEX_HEADER_MAGIC) {
            Log.e(TAG, "Index file appears to be corrupt (" + magic + " != " + INDEX_HEADER_MAGIC + "), "
                    + indexFilePath);
            valid = false;
        }
        if (valid && version != INDEX_HEADER_VERSION) {
            // Future versions can implement upgrade in this case.
            Log.e(TAG, "Index file version " + version + " not supported");
            valid = false;
        }
        if (valid) {
            mTailChunk = dataInput.readShort();
        }

        // Read the entries.
        if (valid) {
            // Parse the index file body into the in-memory map.
            final int numEntries = dataInput.readInt();
            mIndexMap = new LongSparseArray<Record>(numEntries);
            synchronized (mIndexMap) {
                for (int i = 0; i < numEntries; ++i) {
                    final long key = dataInput.readLong();
                    final int chunk = dataInput.readShort();
                    final int offset = dataInput.readInt();
                    final int size = dataInput.readInt();
                    final int sizeOnDisk = dataInput.readInt();
                    final long timestamp = dataInput.readLong();
                    mIndexMap.append(key, new Record(chunk, offset, size, sizeOnDisk, timestamp));
                }
            }
        }

        dataInput.close();
        if (!valid) {
            deleteAll();
        }

    } catch (FileNotFoundException e) {
        // If the file does not exist the cache is empty, so just continue.
    } catch (IOException e) {
        Log.e(TAG, "Unable to read the index file " + indexFilePath);
    } finally {
        if (mIndexMap == null) {
            mIndexMap = new LongSparseArray<Record>();
        }
    }
}