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:org.csc.phynixx.loggersystem.logrecord.XADataLogger.java

/**
 *
 * a new data record is created an added to dataRecorder
 *
 * @param dataRecorder//w w  w .  j  a  va 2  s  .c om
 *            DataRecorder that uses /operates on the current physical
 *            logger
 *
 * @param logRecordType
 * @param fieldData
 */
private void recoverData(PhynixxXADataRecorder dataRecorder, XALogRecordType logRecordType,
        byte[][] fieldData) {
    if (LOGGER.isDebugEnabled()) {
        if (fieldData == null || fieldData.length == 0) {
            throw new IllegalArgumentException("Record fields are empty");
        }
    }
    // field 0 is header
    byte[] headerData = fieldData[0];
    DataInputStream io = new DataInputStream(new ByteArrayInputStream(headerData));
    try {
        // redundant , just read it an skip
        io.readLong();

        int ordinal = io.readInt();
        byte[][] content = null;

        if (fieldData.length > 1) {
            content = new byte[fieldData.length - 1][];
            for (int i = 0; i < fieldData.length - 1; i++) {
                content[i] = fieldData[i + 1];
            }
        } else {
            content = new byte[][] {};
        }

        PhynixxDataRecord msg = new PhynixxDataRecord(dataRecorder.getXADataRecorderId(), ordinal,
                logRecordType, content);
        dataRecorder.addMessage(msg);

    } catch (Exception e) {
        throw new DelegatedRuntimeException(e);
    } finally {
        if (io != null) {
            IOUtils.closeQuietly(io);
        }
    }
}

From source file:com.facebook.infrastructure.db.SuperColumn.java

public void skip(DataInputStream dis) throws IOException {
    defreezeSuperColumn(dis);//from w w  w. j a v a  2  s  .c o m
    /* read the number of columns stored */
    dis.readInt();
    /* read the size of all columns to skip */
    int size = dis.readInt();
    dis.skip(size);
}

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

private SuperColumn defreezeSuperColumn(DataInputStream dis) throws IOException {
    String name = dis.readUTF();/*from  ww  w  . j  av  a2 s  .co m*/
    SuperColumn superColumn = new SuperColumn(name);
    superColumn.markForDeleteAt(dis.readInt(), dis.readLong());
    return superColumn;
}

From source file:WriteReadMixedDataTypesExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);/*ww  w. j a va2 s  .c om*/
        notifyDestroyed();
    } else if (command == start) {
        try {
            recordstore = RecordStore.openRecordStore("myRecordStore", true);
        } catch (Exception error) {
            alert = new Alert("Error Creating", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            byte[] outputRecord;
            String outputString = "First Record";
            int outputInteger = 15;
            boolean outputBoolean = true;
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            DataOutputStream outputDataStream = new DataOutputStream(outputStream);
            outputDataStream.writeUTF(outputString);
            outputDataStream.writeBoolean(outputBoolean);
            outputDataStream.writeInt(outputInteger);
            outputDataStream.flush();
            outputRecord = outputStream.toByteArray();
            recordstore.addRecord(outputRecord, 0, outputRecord.length);
            outputStream.reset();
            outputStream.close();
            outputDataStream.close();
        } catch (Exception error) {
            alert = new Alert("Error Writing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            String inputString = null;
            int inputInteger = 0;
            boolean inputBoolean = false;
            byte[] byteInputData = new byte[100];
            ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
            DataInputStream inputDataStream = new DataInputStream(inputStream);
            for (int x = 1; x <= recordstore.getNumRecords(); x++) {
                recordstore.getRecord(x, byteInputData, 0);
                inputString = inputDataStream.readUTF();
                inputBoolean = inputDataStream.readBoolean();
                inputInteger = inputDataStream.readInt();
                inputStream.reset();
            }
            inputStream.close();
            inputDataStream.close();
            alert = new Alert("Reading", inputString + " " + inputInteger + " " + inputBoolean, null,
                    AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        } catch (Exception error) {
            alert = new Alert("Error Reading", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            recordstore.closeRecordStore();
        } catch (Exception error) {
            alert = new Alert("Error Closing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        if (RecordStore.listRecordStores() != null) {
            try {
                RecordStore.deleteRecordStore("myRecordStore");
            } catch (Exception error) {
                alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING);
                alert.setTimeout(Alert.FOREVER);
                display.setCurrent(alert);
            }
        }
    }
}

From source file:com.facebook.infrastructure.db.Column.java

public void skip(DataInputStream dis) throws IOException {
    /* read the column name */
    dis.readUTF();/*from w ww.  ja v a 2s  .  c  o m*/
    /* boolean indicating if the column is deleted */
    dis.readBoolean();
    /* timestamp associated with the column */
    dis.readLong();
    /* size of the column */
    int size = dis.readInt();
    dis.skip(size);
}

From source file:com.msopentech.thali.utilities.universal.HttpKeySocksProxyClientConnOperator.java

@Override
public void openConnection(final OperatedClientConnection conn, final HttpHost target, final InetAddress local,
        final HttpContext context, final HttpParams params) throws IOException {
    Socket socket = null;/*from   w  w  w.  ja v  a  2 s . c om*/
    Socket sslSocket = null;
    try {
        if (conn == null || target == null || params == null) {
            throw new IllegalArgumentException("Required argument may not be null");
        }
        if (conn.isOpen()) {
            throw new IllegalStateException("Connection must not be open");
        }

        // The original NetCipher code uses a SchemeSocketFactory class that isn't supported by the version
        // of Apache that ships standard with Android. It also doesn't support the layered socket factory
        // interface either. We work around this later on but for now we just get our HttpKeySSLSocketFactory
        Scheme scheme = schemeRegistry.getScheme(target.getSchemeName());
        HttpKeySSLSocketFactory httpKeySSLSocketFactory = (HttpKeySSLSocketFactory) scheme.getSocketFactory();

        int port = scheme.resolvePort(target.getPort());
        String host = target.getHostName();

        // Perform explicit SOCKS4a connection request. SOCKS4a supports remote host name resolution
        // (i.e., Tor resolves the hostname, which may be an onion address).
        // The Android (Apache Harmony) Socket class appears to support only SOCKS4 and throws an
        // exception on an address created using INetAddress.createUnresolved() -- so the typical
        // technique for using Java SOCKS4a/5 doesn't appear to work on Android:
        // https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/java/net/PlainSocketImpl.java
        // See also: http://www.mit.edu/~foley/TinFoil/src/tinfoil/TorLib.java, for a similar implementation

        // From http://en.wikipedia.org/wiki/SOCKS#SOCKS4a:
        //
        // field 1: SOCKS version number, 1 byte, must be 0x04 for this version
        // field 2: command code, 1 byte:
        //     0x01 = establish a TCP/IP stream connection
        //     0x02 = establish a TCP/IP port binding
        // field 3: network byte order port number, 2 bytes
        // field 4: deliberate invalid IP address, 4 bytes, first three must be 0x00 and the last one must not be 0x00
        // field 5: the user ID string, variable length, terminated with a null (0x00)
        // field 6: the domain name of the host we want to contact, variable length, terminated with a null (0x00)

        socket = new Socket();
        conn.opening(socket, target);
        socket.setSoTimeout(READ_TIMEOUT_MILLISECONDS);
        socket.connect(proxy.address(), CONNECT_TIMEOUT_MILLISECONDS);

        DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
        outputStream.write((byte) 0x04);
        outputStream.write((byte) 0x01);
        outputStream.writeShort((short) port);
        outputStream.writeInt(0x01);
        outputStream.write((byte) 0x00);
        outputStream.write(host.getBytes());
        outputStream.write((byte) 0x00);

        DataInputStream inputStream = new DataInputStream(socket.getInputStream());
        if (inputStream.readByte() != (byte) 0x00 || inputStream.readByte() != (byte) 0x5a) {
            throw new IOException("SOCKS4a connect failed");
        }
        inputStream.readShort();
        inputStream.readInt();

        // In the NetCipher code we cast to SchemeLayeredSocketFactory and call createLayeredSocket which amongst
        // other things takes 'params' as an argument. But none of this is supported in Android. When I looked in
        // Java at what createLayeredSocket was actually doing it was just calling createSocket with exactly the
        // arguments used below (it ignored params completely). So we should be good.
        sslSocket = ((HttpKeySSLSocketFactory) httpKeySSLSocketFactory).createSocket(socket, host, port, true);
        conn.opening(sslSocket, target);
        sslSocket.setSoTimeout(READ_TIMEOUT_MILLISECONDS);
        prepareSocket(sslSocket, context, params);
        conn.openCompleted(httpKeySSLSocketFactory.isSecure(sslSocket), params);
        // TODO: clarify which connection throws java.net.SocketTimeoutException?
    } catch (IOException e) {
        try {
            if (sslSocket != null) {
                sslSocket.close();
            }
            if (socket != null) {
                socket.close();
            }
        } catch (IOException ioe) {
        }
        throw e;
    }
}

From source file:com.facebook.infrastructure.db.SuperColumn.java

private void fillSuperColumn(IColumn superColumn, DataInputStream dis) throws IOException {
    if (dis.available() == 0)
        return;/*from w w w. java2s. c  om*/

    /* read the number of columns */
    int size = dis.readInt();
    /* read the size of all columns */
    dis.readInt();
    for (int i = 0; i < size; ++i) {
        IColumn subColumn = Column.serializer().deserialize(dis);
        superColumn.addColumn(subColumn.name(), subColumn);
    }
}

From source file:RMSGameScores.java

public int compare(byte[] rec1, byte[] rec2) {

    // Construct DataInputStreams for extracting the scores from
    // the records.
    ByteArrayInputStream bais1 = new ByteArrayInputStream(rec1);
    DataInputStream inputStream1 = new DataInputStream(bais1);
    ByteArrayInputStream bais2 = new ByteArrayInputStream(rec2);
    DataInputStream inputStream2 = new DataInputStream(bais2);
    int score1 = 0;
    int score2 = 0;
    try {//ww w. j a va2 s .  co  m
        // Extract the scores.
        score1 = inputStream1.readInt();
        score2 = inputStream2.readInt();
    } catch (EOFException eofe) {
        System.out.println(eofe);
        eofe.printStackTrace();
    } catch (IOException eofe) {
        System.out.println(eofe);
        eofe.printStackTrace();
    }

    // Sort by score
    if (score1 > score2) {
        return RecordComparator.FOLLOWS;
    } else if (score1 < score2) {
        return RecordComparator.PRECEDES;
    } else {
        return RecordComparator.EQUIVALENT;
    }
}

From source file:org.outerrim.snippad.ui.swt.dnd.WikiTransfer.java

/**
 * Reads and returns a single WikiWord from the given stream.
 *
 * @param parent//  w w  w  . j av  a2  s.  c  o  m
 *            Parent word
 * @param dataIn
 *            Stream to read the data from
 * @return The WikiWord contained in the data stream
 * @throws IOException
 */
private WikiWord readWikiWord(final WikiWord parent, final DataInputStream dataIn) throws IOException {
    /*
     * Serialization format is as follows: (String) name of the word
     * (String) wiki text (int) number of child words (WikiWord) child 1 ...
     * repeat for each child
     */
    String title = dataIn.readUTF();
    String text = dataIn.readUTF();
    int n = dataIn.readInt();
    LOG.debug(title + " has " + n + " children");
    WikiWord newParent = new WikiWord(title, text);
    newParent.setParent(parent);

    for (int i = 0; i < n; ++i) {
        readWikiWord(newParent, dataIn);
    }

    return newParent;
}

From source file:org.apache.hadoop.hdfs.tools.offlineImageViewer.OfflineImageDecompressor.java

/**
 * Process image file.//from  www  . j  a  va2 s  . co m
 */
private void go() throws IOException {
    long start = System.currentTimeMillis();
    System.out.println("Decompressing image file: " + inputFile + " to " + outputFile);
    DataInputStream in = null;
    DataOutputStream out = null;

    try {
        // setup in
        PositionTrackingInputStream ptis = new PositionTrackingInputStream(
                new FileInputStream(new File(inputFile)));
        in = new DataInputStream(ptis);

        // read header information
        int imgVersion = in.readInt();
        if (!LayoutVersion.supports(Feature.FSIMAGE_COMPRESSION, imgVersion)) {
            System.out.println("Image is not compressed. No output will be produced.");
            return;
        }
        int namespaceId = in.readInt();
        long numFiles = in.readLong();
        long genstamp = in.readLong();

        long imgTxId = -1;
        if (LayoutVersion.supports(Feature.STORED_TXIDS, imgVersion)) {
            imgTxId = in.readLong();
        }
        FSImageCompression compression = FSImageCompression.readCompressionHeader(new Configuration(), in);
        if (compression.isNoOpCompression()) {
            System.out.println("Image is not compressed. No output will be produced.");
            return;
        }
        in = BufferedByteInputStream.wrapInputStream(compression.unwrapInputStream(in),
                FSImage.LOAD_SAVE_BUFFER_SIZE, FSImage.LOAD_SAVE_CHUNK_SIZE);
        System.out.println("Starting decompression.");

        // setup output
        out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outputFile)));

        // write back the uncompressed information
        out.writeInt(imgVersion);
        out.writeInt(namespaceId);
        out.writeLong(numFiles);
        out.writeLong(genstamp);
        if (LayoutVersion.supports(Feature.STORED_TXIDS, imgVersion)) {
            out.writeLong(imgTxId);
        }
        // no compression
        out.writeBoolean(false);

        // copy the data
        long size = new File(inputFile).length();
        // read in 1MB chunks
        byte[] block = new byte[1024 * 1024];
        while (true) {
            int bytesRead = in.read(block);
            if (bytesRead <= 0)
                break;
            out.write(block, 0, bytesRead);
            printProgress(ptis.getPos(), size);
        }

        out.close();

        long stop = System.currentTimeMillis();
        System.out.println("Input file : " + inputFile + " size: " + size);
        System.out.println("Output file: " + outputFile + " size: " + new File(outputFile).length());
        System.out.println("Decompression completed in " + (stop - start) + " ms.");
    } finally {
        if (in != null)
            in.close();
        if (out != null)
            out.close();
    }
}