KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > axis2 > util > tcpmon


1 /*
2  * Copyright 2004,2005 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.apache.axis2.util;
17
18 import javax.swing.*;
19 import javax.swing.border.TitledBorder JavaDoc;
20 import javax.swing.event.ChangeEvent JavaDoc;
21 import javax.swing.event.ListSelectionEvent JavaDoc;
22 import javax.swing.event.ListSelectionListener JavaDoc;
23 import javax.swing.plaf.basic.BasicButtonListener JavaDoc;
24 import javax.swing.table.DefaultTableModel JavaDoc;
25 import javax.swing.table.TableColumn JavaDoc;
26 import javax.swing.table.TableModel JavaDoc;
27 import javax.swing.text.AttributeSet JavaDoc;
28 import javax.swing.text.BadLocationException JavaDoc;
29 import javax.swing.text.Document JavaDoc;
30 import javax.swing.text.PlainDocument JavaDoc;
31 import java.awt.*;
32 import java.awt.event.ActionEvent JavaDoc;
33 import java.awt.event.ActionListener JavaDoc;
34 import java.io.*;
35 import java.net.ServerSocket JavaDoc;
36 import java.net.Socket JavaDoc;
37 import java.net.URL JavaDoc;
38 import java.text.DateFormat JavaDoc;
39 import java.text.SimpleDateFormat JavaDoc;
40 import java.util.Date JavaDoc;
41 import java.util.Iterator JavaDoc;
42 import java.util.ResourceBundle JavaDoc;
43 import java.util.Vector JavaDoc;
44
45 /**
46  * TCP monitor to log http messages and responses, both SOAP and plain HTTP.
47  * If you want to choose a different Swing look and feel, set the property
48  * tcpmon.laf to the classname of the new look and feel
49  *
50  * @author Doug Davis (dug@us.ibm.com)
51  * @author Steve Loughran
52  */

53 public class tcpmon extends JFrame {
54     /**
55      * Field notebook
56      */

57     private JTabbedPane notebook = null;
58
59     /**
60      * Field STATE_COLUMN
61      */

62     private static final int STATE_COLUMN = 0;
63
64     /**
65      * Field OUTHOST_COLUMN
66      */

67     private static final int OUTHOST_COLUMN = 3;
68
69     /**
70      * Field REQ_COLUMN
71      */

72     private static final int REQ_COLUMN = 4;
73
74     /**
75      * Field DEFAULT_HOST
76      */

77     private static final String JavaDoc DEFAULT_HOST = "127.0.0.1";
78
79     /**
80      * Field DEFAULT_PORT
81      */

82     private static final int DEFAULT_PORT = 8080;
83
84     /**
85      * this is the admin page
86      */

87     class AdminPage extends JPanel {
88         /**
89          * Field listenerButton, proxyButton
90          */

91         public JRadioButton listenerButton, proxyButton;
92
93         /**
94          * Field hostLabel, tportLabel
95          */

96         public JLabel hostLabel, tportLabel;
97
98         /**
99          * Field port
100          */

101         public NumberField port;
102
103         /**
104          * Field host
105          */

106         public HostnameField host;
107
108         /**
109          * Field tport
110          */

111         public NumberField tport;
112
113         /**
114          * Field noteb
115          */

116         public JTabbedPane noteb;
117
118         /**
119          * Field HTTPProxyBox
120          */

121         public JCheckBox HTTPProxyBox;
122
123         /**
124          * Field HTTPProxyHost
125          */

126         public HostnameField HTTPProxyHost;
127
128         /**
129          * Field HTTPProxyPort
130          */

131         public NumberField HTTPProxyPort;
132
133         /**
134          * Field HTTPProxyHostLabel, HTTPProxyPortLabel
135          */

136         public JLabel HTTPProxyHostLabel, HTTPProxyPortLabel;
137
138         /**
139          * Field delayTimeLabel, delayBytesLabel
140          */

141         public JLabel delayTimeLabel, delayBytesLabel;
142
143         /**
144          * Field delayTime, delayBytes
145          */

146         public NumberField delayTime, delayBytes;
147
148         /**
149          * Field delayBox
150          */

151         public JCheckBox delayBox;
152
153         /**
154          * Constructor AdminPage
155          *
156          * @param notebook
157          * @param name
158          */

159         public AdminPage(JTabbedPane notebook, String JavaDoc name) {
160             JPanel mainPane = null;
161             JButton addButton = null;
162             this.setLayout(new BorderLayout());
163             noteb = notebook;
164             GridBagLayout layout = new GridBagLayout();
165             GridBagConstraints c = new GridBagConstraints();
166             mainPane = new JPanel(layout);
167             c.anchor = GridBagConstraints.WEST;
168             c.gridwidth = GridBagConstraints.REMAINDER;
169             mainPane.add(
170                     new JLabel(
171                             getMessage("newTCP00", "Create a new TCP/IP Monitor...")
172                                     + " "), c);
173
174             // Add some blank space
175
mainPane.add(Box.createRigidArea(new Dimension(1, 5)), c);
176
177             // The listener info
178
// /////////////////////////////////////////////////////////////////
179
JPanel tmpPanel = new JPanel(new GridBagLayout());
180             c.anchor = GridBagConstraints.WEST;
181             c.gridwidth = 1;
182             tmpPanel.add(new JLabel(getMessage("listenPort00", "Listen Port #")
183                                     + " "), c);
184             c.anchor = GridBagConstraints.WEST;
185             c.gridwidth = GridBagConstraints.REMAINDER;
186             tmpPanel.add(port = new NumberField(4), c);
187             mainPane.add(tmpPanel, c);
188             mainPane.add(Box.createRigidArea(new Dimension(1, 5)), c);
189
190             // Group for the radio buttons
191
ButtonGroup btns = new ButtonGroup();
192             c.anchor = GridBagConstraints.WEST;
193             c.gridwidth = GridBagConstraints.REMAINDER;
194             mainPane.add(new JLabel(getMessage("actAs00", "Act as a...")), c);
195
196             // Target Host/Port section
197
// /////////////////////////////////////////////////////////////////
198
c.anchor = GridBagConstraints.WEST;
199             c.gridwidth = GridBagConstraints.REMAINDER;
200             final String JavaDoc listener = getMessage("listener00", "Listener");
201             mainPane.add(listenerButton = new JRadioButton(listener), c);
202             btns.add(listenerButton);
203             listenerButton.setSelected(true);
204             listenerButton.addActionListener(new ActionListener JavaDoc() {
205                 public void actionPerformed(ActionEvent JavaDoc event) {
206                     if (listener.equals(event.getActionCommand())) {
207                         boolean state = listenerButton.isSelected();
208                         tport.setEnabled(state);
209                         host.setEnabled(state);
210                         hostLabel.setForeground(state
211                                         ? Color.black
212                                         : Color.gray);
213                         tportLabel.setForeground(state
214                                         ? Color.black
215                                         : Color.gray);
216                     }
217                 }
218             });
219             c.anchor = GridBagConstraints.WEST;
220             c.gridwidth = 1;
221             mainPane.add(Box.createRigidArea(new Dimension(25, 0)));
222             mainPane.add(hostLabel =
223                     new JLabel(getMessage("targetHostname00", "Target Hostname")
224                                     + " "), c);
225             c.anchor = GridBagConstraints.WEST;
226             c.gridwidth = GridBagConstraints.REMAINDER;
227             host = new HostnameField(30);
228             mainPane.add(host, c);
229             host.setText(DEFAULT_HOST);
230             c.anchor = GridBagConstraints.WEST;
231             c.gridwidth = 1;
232             mainPane.add(Box.createRigidArea(new Dimension(25, 0)));
233             mainPane.add(tportLabel =
234                     new JLabel(getMessage("targetPort00", "Target Port #")
235                                     + " "), c);
236             c.anchor = GridBagConstraints.WEST;
237             c.gridwidth = GridBagConstraints.REMAINDER;
238             tport = new NumberField(4);
239             mainPane.add(tport, c);
240             tport.setValue(DEFAULT_PORT);
241
242             // Act as proxy section
243
// /////////////////////////////////////////////////////////////////
244
c.anchor = GridBagConstraints.WEST;
245             c.gridwidth = GridBagConstraints.REMAINDER;
246             final String JavaDoc proxy = getMessage("proxy00", "Proxy");
247             mainPane.add(proxyButton = new JRadioButton(proxy), c);
248             btns.add(proxyButton);
249             proxyButton.addActionListener(new ActionListener JavaDoc() {
250                 public void actionPerformed(ActionEvent JavaDoc event) {
251                     if (proxy.equals(event.getActionCommand())) {
252                         boolean state = proxyButton.isSelected();
253                         tport.setEnabled(!state);
254                         host.setEnabled(!state);
255                         hostLabel.setForeground(state
256                                         ? Color.gray
257                                         : Color.black);
258                         tportLabel.setForeground(state
259                                         ? Color.gray
260                                         : Color.black);
261                     }
262                 }
263             });
264
265             // Spacer
266
// ///////////////////////////////////////////////////////////////
267
c.anchor = GridBagConstraints.WEST;
268             c.gridwidth = GridBagConstraints.REMAINDER;
269             mainPane.add(Box.createRigidArea(new Dimension(1, 10)), c);
270
271             // Options section
272
// /////////////////////////////////////////////////////////////////
273
JPanel opts = new JPanel(new GridBagLayout());
274             opts.setBorder(new TitledBorder JavaDoc(getMessage("options00",
275                                     "Options")));
276             c.anchor = GridBagConstraints.WEST;
277             c.gridwidth = GridBagConstraints.REMAINDER;
278             mainPane.add(opts, c);
279
280             // HTTP Proxy Support section
281
// /////////////////////////////////////////////////////////////////
282
c.anchor = GridBagConstraints.WEST;
283             c.gridwidth = GridBagConstraints.REMAINDER;
284             final String JavaDoc proxySupport = getMessage("proxySupport00",
285                     "HTTP Proxy Support");
286             opts.add(HTTPProxyBox = new JCheckBox(proxySupport), c);
287             c.anchor = GridBagConstraints.WEST;
288             c.gridwidth = 1;
289             opts.add(HTTPProxyHostLabel =
290                     new JLabel(getMessage("hostname00", "Hostname") + " "), c);
291             HTTPProxyHostLabel.setForeground(Color.gray);
292             c.anchor = GridBagConstraints.WEST;
293             c.gridwidth = GridBagConstraints.REMAINDER;
294             opts.add(HTTPProxyHost = new HostnameField(30), c);
295             HTTPProxyHost.setEnabled(false);
296             c.anchor = GridBagConstraints.WEST;
297             c.gridwidth = 1;
298             opts.add(HTTPProxyPortLabel =
299                     new JLabel(getMessage("port00", "Port #") + " "), c);
300             HTTPProxyPortLabel.setForeground(Color.gray);
301             c.anchor = GridBagConstraints.WEST;
302             c.gridwidth = GridBagConstraints.REMAINDER;
303             opts.add(HTTPProxyPort = new NumberField(4), c);
304             HTTPProxyPort.setEnabled(false);
305             HTTPProxyBox.addActionListener(new ActionListener JavaDoc() {
306                 public void actionPerformed(ActionEvent JavaDoc event) {
307                     if (proxySupport.equals(event.getActionCommand())) {
308                         boolean b = HTTPProxyBox.isSelected();
309                         Color color = b
310                                 ? Color.black
311                                 : Color.gray;
312                         HTTPProxyHost.setEnabled(b);
313                         HTTPProxyPort.setEnabled(b);
314                         HTTPProxyHostLabel.setForeground(color);
315                         HTTPProxyPortLabel.setForeground(color);
316                     }
317                 }
318             });
319
320             // Set default proxy values...
321
String JavaDoc tmp = System.getProperty("http.proxyHost");
322             if ((tmp != null) && tmp.equals("")) {
323                 tmp = null;
324             }
325             HTTPProxyBox.setSelected(tmp != null);
326             HTTPProxyHost.setEnabled(tmp != null);
327             HTTPProxyPort.setEnabled(tmp != null);
328             HTTPProxyHostLabel.setForeground((tmp != null)
329                             ? Color.black
330                             : Color.gray);
331             HTTPProxyPortLabel.setForeground((tmp != null)
332                             ? Color.black
333                             : Color.gray);
334             if (tmp != null) {
335                 HTTPProxyBox.setSelected(true);
336                 HTTPProxyHost.setText(tmp);
337                 tmp = System.getProperty("http.proxyPort");
338                 if ((tmp != null) && tmp.equals("")) {
339                     tmp = null;
340                 }
341                 if (tmp == null) {
342                     tmp = "80";
343                 }
344                 HTTPProxyPort.setText(tmp);
345             }
346
347             // add byte delay fields
348
opts.add(Box.createRigidArea(new Dimension(1, 10)), c);
349             c.anchor = GridBagConstraints.WEST;
350             c.gridwidth = GridBagConstraints.REMAINDER;
351             final String JavaDoc delaySupport = getMessage("delay00",
352                     "Simulate Slow Connection");
353             opts.add(delayBox = new JCheckBox(delaySupport), c);
354
355             // bytes per pause
356
c.anchor = GridBagConstraints.WEST;
357             c.gridwidth = 1;
358             delayBytesLabel = new JLabel(getMessage("delay01",
359                             "Bytes per Pause"));
360             opts.add(delayBytesLabel, c);
361             delayBytesLabel.setForeground(Color.gray);
362             c.anchor = GridBagConstraints.WEST;
363             c.gridwidth = GridBagConstraints.REMAINDER;
364             opts.add(delayBytes = new NumberField(6), c);
365             delayBytes.setEnabled(false);
366
367             // delay interval
368
c.anchor = GridBagConstraints.WEST;
369             c.gridwidth = 1;
370             delayTimeLabel = new JLabel(getMessage("delay02",
371                             "Delay in Milliseconds"));
372             opts.add(delayTimeLabel, c);
373             delayTimeLabel.setForeground(Color.gray);
374             c.anchor = GridBagConstraints.WEST;
375             c.gridwidth = GridBagConstraints.REMAINDER;
376             opts.add(delayTime = new NumberField(6), c);
377             delayTime.setEnabled(false);
378
379             // enabler callback
380
delayBox.addActionListener(new ActionListener JavaDoc() {
381                 public void actionPerformed(ActionEvent JavaDoc event) {
382                     if (delaySupport.equals(event.getActionCommand())) {
383                         boolean b = delayBox.isSelected();
384                         Color color = b
385                                 ? Color.black
386                                 : Color.gray;
387                         delayBytes.setEnabled(b);
388                         delayTime.setEnabled(b);
389                         delayBytesLabel.setForeground(color);
390                         delayTimeLabel.setForeground(color);
391                     }
392                 }
393             });
394
395             // Spacer
396
// ////////////////////////////////////////////////////////////////
397
mainPane.add(Box.createRigidArea(new Dimension(1, 10)), c);
398
399             // ADD Button
400
// /////////////////////////////////////////////////////////////////
401
c.anchor = GridBagConstraints.WEST;
402             c.gridwidth = GridBagConstraints.REMAINDER;
403             final String JavaDoc add = getMessage("add00", "Add");
404             mainPane.add(addButton = new JButton(add), c);
405             this.add(new JScrollPane(mainPane), BorderLayout.CENTER);
406
407             // addButton.setEnabled( false );
408
addButton.addActionListener(new ActionListener JavaDoc() {
409                 public void actionPerformed(ActionEvent JavaDoc event) {
410                     if (add.equals(event.getActionCommand())) {
411                         String JavaDoc text;
412                         Listener JavaDoc l = null;
413                         int lPort;
414                         lPort = port.getValue(0);
415                         if (lPort == 0) {
416
417                             // no port, button does nothing
418
return;
419                         }
420                         String JavaDoc tHost = host.getText();
421                         int tPort = 0;
422                         tPort = tport.getValue(0);
423                         SlowLinkSimulator slowLink = null;
424                         if (delayBox.isSelected()) {
425                             int bytes = delayBytes.getValue(0);
426                             int time = delayTime.getValue(0);
427                             slowLink = new SlowLinkSimulator(bytes, time);
428                         }
429                         try {
430                             l = new Listener JavaDoc(noteb, null, lPort, tHost, tPort,
431                                     proxyButton.isSelected(),
432                                     slowLink);
433                         } catch (Exception JavaDoc e) {
434                             e.printStackTrace();
435                         }
436
437                         // Pick-up the HTTP Proxy settings
438
// /////////////////////////////////////////////////
439
text = HTTPProxyHost.getText();
440                         if ("".equals(text)) {
441                             text = null;
442                         }
443                         l.HTTPProxyHost = text;
444                         text = HTTPProxyPort.getText();
445                         int proxyPort = HTTPProxyPort.getValue(-1);
446                         if (proxyPort != -1) {
447                             l.HTTPProxyPort = Integer.parseInt(text);
448                         }
449
450                         // reset the port
451
port.setText(null);
452                     }
453                 }
454             });
455             notebook.addTab(name, this);
456             notebook.repaint();
457             notebook.setSelectedIndex(notebook.getTabCount() - 1);
458         }
459     }
460
461     /**
462      * wait for incoming connections, spawn a connection thread when
463      * stuff comes in.
464      */

465     class SocketWaiter extends Thread JavaDoc {
466         /**
467          * Field sSocket
468          */

469         ServerSocket JavaDoc sSocket = null;
470
471         /**
472          * Field listener
473          */

474         Listener JavaDoc listener;
475
476         /**
477          * Field port
478          */

479         int port;
480
481         /**
482          * Field pleaseStop
483          */

484         boolean pleaseStop = false;
485
486         /**
487          * Constructor SocketWaiter
488          *
489          * @param l
490          * @param p
491          */

492         public SocketWaiter(Listener JavaDoc l, int p) {
493             listener = l;
494             port = p;
495             start();
496         }
497
498         /**
499          * Method run
500          */

501         public void run() {
502             try {
503                 listener.setLeft(
504                         new JLabel(
505                                 getMessage("wait00", " Waiting for Connection...")));
506                 listener.repaint();
507                 sSocket = new ServerSocket JavaDoc(port);
508                 for (; ;) {
509                     Socket JavaDoc inSocket = sSocket.accept();
510                     if (pleaseStop) {
511                         break;
512                     }
513                     new Connection(listener, inSocket);
514                     inSocket = null;
515                 }
516             } catch (Exception JavaDoc exp) {
517                 if (!"socket closed".equals(exp.getMessage())) {
518                     JLabel tmp = new JLabel(exp.toString());
519                     tmp.setForeground(Color.red);
520                     listener.setLeft(tmp);
521                     listener.setRight(new JLabel(""));
522                     listener.stop();
523                 }
524             }
525         }
526
527         /**
528          * force a halt by connecting to self and then closing the server socket
529          */

530         public void halt() {
531             try {
532                 pleaseStop = true;
533                 new Socket JavaDoc("127.0.0.1", port);
534                 if (sSocket != null) {
535                     sSocket.close();
536                 }
537             } catch (Exception JavaDoc e) {
538                 e.printStackTrace();
539             }
540         }
541     }
542
543     /**
544      * class to simulate slow connections by slowing down the system
545      */

546     static class SlowLinkSimulator {
547         /**
548          * Field delayBytes
549          */

550         private int delayBytes;
551
552         /**
553          * Field delayTime
554          */

555         private int delayTime;
556
557         /**
558          * Field currentBytes
559          */

560         private int currentBytes;
561
562         /**
563          * Field totalBytes
564          */

565         private int totalBytes;
566
567         /**
568          * construct
569          *
570          * @param delayBytes bytes per delay; set to 0 for no delay
571          * @param delayTime delay time per delay in milliseconds
572          */

573         public SlowLinkSimulator(int delayBytes, int delayTime) {
574             this.delayBytes = delayBytes;
575             this.delayTime = delayTime;
576         }
577
578         /**
579          * construct by copying delay bytes and time, but not current
580          * count of bytes
581          *
582          * @param that source of data
583          */

584         public SlowLinkSimulator(SlowLinkSimulator that) {
585             this.delayBytes = that.delayBytes;
586             this.delayTime = that.delayTime;
587         }
588
589         /**
590          * how many bytes have gone past?
591          *
592          * @return
593          */

594         public int getTotalBytes() {
595             return totalBytes;
596         }
597
598         /**
599          * log #of bytes pumped. Will pause when necessary. This method is not
600          * synchronized
601          *
602          * @param bytes
603          */

604         public void pump(int bytes) {
605             totalBytes += bytes;
606             if (delayBytes == 0) {
607
608                 // when not delaying, we are just a byte counter
609
return;
610             }
611             currentBytes += bytes;
612             if (currentBytes > delayBytes) {
613
614                 // we have overshot. lets find out how far
615
int delaysize = currentBytes / delayBytes;
616                 long delay = delaysize * (long) delayTime;
617
618                 // move byte counter down to the remainder of bytes
619
currentBytes = currentBytes % delayBytes;
620
621                 // now wait
622
try {
623                     Thread.sleep(delay);
624                 } catch (InterruptedException JavaDoc e) {
625                 ; // ignore the exception
626
}
627             }
628         }
629
630         /**
631          * get the current byte count
632          *
633          * @return
634          */

635         public int getCurrentBytes() {
636             return currentBytes;
637         }
638
639         /**
640          * set the current byte count
641          *
642          * @param currentBytes
643          */

644         public void setCurrentBytes(int currentBytes) {
645             this.currentBytes = currentBytes;
646         }
647     }
648
649     /**
650      * this class handles the pumping of data from the incoming socket to the
651      * outgoing socket
652      */

653     class SocketRR extends Thread JavaDoc {
654         /**
655          * Field inSocket
656          */

657         Socket JavaDoc inSocket = null;
658
659         /**
660          * Field outSocket
661          */

662         Socket JavaDoc outSocket = null;
663
664         /**
665          * Field textArea
666          */

667         JTextArea textArea;
668
669         /**
670          * Field in
671          */

672         InputStream in = null;
673
674         /**
675          * Field out
676          */

677         OutputStream out = null;
678
679         /**
680          * Field xmlFormat
681          */

682         boolean xmlFormat;
683
684         /**
685          * Field done
686          */

687         volatile boolean done = false;
688
689         /**
690          * Field tmodel
691          */

692         TableModel JavaDoc tmodel = null;
693
694         /**
695          * Field tableIndex
696          */

697         int tableIndex = 0;
698
699         /**
700          * Field type
701          */

702         String JavaDoc type = null;
703
704         /**
705          * Field myConnection
706          */

707         Connection myConnection = null;
708
709         /**
710          * Field slowLink
711          */

712         SlowLinkSimulator slowLink;
713
714         /**
715          * Constructor SocketRR
716          *
717          * @param c
718          * @param inputSocket
719          * @param inputStream
720          * @param outputSocket
721          * @param outputStream
722          * @param _textArea
723          * @param format
724          * @param tModel
725          * @param index
726          * @param type
727          * @param slowLink
728          */

729         public SocketRR(Connection c, Socket JavaDoc inputSocket,
730                         InputStream inputStream, Socket JavaDoc outputSocket,
731                         OutputStream outputStream, JTextArea _textArea,
732                         boolean format, TableModel JavaDoc tModel, int index,
733                         final String JavaDoc type, SlowLinkSimulator slowLink) {
734             inSocket = inputSocket;
735             in = inputStream;
736             outSocket = outputSocket;
737             out = outputStream;
738             textArea = _textArea;
739             xmlFormat = format;
740             tmodel = tModel;
741             tableIndex = index;
742             this.type = type;
743             myConnection = c;
744             this.slowLink = slowLink;
745             start();
746         }
747
748         /**
749          * Method isDone
750          *
751          * @return
752          */

753         public boolean isDone() {
754             return (done);
755         }
756
757         /**
758          * Method run
759          */

760         public void run() {
761             try {
762                 byte[] buffer = new byte[4096];
763                 byte[] tmpbuffer = new byte[8192];
764                 int saved = 0;
765                 int len;
766                 int i1, i2;
767                 int i;
768                 int reqSaved = 0;
769                 int tabWidth = 3;
770                 boolean atMargin = true;
771                 int thisIndent = -1, nextIndent = -1, previousIndent = -1;
772                 if (tmodel != null) {
773                     String JavaDoc tmpStr = (String JavaDoc) tmodel.getValueAt(tableIndex,
774                             REQ_COLUMN);
775                     if (!"".equals(tmpStr)) {
776                         reqSaved = tmpStr.length();
777                     }
778                 }
779                 a:
780                 for (; ;) {
781                     if (done) {
782                         break;
783                     }
784
785                     // try{
786
// len = in.available();
787
// }catch(Exception e){len=0;}
788
len = buffer.length;
789
790                     // Used to be 1, but if we block it doesn't matter
791
// however 1 will break with some servers, including apache
792
if (len == 0) {
793                         len = buffer.length;
794                     }
795                     if (saved + len > buffer.length) {
796                         len = buffer.length - saved;
797                     }
798                     int len1 = 0;
799                     while (len1 == 0) {
800                         try {
801                             len1 = in.read(buffer, saved, len);
802                         } catch (Exception JavaDoc ex) {
803                             if (done && (saved == 0)) {
804                                 break a;
805                             }
806                             len1 = -1;
807                             break;
808                         }
809                     }
810                     len = len1;
811                     if ((len == -1) && (saved == 0)) {
812                         break;
813                     }
814                     if (len == -1) {
815                         done = true;
816                     }
817
818                     // No matter how we may (or may not) format it, send it
819
// on unformatted - we don't want to mess with how its
820
// sent to the other side, just how its displayed
821
if ((out != null) && (len > 0)) {
822                         slowLink.pump(len);
823                         out.write(buffer, saved, len);
824                     }
825                     if ((tmodel != null) && (reqSaved < 50)) {
826                         String JavaDoc old = (String JavaDoc) tmodel.getValueAt(tableIndex,
827                                 REQ_COLUMN);
828                         old = old + new String JavaDoc(buffer, saved, len);
829                         if (old.length() > 50) {
830                             old = old.substring(0, 50);
831                         }
832                         reqSaved = old.length();
833                         if ((i = old.indexOf('\n')) > 0) {
834                             old = old.substring(0, i - 1);
835                             reqSaved = 50;
836                         }
837                         tmodel.setValueAt(old, tableIndex, REQ_COLUMN);
838                     }
839                     if (xmlFormat) {
840
841                         // Do XML Formatting
842
boolean inXML = false;
843                         int bufferLen = saved;
844                         if (len != -1) {
845                             bufferLen += len;
846                         }
847                         i1 = 0;
848                         i2 = 0;
849                         saved = 0;
850                         for (; i1 < bufferLen; i1++) {
851
852                             // Except when we're at EOF, saved last char
853
if ((len != -1) && (i1 + 1 == bufferLen)) {
854                                 saved = 1;
855                                 break;
856                             }
857                             thisIndent = -1;
858                             if ((buffer[i1] == '<')
859                                     && (buffer[i1 + 1] != '/')) {
860                                 previousIndent = nextIndent++;
861                                 thisIndent = nextIndent;
862                                 inXML = true;
863                             }
864                             if ((buffer[i1] == '<')
865                                     && (buffer[i1 + 1] == '/')) {
866                                 if (previousIndent > nextIndent) {
867                                     thisIndent = nextIndent;
868                                 }
869                                 previousIndent = nextIndent--;
870                                 inXML = true;
871                             }
872                             if ((buffer[i1] == '/')
873                                     && (buffer[i1 + 1] == '>')) {
874                                 previousIndent = nextIndent--;
875                                 inXML = true;
876                             }
877                             if (thisIndent != -1) {
878                                 if (thisIndent > 0) {
879                                     tmpbuffer[i2++] = (byte) '\n';
880                                 }
881                                 for (i = tabWidth * thisIndent; i > 0; i--) {
882                                     tmpbuffer[i2++] = (byte) ' ';
883                                 }
884                             }
885                             atMargin = ((buffer[i1] == '\n')
886                                                    || (buffer[i1] == '\r'));
887                             if (!inXML || !atMargin) {
888                                 tmpbuffer[i2++] = buffer[i1];
889                             }
890                         }
891                         textArea.append(new String JavaDoc(tmpbuffer, 0, i2));
892
893                         // Shift saved bytes to the beginning
894
for (i = 0; i < saved; i++) {
895                             buffer[i] = buffer[bufferLen - saved + i];
896                         }
897                     } else {
898                         textArea.append(new String JavaDoc(buffer, 0, len));
899                     }
900                 }
901             } catch (Exception JavaDoc e) {
902                 e.printStackTrace();
903             } finally {
904                 done = true;
905                 try {
906                     if (out != null) {
907                         out.flush();
908                         if (null != outSocket) {
909                             outSocket.shutdownOutput();
910                         } else {
911                             out.close();
912                         }
913                         out = null;
914                     }
915                 } catch (Exception JavaDoc e) {
916                 }
917                 try {
918                     if (in != null) {
919                         if (inSocket != null) {
920                             inSocket.shutdownInput();
921                         } else {
922                             in.close();
923                         }
924                         in = null;
925                     }
926                 } catch (Exception JavaDoc e) {
927                 }
928                 myConnection.wakeUp();
929             }
930         }
931
932         /**
933          * Method halt
934          */

935         public void halt() {
936             try {
937                 if (inSocket != null) {
938                     inSocket.close();
939                 }
940                 if (outSocket != null) {
941                     outSocket.close();
942                 }
943                 inSocket = null;
944                 outSocket = null;
945                 if (in != null) {
946                     in.close();
947                 }
948                 if (out != null) {
949                     out.close();
950                 }
951                 in = null;
952                 out = null;
953                 done = true;
954             } catch (Exception JavaDoc e) {
955                 e.printStackTrace();
956             }
957         }
958     }
959
960     /**
961      * a connection listens to a single current connection
962      */

963     class Connection extends Thread JavaDoc {
964         /**
965          * Field listener
966          */

967         Listener JavaDoc listener;
968
969         /**
970          * Field active
971          */

972         boolean active;
973
974         /**
975          * Field fromHost
976          */

977         String JavaDoc fromHost;
978
979         /**
980          * Field time
981          */

982         String JavaDoc time;
983
984         /**
985          * Field inputText
986          */

987         JTextArea inputText = null;
988
989         /**
990          * Field inputScroll
991          */

992         JScrollPane inputScroll = null;
993
994         /**
995          * Field outputText
996          */

997         JTextArea outputText = null;
998
999         /**
1000         * Field outputScroll
1001         */

1002        JScrollPane outputScroll = null;
1003
1004        /**
1005         * Field inSocket
1006         */

1007        Socket JavaDoc inSocket = null;
1008
1009        /**
1010         * Field outSocket
1011         */

1012        Socket JavaDoc outSocket = null;
1013
1014        /**
1015         * Field clientThread
1016         */

1017        Thread JavaDoc clientThread = null;
1018
1019        /**
1020         * Field serverThread
1021         */

1022        Thread JavaDoc serverThread = null;
1023
1024        /**
1025         * Field rr1
1026         */

1027        SocketRR rr1 = null;
1028
1029        /**
1030         * Field rr2
1031         */

1032        SocketRR rr2 = null;
1033
1034        /**
1035         * Field inputStream
1036         */

1037        InputStream inputStream = null;
1038
1039        /**
1040         * Field HTTPProxyHost
1041         */

1042        String JavaDoc HTTPProxyHost = null;
1043
1044        /**
1045         * Field HTTPProxyPort
1046         */

1047        int HTTPProxyPort = 80;
1048
1049        /**
1050         * Field slowLink
1051         */

1052        private SlowLinkSimulator slowLink;
1053
1054        /**
1055         * Constructor Connection
1056         *
1057         * @param l
1058         */

1059        public Connection(Listener JavaDoc l) {
1060            listener = l;
1061            HTTPProxyHost = l.HTTPProxyHost;
1062            HTTPProxyPort = l.HTTPProxyPort;
1063            slowLink = l.slowLink;
1064        }
1065
1066        /**
1067         * Constructor Connection
1068         *
1069         * @param l
1070         * @param s
1071         */

1072        public Connection(Listener JavaDoc l, Socket JavaDoc s) {
1073            this(l);
1074            inSocket = s;
1075            start();
1076        }
1077
1078        /**
1079         * Constructor Connection
1080         *
1081         * @param l
1082         * @param in
1083         */

1084        public Connection(Listener JavaDoc l, InputStream in) {
1085            this(l);
1086            inputStream = in;
1087            start();
1088        }
1089
1090        /**
1091         * Method run
1092         */

1093        public void run() {
1094            try {
1095                active = true;
1096                HTTPProxyHost = System.getProperty("http.proxyHost");
1097                if ((HTTPProxyHost != null) && HTTPProxyHost.equals("")) {
1098                    HTTPProxyHost = null;
1099                }
1100                if (HTTPProxyHost != null) {
1101                    String JavaDoc tmp = System.getProperty("http.proxyPort");
1102                    if ((tmp != null) && tmp.equals("")) {
1103                        tmp = null;
1104                    }
1105                    if (tmp == null) {
1106                        HTTPProxyPort = 80;
1107                    } else {
1108                        HTTPProxyPort = Integer.parseInt(tmp);
1109                    }
1110                }
1111                if (inSocket != null) {
1112                    fromHost = (inSocket.getInetAddress()).getHostName();
1113                } else {
1114                    fromHost = "resend";
1115                }
1116                String JavaDoc dateformat = getMessage("dateformat00",
1117                        "yyyy-MM-dd HH:mm:ss");
1118                DateFormat JavaDoc df = new SimpleDateFormat JavaDoc(dateformat);
1119                time = df.format(new Date JavaDoc());
1120                int count = listener.connections.size();
1121                listener.tableModel.insertRow(count + 1,
1122                        new Object JavaDoc[]{
1123                                    getMessage("active00",
1124                                            "Active"),
1125                                    time,
1126                                    fromHost,
1127                                    listener.hostField.getText(),
1128                                    ""});
1129                listener.connections.add(this);
1130                inputText = new JTextArea(null, null, 20, 80);
1131                inputScroll = new JScrollPane(inputText);
1132                outputText = new JTextArea(null, null, 20, 80);
1133                outputScroll = new JScrollPane(outputText);
1134                ListSelectionModel lsm =
1135                        listener.connectionTable.getSelectionModel();
1136                if ((count == 0) || (lsm.getLeadSelectionIndex() == 0)) {
1137                    listener.outPane.setVisible(false);
1138                    int divLoc = listener.outPane.getDividerLocation();
1139                    listener.setLeft(inputScroll);
1140                    listener.setRight(outputScroll);
1141                    listener.removeButton.setEnabled(false);
1142                    listener.removeAllButton.setEnabled(true);
1143                    listener.saveButton.setEnabled(true);
1144                    listener.resendButton.setEnabled(true);
1145                    listener.outPane.setDividerLocation(divLoc);
1146                    listener.outPane.setVisible(true);
1147                }
1148                String JavaDoc targetHost = listener.hostField.getText();
1149                int targetPort =
1150                        Integer.parseInt(listener.tPortField.getText());
1151                int listenPort =
1152                        Integer.parseInt(listener.portField.getText());
1153                InputStream tmpIn1 = inputStream;
1154                OutputStream tmpOut1 = null;
1155                InputStream tmpIn2 = null;
1156                OutputStream tmpOut2 = null;
1157                if (tmpIn1 == null) {
1158                    tmpIn1 = inSocket.getInputStream();
1159                }
1160                if (inSocket != null) {
1161                    tmpOut1 = inSocket.getOutputStream();
1162                }
1163                String JavaDoc bufferedData = null;
1164                StringBuffer JavaDoc buf = null;
1165                int index = listener.connections.indexOf(this);
1166                if (listener.isProxyBox.isSelected()
1167                        || (HTTPProxyHost != null)) {
1168
1169                    // Check if we're a proxy
1170
byte[] b = new byte[1];
1171                    buf = new StringBuffer JavaDoc();
1172                    String JavaDoc s;
1173                    for (; ;) {
1174                        int len;
1175                        len = tmpIn1.read(b, 0, 1);
1176                        if (len == -1) {
1177                            break;
1178                        }
1179                        s = new String JavaDoc(b);
1180                        buf.append(s);
1181                        if (b[0] != '\n') {
1182                            continue;
1183                        }
1184                        break;
1185                    }
1186                    bufferedData = buf.toString();
1187                    inputText.append(bufferedData);
1188                    if (bufferedData.startsWith("GET ")
1189                            || bufferedData.startsWith("POST ")
1190                            || bufferedData.startsWith("PUT ")
1191                            || bufferedData.startsWith("DELETE ")) {
1192                        int start, end;
1193                        URL url;
1194                        start = bufferedData.indexOf(' ') + 1;
1195                        while (bufferedData.charAt(start) == ' ') {
1196                            start++;
1197                        }
1198                        end = bufferedData.indexOf(' ', start);
1199                        String JavaDoc urlString = bufferedData.substring(start, end);
1200                        if (urlString.charAt(0) == '/') {
1201                            urlString = urlString.substring(1);
1202                        }
1203                        if (listener.isProxyBox.isSelected()) {
1204                            url = new URL(urlString);
1205                            targetHost = url.getHost();
1206                            targetPort = url.getPort();
1207                            if (targetPort == -1) {
1208                                targetPort = 80;
1209                            }
1210                            listener.tableModel.setValueAt(targetHost,
1211                                    index + 1,
1212                                    OUTHOST_COLUMN);
1213                            bufferedData = bufferedData.substring(0, start)
1214                                    + url.getFile()
1215                                    + bufferedData.substring(end);
1216                        } else {
1217                            url = new URL("http://" + targetHost + ":"
1218                                            + targetPort + "/" + urlString);
1219                            listener.tableModel.setValueAt(targetHost,
1220                                    index + 1,
1221                                    OUTHOST_COLUMN);
1222                            bufferedData = bufferedData.substring(0, start)
1223                                    + url.toExternalForm()
1224                                    + bufferedData.substring(end);
1225                            targetHost = HTTPProxyHost;
1226                            targetPort = HTTPProxyPort;
1227                        }
1228                    }
1229                } else {
1230
1231                    //
1232
// Change Host: header to point to correct host
1233
//
1234
byte[] b1 = new byte[1];
1235                    buf = new StringBuffer JavaDoc();
1236                    String JavaDoc s1;
1237                    String JavaDoc lastLine = null;
1238                    for (; ;) {
1239                        int len;
1240                        len = tmpIn1.read(b1, 0, 1);
1241                        if (len == -1) {
1242                            break;
1243                        }
1244                        s1 = new String JavaDoc(b1);
1245                        buf.append(s1);
1246                        if (b1[0] != '\n') {
1247                            continue;
1248                        }
1249
1250                        // we have a complete line
1251
String JavaDoc line = buf.toString();
1252                        buf.setLength(0);
1253
1254                        // check to see if we have found Host: header
1255
if (line.startsWith("Host: ")) {
1256
1257                            // we need to update the hostname to target host
1258
String JavaDoc newHost = "Host: " + targetHost + ":"
1259                                    + listenPort + "\r\n";
1260                            bufferedData = bufferedData.concat(newHost);
1261                            break;
1262                        }
1263
1264                        // add it to our headers so far
1265
if (bufferedData == null) {
1266                            bufferedData = line;
1267                        } else {
1268                            bufferedData = bufferedData.concat(line);
1269                        }
1270
1271                        // failsafe
1272
if (line.equals("\r\n")) {
1273                            break;
1274                        }
1275                        if ("\n".equals(lastLine) && line.equals("\n")) {
1276                            break;
1277                        }
1278                        lastLine = line;
1279                    }
1280                    if (bufferedData != null) {
1281                        inputText.append(bufferedData);
1282                        int idx = (bufferedData.length() < 50)
1283                                ? bufferedData.length()
1284                                : 50;
1285                        s1 = bufferedData.substring(0, idx);
1286                        int i = s1.indexOf('\n');
1287                        if (i > 0) {
1288                            s1 = s1.substring(0, i - 1);
1289                        }
1290                        s1 = s1 + " "
1291                                + " ";
1292                        s1 = s1.substring(0, 51);
1293                        listener.tableModel.setValueAt(s1, index + 1,
1294                                REQ_COLUMN);
1295                    }
1296                }
1297                if (targetPort == -1) {
1298                    targetPort = 80;
1299                }
1300                outSocket = new Socket JavaDoc(targetHost, targetPort);
1301                tmpIn2 = outSocket.getInputStream();
1302                tmpOut2 = outSocket.getOutputStream();
1303                if (bufferedData != null) {
1304                    byte[] b = bufferedData.getBytes();
1305                    tmpOut2.write(b);
1306                    slowLink.pump(b.length);
1307                }
1308                boolean format = listener.xmlFormatBox.isSelected();
1309
1310                // this is the channel to the endpoint
1311
rr1 = new SocketRR(this, inSocket, tmpIn1, outSocket, tmpOut2,
1312                        inputText, format, listener.tableModel,
1313                        index + 1, "request:", slowLink);
1314
1315                // create the response slow link from the inbound slow link
1316
SlowLinkSimulator responseLink =
1317                new SlowLinkSimulator(slowLink);
1318
1319                // this is the channel from the endpoint
1320
rr2 = new SocketRR(this, outSocket, tmpIn2, inSocket, tmpOut1,
1321                        outputText, format, null, 0, "response:",
1322                        responseLink);
1323                while ((rr1 != null) || (rr2 != null)) {
1324
1325                    // Only loop as long as the connection to the target
1326
// machine is available - once that's gone we can stop.
1327
// The old way, loop until both are closed, left us
1328
// looping forever since no one closed the 1st one.
1329
// while( !rr2.isDone() )
1330
if ((null != rr1) && rr1.isDone()) {
1331                        if ((index >= 0) && (rr2 != null)) {
1332                            listener.tableModel.setValueAt(
1333                                    getMessage("resp00", "Resp"), 1 + index,
1334                                    STATE_COLUMN);
1335                        }
1336                        rr1 = null;
1337                    }
1338                    if ((null != rr2) && rr2.isDone()) {
1339                        if ((index >= 0) && (rr1 != null)) {
1340                            listener.tableModel.setValueAt(
1341                                    getMessage("req00", "Req"), 1 + index,
1342                                    STATE_COLUMN);
1343                        }
1344                        rr2 = null;
1345                    }
1346
1347                    // Thread.sleep( 10 );
1348
synchronized (this) {
1349                        this.wait(
1350                                1000); // Safety just incase we're not told to wake up.
1351
}
1352                }
1353
1354                // System.out.println("Done ");
1355
// rr1.halt();
1356
// rr2.halt();
1357
active = false;
1358
1359                /*
1360                 * if ( inSocket != null ) {
1361                 * inSocket.close();
1362                 * inSocket = null ;
1363                 * }
1364                 * outSocket.close();
1365                 * outSocket = null ;
1366                 */

1367                if (index >= 0) {
1368                    listener.tableModel.setValueAt(getMessage("done00", "Done"),
1369                            1 + index, STATE_COLUMN);
1370                }
1371            } catch (Exception JavaDoc e) {
1372                StringWriter st = new StringWriter();
1373                PrintWriter wr = new PrintWriter(st);
1374                int index = listener.connections.indexOf(this);
1375                if (index >= 0) {
1376                    listener.tableModel.setValueAt(
1377                            getMessage("error00", "Error"), 1 + index,
1378                            STATE_COLUMN);
1379                }
1380                e.printStackTrace(wr);
1381                wr.close();
1382                if (outputText != null) {
1383                    outputText.append(st.toString());
1384                } else {
1385
1386                    // something went wrong before we had the output area
1387
System.out.println(st.toString());
1388                }
1389                halt();
1390            }
1391        }
1392
1393        /**
1394         * Method wakeUp
1395         */

1396        synchronized void wakeUp() {
1397            this.notifyAll();
1398        }
1399
1400        /**
1401         * Method halt
1402         */

1403        public void halt() {
1404            try {
1405                if (rr1 != null) {
1406                    rr1.halt();
1407                }
1408                if (rr2 != null) {
1409                    rr2.halt();
1410                }
1411                if (inSocket != null) {
1412                    inSocket.close();
1413                }
1414                inSocket = null;
1415                if (outSocket != null) {
1416                    outSocket.close();
1417                }
1418                outSocket = null;
1419            } catch (Exception JavaDoc e) {
1420                e.printStackTrace();
1421            }
1422        }
1423
1424        /**
1425         * Method remove
1426         */

1427        public void remove() {
1428            int index = -1;
1429            try {
1430                halt();
1431                index = listener.connections.indexOf(this);
1432                listener.tableModel.removeRow(index + 1);
1433                listener.connections.remove(index);
1434            } catch (Exception JavaDoc e) {
1435                System.err.println("index:=" + index + this);
1436                e.printStackTrace();
1437            }
1438        }
1439    }
1440
1441    /**
1442     * this is one of the tabbed panels that acts as the actual proxy
1443     */

1444    class Listener extends JPanel {
1445        /**
1446         * Field inputSocket
1447         */

1448        public Socket JavaDoc inputSocket = null;
1449
1450        /**
1451         * Field outputSocket
1452         */

1453        public Socket JavaDoc outputSocket = null;
1454
1455        /**
1456         * Field portField
1457         */

1458        public JTextField portField = null;
1459
1460        /**
1461         * Field hostField
1462         */

1463        public JTextField hostField = null;
1464
1465        /**
1466         * Field tPortField
1467         */

1468        public JTextField tPortField = null;
1469
1470        /**
1471         * Field isProxyBox
1472         */

1473        public JCheckBox isProxyBox = null;
1474
1475        /**
1476         * Field stopButton
1477         */

1478        public JButton stopButton = null;
1479
1480        /**
1481         * Field removeButton
1482         */

1483        public JButton removeButton = null;
1484
1485        /**
1486         * Field removeAllButton
1487         */

1488        public JButton removeAllButton = null;
1489
1490        /**
1491         * Field xmlFormatBox
1492         */

1493        public JCheckBox xmlFormatBox = null;
1494
1495        /**
1496         * Field saveButton
1497         */

1498        public JButton saveButton = null;
1499
1500        /**
1501         * Field resendButton
1502         */

1503        public JButton resendButton = null;
1504
1505        /**
1506         * Field switchButton
1507         */

1508        public JButton switchButton = null;
1509
1510        /**
1511         * Field closeButton
1512         */

1513        public JButton closeButton = null;
1514
1515        /**
1516         * Field connectionTable
1517         */

1518        public JTable connectionTable = null;
1519
1520        /**
1521         * Field tableModel
1522         */

1523        public DefaultTableModel JavaDoc tableModel = null;
1524
1525        /**
1526         * Field outPane
1527         */

1528        public JSplitPane outPane = null;
1529
1530        /**
1531         * Field sSocket
1532         */

1533        public ServerSocket JavaDoc sSocket = null;
1534
1535        /**
1536         * Field sw
1537         */

1538        public SocketWaiter sw = null;
1539
1540        /**
1541         * Field leftPanel
1542         */

1543        public JPanel leftPanel = null;
1544
1545        /**
1546         * Field rightPanel
1547         */

1548        public JPanel rightPanel = null;
1549
1550        /**
1551         * Field notebook
1552         */

1553        public JTabbedPane notebook = null;
1554
1555        /**
1556         * Field HTTPProxyHost
1557         */

1558        public String JavaDoc HTTPProxyHost = null;
1559
1560        /**
1561         * Field HTTPProxyPort
1562         */

1563        public int HTTPProxyPort = 80;
1564
1565        /**
1566         * Field delayBytes
1567         */

1568        public int delayBytes = 0;
1569
1570        /**
1571         * Field delayTime
1572         */

1573        public int delayTime = 0;
1574
1575        /**
1576         * Field slowLink
1577         */

1578        public SlowLinkSimulator slowLink;
1579
1580        /**
1581         * Field connections
1582         */

1583        public final Vector JavaDoc connections = new Vector JavaDoc();
1584
1585        /**
1586         * create a listener
1587         *
1588         * @param _notebook
1589         * @param name
1590         * @param listenPort
1591         * @param host
1592         * @param targetPort
1593         * @param isProxy
1594         * @param slowLink optional reference to a slow connection
1595         */

1596        public Listener(JTabbedPane _notebook, String JavaDoc name, int listenPort,
1597                        String JavaDoc host, int targetPort, boolean isProxy,
1598                        SlowLinkSimulator slowLink) {
1599            notebook = _notebook;
1600            if (name == null) {
1601                name = getMessage("port01", "Port") + " " + listenPort;
1602            }
1603
1604            // set the slow link to the passed down link
1605
if (slowLink != null) {
1606                this.slowLink = slowLink;
1607            } else {
1608
1609                // or make up a no-op one.
1610
this.slowLink = new SlowLinkSimulator(0, 0);
1611            }
1612            this.setLayout(new BorderLayout());
1613
1614            // 1st component is just a row of labels and 1-line entry fields
1615
// ///////////////////////////////////////////////////////////////////
1616
JPanel top = new JPanel();
1617            top.setLayout(new BoxLayout(top, BoxLayout.X_AXIS));
1618            top.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
1619            final String JavaDoc start = getMessage("start00", "Start");
1620            top.add(stopButton = new JButton(start));
1621            top.add(Box.createRigidArea(new Dimension(5, 0)));
1622            top.add(new JLabel(" "
1623                                    + getMessage("listenPort01", "Listen Port:")
1624                                    + " ", SwingConstants.RIGHT));
1625            top.add(portField = new JTextField("" + listenPort, 4));
1626            top.add(new JLabel(" " + getMessage("host00", "Host:"),
1627                            SwingConstants.RIGHT));
1628            top.add(hostField = new JTextField(host, 30));
1629            top.add(new JLabel(" " + getMessage("port02", "Port:") + " ",
1630                            SwingConstants.RIGHT));
1631            top.add(tPortField = new JTextField("" + targetPort, 4));
1632            top.add(Box.createRigidArea(new Dimension(5, 0)));
1633            top.add(isProxyBox = new JCheckBox(getMessage("proxy00", "Proxy")));
1634            isProxyBox.addChangeListener(new BasicButtonListener JavaDoc(isProxyBox) {
1635                public void stateChanged(ChangeEvent JavaDoc event) {
1636                    JCheckBox box = (JCheckBox) event.getSource();
1637                    boolean state = box.isSelected();
1638                    tPortField.setEnabled(!state);
1639                    hostField.setEnabled(!state);
1640                }
1641            });
1642            isProxyBox.setSelected(isProxy);
1643            portField.setEditable(false);
1644            portField.setMaximumSize(new Dimension(50, Short.MAX_VALUE));
1645            hostField.setEditable(false);
1646            hostField.setMaximumSize(new Dimension(85, Short.MAX_VALUE));
1647            tPortField.setEditable(false);
1648            tPortField.setMaximumSize(new Dimension(50, Short.MAX_VALUE));
1649            stopButton.addActionListener(new ActionListener JavaDoc() {
1650                public void actionPerformed(ActionEvent JavaDoc event) {
1651                    if (getMessage("stop00",
1652                            "Stop").equals(event.getActionCommand())) {
1653                        stop();
1654                    }
1655                    if (start.equals(event.getActionCommand())) {
1656                        start();
1657                    }
1658                }
1659            });
1660            this.add(top, BorderLayout.NORTH);
1661
1662            // 2nd component is a split pane with a table on the top
1663
// and the request/response text areas on the bottom
1664
// ///////////////////////////////////////////////////////////////////
1665
tableModel = new DefaultTableModel JavaDoc(new String JavaDoc[]{
1666                                getMessage("state00", "State"),
1667                                getMessage("time00", "Time"),
1668                                getMessage("requestHost00", "Request Host"),
1669                                getMessage("targetHost", "Target Host"),
1670                                getMessage("request00", "Request...")}, 0);
1671            tableModel.addRow(new Object JavaDoc[]{"---",
1672                                getMessage("mostRecent00",
1673                                        "Most Recent"),
1674                                "---", "---", "---"});
1675            connectionTable = new JTable(1, 2);
1676            connectionTable.setModel(tableModel);
1677            connectionTable.setSelectionMode(
1678                    ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
1679
1680            // Reduce the STATE column and increase the REQ column
1681
TableColumn JavaDoc col;
1682            col = connectionTable.getColumnModel().getColumn(STATE_COLUMN);
1683            col.setMaxWidth(col.getPreferredWidth() / 2);
1684            col = connectionTable.getColumnModel().getColumn(REQ_COLUMN);
1685            col.setPreferredWidth(col.getPreferredWidth() * 2);
1686            ListSelectionModel sel = connectionTable.getSelectionModel();
1687            sel.addListSelectionListener(new ListSelectionListener JavaDoc() {
1688                public void valueChanged(ListSelectionEvent JavaDoc event) {
1689                    if (event.getValueIsAdjusting()) {
1690                        return;
1691                    }
1692                    ListSelectionModel m =
1693                            (ListSelectionModel) event.getSource();
1694                    int divLoc = outPane.getDividerLocation();
1695                    if (m.isSelectionEmpty()) {
1696                        setLeft(
1697                                new JLabel(
1698                                        " "
1699                                                + getMessage(
1700                                                        "wait00", "Waiting for Connection...")));
1701                        setRight(new JLabel(""));
1702                        removeButton.setEnabled(false);
1703                        removeAllButton.setEnabled(false);
1704                        saveButton.setEnabled(false);
1705                        resendButton.setEnabled(false);
1706                    } else {
1707                        int row = m.getLeadSelectionIndex();
1708                        if (row == 0) {
1709                            if (connections.size() == 0) {
1710                                setLeft(
1711                                        new JLabel(
1712                                                " "
1713                                                        + getMessage(
1714                                                                "wait00",
1715                                                                "Waiting for connection...")));
1716                                setRight(new JLabel(""));
1717                                removeButton.setEnabled(false);
1718                                removeAllButton.setEnabled(false);
1719                                saveButton.setEnabled(false);
1720                                resendButton.setEnabled(false);
1721                            } else {
1722                                Connection conn =
1723                                        (Connection) connections.lastElement();
1724                                setLeft(conn.inputScroll);
1725                                setRight(conn.outputScroll);
1726                                removeButton.setEnabled(false);
1727                                removeAllButton.setEnabled(true);
1728                                saveButton.setEnabled(true);
1729                                resendButton.setEnabled(true);
1730                            }
1731                        } else {
1732                            Connection conn = (Connection) connections.get(row
1733                                            - 1);
1734                            setLeft(conn.inputScroll);
1735                            setRight(conn.outputScroll);
1736                            removeButton.setEnabled(true);
1737                            removeAllButton.setEnabled(true);
1738                            saveButton.setEnabled(true);
1739                            resendButton.setEnabled(true);
1740                        }
1741                    }
1742                    outPane.setDividerLocation(divLoc);
1743                }
1744            });
1745            JPanel tablePane = new JPanel();
1746            tablePane.setLayout(new BorderLayout());
1747            JScrollPane tableScrollPane = new JScrollPane(connectionTable);
1748            tablePane.add(tableScrollPane, BorderLayout.CENTER);
1749            JPanel buttons = new JPanel();
1750            buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS));
1751            buttons.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
1752            final String JavaDoc removeSelected = getMessage("removeSelected00",
1753                    "Remove Selected");
1754            buttons.add(removeButton = new JButton(removeSelected));
1755            buttons.add(Box.createRigidArea(new Dimension(5, 0)));
1756            final String JavaDoc removeAll = getMessage("removeAll00", "Remove All");
1757            buttons.add(removeAllButton = new JButton(removeAll));
1758            tablePane.add(buttons, BorderLayout.SOUTH);
1759            removeButton.setEnabled(false);
1760            removeButton.addActionListener(new ActionListener JavaDoc() {
1761                public void actionPerformed(ActionEvent JavaDoc event) {
1762                    if (removeSelected.equals(event.getActionCommand())) {
1763                        remove();
1764                    }
1765                }
1766            });
1767            removeAllButton.setEnabled(false);
1768            removeAllButton.addActionListener(new ActionListener JavaDoc() {
1769                public void actionPerformed(ActionEvent JavaDoc event) {
1770                    if (removeAll.equals(event.getActionCommand())) {
1771                        removeAll();
1772                    }
1773                }
1774            });
1775
1776            // Add Response Section
1777
// ///////////////////////////////////////////////////////////////////
1778
JPanel pane2 = new JPanel();
1779            pane2.setLayout(new BorderLayout());
1780            leftPanel = new JPanel();
1781            leftPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
1782            leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
1783            leftPanel.add(new JLabel(" "
1784                                    + getMessage("request01", "Request")));
1785            leftPanel.add(new JLabel(" "
1786                                    + getMessage("wait01",
1787                                            "Waiting for connection")));
1788            rightPanel = new JPanel();
1789            rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
1790            rightPanel.add(new JLabel(" "
1791                                    + getMessage("response00", "Response")));
1792            rightPanel.add(new JLabel(""));
1793            outPane = new JSplitPane(0, leftPanel, rightPanel);
1794            outPane.setDividerSize(4);
1795            pane2.add(outPane, BorderLayout.CENTER);
1796            JPanel bottomButtons = new JPanel();
1797            bottomButtons.setLayout(new BoxLayout(bottomButtons,
1798                            BoxLayout.X_AXIS));
1799            bottomButtons.setBorder(BorderFactory.createEmptyBorder(5, 5, 5,
1800                            5));
1801            bottomButtons.add(xmlFormatBox =
1802                    new JCheckBox(getMessage("xmlFormat00", "XML Format")));
1803            bottomButtons.add(Box.createRigidArea(new Dimension(5, 0)));
1804            final String JavaDoc save = getMessage("save00", "Save");
1805            bottomButtons.add(saveButton = new JButton(save));
1806            bottomButtons.add(Box.createRigidArea(new Dimension(5, 0)));
1807            final String JavaDoc resend = getMessage("resend00", "Resend");
1808            bottomButtons.add(resendButton = new JButton(resend));
1809            bottomButtons.add(Box.createRigidArea(new Dimension(5, 0)));
1810            final String JavaDoc switchStr = getMessage("switch00", "Switch Layout");
1811            bottomButtons.add(switchButton = new JButton(switchStr));
1812            bottomButtons.add(Box.createHorizontalGlue());
1813            final String JavaDoc close = getMessage("close00", "Close");
1814            bottomButtons.add(closeButton = new JButton(close));
1815            pane2.add(bottomButtons, BorderLayout.SOUTH);
1816            saveButton.setEnabled(false);
1817            saveButton.addActionListener(new ActionListener JavaDoc() {
1818                public void actionPerformed(ActionEvent JavaDoc event) {
1819                    if (save.equals(event.getActionCommand())) {
1820                        save();
1821                    }
1822                }
1823            });
1824            resendButton.setEnabled(false);
1825            resendButton.addActionListener(new ActionListener JavaDoc() {
1826                public void actionPerformed(ActionEvent JavaDoc event) {
1827                    if (resend.equals(event.getActionCommand())) {
1828                        resend();
1829                    }
1830                }
1831            });
1832            switchButton.addActionListener(new ActionListener JavaDoc() {
1833                public void actionPerformed(ActionEvent JavaDoc event) {
1834                    if (switchStr.equals(event.getActionCommand())) {
1835                        int v = outPane.getOrientation();
1836                        if (v == 0) {
1837
1838                            // top/bottom
1839
outPane.setOrientation(1);
1840                        } else {
1841
1842                            // left/right
1843
outPane.setOrientation(0);
1844                        }
1845                        outPane.setDividerLocation(0.5);
1846                    }
1847                }
1848            });
1849            closeButton.addActionListener(new ActionListener JavaDoc() {
1850                public void actionPerformed(ActionEvent JavaDoc event) {
1851                    if (close.equals(event.getActionCommand())) {
1852                        close();
1853                    }
1854                }
1855            });
1856            JSplitPane pane1 = new JSplitPane(0);
1857            pane1.setDividerSize(4);
1858            pane1.setTopComponent(tablePane);
1859            pane1.setBottomComponent(pane2);
1860            pane1.setDividerLocation(150);
1861            this.add(pane1, BorderLayout.CENTER);
1862
1863            //
1864
// //////////////////////////////////////////////////////////////////
1865
sel.setSelectionInterval(0, 0);
1866            outPane.setDividerLocation(150);
1867            notebook.addTab(name, this);
1868            start();
1869        }
1870
1871        /**
1872         * Method setLeft
1873         *
1874         * @param left
1875         */

1876        public void setLeft(Component left) {
1877            leftPanel.removeAll();
1878            leftPanel.add(left);
1879        }
1880
1881        /**
1882         * Method setRight
1883         *
1884         * @param right
1885         */

1886        public void setRight(Component right) {
1887            rightPanel.removeAll();
1888            rightPanel.add(right);
1889        }
1890
1891        /**
1892         * Method start
1893         */

1894        public void start() {
1895            int port = Integer.parseInt(portField.getText());
1896            portField.setText("" + port);
1897            int i = notebook.indexOfComponent(this);
1898            notebook.setTitleAt(i, getMessage("port01", "Port") + " " + port);
1899            int tmp = Integer.parseInt(tPortField.getText());
1900            tPortField.setText("" + tmp);
1901            sw = new SocketWaiter(this, port);
1902            stopButton.setText(getMessage("stop00", "Stop"));
1903            portField.setEditable(false);
1904            hostField.setEditable(false);
1905            tPortField.setEditable(false);
1906            isProxyBox.setEnabled(false);
1907        }
1908
1909        /**
1910         * Method close
1911         */

1912        public void close() {
1913            stop();
1914            notebook.remove(this);
1915        }
1916
1917        /**
1918         * Method stop
1919         */

1920        public void stop() {
1921            try {
1922                for (int i = 0; i < connections.size(); i++) {
1923                    Connection conn = (Connection) connections.get(i);
1924                    conn.halt();
1925                }
1926                sw.halt();
1927                stopButton.setText(getMessage("start00", "Start"));
1928                portField.setEditable(true);
1929                hostField.setEditable(true);
1930                tPortField.setEditable(true);
1931                isProxyBox.setEnabled(true);
1932            } catch (Exception JavaDoc e) {
1933                e.printStackTrace();
1934            }
1935        }
1936
1937        /**
1938         * Method remove
1939         */

1940        public void remove() {
1941            ListSelectionModel lsm = connectionTable.getSelectionModel();
1942            int bot = lsm.getMinSelectionIndex();
1943            int top = lsm.getMaxSelectionIndex();
1944            for (int i = top; i >= bot; i--) {
1945                ((Connection) connections.get(i - 1)).remove();
1946            }
1947            if (bot > connections.size()) {
1948                bot = connections.size();
1949            }
1950            lsm.setSelectionInterval(bot, bot);
1951        }
1952
1953        /**
1954         * Method removeAll
1955         */

1956        public void removeAll() {
1957            ListSelectionModel lsm = connectionTable.getSelectionModel();
1958            lsm.clearSelection();
1959            while (connections.size() > 0) {
1960                ((Connection) connections.get(0)).remove();
1961            }
1962            lsm.setSelectionInterval(0, 0);
1963        }
1964
1965        /**
1966         * Method save
1967         */

1968        public void save() {
1969            JFileChooser dialog = new JFileChooser(".");
1970            int rc = dialog.showSaveDialog(this);
1971            if (rc == JFileChooser.APPROVE_OPTION) {
1972                try {
1973                    File file = dialog.getSelectedFile();
1974                    FileOutputStream out = new FileOutputStream(file);
1975                    ListSelectionModel lsm =
1976                            connectionTable.getSelectionModel();
1977                    rc = lsm.getLeadSelectionIndex();
1978                    int n = 0;
1979                    for (Iterator JavaDoc i = connections.iterator(); i.hasNext();
1980                         n++) {
1981                        Connection conn = (Connection) i.next();
1982                        if (lsm.isSelectedIndex(n + 1)
1983                                || (!(i.hasNext())
1984                                               && (lsm.getLeadSelectionIndex() == 0))) {
1985                            rc = Integer.parseInt(portField.getText());
1986                            out.write("\n==============\n".getBytes());
1987                            out.write(
1988                                    ((getMessage("listenPort01", "Listen Port:")
1989                                                 + " " + rc + "\n")).getBytes());
1990                            out.write(
1991                                    (getMessage("targetHost01", "Target Host:")
1992                                                + " " + hostField.getText()
1993                                                + "\n").getBytes());
1994                            rc = Integer.parseInt(tPortField.getText());
1995                            out.write(
1996                                    ((getMessage("targetPort01", "Target Port:")
1997                                                 + " " + rc + "\n")).getBytes());
1998                            out.write((("==== "
1999                                                   + getMessage("request01", "Request")
2000                                                   + " ====\n")).getBytes());
2001                            out.write(conn.inputText.getText().getBytes());
2002                            out.write((("==== "
2003                                                   + getMessage("response00", "Response")
2004                                                   + " ====\n")).getBytes());
2005                            out.write(conn.outputText.getText().getBytes());
2006                            out.write("\n==============\n".getBytes());
2007                        }
2008                    }
2009                    out.close();
2010                } catch (Exception JavaDoc e) {
2011                    e.printStackTrace();
2012                }
2013            }
2014        }
2015
2016        /**
2017         * Method resend
2018         */

2019        public void resend() {
2020            int rc;
2021            try {
2022                ListSelectionModel lsm = connectionTable.getSelectionModel();
2023                rc = lsm.getLeadSelectionIndex();
2024                if (rc == 0) {
2025                    rc = connections.size();
2026                }
2027                Connection conn = (Connection) connections.get(rc - 1);
2028                if (rc > 0) {
2029                    lsm.clearSelection();
2030                    lsm.setSelectionInterval(0, 0);
2031                }
2032                InputStream in = null;
2033                String JavaDoc text = conn.inputText.getText();
2034
2035                // Fix Content-Length HTTP headers
2036
if (text.startsWith("POST ") || text.startsWith("GET ")) {
2037
2038                    // System.err.println("IN CL" );
2039
int pos1, pos2, pos3;
2040                    String JavaDoc headers;
2041                    pos3 = text.indexOf("\n\n");
2042                    if (pos3 == -1) {
2043                        pos3 = text.indexOf("\r\n\r\n");
2044                        if (pos3 != -1) {
2045                            pos3 = pos3 + 4;
2046                        }
2047                    } else {
2048                        pos3 += 2;
2049                    }
2050                    headers = text.substring(0, pos3);
2051                    pos1 = headers.indexOf("Content-Length:");
2052
2053                    // System.err.println("pos1: " + pos1 );
2054
// System.err.println("pos3: " + pos3 );
2055
if (pos1 != -1) {
2056                        int newLen = text.length() - pos3;
2057                        pos2 = headers.indexOf("\n", pos1);
2058                        System.err.println("CL: " + newLen);
2059                        System.err.println("Hdrs: '" + headers + "'");
2060                        System.err.println("subTEXT: '"
2061                                        + text.substring(pos3, pos3 + newLen)
2062                                        + "'");
2063                        text = headers.substring(0, pos1) + "Content-Length: "
2064                                + newLen + "\n" + headers.substring(pos2 + 1)
2065                                + text.substring(pos3);
2066                        System.err.println("\nTEXT: '" + text + "'");
2067                    }
2068                }
2069                in = new ByteArrayInputStream(text.getBytes());
2070                new Connection(this, in);
2071            } catch (Exception JavaDoc e) {
2072                e.printStackTrace();
2073            }
2074        }
2075    }
2076
2077    /**
2078     * Constructor tcpmon
2079     *
2080     * @param listenPort
2081     * @param targetHost
2082     * @param targetPort
2083     * @param embedded
2084     */

2085    public tcpmon(int listenPort, String JavaDoc targetHost, int targetPort,
2086                  boolean embedded) {
2087        super(getMessage("tcpmon00", "TCPMonitor"));
2088        notebook = new JTabbedPane();
2089        this.getContentPane().add(notebook);
2090        new AdminPage(notebook, getMessage("admin00", "Admin"));
2091        if (listenPort != 0) {
2092            Listener JavaDoc l = null;
2093            if (targetHost == null) {
2094                l = new Listener JavaDoc(notebook, null, listenPort, targetHost,
2095                        targetPort, true, null);
2096            } else {
2097                l = new Listener JavaDoc(notebook, null, listenPort, targetHost,
2098                        targetPort, false, null);
2099            }
2100            notebook.setSelectedIndex(1);
2101            l.HTTPProxyHost = System.getProperty("http.proxyHost");
2102            if ((l.HTTPProxyHost != null) && l.HTTPProxyHost.equals("")) {
2103                l.HTTPProxyHost = null;
2104            }
2105            if (l.HTTPProxyHost != null) {
2106                String JavaDoc tmp = System.getProperty("http.proxyPort");
2107                if ((tmp != null) && tmp.equals("")) {
2108                    tmp = null;
2109                }
2110                if (tmp == null) {
2111                    l.HTTPProxyPort = 80;
2112                } else {
2113                    l.HTTPProxyPort = Integer.parseInt(tmp);
2114                }
2115            }
2116        }
2117        if (!embedded) {
2118            this.setDefaultCloseOperation(EXIT_ON_CLOSE);
2119        }
2120        this.pack();
2121        this.setSize(600, 600);
2122        this.setVisible(true);
2123    }
2124
2125    /**
2126     * Constructor tcpmon
2127     *
2128     * @param listenPort
2129     * @param targetHost
2130     * @param targetPort
2131     */

2132    public tcpmon(int listenPort, String JavaDoc targetHost, int targetPort) {
2133        this(listenPort, targetHost, targetPort, false);
2134    }
2135
2136    /**
2137     * set up the L&F
2138     *
2139     * @param nativeLookAndFeel
2140     * @throws Exception
2141     */

2142    private static void setupLookAndFeel(boolean nativeLookAndFeel)
2143            throws Exception JavaDoc {
2144        String JavaDoc classname = UIManager.getCrossPlatformLookAndFeelClassName();
2145        if (nativeLookAndFeel) {
2146            classname = UIManager.getSystemLookAndFeelClassName();
2147        }
2148        String JavaDoc lafProperty = System.getProperty("tcpmon.laf", "");
2149        if (lafProperty.length() > 0) {
2150            classname = lafProperty;
2151        }
2152        try {
2153            UIManager.setLookAndFeel(classname);
2154        } catch (ClassNotFoundException JavaDoc e) {
2155            e.printStackTrace();
2156        } catch (InstantiationException JavaDoc e) {
2157            e.printStackTrace();
2158        } catch (IllegalAccessException JavaDoc e) {
2159            e.printStackTrace();
2160        } catch (UnsupportedLookAndFeelException e) {
2161            e.printStackTrace();
2162        }
2163    }
2164
2165    /**
2166     * this is our main method
2167     *
2168     * @param args
2169     */

2170    public static void main(String JavaDoc[] args) {
2171        try {
2172
2173            // switch between swing L&F here
2174
setupLookAndFeel(true);
2175            if (args.length == 3) {
2176                int p1 = Integer.parseInt(args[0]);
2177                int p2 = Integer.parseInt(args[2]);
2178                new tcpmon(p1, args[1], p2);
2179            } else if (args.length == 1) {
2180                int p1 = Integer.parseInt(args[0]);
2181                new tcpmon(p1, null, 0);
2182            } else if (args.length != 0) {
2183                System.err.println(
2184                        getMessage("usage00", "Usage:")
2185                                + " tcpmon [listenPort targetHost targetPort]\n");
2186            } else {
2187                new tcpmon(0, null, 0);
2188            }
2189        } catch (Throwable JavaDoc exp) {
2190            exp.printStackTrace();
2191        }
2192    }
2193
2194    /**
2195     * Field messages
2196     */

2197    private static ResourceBundle JavaDoc messages = null;
2198
2199    /**
2200     * Get the message with the given key. There are no arguments for this message.
2201     *
2202     * @param key
2203     * @param defaultMsg
2204     * @return
2205     */

2206    public static String JavaDoc getMessage(String JavaDoc key, String JavaDoc defaultMsg) {
2207        try {
2208            if (messages == null) {
2209                initializeMessages();
2210            }
2211            return messages.getString(key);
2212        } catch (Throwable JavaDoc t) {
2213
2214            // If there is any problem whatsoever getting the internationalized
2215
// message, return the default.
2216
return defaultMsg;
2217        }
2218    }
2219
2220    /**
2221     * Load the resource bundle messages from the properties file. This is ONLY done when it is
2222     * needed. If no messages are printed (for example, only Wsdl2java is being run in non-
2223     * verbose mode) then there is no need to read the properties file.
2224     */

2225    private static void initializeMessages() {
2226        messages = ResourceBundle.getBundle("org.apache.axis2.utils.tcpmon");
2227    }
2228
2229    /**
2230     * a text field with a restricted set of characters
2231     */

2232    static class RestrictedTextField extends JTextField {
2233        /**
2234         * Field validText
2235         */

2236        protected String JavaDoc validText;
2237
2238        /**
2239         * Constructor RestrictedTextField
2240         *
2241         * @param validText
2242         */

2243        public RestrictedTextField(String JavaDoc validText) {
2244            setValidText(validText);
2245        }
2246
2247        /**
2248         * Constructor RestrictedTextField
2249         *
2250         * @param columns
2251         * @param validText
2252         */

2253        public RestrictedTextField(int columns, String JavaDoc validText) {
2254            super(columns);
2255            setValidText(validText);
2256        }
2257
2258        /**
2259         * Constructor RestrictedTextField
2260         *
2261         * @param text
2262         * @param validText
2263         */

2264        public RestrictedTextField(String JavaDoc text, String JavaDoc validText) {
2265            super(text);
2266            setValidText(validText);
2267        }
2268
2269        /**
2270         * Constructor RestrictedTextField
2271         *
2272         * @param text
2273         * @param columns
2274         * @param validText
2275         */

2276        public RestrictedTextField(String JavaDoc text, int columns, String JavaDoc validText) {
2277            super(text, columns);
2278            setValidText(validText);
2279        }
2280
2281        /**
2282         * Method setValidText
2283         *
2284         * @param validText
2285         */

2286        private void setValidText(String JavaDoc validText) {
2287            this.validText = validText;
2288        }
2289
2290        /**
2291         * fascinatingly, this method is called in the super() constructor,
2292         * meaning before we are fully initialized. C++ doesnt actually permit
2293         * such a situation, but java clearly does...
2294         *
2295         * @return a new document
2296         */

2297        public Document JavaDoc createDefaultModel() {
2298            return new RestrictedDocument();
2299        }
2300
2301        /**
2302         * this class strips out invaid chars
2303         */

2304        class RestrictedDocument extends PlainDocument JavaDoc {
2305            /**
2306             * Constructs a plain text document. A default model using
2307             * <code>GapContent</code> is constructed and set.
2308             */

2309            public RestrictedDocument() {
2310            }
2311
2312            /**
2313             * add a string; only those chars in the valid text list are allowed
2314             *
2315             * @param offset
2316             * @param string
2317             * @param attributes
2318             * @throws BadLocationException
2319             */

2320            public void insertString(
2321                    int offset, String JavaDoc string, AttributeSet JavaDoc attributes)
2322                    throws BadLocationException JavaDoc {
2323                if (string == null) {
2324                    return;
2325                }
2326                int len = string.length();
2327                StringBuffer JavaDoc buffer = new StringBuffer JavaDoc(string.length());
2328                for (int i = 0; i < len; i++) {
2329                    char ch = string.charAt(i);
2330                    if (validText.indexOf(ch) >= 0) {
2331                        buffer.append(ch);
2332                    }
2333                }
2334                super.insertString(offset, new String JavaDoc(buffer), attributes);
2335            }
2336        } // end class NumericDocument
2337
}
2338
2339    /**
2340     * because we cant use Java1.4's JFormattedTextField, here is
2341     * a class that accepts numbers only
2342     */

2343    static class NumberField extends RestrictedTextField {
2344        /**
2345         * Field VALID_TEXT
2346         */

2347        private static final String JavaDoc VALID_TEXT = "0123456789";
2348
2349        /**
2350         * Constructs a new <code>TextField</code>. A default model is created,
2351         * the initial string is <code>null</code>,
2352         * and the number of columns is set to 0.
2353         */

2354        public NumberField() {
2355            super(VALID_TEXT);
2356        }
2357
2358        /**
2359         * Constructs a new empty <code>TextField</code> with the specified
2360         * number of columns.
2361         * A default model is created and the initial string is set to
2362         * <code>null</code>.
2363         *
2364         * @param columns the number of columns to use to calculate
2365         * the preferred width; if columns is set to zero, the
2366         * preferred width will be whatever naturally results from
2367         * the component implementation
2368         */

2369        public NumberField(int columns) {
2370            super(columns, VALID_TEXT);
2371        }
2372
2373        /**
2374         * get the int value of a field, any invalid (non int) field returns
2375         * the default
2376         *
2377         * @param def default value
2378         * @return the field contents
2379         */

2380        public int getValue(int def) {
2381            int result = def;
2382            String JavaDoc text = getText();
2383            if ((text != null) && (text.length() != 0)) {
2384                try {
2385                    result = Integer.parseInt(text);
2386                } catch (NumberFormatException JavaDoc e) {
2387                }
2388            }
2389            return result;
2390        }
2391
2392        /**
2393         * set the text to a numeric value
2394         *
2395         * @param value number to assign
2396         */

2397        public void setValue(int value) {
2398            setText(Integer.toString(value));
2399        }
2400    } // end class NumericTextField
2401

2402    /**
2403     * hostname fields
2404     */

2405    static class HostnameField extends RestrictedTextField {
2406
2407        // list of valid chars in a hostname
2408

2409        /**
2410         * Field VALID_TEXT
2411         */

2412        private static final String JavaDoc VALID_TEXT =
2413                "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWZYZ-.";
2414
2415        /**
2416         * Constructor HostnameField
2417         *
2418         * @param columns
2419         */

2420        public HostnameField(int columns) {
2421            super(columns, VALID_TEXT);
2422        }
2423
2424        /**
2425         * Constructor HostnameField
2426         */

2427        public HostnameField() {
2428            super(VALID_TEXT);
2429        }
2430    }
2431}
2432
Popular Tags