Some Eclipse Foundation services are deprecated, or will be soon. Please ensure you've read this important communication.
View | Details | Raw Unified | Return to bug 208110 | Differences between
and this patch

Collapse All | Expand All

(-)src-recorder-http-runner/org/eclipse/hyades/execution/recorder/http/remote/ConnectionObj.java (-35 lines)
Removed Link Here
1
/**********************************************************************
2
 * Copyright (c) 2005, 2007 IBM Corporation and others.
3
 * All rights reserved.   This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: ConnectionObj.java,v 1.5 2007/05/02 19:36:27 paules Exp $
8
 * 
9
 * Contributors: 
10
 * IBM Corporation - initial API and implementation
11
 **********************************************************************/
12
package org.eclipse.hyades.execution.recorder.http.remote;
13
14
/**
15
 * This simple class is used to hold connection numbers.
16
 * 
17
 * @author mdunn
18
 * @deprecated  This is not public API.  It will be moved to internal in TPTP 5
19
 *
20
 */
21
public final class ConnectionObj
22
{
23
	private int connectionNumber = 0;
24
	
25
	 int getConnectionNumber(){
26
		
27
		return connectionNumber;
28
	}
29
	// method provided for convenience only if it is ever needed
30
	 void setConnectionNumber(int thisConnectionNumber){
31
		connectionNumber = thisConnectionNumber;
32
	}
33
	
34
35
}
(-)src-recorder-http-runner/org/eclipse/hyades/execution/recorder/http/remote/PeekServerSocket.java (-130 lines)
Removed Link Here
1
/**********************************************************************
2
 * Copyright (c) 2005 IBM Corporation and others.
3
 * All rights reserved.   This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: PeekServerSocket.java,v 1.3 2005/06/09 21:15:29 mddunn Exp $
8
 * 
9
 * Contributors: 
10
 * IBM Corporation - initial API and implementation
11
 **********************************************************************/
12
package org.eclipse.hyades.execution.recorder.http.remote;
13
14
import java.io.IOException;
15
import java.net.InetAddress;
16
import java.net.ServerSocket;
17
import java.net.Socket;
18
19
20
/**
21
 * Function:  Custom server socket that can accept
22
 *            Sockets of type PeekSocket.  
23
 * @author ptasnik@us.ibm.com
24
 * @deprecated  This is not public API.  It will be moved to internal in TPTP 5
25
 *
26
  */
27
public class PeekServerSocket extends ServerSocket {
28
29
	/**
30
	 * @throws java.io.IOException
31
	 */
32
	public PeekServerSocket() throws IOException {
33
		super();
34
	}
35
36
	/**
37
	 * @param port
38
	 * @throws java.io.IOException
39
	 */
40
	public PeekServerSocket(int port) throws IOException {
41
		super(port);
42
	}
43
44
	/**
45
	 * @param port
46
	 * @param backlog
47
	 * @throws java.io.IOException
48
	 */
49
	public PeekServerSocket(int port, int backlog) throws IOException {
50
		super(port, backlog);		
51
	}
52
53
	/**
54
	 * @param port
55
	 * @param backlog
56
	 * @param bindAddr
57
	 * @throws java.io.IOException
58
	 */
59
	public PeekServerSocket(int port, int backlog, InetAddress bindAddr)
60
		throws IOException {
61
		super(port, backlog, bindAddr);		
62
	}
63
	
64
	
65
	/**
66
	 * Override server socket accept to return
67
	 * a empty PeekSocket.  implAccept() does
68
	 * all the work to make it connected to
69
	 * the client socket.
70
	 */
71
72
	public PeekSocket acceptPeekSocket() throws IOException {
73
		PeekSocket s = new PeekSocket();
74
		implAccept(s);
75
		return s;
76
	}
77
78
79
	public static void main(String[] args) {
80
	try {
81
		PeekServerSocket server_sock = new PeekServerSocket (4444);
82
		PeekSocket client_sock;
83
		Thread myThread = new Thread (server_sock.new TestPeekServerSocket());
84
		myThread.start ();
85
		
86
		while (true) {
87
			System.out.println ("Server - waiting to accept ...");
88
			client_sock = server_sock.acceptPeekSocket();
89
			System.out.println ("Server - accepted");
90
			
91
			int peek_int = client_sock.peek();
92
			System.out.println ("Server - peek_int=" + String.valueOf(peek_int));
93
			int peek_read = client_sock.getInputStream().read();
94
			System.out.println ("Server - peek_read=" + String.valueOf(peek_read));
95
			peek_read = client_sock.getInputStream().read();
96
			System.out.println ("Server - peek_read=" + String.valueOf(peek_read));
97
			
98
			client_sock.close();
99
		}
100
		
101
	} catch (Exception e) {
102
		e.printStackTrace ();
103
	}
104
	}
105
	
106
	private class TestPeekServerSocket implements Runnable {
107
		
108
		public void run () {
109
			byte data[] = new byte [20];
110
			data[0] = 'h';
111
			data[1] = 'e';
112
			
113
			while (true) {			
114
				try {
115
					System.out.println ("Client - sleeping");
116
					Thread.sleep(5000); // wait for server
117
					
118
					System.out.println ("Client - going to connect");
119
					Socket s = new Socket ("localhost", 4444);
120
					s.getOutputStream().write(data, 0, 2);
121
					System.out.println ("Client - wrote bytes");
122
					
123
				} catch (Exception e) {
124
					e.printStackTrace ();
125
				}
126
			}
127
		}
128
	}
129
}
130
(-)src-recorder-http-runner/org/eclipse/hyades/execution/recorder/http/remote/RecorderX509TrustManager.java (-50 lines)
Removed Link Here
1
/**********************************************************************
2
 * Copyright (c) 2005, 2007 IBM Corporation and others.
3
 * All rights reserved.   This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: RecorderX509TrustManager.java,v 1.7 2008/03/07 15:06:25 paules Exp $
8
 * 
9
 * Contributors: 
10
 * IBM Corporation - initial API and implementation
11
 **********************************************************************/
12
package org.eclipse.hyades.execution.recorder.http.remote;
13
14
import java.security.cert.X509Certificate;
15
16
import javax.net.ssl.X509TrustManager;
17
18
/**
19
 * This object is used to create the SSL trust manager.
20
 * for the URL Recorder.
21
 * 
22
 * @author mdunn
23
 * @deprecated  This is not public API.  It will be moved to internal in TPTP 5
24
 *
25
 * 
26
 */
27
28
class RecorderX509TrustManager implements X509TrustManager {
29
30
31
	RecorderX509TrustManager() {
32
	}
33
	
34
	public void checkClientTrusted(X509Certificate[] chain, String authType){
35
			
36
		return;
37
   }
38
39
	public void checkServerTrusted(X509Certificate[] chain, String authType){
40
	
41
		return;
42
	}
43
	
44
	public X509Certificate[] getAcceptedIssuers() {
45
		return null;
46
	}
47
	
48
}
49
50
(-)src-recorder-http-runner/org/eclipse/hyades/execution/recorder/http/remote/ClientSideReaderSOCKS.java (-1050 lines)
Removed Link Here
1
/*``````````````````````````````````````````````````````````````/**********************************************************************
2
 * Copyright (c) 2005, 2007 IBM Corporation and others.
3
 * All rights reserved.   This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: ClientSideReaderSOCKS.java,v 1.16 2007/12/10 03:03:15 dmorris Exp $
8
 * 
9
 * Contributors: 
10
 * IBM Corporation - initial API and implementation
11
 **********************************************************************/
12
13
/*
14
 * NONE OF THE QUOTED STRINGS IN THIS FILE ARE TO BE LOCALIZED
15
 * THEY ARE ALL FOR XML TAGS, DEBUGGING SUPPORT, THEY ARE NOT FOR USER INTERFACES
16
 */
17
package org.eclipse.hyades.execution.recorder.http.remote;
18
19
import java.io.IOException;
20
import java.io.InputStream;
21
import java.net.InetAddress;
22
import java.net.InetSocketAddress;
23
import java.net.UnknownHostException;
24
25
/**
26
 * This class extends the ClientSideReader object.  This handles the traffic from the
27
 * browser when the browser 'talks' SOCKS protocol.
28
 * 
29
 * @author dmorris
30
 * modified by:  mddunn 11/17/2003 for Hyades-O 1.2
31
 * @deprecated  This is not public API.  It will be moved to internal in TPTP 5
32
 * 
33
 */
34
public class ClientSideReaderSOCKS extends ClientSideReader {
35
	
36
	public static final String ERROR_SSL_REQUEST_MADE = "-1"; //this is an error until SSL is supported
37
	public static final String ERROR_NO_TESTKEYS = "-2"; //this is an error until SSL is supported
38
	static final String STR_KEEP_ALIVE = "Proxy-Connection: Keep-Alive\r\n";
39
	static final String ClientSideReaderException = HttpRecResourceBundle.RECORDER_CLIENTSIDE_READER_EXCEPTION;
40
	static boolean didSocks5Handshake = false;
41
	// SOCKS5 header maximum = 1 (version) + 1 (number of methods (1-255) + 255 (possible number of methods)
42
	int MAX_LEN_SOCKS5_REQUEST = 257;
43
	int proxyRecorderPort = 0;
44
	// Socks 5 Method Selected
45
	int socks5MethodSelected = 0;
46
	byte[] thisReadBuffer = null;
47
	final int NO_METHOD = -1;
48
	public String socks5DestinationInetAddrStr = null;
49
	public int socks5DestPort = 0;
50
	public int socks5AddressType = 0;
51
	byte [] destinationInetAddress = null;
52
	public static final int ADDRESS_TYPE_V4 = 1;
53
	public static final int ADDRESS_TYPE_V6 = 4;
54
	public static final int ADDRESS_TYPE_DOMAINNAME = 3;
55
	public static final int NO_AUTHENTICATION_REQUIRED = 0;
56
	public static final int NUM_BYTES_V4_ADDR = 4;
57
	public static final int NUM_BYTES_V6_ADDR = 16;
58
	public static final int NUM_BYTES_DESTINATION_PORT = 2;
59
	
60
	ClientSideReaderSOCKS(PeekSocket client, PacketWriter packetWriter, String keyFile, int iProxyRecorderPort){
61
		super(client,packetWriter, keyFile);
62
		proxyRecorderPort = iProxyRecorderPort;
63
	
64
	}
65
	
66
	public void run(){
67
		
68
		int bytes_read = 0;
69
		boolean socks_OK = false;
70
		boolean wroteOnePacket = false;
71
		// Unexpected message
72
		
73
		if (isSSLClassAvailable == -1)	{	
74
			isSSLClassAvailable = findSSLClass();
75
			if (isSSLClassAvailable == 1) {
76
				foundTestKeys = checkForTestKeys();
77
			}
78
		}
79
		this.setName("ClientSideReaderSOCKS-"+"Conn:"+ iConnection);
80
		try{
81
			
82
			byte[] buffer = new byte[client.getReceiveBufferSize()];
83
			//packetWriter.writeRecorderMessage(1, "IN RUN() getReceiveBufferSize is: " + bsize );
84
			socks_OK = processSocksRequest();
85
			if (socks_OK) {
86
				//packetWriter.writeRecorderMessage(1, "IN RUN() just got Back from ProcessSocksRequest() for connection: " + iConnection);
87
				//  check for SSL Connection first before read
88
				bSecure = checkSSLByte();
89
				if (bSecure) {
90
					if (isSSLClassAvailable == 1)	{
91
						if (foundTestKeys) {
92
							SSLCheckClass thisSSLCheck = new SSLCheckClass(this, keyFile);
93
							thisSSLCheck.makeSecureConnection();
94
							if (httpServer != null) {
95
								//packetWriter.writeRecorderMessage(1, "IN RUN() just got NEW SSL SOCKET for connection: " + iConnection);
96
								//respondToClient(true);
97
							}
98
							else {
99
								//respondToClient(false);
100
								// must throw exception 
101
								packetWriter.writeRecorderMessage(1, "Error connecting to SSL Server:" + destServer + " Port: "+serverPort);
102
								packetWriter.getAgentController().sendControlMessageToDataProcessor(ERROR_SSL_REQUEST_MADE);
103
								return;
104
							}
105
						}
106
						else  {
107
							// send message to UI 
108
							packetWriter.getAgentController().sendControlMessageToDataProcessor(ERROR_NO_TESTKEYS);
109
							//respondToClient(false);
110
							return;
111
						}
112
					}
113
					else {
114
						// send message to UI 
115
						packetWriter.getAgentController().sendControlMessageToDataProcessor(ERROR_SSL_REQUEST_MADE);
116
						respondToClient(false);
117
						return;
118
					}
119
				}
120
				else {
121
					//packetWriter.writeRecorderMessage(1, "IN RUN() newAddr is: " + newAddr + " destPort is: " + destPort + " for connection: " + iConnection);
122
					// This next line ensures we get a "plain" socket which does not do Reverse DNS LookUp
123
					httpServer = createPlainSocket();
124
					InetSocketAddress epoint = new InetSocketAddress(newAddr, destPort);
125
					httpServer.connect(epoint);
126
	
127
					if (httpServer != null) {
128
						makeRegularConnection();
129
						//packetWriter.writeRecorderMessage(1, "IN RUN() AFTER MakeRegularConnection, strReturn is: " + strReturn  + " for connection: " + iConnection);
130
						//packetWriter.writeRecorderMessage(1, "IN RUN() just got NEW SOCKET for connection: " + iConnection);
131
						//respondToClient(true);
132
					}
133
					else {
134
						//respondToClient(false);
135
						//packetWriter.getAgentController().sendControlMessageToDataProcessor(ERROR_REQUEST_MADE);
136
						packetWriter.writeRecorderMessage(1, "Error connecting to Server:" + destServer + " Port: "+serverPort);
137
						return;
138
					}
139
				}
140
141
				while ((bytes_read = from_client.read(buffer)) != -1){
142
					yield();
143
					bNoPrintToServer = false;
144
					wroteOnePacket = true;
145
					// bugzilla 137958 simplified the code by always using a byte array for communication buffer
146
					//	Defect 83619 mdd synch for write to socket and write to file
147
148
					/*	if (!bNoPrintToServer){
149
							to_server.write(buffer, 0, bytes_read);
150
							to_server.flush();
151
						}*/
152
					packetWriter.writePacket(bSecure, true, connectionNumber, buffer, bytes_read, to_server, bNoPrintToServer);
153
154
					
155
				}
156
			} else {
157
				//packetWriter.writeRecorderMessage(1, "IN RUN() SOCKS IS NOT OK for connection: " + iConnection);
158
			}
159
			
160
			//packetWriter.writeRecorderMessage(1, "IN RUN()Broke Out of Read Loop for connection: " + iConnection + " Bytes Read is: " + bytes_read);
161
			if (httpServer != null){
162
				//if (! httpServer.isClosed())
163
				//	httpServer.close();
164
				// new mdd
165
				httpServer.setSoLinger(true,0);
166
				if (!wroteOnePacket) {
167
					if (! httpServer.isClosed()) {
168
						//packetWriter.writeRecorderMessage(1, "IN CLIENTSIDEREADER A1 - CLOSED SERVERSIDE COnnection: " + iConnection);
169
						httpServer.close();
170
					}
171
					else {
172
						//packetWriter.writeRecorderMessage(1, "IN CLIENTSIDEREADER A - httpServer IS Closed for COnnection: " + iConnection);
173
					}
174
				}
175
				else if (! httpServer.isOutputShutdown()){
176
					if (bSecure) {
177
						//packetWriter.writeRecorderMessage(1, "IN CLIENTSIDEREADER A WRITING SSL CLOSE ALERT for COnnection: " + iConnection);
178
						to_server.flush();
179
						httpServer.close();
180
						
181
					} else {
182
						httpServer.shutdownOutput();
183
						//packetWriter.writeRecorderMessage(1, "IN CLIENTSIDEREADER A - SHUTDOWN SERVERSIDE OUTPUT for COnnection: " + iConnection);
184
					}
185
				}
186
				else {
187
					//packetWriter.writeRecorderMessage(1, "IN CLIENTSIDEREADER A - NO PACKET and OUTPUT IS Shutdown for COnnection: " + iConnection);
188
				}
189
				//	mdd tell Server reader we are closed
190
				// MAY NEED serverReader.setClosedByClient();
191
			}
192
			else {
193
				//packetWriter.writeRecorderMessage(1, "IN CLIENTSIDEREADER A - httpServer WAS NULL for Connection: " + iConnection);
194
			}
195
			
196
			yield();
197
			//packetWriter.writeCloseConnectionInfo(iConnection);
198
			
199
		}
200
		catch (Exception e) {
201
202
			//packetWriter.writeRecorderMessage(1, "JUST CAUGHT AN EXCEPTION In ClientSideReader connection " + iConnection + " Exception: " +e.getLocalizedMessage() );
203
			
204
			try {
205
				if (httpServer != null) {
206
					//if (!httpServer.isClosed())
207
					//	httpServer.close();
208
					if (!wroteOnePacket) {
209
						if (! httpServer.isClosed()) {
210
							//packetWriter.writeRecorderMessage(1, "IN CLIENTSIDEREADER B1 - CLOSED SERVERSIDE COnnection: " + iConnection);
211
							httpServer.close();
212
						}
213
						else {
214
							//packetWriter.writeRecorderMessage(1, "IN CLIENTSIDEREADER B2 - !wroteOnePacket; httpServer IS CLOSED for COnnection: " + iConnection);
215
						}
216
					} else 	if (!httpServer.isOutputShutdown()&& !httpServer.isClosed()){
217
						if (bSecure) {
218
							//packetWriter.writeRecorderMessage(1, "IN CLIENTSIDEREADER B WRITING SSL CLOSE ALERT for COnnection: " + iConnection);
219
							to_server.flush();
220
							httpServer.close();
221
							
222
						} else {
223
							httpServer.shutdownOutput();
224
							//packetWriter.writeRecorderMessage(1, "IN CLIENTSIDEREADER B - SHUTDOWN SERVERSIDE OUTPUT for COnnection: " + iConnection);
225
						}
226
					}
227
					// mdd tell Server reader we are closed	
228
					// add check for null 032204
229
					//if (serverReader != null)	
230
					// MAT NEED serverReader.setClosedByClient();
231
				}
232
				else {
233
					//packetWriter.writeRecorderMessage(1, "IN CLIENTSIDEREADER B - httpServer IS NULL for COnnection: " + iConnection);
234
				}
235
				
236
				yield();
237
				// force interrupt by nulling the buffer SSR is reading mdd
238
				//serverReader.interrupt();
239
				//packetWriter.writeRecorderMessage(1, "IN CLIENTSIDEREADER NULL BUFFER FORCE INTERRUPT for COnnection: " + iConnection);
240
				//serverReader.ssrBuffer = null;
241
				
242
			}
243
			catch (IOException ioe){
244
				String mess = ioe.getMessage();
245
				// no record for the following exceptions, they are expected
246
				
247
				if (mess.indexOf("Stream closed") < 0 && mess.indexOf("Socket closed") < 0 &&
248
						mess.indexOf("JVM_recv in socket input") <0 && mess.indexOf("onnection closed")<0
249
						&& mess.indexOf("socket closed")<0 && mess.indexOf("onnection reset") < 0
250
						&& mess.indexOf("Socket is closed") <0) {
251
					packetWriter.writeRecorderMessage(2, "IOException in ClientSideReader connection " + iConnection + " : " + e.toString());
252
				}
253
			}
254
		}
255
		//packetWriter.writeRecorderMessage(1, "IN CLIENTSIDEREADER LEAVING RUN METHOD for COnnection: " + iConnection);
256
	}
257
	
258
259
//	private static synchronized void debugMsg (String msg) {
260
//		try {
261
//			FileOutputStream out = new FileOutputStream("c:\\test.out", true);
262
//			String outStr = msg + "\r\n";
263
//			out.write (outStr.getBytes());
264
//		} catch (Exception e) {
265
//			//temp
266
//		}
267
//	}
268
	
269
	/**
270
	 * Attempts to read exactSize from the InputStream, no more, no less.  If a short
271
	 * read comes in block until exactSize is placed in the out buf.  Will not read 
272
	 * more than exactSize from the stream.
273
	 * 
274
	 * Assumptions, buf is large enough from exactSize, IndexOutOfRange would probably occur.
275
	 * 
276
	 * @param in InputStream of bytes.
277
	 * @param buf Output byte[] buffer
278
	 * @param exactSize The exact number of bytes to read, -1 on EOF or exception.
279
	 * @return exactSize if bytes are read, -1 all other times, say on EOF.
280
	 * @throws IOException InputStream.read() exception.
281
	 */
282
	private static int readExactOrBust (InputStream in, byte[]buf, int exactSize) throws IOException {		
283
		int offset = 0;
284
		do {
285
			int currentReadSize = in.read (buf, offset, (exactSize - offset));
286
			//debugMsg (in.toString() + " " + String.valueOf(currentReadSize));
287
			if (currentReadSize <= 0) {
288
				return -1; // read or bust
289
			}
290
			offset += currentReadSize;
291
		} while (offset < exactSize);
292
293
		if (offset != exactSize) {
294
			throw new RuntimeException ("Internal logic problem ClientSideReadSOCKS.readExactOrBust()"); //$NON-NLS-1$
295
		}
296
297
		return offset; // should always be exactSize
298
	}
299
	
300
	/**
301
	 * Skip all bytes including delimitor in the stream.  This operation will block until delimitor
302
	 * is seen or EOF, in which case -1 is returned.  If delimitorByte is read, then the number of bytes
303
	 * read is returned.  
304
	 * 
305
	 * @param in InputStream
306
	 * @param delimitorByte Byte to read until(over).
307
	 * @return Number of byts read or -1 on EOF, will block as described above.
308
	 * @throws IOException Standard InputStream read() exceptions.
309
	 */
310
	private static int flushUntilByteOccurs (InputStream in, byte delimitorByte) throws IOException {
311
		int currentByteAsInt;
312
		int totalBytesRead = 0;
313
		do {
314
			currentByteAsInt = in.read ();
315
			if (currentByteAsInt <= 0) {
316
				return -1; // never saw delimitor
317
			}
318
			totalBytesRead += 1;
319
		} while (delimitorByte != ((byte)currentByteAsInt));
320
		
321
		return totalBytesRead;
322
	}
323
324
	private boolean processSocksRequest() {
325
		boolean returnCode = false;
326
		int bytes_read = 0;
327
		
328
		int socksVersion = 0;
329
		String inetAddrStr = "";
330
		byte newInetAddress[] = new byte[4];
331
		boolean gotSocks5OK = false;
332
		
333
		// first read the entire socks header
334
		try {
335
			//packetWriter.writeRecorderMessage(1, "IN ProcessSocksRequest() for connection: " + iConnection);
336
			byte[] buffer = new byte[client.getReceiveBufferSize()];
337
			socksVersion = client.peek();
338
			if (socksVersion == 4)
339
			{	
340
				bytes_read = ClientSideReaderSOCKS.readExactOrBust (from_client, buffer, 8);
341
				if (bytes_read < 8){
342
					// we have an error, must have at least 8 bytes				
343
					returnCode = false;
344
				}
345
				else {
346
					int i=0;
347
					// have socks header, now process it
348
					for (i = 0; i < 8; i++){
349
						Byte tmpByte = new Byte(buffer[i]);
350
						switch(i){
351
						case 0:
352
							socksVersion = tmpByte.intValue();
353
							break;
354
						case 1:						
355
							break;
356
						case 2:
357
							int tmp = 0;
358
							tmp = tmpByte.intValue();
359
							if (tmp < 0)
360
								tmp = tmp+256;
361
							destPort = (tmp*256) ;
362
							break;
363
						case 3:
364
							int tmp2 = 0;
365
							tmp2 = tmpByte.intValue();
366
							if (tmp2 < 0)
367
								tmp2 += 256;
368
							destPort += tmp2;
369
							break;
370
						case 4:
371
						case 5:
372
						case 6:
373
						case 7:
374
							newInetAddress[i-4] = buffer[i];
375
							break;
376
						}	
377
					}
378
					// Part of SOCKS4 protocol, read until '00', end of request
379
					if (ClientSideReaderSOCKS.flushUntilByteOccurs (from_client, (byte)0) == -1) {
380
						returnCode = false;
381
					}				
382
		
383
					// now must connect to IP address
384
					inetAddrStr = IP4ByteToString(newInetAddress);
385
					packetWriter.writeRecorderMessage(1, "SOCKS 4 Connection");
386
					//packetWriter.writeRecorderMessage(1, "IN ProcessSocksRequest() CALL getByName() for connection: " + iConnection);
387
					// bugzilla 137969 avoid unnecessary NS lookup in getByName()by using getByAddress()
388
					newAddr =  InetAddress.getByAddress(newInetAddress);
389
					//packetWriter.writeRecorderMessage(1, "IN ProcessSocksRequest() return from getByName() for connection: " + iConnection);
390
					//destServer = newAddr.getHostName();
391
					destServer = inetAddrStr;
392
					serverPort = destPort;
393
					returnCode = true;
394
				}
395
				respondToClient(returnCode);
396
			}
397
			else if (socksVersion == 5) {
398
					// first, get the connect request usually: 05 01 00
399
					//packetWriter.writeRecorderMessage(1, "Read Socks5 Connect for" + " Connection: " + iConnection);
400
					gotSocks5OK = readSocks5ConnectRequest(buffer);
401
					if (gotSocks5OK) {
402
						//packetWriter.writeRecorderMessage(1, "Read Socks5 gotSocks5OK is TRUE" + " Connection: " + iConnection);
403
						respondToClientSocks5MethodSelection(gotSocks5OK);
404
						//handShakeWorked = doSocks5Handshake(buffer, bytes_read);
405
						didSocks5Handshake = true;
406
						//packetWriter.writeRecorderMessage(1, "Read Socks5 REGULAR REQUEST" + " Connection: " + iConnection);
407
						returnCode = readSocks5RegularRequest(buffer);
408
						
409
						if (returnCode == true){
410
							//packetWriter.writeRecorderMessage(1, "Read Socks5 REGULAR REQUEST- TRUE" + " Connection: " + iConnection);
411
						}
412
						else {
413
							packetWriter.writeRecorderMessage(1, "Read Socks5 REGULAR REQUEST- FALSE" + " Connection: " + iConnection);
414
						}
415
						
416
						//returnCode = processRegularSocks5Request(buffer);
417
						respondToClientSocks5RegularRequest(returnCode);
418
						//packetWriter.writeRecorderMessage(1, "JUST Responded to Regular Request" + " Connection: " + iConnection);
419
						//	 now must connect to IP address
420
						//inetAddrStr = IP4ByteToString(newInetAddress);
421
						//newAddr =  InetAddress.getByName(socks5DestinationInetAddrStr);
422
						newAddr =  InetAddress.getByAddress(destinationInetAddress);
423
						destServer = socks5DestinationInetAddrStr;
424
						serverPort = socks5DestPort;
425
						destPort = serverPort;
426
						returnCode = true;
427
					} // got Socks5 connect request OK
428
					else {
429
						packetWriter.writeRecorderMessage(1, "Read Socks5 gotSocks5OK is FALSE" + " Connection: " + iConnection);
430
					} // got Socks5 connect request OK
431
			} // version is socks  5 
432
			else {  // unknown socks version (not 4 or 5)
433
				returnCode = false;
434
				respondToClientSocks5MethodSelection(returnCode);
435
			}
436
		}
437
		catch (Exception e) {
438
			packetWriter.writeRecorderMessage(1, "Error Reading from Client" + " Connection: " + iConnection);
439
			
440
			try {
441
				client.close();
442
			}
443
			catch (IOException ioe){
444
				packetWriter.writeRecorderMessage(1, "Error closing Client" + ioe + " Connection: " + iConnection);
445
			}
446
			//packetWriter.writeCloseConnectionInfo(iConnection);
447
		}
448
		//packetWriter.writeRecorderMessage(1, "LEAVING ProcessSocksRequest() for connection: " + iConnection);
449
		return returnCode;
450
	}
451
452
	private boolean readSocks5ConnectRequest(byte[] inBuf){
453
		//boolean returnCode = false;
454
		int bytes_read = -1;
455
		
456
		int selected_method = NO_METHOD; // -1 means not selected 
457
		//doTest(buffer);
458
		// bytes_read = ClientSideReaderSOCKS.readEntireRequest (from_client, buffer, MAX_LEN_SOCKS5_REQUEST);
459
		
460
		byte[] version_buf = new byte[1];
461
		byte[] nmeths_buf = new byte[1];
462
		byte[] supported_auths = {00}; // add additional, perference left to right
463
464
		byte[] methods_buf;
465
		try {
466
			bytes_read = ClientSideReaderSOCKS.readExactOrBust(from_client, version_buf, 1);
467
			if (bytes_read <= 0) return false;
468
			
469
			bytes_read = ClientSideReaderSOCKS.readExactOrBust(from_client, nmeths_buf, 1);
470
			if (bytes_read <= 0) return false;
471
			
472
			int numMethods = (int)nmeths_buf[0];
473
			if (numMethods < 0) numMethods += 256; // Java's byte->int assumes byte is signed
474
			
475
			methods_buf = new byte[numMethods];				
476
			bytes_read = ClientSideReaderSOCKS.readExactOrBust(from_client, methods_buf, numMethods);
477
			if (bytes_read <= 0) 
478
				return false;
479
			
480
			// iterate through the authentication types
481
482
			for (int i = 0; selected_method == NO_METHOD && i < methods_buf.length; i++) {
483
				for (int j = 0; selected_method == NO_METHOD && j < supported_auths.length; j++) {
484
					if (methods_buf[i] == supported_auths[j]) {
485
						selected_method = supported_auths[j];
486
						if (selected_method < 0) selected_method += 256;
487
					}
488
				}
489
			}
490
			if (selected_method == NO_METHOD) {
491
				return false; // don't support that junk
492
			}
493
		} catch (IOException e) {
494
			// TODO Auto-generated catch block
495
			e.printStackTrace();
496
		}
497
		
498
		socks5MethodSelected = selected_method;
499
		return true;
500
	}
501
	private boolean readSocks5RegularRequest(byte[] buffer) {
502
		//int bufferLength = -1;
503
		// number of bytes until you get to the Destination Address
504
		int NUM_BYTES_DESTINATION_PORT = 2;
505
		int numberBytesAddress = 0;
506
		
507
		int bytes_read = -1;
508
		byte[] tmp_buf = new byte[1];
509
		int totalBytesRead = 0;
510
		byte [] tmpReturnBuff = null;
511
		byte [] return_buf = null;
512
		//byte [] destinationInetAddress = null;
513
		byte [] destinationPortBytes = null;
514
		
515
		
516
		/*The SOCKS request is formed as follows:
517
	        +----+-----+-------+------+----------+----------+
518
	        |VER | CMD |  RSV  | ATYP | DST.ADDR | DST.PORT |
519
	        +----+-----+-------+------+----------+----------+
520
	        | 1  |  1  | X'00' |  1   | Variable |    2     |
521
	        +----+-----+-------+------+----------+----------+
522
	     Where:
523
524
	            VER    protocol version: X'05'
525
	            CMD
526
	               CONNECT X'01'
527
	               BIND X'02'
528
	               UDP ASSOCIATE X'03'
529
	            RSV    RESERVED
530
	            ATYP   address type of following address
531
	               IP V4 address: X'01'
532
	               DOMAINNAME: X'03'
533
	               IP V6 address: X'04'
534
	            DST.ADDR       desired destination address
535
	            DST.PORT desired destination port in network octet
536
	             order
537
			 */
538
		
539
		try {
540
			tmpReturnBuff = new byte[client.getReceiveBufferSize()];
541
			
542
			// VERSION - BYTE 1
543
			bytes_read = ClientSideReaderSOCKS.readExactOrBust(from_client, tmp_buf, 1);
544
			if (bytes_read <= 0) 	return false;
545
			//packetWriter.writeRecorderMessage(1, "IN ReadSocks5REGULARREQUEST - VERSION" + " for Connection: " + iConnection);
546
			tmpReturnBuff[totalBytesRead] = tmp_buf[0];
547
			totalBytesRead += 1;
548
			// COMMAND - BYTE 2
549
			bytes_read = ClientSideReaderSOCKS.readExactOrBust(from_client, tmp_buf, 1);
550
			if (bytes_read <= 0) return false;
551
			tmpReturnBuff[totalBytesRead] = tmp_buf[0];
552
			totalBytesRead += 1;
553
			Byte tmpByte = new Byte(tmp_buf[0]);
554
			int tmp = 0;
555
			tmp = tmpByte.intValue();
556
			// 1 is for CONNECT
557
			if (tmp != 1) 	return false;
558
			tmpByte = null;
559
			//packetWriter.writeRecorderMessage(1, "IN ReadSocks5REGULARREQUEST - COMMAND is CONNECT" + " for Connection: " + iConnection);
560
			
561
			// RESERVED - BYTE 3
562
			bytes_read = ClientSideReaderSOCKS.readExactOrBust(from_client, tmp_buf, 1);
563
			if (bytes_read <= 0) 	return false;
564
			//packetWriter.writeRecorderMessage(1, "IN ReadSocks5REGULARREQUEST - RESERVED" + " for Connection: " + iConnection);
565
			tmpReturnBuff[totalBytesRead] = tmp_buf[0];
566
			totalBytesRead += 1;
567
			//	 ADDRESSING TYPE - BYTE 4
568
			//   ATYP   address type of following address
569
			//   IP V4 address: X'01'
570
			//   DOMAINNAME: X'03'
571
			//   IP V6 address: X'04'
572
			int addressType = -1;
573
			bytes_read = ClientSideReaderSOCKS.readExactOrBust(from_client, tmp_buf, 1);
574
			if (bytes_read <= 0) 	return false;
575
			//packetWriter.writeRecorderMessage(1, "IN ReadSocks5REGULARREQUEST - ATYPE" + " for Connection: " + iConnection);
576
			tmpReturnBuff[totalBytesRead] = tmp_buf[0];
577
			totalBytesRead += 1;
578
			tmpByte = new Byte(tmp_buf[0]);
579
			addressType = tmpByte.intValue();
580
			socks5AddressType = addressType;
581
			if (addressType == ADDRESS_TYPE_V4 ){
582
				//packetWriter.writeRecorderMessage(1, "IN ReadSocks5REGULARREQUEST - ATYPE is V4" + " for Connection: " + iConnection);
583
				numberBytesAddress = NUM_BYTES_V4_ADDR;
584
				destinationInetAddress = new byte[NUM_BYTES_V4_ADDR];
585
			} 
586
			else if (addressType == ADDRESS_TYPE_V6){
587
				//packetWriter.writeRecorderMessage(1, "IN ReadSocks5REGULARREQUEST - ATYPE is V6" + " for Connection: " + iConnection);
588
				numberBytesAddress = NUM_BYTES_V6_ADDR;
589
				destinationInetAddress = new byte[NUM_BYTES_V6_ADDR];
590
			}
591
			else {
592
				// not supported DOMAINNAME
593
				packetWriter.writeRecorderMessage(2, "IN ReadSocks5REGULARREQUEST - ATYPE is DOMAIN" + " for Connection: " + iConnection);
594
				return false;
595
			}
596
			bytes_read = ClientSideReaderSOCKS.readExactOrBust(from_client, destinationInetAddress, numberBytesAddress);
597
			if (bytes_read != numberBytesAddress) return false;
598
			for (int j = 0; j <  bytes_read; j++, totalBytesRead++) {
599
				tmpReturnBuff[totalBytesRead]= destinationInetAddress[j];
600
			}
601
			if (addressType == ADDRESS_TYPE_V4){
602
				socks5DestinationInetAddrStr = IP4ByteToString(destinationInetAddress);
603
				//packetWriter.writeRecorderMessage(1, "socks 5, V4 address");
604
			}
605
			else if (addressType == ADDRESS_TYPE_V6) {
606
				socks5DestinationInetAddrStr = IP6ByteToString(destinationInetAddress);
607
				//packetWriter.writeRecorderMessage(1, "socks 5, V6 address");
608
				
609
			}
610
			//packetWriter.writeRecorderMessage(1, "IN ReadSocks5REGULARREQUEST - DESTINATION ADDRESS is: " + socks5DestinationInetAddrStr + " for Connection: " + iConnection);
611
			// DESTINATION PORT 2 bytes long
612
			destinationPortBytes = new byte[NUM_BYTES_DESTINATION_PORT];
613
			bytes_read = ClientSideReaderSOCKS.readExactOrBust(from_client, destinationPortBytes, NUM_BYTES_DESTINATION_PORT);
614
			if (bytes_read != NUM_BYTES_DESTINATION_PORT) return false;
615
			for (int j = 0; j <  bytes_read; j++, totalBytesRead++) {
616
				tmpReturnBuff[totalBytesRead]= destinationPortBytes[j];
617
			}
618
			socks5DestPort = getDestinationPort(destinationPortBytes );
619
			//packetWriter.writeRecorderMessage(1, "IN ReadSocks5REGULARREQUEST - DESTINATION PORT is: " + socks5DestPort + " for Connection: " + iConnection);
620
		} catch (IOException e) {
621
			// TODO Auto-generated catch block
622
			e.printStackTrace();
623
		}
624
		
625
		return_buf = new byte[totalBytesRead];
626
		for (int k = 0; k < totalBytesRead; k++){
627
			return_buf[k] = tmpReturnBuff[k];
628
		}
629
		return true;
630
	}
631
632
	private int getDestinationPort(byte[] destinationPortBytes) {
633
		// TODO Auto-generated method stub
634
		int myDestinationPort = 0;
635
		for (int j = 0; j < NUM_BYTES_DESTINATION_PORT ;  j++){
636
			Byte tmpByte = new Byte(destinationPortBytes[j]);
637
			switch (j) {
638
			case 0:
639
				int tmp = 0;
640
				tmp = tmpByte.intValue();
641
				if (tmp < 0){
642
					tmp = tmp+256;
643
				}
644
				myDestinationPort = (tmp*256);
645
				break;
646
			case 1:
647
				int tmp2 = 0;
648
				tmp2 = tmpByte.intValue();
649
				if (tmp2 < 0)
650
					tmp2 += 256;
651
				myDestinationPort += tmp2;
652
			}
653
		}
654
		return myDestinationPort;
655
	}
656
657
	/**
658
	 * This class responds to a SOCKS 5 regular request.
659
	 * 
660
	 * The SOCKS request information is sent by the client as soon as it has
661
	 *  established a connection to the SOCKS server(the Recorder) , and completed the
662
	 *  authentication negotiations.  The server evaluates the request, and
663
	 *  returns a reply formed as follows:
664
	 *  
665
	 *      VER     REPLY   RSV   ATYPE   BND.ADDR    BND.PORT
666
	 *  	 1        1     X'00     1     Variable      2
667
	 *  
668
	 *  Where:
669
	 *      VER    protocol version: X'05'
670
	 *      REP    Reply field:
671
	 *             X'00' succeeded
672
	 *             X'01' general SOCKS server failure
673
	 *             X'02' connection not allowed by ruleset
674
	 *             X'03' Network unreachable
675
	 *             X'04' Host unreachable
676
	 *             X'05' Connection refused
677
	 *             X'06' TTL expired
678
	 *             X'07' Command not supported
679
	 *             X'08' Address type not supported
680
	 *             X'09' to X'FF' unassigned
681
	 *      RSV    RESERVED
682
	 *      ATYP   address type of following address
683
	 *      
684
	 *             IP V4 address: X'01'
685
	 *                DOMAINNAME: X'03'
686
	 *             IP V6 address: X'04'
687
	 *     BND.ADDR       server bound address
688
	 *     BND.PORT       server bound port in network octet order
689
	 *     
690
	 *     Fields marked RESERVED (RSV) must be set to X'00'.
691
	 * 
692
	 * @param returnCode   -  The code to send to the client
693
	 * 
694
	 * @author mdunn
695
	 * @internal  This is not public API.  
696
	 */
697
	private void respondToClientSocks5RegularRequest(boolean returnCode) {
698
		
699
		byte[] reply_buffer = null;
700
		// reply size depends on addressing type 
701
		int replySize = 0; 
702
		int addressLen = 0;
703
		byte replyAddressType = 0;
704
		int i = 0;
705
		int replyIndx = 0;
706
		
707
		InetAddress lh = null;
708
		try {
709
			lh = InetAddress.getLocalHost();
710
		} catch (UnknownHostException e) {
711
			// TODO Auto-generated catch block
712
			e.printStackTrace();
713
			
714
		}
715
		//packetWriter.writeRecorderMessage(1, "IN ResondToClientSocks5RegularRequest for Connection: " + iConnection);
716
		byte[] localHostAddress = lh.getAddress();
717
		//String tmpLocalhost = lh.toString();
718
		//String localHostStr = getAddressFromLocalhost(tmpLocalhost);
719
		int thisPort = proxyRecorderPort;
720
			
721
	
722
		addressLen = localHostAddress.length;
723
		if (addressLen  == NUM_BYTES_V4_ADDR){
724
			replyAddressType = 1;
725
		}
726
		if (addressLen  == NUM_BYTES_V6_ADDR){
727
			replyAddressType = 4;
728
		}
729
		
730
		// reply will include: Version (1 byte) + Reply (1) + Reserved (1) + AddressType (1) 
731
		// + Bind Address (variable from above) + Bnd.Port (2) == 6 + Bind.Address Length
732
		replySize = addressLen + 6; 
733
		reply_buffer = new byte[replySize];
734
		//packetWriter.writeRecorderMessage(1, "IN ResondToClientSocks5RegularRequest- replySize is: " + replySize + " for Connection: " + iConnection);
735
		
736
		reply_buffer[0] = 5;   // Version 
737
		reply_buffer[1] = 0;   // Reply  - successful = 0
738
		reply_buffer[2] = 0;   // Reserved - must be 0
739
		reply_buffer[3] = replyAddressType;  // address type
740
		for (i = 0, replyIndx = 4 ; i < localHostAddress.length && replyIndx < replySize; i++, replyIndx++){
741
			reply_buffer[replyIndx]=localHostAddress[i];
742
		}
743
		//	convert integet thisPort to 2 bytes
744
		Uint16_Network(thisPort, reply_buffer, replyIndx);
745
		try {
746
			to_client.write(reply_buffer,0, replySize);
747
			to_client.flush();
748
		} catch (Exception e){
749
			packetWriter.writeRecorderMessage(1, "ERROR writing to Client in ResondToClientSocks5RegularRequest for Connection: " + iConnection);
750
			e.printStackTrace();
751
		}		
752
		
753
		
754
	}
755
/*
756
	private void respondToClientSocks5RegularRequest(boolean returnCode) {
757
	
758
		byte[] reply_buffer = null;
759
		// reply size depends on addressing type 
760
		int replySize = 0; 
761
		int addressLen = 0;
762
		byte replyAddressType = 0;
763
		int i = 0;
764
		int replyIndx = 0;
765
		
766
		InetAddress lh = null;
767
		try {
768
			lh = InetAddress.getLocalHost();
769
		} catch (UnknownHostException e) {
770
			// TODO Auto-generated catch block
771
			packetWriter.writeRecorderMessage(1, "ERROR in getLocalHost" + iConnection);
772
			e.printStackTrace();
773
			
774
		}
775
		//packetWriter.writeRecorderMessage(1, "IN ResondToClientSocks5RegularRequest for Connection: " + iConnection);
776
		byte[] localHostAddress = lh.getAddress();
777
		//String tmpLocalhost = lh.toString();
778
		//String localHostStr = getAddressFromLocalhost(tmpLocalhost);
779
		int thisPort = proxyRecorderPort;
780
			
781
		//int thisAddressType = mySocks5Obj.getAddressType();
782
		int thisAddressType = socks5AddressType;
783
		
784
		if (thisAddressType == ADDRESS_TYPE_V4) {
785
			addressLen = NUM_BYTES_V4_ADDR;
786
			replyAddressType = 1;
787
		}
788
		else if (thisAddressType == ADDRESS_TYPE_V6){
789
			addressLen = NUM_BYTES_V6_ADDR;
790
			replyAddressType = 4;
791
		}
792
		// reply will include: Version (1 byte) + Reply (1) + Reserved (1) + AddressType (1) 
793
		// + Bind Address (variable from above) + Bnd.Port (2) == 6 + Bind.Address Length
794
		replySize = addressLen + 6; 
795
		reply_buffer = new byte[replySize];
796
		//packetWriter.writeRecorderMessage(1, "IN ResondToClientSocks5RegularRequest- replySize is: " + replySize + " for Connection: " + iConnection);
797
		
798
		reply_buffer[0] = 5;   // Version 
799
		reply_buffer[1] = 0;   // Reply  - successful = 0
800
		reply_buffer[2] = 0;   // Reserved - must be 0
801
		reply_buffer[3] = replyAddressType;  // address type
802
		for (i = 0, replyIndx = 4 ; i < localHostAddress.length && replyIndx < replySize; i++, replyIndx++){
803
			reply_buffer[replyIndx]=localHostAddress[i];
804
		}
805
		//	convert integet thisPort to 2 bytes
806
		Uint16_Network(thisPort, reply_buffer, replyIndx);
807
		try {
808
			to_client.write(reply_buffer,0, replySize);
809
			to_client.flush();
810
		} catch (Exception e){
811
			packetWriter.writeRecorderMessage(1, "ERROR writing to Client in ResondToClientSocks5RegularRequest for Connection: " + iConnection);
812
			e.printStackTrace();
813
		}		
814
		
815
		
816
	}
817
	*/
818
	/**
819
	 * The server selects from one of the methods given in METHODS, and sends a METHOD selection message:
820
	 * 
821
	 *    VERSION     METHOD  
822
	 *       1          1
823
	 *       
824
	 *    If the selected METHOD is X'FF', none of the methods listed by the
825
	 *    client are acceptable, and the client MUST close the connection.
826
	 *    
827
	 *   The values currently defined for METHOD are:
828
	 *   
829
	 *     X'00' NO AUTHENTICATION REQUIRED
830
	 *     X'01' GSSAPI
831
	 *     X'02' USERNAME/PASSWORD
832
	 *     X'03' to X'7F' IANA ASSIGNED
833
	 *     X'80' to X'FE' RESERVED FOR PRIVATE METHODS
834
	 *     X'FF' NO ACCEPTABLE METHODS
835
	 *     
836
     * @author mdunn
837
     * @internal
838
     * 
839
	 * @param returnCode
840
	 */
841
842
	private void respondToClientSocks5MethodSelection(boolean returnCode) {
843
		int REPLY_SIZE = 2;
844
		byte[] reply_buff = new byte[REPLY_SIZE];
845
		
846
		reply_buff[0] = 5;
847
		if ((returnCode == true) && (socks5MethodSelected != NO_METHOD)){
848
			reply_buff[1] = 0;
849
		}
850
		else {
851
			reply_buff[1] = (byte)255;
852
		}
853
		
854
		try {
855
			to_client.write(reply_buff,0, REPLY_SIZE);
856
			to_client.flush();
857
		} catch (IOException e) {
858
			// TODO Auto-generated catch block
859
			e.printStackTrace();
860
		}
861
862
	}
863
	/**
864
	 * Convert uint16 into 2 octets in unsigned network byte order.
865
	 * 
866
	 * @param uint16 Positive integer 0->2^16. 
867
	 * @param destBuf The buffer to store uint16 in network byte order.
868
	 * @param destStartIdx The offset into buffer, will consome buffer[offset] and
869
	 *                     buffer[offset+1]
870
	 */
871
	public static void Uint16_Network(int uint16, byte[] destBuf, int destStartIdx) {
872
		destBuf[destStartIdx+0] = (byte)(uint16 / 256);
873
		destBuf[destStartIdx+1] = (byte)(uint16 % 256);
874
	}
875
876
	/**
877
	 * 
878
	 * @param myvar
879
	 * @return
880
	 */
881
	private static String IP4ByteToString (byte myvar[]) {
882
		String strResult = "";		
883
		for (int i = 0; i < 4; i++) {
884
			if ((int)myvar[i] >= 0) {
885
				strResult += String.valueOf((int)myvar[i]);
886
			} else {
887
				strResult += String.valueOf(256 + (int)myvar[i]);
888
			}
889
			if (i < 3) {
890
				strResult += ".";
891
			}		
892
		}
893
		return strResult;
894
	}
895
	
896
	private String IP6ByteToString(byte[] destinationInetAddress2) {
897
		String address = null;
898
		try{
899
			InetAddress  add = InetAddress.getByAddress(destinationInetAddress2);
900
			address = add.getHostAddress();
901
		}
902
		catch (UnknownHostException e){
903
			return null;
904
		}
905
		
906
		return address;
907
	}
908
	
909
	
910
	private void respondToClient(boolean flag) {
911
		byte[] reply_buff = new byte[8];
912
	
913
		reply_buff[0] = 0;
914
		if (flag == true){
915
			reply_buff[1] = 90;
916
		}
917
		else {
918
			reply_buff[1] = 91;
919
		}
920
		try {
921
			to_client.write(reply_buff,0, 8);
922
			to_client.flush();
923
		} catch (Exception e){
924
			e.printStackTrace();
925
		}
926
	}
927
928
	private String makeRegularConnection( ){
929
		
930
		String strReturn = null;
931
		//int index;	
932
		//int port = 80;
933
		//String destStr = null;
934
		try{
935
			// Note : already have open port to server
936
			//httpServer = new Socket(destStr, port);
937
			packetWriter.writeOpenConnectionInfo(bSecure, iConnection, destServer, serverPort, client, httpServer, null, null);
938
			
939
			to_server = httpServer.getOutputStream();
940
			from_server = httpServer.getInputStream();
941
						
942
			serverReader = new ServerSideReader(client,
943
												httpServer,
944
												from_server,
945
												to_client,
946
												 packetWriter,
947
												 connectionNumber,
948
												 bSecure,
949
												 httpServer.getReceiveBufferSize());
950
			serverReader.start();
951
	
952
		}
953
		catch (Exception e){
954
				packetWriter.writeRecorderMessage(2, "exception in ClientSideReader : " + e + " Connection: " + iConnection);
955
				packetWriter.getAgentController().reportException(ClientSideReaderException,e);
956
				
957
				try {
958
					if (!client.isClosed()) {
959
						client.close();
960
					}
961
					strReturn = null;
962
				}
963
				catch (IOException ioe){
964
					packetWriter.writeRecorderMessage(2, "IOException in ClientSideReader connection " + iConnection + ": "  + ioe);
965
					
966
				}
967
				//packetWriter.writeCloseConnectionInfo(iConnection);
968
		}
969
		return strReturn;					
970
	}
971
	public int findSSLClass() {
972
		int gotSSL = -1;
973
974
		try{
975
				Class.forName("javax.net.ssl.SSLSocket");
976
				gotSSL = 1;
977
			}
978
			catch (ClassNotFoundException cnf){
979
				gotSSL = 0;			
980
			}
981
		return gotSSL;
982
	}
983
	boolean checkSSLByte() {
984
		boolean isSSL = false;
985
		int ssl_byte = 0;
986
		//TODO must mark beginning of buffer, read 1 byte and check if the
987
		// byte = 128 or 20 or 21 or 22 or 23
988
		// if so, must convert client to spysocket and server to SSLSocketFactory socket
989
		// and reset() the buffer to beginning 
990
991
		try {
992
			ssl_byte = client.peek();
993
		}
994
		catch (IOException e) {
995
			packetWriter.writeRecorderMessage(2, "exception checking for SSL Connection: " + iConnection + e);
996
	
997
		}
998
		// packetWriter.writeRecorderMessage(1, "ssl_byte is: " + ssl_byte );
999
		if ((ssl_byte == 128) || (ssl_byte == 20) || (ssl_byte == 21) 
1000
				|| (ssl_byte == 22) || (ssl_byte == 23)) {
1001
				
1002
			isSSL = true;
1003
			bSecure = true;
1004
		}
1005
		else {
1006
			bSecure = false;
1007
			isSSL = false;
1008
		}
1009
		return isSSL;
1010
	}
1011
1012
//		private static synchronized void debugMsg (String msg) {
1013
//			try {
1014
//				FileOutputStream out = new FileOutputStream("c:\\test.out", true);
1015
//				String outStr = msg + "\r\n";
1016
//				out.write (outStr.getBytes());
1017
//			} catch (Exception e) {
1018
//				//temp
1019
//			}
1020
//		}
1021
		
1022
		/**
1023
		 * Attempts to read exactSize from the InputStream, no more, no less.  If a short
1024
		 * read comes in block until exactSize is placed in the out buf.  Will not read 
1025
		 * more than exactSize from the stream.
1026
		 * 
1027
		 * Assumptions, buf is large enough from exactSize, IndexOutOfRange would probably occur.
1028
		 * 
1029
		 * @param in InputStream of bytes.
1030
		 * @param buf Output byte[] buffer
1031
		 * @param exactSize The exact number of bytes to read, -1 on EOF or exception.
1032
		 * @return exactSize if bytes are read, -1 all other times, say on EOF.
1033
		 * @throws IOException InputStream.read() exception.
1034
		 */
1035
1036
		public String getAddressFromLocalhost(String originalString) {
1037
			String retString = "";
1038
			int foundSlash = -1;
1039
			
1040
			foundSlash = originalString.indexOf("/");
1041
			if (foundSlash == -1) {
1042
				retString = originalString;
1043
			} else {
1044
				retString = originalString.substring(foundSlash + 1);
1045
			}
1046
			
1047
			return retString;
1048
		}
1049
1050
}
(-)src-recorder-http-runner/org/eclipse/hyades/execution/recorder/http/remote/TicketDispatcher.java (-35 lines)
Removed Link Here
1
/**********************************************************************
2
 * Copyright (c) 2005, 2007 IBM Corporation and others.
3
 * All rights reserved.   This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: TicketDispatcher.java,v 1.5 2007/05/02 19:36:26 paules Exp $
8
 * 
9
 * Contributors: 
10
 * IBM Corporation - initial API and implementation
11
 **********************************************************************/
12
package org.eclipse.hyades.execution.recorder.http.remote;
13
14
/**
15
 * This class creates a unique ticket number for each packet of information written to the 
16
 * .rec file.
17
 * 
18
 * @author morris
19
 * @deprecated  This is not public API.  It will be moved to internal in TPTP 5
20
 * 
21
 */
22
public final class TicketDispatcher {
23
	static int iTicket = 0;
24
	
25
	synchronized static int getTicket(){
26
		iTicket++;
27
		return iTicket;
28
	}
29
	// method provided for convenience only if it is ever needed
30
	synchronized static void resetTicketCounter(){
31
		iTicket = 0;
32
	}
33
	
34
35
}
(-)src-recorder-http-runner/org/eclipse/hyades/execution/recorder/http/remote/CleanupObj.java (-65 lines)
Removed Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2005, 2008 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: CleanupObj.java,v 1.7 2008/03/07 14:19:57 paules Exp $
8
 * 
9
 * Contributors:
10
 *     IBM Corporation - initial API and implementation
11
 *******************************************************************************/
12
package org.eclipse.hyades.execution.recorder.http.remote;
13
import java.net.Socket;
14
15
16
/**
17
 * This object is used to clean up any sockets that are still hanging around when we close 
18
 * the URL recorder.
19
 * 
20
 * @author mdunn
21
 * @deprecated  This is not public API.  It will be moved to internal in TPTP 5
22
 *
23
 * 
24
 */
25
public class CleanupObj {
26
	Socket thisSocket = null;
27
	PacketWriter thisWriter = null;
28
	String thisConnection = null;
29
	/**
30
	 * @return Returns the thisSocket.
31
	 */
32
	public Socket getThisSocket() {
33
		return thisSocket;
34
	}
35
	/**
36
	 * @param thisSocket The thisSocket to set.
37
	 */
38
	public void setThisSocket(Socket thisSocket) {
39
		this.thisSocket = thisSocket;
40
	}
41
	/**
42
	 * @return Returns the thisWriter.
43
	 */
44
	public PacketWriter getThisWriter() {
45
		return thisWriter;
46
	}
47
	/**
48
	 * @param thisWriter The thisWriter to set.
49
	 */
50
	public void setThisWriter(PacketWriter thisWriter) {
51
		this.thisWriter = thisWriter;
52
	}
53
	/**
54
	 * @return Returns the thisConnection.
55
	 */
56
	public String getThisConnection() {
57
		return thisConnection;
58
	}
59
	/**
60
	 * @param thisConnection The thisConnection to set.
61
	 */
62
	public void setThisConnection(String thisConnection) {
63
		this.thisConnection = thisConnection;
64
	}
65
}
(-)src-recorder-http-runner/org/eclipse/hyades/execution/recorder/http/remote/PacketWriter.java (-806 lines)
Removed Link Here
1
/**********************************************************************
2
 * Copyright (c) 2005, 2007 IBM Corporation and others.
3
 * All rights reserved.   This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: PacketWriter.java,v 1.27 2007/05/02 19:36:26 paules Exp $
8
 * 
9
 * Contributors: 
10
 * IBM Corporation - initial API and implementation
11
 **********************************************************************/
12
13
/*
14
 * NONE OF THE QUOTED STRINGS IN THIS FILE ARE TO BE LOCALIZED
15
 * THEY ARE ALL FOR XML TAGS, DEBUGGING SUPPORT, THEY ARE NOT FOR USER INTERFACES
16
 */
17
package org.eclipse.hyades.execution.recorder.http.remote;
18
19
import java.io.IOException;
20
import java.io.OutputStream;
21
import java.net.InetAddress;
22
import java.net.Socket;
23
import java.util.Date;
24
import java.util.Properties;
25
26
import javax.net.ssl.SSLSocket;
27
28
import org.eclipse.hyades.execution.recorder.remote.RecorderAgent;
29
30
import com.ibm.icu.text.SimpleDateFormat;
31
32
/**
33
 * This object is used to write the packets of information (XML fragments) to the .rec file
34
 * 
35
 * @author morris
36
 * modified by: mdunn
37
 * @deprecated  This is not public API.  It will be moved to internal in TPTP 5
38
 */
39
public class PacketWriter 
40
{
41
	static final int ENCODING_TYPE_NONE = 0;
42
	static final int ENCODING_TYPE_BASE64 = 1;
43
	static final int ENCODING_TYPE_ASCIIFY = 2;
44
	
45
	static final String PACKET_TAG = "<TRCPacket>\r\n";
46
	static final String XML_IDENT = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n\r\n<TRACE>\r\n\r\n";
47
	
48
	static final String DATA_TAGEND = "]]></data>\r\n";
49
	static final String PACKET_TAGEND = "</TRCPacket>\r\n\r\n";
50
	
51
	static int iTicket = 0;
52
	static long lTimeRef = 0;
53
	
54
	Date date;
55
	static int encodedLength = -1;
56
	static int encodedNonASCIIs = -1;
57
	
58
	static boolean bStopRecording = false;
59
	
60
	private RecorderAgent agent;
61
	
62
	protected GlobalPacketQueue packetQueue;
63
	
64
	public PacketWriter(RecorderAgent theAgentController){
65
		super();
66
		date = new Date();
67
		agent = theAgentController;
68
		bStopRecording = false;
69
		
70
		packetQueue = new GlobalPacketQueue (this);
71
		packetQueue.setPriority(Thread.MIN_PRIORITY);
72
		packetQueue.start();
73
	}
74
	
75
	public synchronized boolean writePacket(boolean bSecure,
76
			boolean bFromClient,
77
			ConnectionObj iConnection,
78
			byte [] buffer,
79
			int bufLength, 
80
			OutputStream where_to, 
81
			boolean bNoPrintToServer) throws Exception {
82
		
83
		boolean bRet = false;
84
		
85
		String dirString = null; 
86
		String typeString = null;
87
		int encodingType = ENCODING_TYPE_NONE; 
88
		String strEncoded = null;
89
		byte [] byteEncodedArray = null;
90
91
		
92
		try {
93
			if (!bNoPrintToServer){
94
				where_to.write(buffer, 0, bufLength);
95
				where_to.flush();
96
			}
97
		} catch (IOException e1) {
98
			// TODO Auto-generated catch block
99
			throw e1;
100
		}
101
		
102
		int thisConn = iConnection.getConnectionNumber();
103
		if (thisConn == 0) {
104
			writeRecorderMessage(1, "REJECTED writePacket - connection number is 0");
105
			return false;
106
		}
107
		
108
		
109
		iTicket = TicketDispatcher.getTicket();
110
		
111
		try{
112
			encodedLength = -1;
113
			encodedNonASCIIs = 0;  // Used to determine if really ALL ASCII
114
				
115
			// ASCIIFY string  --  This sets encodedLength to -100 if more
116
			// than 5 Non-ASCIIs in the first 50 bytes
117
			byteEncodedArray = getASCIIFYEncodedByteArray(buffer, bufLength);
118
119
			// Check length of ASCIIFY encoding
120
			if (encodedLength < 0) {
121
				// Lots of Non-ASCII so Base64 it
122
				strEncoded = getBase64EncodedString(buffer, bufLength);
123
				encodingType = ENCODING_TYPE_BASE64;
124
				encodedLength = strEncoded.length();
125
				byteEncodedArray = null; // Free Up the ASCIIFY string
126
			} else {	
127
/* ASCIIFY all Non-BASE64 packets until TestGen Xerces Parser is fixed to not drop CR's
128
 			} else if (encodedNonASCIIs > 0) {
129
 					// Had some Non-ASCII so we use ASCIIFIED
130
				encodingType = ENCODING_TYPE_ASCIIFY;
131
			} else {
132
				// Had NO Non-ASCII so use the original buffer
133
				encodingType = ENCODING_TYPE_NONE;
134
				byteEncodedArray = null; // Free Up the ASCIIFY string
135
			}
136
*/
137
				encodingType = ENCODING_TYPE_ASCIIFY;
138
			}
139
/*
140
 * End of ASCIIFY temporary fix
141
 */
142
			if (bFromClient == true)
143
				dirString = "CLIENT\" ";
144
			else
145
				dirString = "SERVER\" ";
146
			
147
			if (bSecure == true)
148
				typeString = "HTTPS";
149
			else
150
				typeString = "HTTP";
151
			
152
			
153
			writeString("<TRCPacket ticket=\"" + Integer.toString(iTicket) +
154
					"\" connectionNumber=\"" + iConnection.getConnectionNumber() +
155
					"\" timestamp=\"" + Long.toString(TimeStampDispatcher.getTimeStamp())+
156
					"\" from=\"" + dirString +
157
					" type=\"" + typeString +
158
					"\">\r\n");
159
			
160
			StringBuffer strData;
161
				
162
			strData = new StringBuffer("<data length=\"" + Integer.toString(bufLength)+
163
				"\" encoding=\"");
164
				
165
			switch (encodingType){
166
				case ENCODING_TYPE_BASE64:
167
					strData.append("BASE64\"");
168
					break;	
169
				case ENCODING_TYPE_ASCIIFY:
170
					strData.append("ASCIIFY\"");
171
					break;	
172
				case ENCODING_TYPE_NONE:
173
				default:
174
					strData.append("NONE\"");
175
					break;
176
			};
177
178
			if (encodingType != ENCODING_TYPE_NONE){
179
				strData.append(" encodedLength=\"" + Integer.toString(encodedLength) + "\" ");
180
			}
181
			strData.append(" type=\"HTTPDATA\" ><![CDATA[");
182
			String strTemp = new String(strData);
183
			writeString(strTemp);
184
				
185
			if (encodingType == ENCODING_TYPE_ASCIIFY){
186
				flushStreamWriter();
187
				writeBytes(byteEncodedArray, 0, encodedLength);
188
				byteEncodedArray = null;
189
			}else if (encodingType == ENCODING_TYPE_NONE){
190
				flushStreamWriter();
191
				writeBytes(buffer, 0, bufLength);
192
			}else{  // ENCODING_TYPE_BASE64
193
				writeString(strEncoded);
194
			}
195
			writeString(DATA_TAGEND);
196
			writeString(PACKET_TAGEND);
197
			//flushOutputStream();
198
		}
199
		catch (Exception e){
200
			e.printStackTrace();	
201
		}
202
		return bRet;
203
	}
204
	
205
	public synchronized boolean writeOpenConnectionInfo(boolean bSecure,
206
			int iConnection,
207
			String strServer,
208
			int port,	
209
			Socket client,
210
			Socket server,
211
			SSLSocket sslClient,
212
			SSLSocket sslServer){
213
		
214
		try{
215
			
216
			
217
			// mdd long timeStamp = TimeStampDispatcher.getTimeStamp();
218
			iTicket = TicketDispatcher.getTicket();
219
			//InetAddress tempaddr = client.getInetAddress();
220
			InetAddress lh = InetAddress.getLocalHost();
221
			String tmpLocalhost = lh.toString();
222
			String localHostStr = getAddressFromLocalhost(tmpLocalhost);
223
	
224
			//String tempStr = tempaddr.toString();
225
			//String prtString = "";
226
			
227
			//prtString = removeLeadingSlash(tempStr);
228
			
229
			writeString("<TRCConnection type=\"OPEN\" ticket=\"" +
230
					Integer.toString(iTicket) +
231
					"\" connectionNumber=\"" +
232
					Integer.toString(iConnection) +
233
					"\" timestamp=\"" +
234
					Long.toString(TimeStampDispatcher.getTimeStamp())+
235
					"\">\r\n<servername>\r\n" + strServer +
236
					"</servername>\r\n<port>" + Integer.toString(port) +
237
					"</port>\r\n" +
238
					//"<clientInetAddress>" + prtString + "</clientInetAddress>\r\n" +	
239
					"<clientInetAddress>" + localHostStr + "</clientInetAddress>\r\n" +
240
					"<clientPort>" + Integer.toString(client.getPort()) + "</clientPort>\r\n" +			
241
			"</TRCConnection>\r\n\r\n"); 
242
			//flushOutputStream();
243
			String thisconn = Integer.toString(iConnection);
244
			CleanupObj clean = new CleanupObj();
245
			clean.setThisSocket(server);
246
			clean.setThisWriter(this);
247
			clean.setThisConnection(thisconn);
248
			GlobalSocketList.add(thisconn,clean);
249
		}
250
		catch (Exception e){											 	
251
		}
252
		
253
		return true;	
254
	}
255
	
256
	public synchronized boolean writeOpenSecureConnectionInfo(boolean bSecure,
257
			int iConnection,
258
			String strServer,
259
			int port,	
260
			Socket client,
261
			Socket server,
262
			SSLSocket sslClient,
263
			SSLSocket sslServer,
264
			String cipherSuite,
265
			String sslProtocol){
266
		
267
		try{
268
			
269
			
270
			// mdd long timeStamp = TimeStampDispatcher.getTimeStamp();
271
			iTicket = TicketDispatcher.getTicket();
272
			InetAddress tempaddr = client.getInetAddress();
273
			String tempStr = tempaddr.toString();
274
			
275
			String prtString = "";
276
			
277
			prtString = removeLeadingSlash(tempStr);
278
			
279
			writeString("<TRCConnection type=\"OPEN\" ticket=\"" +
280
					Integer.toString(iTicket) +
281
					"\" connectionNumber=\"" +
282
					Integer.toString(iConnection) +
283
					"\" timestamp=\"" +
284
					Long.toString(TimeStampDispatcher.getTimeStamp())+
285
					"\">\r\n<servername>\r\n" + strServer +
286
					"</servername>\r\n<port>" + Integer.toString(port) +
287
					"</port>\r\n" +
288
					"<clientInetAddress>" + prtString + "</clientInetAddress>\r\n" +
289
					"<clientPort>" + Integer.toString(client.getPort()) + "</clientPort>\r\n" +	
290
					"<cipherSuite>" + cipherSuite + "</cipherSuite>\r\n" +
291
					"<protocol>" + sslProtocol + "</protocol>\r\n" +
292
			"</TRCConnection>\r\n\r\n"); 
293
			//flushOutputStream();
294
			
295
		}
296
		catch (Exception e){											 	
297
		}
298
		String tmpConn = "";
299
		
300
		tmpConn = Integer.toString(iConnection);
301
		CleanupObj tmpCleanup = new CleanupObj();
302
		tmpCleanup.setThisSocket(server);
303
		tmpCleanup.setThisWriter(this);
304
		tmpCleanup.setThisConnection(tmpConn);
305
		
306
		GlobalSocketList.add(tmpConn,tmpCleanup);
307
		
308
		
309
		return true;	
310
	}
311
	
312
	
313
	public synchronized boolean writeCloseConnectionInfo(ConnectionObj iConnection){
314
		
315
		String originalConnectionNumber = Integer.toString(iConnection.getConnectionNumber());											 	
316
		try{
317
			
318
			
319
			// long timeStamp = TimeStampDispatcher.getTimeStamp();
320
			iTicket = TicketDispatcher.getTicket();
321
			
322
			
323
			writeString("<TRCConnection type=\"CLOSE\" ticket=\"" +
324
					Integer.toString(iTicket) +
325
					"\" connectionNumber=\"" +
326
					//Integer.toString(iConnection) +
327
					iConnection.getConnectionNumber() +
328
					"\" timestamp=\"" +
329
					Long.toString(TimeStampDispatcher.getTimeStamp())+
330
			"\"/>\r\n"); 
331
			//flushOutputStream();
332
			//writeRecorderMessage(1, "WRITECLOSECONNECTION - NOW RESET to 0");
333
			iConnection.setConnectionNumber(0);
334
		}
335
		catch (Exception e){											 	
336
			e.printStackTrace();
337
		}
338
		GlobalSocketList.remove(originalConnectionNumber,this);
339
		return true;	
340
	}
341
	public synchronized boolean writeConnectConnectionInfo(int iConnection){
342
		
343
		try{
344
			
345
			// long timeStamp = TimeStampDispatcher.getTimeStamp();
346
			iTicket = TicketDispatcher.getTicket();
347
			
348
			writeString("<TRCConnection type=\"CONNECT\" ticket=\"" +
349
					Integer.toString(iTicket) +
350
					"\" connectionNumber=\"" +
351
					//Integer.toString(iConnection) +
352
					iConnection +
353
					"\" timestamp=\"" +
354
					Long.toString(TimeStampDispatcher.getTimeStamp())+
355
			"\"/>\r\n"); 
356
			//flushOutputStream();
357
		}
358
		catch (Exception e){											 	
359
			e.printStackTrace();
360
		}
361
		return true;	
362
	}
363
364
	
365
	public synchronized boolean writeRecorderStartInfo(int iProxyRecorderPort, 
366
			String iProxyAddr, int iProxyPort, String iSSLProxyAddr, int iSSLProxyPort){
367
		
368
		try{
369
			//long timeStamp = TimeStampDispatcher.getTimeStamp();
370
			iTicket = TicketDispatcher.getTicket();
371
			Properties prop = System.getProperties();
372
			writeString(XML_IDENT);
373
			String recorderInfo = "";
374
			Date now = new Date();
375
			SimpleDateFormat militaryTime = new SimpleDateFormat("MM/dd/yyyy kk:mm:ss");
376
			
377
			
378
			
379
			
380
			recorderInfo = "<TRCRecorderInfo type=\"start\" ticket=\"" +
381
			Integer.toString(iTicket) +
382
			"\" timestamp=\"" +
383
			Long.toString(TimeStampDispatcher.getTimeStamp())+
384
			"\">\r\n<recorderport>" +  Integer.toString(iProxyRecorderPort) +
385
			// "</recorderport>\r\n<date>" + date.toLocaleString() + "</date>\r\n" +
386
			"</recorderport>\r\n<date>" + militaryTime.format(now) + "</date>\r\n" +
387
			"<recorderversion>4.4.0.2</recorderversion>\r\n" +
388
			"<javavmversion>" + prop.getProperty("java.vm.version") + "</javavmversion>\r\n" + 
389
			"<javavmvendor>" + prop.getProperty("java.vm.vendor") + "</javavmvendor>\r\n" +
390
			"<javahome>" + prop.getProperty("java.home") + "</javahome>\r\n" + 
391
			"<osname>" + prop.getProperty("os.name") + "</osname>\r\n" +
392
			"<osversion>" + prop.getProperty("os.version") + "</osversion>\r\n";
393
			if (iProxyAddr != null && iProxyAddr.length() > 0) {
394
				recorderInfo = recorderInfo + "<proxyaddress>" + iProxyAddr + "</proxyaddress>\r\n"+
395
				"<proxyport>" + iProxyPort + "</proxyport>\r\n";
396
			}
397
			if (iSSLProxyAddr != null && iSSLProxyAddr.length() > 0) {
398
				recorderInfo = recorderInfo + "<sslproxyaddress>" + iSSLProxyAddr + "</sslproxyaddress>\r\n"+
399
				"<sslproxyport>" + iSSLProxyPort + "</sslproxyport>\r\n";
400
			}		
401
			
402
			writeString(recorderInfo);
403
			writeString("</TRCRecorderInfo>\r\n\r\n");
404
			
405
			//flushOutputStream();
406
		}
407
		catch (Exception e){											 	
408
		}
409
		
410
		return true;	
411
	}
412
	
413
	public synchronized boolean writeRecorderStopInfo(){
414
		
415
		try{
416
			
417
			
418
			// long timeStamp = TimeStampDispatcher.getTimeStamp();
419
			iTicket = TicketDispatcher.getTicket();
420
			
421
			writeString("<TRCRecorderInfo type=\"STOP\" ticket=\"" +
422
					Integer.toString(iTicket) +
423
					"\" timestamp=\"" +
424
					Long.toString(TimeStampDispatcher.getTimeStamp())+
425
			"\">\r\n");
426
			writeString("</TRCRecorderInfo>\r\n\r\n</TRACE>\r\n");
427
			//flushOutputStream();
428
			bStopRecording = true;
429
		}
430
		catch (Exception e){											 	
431
		}
432
		
433
		return true;	
434
	}
435
	public synchronized boolean writeRecorderBrowserConfigInfo(int iProxyRecorderPort, 
436
			String iProxyAddr, int iProxyPort, String iSSLProxyAddr, int iSSLProxyPort, 
437
			String iProxyOverride, String iProxyAutoConfigURL){
438
		
439
		try{
440
			//long timeStamp = TimeStampDispatcher.getTimeStamp();
441
			iTicket = TicketDispatcher.getTicket();
442
			//Properties prop = System.getProperties();
443
			
444
			String recorderInfo = "";
445
			Date now = new Date();
446
			SimpleDateFormat militaryTime = new SimpleDateFormat("MM/dd/yyyy kk:mm:ss");
447
			
448
//			<TRCRecorderInfo type="WEBBROWSERCONFIG" ticket="2" timestamp="5047">
449
//			<ProxyEnabled>FALSE</ProxyEnabled>
450
//			<ProxyName>NONE</ProxyName>
451
//			<ProxyPort>NONE</ProxyPort>
452
//			<ProxyOverride>NONE</ProxyOverride>
453
//			<AutoConfigURL>NONE</AutoConfigURL>
454
//		</TRCRecorderInfo>
455
456
			
457
			
458
			recorderInfo = "<TRCRecorderInfo type=\"WEBBROWSERCONFIG\" ticket=\"" +
459
			Integer.toString(iTicket) +
460
			"\" timestamp=\"" +
461
			Long.toString(TimeStampDispatcher.getTimeStamp()) + "\">\r\n";
462
//			// TODO MDD need to determine actual data elements for all these
463
//			"\">\r\n<BrowserName>";
464
//			// TODO Must change this to get Browser from preference
465
//			if (Platform.getOS()=="win32") {
466
//				recorderInfo = recorderInfo +  "\"Internet Explorer\"" + "</BrowserName>\r\n" + 
467
//			}
468
//			else {
469
//				recorderInfo = recorderInfo +  "\"Mozilla\"" + "</BrowserName>\r\n" + 
470
//			}
471
			recorderInfo = recorderInfo + "<date>" + militaryTime.format(now) + "</date>\r\n" ;
472
			if (iProxyAddr != null && iProxyAddr.length() > 0) {
473
				recorderInfo = recorderInfo + "<ProxyEnabled>TRUE</ProxyEnabled>\r\n"+
474
				"<ProxyAddress>" + iProxyAddr + "</ProxyAddress>\r\n"+
475
				"<ProxyPort>" + iProxyPort + "</ProxyPort>\r\n";
476
			} else {				
477
				recorderInfo = recorderInfo + "<ProxyEnabled>FALSE</ProxyEnabled>\r\n"+
478
				"<ProxyAddress>NONE</ProxyAddress>\r\n"+
479
				"<ProxyPort>NONE</ProxyPort>\r\n";
480
			}
481
			
482
			if (iSSLProxyAddr != null && iSSLProxyAddr.length() > 0) {
483
				recorderInfo = recorderInfo + "<SSLProxyAddress>" + iSSLProxyAddr + "</SSLProxyAddress>\r\n"+
484
				"<SSLProxyPort>" + iSSLProxyPort + "</SSLProxyPort>\r\n";
485
			}	
486
			// TODO Now need ProxyOverride Info and AutoConfigURL info  will do later
487
			
488
			if (iProxyOverride != null && iProxyOverride.length() > 0) {
489
				recorderInfo = recorderInfo + "<ProxyOverride>" + iProxyOverride + "</ProxyOverride>\r\n";
490
			} else {
491
				recorderInfo = recorderInfo + "<ProxyOverride>" + "NONE" + "</ProxyOverride>\r\n";
492
			}
493
			
494
			if (iProxyAutoConfigURL != null && iProxyAutoConfigURL.length() > 0) {
495
				recorderInfo = recorderInfo + "<ProxyAutoConfigURL>" + iProxyAutoConfigURL + "</ProxyAutoConfigURL>\r\n";
496
			}	else {
497
				recorderInfo = recorderInfo + "<ProxyAutoConfigURL>" + "NONE" + "</ProxyAutoConfigURL>\r\n";
498
			}
499
			
500
			
501
//			recorderInfo = recorderInfo +	"<ProxyOverride>" + "\"NONE\"" + "</ProxyOverride>\r\n" + 
502
//			"<AutoConfigURL>" + "\"NONE\"" + "</AutoConfigURL>\r\n";
503
			
504
			writeString(recorderInfo);
505
			writeString("</TRCRecorderInfo>\r\n\r\n");
506
			
507
			//flushOutputStream();
508
		}
509
		catch (Exception e){											 	
510
		}
511
		
512
		return true;	
513
	}
514
	
515
	public synchronized boolean writeRecorderMessage(int type, String strMessage){
516
		
517
		try{
518
			
519
			
520
			// long timeStamp = TimeStampDispatcher.getTimeStamp();
521
			iTicket = TicketDispatcher.getTicket();
522
			String strType = null;
523
			
524
			switch (type){
525
			case 2:
526
				strType = "ERROR";
527
				break;
528
			default:
529
				strType = "INFORMATION";
530
			break;
531
			};
532
			
533
			writeString("<TRCRecorderInfo type=\"" + strType + "\" ticket=\"" +
534
					Integer.toString(iTicket) +
535
					"\" timestamp=\"" +
536
					Long.toString(TimeStampDispatcher.getTimeStamp())+
537
					"\">\r\n<message>" + strMessage + "</message>\r\n");
538
			writeString("</TRCRecorderInfo>\r\n\r\n");
539
			//flushOutputStream();
540
		}
541
		catch (Exception e){											 	
542
		}
543
		
544
		return true;	
545
	}
546
	
547
	
548
	/**
549
	 *	This utility method converts a passed byte array into a Base 64 encoded
550
	 *	String according to the specification in RFC1521 section 5.2
551
	 */
552
	private static final String mappings = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";//$NON-NLS-1$
553
	private static final String filler = "=";//$NON-NLS-1$
554
	/**
555
	 *	Answer a string representing the Base 64 encoded form of the passed
556
	 *	byte array
557
	 *
558
	 *	@return java.lang.String
559
	 *	@param contents byte[]
560
	 */
561
	
562
	private String getBase64EncodedString(byte[] contents, int bufLength){
563
		
564
		//public static String encode(byte[] contents) {
565
		StringBuffer result = new StringBuffer();
566
		
567
		for (int i = 0; i < bufLength; i = i + 3) {
568
			if (result.length() == 76)
569
				result.append("\n\r");//$NON-NLS-1$
570
			
571
			// output character 1
572
			result.append(mappings.charAt((contents[i] & 0xFC) >> 2));
573
			
574
			// output character 2
575
			int c2 = (contents[i] & 0x03) << 4;
576
			// bugzilla 138644 - replace contents.length with bufLength in line below
577
			//if (i + 1 >= contents.length) {
578
			if (i + 1 >= bufLength) {
579
				result.append(mappings.charAt(c2));
580
				result.append(filler);
581
				result.append(filler);
582
				return result.toString();
583
			}
584
			
585
			c2 |= ((contents[i + 1] & 0xF0) >> 4);
586
			result.append(mappings.charAt(c2));
587
			
588
			// output character 3
589
			int c3 = (contents[i + 1] & 0x0F) << 2;
590
			// bugzilla 138644 - replace contents.length with bufLength in line below
591
			//if (i + 2 >= contents.length) {
592
			if (i + 2 >= bufLength) {
593
				result.append(mappings.charAt(c3));
594
				result.append(filler);
595
				return result.toString();
596
			}
597
			
598
			c3 |= ((contents[i + 2] & 0xC0) >> 6);
599
			result.append(mappings.charAt(c3));
600
			
601
			// output character 4
602
			result.append(mappings.charAt(contents[i + 2] & 0x3F));
603
		}
604
		
605
		return result.toString();
606
	}
607
	
608
	
609
	private byte [] getASCIIFYEncodedByteArray(byte[] buffer, int bufLength)
610
	{
611
		int iLoop, iLoc = 0;
612
		byte b1;
613
		boolean bEncoded = false, bNeedsEncoding = false;
614
		final byte [] asciiRef = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
615
		
616
		byte [] encodedBuf = new byte[bufLength * 4 + 4];
617
		
618
		try{
619
			
620
			for (iLoop = 0; iLoop < bufLength; iLoop++){
621
				b1 = buffer[iLoop];
622
				bNeedsEncoding = isByteBinary(b1);
623
				
624
				// two ascii characters in a row are needed to switch back to 
625
				// non-encoding mode
626
				if (bEncoded && !bNeedsEncoding){
627
					// obviously, check so we don't go past the end
628
					if ((iLoop + 1) < bufLength){
629
						bNeedsEncoding = isByteBinary(buffer[iLoop + 1]);
630
					}
631
				}
632
				if (bNeedsEncoding){
633
					if (iLoop < 50) {  //Check first 50 chars
634
						if (encodedNonASCIIs > 5) {  //for Over 5 Non-ASCIIs
635
							encodedLength = -100;
636
							return encodedBuf;  // Let us BASE64 this one
637
						}
638
					}
639
					if ((b1 != 13) && (b1 != 10) && (b1 != '`'))
640
						encodedNonASCIIs++;
641
					if (!bEncoded){
642
						encodedBuf[iLoc] = '`';
643
						iLoc++;
644
					}
645
					int i = (int)b1;
646
					if (i < 0)
647
						i += 256;
648
					i = i >> 4;
649
					if (i < 0 || i > 15){
650
						i = 0;
651
					}
652
					encodedBuf[iLoc] = asciiRef[i];
653
					iLoc++;
654
					i = (b1 & 0x0f);
655
					if (i < 0 || i > 15){
656
						
657
						i = 0;
658
					}
659
					encodedBuf[iLoc] = asciiRef[i];
660
					iLoc++;
661
					bEncoded = true;
662
				}
663
				else{
664
					if (bEncoded){
665
						encodedBuf[iLoc] = '`';
666
						iLoc++;
667
						bEncoded = false;
668
					}
669
					encodedBuf[iLoc] = buffer[iLoop];
670
					iLoc++;
671
				}	
672
			}
673
			if (bEncoded){
674
				encodedBuf[iLoc] = '`';
675
				iLoc++;
676
			}
677
			encodedLength = iLoc;
678
		}
679
		catch (Exception e){
680
			e.printStackTrace();
681
		}
682
		
683
		return encodedBuf;
684
	}
685
	
686
//[TDA Rewrote]		
687
	private boolean isByteBinary(byte b){
688
		boolean bRet = false;
689
		// the ']' character is included to guard against writing a "]]>" which
690
		// would terminate a CDATA tag and backQuote is the escape char
691
		if ((b == ']') || (b == '`'))  
692
			bRet = true;
693
		else if ((b < 32) || (b > 126)){
694
			if ((b != '\n') && (b != '\t'))  //Preserve for readability
695
				bRet = true;
696
		}
697
		return bRet;	
698
	}
699
//[TDA Rewrote]		
700
701
	protected void flushOutputStream() throws IOException
702
	{
703
		//if(agent==null)
704
		//	to_file.flush();
705
	}
706
	
707
	private void flushStreamWriter() throws IOException
708
	{
709
		//if(agent == null)
710
		//	to_fileXML.flush();
711
	}
712
	
713
	protected void writeString(String data) throws IOException
714
	{
715
		if (!bStopRecording)
716
			packetQueue.add(data);
717
		/*if(agent!=null && !bStopRecording)
718
			agent.sendByteDataToDataProcessor(data.getBytes(), 0, data.getBytes().length);
719
			*/
720
		//else
721
		//	to_fileXML.write(data);
722
	}
723
	
724
	private void writeBytes(byte[] buffer, int iOffset, int buflength) throws IOException
725
	{
726
		if (!bStopRecording)
727
			packetQueue.add( buffer,iOffset,buflength);
728
		/*if(agent!=null && !bStopRecording)
729
			agent.sendByteDataToDataProcessor(buffer, iOffset, buflength);
730
			*/
731
		
732
		//else
733
		//	to_file.write(buffer,0,buflength);
734
	}
735
736
	public void sendToDataProcessor(byte[] byteBuf) {
737
		if(agent!=null) {
738
			agent.sendByteDataToDataProcessor(byteBuf, 0, byteBuf.length);
739
		}
740
	}
741
	public void flushRemainingPackets () {
742
		//writeRecorderMessage(1, "IN flushRemainingPackets(), call Initiate Shutdown");
743
		packetQueue.initiateShutdown();
744
		try {
745
			packetQueue.join();
746
		} catch (Exception e) {
747
			//
748
		}
749
	}
750
751
	/**
752
	 * @return
753
	 */
754
	public RecorderAgent getAgentController()
755
	{
756
		return agent;
757
	}
758
	public String removeLeadingSlash(String originalString) {
759
		String prtString = "";
760
		if (originalString.startsWith("/")) {
761
			prtString = originalString.substring(1);
762
		}
763
		else 
764
			prtString = originalString;
765
		
766
		return prtString;
767
	}
768
	public String getAddressFromLocalhost(String originalString) {
769
		String retString = "";
770
		int foundSlash = -1;
771
		
772
		foundSlash = originalString.indexOf("/");
773
		if (foundSlash == -1) {
774
			retString = originalString;
775
		} else {
776
			retString = originalString.substring(foundSlash + 1);
777
		}
778
		
779
		return retString;
780
	}
781
782
	
783
	public synchronized boolean writeCloseConnectionInfo(String iConnection){
784
		
785
		try{
786
			
787
			//long timeStamp = TimeStampDispatcher.getTimeStamp();
788
			iTicket = TicketDispatcher.getTicket();
789
			
790
			writeString("<TRCConnection type=\"CLOSE\" ticket=\"" +
791
					Integer.toString(iTicket) +
792
					"\" connectionNumber=\"" +
793
					//Integer.toString(iConnection) +
794
					iConnection +
795
					"\" timestamp=\"" +
796
					Long.toString(TimeStampDispatcher.getTimeStamp())+
797
			"\"/>\r\n"); 
798
			//flushOutputStream();
799
		}
800
		catch (Exception e){											 	
801
			e.printStackTrace();
802
		}
803
		return true;	
804
	}
805
	
806
}
(-)src-recorder-http-runner/org/eclipse/hyades/execution/recorder/http/remote/messages.properties (-29 lines)
Removed Link Here
1
###############################################################################
2
# Copyright (c) 2005, 2007 IBM Corporation and others.
3
# All rights reserved. This program and the accompanying materials
4
# are made available under the terms of the Eclipse Public License v1.0
5
# which accompanies this distribution, and is available at
6
# http://www.eclipse.org/legal/epl-v10.html
7
# $Id: messages.properties,v 1.2 2007/04/19 12:19:36 paules Exp $
8
#
9
# Contributors:
10
# IBM Corporation - initial API and implementation
11
###############################################################################
12
#
13
# httprecRunner.properties
14
#
15
# NOTE:  When using substitution parameters, all single quote characters (e.g. ') must be escaped with a preceding single quote character (e.g. ''text in single quotes'').
16
#
17
# NLS_MESSAGEFORMAT_VAR
18
# NLS_ENCODING=UTF-8
19
20
RECORDER_CLIENTSIDE_READER_EXCEPTION=exception in ClientSideReader:
21
RECORDER_SSL_SPYSOCKET_EXCEPTION=exception creating SSL SpySocket:
22
RECORDER_ERR_STARTING=Exception trying to start proxy recorder:
23
RECORDER_STARTING_SSLPROXYRECORDER=about to start SSLProxyServer
24
RECORDER_LISTENING_TO_PORT=proxy recorder listening to port
25
RECORDER_CREATING_CLIENTSIDEREADER=Error Creating ClientSideReader
26
RECORDER_BIND_ERROR=Error Binding to Port:
27
RECORDER_TOO_MANY_BIND_ERROR=Too Many Bind Errors - Error Binding to Port:
28
RECORDER_NOTIFY_ON_ADD=TRUE
29
RECORDER_PACKET_WAIT_TOLERANCE=500
(-)src-recorder-http-runner/org/eclipse/hyades/execution/recorder/http/remote/GlobalSocketList.java (-116 lines)
Removed Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2005, 2007 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: GlobalSocketList.java,v 1.7 2007/05/02 19:36:27 paules Exp $
8
 * 
9
 * Contributors:
10
 *     IBM Corporation - initial API and implementation
11
 *******************************************************************************/
12
package org.eclipse.hyades.execution.recorder.http.remote;
13
import java.net.Socket;
14
import java.util.HashMap;
15
import java.util.Iterator;
16
import java.util.Set;
17
18
/**
19
 * This is the object that is used to put items on the linked list and take elements
20
 * off the linked list.
21
 *  
22
 * @author mdunn
23
 * @deprecated  This is not public API.  It will be moved to internal in TPTP 5
24
 * 
25
 */
26
public class GlobalSocketList {
27
	private static HashMap socketList = new HashMap();
28
	public static void add(String key, CleanupObj thisClean) {
29
		
30
		synchronized (socketList) {
31
			try {
32
				socketList.put(key, thisClean);
33
			} catch (Exception e) {
34
			}
35
		}
36
	}
37
	public static void remove(String key, PacketWriter tmpWriter) {
38
		synchronized (socketList) {
39
			socketList.remove(key);
40
			//tmpWriter.writeRecorderMessage(1, "After Remove Key: " + key + " Size is: " + numSockets);
41
		}
42
	}
43
	public static void killAllOpenSockets(PacketWriter tmpWriter) {
44
		Set thisSet = socketList.keySet();
45
		Iterator it = thisSet.iterator();
46
		String thisKey = "";
47
		Socket thisSocket = null;
48
		int numSockets = 0;
49
		CleanupObj tmpCleanup = null;
50
		synchronized (socketList) {
51
			numSockets = thisSet.size();
52
53
			if (numSockets > 0) {
54
				
55
				try {
56
					Thread.yield();
57
					Thread.sleep(1000);
58
				} catch (InterruptedException e) {
59
				}
60
				while (it.hasNext()) {
61
					thisKey = (String) it.next();
62
					//thisSocket = (Socket)socketList.get(thisKey);
63
					tmpCleanup = (CleanupObj) socketList.get(thisKey);
64
					thisSocket = tmpCleanup.getThisSocket();
65
					
66
					try {
67
						thisSocket.close();
68
						Thread.yield();
69
					} catch (Exception ioe) {
70
						System.out.println("In killAllOpenSockets() exception: "
71
										+ ioe.getMessage());
72
					}
73
				}
74
			}
75
		}
76
	}
77
	public static void writeCloseMessages(PacketWriter tmpWriter) {
78
79
		String thisKey = "";
80
		Socket thisSocket = null;
81
		int numSockets = 0;
82
		CleanupObj tmpCleanup = null;
83
		String tmpNumberStr = "";
84
		
85
		try {
86
			// let close() finish and write close message if it can 
87
			Thread.yield();
88
			Thread.sleep(1000);
89
		} catch (InterruptedException e) {
90
		}
91
		
92
		synchronized (socketList) {
93
			Set thisSet = socketList.keySet();
94
			Iterator it = thisSet.iterator();
95
			numSockets = thisSet.size();
96
97
			if (numSockets > 0) {
98
				
99
				while (it.hasNext()) {
100
					thisKey = (String) it.next();
101
					tmpCleanup = (CleanupObj) socketList.get(thisKey);
102
					thisSocket = tmpCleanup.getThisSocket();
103
					try {
104
						tmpNumberStr = tmpCleanup.getThisConnection();
105
						tmpWriter.writeCloseConnectionInfo(tmpNumberStr);
106
						thisSocket.close();
107
						Thread.yield();
108
					} catch (Exception ioe) {
109
						System.out.println("In writeCloseMessages() exception: "
110
										+ ioe.getMessage());
111
					}
112
				}
113
			}
114
		}
115
	}
116
}
(-)src-recorder-http-runner/org/eclipse/hyades/execution/recorder/http/remote/SSLCheckClass.java (-448 lines)
Removed Link Here
1
/**********************************************************************
2
 * Copyright (c) 2005, 2007 IBM Corporation and others.
3
 * All rights reserved.   This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: SSLCheckClass.java,v 1.11 2007/05/03 01:50:21 paules Exp $
8
 * 
9
 * Contributors: 
10
 * IBM Corporation - initial API and implementation
11
 **********************************************************************/
12
/*
13
 * Created on Nov 14, 2003
14
 *
15
 * To change the template for this generated file go to
16
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
17
 */
18
package org.eclipse.hyades.execution.recorder.http.remote;
19
import java.io.FileInputStream;
20
import java.io.IOException;
21
import java.net.Socket;
22
import java.security.KeyStore;
23
import java.util.Enumeration;
24
import java.util.StringTokenizer;
25
import java.util.Vector;
26
27
import javax.net.ssl.KeyManagerFactory;
28
import javax.net.ssl.SSLContext;
29
import javax.net.ssl.SSLSession;
30
import javax.net.ssl.SSLSessionContext;
31
import javax.net.ssl.SSLSocket;
32
import javax.net.ssl.SSLSocketFactory;
33
import javax.net.ssl.TrustManager;
34
35
/**
36
 * @author mdunn
37
 * @deprecated  This is not public API.  It will be moved to internal in TPTP 5
38
 * 
39
 * This class does all the SSL connections 
40
 *  
41
 */
42
public class SSLCheckClass {
43
	String sslCipherSuite = "";
44
	String sslProtocol = "";
45
	SSLContext serverSideConnectionContext = null;
46
	String sslKeyFile = "C:\\testkeys";
47
	
48
	
49
	public boolean makeSecureConnection() {
50
		//csr.packetWriter.writeRecorderMessage(1, "IN makeSecureConnection()- call connectToSecureServer() for connection: " + csr.iConnection);	
51
		if ((connectToSecureServer(csr.destServer, csr.serverPort)) == true){
52
			if ((createSSLSpyServerSocket()) == true) {
53
				checkRightSideContexts();
54
				
55
				csr.packetWriter.writeOpenSecureConnectionInfo(csr.bSecure, csr.iConnection, 
56
					csr.destServer, csr.serverPort, csr.client, csr.httpServer, spySocket, 
57
					sslServer, csr.sslCipherSuite, csr.sslProtocol);
58
			}
59
			try {
60
				csr.to_client= spySocket.getOutputStream();
61
				csr.from_client = spySocket.getInputStream();
62
						
63
				// these are the decrypted streams
64
				csr.to_server = sslServer.getOutputStream();
65
				csr.from_server = sslServer.getInputStream();
66
				//Temporarily Removed - mdd 11/10/2004
67
				//csr.httpServer.close();
68
				csr.httpServer = sslServer;
69
70
				csr.bSecure = true;
71
				csr.serverReader = new ServerSideReader(csr.client,
72
													csr.httpServer,
73
													csr.from_server,
74
													csr.to_client,
75
													 csr.packetWriter,
76
													 //csr.iConnection,
77
													 csr.connectionNumber,
78
													 csr.bSecure,
79
													 spySocket.getReceiveBufferSize());
80
				csr.serverReader.start();
81
			} 
82
			catch (IOException e) {
83
				csr.packetWriter.writeRecorderMessage(2, "exception in creating SSL Spy Socket: " + e);
84
				csr.packetWriter.getAgentController().reportException(SpySocketException,e);
85
				return false;
86
			}
87
		}
88
		csr.bNoPrintToServer = true;
89
		//csr.bSecure = isSecure;
90
		//return isSecure;
91
		return csr.bSecure;
92
	}
93
	public boolean connectToSecureServer(String destStr, int port){
94
		SSLContext ctx = null;
95
		try{
96
			//csr.packetWriter.writeRecorderMessage(1, "IN connectToSecureServer() for connection: " + csr.iConnection);
97
			SSLSocketFactory ssf = null;
98
			//TODO  use createSocket method that uses socket as input 
99
			TrustManager[] myTM = new TrustManager [] {new RecorderX509TrustManager() };
100
			//SSLContext ctx = SSLContext.getInstance("SSL");
101
			ctx = SSLContext.getInstance("SSL");
102
			ctx.init(null, myTM, null);
103
104
			ssf = ctx.getSocketFactory();			
105
			//sslServer = (SSLSocket)sslFact.createSocket(httpServer,destServer, serverPort,true);
106
			sslServer = (SSLSocket)ssf.createSocket(destStr, port);
107
			// when startHandshake returns, an SSL connection is
108
			// satisfied and handshaking is done transparently to this code
109
			// remove after testing
110
111
			sslServer.startHandshake();
112
		}
113
		catch (Exception e){
114
			csr.packetWriter.writeRecorderMessage(2, "exception in ClientSideReader: " + e);
115
			csr.packetWriter.getAgentController().reportException(ClientSideReaderException,e);
116
			return false;
117
		}
118
		serverSideConnectionContext = ctx;
119
		
120
		//csr.packetWriter.writeRecorderMessage(1, "LEAVING connectToSecureServer() for connection: " + csr.iConnection);
121
		return true;
122
	}		
123
	
124
	SSLSocket sslServer = null;
125
	SSLSocket spySocket = null;
126
	ClientSideReader csr = null;
127
	SSLSocket HTTPServerSocket = null;
128
	
129
	// ClientSideReaderHTTP csrHTTP = null;
130
	static final String SpySocketException = HttpRecResourceBundle.RECORDER_SSL_SPYSOCKET_EXCEPTION;
131
	static final String ClientSideReaderException = HttpRecResourceBundle.RECORDER_CLIENTSIDE_READER_EXCEPTION;
132
133
	// a call here means the client has issued a CONNECT statement to this proxy server
134
	// we will attempt to open a separate secure connection to the requested server on the
135
	// requested port
136
	public SSLCheckClass(ClientSideReader thisCSR, String testKeys) {
137
		super();
138
		this.sslKeyFile = testKeys;
139
		csr = thisCSR; 
140
		
141
	}
142
143
	/**
144
	 * @param thisCSR
145
	 * @deprecated
146
	 */
147
	public SSLCheckClass(ClientSideReader thisCSR)
148
	{
149
		this(thisCSR, "C:\\testkeys");
150
	}
151
	
152
	public boolean createSSLSpyServerSocket(){	
153
	
154
		SSLSocketFactory ssf = null;
155
		SSLContext ctx = null;
156
		try {
157
		// set up key manager to do server authentication
158
		
159
		KeyManagerFactory kmf;
160
		KeyStore ks;
161
		char[] passphrase = "passphrase".toCharArray();
162
		String vendor = System.getProperty("java.vm.vendor");
163
	
164
		if ((vendor.indexOf("Sun")) >= 0){
165
			// The following to use Sun JVM
166
			ctx = SSLContext.getInstance("TLS");
167
			kmf = KeyManagerFactory.getInstance("SunX509");
168
		}
169
		else{
170
			// or use the following for the IBM JVM
171
			ctx = SSLContext.getInstance("SSL_TLS");
172
			kmf = KeyManagerFactory.getInstance("IbmX509");
173
		}
174
		
175
		ks = KeyStore.getInstance("jks");
176
177
		// TODO Need better place for testkeys file
178
		if (sslKeyFile == null || sslKeyFile.length() == 0)
179
			sslKeyFile = "C:\\testkeys";
180
		ks.load(new FileInputStream(sslKeyFile), passphrase);
181
		kmf.init(ks, passphrase);
182
		ctx.init(kmf.getKeyManagers(), null, null);
183
		ssf = ctx.getSocketFactory();
184
		
185
		spySocket = (SSLSocket)ssf.createSocket(csr.client,
186
				 "localhost", csr.client.getLocalPort(), true);
187
		spySocket.setUseClientMode(false);
188
		}
189
		catch (Exception e) {
190
			csr.packetWriter.writeRecorderMessage(2, "exception in creating SSL Spy Socket: " + e);
191
			csr.packetWriter.getAgentController().reportException(SpySocketException,e);
192
			return false;
193
		}
194
		//clientSideConnectionContext = ctx;
195
		return true;
196
	}	
197
	// bugzilla 137958 modify the call to use a byte array and length, not a string 
198
	public boolean makeSecureConnectionHTTP(byte[] proxyConnect, int proxyLength, String proxyAddr,int proxyPort, boolean diffSSLProxy) {
199
		boolean isOK = false;
200
		boolean sslConnectOK = false;
201
		if (proxyLength > 0) {		
202
			// defect 79219 mdd 
203
			if (diffSSLProxy) {
204
				sslConnectOK = connectToProxyServerSSL(proxyAddr, proxyPort);
205
				if (sslConnectOK == false)
206
					return false;
207
				// point buffers to correct place
208
				try {
209
					csr.to_server = csr.httpSSLServer.getOutputStream();
210
					csr.from_server = csr.httpSSLServer.getInputStream();
211
				} catch (Exception e) {
212
					csr.packetWriter.writeRecorderMessage(2, "exception in ClientSideReader : " + e + " Connection: " + csr.iConnection);
213
					csr.packetWriter.getAgentController().reportException(ClientSideReaderException,e);
214
				}
215
				// bugzilla 137958 modify the call to use a byte array and length, not a string
216
				isOK = sendConnectToProxyServer(proxyConnect, proxyLength);
217
			}
218
			else {
219
				// Send CONNECT string to HTTP Proxy Server
220
				// bugzilla 137958 modify the call to use a byte array
221
				isOK = sendConnectToProxyServer(proxyConnect, proxyLength);
222
			}
223
			if (!isOK) {
224
				return false;
225
			}
226
			
227
			// Now convert current httpServer Socket into SSL Socket 
228
			
229
			//if ((connectToSecureServer(csr.destServer, csr.serverPort)) == true){
230
			boolean conversionOK = false;
231
			conversionOK = convertHTTPServerConnectionToSSL(proxyAddr,proxyPort);
232
			if (conversionOK == true) {
233
				if ((createSSLSpyServerSocket()) == true)
234
					checkRightSideContexts();
235
					csr.packetWriter.writeOpenSecureConnectionInfo(csr.bSecure,csr.iConnection, 
236
							proxyAddr, proxyPort, csr.client,csr.httpServer, 
237
							spySocket, sslServer,csr.sslCipherSuite,csr.sslProtocol);
238
				try {
239
					csr.to_client= spySocket.getOutputStream();
240
					csr.from_client = spySocket.getInputStream();
241
					// csr.client=(SSLSocket)spySocket;
242
							
243
					// these are the decrypted streams
244
					// new thing below - mdd
245
					csr.httpServer = HTTPServerSocket;
246
					csr.to_server = HTTPServerSocket.getOutputStream();
247
					csr.from_server = HTTPServerSocket.getInputStream();
248
					csr.bSecure = true;
249
					csr.secureConnectionOK = true;
250
					csr.serverReader = new ServerSideReader(csr.client,
251
														csr.httpServer,
252
														csr.from_server,
253
														csr.to_client,
254
														 csr.packetWriter,
255
														 //csr.iConnection,
256
														 csr.connectionNumber,
257
														 csr.bSecure,
258
														 spySocket.getReceiveBufferSize());
259
					csr.serverReader.start();
260
				} 
261
				catch (IOException e) {
262
					csr.packetWriter.writeRecorderMessage(2, "exception in creating SSL Spy Socket: " + e);
263
					csr.packetWriter.getAgentController().reportException(SpySocketException,e);
264
					return false;
265
				}
266
			}
267
		}
268
		csr.bNoPrintToServer = true;
269
		return csr.bSecure;
270
	}
271
	
272
	// bugzilla 137958 modify the call to use a byte array	
273
	boolean sendConnectToProxyServer(byte[] sendBuffer, int bufferLength){
274
		boolean isOK = false;
275
		// bugzilla 103181 
276
		int status = -1;
277
		boolean foundOK = false;
278
		boolean proxyAuthentication = false;
279
		if (bufferLength > 0) {		
280
				// Send CONNECT string to HTTP Proxy Server
281
				try {
282
			
283
					byte[] ackBuffer = new byte[csr.httpServer.getReceiveBufferSize()];
284
						
285
					csr.to_server.write(sendBuffer, 0, bufferLength);
286
					csr.to_server.flush();	
287
					int ackBytes_read = csr.from_server.read(ackBuffer);
288
					if (ackBytes_read > 0){
289
						// check for status
290
						String statusLine = new String(ackBuffer, 0, ackBytes_read); 
291
						// bugzilla 103181 mdd 7/26/2006
292
						// also send 407 (proxy authentication ) through to the browser client
293
						status = getStatus(statusLine);
294
						if (status == 200) {
295
							//int findOK = statusLine.indexOf(" 200 ");
296
							foundOK = true;
297
						}
298
						//	 bugzilla 103181 mdd 7/26/2006
299
						else if (status == 407){
300
							proxyAuthentication = true;
301
						}
302
						// bugzilla 103181 mdd 7/26/2006
303
						if (foundOK || proxyAuthentication == true){
304
							// send OK to client
305
							csr.to_client.write(ackBuffer,0,ackBytes_read);
306
							csr.to_client.flush();
307
							isOK = true;
308
						}
309
						else{
310
							isOK = false;
311
						}
312
					}
313
				
314
				} catch (IOException e) {
315
					csr.packetWriter.writeRecorderMessage(2, "exception in makeSecureConnection(): " + e);
316
					csr.packetWriter.getAgentController().reportException(SpySocketException,e);
317
					return false;
318
				}
319
		}
320
		return isOK;
321
	}
322
	boolean convertHTTPServerConnectionToSSL(String proxyAddr, int proxyPort) {
323
		boolean convertOK = true;
324
		SSLSocketFactory ssf = null;
325
		SSLContext ctx;
326
	
327
		try {
328
329
			TrustManager[] myTM = new TrustManager [] {new RecorderX509TrustManager() };
330
			//SSLContext ctx = SSLContext.getInstance("SSL");
331
			ctx = SSLContext.getInstance("SSL");
332
			ctx.init(null, myTM, null);
333
			ssf = ctx.getSocketFactory();
334
			
335
			HTTPServerSocket = (SSLSocket)ssf.createSocket(csr.httpServer,
336
					csr.destServer, csr.serverPort,true);
337
	//				 proxyAddr, proxyPort, true);
338
			HTTPServerSocket.setUseClientMode(true);
339
			
340
			csr.httpServer = HTTPServerSocket;
341
			// Handshake begins automatically when data passed through socket
342
			//HTTPServerSocket.startHandshake();
343
		}
344
		catch (Exception e) {
345
			csr.packetWriter.writeRecorderMessage(2, "exception in creating HTTPServer Spy Socket: " + e);
346
			csr.packetWriter.getAgentController().reportException(SpySocketException,e);
347
			return false;
348
		}
349
		serverSideConnectionContext = ctx;
350
		return convertOK;
351
	}
352
	public void checkRightSideContexts() {
353
		byte [] clientID;
354
		//Vector allServerSessions = new Vector();
355
		Vector allClientSessions = new Vector();
356
		//Vector allServerCipherSuites = new Vector();
357
		//Vector allServerProtocols = new Vector();
358
		Vector allClientCipherSuites = new Vector();
359
		Vector allClientProtocols = new Vector();
360
		
361
		// first check ServerSide
362
		SSLSessionContext serverClientSessionContext = serverSideConnectionContext.getClientSessionContext();
363
		Enumeration clientE = serverClientSessionContext.getIds();
364
		
365
366
		// Get all Sessions for ClientSideSessionContext
367
		for ( ; clientE.hasMoreElements(); ) {
368
			clientID = (byte [])clientE.nextElement();
369
			allClientSessions.add(serverClientSessionContext.getSession(clientID));
370
		}
371
372
		
373
		// Get all CipherSuites for ClientSideSessions
374
		int clientSessionsCount = allClientSessions.size();
375
		for (int i = 0; i < clientSessionsCount; i++){
376
			SSLSession tempSess = (SSLSession)allClientSessions.elementAt(i);
377
			allClientCipherSuites.add(tempSess.getCipherSuite());
378
			allClientProtocols.add(tempSess.getProtocol());
379
		}	
380
381
		for (int i = 0; i < clientSessionsCount; i++){
382
		//	String tmpProtStr = "Protocol for Client Session ";
383
		//	String tmpProtStr1 = " is : ";
384
		//	String tmpCipherStr = ", CipherSuite is: ";
385
			
386
			String tmpProtocol = (String)allClientProtocols.get(i);
387
			String tmpCipher = (String) allClientCipherSuites.get(i);
388
			if (i == 0) {
389
				csr.sslProtocol = tmpProtocol;
390
				csr.sslCipherSuite = tmpCipher;
391
				//csr.packetWriter.writeRecorderMessage(1, "In CheckRightSide, Assign cipherSuite: " + csr.sslCipherSuite + " Protocol: " + csr.sslProtocol);
392
			}
393
			
394
		//	csr.packetWriter.writeRecorderMessage(1, tmpProtStr + i + tmpProtStr1 + tmpProtocol + tmpCipherStr + tmpCipher);
395
		}
396
		// now set sslCipherSuite if not already set
397
		if ((csr.sslCipherSuite.length() > 0) && (csr.sslProtocol.length()) > 0) {
398
			//csr.packetWriter.writeRecorderMessage(1, "In CheckRightSide, ASSIGN NEW DEFAULTS cipherSuite: " + csr.sslCipherSuite + " Protocol: " + csr.sslProtocol);
399
			csr.defaultCipherSuite = csr.sslCipherSuite;
400
			csr.defaultProtocol = csr.sslProtocol;
401
		}
402
		else {
403
			csr.sslCipherSuite = csr.defaultCipherSuite;
404
			csr.sslProtocol = csr.defaultProtocol;
405
			//csr.packetWriter.writeRecorderMessage(1, "In CheckRightSide, USE DEFAULTS cipherSuite: " + csr.sslCipherSuite + " Protocol: " + csr.sslProtocol);
406
		}
407
	}
408
	private boolean connectToProxyServerSSL(String sslProxyAddr, int sslProxyPort) {
409
		boolean isConnected = false;
410
		// now must connect to IP address
411
		
412
		try {
413
			
414
			csr.httpSSLServer = new Socket(sslProxyAddr, sslProxyPort);
415
			if (csr.httpSSLServer != null) {
416
				//respondToClient(true);
417
				isConnected = true;
418
				csr.httpServer = csr.httpSSLServer;
419
			
420
			}
421
			else {
422
				isConnected = false;
423
				// TODO write error msg to log 
424
				//respondToClient(false);
425
				csr.packetWriter.writeRecorderMessage(1, "Error connecting to Server:" + sslProxyAddr + " Port: "+sslProxyPort);
426
			}
427
		} catch (IOException ioe){
428
			csr.packetWriter.writeRecorderMessage(1, "Error Connecting to Proxy Server:" + sslProxyAddr + ":" + sslProxyPort + ioe);
429
		}			
430
		
431
		return isConnected;
432
	}
433
	private int getStatus(String statLine) {
434
		String	CRNL	= "\r\n";
435
		String BLANK   = " ";
436
		
437
		StringTokenizer bodyTokenizer = new StringTokenizer(statLine, CRNL);
438
		String statusLine = bodyTokenizer.nextToken();
439
		// at this point have HTTP/1.1 407 Proxy Authentication Required
440
		StringTokenizer status = new StringTokenizer(statusLine, BLANK);
441
		status.nextToken();  // This is HTTP/1.1
442
		String actualStatus = status.nextToken();// This is 200 or 302 or 301, etc...
443
		Integer intStat = new Integer(actualStatus);
444
		int actualVal = intStat.intValue();
445
		
446
		return actualVal;
447
	}
448
}
(-)src-recorder-http-runner/org/eclipse/hyades/execution/recorder/http/remote/ServerSideReader.java (-141 lines)
Removed Link Here
1
/**********************************************************************
2
 * Copyright (c) 2005, 2007 IBM Corporation and others.
3
 * All rights reserved.   This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: ServerSideReader.java,v 1.8 2007/05/02 19:36:27 paules Exp $
8
 * 
9
 * Contributors: 
10
 * IBM Corporation - initial API and implementation
11
 **********************************************************************/
12
13
/*
14
 * NONE OF THE QUOTED STRINGS IN THIS FILE ARE TO BE LOCALIZED
15
 * THEY ARE ALL FOR XML TAGS, DEBUGGING SUPPORT, THEY ARE NOT FOR USER INTERFACES
16
 */
17
package org.eclipse.hyades.execution.recorder.http.remote;
18
19
import java.io.FileOutputStream;
20
import java.io.InputStream;
21
import java.io.OutputStream;
22
import java.net.Socket;
23
24
/**
25
 * This object is the server side reader class.  It handles all http traffic 
26
 * from the server and the data is passed through to the client (browser)
27
 * 
28
 * @author dmorris
29
 * modified by:  mddunn 11/17/2003 for Hyades-O 1.2
30
 * @deprecated  This is not public API.  It will be moved to internal in TPTP 5
31
 * 
32
 */
33
34
public class ServerSideReader extends Thread{
35
	InputStream from_server;
36
	OutputStream to_spySocket;
37
	InputStream from_sslPassThroughStream;
38
	OutputStream to_client;
39
	FileOutputStream to_file;
40
	PacketWriter packetWriter = null;
41
	boolean bSecure;
42
	boolean bClosedByClient = false;
43
	int iConnection = 0;
44
	int iReceiveBufSize = 0;
45
	Socket client;
46
	Socket server;
47
	ConnectionObj connectionNumber;
48
	byte[] ssrBuffer = null;
49
	
50
	ServerSideReader(Socket client,
51
					 Socket server,
52
					 InputStream from_server,
53
					 OutputStream to_client,
54
					 PacketWriter packetWriter,
55
					 //int iConnection,
56
					 ConnectionObj connectionNumber,
57
					 boolean bSecure,
58
					 int iReceiveBufSize){
59
		
60
		this.client = client;
61
		this.server = server;
62
		this.from_server = from_server;
63
		this.to_client = to_client;
64
		this.packetWriter = packetWriter;
65
		this.bSecure = bSecure;
66
		this.iConnection = connectionNumber.getConnectionNumber();
67
		this.connectionNumber = connectionNumber;
68
		this.iReceiveBufSize = iReceiveBufSize;
69
		
70
	}
71
	public void setClosedByClient(){
72
		bClosedByClient = true;
73
	}
74
	
75
	public void run(){
76
		
77
		//byte[] buffer = new byte[iReceiveBufSize];
78
		ssrBuffer = new byte[iReceiveBufSize];
79
		int bytes_read = 0;
80
		
81
		this.setName("ServerSideReader-Conn:"+iConnection);
82
		
83
		try{
84
			// Try new statement below mdd
85
			//packetWriter.writeRecorderMessage(1, "IN SERVERSIDEREADER BEGIN READING... for Connection: " + iConnection );
86
			while ((bytes_read = from_server.read(ssrBuffer)) >= 0){
87
				
88
/*				to_client.write(ssrBuffer,0, bytes_read);
89
				to_client.flush();*/
90
				//  Defect 83619 mdd synch for write to socket and write to file
91
				packetWriter.writePacket(bSecure, false, this.connectionNumber, ssrBuffer, bytes_read, to_client, false);
92
			}
93
		}
94
		catch (NullPointerException npc) {
95
			packetWriter.writeRecorderMessage(1, "IN SERVERSIDEREADER CAUGHT NULLPOINTEREXCEPTION for Connection: " + iConnection );
96
		}
97
		catch (Exception e) {
98
			//packetWriter.writeRecorderMessage(1, "IN SERVERSIDEREADER GETMESSAGE() for Connection: " + iConnection );
99
			
100
			String mess = e.getMessage();
101
			// no record for the following exceptions, they are expected
102
			
103
			if (mess.indexOf("Stream closed") < 0 && mess.indexOf("Socket closed") < 0 &&
104
					mess.indexOf("JVM_recv in socket input") <0 && mess.indexOf("onnection closed")<0
105
					&& mess.indexOf("socket closed")<0 && mess.indexOf("onnection reset") < 0
106
					&& mess.indexOf("Socket is closed") <0) {
107
				packetWriter.writeRecorderMessage(2, "exception in ServerSideReader connection " + iConnection + " : " + e.toString());
108
			}
109
			
110
		}
111
		finally {
112
			try {
113
				// if the server we are connected to terminated the connection, close the client side also
114
				// if the client closed the connection, just exit
115
				// New stuff 042204
116
			
117
				server.close();
118
				//packetWriter.writeRecorderMessage(1, "WRITE CLOSE CONNECTION for SERVERSIDEREADER Input Side " + iConnection );
119
				packetWriter.writeCloseConnectionInfo(connectionNumber);
120
				// MAY NEED if (!bClosedByClient)
121
				//	client.close();
122
				if (client != null) {
123
					if ((!client.isOutputShutdown()) && !client.isClosed() )
124
					{
125
						client.shutdownOutput();
126
						//packetWriter.writeRecorderMessage(1, "SHUTDOWN CLIENT OUTPUT IN SERVERSIDEREADER FOR Connection: " + iConnection );
127
					} else {
128
						//packetWriter.writeRecorderMessage(1, "CLIENT WAS ALREADY CLOSED IN SERVERSIDEREADER FOR Connection: " + iConnection );	
129
					}
130
				} else {
131
					//packetWriter.writeRecorderMessage(1, "CLIENT WAS NULL IN SERVERSIDEREADER FOR Connection: " + iConnection );
132
				}
133
			}
134
			catch (Exception e){
135
				packetWriter.writeRecorderMessage(2, "exception in ServerSideReader executing finally block connection " + iConnection + " : " + e.toString());
136
				
137
			}
138
		}
139
		//packetWriter.writeRecorderMessage(1, "LEAVING SERVERSIDEREADER " + iConnection );
140
	}
141
}
(-)src-recorder-http-runner/org/eclipse/hyades/execution/recorder/http/remote/ClientSideReader.java (-204 lines)
Removed Link Here
1
/*``````````````````````````````````````````````````````````````/**********************************************************************
2
 * Copyright (c) 2005, 2007 IBM Corporation and others.
3
 * All rights reserved.   This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: ClientSideReader.java,v 1.11 2007/04/26 20:49:12 paules Exp $
8
 * 
9
 * Contributors: 
10
 * IBM Corporation - initial API and implementation
11
 **********************************************************************/
12
13
/*
14
 * NONE OF THE QUOTED STRINGS IN THIS FILE ARE TO BE LOCALIZED
15
 * THEY ARE ALL FOR XML TAGS, DEBUGGING SUPPORT, THEY ARE NOT FOR USER INTERFACES
16
 */
17
package org.eclipse.hyades.execution.recorder.http.remote;
18
19
import java.io.File;
20
import java.io.InputStream;
21
import java.io.OutputStream;
22
import java.lang.reflect.Constructor;
23
import java.lang.reflect.Field;
24
import java.net.InetAddress;
25
import java.net.Socket;
26
27
/**
28
 * This object is the base client side reader class.  It should be extended by specific 
29
 * reader such as SOCKS or HTTP.  It reads from the client (browswer)
30
 * 
31
 * @author dmorris
32
 * modified by:  mddunn 11/17/2003 for Hyades-O 1.2
33
 * @deprecated  This is not public API.  It will be moved to internal in TPTP 5
34
 * 
35
 */
36
abstract public class ClientSideReader extends Thread{
37
	
38
	public static final String ERROR_SSL_REQUEST_MADE = "-1"; //this is an error until SSL is supported
39
	public static final String ERROR_NO_TESTKEYS = "-2"; //this is an error until SSL is supported
40
	static final String STR_KEEP_ALIVE = "Proxy-Connection: Keep-Alive\r\n";
41
	static int iConn = 0;
42
	static final String ClientSideReaderException = HttpRecResourceBundle.RECORDER_CLIENTSIDE_READER_EXCEPTION;
43
	String defaultCipherSuite = "SSL_RSA_WITH_RC4_128_MD5";
44
	String defaultProtocol = "TLSv1";
45
	
46
	InputStream from_client;
47
	OutputStream to_client;
48
	InputStream from_server;
49
	OutputStream to_server;
50
	//Socket client = null;
51
	PeekSocket client = null;
52
	Socket httpServer = null;
53
	// bugzilla 79219 mdd 
54
	Socket httpSSLServer = null;
55
	ServerSideReader serverReader = null;
56
	// this flag indicates whether we are operating an SSL connection
57
	boolean bSecure = false;
58
	boolean bNoPrintToServer = false;
59
	PacketWriter packetWriter = null;
60
	boolean secureConnectionOK = false;
61
62
	String destServer = null;
63
	String keyFile = null;
64
	int serverPort = 80;
65
	int iConnection = 0;
66
	ConnectionObj connectionNumber = new ConnectionObj();
67
	static int isSSLClassAvailable = -1;
68
	static boolean foundTestKeys = false;
69
	// new SSL info
70
	String sslCipherSuite = "";
71
	String sslProtocol = "";
72
	InetAddress newAddr = null;
73
	int destPort = 0;
74
	
75
76
	/**
77
	 * Old constructor to keep old support.  Not intended for new readers.  Use ClientSideReader(PeekSocket, PacketWriter, String)
78
	 * @param client
79
	 * @param packetWriter
80
	 * @deprecated
81
	 */
82
	ClientSideReader(PeekSocket client, PacketWriter packetWriter)
83
	{
84
		this(client, packetWriter, "C:\\testkeys");
85
	}
86
	
87
	ClientSideReader(PeekSocket client, PacketWriter packetWriter, String keyFile){
88
		try{
89
			this.from_client = client.getInputStream();
90
			this.to_client = client.getOutputStream();
91
			this.client = client;
92
			this.iConnection = getNextConnection();
93
			this.connectionNumber.setConnectionNumber(iConnection);
94
			this.packetWriter = packetWriter;
95
			this.keyFile = keyFile;
96
			packetWriter.writeRecorderMessage(1, "Client Connected, connection " + iConnection );
97
			packetWriter.writeConnectConnectionInfo(iConnection );
98
					
99
		}
100
		catch (Exception e){
101
			packetWriter.writeRecorderMessage(2, "exception in ClientSideReader: " + e);
102
			packetWriter.getAgentController().reportException(ClientSideReaderException,e);
103
		}
104
	
105
	}
106
	ClientSideReader(){
107
		
108
	}
109
	synchronized static int getNextConnection(){
110
		iConn++;
111
		return iConn;
112
	}
113
	
114
	abstract public void run();
115
	
116
117
118
//	private static String IP4ByteToString (byte myvar[]) {
119
//		String strResult = "";		
120
//		for (int i = 0; i < 4; i++) {
121
//			if ((int)myvar[i] >= 0) {
122
//				strResult += String.valueOf((int)myvar[i]);
123
//			} else {
124
//				strResult += String.valueOf(256 + (int)myvar[i]);
125
//			}
126
//			if (i < 3) {
127
//				strResult += ".";
128
//			}		
129
//		}
130
//		return strResult;
131
//	}
132
133
	public int findSSLClass() {
134
		int gotSSL = -1;
135
136
		try{
137
				Class.forName("javax.net.ssl.SSLSocket");
138
				gotSSL = 1;
139
			}
140
			catch (ClassNotFoundException cnf){
141
				gotSSL = 0;			
142
			}
143
		return gotSSL;
144
	}
145
146
	public boolean checkForTestKeys() {
147
		if (keyFile == null || keyFile.length() == 0)
148
			keyFile = "C:\\testkeys";
149
		boolean foundIt = false;
150
		File keysFile = new File(keyFile);
151
		foundIt = keysFile.exists();
152
		return foundIt;
153
	}
154
	
155
	
156
	/**
157
	 * This method creates a socket.  If called from a 1.4 JRE, the no-arg
158
	 * Socket() constructor is used.  If called from a Java 5 JRE, we 
159
	 * reflectively call the Socket(Proxy) constructor with Proxy.NO_PROXY
160
	 * as the argument.
161
	 * 
162
	 * This is done becaust the Default Socket on 1.5+ does a Reverse DNS Lookup
163
	 * on every new socket created.  Much overhead for recording.
164
	 * 
165
	 * @return an unconnected Socket.
166
	 */
167
	 Socket createPlainSocket() {
168
		Socket socket = null;
169
170
		// Determine if the Socket(Proxy) constructor exists 
171
		// (it was new in Java 5.)
172
		Class socketClass = Socket.class;
173
		Constructor[] constructors = socketClass.getDeclaredConstructors();
174
175
		try {
176
			Class proxyClass = Class.forName("java.net.Proxy");
177
178
			for (int i=0; i<constructors.length; i++) {
179
				Constructor cons = constructors[i];
180
				Class[] params = cons.getParameterTypes();
181
				if (params.length == 1 && params[0] == proxyClass) {
182
					// Get the NO_PROXY static field from the Proxy class
183
					Field noproxyField = proxyClass.
184
						getDeclaredField("NO_PROXY"); //$NON-NLS-1$
185
					Object noproxy = noproxyField.get(null);
186
					
187
					// Call the Socket(Proxy) constructor
188
					socket = (Socket) cons.newInstance(new Object[]{noproxy});
189
					break;
190
				}
191
			}
192
		}
193
		catch (Exception e) {
194
			// If an exception was thrown, it means we're not in Java 5.
195
			// Ignore the exception and create the socket the old fashioned way.
196
		}
197
198
		if ( socket == null )
199
			socket = new Socket();
200
		
201
		return socket;
202
	}
203
204
}
(-)src-recorder-http-runner/org/eclipse/hyades/execution/recorder/http/remote/ClientSideReaderHTTP.java (-340 lines)
Removed Link Here
1
/*``````````````````````````````````````````````````````````````/**********************************************************************
2
 * Copyright (c) 2005, 2007 IBM Corporation and others.
3
 * All rights reserved.   This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: ClientSideReaderHTTP.java,v 1.12 2007/04/26 20:56:11 paules Exp $
8
 * 
9
 * Contributors: 
10
 * IBM Corporation - initial API and implementation
11
 **********************************************************************/
12
13
/*
14
 * NONE OF THE QUOTED STRINGS IN THIS FILE ARE TO BE LOCALIZED
15
 * THEY ARE ALL FOR XML TAGS, DEBUGGING SUPPORT, THEY ARE NOT FOR USER INTERFACES
16
 */
17
package org.eclipse.hyades.execution.recorder.http.remote;
18
19
import java.io.IOException;
20
import java.net.InetSocketAddress;
21
22
/**
23
 * This class extends the ClientSideReader class. This class handles the specific 
24
 * transactions when the browser is 'talking' HTTP protocol.
25
 * 
26
 * @author dmorris
27
 * modified by:  mddunn 11/17/2003 for Hyades-O 1.2
28
 * @deprecated  This is not public API.  It will be moved to internal in TPTP 5
29
 *  
30
 */
31
public class ClientSideReaderHTTP extends ClientSideReader {
32
	
33
	public static final String ERROR_SSL_REQUEST_MADE = "-1"; //this is an error until SSL is supported
34
	public static final String ERROR_NO_TESTKEYS = "-2"; //this is an error until SSL is supported
35
	static final String STR_KEEP_ALIVE = "Proxy-Connection: Keep-Alive\r\n";
36
	static int iConn = 0;
37
	static final String ClientSideReaderException = HttpRecResourceBundle.RECORDER_CLIENTSIDE_READER_EXCEPTION;
38
	
39
	String iProxyAddr = "";
40
	int iProxyPort = 0;	
41
	boolean secureConnectionOK = false;
42
	// try this mdd
43
	boolean didOpenConnection = false;
44
	boolean wroteOnePacket = false;
45
	// defect 79219 mdd
46
	String iSSLProxyAddr = "";
47
	int iSSLProxyPort = 0;	
48
	
49
	ClientSideReaderHTTP(PeekSocket client, PacketWriter packetWriter,
50
			String keyFile, String proxyAddr, int proxyPort){
51
		super(client,packetWriter, keyFile);
52
		iProxyAddr = proxyAddr;
53
		iProxyPort = proxyPort;
54
	}
55
	
56
	ClientSideReaderHTTP(PeekSocket client, PacketWriter packetWriter,
57
			String keyFile, String proxyAddr, int proxyPort, String sSLProxyAddr, int sSLProxyPort){
58
		super(client,packetWriter, keyFile);
59
		iProxyAddr = proxyAddr;
60
		iProxyPort = proxyPort;
61
		iSSLProxyAddr = sSLProxyAddr;
62
		iSSLProxyPort = sSLProxyPort;
63
	}
64
	
65
	public void run(){
66
		
67
		int bytes_read = 0;
68
		boolean isConnected = false;
69
		
70
		if (isSSLClassAvailable == -1)	{	
71
			isSSLClassAvailable = findSSLClass();
72
			if (isSSLClassAvailable == 1) {
73
				foundTestKeys = checkForTestKeys();
74
			}
75
		}
76
		
77
		this.setName("ClientSideReaderHTTP-"+"Conn:"+iConnection+":"+iProxyAddr+":"+iProxyPort);
78
		try {
79
			
80
			byte[] buffer = new byte[client.getReceiveBufferSize()];
81
			
82
			isConnected = connectToProxyServer();
83
			
84
			if (isConnected ) {
85
				while ((bytes_read = from_client.read(buffer)) != -1){
86
					boolean isConnectRequest = false;
87
					
88
					yield();
89
					bNoPrintToServer = false;
90
					
91
					if (buffer[0] == 'C') {
92
						String str = new String(buffer, 0, bytes_read);
93
						isConnectRequest  = checkForSSLRequest(str);
94
					}
95
					wroteOnePacket = true;
96
					// If bSecure is set to true, leave it alone
97
					
98
					if (isConnectRequest){
99
						if (isSSLClassAvailable == 1)	{
100
							if (foundTestKeys) {
101
								SSLCheckClass thisSSLCheck = new SSLCheckClass(this, keyFile);
102
								to_server = httpServer.getOutputStream();
103
								from_server = httpServer.getInputStream();
104
								if (iSSLProxyAddr.length()> 0 && iSSLProxyPort > 0) {
105
									// defect 79219 last parameter 'true' means we are using a different Proxy for SSL
106
									// bugzilla 137958 modify the call to use a byte array
107
									thisSSLCheck.makeSecureConnectionHTTP(buffer, bytes_read, iSSLProxyAddr, iSSLProxyPort, true);
108
								}
109
								else {
110
									// bugzilla 137958 modify the call to use a byte array
111
									thisSSLCheck.makeSecureConnectionHTTP(buffer,bytes_read, iProxyAddr, iProxyPort, false);
112
								}
113
							}
114
							else  {
115
								// send message to UI 
116
								packetWriter.getAgentController().sendControlMessageToDataProcessor(ERROR_NO_TESTKEYS);
117
								return;
118
							}
119
						}					
120
					}
121
					
122
					// if (!bSecure)
123
					if (!bSecure && !didOpenConnection )
124
						makeRegularConnection();
125
126
					// Defect 83619 mdd synch for write to socket and write to file 
127
					packetWriter.writePacket(bSecure, true, connectionNumber, buffer, bytes_read, to_server, bNoPrintToServer);
128
				}
129
			}  // isConnected is true 
130
			
131
			// mdd this moved to serversidereader 
132
			//packetWriter.writeCloseConnectionInfo(iConnection);
133
			if (httpServer != null){
134
				httpServer.setSoLinger(false,0);
135
				if (!wroteOnePacket) {
136
					if (! httpServer.isClosed()) {
137
						//packetWriter.writeRecorderMessage(1, "IN CLIENTSIDEREADER A1 - CLOSED SERVERSIDE COnnection: " + iConnection);
138
						httpServer.close();
139
					}
140
				}
141
				else if (! httpServer.isOutputShutdown()){
142
					if (bSecure) {
143
						//packetWriter.writeRecorderMessage(1, "IN CLIENTSIDEREADER A WRITING SSL CLOSE ALERT for COnnection: " + iConnection);
144
						to_server.flush();
145
//						// Bugzilla defect 78832 mdd
146
						httpServer.close();
147
					} else {
148
						httpServer.shutdownOutput();
149
						//packetWriter.writeRecorderMessage(1, "IN CLIENTSIDEREADER A - SHUTDOWN SERVERSIDE OUTPUT for COnnection: " + iConnection);
150
					}
151
				}
152
				//	mdd tell Server reader we are closed
153
				if (serverReader != null)
154
					serverReader.setClosedByClient();
155
			}
156
			
157
		}
158
		catch (Exception e) {
159
			// mdd add check 
160
			/* OLD WAY
161
			 if (!httpServer.isClosed())
162
				 packetWriter.writeCloseConnectionInfo(iConnection);
163
				 try {
164
					 if (httpServer != null) {
165
					 if (!httpServer.isClosed())
166
					 httpServer.close();
167
					 // mdd tell Server reader we are closed	
168
					  if (serverReader != null)
169
					  serverReader.setClosedByClient();
170
				  }
171
			  }
172
			  catch (IOException ioe){
173
			  packetWriter.writeRecorderMessage(2, "IOException in ClientSideReader connection " + iConnection + ": "  + ioe);
174
			  } */
175
			// NEW WAY
176
			//packetWriter.writeRecorderMessage(1, "JUST CAUGHT AN EXCEPTION In ClientSideReader connection " + iConnection + " Exception: " +e.getLocalizedMessage() );
177
			
178
			try {
179
				if (httpServer != null) {
180
					//if (!httpServer.isClosed())
181
					//	httpServer.close();
182
					if (!wroteOnePacket) {
183
						if (! httpServer.isClosed()) {
184
							//packetWriter.writeRecorderMessage(1, "IN CLIENTSIDEREADER B1 - CLOSED SERVERSIDE COnnection: " + iConnection);
185
							httpServer.close();
186
						}
187
					} else 	if (!httpServer.isOutputShutdown()){
188
						if (bSecure) {
189
							//packetWriter.writeRecorderMessage(1, "IN CLIENTSIDEREADER B WRITING SSL CLOSE ALERT for COnnection: " + iConnection);
190
							to_server.flush();
191
							// Bugzilla defect 78832 mdd
192
							httpServer.close();
193
						} else {
194
							httpServer.shutdownOutput();
195
							//packetWriter.writeRecorderMessage(1, "IN CLIENTSIDEREADER B - SHUTDOWN SERVERSIDE OUTPUT for COnnection: " + iConnection);
196
						}
197
					}
198
					// mdd tell Server reader we are closed	
199
					// add check for null 032204
200
					//if (serverReader != null)	
201
					// MAT NEED serverReader.setClosedByClient();
202
				}
203
				
204
				yield();
205
206
			}
207
			catch (IOException ioe){
208
				String mess = ioe.getMessage();
209
				// no record for the following exceptions, they are expected
210
				
211
				if (mess.indexOf("Stream closed") < 0 && mess.indexOf("Socket closed") < 0 &&
212
						mess.indexOf("JVM_recv in socket input") <0 && mess.indexOf("onnection closed")<0
213
						&& mess.indexOf("socket closed")<0 && mess.indexOf("onnection reset") < 0
214
						&& mess.indexOf("Socket is closed") <0) {
215
					packetWriter.writeRecorderMessage(2, "IOException in ClientSideReader connection " + iConnection + " : " + e.toString());
216
				}
217
			}
218
			// NEW WAY
219
		}
220
		
221
	}
222
	
223
	
224
	private boolean connectToProxyServer() {
225
		boolean isConnected = false;
226
		// now must connect to IP address
227
		
228
		try {
229
			// This next line ensures we get a "plain" socket which does not do Reverse DNS LookUp
230
			httpServer = createPlainSocket();
231
			InetSocketAddress epoint = new InetSocketAddress(iProxyAddr, iProxyPort);
232
			httpServer.connect(epoint);
233
234
			if (httpServer != null) {
235
				//respondToClient(true);
236
				isConnected = true;
237
			}
238
			else {
239
				isConnected = false;
240
				// TODO write error msg to log 
241
				//respondToClient(false);
242
				packetWriter.writeRecorderMessage(1, "Error connecting to Server:" + destServer + " Port: "+serverPort);
243
			}
244
		} catch (IOException ioe){
245
			packetWriter.writeRecorderMessage(1, "Error Connecting to Proxy Server:" + iProxyAddr + ":" + iProxyPort + ioe);
246
		}			
247
		
248
		return isConnected;
249
	}
250
251
//	private void respondToClient(boolean flag) {
252
//		byte[] reply_buff = new byte[8];
253
//		
254
//		reply_buff[0] = 0;
255
//		if (flag == true){
256
//			reply_buff[1] = 90;
257
//		}
258
//		else {
259
//			reply_buff[1] = 91;
260
//		}
261
//		try {
262
//			to_client.write(reply_buff,0, 8);
263
//			to_client.flush();
264
//		} catch (Exception e){
265
//		}
266
//	}
267
	
268
	private boolean checkForSSLRequest(String request) {
269
		boolean returnCode = false;
270
		int index;
271
		// when a client connects to a proxy for SSL, we get a string of the following form from the client:
272
		//  CONNECT whateverssl.server.com:443\r\n
273
		// that is the string we must parse to do the SSL connection
274
		if ((index = request.indexOf("CONNECT ")) >= 0){
275
			// code here to connect to SSL server
276
			int indexEnd;
277
			returnCode = true;
278
			index += 8;  // go past the word CONNECT + space
279
			if ((indexEnd = request.indexOf(":", index)) > index){
280
				String destStr = request.substring(index, indexEnd);
281
				// now we have server string to go to in destStr, get the port
282
				index = indexEnd + 1; // next character after the colon 
283
				if ((indexEnd = request.indexOf(" ", index)) > index){
284
					int port;
285
					String portStr = request.substring(index, indexEnd);
286
					// now we have the port								
287
					port = Integer.parseInt(portStr);
288
					// now we can try to connect to the secure port
289
					destServer = destStr;
290
					serverPort = port;
291
					//packetWriter.writeOpenConnectionInfo(bSecure, iConnection, destStr, port, client, httpServer, null, null);
292
				}
293
			}
294
		}
295
		return returnCode;
296
	}
297
	
298
	private String makeRegularConnection( ){
299
		
300
		String strReturn = null;
301
		//int index;	
302
		//int port = 80;
303
		//String destStr = null;
304
		//boolean bFoundMessage = false;	
305
		
306
		try{
307
			// Note : already have open port to server
308
			packetWriter.writeOpenConnectionInfo(bSecure, iConnection, iProxyAddr, iProxyPort, client, httpServer, null, null);
309
			
310
			to_server = httpServer.getOutputStream();
311
			from_server = httpServer.getInputStream();
312
			
313
			serverReader = new ServerSideReader(client,
314
					httpServer,
315
					from_server,
316
					to_client,
317
					packetWriter,
318
					connectionNumber,
319
					bSecure,
320
					httpServer.getReceiveBufferSize());
321
			serverReader.start();
322
			
323
		}
324
		catch (Exception e){
325
			packetWriter.writeRecorderMessage(2, "exception in ClientSideReader: " + e);
326
			packetWriter.getAgentController().reportException(ClientSideReaderException,e);
327
			packetWriter.writeCloseConnectionInfo(connectionNumber);
328
			try {
329
				client.close();
330
				strReturn = null;
331
			}
332
			catch (IOException ioe){
333
				packetWriter.writeRecorderMessage(2, "IOException in ClientSideReader connection " + iConnection + ": "  + ioe);
334
			}
335
		}
336
		didOpenConnection = true;
337
		return strReturn;					
338
	}
339
	
340
}
(-)src-recorder-http-runner/org/eclipse/hyades/execution/recorder/http/remote/TimeStampDispatcher.java (-34 lines)
Removed Link Here
1
/**********************************************************************
2
 * Copyright (c) 2005, 2007 IBM Corporation and others.
3
 * All rights reserved.   This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: TimeStampDispatcher.java,v 1.5 2007/05/02 19:36:27 paules Exp $
8
 * 
9
 * Contributors: 
10
 * IBM Corporation - initial API and implementation
11
 **********************************************************************/
12
package org.eclipse.hyades.execution.recorder.http.remote;
13
14
/**
15
 * This class creates the time stamp for each packet of information written to the 
16
 * .rec file.
17
 * 
18
 * @author morris
19
 * @deprecated  This is not public API.  It will be moved to internal in TPTP 5
20
 */
21
public final class TimeStampDispatcher {
22
	static long refTimeStamp = System.currentTimeMillis();
23
	
24
	synchronized static long getTimeStamp(){
25
		long currTime = System.currentTimeMillis();
26
		// the returned value will be the time in milliseconds since the recorder started
27
		return (currTime - refTimeStamp);
28
	}
29
	// method for convenience in case it is needed.
30
	synchronized static void resetRefTimeStamp(){
31
		refTimeStamp = System.currentTimeMillis();
32
	}
33
34
}
(-)src-recorder-http-runner/org/eclipse/hyades/execution/recorder/http/remote/GlobalPacketQueue.java (-172 lines)
Removed Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2005, 2007 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: GlobalPacketQueue.java,v 1.6 2007/04/26 18:49:54 paules Exp $
8
 * 
9
 * Contributors:
10
 *     IBM Corporation - initial API and implementation
11
 *******************************************************************************/
12
package org.eclipse.hyades.execution.recorder.http.remote;
13
import java.util.Collection;
14
import java.util.Iterator;
15
import java.util.LinkedList;
16
import java.util.MissingResourceException;
17
18
/**
19
 * This class is used to hold a linked list of strings that represent the data
20
 * obtained from listening to the http data going from browser to server and 
21
 * server to browser.  That data is then used to  generate XML fragments and then 
22
 * encapsulated in strings.  The generated strings are put on this 'queue' in real time,
23
 * and a separated process pulls the strings off the queue and writes them to the .rec file 
24
 * when no other activity is taking place.
25
 *  
26
 * @author mdunn
27
 * @deprecated  This is not public API.  It will be moved to internal in TPTP 5
28
 * 
29
 */
30
public class GlobalPacketQueue extends Thread {
31
	
32
	static boolean NOTIFY_ON_ADD = false;
33
	
34
	/**
35
	 * Milliseconds to wait for inactivity.
36
	 */
37
	static long PACKET_WAIT_TOLERANCE = 500;
38
	
39
	
40
	static {
41
		try {
42
			String strValue = HttpRecResourceBundle.RECORDER_NOTIFY_ON_ADD;
43
			if (strValue.compareToIgnoreCase("TRUE") == 0) {
44
				NOTIFY_ON_ADD = true;
45
			}
46
		} catch (MissingResourceException e) {
47
			// Use default option
48
		}
49
		
50
		try {
51
			String strValue = HttpRecResourceBundle.RECORDER_PACKET_WAIT_TOLERANCE;
52
			PACKET_WAIT_TOLERANCE = Long.parseLong(strValue);
53
		} catch (Exception e) {
54
			// Use default option
55
		}
56
		
57
	}
58
	
59
	protected PacketWriter packetWriter;
60
	protected boolean shuttingDown = false;
61
	protected long timeOfLastPackedAdd = 0L;
62
	
63
	public GlobalPacketQueue (PacketWriter writer) {
64
		packetWriter = writer;
65
	}
66
	
67
	public void initiateShutdown () {
68
		shuttingDown = true;
69
		synchronized (this) {
70
			notify();
71
		}
72
	}
73
	
74
	public void run () {
75
		this.setName("PacketQueueWriter");
76
		//packetWriter.writeRecorderMessage(1,"IN GlobalPacketQueue.run(), PACKET_WAIT_TOLERANCE is: " + PACKET_WAIT_TOLERANCE);
77
		while (!shuttingDown) {
78
			synchronized (this) {
79
				if (packetQueue.size() == 0) {
80
					//If nothing on queue, wait for another thread to enqueue a packet
81
					try {
82
						wait();
83
					} catch (InterruptedException e) {
84
						//no problem
85
					}
86
				}
87
			}
88
			removeAndWrite ();
89
			Thread.yield();
90
		}
91
		removeAndWrite();
92
	}
93
	
94
95
	protected void removeAndWrite () {
96
		Collection packetsCollection = removeAll();
97
		if (packetsCollection != null) {
98
			Iterator iter = packetsCollection.iterator();
99
			while (iter.hasNext()) {
100
				byte[] bytePacket = (byte[])iter.next(); // get rid of refer
101
				
102
				// only write packet when no activity has 
103
				// occurred in a while
104
				waitForInactivity ();
105
				
106
				packetWriter.sendToDataProcessor (bytePacket);
107
				Thread.yield();
108
			}
109
		}
110
	}
111
112
	/**
113
	 * Sleep until no packet has been added for PACKET_WAIT_TOLERANCE
114
	 * from the previous packet add.
115
	 */
116
	protected void waitForInactivity () {
117
		long lastUpdate, curTime, nextCheckTime;
118
		while (true) {
119
			curTime = System.currentTimeMillis();
120
			lastUpdate = timeOfLastPackedAdd;
121
			nextCheckTime = lastUpdate + PACKET_WAIT_TOLERANCE;
122
			if (nextCheckTime > curTime) {
123
				try {
124
					Thread.sleep(nextCheckTime - curTime);
125
				} catch (InterruptedException e) {
126
					// doesn't matter
127
				}
128
			} else {
129
				break;
130
			}
131
		}
132
	}
133
134
	protected LinkedList packetQueue = new LinkedList();
135
136
	public void add (byte buf[], int offset, int len) {
137
		byte[] tmpBuff = new byte[len];
138
		System.arraycopy(buf,offset,tmpBuff,0,len);
139
		synchronized (this) {
140
			packetQueue.addLast(tmpBuff); 
141
			timeOfLastPackedAdd = System.currentTimeMillis();
142
			if (NOTIFY_ON_ADD) {
143
				notify();
144
			}
145
		}
146
	}
147
	
148
	public void add (String thisPacket) {
149
		byte []buf = thisPacket.getBytes();
150
		add (buf, 0, thisPacket.length());
151
	}
152
	/**
153
	 * Returns the LinkedList representing the queue and
154
	 * creates a new LinkedList to represent the queue.
155
	 * Returns null if no items are currently in the queue. 
156
	 * 
157
	 * @return LinkedList representing the queue.
158
	 */
159
	public Collection removeAll () {
160
		LinkedList workToDo = null;
161
		synchronized (this) {
162
			if (packetQueue.size() == 0) {
163
				workToDo = null;
164
			} else {
165
				workToDo = packetQueue;
166
				packetQueue = null;
167
				packetQueue = new LinkedList();
168
			}
169
		}
170
		return workToDo;
171
	}
172
}
(-)src-recorder-http-runner/org/eclipse/hyades/execution/recorder/http/remote/PeekSocket.java (-61 lines)
Removed Link Here
1
/**********************************************************************
2
 * Copyright (c) 2005, 2007 IBM Corporation and others.
3
 * All rights reserved.   This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: PeekSocket.java,v 1.5 2007/05/02 19:36:27 paules Exp $
8
 * 
9
 * Contributors: 
10
 * IBM Corporation - initial API and implementation
11
 **********************************************************************/
12
package org.eclipse.hyades.execution.recorder.http.remote;
13
import java.io.BufferedInputStream;
14
import java.io.IOException;
15
import java.io.InputStream;
16
import java.net.Socket;
17
18
/**
19
 * @author ptasnik@us.ibm.com
20
 * @deprecated  This is not public API.  It will be moved to internal in TPTP 5
21
 * Created on Oct 14, 2003
22
 * 
23
 * Only designed currently to peek on read side of sockets
24
 * created from PeekServerSocket, could be changed to make
25
 * peek available from read side of client. 
26
 */
27
public class PeekSocket extends Socket {	
28
	
29
	public PeekSocket() {
30
		super();
31
	}
32
33
	protected BufferedInputStream m_BufferedIn = null;
34
	protected synchronized void setupBufferedInputStream () throws IOException {
35
		//
36
		// Better be connected or we are screwed
37
		//
38
		if (m_BufferedIn == null) {
39
			m_BufferedIn = new BufferedInputStream (super.getInputStream());	
40
		}
41
	}
42
	
43
	public InputStream getInputStream() throws IOException {
44
		setupBufferedInputStream ();
45
		return (m_BufferedIn);
46
	}
47
48
	//
49
	// peek - method will block 
50
	//
51
	public int peek () throws IOException {
52
		int peekbyte = 0;
53
		BufferedInputStream in = (BufferedInputStream)getInputStream(); 
54
		
55
		in.mark (1);
56
		peekbyte = in.read();	 		
57
		in.reset ();
58
59
		return peekbyte;	
60
	}
61
}
(-)src-recorder-http-runner/org/eclipse/hyades/execution/recorder/http/remote/SSLProxyRecorder.java (-439 lines)
Removed Link Here
1
/**********************************************************************
2
 * Copyright (c) 2005, 2007 IBM Corporation and others.
3
 * All rights reserved.   This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: SSLProxyRecorder.java,v 1.12 2007/05/03 01:34:39 paules Exp $
8
 *
9
 * Contributors:
10
 * IBM - Initial API and implementation
11
 **********************************************************************/
12
/*
13
 * NONE OF THE QUOTED STRINGS IN THIS FILE ARE TO BE LOCALIZED
14
 * THEY ARE ALL FOR XML TAGS, DEBUGGING SUPPORT, THEY ARE NOT FOR USER INTERFACES
15
 */
16
 
17
/*
18
 * Created on Jun 21, 2003
19
 *
20
 * To change this generated comment go to 
21
 * Window>Preferences>Java>Code Generation>Code and Comments
22
 */
23
package org.eclipse.hyades.execution.recorder.http.remote;
24
25
import java.io.IOException;
26
import java.io.PrintWriter;
27
import java.io.StringWriter;
28
import java.io.Writer;
29
import java.net.SocketException;
30
31
import org.eclipse.hyades.execution.recorder.remote.RecorderAgent;
32
import org.eclipse.hyades.internal.execution.recorder.remote.RecorderAgentController;
33
34
/**
35
 * This is the main class for the HTTP Proxy Recorder
36
 * 
37
 * @author morris
38
 * @deprecated  This is not public API.  It will be moved to internal in TPTP 5
39
 */
40
41
public class SSLProxyRecorder extends RecorderAgent
42
{
43
	static int iProxyRecorderPort = 0;
44
	static Proxy proxy = null;
45
	// mdd Hyades 1.3 HTTP Proxy 
46
	static String strProxyType = "";
47
	static String strProxyAddr = "";
48
	static int iProxyPort = 0;
49
	// defect 79219 mdd
50
	static String strSSLProxyAddr = "";
51
	static int sslIProxyPort = 0;
52
	public static final String ERROR_CREATING_CLIENTSIDEREADER = "-3";
53
	// mdd
54
	static String strProxyOverride = "";
55
	static String strProxyAutoConfigURL = "";
56
	
57
	//jn
58
	static String strKeyFile = "C:\\testkeys";
59
	private static boolean bFinished = false;
60
	
61
	static final String ErrorStartingRecorder = HttpRecResourceBundle.RECORDER_ERR_STARTING;
62
	static final String StartingRecorder = HttpRecResourceBundle.RECORDER_STARTING_SSLPROXYRECORDER;
63
	static final String ListeningToPort = HttpRecResourceBundle.RECORDER_LISTENING_TO_PORT;
64
	static final String SocketBindError = HttpRecResourceBundle.RECORDER_BIND_ERROR;
65
	static final String CSRCreateError = HttpRecResourceBundle.RECORDER_CREATING_CLIENTSIDEREADER;
66
	static final String TooManyBindErrors = HttpRecResourceBundle.RECORDER_TOO_MANY_BIND_ERROR;
67
	
68
	
69
	public static void main(String[] args)
70
	{		
71
		new SSLProxyRecorder().run();
72
		
73
	}
74
75
	public Thread run()
76
	{
77
78
		try
79
		{
80
			sendDebugMessageToDataProcessor(StartingRecorder);
81
			proxy = new Proxy(this, controller);
82
			proxy.start();
83
			sendDebugMessageToDataProcessor(ListeningToPort + iProxyRecorderPort);
84
					
85
		}
86
		
87
		catch (Exception e){
88
			controller.reportException(ErrorStartingRecorder + e.getMessage(), e);
89
			System.err.println(e);
90
			System.exit(1);
91
		}
92
		
93
		setIsReady(true);
94
		return proxy;
95
	}
96
	
97
	
98
	static PacketWriter packetWriter = null;
99
		
100
	/**
101
	 * This is the inner class for the HTTP Proxy Recorder 
102
	 * 
103
	 * @author morris
104
	 * @deprecated  This is not public API.  It will be moved to internal in TPTP 5
105
	 */
106
	public static class Proxy extends Thread 
107
	{
108
		String host;
109
		RecorderAgent agent = null;
110
		RecorderAgentController controller = null;
111
		PeekServerSocket serversocket = null;
112
		Thread packetQueueThread = null;
113
		
114
		public Proxy(RecorderAgent agent, RecorderAgentController controller)
115
		{
116
			this.setName("Proxy");
117
			this.agent = agent;
118
			this.controller = controller;
119
			packetWriter = new PacketWriter(agent);
120
			
121
			packetWriter.writeRecorderStartInfo(iProxyRecorderPort,
122
						strProxyAddr, iProxyPort, strSSLProxyAddr, sslIProxyPort);	
123
			
124
			packetWriter.writeRecorderBrowserConfigInfo(iProxyRecorderPort,
125
					strProxyAddr, iProxyPort, strSSLProxyAddr, sslIProxyPort,strProxyOverride, strProxyAutoConfigURL);
126
		}
127
		
128
		public void run()  {
129
			//ServerSocket serversocket = null;
130
			
131
			int numTries = 0;
132
						
133
			try{
134
			
135
				//serversocket = new ServerSocket(iProxyRecorderPort);
136
				
137
				try {
138
					// to test throw new Exception ("bind IN USE");
139
			
140
					serversocket = new PeekServerSocket(iProxyRecorderPort);
141
					serversocket.setSoTimeout(600000);
142
				} catch (IOException listen_exception) {
143
					//TODO tell user about error in eclipse
144
					this.agent.sendDebugMessageToDataProcessor(CSRCreateError + " Port: " + iProxyRecorderPort);
145
					packetWriter.writeRecorderMessage(2, CSRCreateError + " Exception: " +getStackTraceInfo (listen_exception));
146
					//sendStatusMessageToControlView(CSRCreateError);
147
					agent.reportException(CSRCreateError,listen_exception);
148
					throw listen_exception;		
149
				}				 
150
151
				while (!bFinished){
152
					ClientSideReader cli_reader;
153
					
154
					try{
155
						//Socket client = serversocket.accept();
156
						
157
						PeekSocket client = serversocket.acceptPeekSocket();
158
						if (strProxyType.equalsIgnoreCase("http")) {
159
							if (strSSLProxyAddr.length() > 0 && sslIProxyPort > 0){
160
								cli_reader = new ClientSideReaderHTTP(client, packetWriter, strKeyFile, 
161
										strProxyAddr, iProxyPort, strSSLProxyAddr ,sslIProxyPort);
162
							} else {
163
								cli_reader = new ClientSideReaderHTTP(client, packetWriter, strKeyFile, 
164
										strProxyAddr, iProxyPort);
165
							}
166
						}
167
						else {
168
							cli_reader = new ClientSideReaderSOCKS(client, packetWriter, strKeyFile, iProxyRecorderPort);
169
						}
170
						cli_reader.start();
171
					} catch (Exception e) {			
172
						if (numTries >= 10){
173
							throw new Exception (TooManyBindErrors);
174
						}
175
						numTries += 1;
176
						
177
						String mess = e.getLocalizedMessage();
178
						// no record for the following exceptions, they are expected
179
						
180
						if (mess.indexOf("Stream closed") < 0 && mess.indexOf("Socket closed") < 0 &&
181
								mess.indexOf("JVM_recv in socket input") <0 && mess.indexOf("onnection closed")<0
182
								&& mess.indexOf("socket closed")<0 && mess.indexOf("onnection reset") < 0
183
								&& mess.indexOf("Socket is closed") <0) {
184
							//PRINT THESE TO ECLIPSE TOO 
185
							this.agent.sendDebugMessageToDataProcessor(SocketBindError + iProxyRecorderPort + " Exception: " + getStackTraceInfo(e));
186
							packetWriter.writeRecorderMessage(2, SocketBindError + iProxyRecorderPort + " Exception: " + getStackTraceInfo (e));
187
						}
188
	
189
						//controller.stopRecording();
190
						
191
					}
192
				}
193
				
194
			} catch (Exception e) {		
195
	
196
				//controller.sendCompleteNotification();
197
				packetWriter.writeRecorderMessage(2, "exception in socket run: " + getStackTraceInfo (e));
198
				packetWriter.getAgentController().sendControlMessageToDataProcessor(ERROR_CREATING_CLIENTSIDEREADER);
199
				controller.stopRecording();
200
201
			}
202
			
203
			System.out.println("Exiting Proxy normally");
204
		}
205
					
206
	}
207
208
	public static String getStackTraceInfo (Throwable exception) {
209
		Writer strResult = new StringWriter ();
210
		PrintWriter printWriter = new PrintWriter (strResult);
211
		exception.printStackTrace (printWriter);
212
	    return strResult.toString();
213
	 }
214
215
	/**
216
	 * init routine (String configuration)
217
	 * configuration is the configuration string passed in when the class is executed
218
	 */
219
	
220
	public boolean init(String configuration )
221
	{
222
//		final String sslFile = "sslkeyfile";
223
		bFinished = false;
224
		setPortInfo(configuration);
225
		setProxyInfo(configuration);
226
		setSSLInfo(configuration);
227
		setBrowserConfigInfo(configuration);
228
		return true;
229
	}
230
/*
231
 *  (non-Javadoc)
232
 * @see org.eclipse.hyades.internal.execution.recorder.remote.RecorderAgent#handleCommand(int, java.lang.String)
233
		String proxyInfo = getProxyInfo(inputFileContents);
234
		if (proxyInfo.length()!= 0) {
235
			String[] proxySplit = proxyInfo.split(":");
236
			String myProxyAddr = proxySplit[0];
237
			String myProxyPort = proxySplit[1];
238
			setProxyAddr(myProxyAddr);	
239
			setProxyPort(myProxyPort);
240
			setProxyType("http");
241
		}
242
		else {
243
			setProxyType("socks");
244
		}
245
 * */	
246
247
	
248
	/**
249
	 * @param configuration
250
	 */
251
	private void setPortInfo(String configuration) {
252
		int iStartPos;
253
		int iEndPos;
254
		int iPortPos = configuration.indexOf("port,");
255
		if (iPortPos >= 0){
256
			iStartPos = iPortPos + 5;
257
			iEndPos = configuration.indexOf(";", iStartPos);
258
				if (iEndPos >= 0){
259
					iProxyRecorderPort = Integer.parseInt(configuration.substring(iStartPos, iEndPos ));
260
			}
261
			else{
262
				iProxyRecorderPort = Integer.parseInt(configuration.substring(iStartPos));
263
			}
264
		}
265
	}
266
267
	private void setSSLInfo(String configuration) {
268
		int iStartPos;
269
		int iEndPos;
270
		iStartPos = configuration.indexOf("sslkeyfile,");
271
		if (iStartPos >= 0){
272
			iStartPos = iStartPos + 11;
273
			iEndPos = configuration.indexOf(";", iStartPos);
274
				if (iEndPos >= 0){
275
					strKeyFile = configuration.substring(iStartPos, iEndPos );
276
			}
277
			else{
278
				strKeyFile = configuration.substring(iStartPos);
279
			}
280
		}
281
	}
282
	/**
283
	 * @param configuration
284
	 */
285
	private void setProxyInfo(String configuration) {
286
		int iStartPos = 0;
287
		int iEndPos = 0;
288
		final String proxyStr = "proxyInfo,";
289
		final String httpStr = "http=";
290
//		final String socksStr = "socks";
291
		// defect 79219 mdd
292
//		final String SSLproxyStr = "sslProxyInfo,";
293
//		final String httpsStr = "https=";
294
		
295
		int iProxyInfoPos = configuration.indexOf(proxyStr);
296
		if (iProxyInfoPos >= 0) {
297
			iStartPos = iProxyInfoPos + proxyStr.length();
298
			iEndPos = configuration.indexOf(';', iStartPos);
299
			String pInfo;
300
			if (iEndPos >= 0)
301
				pInfo = configuration.substring(iStartPos, iEndPos);
302
			else
303
				pInfo = configuration.substring(iStartPos);
304
			
305
			if (pInfo.startsWith(httpStr)) {
306
				strProxyType = "http";
307
				String pAddr = pInfo.substring(httpStr.length());
308
				if (pAddr.length() != 0) {
309
					String[] proxySplit = pAddr.split(":");
310
					strProxyAddr = proxySplit[0];
311
					String tmpPort = proxySplit[1];
312
					iProxyPort = Integer.parseInt(tmpPort);
313
				} else {
314
					strProxyType = "socks";
315
				}
316
				// defect 79219 mdd
317
				int isSame = -1;
318
				isSame = strProxyType.compareToIgnoreCase("http");
319
				if (isSame == 0) {
320
					setSSLProxyInfo(configuration);
321
				}
322
			}
323
			else {
324
				strProxyType = "socks";
325
			}
326
		}
327
	}
328
	private void setBrowserConfigInfo(String configuration) {
329
		int iStartPos = 0;
330
331
		// defect 79219 mdd
332
		final String proxyOverrideStr = "proxyOverride,";
333
		final String autoConfigURLStr = "autoConfigURL,";
334
		
335
		int iAutoConfigURLPos = configuration.indexOf(autoConfigURLStr);
336
		int iProxyOverridePos = configuration.indexOf(proxyOverrideStr);
337
		String tmpOverrideStr = "";
338
		String tmpAutoConfigURLStr = "";
339
		boolean foundProxyOverride = false;
340
		boolean foundAutoConfigURL = false;
341
		int tmpFirstInfo = 0;
342
	
343
		if (iProxyOverridePos >= 0) {
344
				foundProxyOverride = true;
345
				tmpFirstInfo = iProxyOverridePos;
346
		}
347
		if (iAutoConfigURLPos >= 0) {
348
			foundAutoConfigURL = true;
349
			if (iAutoConfigURLPos < tmpFirstInfo) {
350
				tmpFirstInfo = iAutoConfigURLPos;
351
			}
352
		}
353
		
354
		// This assumes ProxyOverride will be written before 
355
		if (foundProxyOverride) {
356
			iStartPos = iProxyOverridePos + proxyOverrideStr.length();
357
			// may have multiple ';'
358
			if (iAutoConfigURLPos > -1) {
359
				tmpOverrideStr = configuration.substring(iStartPos,iAutoConfigURLPos);
360
			} else {
361
				tmpOverrideStr = configuration.substring(iStartPos,configuration.length());
362
			}
363
			strProxyOverride = tmpOverrideStr;
364
		}
365
		
366
		if (foundAutoConfigURL) {
367
			iStartPos = iAutoConfigURLPos + autoConfigURLStr.length();
368
			tmpAutoConfigURLStr = configuration.substring(iStartPos,configuration.length());
369
			
370
			strProxyAutoConfigURL = tmpAutoConfigURLStr ;
371
		}
372
		
373
	}
374
375
	public boolean handleCommand(int commandID, String commandData)
376
	{
377
		switch(commandID)
378
		{
379
			case STOP_RECORDING:
380
				bFinished = true;
381
				
382
				if (packetWriter != null) {
383
					GlobalSocketList.killAllOpenSockets(packetWriter);
384
					GlobalSocketList.writeCloseMessages(packetWriter);
385
					packetWriter.writeRecorderStopInfo();
386
					packetWriter.flushRemainingPackets();
387
				}
388
				// bugzilla_69967
389
				try {
390
					proxy.serversocket.close();
391
				}
392
				catch (SocketException se) {
393
					//this will occur if serversocket is in the middle of an accept(),
394
					//chance of incomplete data -- but probably it's just waiting for another page
395
					//System.out.println(se);
396
				}catch (IOException ioe) {}
397
				return true;
398
				
399
			default:
400
				return false;
401
		}
402
	}
403
	private void setSSLProxyInfo(String configuration) {
404
		int iStartPos = 0;
405
		int iEndPos = 0;
406
407
		// defect 79219 mdd
408
		final String SSLproxyStr = "sslProxyInfo,";
409
		final String httpsStr = "https=";
410
		
411
		int iSSLProxyInfoPos = configuration.indexOf(SSLproxyStr);
412
		if (iSSLProxyInfoPos >= 0) {
413
			iStartPos = iSSLProxyInfoPos + SSLproxyStr.length();
414
			// note - may not have ';' at end, may just be end of string
415
			iEndPos = configuration.indexOf(';', iStartPos);
416
			if (iEndPos == -1){
417
				iEndPos = configuration.length();
418
			}
419
			String pInfo;
420
			if (iEndPos >= 0)
421
				pInfo = configuration.substring(iStartPos, iEndPos);
422
			else
423
				pInfo = configuration.substring(iStartPos);
424
			
425
			if (pInfo.startsWith(httpsStr)) {
426
				
427
				String pAddr = pInfo.substring(httpsStr.length());
428
				if (pAddr.length() != 0) {
429
					String[] proxySplit = pAddr.split(":");
430
					strSSLProxyAddr = proxySplit[0];
431
					String tmpPort = proxySplit[1];
432
					sslIProxyPort = Integer.parseInt(tmpPort);
433
				} 
434
			}
435
		}
436
	}
437
438
439
}
(-)src-recorder-http-runner/org/eclipse/hyades/execution/recorder/http/remote/HttpRecResourceBundle.java (-47 lines)
Removed Link Here
1
/**********************************************************************
2
 * Copyright (c) 2007 IBM Corporation and others.
3
 * All rights reserved.   This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: HttpRecResourceBundle.java,v 1.5 2007/03/22 00:31:24 paules Exp $
8
 * 
9
 * Contributors: 
10
 * IBM - Initial API and implementation
11
 **********************************************************************/
12
package org.eclipse.hyades.execution.recorder.http.remote;
13
14
import org.eclipse.osgi.util.NLS;
15
16
/**
17
 * Runner level resource bundle.
18
 * <p>
19
 * 
20
 * 
21
 * @author      Paul E. Slauenwhite
22
 * @version     March 21, 2007
23
 * @since       March 21, 2007
24
 */
25
public final class HttpRecResourceBundle extends NLS {
26
27
	private static final String BUNDLE_NAME = "org.eclipse.hyades.execution.recorder.http.remote.messages";//$NON-NLS-1$
28
29
	private HttpRecResourceBundle() {
30
		// Do not instantiate
31
	}
32
33
	public static String RECORDER_CLIENTSIDE_READER_EXCEPTION;
34
	public static String RECORDER_SSL_SPYSOCKET_EXCEPTION;
35
	public static String RECORDER_ERR_STARTING;
36
	public static String RECORDER_STARTING_SSLPROXYRECORDER;
37
	public static String RECORDER_LISTENING_TO_PORT;
38
	public static String RECORDER_CREATING_CLIENTSIDEREADER;
39
	public static String RECORDER_BIND_ERROR;
40
	public static String RECORDER_TOO_MANY_BIND_ERROR;
41
	public static String RECORDER_NOTIFY_ON_ADD;
42
	public static String RECORDER_PACKET_WAIT_TOLERANCE;
43
44
	static {
45
		NLS.initializeMessages(BUNDLE_NAME, HttpRecResourceBundle.class);
46
	}
47
}
(-)src-testgen-http/org/eclipse/hyades/execution/testgen/http/TRCNodeAssembler.java (-75 lines)
Removed Link Here
1
/**********************************************************************
2
 * Copyright (c) 2005 IBM Corporation and others.
3
 * All rights reserved.   This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: TRCNodeAssembler.java,v 1.5 2005/06/09 17:00:43 jnevicos Exp $
8
 * 
9
 * Contributors: 
10
 * IBM Corporation - initial API and implementation
11
 **********************************************************************/
12
package org.eclipse.hyades.execution.testgen.http;
13
14
import org.eclipse.hyades.test.core.testgen.TestgenException;
15
16
17
/**
18
 * @author dhinson
19
 *
20
 * @deprecated should not be public API. Will be changed to internal in TPTP 5.
21
 */
22
public class TRCNodeAssembler
23
{	
24
	private TRCNodeDispatcher	dispatcher;
25
	private TRCNode				topNode;
26
	private TRCNode				currentNode = topNode;
27
	private int					previousDepth;
28
	
29
	public TRCNodeAssembler (TRCNodeDispatcher dispatcher)
30
	{
31
		this.dispatcher = dispatcher;
32
	}
33
	
34
	public void newElement (TRCElement element, int depth, String name)
35
		throws TestgenException
36
	{
37
		if (name.equals("TRACE"))
38
			return;
39
			
40
		TRCNode node = new TRCNode(name);
41
		// bind element with node
42
		element.setNode(node);
43
		node.setElement(element);
44
		
45
		if (depth == 2)
46
			topNode = node;
47
		else {
48
			if (depth < previousDepth) /* ascendant */ {
49
				node.setParentNode(currentNode.getParentNode().getParentNode());
50
			}
51
			else if (depth > previousDepth) /* descendant */ {
52
				node.setParentNode(currentNode);
53
			}
54
			else /* sibling */ {
55
				node.setParentNode(currentNode.getParentNode());
56
			}
57
			node.getParentNode().getSubNodes().addLast(node);
58
		}
59
		currentNode = node;
60
		previousDepth = depth;
61
	}
62
63
	public void completeElement (TRCElement element, int depth, String name)
64
		throws TestgenException
65
	{
66
		if (name.equals("TRACE"))
67
			return;
68
					
69
		TRCNode node = element.getNode();
70
			
71
		if (depth == 2)
72
			dispatcher.dispatch(node);
73
	}
74
75
}
(-)src-testgen-http/org/eclipse/hyades/execution/testgen/http/TRCContext.java (-292 lines)
Removed Link Here
1
/**********************************************************************
2
 * Copyright (c) 2005, 2008 IBM Corporation and others.
3
 * All rights reserved.   This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: TRCContext.java,v 1.16 2008/01/21 19:09:05 paules Exp $
8
 * 
9
 * Contributors: 
10
 * IBM Corporation - initial API and implementation
11
 **********************************************************************/
12
package org.eclipse.hyades.execution.testgen.http;
13
14
import java.util.ArrayList;
15
import java.util.HashMap;
16
import java.util.Iterator;
17
import java.util.LinkedList;
18
import java.util.List;
19
20
import org.eclipse.core.runtime.IPath;
21
import org.eclipse.emf.common.util.URI;
22
import org.eclipse.emf.ecore.resource.Resource;
23
import org.eclipse.hyades.models.common.configuration.CFGInstance;
24
import org.eclipse.hyades.models.common.configuration.impl.Common_ConfigurationFactoryImpl;
25
import org.eclipse.hyades.models.common.facades.behavioral.ILoop;
26
import org.eclipse.hyades.models.common.facades.behavioral.IProperty;
27
import org.eclipse.hyades.models.common.facades.behavioral.IPropertyGroup;
28
import org.eclipse.hyades.models.common.facades.behavioral.ITestCase;
29
import org.eclipse.hyades.models.common.facades.behavioral.ITestInvocation;
30
import org.eclipse.hyades.models.common.facades.behavioral.ITestSuite;
31
import org.eclipse.hyades.models.common.facades.behavioral.impl.HyadesFactory;
32
import org.eclipse.hyades.models.common.testprofile.TPFTestSuite;
33
import org.eclipse.hyades.models.common.util.ICommonConstants;
34
import org.eclipse.hyades.test.core.util.EMFUtil;
35
import org.eclipse.hyades.test.core.util.JavaUtil;
36
import org.eclipse.hyades.test.tools.core.common.TestCommon;
37
import org.eclipse.hyades.test.tools.core.common.util.TestCommonUtil;
38
import org.eclipse.hyades.test.tools.core.http.util.RequestHelper;
39
import org.eclipse.hyades.test.tools.core.internal.resources.CorePluginResourceBundle;
40
41
/**
42
 * @author dhinson
43
 *
44
 * @deprecated should not be public API. Will be changed to internal in TPTP 5.
45
 */
46
public class TRCContext
47
{
48
	private RequestHelper	requestHelper;
49
	private List			resources;
50
	
51
	private IPath			testSuiteFolderPath;
52
	private String			testSuiteBaseName;
53
	private ITestSuite		currentTestSuite;
54
	
55
	private int				testCaseCounter;
56
	private ITestCase		currentTestCase;
57
	
58
	private ILoop			currentLoop;
59
	private ILoop			currentPage;
60
		
61
	// @TODO mdd new 
62
	public static final String GLOBAL_LASTRECV	= "__global";
63
	private LinkedList pageList;
64
	private int pageNumber;
65
	private HashMap	lastRecvHashMap = new HashMap();
66
	
67
68
	public TRCContext ()
69
	{
70
		requestHelper = new RequestHelper();
71
		pageList = new LinkedList();
72
		pageNumber = 0;
73
		lastRecvHashMap.put(GLOBAL_LASTRECV, new Integer(-1));
74
	}
75
76
	public RequestHelper getRequestHelper ()
77
	{
78
		return this.requestHelper;
79
	}
80
		
81
	public void setOutputFolder (IPath outputFolder)
82
	{
83
		this.testSuiteFolderPath = outputFolder;
84
	}
85
	
86
	public void setTestSuiteBaseName (String testSuiteBaseName)
87
	{
88
		this.testSuiteBaseName = testSuiteBaseName;
89
	}
90
	
91
	public ITestSuite newTestSuiteContext ()
92
	{
93
		currentTestSuite = createTestSuite();
94
		currentLoop = createLoop();
95
		currentTestSuite.getImplementor().getBlock().getActions().
96
			add(currentLoop);
97
		return currentTestSuite;
98
	}
99
100
	public ITestCase newTestCaseContext (String name)
101
	{
102
		currentTestCase = createTestCase(currentTestSuite, currentPage, name);
103
		requestHelper.setTestCase(currentTestCase);
104
		return currentTestCase;
105
	}
106
	
107
	public void finish ()
108
	{
109
		saveResources();
110
		dispose();
111
	}
112
		
113
	public void dispose ()
114
	{
115
		if(requestHelper != null)
116
			requestHelper.dispose();
117
		if(resources != null)
118
			resources.clear();	
119
	}
120
	
121
	private ITestSuite createTestSuite()
122
	{
123
		if(resources == null)
124
			resources = new ArrayList();
125
			
126
		IPath path = testSuiteFolderPath.append(testSuiteBaseName).
127
			addFileExtension(ICommonConstants.TEST_SUITE_FILE_EXTENSION);
128
		
129
		URI uri = URI.createPlatformResourceURI(path.toString());
130
		Resource resource = EMFUtil.getResourceFactory(ICommonConstants.
131
			TEST_SUITE_FILE_EXTENSION).createResource(uri);
132
		resources.add(resource);
133
		
134
		ITestSuite testSuite = HyadesFactory.INSTANCE.createTestSuite(resource);
135
		testSuite.setType(TestCommon.HTTP_JUNIT_TEST_SUITE_TYPE);
136
		testSuite.setName(testSuiteBaseName);		
137
		if(testSuite.getImplementor() == null)
138
			HyadesFactory.INSTANCE.createImplementor(testSuite, false);
139
			
140
		String clsName = JavaUtil.getValidClassName(testSuite.getName(), true);
141
		if(clsName == null)
142
			clsName = "Test";
143
		testSuite.getImplementor().setResource("test." + clsName);
144
145
		//bugzilla_90127 - default 1 user
146
		if (testSuite instanceof TPFTestSuite)
147
		{
148
		    TPFTestSuite tpftest = (TPFTestSuite) testSuite;
149
		    CFGInstance instance = null;
150
		    if (tpftest.getInstances().size() == 0)
151
		    {
152
		        instance = Common_ConfigurationFactoryImpl.eINSTANCE.createCFGInstance();		        
153
		        tpftest.getInstances().add(instance);
154
		    }
155
		    else
156
		        instance = (CFGInstance) tpftest.getInstances().get(0);
157
158
		    if (instance != null)
159
		        instance.setMaxCount(1);
160
		}    
161
		return testSuite;
162
	}
163
	
164
	private ITestCase createTestCase(ITestSuite testSuite, ILoop loop,
165
		String testCaseBaseName)
166
	{
167
		String testCaseName = (++testCaseCounter) + " " + testCaseBaseName;
168
		ITestCase testCase = TestCommonUtil.createTestCase(testSuite,
169
			TestCommon.HTTP_JUNIT_TEST_CASE_TYPE, false, testCaseName);
170
171
		ITestInvocation testInvocation = HyadesFactory.INSTANCE.
172
			createTestInvocation(testCase);
173
		loop.getBlock().getActions().add(testInvocation);
174
175
		String baseName = CorePluginResourceBundle.W_LWR_INV;
176
		String testName = testCase.getName();
177
		if(testName == null)
178
			testInvocation.setName(TestCommonUtil.getUniqueName(baseName,
179
				loop.getBlock().getActions()));
180
		else
181
			testInvocation.setName((testName.concat(" - ").concat(baseName)));
182
		
183
		return testCase;
184
	}
185
	/** Create a default loop
186
	 * 
187
	 * @return ILoop
188
	 */
189
	private ILoop createLoop()
190
	{
191
		return createLoop(CorePluginResourceBundle.W_LOOP + " " + 1, 1);
192
	}
193
	
194
//	private ILoop createLoop()
195
//	{
196
//		ILoop loop = HyadesFactory.INSTANCE.createLoop();
197
//		loop.setName(TestJavaPlugin.getString("W_LOOP") + " " +
198
//			/* pageCount */ 1);
199
//		loop.getCondition().setConstraint("1");
200
//		return loop;
201
//	}
202
	
203
	private void saveResources()
204
	{
205
		for (Iterator i = resources.iterator(); i.hasNext();) {
206
			try {
207
				EMFUtil.save((Resource)i.next());
208
			}
209
			catch (Exception e) {
210
			}
211
		}
212
	}
213
	
214
	/**
215
	 * @return
216
	 */
217
	public LinkedList getPageList() {
218
		return pageList;
219
	}
220
221
	/**
222
	 * @param list
223
	 */
224
	public void setPageList(LinkedList list) {
225
		pageList = list;
226
	}
227
	public ILoop createNewPage(int i) {
228
		currentPage = createPage(i);
229
		currentLoop.getBlock().getActions().add(currentPage);
230
		return currentPage;
231
	}
232
	
233
	public ILoop createNewPage(String s)
234
	{
235
		currentPage = createPage(CorePluginResourceBundle.Page + " " + s);
236
		currentLoop.getBlock().getActions().add(currentPage);
237
		return currentPage;
238
		
239
	}
240
	private ILoop createLoop(String name, int constraint)
241
	{
242
		ILoop loop = HyadesFactory.INSTANCE.createLoop();
243
		loop.setName(name);
244
		loop.getCondition().setConstraint(Integer.toString(constraint));
245
		return loop;
246
	}
247
	private ILoop createPage(int n)
248
	{
249
		return createPage(CorePluginResourceBundle.Page + " " + Integer.toString(n));
250
	}
251
252
	private ILoop createPage(String s)
253
	{
254
		ILoop page =  createLoop(s, 1);
255
		IPropertyGroup props = page.getActionProperties();
256
		List propList = props.getProperties();
257
		//create new Page property
258
		IProperty prop = HyadesFactory.INSTANCE.createProperty();
259
		prop.setName("HTTPPAGE");
260
		prop.setValue("true");
261
		propList.add(prop);
262
		return page;
263
	}
264
	/**
265
	 * @return
266
	 */
267
	public int getPageNumber() {
268
		return pageNumber;
269
	}
270
271
	/**
272
	 * @param i
273
	 */
274
	public void setPageNumber(int i) {
275
		pageNumber = i;
276
	}
277
278
	/**
279
	 * @return
280
	 */
281
	public HashMap getLastRecvHashMap() {
282
		return lastRecvHashMap;
283
	}
284
285
	/**
286
	 * @param map
287
	 */
288
	public void setLastRecvHashMap(HashMap map) {
289
		lastRecvHashMap = map;
290
	}
291
292
}
(-)src-testgen-http/org/eclipse/hyades/execution/testgen/http/TRCPacketNodeHandler.java (-70 lines)
Removed Link Here
1
/**********************************************************************
2
 * Copyright (c) 2005, 2007 IBM Corporation and others.
3
 * All rights reserved.   This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: TRCPacketNodeHandler.java,v 1.8 2007/05/03 01:36:55 paules Exp $
8
 * 
9
 * Contributors: 
10
 * IBM Corporation - initial API and implementation
11
 **********************************************************************/
12
package org.eclipse.hyades.execution.testgen.http;
13
14
// import java.util.HashMap;
15
16
import java.util.LinkedList;
17
18
import org.eclipse.hyades.test.core.testgen.TestgenException;
19
20
/**
21
 * @author dhinson
22
 *
23
 * @deprecated should not be public API. Will be changed to internal in TPTP 5.
24
 */
25
public class TRCPacketNodeHandler extends TRCNodeHandler implements ITRCNodeHandler
26
{
27
28
	private static final String	PACKET_A_TYPE
29
														= "type";
30
	private static final String	PACKET_A_TYPE_V_HTTP
31
														= "HTTP";
32
	private static final String	PACKET_A_TYPE_V_HTTPS
33
														= "HTTPS";
34
35
	
36
	// name of global last receive timestamp
37
//	private static final String GLOBAL_LASTRECV	= "__global";
38
	
39
	// private ParsedHttpMessage	currentHttpRequest;
40
41
	public void init (TRCContext context)
42
		throws TestgenException
43
	{
44
		super.init(context);
45
		
46
		LinkedList myPageList = context.getPageList();
47
		myPageList.clear();
48
		context.setPageList(myPageList);
49
	}
50
	
51
	public void node (TRCNode node)
52
		throws TestgenException
53
	{
54
		LinkedList myPageList;
55
		// dispatch on type attribute
56
		String typeValue = getAttributeValue(PACKET_A_TYPE, node);		
57
		if ((!typeValue.equals(PACKET_A_TYPE_V_HTTP))&& (!typeValue.equals(PACKET_A_TYPE_V_HTTPS)) )
58
			// currently ignore anything but "HTTP"
59
			return;
60
		myPageList = context.getPageList();
61
		myPageList.add(node);
62
		context.setPageList(myPageList);
63
		// Http Specific Call below
64
		// Skip this call to handle_node() mdd 11/24/2003
65
		//thisHttp.handle_node(node);
66
		return;
67
	}
68
		
69
70
}
(-)src-testgen-http/org/eclipse/hyades/execution/testgen/http/TRCNodeHandler.java (-169 lines)
Removed Link Here
1
/**********************************************************************
2
 * Copyright (c) 2005 IBM Corporation and others.
3
 * All rights reserved.   This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: TRCNodeHandler.java,v 1.5 2005/06/09 17:00:43 jnevicos Exp $
8
 * 
9
 * Contributors: 
10
 * IBM Corporation - initial API and implementation
11
 **********************************************************************/
12
package org.eclipse.hyades.execution.testgen.http;
13
14
import java.io.PrintStream;
15
import java.util.ArrayList;
16
import java.util.List;
17
import java.util.ListIterator;
18
19
import org.eclipse.hyades.test.core.testgen.TestgenException;
20
21
22
/**
23
 * @author dhinson
24
 *
25
 * @deprecated should not be public API. Will be changed to internal in TPTP 5.
26
 */
27
public class TRCNodeHandler implements ITRCNodeHandler
28
{
29
	protected TRCContext context;
30
	
31
	public void init (TRCContext context)
32
		throws TestgenException
33
	{
34
		this.context = context;
35
	}
36
	
37
	public void node (TRCNode node)
38
		throws TestgenException
39
	{
40
		// no-op
41
	}
42
43
	//
44
	// class utility methods
45
	//
46
	
47
	private static final String SPACES  = "          ";
48
49
	protected static String getAttributeValue (String name, TRCNode node)
50
	{
51
		TRCElement element = node.getElement();
52
		TRCElement.TRCAttribute [] attributes = element.getAttributes();
53
		for (int i = 0; i < attributes.length; ++i)
54
			if (attributes[i].name.equals(name))
55
				return attributes[i].value;
56
		return null;
57
	}
58
	
59
	protected static TRCNode getSubNode (String name, TRCNode node)
60
	{
61
		ListIterator itr = node.getSubNodes().listIterator();
62
		TRCNode subNode = null;
63
		while (itr.hasNext()) {
64
			subNode = (TRCNode)itr.next();
65
			if (subNode.getName().equals(name))
66
				break;
67
		}
68
		return subNode;
69
	}
70
	
71
	protected static List getSubNodeList (String name, TRCNode node)
72
	{
73
		ArrayList list = new ArrayList();
74
		ListIterator itr = node.getSubNodes().listIterator();
75
		while (itr.hasNext()) {
76
			TRCNode subNode = (TRCNode)itr.next();
77
			if (subNode.getName().equals(name))
78
				list.add(subNode);
79
		}
80
		return list;
81
	}
82
	
83
	protected static void dumpVertexElementName (PrintStream debugStream, int nSpaces, TRCElement element)
84
	{
85
		if (debugStream != null)
86
			debugStream.println(SPACES.substring(1, nSpaces) + "* [" +
87
				element.getName() + "]");
88
	}
89
	
90
	protected static void dumpElementName (PrintStream debugStream, int nSpaces, TRCElement element)
91
	{
92
		if (debugStream != null)
93
			debugStream.println(SPACES.substring(1, nSpaces) + "[" +
94
				element.getName() + "]");
95
	}
96
	
97
	protected static void dumpElementAttributes (PrintStream debugStream, int nSpaces, TRCElement element)
98
	{
99
		TRCElement.TRCAttribute [] attributes = element.getAttributes();
100
		for (int i = 0; i < attributes.length; ++i)
101
			if (debugStream != null)
102
				debugStream.println(SPACES.substring(1, nSpaces)+ "([" +
103
					attributes[i].name + "] = [" + attributes[i].value + "])");
104
	}
105
106
	protected static void dumpElementContent (PrintStream debugStream, int nSpaces, TRCElement element)
107
	{
108
		if (debugStream != null)
109
			debugStream.println(SPACES.substring(1, nSpaces) + "<" +
110
				element.getContent().trim() + ">");
111
	}
112
		
113
	protected static void dumpFirstOrderSection (PrintStream debugStream, TRCNode topNode)
114
	{
115
		if (debugStream != null)
116
			debugStream.println();
117
		dumpVertexElementName(debugStream, 2, topNode.getElement());
118
		dumpElementAttributes(debugStream, 4, topNode.getElement());		
119
							
120
		ListIterator itr = topNode.getSubNodes().listIterator();
121
		while (itr.hasNext()) {
122
			TRCNode node1 = (TRCNode)itr.next();
123
			TRCElement element1 = node1.getElement();
124
								
125
			dumpElementName(debugStream, 4, element1);
126
			dumpElementAttributes(debugStream, 6, element1);
127
			dumpElementContent(debugStream, 6, element1);
128
		}
129
	}
130
131
	protected static void dumpSecondOrderSection (PrintStream debugStream, TRCNode topNode, String [] vertices)
132
	{
133
		if (debugStream != null)
134
			debugStream.println();
135
		dumpVertexElementName(debugStream, 2, topNode.getElement());		
136
		dumpElementAttributes(debugStream, 4, topNode.getElement());
137
								
138
		ListIterator itr = topNode.getSubNodes().listIterator();
139
		while (itr.hasNext()) {
140
			TRCNode node1 = (TRCNode)itr.next();
141
			TRCElement element1 = node1.getElement();
142
			
143
			boolean match = false;
144
			for (int i = 0; i < vertices.length; ++i)
145
				if (vertices[i].equals(element1.getName()))
146
					match = true;
147
			if (match) {
148
				dumpVertexElementName(debugStream, 4, element1);
149
				dumpElementAttributes(debugStream, 6, element1);
150
151
				ListIterator itr2 = node1.getSubNodes().listIterator();
152
				while (itr2.hasNext()) {
153
					TRCNode node2 = (TRCNode)itr2.next();
154
					TRCElement element2 = node2.getElement();
155
					
156
					dumpElementName(debugStream, 6, element2);
157
					dumpElementAttributes(debugStream, 8, element2);
158
					dumpElementContent(debugStream, 8, element2);
159
				}
160
			}
161
			else {
162
				dumpElementName(debugStream, 4, element1);
163
				dumpElementAttributes(debugStream, 6, element1);
164
				dumpElementContent(debugStream, 6, element1);
165
			}			
166
		}
167
	}
168
169
}
(-)src-testgen-http/org/eclipse/hyades/execution/testgen/http/ITRCNodeHandler.java (-32 lines)
Removed Link Here
1
/**********************************************************************
2
 * Copyright (c) 2005 IBM Corporation and others.
3
 * All rights reserved.   This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: ITRCNodeHandler.java,v 1.5 2005/06/09 17:00:43 jnevicos Exp $
8
 * 
9
 * Contributors: 
10
 * IBM Corporation - initial API and implementation
11
 **********************************************************************/
12
/*
13
 * Created on Oct 28, 2003
14
 *
15
 * To change the template for this generated file go to
16
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
17
 */
18
package org.eclipse.hyades.execution.testgen.http;
19
20
import org.eclipse.hyades.test.core.testgen.TestgenException;
21
22
23
/**
24
 * @author dhinson
25
 *
26
 * @deprecated should not be public API. Will be changed to internal in TPTP 5.
27
 */
28
public interface ITRCNodeHandler
29
{
30
	public void init (TRCContext context) throws TestgenException;
31
	public void node (TRCNode node) throws TestgenException;
32
}
(-)src-testgen-http/org/eclipse/hyades/execution/testgen/http/TRCAsciifier.java (-114 lines)
Removed Link Here
1
/**********************************************************************
2
 * Copyright (c) 2005, 2007 IBM Corporation and others.
3
 * All rights reserved.   This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: TRCAsciifier.java,v 1.5 2007/05/03 01:35:29 paules Exp $
8
 * 
9
 * Contributors: 
10
 * IBM Corporation - initial API and implementation
11
 **********************************************************************/
12
package org.eclipse.hyades.execution.testgen.http;
13
14
/**
15
 * @author dhinson
16
 *
17
 * @deprecated should not be public API. Will be changed to internal in TPTP 5.
18
 */
19
public class TRCAsciifier
20
{
21
22
	static private final char C_DELIM = '`';
23
24
	public String encode (byte [] inBuf, int inDatOfs, int inDatLen)
25
	{
26
		StringBuffer outBuf = new StringBuffer();
27
		boolean isHex = false;
28
		for (int inOfs = inDatOfs; inOfs < inDatLen; ++inOfs) {
29
			char c = (char)inBuf[inOfs];
30
			if (Character.isISOControl(c) || c == '`') {
31
				if (!isHex)
32
					outBuf.append(C_DELIM);
33
				outBuf.append(Character.forDigit((c >> 4), 16));
34
				outBuf.append(Character.forDigit((c & 0xf), 16));
35
				if (inOfs == inDatLen - 1)
36
					outBuf.append(C_DELIM);				
37
				isHex = true;
38
			}
39
			else {
40
				if (isHex)
41
					outBuf.append(C_DELIM);
42
				outBuf.append(c);
43
				isHex = false;
44
			}
45
		}
46
		return outBuf.toString();			
47
	}
48
49
	public int decode (String inBuf, int inDatOfs, int inDatLen, byte [] outBuf)
50
	{
51
		boolean inHex = false;
52
		int outOfs = 0;
53
		char c;
54
		for (int inOfs = inDatOfs; inOfs < inDatLen; ++inOfs) {
55
			if ((c = inBuf.charAt(inOfs)) == C_DELIM)
56
				inHex = !inHex;
57
			else
58
				outBuf[outOfs++] = inHex ?
59
					(byte)((Character.digit(c, 16) << 4) |
60
					Character.digit(inBuf.charAt(++inOfs), 16)) :
61
					(byte)c;		
62
		}				
63
		return outOfs;
64
	}
65
66
67
	public static void main (String[] args)
68
	{
69
		TRCAsciifier asciifier = new TRCAsciifier();
70
		
71
		byte [] bytes;
72
		String encDat1;
73
		String encDat2;
74
		byte [] decBuf;
75
		int decLen;
76
77
		// encode
78
		bytes = new byte [] { '0', '`', '0', 1, '`', 1, '2', '`', '2', 3, '`', 3 };
79
		encDat1 = asciifier.encode(bytes, 0, bytes.length);
80
		System.out.println("[" + encDat1 + "]");
81
		
82
		// decode
83
		decBuf = new byte[encDat1.length()];
84
		decLen = asciifier.decode(encDat1, 0, encDat1.length(), decBuf); 
85
86
		// re-encode & compare
87
		encDat2 = asciifier.encode(decBuf, 0, decLen);
88
		System.out.println("[" + encDat2 + "]");
89
		if (encDat2.equals(encDat1))
90
			System.out.println("same");
91
		else
92
			System.out.println("wrong");
93
		
94
		// encode
95
		bytes = new byte [] { 0, '`', 0, '1', '`', '1', 2, '`', 2, '3', '`', '3' };
96
		encDat1 = asciifier.encode(bytes, 0, bytes.length);
97
		System.out.println("[" + encDat1 + "]");
98
		
99
		// decode
100
		decBuf = new byte[encDat1.length()];
101
		decLen = asciifier.decode(encDat1, 0, encDat1.length(), decBuf); 
102
103
		// re-encode & compare
104
		encDat2 = asciifier.encode(decBuf, 0, decLen);
105
		System.out.println("[" + encDat2 + "]");
106
		if (encDat2.equals(encDat1))
107
			System.out.println("same");
108
		else
109
			System.out.println("wrong");
110
		
111
	}
112
	
113
}
114
(-)src-testgen-http/org/eclipse/hyades/execution/testgen/http/TRCFileLoader.java (-218 lines)
Removed Link Here
1
/**********************************************************************
2
 * Copyright (c) 2005, 2007 IBM Corporation and others.
3
 * All rights reserved.   This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: TRCFileLoader.java,v 1.10 2007/05/03 01:35:52 paules Exp $
8
 * 
9
 * Contributors: 
10
 * IBM Corporation - initial API and implementation
11
 **********************************************************************/
12
package org.eclipse.hyades.execution.testgen.http;
13
14
import java.io.File;
15
import java.io.IOException;
16
import java.io.InputStream;
17
import java.io.PrintStream;
18
import java.util.LinkedList;
19
20
import javax.xml.parsers.ParserConfigurationException;
21
import javax.xml.parsers.SAXParser;
22
import javax.xml.parsers.SAXParserFactory;
23
24
import org.eclipse.core.resources.IFile;
25
import org.eclipse.core.runtime.CoreException;
26
import org.eclipse.core.runtime.Path;
27
import org.eclipse.hyades.test.core.testgen.TestgenException;
28
import org.eclipse.hyades.test.tools.core.internal.resources.CorePluginResourceBundle;
29
import org.xml.sax.Attributes;
30
import org.xml.sax.InputSource;
31
import org.xml.sax.SAXException;
32
import org.xml.sax.XMLReader;
33
import org.xml.sax.helpers.DefaultHandler;
34
35
36
/**
37
 * @author dhinson
38
 *
39
 * @deprecated should not be public API. Will be changed to internal in TPTP 5.
40
 */
41
public class TRCFileLoader extends DefaultHandler
42
{
43
	private XMLReader 				xmlReader;
44
	private LinkedList				list = new LinkedList();
45
	
46
	private TRCFileLoader 			handler;
47
	private TRCNodeAssembler		assembler;
48
	private TRCNodeDispatcher		dispatcher;
49
	
50
	private Testgen.ProgressUpdater	updater;
51
			
52
	public TRCFileLoader (Testgen.ProgressUpdater updater)
53
	{
54
		super();
55
		
56
		handler = this;
57
		this.updater = updater;
58
	}
59
60
	public TRCFileLoader (Testgen.ProgressUpdater updater,
61
		PrintStream debugStream)
62
	{
63
		super();
64
		
65
		handler = this;
66
		this.updater = updater;
67
	}
68
69
	public boolean load (IFile recFile, String outputFileName)
70
		throws TestgenException
71
	{
72
		if (recFile == null)
73
			throw new TestgenException(CorePluginResourceBundle.E_INVALID_REC_FILE);
74
			
75
		// create and initialize decoding context
76
		TRCContext context = new TRCContext();
77
		File file = new File(outputFileName.toString());
78
		context.setOutputFolder(new Path(file.getParent()));
79
		String baseName = file.getName();
80
		baseName = baseName.substring(0, baseName.lastIndexOf('.'));
81
		context.setTestSuiteBaseName(baseName);
82
		context.newTestSuiteContext();
83
		
84
		// create node dispatcher
85
		dispatcher = new TRCNodeDispatcher(context);
86
		 		
87
		// create node assembler
88
		assembler = new TRCNodeAssembler(dispatcher);
89
90
		// initialize SAX parser
91
		SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
92
		saxParserFactory.setNamespaceAware(true);
93
		saxParserFactory.setValidating(false);
94
		
95
		try {
96
			saxParserFactory.setFeature("http://xml.org/sax/features/validation", false);
97
			saxParserFactory.setFeature("http://xml.org/sax/features/namespaces", true);
98
			saxParserFactory.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
99
			SAXParser saxParser = saxParserFactory.newSAXParser();
100
					
101
			xmlReader = saxParser.getXMLReader();
102
		}
103
		catch ( SAXException exc )
104
		{
105
			throw new TestgenException(CorePluginResourceBundle.E_SAX_DRIVER_FAILURE, exc);
106
		}
107
		catch ( ParserConfigurationException exc )
108
		{
109
			throw new TestgenException(CorePluginResourceBundle.E_SAX_DRIVER_FAILURE, exc);
110
		}
111
		
112
		if (xmlReader == null)
113
			throw new TestgenException(CorePluginResourceBundle.E_SAX_DRIVER_FAILURE);
114
115
		xmlReader.setContentHandler(handler);
116
		xmlReader.setErrorHandler(handler);
117
118
		// derive inputSource	
119
		InputStream inputStream = null;
120
		try {
121
			inputStream = recFile.getContents();
122
		}
123
		catch (CoreException e) {
124
			e.printStackTrace();
125
		}
126
		InputSource inputSource = new InputSource(inputStream);
127
128
		// call SAX to parse inputSource
129
		try {
130
			xmlReader.parse(inputSource);
131
		}
132
		catch (IOException e) {
133
			throw new TestgenException(CorePluginResourceBundle.E_SAX_IOEXCEPTION, e);
134
		}
135
		catch (SAXException e) {
136
			throw new TestgenException(CorePluginResourceBundle.E_SAX_SAXEXCEPTION, e);
137
		}
138
	
139
		context.finish();
140
		
141
		return true;
142
	}
143
	
144
	//
145
	// begin SAX callbacks
146
	//
147
	
148
	public void startElement (String uri, String localName,
149
					String qName, Attributes attributes)
150
	{
151
		updater.progress(CorePluginResourceBundle.I_PROCESSING);
152
153
		TRCElement element = new TRCElement(attributes.getLength());
154
		element.setName(qName);
155
		for (int i = 0; i < attributes.getLength(); ++i)
156
			element.addAttribute(attributes.getQName(i),
157
				attributes.getValue(i));
158
		list.addLast(element);
159
160
		try {
161
			assembler.newElement(element, list.size() /* depth */, qName);
162
		}
163
		catch (TestgenException e) {
164
			e.printStackTrace();
165
		}
166
	}
167
		
168
	public void endElement (String uri, String localName,
169
					String qName)
170
	{
171
		TRCElement element = (TRCElement)list.removeLast();
172
		try {
173
			assembler.completeElement(element, list.size() + 1 /* depth */,
174
				qName);
175
		}
176
		catch (TestgenException e) {
177
			e.printStackTrace();
178
		}
179
	}
180
	
181
	public void characters (char [] ch, int start, int length)
182
	{
183
		TRCElement element = (TRCElement)list.getLast();
184
		element.setContent(new String(ch, start, length));
185
	}
186
	
187
//	public void startDocument ()
188
//	{
189
//	}
190
	
191
//	public void endDocument ()
192
//	{
193
//	}
194
	
195
//	public void ignorableWhitespace (char [] ch, int start, int length)
196
//	{
197
//	}
198
199
//	public void warning (SAXParseException e)
200
//	{
201
//		System.err.println(e.getMessage());
202
//	}
203
	
204
//	public void error (SAXParseException e)
205
//	{
206
//		System.err.println(e.getMessage());
207
//	}
208
	
209
//	public void fatalError (SAXParseException e)
210
//	{
211
//		System.err.println(e.getMessage());
212
//	}
213
214
	//
215
	// end SAX callbacks
216
	//
217
	
218
}
(-)src-testgen-http/org/eclipse/hyades/execution/testgen/http/TRCNodeDispatcher.java (-182 lines)
Removed Link Here
1
/**********************************************************************
2
 * Copyright (c) 2005, 2007 IBM Corporation and others.
3
 * All rights reserved.   This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: TRCNodeDispatcher.java,v 1.10 2007/03/22 14:42:21 paules Exp $
8
 * 
9
 * Contributors: 
10
 * IBM Corporation - initial API and implementation
11
 **********************************************************************/
12
package org.eclipse.hyades.execution.testgen.http;
13
14
import java.lang.reflect.Constructor;
15
import java.util.HashMap;
16
17
import org.eclipse.core.runtime.CoreException;
18
import org.eclipse.core.runtime.IConfigurationElement;
19
import org.eclipse.core.runtime.IExtension;
20
import org.eclipse.core.runtime.IExtensionPoint;
21
import org.eclipse.core.runtime.Platform;
22
import org.eclipse.hyades.test.core.testgen.TestgenException;
23
import org.eclipse.hyades.test.tools.core.internal.resources.CorePluginResourceBundle;
24
25
26
/**
27
 * @author dhinson
28
 *
29
 * TRCNodeDispatcher is responsible for managing and invoking trace element (node)
30
 * handlers.  On creation, TRCNodeDispatcher first searches for node handlers that
31
 * have extended the plugin's nodeHandlers extension.  Next, for each handler kind
32
 * defined in HANDLER_KINDS which does not have an extension handler, a handler
33
 * defining plugin properties entry is sought (using a standard naming convention).
34
 * Failing that, a handler class using the same naming convention is searched for in
35
 * the local package.  If not found then a handler not found exception is thrown.
36
 * 
37
 * This design requires, at minimum, a handler be bound to each kind defined in
38
 * HANDLER_KINDS.  The node handler base class TRCNodeHandler can be used as a
39
 * default handler for any required kinds in lieu of a real implementation.  In this
40
 * case a CorePlugin.properties entry should be made of the form:
41
 *     <node-kind>NodeHandler=org.eclipse.hyades.execution.testgen.http.TRCNodeHandler
42
 * for each node-kind without an implementation.
43
 * 
44
 * Note that handler binding via the nodeHandlers extension overrides any properties
45
 * or local package bindings, and additionally permits handlers to be defined for
46
 * kinds not listed in HANDLER_KINDS.  Although the later feature should be used
47
 * with caution as it would involve trace elements not present in
48
 * schema/TRCHTTPSchema.xsd.
49
 * 
50
 * @deprecated should not be public API. Will be changed to internal in TPTP 5.
51
 */
52
public class TRCNodeDispatcher
53
{
54
	private static final String DEFAULT_HANDLER_PACKAGE_NAME ="org.eclipse.hyades.test.tools.core";
55
56
	// add additional handler kinds here.  note: the handler kinds listed here
57
	// should be consistent with the set of trace elements defined in
58
	// schema/TRCHTTPSchema.xsd.		
59
	private static final String []	HANDLER_KINDS = {
60
		"TRCAnnotation",
61
		"TRCConnection",
62
		"TRCExecutorInfo",
63
		"TRCPacket",
64
		"TRCRecorderInfo"
65
	};
66
	
67
	private HashMap map = new HashMap();
68
	
69
	public TRCNodeDispatcher (TRCContext context)
70
		throws TestgenException
71
	{
72
		registerHandlersFromRegistry(context);
73
		registerHandlersFromProperties(context);
74
	}
75
76
	private void registerHandlersFromRegistry (TRCContext context)
77
		throws TestgenException
78
	{	
79
		IExtensionPoint extPoint = Platform.getExtensionRegistry().getExtensionPoint(DEFAULT_HANDLER_PACKAGE_NAME,
80
			"nodeHandlers");
81
82
		IExtension[] exts = extPoint.getExtensions();
83
		for (int i = 0; i < exts.length; ++i) {
84
			IExtension ext = exts[i];
85
			IConfigurationElement [] confElems = ext.getConfigurationElements();
86
			for (int j = 0; j < confElems.length; ++j) {
87
				IConfigurationElement confElem = confElems[j];
88
				
89
				String nodeKind = confElem.getAttribute("nodeKind");
90
91
				TRCNodeHandler handler = null;				
92
				try {
93
					handler = (TRCNodeHandler)confElem.createExecutableExtension("class");
94
				}
95
				catch (CoreException exc) {
96
					exc.printStackTrace();
97
				}
98
				handler.init(context);
99
				registerHandler(nodeKind, handler);
100
			}
101
		}
102
	}
103
	
104
	private void registerHandlersFromProperties (TRCContext context)
105
		throws TestgenException
106
	{
107
		for (int kind = 0; kind < HANDLER_KINDS.length; ++kind) {
108
			String handlerKind = HANDLER_KINDS[kind];
109
110
			// if a handler is already registered for this kind then skip
111
			if (handlerIsRegistered(handlerKind))
112
				continue;
113
					
114
			String handlerClassFQName = null;
115
			
116
			if((handlerKind.equals("TRCAnnotation")) || (handlerKind.equals("TRCConnection")) || (handlerKind.equals("TRCExecutorInfo"))){
117
				handlerClassFQName = "org.eclipse.hyades.execution.testgen.http.TRCNodeHandler";
118
			}
119
			else if(handlerKind.equals("TRCPacket")){
120
				handlerClassFQName = "org.eclipse.hyades.execution.testgen.http.TRCPacketNodeHandler";
121
			}
122
			else if(handlerKind.equals("TRCRecorderInfo")){
123
				handlerClassFQName = "org.eclipse.hyades.execution.testgen.http.TRCRecorderInfoNodeHandler";
124
			}
125
			else{
126
				handlerClassFQName = DEFAULT_HANDLER_PACKAGE_NAME + "." + handlerKind + "NodeHandler";
127
			}
128
			
129
			TRCNodeHandler handler = newNodeHandler(handlerClassFQName, context);
130
			handler.init(context);
131
			registerHandler(HANDLER_KINDS[kind], handler);
132
		}
133
	}
134
	
135
	private void registerHandler (String name, TRCNodeHandler handler)
136
	{
137
//		System.err.println("registerHandler: [" + name + "] [" + handler + "]");
138
		map.put(name, handler);
139
	}
140
141
	private boolean handlerIsRegistered (String name)
142
	{
143
		return (map.get(name) == null) ? false : true;
144
	}
145
	
146
	private TRCNodeHandler newNodeHandler (String classFQName, TRCContext context)
147
		throws TestgenException
148
	{
149
			Class clas = null;
150
			try {
151
				clas = Class.forName(classFQName);
152
			}
153
			catch (Exception e) {
154
				throw new TestgenException(CorePluginResourceBundle.E_LOAD_NODE_HANDLER + " " + classFQName, e);
155
			}
156
157
			TRCNodeHandler handler = null;
158
			try {
159
				Constructor constructor = clas.getConstructor(null);
160
				handler = (TRCNodeHandler)constructor.newInstance(null);
161
			}
162
			catch (Exception e) {
163
				throw new TestgenException(null, e);
164
			}
165
			return handler;
166
	}
167
168
	public void dispatch (TRCNode node)
169
		throws TestgenException
170
	{
171
		TRCNodeHandler handler = (TRCNodeHandler)map.get(node.getName());
172
		// if no handler is registered for this kind then automatically register
173
		// a default one.  note that this will only happen if a new trace element
174
		// is discovered during trace parsing that is not listed in HANDLER_KINDS. 
175
		if (handler == null) {
176
			handler = new TRCNodeHandler();
177
			registerHandler(node.getName(), handler);
178
		}
179
		handler.node(node);
180
	}
181
	
182
}
(-)src-testgen-http/org/eclipse/hyades/execution/testgen/http/Testgen.java (-96 lines)
Removed Link Here
1
/**********************************************************************
2
 * Copyright (c) 2005 IBM Corporation and others.
3
 * All rights reserved.   This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: Testgen.java,v 1.5 2005/06/09 17:00:43 jnevicos Exp $
8
 * 
9
 * Contributors: 
10
 * IBM Corporation - initial API and implementation
11
 **********************************************************************/
12
package org.eclipse.hyades.execution.testgen.http;
13
14
import java.io.PrintStream;
15
16
import org.eclipse.core.resources.IFile;
17
import org.eclipse.hyades.test.core.testgen.TestGenerator;
18
import org.eclipse.hyades.test.core.testgen.TestgenException;
19
import org.eclipse.hyades.test.core.testgen.util.TestGenFileUtil;
20
21
/**
22
 * @author dhinson
23
 *
24
 * @deprecated should not be public API. Will be changed to internal in TPTP 5.
25
 */
26
public class Testgen extends TestGenerator 
27
{
28
29
	PrintStream debugStream;
30
31
	public class ProgressUpdater
32
	{
33
		public int ticks;
34
		
35
		public void progress ()
36
		{
37
			setProgress(ticks = (++ticks % 100));
38
		}
39
		
40
		public void message (String message)
41
		{
42
			setMessage(message);
43
		}
44
		
45
		public void progress (String message)
46
		{
47
			progress();
48
			if (message != null)
49
				message(message);
50
		}
51
		
52
		public void finishedOk ()
53
		{
54
			setProgress(100);
55
			closeProgressDialog();
56
		}
57
		
58
		public void finishedError ()
59
		{
60
			closeProgressDialog();
61
		}
62
	}
63
	
64
	public boolean runTestGen ()
65
		throws TestgenException
66
	{
67
		debugStream = System.out;
68
69
		// get IFile from recModelFile parser
70
		IFile file = TestGenFileUtil.getTraceFile(recModelFile);	
71
72
		ProgressUpdater updater = new ProgressUpdater();
73
		TRCFileLoader loader = new TRCFileLoader(updater, debugStream);
74
		try {
75
			loader.load(file, outputFileName);
76
		}
77
		catch (TestgenException e) {
78
			e.dumpMessages(System.err);
79
			e.printStackTrace();
80
			updater.finishedError();
81
			return false;
82
		}
83
		updater.finishedOk();
84
						
85
		return true;
86
	}
87
88
	/* (non-Javadoc)
89
	 * @see org.eclipse.hyades.loadtest.testgen.TestGenerator#showProgress()
90
	 */
91
	public boolean showProgress()
92
	{
93
		return true;
94
	}
95
96
}
(-)src-testgen-http/org/eclipse/hyades/execution/testgen/http/TestGenHttp.java (-1203 lines)
Removed Link Here
1
/**********************************************************************
2
 * Copyright (c) 2005, 2007 IBM Corporation and others.
3
 * All rights reserved.   This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: TestGenHttp.java,v 1.14 2007/04/26 21:07:34 paules Exp $
8
 * 
9
 * Contributors: 
10
 * IBM Corporation - initial API and implementation
11
 **********************************************************************/
12
package org.eclipse.hyades.execution.testgen.http;
13
14
import java.net.MalformedURLException;
15
import java.net.URL;
16
import java.util.ArrayList;
17
import java.util.Collections;
18
import java.util.Comparator;
19
import java.util.HashMap;
20
import java.util.LinkedList;
21
import java.util.List;
22
import java.util.ListIterator;
23
import java.util.StringTokenizer;
24
25
import org.eclipse.hyades.test.core.testgen.TestgenException;
26
import org.eclipse.hyades.test.http.runner.HttpRequest;
27
import org.eclipse.hyades.test.tools.core.http.util.RequestHelper;
28
import org.eclipse.hyades.test.tools.core.internal.resources.CorePluginResourceBundle;
29
30
31
/**
32
 * @author mdunn
33
 *
34
 * @deprecated should not be public API. Will be changed to internal in TPTP 5.
35
 */
36
public class TestGenHttp 
37
{
38
	private static final String	PACKET_A_CONNECTIONNAME
39
														= "connectionNumber";
40
	private static final String	PACKET_S_DATA
41
														= "data";
42
	private static final String	PACKET_S_DATA_A_ENCODING
43
														= "encoding";
44
	private static final String	PACKET_S_DATA_A_ENCODING_V_NONE
45
														= "NONE";
46
	private static final String	PACKET_S_DATA_A_ENCODING_V_ASCIIFY
47
														= "ASCIIFY";
48
	private static final String	PACKET_S_DATA_A_ENCODING_V_BASE64
49
														= "BASE64";
50
//	private static final String	PACKET_S_DATA_A_LENGTH
51
//														= "length";
52
	private static final String	PACKET_S_DATA_A_TYPE
53
														= "type";
54
	private static final String	PACKET_S_DATA_A_TYPE_V_HTTPCONTENT
55
														= "HTTPCONTENT";
56
	private static final String	PACKET_S_DATA_A_TYPE_V_HTTPMESSAGE
57
														= "HTTPMESSAGE";
58
	//added for bugzilla #90867 - tejas.patel@ca.com
59
	private static final String	PACKET_S_DATA_A_TYPE_V_HTTPDATA
60
														= "HTTPDATA";
61
	private static final String	PACKET_A_FROM
62
														= "from";
63
	private static final String	PACKET_A_FROM_V_CLIENT
64
														= "CLIENT";
65
	private static final String	PACKET_A_FROM_V_SERVER
66
														= "SERVER";
67
//	private static final String	PACKET_A_TICKET
68
//														= "ticket";
69
	private static final String	PACKET_A_TIMESTAMP
70
														= "timestamp";
71
	private static final String	PACKET_A_TYPE
72
														= "type";
73
//	private static final String	PACKET_A_TYPE_V_HTTP
74
//														= "HTTP";
75
	private static final String	PACKET_A_TYPE_V_HTTPS
76
														= "HTTPS";
77
78
	private static final String	HTTP_POST	= "POST";
79
		
80
	private static final String	CRNL	= "\r\n";
81
	private static final char	SLASH	= '/';
82
	private static final char	COLON	= ':';
83
	private static final String BLANK   = " ";
84
	
85
	private boolean isNewType = false;
86
	
87
	private class ParsedHttpMessage
88
	{
89
		String			method;
90
		String			protocol;
91
		String			host;
92
		int				port;
93
		String			path;
94
		String			version;
95
		boolean 		bSSL;
96
		int 			enumPage;
97
		int 			nPageNum;
98
		int 			nConnID;
99
		boolean 		newPage;
100
		String 			timeStampString;
101
		ArrayList		headerNames = new ArrayList();
102
		ArrayList		headerValues = new ArrayList();
103
		StringBuffer	body = new StringBuffer();
104
	}
105
	// New Object to handle 
106
	private class ConnectionNode
107
	{
108
		int connectionNumber;
109
		LinkedList childrenNodes;
110
	}
111
// Object to hold Response information
112
	private class ResponseInfo {
113
		String timeStampString;
114
		boolean newPage;
115
	}
116
	/**
117
	 * Comparator class which compares the nodes in the linked list according
118
	 * to the timestamp values
119
	 * @author shobhit.maini@ca.com
120
	 *
121
	 */
122
	private class NewPageListComparator implements Comparator{
123
124
		public int compare(Object Node1, Object Node2) {
125
			
126
			TRCNode node1 = (TRCNode) Node1;
127
			TRCNode node2 = (TRCNode) Node2;
128
			
129
			String node1Timestamp = TRCNodeHandler.getAttributeValue(PACKET_A_TIMESTAMP, node1);
130
			String node2Timestamp = TRCNodeHandler.getAttributeValue(PACKET_A_TIMESTAMP, node2);
131
			
132
			int node1TimestampVal = Integer.parseInt(node1Timestamp);
133
			int node2TimestampVal = Integer.parseInt(node2Timestamp);
134
			
135
			if(node1TimestampVal > node2TimestampVal){
136
				return 1;
137
			}
138
			else if (node1TimestampVal < node2TimestampVal){
139
				return -1;
140
			}else return 0;
141
		}
142
	}
143
144
	LinkedList connectionsList;
145
	
146
	// private HashMap				lastRecvHashMap = new HashMap();
147
	private ParsedHttpMessage	currentHttpRequest;
148
	private ParsedHttpMessage 	previousHttpRequest;
149
	TRCContext context = null;
150
	LinkedList newPageList; 
151
152
	/**
153
	 * @param context
154
	 */
155
	public TestGenHttp (TRCContext context)
156
	{
157
		super();
158
		
159
		this.context = context;
160
		connectionsList = new LinkedList();
161
		newPageList = new LinkedList();
162
	}
163
	
164
	/**
165
	 * Parse Request Message for Message information
166
	 * modified for bugzilla #90867 & #83976 -george.sebastian@ca.com
167
	 * @param dataNode
168
	 * @throws TestgenException
169
	 */
170
	private void httpRequestMessage (TRCNode dataNode)
171
		throws TestgenException
172
	{
173
		String tempContent = null;
174
		byte[] decContent = null;
175
		String content = dataNode.getElement().getContent();
176
		if (content == null)
177
			throw new TestgenException(CorePluginResourceBundle.E_DATA_NO_CONTENT, null);
178
179
		String encoding = getAttributeValue(PACKET_S_DATA_A_ENCODING, dataNode);
180
		if (encoding == null)
181
			throw new TestgenException(CorePluginResourceBundle.E_DATA_NO_ENCODING_ATT, null);
182
		// TODO: dhinson: needs to handle non-NONE encodings eventually			
183
		// TODO: dhinson: change to equals() when DuWayne fixes value
184
		if (encoding.equalsIgnoreCase(PACKET_S_DATA_A_ENCODING_V_NONE))
185
			; // do nothing (no translation required)
186
		else if (encoding.equals(PACKET_S_DATA_A_ENCODING_V_ASCIIFY)) {
187
			TRCAsciifier myasc = new TRCAsciifier();
188
			decContent = new byte[content.length()];
189
			myasc.decode(content, 0, content.length(), decContent);
190
			tempContent = new String(decContent);
191
			String tmp = tempContent.trim();
192
			content = tmp;
193
			//return; // silently ignore
194
		}
195
		else if (encoding.equals(PACKET_S_DATA_A_ENCODING_V_BASE64))
196
			return; // silently ignore
197
		else
198
			return; // silently ignore
199
			
200
		StringTokenizer bodyTokenizer = new StringTokenizer(content, CRNL);
201
		for (int headerCount = 0; bodyTokenizer.hasMoreTokens();
202
			++headerCount) {
203
			String header = bodyTokenizer.nextToken();
204
			if (headerCount == 0) {
205
				StringTokenizer headerTokenizer = new StringTokenizer(header);
206
				
207
				currentHttpRequest.method = headerTokenizer.nextToken();
208
				
209
				String urn = headerTokenizer.nextToken();
210
				if (urn.length() > 6 && urn.substring(0, 7).equals("http://")) {
211
					try {
212
						URL url = new URL(urn);
213
						currentHttpRequest.path = url.getPath();
214
					}
215
					catch (MalformedURLException e) {
216
					}
217
				} else
218
					currentHttpRequest.path = urn;
219
				
220
				String version = headerTokenizer.nextToken();
221
				currentHttpRequest.version =
222
					version.substring(version.indexOf(SLASH) + 1,
223
						version.length());				
224
			}
225
			else {
226
				int colonIndex = header.indexOf(COLON);
227
				if(colonIndex!=-1){
228
					String name = header.substring(0, colonIndex);
229
					String value = header.substring(colonIndex + 1, header.length());
230
					currentHttpRequest.headerNames.add(name);
231
					currentHttpRequest.headerValues.add(value);
232
					
233
					// fetch host and port from Host: header
234
					if (name.trim().equals("Host")) {
235
						try {
236
							URL url = new URL("http://" + value.trim());
237
							currentHttpRequest.host = url.getHost();
238
							currentHttpRequest.port = url.getPort();
239
							if (currentHttpRequest.port == -1) {
240
								// Check if SSL - if so, use 443 for port
241
								if (currentHttpRequest.bSSL)
242
									currentHttpRequest.port = 443;
243
								else
244
									currentHttpRequest.port = 80;
245
							}
246
						}
247
						catch (MalformedURLException e) {
248
							e.printStackTrace();
249
						}
250
					}
251
				}
252
				else if(!(CRNL+CRNL).equalsIgnoreCase(header)){
253
					currentHttpRequest.body.append(header);
254
				}
255
			}	
256
		}
257
	}
258
	
259
	/**
260
261
	 * 
262
	 * @param dataNode
263
	 * modified for bugzilla #90867 & #83976 - tejas.patel.ca.com,george.sebastian@ca.com
264
	 * @throws TestgenException
265
	 */
266
	private void httpRequestContent (TRCNode dataNode)
267
		throws TestgenException
268
	{
269
		String content = dataNode.getElement().getContent();
270
		if (content == null)
271
			throw new TestgenException(CorePluginResourceBundle.E_DATA_NO_CONTENT, null);
272
273
		String encoding = getAttributeValue(PACKET_S_DATA_A_ENCODING, dataNode);
274
		if (encoding == null)
275
			throw new TestgenException(CorePluginResourceBundle.E_DATA_NO_ENCODING_ATT, null);
276
		// TODO: dhinson: needs to handle non-NONE encodings eventually			
277
		// TODO: dhinson: change to equals() when DuWayne fixes value
278
		if (encoding.equalsIgnoreCase(PACKET_S_DATA_A_ENCODING_V_NONE))
279
			currentHttpRequest.body.append(content);
280
		else if (encoding.equals(PACKET_S_DATA_A_ENCODING_V_ASCIIFY))
281
			; // silently ignore
282
		else if (encoding.equals(PACKET_S_DATA_A_ENCODING_V_BASE64))
283
			; // silently ignore
284
		else
285
			; // silently ignore
286
	}
287
	
288
	/**
289
	 * This method is called when the TRCRecordingInfo node handler
290
	 * has determined that a STOP message has been found
291
	 * 
292
	 * This method will call reorderNodeList() to reorder the list of
293
	 * nodes, then call writeNewPageList() to parse the node list and 
294
	 * write the information into the behavior model.
295
	 * 
296
	 * @throws TestgenException
297
	 * modified for bugzilla #90867  - george.sebastian@ca.com
298
	 */
299
	protected void handle_http_stop() throws TestgenException {
300
		// remove_unwanted_responses();
301
		// Call new routine to group the nodes
302
		reorderNodeList();
303
		reorderNodeListAccordingToTimestamp();
304
		writeNewPageList();
305
		//determinePageEnum(); 
306
		//writePageList();
307
		context.setPageNumber(0);	
308
		
309
	}
310
	/**
311
	 * This method will parse a http response and return whether it
312
	 * is a new page or not (Content-Type: equals text/html )
313
	 *  
314
	 * @param node
315
	 * @return true if Content-Type header equals text/html
316
	 * modified for bugzilla #90867 & #83976 - tejas.patel.ca.com,george.sebastian@ca.com
317
	 * @throws TestgenException
318
	 */
319
	private boolean checkResponseForNewPage(TRCNode node) 
320
		throws TestgenException {
321
		boolean retcode = false;
322
323
				
324
		List dataNodeList = TRCNodeHandler.getSubNodeList(PACKET_S_DATA, node);
325
		if (dataNodeList.isEmpty())
326
			throw new TestgenException(CorePluginResourceBundle.E_PACKET_NO_DATA, null);
327
328
		// populate currentHttpRequest
329
		ListIterator itr = dataNodeList.listIterator();
330
		while (itr.hasNext()) {
331
			TRCNode dataNode = (TRCNode)itr.next();
332
333
			String type = TRCNodeHandler.getAttributeValue(PACKET_S_DATA_A_TYPE, dataNode);
334
			if (type == null)
335
				throw new TestgenException(CorePluginResourceBundle.E_DATA_NO_TYPE_ATT, null);
336
			
337
			if(type.equalsIgnoreCase(PACKET_S_DATA_A_TYPE_V_HTTPDATA)){
338
				retcode = httpRequestMessageContentType(dataNode);
339
				break;
340
			}
341
			if (type.equals(PACKET_S_DATA_A_TYPE_V_HTTPMESSAGE)){
342
				retcode = httpRequestMessageContentType(dataNode);
343
				break;
344
			}
345
			else
346
				// ignore any others
347
				continue;
348
		}
349
		return retcode;	
350
	}
351
	/**
352
	 * Parse http Request to see if Content-Type: is 
353
	 * text/html.  Return true to indicate new page.
354
	 * 
355
	 * @param dataNode
356
	 * modified for bugzilla #90867 & #83976 -george.sebastian@ca.com
357
	 * @return
358
	 * @throws TestgenException
359
	 */
360
	private boolean httpRequestMessageContentType(TRCNode dataNode) 
361
		throws TestgenException {
362
		boolean isNewPage = false;
363
		
364
		String content = dataNode.getElement().getContent();
365
		if (content == null)
366
			throw new TestgenException(CorePluginResourceBundle.E_DATA_NO_CONTENT, null);
367
		int contentLocation = getContentLocation(content);
368
		if (contentLocation!=-1){
369
			content = content.substring(0,contentLocation-CRNL.length());
370
		}
371
		StringTokenizer bodyTokenizer = new StringTokenizer(content, CRNL);
372
		for (int headerCount = 0; bodyTokenizer.hasMoreTokens();
373
			++headerCount) {
374
			String header = bodyTokenizer.nextToken();
375
			if (headerCount == 0) {
376
				// Do nothing 		
377
			}
378
			else {
379
				int colonIndex = header.indexOf(COLON);
380
				if(colonIndex==-1){
381
					continue;
382
				}
383
				String name = header.substring(0, colonIndex);
384
				String value = header.substring(colonIndex + 1, header.length());
385
				
386
				// fetch Content-Type
387
				if (name.trim().equalsIgnoreCase("Content-Type")) {
388
					String tempstr = value.trim().toLowerCase();
389
					if (tempstr.trim().startsWith("text/html"))
390
						isNewPage = true;
391
					else
392
						isNewPage = false;
393
					break;
394
				}
395
			}
396
		}	
397
		if (!isNewPage) {
398
			// now check for Redirection - status code of 301 or 302
399
			isNewPage = checkForRedirect(dataNode);
400
		}
401
		return isNewPage;
402
	}
403
	/**
404
	 * Loops through the original list of TRCNode nodes, removing responses 
405
	 * that contain html or jpeg information (that don't have headers)
406
	 * 
407
	 * @throws TestgenException
408
	 */
409
	private void remove_unwanted_responses() throws TestgenException {
410
		LinkedList pageList = null;
411
		boolean writethisNode = true;
412
		int totalNodes = 0;
413
		int i = 0;
414
		TRCNode node = null;
415
		LinkedList newPageList = new LinkedList();
416
		
417
		pageList = context.getPageList();
418
		totalNodes = pageList.size();
419
		for (i = 0; i < totalNodes; i++) {
420
			node = (TRCNode)pageList.get(i);
421
			writethisNode = shouldIWriteNode(node);
422
			if (writethisNode)
423
				newPageList.add(node);
424
		}
425
		int newTotalNodes = newPageList.size();
426
		if (newTotalNodes > 0){
427
			pageList.clear();
428
			context.setPageList(newPageList);
429
		}
430
	}
431
	/**
432
	 * Determine whether a  node has information we need and should be 
433
	 * included in the new list of nodes.
434
	 * 
435
	 * @param node
436
	 * modified for bugzilla #90867 & #83976 - tejas.patel.ca.com,george.sebastian@ca.com
437
	 * @return false if this node is from server and is content only
438
	 * @throws TestgenException
439
	 */
440
	boolean shouldIWriteNode(TRCNode node) throws TestgenException {
441
		boolean writeNode = true;
442
		boolean fromServer = false;
443
		boolean isContent = false;
444
				
445
		// populate currentHttpRequest
446
		
447
		String from = TRCNodeHandler.getAttributeValue(PACKET_A_FROM, node);
448
		if (from.equals(PACKET_A_FROM_V_CLIENT)) {
449
			return true;
450
		}
451
		else if (from.equals(PACKET_A_FROM_V_SERVER)) {
452
			fromServer = true;
453
		}
454
		
455
		List dataNodeList = TRCNodeHandler.getSubNodeList(PACKET_S_DATA, node);
456
		if (dataNodeList.isEmpty())
457
			throw new TestgenException(CorePluginResourceBundle.E_PACKET_NO_DATA, null);
458
		
459
		ListIterator itr = dataNodeList.listIterator();
460
		while (itr.hasNext()) {
461
			TRCNode dataNode = (TRCNode)itr.next();
462
463
			String type = TRCNodeHandler.getAttributeValue(PACKET_S_DATA_A_TYPE, dataNode);
464
			if (type == null)
465
				throw new TestgenException(CorePluginResourceBundle.E_DATA_NO_TYPE_ATT, null);
466
			if (type.equals(PACKET_S_DATA_A_TYPE_V_HTTPMESSAGE)) {
467
				return true;
468
			}
469
			if (type.equals(PACKET_S_DATA_A_TYPE_V_HTTPCONTENT)) {
470
				isContent = true;
471
				break;
472
			}
473
			if (type.equals(PACKET_S_DATA_A_TYPE_V_HTTPDATA)){
474
				isNewType = true;
475
				return true;
476
			}
477
			else
478
				// ignore any others
479
				continue;
480
		}
481
		if (fromServer && isContent)
482
			writeNode = false;
483
		
484
		return writeNode;
485
	}
486
	
487
	/**
488
	 * @param node
489
	 * @return true if this node is a response (from server)
490
	 */
491
	boolean checkIsResponse(TRCNode node) {
492
		boolean isResponse = false;
493
		
494
		String from = TRCNodeHandler.getAttributeValue(PACKET_A_FROM, node);
495
		if (from.equals(PACKET_A_FROM_V_CLIENT)){
496
			isResponse = false;
497
		}
498
		else if (from.equals(PACKET_A_FROM_V_SERVER)) {
499
			isResponse = true;
500
		}
501
		return isResponse;	
502
	}
503
	
504
	/**
505
	 * @param node
506
	 * @return true if this node is from the CLIENT 
507
	 */
508
	boolean checkIsRequest(TRCNode node) {
509
		boolean isRequest = false;
510
	
511
		String from = TRCNodeHandler.getAttributeValue(PACKET_A_FROM, node);
512
		if (from.equals(PACKET_A_FROM_V_CLIENT)){
513
			isRequest = true;
514
		}
515
		else if (from.equals(PACKET_A_FROM_V_SERVER)) {
516
			isRequest = false;
517
		}
518
		return isRequest;	
519
	}
520
	/**
521
	 * Check response for status code of 301 or 302 which indicates redirection
522
	 * 
523
	 * @param node
524
	 * @return
525
	 * @throws TestgenException
526
	 */
527
	boolean checkForRedirect(TRCNode node) throws TestgenException {
528
		
529
		boolean isRedirect = false;
530
		String content = node.getElement().getContent();
531
		if (content == null) {
532
			throw new TestgenException(CorePluginResourceBundle.E_DATA_NO_CONTENT, null);
533
		}
534
		StringTokenizer bodyTokenizer = new StringTokenizer(content, CRNL);
535
		String statusLine = bodyTokenizer.nextToken();
536
		// at this point have HTTP/1.1 301 Object Temporarily Moved
537
		StringTokenizer status = new StringTokenizer(statusLine, BLANK);
538
		status.nextToken();  // This is HTTP/1.1
539
		String actualStatus = status.nextToken();// This is 200 or 302 or 301, etc...
540
		Integer intStat = new Integer(actualStatus);
541
		int actualVal = intStat.intValue();
542
		if ((actualVal == 302) || (actualVal == 301))
543
			isRedirect = true;
544
		
545
		return isRedirect;
546
	}
547
	/**
548
	 * @param node
549
	 * modifed for bugzilla #90867 & #83976 - tejas.patel.ca.com,george.sebastian@ca.com
550
	 * @return
551
	 * @throws TestgenException
552
	 */
553
	private boolean parseHttpRequest (TRCNode node)
554
		throws TestgenException
555
	{
556
		boolean retcode = false;
557
		String timestampString = TRCNodeHandler.getAttributeValue(PACKET_A_TIMESTAMP, node);
558
				
559
		List dataNodeList = TRCNodeHandler.getSubNodeList(PACKET_S_DATA, node);
560
		if (dataNodeList.isEmpty())
561
			throw new TestgenException(CorePluginResourceBundle.E_PACKET_NO_DATA, null);
562
563
		// reset currentHttpRequest
564
		currentHttpRequest = new ParsedHttpMessage();
565
566
		String typeValue = TRCNodeHandler.getAttributeValue(PACKET_A_TYPE, node);
567
		if (typeValue.equals(PACKET_A_TYPE_V_HTTPS))
568
			currentHttpRequest.bSSL = true;
569
		else 
570
			currentHttpRequest.bSSL = false;
571
572
		// populate currentHttpRequest
573
		ListIterator itr = dataNodeList.listIterator();
574
		while (itr.hasNext()) {
575
			TRCNode dataNode = (TRCNode)itr.next();
576
577
			String type = TRCNodeHandler.getAttributeValue(PACKET_S_DATA_A_TYPE, dataNode);
578
			if (type == null)
579
				throw new TestgenException(CorePluginResourceBundle.E_DATA_NO_TYPE_ATT, null);
580
			
581
			if(type.equals(PACKET_S_DATA_A_TYPE_V_HTTPDATA)){
582
				httpRequestMessage(dataNode);
583
				//httpRequestContent(dataNode);
584
			}
585
			else if (type.equals(PACKET_S_DATA_A_TYPE_V_HTTPMESSAGE))
586
				httpRequestMessage(dataNode);
587
			else if (type.equals(PACKET_S_DATA_A_TYPE_V_HTTPCONTENT))
588
				httpRequestContent(dataNode);
589
			else
590
				// ignore any others
591
				continue;
592
		}
593
		
594
		int pageNumber = context.getPageNumber();
595
		currentHttpRequest.nPageNum = pageNumber;
596
		String connectionNumber = TRCNodeHandler.getAttributeValue(PACKET_A_CONNECTIONNAME, node);
597
		Integer thisConn = new Integer(connectionNumber);
598
		currentHttpRequest.nConnID = thisConn.intValue();
599
		currentHttpRequest.timeStampString = timestampString;
600
601
		return retcode;
602
	}
603
	/**
604
	 * @param thisMessage
605
	 * @return
606
	 */
607
	private boolean createPage(ParsedHttpMessage thisMessage){
608
		boolean retcode = false;
609
		
610
		int timestamp = 0;
611
		
612
		int pageNumber = context.getPageNumber();
613
		
614
		String timestampString = thisMessage.timeStampString;
615
		if (timestampString != null)
616
			timestamp = Integer.parseInt(timestampString);
617
		if ((thisMessage.enumPage == HttpRequest.PAGE_ONLY) || (thisMessage.enumPage == HttpRequest.PAGE_START)
618
			|| (pageNumber == 0))
619
		{
620
			pageNumber += 1;
621
			context.setPageNumber(pageNumber);
622
			// thisLoop = context.createNewPage(pageNumber);
623
			String newPageName = thisMessage.host + thisMessage.path;
624
			context.createNewPage(newPageName);
625
		}
626
		String testCaseName = thisMessage.method + " " +
627
			thisMessage.host;
628
		context.newTestCaseContext(testCaseName);
629
		thisMessage.nPageNum = pageNumber;
630
		// fetch and populate RequestHelper...
631
		RequestHelper requestHelper = context.getRequestHelper();
632
		
633
		// ... headers
634
		requestHelper.setAttribute(RequestHelper.ATT_METHOD,
635
			thisMessage.method);
636
		requestHelper.setAttribute(RequestHelper.ATT_HOST,
637
			thisMessage.host);
638
		requestHelper.setAttribute(RequestHelper.ATT_PORT,
639
			Integer.toString(thisMessage.port));
640
		requestHelper.setAttribute(RequestHelper.ATT_ABS_PATH,
641
			thisMessage.path);
642
		requestHelper.setAttribute(RequestHelper.ATT_VERSION,
643
			thisMessage.version);
644
		for (int i = 0; i < thisMessage.headerNames.size(); ++i)
645
			requestHelper.setHeader(((String)thisMessage.headerNames.
646
				get(i)).trim(), ((String)thisMessage.headerValues.
647
				get(i)).trim());
648
649
		//  New attributes from RequestHelper mdd
650
		// ATT_PAGE_NUM = 8;
651
		// ATT_PAGE_ORDER = 9;
652
		// ATT_CONN_ID = 10;
653
		// ATT_CONN_ORDER = 11;
654
		// ATT_IS_SSL = 12;
655
656
		requestHelper.setAttribute(RequestHelper.ATT_PAGE_NUM,
657
			Integer.toString(thisMessage.nPageNum));
658
		requestHelper.setAttribute(RequestHelper.ATT_PAGE_ORDER,
659
			Integer.toString(thisMessage.enumPage));
660
		requestHelper.setAttribute(RequestHelper.ATT_CONN_ID,
661
			Integer.toString(thisMessage.nConnID));
662
		if (thisMessage.bSSL)
663
			requestHelper.setAttribute(RequestHelper.ATT_IS_SSL, "true");
664
		else
665
			requestHelper.setAttribute(RequestHelper.ATT_IS_SSL, "false");
666
			
667
		// ... body
668
		requestHelper.setAttribute(RequestHelper.ATT_BODY,
669
		thisMessage.body.toString());
670
671
		// ... calculate and set request's think time
672
		HashMap	myLastRecvHashMap = context.getLastRecvHashMap();
673
		
674
		int thinkTime = 0;
675
		Integer lastRecvInteger = (Integer)myLastRecvHashMap.get(TRCContext.GLOBAL_LASTRECV);
676
		if (lastRecvInteger != null) {
677
			int lastRecv = lastRecvInteger.intValue();
678
			// thinkTime = (lastRecv == -1) ? timestamp : timestamp - lastRecv;
679
			thinkTime = (lastRecv == -1) ? 0 : timestamp - lastRecv;
680
			if (thinkTime < 0)
681
				thinkTime = 0;
682
		}
683
		requestHelper.setAttribute(RequestHelper.ATT_THINK_TIME,
684
			Integer.toString(thinkTime));
685
		
686
		return retcode;
687
	}
688
	
689
	/**
690
	 * @param node
691
	 * @return
692
	 * @throws TestgenException
693
	 */
694
	private ResponseInfo parseHttpResponse(TRCNode node) throws TestgenException {
695
		ResponseInfo thisResponse = new ResponseInfo();
696
		HashMap	myLastRecvHashMap = context.getLastRecvHashMap();
697
			
698
		int timestamp = Integer.parseInt(TRCNodeHandler.getAttributeValue(PACKET_A_TIMESTAMP,
699
			node));
700
		myLastRecvHashMap.put(TRCContext.GLOBAL_LASTRECV, new Integer(timestamp));
701
		context.setLastRecvHashMap(myLastRecvHashMap);
702
		thisResponse.timeStampString = TRCNodeHandler.getAttributeValue(PACKET_A_TIMESTAMP,node);
703
		thisResponse.newPage = checkResponseForNewPage(node);
704
		
705
		return thisResponse;
706
	}
707
708
	/**
709
	 * @throws TestgenException
710
	 * This routine will reorder the node list in connections then use the new
711
	 * this list to process.
712
	 */
713
	private void reorderNodeList() throws TestgenException {
714
		int totalNodes = -1;
715
		int i = 0;
716
		remove_unwanted_responses();
717
		LinkedList originalNodeList = context.getPageList();
718
		totalNodes = originalNodeList.size();
719
		TRCNode node; 
720
		int connectionIndex = -1;
721
		int connectionNumber = -1;
722
		
723
		for (i = 0; i < totalNodes; i++){
724
			// check connection number first
725
			node = (TRCNode)originalNodeList.get(i);
726
			String strConnectionNumber = TRCNodeHandler.getAttributeValue(PACKET_A_CONNECTIONNAME, node);	
727
			Integer thisConn = new Integer(strConnectionNumber);
728
			connectionNumber = thisConn.intValue();
729
			
730
			connectionIndex = findConnection(connectionNumber);
731
			if (connectionIndex == -1) {
732
				addConnectionNode(connectionNumber,node); 
733
			}
734
			else {
735
				addConnectionChild(connectionIndex, node);
736
			}
737
		} 
738
		// Now replace old List with New List
739
		createNewPageList();
740
	}
741
	/**
742
	 * Reorders the nodes in newpage list in the ascending order of time stamp
743
	 * added for for bugzilla #90867 & #83976 - shobhit.maini@ca.com
744
	 * @throws TestgenException
745
	 */
746
	
747
	private void reorderNodeListAccordingToTimestamp() throws TestgenException {
748
749
		Collections.sort(newPageList, new NewPageListComparator());
750
	}
751
	
752
		
753
	
754
	/**
755
	 * This routine will return the index for this connection, if it exists
756
	 * 
757
	 * @param connectionNumber 
758
	 * 		the connection number to find
759
	 * @return 
760
	 * 		The index of the found connection number or 
761
	 * 		-1 if not found
762
	 */
763
	private int findConnection(int connectionNumber) {
764
		int foundIndex = -1;
765
		int numberOfConnections = -1;
766
		int i = 0;
767
		ConnectionNode thisConnection;
768
		
769
		numberOfConnections = connectionsList.size();
770
		if (numberOfConnections == 0) {
771
			foundIndex = -1;	
772
		}
773
		else {
774
			for (i = 0; i < numberOfConnections; i++) {
775
				thisConnection = (ConnectionNode)connectionsList.get(i);
776
				if (thisConnection.connectionNumber == connectionNumber) {
777
					foundIndex = i;
778
					break;
779
				}	
780
			}
781
		}
782
		return foundIndex;
783
	}
784
	
785
	/**
786
	 * This method creates a new Connection node, and adds newNode as
787
	 * the first child of that node
788
	 * 
789
	 * @param connectionNumber
790
	 * @param newNode
791
	 * @return
792
	 */
793
	private boolean addConnectionNode(int connectionNumber, TRCNode newNode){
794
		boolean retcode = true;
795
			
796
		// Create a new ConnectionNode
797
		ConnectionNode newConnectionNode = new ConnectionNode();
798
		// Add the connection number and the new child
799
		newConnectionNode.connectionNumber = connectionNumber;
800
		newConnectionNode.childrenNodes = new LinkedList();
801
		newConnectionNode.childrenNodes.add(newNode);
802
		// Add this connectionNode to the ConnectionsList 
803
		connectionsList.add(newConnectionNode);
804
		
805
		
806
		return retcode;
807
	}
808
	/**
809
	 * This method adds newNode as a child of the Connection node found
810
	 * at connectionIndex
811
	 * 
812
	 * @param connectionIndex
813
	 * @param newNode
814
	 * @return
815
	 */
816
	public boolean addConnectionChild(int connectionIndex, TRCNode newNode){
817
		boolean retcode = true;
818
		
819
		ConnectionNode thisConnection = (ConnectionNode)connectionsList.get(connectionIndex);
820
		thisConnection.childrenNodes.add(newNode);
821
		return retcode;	
822
	}
823
	
824
	/**
825
	 * This method goes through each Connection node, and adds each child
826
	 * found for that Connection node to the reordered list of TRCNode nodes
827
	 * 
828
	 * This newPageList will be processed to create the testsuite.
829
	 * @return 
830
	 * modified for bugzilla #90867 & #83976 - george.sebastian@ca.com
831
	 * @throws TestgenException 
832
	 * 
833
	 */
834
	private void createNewPageList() throws TestgenException {
835
	
836
		if (isNewType()){
837
			createPageListNew();
838
			return;
839
		}		
840
		createPageListOld();
841
	}
842
	
843
	//added for bugzilla #90867 & #83976 - tejas.patel.ca.com,george.sebastian@ca.com
844
	private void createPageListOld() throws TestgenException {
845
		int totalConnections = -1;
846
		int i = 0;
847
		int j = 0; 
848
		ConnectionNode thisConnection = null;
849
		TRCNode thisNode = null;
850
		TRCNode nextNode = null;
851
		int totalChildren = -1;
852
		totalConnections = connectionsList.size();
853
		for (i = 0; i < totalConnections; i++){
854
			thisConnection = (ConnectionNode)connectionsList.get(i);
855
			totalChildren = thisConnection.childrenNodes.size();
856
			childrenLoop:
857
			for (j = 0; j < totalChildren; j++){
858
				thisNode = (TRCNode)thisConnection.childrenNodes.get(j);
859
				for(int counter = 1; ; counter++)
860
				{
861
					if((counter+j) >= totalChildren){
862
						break;
863
					}
864
					if(checkIsPOSTRequest(thisNode)){
865
						
866
						nextNode = (TRCNode)thisConnection.childrenNodes.get(j+counter);
867
						String from = TRCNodeHandler.getAttributeValue(PACKET_A_FROM,nextNode);
868
						if(!from.equalsIgnoreCase(PACKET_A_FROM_V_SERVER)){
869
							thisNode.getElement().setContent(nextNode.getElement().getContent());
870
							((TRCNode)thisNode.getSubNodes().getFirst()).getElement().setContent(
871
									((TRCNode)nextNode.getSubNodes().getFirst()).getElement().getContent());
872
							j++;
873
						}
874
						else{
875
							boolean isContinue = checkForContinue(nextNode);
876
							if(true == isContinue)
877
							{
878
								((TRCNode)thisNode.getSubNodes().getFirst()).getElement().setContent(
879
										((TRCNode)nextNode.getSubNodes().getFirst()).getElement().getContent());
880
								continue;
881
							}
882
							else
883
							{
884
								newPageList.add(thisNode);
885
								j = j + counter - 1;
886
								continue childrenLoop;
887
							}
888
						}
889
					}
890
				}	
891
				newPageList.add(thisNode);
892
				continue childrenLoop;
893
			}
894
		}
895
		
896
	}
897
 // added for bugzilla #90867 & #83976 - tejas.patel.ca.com,george.sebastian@ca.com
898
	private void createPageListNew() throws TestgenException {
899
		int totalConnections = -1;
900
		int i = 0;
901
		int j = 0; 
902
		int counter = 0;
903
		ConnectionNode thisConnection = null;
904
		TRCNode thisNode = null;
905
		int totalChildren = -1;
906
		
907
		totalConnections = connectionsList.size();
908
		connectionLoop:
909
		for (i = 0; i < totalConnections; i++){
910
			
911
			thisConnection = (ConnectionNode)connectionsList.get(i);
912
			totalChildren = thisConnection.childrenNodes.size();
913
			
914
			childrenLoop:
915
			for (j = 0; j < totalChildren; j++){
916
				
917
				thisNode = (TRCNode)thisConnection.childrenNodes.get(j);
918
				String from = TRCNodeHandler.getAttributeValue(PACKET_A_FROM, thisNode);
919
				
920
				if(from.equals(PACKET_A_FROM_V_CLIENT))
921
				{
922
					for(counter = 1; ; counter++)
923
					{
924
						if((j + counter) >= totalChildren)
925
						{
926
							newPageList.add(thisNode);
927
							continue connectionLoop;
928
						}
929
						
930
						TRCNode nextNode = (TRCNode)thisConnection.childrenNodes.get(j + counter);
931
						from = TRCNodeHandler.getAttributeValue(PACKET_A_FROM, nextNode);
932
						
933
						if(from.equals(PACKET_A_FROM_V_SERVER))
934
						{
935
							if(checkIsPOSTRequest(thisNode))
936
							{
937
								boolean isContinue = checkForContinue(nextNode);
938
								if(true == isContinue)
939
								{
940
									((TRCNode)thisNode.getSubNodes().getFirst()).getElement().setContent(
941
											((TRCNode)nextNode.getSubNodes().getFirst()).getElement().getContent());
942
									continue;
943
								}
944
								else
945
								{
946
									newPageList.add(thisNode);
947
									j = j + counter - 1;
948
									continue childrenLoop;
949
								}
950
							}
951
							newPageList.add(thisNode);
952
							j = j + counter - 1;
953
							continue childrenLoop;
954
						}else{
955
						//thisNode.getElement().setContent(nextNode.getElement().getContent());
956
							((TRCNode)thisNode.getSubNodes().getFirst()).getElement().setContent(
957
									((TRCNode)nextNode.getSubNodes().getFirst()).getElement().getContent());
958
						}
959
					}
960
					
961
				}
962
				if (from.equals(PACKET_A_FROM_V_SERVER)) {
963
					
964
					for(counter = 1; ; counter++)
965
					{
966
						if((j + counter) >= totalChildren)
967
						{
968
							newPageList.add(thisNode);
969
							continue connectionLoop;
970
						}
971
						
972
						TRCNode nextNode = (TRCNode)thisConnection.childrenNodes.get(j + counter);
973
						from = TRCNodeHandler.getAttributeValue(PACKET_A_FROM, nextNode);
974
						if(from.equals(PACKET_A_FROM_V_CLIENT))
975
						{
976
							newPageList.add(thisNode);
977
							j = j + counter - 1;
978
							continue childrenLoop;
979
						}
980
						thisNode.getElement().setContent(nextNode.getElement().getContent());
981
					}
982
										
983
				}
984
				newPageList.add(thisNode);
985
			}
986
		}
987
		
988
	}
989
	
990
   /** Check request for POST method
991
	 * 
992
	 * @param dataNode
993
	 * @return
994
	 * added for bugzilla #90867 & #83976 - tejas.patel.ca.com,george.sebastian@ca.com
995
	 * @throws TestgenException
996
	 */
997
	boolean checkIsPOSTRequest(TRCNode dataNode) throws TestgenException {
998
		boolean isPOSTRequest = false;
999
		String tempContent = null;
1000
		byte[] decContent = null;
1001
		String content = ((TRCNode)dataNode.getSubNodes().getFirst()).getElement().getContent();
1002
		if (content == null)
1003
			throw new TestgenException(CorePluginResourceBundle.E_DATA_NO_CONTENT, null);
1004
1005
		String encoding = getAttributeValue(PACKET_S_DATA_A_ENCODING, dataNode);
1006
		if (encoding == null)
1007
			throw new TestgenException(CorePluginResourceBundle.E_DATA_NO_ENCODING_ATT, null);
1008
		// TODO: dhinson: needs to handle non-NONE encodings eventually			
1009
		// TODO: dhinson: change to equals() when DuWayne fixes value
1010
		if (encoding.equalsIgnoreCase(PACKET_S_DATA_A_ENCODING_V_NONE))
1011
			; // do nothing (no translation required)
1012
		else if (encoding.equals(PACKET_S_DATA_A_ENCODING_V_ASCIIFY)) {
1013
			TRCAsciifier myasc = new TRCAsciifier();
1014
			decContent = new byte[content.length()];
1015
			myasc.decode(content, 0, content.length(), decContent);
1016
			tempContent = new String(decContent);
1017
			String tmp = tempContent.trim();
1018
			content = tmp;
1019
			
1020
		}
1021
		else if (encoding.equals(PACKET_S_DATA_A_ENCODING_V_BASE64))
1022
			return false; 
1023
		else
1024
			return false; 
1025
		
1026
		StringTokenizer bodyTokenizer = new StringTokenizer(content, CRNL);
1027
		for (int headerCount = 0; bodyTokenizer.hasMoreTokens();
1028
			++headerCount) {
1029
			String header = bodyTokenizer.nextToken();
1030
			if (headerCount == 0) {
1031
				StringTokenizer headerTokenizer = new StringTokenizer(header);
1032
				if(HTTP_POST.equalsIgnoreCase(headerTokenizer.nextToken().trim())){
1033
					return true;
1034
				
1035
				}
1036
				
1037
			}	
1038
		}		
1039
		return isPOSTRequest;
1040
	}
1041
	
1042
	/** Check response for status code of 100 which indicates continue
1043
	  * 
1044
	  * @param node
1045
	  * added for bugzilla #90867 & #83976 - tejas.patel.ca.com
1046
	  * @return
1047
	  * @throws TestgenException
1048
	  */
1049
	boolean checkForContinue(TRCNode node) throws TestgenException {
1050
		
1051
		boolean isContinue = false;
1052
		String content = ((TRCNode)node.getSubNodes().getFirst()).getElement().getContent();
1053
		//String content = node.getElement().getContent();
1054
		if (content == null) {
1055
			throw new TestgenException(CorePluginResourceBundle.E_DATA_NO_CONTENT, null);
1056
		}
1057
		StringTokenizer bodyTokenizer = new StringTokenizer(content, CRNL);
1058
		String statusLine = bodyTokenizer.nextToken();
1059
		// at this point have HTTP/1.1 100 Continue
1060
		StringTokenizer status = new StringTokenizer(statusLine, BLANK);
1061
		status.nextToken();  // This is HTTP/1.1
1062
		String actualStatus = status.nextToken();// This is 200 or 100 or 301, etc...
1063
		Integer intStat = new Integer(actualStatus);
1064
		int actualVal = intStat.intValue();
1065
		if (actualVal == 100){
1066
			isContinue = true;
1067
		}
1068
		return isContinue;
1069
	}
1070
	/**
1071
	 * This method goes through the newly reordered TRCNode node list, 
1072
	 *	and creates Behavior Model entries for each. One of the elements of 
1073
	 *	the behavior model is page enumeration (begin, middle, end or only).
1074
	 *	Since you don't know the enumeration of a particular request/response
1075
	 *	pair until you have looked at the subsequent pair, we must store the 
1076
	 *	request and compare the current request to the previous response to 
1077
	 *	determine enumeration.
1078
	 *
1079
	 *		Determine if node is a HttpRequest or HttpResponse
1080
	 *		If HttpRequest
1081
	 *			parse request and populate currentHttpRequest
1082
	 *		If HttpResponse
1083
	 *			parse request and determine if it is a New Page 
1084
	 *
1085
	 *		If have both the request and response
1086
	 *			Determine the Page Enumeration for Previous Response
1087
	 *			Write Previous Response
1088
	 *
1089
	 * @throws TestgenException
1090
	 */
1091
	public void writeNewPageList()  throws TestgenException {
1092
		int totalNodes = -1;
1093
		int i = 0;
1094
		boolean isARequest = false;
1095
		TRCNode currentNode = null;
1096
		boolean haveRequest = false;
1097
		boolean haveResponse = false;
1098
		ResponseInfo responseInfo = null;
1099
1100
		// Process the entire node list
1101
		totalNodes = newPageList.size();
1102
		for (i = 0; i < totalNodes; i++) {
1103
			currentNode = (TRCNode)newPageList.get(i);
1104
			isARequest = checkIsRequest(currentNode);
1105
			if (isARequest) {
1106
				haveRequest = true;
1107
				parseHttpRequest(currentNode);
1108
			}
1109
			else {
1110
				haveResponse = true;
1111
				responseInfo = parseHttpResponse(currentNode);
1112
				currentHttpRequest.timeStampString = responseInfo.timeStampString;
1113
				currentHttpRequest.newPage = responseInfo.newPage;
1114
			}
1115
			
1116
			if (haveRequest && haveResponse) {
1117
				haveRequest = false;
1118
				haveResponse = false;
1119
				if (totalNodes == 2) {
1120
					currentHttpRequest.newPage = true;
1121
					currentHttpRequest.enumPage = HttpRequest.PAGE_ONLY;
1122
					createPage(currentHttpRequest);
1123
					break;
1124
				}
1125
				if ((previousHttpRequest == null) || (i == 1)) {
1126
					// This is the First Page
1127
					currentHttpRequest.newPage = true;
1128
					currentHttpRequest.enumPage = HttpRequest.PAGE_START;
1129
					previousHttpRequest = currentHttpRequest;
1130
				}
1131
				else {
1132
					if (previousHttpRequest.newPage) {
1133
						// Previous Request IS a new page
1134
						if (currentHttpRequest.newPage) {
1135
							previousHttpRequest.enumPage = HttpRequest.PAGE_ONLY;
1136
						}
1137
						else {
1138
							// Current Request NOT a new page
1139
							previousHttpRequest.enumPage = HttpRequest.PAGE_START;
1140
						}
1141
					}
1142
					else {
1143
						// Previous Message NOT a new page
1144
						if (currentHttpRequest.newPage) {
1145
							previousHttpRequest.enumPage = HttpRequest.PAGE_END;
1146
						}
1147
						else {
1148
							previousHttpRequest.enumPage = HttpRequest.PAGE_MID;
1149
						}
1150
					}
1151
					createPage(previousHttpRequest);
1152
					previousHttpRequest = currentHttpRequest;
1153
					previousHttpRequest.enumPage = HttpRequest.PAGE_END;
1154
					if (i == (totalNodes - 1)) {
1155
						if (previousHttpRequest.newPage)
1156
							previousHttpRequest.enumPage = HttpRequest.PAGE_ONLY;
1157
						createPage(previousHttpRequest);
1158
					}
1159
					
1160
				}
1161
			}
1162
		}
1163
	}
1164
	
1165
	/**
1166
	 * 
1167
	 * @param attribute
1168
	 * added for bugzilla #90867 & #83976 - george.sebastian@ca.com
1169
	 * @param node
1170
	 * @return
1171
	 */
1172
	
1173
	private String getAttributeValue(String attribute, TRCNode node) {
1174
		
1175
		String value = TRCNodeHandler.getAttributeValue(attribute,node);
1176
		if (value == null ){
1177
			
1178
			for (int i = 0 ; i <node.getSubNodes().size() ; i++) {
1179
				value = getAttributeValue(attribute, (TRCNode) node.getSubNodes().get(i));
1180
				if (value != null)
1181
					return value;
1182
			}
1183
		}
1184
		return value;
1185
	}
1186
	//	added for bugzilla #90867 & #83976 - george.sebastian@ca.com
1187
	public boolean isNewType() {
1188
		return isNewType;
1189
	}
1190
	// added for bugzilla #90867 & #83976 - tejas.patel.ca.com
1191
	private int getContentLocation(String str)
1192
	{
1193
		int iRet = -1;
1194
		
1195
		iRet = str.indexOf(CRNL + CRNL);
1196
		
1197
		if(-1 != iRet)
1198
			iRet += 4;
1199
		
1200
		return iRet;
1201
		
1202
	}
1203
}
(-)src-testgen-http/org/eclipse/hyades/execution/testgen/http/TRCElement.java (-87 lines)
Removed Link Here
1
/**********************************************************************
2
 * Copyright (c) 2005 IBM Corporation and others.
3
 * All rights reserved.   This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: TRCElement.java,v 1.4 2005/06/09 17:00:43 jnevicos Exp $
8
 * 
9
 * Contributors: 
10
 * IBM Corporation - initial API and implementation
11
 **********************************************************************/
12
package org.eclipse.hyades.execution.testgen.http;
13
14
15
/**
16
 * @author dhinson
17
 *
18
 * @deprecated should not be public API. Will be changed to internal in TPTP 5.
19
 */
20
public class TRCElement
21
{
22
	public class TRCAttribute
23
	{
24
		public String name;
25
		public String value;
26
		
27
		public TRCAttribute (String name, String value)
28
		{
29
			this.name = name;
30
			this.value = value;
31
		}
32
	}
33
	
34
	private String			name;		
35
	private TRCAttribute []	attributes;
36
	private int				attributeCount;
37
	private StringBuffer	contentBuffer;
38
	private TRCNode			node;
39
	
40
	public TRCElement (int nAttributes)
41
	{
42
		attributes = new TRCAttribute[nAttributes];
43
	}
44
	
45
	public void setName (String name)
46
	{
47
		this.name = name;
48
	}
49
	
50
	public String getName ()
51
	{
52
		return this.name;
53
	}
54
55
	public void addAttribute (String name, String value)
56
	{
57
		attributes[attributeCount++] = new TRCElement.TRCAttribute(name, value);	
58
	}
59
	
60
	public TRCAttribute [] getAttributes ()
61
	{
62
		return this.attributes;
63
	}
64
	
65
	public void setContent (String content)
66
	{
67
		if (contentBuffer == null)
68
			contentBuffer = new StringBuffer();
69
		contentBuffer.append(content);
70
	}
71
	
72
	public String getContent ()
73
	{
74
		return contentBuffer.toString();
75
	}
76
	
77
	public void setNode (TRCNode node)
78
	{
79
		this.node = node;
80
	}
81
	
82
	public TRCNode getNode ()
83
	{
84
		return this.node;
85
	}
86
		
87
}
(-)src-testgen-http/org/eclipse/hyades/execution/testgen/http/TRCNode.java (-74 lines)
Removed Link Here
1
/**********************************************************************
2
 * Copyright (c) 2005 IBM Corporation and others.
3
 * All rights reserved.   This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: TRCNode.java,v 1.4 2005/06/09 17:00:43 jnevicos Exp $
8
 * 
9
 * Contributors: 
10
 * IBM Corporation - initial API and implementation
11
 **********************************************************************/
12
package org.eclipse.hyades.execution.testgen.http;
13
14
import java.util.LinkedList;
15
16
17
/**
18
 * @author dhinson
19
 *
20
 * @deprecated should not be public API. Will be changed to internal in TPTP 5.
21
 */
22
public class TRCNode
23
{
24
	private String		name;
25
	private TRCElement	element;
26
	private TRCNode		parentNode;
27
	private LinkedList	subNodes = new LinkedList();
28
		
29
	public TRCNode (String name)
30
	{
31
		this.name = name;
32
	}
33
34
	public void setName (String name)
35
	{
36
		this.name = name;
37
	}
38
	
39
	public String getName ()
40
	{
41
		return name;
42
	}
43
	
44
	public void setElement (TRCElement element)
45
	{
46
		this.element = element;
47
	}
48
	
49
	public TRCElement getElement ()
50
	{
51
		return element;
52
	}
53
	
54
	public void setParentNode (TRCNode parentNode)
55
	{
56
		this.parentNode = parentNode;
57
	}
58
	
59
	public TRCNode getParentNode ()
60
	{
61
		return parentNode;
62
	}
63
	
64
	public void setSubNodes (LinkedList subNodes)
65
	{
66
		this.subNodes = subNodes;
67
	}
68
	
69
	public LinkedList getSubNodes ()
70
	{
71
		return subNodes;
72
	}
73
74
}
(-)src-testgen-http/org/eclipse/hyades/execution/testgen/http/TRCRecorderInfoNodeHandler.java (-63 lines)
Removed Link Here
1
/**********************************************************************
2
 * Copyright (c) 2005, 2007 IBM Corporation and others.
3
 * All rights reserved.   This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: TRCRecorderInfoNodeHandler.java,v 1.7 2007/05/03 18:21:00 paules Exp $
8
 * 
9
 * Contributors: 
10
 * IBM Corporation - initial API and implementation
11
 **********************************************************************/
12
package org.eclipse.hyades.execution.testgen.http;
13
14
import org.eclipse.hyades.test.core.testgen.TestgenException;
15
16
17
18
/**
19
 * @author mdunn
20
 *
21
 * @deprecated should not be public API. Will be changed to internal in TPTP 5.
22
 * 
23
 */
24
public class TRCRecorderInfoNodeHandler extends TRCNodeHandler implements ITRCNodeHandler
25
{
26
27
	private static final String	RECORDERINFO_A_TYPE
28
														= "type";
29
	private static final String	RECORDERINFO_A_TYPE_V_STOP
30
														= "STOP";
31
	
32
	public void init (TRCContext context)
33
		throws TestgenException
34
	{
35
		super.init(context);
36
	}
37
	
38
	public void node (TRCNode node)
39
		throws TestgenException
40
	{
41
42
		// dispatch on type attribute
43
		String typeValue = getAttributeValue(RECORDERINFO_A_TYPE, node);		
44
		if (typeValue.equals(RECORDERINFO_A_TYPE_V_STOP)) {
45
			handle_stop();
46
			return;
47
		}
48
		else {
49
			// currently ignore anything but "STOP"
50
			return;
51
		}
52
	}
53
	// write all this info out from the pageList LinkedList
54
	private void handle_stop() throws TestgenException {
55
		TestGenHttp myHttp = new TestGenHttp(context);
56
		myHttp.handle_http_stop();
57
		
58
			
59
	}
60
61
62
63
}
(-)src-testgen/org/eclipse/hyades/execution/testgen/TestgenPlugin.java (-144 lines)
Removed Link Here
1
/**********************************************************************
2
 * Copyright (c) 2005, 2007 IBM Corporation and others.
3
 * All rights reserved.   This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 * $Id: TestgenPlugin.java,v 1.10 2007/05/03 17:36:06 paules Exp $
8
 * 
9
 * Contributors: 
10
 * IBM Corporation - initial API and implementation
11
 **********************************************************************/
12
package org.eclipse.hyades.execution.testgen;
13
14
import java.util.MissingResourceException;
15
import java.util.ResourceBundle;
16
17
import org.eclipse.core.resources.IWorkspace;
18
import org.eclipse.core.resources.ResourcesPlugin;
19
import org.eclipse.core.runtime.Platform;
20
import org.eclipse.hyades.test.core.testgen.TestGeneratorFactory;
21
import org.eclipse.hyades.test.ui.UiPlugin;
22
import org.eclipse.jface.preference.IPreferenceStore;
23
import org.eclipse.ui.plugin.AbstractUIPlugin;
24
25
/**
26
 * The main Testgen plugin
27
 * @author Ernest Jessee
28
 * @deprecated use main UIPlugin
29
 */
30
public class TestgenPlugin extends AbstractUIPlugin {
31
	/**
32
	 * The default instance of this plugin
33
	 */
34
	private static TestgenPlugin plugin;
35
	
36
	/**
37
	 * preference store keys
38
	 */
39
	public static final String TEST_GENERATOR="default_test_generator"; //$NON-NLS-1$
40
	//public static final String SELECTED_GENERATOR="selected_generator";	 //$NON-NLS-1$
41
	public static final String ID = "org.eclipse.hyades.test.ui"; //$NON-NLS-1$
42
	private ResourceBundle resourceBundle;
43
	
44
	public TestgenPlugin() {
45
		super();
46
		getResourceBundle();
47
		plugin=this;
48
	}
49
	
50
	/**
51
	 * Returns the shared instance.
52
	 */
53
	public static TestgenPlugin getDefault() {
54
		return plugin;
55
	}
56
57
	/**
58
	 * Returns the workspace instance.
59
	 */
60
	public static IWorkspace getWorkspace() {
61
		return ResourcesPlugin.getWorkspace();
62
	}
63
64
	/**
65
     * Resolves the localized message associated with the parameter <code>key</code>
66
     * based on the default locale from the plugin's resource bundle.
67
     * <p>
68
     * If the <code>key</code> does not exist in the plugin's resource bundle, the 
69
     * <code>key</code> is returned.
70
     * <p>
71
     * Noteworthy, the resultant message is not formatted (e.g. no message parameter substitution). 
72
     * <p>
73
     * 
74
     * @param key The <code>key</code> of the message in the plugin's resource bundle.
75
     * @return The localized message associated with the parameter <code>key</code> from the plugin's resource bundle, otherwise the <code>key</code>.
76
     * @deprecated As of TPTP V4.4, use {@link org.eclipse.hyades.test.ui.internal.resources.UiPluginResourceBundle} for resolving resources.  The plugin.properties property file ONLY contains messages for the this plug-in's MANIFEST.MF and plugin.xml files.
77
     */
78
    public static String getResourceString(String key) {
79
        ResourceBundle bundle = UiPlugin.getDefault().getResourceBundle();
80
        try {
81
            return (bundle != null) ? bundle.getString(key) : key;
82
        } catch (MissingResourceException e) {
83
            return key;
84
        }
85
    }
86
87
    /**
88
     * Resolves the plugin's resource bundle.
89
     * <p>
90
     * If the plugin's resource bundle can not be resolved, <code>null</code> is returned.
91
     * <p>
92
     * IMPORTANT: Do not use this method to retrieve values from the resource bundle.  This method 
93
     * is provided so this plugin's resource bundle can be used as the parent of another plugin's 
94
     * resource bundle.
95
     * <p>
96
     * 
97
     * @return The plugin's resource bundle, otherwise <code>null</code>.
98
     * @deprecated As of TPTP V4.4, use {@link org.eclipse.hyades.test.ui.internal.resources.UiPluginResourceBundle} for resolving resources.  The plugin.properties property file ONLY contains messages for the this plug-in's MANIFEST.MF and plugin.xml files.
99
     */
100
    public ResourceBundle getResourceBundle() {
101
        try {
102
            if (resourceBundle == null)
103
                resourceBundle   = Platform.getResourceBundle(Platform.getBundle(ID));
104
        } catch (MissingResourceException x) {
105
            resourceBundle = null;
106
        }
107
        return resourceBundle;
108
    }
109
	
110
	/**
111
	 * acquires a reference to a plugin preference specified by "key"
112
	 * @param key
113
	 * @return
114
	 */
115
	public static String getPreference(String key)
116
	{
117
		return getDefault().getPreferenceStore().getString(key);
118
	}
119
	
120
	/**
121
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#initializeDefaultPreferences(org.eclipse.jface.preference.IPreferenceStore)
122
	 */
123
	protected void initializeDefaultPreferences(IPreferenceStore store)
124
	{
125
		
126
		store.setDefault(TestgenPlugin.TEST_GENERATOR,getDefaultGeneratorID()); //$NON-NLS-1$
127
		
128
	}
129
130
	public String getDefaultGeneratorID()
131
	{
132
		//find all registered generators, select the highest priority
133
		String[] ids = TestGeneratorFactory.getInstance().getGeneratorIDs();
134
		String defaultID = "org.eclipse.hyades.test.tools.core.TestGenerator.HTTPGenerator";
135
		int nMax = -1;
136
		for (int i = 0; i < ids.length; i++)
137
		{
138
			if (TestGeneratorFactory.getInstance().getGeneratorPriority(ids[i]) > nMax)
139
				defaultID = ids[i];
140
		}
141
		return defaultID;	
142
	}
143
144
}

Return to bug 208110