public static void contents(Integer convID, Integer fromMsgID) { if (fromMsgID == null) { fromMsgID = 0; } Connection c = DB.getConnection(); try { PreparedStatement stmt = c.prepareStatement( "select M.id, UR.name, U.id, M.contents, M.timeSent from `Person` as U, `Conversations` as C, `Messages` as M, `UserRoles` as UR " + "where UR.id = U.role_id and C.id=M.conversation_id and U.id=M.user_id and C.id = ? and M.id>? " + "ORDER BY M.id"); stmt.setInt(1, convID); stmt.setInt(2, fromMsgID); ResultSet rs = stmt.executeQuery(); rs.beforeFirst(); ArrayList<ChatMessage> msgdata = new ArrayList<ChatMessage>(); Integer maxID = fromMsgID; while (rs.next()) { ChatMessage msg = new ChatMessage( rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5)); if (msg.name.equals(Security.connected())) { msg.name = "You"; msg.role = ""; } maxID = Math.max(maxID, msg.id); msgdata.add(msg); } render(msgdata, maxID); } catch (SQLException e) { e.printStackTrace(); } }
@Override public void convert( Context context, RVCommonViewHolder holder, ChatMessage chatMessage, int position) { holder.setText(R.id.chat_send_content, chatMessage.getContent()); holder.setText(R.id.chat_send_name, chatMessage.getName()); holder.setImageResource(R.id.chat_send_icon, R.mipmap.ic_launcher); }
/* * to broadcast a private message to all Clients */ private synchronized void broadcastOnlyOne(String message, ChatMessage cm) { // add HH:mm:ss and \n to the message String time = sdf.format(new Date()); String messageLf = time + " " + message + "\r\n"; System.out.print(messageLf); serverGUI.serverTextArea.append(messageLf); // we loop in reverse order in case we would have to remove a Client // because it has disconnected for (int i = al.size(); --i >= 0; ) { ClientThread ct = al.get(i); // try to write to the Client if it fails remove it from the list if (cm.getType() == ChatMessage.ESTABLISHCONNECTION || cm.getType() == ChatMessage.ESTABLISHCONNECTIONANDPLAY) { if (cm.getTO().equalsIgnoreCase(ct.username) && !ct.writeMsg(cm)) { al.remove(i); display("Disconnected Client " + ct.username + " removed from list."); break; } } else { if (cm.getTO().equalsIgnoreCase(ct.username) && !ct.writeMsg(message)) { al.remove(i); display("Disconnected Client " + ct.username + " removed from list."); break; } } } }
// what will run forever public void run() { // to loop until LOGOUT boolean keepGoing = true; while (keepGoing) { // read a String (which is an object) try { cm = (ChatMessage) sInput.readObject(); } catch (IOException e) { display(username + " Exception reading Streams: " + e); break; } catch (ClassNotFoundException e2) { break; } // the messaage part of the ChatMessage String message = cm.getMessage(); // Switch on the type of message receive switch (cm.getType()) { case ChatMessage.MESSAGE: broadcast(username + ": " + message); break; case ChatMessage.LOGOUT: display(username + " disconnected with a LOGOUT message."); keepGoing = false; break; case ChatMessage.WHOISIN: writeMsg("List of the users connected at " + sdf.format(new Date()) + "\n"); // scan al the users connected for (int i = 0; i < al.size(); ++i) { ClientThread ct = al.get(i); writeMsg((i + 1) + ") " + ct.username + " since " + ct.date); } break; case ChatMessage.TO: broadcastOnlyOne(username + ": " + message, cm); break; case ChatMessage.SENDFILE: sendFile(username + ": " + message, cm); break; case ChatMessage.PROCEED: proceedSendFile(); break; case ChatMessage.SENDMEDIAFILE: String fileList = getFileList(); writeMsg(new ChatMessage(ChatMessage.SENDMEDIAFILE, fileList)); break; case ChatMessage.ESTABLISHCONNECTIONANDPLAY: sendMediaFile(username + ": " + message, cm); break; } } // remove myself from the arrayList containing the list of the // connected Clients remove(id); close(); }
private boolean importAndroidStoredMessagedIntoLibLinphoneStorage() { Log.w("Importing previous messages into new database..."); try { ChatStorage db = LinphoneActivity.instance().getChatStorage(); List<String> conversations = db.getChatList(); for (int j = conversations.size() - 1; j >= 0; j--) { String correspondent = conversations.get(j); LinphoneChatRoom room = LinphoneManager.getLc().getOrCreateChatRoom(correspondent); for (ChatMessage message : db.getMessages(correspondent)) { LinphoneChatMessage msg = room.createLinphoneChatMessage( message.getMessage(), message.getUrl(), message.getStatus(), Long.parseLong(message.getTimestamp()), true, message.isIncoming()); if (message.getImage() != null) { String path = saveImageAsFile(message.getId(), message.getImage()); if (path != null) msg.setExternalBodyUrl(path); } msg.store(); } db.removeDiscussion(correspondent); } return true; } catch (Exception e) { e.printStackTrace(); } return false; }
/** * hessian protocol * * @param message message * @return chat message * @throws Exception exception */ public ChatMessage hessian(ChatMessage message) throws Exception { ByteArrayOutputStream bos = new ByteArrayOutputStream(); Hessian2Output output = new Hessian2Output(bos); output.writeObject(message); output.flush(); byte[] content = bos.toByteArray(); ByteArrayInputStream bis = new ByteArrayInputStream(content); Hessian2Input input = new Hessian2Input(bis); ChatMessage msg = (ChatMessage) input.readObject(ChatMessage.class); msg.setContentLength(content.length); return msg; }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log("new received ack message"); // start connection if it did not DB.instance().connectToDB(); // read sessionId String sessionId = request.getParameter("sessionId"); // find user with this sessionId List<ChatUser> chatUsers = Ebean.find(ChatUser.class).where().eq("sessionId", sessionId).findList(); // define the response message String responseMessage = "{}"; // this user has a sessionId if (chatUsers.size() == 1) { // current chat user ChatUser chatUser = chatUsers.get(0); log("found user for this sessionId, chatUser: "******"messageId"); List<ChatMessage> chatMessages = Ebean.find(ChatMessage.class).where().eq("messageId", messageId).findList(); if (chatMessages.size() == 1) { ChatMessage chatMessage = chatMessages.get(0); log("received message found, chatMessage: " + chatMessage); // update the status to message's last status, this message is send, received and // acknowledged, notified and acknowledged chatMessage.setStatus(ChatMessage.SOURCE_SAID_IT_KNOWS_THIS_MESSAGE_IS_DELIVERED); Ebean.update(chatMessage); log("received message updated, chatMessage: " + chatMessage); } responseMessage = "{\"status\":\"acknowledged\", \"messageId\":\"" + messageId + "\"}"; } // send response response.setContentType("application/json"); PrintWriter out = response.getWriter(); out.print(responseMessage); out.flush(); out.close(); log("done"); }
/** * Appends a chat text update. * * @param block The packet. * @param otherPlayer The player. */ private void appendChatUpdate(PacketBuilder block, Player otherPlayer) { final ChatMessage chatMessage = otherPlayer.getCurrentChatMessage(); block.putShortA(chatMessage.getEffects()); block.putByteC(otherPlayer.getRights().toInteger()); byte[] chatStr = new byte[256]; chatStr[0] = (byte) chatMessage.getText().length(); int offset = 2 + ChatUtils.encryptPlayerChat( chatStr, 0, 1, chatMessage.getText().length(), chatMessage.getText().getBytes()); block.putByteC(offset); block.put(chatStr, 0, offset); }
/** * The message's acknowledgments were already sent to receiver (to set the right colors on sent * data) * * @param cmsg * @param peer_GID */ private static void forwardMsgToReceiverAndSendAckToSender(ChatMessage cmsg, String peer_GID) { if (DEBUG) System.out.println("PLUGIN CHAT: Main: forwardMsgToReceiverAndSendAckToSender: enter"); String msgStr = cmsg.msg; if (DEBUG) System.out.println("From: " + peer_GID + " got: " + msgStr); String peerName = cmsg.getName(); if (DEBUG) System.out.println("-----------receiveTxt(): new message should display"); ChannelDataIn channeldata_in = ChannelDataIn.get(peer_GID); if (channeldata_in.registerIncoming(cmsg)) { sendAckMsg(channeldata_in, cmsg, peer_GID); // create new empty msg as confirmation ack receiver.receiveMessage( cmsg.first_in_this_sequence, cmsg.sequence, msgStr, peerName, peer_GID, cmsg.session_id, cmsg, channeldata_in); } if (DEBUG) System.out.println("PLUGIN CHAT: Main: forwardMsgToReceiverAndSendAckToSender: exit"); }
public Connection saveChatMessage(Connection con, String message) throws NoSuchConnectionException { // load connection, checking if it exists if (con == null) throw new IllegalArgumentException("connectionURI is not set"); if (message == null) throw new IllegalArgumentException("message is not set"); // construct chatMessage object to store in the db ChatMessage chatMessage = new ChatMessage(); chatMessage.setCreationDate(new Date()); chatMessage.setLocalConnectionURI(con.getConnectionURI()); chatMessage.setMessage(message); chatMessage.setOriginatorURI(con.getNeedURI()); // save in the db chatMessageRepository.saveAndFlush(chatMessage); return con; }
private static Notification buildNotification( Context context, boolean playSound, ChatMessage chatMsg) { Resources res = context.getResources(); String message; String title = res.getString(R.string.app_name); String tapToOpen = res.getString(R.string.click_to_open); boolean hasNewMessages = msNotifications.size() > 0; // Build a different message depending on wether we have notifications if (chatMsg != null) { message = chatMsg.getUser() + ": " + chatMsg.getMessage(); } else if (!hasNewMessages) { message = tapToOpen; } else { message = String.format( res.getString(R.string.you_have_pending_notifications), msNotifications.size()) + "\n"; for (int i = msNotifications.size() - 1; i >= 0; --i) { ChatMessage msg = msNotifications.get(i); message = message + "<" + msg.getUser() + "> " + msg.getMessage() + "\n"; } } // Make it Android 4 stylish NotificationCompat.InboxStyle bigTextStyle = new NotificationCompat.InboxStyle(); bigTextStyle.setBigContentTitle(title); if (chatMsg != null) { String msg = "<b>" + chatMsg.getUser() + "</b> " + chatMsg.getMessage(); bigTextStyle.addLine(Html.fromHtml(msg)); } else if (!hasNewMessages) { bigTextStyle.addLine(tapToOpen); } else { bigTextStyle.addLine( String.format( res.getString(R.string.you_have_pending_notifications), msNotifications.size())); for (int i = msNotifications.size() - 1; i >= 0; --i) { ChatMessage msg = msNotifications.get(i); bigTextStyle.addLine(Html.fromHtml("<b>" + msg.getUser() + "</b> " + msg.getMessage())); } } boolean useLights = hasNewMessages || chatMsg != null; int icon = (hasNewMessages || chatMsg != null) ? R.drawable.ic_new_messages : R.drawable.ic_launcher; return buildNotification(context, playSound, useLights, icon, message, bigTextStyle); }
/** * construct message * * @return chat message */ private ChatMessage constructMessage() { ChatMessage msg = new ChatMessage(); msg.setId(11343L); msg.setUserId(1134); msg.setUserNick("linux_china"); msg.setCreatedAt(new Date()); msg.setScore(2.0042); msg.setBody("这是聊天的内容"); msg.getHeaders().put("contentType", "text/plain"); msg.getHeaders().put("room", "123423"); msg.setContentLength(120); return msg; }
/* * Write a String to the Client output stream */ private boolean writeMsg(ChatMessage cm) { // if Client is still connected send the message to it if (!socket.isConnected()) { close(); return false; } // write the message to the stream try { boolean sendChatMessage = cm.getType() == ChatMessage.ESTABLISHCONNECTION; boolean sendMediaFileMessage = cm.getType() == ChatMessage.ESTABLISHCONNECTIONANDPLAY; if (sendChatMessage || sendMediaFileMessage) sOutput.writeObject(cm); else sOutput.writeObject(cm.getMessage()); } // if an error occurs, do not abort just inform the user catch (IOException e) { display("Error sending message to " + username); display(e.toString()); } return true; }
@Override public void consume(Player player, Message message) { log("ChatServer: Received " + message.getType()); if (message.getType() == Message.MessageType.JOIN_CHAT) { JoinChatMessage joinChatMessage = new JoinChatMessage(((JoinChatMessage) message).getMsg()); server.sendToAll(joinChatMessage); } else if (message.getType() == Message.MessageType.CHAT_MSG) { ((ChatMessage) message).addNick(player.getName()); server.sendToAll(message); } }
@Override public void onCreation(final ChatViewManager manager) { final int idPrivate = ChatWindowManager.getInstance().getModeratorWindowId(); final GameDateConst tmp = BaseGameDateProvider.INSTANCE.getDate(); final String time = "[" + tmp.getHours() + ':' + tmp.getMinutes() + "] "; final TextWidgetFormater msg = new TextWidgetFormater(); msg.openText(); msg.addColor(new Color(0.84f, 0.27f, 0.29f, 1.0f)); msg.append(time); msg.b().u(); msg.addId("characterName_" + this.m_sourceId); msg.append(this.m_sourceName); msg._u()._b(); msg.append(WakfuTranslator.getInstance().getString("colon")).append(this.m_message); msg.closeText(); final ChatMessage chatMessage = new ChatMessage(msg.finishAndToString()); chatMessage.setPipeDestination(3); chatMessage.setWindowId(idPrivate); ChatManager.getInstance().pushMessage(chatMessage); }
@Override public void update(ChatMessage message) throws IOException { System.out.println("Inside update() " + number + " received message " + message.getMessage()); System.out.println("sending message..."); // ChatClient client = (ChatClient) message.sender; // char chars[] = (message.getSender().getSenderName() + ": " + // message.getMessage()).toCharArray(); char chars[] = getMessageForSend(message); // TODO convert message to function // char chars[] = message.getMessage().toCharArray(); for (char c : chars) { // outputStream.write((int)c); // System.out.println("Sending " + c); outputStream.write((int) c); } outputStream.flush(); System.out.println("Sent: " + message.getMessage()); }
// what will run forever public void run() { // to loop until LOGOUT boolean keepGoing = true; while (keepGoing) { // read a String (which is an object) try { cm = (ChatMessage) sInput.readObject(); } catch (IOException e) { display(username + " Exception reading Streams: " + e); break; } catch (ClassNotFoundException e2) { break; } // the messaage part of the ChatMessage String message = cm.getMessage(); // Switch on the type of message receive switch (cm.getType()) { case ChatMessage.MESSAGE: broadcast(username + ": " + message); break; case ChatMessage.LOGOUT: display(username + " LOGOUT dari chat."); keepGoing = false; break; case ChatMessage.WHOISIN: writeMsg("Daftar Client yang terkoneksi pada " + sdf.format(new Date()) + "\n"); // scan al the users connected for (int i = 0; i < al.size(); ++i) { ClientThread ct = al.get(i); writeMsg((i + 1) + ") " + ct.username + " sejak " + ct.date); } break; } } // remove myself from the arrayList containing the list of the // connected Clients remove(id); close(); }
@OnMessage public void handleChatMessage(ChatMessage message) { switch (message.getType()) { case NewUserMessage.USERNAME_MESSAGE: this.processNewUser((NewUserMessage) message); break; case ChatMessage.CHAT_DATA_MESSAGE: this.processChatUpdate((ChatUpdateMessage) message); break; case ChatMessage.SIGNOFF_REQUEST: this.processSignoffRequest((UserSignoffMessage) message); } }
@Override public boolean onMessage(final Message message) { switch (message.getId()) { case 19070: { this.askToCloseRequest(); return false; } case 19071: { final AbstractUIMessage msg = (AbstractUIMessage) message; final byte closedReason = msg.getByteValue(); final int idPrivate = ChatWindowManager.getInstance().getModeratorWindowId(); String translatorKey = "contactModerator.closed"; switch (closedReason) { case 4: { translatorKey = "contactModerator.closed"; break; } case 5: { translatorKey = "contactModerator.disconnected"; break; } } final ChatMessage chatMessage = new ChatMessage(WakfuTranslator.getInstance().getString(translatorKey)); chatMessage.setPipeDestination(3); chatMessage.setWindowId(idPrivate); ChatManager.getInstance().pushMessage(chatMessage); return this.m_isRunning = false; } default: { return true; } } }
/** * Sends an acknowledgment for cmsg. Not setting a sequence number, since the ack message is * empty. * * @param cmsg * @param peer_GID */ private static void sendAckMsg(ChannelDataIn channeldata_in, ChatMessage cmsg, String peer_GID) { // boolean DEBUG = true; if (DEBUG) System.out.println("PLUGIN CHAT: Main: sendAckMsg: enter"); ChannelDataOut cd = ChannelDataOut.get(peer_GID); ChatMessage cm = new ChatMessage(); cm.message_type = ChatMessage .MT_EMPTY; // just to inform session_id, session_id_ack, first_in_this_sequence, // last_acknowledged_in_sequence, received_out_of_sequence cm.last_acknowledged_in_sequence = channeldata_in.getLastInSequence(); // cmsg.sequence; cm.received_out_of_sequence = channeldata_in.getOutOfSequence(); cm.session_id_ack = channeldata_in.getSessionID(); // cmsg.session_id; cm.session_id = cd.getSessionID(); cm.first_in_this_sequence = cd.getFirstInSequence(); // cmsg.first_in_this_sequence; // cm.sequence = cd.getNextSequence(); //cmsg.sequence. probably should not be set for empty // messages! ChatElem ce = new ChatElem(); ce.type = 0; // name ce.val = Main.name; cm.content = new ArrayList<ChatElem>(); cm.content.add(ce); // cm.content = null; cm.msg = null; if (DEBUG) System.out.println("PLUGIN CHAT: sendAckMsg: sending " + cm); byte[] _msg = cm.encode(); net.ddp2p.common.plugin_data.PluginRequest envelope = new net.ddp2p.common.plugin_data.PluginRequest(); envelope.msg = _msg; envelope.peer_GID = peer_GID; // destination envelope.type = net.ddp2p.common.plugin_data.PluginRequest.MSG; envelope.plugin_GID = (String) Main.getPluginDataHashtable().get("plugin_GID"); Main.enqueue(envelope); if (DEBUG) System.out.println("PLUGIN CHAT: sendAckMsg: sending env " + envelope); if (DEBUG) System.out.println("PLUGIN CHAT: Main: sendAckMsg: exit"); }
static { defaultInstance = new ChatMessage(true); defaultInstance.initFields(); }
@Override public boolean isForViewType(ChatMessage item, int position) { return !item.isComMeg(); // 是否是自己的这种类型 }
public View getView(int position, View convertView, ViewGroup parent) { View view = null; if (convertView != null) { view = convertView; } else { view = mInflater.inflate(R.layout.chatlist_cell, parent, false); } String contact; boolean isDraft = false; if (position >= mDrafts.size()) { contact = mConversations.get(position - mDrafts.size()); } else { contact = mDrafts.get(position); isDraft = true; } view.setTag(contact); int unreadMessagesCount = LinphoneActivity.instance().getChatStorage().getUnreadMessageCount(contact); LinphoneAddress address; try { address = LinphoneCoreFactory.instance().createLinphoneAddress(contact); } catch (LinphoneCoreException e) { Log.e("Chat view cannot parse address", e); return view; } LinphoneUtils.findUriPictureOfContactAndSetDisplayName( address, view.getContext().getContentResolver()); String message = ""; if (useNativeAPI) { LinphoneChatRoom chatRoom = LinphoneManager.getLc().getOrCreateChatRoom(contact); LinphoneChatMessage[] history = chatRoom.getHistory(20); if (history != null && history.length > 0) { for (int i = history.length - 1; i >= 0; i--) { LinphoneChatMessage msg = history[i]; if (msg.getText() != null && msg.getText().length() > 0) { message = msg.getText(); break; } } } } else { List<ChatMessage> messages = LinphoneActivity.instance().getChatMessages(contact); if (messages != null && messages.size() > 0) { int iterator = messages.size() - 1; ChatMessage lastMessage = null; while (iterator >= 0) { lastMessage = messages.get(iterator); if (lastMessage.getMessage() == null) { iterator--; } else { iterator = -1; } } message = (lastMessage == null || lastMessage.getMessage() == null) ? "" : lastMessage.getMessage(); } } TextView lastMessageView = (TextView) view.findViewById(R.id.lastMessage); lastMessageView.setText(message); TextView sipUri = (TextView) view.findViewById(R.id.sipUri); sipUri.setSelected(true); // For animation if (getResources().getBoolean(R.bool.only_display_username_if_unknown) && address.getDisplayName() != null && LinphoneUtils.isSipAddress(address.getDisplayName())) { address.setDisplayName(LinphoneUtils.getUsernameFromAddress(address.getDisplayName())); } else if (getResources().getBoolean(R.bool.only_display_username_if_unknown) && LinphoneUtils.isSipAddress(contact)) { contact = LinphoneUtils.getUsernameFromAddress(contact); } sipUri.setText(address.getDisplayName() == null ? contact : address.getDisplayName()); if (isDraft) { view.findViewById(R.id.draft).setVisibility(View.VISIBLE); } ImageView delete = (ImageView) view.findViewById(R.id.delete); TextView unreadMessages = (TextView) view.findViewById(R.id.unreadMessages); if (unreadMessagesCount > 0) { unreadMessages.setVisibility(View.VISIBLE); unreadMessages.setText(String.valueOf(unreadMessagesCount)); } else { unreadMessages.setVisibility(View.GONE); } if (isEditMode) { delete.setVisibility(View.VISIBLE); } else { delete.setVisibility(View.INVISIBLE); } return view; }
/** * @param message * @param peerGID * @param peer * @return the message actually sent (and its sequence numbers) */ public static ChatMessage sendMessage(String message, String peerGID, D_Peer peer) { if (DEBUG) System.out.println("PLUGIN CHAT: Main: sendMessage enter: " + message); if (peer != null && peerGID == null) peerGID = peer.getGID(); // create a hashtable where ht(key=peerGID ) ==> cm (chatMessage) ChannelDataOut channeldata_out = ChannelDataOut.get(peerGID); ChannelDataIn channeldata_in = ChannelDataIn.get(peerGID); if (DEBUG) System.out.println("PLUGIN CHAT: Main: sendMessage got channel out: " + channeldata_out); if (DEBUG) System.out.println("PLUGIN CHAT: Main: sendMessage got channel in: " + channeldata_in); ChatMessage cm = new ChatMessage(); cm.session_id = channeldata_out.getSessionID(); // cm.session_id_ack = cmsg.session_id; cm.message_type = ChatMessage.MT_TEXT; cm.first_in_this_sequence = channeldata_out.getFirstInSequence(); // cmsg.first_in_this_sequence; ChatElem ce = new ChatElem(); ce.type = 0; // name ce.val = Main.name; cm.content = new ArrayList<ChatElem>(); cm.content.add(ce); cm.msg = message; // first time message to this peer cm.session_id_ack = channeldata_in.getSessionID(); cm.last_acknowledged_in_sequence = channeldata_in.getLastInSequence(); cm.received_out_of_sequence = channeldata_in.getOutOfSequence(); cm.sequence = channeldata_out.getNextSequence(); // msgTrackingSend.put(peer_GID, cm); // only store the last message info for each peer // save to DB for history ( peer_GID:sender(myself): Date/Time : msg as object ) if (DEBUG) System.out.println("PLUGIN CHAT: Main: send: " + cm); // confirm the sending into the GUI receiver.addSentMessage(cm, peerGID, channeldata_out); byte[] _msg = cm.encode(); net.ddp2p.common.plugin_data.PluginRequest envelope = new net.ddp2p.common.plugin_data.PluginRequest(); envelope.msg = _msg; envelope.peer_GID = peerGID; // destination envelope.type = net.ddp2p.common.plugin_data.PluginRequest.MSG; envelope.plugin_GID = (String) Main.getPluginDataHashtable().get("plugin_GID"); if (DEBUG) System.out.println("PLUGIN CHAT: Main: send envelope: " + envelope); Main.enqueue(envelope); if (DEBUG) System.out.println("PLUGIN CHAT: Main: sendMessage exit"); return cm; }
/** * Composes messages for send (using message body, sender name etc.) * * @param message * @return */ private char[] getMessageForSend(ChatMessage message) { char chars[] = (message.getSender().getSenderName() + ": " + message.getMessage()).toCharArray(); return chars; }
/** * message pack * * @param message message * @return chat message * @throws Exception exception */ public ChatMessage msgpack(ChatMessage message) throws Exception { byte[] content = msgpack.write(message); ChatMessage msg = msgpack.read(content, ChatMessage.class); msg.setContentLength(content.length); return msg; }
/** * json protocol with jackson * * @param message message * @return chat message * @throws Exception exception */ public ChatMessage jackson(ChatMessage message) throws Exception { byte[] jsonText = objectMapper.writeValueAsBytes(message); ChatMessage msg = objectMapper.readValue(jsonText, ChatMessage.class); msg.setContentLength(jsonText.length); return msg; }
public RSCPacket getPacket() { List<Bubble> bubblesNeedingDisplayed = playerToUpdate.getBubblesNeedingDisplayed(); List<ChatMessage> chatMessagesNeedingDisplayed = playerToUpdate.getChatMessagesNeedingDisplayed(); List<Player> playersNeedingHitsUpdate = playerToUpdate.getPlayersRequiringHitsUpdate(); List<Projectile> projectilesNeedingDisplayed = playerToUpdate.getProjectilesNeedingDisplayed(); List<Player> playersNeedingAppearanceUpdate = playerToUpdate.getPlayersRequiringAppearanceUpdate(); int updateSize = bubblesNeedingDisplayed.size() + chatMessagesNeedingDisplayed.size() + playersNeedingHitsUpdate.size() + projectilesNeedingDisplayed.size() + playersNeedingAppearanceUpdate.size(); if (updateSize > 0) { RSCPacketBuilder updates = new RSCPacketBuilder(); updates.setID(53); updates.addShort(updateSize); for (Bubble b : bubblesNeedingDisplayed) { // 0 - Draws item over players head updates.addShort(b.getOwner().getIndex()); updates.addByte((byte) 0); updates.addShort(b.getID()); } for (ChatMessage cm : chatMessagesNeedingDisplayed) { // 1/6 - Player talking updates.addShort(cm.getSender().getIndex()); updates.addByte((byte) (cm.getRecipient() == null ? 1 : 6)); System.out.println(cm.getRecipient() == null); updates.addByte((byte) cm.getLength()); updates.addBytes(cm.getMessage()); } for (Player p : playersNeedingHitsUpdate) { // 2 - Hitpoints update for players, draws health bar etc too updates.addShort(p.getIndex()); updates.addByte((byte) 2); updates.addByte((byte) p.getLastDamage()); updates.addByte((byte) p.getCurStat(3)); updates.addByte((byte) p.getMaxStat(3)); } for (Projectile p : projectilesNeedingDisplayed) { // 3/4 - Draws a projectile Entity victim = p.getVictim(); if (victim instanceof Npc) { updates.addShort(p.getCaster().getIndex()); updates.addByte((byte) 3); updates.addShort(p.getType()); updates.addShort(((Npc) victim).getIndex()); } else if (victim instanceof Player) { updates.addShort(p.getCaster().getIndex()); updates.addByte((byte) 4); updates.addShort(p.getType()); updates.addShort(((Player) victim).getIndex()); } } for (Player p : playersNeedingAppearanceUpdate) { // 5 - Updates players appearance, clothes, skull, // combat etc. PlayerAppearance appearance = p.getPlayerAppearance(); updates.addShort(p.getIndex()); updates.addByte((byte) 5); updates.addShort(p.getAppearanceID()); updates.addLong(p.getUsernameHash()); updates.addLong(p.getClanNameHash()); updates.addByte((byte) p.getWornItems().length); for (int i : p.getWornItems()) { updates.addByte((byte) i); } updates.addByte(appearance.getHairColour()); updates.addByte(appearance.getTopColour()); updates.addByte(appearance.getTrouserColour()); updates.addByte(appearance.getSkinColour()); updates.addByte((byte) p.getCombatLevel()); updates.addByte((byte) (p.isSkulled() ? 1 : 0)); updates.addByte( (byte) (p.isAdmin() ? 3 : (p.isMod() ? 2 : (p.isPMod() ? 1 : (p.isEvent() ? 4 : (p.isDeveloper() ? 5 : 0)))))); updates.addLong(DataConversions.usernameToHash((p.flag == null ? "--" : p.flag))); } return updates.toPacket(); } return null; }