KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > axis > utils > tcpmon


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  *
5  * Copyright (c) 2001-2003 The Apache Software Foundation. All rights
6  * reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  * notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  * notice, this list of conditions and the following disclaimer in
17  * the documentation and/or other materials provided with the
18  * distribution.
19  *
20  * 3. The end-user documentation included with the redistribution,
21  * if any, must include the following acknowledgment:
22  * "This product includes software developed by the
23  * Apache Software Foundation (http://www.apache.org/)."
24  * Alternately, this acknowledgment may appear in the software itself,
25  * if and wherever such third-party acknowledgments normally appear.
26  *
27  * 4. The names "Axis" and "Apache Software Foundation" must
28  * not be used to endorse or promote products derived from this
29  * software without prior written permission. For written
30  * permission, please contact apache@apache.org.
31  *
32  * 5. Products derived from this software may not be called "Apache",
33  * nor may "Apache" appear in their name, without prior written
34  * permission of the Apache Software Foundation.
35  *
36  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
37  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
38  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
39  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
40  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
42  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
43  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
44  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
45  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
46  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47  * SUCH DAMAGE.
48  * ====================================================================
49  *
50  * This software consists of voluntary contributions made by many
51  * individuals on behalf of the Apache Software Foundation. For more
52  * information on the Apache Software Foundation, please see
53  * <http://www.apache.org/>.
54  */

55 package org.jboss.axis.utils;
56
57
58 import javax.swing.*;
59 import javax.swing.border.TitledBorder JavaDoc;
60 import javax.swing.event.ChangeEvent JavaDoc;
61 import javax.swing.event.ListSelectionEvent JavaDoc;
62 import javax.swing.event.ListSelectionListener JavaDoc;
63 import javax.swing.plaf.basic.BasicButtonListener JavaDoc;
64 import javax.swing.table.DefaultTableModel JavaDoc;
65 import javax.swing.table.TableColumn JavaDoc;
66 import javax.swing.table.TableModel JavaDoc;
67 import javax.swing.text.AttributeSet JavaDoc;
68 import javax.swing.text.BadLocationException JavaDoc;
69 import javax.swing.text.Document JavaDoc;
70 import javax.swing.text.PlainDocument JavaDoc;
71 import java.awt.*;
72 import java.awt.event.ActionEvent JavaDoc;
73 import java.awt.event.ActionListener JavaDoc;
74 import java.awt.event.WindowEvent JavaDoc;
75 import java.io.ByteArrayInputStream JavaDoc;
76 import java.io.File JavaDoc;
77 import java.io.FileOutputStream JavaDoc;
78 import java.io.InputStream JavaDoc;
79 import java.io.OutputStream JavaDoc;
80 import java.io.PrintWriter JavaDoc;
81 import java.io.StringWriter JavaDoc;
82 import java.net.ServerSocket JavaDoc;
83 import java.net.Socket JavaDoc;
84 import java.net.URL JavaDoc;
85 import java.text.DateFormat JavaDoc;
86 import java.text.SimpleDateFormat JavaDoc;
87 import java.util.Date JavaDoc;
88 import java.util.Iterator JavaDoc;
89 import java.util.ResourceBundle JavaDoc;
90 import java.util.Vector JavaDoc;
91
92
93 /**
94  * TCP monitor to log http messages and responses, both SOAP and plain HTTP.
95  *
96  * @author Doug Davis (dug@us.ibm.com)
97  * @author Steve Loughran
98  */

99
100 public class tcpmon extends JFrame
101 {
102    private JTabbedPane notebook = null;
103
104    private static final int STATE_COLUMN = 0;
105    private static final int TIME_COLUMN = 1;
106    private static final int INHOST_COLUMN = 2;
107    private static final int OUTHOST_COLUMN = 3;
108    private static final int REQ_COLUMN = 4;
109
110
111    private static final String JavaDoc DEFAULT_HOST = "127.0.0.1";
112    private static final int DEFAULT_PORT = 8080;
113
114    /**
115     * this is the admin page
116     */

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

453                }
454             }
455          });
456
457          notebook.addTab(name, this);
458          notebook.repaint();
459          notebook.setSelectedIndex(notebook.getTabCount() - 1);
460       }
461
462
463    }
464
465    /**
466     * wait for incoming connections, spawn a connection thread when
467     * stuff comes in.
468     */

469    class SocketWaiter extends Thread JavaDoc
470    {
471       ServerSocket JavaDoc sSocket = null;
472       Listener JavaDoc listener;
473       int port;
474       boolean pleaseStop = false;
475
476       public SocketWaiter(Listener JavaDoc l, int p)
477       {
478          listener = l;
479          port = p;
480          start();
481       }
482
483       public void run()
484       {
485          try
486          {
487             listener.setLeft(new JLabel(getMessage("wait00", " Waiting for Connection...")));
488             listener.repaint();
489             sSocket = new ServerSocket JavaDoc(port);
490             for (; ;)
491             {
492                Socket JavaDoc inSocket = sSocket.accept();
493
494                if (pleaseStop)
495                {
496                   break;
497                }
498                new Connection(listener, inSocket);
499                inSocket = null;
500             }
501          }
502          catch (Exception JavaDoc exp)
503          {
504             if (!"socket closed".equals(exp.getMessage()))
505             {
506                JLabel tmp = new JLabel(exp.toString());
507
508                tmp.setForeground(Color.red);
509                listener.setLeft(tmp);
510                listener.setRight(new JLabel(""));
511                listener.stop();
512             }
513          }
514       }
515
516       /**
517        * force a halt by connecting to self and then closing the server socket
518        */

519       public void halt()
520       {
521          try
522          {
523             pleaseStop = true;
524             new Socket JavaDoc("127.0.0.1", port);
525             if (sSocket != null)
526             {
527                sSocket.close();
528             }
529          }
530          catch (Exception JavaDoc e)
531          {
532             e.printStackTrace();
533          }
534       }
535    }
536
537
538    /**
539     * class to simulate slow connections by slowing down the system
540     */

541    static class SlowLinkSimulator
542    {
543       private int delayBytes;
544       private int delayTime;
545       private int currentBytes;
546       private int totalBytes;
547
548       /**
549        * construct
550        *
551        * @param delayBytes bytes per delay; set to 0 for no delay
552        * @param delayTime delay time per delay in milliseconds
553        */

554       public SlowLinkSimulator(int delayBytes, int delayTime)
555       {
556          this.delayBytes = delayBytes;
557          this.delayTime = delayTime;
558       }
559
560       /**
561        * construct by copying delay bytes and time, but not current
562        * count of bytes
563        *
564        * @param that source of data
565        */

566       public SlowLinkSimulator(SlowLinkSimulator that)
567       {
568          this.delayBytes = that.delayBytes;
569          this.delayTime = that.delayTime;
570       }
571
572       /**
573        * how many bytes have gone past?
574        *
575        * @return
576        */

577       public int getTotalBytes()
578       {
579          return totalBytes;
580       }
581
582       /**
583        * log #of bytes pumped. Will pause when necessary. This method is not
584        * synchronized
585        *
586        * @param bytes
587        */

588       public void pump(int bytes)
589       {
590          totalBytes += bytes;
591          if (delayBytes == 0)
592          {
593             //when not delaying, we are just a byte counter
594
return;
595          }
596          currentBytes += bytes;
597          if (currentBytes > delayBytes)
598          {
599             //we have overshot. lets find out how far
600
int delaysize = currentBytes / delayBytes;
601             long delay = delaysize * (long)delayTime;
602             //move byte counter down to the remainder of bytes
603
currentBytes = currentBytes % delayBytes;
604             //now wait
605
try
606             {
607                Thread.sleep(delay);
608             }
609             catch (InterruptedException JavaDoc e)
610             {
611                ; //ignore the exception
612
}
613          }
614       }
615
616       /**
617        * get the current byte count
618        *
619        * @return
620        */

621       public int getCurrentBytes()
622       {
623          return currentBytes;
624       }
625
626       /**
627        * set the current byte count
628        *
629        * @param currentBytes
630        */

631       public void setCurrentBytes(int currentBytes)
632       {
633          this.currentBytes = currentBytes;
634       }
635
636    }
637
638    /**
639     * this class handles the pumping of data from the incoming socket to the
640     * outgoing socket
641     */

642    class SocketRR extends Thread JavaDoc
643    {
644       Socket JavaDoc inSocket = null;
645       Socket JavaDoc outSocket = null;
646       JTextArea textArea;
647       InputStream JavaDoc in = null;
648       OutputStream JavaDoc out = null;
649       boolean xmlFormat;
650       volatile boolean done = false;
651       TableModel JavaDoc tmodel = null;
652       int tableIndex = 0;
653       String JavaDoc type = null;
654       Connection myConnection = null;
655       SlowLinkSimulator slowLink;
656
657       public SocketRR(Connection c, Socket JavaDoc inputSocket, InputStream JavaDoc inputStream,
658                       Socket JavaDoc outputSocket, OutputStream JavaDoc outputStream,
659                       JTextArea _textArea, boolean format,
660                       TableModel JavaDoc tModel, int index, final String JavaDoc type, SlowLinkSimulator slowLink)
661       {
662          inSocket = inputSocket;
663          in = inputStream;
664          outSocket = outputSocket;
665          out = outputStream;
666          textArea = _textArea;
667          xmlFormat = format;
668          tmodel = tModel;
669          tableIndex = index;
670          this.type = type;
671          myConnection = c;
672          this.slowLink = slowLink;
673          start();
674       }
675
676       public boolean isDone()
677       {
678          return (done);
679       }
680
681       public void run()
682       {
683          try
684          {
685             byte[] buffer = new byte[4096];
686             byte[] tmpbuffer = new byte[8192];
687             int saved = 0;
688             int len;
689             int i1, i2;
690             int i;
691             int reqSaved = 0;
692             int tabWidth = 3;
693             boolean atMargin = true;
694             int thisIndent = -1,
695                     nextIndent = -1,
696                     previousIndent = -1;
697
698             //if ( inSocket != null ) inSocket.setSoTimeout( 10 );
699
//if ( outSocket != null ) outSocket.setSoTimeout( 10 );
700

701             if (tmodel != null)
702             {
703                String JavaDoc tmpStr = (String JavaDoc)tmodel.getValueAt(tableIndex,
704                        REQ_COLUMN);
705
706                if (!"".equals(tmpStr))
707                {
708                   reqSaved = tmpStr.length();
709                }
710             }
711
712             a:
713                 for (; ;)
714                 {
715                    if (done)
716                    {
717                       break;
718                    }
719                    //try{
720
//len = in.available();
721
//}catch(Exception e){len=0;}
722
len = buffer.length;
723                    // Used to be 1, but if we block it doesn't matter
724
// however 1 will break with some servers, including apache
725
if (len == 0)
726                    {
727                       len = buffer.length;
728                    }
729                    if (saved + len > buffer.length)
730                    {
731                       len = buffer.length - saved;
732                    }
733                    int len1 = 0;
734
735                    while (len1 == 0)
736                    {
737                       try
738                       {
739                          len1 = in.read(buffer, saved, len);
740                       }
741                       catch (Exception JavaDoc ex)
742                       {
743                          if (done && saved == 0)
744                          {
745                             break a;
746                          }
747                          len1 = -1;
748                          break;
749                       }
750                    }
751                    len = len1;
752
753                    if (len == -1 && saved == 0)
754                    {
755                       break;
756                    }
757                    if (len == -1)
758                    {
759                       done = true;
760                    }
761
762                    // No matter how we may (or may not) format it, send it
763
// on unformatted - we don't want to mess with how its
764
// sent to the other side, just how its displayed
765
if (out != null && len > 0)
766                    {
767                       slowLink.pump(len);
768                       out.write(buffer, saved, len);
769                    }
770
771                    if (tmodel != null && reqSaved < 50)
772                    {
773                       String JavaDoc old = (String JavaDoc)tmodel.getValueAt(tableIndex,
774                               REQ_COLUMN);
775
776                       old = old + new String JavaDoc(buffer, saved, len);
777                       if (old.length() > 50)
778                       {
779                          old = old.substring(0, 50);
780                       }
781
782                       reqSaved = old.length();
783
784                       if ((i = old.indexOf('\n')) > 0)
785                       {
786                          old = old.substring(0, i - 1);
787                          reqSaved = 50;
788                       }
789
790                       tmodel.setValueAt(old, tableIndex, REQ_COLUMN);
791                    }
792
793                    if (xmlFormat)
794                    {
795                       // Do XML Formatting
796
boolean inXML = false;
797                       int bufferLen = saved;
798
799                       if (len != -1)
800                       {
801                          bufferLen += len;
802                       }
803                       i1 = 0;
804                       i2 = 0;
805                       saved = 0;
806                       for (; i1 < bufferLen; i1++)
807                       {
808                          // Except when we're at EOF, saved last char
809
if (len != -1 && i1 + 1 == bufferLen)
810                          {
811                             saved = 1;
812                             break;
813                          }
814                          thisIndent = -1;
815                          if (buffer[i1] == '<' && buffer[i1 + 1] != '/')
816                          {
817                             previousIndent = nextIndent++;
818                             thisIndent = nextIndent;
819                             inXML = true;
820                          }
821                          if (buffer[i1] == '<' && buffer[i1 + 1] == '/')
822                          {
823                             if (previousIndent > nextIndent)
824                             {
825                                thisIndent = nextIndent;
826                             }
827                             previousIndent = nextIndent--;
828                             inXML = true;
829                          }
830                          if (buffer[i1] == '/' && buffer[i1 + 1] == '>')
831                          {
832                             previousIndent = nextIndent--;
833                             inXML = true;
834                          }
835                          if (thisIndent != -1)
836                          {
837                             if (thisIndent > 0)
838                             {
839                                tmpbuffer[i2++] = (byte)'\n';
840                             }
841                             for (i = tabWidth * thisIndent; i > 0; i--)
842                             {
843                                tmpbuffer[i2++] = (byte)' ';
844                             }
845                          }
846                          atMargin = (buffer[i1] == '\n' || buffer[i1] == '\r');
847
848                          if (!inXML || !atMargin)
849                          {
850                             tmpbuffer[i2++] = buffer[i1];
851                          }
852                       }
853
854                       textArea.append(new String JavaDoc(tmpbuffer, 0, i2));
855
856                       // Shift saved bytes to the beginning
857
for (i = 0; i < saved; i++)
858                       {
859                          buffer[i] = buffer[bufferLen - saved + i];
860                       }
861                    }
862                    else
863                    {
864                       textArea.append(new String JavaDoc(buffer, 0, len));
865                    }
866                    // this.sleep(3); // Let other threads have a chance to run
867
}
868             // this.sleep(3); // Let other threads have a chance to run
869
// halt();
870
// Only set the 'done' flag if we were reading from a
871
// Socket - if we were reading from an input stream then
872
// we'll let the other side control when we're done
873
// if ( inSocket != null ) done = true ;
874
}
875          catch (Exception JavaDoc e)
876          {
877             e.printStackTrace();
878          }
879          finally
880          {
881             done = true;
882             try
883             {
884                if (out != null)
885                {
886                   out.flush();
887                   if (null != outSocket)
888                   {
889                      outSocket.shutdownOutput();
890                   }
891                   else
892                   {
893                      out.close();
894                   }
895                   out = null;
896                }
897             }
898             catch (Exception JavaDoc e)
899             {
900                ;
901             }
902             try
903             {
904                if (in != null)
905                {
906                   if (inSocket != null)
907                   {
908                      inSocket.shutdownInput();
909                   }
910                   else
911                   {
912                      in.close();
913                   }
914                   in = null;
915                }
916             }
917             catch (Exception JavaDoc e)
918             {
919                ;
920             }
921             myConnection.wakeUp();
922          }
923       }
924
925       public void halt()
926       {
927          try
928          {
929             if (inSocket != null)
930             {
931                inSocket.close();
932             }
933             if (outSocket != null)
934             {
935                outSocket.close();
936             }
937             inSocket = null;
938             outSocket = null;
939             if (in != null)
940             {
941                in.close();
942             }
943             if (out != null)
944             {
945                out.close();
946             }
947             in = null;
948             out = null;
949             done = true;
950          }
951          catch (Exception JavaDoc e)
952          {
953             e.printStackTrace();
954          }
955       }
956    }
957
958
959    /**
960     * a connection listens to a single current connection
961     */

962    class Connection extends Thread JavaDoc
963    {
964       Listener JavaDoc listener;
965       boolean active;
966       String JavaDoc fromHost;
967       String JavaDoc time;
968       JTextArea inputText = null;
969       JScrollPane inputScroll = null;
970       JTextArea outputText = null;
971       JScrollPane outputScroll = null;
972       Socket JavaDoc inSocket = null;
973       Socket JavaDoc outSocket = null;
974       Thread JavaDoc clientThread = null;
975       Thread JavaDoc serverThread = null;
976       SocketRR rr1 = null;
977       SocketRR rr2 = null;
978       InputStream JavaDoc inputStream = null;
979
980       String JavaDoc HTTPProxyHost = null;
981       int HTTPProxyPort = 80;
982       private SlowLinkSimulator slowLink;
983
984       public Connection(Listener JavaDoc l)
985       {
986          listener = l;
987          HTTPProxyHost = l.HTTPProxyHost;
988          HTTPProxyPort = l.HTTPProxyPort;
989          slowLink = l.slowLink;
990       }
991
992       public Connection(Listener JavaDoc l, Socket JavaDoc s)
993       {
994          this(l);
995          inSocket = s;
996          start();
997       }
998
999       public Connection(Listener JavaDoc l, InputStream JavaDoc in)
1000      {
1001         this(l);
1002         inputStream = in;
1003         start();
1004      }
1005
1006      public void run()
1007      {
1008         try
1009         {
1010            active = true;
1011
1012            HTTPProxyHost = System.getProperty("http.proxyHost");
1013            if (HTTPProxyHost != null && HTTPProxyHost.equals(""))
1014            {
1015               HTTPProxyHost = null;
1016            }
1017
1018            if (HTTPProxyHost != null)
1019            {
1020               String JavaDoc tmp = System.getProperty("http.proxyPort");
1021
1022               if (tmp != null && tmp.equals(""))
1023               {
1024                  tmp = null;
1025               }
1026               if (tmp == null)
1027               {
1028                  HTTPProxyPort = 80;
1029               }
1030               else
1031               {
1032                  HTTPProxyPort = Integer.parseInt(tmp);
1033               }
1034            }
1035
1036            if (inSocket != null)
1037            {
1038               fromHost = (inSocket.getInetAddress()).getHostName();
1039            }
1040            else
1041            {
1042               fromHost = "resend";
1043            }
1044
1045
1046            String JavaDoc dateformat = getMessage("dateformat00", "yyyy-MM-dd HH:mm:ss");
1047            DateFormat JavaDoc df = new SimpleDateFormat JavaDoc(dateformat);
1048
1049            time = df.format(new Date JavaDoc());
1050
1051            int count = listener.connections.size();
1052
1053            listener.tableModel.insertRow(count + 1, new Object JavaDoc[]{
1054               getMessage("active00", "Active"),
1055               time,
1056               fromHost,
1057               listener.hostField.getText(), ""
1058            });
1059            listener.connections.add(this);
1060            inputText = new JTextArea(null, null, 20, 80);
1061            inputScroll = new JScrollPane(inputText);
1062            outputText = new JTextArea(null, null, 20, 80);
1063            outputScroll = new JScrollPane(outputText);
1064
1065            ListSelectionModel lsm = listener.connectionTable.getSelectionModel();
1066
1067            if (count == 0 || lsm.getLeadSelectionIndex() == 0)
1068            {
1069               listener.outPane.setVisible(false);
1070               int divLoc = listener.outPane.getDividerLocation();
1071
1072               listener.setLeft(inputScroll);
1073               listener.setRight(outputScroll);
1074
1075               listener.removeButton.setEnabled(false);
1076               listener.removeAllButton.setEnabled(true);
1077               listener.saveButton.setEnabled(true);
1078               listener.resendButton.setEnabled(true);
1079               listener.outPane.setDividerLocation(divLoc);
1080               listener.outPane.setVisible(true);
1081            }
1082
1083            String JavaDoc targetHost = listener.hostField.getText();
1084            int targetPort = Integer.parseInt(listener.tPortField.getText());
1085
1086            InputStream JavaDoc tmpIn1 = inputStream;
1087            OutputStream JavaDoc tmpOut1 = null;
1088
1089            InputStream JavaDoc tmpIn2 = null;
1090            OutputStream JavaDoc tmpOut2 = null;
1091
1092            if (tmpIn1 == null)
1093            {
1094               tmpIn1 = inSocket.getInputStream();
1095            }
1096
1097            if (inSocket != null)
1098            {
1099               tmpOut1 = inSocket.getOutputStream();
1100            }
1101
1102            String JavaDoc bufferedData = null;
1103            StringBuffer JavaDoc buf = null;
1104
1105            int index = listener.connections.indexOf(this);
1106
1107            if (listener.isProxyBox.isSelected() || HTTPProxyHost != null)
1108            {
1109               // Check if we're a proxy
1110
byte[] b = new byte[1];
1111
1112               buf = new StringBuffer JavaDoc();
1113               String JavaDoc s;
1114
1115               for (; ;)
1116               {
1117                  int len;
1118
1119                  len = tmpIn1.read(b, 0, 1);
1120                  if (len == -1)
1121                  {
1122                     break;
1123                  }
1124                  s = new String JavaDoc(b);
1125                  buf.append(s);
1126                  if (b[0] != '\n')
1127                  {
1128                     continue;
1129                  }
1130                  break;
1131               }
1132
1133               bufferedData = buf.toString();
1134               inputText.append(bufferedData);
1135
1136               if (bufferedData.startsWith("GET ") ||
1137                       bufferedData.startsWith("POST "))
1138               {
1139                  int start, end;
1140                  URL JavaDoc url;
1141
1142                  start = bufferedData.indexOf(' ') + 1;
1143                  while (bufferedData.charAt(start) == ' ')
1144                  {
1145                     start++;
1146                  }
1147                  end = bufferedData.indexOf(' ', start);
1148                  String JavaDoc urlString = bufferedData.substring(start, end);
1149
1150                  if (urlString.charAt(0) == '/')
1151                  {
1152                     urlString = urlString.substring(1);
1153                  }
1154                  if (listener.isProxyBox.isSelected())
1155                  {
1156                     url = new URL JavaDoc(urlString);
1157                     targetHost = url.getHost();
1158                     targetPort = url.getPort();
1159                     if (targetPort == -1)
1160                     {
1161                        targetPort = 80;
1162                     }
1163
1164                     listener.tableModel.setValueAt(targetHost, index + 1,
1165                             OUTHOST_COLUMN);
1166                     bufferedData = bufferedData.substring(0, start) +
1167                             url.getFile() +
1168                             bufferedData.substring(end);
1169                  }
1170                  else
1171                  {
1172                     url = new URL JavaDoc("http://" + targetHost + ":" +
1173                             targetPort + "/" + urlString);
1174
1175                     listener.tableModel.setValueAt(targetHost, index + 1,
1176                             OUTHOST_COLUMN);
1177                     bufferedData = bufferedData.substring(0, start) +
1178                             url.toExternalForm() +
1179                             bufferedData.substring(end);
1180
1181                     targetHost = HTTPProxyHost;
1182                     targetPort = HTTPProxyPort;
1183                  }
1184
1185               }
1186            }
1187            else
1188            {
1189               //
1190
// Change Host: header to point to correct host
1191
//
1192
byte[] b1 = new byte[1];
1193
1194               buf = new StringBuffer JavaDoc();
1195               String JavaDoc s1;
1196               String JavaDoc lastLine = null;
1197
1198               for (; ;)
1199               {
1200                  int len;
1201
1202                  len = tmpIn1.read(b1, 0, 1);
1203                  if (len == -1)
1204                  {
1205                     break;
1206                  }
1207                  s1 = new String JavaDoc(b1);
1208                  buf.append(s1);
1209                  if (b1[0] != '\n')
1210                  {
1211                     continue;
1212                  }
1213                  // we have a complete line
1214
String JavaDoc line = buf.toString();
1215
1216                  buf.setLength(0);
1217                  // check to see if we have found Host: header
1218
if (line.startsWith("Host: "))
1219                  {
1220                     // we need to update the hostname to target host
1221
String JavaDoc newHost = "Host: " + targetHost + "\r\n";
1222
1223                     bufferedData = bufferedData.concat(newHost);
1224                     break;
1225                  }
1226                  // add it to our headers so far
1227
if (bufferedData == null)
1228                  {
1229                     bufferedData = line;
1230                  }
1231                  else
1232                  {
1233                     bufferedData = bufferedData.concat(line);
1234                  }
1235
1236                  // failsafe
1237
if (line.equals("\r\n"))
1238                  {
1239                     break;
1240                  }
1241                  if ("\n".equals(lastLine) && line.equals("\n"))
1242                  {
1243                     break;
1244                  }
1245                  lastLine = line;
1246               }
1247               if (bufferedData != null)
1248               {
1249                  inputText.append(bufferedData);
1250                  int idx = bufferedData.length() < 50 ? bufferedData.length() : 50;
1251                  s1 = bufferedData.substring(0, idx);
1252                  int i = s1.indexOf('\n');
1253
1254                  if (i > 0)
1255                  {
1256                     s1 = s1.substring(0, i - 1);
1257                  }
1258                  s1 = s1 + " " +
1259                          " ";
1260                  s1 = s1.substring(0, 51);
1261                  listener.tableModel.setValueAt(s1, index + 1,
1262                          REQ_COLUMN);
1263               }
1264            }
1265
1266            if (targetPort == -1)
1267            {
1268               targetPort = 80;
1269            }
1270            outSocket = new Socket JavaDoc(targetHost, targetPort);
1271
1272            tmpIn2 = outSocket.getInputStream();
1273            tmpOut2 = outSocket.getOutputStream();
1274
1275            if (bufferedData != null)
1276            {
1277               byte[] b = bufferedData.getBytes();
1278               tmpOut2.write(b);
1279               slowLink.pump(b.length);
1280            }
1281
1282            boolean format = listener.xmlFormatBox.isSelected();
1283
1284
1285            //this is the channel to the endpoint
1286
rr1 = new SocketRR(this, inSocket, tmpIn1, outSocket,
1287                    tmpOut2, inputText, format,
1288                    listener.tableModel, index + 1, "request:", slowLink);
1289            //create the response slow link from the inbound slow link
1290
SlowLinkSimulator responseLink = new SlowLinkSimulator(slowLink);
1291            //this is the channel from the endpoint
1292
rr2 = new SocketRR(this, outSocket, tmpIn2, inSocket,
1293                    tmpOut1, outputText, format,
1294                    null, 0, "response:", responseLink);
1295
1296            while (rr1 != null || rr2 != null)
1297            {
1298               // Only loop as long as the connection to the target
1299
// machine is available - once that's gone we can stop.
1300
// The old way, loop until both are closed, left us
1301
// looping forever since no one closed the 1st one.
1302
// while( !rr2.isDone() )
1303
if (null != rr1 && rr1.isDone())
1304               {
1305                  if (index >= 0 && rr2 != null)
1306                  {
1307                     listener.tableModel.setValueAt(getMessage("resp00", "Resp"),
1308                             1 + index, STATE_COLUMN);
1309                  }
1310                  rr1 = null;
1311               }
1312               if (null != rr2 && rr2.isDone())
1313               {
1314                  if (index >= 0 && rr1 != null)
1315                  {
1316                     listener.tableModel.setValueAt(getMessage("req00", "Req"),
1317                             1 + index, STATE_COLUMN);
1318                  }
1319                  rr2 = null;
1320               }
1321
1322               // Thread.sleep( 10 );
1323
synchronized (this)
1324               {
1325                  this.wait(1000); //Safety just incase we're not told to wake up.
1326
}
1327            }
1328
1329            // System.out.println("Done ");
1330
// rr1.halt();
1331
// rr2.halt();
1332

1333
1334            active = false;
1335
1336            /*
1337             if ( inSocket != null ) {
1338             inSocket.close();
1339             inSocket = null ;
1340             }
1341             outSocket.close();
1342             outSocket = null ;
1343             */

1344
1345            if (index >= 0)
1346            {
1347               listener.tableModel.setValueAt(getMessage("done00", "Done"),
1348                       1 + index, STATE_COLUMN);
1349
1350            }
1351         }
1352         catch (Exception JavaDoc e)
1353         {
1354            StringWriter JavaDoc st = new StringWriter JavaDoc();
1355            PrintWriter JavaDoc wr = new PrintWriter JavaDoc(st);
1356            int index = listener.connections.indexOf(this);
1357
1358            if (index >= 0)
1359            {
1360               listener.tableModel.setValueAt(getMessage("error00", "Error"), 1 + index, STATE_COLUMN);
1361            }
1362            e.printStackTrace(wr);
1363            wr.close();
1364            if (outputText != null)
1365            {
1366               outputText.append(st.toString());
1367            }
1368            else
1369            {
1370               //something went wrong before we had the output area
1371
System.out.println(st.toString());
1372            }
1373            halt();
1374         }
1375      }
1376
1377      synchronized void wakeUp()
1378      {
1379         this.notifyAll();
1380      }
1381
1382      public void halt()
1383      {
1384         try
1385         {
1386            if (rr1 != null)
1387            {
1388               rr1.halt();
1389            }
1390            if (rr2 != null)
1391            {
1392               rr2.halt();
1393            }
1394            if (inSocket != null)
1395            {
1396               inSocket.close();
1397            }
1398            inSocket = null;
1399            if (outSocket != null)
1400            {
1401               outSocket.close();
1402            }
1403            outSocket = null;
1404         }
1405         catch (Exception JavaDoc e)
1406         {
1407            e.printStackTrace();
1408         }
1409      }
1410
1411      public void remove()
1412      {
1413         int index = -1;
1414
1415         try
1416         {
1417            halt();
1418            index = listener.connections.indexOf(this);
1419            listener.tableModel.removeRow(index + 1);
1420            listener.connections.remove(index);
1421         }
1422         catch (Exception JavaDoc e)
1423         {
1424            System.err.println("index:=" + index + this);
1425            e.printStackTrace();
1426         }
1427      }
1428   }
1429
1430
1431   /**
1432    * this is one of the tabbed panels that acts as the actual proxy
1433    */

1434   class Listener extends JPanel
1435   {
1436      public Socket JavaDoc inputSocket = null;
1437      public Socket JavaDoc outputSocket = null;
1438      public JTextField portField = null;
1439      public JTextField hostField = null;
1440      public JTextField tPortField = null;
1441      public JCheckBox isProxyBox = null;
1442      public JButton stopButton = null;
1443      public JButton removeButton = null;
1444      public JButton removeAllButton = null;
1445      public JCheckBox xmlFormatBox = null;
1446      public JButton saveButton = null;
1447      public JButton resendButton = null;
1448      public JButton switchButton = null;
1449      public JButton closeButton = null;
1450      public JTable connectionTable = null;
1451      public DefaultTableModel JavaDoc tableModel = null;
1452      public JSplitPane outPane = null;
1453      public ServerSocket JavaDoc sSocket = null;
1454      public SocketWaiter sw = null;
1455      public JPanel leftPanel = null;
1456      public JPanel rightPanel = null;
1457      public JTabbedPane notebook = null;
1458      public String JavaDoc HTTPProxyHost = null;
1459      public int HTTPProxyPort = 80;
1460      public int delayBytes = 0;
1461      public int delayTime = 0;
1462      public SlowLinkSimulator slowLink;
1463
1464      public final Vector JavaDoc connections = new Vector JavaDoc();
1465
1466      /**
1467       * create a listener
1468       *
1469       * @param _notebook
1470       * @param name
1471       * @param listenPort
1472       * @param host
1473       * @param targetPort
1474       * @param isProxy
1475       * @param slowLink optional reference to a slow connection
1476       */

1477      public Listener(JTabbedPane _notebook, String JavaDoc name,
1478                      int listenPort, String JavaDoc host, int targetPort,
1479                      boolean isProxy, SlowLinkSimulator slowLink)
1480      {
1481         notebook = _notebook;
1482         if (name == null)
1483         {
1484            name = getMessage("port01", "Port") + " " + listenPort;
1485         }
1486         //set the slow link to the passed down link
1487
if (slowLink != null)
1488         {
1489            this.slowLink = slowLink;
1490         }
1491         else
1492         {
1493            //or make up a no-op one.
1494
this.slowLink = new SlowLinkSimulator(0, 0);
1495         }
1496         this.setLayout(new BorderLayout());
1497
1498         // 1st component is just a row of labels and 1-line entry fields
1499
/////////////////////////////////////////////////////////////////////
1500
JPanel top = new JPanel();
1501
1502         top.setLayout(new BoxLayout(top, BoxLayout.X_AXIS));
1503         top.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
1504         final String JavaDoc start = getMessage("start00", "Start");
1505
1506         top.add(stopButton = new JButton(start));
1507         top.add(Box.createRigidArea(new Dimension(5, 0)));
1508         top.add(new JLabel(" " + getMessage("listenPort01", "Listen Port:") + " ", SwingConstants.RIGHT));
1509         top.add(portField = new JTextField("" + listenPort, 4));
1510         top.add(new JLabel(" " + getMessage("host00", "Host:"), SwingConstants.RIGHT));
1511         top.add(hostField = new JTextField(host, 30));
1512         top.add(new JLabel(" " + getMessage("port02", "Port:") + " ", SwingConstants.RIGHT));
1513         top.add(tPortField = new JTextField("" + targetPort, 4));
1514         top.add(Box.createRigidArea(new Dimension(5, 0)));
1515         top.add(isProxyBox = new JCheckBox(getMessage("proxy00", "Proxy")));
1516
1517         isProxyBox.addChangeListener(new BasicButtonListener JavaDoc(isProxyBox)
1518         {
1519            public void stateChanged(ChangeEvent JavaDoc event)
1520            {
1521               JCheckBox box = (JCheckBox)event.getSource();
1522               boolean state = box.isSelected();
1523
1524               tPortField.setEnabled(!state);
1525               hostField.setEnabled(!state);
1526            }
1527         });
1528
1529         isProxyBox.setSelected(isProxy);
1530
1531         portField.setEditable(false);
1532         portField.setMaximumSize(new Dimension(50, Short.MAX_VALUE));
1533         hostField.setEditable(false);
1534         hostField.setMaximumSize(new Dimension(85, Short.MAX_VALUE));
1535         tPortField.setEditable(false);
1536         tPortField.setMaximumSize(new Dimension(50, Short.MAX_VALUE));
1537
1538         stopButton.addActionListener(new ActionListener JavaDoc()
1539         {
1540            public void actionPerformed(ActionEvent JavaDoc event)
1541            {
1542               if (getMessage("stop00", "Stop").equals(event.getActionCommand()))
1543               {
1544                  stop();
1545               }
1546               if (start.equals(event.getActionCommand()))
1547               {
1548                  start();
1549               }
1550            }
1551         });
1552
1553         this.add(top, BorderLayout.NORTH);
1554
1555         // 2nd component is a split pane with a table on the top
1556
// and the request/response text areas on the bottom
1557
/////////////////////////////////////////////////////////////////////
1558

1559         tableModel = new DefaultTableModel JavaDoc(new String JavaDoc[]{
1560            getMessage("state00", "State"),
1561            getMessage("time00", "Time"),
1562            getMessage("requestHost00", "Request Host"),
1563            getMessage("targetHost", "Target Host"),
1564            getMessage("request00", "Request...")
1565         }, 0);
1566
1567         connectionTable = new JTable(1, 2);
1568         connectionTable.setModel(tableModel);
1569         connectionTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
1570         // Reduce the STATE column and increase the REQ column
1571
TableColumn JavaDoc col;
1572
1573         col = connectionTable.getColumnModel().getColumn(STATE_COLUMN);
1574         col.setMaxWidth(col.getPreferredWidth() / 2);
1575         col = connectionTable.getColumnModel().getColumn(REQ_COLUMN);
1576         col.setPreferredWidth(col.getPreferredWidth() * 2);
1577
1578
1579         ListSelectionModel sel = connectionTable.getSelectionModel();
1580
1581         sel.addListSelectionListener(new ListSelectionListener JavaDoc()
1582         {
1583            public void valueChanged(ListSelectionEvent JavaDoc event)
1584            {
1585               if (event.getValueIsAdjusting())
1586               {
1587                  return;
1588               }
1589               ListSelectionModel m = (ListSelectionModel)event.getSource();
1590               int divLoc = outPane.getDividerLocation();
1591
1592               if (m.isSelectionEmpty())
1593               {
1594                  setLeft(new JLabel(" " + getMessage("wait00", "Waiting for Connection...")));
1595                  setRight(new JLabel(""));
1596                  removeButton.setEnabled(false);
1597                  removeAllButton.setEnabled(false);
1598                  saveButton.setEnabled(false);
1599                  resendButton.setEnabled(false);
1600               }
1601               else
1602               {
1603                  int row = m.getLeadSelectionIndex();
1604
1605                  if (row == 0)
1606                  {
1607                     if (connections.size() == 0)
1608                     {
1609                        setLeft(new JLabel(" " + getMessage("wait00", "Waiting for connection...")));
1610                        setRight(new JLabel(""));
1611                        removeButton.setEnabled(false);
1612                        removeAllButton.setEnabled(false);
1613                        saveButton.setEnabled(false);
1614                        resendButton.setEnabled(false);
1615                     }
1616                     else
1617                     {
1618                        Connection conn = (Connection)connections.lastElement();
1619
1620                        setLeft(conn.inputScroll);
1621                        setRight(conn.outputScroll);
1622                        removeButton.setEnabled(false);
1623                        removeAllButton.setEnabled(true);
1624                        saveButton.setEnabled(true);
1625                        resendButton.setEnabled(true);
1626                     }
1627                  }
1628                  else
1629                  {
1630                     Connection conn = (Connection)connections.get(row - 1);
1631
1632                     setLeft(conn.inputScroll);
1633                     setRight(conn.outputScroll);
1634                     removeButton.setEnabled(true);
1635                     removeAllButton.setEnabled(true);
1636                     saveButton.setEnabled(true);
1637                     resendButton.setEnabled(true);
1638                  }
1639               }
1640               outPane.setDividerLocation(divLoc);
1641            }
1642         });
1643         tableModel.addRow(new Object JavaDoc[]{
1644            "---", getMessage("mostRecent00", "Most Recent"), "---", "---", "---"
1645         });
1646
1647         JPanel tablePane = new JPanel();
1648
1649         tablePane.setLayout(new BorderLayout());
1650
1651         JScrollPane tableScrollPane = new JScrollPane(connectionTable);
1652
1653         tablePane.add(tableScrollPane, BorderLayout.CENTER);
1654         JPanel buttons = new JPanel();
1655
1656         buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS));
1657         buttons.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
1658         final String JavaDoc removeSelected = getMessage("removeSelected00", "Remove Selected");
1659
1660         buttons.add(removeButton = new JButton(removeSelected));
1661         buttons.add(Box.createRigidArea(new Dimension(5, 0)));
1662         final String JavaDoc removeAll = getMessage("removeAll00", "Remove All");
1663
1664         buttons.add(removeAllButton = new JButton(removeAll));
1665         tablePane.add(buttons, BorderLayout.SOUTH);
1666
1667         removeButton.setEnabled(false);
1668         removeButton.addActionListener(new ActionListener JavaDoc()
1669         {
1670            public void actionPerformed(ActionEvent JavaDoc event)
1671            {
1672               if (removeSelected.equals(event.getActionCommand()))
1673               {
1674                  remove();
1675               }
1676            }
1677         });
1678
1679         removeAllButton.setEnabled(false);
1680         removeAllButton.addActionListener(new ActionListener JavaDoc()
1681         {
1682            public void actionPerformed(ActionEvent JavaDoc event)
1683            {
1684               if (removeAll.equals(event.getActionCommand()))
1685               {
1686                  removeAll();
1687               }
1688            }
1689         });
1690
1691         // Add Response Section
1692
/////////////////////////////////////////////////////////////////////
1693
JPanel pane2 = new JPanel();
1694
1695         pane2.setLayout(new BorderLayout());
1696
1697         leftPanel = new JPanel();
1698         leftPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
1699         leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
1700         leftPanel.add(new JLabel(" " + getMessage("request01", "Request")));
1701         leftPanel.add(new JLabel(" " + getMessage("wait01", "Waiting for connection")));
1702
1703         rightPanel = new JPanel();
1704         rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
1705         rightPanel.add(new JLabel(" " + getMessage("response00", "Response")));
1706         rightPanel.add(new JLabel(""));
1707
1708         outPane = new JSplitPane(0, leftPanel, rightPanel);
1709         outPane.setDividerSize(4);
1710         pane2.add(outPane, BorderLayout.CENTER);
1711
1712         JPanel bottomButtons = new JPanel();
1713
1714         bottomButtons.setLayout(new BoxLayout(bottomButtons, BoxLayout.X_AXIS));
1715         bottomButtons.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
1716         bottomButtons.add(xmlFormatBox = new JCheckBox(getMessage("xmlFormat00", "XML Format")));
1717         bottomButtons.add(Box.createRigidArea(new Dimension(5, 0)));
1718         final String JavaDoc save = getMessage("save00", "Save");
1719
1720         bottomButtons.add(saveButton = new JButton(save));
1721         bottomButtons.add(Box.createRigidArea(new Dimension(5, 0)));
1722         final String JavaDoc resend = getMessage("resend00", "Resend");
1723
1724         bottomButtons.add(resendButton = new JButton(resend));
1725         bottomButtons.add(Box.createRigidArea(new Dimension(5, 0)));
1726         final String JavaDoc switchStr = getMessage("switch00", "Switch Layout");
1727
1728         bottomButtons.add(switchButton = new JButton(switchStr));
1729         bottomButtons.add(Box.createHorizontalGlue());
1730         final String JavaDoc close = getMessage("close00", "Close");
1731
1732         bottomButtons.add(closeButton = new JButton(close));
1733         pane2.add(bottomButtons, BorderLayout.SOUTH);
1734
1735         saveButton.setEnabled(false);
1736         saveButton.addActionListener(new ActionListener JavaDoc()
1737         {
1738            public void actionPerformed(ActionEvent JavaDoc event)
1739            {
1740               if (save.equals(event.getActionCommand()))
1741               {
1742                  save();
1743               }
1744            }
1745         });
1746
1747         resendButton.setEnabled(false);
1748         resendButton.addActionListener(new ActionListener JavaDoc()
1749         {
1750            public void actionPerformed(ActionEvent JavaDoc event)
1751            {
1752               if (resend.equals(event.getActionCommand()))
1753               {
1754                  resend();
1755               }
1756            }
1757         });
1758
1759         switchButton.addActionListener(new ActionListener JavaDoc()
1760         {
1761            public void actionPerformed(ActionEvent JavaDoc event)
1762            {
1763               if (switchStr.equals(event.getActionCommand()))
1764               {
1765                  int v = outPane.getOrientation();
1766
1767                  if (v == 0)
1768                  {
1769                     // top/bottom
1770
outPane.setOrientation(1);
1771                  }
1772                  else
1773                  {
1774                     // left/right
1775
outPane.setOrientation(0);
1776                  }
1777                  outPane.setDividerLocation(0.5);
1778               }
1779            }
1780         });
1781
1782         closeButton.addActionListener(new ActionListener JavaDoc()
1783         {
1784            public void actionPerformed(ActionEvent JavaDoc event)
1785            {
1786               if (close.equals(event.getActionCommand()))
1787               {
1788                  close();
1789               }
1790            }
1791         });
1792
1793         JSplitPane pane1 = new JSplitPane(0);
1794
1795         pane1.setDividerSize(4);
1796         pane1.setTopComponent(tablePane);
1797         pane1.setBottomComponent(pane2);
1798         pane1.setDividerLocation(150);
1799         this.add(pane1, BorderLayout.CENTER);
1800
1801         //
1802
////////////////////////////////////////////////////////////////////
1803
sel.setSelectionInterval(0, 0);
1804         outPane.setDividerLocation(150);
1805         notebook.addTab(name, this);
1806         start();
1807      }
1808
1809      public void setLeft(Component left)
1810      {
1811         leftPanel.removeAll();
1812         leftPanel.add(left);
1813      }
1814
1815      public void setRight(Component right)
1816      {
1817         rightPanel.removeAll();
1818         rightPanel.add(right);
1819      }
1820
1821      public void start()
1822      {
1823         int port = Integer.parseInt(portField.getText());
1824
1825         portField.setText("" + port);
1826         int i = notebook.indexOfComponent(this);
1827
1828         notebook.setTitleAt(i, getMessage("port01", "Port") + " " + port);
1829
1830         int tmp = Integer.parseInt(tPortField.getText());
1831
1832         tPortField.setText("" + tmp);
1833
1834         sw = new SocketWaiter(this, port);
1835         stopButton.setText(getMessage("stop00", "Stop"));
1836
1837         portField.setEditable(false);
1838         hostField.setEditable(false);
1839         tPortField.setEditable(false);
1840         isProxyBox.setEnabled(false);
1841      }
1842
1843      public void close()
1844      {
1845         stop();
1846         notebook.remove(this);
1847      }
1848
1849      public void stop()
1850      {
1851         try
1852         {
1853            for (int i = 0; i < connections.size(); i++)
1854            {
1855               Connection conn = (Connection)connections.get(i);
1856
1857               conn.halt();
1858            }
1859            sw.halt();
1860            stopButton.setText(getMessage("start00", "Start"));
1861            portField.setEditable(true);
1862            hostField.setEditable(true);
1863            tPortField.setEditable(true);
1864            isProxyBox.setEnabled(true);
1865         }
1866         catch (Exception JavaDoc e)
1867         {
1868            e.printStackTrace();
1869         }
1870      }
1871
1872      public void remove()
1873      {
1874         ListSelectionModel lsm = connectionTable.getSelectionModel();
1875         int bot = lsm.getMinSelectionIndex();
1876         int top = lsm.getMaxSelectionIndex();
1877
1878         for (int i = top; i >= bot; i--)
1879         {
1880            ((Connection)connections.get(i - 1)).remove();
1881         }
1882         if (bot > connections.size())
1883         {
1884            bot = connections.size();
1885         }
1886         lsm.setSelectionInterval(bot, bot);
1887      }
1888
1889      public void removeAll()
1890      {
1891         ListSelectionModel lsm = connectionTable.getSelectionModel();
1892         lsm.clearSelection();
1893         while (connections.size() > 0)
1894         {
1895            ((Connection)connections.get(0)).remove();
1896         }
1897
1898         lsm.setSelectionInterval(0, 0);
1899      }
1900
1901      public void save()
1902      {
1903         JFileChooser dialog = new JFileChooser(".");
1904         int rc = dialog.showSaveDialog(this);
1905
1906         if (rc == JFileChooser.APPROVE_OPTION)
1907         {
1908            try
1909            {
1910               File JavaDoc file = dialog.getSelectedFile();
1911               FileOutputStream JavaDoc out = new FileOutputStream JavaDoc(file);
1912
1913               ListSelectionModel lsm = connectionTable.getSelectionModel();
1914
1915               rc = lsm.getLeadSelectionIndex();
1916
1917               int n = 0;
1918               for (Iterator JavaDoc i = connections.iterator(); i.hasNext(); n++)
1919               {
1920                  Connection conn = (Connection)i.next();
1921                  if (lsm.isSelectedIndex(n + 1) ||
1922                          (!(i.hasNext()) && lsm.getLeadSelectionIndex() == 0))
1923                  {
1924                     rc = Integer.parseInt(portField.getText());
1925                     out.write("\n==============\n".getBytes());
1926                     out.write((new String JavaDoc(getMessage("listenPort01", "Listen Port:") + " " + rc + "\n")).getBytes());
1927                     out.write((new String JavaDoc(getMessage("targetHost01", "Target Host:") + " " + hostField.getText() +
1928                             "\n")).getBytes());
1929                     rc = Integer.parseInt(tPortField.getText());
1930                     out.write((new String JavaDoc(getMessage("targetPort01", "Target Port:") + " " + rc + "\n")).getBytes());
1931
1932                     out.write((new String JavaDoc("==== " + getMessage("request01", "Request") + " ====\n")).getBytes());
1933                     out.write(conn.inputText.getText().getBytes());
1934
1935                     out.write((new String JavaDoc("==== " + getMessage("response00", "Response") + " ====\n")).getBytes());
1936                     out.write(conn.outputText.getText().getBytes());
1937                     out.write("\n==============\n".getBytes());
1938                  }
1939               }
1940
1941               out.close();
1942            }
1943            catch (Exception JavaDoc e)
1944            {
1945               e.printStackTrace();
1946            }
1947         }
1948      }
1949
1950      public void resend()
1951      {
1952         int rc;
1953
1954         try
1955         {
1956            ListSelectionModel lsm = connectionTable.getSelectionModel();
1957
1958            rc = lsm.getLeadSelectionIndex();
1959            if (rc == 0)
1960            {
1961               rc = connections.size();
1962            }
1963            Connection conn = (Connection)connections.get(rc - 1);
1964
1965            if (rc > 0)
1966            {
1967               lsm.clearSelection();
1968               lsm.setSelectionInterval(0, 0);
1969            }
1970
1971            InputStream JavaDoc in = null;
1972            String JavaDoc text = conn.inputText.getText();
1973
1974            // Fix Content-Length HTTP headers
1975
if (text.startsWith("POST ") || text.startsWith("GET "))
1976            {
1977               System.err.println("IN CL");
1978               int pos1, pos2, pos3;
1979               String JavaDoc body, headers, headers1, header2;
1980
1981               pos3 = text.indexOf("\n\n");
1982               if (pos3 == -1)
1983               {
1984                  pos3 = text.indexOf("\r\n\r\n");
1985                  if (pos3 != -1)
1986                  {
1987                     pos3 = pos3 + 4;
1988                  }
1989               }
1990               else
1991               {
1992                  pos3 += 2;
1993               }
1994
1995               headers = text.substring(0, pos3);
1996
1997               pos1 = headers.indexOf("Content-Length:");
1998               System.err.println("pos1: " + pos1);
1999               System.err.println("pos3: " + pos3);
2000               if (pos1 != -1)
2001               {
2002                  int newLen = text.length() - pos3;
2003
2004                  pos2 = headers.indexOf("\n", pos1);
2005
2006                  System.err.println("CL: " + newLen);
2007                  System.err.println("Hdrs: '" + headers + "'");
2008                  System.err.println("subTEXT: '" +
2009                          text.substring(pos3, pos3 + newLen) + "'");
2010                  text = headers.substring(0, pos1) +
2011                          "Content-Length: " + newLen + "\n" +
2012                          headers.substring(pos2 + 1) +
2013                          text.substring(pos3);
2014                  System.err.println("\nTEXT: '" + text + "'");
2015               }
2016            }
2017
2018            in = new ByteArrayInputStream JavaDoc(text.getBytes());
2019            new Connection(this, in);
2020         }
2021         catch (Exception JavaDoc e)
2022         {
2023            e.printStackTrace();
2024         }
2025      }
2026   }
2027
2028
2029   public tcpmon(int listenPort, String JavaDoc targetHost, int targetPort)
2030   {
2031      super(getMessage("tcpmon00", "TCPMonitor"));
2032
2033      notebook = new JTabbedPane();
2034      this.getContentPane().add(notebook);
2035
2036      new AdminPage(notebook, getMessage("admin00", "Admin"));
2037
2038      if (listenPort != 0)
2039      {
2040         Listener JavaDoc l = null;
2041
2042         if (targetHost == null)
2043         {
2044            l = new Listener JavaDoc(notebook, null, listenPort,
2045                    targetHost, targetPort, true, null);
2046         }
2047         else
2048         {
2049            l = new Listener JavaDoc(notebook, null, listenPort,
2050                    targetHost, targetPort, false, null);
2051         }
2052         notebook.setSelectedIndex(1);
2053
2054         l.HTTPProxyHost = System.getProperty("http.proxyHost");
2055         if (l.HTTPProxyHost != null && l.HTTPProxyHost.equals(""))
2056         {
2057            l.HTTPProxyHost = null;
2058         }
2059
2060         if (l.HTTPProxyHost != null)
2061         {
2062            String JavaDoc tmp = System.getProperty("http.proxyPort");
2063
2064            if (tmp != null && tmp.equals(""))
2065            {
2066               tmp = null;
2067            }
2068            if (tmp == null)
2069            {
2070               l.HTTPProxyPort = 80;
2071            }
2072            else
2073            {
2074               l.HTTPProxyPort = Integer.parseInt(tmp);
2075            }
2076         }
2077      }
2078
2079      this.pack();
2080      this.setSize(600, 600);
2081      this.setVisible(true);
2082   }
2083
2084   protected void processWindowEvent(WindowEvent JavaDoc event)
2085   {
2086      switch (event.getID())
2087      {
2088         case WindowEvent.WINDOW_CLOSING:
2089            exit();
2090            break;
2091
2092         default:
2093            super.processWindowEvent(event);
2094            break;
2095      }
2096   }
2097
2098   private void exit()
2099   {
2100      System.exit(0);
2101   }
2102
2103   public void setInputPort(int port)
2104   {
2105   }
2106
2107   public void setOutputHostPort(char hostName, int port)
2108   {
2109   }
2110
2111   /**
2112    * set up the L&F
2113    */

2114   private static void setupLookAndFeel(boolean nativeLookAndFeel) throws Exception JavaDoc
2115   {
2116      UIManager.setLookAndFeel(nativeLookAndFeel ? UIManager.getSystemLookAndFeelClassName()
2117              : UIManager.getCrossPlatformLookAndFeelClassName());
2118      //JFrame.setDefaultLookAndFeelDecorated(true);
2119
}
2120
2121   /**
2122    * this is our main method
2123    *
2124    * @param args
2125    */

2126   public static void main(String JavaDoc[] args)
2127   {
2128      try
2129      {
2130         //switch between swing L&F here
2131
setupLookAndFeel(true);
2132         if (args.length == 3)
2133         {
2134            int p1 = Integer.parseInt(args[0]);
2135            int p2 = Integer.parseInt(args[2]);
2136
2137            new tcpmon(p1, args[1], p2);
2138         }
2139         else if (args.length == 1)
2140         {
2141            int p1 = Integer.parseInt(args[0]);
2142
2143            new tcpmon(p1, null, 0);
2144         }
2145         else if (args.length != 0)
2146         {
2147            System.err.println(getMessage("usage00", "Usage:")
2148                    + " tcpmon [listenPort targetHost targetPort]\n");
2149         }
2150         else
2151         {
2152            new tcpmon(0, null, 0);
2153         }
2154      }
2155      catch (Throwable JavaDoc exp)
2156      {
2157         exp.printStackTrace();
2158      }
2159   }
2160
2161   // Message resource bundle.
2162
private static ResourceBundle JavaDoc messages = null;
2163
2164   /**
2165    * Get the message with the given key. There are no arguments for this message.
2166    */

2167   public static String JavaDoc getMessage(String JavaDoc key, String JavaDoc defaultMsg)
2168   {
2169      try
2170      {
2171         if (messages == null)
2172         {
2173            initializeMessages();
2174         }
2175         return messages.getString(key);
2176      }
2177      catch (Throwable JavaDoc t)
2178      {
2179         // If there is any problem whatsoever getting the internationalized
2180
// message, return the default.
2181
return defaultMsg;
2182      }
2183   } // getMessage
2184

2185   /**
2186    * Load the resource bundle messages from the properties file. This is ONLY done when it is
2187    * needed. If no messages are printed (for example, only Wsdl2java is being run in non-
2188    * verbose mode) then there is no need to read the properties file.
2189    */

2190   private static void initializeMessages()
2191   {
2192      messages = ResourceBundle.getBundle("org.jboss.axis.utils.tcpmon");
2193   } // initializeMessages
2194

2195   /**
2196    * a text field with a restricted set of characters
2197    */

2198   static class RestrictedTextField extends JTextField
2199   {
2200      protected String JavaDoc validText;
2201
2202      public RestrictedTextField(String JavaDoc validText)
2203      {
2204         setValidText(validText);
2205      }
2206
2207      public RestrictedTextField(int columns, String JavaDoc validText)
2208      {
2209         super(columns);
2210         setValidText(validText);
2211      }
2212
2213      public RestrictedTextField(String JavaDoc text, String JavaDoc validText)
2214      {
2215         super(text);
2216         setValidText(validText);
2217      }
2218
2219      public RestrictedTextField(String JavaDoc text, int columns, String JavaDoc validText)
2220      {
2221         super(text, columns);
2222         setValidText(validText);
2223      }
2224
2225      private void setValidText(String JavaDoc validText)
2226      {
2227         this.validText = validText;
2228      }
2229
2230      /**
2231       * fascinatingly, this method is called in the super() constructor,
2232       * meaning before we are fully initialized. C++ doesnt actually permit
2233       * such a situation, but java clearly does...
2234       *
2235       * @return a new document
2236       */

2237      public Document JavaDoc createDefaultModel()
2238      {
2239         return new RestrictedDocument();
2240      }
2241
2242      /**
2243       * this class strips out invaid chars
2244       */

2245      class RestrictedDocument extends PlainDocument JavaDoc
2246      {
2247
2248
2249         /**
2250          * Constructs a plain text document. A default model using
2251          * <code>GapContent</code> is constructed and set.
2252          */

2253         public RestrictedDocument()
2254         {
2255
2256         }
2257
2258         /**
2259          * add a string; only those chars in the valid text list are allowed
2260          *
2261          * @param offset
2262          * @param string
2263          * @param attributes
2264          * @throws BadLocationException
2265          */

2266         public void insertString(int offset, String JavaDoc string, AttributeSet JavaDoc attributes)
2267                 throws BadLocationException JavaDoc
2268         {
2269
2270            if (string == null)
2271            {
2272               return;
2273            }
2274            int len = string.length();
2275            StringBuffer JavaDoc buffer = new StringBuffer JavaDoc(string.length());
2276            for (int i = 0; i < len; i++)
2277            {
2278               char ch = string.charAt(i);
2279               if (validText.indexOf(ch) >= 0)
2280               {
2281                  buffer.append(ch);
2282               }
2283            }
2284            super.insertString(offset, new String JavaDoc(buffer), attributes);
2285         }
2286      } //end class NumericDocument
2287
}
2288
2289   /**
2290    * because we cant use Java1.4's JFormattedTextField, here is
2291    * a class that accepts numbers only
2292    */

2293   static class NumberField extends RestrictedTextField
2294   {
2295
2296      private static final String JavaDoc VALID_TEXT = "0123456789";
2297
2298      /**
2299       * Constructs a new <code>TextField</code>. A default model is created,
2300       * the initial string is <code>null</code>,
2301       * and the number of columns is set to 0.
2302       */

2303      public NumberField()
2304      {
2305         super(VALID_TEXT);
2306      }
2307
2308      /**
2309       * Constructs a new empty <code>TextField</code> with the specified
2310       * number of columns.
2311       * A default model is created and the initial string is set to
2312       * <code>null</code>.
2313       *
2314       * @param columns the number of columns to use to calculate
2315       * the preferred width; if columns is set to zero, the
2316       * preferred width will be whatever naturally results from
2317       * the component implementation
2318       */

2319      public NumberField(int columns)
2320      {
2321         super(columns, VALID_TEXT);
2322      }
2323
2324
2325      /**
2326       * get the int value of a field, any invalid (non int) field returns
2327       * the default
2328       *
2329       * @param def default value
2330       * @return the field contents
2331       */

2332      public int getValue(int def)
2333      {
2334         int result = def;
2335         String JavaDoc text = getText();
2336         if (text != null && text.length() != 0)
2337         {
2338            try
2339            {
2340               result = Integer.parseInt(text);
2341            }
2342            catch (NumberFormatException JavaDoc e)
2343            {
2344
2345            }
2346         }
2347         return result;
2348      }
2349
2350      /**
2351       * set the text to a numeric value
2352       *
2353       * @param value number to assign
2354       */

2355      public void setValue(int value)
2356      {
2357         setText(Integer.toString(value));
2358      }
2359
2360   } //end class NumericTextField
2361

2362   /**
2363    * hostname fields
2364    */

2365   static class HostnameField extends RestrictedTextField
2366   {
2367      //list of valid chars in a hostname
2368
private static final String JavaDoc VALID_TEXT =
2369              "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWZYZ-.";
2370
2371      public HostnameField(int columns)
2372      {
2373         super(columns, VALID_TEXT);
2374      }
2375
2376      public HostnameField()
2377      {
2378         super(VALID_TEXT);
2379      }
2380   }
2381
2382}
2383
Popular Tags