List of usage examples for java.nio ByteBuffer remaining
public final int remaining()
From source file:com.blm.orc.RecordReaderImpl.java
/** * Read the list of ranges from the file. * @param file the file to read/*from ww w . j a v a2 s .c o m*/ * @param base the base of the stripe * @param ranges the disk ranges within the stripe to read * @return the bytes read for each disk range, which is the same length as * ranges * @throws IOException */ List<BufferChunk> readDiskRanges(FSDataInputStream file, long base, List<DiskRange> ranges) throws IOException { ArrayList<BufferChunk> result = new ArrayList<RecordReaderImpl.BufferChunk>(ranges.size()); for (DiskRange range : ranges) { int len = (int) (range.end - range.offset); long off = range.offset; file.seek(base + off); if (zcr != null) { while (len > 0) { ByteBuffer partial = zcr.readBuffer(len, false); result.add(new BufferChunk(partial, off)); int read = partial.remaining(); len -= read; off += read; } } else { byte[] buffer = new byte[len]; file.readFully(buffer, 0, buffer.length); result.add(new BufferChunk(ByteBuffer.wrap(buffer), range.offset)); } } return result; }
From source file:com.l2jfree.gameserver.network.L2ClientPacketHandlerFinal.java
@Override public L2ClientPacket handlePacket(ByteBuffer buf, L2Client client, final int opcode) { L2ClientPacket msg = null;//from w w w. ja v a 2 s. c o m GameClientState state = client.getState(); switch (state) { case CONNECTED: switch (opcode) { case 0x0e: msg = new ProtocolVersion(); break; case 0x2b: msg = new AuthLogin(); break; default: printDebug(buf, client, opcode); break; } break; case AUTHED: switch (opcode) { case 0x00: msg = new Logout(); break; case 0x0c: msg = new NewCharacter(); break; case 0x0d: msg = new CharacterDelete(); break; case 0x0f: // MoveBackwardsToLocation, lag issue break; case 0x12: msg = new CharacterSelected(); break; case 0x13: msg = new NewCharacterInit(); break; case 0x57: // RequestRestart, lag issue break; case 0x7b: msg = new CharacterRestore(); break; case 0xd0: int id2 = -1; if (buf.remaining() >= 2) { id2 = buf.getShort() & 0xffff; } else { if (Config.PACKET_HANDLER_DEBUG) _log.warn("Client: " + client.toString() + " sent a 0xd0 without the second opcode."); break; } switch (id2) { case 0x24: // RequestSaveInventoryOrder, lag issue break; case 0x36: msg = new CharacterPrevState(); break; case 0x39: // most probably using L2NET break; case 0x3d: // client definitely sends it right now, enable if supposed to be //msg = new RequestAllFortressInfo(); break; case 0x5a: int id3 = 0; if (buf.remaining() >= 4) { id3 = buf.getInt() & 0xffffffff; } else { if (Config.PACKET_HANDLER_DEBUG) _log.warn("Client: " + client + " sent a 0xd0:0x5a without the third opcode."); break; } switch (id3) { case 0x00: msg = new RequestExCubeGameChangeTeam(); break; default: printDebug(buf, client, opcode, id2, id3); break; } break; default: printDebug(buf, client, opcode, id2); } break; // to avoid unnecessary warning about invalid opcode (if the client lags a bit, then it starts spamming this packet) case 0x59: // ValidatePosition break; // default: printDebug(buf, client, opcode); break; } break; case IN_GAME: switch (opcode) { // to avoid unnecessary warning about invalid opcode (player clicked the button multiple times) case 0x12: // CharacterSelected break; // case 0x00: msg = new Logout(); break; case 0x01: msg = new AttackRequest(); break; case 0x03: msg = new RequestStartPledgeWar(); break; case 0x04: msg = new RequestReplyStartPledgeWar(); break; case 0x05: msg = new RequestStopPledgeWar(); break; case 0x06: // RequestSCCheck msg = new RequestReplyStopPledgeWar(); break; case 0x07: msg = new RequestSurrenderPledgeWar(); break; case 0x08: msg = new RequestReplySurrenderPledgeWar(); break; case 0x09: msg = new RequestSetPledgeCrest(); break; case 0x0b: msg = new RequestGiveNickName(); break; case 0x0f: msg = new MoveBackwardToLocation(); break; case 0x10: // Say break; case 0x11: msg = new EnterWorld(); break; case 0x14: msg = new RequestItemList(); break; case 0x15: // RequestEquipItem break; case 0x16: msg = new RequestUnEquipItem(); break; case 0x17: msg = new RequestDropItem(); break; case 0x19: msg = new UseItem(); break; case 0x1a: msg = new TradeRequest(); break; case 0x1b: msg = new AddTradeItem(); break; case 0x1c: msg = new TradeDone(); break; case 0x1f: msg = new Action(); break; case 0x22: msg = new RequestLinkHtml(); break; case 0x23: msg = new RequestBypassToServer(); break; case 0x24: msg = new RequestBBSwrite(); break; case 0x25: // RequestCreatePledge break; case 0x26: msg = new RequestJoinPledge(); break; case 0x27: msg = new RequestAnswerJoinPledge(); break; case 0x28: msg = new RequestWithdrawalPledge(); break; case 0x29: msg = new RequestOustPledgeMember(); break; case 0x2c: msg = new RequestGetItemFromPet(); break; case 0x2e: msg = new RequestAllyInfo(); break; case 0x2f: msg = new RequestCrystallizeItem(); break; case 0x30: msg = new RequestPrivateStoreManageSell(); break; case 0x31: msg = new SetPrivateStoreListSell(); break; case 0x32: msg = new AttackRequest(); break; case 0x33: // RequestTeleportPacket break; case 0x34: msg = new RequestSocialAction(); break; case 0x35: msg = new ChangeMoveType(); break; case 0x36: msg = new ChangeWaitType(); break; case 0x37: msg = new RequestSellItem(); break; case 0x38: // RequestMagicSkillList break; case 0x39: msg = new RequestMagicSkillUse(); break; case 0x3a: msg = new SendAppearing(); break; case 0x3b: if (Config.ALLOW_WAREHOUSE) msg = new SendWareHouseDepositList(); break; case 0x3c: msg = new SendWareHouseWithDrawList(); break; case 0x3d: msg = new RequestShortCutReg(); break; case 0x3f: msg = new RequestShortCutDel(); break; case 0x40: msg = new RequestBuyItem(); break; case 0x41: // RequestDismissPledge break; case 0x42: msg = new RequestJoinParty(); break; case 0x43: msg = new RequestAnswerJoinParty(); break; case 0x44: msg = new RequestWithDrawalParty(); break; case 0x45: msg = new RequestOustPartyMember(); break; case 0x46: // RequestDismissParty break; case 0x47: msg = new CannotMoveAnymore(); break; case 0x48: msg = new RequestTargetCanceld(); break; case 0x49: msg = new Say2(); break; case 0x4a: int id_2 = -1; if (buf.remaining() >= 2) { id_2 = buf.get() & 0xff; } else { if (Config.PACKET_HANDLER_DEBUG) _log.warn("Client: " + client.toString() + " sent a 0x4a without the second opcode."); break; } switch (id_2) { case 0x00: msg = new SuperCmdCharacterInfo(); break; case 0x01: msg = new SuperCmdSummonCmd(); break; case 0x02: msg = new SuperCmdServerStatus(); break; case 0x03: msg = new SendL2ParamSetting(); break; default: printDebug(buf, client, opcode, id_2); break; } break; case 0x4d: msg = new RequestPledgeMemberList(); break; case 0x4f: //RequestMagicList break; case 0x50: msg = new RequestSkillList(); break; case 0x52: msg = new MoveWithDelta(); break; case 0x53: msg = new RequestGetOnVehicle(); break; case 0x54: msg = new RequestGetOffVehicle(); break; case 0x55: msg = new AnswerTradeRequest(); break; case 0x56: msg = new RequestActionUse(); break; case 0x57: msg = new RequestRestart(); break; case 0x58: msg = new RequestSiegeInfo(); break; case 0x59: msg = new ValidatePosition(); break; case 0x5a: // RequestSEKCustom break; case 0x5b: // StartRotating break; case 0x5c: // FinishRotating break; case 0x5e: msg = new RequestShowBoard(); break; case 0x5f: msg = new RequestEnchantItem(); break; case 0x60: msg = new RequestDestroyItem(); break; case 0x62: msg = new RequestQuestList(); break; case 0x63: // RequestDestroyQuest msg = new RequestQuestAbort(); break; case 0x65: msg = new RequestPledgeInfo(); break; case 0x66: msg = new RequestPledgeExtendedInfo(); break; case 0x67: msg = new RequestPledgeCrest(); break; case 0x6b: msg = new RequestSendFriendMsg(); break; case 0x6c: msg = new RequestShowMiniMap(); break; case 0x6d: // RequestSendMsnChatLog break; case 0x6e: //RequestReload msg = new RequestRecordInfo(); break; case 0x6f: msg = new RequestHennaEquip(); break; case 0x70: msg = new RequestHennaRemoveList(); break; case 0x71: msg = new RequestHennaItemRemoveInfo(); break; case 0x72: msg = new RequestHennaRemove(); break; case 0x73: msg = new RequestAquireSkillInfo(); break; case 0x74: msg = new SendBypassBuildCmd(); break; case 0x75: msg = new RequestMoveToLocationInVehicle(); break; case 0x76: msg = new CannotMoveAnymoreInVehicle(); break; case 0x77: msg = new RequestFriendInvite(); break; case 0x78: msg = new RequestAnswerFriendInvite(); break; case 0x79: msg = new RequestFriendList(); break; case 0x7a: msg = new RequestFriendDel(); break; case 0x7c: // send when a skill to be learned is selected msg = new RequestAquireSkill(); break; case 0x7d: msg = new RequestRestartPoint(); break; case 0x7e: msg = new RequestGMCommand(); break; case 0x7f: msg = new RequestPartyMatchConfig(); break; case 0x80: msg = new RequestPartyMatchList(); break; case 0x81: msg = new RequestPartyMatchDetail(); break; case 0x83: msg = new RequestPrivateStoreBuy(); break; case 0x85: msg = new RequestTutorialLinkHtml(); break; case 0x86: msg = new RequestTutorialPassCmdToServer(); break; case 0x87: msg = new RequestTutorialQuestionMark(); break; case 0x88: msg = new RequestTutorialClientEvent(); break; case 0x89: msg = new RequestPetition(); break; case 0x8a: msg = new RequestPetitionCancel(); break; case 0x8b: msg = new RequestGmList(); break; case 0x8c: msg = new RequestJoinAlly(); break; case 0x8d: msg = new RequestAnswerJoinAlly(); break; case 0x8e: msg = new RequestWithdrawAlly(); break; case 0x8f: msg = new RequestOustAlly(); break; case 0x90: msg = new RequestDismissAlly(); break; case 0x91: msg = new RequestSetAllyCrest(); break; case 0x92: msg = new RequestAllyCrest(); break; case 0x93: msg = new RequestChangePetName(); break; case 0x94: msg = new RequestPetUseItem(); break; case 0x95: msg = new RequestGiveItemToPet(); break; case 0x96: msg = new RequestPrivateStoreQuitSell(); break; case 0x97: msg = new SetPrivateStoreMsgSell(); break; case 0x98: msg = new RequestPetGetItem(); break; case 0x99: msg = new RequestPrivateStoreManageBuy(); break; case 0x9a: msg = new SetPrivateStoreListBuy(); break; case 0x9c: msg = new RequestPrivateStoreQuitBuy(); break; case 0x9d: msg = new SetPrivateStoreMsgBuy(); break; case 0x9f: // SendPrivateStoreBuyList msg = new RequestPrivateStoreSell(); break; case 0xa0: //SendTimeCheckPacket break; case 0xa6: // RequestSkillCoolTime break; case 0xa7: msg = new RequestPackageSendableItemList(); break; case 0xa8: msg = new RequestPackageSend(); break; case 0xa9: msg = new RequestBlock(); break; case 0xaa: msg = new RequestSiegeInfo(); break; case 0xab: msg = new RequestSiegeAttackerList(); break; case 0xac: msg = new RequestSiegeDefenderList(); break; case 0xad: msg = new RequestJoinSiege(); break; case 0xae: msg = new RequestConfirmSiegeWaitingList(); break; case 0xaf: // RequestSetCastleSiegeTime break; case 0xb0: msg = new MultiSellChoose(); break; case 0xb1: // NetPing break; case 0xb2: msg = new RequestRemainTime(); break; case 0xb3: msg = new BypassUserCmd(); break; case 0xb4: msg = new SnoopQuit(); break; case 0xb5: msg = new RequestRecipeBookOpen(); break; case 0xb6: // RequestRecipeItemDelete msg = new RequestRecipeBookDestroy(); break; case 0xb7: msg = new RequestRecipeItemMakeInfo(); break; case 0xb8: msg = new RequestRecipeItemMakeSelf(); break; case 0xb9: // RequestRecipeShopManageList break; case 0xba: msg = new RequestRecipeShopMessageSet(); break; case 0xbb: msg = new RequestRecipeShopListSet(); break; case 0xbc: msg = new RequestRecipeShopManageQuit(); break; case 0xbd: // RequestRecipeShopManageCancel break; case 0xbe: msg = new RequestRecipeShopMakeInfo(); break; case 0xbf: msg = new RequestRecipeShopMakeItem(); break; case 0xc0: msg = new RequestRecipeShopSellList(); break; case 0xc1: msg = new RequestObserverEnd(); break; case 0xc2: // VoteSociality msg = new VoteSociality(); break; case 0xc3: // RequestHennaItemList msg = new RequestHennaDrawList(); break; case 0xc4: msg = new RequestHennaItemDrawInfo(); break; case 0xc5: msg = new RequestBuySeed(); break; case 0xc6: msg = new ConfirmDlgAnswer(); break; case 0xc7: msg = new RequestWearItem(); break; case 0xc8: msg = new RequestSSQStatus(); break; case 0xc9: // PetitionVote break; case 0xcb: msg = new GameGuardReply(); break; case 0xcc: // Clan Privileges msg = new RequestPledgePower(); break; case 0xcd: msg = new RequestMakeMacro(); break; case 0xce: msg = new RequestDeleteMacro(); break; // Manor case 0xcf: // RequestProcureCrop msg = new RequestBuyProcure(); break; case 0xd0: int id2 = -1; if (buf.remaining() >= 2) { id2 = buf.getShort() & 0xffff; } else { if (Config.PACKET_HANDLER_DEBUG) _log.warn("Client: " + client.toString() + " sent a 0xd0 without the second opcode."); break; } switch (id2) { case 0x01: msg = new RequestManorList(); break; case 0x02: msg = new RequestProcureCropList(); break; case 0x03: msg = new RequestSetSeed(); break; case 0x04: msg = new RequestSetCrop(); break; case 0x05: msg = new RequestWriteHeroWords(); break; case 0x06: msg = new RequestExAskJoinMPCC(); break; case 0x07: msg = new RequestExAcceptJoinMPCC(); break; case 0x08: msg = new RequestExOustFromMPCC(); break; case 0x09: msg = new RequestOustFromPartyRoom(); break; case 0x0a: msg = new RequestDismissPartyRoom(); break; case 0x0b: msg = new RequestWithdrawPartyRoom(); break; case 0x0c: msg = new RequestChangePartyLeader(); break; case 0x0d: msg = new RequestAutoSoulShot(); break; case 0x0e: msg = new RequestExEnchantSkillInfo(); break; case 0x0f: msg = new RequestExEnchantSkill(); break; case 0x10: msg = new RequestExPledgeCrestLarge(); break; case 0x11: msg = new RequestExSetPledgeCrestLarge(); break; case 0x12: msg = new RequestPledgeSetAcademyMaster(); break; case 0x13: msg = new RequestPledgePowerGradeList(); break; case 0x14: msg = new RequestPledgeMemberPowerInfo(); break; case 0x15: msg = new RequestPledgeSetMemberPowerGrade(); break; case 0x16: msg = new RequestPledgeMemberInfo(); break; case 0x17: msg = new RequestPledgeWarList(); break; case 0x18: msg = new RequestExFishRanking(); break; case 0x19: msg = new RequestPCCafeCouponUse(); break; case 0x1b: msg = new RequestDuelStart(); break; case 0x1c: msg = new RequestDuelAnswerStart(); break; case 0x1d: // RequestExSetTutorial break; case 0x1e: msg = new RequestExRqItemLink(); break; case 0x1f: // CanNotMoveAnymoreAirShip break; case 0x20: msg = new MoveToLocationInAirShip(); break; case 0x21: msg = new RequestKeyMapping(); break; case 0x22: // RequestSaveKeyMapping break; case 0x23: msg = new RequestExRemoveItemAttribute(); break; case 0x24: msg = new RequestSaveInventoryOrder(); break; case 0x25: msg = new RequestExitPartyMatchingWaitingRoom(); break; case 0x26: msg = new RequestConfirmTargetItem(); break; case 0x27: msg = new RequestConfirmRefinerItem(); break; case 0x28: msg = new RequestConfirmGemStone(); break; case 0x29: msg = new RequestOlympiadObserverEnd(); break; case 0x2a: msg = new RequestCursedWeaponList(); break; case 0x2b: msg = new RequestCursedWeaponLocation(); break; case 0x2c: msg = new RequestPledgeReorganizeMember(); break; case 0x2d: msg = new RequestExMPCCShowPartyMembersInfo(); break; case 0x2e: msg = new RequestOlympiadMatchList(); break; case 0x2f: msg = new RequestAskJoinPartyRoom(); break; case 0x30: msg = new AnswerJoinPartyRoom(); break; case 0x31: msg = new RequestListPartyMatchingWaitingRoom(); break; case 0x32: msg = new RequestExEnchantSkillSafe(); break; case 0x33: msg = new RequestExEnchantSkillUntrain(); break; case 0x34: msg = new RequestExEnchantSkillRouteChange(); break; case 0x35: msg = new RequestExEnchantItemAttribute(); break; case 0x36: msg = new ExGetOnAirShip(); break; case 0x38: // MoveToLocationAirShip break; case 0x39: msg = new RequestBidItemAuction(); break; case 0x3a: msg = new RequestInfoItemAuction(); break; case 0x3b: msg = new RequestExChangeName(); break; case 0x3c: msg = new RequestAllCastleInfo(); break; case 0x3d: msg = new RequestAllFortressInfo(); break; case 0x3e: msg = new RequestAllAgitInfo(); break; case 0x3f: msg = new RequestFortressSiegeInfo(); break; case 0x40: msg = new RequestGetBossRecord(); break; case 0x41: msg = new RequestRefine(); break; case 0x42: msg = new RequestConfirmCancelItem(); break; case 0x43: msg = new RequestRefineCancel(); break; case 0x44: msg = new RequestExMagicSkillUseGround(); break; case 0x45: msg = new RequestDuelSurrender(); break; case 0x46: msg = new RequestExEnchantSkillInfoDetail(); break; case 0x48: msg = new RequestFortressMapInfo(); break; case 0x49: msg = new RequestPVPMatchRecord(); break; case 0x4a: msg = new SetPrivateStoreWholeMsg(); break; case 0x4b: msg = new RequestDispel(); break; case 0x4c: msg = new RequestExTryToPutEnchantTargetItem(); break; case 0x4d: msg = new RequestExTryToPutEnchantSupportItem(); break; case 0x4e: msg = new RequestExCancelEnchantItem(); break; case 0x4f: msg = new RequestChangeNicknameColor(); break; case 0x50: msg = new RequestResetNickname(); break; case 0x51: int id3 = 0; if (buf.remaining() >= 4) { id3 = buf.getInt() & 0xffffffff; } else { if (Config.PACKET_HANDLER_DEBUG) _log.warn("Client: " + client + " sent a 0xd0:0x51 without the third opcode."); break; } switch (id3) { case 0x00: msg = new RequestBookMarkSlotInfo(); break; case 0x01: msg = new RequestSaveBookMarkSlot(); break; case 0x02: msg = new RequestModifyBookMarkSlot(); break; case 0x03: msg = new RequestDeleteBookMarkSlot(); break; case 0x04: msg = new RequestTeleportBookMark(); break; case 0x05: // RequestChangeBookMarkSlot break; default: printDebug(buf, client, opcode, id2, id3); break; } break; case 0x52: msg = new RequestWithDrawPremiumItem(); break; case 0x53: msg = new RequestJump(); break; case 0x54: msg = new RequestStartShowCrataeCubeRank(); break; case 0x55: msg = new RequestStopShowCrataeCubeRank(); break; case 0x56: msg = new NotifyStartMiniGame(); break; case 0x57: msg = new RequestJoinDominionWar(); break; case 0x58: msg = new RequestDominionInfo(); break; case 0x59: msg = new RequestExCleftEnter(); break; case 0x5a: id3 = 0; if (buf.remaining() >= 4) { id3 = buf.getInt() & 0xffffffff; } else { _log.warn("Client: " + client + " sent a 0xd0:0x5a without the third opcode."); break; } switch (id3) { case 0x00: msg = new RequestExCubeGameChangeTeam(); break; default: printDebug(buf, client, opcode, id2, id3); break; } break; case 0x5b: msg = new EndScenePlayer(); break; case 0x5c: msg = new RequestExBlockGameVote(); break; case 0x63: msg = new RequestSeedPhase(); break; case 0x65: msg = new BrGamePoint(); break; case 0x66: msg = new BrProductList(); break; case 0x67: msg = new BrProductInfo(); break; case 0x68: msg = new BrBuyProduct(); break; default: printDebug(buf, client, opcode, id2); break; } break; /* * case 0xee: msg = new RequestChangePartyLeader(data, * _client); break; */ default: printDebug(buf, client, opcode); break; } break; } return msg; }
From source file:com.l2jfree.gameserver.network.L2ClientPacketHandler.java
@Override public L2ClientPacket handlePacket(ByteBuffer buf, L2Client client, final int opcode) { L2ClientPacket msg = null;// w w w . j a v a 2 s.co m GameClientState state = client.getState(); switch (state) { case CONNECTED: switch (opcode) { /* Commented out by Kerberos: not useful anymore case 0x00: if (Config.PACKET_HANDLER_DEBUG) _log.warn("Client " + client.toString() + " is trying to connect using Interlude Client"); break; */ case 0x0e: msg = new ProtocolVersion(); break; case 0x2b: msg = new AuthLogin(); break; default: printDebug(buf, client, opcode); break; } break; case AUTHED: switch (opcode) { case 0x00: msg = new Logout(); break; case 0x0c: msg = new NewCharacter(); break; case 0x0d: msg = new CharacterDelete(); break; case 0x12: msg = new CharacterSelected(); break; case 0x13: msg = new NewCharacterInit(); break; /* Commented out by Kerberos: not being used anymore case 0x54: // client send this packet when u are on boat and u relog game X_x break; */ case 0x67: msg = new RequestPledgeCrest(); break; case 0x7b: msg = new CharacterRestore(); break; case 0xd0: int id2 = -1; if (buf.remaining() >= 2) { id2 = buf.getShort() & 0xffff; } else { if (Config.PACKET_HANDLER_DEBUG) _log.warn("Client: " + client.toString() + " sent a 0xd0 without the second opcode."); break; } // single packet if (id2 == 0x39 || id2 == 0x36) { msg = new CharacterPrevState(); } else { printDebug(buf, client, opcode, id2); } break; // to avoid unnecessary warning about invalid opcode (if the client lags a bit, then it starts spamming this packet) case 0x59: // ValidatePosition break; // default: printDebug(buf, client, opcode); break; } break; case IN_GAME: switch (opcode) { // to avoid unnecessary warning about invalid opcode (player clicked the button multiple times) case 0x12: // CharacterSelected break; // case 0x00: msg = new Logout(); break; case 0x01: msg = new AttackRequest(); break; case 0x03: msg = new RequestStartPledgeWar(); break; case 0x04: msg = new RequestReplyStartPledgeWar(); break; case 0x05: msg = new RequestStopPledgeWar(); break; case 0x06: msg = new RequestReplyStopPledgeWar(); break; case 0x07: msg = new RequestSurrenderPledgeWar(); break; case 0x08: msg = new RequestReplySurrenderPledgeWar(); break; case 0x09: msg = new RequestSetPledgeCrest(); break; case 0x0b: msg = new RequestGiveNickName(); break; case 0x0f: msg = new MoveBackwardToLocation(); break; case 0x11: msg = new EnterWorld(); break; case 0x14: msg = new RequestItemList(); break; case 0x16: msg = new RequestUnEquipItem(); // confirm break; case 0x17: msg = new RequestDropItem(); break; case 0x19: msg = new UseItem(); break; case 0x1a: msg = new TradeRequest(); break; case 0x1b: msg = new AddTradeItem(); break; case 0x1c: msg = new TradeDone(); break; case 0x1f: msg = new Action(); break; case 0x22: msg = new RequestLinkHtml(); break; case 0x23: msg = new RequestBypassToServer(); break; case 0x24: msg = new RequestBBSwrite(); break; case 0x26: msg = new RequestJoinPledge(); break; case 0x27: msg = new RequestAnswerJoinPledge(); break; case 0x28: msg = new RequestWithdrawalPledge(); break; case 0x29: msg = new RequestOustPledgeMember(); break; case 0x2c: msg = new RequestGetItemFromPet(); break; case 0x2e: msg = new RequestAllyInfo(); break; case 0x2f: msg = new RequestCrystallizeItem(); break; case 0x30: // t1 ?? msg = new RequestPrivateStoreManageSell(); break; case 0x31: // t1 ?? msg = new SetPrivateStoreListSell(); break; // case 0x32: // msg = new RequestPrivateStoreManageCancel(data, _client); // break; case 0x34: msg = new RequestSocialAction(); break; case 0x35: msg = new ChangeMoveType(); break; case 0x36: msg = new ChangeWaitType(); break; case 0x37: msg = new RequestSellItem(); break; case 0x39: msg = new RequestMagicSkillUse(); break; case 0x3a: msg = new SendAppearing(); // (after death) break; case 0x3b: if (Config.ALLOW_WAREHOUSE) msg = new SendWareHouseDepositList(); break; case 0x3c: msg = new SendWareHouseWithDrawList(); break; case 0x3d: msg = new RequestShortCutReg(); break; case 0x3f: msg = new RequestShortCutDel(); break; case 0x40: // t1 ?? msg = new RequestBuyItem(); break; case 0x42: msg = new RequestJoinParty(); break; case 0x43: msg = new RequestAnswerJoinParty(); break; case 0x44: msg = new RequestWithDrawalParty(); break; case 0x45: msg = new RequestOustPartyMember(); break; case 0x46: // RequestDismissParty break; case 0x47: msg = new CannotMoveAnymore(); break; case 0x48: msg = new RequestTargetCanceld(); break; case 0x49: msg = new Say2(); break; case 0x4d: msg = new RequestPledgeMemberList(); break; case 0x4f: msg = new DummyPacket(); break; case 0x50: msg = new RequestSkillList(); break; case 0x52: msg = new MoveWithDelta(); break; case 0x53: msg = new RequestGetOnVehicle(); break; case 0x54: msg = new RequestGetOffVehicle(); break; case 0x55: msg = new AnswerTradeRequest(); break; case 0x56: msg = new RequestActionUse(); break; case 0x57: msg = new RequestRestart(); break; case 0x58: msg = new RequestSiegeInfo(); break; case 0x59: // t1 ?? msg = new ValidatePosition(); break; // case 0x5a: // // RequestSEKCustom // break; // THESE ARE NOW TEMPORARY DISABLED case 0x5b: //new StartRotating(); break; case 0x5c: //new FinishRotating(); break; case 0x5e: msg = new RequestShowBoard(); break; case 0x5f: msg = new RequestEnchantItem(); break; case 0x60: msg = new RequestDestroyItem(); break; case 0x62: msg = new RequestQuestList(); break; case 0x63: msg = new RequestQuestAbort(); break; case 0x65: msg = new RequestPledgeInfo(); break; case 0x66: msg = new RequestPledgeExtendedInfo(); break; case 0x67: msg = new RequestPledgeCrest(); break; case 0x6f: msg = new RequestHennaEquip(); break; case 0x70: msg = new RequestHennaRemoveList(); break; case 0x71: msg = new RequestHennaItemRemoveInfo(); break; case 0x72: msg = new RequestHennaRemove(); break; case 0x73: // send when talking to trainer npc, to show list of available skills msg = new RequestAquireSkillInfo();// --> [s] 0xa4; break; case 0x74: msg = new SendBypassBuildCmd(); break; case 0x75: msg = new RequestMoveToLocationInVehicle(); break; case 0x76: msg = new CannotMoveAnymoreInVehicle(); break; case 0x77: msg = new RequestFriendInvite(); break; case 0x78: msg = new RequestAnswerFriendInvite(); break; case 0x79: msg = new RequestFriendList(); break; case 0x7a: msg = new RequestFriendDel(); break; case 0x7c: // send when a skill to be learned is selected msg = new RequestAquireSkill(); break; case 0x7d: msg = new RequestRestartPoint(); break; case 0x7e: msg = new RequestGMCommand(); break; case 0x7f: msg = new RequestPartyMatchConfig(); break; case 0x80: msg = new RequestPartyMatchList(); break; case 0x81: msg = new RequestPartyMatchDetail(); break; // case 0x82: // // RequestPrivateStoreList // break; case 0x83: msg = new RequestPrivateStoreBuy(); break; case 0x85: msg = new RequestTutorialLinkHtml(); break; case 0x86: msg = new RequestTutorialPassCmdToServer(); break; case 0x87: msg = new RequestTutorialQuestionMark(); break; case 0x88: msg = new RequestTutorialClientEvent(); break; case 0x89: msg = new RequestPetition(); break; case 0x8a: msg = new RequestPetitionCancel(); break; case 0x8b: msg = new RequestGmList(); break; case 0x8c: msg = new RequestJoinAlly(); break; case 0x8d: msg = new RequestAnswerJoinAlly(); break; case 0x8e: msg = new RequestWithdrawAlly(); break; case 0x8f: msg = new RequestOustAlly(); break; case 0x90: msg = new RequestDismissAlly(); break; case 0x91: msg = new RequestSetAllyCrest(); break; case 0x92: msg = new RequestAllyCrest(); break; case 0x93: msg = new RequestChangePetName(); break; case 0x94: msg = new RequestPetUseItem(); break; case 0x95: msg = new RequestGiveItemToPet(); break; case 0x96: msg = new RequestPrivateStoreQuitSell(); break; case 0x97: msg = new SetPrivateStoreMsgSell(); break; case 0x98: msg = new RequestPetGetItem(); break; case 0x99: msg = new RequestPrivateStoreManageBuy(); break; case 0x9a: msg = new SetPrivateStoreListBuy(); break; // case 0x92: // // RequestPrivateStoreBuyManageCancel // break; case 0x9c: msg = new RequestPrivateStoreQuitBuy(); break; case 0x9d: msg = new SetPrivateStoreMsgBuy(); break; // case 0x95: // // RequestPrivateStoreBuyList // break; case 0x9f: msg = new RequestPrivateStoreSell(); break; // case 0x97: // // SendTimeCheckPacket // break; // case 0x98: // // RequestStartAllianceWar // break; // case 0x99: // // ReplyStartAllianceWar // break; // case 0x9a: // // RequestStopAllianceWar // break; // case 0x9b: // // ReplyStopAllianceWar // break; // case 0x9c: // // RequestSurrenderAllianceWar // break; case 0xa6: // RequestSkillCoolTime /*if (Config.DEBUG) _log.info("Request Skill Cool Time .. ignored"); msg = null;*/ break; case 0xa7: msg = new RequestPackageSendableItemList(); break; case 0xa8: msg = new RequestPackageSend(); break; case 0xa9: msg = new RequestBlock(); break; case 0xaa: // RequestCastleSiegeInfo break; case 0xab: msg = new RequestSiegeAttackerList(); break; case 0xac: msg = new RequestSiegeDefenderList(); break; case 0xad: msg = new RequestJoinSiege(); break; case 0xae: msg = new RequestConfirmSiegeWaitingList(); break; // case 0xaf: // // RequestSetCastleSiegeTime // break; case 0xb0: msg = new MultiSellChoose(); break; // case 0xb1: // // NetPing // break; case 0xb3: msg = new BypassUserCmd(); break; case 0xb4: msg = new SnoopQuit(); break; case 0xb5: // we still need this packet to handle BACK button of craft dialog msg = new RequestRecipeBookOpen(); break; case 0xb6: msg = new RequestRecipeBookDestroy(); break; case 0xb7: msg = new RequestRecipeItemMakeInfo(); break; case 0xb8: msg = new RequestRecipeItemMakeSelf(); break; //case 0xb9: // msg = new RequestRecipeShopManageList(data, client); // break; case 0xba: msg = new RequestRecipeShopMessageSet(); break; case 0xbb: msg = new RequestRecipeShopListSet(); break; case 0xbc: msg = new RequestRecipeShopManageQuit(); break; case 0xbe: msg = new RequestRecipeShopMakeInfo(); break; case 0xbf: msg = new RequestRecipeShopMakeItem(); break; case 0xc0: msg = new RequestRecipeShopSellList(); break; case 0xc1: msg = new RequestObserverEnd(); break; case 0xc2: msg = new VoteSociality(); break; case 0xc3: msg = new RequestHennaDrawList(); break; case 0xc4: msg = new RequestHennaItemDrawInfo(); break; case 0xcc: // Clan Privileges msg = new RequestPledgePower(); break; case 0xcd: msg = new RequestMakeMacro(); break; case 0xce: msg = new RequestDeleteMacro(); break; // Manor case 0xcf: msg = new RequestBuyProcure(); break; case 0xc5: msg = new RequestBuySeed(); break; case 0xc6: msg = new ConfirmDlgAnswer(); break; case 0xc7: msg = new RequestWearItem(); break; case 0xc8: msg = new RequestSSQStatus(); break; case 0xcb: msg = new GameGuardReply(); break; case 0x6b: msg = new RequestSendFriendMsg(); break; case 0x6c: msg = new RequestShowMiniMap(); break; case 0x6d: // MSN dialogs so that you dont see them in the console. break; case 0x6e: //record video msg = new RequestRecordInfo(); break; case 0xd0: int id2 = -1; if (buf.remaining() >= 2) { id2 = buf.getShort() & 0xffff; } else { if (Config.PACKET_HANDLER_DEBUG) _log.warn("Client: " + client.toString() + " sent a 0xd0 without the second opcode."); break; } switch (id2) { case 0x01: msg = new RequestManorList(); break; case 0x02: msg = new RequestProcureCropList(); break; case 0x03: msg = new RequestSetSeed(); break; case 0x04: msg = new RequestSetCrop(); break; case 0x05: msg = new RequestWriteHeroWords(); break; case 0x06: msg = new RequestExAskJoinMPCC(); break; case 0x07: msg = new RequestExAcceptJoinMPCC(); break; case 0x08: msg = new RequestExOustFromMPCC(); break; case 0x09: msg = new RequestOustFromPartyRoom(); break; case 0x0a: msg = new RequestDismissPartyRoom(); break; case 0x0b: msg = new RequestWithdrawPartyRoom(); break; case 0x0c: msg = new RequestChangePartyLeader(); break; case 0x0d: msg = new RequestAutoSoulShot(); break; case 0x0e: msg = new RequestExEnchantSkillInfo(); break; case 0x0f: msg = new RequestExEnchantSkill(); break; case 0x10: msg = new RequestExPledgeCrestLarge(); break; case 0x11: msg = new RequestExSetPledgeCrestLarge(); break; case 0x12: msg = new RequestPledgeSetAcademyMaster(); break; case 0x13: msg = new RequestPledgePowerGradeList(); break; case 0x14: msg = new RequestPledgeMemberPowerInfo(); break; case 0x15: msg = new RequestPledgeSetMemberPowerGrade(); break; case 0x16: msg = new RequestPledgeMemberInfo(); break; case 0x17: msg = new RequestPledgeWarList(); break; case 0x18: msg = new RequestExFishRanking(); break; case 0x19: msg = new RequestPCCafeCouponUse(); break; case 0x1b: msg = new RequestDuelStart(); break; case 0x1c: msg = new RequestDuelAnswerStart(); break; case 0x1e: msg = new RequestExRqItemLink(); break; case 0x21: msg = new RequestKeyMapping(); break; case 0x22: // TODO implement me (just disabling warnings for this packet) break; case 0x23: msg = new RequestExRemoveItemAttribute(); break; case 0x24: msg = new RequestSaveInventoryOrder(); break; case 0x25: msg = new RequestExitPartyMatchingWaitingRoom(); break; case 0x26: msg = new RequestConfirmTargetItem(); break; case 0x27: msg = new RequestConfirmRefinerItem(); break; case 0x28: msg = new RequestConfirmGemStone(); break; case 0x29: msg = new RequestOlympiadObserverEnd(); break; case 0x2a: msg = new RequestCursedWeaponList(); break; case 0x2b: msg = new RequestCursedWeaponLocation(); break; case 0x2c: msg = new RequestPledgeReorganizeMember(); break; case 0x2e: msg = new RequestExMPCCShowPartyMembersInfo(); break; case 0x2f: msg = new RequestOlympiadMatchList(); break; case 0x30: msg = new RequestAskJoinPartyRoom(); break; case 0x31: msg = new AnswerJoinPartyRoom(); break; case 0x32: msg = new RequestListPartyMatchingWaitingRoom(); break; case 0x33: msg = new RequestExEnchantSkillSafe(); break; case 0x34: msg = new RequestExEnchantSkillUntrain(); break; case 0x35: msg = new RequestExEnchantSkillRouteChange(); break; case 0x36: msg = new ExGetOnAirShip(); break; case 0x38: msg = new RequestExEnchantItemAttribute(); break; case 0x3f: msg = new RequestAllCastleInfo(); break; case 0x40: msg = new RequestAllFortressInfo(); break; case 0x41: msg = new RequestAllAgitInfo(); break; case 0x42: msg = new RequestFortressSiegeInfo(); break; case 0x43: msg = new RequestGetBossRecord(); break; case 0x44: msg = new RequestRefine(); break; case 0x45: msg = new RequestConfirmCancelItem(); break; case 0x46: msg = new RequestRefineCancel(); break; case 0x47: msg = new RequestExMagicSkillUseGround(); break; case 0x48: msg = new RequestDuelSurrender(); break; case 0x49: msg = new RequestExEnchantSkillInfoDetail(); break; case 0x4b: msg = new RequestFortressMapInfo(); break; case 0x4d: msg = new SetPrivateStoreWholeMsg(); break; case 0x4e: msg = new RequestDispel(); break; case 0x4f: msg = new RequestExTryToPutEnchantTargetItem(); break; case 0x50: msg = new RequestExTryToPutEnchantSupportItem(); break; case 0x51: msg = new RequestExCancelEnchantItem(); break; case 0x52: msg = new RequestChangeNicknameColor(); break; case 0x53: msg = new RequestResetNickname(); break; case 0x54: // TODO: implement me (just disabling warnings for this packet) break; case 0x58: // TODO: implement me (just disabling warnings for this packet) break; default: printDebug(buf, client, opcode, id2); break; } break; /*case 0xee: msg = new RequestChangePartyLeader(data, _client); break;*/ default: printDebug(buf, client, opcode); break; } break; } return msg; }
From source file:org.apache.bookkeeper.bookie.BookieShell.java
/** * Format the message into a readable format. * * @param pos//from w w w . j av a 2s . c o m * File offset of the message stored in entry log file * @param recBuff * Entry Data * @param printMsg * Whether printing the message body */ private void formatEntry(long pos, ByteBuffer recBuff, boolean printMsg) { long ledgerId = recBuff.getLong(); long entryId = recBuff.getLong(); int entrySize = recBuff.limit(); System.out.println("--------- Lid=" + ledgerId + ", Eid=" + entryId + ", ByteOffset=" + pos + ", EntrySize=" + entrySize + " ---------"); if (entryId == Bookie.METAENTRY_ID_LEDGER_KEY) { int masterKeyLen = recBuff.getInt(); byte[] masterKey = new byte[masterKeyLen]; recBuff.get(masterKey); System.out.println("Type: META"); System.out.println("MasterKey: " + bytes2Hex(masterKey)); System.out.println(); return; } if (entryId == Bookie.METAENTRY_ID_FENCE_KEY) { System.out.println("Type: META"); System.out.println("Fenced"); System.out.println(); return; } // process a data entry long lastAddConfirmed = recBuff.getLong(); System.out.println("Type: DATA"); System.out.println("LastConfirmed: " + lastAddConfirmed); if (!printMsg) { System.out.println(); return; } // skip digest checking recBuff.position(32 + 8); System.out.println("Data:"); System.out.println(); try { byte[] ret = new byte[recBuff.remaining()]; recBuff.get(ret); formatter.formatEntry(ret); } catch (Exception e) { System.out.println("N/A. Corrupted."); } System.out.println(); }
From source file:com.google.wireless.speed.speedometer.measurements.HttpTask.java
/** Runs the HTTP measurement task. Will acquire power lock to ensure wifi is not turned off */ @Override// w w w.j a v a 2s . co m public MeasurementResult call() throws MeasurementError { int statusCode = HttpTask.DEFAULT_STATUS_CODE; long duration = 0; long originalHeadersLen = 0; long originalBodyLen; String headers = null; ByteBuffer body = ByteBuffer.allocate(HttpTask.MAX_BODY_SIZE_TO_UPLOAD); boolean success = false; String errorMsg = ""; InputStream inputStream = null; try { // set the download URL, a URL that points to a file on the Internet // this is the file to be downloaded HttpDesc task = (HttpDesc) this.measurementDesc; String urlStr = task.url; // TODO(Wenjie): Need to set timeout for the HTTP methods httpClient = AndroidHttpClient.newInstance(Util.prepareUserAgent(this.parent)); HttpRequestBase request = null; if (task.method.compareToIgnoreCase("head") == 0) { request = new HttpHead(urlStr); } else if (task.method.compareToIgnoreCase("get") == 0) { request = new HttpGet(urlStr); } else if (task.method.compareToIgnoreCase("post") == 0) { request = new HttpPost(urlStr); HttpPost postRequest = (HttpPost) request; postRequest.setEntity(new StringEntity(task.body)); } else { // Use GET by default request = new HttpGet(urlStr); } if (task.headers != null && task.headers.trim().length() > 0) { for (String headerLine : task.headers.split("\r\n")) { String tokens[] = headerLine.split(":"); if (tokens.length == 2) { request.addHeader(tokens[0], tokens[1]); } else { throw new MeasurementError("Incorrect header line: " + headerLine); } } } byte[] readBuffer = new byte[HttpTask.READ_BUFFER_SIZE]; int readLen; int totalBodyLen = 0; long startTime = System.currentTimeMillis(); HttpResponse response = httpClient.execute(request); /* TODO(Wenjie): HttpClient does not automatically handle the following codes * 301 Moved Permanently. HttpStatus.SC_MOVED_PERMANENTLY * 302 Moved Temporarily. HttpStatus.SC_MOVED_TEMPORARILY * 303 See Other. HttpStatus.SC_SEE_OTHER * 307 Temporary Redirect. HttpStatus.SC_TEMPORARY_REDIRECT * * We may want to fetch instead from the redirected page. */ StatusLine statusLine = response.getStatusLine(); if (statusLine != null) { statusCode = statusLine.getStatusCode(); success = (statusCode == 200); } /* For HttpClient to work properly, we still want to consume the entire response even if * the status code is not 200 */ HttpEntity responseEntity = response.getEntity(); originalBodyLen = responseEntity.getContentLength(); long expectedResponseLen = HttpTask.MAX_HTTP_RESPONSE_SIZE; // getContentLength() returns negative number if body length is unknown if (originalBodyLen > 0) { expectedResponseLen = originalBodyLen; } if (responseEntity != null) { inputStream = responseEntity.getContent(); while ((readLen = inputStream.read(readBuffer)) > 0 && totalBodyLen <= HttpTask.MAX_HTTP_RESPONSE_SIZE) { totalBodyLen += readLen; // Fill in the body to report up to MAX_BODY_SIZE if (body.remaining() > 0) { int putLen = body.remaining() < readLen ? body.remaining() : readLen; body.put(readBuffer, 0, putLen); } this.progress = (int) (100 * totalBodyLen / expectedResponseLen); this.progress = Math.min(Config.MAX_PROGRESS_BAR_VALUE, progress); broadcastProgressForUser(this.progress); } duration = System.currentTimeMillis() - startTime; } Header[] responseHeaders = response.getAllHeaders(); if (responseHeaders != null) { headers = ""; for (Header hdr : responseHeaders) { /* * TODO(Wenjie): There can be preceding and trailing white spaces in * each header field. I cannot find internal methods that return the * number of bytes in a header. The solution here assumes the encoding * is one byte per character. */ originalHeadersLen += hdr.toString().length(); headers += hdr.toString() + "\r\n"; } } PhoneUtils phoneUtils = PhoneUtils.getPhoneUtils(); MeasurementResult result = new MeasurementResult(phoneUtils.getDeviceInfo().deviceId, phoneUtils.getDeviceProperty(), HttpTask.TYPE, System.currentTimeMillis() * 1000, success, this.measurementDesc); result.addResult("code", statusCode); if (success) { result.addResult("time_ms", duration); result.addResult("headers_len", originalHeadersLen); result.addResult("body_len", totalBodyLen); result.addResult("headers", headers); result.addResult("body", Base64.encodeToString(body.array(), Base64.DEFAULT)); } Log.i(SpeedometerApp.TAG, MeasurementJsonConvertor.toJsonString(result)); return result; } catch (MalformedURLException e) { errorMsg += e.getMessage() + "\n"; Log.e(SpeedometerApp.TAG, e.getMessage()); } catch (IOException e) { errorMsg += e.getMessage() + "\n"; Log.e(SpeedometerApp.TAG, e.getMessage()); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { Log.e(SpeedometerApp.TAG, "Fails to close the input stream from the HTTP response"); } } if (httpClient != null) { httpClient.close(); } } throw new MeasurementError("Cannot get result from HTTP measurement because " + errorMsg); }
From source file:edu.hawaii.soest.kilonalu.adcp.ADCPSource.java
/** * A method that executes the streaming of data from the source to the RBNB * server after all configuration of settings, connections to hosts, and * thread initiatizing occurs. This method contains the detailed code for * streaming the data and interpreting the stream. *///from w w w. j ava 2 s . c o m protected boolean execute() { // do not execute the stream if there is no connection if (!isConnected()) return false; boolean failed = false; SocketChannel socket = getSocketConnection(); // while data are being sent, read them into the buffer try { // create four byte placeholders used to evaluate up to a four-byte // window. The FIFO layout looks like: // ------------------------- // in ---> | One | Two |Three|Four | ---> out // ------------------------- byte byteOne = 0x00, // set initial placeholder values byteTwo = 0x00, byteThree = 0x00, byteFour = 0x00; // Create a buffer that will store the ensemble bytes as they are read ByteBuffer ensembleBuffer = ByteBuffer.allocate(getBufferSize()); // create a byte buffer to store bytes from the TCP stream ByteBuffer buffer = ByteBuffer.allocateDirect(getBufferSize()); // add a channel of data that will be pushed to the server. // Each ensemble will be sent to the Data Turbine as an rbnb frame. ChannelMap rbnbChannelMap = new ChannelMap(); int channelIndex = rbnbChannelMap.Add(getRBNBChannelName()); // while there are bytes to read from the socket ... while (socket.read(buffer) != -1 || buffer.position() > 0) { // prepare the buffer for reading buffer.flip(); // while there are unread bytes in the ByteBuffer while (buffer.hasRemaining()) { byteOne = buffer.get(); // Use a State Machine to process the byte stream. // Start building an rbnb frame for the entire ensemble, first by // inserting a timestamp into the channelMap. This time is merely // the time of insert into the data turbine, not the time of // observations of the measurements. That time should be parsed out // of the ensemble in the Sink client code System.out.print("\rProcessed byte # " + ensembleByteCount + " " + new String(Hex.encodeHex((new byte[] { byteOne }))) + " - log msg is: "); switch (state) { case 0: // find ensemble header id if (byteOne == 0x7F && byteTwo == 0x7F) { ensembleByteCount++; // add Header ID ensembleChecksum += (byteTwo & 0xFF); ensembleByteCount++; // add Data Source ID ensembleChecksum += (byteOne & 0xFF); state = 1; break; } else { break; } case 1: // find the Ensemble Length (LSB) ensembleByteCount++; // add Ensemble Byte Count (LSB) ensembleChecksum += (byteOne & 0xFF); state = 2; break; case 2: // find the Ensemble Length (MSB) ensembleByteCount++; // add Ensemble Byte Count (MSB) ensembleChecksum += (byteOne & 0xFF); int upperEnsembleByte = (byteOne & 0xFF) << 8; int lowerEnsembleByte = (byteTwo & 0xFF); ensembleBytes = upperEnsembleByte + lowerEnsembleByte; logger.debug("Number of Bytes in the Ensemble: " + ensembleBytes); if (ensembleBuffer.remaining() > 0) { ensembleBuffer.put(byteFour); ensembleBuffer.put(byteThree); ensembleBuffer.put(byteTwo); ensembleBuffer.put(byteOne); } else { ensembleBuffer.compact(); ensembleBuffer.put(byteFour); ensembleBuffer.put(byteThree); ensembleBuffer.put(byteTwo); ensembleBuffer.put(byteOne); } state = 3; break; // verify that the header is real, not a random 0x7F7F case 3: // find the number of data types in the ensemble // set the numberOfDataTypes byte if (ensembleByteCount == NUMBER_OF_DATA_TYPES_OFFSET - 1) { ensembleByteCount++; ensembleChecksum += (byteOne & 0xFF); numberOfDataTypes = (byteOne & 0xFF); // calculate the number of bytes to the Fixed Leader ID dataTypeOneOffset = 6 + (2 * numberOfDataTypes); if (ensembleBuffer.remaining() > 0) { ensembleBuffer.put(byteOne); } else { ensembleBuffer.compact(); ensembleBuffer.put(byteOne); } state = 4; break; } else { ensembleByteCount++; ensembleChecksum += (byteOne & 0xFF); if (ensembleBuffer.remaining() > 0) { ensembleBuffer.put(byteOne); } else { ensembleBuffer.compact(); ensembleBuffer.put(byteOne); } break; } case 4: // find the offset to data type #1 and verify the header ID if ((ensembleByteCount == dataTypeOneOffset + 1) && byteOne == 0x00 && byteTwo == 0x00) { ensembleByteCount++; ensembleChecksum += (byteOne & 0xFF); // we are confident that the previous sequence of 0x7F7F is truly // an headerID and not a random occurrence in the stream because // we have identified the Fixed Leader ID (0x0000) the correct // number of bytes beyond the 0x7F7F headerIsVerified = true; if (ensembleBuffer.remaining() > 0) { ensembleBuffer.put(byteOne); } else { ensembleBuffer.compact(); ensembleBuffer.put(byteOne); } state = 5; break; } else { if (ensembleByteCount > dataTypeOneOffset + 1) { // We've hit a random 0x7F7F byte sequence that is not a true // ensemble header id. Reset the processing and look for the // next 0x7F7F sequence in the stream ensembleByteCount = 0; ensembleChecksum = 0; dataTypeOneOffset = 0; numberOfDataTypes = 0; headerIsVerified = false; ensembleBuffer.clear(); rbnbChannelMap.Clear(); channelIndex = rbnbChannelMap.Add(getRBNBChannelName()); byteOne = 0x00; byteTwo = 0x00; byteThree = 0x00; byteFour = 0x00; state = 0; if (ensembleBuffer.remaining() > 0) { ensembleBuffer.put(byteOne); } else { ensembleBuffer.compact(); ensembleBuffer.put(byteOne); } break; } else { // We are still parsing bytes between the purported header ID // and fixed leader ID. Keep parsing until we hit the fixed // leader ID, or until we are greater than the dataTypeOneOffset // stated value. ensembleByteCount++; ensembleChecksum += (byteOne & 0xFF); if (ensembleBuffer.remaining() > 0) { ensembleBuffer.put(byteOne); } else { ensembleBuffer.compact(); ensembleBuffer.put(byteOne); } break; } } case 5: // read the rest of the bytes to the next Header ID // if we've made it to the next ensemble's header id, prepare to // flush the data. Also check that the calculated byte count // is greater than the recorded byte count in case of finding an // arbitrary 0x7f 0x7f sequence in the data stream if (byteOne == 0x7F && byteTwo == 0x7F && (ensembleByteCount == ensembleBytes + 3) && headerIsVerified) { // remove the last bytes from the count (byteOne and byteTwo) ensembleByteCount -= 1; // remove the last three bytes from the checksum: // the two checksum bytes are not included, and the two 0x7f //bytes belong to the next ensemble, and one of them was // previously added. Reset the buffer position due to this too. //ensembleChecksum -= (byteOne & 0xFF); ensembleChecksum -= (byteTwo & 0xFF); ensembleChecksum -= (byteThree & 0xFF); ensembleChecksum -= (byteFour & 0xFF); // We are consistently 1 byte over in the checksum. Trim it. We need to // troubleshoot why this is. CSJ 12/18/2007 ensembleChecksum = ensembleChecksum - 1; // jockey byteThree into LSB, byteFour into MSB int upperChecksumByte = (byteThree & 0xFF) << 8; int lowerChecksumByte = (byteFour & 0xFF); int trueChecksum = upperChecksumByte + lowerChecksumByte; if (ensembleBuffer.remaining() > 0) { ensembleBuffer.put((byte) lowerChecksumByte); ensembleBuffer.put((byte) (upperChecksumByte >> 8)); } else { ensembleBuffer.compact(); ensembleBuffer.put((byte) lowerChecksumByte); ensembleBuffer.put((byte) (upperChecksumByte >> 8)); } // check if the calculated checksum (modulo 65535) is equal // to the true checksum; if so, flush to the data turbine // Also, if the checksums are off by 1 byte, also flush the // data. We need to troubleshoot this bug CSJ 06/11/2008 if (((ensembleChecksum % 65535) == trueChecksum) || ((ensembleChecksum + 1) % 65535 == trueChecksum) || ((ensembleChecksum - 1) % 65535 == trueChecksum)) { // extract just the length of the ensemble bytes out of the // ensemble buffer, and place it in the channel map as a // byte array. Then, send it to the data turbine. byte[] ensembleArray = new byte[ensembleByteCount]; ensembleBuffer.flip(); ensembleBuffer.get(ensembleArray); // send the ensemble to the data turbine rbnbChannelMap.PutTimeAuto("server"); rbnbChannelMap.PutDataAsByteArray(channelIndex, ensembleArray); getSource().Flush(rbnbChannelMap); logger.debug("flushed: " + ensembleByteCount + " " + "ens cksum: " + ensembleChecksum + "\t\t" + "ens pos: " + ensembleBuffer.position() + "\t" + "ens rem: " + ensembleBuffer.remaining() + "\t" + "buf pos: " + buffer.position() + "\t" + "buf rem: " + buffer.remaining() + "\t" + "state: " + state); logger.info("Sent ADCP ensemble to the data turbine."); // only clear all four bytes if we are not one or two bytes // from the end of the byte buffer (i.e. the header id // is split or is all in the previous buffer) if (byteOne == 0x7f && byteTwo == 0x7f && ensembleByteCount > ensembleBytes && buffer.position() == 0) { byteThree = 0x00; byteFour = 0x00; logger.debug("Cleared ONLY b3, b4."); } else if (byteOne == 0x7f && ensembleByteCount > ensembleBytes && buffer.position() == 1) { buffer.position(buffer.position() - 1); byteTwo = 0x00; byteThree = 0x00; byteFour = 0x00; logger.debug("Cleared ONLY b2, b3, b4."); } else { byteOne = 0x00; byteTwo = 0x00; byteThree = 0x00; byteFour = 0x00; logger.debug("Cleared ALL b1, b2, b3, b4."); } //rewind the position to before the next ensemble's header id if (buffer.position() >= 2) { buffer.position(buffer.position() - 2); logger.debug("Moved position back two, now: " + buffer.position()); } ensembleBuffer.clear(); ensembleByteCount = 0; ensembleBytes = 0; ensembleChecksum = 0; state = 0; break; } else { // The checksums don't match, move on logger.info("not equal: " + "calc chksum: " + (ensembleChecksum % 65535) + "\tens chksum: " + trueChecksum + "\tbuf pos: " + buffer.position() + "\tbuf rem: " + buffer.remaining() + "\tens pos: " + ensembleBuffer.position() + "\tens rem: " + ensembleBuffer.remaining() + "\tstate: " + state); rbnbChannelMap.Clear(); channelIndex = rbnbChannelMap.Add(getRBNBChannelName()); ensembleBuffer.clear(); ensembleByteCount = 0; ensembleChecksum = 0; ensembleBuffer.clear(); state = 0; break; } } else { // still in the middle of the ensemble, keep adding bytes ensembleByteCount++; // add each byte found ensembleChecksum += (byteOne & 0xFF); if (ensembleBuffer.remaining() > 0) { ensembleBuffer.put(byteOne); } else { ensembleBuffer.compact(); ensembleBuffer.put(byteOne); } break; } } // shift the bytes in the FIFO window byteFour = byteThree; byteThree = byteTwo; byteTwo = byteOne; logger.debug("remaining:\t" + buffer.remaining() + "\tstate:\t" + state + "\tens byte count:\t" + ensembleByteCount + "\tens bytes:\t" + ensembleBytes + "\tver:\t" + headerIsVerified + "\tbyte value:\t" + new String(Hex.encodeHex((new byte[] { byteOne })))); } //end while (more unread bytes) // prepare the buffer to read in more bytes from the stream buffer.compact(); } // end while (more socket bytes to read) socket.close(); } catch (IOException e) { // handle exceptions // In the event of an i/o exception, log the exception, and allow execute() // to return false, which will prompt a retry. failed = true; e.printStackTrace(); return !failed; } catch (SAPIException sapie) { // In the event of an RBNB communication exception, log the exception, // and allow execute() to return false, which will prompt a retry. failed = true; sapie.printStackTrace(); return !failed; } return !failed; }
From source file:com.mobiperf_library.measurements.HttpTask.java
/** Runs the HTTP measurement task. Will acquire power lock to ensure wifi * is not turned off *//*from w w w . j a v a 2 s . c o m*/ @Override public MeasurementResult[] call() throws MeasurementError { int statusCode = HttpTask.DEFAULT_STATUS_CODE; long duration = 0; long originalHeadersLen = 0; long originalBodyLen; String headers = null; ByteBuffer body = ByteBuffer.allocate(HttpTask.MAX_BODY_SIZE_TO_UPLOAD); // boolean success = false; TaskProgress taskProgress = TaskProgress.FAILED; String errorMsg = ""; InputStream inputStream = null; try { // set the download URL, a URL that points to a file on the Internet // this is the file to be downloaded HttpDesc task = (HttpDesc) this.measurementDesc; String urlStr = task.url; // TODO(Wenjie): Need to set timeout for the HTTP methods httpClient = AndroidHttpClient.newInstance(Util.prepareUserAgent()); HttpRequestBase request = null; if (task.method.compareToIgnoreCase("head") == 0) { request = new HttpHead(urlStr); } else if (task.method.compareToIgnoreCase("get") == 0) { request = new HttpGet(urlStr); } else if (task.method.compareToIgnoreCase("post") == 0) { request = new HttpPost(urlStr); HttpPost postRequest = (HttpPost) request; postRequest.setEntity(new StringEntity(task.body)); } else { // Use GET by default request = new HttpGet(urlStr); } if (task.headers != null && task.headers.trim().length() > 0) { for (String headerLine : task.headers.split("\r\n")) { String tokens[] = headerLine.split(":"); if (tokens.length == 2) { request.addHeader(tokens[0], tokens[1]); } else { throw new MeasurementError("Incorrect header line: " + headerLine); } } } byte[] readBuffer = new byte[HttpTask.READ_BUFFER_SIZE]; int readLen; int totalBodyLen = 0; long startTime = System.currentTimeMillis(); HttpResponse response = httpClient.execute(request); /* TODO(Wenjie): HttpClient does not automatically handle the following codes * 301 Moved Permanently. HttpStatus.SC_MOVED_PERMANENTLY * 302 Moved Temporarily. HttpStatus.SC_MOVED_TEMPORARILY * 303 See Other. HttpStatus.SC_SEE_OTHER * 307 Temporary Redirect. HttpStatus.SC_TEMPORARY_REDIRECT * * We may want to fetch instead from the redirected page. */ StatusLine statusLine = response.getStatusLine(); if (statusLine != null) { statusCode = statusLine.getStatusCode(); if (statusCode == 200) { taskProgress = TaskProgress.COMPLETED; } else { taskProgress = TaskProgress.FAILED; } } /* For HttpClient to work properly, we still want to consume the entire * response even if the status code is not 200 */ HttpEntity responseEntity = response.getEntity(); originalBodyLen = responseEntity.getContentLength(); long expectedResponseLen = HttpTask.MAX_HTTP_RESPONSE_SIZE; // getContentLength() returns negative number if body length is unknown if (originalBodyLen > 0) { expectedResponseLen = originalBodyLen; } if (responseEntity != null) { inputStream = responseEntity.getContent(); while ((readLen = inputStream.read(readBuffer)) > 0 && totalBodyLen <= HttpTask.MAX_HTTP_RESPONSE_SIZE) { totalBodyLen += readLen; // Fill in the body to report up to MAX_BODY_SIZE if (body.remaining() > 0) { int putLen = body.remaining() < readLen ? body.remaining() : readLen; body.put(readBuffer, 0, putLen); } } duration = System.currentTimeMillis() - startTime;//TODO check this } Header[] responseHeaders = response.getAllHeaders(); if (responseHeaders != null) { headers = ""; for (Header hdr : responseHeaders) { /* * TODO(Wenjie): There can be preceding and trailing white spaces in * each header field. I cannot find internal methods that return the * number of bytes in a header. The solution here assumes the encoding * is one byte per character. */ originalHeadersLen += hdr.toString().length(); headers += hdr.toString() + "\r\n"; } } PhoneUtils phoneUtils = PhoneUtils.getPhoneUtils(); MeasurementResult result = new MeasurementResult(phoneUtils.getDeviceInfo().deviceId, phoneUtils.getDeviceProperty(), HttpTask.TYPE, System.currentTimeMillis() * 1000, taskProgress, this.measurementDesc); result.addResult("code", statusCode); if (taskProgress == TaskProgress.COMPLETED) { result.addResult("time_ms", duration); result.addResult("headers_len", originalHeadersLen); result.addResult("body_len", totalBodyLen); result.addResult("headers", headers); result.addResult("body", Base64.encodeToString(body.array(), Base64.DEFAULT)); } Logger.i(MeasurementJsonConvertor.toJsonString(result)); MeasurementResult[] mrArray = new MeasurementResult[1]; mrArray[0] = result; return mrArray; } catch (MalformedURLException e) { errorMsg += e.getMessage() + "\n"; Logger.e(e.getMessage()); } catch (IOException e) { errorMsg += e.getMessage() + "\n"; Logger.e(e.getMessage()); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { Logger.e("Fails to close the input stream from the HTTP response"); } } if (httpClient != null) { httpClient.close(); } } throw new MeasurementError("Cannot get result from HTTP measurement because " + errorMsg); }
From source file:com.healthmarketscience.jackcess.impl.TableImpl.java
/** * @param database database which owns this table * @param tableBuffer Buffer to read the table with * @param pageNumber Page number of the table definition * @param name Table name//from www . j a va 2 s .co m */ protected TableImpl(DatabaseImpl database, ByteBuffer tableBuffer, int pageNumber, String name, int flags) throws IOException { _database = database; _tableDefPageNumber = pageNumber; _name = name; _flags = flags; // read table definition tableBuffer = loadCompleteTableDefinitionBuffer(tableBuffer); _rowCount = tableBuffer.getInt(getFormat().OFFSET_NUM_ROWS); _lastLongAutoNumber = tableBuffer.getInt(getFormat().OFFSET_NEXT_AUTO_NUMBER); if (getFormat().OFFSET_NEXT_COMPLEX_AUTO_NUMBER >= 0) { _lastComplexTypeAutoNumber = tableBuffer.getInt(getFormat().OFFSET_NEXT_COMPLEX_AUTO_NUMBER); } _tableType = tableBuffer.get(getFormat().OFFSET_TABLE_TYPE); _maxColumnCount = tableBuffer.getShort(getFormat().OFFSET_MAX_COLS); _maxVarColumnCount = tableBuffer.getShort(getFormat().OFFSET_NUM_VAR_COLS); short columnCount = tableBuffer.getShort(getFormat().OFFSET_NUM_COLS); _logicalIndexCount = tableBuffer.getInt(getFormat().OFFSET_NUM_INDEX_SLOTS); _indexCount = tableBuffer.getInt(getFormat().OFFSET_NUM_INDEXES); tableBuffer.position(getFormat().OFFSET_OWNED_PAGES); _ownedPages = UsageMap.read(getDatabase(), tableBuffer, false); tableBuffer.position(getFormat().OFFSET_FREE_SPACE_PAGES); _freeSpacePages = UsageMap.read(getDatabase(), tableBuffer, false); for (int i = 0; i < _indexCount; i++) { _indexDatas.add(IndexData.create(this, tableBuffer, i, getFormat())); } readColumnDefinitions(tableBuffer, columnCount); readIndexDefinitions(tableBuffer); // read column usage map info while (tableBuffer.remaining() >= 2) { short umapColNum = tableBuffer.getShort(); if (umapColNum == IndexData.COLUMN_UNUSED) { break; } int pos = tableBuffer.position(); UsageMap colOwnedPages = null; UsageMap colFreeSpacePages = null; try { colOwnedPages = UsageMap.read(getDatabase(), tableBuffer, false); colFreeSpacePages = UsageMap.read(getDatabase(), tableBuffer, false); } catch (IllegalStateException e) { // ignore invalid usage map info colOwnedPages = null; colFreeSpacePages = null; tableBuffer.position(pos + 8); LOG.warn("Table " + _name + " invalid column " + umapColNum + " usage map definition: " + e); } for (ColumnImpl col : _columns) { if (col.getColumnNumber() == umapColNum) { col.setUsageMaps(colOwnedPages, colFreeSpacePages); break; } } } // re-sort columns if necessary if (getDatabase().getColumnOrder() != ColumnOrder.DATA) { Collections.sort(_columns, DISPLAY_ORDER_COMPARATOR); } for (ColumnImpl col : _columns) { // some columns need to do extra work after the table is completely // loaded col.postTableLoadInit(); } _fkEnforcer = new FKEnforcer(this); if (!isSystem()) { // after fully constructed, allow column validator to be configured (but // only for user tables) for (ColumnImpl col : _columns) { col.setColumnValidator(null); } } }
From source file:com.mobilyzer.measurements.HttpTask.java
/** Runs the HTTP measurement task. Will acquire power lock to ensure wifi * is not turned off *//*from ww w . ja v a 2 s . c o m*/ @Override public MeasurementResult[] call() throws MeasurementError { int statusCode = HttpTask.DEFAULT_STATUS_CODE; long duration = 0; long originalHeadersLen = 0; long originalBodyLen; String headers = null; ByteBuffer body = ByteBuffer.allocate(HttpTask.MAX_BODY_SIZE_TO_UPLOAD); // boolean success = false; TaskProgress taskProgress = TaskProgress.FAILED; String errorMsg = ""; InputStream inputStream = null; long currentRxTx = Util.getCurrentRxTxBytes(); try { // set the download URL, a URL that points to a file on the Internet // this is the file to be downloaded HttpDesc task = (HttpDesc) this.measurementDesc; String urlStr = task.url; // TODO(Wenjie): Need to set timeout for the HTTP methods httpClient = AndroidHttpClient.newInstance(Util.prepareUserAgent()); HttpRequestBase request = null; if (task.method.compareToIgnoreCase("head") == 0) { request = new HttpHead(urlStr); } else if (task.method.compareToIgnoreCase("get") == 0) { request = new HttpGet(urlStr); } else if (task.method.compareToIgnoreCase("post") == 0) { request = new HttpPost(urlStr); HttpPost postRequest = (HttpPost) request; postRequest.setEntity(new StringEntity(task.body)); } else { // Use GET by default request = new HttpGet(urlStr); } if (task.headers != null && task.headers.trim().length() > 0) { for (String headerLine : task.headers.split("\r\n")) { String tokens[] = headerLine.split(":"); if (tokens.length == 2) { request.addHeader(tokens[0], tokens[1]); } else { throw new MeasurementError("Incorrect header line: " + headerLine); } } } byte[] readBuffer = new byte[HttpTask.READ_BUFFER_SIZE]; int readLen; int totalBodyLen = 0; long startTime = System.currentTimeMillis(); HttpResponse response = httpClient.execute(request); /* TODO(Wenjie): HttpClient does not automatically handle the following codes * 301 Moved Permanently. HttpStatus.SC_MOVED_PERMANENTLY * 302 Moved Temporarily. HttpStatus.SC_MOVED_TEMPORARILY * 303 See Other. HttpStatus.SC_SEE_OTHER * 307 Temporary Redirect. HttpStatus.SC_TEMPORARY_REDIRECT * * We may want to fetch instead from the redirected page. */ StatusLine statusLine = response.getStatusLine(); if (statusLine != null) { statusCode = statusLine.getStatusCode(); if (statusCode == 200) { taskProgress = TaskProgress.COMPLETED; } else { taskProgress = TaskProgress.FAILED; } } /* For HttpClient to work properly, we still want to consume the entire * response even if the status code is not 200 */ HttpEntity responseEntity = response.getEntity(); originalBodyLen = responseEntity.getContentLength(); long expectedResponseLen = HttpTask.MAX_HTTP_RESPONSE_SIZE; // getContentLength() returns negative number if body length is unknown if (originalBodyLen > 0) { expectedResponseLen = originalBodyLen; } if (responseEntity != null) { inputStream = responseEntity.getContent(); while ((readLen = inputStream.read(readBuffer)) > 0 && totalBodyLen <= HttpTask.MAX_HTTP_RESPONSE_SIZE) { totalBodyLen += readLen; // Fill in the body to report up to MAX_BODY_SIZE if (body.remaining() > 0) { int putLen = body.remaining() < readLen ? body.remaining() : readLen; body.put(readBuffer, 0, putLen); } } duration = System.currentTimeMillis() - startTime;//TODO check this } Header[] responseHeaders = response.getAllHeaders(); if (responseHeaders != null) { headers = ""; for (Header hdr : responseHeaders) { /* * TODO(Wenjie): There can be preceding and trailing white spaces in * each header field. I cannot find internal methods that return the * number of bytes in a header. The solution here assumes the encoding * is one byte per character. */ originalHeadersLen += hdr.toString().length(); headers += hdr.toString() + "\r\n"; } } PhoneUtils phoneUtils = PhoneUtils.getPhoneUtils(); MeasurementResult result = new MeasurementResult(phoneUtils.getDeviceInfo().deviceId, phoneUtils.getDeviceProperty(this.getKey()), HttpTask.TYPE, System.currentTimeMillis() * 1000, taskProgress, this.measurementDesc); result.addResult("code", statusCode); dataConsumed += (Util.getCurrentRxTxBytes() - currentRxTx); if (taskProgress == TaskProgress.COMPLETED) { result.addResult("time_ms", duration); result.addResult("headers_len", originalHeadersLen); result.addResult("body_len", totalBodyLen); result.addResult("headers", headers); result.addResult("body", Base64.encodeToString(body.array(), Base64.DEFAULT)); } Logger.i(MeasurementJsonConvertor.toJsonString(result)); MeasurementResult[] mrArray = new MeasurementResult[1]; mrArray[0] = result; return mrArray; } catch (MalformedURLException e) { errorMsg += e.getMessage() + "\n"; Logger.e(e.getMessage()); } catch (IOException e) { errorMsg += e.getMessage() + "\n"; Logger.e(e.getMessage()); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { Logger.e("Fails to close the input stream from the HTTP response"); } } if (httpClient != null) { httpClient.close(); } } throw new MeasurementError("Cannot get result from HTTP measurement because " + errorMsg); }
From source file:com.mobilyzer.measurements.HttpTask_original.java
/** Runs the HTTP measurement task. Will acquire power lock to ensure wifi * is not turned off *//* w ww . j a va 2 s . co m*/ @Override public MeasurementResult[] call() throws MeasurementError { int statusCode = HttpTask.DEFAULT_STATUS_CODE; long duration = 0; long originalHeadersLen = 0; long originalBodyLen; String headers = null; ByteBuffer body = ByteBuffer.allocate(HttpTask_original.MAX_BODY_SIZE_TO_UPLOAD); // boolean success = false; TaskProgress taskProgress = TaskProgress.FAILED; String errorMsg = ""; InputStream inputStream = null; long currentRxTx = Util.getCurrentRxTxBytes(); try { // set the download URL, a URL that points to a file on the Internet // this is the file to be downloaded HttpDesc task = (HttpDesc) this.measurementDesc; String urlStr = task.url; // TODO(Wenjie): Need to set timeout for the HTTP methods httpClient = AndroidHttpClient.newInstance(Util.prepareUserAgent()); HttpRequestBase request = null; if (task.method.compareToIgnoreCase("head") == 0) { request = new HttpHead(urlStr); } else if (task.method.compareToIgnoreCase("get") == 0) { request = new HttpGet(urlStr); } else if (task.method.compareToIgnoreCase("post") == 0) { request = new HttpPost(urlStr); HttpPost postRequest = (HttpPost) request; postRequest.setEntity(new StringEntity(task.body)); } else { // Use GET by default request = new HttpGet(urlStr); } if (task.headers != null && task.headers.trim().length() > 0) { for (String headerLine : task.headers.split("\r\n")) { String tokens[] = headerLine.split(":"); if (tokens.length == 2) { request.addHeader(tokens[0], tokens[1]); } else { throw new MeasurementError("Incorrect header line: " + headerLine); } } } byte[] readBuffer = new byte[HttpTask.READ_BUFFER_SIZE]; int readLen; int totalBodyLen = 0; long startTime = System.currentTimeMillis(); HttpResponse response = httpClient.execute(request); /* TODO(Wenjie): HttpClient does not automatically handle the following codes * 301 Moved Permanently. HttpStatus.SC_MOVED_PERMANENTLY * 302 Moved Temporarily. HttpStatus.SC_MOVED_TEMPORARILY * 303 See Other. HttpStatus.SC_SEE_OTHER * 307 Temporary Redirect. HttpStatus.SC_TEMPORARY_REDIRECT * * We may want to fetch instead from the redirected page. */ StatusLine statusLine = response.getStatusLine(); if (statusLine != null) { statusCode = statusLine.getStatusCode(); if (statusCode == 200) { taskProgress = TaskProgress.COMPLETED; } else { taskProgress = TaskProgress.FAILED; } } /* For HttpClient to work properly, we still want to consume the entire * response even if the status code is not 200 */ HttpEntity responseEntity = response.getEntity(); originalBodyLen = responseEntity.getContentLength(); long expectedResponseLen = HttpTask.MAX_HTTP_RESPONSE_SIZE; // getContentLength() returns negative number if body length is unknown if (originalBodyLen > 0) { expectedResponseLen = originalBodyLen; } if (responseEntity != null) { inputStream = responseEntity.getContent(); while ((readLen = inputStream.read(readBuffer)) > 0 && totalBodyLen <= HttpTask.MAX_HTTP_RESPONSE_SIZE) { totalBodyLen += readLen; // Fill in the body to report up to MAX_BODY_SIZE if (body.remaining() > 0) { int putLen = body.remaining() < readLen ? body.remaining() : readLen; body.put(readBuffer, 0, putLen); } } duration = System.currentTimeMillis() - startTime;//TODO check this } Header[] responseHeaders = response.getAllHeaders(); if (responseHeaders != null) { headers = ""; for (Header hdr : responseHeaders) { /* * TODO(Wenjie): There can be preceding and trailing white spaces in * each header field. I cannot find internal methods that return the * number of bytes in a header. The solution here assumes the encoding * is one byte per character. */ originalHeadersLen += hdr.toString().length(); headers += hdr.toString() + "\r\n"; } } PhoneUtils phoneUtils = PhoneUtils.getPhoneUtils(); MeasurementResult result = new MeasurementResult(phoneUtils.getDeviceInfo().deviceId, phoneUtils.getDeviceProperty(this.getKey()), HttpTask.TYPE, System.currentTimeMillis() * 1000, taskProgress, this.measurementDesc); result.addResult("code", statusCode); dataConsumed += (Util.getCurrentRxTxBytes() - currentRxTx); if (taskProgress == TaskProgress.COMPLETED) { result.addResult("time_ms", duration); result.addResult("headers_len", originalHeadersLen); result.addResult("body_len", totalBodyLen); result.addResult("headers", headers); result.addResult("body", Base64.encodeToString(body.array(), Base64.DEFAULT)); } Logger.i(MeasurementJsonConvertor.toJsonString(result)); MeasurementResult[] mrArray = new MeasurementResult[1]; mrArray[0] = result; return mrArray; } catch (MalformedURLException e) { errorMsg += e.getMessage() + "\n"; Logger.e(e.getMessage()); } catch (IOException e) { errorMsg += e.getMessage() + "\n"; Logger.e(e.getMessage()); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { Logger.e("Fails to close the input stream from the HTTP response"); } } if (httpClient != null) { httpClient.close(); } } throw new MeasurementError("Cannot get result from HTTP measurement because " + errorMsg); }