KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > axis > utils > TCPInterceptor


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  *
5  * Copyright (c) 2001 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.apache.axis.utils;
56
57
58 import javax.swing.*;
59 import javax.swing.border.TitledBorder JavaDoc;
60 import javax.swing.event.*;
61 import javax.swing.plaf.basic.BasicButtonListener JavaDoc;
62 import javax.swing.table.*;
63 import java.awt.*;
64 import java.awt.event.*;
65 import java.io.*;
66 import java.net.*;
67 import java.text.DateFormat JavaDoc;
68 import java.text.SimpleDateFormat JavaDoc;
69 import java.util.*;
70
71
72 /**
73  * @author Doug Davis (dug@us.ibm.com)
74  * @author Chris Betts (chris.betts@ca.com) - added interceptor capability to TCPMon program; also cleaned some stuff up.
75  */

76
77 public class TCPInterceptor extends JFrame
78 {
79     private JTabbedPane notebook = null;
80
81     private static int STATE_COLUMN = 0;
82     private static int TIME_COLUMN = 1;
83     private static int INHOST_COLUMN = 2;
84     private static int OUTHOST_COLUMN = 3;
85     private static int REQ_COLUMN = 4;
86
87     class AdminPage extends JPanel
88     {
89         public JRadioButton listenerButton, proxyButton;
90         public JLabel hostLabel, tportLabel;
91         public JTextField port, host, tport;
92         public JTabbedPane noteb;
93         public JCheckBox HTTPProxyBox;
94         public JTextField HTTPProxyHost, HTTPProxyPort;
95         public JLabel HTTPProxyHostLabel, HTTPProxyPortLabel;
96
97         public AdminPage(JTabbedPane notebook, String JavaDoc name)
98         {
99             JPanel mainPane = null;
100             JButton addButton = null;
101
102             this.setLayout(new BorderLayout());
103             noteb = notebook;
104
105             GridBagLayout layout = new GridBagLayout();
106             GridBagConstraints c = new GridBagConstraints();
107
108             mainPane = new JPanel(layout);
109
110             c.anchor = GridBagConstraints.WEST;
111             c.gridwidth = GridBagConstraints.REMAINDER;
112             mainPane.add(new JLabel(getMessage("newTCP00", "Create a new TCP/IP Monitor...") + " "), c);
113
114             // Add some blank space
115
mainPane.add(Box.createRigidArea(new Dimension(1, 5)), c);
116
117             // The listener info
118
///////////////////////////////////////////////////////////////////
119
JPanel tmpPanel = new JPanel(new GridBagLayout());
120
121             c.anchor = GridBagConstraints.WEST;
122             c.gridwidth = 1;
123             tmpPanel.add(new JLabel(getMessage("listenPort00", "Listen Port #") + " "), c);
124
125             c.anchor = GridBagConstraints.WEST;
126             c.gridwidth = GridBagConstraints.REMAINDER;
127             tmpPanel.add(port = new JTextField(4), c);
128
129             mainPane.add(tmpPanel, c);
130
131             mainPane.add(Box.createRigidArea(new Dimension(1, 5)), c);
132
133             // Group for the radio buttons
134
ButtonGroup btns = new ButtonGroup();
135
136             c.anchor = GridBagConstraints.WEST;
137             c.gridwidth = GridBagConstraints.REMAINDER;
138             mainPane.add(new JLabel(getMessage("actAs00", "Act as a...")), c);
139
140             // Target Host/Port section
141
///////////////////////////////////////////////////////////////////
142
c.anchor = GridBagConstraints.WEST;
143             c.gridwidth = GridBagConstraints.REMAINDER;
144
145             final String JavaDoc listener = getMessage("listener00", "Listener");
146
147             mainPane.add(listenerButton = new JRadioButton(listener), c);
148             btns.add(listenerButton);
149             listenerButton.setSelected(true);
150
151             listenerButton.addActionListener(new ActionListener()
152             {
153                 public void actionPerformed(ActionEvent event)
154                 {
155                     if (listener.equals(event.getActionCommand()))
156                     {
157                         boolean state = listenerButton.isSelected();
158
159                         tport.setEnabled(state);
160                         host.setEnabled(state);
161                         hostLabel.setForeground(state ? Color.black : Color.gray);
162                         tportLabel.setForeground(state ? Color.black : Color.gray);
163                     }
164                 }
165             }
166             );
167
168             c.anchor = GridBagConstraints.WEST;
169             c.gridwidth = 1;
170             mainPane.add(Box.createRigidArea(new Dimension(25, 0)));
171             mainPane.add(hostLabel = new JLabel(getMessage("targetHostname00", "Target Hostname") + " "), c);
172
173             c.anchor = GridBagConstraints.WEST;
174             c.gridwidth = GridBagConstraints.REMAINDER;
175             mainPane.add(host = new JTextField(30), c);
176
177             c.anchor = GridBagConstraints.WEST;
178             c.gridwidth = 1;
179             mainPane.add(Box.createRigidArea(new Dimension(25, 0)));
180             mainPane.add(tportLabel = new JLabel(getMessage("targetPort00", "Target Port #") + " "), c);
181
182             c.anchor = GridBagConstraints.WEST;
183             c.gridwidth = GridBagConstraints.REMAINDER;
184             mainPane.add(tport = new JTextField(4), c);
185
186             // Act as proxy section
187
///////////////////////////////////////////////////////////////////
188
c.anchor = GridBagConstraints.WEST;
189             c.gridwidth = GridBagConstraints.REMAINDER;
190             final String JavaDoc proxy = getMessage("proxy00", "Proxy");
191
192             mainPane.add(proxyButton = new JRadioButton(proxy), c);
193             btns.add(proxyButton);
194
195             proxyButton.addActionListener(new ActionListener()
196             {
197                 public void actionPerformed(ActionEvent event)
198                 {
199                     if (proxy.equals(event.getActionCommand()))
200                     {
201                         boolean state = proxyButton.isSelected();
202
203                         tport.setEnabled(!state);
204                         host.setEnabled(!state);
205                         hostLabel.setForeground(state ? Color.gray : Color.black);
206                         tportLabel.setForeground(state ? Color.gray : Color.black);
207                     }
208                 }
209             }
210             );
211
212             // Spacer
213
/////////////////////////////////////////////////////////////////
214
c.anchor = GridBagConstraints.WEST;
215             c.gridwidth = GridBagConstraints.REMAINDER;
216             mainPane.add(Box.createRigidArea(new Dimension(1, 10)), c);
217
218             // Options section
219
///////////////////////////////////////////////////////////////////
220
JPanel opts = new JPanel(new GridBagLayout());
221
222             opts.setBorder(new TitledBorder JavaDoc(getMessage("options00", "Options")));
223             c.anchor = GridBagConstraints.WEST;
224             c.gridwidth = GridBagConstraints.REMAINDER;
225             mainPane.add(opts, c);
226
227             // HTTP Proxy Support section
228
///////////////////////////////////////////////////////////////////
229
c.anchor = GridBagConstraints.WEST;
230             c.gridwidth = GridBagConstraints.REMAINDER;
231             final String JavaDoc proxySupport = getMessage("proxySupport00", "HTTP Proxy Support");
232
233             opts.add(HTTPProxyBox = new JCheckBox(proxySupport), c);
234
235             c.anchor = GridBagConstraints.WEST;
236             c.gridwidth = 1;
237             opts.add(HTTPProxyHostLabel = new JLabel(getMessage("hostname00", "Hostname") + " "), c);
238             HTTPProxyHostLabel.setForeground(Color.gray);
239
240             c.anchor = GridBagConstraints.WEST;
241             c.gridwidth = GridBagConstraints.REMAINDER;
242             opts.add(HTTPProxyHost = new JTextField(30), c);
243             HTTPProxyHost.setEnabled(false);
244
245             c.anchor = GridBagConstraints.WEST;
246             c.gridwidth = 1;
247             opts.add(HTTPProxyPortLabel = new JLabel(getMessage("port00", "Port #") + " "), c);
248             HTTPProxyPortLabel.setForeground(Color.gray);
249
250             c.anchor = GridBagConstraints.WEST;
251             c.gridwidth = GridBagConstraints.REMAINDER;
252             opts.add(HTTPProxyPort = new JTextField(4), c);
253             HTTPProxyPort.setEnabled(false);
254
255             HTTPProxyBox.addActionListener(new ActionListener()
256             {
257                 public void actionPerformed(ActionEvent event)
258                 {
259                     if (proxySupport.equals(event.getActionCommand()))
260                     {
261                         boolean b = HTTPProxyBox.isSelected();
262                         Color color = b ? Color.black : Color.gray;
263
264                         HTTPProxyHost.setEnabled(b);
265                         HTTPProxyPort.setEnabled(b);
266                         HTTPProxyHostLabel.setForeground(color);
267                         HTTPProxyPortLabel.setForeground(color);
268                     }
269                 }
270                 ;
271             }
272             );
273
274             // Set default proxy values...
275
String JavaDoc tmp = System.getProperty("http.proxyHost");
276
277             if (tmp != null && tmp.equals(""))
278                 tmp = null;
279
280             HTTPProxyBox.setSelected(tmp != null);
281             HTTPProxyHost.setEnabled(tmp != null);
282             HTTPProxyPort.setEnabled(tmp != null);
283             HTTPProxyHostLabel.setForeground(tmp != null ? Color.black : Color.gray);
284             HTTPProxyPortLabel.setForeground(tmp != null ? Color.black : Color.gray);
285
286             if (tmp != null)
287             {
288                 HTTPProxyBox.setSelected(true);
289                 HTTPProxyHost.setText(tmp);
290                 tmp = System.getProperty("http.proxyPort");
291                 if (tmp != null && tmp.equals("")) tmp = null;
292                 if (tmp == null) tmp = "80";
293                 HTTPProxyPort.setText(tmp);
294             }
295
296             // Spacer
297
//////////////////////////////////////////////////////////////////
298
mainPane.add(Box.createRigidArea(new Dimension(1, 10)), c);
299
300             // ADD Button
301
///////////////////////////////////////////////////////////////////
302
c.anchor = GridBagConstraints.WEST;
303             c.gridwidth = GridBagConstraints.REMAINDER;
304             final String JavaDoc add = getMessage("add00", "Add");
305
306             mainPane.add(addButton = new JButton(add), c);
307
308
309             this.add(new JScrollPane(mainPane), BorderLayout.CENTER);
310
311             // addButton.setEnabled( false );
312
addButton.addActionListener(new ActionListener()
313             {
314                 public void actionPerformed(ActionEvent event)
315                 {
316                     if (add.equals(event.getActionCommand()))
317                     {
318                         String JavaDoc text;
319                         Listener JavaDoc l = null;
320                         int lPort = Integer.parseInt(port.getText());
321                         String JavaDoc tHost = host.getText();
322                         int tPort = 0;
323
324                         text = tport.getText();
325                         if (text != null && !text.equals(""))
326                             tPort = Integer.parseInt(text);
327                         l = new Listener JavaDoc(noteb, null, lPort, tHost, tPort,
328                                 proxyButton.isSelected());
329
330                         // Pick-up the HTTP Proxy settings
331
///////////////////////////////////////////////////
332
text = HTTPProxyHost.getText();
333                         if ("".equals(text)) text = null;
334                         l.HTTPProxyHost = text;
335                         text = HTTPProxyPort.getText();
336                         if ("".equals(text)) text = null;
337                         if (text != null)
338                             l.HTTPProxyPort = Integer.parseInt(text);
339
340                         port.setText(null);
341                         host.setText(null);
342                         tport.setText(null);
343                     }
344                 }
345                 ;
346             }
347             );
348
349             notebook.addTab(name, this);
350             notebook.repaint();
351             notebook.setSelectedIndex(notebook.getTabCount() - 1);
352         }
353     }
354
355     class SocketWaiter extends Thread JavaDoc
356     {
357         ServerSocket sSocket = null;
358         Listener JavaDoc listener;
359         int port;
360         boolean pleaseStop = false;
361
362         public SocketWaiter(Listener JavaDoc l, int p)
363         {
364             listener = l;
365             port = p;
366             start();
367         }
368
369         public void run()
370         {
371             try
372             {
373                 listener.setLeft(new JLabel(getMessage("wait00", " Waiting for Connection...")));
374                 listener.repaint();
375                 sSocket = new ServerSocket(port);
376                 for (; ;)
377                 {
378                     Socket inSocket = sSocket.accept();
379
380                     if (pleaseStop) break;
381                     new Connection(listener, inSocket);
382                     inSocket = null;
383                 }
384             }
385             catch (Exception JavaDoc exp)
386             {
387                 if (!"socket closed".equals(exp.getMessage()))
388                 {
389                     JLabel tmp = new JLabel(exp.toString());
390
391                     tmp.setForeground(Color.red);
392                     listener.setLeft(tmp);
393                     listener.setRight(new JLabel(""));
394                     listener.stop();
395                 }
396             }
397         }
398
399         public void halt()
400         {
401             try
402             {
403                 pleaseStop = true;
404                 new Socket("127.0.0.1", port);
405                 if (sSocket != null) sSocket.close();
406             }
407             catch (Exception JavaDoc e)
408             {
409                 e.printStackTrace();
410             }
411         }
412     }
413
414
415     class SocketRR extends Thread JavaDoc
416     {
417         Socket inSocket = null;
418         Socket outSocket = null;
419         JTextArea textArea;
420         JButton sendXMLButton;
421         InputStream in = null;
422         OutputStream out = null;
423         boolean xmlFormat;
424         volatile boolean done = false;
425         TableModel tableModel = null;
426         int tableIndex = 0;
427         String JavaDoc type = null;
428         Connection myConnection = null;
429         boolean holdXMLUntilEdited = false;
430
431         /**
432          *
433          * @param c
434          * @param inputSocket
435          * @param inputStream
436          * @param outputSocket
437          * @param outputStream
438          * @param _textArea
439          * @param format
440          * @param tModel
441          * @param index
442          * @param type
443          * @param hold Whether to hold on to the XML message until the user has
444          * edited it - if false, message is sent on immediately (as per
445          * original TcpMon behaviour).
446          * @param send a button which allows the user to send the message on manually,
447          * but is only active if 'hold' is true.
448          */

449         public SocketRR(Connection c, Socket inputSocket, InputStream inputStream,
450                         Socket outputSocket, OutputStream outputStream,
451                         JTextArea _textArea, boolean format,
452                         TableModel tModel, int index, final String JavaDoc type,
453                         boolean hold, JButton send)
454         {
455             inSocket = inputSocket;
456             in = inputStream;
457             outSocket = outputSocket;
458             out = outputStream;
459             textArea = _textArea;
460             xmlFormat = format;
461             tableModel = tModel;
462             tableIndex = index;
463             this.type = type;
464             myConnection = c;
465             holdXMLUntilEdited = hold;
466             sendXMLButton = send;
467
468             start();
469         }
470
471         public boolean isDone()
472         {
473             return (done);
474         }
475
476         public void run()
477         {
478             try
479             {
480                 // fancy pants hold-and-forward stuff dies if these buffer lengths are exceeded for a
481
// single http request or response... - CB
482
byte[] buffer = new byte[32768];
483                 byte[] tmpbuffer = new byte[65536];
484                 int saved = 0;
485                 int len;
486             // int i1, i2;
487
int i;
488                 int reqSaved = 0;
489                 int tabWidth = 3;
490                 boolean atMargin = true;
491
492
493                 //if ( inSocket != null ) inSocket.setSoTimeout( 10 );
494
//if ( outSocket != null ) outSocket.setSoTimeout( 10 );
495

496                 if (tableModel != null)
497                 {
498                     String JavaDoc tmpStr = (String JavaDoc) tableModel.getValueAt(tableIndex,
499                             REQ_COLUMN);
500
501                     if (!"".equals(tmpStr))
502                         reqSaved = tmpStr.length();
503                 }
504                //XXX clear out old listeners?
505
if (holdXMLUntilEdited)
506                     sendXMLButton.addActionListener(new ActionListener()
507                     {
508                         public void actionPerformed(ActionEvent e)
509                         {
510                             try
511                             {
512                                 sendXMLButton.setEnabled(false);
513                                 String JavaDoc text = textArea.getText();
514                                 text = fixContentLengthHeaders(text);
515                                 textArea.setText(text);
516                                 byte[] buffer = text.getBytes(); // XXX do we need to force "UTF-8" ?
517
out.write(buffer, 0, buffer.length);
518                             }
519                             catch (Exception JavaDoc e2)
520                             {
521                                 e2.printStackTrace();
522                             }
523                             finally
524                             {
525                                 finishUp();
526                             }
527                         }
528                     });
529
530
531                 readWriteLoop(buffer, saved, reqSaved, tmpbuffer, tabWidth);
532
533
534                 // this.sleep(3); // Let other threads have a chance to run
535
// halt();
536
// Only set the 'done' flag if we were reading from a
537
// Socket - if we were reading from an input stream then
538
// we'll let the other side control when we're done
539
// if ( inSocket != null ) done = true ;
540
}
541             catch (Exception JavaDoc e)
542             {
543                 e.printStackTrace();
544             }
545             finally
546             {
547                 if (!holdXMLUntilEdited)
548                     finishUp();
549             }
550         }
551
552         private void readWriteLoop(byte[] buffer, int saved, int reqSaved, byte[] tmpbuffer, int tabWidth) throws IOException
553         {
554             int len;
555             int i;
556
557
558
559             readloop:
560             for (; ;)
561             {
562                 if (done) break;
563                 len = buffer.length;
564                 // Used to be 1, but if we block it doesn't matter
565
// however 1 will break with some servers, including apache
566
if (len == 0) len = buffer.length;
567                 if (saved + len > buffer.length) len = buffer.length - saved;
568                 int len1 = 0;
569
570                 while (len1 == 0)
571                 {
572                     try
573                     {
574                         len1 = in.read(buffer, saved, len);
575                     }
576                     catch (Exception JavaDoc ex)
577                     {
578                         if (done && saved == 0) break readloop;
579                         len1 = -1;
580                         break;
581                     }
582                 }
583                 len = len1;
584
585                 if (len == -1 && saved == 0) break;
586                 if (len == -1) done = true;
587
588                 // No matter how we may (or may not) format it, send it
589
// on unformatted - we don't want to mess with how its
590
// sent to the other side, just how its displayed
591
if (!holdXMLUntilEdited && out != null && len > 0)
592                 {
593                     out.write(buffer, saved, len);
594                 }
595
596                 if (tableModel != null && reqSaved < 50)
597                 {
598                     String JavaDoc old = (String JavaDoc) tableModel.getValueAt(tableIndex,
599                             REQ_COLUMN);
600
601                     old = old + new String JavaDoc(buffer, saved, len);
602                     if (old.length() > 50)
603                         old = old.substring(0, 50);
604
605                     reqSaved = old.length();
606
607                     if ((i = old.indexOf('\n')) > 0)
608                     {
609                         old = old.substring(0, i - 1);
610                         reqSaved = 50;
611                     }
612
613                     tableModel.setValueAt(old, tableIndex, REQ_COLUMN);
614                 }
615
616                 if (xmlFormat)
617                 {
618                     saved = xmlFormatTextArea(saved, len, buffer, tmpbuffer, tabWidth);
619                 }
620                 else
621                 {
622                     textArea.append(new String JavaDoc(buffer, 0, len));
623                 }
624
625                 if (holdXMLUntilEdited)
626                 {
627                     sendXMLButton.setEnabled(true);
628                 }
629
630
631                 // this.sleep(3); // Let other threads have a chance to run
632
}
633         }
634
635         private int xmlFormatTextArea(int saved, int len, byte[] buffer, byte[] tmpbuffer, int tabWidth)
636         {
637             int i;
638             boolean atMargin;
639             // Do XML Formatting
640
boolean inXML = false;
641             int bufferLen = saved;
642
643             if (len != -1) bufferLen += len;
644             int i1 = 0;
645             int i2 = 0;
646             int thisIndent = -1, nextIndent = -1, previousIndent = -1;
647             saved = 0;
648             for (; i1 < bufferLen; i1++)
649             {
650                 // Except when we're at EOF, saved last char
651
if (len != -1 && i1 + 1 == bufferLen)
652                 {
653                     if (buffer[i1] > 32) // CB - But ONLY do that if it isn't a character we want!!!
654
{
655                         tmpbuffer[i2++] = buffer[i1];
656                         saved = 0;
657                     }
658                     else
659                         saved = 1;
660
661                     break;
662                 }
663                 thisIndent = -1;
664                 if (buffer[i1] == '<' && buffer[i1 + 1] != '/')
665                 {
666                     previousIndent = nextIndent++;
667                     thisIndent = nextIndent;
668                     inXML = true;
669                 }
670                 if (buffer[i1] == '<' && buffer[i1 + 1] == '/')
671                 {
672                     if (previousIndent > nextIndent)
673                         thisIndent = nextIndent;
674                     previousIndent = nextIndent--;
675                     inXML = true;
676                 }
677                 if (buffer[i1] == '/' && buffer[i1 + 1] == '>')
678                 {
679                     previousIndent = nextIndent--;
680                     inXML = true;
681                 }
682                 if (thisIndent != -1)
683                 {
684                     if (thisIndent > 0) tmpbuffer[i2++] = (byte) '\n';
685                     for (i = tabWidth * thisIndent; i > 0; i--)
686                         tmpbuffer[i2++] = (byte) ' ';
687                 }
688                 atMargin = (buffer[i1] == '\n' || buffer[i1] == '\r');
689
690                 if (!inXML || !atMargin)
691                 {
692                     tmpbuffer[i2++] = buffer[i1];
693                 }
694             }
695
696             String JavaDoc text = new String JavaDoc(tmpbuffer, 0, i2);
697             textArea.append(text);
698
699             // Shift saved bytes to the beginning
700
for (i = 0; i < saved; i++)
701                 buffer[i] = buffer[bufferLen - saved + i];
702             return saved;
703         }
704
705         private void finishUp()
706         {
707             done = true;
708             try
709             {
710                 if (out != null)
711                 {
712                     out.flush();
713                     if (null != outSocket)
714                         outSocket.shutdownOutput();
715                     else
716                         out.close();
717                     out = null;
718                 }
719             }
720             catch (Exception JavaDoc e)
721             {
722                 ;
723             }
724             try
725             {
726                 if (in != null)
727                 {
728                     if (inSocket != null)
729                         inSocket.shutdownInput();
730                     else
731                         in.close();
732                     in = null;
733                 }
734             }
735             catch (Exception JavaDoc e)
736             {
737                 ;
738             }
739             myConnection.wakeUp();
740         }
741
742         public void halt()
743         {
744             try
745             {
746                 if (inSocket != null) inSocket.close();
747                 if (outSocket != null) outSocket.close();
748                 inSocket = null;
749                 outSocket = null;
750                 if (in != null) in.close();
751                 if (out != null) out.close();
752                 in = null;
753                 out = null;
754                 done = true;
755             }
756             catch (Exception JavaDoc e)
757             {
758                 e.printStackTrace();
759             }
760         }
761     }
762
763
764     class Connection extends Thread JavaDoc
765     {
766         Listener JavaDoc listener;
767         boolean active;
768         String JavaDoc fromHost;
769         String JavaDoc time;
770         JTextArea inputText = null;
771         JScrollPane inputScroll = null;
772         JTextArea outputText = null;
773         JScrollPane outputScroll = null;
774         Socket inSocket = null;
775         Socket outSocket = null;
776         Thread JavaDoc clientThread = null;
777         Thread JavaDoc serverThread = null;
778         SocketRR requestSocketRR = null;
779         SocketRR ResponseSocketRR = null;
780         InputStream inputStream = null;
781
782         String JavaDoc HTTPProxyHost = null;
783         int HTTPProxyPort = 80;
784
785         public Connection(Listener JavaDoc l)
786         {
787             listener = l;
788             HTTPProxyHost = l.HTTPProxyHost;
789             HTTPProxyPort = l.HTTPProxyPort;
790         }
791
792         public Connection(Listener JavaDoc l, Socket s)
793         {
794             this(l);
795             inSocket = s;
796             start();
797         }
798
799         public Connection(Listener JavaDoc l, InputStream in)
800         {
801             this(l);
802             inputStream = in;
803             start();
804         }
805
806         public void run()
807         {
808             try
809             {
810                 active = true;
811
812                 HTTPProxyHost = System.getProperty("http.proxyHost");
813                 if (HTTPProxyHost != null && HTTPProxyHost.equals(""))
814                     HTTPProxyHost = null;
815
816                 if (HTTPProxyHost != null)
817                 {
818                     String JavaDoc tmp = System.getProperty("http.proxyPort");
819
820                     if (tmp != null && tmp.equals("")) tmp = null;
821                     if (tmp == null)
822                         HTTPProxyPort = 80;
823                     else
824                         HTTPProxyPort = Integer.parseInt(tmp);
825                 }
826
827                 if (inSocket != null)
828                     fromHost = (inSocket.getInetAddress()).getHostName();
829                 else
830                     fromHost = "resend";
831
832                 DateFormat JavaDoc df = new SimpleDateFormat JavaDoc("MM/dd/yy hh:mm:ss aa");
833
834                 time = df.format(new Date());
835
836                 int count = listener.connections.size();
837
838                 listener.tableModel.insertRow(count + 1, new Object JavaDoc[]{
839                     getMessage("active00", "Active"),
840                     time,
841                     fromHost,
842                     listener.hostField.getText(), ""
843                 }
844                 );
845                 listener.connections.add(this);
846                 inputText = new JTextArea(null, null, 20, 80);
847                 inputScroll = new JScrollPane(inputText);
848                 outputText = new JTextArea(null, null, 20, 80);
849                 outputScroll = new JScrollPane(outputText);
850
851                 ListSelectionModel lsm = listener.connectionTable.getSelectionModel();
852
853                 if (count == 0 || lsm.getLeadSelectionIndex() == 0)
854                 {
855                     listener.outPane.setVisible(false);
856                     int divLoc = listener.outPane.getDividerLocation();
857
858                     listener.setLeft(inputScroll);
859                     listener.setRight(outputScroll);
860
861                     listener.removeButton.setEnabled(false);
862                     listener.removeAllButton.setEnabled(true);
863                     listener.saveButton.setEnabled(true);
864                     listener.resendButton.setEnabled(true);
865                     listener.outPane.setDividerLocation(divLoc);
866                     listener.outPane.setVisible(true);
867                 }
868
869                 String JavaDoc targetHost = listener.hostField.getText();
870                 int targetPort = Integer.parseInt(listener.tPortField.getText());
871
872                 InputStream inSocketInputStream = inputStream;
873                 OutputStream inSocketOutputStream = null;
874
875                 InputStream tmpIn2 = null;
876                 OutputStream tmpOut2 = null;
877
878                 if (inSocketInputStream == null)
879                     inSocketInputStream = inSocket.getInputStream();
880
881                 if (inSocket != null)
882                     inSocketOutputStream = inSocket.getOutputStream();
883
884                 String JavaDoc bufferedData = null;
885                 StringBuffer JavaDoc buf = null;
886
887                 int index = listener.connections.indexOf(this);
888
889                 if (listener.isProxyBox.isSelected() || HTTPProxyHost != null)
890                 {
891                     // Check if we're a proxy
892
byte[] b = new byte[1];
893
894                     buf = new StringBuffer JavaDoc();
895                     String JavaDoc s;
896
897                     for (; ;)
898                     {
899                         int len;
900
901                         len = inSocketInputStream.read(b, 0, 1);
902                         if (len == -1) break;
903                         s = new String JavaDoc(b);
904                         buf.append(s);
905                         if (b[0] != '\n') continue;
906                         break;
907                     }
908
909                     bufferedData = buf.toString();
910                     inputText.append(bufferedData);
911
912                     if (bufferedData.startsWith("GET ") ||
913                             bufferedData.startsWith("POST "))
914                     {
915                         int start, end;
916                         URL url;
917
918                         start = bufferedData.indexOf(' ') + 1;
919                         while (bufferedData.charAt(start) == ' ') start++;
920                         end = bufferedData.indexOf(' ', start);
921                         String JavaDoc urlString = bufferedData.substring(start, end);
922
923                         if (urlString.charAt(0) == '/') urlString = urlString.substring(1);
924                         if (listener.isProxyBox.isSelected())
925                         {
926                             url = new URL(urlString);
927                             targetHost = url.getHost();
928                             targetPort = url.getPort();
929                             if (targetPort == -1) targetPort = 80;
930
931                             listener.tableModel.setValueAt(targetHost, index + 1,
932                                     OUTHOST_COLUMN);
933                             bufferedData = bufferedData.substring(0, start) +
934                                     url.getFile() +
935                                     bufferedData.substring(end);
936                         }
937                         else
938                         {
939                             url = new URL("http://" + targetHost + ":" +
940                                     targetPort + "/" + urlString);
941
942                             listener.tableModel.setValueAt(targetHost, index + 1,
943                                     OUTHOST_COLUMN);
944                             bufferedData = bufferedData.substring(0, start) +
945                                     url.toExternalForm() +
946                                     bufferedData.substring(end);
947
948                             targetHost = HTTPProxyHost;
949                             targetPort = HTTPProxyPort;
950                         }
951
952                     }
953                 }
954                 else
955                 /*
956                  * Change Host: header to point to correct host
957                  * keep reading a byte at a time until we find
958                  * a line (a data block ending in '\n') that starts with
959                  * 'Host' - in which case we replace it with our own host.
960                  */

961                 {
962                     //
963
//
964
//
965
byte[] b1 = new byte[1];
966
967                     buf = new StringBuffer JavaDoc();
968                     String JavaDoc s1;
969                     String JavaDoc lastLine = null;
970
971                     for (; ;)
972                     {
973                         int len;
974                         len = inSocketInputStream.read(b1, 0, 1);
975                         if (len == -1)
976                             break;
977                         s1 = new String JavaDoc(b1);
978                         buf.append(s1);
979                         if (b1[0] != '\n')
980                             continue;
981                         // we have a complete line
982
String JavaDoc line = buf.toString();
983
984                         buf.setLength(0);
985                         // check to see if we have found Host: header
986
if (line.startsWith("Host: "))
987                         {
988                             // we need to update the hostname to target host
989
String JavaDoc newHost = "Host: " + targetHost + "\r\n";
990
991                             bufferedData = bufferedData.concat(newHost);
992                             break;
993                         }
994                         // add it to our headers so far
995
if (bufferedData == null)
996                             bufferedData = line;
997                         else
998                             bufferedData = bufferedData.concat(line);
999
1000                        // failsafe
1001
if (line.equals("\r\n")) break;
1002                        if ("\n".equals(lastLine) && line.equals("\n")) break;
1003                        lastLine = line;
1004                    }
1005                    if (bufferedData != null)
1006                    {
1007                        inputText.append(bufferedData);
1008                        int idx = bufferedData.length() < 50 ? bufferedData.length() : 50;
1009                        s1 = bufferedData.substring(0, idx);
1010                        int i = s1.indexOf('\n');
1011
1012                        if (i > 0) s1 = s1.substring(0, i - 1);
1013                        s1 = s1 + " " +
1014                                " ";
1015                        s1 = s1.substring(0, 51);
1016                        listener.tableModel.setValueAt(s1, index + 1,
1017                                REQ_COLUMN);
1018                    }
1019                }
1020
1021                if (targetPort == -1) targetPort = 80;
1022                outSocket = new Socket(targetHost, targetPort);
1023
1024                tmpIn2 = outSocket.getInputStream();
1025                tmpOut2 = outSocket.getOutputStream();
1026
1027                if (!listener.holdRequestBox.isSelected() && bufferedData != null)
1028                {
1029                    byte[] b = bufferedData.getBytes();
1030                    tmpOut2.write(b);
1031                }
1032
1033                boolean format = listener.xmlFormatBox.isSelected();
1034
1035                requestSocketRR = new SocketRR(this, inSocket, inSocketInputStream, outSocket,
1036                        tmpOut2, inputText, format,
1037                        listener.tableModel, index + 1, "request:",
1038                        listener.holdRequestBox.isSelected(), listener.sendButton);
1039                ResponseSocketRR = new SocketRR(this, outSocket, tmpIn2, inSocket,
1040                        inSocketOutputStream, outputText, format,
1041                        null, 0, "response:",
1042                        listener.holdResponseBox.isSelected(), listener.sendButton);
1043
1044                while (requestSocketRR != null || ResponseSocketRR != null)
1045                {
1046                    // Only loop as long as the connection to the target
1047
// machine is available - once that's gone we can stop.
1048
// The old way, loop until both are closed, left us
1049
// looping forever since no one closed the 1st one.
1050
// while( !ResponseSocketRR.isDone() )
1051
if (null != requestSocketRR && requestSocketRR.isDone())
1052                    {
1053                        if (index >= 0 && ResponseSocketRR != null)
1054                        {
1055                            listener.tableModel.setValueAt(getMessage("resp00", "Resp"),
1056                                    1 + index, STATE_COLUMN);
1057                        }
1058                        requestSocketRR = null;
1059                    }
1060                    if (null != ResponseSocketRR && ResponseSocketRR.isDone())
1061                    {
1062                        if (index >= 0 && requestSocketRR != null)
1063                        {
1064                            listener.tableModel.setValueAt(getMessage("req00", "Req"),
1065                                    1 + index, STATE_COLUMN);
1066                        }
1067                        ResponseSocketRR = null;
1068                    }
1069
1070                    // Thread.sleep( 10 );
1071
synchronized (this)
1072                    {
1073                        this.wait(1000); //Safety just incase we're not told to wake up.
1074
}
1075                }
1076
1077                // System.out.println("Done ");
1078
// requestSocketRR.halt();
1079
// ResponseSocketRR.halt();
1080

1081
1082                active = false;
1083
1084                /*
1085                 if ( inSocket != null ) {
1086                 inSocket.close();
1087                 inSocket = null ;
1088                 }
1089                 outSocket.close();
1090                 outSocket = null ;
1091                 */

1092
1093                if (index >= 0)
1094                {
1095                    listener.tableModel.setValueAt(getMessage("done00", "Done"),
1096                            1 + index, STATE_COLUMN);
1097
1098                }
1099            }
1100            catch (Exception JavaDoc e)
1101            {
1102                StringWriter st = new StringWriter();
1103                PrintWriter wr = new PrintWriter(st);
1104                int index = listener.connections.indexOf(this);
1105
1106                if (index >= 0)
1107                    listener.tableModel.setValueAt(getMessage("error00", "Error"), 1 + index, STATE_COLUMN);
1108                e.printStackTrace(wr);
1109                wr.close();
1110                outputText.append(st.toString());
1111                halt();
1112            }
1113        }
1114
1115        synchronized void wakeUp()
1116        {
1117            this.notifyAll();
1118        }
1119
1120        public void halt()
1121        {
1122            try
1123            {
1124                if (requestSocketRR != null) requestSocketRR.halt();
1125                if (ResponseSocketRR != null) ResponseSocketRR.halt();
1126                if (inSocket != null) inSocket.close();
1127                inSocket = null;
1128                if (outSocket != null) outSocket.close();
1129                outSocket = null;
1130            }
1131            catch (Exception JavaDoc e)
1132            {
1133                e.printStackTrace();
1134            }
1135        }
1136
1137        public void remove()
1138        {
1139            int index = -1;
1140
1141            try
1142            {
1143                halt();
1144                index = listener.connections.indexOf(this);
1145                listener.tableModel.removeRow(index + 1);
1146                listener.connections.remove(index);
1147            }
1148            catch (Exception JavaDoc e)
1149            {
1150                System.err.println("index:=" + index + this);
1151                e.printStackTrace();
1152            }
1153        }
1154    }
1155
1156
1157    class Listener extends JPanel
1158    {
1159        public Socket inputSocket = null;
1160        public Socket outputSocket = null;
1161        public JTextField portField = null;
1162        public JTextField hostField = null;
1163        public JTextField tPortField = null;
1164        public JCheckBox isProxyBox = null;
1165        public JCheckBox holdRequestBox = null;
1166        public JCheckBox holdResponseBox = null;
1167        public JButton stopButton = null;
1168        public JButton removeButton = null;
1169        public JButton removeAllButton = null;
1170        public JCheckBox xmlFormatBox = null;
1171        public JButton saveButton = null;
1172        public JButton resendButton = null;
1173        public JButton sendButton = null;
1174        public JButton switchButton = null;
1175        public JButton closeButton = null;
1176        public JTable connectionTable = null;
1177        public DefaultTableModel tableModel = null;
1178        public JSplitPane outPane = null;
1179        public ServerSocket sSocket = null;
1180        public SocketWaiter sw = null;
1181        public JPanel leftPanel = null;
1182        public JPanel rightPanel = null;
1183        public JTabbedPane notebook = null;
1184        public String JavaDoc HTTPProxyHost = null;
1185        public int HTTPProxyPort = 80;
1186
1187        final public Vector connections = new Vector();
1188
1189        public Listener(JTabbedPane _notebook, String JavaDoc name,
1190                        int listenPort, String JavaDoc host, int targetPort,
1191                        boolean isProxy)
1192        {
1193            notebook = _notebook;
1194            if (name == null) name = getMessage("port01", "Port") + " " + listenPort;
1195
1196            this.setLayout(new BorderLayout());
1197
1198            // 1st component is just a row of labels and 1-line entry fields
1199
/////////////////////////////////////////////////////////////////////
1200
JPanel top = new JPanel();
1201
1202            top.setLayout(new BoxLayout(top, BoxLayout.X_AXIS));
1203            top.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
1204            final String JavaDoc start = getMessage("start00", "Start");
1205
1206            top.add(stopButton = new JButton(start));
1207            top.add(Box.createRigidArea(new Dimension(5, 0)));
1208            top.add(new JLabel(" " + getMessage("listenPort01", "Listen Port:") + " ", SwingConstants.RIGHT));
1209            top.add(portField = new JTextField("" + listenPort, 4));
1210            top.add(new JLabel(" " + getMessage("host00", "Host:"), SwingConstants.RIGHT));
1211            top.add(hostField = new JTextField(host, 30));
1212            top.add(new JLabel(" " + getMessage("port02", "Port:") + " ", SwingConstants.RIGHT));
1213            top.add(tPortField = new JTextField("" + targetPort, 4));
1214            top.add(Box.createRigidArea(new Dimension(5, 0)));
1215            top.add(isProxyBox = new JCheckBox(getMessage("proxy00", "Proxy")));
1216            top.add(holdRequestBox = new JCheckBox(getMessage("holdRequest", "Hold Request")));
1217            top.add(holdResponseBox = new JCheckBox(getMessage("holdResponse", "Hold Response")));
1218
1219            isProxyBox.addChangeListener(new BasicButtonListener JavaDoc(isProxyBox)
1220            {
1221                public void stateChanged(ChangeEvent event)
1222                {
1223                    JCheckBox box = (JCheckBox) event.getSource();
1224                    boolean state = box.isSelected();
1225
1226                    tPortField.setEnabled(!state);
1227                    hostField.setEnabled(!state);
1228                }
1229            }
1230            );
1231
1232            isProxyBox.setSelected(isProxy);
1233
1234            portField.setEditable(false);
1235            portField.setMaximumSize(new Dimension(50, Short.MAX_VALUE));
1236            hostField.setEditable(false);
1237            hostField.setMaximumSize(new Dimension(85, Short.MAX_VALUE));
1238            tPortField.setEditable(false);
1239            tPortField.setMaximumSize(new Dimension(50, Short.MAX_VALUE));
1240
1241            stopButton.addActionListener(new ActionListener()
1242            {
1243                public void actionPerformed(ActionEvent event)
1244                {
1245                    if (getMessage("stop00", "Stop").equals(event.getActionCommand())) stop();
1246                    if (start.equals(event.getActionCommand())) start();
1247                }
1248            }
1249            );
1250
1251            this.add(top, BorderLayout.NORTH);
1252
1253            // 2nd component is a split pane with a table on the top
1254
// and the request/response text areas on the bottom
1255
/////////////////////////////////////////////////////////////////////
1256

1257            tableModel = new DefaultTableModel(new String JavaDoc[]{
1258                getMessage("state00", "State"),
1259                getMessage("time00", "Time"),
1260                getMessage("requestHost00", "Request Host"),
1261                getMessage("targetHost", "Target Host"),
1262                getMessage("request00", "Request...")
1263            }, 0);
1264
1265            connectionTable = new JTable(1, 2);
1266            connectionTable.setModel(tableModel);
1267            connectionTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
1268            // Reduce the STATE column and increase the REQ column
1269
TableColumn col;
1270
1271            col = connectionTable.getColumnModel().getColumn(STATE_COLUMN);
1272            col.setMaxWidth(col.getPreferredWidth() / 2);
1273            col = connectionTable.getColumnModel().getColumn(REQ_COLUMN);
1274            col.setPreferredWidth(col.getPreferredWidth() * 2);
1275
1276
1277            ListSelectionModel sel = connectionTable.getSelectionModel();
1278
1279
1280            tableModel.addRow(new Object JavaDoc[]{
1281                "---", getMessage("mostRecent00", "Most Recent"), "---", "---", "---"
1282            }
1283            );
1284
1285            JPanel tablePane = new JPanel();
1286
1287            tablePane.setLayout(new BorderLayout());
1288
1289            JScrollPane tableScrollPane = new JScrollPane(connectionTable);
1290
1291            tablePane.add(tableScrollPane, BorderLayout.CENTER);
1292            JPanel buttons = new JPanel();
1293
1294            buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS));
1295            buttons.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
1296            final String JavaDoc removeSelected = getMessage("removeSelected00", "Remove Selected");
1297
1298            buttons.add(removeButton = new JButton(removeSelected));
1299            buttons.add(Box.createRigidArea(new Dimension(5, 0)));
1300            final String JavaDoc removeAll = getMessage("removeAll00", "Remove All");
1301
1302            buttons.add(removeAllButton = new JButton(removeAll));
1303            tablePane.add(buttons, BorderLayout.SOUTH);
1304
1305            removeButton.setEnabled(false);
1306            removeButton.addActionListener(new ActionListener()
1307            {
1308                public void actionPerformed(ActionEvent event)
1309                {
1310                    if (removeSelected.equals(event.getActionCommand())) remove();
1311                }
1312            }
1313            );
1314
1315            removeAllButton.setEnabled(false);
1316            removeAllButton.addActionListener(new ActionListener()
1317            {
1318                public void actionPerformed(ActionEvent event)
1319                {
1320                    if (removeAll.equals(event.getActionCommand())) removeAll();
1321                }
1322            }
1323            );
1324
1325            // Add Response Section
1326
/////////////////////////////////////////////////////////////////////
1327
JPanel pane2 = new JPanel();
1328
1329            pane2.setLayout(new BorderLayout());
1330
1331            leftPanel = new JPanel();
1332            leftPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
1333            leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
1334            leftPanel.add(new JLabel(" " + getMessage("request01", "Request")));
1335            leftPanel.add(new JLabel(" " + getMessage("wait01", "Waiting for connection")));
1336
1337            rightPanel = new JPanel();
1338            rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
1339            rightPanel.add(new JLabel(" " + getMessage("response00", "Response")));
1340            rightPanel.add(new JLabel(""));
1341
1342            outPane = new JSplitPane(0, leftPanel, rightPanel);
1343            outPane.setDividerSize(4);
1344            pane2.add(outPane, BorderLayout.CENTER);
1345
1346            JPanel bottomButtons = new JPanel();
1347
1348            bottomButtons.setLayout(new BoxLayout(bottomButtons, BoxLayout.X_AXIS));
1349            bottomButtons.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
1350            bottomButtons.add(xmlFormatBox = new JCheckBox(getMessage("xmlFormat00", "XML Format")));
1351            bottomButtons.add(Box.createRigidArea(new Dimension(5, 0)));
1352
1353            final String JavaDoc save = getMessage("save00", "Save");
1354            bottomButtons.add(saveButton = new JButton(save));
1355            bottomButtons.add(Box.createRigidArea(new Dimension(5, 0)));
1356
1357            final String JavaDoc resend = getMessage("resend00", "Resend");
1358            bottomButtons.add(resendButton = new JButton(resend));
1359            bottomButtons.add(Box.createRigidArea(new Dimension(5, 0)));
1360
1361            final String JavaDoc sendStr = getMessage("send", "Send");
1362            bottomButtons.add(sendButton = new JButton(sendStr));
1363            bottomButtons.add(Box.createRigidArea(new Dimension(5, 0)));
1364
1365            final String JavaDoc switchStr = getMessage("switch00", "Switch Layout");
1366            bottomButtons.add(switchButton = new JButton(switchStr));
1367            bottomButtons.add(Box.createHorizontalGlue());
1368
1369            final String JavaDoc close = getMessage("close00", "Close");
1370            bottomButtons.add(closeButton = new JButton(close));
1371            pane2.add(bottomButtons, BorderLayout.SOUTH);
1372
1373            saveButton.setEnabled(false);
1374            saveButton.addActionListener(new ActionListener()
1375            {
1376                public void actionPerformed(ActionEvent event)
1377                {
1378                    if (save.equals(event.getActionCommand())) save();
1379                }
1380            }
1381            );
1382
1383            resendButton.setEnabled(false);
1384            resendButton.addActionListener(new ActionListener()
1385            {
1386                public void actionPerformed(ActionEvent event)
1387                {
1388                    if (resend.equals(event.getActionCommand())) resend();
1389                }
1390            }
1391            );
1392
1393            switchButton.addActionListener(new ActionListener()
1394            {
1395                public void actionPerformed(ActionEvent event)
1396                {
1397                    if (switchStr.equals(event.getActionCommand()))
1398                    {
1399                        int v = outPane.getOrientation();
1400
1401                        if (v == 0) // top/bottom
1402
outPane.setOrientation(1);
1403                        else // left/right
1404
outPane.setOrientation(0);
1405                        outPane.setDividerLocation(0.5);
1406                    }
1407                }
1408            }
1409            );
1410
1411            closeButton.addActionListener(new ActionListener()
1412            {
1413                public void actionPerformed(ActionEvent event)
1414                {
1415                    if (close.equals(event.getActionCommand()))
1416                        close();
1417                }
1418            }
1419            );
1420
1421            JSplitPane pane1 = new JSplitPane(0);
1422
1423            pane1.setDividerSize(4);
1424            pane1.setTopComponent(tablePane);
1425            pane1.setBottomComponent(pane2);
1426            pane1.setDividerLocation(150);
1427            this.add(pane1, BorderLayout.CENTER);
1428
1429            //
1430
////////////////////////////////////////////////////////////////////
1431
sel.setSelectionInterval(0, 0);
1432            outPane.setDividerLocation(150);
1433            notebook.addTab(name, this);
1434
1435              sel.addListSelectionListener(new ListSelectionListener()
1436            {
1437                public void valueChanged(ListSelectionEvent event)
1438                {
1439                    if (event.getValueIsAdjusting()) return;
1440                    ListSelectionModel m = (ListSelectionModel) event.getSource();
1441                    int divLoc = outPane.getDividerLocation();
1442
1443                    if (m.isSelectionEmpty())
1444                    {
1445                        setLeft(new JLabel(" " + getMessage("wait00", "Waiting for Connection...")));
1446                        setRight(new JLabel(""));
1447                        removeButton.setEnabled(false);
1448                        removeAllButton.setEnabled(false);
1449                        saveButton.setEnabled(false);
1450                        resendButton.setEnabled(false);
1451                        sendButton.setEnabled(false);
1452                    }
1453                    else
1454                    {
1455                        int row = m.getLeadSelectionIndex();
1456
1457                        if (row == 0)
1458                        {
1459                            if (connections.size() == 0)
1460                            {
1461                                setLeft(new JLabel(" " + getMessage("wait00", "Waiting for connection...")));
1462                                setRight(new JLabel(""));
1463                                removeButton.setEnabled(false);
1464                                removeAllButton.setEnabled(false);
1465                                saveButton.setEnabled(false);
1466                                resendButton.setEnabled(false);
1467                                sendButton.setEnabled(false);
1468                            }
1469                            else
1470                            {
1471                                Connection conn = (Connection) connections.lastElement();
1472
1473                                setLeft(conn.inputScroll);
1474                                setRight(conn.outputScroll);
1475                                removeButton.setEnabled(false);
1476                                removeAllButton.setEnabled(true);
1477                                saveButton.setEnabled(true);
1478                                resendButton.setEnabled(true);
1479                            }
1480                        }
1481                        else
1482                        {
1483                            Connection conn = (Connection) connections.get(row - 1);
1484
1485                            setLeft(conn.inputScroll);
1486                            setRight(conn.outputScroll);
1487                            removeButton.setEnabled(true);
1488                            removeAllButton.setEnabled(true);
1489                            saveButton.setEnabled(true);
1490                            resendButton.setEnabled(true);
1491                        }
1492                    }
1493                    outPane.setDividerLocation(divLoc);
1494                }
1495            }
1496            );
1497
1498            start();
1499        }
1500
1501        public void setLeft(Component left)
1502        {
1503            leftPanel.removeAll();
1504            leftPanel.add(left);
1505        }
1506
1507        public void setRight(Component right)
1508        {
1509            rightPanel.removeAll();
1510            rightPanel.add(right);
1511        }
1512
1513        public void start()
1514        {
1515            int port = Integer.parseInt(portField.getText());
1516
1517            portField.setText("" + port);
1518            int i = notebook.indexOfComponent(this);
1519
1520            notebook.setTitleAt(i, getMessage("port01", "Port") + " " + port);
1521
1522            int tmp = Integer.parseInt(tPortField.getText());
1523
1524            tPortField.setText("" + tmp);
1525
1526            sw = new SocketWaiter(this, port);
1527            stopButton.setText(getMessage("stop00", "Stop"));
1528
1529            portField.setEditable(false);
1530            hostField.setEditable(false);
1531            tPortField.setEditable(false);
1532            isProxyBox.setEnabled(false);
1533        }
1534
1535        public void close()
1536        {
1537            stop();
1538            notebook.remove(this);
1539        }
1540
1541        public void stop()
1542        {
1543            try
1544            {
1545                for (int i = 0; i < connections.size(); i++)
1546                {
1547                    Connection conn = (Connection) connections.get(i);
1548
1549                    conn.halt();
1550                }
1551                sw.halt();
1552                stopButton.setText(getMessage("start00", "Start"));
1553                portField.setEditable(true);
1554                hostField.setEditable(true);
1555                tPortField.setEditable(true);
1556                isProxyBox.setEnabled(true);
1557            }
1558            catch (Exception JavaDoc e)
1559            {
1560                e.printStackTrace();
1561            }
1562        }
1563
1564        public void remove()
1565        {
1566            ListSelectionModel lsm = connectionTable.getSelectionModel();
1567            int bot = lsm.getMinSelectionIndex();
1568            int top = lsm.getMaxSelectionIndex();
1569
1570            for (int i = top; i >= bot; i--)
1571            {
1572                ((Connection) connections.get(i - 1)).remove();
1573            }
1574            if (bot > connections.size()) bot = connections.size();
1575            lsm.setSelectionInterval(bot, bot);
1576        }
1577
1578        public void removeAll()
1579        {
1580            ListSelectionModel lsm = connectionTable.getSelectionModel();
1581            lsm.clearSelection();
1582            while (connections.size() > 0)
1583                ((Connection) connections.get(0)).remove();
1584
1585            lsm.setSelectionInterval(0, 0);
1586        }
1587
1588        public void save()
1589        {
1590            JFileChooser dialog = new JFileChooser(".");
1591            int rc = dialog.showSaveDialog(this);
1592
1593            if (rc == JFileChooser.APPROVE_OPTION)
1594            {
1595                try
1596                {
1597                    File file = dialog.getSelectedFile();
1598                    FileOutputStream out = new FileOutputStream(file);
1599
1600                    ListSelectionModel lsm = connectionTable.getSelectionModel();
1601
1602                    rc = lsm.getLeadSelectionIndex();
1603                    if (rc == 0) rc = connections.size();
1604                    Connection conn = (Connection) connections.get(rc - 1);
1605
1606                    rc = Integer.parseInt(portField.getText());
1607                    out.write((new String JavaDoc(getMessage("listenPort01", "Listen Port:") + " " + rc + "\n")).getBytes());
1608                    out.write((new String JavaDoc(getMessage("targetHost01", "Target Host:") + " " + hostField.getText() +
1609                            "\n")).getBytes());
1610                    rc = Integer.parseInt(tPortField.getText());
1611                    out.write((new String JavaDoc(getMessage("targetPort01", "Target Port:") + " " + rc + "\n")).getBytes());
1612
1613                    out.write((new String JavaDoc("==== " + getMessage("request01", "Request") + " ====\n")).getBytes());
1614                    out.write(conn.inputText.getText().getBytes());
1615
1616                    out.write((new String JavaDoc("==== " + getMessage("response00", "Response") + " ====\n")).getBytes());
1617                    out.write(conn.outputText.getText().getBytes());
1618
1619                    out.close();
1620                }
1621                catch (Exception JavaDoc e)
1622                {
1623                    e.printStackTrace();
1624                }
1625            }
1626        }
1627
1628        public void resend()
1629        {
1630            int rc;
1631
1632            try
1633            {
1634                ListSelectionModel lsm = connectionTable.getSelectionModel();
1635
1636                rc = lsm.getLeadSelectionIndex();
1637                if (rc == 0) rc = connections.size();
1638                Connection conn = (Connection) connections.get(rc - 1);
1639
1640                if (rc > 0)
1641                {
1642                    lsm.clearSelection();
1643                    lsm.setSelectionInterval(0, 0);
1644                }
1645
1646                InputStream in = null;
1647                String JavaDoc text = conn.inputText.getText();
1648
1649                text = fixContentLengthHeaders(text);
1650
1651                in = new ByteArrayInputStream(text.getBytes());
1652                new Connection(this, in);
1653            }
1654            catch (Exception JavaDoc e)
1655            {
1656                e.printStackTrace();
1657            }
1658        }
1659
1660    }
1661
1662
1663    public TCPInterceptor(int listenPort, String JavaDoc targetHost, int targetPort)
1664    {
1665        super(getMessage("tcpint00", "TCPInterceptor"));
1666
1667        notebook = new JTabbedPane();
1668        this.getContentPane().add(notebook);
1669
1670        new AdminPage(notebook, getMessage("admin00", "Admin"));
1671
1672        if (listenPort != 0)
1673        {
1674            Listener JavaDoc l = null;
1675
1676            if (targetHost == null)
1677                l = new Listener JavaDoc(notebook, null, listenPort,
1678                        targetHost, targetPort, true);
1679            else
1680                l = new Listener JavaDoc(notebook, null, listenPort,
1681                        targetHost, targetPort, false);
1682            notebook.setSelectedIndex(1);
1683
1684            l.HTTPProxyHost = System.getProperty("http.proxyHost");
1685            if (l.HTTPProxyHost != null && l.HTTPProxyHost.equals(""))
1686                l.HTTPProxyHost = null;
1687
1688            if (l.HTTPProxyHost != null)
1689            {
1690                String JavaDoc tmp = System.getProperty("http.proxyPort");
1691
1692                if (tmp != null && tmp.equals("")) tmp = null;
1693                if (tmp == null)
1694                    l.HTTPProxyPort = 80;
1695                else
1696                    l.HTTPProxyPort = Integer.parseInt(tmp);
1697            }
1698        }
1699
1700        this.pack();
1701        this.setSize(800, 600);
1702        this.setVisible(true);
1703    }
1704
1705    protected void processWindowEvent(WindowEvent event)
1706    {
1707        switch (event.getID())
1708        {
1709            case WindowEvent.WINDOW_CLOSING:
1710                exit();
1711                break;
1712
1713            default:
1714                super.processWindowEvent(event);
1715                break;
1716        }
1717    }
1718
1719    /**
1720     * A utility method that sorts out the correct content length headers
1721     * for a post/get request.
1722     * @param text the http text to correct (or simply confirm).
1723     * @return the text, modified with correct content length
1724     */

1725    private static String JavaDoc fixContentLengthHeaders(String JavaDoc text)
1726    {
1727        // Fix Content-Length HTTP headers
1728
if (text.startsWith("POST ") || text.startsWith("GET "))
1729        {
1730            int pos1, pos2, pos3;
1731            String JavaDoc body, headers, headers1, header2;
1732
1733            pos3 = text.indexOf("\n\n");
1734            if (pos3 == -1)
1735            {
1736                pos3 = text.indexOf("\r\n\r\n");
1737                if (pos3 != -1) pos3 = pos3 + 4;
1738            }
1739            else
1740                pos3 += 2;
1741
1742            headers = text.substring(0, pos3);
1743
1744            pos1 = headers.indexOf("Content-Length:");
1745            if (pos1 != -1)
1746            {
1747                int newLen = text.length() - pos3;
1748
1749                pos2 = headers.indexOf("\n", pos1);
1750
1751                text = headers.substring(0, pos1) +
1752                        "Content-Length: " + newLen + "\n" +
1753                        headers.substring(pos2 + 1) +
1754                        text.substring(pos3);
1755            }
1756        }
1757        else
1758            System.err.println("Error - asked to fix content length for a bad request (no POST or GET)");
1759        return text;
1760    }
1761
1762
1763    private void exit()
1764    {
1765        System.exit(0);
1766    }
1767
1768    public void setInputPort(int port)
1769    {
1770    }
1771
1772    public void setOutputHostPort(char hostName, int port)
1773    {
1774    }
1775
1776    public static void main(String JavaDoc[] args)
1777    {
1778        try
1779        {
1780            if (args.length == 3)
1781            {
1782                int p1 = Integer.parseInt(args[0]);
1783                int p2 = Integer.parseInt(args[2]);
1784
1785                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
1786                new TCPInterceptor(p1, args[1], p2);
1787            }
1788            else if (args.length == 1)
1789            {
1790                int p1 = Integer.parseInt(args[0]);
1791
1792                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
1793                new TCPInterceptor(p1, null, 0);
1794            }
1795            else if (args.length != 0)
1796            {
1797                System.err.println(getMessage("usage00", "Usage:") + " TCPInterceptor [listenPort targetHost targetPort]\n");
1798            }
1799            else
1800            {
1801                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
1802                new TCPInterceptor(8080, "localhost", 8888);
1803            }
1804        }
1805        catch (Throwable JavaDoc exp)
1806        {
1807            exp.printStackTrace();
1808        }
1809    }
1810
1811    // Message resource bundle.
1812
private static ResourceBundle messages = null;
1813
1814    /**
1815     * Get the message with the given key. There are no arguments for this message.
1816     */

1817    public static String JavaDoc getMessage(String JavaDoc key, String JavaDoc defaultMsg)
1818    {
1819        try
1820        {
1821            if (messages == null)
1822            {
1823                initializeMessages();
1824            }
1825            return messages.getString(key);
1826        }
1827        catch (Throwable JavaDoc t)
1828        {
1829            // If there is any problem whatsoever getting the internationalized
1830
// message, return the default.
1831
return defaultMsg;
1832        }
1833    } // getMessage
1834

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

1840    private static void initializeMessages()
1841    {
1842        messages = ResourceBundle.getBundle("org.apache.axis.utils.TCPInterceptor");
1843    } // initializeMessages
1844

1845}
1846
Popular Tags