You are viewing a plain text version of this content. The canonical link for it is here.
Posted to jmeter-dev@jakarta.apache.org by se...@apache.org on 2005/11/21 00:02:02 UTC

svn commit: r345790 - in /jakarta/jmeter/branches/rel-2-1/src/protocol/http/org/apache/jmeter/protocol/http/sampler: HTTPSampler.java HTTPSampler2.java HTTPSamplerBase.java

Author: sebb
Date: Sun Nov 20 15:01:56 2005
New Revision: 345790

URL: http://svn.apache.org/viewcvs?rev=345790&view=rev
Log:
Tidy up use of strings; extract some common code

Modified:
    jakarta/jmeter/branches/rel-2-1/src/protocol/http/org/apache/jmeter/protocol/http/sampler/HTTPSampler.java
    jakarta/jmeter/branches/rel-2-1/src/protocol/http/org/apache/jmeter/protocol/http/sampler/HTTPSampler2.java
    jakarta/jmeter/branches/rel-2-1/src/protocol/http/org/apache/jmeter/protocol/http/sampler/HTTPSamplerBase.java

Modified: jakarta/jmeter/branches/rel-2-1/src/protocol/http/org/apache/jmeter/protocol/http/sampler/HTTPSampler.java
URL: http://svn.apache.org/viewcvs/jakarta/jmeter/branches/rel-2-1/src/protocol/http/org/apache/jmeter/protocol/http/sampler/HTTPSampler.java?rev=345790&r1=345789&r2=345790&view=diff
==============================================================================
--- jakarta/jmeter/branches/rel-2-1/src/protocol/http/org/apache/jmeter/protocol/http/sampler/HTTPSampler.java (original)
+++ jakarta/jmeter/branches/rel-2-1/src/protocol/http/org/apache/jmeter/protocol/http/sampler/HTTPSampler.java Sun Nov 20 15:01:56 2005
@@ -49,7 +49,7 @@
  * 
  */
 public class HTTPSampler extends HTTPSamplerBase {
-	private static final Logger log = LoggingManager.getLoggerForClass();
+    private static final Logger log = LoggingManager.getLoggerForClass();
 
 	private static final int MAX_CONN_RETRIES = 10; // Maximum connection
 
@@ -59,9 +59,10 @@
 	private static final PostWriter postWriter = new PostWriter();
 
 	static {// TODO - document what this is doing and why
-		System.setProperty("java.protocol.handler.pkgs", JMeterUtils.getPropDefault("ssl.pkgs",
-				"com.sun.net.ssl.internal.www.protocol"));
-		System.setProperty("javax.net.ssl.debug", "all");
+		System.setProperty("java.protocol.handler.pkgs", // $NON-NLS-1$ 
+                JMeterUtils.getPropDefault("ssl.pkgs", // $NON-NLS-1$
+				"com.sun.net.ssl.internal.www.protocol")); // $NON-NLS-1$
+		System.setProperty("javax.net.ssl.debug", "all"); // $NON-NLS-1$  // $NON-NLS-2$
 	}
 
 	/**
@@ -131,7 +132,7 @@
 		conn = (HttpURLConnection) u.openConnection();
 		// Delegate SSL specific stuff to SSLManager so that compilation still
 		// works otherwise.
-		if ("https".equalsIgnoreCase(u.getProtocol())) {
+		if (PROTOCOL_HTTPS.equalsIgnoreCase(u.getProtocol())) {
 			try {
 				SSLManager.getInstance().setContext(conn);
 			} catch (Exception e) {
@@ -144,9 +145,9 @@
 		// leave it to the server to close the connection after their
 		// timeout period. Leave it to the JMeter user to decide.
 		if (getUseKeepAlive()) {
-			conn.setRequestProperty("Connection", "keep-alive");
+			conn.setRequestProperty(HEADER_CONNECTION, KEEP_ALIVE);
 		} else {
-			conn.setRequestProperty("Connection", "close");
+			conn.setRequestProperty(HEADER_CONNECTION, CONNECTION_CLOSE);
 		}
 
 		conn.setRequestMethod(method);
@@ -184,9 +185,8 @@
 		BufferedInputStream in;
 		boolean logError = false; // Should we log the error?
 		try {
-			if ("gzip".equals(conn.getContentEncoding()))// works OK even if
-			// CE is null
-			{
+            // works OK even if ContentEncoding is null
+			if (ENCODING_GZIP.equals(conn.getContentEncoding())) {
 				in = new BufferedInputStream(new GZIPInputStream(conn.getInputStream()));
 			} else {
 				in = new BufferedInputStream(conn.getInputStream());
@@ -260,35 +260,21 @@
 		// headerBuf.append(conn.getResponseMessage());
 		headerBuf.append("\n");
 
-		for (int i = 1; conn.getHeaderFieldKey(i) != null; i++) {
-			modifyHeaderValues(conn, i, headerBuf);
+        String hfk;
+		for (int i = 1; (hfk=conn.getHeaderFieldKey(i)) != null; i++) {
+            // TODO - why is this not saved? A: it might be a proxy server specific field.
+            // If JMeter is using a proxy, the browser wouldn't know about that.
+            if (!TRANSFER_ENCODING.equalsIgnoreCase(hfk)) {
+                headerBuf.append(hfk);
+                headerBuf.append(": "); // $NON-NLS-1$
+                headerBuf.append(conn.getHeaderField(i));
+                headerBuf.append("\n"); // $NON-NLS-1$
+            }
 		}
 		return headerBuf.toString();
 	}
 
 	/**
-	 * @param conn
-	 *            connection
-	 * @param headerIndex
-	 *            which header to use
-	 * @param resultBuf
-	 *            output string buffer
-	 */
-	protected void modifyHeaderValues(HttpURLConnection conn, int headerIndex, StringBuffer resultBuf) {
-		if ("transfer-encoding" // TODO - why is this not saved? A: it might be
-		// a proxy server specific field.
-				// If JMeter is using a proxy, the browser wouldn't know about
-				// that.
-				.equalsIgnoreCase(conn.getHeaderFieldKey(headerIndex))) {
-			return;
-		}
-		resultBuf.append(conn.getHeaderFieldKey(headerIndex));
-		resultBuf.append(": ");
-		resultBuf.append(conn.getHeaderField(headerIndex));
-		resultBuf.append("\n");
-	}
-
-	/**
 	 * Extracts all the required cookies for that particular URL request and
 	 * sets them in the <code>HttpURLConnection</code> passed in.
 	 * 
@@ -306,7 +292,7 @@
 		if (cookieManager != null) {
 			cookieHeader = cookieManager.getCookieHeaderForURL(u);
 			if (cookieHeader != null) {
-				conn.setRequestProperty("Cookie", cookieHeader);
+				conn.setRequestProperty(HEADER_COOKIE, cookieHeader);
 			}
 		}
 		return cookieHeader;
@@ -338,9 +324,9 @@
 					String v = header.getValue();
 					conn.setRequestProperty(n, v);
 					hdrs.append(n);
-					hdrs.append(": ");
+					hdrs.append(": "); // $NON-NLS-1$
 					hdrs.append(v);
-					hdrs.append("\n");
+					hdrs.append("\n"); // $NON-NLS-1$
 				}
 			}
 		}
@@ -364,7 +350,7 @@
 		if (authManager != null) {
 			Authorization auth = authManager.getAuthForURL(u);
 			if (auth != null) {
-				conn.setRequestProperty("Authorization", auth.toBasicHeader());
+				conn.setRequestProperty(HEADER_AUTHORIZATION, auth.toBasicHeader());
 			}
 		}
 	}
@@ -446,11 +432,11 @@
 
 			int errorLevel = conn.getResponseCode();
 			res.setResponseCode(Integer.toString(errorLevel));
-			res.setSuccessful(200 <= errorLevel && errorLevel <= 399);
+			res.setSuccessful(isSuccessCode(errorLevel));
 
 			res.setResponseMessage(conn.getResponseMessage());
 
-			String ct = conn.getContentType();// getHeaderField("Content-type");
+			String ct = conn.getContentType();
 			res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1
             res.setEncodingAndType(ct);
 
@@ -479,10 +465,10 @@
 
 	protected void disconnect(HttpURLConnection conn) {
 		if (conn != null) {
-			String connection = conn.getHeaderField("Connection");
+			String connection = conn.getHeaderField(HEADER_CONNECTION);
 			String protocol = conn.getHeaderField(0);
-			if ((connection == null && (protocol == null || !protocol.startsWith("HTTP/1.1")))
-					|| (connection != null && connection.equalsIgnoreCase("close"))) {
+			if ((connection == null && (protocol == null || !protocol.startsWith(HTTP_1_1)))
+					|| (connection != null && connection.equalsIgnoreCase(CONNECTION_CLOSE))) {
 				conn.disconnect();
 			}
 		}
@@ -504,7 +490,7 @@
 	private void saveConnectionCookies(HttpURLConnection conn, URL u, CookieManager cookieManager) {
 		if (cookieManager != null) {
 			for (int i = 1; conn.getHeaderFieldKey(i) != null; i++) {
-				if (conn.getHeaderFieldKey(i).equalsIgnoreCase("set-cookie")) {
+				if (conn.getHeaderFieldKey(i).equalsIgnoreCase(HEADER_SET_COOKIE)) {
 					cookieManager.addCookieFromHeader(conn.getHeaderField(i), u);
 				}
 			}

Modified: jakarta/jmeter/branches/rel-2-1/src/protocol/http/org/apache/jmeter/protocol/http/sampler/HTTPSampler2.java
URL: http://svn.apache.org/viewcvs/jakarta/jmeter/branches/rel-2-1/src/protocol/http/org/apache/jmeter/protocol/http/sampler/HTTPSampler2.java?rev=345790&r1=345789&r2=345790&view=diff
==============================================================================
--- jakarta/jmeter/branches/rel-2-1/src/protocol/http/org/apache/jmeter/protocol/http/sampler/HTTPSampler2.java (original)
+++ jakarta/jmeter/branches/rel-2-1/src/protocol/http/org/apache/jmeter/protocol/http/sampler/HTTPSampler2.java Sun Nov 20 15:01:56 2005
@@ -33,10 +33,8 @@
 import org.apache.commons.httpclient.DefaultMethodRetryHandler;
 import org.apache.commons.httpclient.HostConfiguration;
 import org.apache.commons.httpclient.HttpConnection;
-import org.apache.commons.httpclient.HttpConstants;
 import org.apache.commons.httpclient.HttpMethod;
 import org.apache.commons.httpclient.HttpMethodBase;
-import org.apache.commons.httpclient.HttpRecoverableException;
 import org.apache.commons.httpclient.HttpState;
 import org.apache.commons.httpclient.NTCredentials;
 import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
@@ -68,8 +66,6 @@
 public class HTTPSampler2 extends HTTPSamplerBase {
     private static final Logger log = LoggingManager.getLoggerForClass();
 
-    private static final String PROTOCOL_HTTP = "http"; // $NON-NLS-1$
-
     /*
      * Connection is re-used within the thread if possible
      */
@@ -86,6 +82,9 @@
 		}
         log.info("httpsampler2.basicauth=" + basicAuth); // $NON-NLS-1$
         
+        System.setProperty("apache.commons.httpclient.cookiespec", // $NON-NLS-1$
+                "COMPATIBILITY"); // $NON-NLS-1$
+
         int cps =
             JMeterUtils.getPropDefault("httpclient.socket.http.cps", 0); // $NON-NLS-1$        
 
@@ -165,13 +164,13 @@
 				post.setRequestContentLength(EntityEnclosingMethod.CONTENT_LENGTH_CHUNKED);
 			}
 			// TODO - is this correct?
-			post.setRequestHeader("Content-Disposition" // $NON-NLS-1$
+			post.setRequestHeader(HEADER_CONTENT_DISPOSITION
                     , "form-data; name=\"" // $NON-NLS-1$ // $NON-NLS-1$
                     + encode(sampler.getFileField())
 					+ "\"; filename=\""  // $NON-NLS-1$
                     + encode(filename) + "\""); // $NON-NLS-1$
 			// Specify content type and encoding
-			post.setRequestHeader("Content-Type", sampler.getMimetype()); // $NON-NLS-1$
+			post.setRequestHeader(HEADER_CONTENT_TYPE, sampler.getMimetype());
 			post.setRequestBody(new FileInputStream(input));
 		}
 	}
@@ -213,7 +212,7 @@
 		org.apache.commons.httpclient.URI uri = new org.apache.commons.httpclient.URI(urlStr);
 
 		String schema = uri.getScheme();
-		if ((schema == null) || (schema.equals(""))) { // $NON-NLS-1$
+		if ((schema == null) || (schema.length()==0)) {
 			schema = PROTOCOL_HTTP;
 		}
 		Protocol protocol = Protocol.getProtocol(schema);
@@ -246,7 +245,7 @@
 		} else {
 			httpMethod = new GetMethod(urlStr);
 			// httpMethod;
-			new DefaultMethodRetryHandler();
+			new DefaultMethodRetryHandler();//TODO what is this doing??
 		}
 
 		httpMethod.setHttp11(!JMeterUtils.getPropDefault("httpclient.version", "1.1").equals("1.0")); // $NON-NLS-1$ // $NON-NLS-2$ // $NON-NLS-3$
@@ -267,14 +266,13 @@
 		// leave it to the server to close the connection after their
 		// timeout period. Leave it to the JMeter user to decide.
 		if (getUseKeepAlive()) {
-			httpMethod.setRequestHeader("Connection", "keep-alive"); // $NON-NLS-1$ // $NON-NLS-2$
+			httpMethod.setRequestHeader(HEADER_CONNECTION, KEEP_ALIVE);
 		} else {
-			httpMethod.setRequestHeader("Connection", "close"); // $NON-NLS-1$ // $NON-NLS-2$
+			httpMethod.setRequestHeader(HEADER_CONNECTION, CONNECTION_CLOSE);
 		}
 
 		String hdrs = setConnectionHeaders(httpMethod, u, getHeaderManager());
 		String cookies = setConnectionCookie(httpMethod, u, getCookieManager());
-		//System.out.println("setupConnection: cookies = " + cookies);
 
 		if (res != null) {
             res.setURL(u);
@@ -327,17 +325,17 @@
 		org.apache.commons.httpclient.Header rh[] = method.getResponseHeaders();
 		headerBuf.append(method.getStatusLine());// header[0] is not the
 													// status line...
-		headerBuf.append("\n");
+		headerBuf.append("\n"); // $NON-NLS-1$
 
 		for (int i = 0; i < rh.length; i++) {
 			String key = rh[i].getName();
-			if (!key.equalsIgnoreCase("transfer-encoding")) // $NON-NLS-1$
+			if (!key.equalsIgnoreCase(TRANSFER_ENCODING))
                 // TODO - why is this not saved?
 			{
 				headerBuf.append(key);
-				headerBuf.append(": ");
+				headerBuf.append(": "); // $NON-NLS-1$
 				headerBuf.append(rh[i].getValue());
-				headerBuf.append("\n");
+				headerBuf.append("\n"); // $NON-NLS-1$
 			}
 		}
 		return headerBuf.toString();
@@ -358,7 +356,7 @@
 	private String setConnectionCookie(HttpMethod method, URL u, CookieManager cookieManager) {
         // TODO recode to use HTTPClient matches methods or similar
         
-		String cookieHeader = ""; // $NON-NLS-1$
+		StringBuffer cookieHeader = new StringBuffer(100);
         if (cookieManager!=null){
     		String host = "." + u.getHost(); // $NON-NLS-1$
     		
@@ -375,11 +373,13 @@
                     = new org.apache.commons.httpclient.Cookie(cookie.getDomain(), cookie.getName(),
     				     cookie.getValue(), cookie.getPath(), null, false);
     				httpState.addCookie(newCookie);
-    				cookieHeader += cookie.getName() + "=" + cookie.getValue(); // $NON-NLS-1$
+    				cookieHeader.append(cookie.getName());
+                    cookieHeader.append("="); // $NON-NLS-1$
+                    cookieHeader.append(cookie.getValue());
     			}
     		}
         }
-		return cookieHeader;
+		return cookieHeader.toString();
 	}
 
 	/**
@@ -409,9 +409,9 @@
 					String v = header.getValue();
 					method.addRequestHeader(n, v);
 					hdrs.append(n);
-					hdrs.append(": ");
+					hdrs.append(": "); // $NON-NLS-1$
 					hdrs.append(v);
-					hdrs.append("\n");
+					hdrs.append("\n"); // $NON-NLS-1$
 				}
 			}
 		}
@@ -432,14 +432,11 @@
 	 */
 	private void setConnectionAuthorization(HttpMethod method, URL u, AuthManager authManager) {
 		if (authManager != null) {
-			if (basicAuth) {
-				String authHeader = authManager.getAuthHeaderForURL(u);
-				if (authHeader != null) {
-					method.setRequestHeader("Authorization", authHeader); // $NON-NLS-1$
-				}
-			} else {
-				Authorization auth = authManager.getAuthForURL(u);
-				if (auth != null) {
+            Authorization auth = authManager.getAuthForURL(u);
+            if (auth != null) {
+    			if (basicAuth) {
+    					method.setRequestHeader(HEADER_AUTHORIZATION, auth.toBasicHeader());
+    			} else {
                     /*
                      * TODO: better method...
                      * HACK: if user contains \ and or @
@@ -552,35 +549,18 @@
 			res.setResponseData(responseData);
 
 			res.setResponseCode(Integer.toString(statusCode));
-			res.setSuccessful(200 <= statusCode && statusCode <= 399);
+			res.setSuccessful(isSuccessCode(statusCode));
 
 			res.setResponseMessage(httpMethod.getStatusText());
 
 			String ct = null;
 			org.apache.commons.httpclient.Header h 
-                = httpMethod.getResponseHeader("Content-Type"); // $NON-NLS-1$
+                = httpMethod.getResponseHeader(HEADER_CONTENT_TYPE); // $NON-NLS-1$
 			if (h != null)// Can be missing, e.g. on redirect
 			{
 				ct = h.getValue();
 				res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1
-			}
-			if (ct != null) {
-				// Extract charset and store as DataEncoding
-				// TODO do we need process http-equiv META tags, e.g.:
-				// <META http-equiv="content-type" content="text/html;
-				// charset=foobar">
-				// or can we leave that to the renderer ?
-				String de = ct.toLowerCase();
-				final String cs = "charset="; // $NON-NLS-1$
-				int cset = de.indexOf(cs);
-				if (cset >= 0) {
-					res.setDataEncoding(de.substring(cset + cs.length()));
-				}
-				if (ct.startsWith("image/")) { // $NON-NLS-1$
-					res.setDataType(HTTPSampleResult.BINARY);
-				} else {
-					res.setDataType(HTTPSampleResult.TEXT);
-				}
+                res.setEncodingAndType(ct);
 			}
 
 			res.setResponseHeaders(getResponseHeaders(httpMethod));
@@ -670,8 +650,6 @@
 
 	public void threadStarted() {
 		log.debug("Thread Started");
-		
-		System.setProperty("apache.commons.httpclient.cookiespec", "COMPATIBILITY"); // $NON-NLS-1$ // $NON-NLS-2$
 		
 		synchronized ( this.getClass() )
 		{

Modified: jakarta/jmeter/branches/rel-2-1/src/protocol/http/org/apache/jmeter/protocol/http/sampler/HTTPSamplerBase.java
URL: http://svn.apache.org/viewcvs/jakarta/jmeter/branches/rel-2-1/src/protocol/http/org/apache/jmeter/protocol/http/sampler/HTTPSamplerBase.java?rev=345790&r1=345789&r2=345790&view=diff
==============================================================================
--- jakarta/jmeter/branches/rel-2-1/src/protocol/http/org/apache/jmeter/protocol/http/sampler/HTTPSamplerBase.java (original)
+++ jakarta/jmeter/branches/rel-2-1/src/protocol/http/org/apache/jmeter/protocol/http/sampler/HTTPSamplerBase.java Sun Nov 20 15:01:56 2005
@@ -133,6 +133,28 @@
 
     protected static final int MAX_FRAME_DEPTH = JMeterUtils.getPropDefault("httpsampler.max_frame_depth", 5); // $NON-NLS-1$
 
+    protected static final String HEADER_AUTHORIZATION = "Authorization"; // $NON-NLS-1$
+
+    protected static final String HEADER_COOKIE = "Cookie"; // $NON-NLS-1$
+
+    protected static final String HEADER_CONNECTION = "Connection"; // $NON-NLS-1$
+
+    protected static final String CONNECTION_CLOSE = "close"; // $NON-NLS-1$
+
+    protected static final String KEEP_ALIVE = "keep-alive"; // $NON-NLS-1$
+
+    protected static final String TRANSFER_ENCODING = "transfer-encoding";
+
+    protected static final String HTTP_1_1 = "HTTP/1.1"; // $NON-NLS-1$
+
+    protected static final String HEADER_SET_COOKIE = "set-cookie"; // $NON-NLS-1$
+
+    protected static final String ENCODING_GZIP = "gzip"; // $NON-NLS-1$
+
+    protected static final String HEADER_CONTENT_DISPOSITION = "Content-Disposition"; // $NON-NLS-1$
+
+    protected static final String HEADER_CONTENT_TYPE = "Content-Type"; // $NON-NLS-1$
+
     ////////////////////// Variables //////////////////////
     
     private boolean dynamicPath = false;// Set false if spaces are already encoded
@@ -745,4 +767,14 @@
 		}
 		return res;
 	}
+    
+    /**
+     * Determine if the HTTP status code is successful or not
+     * i.e. in range 200 to 399 inclusive
+     * 
+     * @return whether in range 200-399 or not
+     */
+    protected boolean isSuccessCode(int code){
+        return (code >= 200 && code <= 399);
+    }
 }



---------------------------------------------------------------------
To unsubscribe, e-mail: jmeter-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: jmeter-dev-help@jakarta.apache.org