/* * By Dave Makower * Copyright © 1996 by Pencom Web Works, a business unit of Pencom Systems, Inc. * Send inquiries to */ import java.util.StringTokenizer; /** * A Message consists of an int code, a String for the user name * and a String containing the text of the message. When messages * are sent via an I/O stream, they are delimited by | characters. * A Message can not contain more than one line (i.e., it cannot * contain any \n or \r characters. */ public class Message { int code = 0; // what kind of message is this? String user; // name of the user who sent this message String text; // the contents of the message Object sender; // the Object that created this message public Message() { this(0, " ", " ", null); } public Message(String s, Object who) { StringTokenizer st= new StringTokenizer(s, "|", false); sender = who; if ( st.countTokens() > 2) { // Should be a fully-formed message // First field should be an integer code try { code = Integer.parseInt(st.nextToken()); } catch (NumberFormatException e1) { // not properly formed message; // treat it as a normal string // (for backward compatibility) code = 0; user = " "; // no user name text = s; return; } // Second field should be user name user = st.nextToken(); } if (st.hasMoreTokens()) { // Third field should be the message, if any. // Allow '|' characters in the message (but no // line breaks). text = st.nextToken("\r\n"); return; } else { text = " "; return; } } public Message(int c, String u, String t, Object who) { code = c; user = (u == null)? " ": u; text = (t == null)? " ": t; sender = who; } public Message(int c, Message msg) { this (c, msg.getUser(), msg.getText(), msg.getSender()); } public int getCode() { return code; } public String getUser() { return user; } public String getText() { return text; } public Object getSender() { return sender; } public String toString() { String codeString = new Integer(code).toString(); String userString = (user == null)? " " : user; // Note that the sender is not encoded into the String // ... but the code, user, and text are. This puts // ... messages in the format in which they are sent // ... over the network. return (codeString + "|" + userString + "|" + text); } }