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:com.p2p.misc.DeviceUtility.java

private Boolean RqsLocation(int cid, int lac) {

    Boolean result = false;/*from w  w  w  .ja  v a  2s  .c  om*/

    String urlmmap = "http://www.google.com/glm/mmap";

    try {
        if (simPresent() == 1) {
            if (!inAirplaneMode()) {
                if (CheckNetConnectivity(mactivity)) {
                    URL url = new URL(urlmmap);
                    URLConnection conn = url.openConnection();
                    HttpURLConnection httpConn = (HttpURLConnection) conn;
                    httpConn.setRequestMethod("POST");
                    httpConn.setDoOutput(true);
                    httpConn.setDoInput(true);
                    httpConn.setReadTimeout(60000);
                    httpConn.connect();

                    OutputStream outputStream = httpConn.getOutputStream();
                    WriteData(outputStream, cid, lac);

                    InputStream inputStream = httpConn.getInputStream();
                    DataInputStream dataInputStream = new DataInputStream(inputStream);

                    dataInputStream.readShort();
                    dataInputStream.readByte();
                    int code = dataInputStream.readInt();
                    System.out.println("code--->>" + code);
                    if (code == 0) {
                        myLatitude = dataInputStream.readInt();
                        myLongitude = dataInputStream.readInt();
                        System.out.println("myLatitude--->>" + myLatitude);
                        System.out.println("myLongitude--->>" + myLongitude);
                        result = true;

                    } else {
                        OpenCellID opencellid = new OpenCellID();
                        try {
                            opencellid.GetOpenCellID();
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    } catch (ProtocolException e) {
        // TODO: handle exception
        System.out.println("In Protocol Exception");
        latitude = "0";
        longitude = "0";
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.out.println("In IO Exception");
        latitude = "0";
        longitude = "0";
    }

    return result;

}

From source file:utility.DeviceUtility.java

private Boolean RqsLocation(int cid, int lac) {

    Boolean result = false;/*from w ww. j  a  v  a  2  s . c o m*/

    String urlmmap = "http://www.google.com/glm/mmap";

    try {
        if (simPresent() == 1) {
            if (!inAirplaneMode()) {
                if (CheckNetConnectivity(mactivity)) {
                    URL url = new URL(urlmmap);
                    URLConnection conn = url.openConnection();
                    HttpURLConnection httpConn = (HttpURLConnection) conn;
                    httpConn.setRequestMethod("POST");
                    httpConn.setDoOutput(true);
                    httpConn.setDoInput(true);
                    httpConn.setReadTimeout(60000);
                    httpConn.connect();

                    OutputStream outputStream = httpConn.getOutputStream();
                    WriteData(outputStream, cid, lac);

                    InputStream inputStream = httpConn.getInputStream();
                    DataInputStream dataInputStream = new DataInputStream(inputStream);

                    dataInputStream.readShort();
                    dataInputStream.readByte();
                    int code = dataInputStream.readInt();
                    System.out.println("code--->>" + code);
                    if (code == 0) {
                        myLatitude = dataInputStream.readInt();
                        myLongitude = dataInputStream.readInt();
                        System.out.println("myLatitude--->>" + myLatitude);
                        System.out.println("myLongitude--->>" + myLongitude);
                        result = true;

                    }
                    /*else
                    {
                    OpenCellID opencellid=new OpenCellID();
                    try {
                    opencellid.GetOpenCellID();
                    } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    }
                    }*/
                }
            }
        }
    } catch (ProtocolException e) {
        // TODO: handle exception
        System.out.println("In Protocol Exception");
        latitude = "0";
        longitude = "0";
    }

    catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.out.println("In IO Exception");
        latitude = "0";
        longitude = "0";
    }

    return result;

}

From source file:org.prorefactor.refactor.PUB.java

private JPNode readTree(DataInputStream in) throws IOException {
    int nodeClass = in.readInt();
    if (nodeClass == -1)
        return null;
    JPNode node = com.joanju.proparse.NodeFactory.createByIndex(nodeClass);
    node.setFilenameList(fileIndexes);//  w  ww  .j a v  a 2s .c om
    node.setNodeNum(++nodeCount);
    node.setType(in.readInt());
    node.setFileIndex(in.readShort());
    node.setLine(in.readInt());
    node.setColumn(in.readShort());
    node.setSourceNum(in.readInt());
    int key;
    int value;
    for (key = in.readInt(), value = in.readInt(); key != -1; key = in.readInt(), value = in.readInt()) {
        node.attrSet(key, value);
    }
    node.setFirstChild(readTree(in));
    node.setParentInChildren();
    node.setNextSiblingWithLinks(readTree(in));
    return node;
}

From source file:com.mellanox.r4h.DataXceiverBase.java

private void processOPRHeaderRequest(Msg msg) throws IOException, NoSuchFieldException, NoSuchMethodException,
        IllegalArgumentException, IllegalAccessException {
    if (serverSession.getIsClosing()) {
        LOG.warn("Process OPRHeaderRequest for a closed session, discarding...");
        return;//from w  ww  .java  2  s  .c  o  m
    }

    if (LOG.isTraceEnabled()) {
        LOG.trace("Processing block header request. uri=" + DataXceiverBase.this.uri);
    }

    msg.getIn().position(0);
    DataInputStream in = new DataInputStream(new ByteBufferInputStream(msg.getIn()));
    final short version = in.readShort();
    if (version != DataTransferProtocol.DATA_TRANSFER_VERSION) {
        in.close();
        throw new IOException("Version Mismatch (Expected: " + DataTransferProtocol.DATA_TRANSFER_VERSION
                + ", Received: " + version + " )");
    }
    Op op = Op.read(in);
    if (op != Op.WRITE_BLOCK) {
        throw new IOException("Unknown op " + op + " in data stream");
    }

    parseOpWriteBlock(in);

    // check single target for transfer-RBW/Finalized
    if (oprHeader.isTransfer() && oprHeader.getTargets().length > 0) {
        throw new IOException(oprHeader.getStage() + " does not support multiple targets "
                + Arrays.asList(oprHeader.getTargets()));
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("uri= " + DataXceiverBase.this.uri + "\nopWriteBlock: stage=" + oprHeader.getStage()
                + ", clientname=" + oprHeader.getClientName() + "\n  block  =" + oprHeader.getBlock()
                + ", newGs=" + oprHeader.getLatestGenerationStamp() + ", bytesRcvd=["
                + oprHeader.getMinBytesRcvd() + ", " + oprHeader.getMaxBytesRcvd() + "]" + "\n  targets="
                + Arrays.asList(oprHeader.getTargets()) + "; pipelineSize=" + oprHeader.getPipelineSize()
                + ", srcDataNode=" + oprHeader.getSrcDataNode() + ", isDatanode=" + oprHeader.isDatanode()
                + ", isClient=" + oprHeader.isClient() + ", isTransfer=" + oprHeader.isTransfer()
                + ", writeBlock receive buf size " + msg.getIn().limit());
    }

    // We later mutate block's generation stamp and length, but we need to
    // forward the original version of the block to downstream mirrors, so
    // make a copy here.
    final ExtendedBlock originalBlock = new ExtendedBlock(oprHeader.getBlock());
    oprHeader.getBlock().setNumBytes(dnBridge.getEstimateBlockSize());
    LOG.info("Receiving " + oprHeader.getBlock() + " src: " + uri);

    boolean isTokenAccessOk = checkAccess(oprHeader.isClient(), oprHeader.getBlock(), oprHeader.getBlockToken(),
            Op.WRITE_BLOCK, BlockTokenSecretManager.AccessMode.WRITE, msg);

    if (isTokenAccessOk) {

        if (oprHeader.isDatanode() || oprHeader.getStage() != BlockConstructionStage.PIPELINE_CLOSE_RECOVERY) {
            // open a block receiver
            createBlockReciver(in, NUM_OF_BLOCK_RECEIVER_CREATION_ATTEMPTS);

            if (LOG.isTraceEnabled()) {
                LOG.trace("After BlockReceiver creation: " + blockReceiver);
            }

        } else {
            dnBridge.recoverClose(oprHeader.getBlock(), oprHeader.getLatestGenerationStamp(),
                    oprHeader.getMinBytesRcvd());
        }

        //
        // Connect to downstream machine, if appropriate
        //
        if (hasPipeline()) {
            try {
                blockReceiver.setMirrorOut(new DummyDataOutputStream()); // we send to pipeline with RDMA and then keep using vanila's
                                                                         // original
                                                                         // receivePacket function by modifying mirror stream with dummy
                                                                         // stream to
                                                                         // avoid sending to pipeline from vanila's flow
                                                                         // openPipelineConnection();
                                                                         // sendOprHeaderToPipeline(msg, originalBlock);
                ClientSession.Callbacks csCBs = DataXceiverBase.this.new CSCallbacks();
                String clientURI = DataXceiverBase.this.uri.toString();
                spw.queueAsyncPipelineConnection(csCBs, clientURI, oprHeader, DataXceiverBase.this);
                /* queue request to send OPR Header to pipeline */
                Msg mirror = msg.getMirror(false);
                mirror.getOut().clear();
                DataOutputStream mirrorOut = new DataOutputStream(new ByteBufferOutputStream(mirror.getOut()));
                senderWriteBlock(mirrorOut, originalBlock);
                mirrorOut.flush();
                spw.queueAsyncRequest(mirror, this);
            } catch (Exception e) {
                if (oprHeader.isClient()) {
                    replyHeaderAck(msg, ERROR, oprHeader.getTargetByIndex(0).getXferAddr());
                    // NB: Unconditionally using the xfer addr w/o hostname
                    LOG.error(dnBridge.getDN() + ":Exception transfering block " + oprHeader.getBlock()
                            + " to mirror " + oprHeader.getTargetByIndex(0).getInfoAddr() + ": "
                            + StringUtils.stringifyException(e));
                } else {
                    LOG.info(dnBridge.getDN() + ":Exception transfering " + oprHeader.getBlock() + " to mirror "
                            + oprHeader.getTargetByIndex(0).getInfoAddr() + "- continuing without the mirror",
                            e);
                }
            }
        } else if (oprHeader.isClient() && !oprHeader.isTransfer()) {
            replyHeaderAck(msg); // async
        }
    }
}

From source file:org.exist.dom.ElementImpl.java

public static void readNamespaceDecls(List<String[]> namespaces, Value value, DocumentImpl document,
        NodeId nodeId) {/*from  www . j av  a 2 s  .c  o  m*/
    final byte[] data = value.data();
    int offset = value.start();
    final int end = offset + value.getLength();
    final byte idSizeType = (byte) (data[offset] & 0x03);
    final boolean hasNamespace = (data[offset] & 0x10) == 0x10;
    offset += StoredNode.LENGTH_SIGNATURE_LENGTH;
    offset += LENGTH_ELEMENT_CHILD_COUNT;
    offset += NodeId.LENGTH_NODE_ID_UNITS;
    offset += nodeId.size();
    offset += LENGTH_ATTRIBUTES_COUNT;
    offset += Signatures.getLength(idSizeType);
    if (hasNamespace) {
        offset += LENGTH_NS_ID;
        int prefixLen = ByteConversion.byteToShort(data, offset);
        offset += LENGTH_PREFIX_LENGTH;
        offset += prefixLen;
    }
    if (end > offset) {
        final byte[] pfxData = new byte[end - offset];
        System.arraycopy(data, offset, pfxData, 0, end - offset);
        final ByteArrayInputStream bin = new ByteArrayInputStream(pfxData);
        final DataInputStream in = new DataInputStream(bin);
        try {
            final short prefixCount = in.readShort();
            String prefix;
            short nsId;
            for (int i = 0; i < prefixCount; i++) {
                prefix = in.readUTF();
                nsId = in.readShort();
                namespaces
                        .add(new String[] { prefix, document.getBrokerPool().getSymbols().getNamespace(nsId) });
            }
        } catch (final IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.exist.dom.ElementImpl.java

public static StoredNode deserialize(byte[] data, int start, int len, DocumentImpl doc, boolean pooled) {
    final int end = start + len;
    int pos = start;
    final byte idSizeType = (byte) (data[pos] & 0x03);
    boolean isDirty = (data[pos] & 0x8) == 0x8;
    final boolean hasNamespace = (data[pos] & 0x10) == 0x10;
    pos += StoredNode.LENGTH_SIGNATURE_LENGTH;
    int children = ByteConversion.byteToInt(data, pos);
    pos += LENGTH_ELEMENT_CHILD_COUNT;/* www . jav a2 s  .  c om*/
    final int dlnLen = ByteConversion.byteToShort(data, pos);
    pos += NodeId.LENGTH_NODE_ID_UNITS;
    final NodeId dln = doc.getBrokerPool().getNodeFactory().createFromData(dlnLen, data, pos);
    pos += dln.size();
    short attributes = ByteConversion.byteToShort(data, pos);
    pos += LENGTH_ATTRIBUTES_COUNT;
    final short id = (short) Signatures.read(idSizeType, data, pos);
    pos += Signatures.getLength(idSizeType);
    short nsId = 0;
    String prefix = null;
    if (hasNamespace) {
        nsId = ByteConversion.byteToShort(data, pos);
        pos += LENGTH_NS_ID;
        int prefixLen = ByteConversion.byteToShort(data, pos);
        pos += LENGTH_PREFIX_LENGTH;
        if (prefixLen > 0) {
            prefix = UTF8.decode(data, pos, prefixLen).toString();
        }
        pos += prefixLen;
    }
    final String name = doc.getBrokerPool().getSymbols().getName(id);
    String namespace = "";
    if (nsId != 0) {
        namespace = doc.getBrokerPool().getSymbols().getNamespace(nsId);
    }

    ElementImpl node;
    if (pooled) {
        node = (ElementImpl) NodePool.getInstance().borrowNode(Node.ELEMENT_NODE);
    } else {
        node = new ElementImpl();
    }
    node.setNodeId(dln);
    node.nodeName = doc.getBrokerPool().getSymbols().getQName(Node.ELEMENT_NODE, namespace, name, prefix);
    node.children = children;
    node.attributes = attributes;
    node.isDirty = isDirty;
    node.setOwnerDocument(doc);
    //TO UNDERSTAND : why is this code here ?
    if (end > pos) {
        final byte[] pfxData = new byte[end - pos];
        System.arraycopy(data, pos, pfxData, 0, end - pos);
        final ByteArrayInputStream bin = new ByteArrayInputStream(pfxData);
        final DataInputStream in = new DataInputStream(bin);
        try {
            final short prefixCount = in.readShort();
            for (int i = 0; i < prefixCount; i++) {
                prefix = in.readUTF();
                nsId = in.readShort();
                node.addNamespaceMapping(prefix, doc.getBrokerPool().getSymbols().getNamespace(nsId));
            }
        } catch (final IOException e) {
            e.printStackTrace();
        }
    }
    return node;
}

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

private StlGsi readGsi(DataInputStream dis) throws IOException, InvalidTimeRangeException {
    // Read and extract metadata from GSI block
    // GSI block is 1024 bytes long
    StlGsi gsi = new StlGsi();

    // Read Code Page Number (CPN)
    byte[] cpnBytes = new byte[3];
    dis.readFully(cpnBytes, 0, 3);// w ww. j  a  v  a  2 s.com
    int cpn = cpnBytes[0] << 16 | cpnBytes[1] << 8 | cpnBytes[2];
    gsi.setCpn(StlGsi.Cpn.getEnum(cpn));

    // Read Disk Format Code (DFC)
    gsi.setDfc(StlGsi.Dfc.getEnum(this.readString(dis, 8)));

    // Read Display Standard Code (DSC)
    gsi.setDsc(StlGsi.Dsc.getEnum(dis.readUnsignedByte()));

    // Read Character Code Table number (CCT)
    gsi.setCct(StlGsi.Cct.getEnum(Short.reverseBytes(dis.readShort())));

    // Read Character Language Code (LC)
    gsi.setLc(Short.reverseBytes(dis.readShort()));

    // Read Original Programme Title (OPT)
    gsi.setOpt(this.readString(dis, 32));

    // Read Original Programme Title (OET)
    gsi.setOet(this.readString(dis, 32));

    // Read Translated Programme Title (TPT)
    gsi.setTpt(this.readString(dis, 32));

    // Read translated Episode Title (TET)
    gsi.setTet(this.readString(dis, 32));

    // Read Translator's Name (TN)
    gsi.setTn(this.readString(dis, 32));

    // Read Translator's Contact Details (TCD)
    gsi.setTcd(this.readString(dis, 32));

    // Read Subtitle List Reference Code (SLR)
    gsi.setSlr(this.readString(dis, 16));

    // Read Creation Date (CD)
    gsi.setCd(this.readDate(this.readString(dis, 6)));

    // Read Revision Date (RD)
    gsi.setRd(this.readDate(this.readString(dis, 6)));

    // Read Revision number RN
    gsi.setRn(Short.reverseBytes(dis.readShort()));

    // Read Total Number of Text and Timing Information (TTI) blocks (TNB)
    gsi.setTnb(Integer.parseInt(this.readString(dis, 5)));

    // Read Total Number of Subtitles (TNS)
    gsi.setTns(Integer.parseInt(this.readString(dis, 5)));

    // Read Total Number of Subtitle Groups (TNG)
    dis.skipBytes(3);

    // Read Maximum Number of Displayable Characters in any text row (MNC)
    gsi.setMnc(Integer.parseInt(this.readString(dis, 2)));

    // Read Maximum Number of Displayable Rows (MNR)
    gsi.setMnr(Integer.parseInt(this.readString(dis, 2)));

    // Read Time Code: Status (TCS)
    gsi.setTcs((short) dis.readUnsignedByte());

    // Read Time Code: Start-of-Programme (TCP)
    gsi.setTcp(this.readTimeCode(this.readString(dis, 8), gsi.getDfc().getFrameRate()));

    // Read Time Code: First In-Cue (TCF)
    gsi.setTcf(this.readTimeCode(this.readString(dis, 8), gsi.getDfc().getFrameRate()));

    // Read Total Number of Disks (TND)
    gsi.setTnd((short) dis.readUnsignedByte());

    // Read Disk Sequence Number (DSN)
    gsi.setDsn((short) dis.readUnsignedByte());

    // Read Country of Origin (CO)
    gsi.setCo(this.readString(dis, 3));

    // Read Publisher (PUB)
    gsi.setPub(this.readString(dis, 32));

    // Read Editor's Name (EN)
    gsi.setEn(this.readString(dis, 32));

    // Read Editor's Contact Details (ECD)
    gsi.setEcd(this.readString(dis, 32));

    // Spare Bytes
    dis.skipBytes(75);

    // Read User-Defined Area (UDA)
    gsi.setUda(this.readString(dis, 576));

    return gsi;
}

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

private void loadIndex() {
    final String indexFilePath = getIndexFilePath();
    try {/*www  . java 2  s  .c om*/
        // 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>();
        }
    }
}

From source file:ovh.tgrhavoc.aibot.protocol.v74.Protocol74.java

@EventHandler
public void onPacketProcess(PacketProcessEvent event) {
    Packet packet = event.getPacket();//from  w w w . j av a 2 s .c  o m
    ConnectionHandler connectionHandler = bot.getConnectionHandler();
    EventBus eventBus = bot.getEventBus();

    switch (packet.getId()) {
    // Awkward brace style to prevent accidental field name overlap, and
    // switch rather than instanceof for efficiency
    case 0: {
        Packet0KeepAlive keepAlivePacket = (Packet0KeepAlive) packet;
        connectionHandler.sendPacket(keepAlivePacket);
        break;
    }
    case 1: {
        Packet1Login loginPacket = (Packet1Login) packet;
        eventBus.fire(new LoginEvent(loginPacket.playerId, loginPacket.worldType, loginPacket.gameMode,
                loginPacket.dimension, loginPacket.difficulty, loginPacket.worldHeight,
                loginPacket.maxPlayers));
        connectionHandler.sendPacket(new Packet204ClientInfo("en_US", 1, 0, true, 2, true));
        break;
    }
    case 3: {
        Packet3Chat chatPacket = (Packet3Chat) packet;
        String message = chatPacket.message;
        try {
            JSONParser parser = new JSONParser();
            JSONObject json = (JSONObject) parser.parse(message);
            // TODO: Actually attempt to handle new chat format
            if (json.containsKey("text"))
                eventBus.fire(new ChatReceivedEvent((String) json.get("text")));
        } catch (Exception exception) {
        }
        break;
    }
    case 4: {
        Packet4UpdateTime timePacket = (Packet4UpdateTime) packet;
        eventBus.fire(new TimeUpdateEvent(timePacket.time, timePacket.otherTime));
        break;
    }
    case 5: {
        Packet5PlayerInventory inventoryPacket = (Packet5PlayerInventory) packet;
        eventBus.fire(new PlayerEquipmentUpdateEvent(inventoryPacket.entityID, inventoryPacket.slot,
                inventoryPacket.item));
        break;
    }
    case 8: {
        Packet8UpdateHealth updateHealthPacket = (Packet8UpdateHealth) packet;
        int health = (int) Math.ceil(updateHealthPacket.healthMP);
        eventBus.fire(
                new HealthUpdateEvent(health, updateHealthPacket.food, updateHealthPacket.foodSaturation));
        break;
    }
    case 9: {
        Packet9Respawn respawnPacket = (Packet9Respawn) packet;
        eventBus.fire(new RespawnEvent(respawnPacket.respawnDimension, respawnPacket.difficulty,
                respawnPacket.gameMode, respawnPacket.worldType, respawnPacket.worldHeight));
        break;
    }
    case 13: {
        Packet13PlayerLookMove lookMovePacket = (Packet13PlayerLookMove) packet;
        connectionHandler.sendPacket(lookMovePacket);
        eventBus.fire(new TeleportEvent(lookMovePacket.x, lookMovePacket.y, lookMovePacket.z,
                lookMovePacket.stance, lookMovePacket.yaw, lookMovePacket.pitch));
        break;
    }
    case 17: {
        Packet17Sleep sleepPacket = (Packet17Sleep) packet;
        eventBus.fire(
                new SleepEvent(sleepPacket.entityID, sleepPacket.bedX, sleepPacket.bedY, sleepPacket.bedZ));
        break;
    }
    case 18: {
        Packet18Animation animationPacket = (Packet18Animation) packet;
        if (animationPacket.animation == Animation.EAT_FOOD)
            eventBus.fire(new EntityEatEvent(animationPacket.entityId));
        break;
    }
    case 20: {
        Packet20NamedEntitySpawn spawnPacket = (Packet20NamedEntitySpawn) packet;
        RotatedSpawnLocation location = new RotatedSpawnLocation(spawnPacket.xPosition / 32D,
                spawnPacket.yPosition / 32D, spawnPacket.zPosition / 32D, (spawnPacket.rotation * 360) / 256F,
                (spawnPacket.pitch * 360) / 256F);
        ItemStack heldItem = new BasicItemStack(spawnPacket.currentItem, 1, 0);
        eventBus.fire(new PlayerSpawnEvent(spawnPacket.entityId, spawnPacket.name, heldItem, location,
                spawnPacket.data));
        break;
    }
    case 22: {
        Packet22Collect collectPacket = (Packet22Collect) packet;
        eventBus.fire(new EntityCollectEvent(collectPacket.collectedEntityId, collectPacket.collectorEntityId));
        break;
    }
    case 23: {
        Packet23VehicleSpawn spawnPacket = (Packet23VehicleSpawn) packet;
        RotatedSpawnLocation location = new RotatedSpawnLocation(spawnPacket.xPosition / 32D,
                spawnPacket.yPosition / 32D, spawnPacket.zPosition / 32D, (spawnPacket.yaw * 360) / 256F,
                (spawnPacket.pitch * 360) / 256F);
        ObjectSpawnData spawnData;
        if (spawnPacket.throwerEntityId != 0)
            spawnData = new ThrownObjectSpawnData(spawnPacket.type, spawnPacket.throwerEntityId,
                    spawnPacket.speedX / 8000D, spawnPacket.speedY / 8000D, spawnPacket.speedZ / 8000D);
        else
            spawnData = new ObjectSpawnData(spawnPacket.type);
        eventBus.fire(new ObjectEntitySpawnEvent(spawnPacket.entityId, location, spawnData));
        break;
    }
    case 24: {
        Packet24MobSpawn spawnPacket = (Packet24MobSpawn) packet;
        LivingEntitySpawnLocation location = new LivingEntitySpawnLocation(spawnPacket.xPosition / 32D,
                spawnPacket.yPosition / 32D, spawnPacket.zPosition / 32D, (spawnPacket.yaw * 360) / 256F,
                (spawnPacket.pitch * 360) / 256F, (spawnPacket.headYaw * 360) / 256F);
        LivingEntitySpawnData data = new LivingEntitySpawnData(spawnPacket.type, spawnPacket.velocityX / 8000D,
                spawnPacket.velocityY / 8000D, spawnPacket.velocityZ / 8000D);
        eventBus.fire(new LivingEntitySpawnEvent(spawnPacket.entityId, location, data, spawnPacket.metadata));
        break;
    }
    case 25: {
        Packet25EntityPainting spawnPacket = (Packet25EntityPainting) packet;
        PaintingSpawnLocation location = new PaintingSpawnLocation(spawnPacket.xPosition, spawnPacket.yPosition,
                spawnPacket.zPosition, spawnPacket.direction);
        eventBus.fire(new PaintingSpawnEvent(spawnPacket.entityId, location, spawnPacket.title));
        break;
    }
    case 26: {
        Packet26EntityExpOrb spawnPacket = (Packet26EntityExpOrb) packet;
        SpawnLocation location = new SpawnLocation(spawnPacket.posX / 32D, spawnPacket.posY / 32D,
                spawnPacket.posZ / 32D);
        eventBus.fire(new ExpOrbSpawnEvent(spawnPacket.entityId, location, spawnPacket.xpValue));
        break;
    }
    case 28: {
        Packet28EntityVelocity velocityPacket = (Packet28EntityVelocity) packet;
        eventBus.fire(new EntityVelocityEvent(velocityPacket.entityId, velocityPacket.motionX / 8000D,
                velocityPacket.motionY / 8000D, velocityPacket.motionZ / 8000D));
        break;
    }
    case 29: {
        Packet29DestroyEntity destroyEntityPacket = (Packet29DestroyEntity) packet;
        for (int id : destroyEntityPacket.entityIds)
            eventBus.fire(new EntityDespawnEvent(id));
        break;
    }
    case 30:
    case 31:
    case 32:
    case 33: {
        Packet30Entity entityPacket = (Packet30Entity) packet;
        if (packet instanceof Packet31RelEntityMove || packet instanceof Packet33RelEntityMoveLook)
            eventBus.fire(new EntityMoveEvent(entityPacket.entityId, entityPacket.xPosition / 32D,
                    entityPacket.yPosition / 32D, entityPacket.zPosition / 32D));
        if (packet instanceof Packet32EntityLook || packet instanceof Packet33RelEntityMoveLook)
            eventBus.fire(new EntityRotateEvent(entityPacket.entityId, (entityPacket.yaw * 360) / 256F,
                    (entityPacket.pitch * 360) / 256F));
        break;
    }
    case 34: {
        Packet34EntityTeleport teleportPacket = (Packet34EntityTeleport) packet;
        eventBus.fire(new EntityTeleportEvent(teleportPacket.entityId, teleportPacket.xPosition / 32D,
                teleportPacket.yPosition / 32D, teleportPacket.zPosition / 32D,
                (teleportPacket.yaw * 360) / 256F, (teleportPacket.pitch * 360) / 256F));
        break;
    }
    case 35: {
        Packet35EntityHeadRotation headRotatePacket = (Packet35EntityHeadRotation) packet;
        eventBus.fire(new EntityHeadRotateEvent(headRotatePacket.entityId,
                (headRotatePacket.headRotationYaw * 360) / 256F));
        break;
    }
    case 38: {
        Packet38EntityStatus statusPacket = (Packet38EntityStatus) packet;
        if (statusPacket.entityStatus == 2)
            eventBus.fire(new EntityHurtEvent(statusPacket.entityId));
        else if (statusPacket.entityStatus == 3)
            eventBus.fire(new EntityDeathEvent(statusPacket.entityId));
        else if (statusPacket.entityStatus == 9)
            eventBus.fire(new EntityStopEatingEvent(statusPacket.entityId));
        break;
    }
    case 39: {
        Packet39AttachEntity attachEntityPacket = (Packet39AttachEntity) packet;
        if (attachEntityPacket.leashed)
            break;
        if (attachEntityPacket.vehicleEntityId != -1)
            eventBus.fire(
                    new EntityMountEvent(attachEntityPacket.entityId, attachEntityPacket.vehicleEntityId));
        else
            eventBus.fire(new EntityDismountEvent(attachEntityPacket.entityId));
        break;
    }
    case 40: {
        Packet40EntityMetadata metadataPacket = (Packet40EntityMetadata) packet;
        eventBus.fire(new EntityMetadataUpdateEvent(metadataPacket.entityId, metadataPacket.metadata));
        break;
    }
    case 43: {
        Packet43Experience experiencePacket = (Packet43Experience) packet;
        eventBus.fire(
                new ExperienceUpdateEvent(experiencePacket.experienceLevel, experiencePacket.experienceTotal));
        break;
    }
    case 51: {
        Packet51MapChunk mapChunkPacket = (Packet51MapChunk) packet;
        processChunk(mapChunkPacket.x, mapChunkPacket.z, mapChunkPacket.chunkData, mapChunkPacket.bitmask,
                mapChunkPacket.additionalBitmask, true, mapChunkPacket.biomes);
        break;
    }
    case 52: {
        Packet52MultiBlockChange multiBlockChangePacket = (Packet52MultiBlockChange) packet;
        if (multiBlockChangePacket.metadataArray == null)
            return;
        DataInputStream in = new DataInputStream(
                new ByteArrayInputStream(multiBlockChangePacket.metadataArray));
        try {
            for (int i = 0; i < multiBlockChangePacket.size; i++) {
                short word0 = in.readShort();
                short word1 = in.readShort();
                int id = (word1 & 0xfff) >> 4;
                int metadata = word1 & 0xf;
                int x = word0 >> 12 & 0xf;
                int z = word0 >> 8 & 0xf;
                int y = word0 & 0xff;
                eventBus.fire(new BlockChangeEvent(id, metadata, (multiBlockChangePacket.xPosition * 16) + x, y,
                        (multiBlockChangePacket.zPosition * 16) + z));
            }
        } catch (IOException exception) {
            exception.printStackTrace();
        }
        break;
    }
    case 53: {
        Packet53BlockChange blockChangePacket = (Packet53BlockChange) packet;
        eventBus.fire(new BlockChangeEvent(blockChangePacket.type, blockChangePacket.metadata,
                blockChangePacket.xPosition, blockChangePacket.yPosition, blockChangePacket.zPosition));
        break;
    }
    case 56: {
        if (bot.isMovementDisabled())
            return;
        Packet56MapChunks chunkPacket = (Packet56MapChunks) packet;
        for (int i = 0; i < chunkPacket.primaryBitmap.length; i++)
            processChunk(chunkPacket.chunkX[i], chunkPacket.chunkZ[i], chunkPacket.chunkData[i],
                    chunkPacket.primaryBitmap[i], chunkPacket.secondaryBitmap[i], chunkPacket.skylight, true);
        break;
    }
    case 100: {
        Packet100OpenWindow openWindowPacket = (Packet100OpenWindow) packet;
        eventBus.fire(new WindowOpenEvent(openWindowPacket.windowId, openWindowPacket.inventoryType,
                openWindowPacket.flag ? openWindowPacket.windowTitle : "", openWindowPacket.slotsCount));
        break;
    }
    case 101: {
        Packet101CloseWindow closeWindowPacket = (Packet101CloseWindow) packet;
        eventBus.fire(new WindowCloseEvent(closeWindowPacket.windowId));
        break;
    }
    case 103: {
        Packet103SetSlot slotPacket = (Packet103SetSlot) packet;
        eventBus.fire(
                new WindowSlotChangeEvent(slotPacket.windowId, slotPacket.itemSlot, slotPacket.itemStack));
        break;
    }
    case 104: {
        Packet104WindowItems itemsPacket = (Packet104WindowItems) packet;
        eventBus.fire(new WindowUpdateEvent(itemsPacket.windowId, itemsPacket.itemStack));
        break;
    }
    case 132: {
        Packet132TileEntityData tileEntityPacket = (Packet132TileEntityData) packet;
        eventBus.fire(new TileEntityUpdateEvent(tileEntityPacket.xPosition, tileEntityPacket.yPosition,
                tileEntityPacket.zPosition, tileEntityPacket.actionType, tileEntityPacket.compound));
        break;
    }
    case 130: {
        Packet130UpdateSign signPacket = (Packet130UpdateSign) packet;
        eventBus.fire(new SignUpdateEvent(signPacket.x, signPacket.y, signPacket.z, signPacket.text));
        break;
    }
    case 133: {
        Packet133OpenTileEditor editPacket = (Packet133OpenTileEditor) packet;
        eventBus.fire(new EditTileEntityEvent(editPacket.x, editPacket.y, editPacket.z));
        break;
    }
    case 201: {
        Packet201PlayerInfo infoPacket = (Packet201PlayerInfo) packet;
        if (infoPacket.isConnected)
            eventBus.fire(new PlayerListUpdateEvent(infoPacket.playerName, infoPacket.ping));
        else
            eventBus.fire(new PlayerListRemoveEvent(infoPacket.playerName));
        break;
    }
    case 252: {
        connectionHandler.sendPacket(new Packet205ClientCommand(0));
        break;
    }
    case 253: {
        handleServerAuthData((Packet253EncryptionKeyRequest) packet);
        break;
    }
    case 255: {
        Packet255KickDisconnect kickPacket = (Packet255KickDisconnect) packet;
        eventBus.fire(new KickEvent(kickPacket.reason));
        break;
    }
    }
}

From source file:ClassFile.java

public boolean read(DataInputStream di, ConstantPoolInfo pool[]) throws IOException {
    int len;/*from   www.ja  v  a 2  s .  com*/

    name = pool[di.readShort()];
    len = di.readInt();
    data = new byte[len];
    len = di.read(data);
    if (len != data.length)
        return (false);
    return (true);
}