e.g. Calendar Search Help
You must enter a value before pressing Search
axis

Class: org.apache.axis.utils.tcpmon   ©

 OK to copy?
0001 /*
0002  * The Apache Software License, Version 1.1
0003  *
0004  *
0005  * Copyright (c) 2001-2003 The Apache Software Foundation.  All rights
0006  * reserved.
0007  *
0008  * Redistribution and use in source and binary forms, with or without
0009  * modification, are permitted provided that the following conditions
0010  * are met:
0011  *
0012  * 1. Redistributions of source code must retain the above copyright
0013  *    notice, this list of conditions and the following disclaimer.
0014  *
0015  * 2. Redistributions in binary form must reproduce the above copyright
0016  *    notice, this list of conditions and the following disclaimer in
0017  *    the documentation and/or other materials provided with the
0018  *    distribution.
0019  *
0020  * 3. The end-user documentation included with the redistribution,
0021  *    if any, must include the following acknowledgment:
0022  *       "This product includes software developed by the
0023  *        Apache Software Foundation (http://www.apache.org/)."
0024  *    Alternately, this acknowledgment may appear in the software itself,
0025  *    if and wherever such third-party acknowledgments normally appear.
0026  *
0027  * 4. The names "Axis" and "Apache Software Foundation" must
0028  *    not be used to endorse or promote products derived from this
0029  *    software without prior written permission. For written
0030  *    permission, please contact apache@apache.org.
0031  *
0032  * 5. Products derived from this software may not be called "Apache",
0033  *    nor may "Apache" appear in their name, without prior written
0034  *    permission of the Apache Software Foundation.
0035  *
0036  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
0037  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
0038  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
0039  * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
0040  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
0041  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
0042  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
0043  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
0044  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
0045  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
0046  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
0047  * SUCH DAMAGE.
0048  * ====================================================================
0049  *
0050  * This software consists of voluntary contributions made by many
0051  * individuals on behalf of the Apache Software Foundation.  For more
0052  * information on the Apache Software Foundation, please see
0053  * <http://www.apache.org/>.
0054  */
0055 package org.apache.axis.utils ;
0056 
0057 
0058 import javax.swing.BorderFactory;
0059 import javax.swing.Box;
0060 import javax.swing.BoxLayout;
0061 import javax.swing.ButtonGroup;
0062 import javax.swing.JButton;
0063 import javax.swing.JCheckBox;
0064 import javax.swing.JFileChooser;
0065 import javax.swing.JFrame;
0066 import javax.swing.JLabel;
0067 import javax.swing.JPanel;
0068 import javax.swing.JRadioButton;
0069 import javax.swing.JScrollPane;
0070 import javax.swing.JSplitPane;
0071 import javax.swing.JTabbedPane;
0072 import javax.swing.JTable;
0073 import javax.swing.JTextArea;
0074 import javax.swing.JTextField;
0075 import javax.swing.ListSelectionModel;
0076 import javax.swing.SwingConstants;
0077 import javax.swing.UIManager;
0078 import javax.swing.border.TitledBorder;
0079 import javax.swing.event.ChangeEvent;
0080 import javax.swing.event.ListSelectionEvent;
0081 import javax.swing.event.ListSelectionListener;
0082 import javax.swing.plaf.basic.BasicButtonListener;
0083 import javax.swing.table.DefaultTableModel;
0084 import javax.swing.table.TableColumn;
0085 import javax.swing.table.TableModel;
0086 import javax.swing.text.AttributeSet;
0087 import javax.swing.text.BadLocationException;
0088 import javax.swing.text.Document;
0089 import javax.swing.text.PlainDocument;
0090 import java.awt.BorderLayout;
0091 import java.awt.Color;
0092 import java.awt.Component;
0093 import java.awt.Dimension;
0094 import java.awt.GridBagConstraints;
0095 import java.awt.GridBagLayout;
0096 import java.awt.event.ActionEvent;
0097 import java.awt.event.ActionListener;
0098 import java.awt.event.WindowEvent;
0099 import java.io.ByteArrayInputStream;
0100 import java.io.File;
0101 import java.io.FileOutputStream;
0102 import java.io.InputStream;
0103 import java.io.OutputStream;
0104 import java.io.PrintWriter;
0105 import java.io.StringWriter;
0106 import java.net.ServerSocket;
0107 import java.net.Socket;
0108 import java.net.URL;
0109 import java.text.DateFormat;
0110 import java.text.SimpleDateFormat;
0111 import java.util.Date;
0112 import java.util.Iterator;
0113 import java.util.ResourceBundle;
0114 import java.util.Vector;
0115 
0116 
0117 /**
0118  * TCP monitor to log http messages and responses, both SOAP and plain HTTP.
0119  * @author Doug Davis (dug@us.ibm.com)
0120  * @author Steve Loughran
0121  */
0122 
0123 public class tcpmon extends JFrame {
0124     private JTabbedPane  notebook = null ;
0125 
0126     private static final int STATE_COLUMN    = 0 ;
0127     private static final int TIME_COLUMN     = 1 ;
0128     private static final int INHOST_COLUMN   = 2 ;
0129     private static final int OUTHOST_COLUMN  = 3 ;
0130     private static final int REQ_COLUMN      = 4 ;
0131 
0132 
0133     private static final String DEFAULT_HOST="127.0.0.1";
0134     private static final int    DEFAULT_PORT=8080;
0135 
0136     /**
0137      * this is the admin page
0138      */
0139     class AdminPage extends JPanel {
0140         public JRadioButton  listenerButton, proxyButton ;
0141         public JLabel        hostLabel, tportLabel;
0142         public NumberField  port;
0143         public HostnameField host;
0144         public NumberField  tport ;
0145         public JTabbedPane   noteb ;
0146         public JCheckBox     HTTPProxyBox ;
0147         public HostnameField    HTTPProxyHost;
0148         public NumberField HTTPProxyPort ;
0149         public JLabel        HTTPProxyHostLabel, HTTPProxyPortLabel ;
0150         public JLabel        delayTimeLabel, delayBytesLabel;
0151         public NumberField delayTime, delayBytes;
0152         public JCheckBox     delayBox;
0153 
0154         public AdminPage( JTabbedPane notebook, String name ) {
0155             JPanel     mainPane  = null ;
0156             JButton    addButton = null ;
0157 
0158             this.setLayout( new BorderLayout() );
0159             noteb = notebook ;
0160 
0161             GridBagLayout       layout        = new GridBagLayout();
0162             GridBagConstraints  c             = new GridBagConstraints();
0163 
0164             mainPane = new JPanel(layout);
0165 
0166             c.anchor    = GridBagConstraints.WEST ;
0167             c.gridwidth = GridBagConstraints.REMAINDER;
0168             mainPane.add( new JLabel(getMessage("newTCP00", "Create a new TCP/IP Monitor...") + " "), c );
0169 
0170             // Add some blank space
0171             mainPane.add( Box.createRigidArea(new Dimension(1, 5)), c );
0172 
0173             // The listener info
0174             ///////////////////////////////////////////////////////////////////
0175             JPanel   tmpPanel = new JPanel(new GridBagLayout());
0176 
0177             c.anchor    = GridBagConstraints.WEST ;
0178             c.gridwidth = 1 ;
0179             tmpPanel.add( new JLabel(getMessage("listenPort00", "Listen Port #") + " "), c );
0180 
0181             c.anchor    = GridBagConstraints.WEST ;
0182             c.gridwidth = GridBagConstraints.REMAINDER ;
0183             tmpPanel.add( port = new NumberField(4), c );
0184 
0185             mainPane.add( tmpPanel, c );
0186 
0187             mainPane.add( Box.createRigidArea(new Dimension(1, 5)), c );
0188 
0189             // Group for the radio buttons
0190             ButtonGroup btns = new ButtonGroup();
0191 
0192             c.anchor    = GridBagConstraints.WEST ;
0193             c.gridwidth = GridBagConstraints.REMAINDER ;
0194             mainPane.add( new JLabel(getMessage("actAs00", "Act as a...") ), c );
0195 
0196             // Target Host/Port section
0197             ///////////////////////////////////////////////////////////////////
0198             c.anchor    = GridBagConstraints.WEST ;
0199             c.gridwidth = GridBagConstraints.REMAINDER ;
0200 
0201             final String listener = getMessage("listener00", "Listener");
0202 
0203             mainPane.add( listenerButton  = new JRadioButton( listener ), c );
0204             btns.add( listenerButton );
0205             listenerButton.setSelected( true );
0206 
0207             listenerButton.addActionListener( new ActionListener() {
0208                     public void actionPerformed(ActionEvent event) {
0209                         if (listener.equals(event.getActionCommand())) {
0210                             boolean state = listenerButton.isSelected();
0211 
0212                             tport.setEnabled( state );
0213                             host.setEnabled( state );
0214                             hostLabel.setForeground(state ? Color.black : Color.gray);
0215                             tportLabel.setForeground(state ? Color.black : Color.gray);
0216                         }
0217                     }
0218                 }
0219             );
0220 
0221             c.anchor    = GridBagConstraints.WEST ;
0222             c.gridwidth = 1 ;
0223             mainPane.add( Box.createRigidArea(new Dimension(25, 0)) );
0224             mainPane.add( hostLabel = new JLabel(getMessage("targetHostname00", "Target Hostname") + " "), c );
0225 
0226             c.anchor    = GridBagConstraints.WEST ;
0227             c.gridwidth = GridBagConstraints.REMAINDER ;
0228             host = new HostnameField(30);
0229             mainPane.add( host, c );
0230             host.setText(DEFAULT_HOST);
0231 
0232             c.anchor    = GridBagConstraints.WEST ;
0233             c.gridwidth = 1 ;
0234             mainPane.add( Box.createRigidArea(new Dimension(25, 0)) );
0235             mainPane.add( tportLabel = new JLabel(getMessage("targetPort00", "Target Port #") + " "), c );
0236 
0237             c.anchor    = GridBagConstraints.WEST ;
0238             c.gridwidth = GridBagConstraints.REMAINDER ;
0239             tport = new NumberField(4);
0240             mainPane.add( tport, c );
0241             tport.setValue(DEFAULT_PORT);
0242 
0243             // Act as proxy section
0244             ///////////////////////////////////////////////////////////////////
0245             c.anchor    = GridBagConstraints.WEST ;
0246             c.gridwidth = GridBagConstraints.REMAINDER ;
0247             final String proxy = getMessage("proxy00", "Proxy");
0248 
0249             mainPane.add( proxyButton = new JRadioButton( proxy ), c);
0250             btns.add( proxyButton );
0251 
0252             proxyButton.addActionListener( new ActionListener() {
0253                     public void actionPerformed(ActionEvent event) {
0254                         if (proxy.equals(event.getActionCommand())) {
0255                             boolean state = proxyButton.isSelected();
0256 
0257                             tport.setEnabled( !state );
0258                             host.setEnabled( !state );
0259                             hostLabel.setForeground(state ? Color.gray : Color.black);
0260                             tportLabel.setForeground(state ? Color.gray : Color.black);
0261                         }
0262                     }
0263                 }
0264             );
0265 
0266             // Spacer
0267             /////////////////////////////////////////////////////////////////
0268             c.anchor    = GridBagConstraints.WEST ;
0269             c.gridwidth = GridBagConstraints.REMAINDER ;
0270             mainPane.add( Box.createRigidArea(new Dimension(1, 10)), c );
0271 
0272             // Options section
0273             ///////////////////////////////////////////////////////////////////
0274             JPanel       opts = new JPanel(new GridBagLayout());
0275 
0276             opts.setBorder( new TitledBorder(getMessage("options00", "Options")) );
0277             c.anchor    = GridBagConstraints.WEST ;
0278             c.gridwidth = GridBagConstraints.REMAINDER ;
0279             mainPane.add( opts, c );
0280 
0281             // HTTP Proxy Support section
0282             ///////////////////////////////////////////////////////////////////
0283             c.anchor    = GridBagConstraints.WEST ;
0284             c.gridwidth = GridBagConstraints.REMAINDER ;
0285             final String proxySupport = getMessage("proxySupport00", "HTTP Proxy Support");
0286 
0287             opts.add(HTTPProxyBox = new JCheckBox(proxySupport), c);
0288 
0289             c.anchor    = GridBagConstraints.WEST ;
0290             c.gridwidth = 1 ;
0291             opts.add( HTTPProxyHostLabel = new JLabel(getMessage("hostname00", "Hostname") + " "), c );
0292             HTTPProxyHostLabel.setForeground( Color.gray );
0293 
0294             c.anchor    = GridBagConstraints.WEST ;
0295             c.gridwidth = GridBagConstraints.REMAINDER ;
0296             opts.add( HTTPProxyHost = new HostnameField(30), c );
0297             HTTPProxyHost.setEnabled( false );
0298 
0299             c.anchor    = GridBagConstraints.WEST ;
0300             c.gridwidth = 1 ;
0301             opts.add( HTTPProxyPortLabel = new JLabel(getMessage("port00", "Port #") + " "), c );
0302             HTTPProxyPortLabel.setForeground( Color.gray );
0303 
0304             c.anchor    = GridBagConstraints.WEST ;
0305             c.gridwidth = GridBagConstraints.REMAINDER ;
0306             opts.add( HTTPProxyPort = new NumberField(4), c );
0307             HTTPProxyPort.setEnabled( false );
0308 
0309             HTTPProxyBox.addActionListener( new ActionListener() {
0310                     public void actionPerformed(ActionEvent event) {
0311                         if (proxySupport.equals(event.getActionCommand())) {
0312                             boolean b = HTTPProxyBox.isSelected();
0313                             Color   color = b ? Color.black : Color.gray ;
0314 
0315                             HTTPProxyHost.setEnabled( b );
0316                             HTTPProxyPort.setEnabled( b );
0317                             HTTPProxyHostLabel.setForeground( color );
0318                             HTTPProxyPortLabel.setForeground( color );
0319                         }
0320                     }
0321                 }
0322             );
0323 
0324             // Set default proxy values...
0325             String tmp = System.getProperty( "http.proxyHost" );
0326 
0327             if ( tmp != null && tmp.equals("") ) {
0328                 tmp = null ;
0329             }
0330 
0331             HTTPProxyBox.setSelected( tmp != null );
0332             HTTPProxyHost.setEnabled( tmp != null );
0333             HTTPProxyPort.setEnabled( tmp != null );
0334             HTTPProxyHostLabel.setForeground( tmp != null ? Color.black : Color.gray);
0335             HTTPProxyPortLabel.setForeground( tmp != null ? Color.black : Color.gray);
0336 
0337             if ( tmp != null ) {
0338                 HTTPProxyBox.setSelected( true );
0339                 HTTPProxyHost.setText( tmp );
0340                 tmp = System.getProperty( "http.proxyPort" );
0341                 if ( tmp != null && tmp.equals("") ) {
0342                     tmp = null ;
0343                 }
0344                 if ( tmp == null ) {
0345                     tmp = "80" ;
0346                 }
0347                 HTTPProxyPort.setText( tmp );
0348             }
0349 
0350             //add byte delay fields
0351             opts.add(Box.createRigidArea(new Dimension(1, 10)), c);
0352             c.anchor = GridBagConstraints.WEST;
0353             c.gridwidth = GridBagConstraints.REMAINDER;
0354             final String delaySupport = getMessage("delay00", "Simulate Slow Connection");
0355             opts.add(delayBox = new JCheckBox(delaySupport), c);
0356 
0357             //bytes per pause
0358             c.anchor = GridBagConstraints.WEST;
0359             c.gridwidth = 1;
0360             delayBytesLabel=new JLabel(getMessage("delay01",  "Bytes per Pause"));
0361             opts.add(delayBytesLabel, c);
0362             delayBytesLabel.setForeground(Color.gray);
0363             c.anchor = GridBagConstraints.WEST;
0364             c.gridwidth = GridBagConstraints.REMAINDER;
0365             opts.add(delayBytes = new NumberField(6), c);
0366             delayBytes.setEnabled(false);
0367 
0368             //delay interval
0369             c.anchor = GridBagConstraints.WEST;
0370             c.gridwidth = 1;
0371             delayTimeLabel = new JLabel(getMessage("delay02", "Delay in Milliseconds"));
0372             opts.add(delayTimeLabel, c);
0373             delayTimeLabel.setForeground(Color.gray);
0374             c.anchor = GridBagConstraints.WEST;
0375             c.gridwidth = GridBagConstraints.REMAINDER;
0376             opts.add(delayTime = new NumberField(6), c);
0377             delayTime.setEnabled(false);
0378 
0379             //enabler callback
0380             delayBox.addActionListener(new ActionListener() {
0381                 public void actionPerformed(ActionEvent event) {
0382                     if (delaySupport.equals(event.getActionCommand())) {
0383                         boolean b = delayBox.isSelected();
0384                         Color color = b ? Color.black : Color.gray;
0385 
0386                         delayBytes.setEnabled(b);
0387                         delayTime.setEnabled(b);
0388                         delayBytesLabel.setForeground(color);
0389                         delayTimeLabel.setForeground(color);
0390                     }
0391                 }
0392             }
0393             );
0394 
0395             // Spacer
0396             //////////////////////////////////////////////////////////////////
0397             mainPane.add( Box.createRigidArea(new Dimension(1, 10)), c );
0398 
0399             // ADD Button
0400             ///////////////////////////////////////////////////////////////////
0401             c.anchor    = GridBagConstraints.WEST ;
0402             c.gridwidth = GridBagConstraints.REMAINDER ;
0403             final String add = getMessage("add00", "Add");
0404 
0405             mainPane.add( addButton = new JButton( add ), c );
0406 
0407 
0408             this.add( new JScrollPane( mainPane ), BorderLayout.CENTER );
0409 
0410             // addButton.setEnabled( false );
0411             addButton.addActionListener( new ActionListener() {
0412                     public void actionPerformed(ActionEvent event) {
0413                         if ( add.equals(event.getActionCommand()) ) {
0414                             String   text ;
0415                             Listener l = null ;
0416                             int      lPort;
0417                             lPort=port.getValue(0);
0418                             if(lPort==0) {
0419                                 //no port, button does nothing
0420                                 return;
0421                             }
0422                             String   tHost = host.getText();
0423                             int      tPort = 0 ;
0424                             tPort=tport.getValue(0);
0425                             SlowLinkSimulator slowLink=null;
0426                             if(delayBox.isSelected()) {
0427                                 int bytes= delayBytes.getValue(0);
0428                                 int time = delayTime.getValue(0);
0429                                 slowLink=new SlowLinkSimulator(bytes,time);
0430                             }
0431                             l = new Listener( noteb, null, lPort, tHost, tPort,
0432                                            proxyButton.isSelected(), slowLink);
0433 
0434                             // Pick-up the HTTP Proxy settings
0435                             ///////////////////////////////////////////////////
0436                             text = HTTPProxyHost.getText();
0437                             if ( "".equals(text) ) {
0438                                 text = null ;
0439                             }
0440                             l.HTTPProxyHost = text ;
0441                             text = HTTPProxyPort.getText();
0442                             int proxyPort=HTTPProxyPort.getValue(-1);
0443                             if(proxyPort!=-1) {
0444                                 l.HTTPProxyPort = Integer.parseInt(text);
0445                             }
0446                             //reset the port
0447                             port.setText(null);
0448 
0449                             /* but not, any more, the target port and host
0450                                values
0451                             host.setText(null);
0452                             tport.setText(null);
0453                             */
0454                         }
0455                     }
0456                 }
0457             );
0458 
0459             notebook.addTab( name, this );
0460             notebook.repaint();
Rate0461             notebook.setSelectedIndex( notebook.getTabCount() - 1 );
0462         }
0463 
0464 
0465     }
0466 
0467     /**
0468      * wait for incoming connections, spawn a connection thread when
0469      * stuff comes in.
0470      */
0471     class SocketWaiter extends Thread {
0472         ServerSocket  sSocket = null ;
0473         Listener      listener ;
0474         int           port ;
0475         boolean       pleaseStop = false ;
0476 
0477         public SocketWaiter(Listener l, int p) {
0478             listener = l ;
0479             port = p ;
0480             start();
0481         }
0482 
0483         public void run() {
0484             try {
0485                 listener.setLeft( new JLabel(getMessage("wait00", " Waiting for Connection...") ) );
0486                 listener.repaint();
0487                 sSocket = new ServerSocket( port );
0488                 for (; ; ) {
0489                     Socket inSocket = sSocket.accept();
0490 
0491                     if ( pleaseStop ) {
0492                         break ;
0493                     }
0494                     new Connection( listener, inSocket );
0495                     inSocket = null ;
0496                 }
0497             } catch ( Exception exp ) {
0498                 if ( !"socket closed".equals(exp.getMessage()) ) {
0499                     JLabel tmp = new JLabel( exp.toString() );
0500 
0501                     tmp.setForeground( Color.red );
0502                     listener.setLeft( tmp );
0503                     listener.setRight( new JLabel("") );
0504                     listener.stop();
0505                 }
0506             }
0507         }
0508 
0509         /**
0510          * force a halt by connecting to self and then closing the server socket
0511          */
0512         public void halt() {
0513             try {
0514                 pleaseStop = true ;
0515                 new Socket( "127.0.0.1", port );
0516                 if ( sSocket != null ) {
0517                     sSocket.close();
0518                 }
0519             } catch ( Exception e ) {
0520                 e.printStackTrace();
0521             }
0522         }
0523     }
0524 
0525 
0526     /**
0527      * class to simulate slow connections by slowing down the system
0528      */
0529     static class SlowLinkSimulator {
0530         private int delayBytes;
0531         private int delayTime;
0532         private int currentBytes;
0533         private int totalBytes;
0534 
0535         /**
0536          * construct
0537          * @param delayBytes bytes per delay; set to 0 for no delay
0538          * @param delayTime delay time per delay in milliseconds
0539          */
0540         public SlowLinkSimulator(int delayBytes, int delayTime) {
0541             this.delayBytes = delayBytes;
0542             this.delayTime = delayTime;
0543         }
0544 
0545         /**
0546          * construct by copying delay bytes and time, but not current
0547          * count of bytes
0548          * @param that source of data
0549          */
0550         public SlowLinkSimulator(SlowLinkSimulator that) {
0551             this.delayBytes=that.delayBytes;
0552             this.delayTime=that.delayTime;
0553         }
0554 
0555         /**
0556          * how many bytes have gone past?
0557          * @return
0558          */
0559         public int getTotalBytes() {
0560             return totalBytes;
0561         }
0562 
0563         /**
0564          * log #of bytes pumped. Will pause when necessary. This method is not
0565          * synchronized
0566          * @param bytes
0567          */
0568         public void pump(int bytes) {
0569             totalBytes+=bytes;
0570             if(delayBytes==0) {
0571                 //when not delaying, we are just a byte counter
0572                 return;
0573             }
0574             currentBytes += bytes;
0575             if(currentBytes>delayBytes) {
0576                 //we have overshot. lets find out how far
0577                 int delaysize=currentBytes/delayBytes;
0578                 long delay=delaysize*(long)delayTime;
0579                 //move byte counter down to the remainder of bytes
0580                 currentBytes=currentBytes%delayBytes;
0581                 //now wait
0582                 try {
0583                     Thread.sleep(delay);
0584                 } catch (InterruptedException e) {
0585                     ; //ignore the exception
0586                 }
0587             }
0588         }
0589 
0590         /**
0591          * get the current byte count
0592          * @return
0593          */
0594         public int getCurrentBytes() {
0595             return currentBytes;
0596         }
0597 
0598         /**
0599          * set the current byte count
0600          * @param currentBytes
0601          */
0602         public void setCurrentBytes(int currentBytes) {
0603             this.currentBytes = currentBytes;
0604         }
0605 
0606     }
0607 
0608     /**
0609      * this class handles the pumping of data from the incoming socket to the
0610      * outgoing socket
0611      */
0612     class SocketRR extends Thread {
0613         Socket        inSocket  = null ;
0614         Socket        outSocket  = null ;
0615         JTextArea     textArea ;
0616         InputStream   in = null ;
0617         OutputStream  out = null ;
0618         boolean       xmlFormat ;
0619         volatile boolean       done = false ;
0620         TableModel    tmodel = null ;
0621         int           tableIndex = 0 ;
0622         String type = null;
0623         Connection    myConnection = null;
0624         SlowLinkSimulator slowLink;
0625 
0626         public SocketRR(Connection c, Socket inputSocket, InputStream inputStream,
0627             Socket outputSocket, OutputStream outputStream,
0628             JTextArea _textArea, boolean format,
0629             TableModel tModel, int index, final String type, SlowLinkSimulator slowLink) {
0630             inSocket = inputSocket ;
0631             in       = inputStream ;
0632             outSocket = outputSocket ;
0633             out       = outputStream ;
0634             textArea  = _textArea ;
0635             xmlFormat = format ;
0636             tmodel    = tModel ;
0637             tableIndex = index ;
0638             this.type = type;
0639             myConnection = c;
0640             this.slowLink= slowLink;
0641             start();
0642         }
0643 
0644         public boolean isDone() {
0645             return ( done );
0646         }
0647 
0648         public void run() {
0649             try {
0650                 byte[]      buffer = new byte[4096];
0651                 byte[]      tmpbuffer = new byte[8192];
0652                 int         saved = 0 ;
0653                 int         len ;
0654                 int         i1, i2 ;
0655                 int         i ;
0656                 int         reqSaved = 0 ;
0657                 int         tabWidth = 3 ;
0658                 boolean     atMargin = true ;
0659                 int         thisIndent = -1,
0660                     nextIndent = -1,
0661                     previousIndent = -1;
0662 
0663                 //if ( inSocket  != null ) inSocket.setSoTimeout( 10 );
0664                 //if ( outSocket != null ) outSocket.setSoTimeout( 10 );
0665 
0666                 if ( tmodel != null ) {
0667                     String tmpStr = (String) tmodel.getValueAt(tableIndex,
0668                             REQ_COLUMN);
0669 
0670                     if ( !"".equals(tmpStr) ) {
0671                         reqSaved = tmpStr.length();
0672                     }
0673                 }
0674 
0675             a:
0676                 for ( ; ; ) {
0677                     if ( done ) {
0678                         break;
0679                     }
0680                     //try{
0681                     //len = in.available();
0682                     //}catch(Exception e){len=0;}
0683                     len = buffer.length ;
0684                     // Used to be 1, but if we block it doesn't matter
0685                     // however 1 will break with some servers, including apache
0686                     if ( len == 0 ) {
0687                         len = buffer.length;
0688                     }
0689                     if ( saved + len > buffer.length) {
0690                         len = buffer.length - saved ;
0691                     }
0692                     int len1 = 0;
0693 
0694                     while ( len1 == 0 ) {
0695                         try {
0696                             len1 = in.read(buffer, saved, len);
0697                         }
0698                         catch ( Exception ex ) {
0699                             if ( done && saved == 0  ) {
0700                                 break a;
0701                             }
0702                             len1 = -1;
0703                             break;
0704                         }
0705                     }
0706                     len = len1;
0707 
0708                     if ( len == -1 && saved == 0 ) {
0709                         break ;
0710                     }
0711                     if ( len == -1) {
0712                         done = true;
0713                     }
0714 
0715                     // No matter how we may (or may not) format it, send it
0716                     // on unformatted - we don't want to mess with how its
0717                     // sent to the other side, just how its displayed
0718                     if ( out != null && len > 0 ) {
0719                         slowLink.pump(len);
0720                         out.write( buffer, saved, len );
0721                     }
0722 
0723                     if ( tmodel != null && reqSaved < 50 ) {
0724                         String old = (String) tmodel.getValueAt( tableIndex,
0725                                 REQ_COLUMN);
0726 
0727                         old = old + new String(buffer, saved, len);
0728                         if ( old.length() > 50 ) {
0729                             old = old.substring(0, 50);
0730                         }
0731 
0732                         reqSaved = old.length();
0733 
0734                         if ( (i = old.indexOf('\n')) > 0 ) {
0735                             old = old.substring(0, i - 1);
0736                             reqSaved = 50 ;
0737                         }
0738 
0739                         tmodel.setValueAt( old, tableIndex, REQ_COLUMN );
0740                     }
0741 
0742                     if ( xmlFormat ) {
0743                         // Do XML Formatting
0744                         boolean inXML = false ;
0745                         int     bufferLen = saved ;
0746 
0747                         if ( len != -1 ) {
0748                             bufferLen += len ;
0749                         }
0750                         i1 = 0 ;
0751                         i2 = 0 ;
0752                         saved = 0 ;
0753                         for ( ; i1 < bufferLen ; i1++ ) {
0754                             // Except when we're at EOF, saved last char
0755                             if ( len != -1 && i1 + 1 == bufferLen ) {
0756                                 saved = 1;
0757                                 break;
0758                             }
0759                             thisIndent = -1;
0760                             if ( buffer[i1] == '<' && buffer[i1 + 1] != '/' ) {
0761                                 previousIndent = nextIndent++;
0762                                 thisIndent = nextIndent;
0763                                 inXML = true ;
0764                             }
0765                             if ( buffer[i1] == '<' && buffer[i1 + 1] == '/' ) {
0766                                 if (previousIndent > nextIndent) {
0767                                     thisIndent = nextIndent;
0768                                 }
0769                                 previousIndent = nextIndent--;
0770                                 inXML = true ;
0771                             }
0772                             if ( buffer[i1] == '/' && buffer[i1 + 1] == '>' ) {
0773                                 previousIndent = nextIndent--;
0774                                 inXML = true ;
0775                             }
0776                             if ( thisIndent != -1 ) {
0777                                 if ( thisIndent > 0 ) {
0778                                     tmpbuffer[i2++] = (byte) '\n';
0779                                 }
0780                                 for ( i = tabWidth * thisIndent; i > 0; i-- ) {
0781                                     tmpbuffer[i2++] = (byte) ' ';
0782                                 }
0783                             }
0784                             atMargin = ( buffer[i1] == '\n' || buffer[i1] == '\r');
0785 
0786                             if ( !inXML || !atMargin ) {
0787                                 tmpbuffer[i2++] = buffer[i1];
0788                             }
0789                         }
0790 
0791                         textArea.append( new String( tmpbuffer, 0, i2 ) );
0792 
0793                         // Shift saved bytes to the beginning
0794                         for ( i = 0 ; i < saved ; i++ ) {
0795                             buffer[i] = buffer[bufferLen - saved + i];
0796                         }
0797                     }
0798                     else {
0799                         textArea.append( new String( buffer, 0, len ) );
0800                     }
0801                 // this.sleep(3);  // Let other threads have a chance to run
0802                 }
0803             // this.sleep(3);  // Let other threads have a chance to run
0804             // halt();
0805             // Only set the 'done' flag if we were reading from a
0806             // Socket - if we were reading from an input stream then
0807             // we'll let the other side control when we're done
0808             //      if ( inSocket != null ) done = true ;
0809             }
0810             catch ( Exception e ) {
0811                 e.printStackTrace();
0812             }
0813             finally {
0814                 done = true ;
0815                 try {
0816                     if (out != null) {
0817                         out.flush();
0818                         if (null != outSocket) {
0819                             outSocket.shutdownOutput();
0820                         } else {
0821                             out.close();
0822                         }
0823                         out = null;
0824                     }
0825                 }
0826                 catch (Exception e) {
0827                     ;
0828                 }
0829                 try {
0830                     if (in != null) {
0831                         if (inSocket != null) {
0832                             inSocket.shutdownInput();
0833                         } else {
0834                             in.close();
0835                         }
0836                         in = null;
0837                     }
0838                 }
0839                 catch (Exception e) {
0840                     ;
0841                 }
0842                 myConnection.wakeUp();
0843             }
0844         }
0845 
0846         public  void halt() {
0847             try {
0848                 if ( inSocket != null ) {
0849                     inSocket.close();
0850                 }
0851                 if ( outSocket != null ) {
0852                     outSocket.close();
0853                 }
0854                 inSocket  = null ;
0855                 outSocket = null ;
0856                 if ( in != null ) {
0857                     in.close();
0858                 }
0859                 if ( out != null ) {
0860                     out.close();
0861                 }
0862                 in = null ;
0863                 out = null ;
0864                 done = true;
0865             }
0866             catch ( Exception e ) {
0867                 e.printStackTrace();
0868             }
0869         }
0870     }
0871 
0872 
0873     /**
0874      * a connection listens to a single current connection
0875      */
0876     class Connection extends Thread {
0877         Listener     listener ;
0878         boolean      active ;
0879         String       fromHost ;
0880         String       time ;
0881         JTextArea    inputText    = null ;
0882         JScrollPane  inputScroll  = null ;
0883         JTextArea    outputText   = null ;
0884         JScrollPane  outputScroll = null ;
0885         Socket       inSocket     = null ;
0886         Socket       outSocket    = null ;
0887         Thread       clientThread = null ;
0888         Thread       serverThread = null ;
0889         SocketRR     rr1          = null ;
0890         SocketRR     rr2          = null ;
0891         InputStream  inputStream  = null ;
0892 
0893         String       HTTPProxyHost = null ;
0894         int          HTTPProxyPort = 80 ;
0895         private SlowLinkSimulator slowLink;
0896 
0897         public Connection(Listener l) {
0898             listener = l ;
0899             HTTPProxyHost = l.HTTPProxyHost ;
0900             HTTPProxyPort = l.HTTPProxyPort ;
0901             slowLink =l.slowLink;
0902         }
0903 
0904         public Connection(Listener l, Socket s ) {
0905             this (l);
0906             inSocket = s ;
0907             start();
0908         }
0909 
0910         public Connection(Listener l, InputStream in ) {
0911             this (l);
0912             inputStream = in ;
0913             start();
0914         }
0915 
0916         public void run() {
0917             try {
0918                 active        = true ;
0919 
0920                 HTTPProxyHost = System.getProperty( "http.proxyHost" );
0921                 if ( HTTPProxyHost != null && HTTPProxyHost.equals("") ) {
0922                     HTTPProxyHost = null ;
0923                 }
0924 
0925                 if ( HTTPProxyHost != null ) {
0926                     String tmp = System.getProperty( "http.proxyPort" );
0927 
0928                     if ( tmp != null && tmp.equals("") ) {
0929                         tmp = null ;
0930                     }
0931                     if ( tmp == null ) {
0932                         HTTPProxyPort = 80 ;
0933                     } else {
0934                         HTTPProxyPort = Integer.parseInt( tmp );
0935                     }
0936                 }
0937 
0938                 if ( inSocket != null ) {
0939                     fromHost = (inSocket.getInetAddress()).getHostName();
0940                 } else {
0941                     fromHost = "resend" ;
0942                 }
0943 
0944 
0945                 String dateformat=getMessage("dateformat00", "yyyy-MM-dd HH:mm:ss");
0946                 DateFormat   df = new SimpleDateFormat(dateformat);
0947 
0948                 time = df.format( new Date() );
0949 
0950                 int count = listener.connections.size();
0951 
0952                 listener.tableModel.insertRow(count + 1, new Object[] {
0953                         getMessage("active00", "Active"),
0954                         time,
0955                         fromHost,
0956                         listener.hostField.getText(), ""
0957                     }
0958                 );
0959                 listener.connections.add( this );
0960                 inputText  = new JTextArea( null, null, 20, 80 );
0961                 inputScroll = new JScrollPane( inputText );
0962                 outputText = new JTextArea( null, null, 20, 80 );
0963                 outputScroll = new JScrollPane( outputText );
0964 
0965                 ListSelectionModel lsm = listener.connectionTable.getSelectionModel();
0966 
0967                 if ( count == 0 || lsm.getLeadSelectionIndex() == 0 ) {
0968                     listener.outPane.setVisible( false );
0969                     int divLoc = listener.outPane.getDividerLocation();
0970 
0971                     listener.setLeft( inputScroll );
0972                     listener.setRight( outputScroll );
0973 
0974                     listener.removeButton.setEnabled(false);
0975                     listener.removeAllButton.setEnabled(true);
0976                     listener.saveButton.setEnabled(true);
0977                     listener.resendButton.setEnabled(true);
0978                     listener.outPane.setDividerLocation(divLoc);
0979                     listener.outPane.setVisible( true );
0980                 }
0981 
0982                 String targetHost = listener.hostField.getText();
0983                 int    targetPort = Integer.parseInt(listener.tPortField.getText());
0984 
0985                 InputStream  tmpIn1  = inputStream ;
0986                 OutputStream tmpOut1 = null ;
0987 
0988                 InputStream  tmpIn2  = null ;
0989                 OutputStream tmpOut2 = null ;
0990 
0991                 if ( tmpIn1 == null ) {
0992                     tmpIn1  = inSocket.getInputStream();
0993                 }
0994 
0995                 if ( inSocket != null ) {
0996                     tmpOut1 = inSocket.getOutputStream();
0997                 }
0998 
0999                 String         bufferedData = null ;
1000                 StringBuffer   buf = null ;
1001 
1002                 int index = listener.connections.indexOf( this );
1003 
1004                 if (listener.isProxyBox.isSelected() || HTTPProxyHost != null) {
1005                     // Check if we're a proxy
1006                     byte[]       b = new byte[1];
1007 
1008                     buf = new StringBuffer();
1009                     String       s ;
1010 
1011                     for ( ; ; ) {
1012                         int len ;
1013 
1014                         len = tmpIn1.read(b, 0, 1);
1015                         if ( len == -1 ) {
1016                             break ;
1017                         }
1018                         s = new String( b );
1019                         buf.append( s );
1020                         if ( b[0] != '\n' ) {
1021                             continue ;
1022                         }
1023                         break ;
1024                     }
1025 
1026                     bufferedData = buf.toString();
1027                     inputText.append( bufferedData );
1028 
1029                     if ( bufferedData.startsWith( "GET " ) ||
1030                         bufferedData.startsWith( "POST " ) ) {
1031                         int  start, end ;
1032                         URL  url ;
1033 
1034                         start = bufferedData.indexOf( ' ' ) + 1;
1035                         while ( bufferedData.charAt(start) == ' ' ) {
1036                             start++ ;
1037                         }
1038                         end   = bufferedData.indexOf( ' ', start );
1039                         String urlString = bufferedData.substring( start, end );
1040 
1041                         if ( urlString.charAt(0) == '/' ) {
1042                             urlString = urlString.substring(1);
1043                         }
1044                         if ( listener.isProxyBox.isSelected() ) {
1045                             url = new URL( urlString );
1046                             targetHost = url.getHost();
1047                             targetPort = url.getPort();
1048                             if ( targetPort == -1 ) {
1049                                 targetPort = 80 ;
1050                             }
1051 
1052                             listener.tableModel.setValueAt( targetHost, index + 1,
1053                                 OUTHOST_COLUMN );
1054                             bufferedData = bufferedData.substring( 0, start) +
1055                             url.getFile() +
1056                             bufferedData.substring( end );
1057                         }
1058                         else {
1059                             url = new URL( "http://" + targetHost + ":" +
1060                                 targetPort + "/" + urlString );
1061 
1062                             listener.tableModel.setValueAt( targetHost, index + 1,
1063                                 OUTHOST_COLUMN );
1064                             bufferedData = bufferedData.substring( 0, start) +
1065                                 url.toExternalForm() +
1066                                 bufferedData.substring( end );
1067 
1068                             targetHost = HTTPProxyHost ;
1069                             targetPort = HTTPProxyPort ;
1070                         }
1071 
1072                     }
1073                 }
1074                 else {
1075                     //
1076                     // Change Host: header to point to correct host
1077                     //
1078                     byte[] b1 = new byte[1];
1079 
1080                     buf = new StringBuffer();
1081                     String s1;
1082                     String lastLine = null ;
1083 
1084                     for ( ; ; ) {
1085                         int len ;
1086 
1087                         len = tmpIn1.read(b1, 0, 1);
1088                         if ( len == -1 ) {
1089                             break ;
1090                         }
1091                         s1 = new String( b1 );
1092                         buf.append( s1 );
1093                         if ( b1[0] != '\n' ) {
1094                             continue ;
1095                         }
1096                         // we have a complete line
1097                         String line = buf.toString();
1098 
1099                         buf.setLength(0);
1100                         // check to see if we have found Host: header
1101                         if (line.startsWith("Host: ")) {
1102                             // we need to update the hostname to target host
1103                             String newHost = "Host: " + targetHost + "\r\n";
1104 
1105                             bufferedData = bufferedData.concat(newHost);
1106                             break ;
1107                         }
1108                         // add it to our headers so far
1109                         if (bufferedData == null) {
1110                             bufferedData = line;
1111                         } else {
1112                             bufferedData = bufferedData.concat(line);
1113                         }
1114 
1115                         // failsafe
1116                         if (line.equals("\r\n")) {
1117                             break;
1118                         }
1119                         if ("\n".equals(lastLine) && line.equals("\n")) {
1120                             break ;
1121                         }
1122                         lastLine = line ;
1123                     }
1124                     if ( bufferedData != null ) {
1125                         inputText.append( bufferedData );
1126                         int idx = bufferedData.length() < 50 ? bufferedData.length() : 50;
1127                         s1 = bufferedData.substring( 0, idx );
1128                         int i = s1.indexOf('\n');
1129 
1130                         if ( i > 0 ) {
1131                             s1 = s1.substring(0, i - 1);
1132                         }
1133                         s1 = s1 + "                           " +
1134                                   "                       ";
1135                         s1 = s1.substring(0, 51);
1136                         listener.tableModel.setValueAt( s1, index + 1,
1137                             REQ_COLUMN );
1138                     }
1139                 }
1140 
1141                 if ( targetPort == -1 ) {
1142                     targetPort = 80 ;
1143                 }
1144                 outSocket = new Socket(targetHost, targetPort );
1145 
1146                 tmpIn2  = outSocket.getInputStream();
1147                 tmpOut2 = outSocket.getOutputStream();
1148 
1149                 if ( bufferedData != null ) {
1150                     byte[] b = bufferedData.getBytes();
1151                     tmpOut2.write( b );
1152                     slowLink.pump(b.length);
1153                 }
1154 
1155                 boolean format = listener.xmlFormatBox.isSelected();
1156 
1157 
1158                 //this is the channel to the endpoint
1159                 rr1 = new SocketRR(this, inSocket, tmpIn1, outSocket,
1160                     tmpOut2, inputText, format,
1161                     listener.tableModel, index + 1, "request:", slowLink);
1162                 //create the response slow link from the inbound slow link
1163                 SlowLinkSimulator responseLink = new SlowLinkSimulator(slowLink);
1164                 //this is the channel from the endpoint
1165                 rr2 = new SocketRR( this, outSocket, tmpIn2, inSocket,
1166                     tmpOut1, outputText, format,
1167                     null, 0, "response:", responseLink);
1168 
1169                 while ( rr1 != null || rr2 != null ) {
1170                     // Only loop as long as the connection to the target
1171                     // machine is available - once that's gone we can stop.
1172                     // The old way, loop until both are closed, left us
1173                     // looping forever since no one closed the 1st one.
1174                     // while( !rr2.isDone() )
1175                     if (null != rr1 && rr1.isDone()) {
1176                         if ( index >= 0  && rr2 != null) {
1177                             listener.tableModel.setValueAt(getMessage("resp00", "Resp"),
1178                                 1 + index, STATE_COLUMN );
1179                         }
1180                        rr1 = null;
1181                     }
1182                     if (null != rr2 && rr2.isDone()) {
1183                         if ( index >= 0 && rr1 != null ) {
1184                             listener.tableModel.setValueAt(getMessage("req00", "Req"),
1185                                 1 + index, STATE_COLUMN );
1186                         }
1187                         rr2 = null;
1188                     }
1189 
1190                     //  Thread.sleep( 10 );
1191                     synchronized ( this) {
1192                         this.wait(1000); //Safety just incase we're not told to wake up.
1193                     }
1194                 }
1195 
1196                 //  System.out.println("Done ");
1197                 // rr1.halt();
1198                 // rr2.halt();
1199 
1200 
1201                 active = false ;
1202 
1203                 /*
1204                  if ( inSocket != null ) {
1205                  inSocket.close();
1206                  inSocket = null ;
1207                  }
1208                  outSocket.close();
1209                  outSocket = null ;
1210                  */
1211 
1212                 if ( index >= 0 ) {
1213                     listener.tableModel.setValueAt(getMessage("done00", "Done"),
1214                         1 + index, STATE_COLUMN );
1215 
1216                 }
1217             }
1218             catch ( Exception e ) {
1219                 StringWriter st = new StringWriter();
1220                 PrintWriter  wr = new PrintWriter(st);
1221                 int index = listener.connections.indexOf( this );
1222 
1223                 if ( index >= 0 ) {
1224                     listener.tableModel.setValueAt( getMessage("error00", "Error"), 1 + index, STATE_COLUMN );
1225                 }
1226                 e.printStackTrace(wr);
1227                 wr.close();
1228                 if(outputText!=null) {
1229                     outputText.append( st.toString() );
1230                 } else {
1231                     //something went wrong before we had the output area
1232                     System.out.println(st.toString());
1233                 }
1234                 halt();
1235             }
1236         }
1237 
1238         synchronized void wakeUp() {
1239             this.notifyAll();
1240         }
1241 
1242         public void halt() {
1243             try {
1244                 if ( rr1 != null ) {
1245                     rr1.halt();
1246                 }
1247                 if ( rr2 != null ) {
1248                     rr2.halt();
1249                 }
1250                 if ( inSocket  != null ) {
1251                     inSocket.close();
1252                 }
1253                 inSocket = null ;
1254                 if ( outSocket != null ) {
1255                     outSocket.close();
1256                 }
1257                 outSocket = null ;
1258             }
1259             catch ( Exception e ) {
1260                 e.printStackTrace();
1261             }
1262         }
1263 
1264         public void remove() {
1265             int index = -1;
1266 
1267             try {
1268                 halt();
1269                 index = listener.connections.indexOf( this );
1270                 listener.tableModel.removeRow( index + 1 );
1271                 listener.connections.remove( index );
1272             }
1273             catch ( Exception e ) {
1274                 System.err.println("index:=" + index + this );
1275                 e.printStackTrace();
1276             }
1277         }
1278     }
1279 
1280 
1281     /**
1282      * this is one of the tabbed panels that acts as the actual proxy
1283      */
1284     class Listener extends JPanel {
1285         public  Socket      inputSocket     = null ;
1286         public  Socket      outputSocket    = null ;
1287         public  JTextField  portField       = null ;
1288         public  JTextField  hostField       = null ;
1289         public  JTextField  tPortField      = null ;
1290         public  JCheckBox   isProxyBox      = null ;
1291         public  JButton     stopButton      = null ;
1292         public  JButton     removeButton    = null ;
1293         public  JButton     removeAllButton = null ;
1294         public  JCheckBox   xmlFormatBox    = null ;
1295         public  JButton     saveButton      = null ;
1296         public  JButton     resendButton    = null ;
1297         public  JButton     switchButton    = null ;
1298         public  JButton     closeButton     = null ;
1299         public  JTable      connectionTable = null ;
1300         public  DefaultTableModel  tableModel      = null ;
1301         public  JSplitPane  outPane         = null ;
1302         public  ServerSocket sSocket        = null ;
1303         public  SocketWaiter sw = null ;
1304         public  JPanel      leftPanel       = null ;
1305         public  JPanel      rightPanel      = null ;
1306         public  JTabbedPane notebook        = null ;
1307         public  String      HTTPProxyHost   = null ;
1308         public  int         HTTPProxyPort   = 80 ;
1309         public  int         delayBytes      = 0;
1310         public  int         delayTime       = 0;
1311         public SlowLinkSimulator slowLink;
1312 
1313         public final Vector connections = new Vector();
1314 
1315         /**
1316          * create a listener
1317          * @param _notebook
1318          * @param name
1319          * @param listenPort
1320          * @param host
1321          * @param targetPort
1322          * @param isProxy
1323          * @param slowLink optional reference to a slow connection
1324          */
1325         public Listener(JTabbedPane _notebook, String name,
1326             int listenPort, String host, int targetPort,
1327             boolean isProxy, SlowLinkSimulator slowLink) {
1328             notebook = _notebook ;
1329             if ( name == null ) {
1330                 name = getMessage("port01", "Port") + " " + listenPort ;
1331             }
1332             //set the slow link to the passed down link
1333             if(slowLink!=null) {
1334                 this.slowLink=slowLink;
1335             } else {
1336                 //or make up a no-op one.
1337                 this.slowLink=new SlowLinkSimulator(0,0);
1338             }
1339             this.setLayout( new BorderLayout() );
1340 
1341             // 1st component is just a row of labels and 1-line entry fields
1342             /////////////////////////////////////////////////////////////////////
1343             JPanel top = new JPanel();
1344 
1345             top.setLayout( new BoxLayout(top, BoxLayout.X_AXIS) );
1346             top.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
1347             final String start = getMessage("start00", "Start");
1348 
1349             top.add( stopButton = new JButton( start ) );
1350             top.add( Box.createRigidArea(new Dimension(5, 0)) );
1351             top.add( new JLabel( "  " + getMessage("listenPort01", "Listen Port:") + " ", SwingConstants.RIGHT ) );
1352             top.add( portField = new JTextField( "" + listenPort, 4 ) );
1353             top.add( new JLabel( "  " + getMessage("host00", "Host:"), SwingConstants.RIGHT ) );
1354             top.add( hostField = new JTextField( host, 30 ) );
1355             top.add( new JLabel( "  " + getMessage("port02", "Port:") + " ", SwingConstants.RIGHT ) );
1356             top.add( tPortField = new JTextField( "" + targetPort, 4 ) );
1357             top.add( Box.createRigidArea(new Dimension(5, 0)) );
1358             top.add( isProxyBox = new JCheckBox(getMessage("proxy00", "Proxy")) );
1359 
1360             isProxyBox.addChangeListener( new BasicButtonListener(isProxyBox) {
1361                     public void stateChanged(ChangeEvent event) {
1362                         JCheckBox box = (JCheckBox) event.getSource();
1363                         boolean state = box.isSelected();
1364 
1365                         tPortField.setEnabled( !state );
1366                         hostField.setEnabled( !state );
1367                     }
1368                 }
1369             );
1370 
1371             isProxyBox.setSelected(isProxy);
1372 
1373             portField.setEditable(false);
1374             portField.setMaximumSize(new Dimension(50, Short.MAX_VALUE) );
1375             hostField.setEditable(false);
1376             hostField.setMaximumSize(new Dimension(85, Short.MAX_VALUE) );
1377             tPortField.setEditable(false);
1378             tPortField.setMaximumSize(new Dimension(50, Short.MAX_VALUE) );
1379 
1380             stopButton.addActionListener( new ActionListener() {
1381                     public void actionPerformed(ActionEvent event) {
1382                         if ( getMessage("stop00", "Stop").equals(event.getActionCommand()) ) {
1383                             stop();
1384                         }
1385                         if ( start.equals(event.getActionCommand()) ) {
1386                             start();
1387                         }
1388                     }
1389                 }
1390             );
1391 
1392             this.add( top, BorderLayout.NORTH );
1393 
1394             // 2nd component is a split pane with a table on the top
1395             // and the request/response text areas on the bottom
1396             /////////////////////////////////////////////////////////////////////
1397 
1398             tableModel = new DefaultTableModel(new String[] {
1399                     getMessage("state00", "State"),
1400                     getMessage("time00", "Time"),
1401                     getMessage("requestHost00", "Request Host"),
1402                     getMessage("targetHost", "Target Host"),
1403                     getMessage("request00", "Request...")
1404                 } , 0 );
1405 
1406             connectionTable = new JTable(1, 2);
1407             connectionTable.setModel( tableModel );
1408             connectionTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
1409             // Reduce the STATE column and increase the REQ column
1410             TableColumn col ;
1411 
1412             col = connectionTable.getColumnModel().getColumn(STATE_COLUMN);
1413             col.setMaxWidth( col.getPreferredWidth() / 2 );
1414             col = connectionTable.getColumnModel().getColumn(REQ_COLUMN);
1415             col.setPreferredWidth( col.getPreferredWidth() * 2 );
1416 
1417 
1418             ListSelectionModel sel = connectionTable.getSelectionModel();
1419 
1420             sel.addListSelectionListener( new ListSelectionListener() {
1421                     public void valueChanged(ListSelectionEvent event) {
1422                         if (event.getValueIsAdjusting()) {
1423                             return ;
1424                         }
1425                         ListSelectionModel m = (ListSelectionModel) event.getSource();
1426                         int divLoc = outPane.getDividerLocation();
1427 
1428                         if (m.isSelectionEmpty()) {
1429                             setLeft( new JLabel(" " + getMessage("wait00", "Waiting for Connection...") ) );
1430                             setRight( new JLabel("") );
1431                             removeButton.setEnabled(false);
1432                             removeAllButton.setEnabled(false);
1433                             saveButton.setEnabled(false);
1434                             resendButton.setEnabled(false);
1435                         }
1436                         else {
1437                             int row = m.getLeadSelectionIndex();
1438 
1439                             if ( row == 0 ) {
1440                                 if ( connections.size() == 0 ) {
1441                                     setLeft(new JLabel(" " + getMessage("wait00", "Waiting for connection...")));
1442                                     setRight(new JLabel(""));
1443                                     removeButton.setEnabled(false);
1444                                     removeAllButton.setEnabled(false);
1445                                     saveButton.setEnabled(false);
1446                                     resendButton.setEnabled(false);
1447                                 }
1448                                 else {
1449                                     Connection conn = (Connection) connections.lastElement();
1450 
1451                                     setLeft( conn.inputScroll );
1452                                     setRight( conn.outputScroll );
1453                                     removeButton.setEnabled(false);
1454                                     removeAllButton.setEnabled(true);
1455                                     saveButton.setEnabled(true);
1456                                     resendButton.setEnabled(true);
1457                                 }
1458                             }
1459                             else {
1460                                 Connection conn = (Connection) connections.get(row - 1);
1461 
1462                                 setLeft( conn.inputScroll );
1463                                 setRight( conn.outputScroll );
1464                                 removeButton.setEnabled(true);
1465                                 removeAllButton.setEnabled(true);
1466                                 saveButton.setEnabled(true);
1467                                 resendButton.setEnabled(true);
1468                             }
1469                         }
1470                         outPane.setDividerLocation(divLoc);
1471                     }
1472                 }
1473             );
1474             tableModel.addRow( new Object[] {
1475                     "---", getMessage("mostRecent00", "Most Recent"), "---", "---", "---"
1476                 }
1477             );
1478 
1479             JPanel  tablePane = new JPanel();
1480 
1481             tablePane.setLayout( new BorderLayout() );
1482 
1483             JScrollPane tableScrollPane = new JScrollPane( connectionTable );
1484 
1485             tablePane.add( tableScrollPane, BorderLayout.CENTER );
1486             JPanel buttons = new JPanel();
1487 
1488             buttons.setLayout( new BoxLayout(buttons, BoxLayout.X_AXIS) );
1489             buttons.setBorder( BorderFactory.createEmptyBorder(5, 5, 5, 5) );
1490             final String removeSelected = getMessage("removeSelected00", "Remove Selected");
1491 
1492             buttons.add( removeButton = new JButton(removeSelected) );
1493             buttons.add( Box.createRigidArea(new Dimension(5, 0)) );
1494             final String removeAll = getMessage("removeAll00", "Remove All");
1495 
1496             buttons.add( removeAllButton = new JButton(removeAll) );
1497             tablePane.add( buttons, BorderLayout.SOUTH );
1498 
1499             removeButton.setEnabled( false );
1500             removeButton.addActionListener( new ActionListener() {
1501                     public void actionPerformed(ActionEvent event) {
1502                         if ( removeSelected.equals(event.getActionCommand()) ) {
1503                             remove();
1504                         }
1505                     }
1506                 }
1507             );
1508 
1509             removeAllButton.setEnabled( false );
1510             removeAllButton.addActionListener( new ActionListener() {
1511                     public void actionPerformed(ActionEvent event) {
1512                         if ( removeAll.equals(event.getActionCommand()) ) {
1513                             removeAll();
1514                         }
1515                     }
1516                 }
1517             );
1518 
1519             // Add Response Section
1520             /////////////////////////////////////////////////////////////////////
1521             JPanel     pane2     = new JPanel();
1522 
1523             pane2.setLayout( new BorderLayout() );
1524 
1525             leftPanel = new JPanel();
1526             leftPanel.setAlignmentX( Component.LEFT_ALIGNMENT );
1527             leftPanel.setLayout( new BoxLayout(leftPanel, BoxLayout.Y_AXIS) );
1528             leftPanel.add( new JLabel("  " + getMessage("request01", "Request")) );
1529             leftPanel.add( new JLabel(" " + getMessage("wait01", "Waiting for connection") ));
1530 
1531             rightPanel = new JPanel();
1532             rightPanel.setLayout( new BoxLayout(rightPanel, BoxLayout.Y_AXIS) );
1533             rightPanel.add( new JLabel("  " + getMessage("response00", "Response")) );
1534             rightPanel.add( new JLabel("") );
1535 
1536             outPane = new JSplitPane(0, leftPanel, rightPanel );
1537             outPane.setDividerSize(4);
1538             pane2.add( outPane, BorderLayout.CENTER );
1539 
1540             JPanel bottomButtons = new JPanel();
1541 
1542             bottomButtons.setLayout( new BoxLayout(bottomButtons, BoxLayout.X_AXIS));
1543             bottomButtons.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
1544             bottomButtons.add( xmlFormatBox = new JCheckBox( getMessage("xmlFormat00", "XML Format") ) );
1545             bottomButtons.add( Box.createRigidArea(new Dimension(5, 0)) );
1546             final String save = getMessage("save00", "Save");
1547 
1548             bottomButtons.add( saveButton = new JButton( save ) );
1549             bottomButtons.add( Box.createRigidArea(new Dimension(5, 0)) );
1550             final String resend = getMessage("resend00", "Resend");
1551 
1552             bottomButtons.add( resendButton = new JButton( resend ) );
1553             bottomButtons.add( Box.createRigidArea(new Dimension(5, 0)) );
1554             final String switchStr = getMessage("switch00", "Switch Layout");
1555 
1556             bottomButtons.add( switchButton = new JButton( switchStr ) );
1557             bottomButtons.add( Box.createHorizontalGlue() );
1558             final String close = getMessage("close00", "Close");
1559 
1560             bottomButtons.add( closeButton = new JButton( close ) );
1561             pane2.add( bottomButtons, BorderLayout.SOUTH );
1562 
1563             saveButton.setEnabled( false );
1564             saveButton.addActionListener( new ActionListener() {
1565                     public void actionPerformed(ActionEvent event) {
1566                         if ( save.equals(event.getActionCommand()) ) {
1567                             save();
1568                         }
1569                     }
1570                 }
1571             );
1572 
1573             resendButton.setEnabled( false );
1574             resendButton.addActionListener( new ActionListener() {
1575                     public void actionPerformed(ActionEvent event) {
1576                         if ( resend.equals(event.getActionCommand()) ) {
1577                             resend();
1578                         }
1579                     }
1580                 }
1581             );
1582 
1583             switchButton.addActionListener( new ActionListener() {
1584                     public void actionPerformed(ActionEvent event) {
1585                         if (switchStr.equals(event.getActionCommand()) ) {
1586                             int v = outPane.getOrientation();
1587 
1588                             if ( v == 0 ) {
1589                                 // top/bottom
1590                                 outPane.setOrientation(1);
1591                             }
1592                             else  {
1593                                 // left/right
1594                                 outPane.setOrientation(0);
1595                             }
1596                             outPane.setDividerLocation(0.5);
1597                         }
1598                     }
1599                 }
1600             );
1601 
1602             closeButton.addActionListener( new ActionListener() {
1603                     public void actionPerformed(ActionEvent event) {
1604                         if (close.equals(event.getActionCommand()) ) {
1605                             close();
1606                         }
1607                     }
1608                 }
1609             );
1610 
1611             JSplitPane  pane1 = new JSplitPane( 0 );
1612 
1613             pane1.setDividerSize(4);
1614             pane1.setTopComponent( tablePane );
1615             pane1.setBottomComponent( pane2 );
1616             pane1.setDividerLocation( 150 );
1617             this.add( pane1, BorderLayout.CENTER );
1618 
1619             //
1620             ////////////////////////////////////////////////////////////////////
1621             sel.setSelectionInterval(0, 0);
1622             outPane.setDividerLocation( 150 );
1623             notebook.addTab( name, this );
1624             start();
1625         }
1626 
1627         public void setLeft(Component left) {
1628             leftPanel.removeAll();
1629             leftPanel.add(left);
1630         }
1631 
1632         public void setRight(Component right) {
1633             rightPanel.removeAll();
1634             rightPanel.add(right);
1635         }
1636 
1637         public void start() {
1638             int  port = Integer.parseInt( portField.getText() );
1639 
1640             portField.setText( "" + port );
1641             int i = notebook.indexOfComponent( this );
1642 
1643             notebook.setTitleAt( i, getMessage("port01", "Port") + " " + port );
1644 
1645             int  tmp = Integer.parseInt( tPortField.getText() );
1646 
1647             tPortField.setText( "" + tmp );
1648 
1649             sw = new SocketWaiter( this, port );
1650             stopButton.setText( getMessage("stop00", "Stop") );
1651 
1652             portField.setEditable(false);
1653             hostField.setEditable(false);
1654             tPortField.setEditable(false);
1655             isProxyBox.setEnabled(false);
1656         }
1657 
1658         public void close() {
1659             stop();
1660             notebook.remove( this );
1661         }
1662 
1663         public void stop() {
1664             try {
1665                 for ( int i = 0 ; i < connections.size() ; i++ ) {
1666                     Connection conn = (Connection) connections.get( i );
1667 
1668                     conn.halt();
1669                 }
1670                 sw.halt();
1671                 stopButton.setText( getMessage("start00", "Start") );
1672                 portField.setEditable(true);
1673                 hostField.setEditable(true);
1674                 tPortField.setEditable(true);
1675                 isProxyBox.setEnabled(true);
1676             }
1677             catch ( Exception e ) {
1678                 e.printStackTrace();
1679             }
1680         }
1681 
1682         public void remove() {
1683             ListSelectionModel lsm = connectionTable.getSelectionModel();
1684             int bot = lsm.getMinSelectionIndex();
1685             int top = lsm.getMaxSelectionIndex();
1686 
1687             for ( int i = top ; i >= bot ; i-- ) {
1688                 ((Connection) connections.get(i - 1)).remove();
1689             }
1690             if ( bot > connections.size() ) {
1691                 bot = connections.size();
1692             }
1693             lsm.setSelectionInterval(bot, bot);
1694         }
1695 
1696         public void removeAll() {
1697             ListSelectionModel lsm = connectionTable.getSelectionModel();
1698             lsm.clearSelection();
1699             while ( connections.size() > 0 ) {
1700                 ((Connection) connections.get(0)).remove();
1701             }
1702 
1703             lsm.setSelectionInterval(0, 0);
1704         }
1705 
1706         public void save() {
1707             JFileChooser  dialog = new JFileChooser( "." );
1708             int rc = dialog.showSaveDialog( this );
1709 
1710             if ( rc == JFileChooser.APPROVE_OPTION ) {
1711                 try {
1712                     File             file = dialog.getSelectedFile();
1713                     FileOutputStream out  = new FileOutputStream( file );
1714 
1715                     ListSelectionModel lsm = connectionTable.getSelectionModel();
1716 
1717                     rc = lsm.getLeadSelectionIndex();
1718 
1719                     int n = 0;
1720                     for (Iterator i = connections.iterator();i.hasNext();n++) {
1721                       Connection conn = (Connection)i.next();
1722                       if (lsm.isSelectedIndex(n + 1) ||
1723                                    (!(i.hasNext()) && lsm.getLeadSelectionIndex() == 0)) {
1724                         rc = Integer.parseInt( portField.getText() );
1725                         out.write("\n==============\n".getBytes());
1726                         out.write( (new String(getMessage("listenPort01", "Listen Port:") + " " + rc + "\n" )).getBytes() );
1727                         out.write( (new String(getMessage("targetHost01", "Target Host:") + " " + hostField.getText() +
1728                                     "\n" )).getBytes() );
1729                         rc = Integer.parseInt( tPortField.getText() );
1730                         out.write( (new String(getMessage("targetPort01", "Target Port:") + " " + rc + "\n" )).getBytes() );
1731 
1732                         out.write( (new String("==== " + getMessage("request01", "Request") + " ====\n" )).getBytes() );
1733                         out.write( conn.inputText.getText().getBytes() );
1734 
1735                         out.write( (new String("==== " + getMessage("response00", "Response") + " ====\n" )).getBytes() );
1736                         out.write( conn.outputText.getText().getBytes() );
1737                         out.write("\n==============\n".getBytes());
1738                       }
1739                     }
1740 
1741                     out.close();
1742                 }
1743                 catch ( Exception e ) {
1744                     e.printStackTrace();
1745                 }
1746             }
1747         }
1748 
1749         public void resend() {
1750             int rc ;
1751 
1752             try {
1753                 ListSelectionModel lsm = connectionTable.getSelectionModel();
1754 
1755                 rc = lsm.getLeadSelectionIndex();
1756                 if ( rc == 0 ) {
1757                     rc = connections.size();
1758                 }
1759                 Connection conn = (Connection) connections.get( rc - 1 );
1760 
1761                 if ( rc > 0 ) {
1762                     lsm.clearSelection();
1763                     lsm.setSelectionInterval(0, 0);
1764                 }
1765 
1766                 InputStream in = null ;
1767                 String      text = conn.inputText.getText();
1768 
1769                 // Fix Content-Length HTTP headers
1770                 if ( text.startsWith("POST ") || text.startsWith("GET ") ) {
1771                     System.err.println("IN CL" );
1772                     int         pos1, pos2, pos3 ;
1773                     String      body, headers, headers1, header2 ;
1774 
1775                     pos3 = text.indexOf( "\n\n" );
1776                     if ( pos3 == -1 ) {
1777                         pos3 = text.indexOf( "\r\n\r\n" );
1778                         if ( pos3 != -1 ) {
1779                             pos3 = pos3 + 4 ;
1780                         }
1781                     }
1782                     else {
1783                         pos3 += 2 ;
1784                     }
1785 
1786                     headers = text.substring( 0, pos3 );
1787 
1788                     pos1 = headers.indexOf( "Content-Length:" );
1789                     System.err.println("pos1: " + pos1 );
1790                     System.err.println("pos3: " + pos3 );
1791                     if ( pos1 != -1 ) {
1792                         int  newLen = text.length() - pos3 ;
1793 
1794                         pos2 = headers.indexOf( "\n", pos1 );
1795 
1796                         System.err.println("CL: " + newLen );
1797                         System.err.println("Hdrs: '" + headers + "'" );
1798                         System.err.println("subTEXT: '" +
1799                             text.substring(pos3, pos3 + newLen) + "'");
1800                         text = headers.substring(0, pos1) +
1801                         "Content-Length: " + newLen + "\n" +
1802                         headers.substring(pos2 + 1) +
1803                         text.substring(pos3) ;
1804                         System.err.println("\nTEXT: '" + text + "'" );
1805                     }
1806                 }
1807 
1808                 in = new ByteArrayInputStream( text.getBytes() );
1809                 new Connection( this, in );
1810             }
1811             catch ( Exception e ) {
1812                 e.printStackTrace();
1813             }
1814         }
1815     }
1816 
1817 
1818     public tcpmon(int listenPort, String targetHost, int targetPort) {
1819         super ( getMessage("tcpmon00", "TCPMonitor") );
1820 
1821         notebook = new JTabbedPane();
1822         this.getContentPane().add( notebook );
1823 
1824         new AdminPage( notebook, getMessage("admin00", "Admin") );
1825 
1826         if ( listenPort != 0 ) {
1827             Listener l = null ;
1828 
1829             if ( targetHost == null ) {
1830                 l = new Listener( notebook, null, listenPort,
1831                     targetHost, targetPort, true, null);
1832             } else {
1833                 l = new Listener( notebook, null, listenPort,
1834                     targetHost, targetPort, false, null);
1835             }
Rate1836             notebook.setSelectedIndex( 1 );
1837 
1838             l.HTTPProxyHost = System.getProperty( "http.proxyHost" );
1839             if ( l.HTTPProxyHost != null && l.HTTPProxyHost.equals("") ) {
1840                 l.HTTPProxyHost = null ;
1841             }
1842 
1843             if ( l.HTTPProxyHost != null ) {
1844                 String tmp = System.getProperty( "http.proxyPort" );
1845 
1846                 if ( tmp != null && tmp.equals("") ) {
1847                     tmp = null ;
1848                 }
1849                 if ( tmp == null ) {
1850                     l.HTTPProxyPort = 80 ;
1851                 } else {
1852                     l.HTTPProxyPort = Integer.parseInt( tmp );
1853                 }
1854             }
1855         }
1856 
1857         this.pack();
1858         this.setSize( 600, 600 );
1859         this.setVisible( true );
1860     }
1861 
1862     protected void processWindowEvent(WindowEvent event) {
1863         switch ( event.getID() ) {
1864         case WindowEvent.WINDOW_CLOSING:
1865             exit();
1866             break ;
1867 
1868         default:
1869             super.processWindowEvent(event);
1870             break ;
1871         }
1872     }
1873 
1874     private void exit() {
1875         System.exit(0);
1876     }
1877 
1878     public void setInputPort(int port) {
1879     }
1880 
1881     public void setOutputHostPort(char hostName, int port) {
1882     }
1883 
1884     /**
1885      * set up the L&F
1886      */
1887     private static void setupLookAndFeel(boolean nativeLookAndFeel) throws Exception {
1888         UIManager.setLookAndFeel(
1889                 nativeLookAndFeel ? UIManager.getSystemLookAndFeelClassName()
1890                     : UIManager.getCrossPlatformLookAndFeelClassName());
1891         //JFrame.setDefaultLookAndFeelDecorated(true);
1892     }
1893     /**
1894      * this is our main method
1895      * @param args
1896      */
1897     public static void main(String[] args) {
1898         try {
1899             //switch between swing L&F here
1900             setupLookAndFeel(true);
1901             if ( args.length == 3 ) {
1902                 int p1 = Integer.parseInt( args[0] );
1903                 int p2 = Integer.parseInt( args[2] );
1904 
1905                 new tcpmon( p1, args[1], p2 );
1906             }
1907             else if ( args.length == 1 ) {
1908                 int p1 = Integer.parseInt( args[0] );
1909 
1910                 new tcpmon( p1, null, 0 );
1911             }
1912             else if ( args.length != 0 ) {
1913                 System.err.println( getMessage("usage00", "Usage:")
1914                         + " tcpmon [listenPort targetHost targetPort]\n");
1915             }
1916             else {
1917                 new tcpmon(0, null, 0);
1918             }
1919         }
1920         catch ( Throwable exp ) {
1921             exp.printStackTrace();
1922         }
1923     }
1924 
1925     // Message resource bundle.
1926     private static ResourceBundle messages = null;
1927 
1928     /**
1929      * Get the message with the given key.  There are no arguments for this message.
1930      */
1931     public static String getMessage(String key, String defaultMsg) {
1932         try {
1933             if (messages == null) {
1934                 initializeMessages();
1935             }
1936             return messages.getString(key);
1937         } catch (Throwable t) {
1938             // If there is any problem whatsoever getting the internationalized
1939             // message, return the default.
1940             return defaultMsg;
1941         }
1942     } // getMessage
1943 
1944     /**
1945      * Load the resource bundle messages from the properties file.  This is ONLY done when it is
1946      * needed.  If no messages are printed (for example, only Wsdl2java is being run in non-
1947      * verbose mode) then there is no need to read the properties file.
1948      */
1949     private static void initializeMessages() {
1950         messages = ResourceBundle.getBundle("org.apache.axis.utils.tcpmon");
1951     } // initializeMessages
1952 
1953     /**
1954      * a text field with a restricted set of characters
1955      */
1956     static class RestrictedTextField extends JTextField {
1957         protected String validText;
1958 
1959         public RestrictedTextField(String validText) {
1960             setValidText(validText);
1961         }
1962 
1963         public RestrictedTextField(int columns, String validText) {
1964             super(columns);
1965             setValidText(validText);
1966         }
1967 
1968         public RestrictedTextField(String text, String validText) {
1969             super(text);
1970             setValidText(validText);
1971         }
1972 
1973         public RestrictedTextField(String text, int columns, String validText) {
1974             super(text, columns);
1975             setValidText(validText);
1976         }
1977 
1978         private void setValidText(String validText) {
1979             this.validText = validText;
1980         }
1981 
1982         /**
1983          * fascinatingly, this method is called in the super() constructor,
1984          * meaning before we are fully initialized. C++ doesnt actually permit
1985          * such a situation, but java clearly does...
1986          * @return a new document
1987          */
1988         public Document createDefaultModel() {
1989             return new RestrictedDocument();
1990         }
1991 
1992         /**
1993          * this class strips out invaid chars
1994          */
1995         class RestrictedDocument extends PlainDocument {
1996 
1997 
1998             /**
1999              * Constructs a plain text document.  A default model using
2000              * <code>GapContent</code> is constructed and set.
2001              */
2002             public RestrictedDocument() {
2003 
2004             }
2005 
2006             /**
2007              * add a string; only those chars in the valid text list are allowed
2008              * @param offset
2009              * @param string
2010              * @param attributes
2011              * @throws BadLocationException
2012              */
2013             public void insertString(int offset, String string, AttributeSet attributes)
2014                     throws BadLocationException {
2015 
2016                 if (string == null) {
2017                     return;
2018                 }
2019                 int len = string.length();
2020                 StringBuffer buffer = new StringBuffer(string.length());
2021                 for (int i = 0; i < len; i++) {
2022                     char ch = string.charAt(i);
2023                     if (validText.indexOf(ch) >= 0) {
2024                         buffer.append(ch);
2025                     }
2026                 }
2027                 super.insertString(offset, new String(buffer), attributes);
2028             }
2029         } //end class NumericDocument
2030     }
2031 
2032     /**
2033      * because we cant use Java1.4's JFormattedTextField, here is
2034      * a class that accepts numbers only
2035      */
2036     static class NumberField extends RestrictedTextField {
2037 
2038         private static final String VALID_TEXT = "0123456789";
2039 
2040         /**
2041          * Constructs a new <code>TextField</code>.  A default model is created,
2042          * the initial string is <code>null</code>,
2043          * and the number of columns is set to 0.
2044          */
2045         public NumberField() {
2046             super(VALID_TEXT);
2047         }
2048 
2049         /**
2050          * Constructs a new empty <code>TextField</code> with the specified
2051          * number of columns.
2052          * A default model is created and the initial string is set to
2053          * <code>null</code>.
2054          *
2055          * @param columns  the number of columns to use to calculate
2056          *   the preferred width; if columns is set to zero, the
2057          *   preferred width will be whatever naturally results from
2058          *   the component implementation
2059          */
2060         public NumberField(int columns) {
2061             super(columns, VALID_TEXT);
2062         }
2063 
2064 
2065         /**
2066          * get the int value of a field, any invalid (non int) field returns
2067          * the default
2068          * @param def default value
2069          * @return the field contents
2070          */
2071         public int getValue(int def) {
2072             int result = def;
2073             String text = getText();
2074             if (text != null && text.length() != 0) {
2075                 try {
2076                     result = Integer.parseInt(text);
2077                 } catch (NumberFormatException e) {
2078 
2079                 }
2080             }
2081             return result;
2082         }
2083 
2084         /**
2085          * set the text to a numeric value
2086          * @param value number to assign
2087          */
2088         public void setValue(int value) {
2089             setText(Integer.toString(value));
2090         }
2091 
2092     } //end class NumericTextField
2093 
2094     /**
2095      * hostname fields
2096      */
2097     static class HostnameField extends RestrictedTextField {
2098         //list of valid chars in a hostname
2099         private static final String VALID_TEXT =
2100                 "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWZYZ-.";
2101 
2102         public HostnameField(int columns) {
2103             super(columns, VALID_TEXT);
2104         }
2105 
2106         public HostnameField() {
2107             super(VALID_TEXT);
2108         }
2109     }
2110 
2111 }

            
All Examples in File:
Example
Line
Rating (found
useful by...)
461 0% of 0
1836 0% of 0