|
From: <mol...@us...> - 2007-07-12 17:17:46
|
Revision: 363
http://svn.sourceforge.net/openutils/?rev=363&view=rev
Author: molaschi
Date: 2007-07-12 10:17:48 -0700 (Thu, 12 Jul 2007)
Log Message:
-----------
Openutils, module openutils-testing-testng-dwr for dwr testing support
Modified Paths:
--------------
trunk/pom.xml
Added Paths:
-----------
trunk/openutils-testing-testng-dwr/
trunk/openutils-testing-testng-dwr/pom.xml
trunk/openutils-testing-testng-dwr/src/
trunk/openutils-testing-testng-dwr/src/main/
trunk/openutils-testing-testng-dwr/src/main/java/
trunk/openutils-testing-testng-dwr/src/main/java/it/
trunk/openutils-testing-testng-dwr/src/main/java/it/openutils/
trunk/openutils-testing-testng-dwr/src/main/java/it/openutils/testing/
trunk/openutils-testing-testng-dwr/src/main/java/it/openutils/testing/testng/
trunk/openutils-testing-testng-dwr/src/main/java/it/openutils/testing/testng/dwr/
trunk/openutils-testing-testng-dwr/src/main/java/it/openutils/testing/testng/dwr/DwrTestCase.java
trunk/openutils-testing-testng-dwr/src/main/java/it/openutils/testing/testng/dwr/JsException.java
trunk/openutils-testing-testng-dwr/src/main/java/it/openutils/testing/testng/dwr/XMLHttpRequest.java
trunk/openutils-testing-testng-dwr/src/main/resources/
trunk/openutils-testing-testng-dwr/src/main/resources/webEnv.js
Added: trunk/openutils-testing-testng-dwr/pom.xml
===================================================================
--- trunk/openutils-testing-testng-dwr/pom.xml (rev 0)
+++ trunk/openutils-testing-testng-dwr/pom.xml 2007-07-12 17:17:48 UTC (rev 363)
@@ -0,0 +1,108 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>net.sourceforge.openutils</groupId>
+ <artifactId>openutils</artifactId>
+ <version>3</version>
+ <relativePath>..</relativePath>
+ </parent>
+ <artifactId>openutils-testing-testng-dwr</artifactId>
+ <name>openutils test utils (testng) for dwr</name>
+ <version>1.0-SNAPSHOT</version>
+ <description>openutils test utils for dwr</description>
+ <dependencies>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-log4j12</artifactId>
+ <version>1.2</version>
+ </dependency>
+ <dependency>
+ <groupId>log4j</groupId>
+ <artifactId>log4j</artifactId>
+ <version>1.2.13</version>
+ </dependency>
+ <dependency>
+ <groupId>org.testng</groupId>
+ <artifactId>testng</artifactId>
+ <classifier>jdk15</classifier>
+ <version>5.1</version>
+ </dependency>
+ <dependency>
+ <groupId>httpunit</groupId>
+ <artifactId>httpunit</artifactId>
+ <version>1.6.1</version>
+ <exclusions>
+ <exclusion>
+ <groupId>xerces</groupId>
+ <artifactId>xmlParserAPIs</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>xerces</groupId>
+ <artifactId>xercesImpl</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>nekohtml</groupId>
+ <artifactId>nekohtml</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>rhino</groupId>
+ <artifactId>js</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>javax.servlet</groupId>
+ <artifactId>servlet-api</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>tomcat</groupId>
+ <artifactId>jasper-compiler-jdt</artifactId>
+ <version>5.5.12</version>
+ </dependency>
+ <dependency>
+ <groupId>tomcat</groupId>
+ <artifactId>naming-resources</artifactId>
+ <version>5.5.15</version>
+ </dependency>
+ <dependency>
+ <groupId>tomcat</groupId>
+ <artifactId>jasper-runtime</artifactId>
+ <version>5.5.12</version>
+ </dependency>
+ <dependency>
+ <groupId>tomcat</groupId>
+ <artifactId>jasper-compiler</artifactId>
+ <version>5.5.12</version>
+ </dependency>
+ <dependency>
+ <groupId>tomcat</groupId>
+ <artifactId>naming-factory</artifactId>
+ <version>5.5.15</version>
+ </dependency>
+ <dependency>
+ <groupId>javax.servlet</groupId>
+ <artifactId>jstl</artifactId>
+ <version>1.1.2</version>
+ </dependency>
+ <dependency>
+ <groupId>javax.servlet</groupId>
+ <artifactId>jsp-api</artifactId>
+ <version>2.0</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>commons-el</groupId>
+ <artifactId>commons-el</artifactId>
+ <version>1.0</version>
+ </dependency>
+ <dependency>
+ <groupId>rhino</groupId>
+ <artifactId>js</artifactId>
+ <version>1.6R6-candidate2</version>
+ </dependency>
+ </dependencies>
+</project>
\ No newline at end of file
Added: trunk/openutils-testing-testng-dwr/src/main/java/it/openutils/testing/testng/dwr/DwrTestCase.java
===================================================================
--- trunk/openutils-testing-testng-dwr/src/main/java/it/openutils/testing/testng/dwr/DwrTestCase.java (rev 0)
+++ trunk/openutils-testing-testng-dwr/src/main/java/it/openutils/testing/testng/dwr/DwrTestCase.java 2007-07-12 17:17:48 UTC (rev 363)
@@ -0,0 +1,301 @@
+package it.openutils.testing.testng.dwr;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.mozilla.javascript.Context;
+import org.mozilla.javascript.Scriptable;
+import org.mozilla.javascript.ScriptableObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import org.xml.sax.SAXException;
+
+import com.meterware.httpunit.GetMethodWebRequest;
+import com.meterware.httpunit.WebResponse;
+import com.meterware.servletunit.ServletRunner;
+import com.meterware.servletunit.ServletUnitClient;
+
+@Test
+public class DwrTestCase
+{
+
+ private static Logger log = LoggerFactory.getLogger(DwrTestCase.class);
+
+ public static final String SERVLET_UNIT_CLIENT = "SERVLET_UNIT_CLIENT";
+
+ private Context context;
+
+ private Scriptable scope;
+
+ private ServletUnitClient servletUnitClient;
+
+ private ServletRunner servletRunner;
+
+ private String webXmlLocation;
+
+ private String contextPath = "/webapp";
+
+ private List<String> jsLibraries = new ArrayList<String>();
+
+ protected void setAbsoluteWebXmlLocation(String absoluteWebXmlLocation)
+ {
+ this.webXmlLocation = absoluteWebXmlLocation;
+ }
+
+ protected void setContextPath(String contextPath)
+ {
+ this.contextPath = contextPath;
+ if (this.contextPath != null)
+ {
+ this.contextPath = this.contextPath.replace('\\', '/');
+ if (!this.contextPath.startsWith("/"))
+ {
+ this.contextPath = "/" + this.contextPath;
+ }
+ }
+ }
+
+ public void addJsLibrary(String library)
+ {
+ jsLibraries.add(library);
+ }
+
+ @BeforeClass
+ protected void setUpServer() throws Exception
+ {
+ // run httpunit servlet engine
+ servletRunner = new ServletRunner(new File(webXmlLocation), contextPath);
+ }
+
+ @BeforeMethod
+ protected void setUp() throws Exception
+ {
+ servletUnitClient = servletRunner.newClient();
+
+ // init scripting context
+ context = Context.enter();
+ context.setLanguageVersion(Context.VERSION_1_6);
+
+ // store servletUnitClient in context
+ context.putThreadLocal(DwrTestCase.SERVLET_UNIT_CLIENT, servletUnitClient);
+
+ // load js support for window and document
+ String jsWebEnvironment = "";
+ InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("webEnv.js");
+ byte[] buffer = new byte[1024];
+ int read = 0;
+ int length = 1024;
+ while ((read = is.read(buffer, 0, length)) > 0)
+ {
+ jsWebEnvironment += new String(buffer, 0, read);
+ }
+ is.close();
+
+ //
+ scope = context.initStandardObjects();
+ ScriptableObject.defineClass(scope, XMLHttpRequest.class);
+ // ScriptableObject.defineClass(scope, JsJUnitAssert.class);
+ context.evaluateString(scope, jsWebEnvironment, "webEnv.js", -1, null);
+ scope.put("Test", scope, this);
+
+ // add javascript
+ for (String library : jsLibraries)
+ {
+ if (loadLibraryFromLocalServer(library))
+ {
+ log.info("Loaded library from local server: " + library);
+ }
+ else if (loadLibraryFromRemoteServer(library))
+ {
+ log.info("Loaded library from remote server: " + library);
+ }
+ else if (loadLibraryFromClasspath(library))
+ {
+ log.info("Loaded library from classpath: " + library);
+ }
+ else if (loadLibraryFromFileSystem(library))
+ {
+ log.info("Loaded library from filesystem: " + library);
+ }
+ else
+ {
+ log.error("Can't load library " + library);
+ throw new FileNotFoundException(library);
+ }
+ }
+ }
+
+ private boolean loadLibraryFromLocalServer(String library) throws MalformedURLException, SAXException, IOException,
+ URISyntaxException
+ {
+ if (!library.startsWith("http://localhost/"))
+ {
+ return false;
+ }
+
+ WebResponse response = servletUnitClient.getResponse(new GetMethodWebRequest(library));
+ if (response == null)
+ {
+ return false;
+ }
+ URI uri = new URI(library);
+ context.evaluateString(scope, response.getText(), uri.getPath(), -1, null);
+
+ return true;
+ }
+
+ private boolean loadLibraryFromRemoteServer(String library) throws MalformedURLException, SAXException,
+ IOException, URISyntaxException
+ {
+ if (!library.startsWith("http://"))
+ {
+ return false;
+ }
+
+ URL url = new URL(library);
+
+ // connect to library
+ HttpURLConnection connection = (HttpURLConnection) url.openConnection();
+ connection.setRequestMethod("GET");
+ connection.setDoInput(true);
+ connection.connect();
+
+ // get response
+ InputStream is = connection.getInputStream();
+ StringBuffer sb = new StringBuffer();
+
+ int i;
+ while ((i = is.read()) != -1)
+ {
+ sb.append((char) i);
+ }
+ is.close();
+ connection.disconnect();
+
+ // put response in context
+ context.evaluateString(scope, sb.toString(), url.getPath(), -1, null);
+
+ return true;
+ }
+
+ private boolean loadLibraryFromClasspath(String library) throws IOException
+ {
+ String js = loadFileFromClassPath(library);
+
+ if (js == null)
+ {
+ return false;
+ }
+
+ context.evaluateString(scope, js, library, -1, null);
+
+ return true;
+ }
+
+ private String loadFileFromClassPath(String file) throws IOException
+ {
+ InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(file);
+ if (is == null)
+ {
+ return null;
+ }
+ byte[] buffer = new byte[1024];
+ int read = 0;
+ String js = "";
+ while ((read = is.read(buffer, 0, buffer.length)) > 0)
+ {
+ js += new String(buffer, 0, read);
+ }
+ is.close();
+
+ return js;
+ }
+
+ private boolean loadLibraryFromFileSystem(String library) throws FileNotFoundException, IOException
+ {
+ String js = loadFileFromFileSystem(library);
+
+ if (js == null)
+ {
+ return false;
+ }
+
+ context.evaluateString(scope, js, library, -1, null);
+
+ return true;
+ }
+
+ private String loadFileFromFileSystem(String file) throws FileNotFoundException, IOException
+ {
+ File f = new File(file);
+ if (!f.exists())
+ {
+ return null;
+ }
+
+ InputStream is = new FileInputStream(f);
+ if (is == null)
+ {
+ return null;
+ }
+ byte[] buffer = new byte[1024];
+ int read = 0;
+ String js = "";
+ while ((read = is.read(buffer, 0, buffer.length)) > 0)
+ {
+ js += new String(buffer, 0, read);
+ }
+ is.close();
+
+ return js;
+ }
+
+ @AfterMethod
+ protected void tearDown() throws Exception
+ {
+ scope = null;
+ Context.exit();
+ }
+
+ @AfterClass
+ protected void tearDownServer() throws Exception
+ {
+ servletRunner.shutDown();
+ }
+
+ public void runScript(String script)
+ {
+ context.evaluateString(scope, script, "inline", -1, null);
+ }
+
+ public void runScriptFile(String scriptFile) throws FileNotFoundException, IOException
+ {
+ String js = loadFileFromClassPath(scriptFile);
+ if (js == null)
+ {
+ js = loadFileFromFileSystem(scriptFile);
+ if (js == null)
+ {
+ throw new FileNotFoundException(scriptFile);
+ }
+ }
+
+ context.evaluateString(scope, js, scriptFile, -1, null);
+ }
+
+}
Added: trunk/openutils-testing-testng-dwr/src/main/java/it/openutils/testing/testng/dwr/JsException.java
===================================================================
--- trunk/openutils-testing-testng-dwr/src/main/java/it/openutils/testing/testng/dwr/JsException.java (rev 0)
+++ trunk/openutils-testing-testng-dwr/src/main/java/it/openutils/testing/testng/dwr/JsException.java 2007-07-12 17:17:48 UTC (rev 363)
@@ -0,0 +1,23 @@
+package it.openutils.testing.testng.dwr;
+
+import org.mozilla.javascript.ScriptableObject;
+
+
+/**
+ * @author mmolaschi
+ * @version $Id: $
+ */
+public class JsException extends ScriptableObject
+{
+
+ @Override
+ public String getClassName()
+ {
+ return "Exception";
+ }
+
+ public void js_constructor(String message) throws Exception
+ {
+ throw new Exception(message);
+ }
+}
Added: trunk/openutils-testing-testng-dwr/src/main/java/it/openutils/testing/testng/dwr/XMLHttpRequest.java
===================================================================
--- trunk/openutils-testing-testng-dwr/src/main/java/it/openutils/testing/testng/dwr/XMLHttpRequest.java (rev 0)
+++ trunk/openutils-testing-testng-dwr/src/main/java/it/openutils/testing/testng/dwr/XMLHttpRequest.java 2007-07-12 17:17:48 UTC (rev 363)
@@ -0,0 +1,479 @@
+//=============================================================================
+//Change History:
+//Date UserId Defect Description
+//----------------------------------------------------------------------------
+//07/02/05 ant ??? Initial version.
+//09/02/05 ant Support both HTTP GET and POST
+//14/02/05 ant Fix call backs in functions
+//20/02/05 ant Support HTTP HEAD
+//28/02/05 ant HTTP basic authentication support
+//
+package it.openutils.testing.testng.dwr;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStreamWriter;
+import java.io.StringReader;
+import java.net.Authenticator;
+import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
+import java.net.PasswordAuthentication;
+import java.net.URL;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import org.mozilla.javascript.Context;
+import org.mozilla.javascript.NativeFunction;
+import org.mozilla.javascript.Scriptable;
+import org.mozilla.javascript.ScriptableObject;
+import org.w3c.dom.Document;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+
+import com.meterware.httpunit.GetMethodWebRequest;
+import com.meterware.httpunit.PostMethodWebRequest;
+import com.meterware.httpunit.WebRequest;
+import com.meterware.httpunit.WebResponse;
+import com.meterware.servletunit.ServletUnitClient;
+import com.sun.org.apache.xerces.internal.parsers.DOMParser;
+
+
+/**
+ * XMLHttpRequest simulates the Mozilla XMLHttpRequest. Add this class to the Rhino classpath and then define to Rhino
+ * with <code>defineClass('xmlhttp.XMLHttpRequest');</code>
+ * @author <a href="mailto:ant...@uk...">Ant Elder </a>
+ */
+public class XMLHttpRequest extends ScriptableObject
+{
+
+ private String url;
+
+ private String httpMethod;
+
+ private int httpStatus;
+
+ private String httpStatusText;
+
+ private Map requestHeaders;
+
+ private String userName;
+
+ private String password;
+
+ private String responseText;
+
+ private Document responseXML;
+
+ private int readyState;
+
+ private NativeFunction readyStateChangeFunction;
+
+ private boolean asyncFlag;
+
+ private Thread asyncThread;
+
+ private ServletUnitClient suc;
+
+ private WebRequest request;
+
+ private WebResponse response;
+
+ private boolean localRequest = false;
+
+ private HttpURLConnection connection;
+
+ public XMLHttpRequest()
+ {
+ }
+
+ public void jsConstructor()
+ {
+ suc = (ServletUnitClient) Context.getCurrentContext().getThreadLocal(DwrTestCase.SERVLET_UNIT_CLIENT);
+ }
+
+ @Override
+ public String getClassName()
+ {
+ return "XMLHttpRequest";
+ }
+
+ public void jsFunction_setRequestHeader(String headerName, String value)
+ {
+ if (readyState > 1)
+ {
+ throw new IllegalStateException("request already in progress");
+ }
+
+ if (requestHeaders == null)
+ {
+ requestHeaders = new HashMap();
+ }
+
+ requestHeaders.put(headerName, value);
+ }
+
+ public Map<String, String[]> jsFunction_getAllResponseHeaders()
+ {
+ if (readyState < 3)
+ {
+ throw new IllegalStateException("must call send before getting response headers");
+ }
+ Map<String, String[]> map = new HashMap<String, String[]>();
+ for (String name : response.getHeaderFieldNames())
+ {
+ map.put(name.toLowerCase(), response.getHeaderFields(name));
+ }
+ return map;
+ }
+
+ public String jsFunction_getResponseHeader(String headerName)
+ {
+ String theValue = "";
+ String theValues[] = jsFunction_getAllResponseHeaders().get(headerName.toLowerCase());
+ for (String value : theValues)
+ {
+ theValue = ((theValue.length() > 0) ? " " : "") + value;
+ }
+ return theValue;
+ }
+
+ public void jsFunction_open(String httpMethod, String url, boolean asyncFlag, String userName, String password)
+ {
+
+ if (readyState != 0)
+ {
+ throw new IllegalStateException("already open");
+ }
+
+ this.httpMethod = httpMethod;
+
+ this.url = url;
+
+ if (!this.url.startsWith("http://"))
+ {
+ this.url = "http://localhost" + ((this.url.startsWith("/")) ? "" : "/") + this.url;
+ }
+
+ if (this.url.startsWith("http://localhost/"))
+ {
+ this.localRequest = true;
+ }
+ else
+ {
+ this.localRequest = false;
+ }
+
+ this.asyncFlag = asyncFlag;
+
+ if ("undefined".equals(userName) || "".equals(userName))
+ {
+ this.userName = null;
+ }
+ else
+ {
+ this.userName = userName;
+ }
+ if ("undefined".equals(password) || "".equals(password))
+ {
+ this.password = null;
+ }
+ else
+ {
+ this.password = password;
+ }
+ if (this.userName != null)
+ {
+ setAuthenticator();
+ }
+
+ setReadyState(1);
+ }
+
+ private void setAuthenticator()
+ {
+ Authenticator.setDefault(new Authenticator()
+ {
+
+ @Override
+ protected PasswordAuthentication getPasswordAuthentication()
+ {
+ return new PasswordAuthentication(userName, password.toCharArray());
+ }
+ });
+ }
+
+ public void jsFunction_send(Object o) throws SAXException, MalformedURLException, IOException
+ {
+ final String content = (o == null) ? "" : o.toString();
+ /*
+ * if (asyncFlag) { Runnable r = new Runnable() {
+ *
+ * public void run() { try { doSend(content); } catch (SAXException ex) { throw new
+ * NestableRuntimeException(ex); } } }; this.asyncThread = new Thread(r); asyncThread.start(); } else
+ */
+ {
+ doSend(content);
+ }
+ }
+
+ public void jsFunction_abort()
+ {
+ if (asyncThread != null)
+ {
+ asyncThread.interrupt();
+ }
+ }
+
+ /**
+ * @return Returns the readyState.
+ */
+ public int jsGet_readyState()
+ {
+ return readyState;
+ }
+
+ /**
+ * @return Returns the responseText.
+ */
+ public String jsGet_responseText()
+ {
+ if (readyState < 2)
+ {
+ throw new IllegalStateException("request not yet sent");
+ }
+ return responseText;
+ }
+
+ /**
+ * @return Returns the responseXML as a DOM Document.
+ */
+ public Document jsGet_responseXML()
+ {
+ if (responseXML == null && responseText != null)
+ {
+ convertResponse2DOM();
+ }
+ return responseXML;
+ }
+
+ private void convertResponse2DOM()
+ {
+ try
+ {
+
+ DOMParser parser = new DOMParser();
+ StringReader sr = new StringReader(jsGet_responseText());
+ parser.parse(new InputSource(sr));
+ this.responseXML = parser.getDocument();
+
+ }
+ catch (SAXException e)
+ {
+ throw new RuntimeException("ex: " + e, e);
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException("ex: " + e, e);
+ }
+ }
+
+ /**
+ * @return Returns the htto status.
+ */
+ public int jsGet_status()
+ {
+ return httpStatus;
+ }
+
+ /**
+ * @return Returns the http status text.
+ */
+ public String jsGet_statusText()
+ {
+ return httpStatusText;
+ }
+
+ /**
+ * @return Returns the onreadystatechange.
+ */
+ public Object jsGet_onreadystatechange()
+ {
+ return readyStateChangeFunction;
+ }
+
+ /**
+ * @param onreadystatechange The onreadystatechange to set.
+ */
+ public void jsSet_onreadystatechange(NativeFunction function)
+ {
+ readyStateChangeFunction = function;
+ }
+
+ private void doSend(String content) throws SAXException, MalformedURLException, IOException
+ {
+
+ connect(content);
+
+ setRequestHeaders();
+
+ sendRequest(content);
+
+ if ("POST".equals(this.httpMethod) || "GET".equals(this.httpMethod))
+ {
+ readResponse();
+ }
+
+ setReadyState(4);
+
+ }
+
+ private void connect(String content) throws MalformedURLException, IOException
+ {
+ if (httpMethod == "POST")
+ {
+ if (this.localRequest)
+ {
+ ByteArrayInputStream bis = new ByteArrayInputStream(content.getBytes());
+ request = new PostMethodWebRequest(url, bis, null);
+ }
+ else
+ {
+ URL url = new URL(this.url);
+ connection = (HttpURLConnection) url.openConnection();
+ connection.setDoInput(true);
+ connection.setDoOutput(true);
+ connection.setRequestMethod("POST");
+ }
+ }
+ else
+ {
+ if (this.localRequest)
+ {
+ request = new GetMethodWebRequest("http://localhost/" + url);
+ }
+ else
+ {
+ URL url = new URL(this.url);
+ connection = (HttpURLConnection) url.openConnection();
+ connection.setDoInput(true);
+ connection.setRequestMethod("GET");
+ }
+
+ }
+ }
+
+ private void setRequestHeaders()
+ {
+ if (this.requestHeaders != null)
+ {
+ for (Iterator i = requestHeaders.keySet().iterator(); i.hasNext();)
+ {
+ String header = (String) i.next();
+ String value = (String) requestHeaders.get(header);
+ if (this.localRequest)
+ {
+ request.setHeaderField(header, value);
+ }
+ else
+ {
+ connection.setRequestProperty(header, value);
+ }
+ }
+ }
+ }
+
+ private void sendRequest(String content) throws SAXException
+ {
+ try
+ {
+ if ("POST".equals(this.httpMethod) || content.length() > 0)
+ {
+ if (this.localRequest)
+ {
+ response = suc.getResponse(request);
+ }
+ else
+ {
+ OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "ASCII");
+ out.write(content);
+ out.flush();
+ out.close();
+
+ }
+ }
+
+ if (this.localRequest)
+ {
+ httpStatus = response.getResponseCode();
+ httpStatusText = response.getResponseMessage();
+ }
+ else
+ {
+ httpStatus = connection.getResponseCode();
+ httpStatusText = connection.getResponseMessage();
+ }
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException("IOException: " + e, e);
+ }
+
+ setReadyState(2);
+ }
+
+ private void readResponse()
+ {
+ try
+ {
+ if (this.localRequest)
+ {
+ this.responseText = response.getText();
+ }
+ else
+ {
+ InputStream is = connection.getInputStream();
+ StringBuffer sb = new StringBuffer();
+
+ setReadyState(3);
+
+ int i;
+ while ((i = is.read()) != -1)
+ {
+ sb.append((char) i);
+ }
+ is.close();
+
+ this.responseText = sb.toString();
+ }
+ }
+ catch (IOException e)
+ {
+ throw new RuntimeException("IOException: " + e, e);
+ }
+ }
+
+ private void setReadyState(int state)
+ {
+ this.readyState = state;
+ callOnreadyStateChange();
+ }
+
+ private void callOnreadyStateChange()
+ {
+ if (readyStateChangeFunction != null)
+ {
+ Context cx = Context.enter();
+ try
+ {
+ Scriptable scope = cx.initStandardObjects();
+ readyStateChangeFunction.call(cx, scope, this, new Object[]{});
+ }
+ finally
+ {
+ Context.exit();
+ }
+ }
+ }
+}
\ No newline at end of file
Added: trunk/openutils-testing-testng-dwr/src/main/resources/webEnv.js
===================================================================
--- trunk/openutils-testing-testng-dwr/src/main/resources/webEnv.js (rev 0)
+++ trunk/openutils-testing-testng-dwr/src/main/resources/webEnv.js 2007-07-12 17:17:48 UTC (rev 363)
@@ -0,0 +1,596 @@
+/*
+ * Simulated browser environment for Rhino
+ * By John Resig <http://ejohn.org/>
+ * Copyright 2007 John Resig, under the MIT License
+ */
+
+// The window Object
+var window = this;
+
+(function(){
+
+ // Browser Navigator
+
+ window.navigator = {
+ get userAgent(){
+ return "Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3";
+ }
+ };
+
+ var curLocation = (new java.io.File("./")).toURL();
+
+ window.__defineSetter__("location", function(url){
+ var xhr = new XMLHttpRequest();
+ xhr.open("GET", url);
+ xhr.onreadystatechange = function(){
+ curLocation = new java.net.URL( curLocation, url );
+ window.document = xhr.responseXML;
+
+ var event = document.createEvent();
+ event.initEvent("load");
+ window.dispatchEvent( event );
+ };
+ xhr.send();
+ });
+
+ window.__defineGetter__("location", function(url){
+ return {
+ get pathname(){
+ if (curLocation.toString().indexOf('?') >= 0)
+ {
+ return curLocation.toString().substring(0, curLocation.toString().indexOf('?'));
+ }
+ return curLocation.toString();
+ },
+ get search(){
+ if (curLocation.toString().indexOf('?') >= 0)
+ {
+ return curLocation.toString().substring(curLocation.toString().indexOf('?') + 1, curLocation.toString().length());
+ }
+ return "";
+ },
+ get protocol(){
+ return curLocation.getProtocol() + ":";
+ },
+ get href(){
+ return curLocation.toString();
+ },
+ toString: function(){
+ return this.href;
+ }
+ };
+ });
+
+ // Timers
+
+ var timers = [];
+
+ window.setTimeout = function(fn, time){
+ var num;
+ return num = setInterval(function(){
+ fn();
+ clearInterval(num);
+ }, time);
+ };
+
+ window.setInterval = function(fn, time){
+ var num = timers.length;
+
+ timers[num] = new java.lang.Thread(new java.lang.Runnable({
+ run: function(){
+ while (true){
+ java.lang.Thread.currentThread().sleep(time);
+ fn();
+ }
+ }
+ }));
+
+ timers[num].start();
+
+ return num;
+ };
+
+ window.clearInterval = function(num){
+ if ( timers[num] ) {
+ timers[num].stop();
+ delete timers[num];
+ }
+ };
+
+ // Window Events
+
+ var events = [{}];
+
+ window.addEventListener = function(type, fn){
+ if ( !this.uuid || this == window ) {
+ this.uuid = events.length;
+ events[this.uuid] = {};
+ }
+
+ if ( !events[this.uuid][type] )
+ events[this.uuid][type] = [];
+
+ if ( events[this.uuid][type].indexOf( fn ) < 0 )
+ events[this.uuid][type].push( fn );
+ };
+
+ window.removeEventListener = function(type, fn){
+ if ( !this.uuid || this == window ) {
+ this.uuid = events.length;
+ events[this.uuid] = {};
+ }
+
+ if ( !events[this.uuid][type] )
+ events[this.uuid][type] = [];
+
+ events[this.uuid][type] =
+ events[this.uuid][type].filter(function(f){
+ return f != fn;
+ });
+ };
+
+ window.dispatchEvent = function(event){
+ if ( event.type ) {
+ if ( this.uuid && events[this.uuid][event.type] ) {
+ var self = this;
+
+ events[this.uuid][event.type].forEach(function(fn){
+ fn.call( self, event );
+ });
+ }
+
+ if ( this["on" + event.type] )
+ this["on" + event.type].call( self, event );
+ }
+ };
+
+ // DOM Document
+
+ window.DOMDocument = function(file){
+ this._file = file;
+ this._dom = Packages.javax.xml.parsers.
+ DocumentBuilderFactory.newInstance()
+ .newDocumentBuilder().parse(file);
+
+ if ( !obj_nodes.containsKey( this._dom ) )
+ obj_nodes.put( this._dom, this );
+ };
+
+ DOMDocument.prototype = {
+ createTextNode: function(text){
+ return makeNode( this._dom.createTextNode(
+ text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">")) );
+ },
+ createElement: function(name){
+ return makeNode( this._dom.createElement(name.toLowerCase()) );
+ },
+ getElementsByTagName: function(name){
+ return new DOMNodeList( this._dom.getElementsByTagName(
+ name.toLowerCase()) );
+ },
+ getElementById: function(id){
+ var elems = this._dom.getElementsByTagName("*");
+
+ for ( var i = 0; i < elems.length; i++ ) {
+ var elem = elems.item(i);
+ if ( elem.getAttribute("id") == id )
+ return makeNode(elem);
+ }
+
+ return null;
+ },
+ get body(){
+ return this.getElementsByTagName("body")[0];
+ },
+ get documentElement(){
+ return makeNode( this._dom.getDocumentElement() );
+ },
+ get ownerDocument(){
+ return null;
+ },
+ addEventListener: window.addEventListener,
+ removeEventListener: window.removeEventListener,
+ dispatchEvent: window.dispatchEvent,
+ get nodeName() {
+ return "#document";
+ },
+ importNode: function(node, deep){
+ return makeNode( this._dom.importNode(node._dom, deep) );
+ },
+ toString: function(){
+ return "Document" + (typeof this._file == "string" ?
+ ": " + this._file : "");
+ },
+ get innerHTML(){
+ return this.documentElement.outerHTML;
+ },
+
+ get defaultView(){
+ return {
+ getComputedStyle: function(elem){
+ return {
+ getPropertyValue: function(prop){
+ prop = prop.replace(/\-(\w)/g,function(m,c){
+ return c.toUpperCase();
+ });
+ var val = elem.style[prop];
+
+ if ( prop == "opacity" && val == "" )
+ val = "1";
+
+ return val;
+ }
+ };
+ }
+ };
+ },
+
+ createEvent: function(){
+ return {
+ type: "",
+ initEvent: function(type){
+ this.type = type;
+ }
+ };
+ }
+ };
+
+ function getDocument(node){
+ return obj_nodes.get(node);
+ }
+
+ // DOM NodeList
+
+ window.DOMNodeList = function(list){
+ this._dom = list;
+ this.length = list.getLength();
+
+ for ( var i = 0; i < this.length; i++ ) {
+ var node = list.item(i);
+ this[i] = makeNode( node );
+ }
+ };
+
+ DOMNodeList.prototype = {
+ toString: function(){
+ return "[ " +
+ Array.prototype.join.call( this, ", " ) + " ]";
+ },
+ get outerHTML(){
+ return Array.prototype.map.call(
+ this, function(node){return node.outerHTML;}).join('');
+ }
+ };
+
+ // DOM Node
+
+ window.DOMNode = function(node){
+ this._dom = node;
+ };
+
+ DOMNode.prototype = {
+ get nodeType(){
+ return this._dom.getNodeType();
+ },
+ get nodeValue(){
+ return this._dom.getNodeValue();
+ },
+ get nodeName() {
+ return this._dom.getNodeName();
+ },
+ cloneNode: function(deep){
+ return makeNode( this._dom.cloneNode(deep) );
+ },
+ get ownerDocument(){
+ return getDocument( this._dom.ownerDocument );
+ },
+ get documentElement(){
+ return makeNode( this._dom.documentElement );
+ },
+ get parentNode() {
+ return makeNode( this._dom.getParentNode() );
+ },
+ get nextSibling() {
+ return makeNode( this._dom.getNextSibling() );
+ },
+ get previousSibling() {
+ return makeNode( this._dom.getPreviousSibling() );
+ },
+ toString: function(){
+ return '"' + this.nodeValue + '"';
+ },
+ get outerHTML(){
+ return this.nodeValue;
+ }
+ };
+
+ // DOM Element
+
+ window.DOMElement = function(elem){
+ this._dom = elem;
+ this.style = {
+ get opacity(){ return this._opacity; },
+ set opacity(val){ this._opacity = val + ""; }
+ };
+
+ // Load CSS info
+ var styles = (this.getAttribute("style") || "").split(/\s*;\s*/);
+
+ for ( var i = 0; i < styles.length; i++ ) {
+ var style = styles[i].split(/\s*:\s*/);
+ if ( style.length == 2 )
+ this.style[ style[0] ] = style[1];
+ }
+ };
+
+ DOMElement.prototype = extend( new DOMNode(), {
+ get nodeName(){
+ return this.tagName.toUpperCase();
+ },
+ get tagName(){
+ return this._dom.getTagName();
+ },
+ toString: function(){
+ return "<" + this.tagName + (this.id ? "#" + this.id : "" ) + ">";
+ },
+ get outerHTML(){
+ var ret = "<" + this.tagName, attr = this.attributes;
+
+ for ( var i in attr )
+ ret += " " + i + "='" + attr[i] + "'";
+
+ if ( this.childNodes.length || this.nodeName == "SCRIPT" )
+ ret += ">" + this.childNodes.outerHTML +
+ "</" + this.tagName + ">";
+ else
+ ret += "/>";
+
+ return ret;
+ },
+
+ get attributes(){
+ var attr = {}, attrs = this._dom.getAttributes();
+
+ for ( var i = 0; i < attrs.getLength(); i++ )
+ attr[ attrs.item(i).nodeName ] = attrs.item(i).nodeValue;
+
+ return attr;
+ },
+
+ get innerHTML(){
+ return this.childNodes.outerHTML;
+ },
+ set innerHTML(html){
+ html = html.replace(/<\/?([A-Z]+)/g, function(m){
+ return m.toLowerCase();
+ });
+
+ var nodes = this.ownerDocument.importNode(
+ new DOMDocument( new java.io.ByteArrayInputStream(
+ (new java.lang.String("<wrap>" + html + "</wrap>"))
+ .getBytes("UTF8"))).documentElement, true).childNodes;
+
+ while (this.firstChild)
+ this.removeChild( this.firstChild );
+
+ for ( var i = 0; i < nodes.length; i++ )
+ this.appendChild( nodes[i] );
+ },
+
+ get textContent(){
+ return nav(this.childNodes);
+
+ function nav(nodes){
+ var str = "";
+ for ( var i = 0; i < nodes.length; i++ )
+ if ( nodes[i].nodeType == 3 )
+ str += nodes[i].nodeValue;
+ else if ( nodes[i].nodeType == 1 )
+ str += nav(nodes[i].childNodes);
+ return str;
+ }
+ },
+ set textContent(text){
+ while (this.firstChild)
+ this.removeChild( this.firstChild );
+ this.appendChild( this.ownerDocument.createTextNode(text));
+ },
+
+ style: {},
+ clientHeight: 0,
+ clientWidth: 0,
+ offsetHeight: 0,
+ offsetWidth: 0,
+
+ get disabled() {
+ var val = this.getAttribute("disabled");
+ return val != "false" && !!val;
+ },
+ set disabled(val) { return this.setAttribute("disabled",val); },
+
+ get checked() {
+ var val = this.getAttribute("checked");
+ return val != "false" && !!val;
+ },
+ set checked(val) { return this.setAttribute("checked",val); },
+
+ get selected() {
+ if ( !this._selectDone ) {
+ this._selectDone = true;
+
+ if ( this.nodeName == "OPTION" && !this.parentNode.getAttribute("multiple") ) {
+ var opt = this.parentNode.getElementsByTagName("option");
+
+ if ( this == opt[0] ) {
+ var select = true;
+
+ for ( var i = 1; i < opt.length; i++ )
+ if ( opt[i].selected ) {
+ select = false;
+ break;
+ }
+
+ if ( select )
+ this.selected = true;
+ }
+ }
+ }
+
+ var val = this.getAttribute("selected");
+ return val != "false" && !!val;
+ },
+ set selected(val) { return this.setAttribute("selected",val); },
+
+ get className() { return this.getAttribute("class") || ""; },
+ set className(val) {
+ return this.setAttribute("class",
+ val.replace(/(^\s*|\s*$)/g,""));
+ },
+
+ get type() { return this.getAttribute("type") || ""; },
+ set type(val) { return this.setAttribute("type",val); },
+
+ get value() { return this.getAttribute("value") || ""; },
+ set value(val) { return this.setAttribute("value",val); },
+
+ get src() { return this.getAttribute("src") || ""; },
+ set src(val) { return this.setAttribute("src",val); },
+
+ get id() { return this.getAttribute("id") || ""; },
+ set id(val) { return this.setAttribute("id",val); },
+
+ getAttribute: function(name){
+ return this._dom.hasAttribute(name) ?
+ new String( this._dom.getAttribute(name) ) :
+ null;
+ },
+ setAttribute: function(name,value){
+ this._dom.setAttribute(name,value);
+ },
+ removeAttribute: function(name){
+ this._dom.removeAttribute(name);
+ },
+
+ get childNodes(){
+ return new DOMNodeList( this._dom.getChildNodes() );
+ },
+ get firstChild(){
+ return makeNode( this._dom.getFirstChild() );
+ },
+ get lastChild(){
+ return makeNode( this._dom.getLastChild() );
+ },
+ appendChild: function(node){
+ this._dom.appendChild( node._dom );
+ },
+ insertBefore: function(node,before){
+ this._dom.insertBefore( node._dom, before ? before._dom : before );
+ },
+ removeChild: function(node){
+ this._dom.removeChild( node._dom );
+ },
+
+ getElementsByTagName: DOMDocument.prototype.getElementsByTagName,
+
+ addEventListener: window.addEventListener,
+ removeEventListener: window.removeEventListener,
+ dispatchEvent: window.dispatchEvent,
+
+ click: function(){
+ var event = document.createEvent();
+ event.initEvent("click");
+ this.dispatchEvent(event);
+ },
+ submit: function(){
+ var event = document.createEvent();
+ event.initEvent("submit");
+ this.dispatchEvent(event);
+ },
+ focus: function(){
+ var event = document.createEvent();
+ event.initEvent("focus");
+ this.dispatchEvent(event);
+ },
+ blur: function(){
+ var event = document.createEvent();
+ event.initEvent("blur");
+ this.dispatchEvent(event);
+ },
+ get elements(){
+ return this.getElementsByTagName("*");
+ },
+ get contentWindow(){
+ return this.nodeName == "IFRAME" ? {
+ document: this.contentDocument
+ } : null;
+ },
+ get contentDocument(){
+ if ( this.nodeName == "IFRAME" ) {
+ if ( !this._doc )
+ this._doc = new DOMDocument(
+ new java.io.ByteArrayInputStream((new java.lang.String(
+ "<html><head><title></title></head><body></body></html>"))
+ .getBytes("UTF8")));
+ return this._doc;
+ } else
+ return null;
+ }
+ });
+
+ // Helper method for extending one object with another
+
+ function extend(a,b) {
+ for ( var i in b ) {
+ var g = b.__lookupGetter__(i), s = b.__lookupSetter__(i);
+
+ if ( g || s ) {
+ if ( g )
+ a.__defineGetter__(i, g);
+ if ( s )
+ a.__defineSetter__(i, s);
+ } else
+ a[i] = b[i];
+ }
+ return a;
+ }
+
+ // Helper method for generating the right
+ // DOM objects based upon the type
+
+ var obj_nodes = new java.util.HashMap();
+
+ function makeNode(node){
+ if ( node ) {
+ if ( !obj_nodes.containsKey( node ) )
+ obj_nodes.put( node, node.getNodeType() ==
+ Packages.org.w3c.dom.Node.ELEMENT_NODE ?
+ new DOMElement( node ) : new DOMNode( node ) );
+
+ return obj_nodes.get(node);
+ } else
+ return null;
+ }
+
+})();
+
+var document = {
+
+ location: window.location,
+ cookie: '',
+
+ getElementById: function(id){
+ if (id == "dwr-debug"){
+ var dbEl = {
+ get innerHTML(){
+ return "";
+ },
+ set innerHTML(value){
+ java.lang.System.out.print(value.replace("<br>", "\n"));
+ }
+ }
+ return dbEl;
+ }
+ return null;
+ }
+
+}
Modified: trunk/pom.xml
===================================================================
--- trunk/pom.xml 2007-07-12 15:30:05 UTC (rev 362)
+++ trunk/pom.xml 2007-07-12 17:17:48 UTC (rev 363)
@@ -161,6 +161,7 @@
<module>openutils-usermanagement-dataobjects</module>
<module>openutils-usermanagement</module>
<module>openutils-testing-testng</module>
+ <module>openutils-testing-testng-dwr</module>
<module>openutils-testing-junit</module>
<module>openutils-testing-junit-dwr</module>
<module>openutils-web</module>
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|