1 package Jt.examples.patterns; 2 3 import Jt.*; 4 import java.io.*; 5 import java.util.*; 6 import Jt.xml.*; 7 8 14 15 public class Calculator extends JtCommand { 16 17 18 private int total = 0; 20 public Calculator () { 21 } 22 23 24 25 26 32 33 public Object processMessage (Object message) { 34 35 String msgid = null; 36 JtMessage msg = (JtMessage) message; 37 Object content; 38 39 if (msg == null) 40 return null; 41 42 44 msgid = (String ) msg.getMsgId (); 45 46 if (msgid == null) 47 return null; 48 49 content = msg.getMsgContent(); 50 51 53 if (msgid.equals ("ADD")) { 54 55 total += ((Integer ) content).intValue (); 56 57 logMessage (msg); 59 return (new Integer (total)); 60 } 61 62 64 if (msgid.equals ("JtREMOVE")) { 65 return (null); 66 } 67 68 handleError ("Calculator.processMessage: invalid message id:" + msgid); 69 return (null); 70 } 71 72 73 74 77 78 public static void main(String [] args) { 79 80 JtObject main = new JtFactory (); 81 JtMessage msg, msg1; 82 JtXMLHelper xmlHelper = new JtXMLHelper (); 83 Object total; 84 JtKeyboard keyboard; 85 String input; 86 int num = 0; 87 88 90 main.createObject ("Jt.examples.patterns.Calculator", "calculator"); 91 keyboard = (JtKeyboard) main.createObject ("Jt.JtKeyboard", "keyboard"); 92 93 System.out.println ("Enter a number to be added to the total (or <CR> to exit):"); 94 95 for (;;) { 96 97 99 input = (String ) main.sendMessage (keyboard, new JtMessage ("JtACTIVATE")); 100 101 input = input.trim (); 102 103 if ("".equals (input)) 104 break; 105 106 107 try { 108 num = Integer.parseInt (input); 109 } catch (Exception e) { 110 111 System.err.println (e); 112 } 113 114 115 msg = new JtMessage ("ADD"); 117 msg.setMsgContent (new Integer (num)); 118 total = main.sendMessage ("calculator", msg); 119 120 System.out.println ("Total:" + total); 121 122 } 123 124 125 129 msg = new JtMessage ("JtCONVERT_OBJECT_TO_XML"); 130 msg.setMsgContent (main.getValue ("calculator", "messageLog")); 131 132 System.out.println ("Log:\n" + 133 main.sendMessage (xmlHelper, msg)); 134 135 136 137 139 main.removeObject ("calculator"); 140 141 } 142 143 } 144 145 146 147 | Popular Tags |