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:org.apache.hadoop.hdfs.server.datanode.TestSimulatedFSDataset.java

@Test
public void testGetMetaData() throws IOException {
    final SimulatedFSDataset fsdataset = getSimulatedFSDataset();
    ExtendedBlock b = new ExtendedBlock(bpid, 1, 5, 0);
    try {/*from  w ww  .  jav a 2 s . co  m*/
        assertTrue(fsdataset.getMetaDataInputStream(b) == null);
        assertTrue("Expected an IO exception", false);
    } catch (IOException e) {
        // ok - as expected
    }
    addSomeBlocks(fsdataset); // Only need to add one but ....
    b = new ExtendedBlock(bpid, 1, 0, 0);
    InputStream metaInput = fsdataset.getMetaDataInputStream(b);
    DataInputStream metaDataInput = new DataInputStream(metaInput);
    short version = metaDataInput.readShort();
    assertEquals(BlockMetadataHeader.VERSION, version);
    DataChecksum checksum = DataChecksum.newDataChecksum(metaDataInput);
    assertEquals(DataChecksum.Type.NULL, checksum.getChecksumType());
    assertEquals(0, checksum.getChecksumSize());
}

From source file:com.jivesoftware.os.amza.service.replication.http.endpoints.AmzaReplicationRestEndpoints.java

@POST
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Path("/ackBatch")
public Response ackBatch(InputStream is) {
    try {//w w w  .  j a v a 2s . c  om

        DataInputStream in = new DataInputStream(is);
        try {

            while (in.readByte() == 1) {

                int length = in.readShort();
                byte[] bytes = new byte[length];
                in.readFully(bytes);
                VersionedPartitionName versionedPartitionName = amzaInterner.internVersionedPartitionName(bytes,
                        0, length);

                length = in.readShort();
                bytes = new byte[length];
                in.readFully(bytes);
                RingMember ringMember = amzaInterner.internRingMember(bytes, 0, length);

                long takeSessionId = in.readLong();
                long takeSharedKey = in.readLong();
                long txId = in.readLong();
                long leadershipToken = in.readLong();

                amzaInstance.rowsTaken(ringMember, takeSessionId, takeSharedKey, versionedPartitionName, txId,
                        leadershipToken);

            }

            if (in.readByte() == 1) {
                int length = in.readShort();
                byte[] bytes = new byte[length];
                in.readFully(bytes);
                RingMember ringMember = amzaInterner.internRingMember(bytes, 0, length);

                long takeSessionId = in.readLong();
                long takeSharedKey = in.readLong();

                amzaInstance.pong(ringMember, takeSessionId, takeSharedKey);
            }

            return Response.ok(conf.asByteArray(Boolean.TRUE)).build();

        } finally {
            try {
                in.close();
            } catch (Exception x) {
                LOG.error("Failed to close input stream", x);
            }
        }

    } catch (Exception x) {
        LOG.warn("Failed ackBatch", x);
        return ResponseHelper.INSTANCE.errorResponse("Failed ackBatch.", x);
    } finally {
        amzaStats.pongsReceived.increment();
    }
}

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  ww  . ja v  a  2  s .  c o m
    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.igormaznitsa.jhexed.hexmap.HexFieldLayer.java

public HexFieldLayer(final InputStream in) throws IOException {
    final DataInputStream din = in instanceof DataInputStream ? (DataInputStream) in : new DataInputStream(in);
    this.name = din.readUTF();
    this.comments = din.readUTF();

    final int valuesNum = din.readShort() & 0xFFFF;
    for (int i = 0; i < valuesNum; i++) {
        final HexFieldValue value = HexFieldValue.readValue(in);
        value.setIndex(i);/*  ww w .  j  a  v a 2 s.c  o m*/
        this.values.add(value);
    }

    this.columns = din.readInt();
    this.rows = din.readInt();
    this.visible = din.readBoolean();

    final byte[] packedLayerData = new byte[din.readInt()];
    IOUtils.readFully(din, packedLayerData);
    this.array = Utils.unpackArray(packedLayerData);

    if (this.array.length != (this.columns * this.rows))
        throw new IOException("Wrong field size");
}

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 w  w w.  jav a  2  s  .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:com.github.ambry.commons.BlobIdTest.java

/**
 * Gets the version number from a blobId string.
 * @param blobId The blobId string to get version number.
 * @return Version number//from   ww w  . ja v a 2s. com
 * @throws Exception Any unexpected exception.
 */
private short getVersionFromBlobString(String blobId) throws Exception {
    DataInputStream dis = new DataInputStream(
            new ByteBufferInputStream(ByteBuffer.wrap(Base64.decodeBase64(blobId))));
    try {
        return dis.readShort();
    } finally {
        dis.close();
    }
}

From source file:edu.msu.cme.rdp.readseq.readers.core.SFFCore.java

public ReadBlock readReadBlock() throws IOException {
    try {/* w  w w.  j a  va 2 s  .c o m*/
        DataInput seqFile = super.getDataInput();

        ReadBlock ret = new ReadBlock();

        /*
         * READ BLOCK HEADER
         */

        ret.headerLength = seqFile.readShort();
        ret.nameLength = seqFile.readShort();

        int tmp = (ret.headerLength << 16) | ret.nameLength;
        if (tmp == mftMagicNumber) { //We ended up in the index...certainly possible
            return null;
        }

        ret.numBases = seqFile.readInt();
        ret.clipQualLeft = seqFile.readUnsignedShort();
        ret.clipQualRight = seqFile.readUnsignedShort();
        ret.clipAdapterLeft = seqFile.readUnsignedShort();
        ret.clipAdapterRight = seqFile.readUnsignedShort();

        byte[] readName = new byte[ret.nameLength];
        super.read(readName);

        int dataOffset = ret.headerLength - (ret.nameLength + READ_BLOCK_STATIC_SIZE);
        if (dataOffset < 0) {
            throw new IOException("Illegal ReadBlock header length (" + ret.headerLength
                    + "), it would have me seek back in to the readblock");
        }

        seqFile.skipBytes(dataOffset);

        /*
         * READ BLOCK DATA
         */

        byte[] flowgramIndex = new byte[ret.numBases];
        byte[] bases = new byte[ret.numBases];
        byte[] quality = new byte[ret.numBases];

        byte[] homopolymerStretchEstimates = new byte[(commonHeader.flowLength) * 2];

        super.read(homopolymerStretchEstimates);
        super.read(flowgramIndex);
        super.read(bases);
        super.read(quality);

        DataInputStream flowgramStream = new DataInputStream(
                new ByteArrayInputStream(homopolymerStretchEstimates));

        short[] flowgrams = new short[commonHeader.flowLength];
        for (int index = 0; index < commonHeader.flowLength; index++) {
            flowgrams[index] = flowgramStream.readShort();
        }
        flowgramStream.close();

        ret.name = new String(readName);
        ret.flowgrams = flowgrams;
        ret.flowIndex = flowgramIndex;
        ret.seq = new String(bases);
        ret.qual = quality;
        int bytesRead = homopolymerStretchEstimates.length + flowgramIndex.length + bases.length
                + quality.length;

        alignToBoundary(bytesRead);

        return ret;
    } catch (EOFException e) {
        return null;
    }
}

From source file:fr.noop.subtitle.stl.StlParser.java

private StlTti readTti(DataInputStream dis, StlGsi gsi) throws IOException, InvalidTimeRangeException {
    // Get charset from gsi
    String charset = gsi.getCct().getCharset();

    // Get frame rate from gsi
    int frameRate = gsi.getDfc().getFrameRate();

    // Read and extract metadata from TTI block
    // Each TTI block is 128 bytes long
    StlTti tti = new StlTti();

    // Read Subtitle Group Number (SGN)
    tti.setSgn((short) dis.readUnsignedByte());

    // Read Subtitle Number (SN)
    tti.setSn(Short.reverseBytes(dis.readShort()));

    // Read Extension Block Number (EBN)
    tti.setEbn((short) dis.readUnsignedByte());

    // Read Cumulative Status (CS)
    tti.setCs((short) dis.readUnsignedByte());

    // Read Time Code In (TCI)
    tti.setTci(this.readTimeCode(dis, frameRate));

    // Read Time Code Out (TCO)
    tti.setTco(this.readTimeCode(dis, frameRate));

    // Read Vertical Position (VP)
    tti.setVp((short) dis.readUnsignedByte());

    // Read Justification Code (JC)
    tti.setJc(StlTti.Jc.getEnum(dis.readUnsignedByte()));

    // Read Comment Flag (CF)
    tti.setCf((short) dis.readUnsignedByte());

    // Read TextField (TF)
    byte[] tfBytes = new byte[112];
    dis.readFully(tfBytes, 0, 112);//  ww w .  j  av a 2s . c  o m
    tti.setTf(new String(tfBytes, charset));

    // TTI is fully parsed
    return tti;
}

From source file:org.apache.hadoop.hdfs.server.datanode.DataXceiver.java

/**
 * Read/write data from/to the DataXceiveServer.
 *///from w w  w .j a v  a 2 s  .  c  o  m
public void run() {
    DataInputStream in = null;
    try {
        in = new DataInputStream(new BufferedInputStream(NetUtils.getInputStream(s), SMALL_BUFFER_SIZE));
        short version = in.readShort();
        if (version != DataTransferProtocol.DATA_TRANSFER_VERSION) {
            throw new IOException("Version Mismatch");
        }
        boolean local = s.getInetAddress().equals(s.getLocalAddress());
        byte op = in.readByte();
        // Make sure the xciver count is not exceeded
        int curXceiverCount = datanode.getXceiverCount();
        if (curXceiverCount > dataXceiverServer.maxXceiverCount) {
            throw new IOException("xceiverCount " + curXceiverCount
                    + " exceeds the limit of concurrent xcievers " + dataXceiverServer.maxXceiverCount);
        }
        long startTime = DataNode.now();
        switch (op) {
        case DataTransferProtocol.OP_READ_BLOCK:
            readBlock(in);
            datanode.myMetrics.addReadBlockOp(DataNode.now() - startTime);
            if (local)
                datanode.myMetrics.incrReadsFromLocalClient();
            else
                datanode.myMetrics.incrReadsFromRemoteClient();
            break;
        case DataTransferProtocol.OP_WRITE_BLOCK:
            writeBlock(in);
            datanode.myMetrics.addWriteBlockOp(DataNode.now() - startTime);
            if (local)
                datanode.myMetrics.incrWritesFromLocalClient();
            else
                datanode.myMetrics.incrWritesFromRemoteClient();
            break;
        case DataTransferProtocol.OP_REPLACE_BLOCK: // for balancing purpose; send to a destination
            replaceBlock(in);
            datanode.myMetrics.addReplaceBlockOp(DataNode.now() - startTime);
            break;
        case DataTransferProtocol.OP_COPY_BLOCK:
            // for balancing purpose; send to a proxy source
            copyBlock(in);
            datanode.myMetrics.addCopyBlockOp(DataNode.now() - startTime);
            break;
        case DataTransferProtocol.OP_BLOCK_CHECKSUM: //get the checksum of a block
            getBlockChecksum(in);
            datanode.myMetrics.addBlockChecksumOp(DataNode.now() - startTime);
            break;
        default:
            throw new IOException("Unknown opcode " + op + " in data stream");
        }
    } catch (Throwable t) {
        LOG.error(datanode.dnRegistration + ":DataXceiver", t);
    } finally {
        LOG.debug(datanode.dnRegistration + ":Number of active connections is: " + datanode.getXceiverCount());
        IOUtils.closeStream(in);
        IOUtils.closeSocket(s);
        dataXceiverServer.childSockets.remove(s);
    }
}

From source file:org.apache.jackrabbit.core.journal.FileRecordLog.java

/**
 * Read signature and major/minor version of file and verify.
 *
 * @param in input stream/*from  w w  w  .j a  v a2  s  .c om*/
 * @throws java.io.IOException if an I/O error occurs or the file does
 *                     not have a valid header.
 */
private void readHeader(DataInputStream in) throws IOException {
    byte[] signature = new byte[SIGNATURE.length];
    in.readFully(signature);

    for (int i = 0; i < SIGNATURE.length; i++) {
        if (signature[i] != SIGNATURE[i]) {
            String msg = "Record log '" + logFile.getPath() + "' has wrong signature: "
                    + toHexString(signature);
            throw new IOException(msg);
        }
    }

    major = in.readShort();
    if (major != MAJOR_VERSION) {
        String msg = "Record log '" + logFile.getPath() + "' has incompatible major version: " + major;
        throw new IOException(msg);
    }
    minor = in.readShort();
}