httpunit-commit Mailing List for httpunit (Page 2)
Brought to you by:
russgold
You can subscribe to this list here.
| 2000 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
(5) |
Sep
(31) |
Oct
(39) |
Nov
(18) |
Dec
(6) |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2001 |
Jan
(8) |
Feb
(5) |
Mar
(8) |
Apr
(25) |
May
(20) |
Jun
(23) |
Jul
(28) |
Aug
(10) |
Sep
(3) |
Oct
(32) |
Nov
(61) |
Dec
(24) |
| 2002 |
Jan
(50) |
Feb
(34) |
Mar
(35) |
Apr
(3) |
May
(25) |
Jun
(25) |
Jul
(30) |
Aug
(146) |
Sep
(49) |
Oct
(156) |
Nov
(121) |
Dec
(54) |
| 2003 |
Jan
(12) |
Feb
(79) |
Mar
(88) |
Apr
(26) |
May
(67) |
Jun
(29) |
Jul
(8) |
Aug
(16) |
Sep
(20) |
Oct
(17) |
Nov
|
Dec
(5) |
| 2004 |
Jan
|
Feb
(40) |
Mar
(30) |
Apr
(5) |
May
|
Jun
(83) |
Jul
(34) |
Aug
(20) |
Sep
(44) |
Oct
(46) |
Nov
|
Dec
(14) |
| 2005 |
Jan
(4) |
Feb
|
Mar
(5) |
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
(4) |
Oct
|
Nov
|
Dec
(1) |
| 2006 |
Jan
|
Feb
|
Mar
(26) |
Apr
(8) |
May
(2) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
(5) |
Nov
|
Dec
|
| 2008 |
Jan
|
Feb
|
Mar
|
Apr
(36) |
May
(38) |
Jun
(1) |
Jul
(1) |
Aug
|
Sep
(4) |
Oct
|
Nov
(18) |
Dec
(4) |
| 2009 |
Jan
|
Feb
(2) |
Mar
(3) |
Apr
|
May
|
Jun
(2) |
Jul
|
Aug
(35) |
Sep
(1) |
Oct
|
Nov
|
Dec
(1) |
| 2010 |
Jan
|
Feb
|
Mar
|
Apr
|
May
(3) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
| 2011 |
Jan
(9) |
Feb
|
Mar
|
Apr
(1) |
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(1) |
| 2012 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
(21) |
Oct
(18) |
Nov
(1) |
Dec
|
|
From: <wol...@us...> - 2012-09-12 21:24:08
|
Revision: 1094
http://httpunit.svn.sourceforge.net/httpunit/?rev=1094&view=rev
Author: wolfgang_fahl
Date: 2012-09-12 21:24:01 +0000 (Wed, 12 Sep 2012)
Log Message:
-----------
fix BR 2946821 getDOM changes since 1.5.4
by max
Modified Paths:
--------------
trunk/httpunit/src/main/java/com/meterware/httpunit/dom/DocumentImpl.java
trunk/httpunit/src/main/java/com/meterware/httpunit/dom/HTMLDocumentImpl.java
trunk/httpunit/src/test/java/com/meterware/httpunit/XMLPageTest.java
Modified: trunk/httpunit/src/main/java/com/meterware/httpunit/dom/DocumentImpl.java
===================================================================
--- trunk/httpunit/src/main/java/com/meterware/httpunit/dom/DocumentImpl.java 2012-09-12 20:40:55 UTC (rev 1093)
+++ trunk/httpunit/src/main/java/com/meterware/httpunit/dom/DocumentImpl.java 2012-09-12 21:24:01 UTC (rev 1094)
@@ -30,7 +30,7 @@
**/
public class DocumentImpl extends NodeImpl implements Document {
- private Element _documentElement;
+ protected Element _documentElement;
static DocumentImpl createDocument() {
@@ -176,6 +176,11 @@
}
+ /**
+ * import the children
+ * @param original
+ * @param copy
+ */
void importChildren( Node original, Node copy ) {
NodeList children = original.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Modified: trunk/httpunit/src/main/java/com/meterware/httpunit/dom/HTMLDocumentImpl.java
===================================================================
--- trunk/httpunit/src/main/java/com/meterware/httpunit/dom/HTMLDocumentImpl.java 2012-09-12 20:40:55 UTC (rev 1093)
+++ trunk/httpunit/src/main/java/com/meterware/httpunit/dom/HTMLDocumentImpl.java 2012-09-12 21:24:01 UTC (rev 1094)
@@ -258,7 +258,11 @@
public Node cloneNode( boolean deep ) {
HTMLDocumentImpl copy = new HTMLDocumentImpl();
- if (deep) copy.importChildren( this, copy );
+
+ if (deep) {
+ copy.importChildren( this, copy );
+ copy._documentElement=copy.getHtmlElement();
+ }
return copy;
}
Modified: trunk/httpunit/src/test/java/com/meterware/httpunit/XMLPageTest.java
===================================================================
--- trunk/httpunit/src/test/java/com/meterware/httpunit/XMLPageTest.java 2012-09-12 20:40:55 UTC (rev 1093)
+++ trunk/httpunit/src/test/java/com/meterware/httpunit/XMLPageTest.java 2012-09-12 21:24:01 UTC (rev 1094)
@@ -20,11 +20,15 @@
*
*******************************************************************************************************************/
+import java.io.IOException;
import java.util.Iterator;
import org.junit.Test;
+import org.junit.Ignore;
+import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
+import org.xml.sax.SAXException;
import static org.junit.Assert.*;
@@ -52,7 +56,8 @@
*
* @throws Exception
*/
- public void xtestXMLisHTML() throws Exception {
+ @Ignore
+ public void testXMLisHTML() throws Exception {
String originalXml = "<?xml version=\"1.0\" ?><main><title>See me now</title></main>";
defineResource("SimplePage.xml", originalXml, "text/xml");
WebConversation wc = new WebConversation();
@@ -64,6 +69,24 @@
assertNotNull("we do have an root-element", simplePage.getDOM().getDocumentElement());
assertEquals("the actual root must be the root of our test-xml", simplePage.getDOM().getDocumentElement().getTagName(), "main");
}
+
+ /**
+ * test for BR 2946821
+ * @throws SAXException
+ * @throws IOException
+ */
+ @Test
+ public void testGetDocumentElement() throws IOException, SAXException {
+ String html="<html><body></body></html>";
+ defineResource("BR2946821.html",html,"text/html");
+ WebConversation wc = new WebConversation();
+ WebRequest request = new GetMethodWebRequest(getHostPath() + "/BR2946821.html");
+ WebResponse page = wc.getResponse(request);
+ assertTrue(page.isHTML());
+ Document doc = page.getDOM();
+ Element docElement = doc.getDocumentElement();
+ assertNotNull("There should be a root element",docElement);
+ }
@Test
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <wol...@us...> - 2012-09-12 20:41:01
|
Revision: 1093
http://httpunit.svn.sourceforge.net/httpunit/?rev=1093&view=rev
Author: wolfgang_fahl
Date: 2012-09-12 20:40:55 +0000 (Wed, 12 Sep 2012)
Log Message:
-----------
fixes BR 2883515 noscript tag parsing incorrect
by Matthias Hanisch
Modified Paths:
--------------
trunk/httpunit/src/main/java/com/meterware/httpunit/WebResponse.java
trunk/httpunit/src/test/java/com/meterware/httpunit/WebPageTest.java
Modified: trunk/httpunit/src/main/java/com/meterware/httpunit/WebResponse.java
===================================================================
--- trunk/httpunit/src/main/java/com/meterware/httpunit/WebResponse.java 2012-09-12 20:16:44 UTC (rev 1092)
+++ trunk/httpunit/src/main/java/com/meterware/httpunit/WebResponse.java 2012-09-12 20:40:55 UTC (rev 1093)
@@ -1031,6 +1031,11 @@
}
+ /**
+ * replace the given text
+ * @param text - the text to replace
+ * @param contentType - the contenttype
+ */
public boolean replaceText( String text, String contentType ) {
if (_parsingPage) return false;
_responseText = text;
@@ -1174,18 +1179,24 @@
return available;
}
-
+ /**
+ * read the tags from the given message
+ * @param rawMessage
+ * @throws UnsupportedEncodingException
+ * @throws MalformedURLException
+ */
private void readTags( byte[] rawMessage ) throws UnsupportedEncodingException, MalformedURLException {
ByteTagParser parser = new ByteTagParser( rawMessage );
ByteTag tag = parser.getNextTag();
while (tag != null ) {
if (tag.getName().equalsIgnoreCase( "meta" )) processMetaTag( tag );
if (tag.getName().equalsIgnoreCase( "base" )) processBaseTag( tag );
+ // loop over a noscript region
if (tag.getName().equalsIgnoreCase( "noscript") && HttpUnitOptions.isScriptingEnabled()) {
do {
tag = parser.getNextTag();
}
- while (tag.getName().equalsIgnoreCase( "/noscript") );
+ while (!tag.getName().equalsIgnoreCase( "/noscript") );
}
tag = parser.getNextTag();
}
Modified: trunk/httpunit/src/test/java/com/meterware/httpunit/WebPageTest.java
===================================================================
--- trunk/httpunit/src/test/java/com/meterware/httpunit/WebPageTest.java 2012-09-12 20:16:44 UTC (rev 1092)
+++ trunk/httpunit/src/test/java/com/meterware/httpunit/WebPageTest.java 2012-09-12 20:40:55 UTC (rev 1093)
@@ -26,10 +26,12 @@
import java.io.IOException;
import java.net.URL;
+import org.junit.Ignore;
import org.junit.Test;
import org.w3c.dom.html.HTMLDocument;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
+import org.xml.sax.SAXException;
import static org.junit.Assert.*;
@@ -173,10 +175,10 @@
assertEquals("", text);
}
-
+ //@Ignore
@Test
public void testTitle() throws Exception {
- defineResource("SimpleTitlePage.html",
+ defineResource("/SimpleTitlePage.html",
"<html><head><title>A Sample Page</title></head>\n" +
"<body>This has no forms but it does\n" +
"have <a href=\"/other.html\">an <b>active</b> link</A>\n" +
@@ -191,7 +193,6 @@
assertNull("No refresh request should have been found", simplePage.getRefreshRequest());
}
-
@Test
public void testLocalFile() throws Exception {
File file = new File("temp.html");
@@ -591,6 +592,20 @@
//check the response
assertTrue(resp.getText().indexOf("Success") >= 0);
}
+
+ /**
+ * test case for BR 2883515
+ * @throws SAXException
+ * @throws IOException
+ */
+ @Test
+ public void testInvalidNoScriptHandling() throws IOException, SAXException {
+ defineResource("/InvalidNoScriptPage.html","<html><body></body></html><noscript>t</noscript>");
+ WebConversation wc = new WebConversation();
+ WebResponse resp = wc.getResponse(getHostPath() + "/InvalidNoScriptPage.html");
+ // indirectly invoke readTags
+ resp.replaceText("dummy", "dummy");
+ }
/**
* Create a fragment of HTML defining JavaScript that writes a document into a different window.
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <wol...@us...> - 2012-09-12 20:16:54
|
Revision: 1092
http://httpunit.svn.sourceforge.net/httpunit/?rev=1092&view=rev
Author: wolfgang_fahl
Date: 2012-09-12 20:16:44 +0000 (Wed, 12 Sep 2012)
Log Message:
-----------
switch to latest jtidy release as asked for by BR 2880636
by Chuck Betts
Modified Paths:
--------------
trunk/httpunit/pom.xml
trunk/httpunit/src/main/java/com/meterware/httpunit/parsing/JTidyHTMLParser.java
Modified: trunk/httpunit/pom.xml
===================================================================
--- trunk/httpunit/pom.xml 2012-09-12 20:05:28 UTC (rev 1091)
+++ trunk/httpunit/pom.xml 2012-09-12 20:16:44 UTC (rev 1092)
@@ -1,271 +1,177 @@
<?xml version="1.0" encoding="UTF-8"?>
-<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/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
+<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/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.sonatype.oss</groupId>
- <artifactId>oss-parent</artifactId>
- <version>7</version>
- </parent>
+ <parent>
+ <groupId>org.sonatype.oss</groupId>
+ <artifactId>oss-parent</artifactId>
+ <version>7</version>
+ </parent>
- <groupId>org.httpunit</groupId>
- <artifactId>httpunit</artifactId>
- <name>HttpUnit</name>
- <version>1.7.2-SNAPSHOT</version>
- <description>A library for testing websites programmatically</description>
+ <groupId>org.httpunit</groupId>
+ <artifactId>httpunit</artifactId>
+ <name>HttpUnit</name>
+ <version>1.7.2-SNAPSHOT</version>
+ <description>A library for testing websites programmatically</description>
- <url>http://www.httpunit.org</url>
+ <url>http://www.httpunit.org</url>
- <licenses>
- <license>
- <name>MIT</name>
- <url>http://www.opensource.org/licenses/mit-license.php</url>
- </license>
- </licenses>
+ <licenses>
+ <license>
+ <name>MIT</name>
+ <url>http://www.opensource.org/licenses/mit-license.php</url>
+ </license>
+ </licenses>
- <scm>
- <url>http://httpunit.svn.sourceforge.net/viewvc/httpunit</url>
- <developerConnection>scm:svn:https://httpunit.svn.sourceforge.net/svnroot/httpunit</developerConnection>
- <connection>scm:svn:http://httpunit.svn.sourceforge.net/svnroot/httpunit</connection>
- </scm>
+ <scm>
+ <url>http://httpunit.svn.sourceforge.net/viewvc/httpunit</url>
+ <developerConnection>scm:svn:https://httpunit.svn.sourceforge.net/svnroot/httpunit</developerConnection>
+ <connection>scm:svn:http://httpunit.svn.sourceforge.net/svnroot/httpunit</connection>
+ </scm>
- <developers>
- <developer>
- <id>russgold</id>
- <name>Russell Gold</name>
- <organization>Oracle, Inc.</organization>
- <roles>
- <role>lead</role>
- <role>developer</role>
- </roles>
- </developer>
- <developer>
- <id>wolfgang_fahl</id>
- <name>Wolfgang Fahl</name>
- <organization>BitPlan</organization>
- <roles>
- <role>lead</role>
- <role>developer</role>
- </roles>
- </developer>
- </developers>
+ <developers>
+ <developer>
+ <id>russgold</id>
+ <name>Russell Gold</name>
+ <organization>Oracle, Inc.</organization>
+ <roles>
+ <role>lead</role>
+ <role>developer</role>
+ </roles>
+ </developer>
+ <developer>
+ <id>wolfgang_fahl</id>
+ <name>Wolfgang Fahl</name>
+ <organization>BitPlan</organization>
+ <roles>
+ <role>lead</role>
+ <role>developer</role>
+ </roles>
+ </developer>
+ </developers>
- <issueManagement>
- <system>Sourceforge</system>
- <url>http://sourceforge.net/tracker/?group_id=6550&atid=106550</url>
- </issueManagement>
+ <issueManagement>
+ <system>Sourceforge</system>
+ <url>http://sourceforge.net/tracker/?group_id=6550&atid=106550</url>
+ </issueManagement>
- <dependencies>
- <dependency>
- <groupId>rhino</groupId>
- <artifactId>js</artifactId>
- <version>1.6R5</version>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.7</version>
- </dependency>
- <dependency>
- <groupId>nekohtml</groupId>
- <artifactId>nekohtml</artifactId>
- <version>0.9.5</version>
- </dependency>
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>servlet-api</artifactId>
- <version>2.4</version>
- </dependency>
- <dependency>
- <groupId>jtidy</groupId>
- <artifactId>jtidy</artifactId>
- <version>4aug2000r7-dev</version>
- </dependency>
- <dependency>
- <groupId>xerces</groupId>
- <artifactId>xercesImpl</artifactId>
- <version>2.6.1</version>
- </dependency>
- <dependency>
- <groupId>xerces</groupId>
- <artifactId>xmlParserAPIs</artifactId>
- <version>2.6.1</version>
- </dependency>
- <dependency>
- <groupId>javax.mail</groupId>
- <artifactId>mail</artifactId>
- <version>1.4</version>
- <scope>test</scope>
- </dependency>
- </dependencies>
+ <dependencies>
+ <dependency>
+ <groupId>rhino</groupId>
+ <artifactId>js</artifactId>
+ <version>1.6R5</version>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>4.7</version>
+ </dependency>
+ <dependency>
+ <groupId>nekohtml</groupId>
+ <artifactId>nekohtml</artifactId>
+ <version>0.9.5</version>
+ </dependency>
+ <dependency>
+ <groupId>javax.servlet</groupId>
+ <artifactId>servlet-api</artifactId>
+ <version>2.4</version>
+ </dependency>
+ <!-- Java port of html tidy http://jtidy.sourceforge.net/ -->
+ <dependency>
+ <groupId>net.sf.jtidy</groupId>
+ <artifactId>jtidy</artifactId>
+ <version>r938</version>
+ </dependency>
+ <!-- <dependency> <groupId>jtidy</groupId> <artifactId>jtidy</artifactId>
+ <version>4aug2000r7-dev</version> </dependency> -->
+ <dependency>
+ <groupId>xerces</groupId>
+ <artifactId>xercesImpl</artifactId>
+ <version>2.6.1</version>
+ </dependency>
+ <dependency>
+ <groupId>xerces</groupId>
+ <artifactId>xmlParserAPIs</artifactId>
+ <version>2.6.1</version>
+ </dependency>
+ <dependency>
+ <groupId>javax.mail</groupId>
+ <artifactId>mail</artifactId>
+ <version>1.4</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
- <version>2.3.2</version>
- <configuration>
- <source>1.5</source>
- <target>1.5</target>
- <compilerArgument>-proc:none</compilerArgument>
- </configuration>
- </plugin>
- </plugins>
- <testResources>
- <testResource>
- <directory>META-INF</directory>
- </testResource>
- </testResources>
- </build>
-
- <reporting>
- <plugins>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>findbugs-maven-plugin</artifactId>
- <version>2.5.1</version>
- </plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>cobertura-maven-plugin</artifactId>
- <version>2.5.1</version>
- </plugin>
- </plugins>
- </reporting>
-
-<!--
-
<build>
- <sourceDirectory>src</sourceDirectory>
- <testSourceDirectory>test</testSourceDirectory>
- <testResources>
- <testResource>
- <directory>META-INF</directory>
- </testResource>
- </testResources>
- <resources>
- <resource>
- <directory>META-INF</directory>
- </resource>
- </resources>
<plugins>
<plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>cobertura-maven-plugin</artifactId>
- </plugin>
- <plugin>
<groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-source-plugin</artifactId>
- <executions>
- <execution>
- <id>attach-sources</id>
- <phase>package</phase>
- <goals>
- <goal>jar</goal>
- <goal>test-jar</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>build-helper-maven-plugin</artifactId>
- <version>1.0</version>
- <executions>
- <execution>
- <id>add-source</id>
- <phase>generate-sources</phase>
- <goals>
- <goal>add-source</goal>
- </goals>
- <configuration>
- <sources>
- <source>src-1.4</source>
- </sources>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-jar-plugin</artifactId>
-
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>2.3.2</version>
<configuration>
- <forkMode>never</forkMode>
- <!- Assertions diasabled due to a bug in xmlbeans
- https://issues.apache.org/jira/browse/XMLBEANS-317 ->
- <enableAssertions>false</enableAssertions>
- <excludes>
- <exclude>**/TestSuite$1.class</exclude>
- <exclude>**/EventAwareTestBase.class</exclude>
- <exclude>**/WebClientTest.class</exclude>
- <exclude>**/WebPageTest.class</exclude>
- </excludes>
+ <source>1.5</source>
+ <target>1.5</target>
+ <compilerArgument>-proc:none</compilerArgument>
</configuration>
</plugin>
</plugins>
-
+ <testResources>
+ <testResource>
+ <directory>META-INF</directory>
+ </testResource>
+ </testResources>
</build>
+
<reporting>
<plugins>
<plugin>
- <artifactId>maven-javadoc-plugin</artifactId>
- </plugin>
- <plugin>
- <artifactId>maven-surefire-report-plugin</artifactId>
- <configuration>
- <additionalClasspathElements>
- <additionalClasspathElement>
- META-INF
- </additionalClasspathElement>
- </additionalClasspathElements>
- </configuration>
- </plugin>
- <plugin>
- <artifactId>maven-jxr-plugin</artifactId>
- </plugin>
- <plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>findbugs-maven-plugin</artifactId>
- <configuration>
- <threshold>Normal</threshold>
- </configuration>
+ <version>2.5.1</version>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
+ <version>2.5.1</version>
</plugin>
</plugins>
-
</reporting>
--->
- <!-- Jetty libraries needed for Testing BR [ 2264431 ] form.submit() sends multiple HTTP POSTS
- <dependency>
- <groupId>org.mortbay.jetty</groupId>
- <artifactId>jetty</artifactId>
- <version>6.1.4</version>
- </dependency>
- <dependency>
- <groupId>org.mortbay.jetty</groupId>
- <artifactId>jetty-naming</artifactId>
- <version>6.1.4</version>
- </dependency>
- <dependency>
- <groupId>org.mortbay.jetty</groupId>
- <artifactId>jetty-plus</artifactId>
- <version>6.1.4</version>
- </dependency>
- <dependency>
- <groupId>org.mortbay.jetty</groupId>
- <artifactId>jetty-util</artifactId>
- <version>6.1.4</version>
- </dependency> -->
+ <!-- <build> <sourceDirectory>src</sourceDirectory> <testSourceDirectory>test</testSourceDirectory>
+ <testResources> <testResource> <directory>META-INF</directory> </testResource>
+ </testResources> <resources> <resource> <directory>META-INF</directory> </resource>
+ </resources> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId>
+ </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId>
+ <executions> <execution> <id>attach-sources</id> <phase>package</phase> <goals>
+ <goal>jar</goal> <goal>test-jar</goal> </goals> </execution> </executions>
+ </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId>
+ <version>1.0</version> <executions> <execution> <id>add-source</id> <phase>generate-sources</phase>
+ <goals> <goal>add-source</goal> </goals> <configuration> <sources> <source>src-1.4</source>
+ </sources> </configuration> </execution> </executions> </plugin> <plugin>
+ <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId>
+ </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId>
+ <configuration> <forkMode>never</forkMode> <!- Assertions diasabled due to
+ a bug in xmlbeans https://issues.apache.org/jira/browse/XMLBEANS-317 -> <enableAssertions>false</enableAssertions>
+ <excludes> <exclude>**/TestSuite$1.class</exclude> <exclude>**/EventAwareTestBase.class</exclude>
+ <exclude>**/WebClientTest.class</exclude> <exclude>**/WebPageTest.class</exclude>
+ </excludes> </configuration> </plugin> </plugins> </build> <reporting> <plugins>
+ <plugin> <artifactId>maven-javadoc-plugin</artifactId> </plugin> <plugin>
+ <artifactId>maven-surefire-report-plugin</artifactId> <configuration> <additionalClasspathElements>
+ <additionalClasspathElement> META-INF </additionalClasspathElement> </additionalClasspathElements>
+ </configuration> </plugin> <plugin> <artifactId>maven-jxr-plugin</artifactId>
+ </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>findbugs-maven-plugin</artifactId>
+ <configuration> <threshold>Normal</threshold> </configuration> </plugin>
+ <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId>
+ </plugin> </plugins> </reporting> -->
+
+ <!-- Jetty libraries needed for Testing BR [ 2264431 ] form.submit() sends
+ multiple HTTP POSTS <dependency> <groupId>org.mortbay.jetty</groupId> <artifactId>jetty</artifactId>
+ <version>6.1.4</version> </dependency> <dependency> <groupId>org.mortbay.jetty</groupId>
+ <artifactId>jetty-naming</artifactId> <version>6.1.4</version> </dependency>
+ <dependency> <groupId>org.mortbay.jetty</groupId> <artifactId>jetty-plus</artifactId>
+ <version>6.1.4</version> </dependency> <dependency> <groupId>org.mortbay.jetty</groupId>
+ <artifactId>jetty-util</artifactId> <version>6.1.4</version> </dependency> -->
</project>
Modified: trunk/httpunit/src/main/java/com/meterware/httpunit/parsing/JTidyHTMLParser.java
===================================================================
--- trunk/httpunit/src/main/java/com/meterware/httpunit/parsing/JTidyHTMLParser.java 2012-09-12 20:05:28 UTC (rev 1091)
+++ trunk/httpunit/src/main/java/com/meterware/httpunit/parsing/JTidyHTMLParser.java 2012-09-12 20:16:44 UTC (rev 1092)
@@ -85,9 +85,16 @@
final private static String UTF_ENCODING = "UTF-8";
+ /**
+ * get the parser of the given url
+ * @param url
+ * @return the parser
+ */
private static Tidy getParser( URL url ) {
Tidy tidy = new Tidy();
- tidy.setCharEncoding( org.w3c.tidy.Configuration.UTF8 );
+ // BR 2880636 httpunit 1.7 does not work with latest Tidy release r918
+ // tidy.setCharEncoding( org.w3c.tidy.Configuration.UTF8 );
+ tidy.setInputEncoding("UTF8");
tidy.setQuiet( true );
tidy.setShowWarnings( HTMLParserFactory.isParserWarningsEnabled() );
if (!HTMLParserFactory.getHTMLParserListeners().isEmpty()) {
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <wol...@us...> - 2012-09-12 20:05:34
|
Revision: 1091
http://httpunit.svn.sourceforge.net/httpunit/?rev=1091&view=rev
Author: wolfgang_fahl
Date: 2012-09-12 20:05:28 +0000 (Wed, 12 Sep 2012)
Log Message:
-----------
comment added for BR 2871999 by Prafulla Bhalekar
rated as duplicate of BR 2076028
Modified Paths:
--------------
trunk/httpunit/src/test/java/com/meterware/httpunit/cookies/CookieTest.java
Modified: trunk/httpunit/src/test/java/com/meterware/httpunit/cookies/CookieTest.java
===================================================================
--- trunk/httpunit/src/test/java/com/meterware/httpunit/cookies/CookieTest.java 2012-09-12 16:26:05 UTC (rev 1090)
+++ trunk/httpunit/src/test/java/com/meterware/httpunit/cookies/CookieTest.java 2012-09-12 20:05:28 UTC (rev 1091)
@@ -3,7 +3,7 @@
* $Id$
* $URL$
*
- * Copyright (c) 2002-2004,2008 Russell Gold
+ * Copyright (c) 2002-2004,2008, 2012 Russell Gold
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
@@ -318,7 +318,9 @@
}
/**
- * test for bug report [ 2076028 ] Cookies are handeled incorrectly
+ * test for bug report [ 2076028 ] Cookies are handled incorrectly
+ * should also fit duplicate bug report 2871999
+ * https://sourceforge.net/tracker/?func=detail&aid=2871999&group_id=6550&atid=106550
*/
@Test
public void testHttpOnlyCookiePath() throws Exception {
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <wol...@us...> - 2012-09-12 16:26:16
|
Revision: 1090
http://httpunit.svn.sourceforge.net/httpunit/?rev=1090&view=rev
Author: wolfgang_fahl
Date: 2012-09-12 16:26:05 +0000 (Wed, 12 Sep 2012)
Log Message:
-----------
Fixes BR 2834933 There is no facility to allow recursive redirects
by Aptivate
Modified Paths:
--------------
trunk/httpunit/src/main/java/com/meterware/httpunit/ClientProperties.java
trunk/httpunit/src/main/java/com/meterware/httpunit/WebWindow.java
trunk/httpunit/src/test/java/com/meterware/httpunit/WebClientTest.java
Modified: trunk/httpunit/src/main/java/com/meterware/httpunit/ClientProperties.java
===================================================================
--- trunk/httpunit/src/main/java/com/meterware/httpunit/ClientProperties.java 2012-09-12 16:08:03 UTC (rev 1089)
+++ trunk/httpunit/src/main/java/com/meterware/httpunit/ClientProperties.java 2012-09-12 16:26:05 UTC (rev 1090)
@@ -160,8 +160,24 @@
_acceptGzip = acceptGzip;
}
+ /**
+ * get Maximum number of redirect requests
+ * @return it
+ */
+ public int getMaxRedirects() {
+ return _maxRedirects;
+ }
/**
+ * set the maximum number of redirects
+ * @param maxRedirects
+ */
+ public void setMaxRedirects( int maxRedirects ) {
+ _maxRedirects = maxRedirects;
+ }
+
+
+ /**
* Returns true if the client should automatically follow page redirect requests (status 3xx).
* By default, this is true.
**/
@@ -294,6 +310,7 @@
private String _overrideContentType = null;
private int _availWidth = 800;
private int _availHeight = 600;
+ private int _maxRedirects = 5;
private boolean _iframeSupported = true;
private boolean _acceptCookies = true;
@@ -333,6 +350,7 @@
_autoRedirect = source._autoRedirect;
_autoRefresh = source._autoRefresh;
_sendReferer = source._sendReferer;
+ _maxRedirects = source._maxRedirects;
}
Modified: trunk/httpunit/src/main/java/com/meterware/httpunit/WebWindow.java
===================================================================
--- trunk/httpunit/src/main/java/com/meterware/httpunit/WebWindow.java 2012-09-12 16:08:03 UTC (rev 1089)
+++ trunk/httpunit/src/main/java/com/meterware/httpunit/WebWindow.java 2012-09-12 16:26:05 UTC (rev 1090)
@@ -1,8 +1,9 @@
package com.meterware.httpunit;
+
/********************************************************************************************************************
* $Id$
*
- * Copyright (c) 2002-2008, Russell Gold
+ * Copyright (c) 2002-2008,2012 Russell Gold
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
@@ -23,339 +24,357 @@
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
-import java.util.HashSet;
+import java.util.Hashtable;
import java.util.List;
-import java.util.Set;
+import java.util.Map;
import org.xml.sax.SAXException;
import com.meterware.httpunit.scripting.ScriptingHandler;
/**
* A window managed by a {@link com.meterware.httpunit.WebClient WebClient}.
- *
+ *
* @author <a href="mailto:rus...@ht...">Russell Gold</a>
**/
public class WebWindow {
- /** The client which created this window. **/
- private WebClient _client;
+ /** The client which created this window. **/
+ private WebClient _client;
- /** A map of frame names to current contents. **/
- private FrameHolder _frameContents;
+ /** A map of frame names to current contents. **/
+ private FrameHolder _frameContents;
- /** The name of the window, set via JavaScript. **/
- private String _name = "";
+ /** The name of the window, set via JavaScript. **/
+ private String _name = "";
- /** The web response containing the reference that opened this window **/
- private WebResponse _opener;
+ /** The web response containing the reference that opened this window **/
+ private WebResponse _opener;
- /** True if this window has been closed. **/
- private boolean _closed;
+ /** True if this window has been closed. **/
+ private boolean _closed;
+ static final String NO_NAME = "$$HttpUnit_Window$$_";
- static final String NO_NAME = "$$HttpUnit_Window$$_";
-
- /**
- * The urls that have been encountered as redirect locations in the course
- * of a single client-initiated request
- * @since patch [ 1155415 ] Handle redirect instructions which can lead to a loop
- */
- private final Set _redirects;
-
- /** True if seen initial request
- * @since patch [ 1155415 ] Handle redirect instructions which can lead to a loop
- */
- private boolean _isInitialRequest = true;
-
- /**
- * Cache the initial client request to ensure that the _redirects
- * structure gets reset.
- * @since patch [ 1155415 ] Handle redirect instructions which can lead to a loop
- */
- private WebRequest _initialRequest;
-
+ /**
+ * The urls that have been encountered as redirect locations in the course
+ * of a single client-initiated request
+ *
+ * @since patch [ 1155415 ] Handle redirect instructions which can lead to a
+ * loop
+ */
+ private final Map _redirects;
- /**
- * Returns the web client associated with this window.
- */
- public WebClient getClient() {
- return _client;
- }
+ /**
+ * True if seen initial request
+ *
+ * @since patch [ 1155415 ] Handle redirect instructions which can lead to a
+ * loop
+ */
+ private boolean _isInitialRequest = true;
+ /**
+ * Cache the initial client request to ensure that the _redirects structure
+ * gets reset.
+ *
+ * @since patch [ 1155415 ] Handle redirect instructions which can lead to a
+ * loop
+ */
+ private WebRequest _initialRequest;
- /**
- * Returns true if this window has been closed.
- */
- public boolean isClosed() {
- return _closed;
- }
+ /**
+ * Returns the web client associated with this window.
+ */
+ public WebClient getClient() {
+ return _client;
+ }
+ /**
+ * Returns true if this window has been closed.
+ */
+ public boolean isClosed() {
+ return _closed;
+ }
- /**
- * Closes this window.
- */
- public void close() {
- if (!_closed) _client.close( this );
- _closed = true;
- }
+ /**
+ * Closes this window.
+ */
+ public void close() {
+ if (!_closed)
+ _client.close(this);
+ _closed = true;
+ }
+ /**
+ * Returns the name of this window. Windows created through normal HTML or
+ * browser commands have empty names, but JavaScript can set the name. A
+ * name may be used as a target for a request.
+ */
+ public String getName() {
+ return _name;
+ }
- /**
- * Returns the name of this window. Windows created through normal HTML or browser commands have empty names,
- * but JavaScript can set the name. A name may be used as a target for a request.
- */
- public String getName() {
- return _name;
- }
+ /**
+ * Returns the web response that contained the script which opened this
+ * window.
+ */
+ public WebResponse getOpener() {
+ return _opener;
+ }
+ /**
+ * Submits a GET method request and returns a response.
+ *
+ * @exception SAXException
+ * thrown if there is an error parsing the retrieved page
+ **/
+ public WebResponse getResponse(String urlString) throws IOException,
+ SAXException {
+ return getResponse(new GetMethodWebRequest(urlString));
+ }
- /**
- * Returns the web response that contained the script which opened this window.
- */
- public WebResponse getOpener() {
- return _opener;
- }
+ /**
+ * Submits a web request and returns a response. This is an alternate name
+ * for the getResponse method.
+ *
+ * @return the WebResponse or null
+ **/
+ public WebResponse sendRequest(WebRequest request) throws IOException,
+ SAXException {
+ return getResponse(request);
+ }
+ /**
+ * Submits a web request and returns a response, using all state developed
+ * so far as stored in cookies as requested by the server. see patch [
+ * 1155415 ] Handle redirect instructions which can lead to a loop
+ *
+ * @exception SAXException
+ * thrown if there is an error parsing the retrieved page
+ * @return the WebResponse or null
+ **/
+ public WebResponse getResponse(WebRequest request) throws IOException,
+ SAXException {
+ // Need to have some sort of ExecuteAroundMethod to ensure that the
+ // redirects data structure gets cleared down upon exit - not
+ // straightforward, since this could be a recursive call
+ if (_isInitialRequest) {
+ _initialRequest = request;
+ _isInitialRequest = false;
+ }
- /**
- * Submits a GET method request and returns a response.
- * @exception SAXException thrown if there is an error parsing the retrieved page
- **/
- public WebResponse getResponse( String urlString ) throws IOException, SAXException {
- return getResponse( new GetMethodWebRequest( urlString ) );
- }
+ WebResponse result = null;
+ try {
+ final RequestContext requestContext = new RequestContext();
+ final WebResponse response = getSubframeResponse(request,
+ requestContext);
+ requestContext.runScripts();
+ result = response == null ? null : response.getWindow()
+ .getFrameContents(response.getFrame()); // javascript might
+ // replace the
+ // response in its
+ // frame
+ } finally {
+ if (null != request && request.equals(_initialRequest)) {
+ _redirects.clear();
+ _initialRequest = null;
+ _isInitialRequest = true;
+ }
+ }
+ return result;
+ }
- /**
- * Submits a web request and returns a response. This is an alternate name for the getResponse method.
- * @return the WebResponse or null
- **/
- public WebResponse sendRequest( WebRequest request ) throws IOException, SAXException {
- return getResponse( request );
- }
+ /**
+ * get a Response from a SubFrame
+ *
+ * @param request
+ * @param requestContext
+ * @return the WebResponse or null
+ * @throws IOException
+ * @throws SAXException
+ */
+ WebResponse getSubframeResponse(WebRequest request,
+ RequestContext requestContext) throws IOException, SAXException {
+ WebResponse response = getResource(request);
+ return response == null ? null : updateWindow(request.getTarget(),
+ response, requestContext);
+ }
- /**
- * Submits a web request and returns a response, using all state developed so far as stored in
- * cookies as requested by the server.
- * see patch [ 1155415 ] Handle redirect instructions which can lead to a loop
- * @exception SAXException thrown if there is an error parsing the retrieved page
- * @return the WebResponse or null
- **/
- public WebResponse getResponse( WebRequest request ) throws IOException, SAXException {
- // Need to have some sort of ExecuteAroundMethod to ensure that the
- // redirects data structure gets cleared down upon exit - not
- // straightforward, since this could be a recursive call
- if (_isInitialRequest) {
- _initialRequest = request;
- _isInitialRequest = false;
- }
-
- WebResponse result = null;
-
- try {
- final RequestContext requestContext = new RequestContext();
- final WebResponse response = getSubframeResponse( request, requestContext );
- requestContext.runScripts();
- result = response == null ? null : response.getWindow().getFrameContents( response.getFrame() ); // javascript might replace the response in its frame
- } finally {
- if (null != request && request.equals(_initialRequest)) {
- _redirects.clear();
- _initialRequest = null;
- _isInitialRequest = true;
- }
- }
- return result;
+ /**
+ * Updates this web client based on a received response. This includes
+ * updating cookies and frames.
+ **/
+ WebResponse updateWindow(String requestTarget, WebResponse response,
+ RequestContext requestContext) throws IOException, SAXException {
+ _client.updateClient(response);
+ if (getClient().getClientProperties().isAutoRefresh()
+ && response.getRefreshRequest() != null) {
+ WebRequest request = response.getRefreshRequest();
+ WebResponse result = getResponse(request);
+ return result;
+ } else if (shouldFollowRedirect(response)) {
+ delay(HttpUnitOptions.getRedirectDelay());
+ return getResponse(new RedirectWebRequest(response));
+ } else {
+ _client.updateFrameContents(this, requestTarget, response,
+ requestContext);
+ return response;
}
+ }
+ /**
+ * Returns the resource specified by the request. Does not update the window
+ * or load included framesets. May return null if the resource is a
+ * JavaScript URL which would normally leave the client unchanged.
+ */
+ public WebResponse getResource(WebRequest request) throws IOException {
+ _client.tellListeners(request);
- /**
- * get a Response from a SubFrame
- * @param request
- * @param requestContext
- * @return the WebResponse or null
- * @throws IOException
- * @throws SAXException
- */
- WebResponse getSubframeResponse( WebRequest request, RequestContext requestContext ) throws IOException, SAXException {
- WebResponse response = getResource( request );
+ WebResponse response = null;
+ String urlString = request.getURLString().trim();
+ FrameSelector targetFrame = _frameContents.getTargetFrame(request);
+ if (urlString.startsWith("about:")) {
+ response = new DefaultWebResponse(_client, targetFrame, null, "");
+ } else if (!HttpUnitUtils.isJavaScriptURL(urlString)) {
+ response = _client.createResponse(request, targetFrame);
+ } else {
+ ScriptingHandler handler = request.getSourceScriptingHandler();
+ if (handler == null)
+ handler = getCurrentPage().getScriptingHandler();
+ Object result = handler.evaluateExpression(urlString);
+ if (result != null) {
+ response = new DefaultWebResponse(_client, targetFrame,
+ request.getURL(), result.toString());
+ }
+ }
- return response == null ? null : updateWindow( request.getTarget(), response, requestContext );
- }
+ if (response != null)
+ _client.tellListeners(response);
+ return response;
+ }
+ /**
+ * Returns the name of the currently active frames.
+ **/
+ public String[] getFrameNames() {
+ final List names = _frameContents.getActiveFrameNames();
+ return (String[]) names.toArray(new String[names.size()]);
+ }
- /**
- * Updates this web client based on a received response. This includes updating
- * cookies and frames.
- **/
- WebResponse updateWindow( String requestTarget, WebResponse response, RequestContext requestContext ) throws IOException, SAXException {
- _client.updateClient( response );
- if (getClient().getClientProperties().isAutoRefresh() && response.getRefreshRequest() != null) {
- WebRequest request=response.getRefreshRequest();
- WebResponse result=getResponse( request );
- return result;
- } else if (shouldFollowRedirect( response )) {
- delay( HttpUnitOptions.getRedirectDelay() );
- return getResponse( new RedirectWebRequest( response ) );
- } else {
- _client.updateFrameContents( this, requestTarget, response, requestContext );
- return response;
- }
- }
+ /**
+ * Returns true if the specified frame name is defined in this window.
+ */
+ public boolean hasFrame(String frameName) {
+ return _frameContents.get(frameName) != null;
+ }
+ boolean hasFrame(FrameSelector frame) {
+ return _frameContents.get(frame) != null;
+ }
- /**
- * Returns the resource specified by the request. Does not update the window or load included framesets.
- * May return null if the resource is a JavaScript URL which would normally leave the client unchanged.
- */
- public WebResponse getResource( WebRequest request ) throws IOException {
- _client.tellListeners( request );
+ /**
+ * Returns the response associated with the specified frame name. Throws a
+ * runtime exception if no matching frame is defined.
+ **/
+ public WebResponse getFrameContents(String frameName) {
+ WebResponse response = _frameContents.get(frameName);
+ if (response == null)
+ throw new NoSuchFrameException(frameName);
+ return response;
+ }
- WebResponse response = null;
- String urlString = request.getURLString().trim();
- FrameSelector targetFrame = _frameContents.getTargetFrame( request );
- if (urlString.startsWith( "about:" )) {
- response = new DefaultWebResponse( _client, targetFrame, null, "" );
- } else if (!HttpUnitUtils.isJavaScriptURL( urlString )) {
- response = _client.createResponse( request, targetFrame );
- } else {
- ScriptingHandler handler = request.getSourceScriptingHandler();
- if (handler == null) handler = getCurrentPage().getScriptingHandler();
- Object result = handler.evaluateExpression( urlString );
- if (result != null) {
- response = new DefaultWebResponse( _client, targetFrame, request.getURL(), result.toString() );
- }
- }
+ /**
+ * Returns the response associated with the specified frame target. Throws a
+ * runtime exception if no matching frame is defined.
+ **/
+ WebResponse getFrameContents(FrameSelector targetFrame) {
+ return _frameContents.getFrameContents(targetFrame);
+ }
- if (response != null) _client.tellListeners( response );
- return response;
- }
+ WebResponse getSubframeContents(FrameSelector frame, String subFrameName) {
+ return _frameContents.getSubframeContents(frame, subFrameName);
+ }
+ WebResponse getParentFrameContents(FrameSelector frame) {
+ return _frameContents.getParentFrameContents(frame);
+ }
- /**
- * Returns the name of the currently active frames.
- **/
- public String[] getFrameNames() {
- final List names = _frameContents.getActiveFrameNames();
- return (String[]) names.toArray( new String[ names.size() ] );
- }
+ /**
+ * Returns the response representing the main page in this window.
+ */
+ public WebResponse getCurrentPage() {
+ return getFrameContents(WebRequest.TOP_FRAME);
+ }
+ /**
+ * construct a WebWindow from a given client
+ *
+ * @param client
+ * - the client to construct me from
+ */
+ WebWindow(WebClient client) {
+ _client = client;
+ _frameContents = new FrameHolder(this);
+ _name = NO_NAME + _client.getOpenWindows().length;
+ _redirects = new Hashtable();
+ }
- /**
- * Returns true if the specified frame name is defined in this window.
- */
- public boolean hasFrame( String frameName ) {
- return _frameContents.get( frameName ) != null;
- }
+ WebWindow(WebClient client, WebResponse opener) {
+ this(client);
+ _opener = opener;
+ }
+ void updateFrameContents(WebResponse response, RequestContext requestContext)
+ throws IOException, SAXException {
+ response.setWindow(this);
+ _frameContents.updateFrames(response, response.getFrame(),
+ requestContext);
+ }
- boolean hasFrame( FrameSelector frame ) {
- return _frameContents.get( frame ) != null;
- }
+ void setName(String name) {
+ _name = name;
+ }
+ /**
+ * Delays the specified amount of time.
+ **/
+ private void delay(int numMilliseconds) {
+ if (numMilliseconds == 0)
+ return;
+ try {
+ Thread.sleep(numMilliseconds);
+ } catch (InterruptedException e) {
+ // ignore the exception
+ }
+ }
- /**
- * Returns the response associated with the specified frame name.
- * Throws a runtime exception if no matching frame is defined.
- **/
- public WebResponse getFrameContents( String frameName ) {
- WebResponse response = _frameContents.get( frameName );
- if (response == null) throw new NoSuchFrameException( frameName );
- return response;
- }
+ /**
+ * check whether redirect is configured
+ *
+ * @param response
+ * @return
+ */
+ private boolean redirectConfigured(WebResponse response) {
+ boolean isAutoredirect = getClient().getClientProperties()
+ .isAutoRedirect();
+ boolean hasLocation = response.getHeaderField("Location") != null;
+ int responseCode = response.getResponseCode();
+ boolean result = isAutoredirect
+ && responseCode >= HttpURLConnection.HTTP_MOVED_PERM
+ && responseCode <= HttpURLConnection.HTTP_MOVED_TEMP
+ && hasLocation;
+ return result;
+ }
-
- /**
- * Returns the response associated with the specified frame target.
- * Throws a runtime exception if no matching frame is defined.
- **/
- WebResponse getFrameContents( FrameSelector targetFrame ) {
- return _frameContents.getFrameContents( targetFrame );
- }
-
-
- WebResponse getSubframeContents( FrameSelector frame, String subFrameName ) {
- return _frameContents.getSubframeContents( frame, subFrameName );
- }
-
-
- WebResponse getParentFrameContents( FrameSelector frame ) {
- return _frameContents.getParentFrameContents( frame );
- }
-
-
- /**
- * Returns the response representing the main page in this window.
- */
- public WebResponse getCurrentPage() {
- return getFrameContents( WebRequest.TOP_FRAME );
- }
-
-
- /**
- * construct a WebWindow from a given client
- * @param client - the client to construct me from
- */
- WebWindow( WebClient client ) {
- _client = client;
- _frameContents = new FrameHolder( this );
- _name = NO_NAME + _client.getOpenWindows().length;
- _redirects = new HashSet();
- }
-
-
- WebWindow( WebClient client, WebResponse opener ) {
- this( client );
- _opener = opener;
- }
-
-
- void updateFrameContents( WebResponse response, RequestContext requestContext ) throws IOException, SAXException {
- response.setWindow( this );
- _frameContents.updateFrames( response, response.getFrame(), requestContext );
- }
-
-
- void setName( String name ) {
- _name = name;
- }
-
-
- /**
- * Delays the specified amount of time.
- **/
- private void delay( int numMilliseconds ) {
- if (numMilliseconds == 0) return;
- try {
- Thread.sleep( numMilliseconds );
- } catch (InterruptedException e) {
- // ignore the exception
- }
- }
-
- /**
- * check whether redirect is configured
- * @param response
- * @return
- */
- private boolean redirectConfigured( WebResponse response ) {
- boolean isAutoredirect=getClient().getClientProperties().isAutoRedirect();
- boolean hasLocation=response.getHeaderField( "Location" ) != null;
- int responseCode=response.getResponseCode();
- boolean result=isAutoredirect
- && responseCode >= HttpURLConnection.HTTP_MOVED_PERM
- && responseCode <= HttpURLConnection.HTTP_MOVED_TEMP
- && hasLocation;
- return result;
- }
-
- /**
- * check wether we should follow the redirect given in the response
- * make sure we don't run into a recursion
- * @param response
- * @return
- */
- private boolean shouldFollowRedirect( WebResponse response ) {
+ /**
+ * check wether we should follow the redirect given in the response make
+ * sure we don't run into a recursion
+ *
+ * @param response
+ * @return
+ */
+ private boolean shouldFollowRedirect( WebResponse response ) {
// first check whether redirect is configured for this response
// this is the old pre [ 1155415 ] Handle redirect instructions which can lead to a loop
// shouldFollowRedirect method - just renamed
@@ -380,25 +399,38 @@
switch (response.getResponseCode()) {
case HttpURLConnection.HTTP_MOVED_PERM:
case HttpURLConnection.HTTP_MOVED_TEMP: // Fall through
- if (null != url && _redirects.contains(url)) {
- // We have already been instructed to redirect to that location in
- // the course of this attempt to resolve the resource
- throw new RecursiveRedirectionException(url,
- "Unable to process request due to redirection loop");
- }
- _redirects.add(url);
+ int count = 0;
+ if (null != url) {
+ Integer value = (Integer)_redirects.get(url);
+ if (null != value) {
+ // We have already been instructed to redirect to that
+ // location in the course of this attempt to resolve the
+ // resource
+
+ count = value.intValue();
+
+ int maxRedirects = getClient().
+ getClientProperties().getMaxRedirects();
+
+ if (count == maxRedirects) {
+ throw new RecursiveRedirectionException(url,
+ "Maximum number of redirects exceeded");
+ }
+ }
+
+ count ++;
+ _redirects.put(url, new Integer(count));
+ }
break;
}
return redirectLocation != null;
- }
-
- FrameSelector getTopFrame() {
- return _frameContents.getTopFrame();
}
+ FrameSelector getTopFrame() {
+ return _frameContents.getTopFrame();
+ }
+ FrameSelector getFrame(String target) {
+ return _frameContents.getFrame(target);
+ }
- FrameSelector getFrame( String target ) {
- return _frameContents.getFrame( target );
- }
-
}
Modified: trunk/httpunit/src/test/java/com/meterware/httpunit/WebClientTest.java
===================================================================
--- trunk/httpunit/src/test/java/com/meterware/httpunit/WebClientTest.java 2012-09-12 16:08:03 UTC (rev 1089)
+++ trunk/httpunit/src/test/java/com/meterware/httpunit/WebClientTest.java 2012-09-12 16:26:05 UTC (rev 1090)
@@ -3,7 +3,7 @@
* $Id$
* $URL$*
*
- * Copyright (c) 2002-2009, Russell Gold
+ * Copyright (c) 2002-2009,2012 Russell Gold
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
@@ -740,7 +740,77 @@
response = wc.getResponse(response.getLinks()[0].getRequest());
assertEquals("Link Referer header", getHostPath() + '/' + linkSource, response.getText().trim());
}
+
+ /**
+ * test for BR 2834933
+ * https://sourceforge.net/tracker/?func=detail&aid=2834933&group_id=6550&atid=106550
+ * by aptivate
+ * @throws Exception
+ */
+ @Test
+ public void testMaxRedirectsNotExceeded() throws Exception {
+ String resourceAName = "something/resourceA";
+ String resourceBName = "something/resourceB";
+ String resourceCName = "something/resourceC";
+
+ // Should test the following :
+ // loads resource A
+ // loads resource B
+ // redirects to resource A
+ // loads resource B
+ // redirects to resource A
+ // loads resource C
+
+ String resourceAContent =
+ "<HTML>" +
+ "<BODY onload='redirect();'>" +
+ "<script type='text/javascript'>" +
+ "function redirect()" +
+ "{" +
+ " if (document.cookie == '')" +
+ " {" +
+ " document.cookie = 'test=1;';\n" +
+ " window.location.replace('/" + resourceBName + "');\n" +
+ " }" +
+ " else if (document.cookie == 'test=1')" +
+ " {" +
+ " document.cookie = 'test=2;';\n" +
+ " window.location.replace('/" + resourceBName + "');\n" +
+ " }" +
+ " else" +
+ " {" +
+ " window.location.replace('/" + resourceCName + "');\n" +
+ " }" +
+ "}" +
+ "</script>" +
+ "</BODY>" +
+ "</HTML>";
+
+ defineResource(resourceAName, resourceAContent,
+ HttpURLConnection.HTTP_OK);
+
+ defineResource(resourceBName, "ignored content",
+ HttpURLConnection.HTTP_MOVED_TEMP);
+ addResourceHeader(resourceBName, "Location: " + getHostPath() + "/"
+ + resourceAName);
+
+ defineResource(resourceCName, "ignored content",
+ HttpURLConnection.HTTP_OK);
+
+ WebConversation wc = new WebConversation();
+ wc.getClientProperties().setMaxRedirects(2);
+
+ try {
+ wc.getResponse(getHostPath() + '/' + resourceAName);
+ } catch (RecursiveRedirectionException e) {
+ fail("Not expecting a RecursiveRedirectionException - " +
+ "max redirects not exceeded");
+ }
+ }
+
+ /**
+
/**
* test for patch [ 1155415 ] Handle redirect instructions which can lead to a loop
*
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <wol...@us...> - 2012-09-12 16:08:11
|
Revision: 1089
http://httpunit.svn.sourceforge.net/httpunit/?rev=1089&view=rev
Author: wolfgang_fahl
Date: 2012-09-12 16:08:03 +0000 (Wed, 12 Sep 2012)
Log Message:
-----------
adds fix for BR BR 2822957 Cannot remove file upload parameter once set in WebForm
by Chris Wilson
Modified Paths:
--------------
trunk/httpunit/src/main/java/com/meterware/httpunit/WebForm.java
trunk/httpunit/src/test/java/com/meterware/httpunit/FileUploadTest.java
Modified: trunk/httpunit/src/main/java/com/meterware/httpunit/WebForm.java
===================================================================
--- trunk/httpunit/src/main/java/com/meterware/httpunit/WebForm.java 2012-09-12 15:55:44 UTC (rev 1088)
+++ trunk/httpunit/src/main/java/com/meterware/httpunit/WebForm.java 2012-09-12 16:08:03 UTC (rev 1089)
@@ -1,24 +1,25 @@
package com.meterware.httpunit;
+
/********************************************************************************************************************
-* $Id$
-*
-* Copyright (c) 2000-2008, Russell Gold
-*
-* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
-* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
-* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
-* to permit persons to whom the Software is furnished to do so, subject to the following conditions:
-*
-* The above copyright notice and this permission notice shall be included in all copies or substantial portions
-* of the Software.
-*
-* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
-* THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
-* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-* DEALINGS IN THE SOFTWARE.
-*
-*******************************************************************************************************************/
+ * $Id$
+ *
+ * Copyright (c) 2000-2008,2012 Russell Gold
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
+ * documentation files (the "Software"), to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
+ * to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions
+ * of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+ * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ *******************************************************************************************************************/
import com.meterware.httpunit.scripting.IdentifiedDelegate;
import com.meterware.httpunit.scripting.NamedDelegate;
import com.meterware.httpunit.scripting.ScriptableDelegate;
@@ -41,1130 +42,1165 @@
import org.w3c.dom.html.HTMLCollection;
import org.xml.sax.SAXException;
-
/**
- * This class represents a form in an HTML page. Users of this class may examine the parameters
- * defined for the form, the structure of the form (as a DOM), or the text of the form. They
- * may also create a {@link WebRequest} to simulate the submission of the form.
- *
+ * This class represents a form in an HTML page. Users of this class may examine
+ * the parameters defined for the form, the structure of the form (as a DOM), or
+ * the text of the form. They may also create a {@link WebRequest} to simulate
+ * the submission of the form.
+ *
* @author <a href="mailto:rus...@ht...">Russell Gold</a>
**/
public class WebForm extends WebRequestSource {
- private final static String[] NO_VALUES = new String[0];
+ private final static String[] NO_VALUES = new String[0];
- private Button[] _buttons;
+ private Button[] _buttons;
- /** The submit buttons in this form. **/
- private SubmitButton[] _submitButtons;
+ /** The submit buttons in this form. **/
+ private SubmitButton[] _submitButtons;
- /** The character set in which the form will be submitted. **/
- private String _characterSet;
+ /** The character set in which the form will be submitted. **/
+ private String _characterSet;
- private Vector _buttonVector;
+ private Vector _buttonVector;
- private FormControl[] _presetParameters;
- private ArrayList _presets;
+ private FormControl[] _presetParameters;
+ private ArrayList _presets;
- private ElementRegistry _registry;
+ private ElementRegistry _registry;
+ /** Predicate to match a link's name. **/
+ public final static HTMLElementPredicate MATCH_NAME;
+ private HTMLFormElement _domElement;
+ /**
+ * Submits this form using the web client from which it was originally
+ * obtained.
+ **/
+ public WebResponse submit() throws IOException, SAXException {
+ return submit(getDefaultButton());
+ }
- /** Predicate to match a link's name. **/
- public final static HTMLElementPredicate MATCH_NAME;
- private HTMLFormElement _domElement;
+ /**
+ * Submits this form using the web client from which it was originally
+ * obtained. Will usually return the result of that submission; however, if
+ * the submit button's 'onclick' or the form's 'onsubmit' event is triggered
+ * and inhibits the submission, will return the updated contents of the
+ * frame containing this form.
+ **/
+ public WebResponse submit(SubmitButton button) throws IOException,
+ SAXException {
+ WebResponse result = submit(button, 0, 0);
+ return result;
+ }
+ /**
+ * Submits this form using the web client from which it was originally
+ * obtained. Will usually return the result of that submission; however, if
+ * the submit button's 'onclick' or the form's 'onsubmit' event is triggered
+ * and inhibits the submission, will return the updated contents of the
+ * frame containing this form.
+ *
+ * @since 1.6
+ **/
+ public WebResponse submit(SubmitButton button, int x, int y)
+ throws IOException, SAXException {
+ WebResponse result = null;
+ if (button == null)
+ throw new IllegalSubmitButtonException("?", "?");
+ button.doOnClickSequence(x, y);
+ result = getCurrentFrameContents();
+ return result;
+ }
- /**
- * Submits this form using the web client from which it was originally obtained.
- **/
- public WebResponse submit() throws IOException, SAXException {
- return submit( getDefaultButton() );
- }
+ /**
+ * Submits this form using the web client from which it was originally
+ * obtained, ignoring any buttons defined for the form.
+ *
+ * @since 1.6
+ **/
+ public WebResponse submitNoButton() throws SAXException, IOException {
+ return submit(SubmitButton.createFakeSubmitButton(this /* fake */));
+ }
+ protected WebResponse submitRequest(String event, WebRequest request)
+ throws IOException, SAXException {
+ try {
+ return super.submitRequest(event, request);
+ } catch (UnknownServiceException e) {
+ throw new UnsupportedActionException("HttpUnit does not support "
+ + request.getURL().getProtocol()
+ + " URLs in form submissions");
+ }
+ }
- /**
- * Submits this form using the web client from which it was originally obtained.
- * Will usually return the result of that submission; however, if the submit button's 'onclick'
- * or the form's 'onsubmit' event is triggered and
- * inhibits the submission, will return the updated contents of the frame containing this form.
- **/
- public WebResponse submit( SubmitButton button ) throws IOException, SAXException {
- WebResponse result=submit(button,0,0);
- return result;
- }
+ /**
+ * Submits the form without also invoking the button's "onclick" event.
+ */
+ WebResponse doFormSubmit(SubmitButton button) throws IOException,
+ SAXException {
+ return submitRequest(getAttribute("onsubmit"), getRequest(button));
+ }
+ WebResponse doFormSubmit(SubmitButton button, int x, int y)
+ throws IOException, SAXException {
+ return submitRequest(getAttribute("onsubmit"), getRequest(button, x, y));
+ }
- /**
- * Submits this form using the web client from which it was originally obtained.
- * Will usually return the result of that submission; however, if the submit button's 'onclick'
- * or the form's 'onsubmit' event is triggered and
- * inhibits the submission, will return the updated contents of the frame containing this form.
- * @since 1.6
- **/
- public WebResponse submit( SubmitButton button, int x, int y ) throws IOException, SAXException {
- WebResponse result=null;
- if (button == null) throw new IllegalSubmitButtonException( "?", "?" );
- button.doOnClickSequence(x, y);
- result=getCurrentFrameContents();
- return result;
- }
+ /**
+ * Returns the method defined for this form.
+ **/
+ public String getMethod() {
+ return getAttribute("method", "GET");
+ }
+ /**
+ * Returns the action defined for this form.
+ **/
+ public String getAction() {
+ return getDestination();
+ }
- /**
- * Submits this form using the web client from which it was originally obtained, ignoring any buttons defined for the form.
- * @since 1.6
- **/
- public WebResponse submitNoButton() throws SAXException, IOException {
- return submit( SubmitButton.createFakeSubmitButton( this /* fake */ ) );
- }
+ /**
+ * Returns true if a parameter with given name exists in this form.
+ **/
+ public boolean hasParameterNamed(String soughtName) {
+ return getFormParameters().containsKey(soughtName);
+ }
+ /**
+ * Returns true if a parameter starting with a given name exists,
+ **/
+ public boolean hasParameterStartingWithPrefix(String prefix) {
+ String[] names = getParameterNames();
+ for (int i = 0; i < names.length; i++) {
+ if (names[i].startsWith(prefix))
+ return true;
+ }
+ return false;
+ }
- protected WebResponse submitRequest( String event, WebRequest request ) throws IOException, SAXException {
- try {
- return super.submitRequest( event, request );
- } catch (UnknownServiceException e) {
- throw new UnsupportedActionException( "HttpUnit does not support " + request.getURL().getProtocol() + " URLs in form submissions" );
- }
- }
+ /**
+ * Returns an array containing all of the buttons defined for this form.
+ **/
+ public Button[] getButtons() {
+ if (_buttons == null) {
+ FormControl[] controls = getFormControls();
+ ArrayList buttonList = new ArrayList();
+ for (int i = 0; i < controls.length; i++) {
+ FormControl control = controls[i];
+ if (control instanceof Button)
+ buttonList.add(control);
+ }
+ _buttons = (Button[]) buttonList.toArray(new Button[buttonList
+ .size()]);
+ }
+ return _buttons;
+ }
+ public Button getButton(HTMLElementPredicate predicate, Object criteria) {
+ Button[] buttons = getButtons();
+ for (int i = 0; i < buttons.length; i++) {
+ if (predicate.matchesCriteria(buttons[i], criteria))
+ return buttons[i];
+ }
+ return null;
+ }
- /**
- * Submits the form without also invoking the button's "onclick" event.
- */
- WebResponse doFormSubmit( SubmitButton button ) throws IOException, SAXException {
- return submitRequest( getAttribute( "onsubmit" ), getRequest( button ) );
- }
+ /**
+ * Convenience method which returns the button with the specified ID.
+ */
+ public Button getButtonWithID(String buttonID) {
+ return getButton(Button.WITH_ID, buttonID);
+ }
+ /**
+ * Returns an array containing the submit buttons defined for this form.
+ **/
+ public SubmitButton[] getSubmitButtons() {
+ if (_submitButtons == null) {
+ Vector buttons = getSubmitButtonVector();
+ _submitButtons = new SubmitButton[buttons.size()];
+ buttons.copyInto(_submitButtons);
+ }
+ return _submitButtons;
+ }
- WebResponse doFormSubmit( SubmitButton button, int x, int y ) throws IOException, SAXException {
- return submitRequest( getAttribute( "onsubmit" ), getRequest( button, x, y ) );
- }
+ /**
+ * Returns the submit button defined in this form with the specified name.
+ * If more than one such button exists, will return the first found. If no
+ * such button is found, will return null.
+ **/
+ public SubmitButton getSubmitButton(String name) {
+ SubmitButton[] buttons = getSubmitButtons();
+ for (int i = 0; i < buttons.length; i++) {
+ if (buttons[i].getName().equals(name)) {
+ return buttons[i];
+ }
+ }
+ return null;
+ }
+ /**
+ * Returns the submit button defined in this form with the specified name
+ * and value. If more than one such button exists, will return the first
+ * found. If no such button is found, will return null.
+ **/
+ public SubmitButton getSubmitButton(String name, String value) {
+ SubmitButton[] buttons = getSubmitButtons();
+ for (int i = 0; i < buttons.length; i++) {
+ if (buttons[i].getName().equals(name)
+ && buttons[i].getValue().equals(value)) {
+ return buttons[i];
+ }
+ }
+ return null;
+ }
- /**
- * Returns the method defined for this form.
- **/
- public String getMethod() {
- return getAttribute( "method", "GET" );
- }
+ /**
+ * Returns the submit button defined in this form with the specified ID. If
+ * more than one such button exists, will return the first found. If no such
+ * button is found, will return null.
+ **/
+ public SubmitButton getSubmitButtonWithID(String ID) {
+ SubmitButton[] buttons = getSubmitButtons();
+ for (int i = 0; i < buttons.length; i++) {
+ if (buttons[i].getID().equals(ID)) {
+ return buttons[i];
+ }
+ }
+ return null;
+ }
+ /**
+ * Creates and returns a web request which will simulate the submission of
+ * this form with a button with the specified name and value.
+ **/
+ public WebRequest getRequest(String submitButtonName,
+ String submitButtonValue) {
+ SubmitButton sb = getSubmitButton(submitButtonName, submitButtonValue);
+ if (sb == null)
+ throw new IllegalSubmitButtonException(submitButtonName,
+ submitButtonValue);
+ return getRequest(sb);
+ }
- /**
- * Returns the action defined for this form.
- **/
- public String getAction() {
- return getDestination();
- }
+ /**
+ * Creates and returns a web request which will simulate the submission of
+ * this form with a button with the specified name.
+ **/
+ public WebRequest getRequest(String submitButtonName) {
+ SubmitButton sb = getSubmitButton(submitButtonName);
+ if (sb == null)
+ throw new IllegalSubmitButtonException(submitButtonName, "");
+ return getRequest(sb);
+ }
+ /**
+ * Creates and returns a web request which will simulate the submission of
+ * this form by pressing the specified button. If the button is null,
+ * simulates the pressing of the default button.
+ **/
+ public WebRequest getRequest(SubmitButton button) {
+ return getRequest(button, 0, 0);
+ }
- /**
- * Returns true if a parameter with given name exists in this form.
- **/
- public boolean hasParameterNamed( String soughtName ) {
- return getFormParameters().containsKey( soughtName );
- }
+ /**
+ * Creates and returns a web request which will simulate the submission of
+ * this form by pressing the specified button. If the button is null,
+ * simulates the pressing of the default button.
+ *
+ * @param button
+ * - the submitbutton to be pressed - may be null
+ * @param x
+ * - the x position
+ * @param y
+ * - the y position
+ **/
+ public WebRequest getRequest(SubmitButton button, int x, int y) {
+ if (button == null)
+ button = getDefaultButton();
+ if (HttpUnitOptions.getParameterValuesValidated()) {
+ if (button == null) {
+ throw new IllegalUnnamedSubmitButtonException();
+ } else if (button.isFake()) {
+ // bypass checks
+ } else if (!getSubmitButtonVector().contains(button)) {
+ throw new IllegalSubmitButtonException(button);
+ } else if (!button.wasEnabled()) {
+ // this is too late for the check of isDisabled()
+ // onclick has already been done ...
+ // [ 1289151 ] Order of events in button.click() is wrong
+ button.throwDisabledException();
+ }
+ }
- /**
- * Returns true if a parameter starting with a given name exists,
- **/
- public boolean hasParameterStartingWithPrefix( String prefix ) {
- String[] names = getParameterNames();
- for (int i = 0; i < names.length; i++) {
- if (names[i].startsWith( prefix )) return true;
- }
- return false;
- }
+ SubmitButton[] buttons = getSubmitButtons();
+ for (int i = 0; i < buttons.length; i++) {
+ buttons[i].setPressed(false);
+ }
+ button.setPressed(true);
+ if (getMethod().equalsIgnoreCase("post")) {
+ return new PostMethodWebRequest(this, button, x, y);
+ } else {
+ return new GetMethodWebRequest(this,
+ WebRequest.newParameterHolder(this), button, x, y);
+ }
+ }
- /**
- * Returns an array containing all of the buttons defined for this form.
- **/
- public Button[] getButtons() {
- if (_buttons == null) {
- FormControl[] controls = getFormControls();
- ArrayList buttonList = new ArrayList();
- for (int i = 0; i < controls.length; i++) {
- FormControl control = controls[ i ];
- if (control instanceof Button) buttonList.add( control );
- }
- _buttons = (Button[]) buttonList.toArray( new Button[ buttonList.size() ] );
- }
- return _buttons;
- }
+ /**
+ * Creates and returns a web request which includes the specified button. If
+ * no button is specified, will include the default button, if any. No
+ * parameter validation will be done on the returned request and no scripts
+ * will be run when it is submitted.
+ **/
+ public WebRequest newUnvalidatedRequest(SubmitButton button) {
+ return newUnvalidatedRequest(button, 0, 0);
+ }
+ /**
+ * Creates and returns a web request which includes the specified button and
+ * position. If no button is specified, will include the default button, if
+ * any. No parameter validation will be done on the returned request and no
+ * scripts will be run when it is submitted.
+ **/
+ public WebRequest newUnvalidatedRequest(SubmitButton button, int x, int y) {
+ if (button == null)
+ button = getDefaultButton();
- public Button getButton( HTMLElementPredicate predicate, Object criteria ) {
- Button[] buttons = getButtons();
- for (int i = 0; i < buttons.length; i++) {
- if (predicate.matchesCriteria( buttons[i], criteria )) return buttons[i];
- }
- return null;
- }
+ SubmitButton[] buttons = getSubmitButtons();
+ for (int i = 0; i < buttons.length; i++) {
+ buttons[i].setPressed(false);
+ }
+ button.setPressed(true);
+ if (getMethod().equalsIgnoreCase("post")) {
+ return new PostMethodWebRequest(this, new UncheckedParameterHolder(
+ this), button, x, y);
+ } else {
+ return new GetMethodWebRequest(this, new UncheckedParameterHolder(
+ this), button, x, y);
+ }
+ }
- /**
- * Convenience method which returns the button with the specified ID.
- */
- public Button getButtonWithID( String buttonID ) {
- return getButton( Button.WITH_ID, buttonID );
- }
+ private WebRequest getScriptedSubmitRequest() {
+ SubmitButton[] buttons = getSubmitButtons();
+ for (int i = 0; i < buttons.length; i++) {
+ buttons[i].setPressed(false);
+ }
+ if (getMethod().equalsIgnoreCase("post")) {
+ return new PostMethodWebRequest(this);
+ } else {
+ return new GetMethodWebRequest(this);
+ }
- /**
- * Returns an array containing the submit buttons defined for this form.
- **/
- public SubmitButton[] getSubmitButtons() {
- if (_submitButtons == null) {
- Vector buttons = getSubmitButtonVector();
- _submitButtons = new SubmitButton[ buttons.size() ];
- buttons.copyInto( _submitButtons );
- }
- return _submitButtons;
- }
+ }
+ /**
+ * Returns the default value of the named parameter. If the parameter does
+ * not exist returns null.
+ **/
+ public String getParameterValue(String name) {
+ String[] values = getParameterValues(name);
+ return values.length == 0 ? null : values[0];
+ }
- /**
- * Returns the submit button defined in this form with the specified name.
- * If more than one such button exists, will return the first found.
- * If no such button is found, will return null.
- **/
- public SubmitButton getSubmitButton( String name ) {
- SubmitButton[] buttons = getSubmitButtons();
- for (int i = 0; i < buttons.length; i++) {
- if (buttons[i].getName().equals( name )) {
- return buttons[i];
- }
- }
- return null;
- }
+ /**
+ * Returns the displayed options defined for the specified parameter name.
+ **/
+ public String[] getOptions(String name) {
+ return getParameter(name).getOptions();
+ }
+ /**
+ * Returns the option values defined for the specified parameter name.
+ **/
+ public String[] getOptionValues(String name) {
+ return getParameter(name).getOptionValues();
+ }
- /**
- * Returns the submit button defined in this form with the specified name and value.
- * If more than one such button exists, will return the first found.
- * If no such button is found, will return null.
- **/
- public SubmitButton getSubmitButton( String name, String value ) {
- SubmitButton[] buttons = getSubmitButtons();
- for (int i = 0; i < buttons.length; i++) {
- if (buttons[i].getName().equals( name ) && buttons[i].getValue().equals( value )) {
- return buttons[i];
- }
- }
- return null;
- }
+ /**
+ * Returns true if the named parameter accepts multiple values.
+ **/
+ public boolean isMultiValuedParameter(String name) {
+ return getParameter(name).isMultiValuedParameter();
+ }
+ /**
+ * Returns the number of text parameters in this form with the specified
+ * name.
+ **/
+ public int getNumTextParameters(String name) {
+ return getParameter(name).getNumTextParameters();
+ }
- /**
- * Returns the submit button defined in this form with the specified ID.
- * If more than one such button exists, will return the first found.
- * If no such button is found, will return null.
- **/
- public SubmitButton getSubmitButtonWithID( String ID ) {
- SubmitButton[] buttons = getSubmitButtons();
- for (int i = 0; i < buttons.length; i++) {
- if (buttons[i].getID().equals( ID )) {
- return buttons[i];
- }
- }
- return null;
- }
+ /**
+ * Returns true if the named parameter accepts free-form text.
+ **/
+ public boolean isTextParameter(String name) {
+ return getParameter(name).isTextParameter();
+ }
+ /**
+ * Returns true if this form is to be submitted using mime encoding (the
+ * default is URL encoding).
+ **/
+ public boolean isSubmitAsMime() {
+ return "multipart/form-data".equalsIgnoreCase(getAttribute("enctype"));
+ }
- /**
- * Creates and returns a web request which will simulate the submission of this form with a button with the specified name and value.
- **/
- public WebRequest getRequest( String submitButtonName, String submitButtonValue ) {
- SubmitButton sb = getSubmitButton( submitButtonName, submitButtonValue );
- if (sb == null) throw new IllegalSubmitButtonException( submitButtonName, submitButtonValue );
- return getRequest( sb );
- }
+ public FormScriptable getScriptableObject() {
+ return (FormScriptable) getScriptingHandler();
+ }
+ /**
+ * Resets all parameters to their initial values.
+ */
+ public void reset() {
+ if (handleEvent("onreset"))
+ resetControls();
+ }
- /**
- * Creates and returns a web request which will simulate the submission of this form with a button with the specified name.
- **/
- public WebRequest getRequest( String submitButtonName ) {
- SubmitButton sb = getSubmitButton( submitButtonName );
- if (sb == null) throw new IllegalSubmitButtonException( submitButtonName, "" );
- return getRequest( sb );
- }
+ private void resetControls() {
+ FormControl[] controls = getFormControls();
+ for (int i = 0; i < controls.length; i++) {
+ controls[i].reset();
+ }
+ }
+ public ScriptableDelegate newScriptable() {
+ return new Scriptable();
+ }
- /**
- * Creates and returns a web request which will simulate the submission of this form by pressing the specified button.
- * If the button is null, simulates the pressing of the default button.
- **/
- public WebRequest getRequest( SubmitButton button ) {
- return getRequest( button, 0, 0 );
- }
+ // ---------------------------------- WebRequestSource methods
+ // --------------------------------
+ /**
+ * Returns the character set encoding for this form.
+ **/
+ public String getCharacterSet() {
+ return _characterSet;
+ }
- /**
- * Creates and returns a web request which will simulate the submission of this form by pressing the specified button.
- * If the button is null, simulates the pressing of the default button.
- * @param button - the submitbutton to be pressed - may be null
- * @param x - the x position
- * @param y - the y position
- **/
- public WebRequest getRequest( SubmitButton button, int x, int y ) {
- if (button == null)
- button = getDefaultButton();
+ /**
+ * Returns true if the named parameter accepts files for upload.
+ **/
+ public boolean isFileParameter(String name) {
+ return getParameter(name).isFileParameter();
+ }
- if (HttpUnitOptions.getParameterValuesValidated()) {
- if (button == null) {
- throw new IllegalUnnamedSubmitButtonException();
- } else if (button.isFake()) {
- // bypass checks
- } else if (!getSubmitButtonVector().contains( button )) {
- throw new IllegalSubmitButtonException( button );
- } else if (!button.wasEnabled()) {
- // this is too late for the check of isDisabled()
- // onclick has already been done ...
- // [ 1289151 ] Order of events in button.click() is wrong
- button.throwDisabledException();
- }
- }
+ /**
+ * Returns an array containing the names of the parameters defined for this
+ * form.
+ **/
+ public String[] getParameterNames() {
+ ArrayList parameterNames = new ArrayList(getFormParameters().keySet());
+ return (String[]) parameterNames.toArray(new String[parameterNames
+ .size()]);
+ }
- SubmitButton[] buttons = getSubmitButtons();
- for (int i = 0; i < buttons.length; i++) {
- buttons[i].setPressed( false );
- }
- button.setPressed( true );
+ /**
+ * Returns the multiple default values of the named parameter.
+ **/
+ public String[] getParameterValues(String name) {
+ final FormParameter parameter = getParameter(name);
+ return parameter.getValues();
+ }
- if (getMethod().equalsIgnoreCase( "post" )) {
- return new PostMethodWebRequest( this, button, x, y );
- } else {
- return new GetMethodWebRequest( this, WebRequest.newParameterHolder( this ), button, x, y );
- }
- }
+ /**
+ * Returns true if the named parameter is read-only. If more than one
+ * control exists with the same name, will return true only if all such
+ * controls are read-only.
+ **/
+ public boolean isReadOnlyParameter(String name) {
+ return getParameter(name).isReadOnlyParameter();
+ }
+ /**
+ * Returns true if the named parameter is disabled. If more than one control
+ * exists with the same name, will return true only if all such controls are
+ * read-only.
+ **/
+ public boolean isDisabledParameter(String name) {
+ return getParameter(name).isDisabledParameter();
+ }
- /**
- * Creates and returns a web request which includes the specified button. If no button is specified, will include
- * the default button, if any. No parameter validation will be done on the returned request and no scripts
- * will be run when it is submitted.
- **/
- public WebRequest newUnvalidatedRequest( SubmitButton button ) {
- return newUnvalidatedRequest( button, 0, 0 );
- }
+ /**
+ * Returns true if the named parameter is hidden. If more than one control
+ * exists with the same name, will return true only if all such controls are
+ * hidden.
+ **/
+ public boolean isHiddenParameter(String name) {
+ return getParameter(name).isHiddenParameter();
+ }
+ /**
+ * Creates and returns a web request which will simulate the submission of
+ * this form with an unnamed submit button.
+ **/
+ public WebRequest getRequest() {
+ return getRequest((SubmitButton) null);
+ }
- /**
- * Creates and returns a web request which includes the specified button and position. If no button is specified,
- * will include the default button, if any. No parameter validation will be done on the returned request
- * and no scripts will be run when it is submitted.
- **/
- public WebRequest newUnvalidatedRequest( SubmitButton button, int x, int y ) {
- if (button == null) button = getDefaultButton();
+ /**
+ * Creates and returns a web request based on the current state of this
+ * form. No parameter validation will be done and there is no guarantee over
+ * the order of parameters transmitted.
+ */
+ public WebRequest newUnvalidatedRequest() {
+ return newUnvalidatedRequest(null);
+ }
- SubmitButton[] buttons = getSubmitButtons();
- for (int i = 0; i < buttons.length; i++) {
- buttons[i].setPressed( false );
- }
- button.setPressed( true );
+ /**
+ * Records a parameter defined by including it in the destination URL.
+ * Ignores any parameters whose name matches a form control.
+ **/
+ protected void addPresetParameter(String name, String value) {
+ FormControl[] formControls = getFormControls();
+ for (int i = 0; i < formControls.length; i++) {
+ if (formControls[i].getName().equals(name))
+ return;
+ }
+ _presets.add(new PresetFormParameter(this, name, value));
+ }
- if (getMethod().equalsIgnoreCase( "post" )) {
- return new PostMethodWebRequest( this, new UncheckedParameterHolder( this ), button, x, y );
- } else {
- return new GetMethodWebRequest( this, new UncheckedParameterHolder( this ), button, x, y );
- }
- }
+ protected String getEmptyParameterValue() {
+ return null;
+ }
+ // ---------------------------------- ParameterHolder methods
+ // --------------------------------
- private WebRequest getScriptedSubmitRequest() {
- SubmitButton[] buttons = getSubmitButtons();
- for (int i = 0; i < buttons.length; i++) {
- buttons[i].setPressed( false );
- }
+ /**
+ * Specifies the position at which an image button (if any) was clicked.
+ **/
+ void selectImageButtonPosition(SubmitButton imageButton, int x, int y) {
+ imageButton.setLocation(x, y);
+ }
- if (getMethod().equalsIgnoreCase( "post" )) {
- return new PostMethodWebRequest( this );
- } else {
- return new GetMethodWebRequest( this );
- }
+ /**
+ * Iterates through the fixed, predefined parameters in this holder,
+ * recording them in the supplied parameter processor.\ These parameters
+ * always go on the URL, no matter what encoding method is used.
+ **/
- }
+ void recordPredefinedParameters(ParameterProcessor processor)
+ throws IOException {
+ FormControl[] controls = getPresetParameters();
+ for (int i = 0; i < controls.length; i++) {
+ controls[i].addValues(processor, getCharacterSet());
+ }
+ }
+ /**
+ * Iterates through the parameters in this holder, recording them in the
+ * supplied parameter processor.
+ **/
+ public void recordParameters(ParameterProcessor processor)
+ throws IOException {
+ FormControl[] controls = getFormControls();
+ for (int i = 0; i < controls.length; i++) {
+ controls[i].addValues(processor, getCharacterSet());
+ }
+ }
- /**
- * Returns the default value of the named parameter. If the parameter does not exist returns null.
- **/
- public String getParameterValue( String name ) {
- String[] values = getParameterValues( name );
- return values.length == 0 ? null : values[0];
- }
+ /**
+ * Removes a parameter name from this collection.
+ **/
+ public void removeParameter(String name) {
+ setParameter(name, NO_VALUES);
+ }
+ /**
+ * Sets the value of a parameter in this form.
+ *
+ * @param name
+ * - the name of the parameter
+ * @param value
+ * - the value of the parameter
+ **/
+ public void setParameter(String name, String value) {
+ setParameter(name, new String[] { value });
+ }
- /**
- * Returns the displayed options defined for the specified parameter name.
- **/
- public String[] getOptions( String name ) {
- return getParameter( name ).getOptions();
- }
+ /**
+ * Sets the multiple values of a parameter in this form. This is generally
+ * used when there are multiple controls with the same name in the form.
+ * @param name
+ * @param values
+ */
+ public void setParameter(String name, final String[] values) {
+ FormParameter parameter = getParameter(name);
+ if (parameter.isUnknown())
+ throw new NoSuchParameterException(name);
+ if (parameter.isFileParameter()) {
+ if (values == NO_VALUES) {
+ parameter.setFiles(new UploadFileSpec[0]);
+ } else {
+ throw new InvalidFileParameterException(name, values);
+ }
+ } else {
+ parameter.setValues(values);
+ }
+ }
- /**
- * Returns the option values defined for the specified parameter name.
- **/
- public String[] getOptionValues( String name ) {
- return getParameter( name ).getOptionValues();
- }
+ /**
+ * Sets the multiple values of a file upload parameter in a web request.
+ **/
+ public void setParameter(String name, UploadFileSpec[] files) {
+ FormParameter parameter = getParameter(name);
+ if ((parameter == null) || (!parameter.isFileParameter()))
+ throw new NoSuchParameterException(name);
+ parameter.setFiles(files);
+ }
+ /**
+ * Sets the single value of a file upload parameter in this form. A more
+ * convenient way to do this than using
+ * {@link #setParameter(String,com.meterware.httpunit.protocol.UploadFileSpec[])}
+ *
+ * @since 1.6
+ */
+ public void setParameter(String name, File file) {
+ setParameter(name, new UploadFileSpec[] { new UploadFileSpec(file) });
+ }
- /**
- * Returns true if the named parameter accepts multiple values.
- **/
- public boolean isMultiValuedParameter( String name ) {
- return getParameter( name ).isMultiValuedParameter();
- }
+ /**
+ * Toggles the value of the specified checkbox parameter.
+ *
+ * @param name
+ * the name of the checkbox parameter
+ * @throws IllegalArgumentException
+ * if the specified parameter is not a checkbox or there is more
+ * than one control with that name.
+ * @since 1.5.4
+ */
+ public void toggleCheckbox(String name) {
+ FormParameter parameter = getParameter(name);
+ if (parameter == null)
+ throw new NoSuchParameterException(name);
+ parameter.toggleCheckbox();
+ }
+ /**
+ * Toggles the value of the specified checkbox parameter.
+ *
+ * @param name
+ * the name of the checkbox parameter
+ * @param value
+ * of the checkbox parameter
+ * @throws IllegalArgumentException
+ * if the specified parameter is not a checkbox or if there is
+ * no checkbox with the specified name and value.
+ * @since 1.6
+ */
+ public void toggleCheckbox(String name, String value) {
+ FormParameter parameter = getParameter(name);
+ if (parameter == null)
+ throw new NoSuchParameterException(name);
+ parameter.toggleCheckbox(value);
+ }
- /**
- * Returns the number of text parameters in this form with the specified name.
- **/
- public int getNumTextParameters( String name ) {
- return getParameter( name ).getNumTextParameters();
- }
+ /**
+ * Sets the value of the specified checkbox parameter.
+ *
+ * @param name
+ * the name of the checkbox parameter
+ * @param state
+ * the new state of the checkbox
+ * @throws IllegalArgumentException
+ * if the specified parameter is not a checkbox or there is more
+ * than one control with that name.
+ * @since 1.5.4
+ */
+ public void setCheckbox(String name, boolean state) {
+ FormParameter parameter = getParameter(name);
+ if (parameter == null)
+ throw new NoSuchParameterException(name);
+ parameter.setValue(state);
+ }
+ /**
+ * Sets the value of the specified checkbox parameter.
+ *
+ * @param name
+ * the name of the checkbox parameter
+ * @param value
+ * of the checkbox parameter
+ * @param state
+ * the new state of the checkbox
+ * @throws IllegalArgumentException
+ * if the specified parameter is not a checkbox or if there is
+ * no checkbox with the specified name and value.
+ * @since 1.6
+ */
+ public void setCheckbox(String name, String value, boolean state) {
+ FormParameter parameter = getParameter(name);
+ if (parameter == null)
+ throw new NoSuchParameterException(name);
+ parameter.setValue(value, state);
+ }
- /**
- * Returns true if the named parameter accepts free-form text.
- **/
- public boolean isTextParameter( String name ) {
- return getParameter( name ).isTextParameter();
- }
+ /**
+ *
+ * Scriptable implementation for the WebForm
+ *
+ */
+ public class Scriptable extends HTMLElementScriptable implements
+ NamedDelegate, IdentifiedDelegate, FormScriptable {
+ public String getAction() {
+ return WebForm.this.getAction();
+ }
+ public void setAction(String newAction) {
+ setDestination(newAction);
+ _presetParameters = null;
+ }
- /**
- * Returns true if this form is to be submitted using mime encoding (the default is URL encoding).
- **/
- public boolean isSubmitAsMime() {
- return "multipart/form-data".equalsIgnoreCase( getAttribute( "enctype" ) );
- }
+ public void submit() throws IOException, SAXException {
+ submitRequest(getScriptedSubmitRequest());
+ }
+ public void reset() throws IOException, SAXException {
+ resetControls();
+ }
- public FormScriptable getScriptableObject() {
- return (FormScriptable) getScriptingHandler();
- }
+ /**
+ * return the name of the WebForm
+ *
+ * @return the name
+ */
+ public String getName() {
+ return WebForm.this.getName().length() != 0 ? WebForm.this
+ .getName() : WebForm.this.getID();
+ }
- /**
- * Resets all parameters to their initial values.
- */
- public void reset() {
- if (handleEvent("onreset"))
- resetControls();
- }
+ /**
+ * return the id of the WebForm
+ *
+ * @return the id
+ */
+ public String getID() {
+ return WebForm.this.getID();
+ }
+ /**
+ * get the Object for the given propertyName
+ *
+ * @param propertyName
+ * - the name of the property to get
+ * @return the Object for the property
+ */
+ public Object get(String propertyName) {
+ if (propertyName.equals("target")) {
+ return getTarget();
+ } else if (propertyName.equals("action")) {
+ return getAction();
+ } else if (propertyName.equals("length")) {
+ return new Integer(getFormControls().length);
+ } else {
+ final FormParameter parameter = getParameter(propertyName);
+ if (!parameter.isUnknown())
+ return parameter.getScriptableObject();
+ FormControl control = getControlWithID(propertyName);
+ return control == null ? super.get(propertyName) : control
+ .getScriptingHandler();
+ }
+ }
- private void resetControls() {
- FormControl[] controls = getFormControls();
- for (int i = 0; i < controls.length; i++) {
- controls[i].reset();
- }
- }
+ /**
+ * Sets the value of the named property. Will throw a runtime exception
+ * if the property does not exist or cannot accept the specified value.
+ *
+ * @param propertyName
+ * - the name of the property
+ * @param value
+ * - the new value
+ **/
+ public void set(String propertyName, Object value) {
+ if (propertyName.equals("target")) {
+ setTargetAttribute(value.toString());
+ } else if (propertyName.equals("action")) {
+ setAction(value.toString());
+ } else if (propertyName.equals("name")) {
+ getElement().setAttribute("name", value.toString());
+ } else if (value instanceof String) {
+ setParameterValue(propertyName, (String) value);
+ } else if (value instanceof Number) {
+ setParameterValue(propertyName,
+ HttpUnitUtils.trimmedValue((Number) value));
+ } else {
+ super.set(propertyName, value);
+ }
+ }
+ public void setParameterValue(String name, String value) {
+ final Object scriptableObject = getParameter(name)
+ .getScriptableObject();
+ if (scriptableObject instanceof ScriptableDelegate) {
+ ((ScriptableDelegate) scriptableObject).set("value", value);
+ } else if (scriptableObject instanceof ScriptableDelegate[]) {
+ ((ScriptableDelegate[]) scriptableObject)[0]
+ .set("value", value);
+ }
+ }
- public ScriptableDelegate newScriptable() {
- return new Scriptable();
- }
+ public ScriptableDelegate[] getElementDelegates() {
+ FormControl[] controls = getFormControls();
+ ScriptableDelegate[] result = new ScriptableDelegate[controls.length];
+ for (int i = 0; i < result.length; i++) {
+ result[i] = (ScriptableDelegate) controls[i]
+ .getScriptingHandler();
+ }
+ return result;
+ }
-//---------------------------------- WebRequestSource methods --------------------------------
+ public ScriptableDelegate[] getElementsByTagName(String name)
+ throws SAXException {
+ return getDelegates(getHTMLPage().getElementsByTagName(
+ getElement(), name));
+ }
- /**
- * Returns the character set encoding for this form.
- **/
- public String getCharacterSet() {
- return _characterSet;
- }
+ Scriptable() {
+ super(WebForm.this);
+ }
+ }
+ // ---------------------------------- package members
+ // --------------------------------
- /**
- * Returns true if the named parameter accepts files for upload.
- **/
- public boolean isFileParameter( String name ) {
- return getParameter( name ).isFileParameter();
- }
+ /**
+ * Contructs a web form given the URL of its source page and the DOM
+ * extracted from that page.
+ **/
+ WebForm(WebResponse response, URL baseURL, Node node, FrameSelector frame,
+ String defaultTarget, String characterSet, ElementRegistry registry) {
+ super(response, node, baseURL, "action", frame, defaultTarget);
+ _characterSet = characterSet;
+ _registry = registry;
+ _domElement = (HTMLFormElement) node;
+ }
+ /**
+ * Returns the form control which is part of this form with the specified
+ * ID.
+ */
+ public FormControl getControlWithID(String id) {
+ FormControl[] controls = getFormControls();
+ for (int i = 0; i < controls.length; i++) {
+ FormControl control = controls[i];
+ if (control.getID().equals(id))
+ return control;
+ }
+ return null;
+ }
- /**
- * Returns an array containing the names of the parameters defined for this form.
- **/
- public String[] getParameterNames() {
- ArrayList parameterNames = new ArrayList( getFormParameters().keySet() );
- return (String[]) parameterNames.toArray( new String[ parameterNames.size() ] );
- }
+ // ---------------------------------- private members
+ // --------------------------------
+ private SubmitButton getDefaultButton() {
+ if (getSubmitButtons().length == 1) {
+ return getSubmitButtons()[0];
+ } else {
+ return getSubmitButton("");
+ }
+ }
- /**
- * Returns the multiple default values of the named parameter.
- **/
- public String[] getParameterValues( String name ) {
- final FormParameter parameter = getParameter( name );
- return parameter.getValues();
- }
+ /**
+ * get the Vector of submit buttons - will always contain at least one
+ * button - if the original vector has none a faked submit button will be
+ * added
+ *
+ * @return a Vector with the submit buttons
+ */
+ private Vector getSubmitButtonVector() {
+ if (_buttonVector == null) {
+ _buttonVector = new Vector();
+ FormControl[] controls = getFormControls();
+ for (int i = 0; i < controls.length; i++) {
+ FormControl control = controls[i];
+ if (control instanceof SubmitButton) {
+ SubmitButton sb = (SubmitButton) control;
+ sb.rememberEnableState();
+ _buttonVector.add(sb);
+ }
+ }
+ /**
+ * make sure that there is always at least one submit button if none
+ * is in the Vector add a faked one
+ */
+ if (_buttonVector.isEmpty())
+ _buttonVector.addElement(SubmitButton
+ .createFakeSubmitButton(this));
+ }
+ return _buttonVector;
+ }
- /**
- * Returns true if the named parameter is read-only. If more than one control exists with the same name,
- * will return true only if all such controls are read-only.
- **/
- public boolean isReadOnlyParameter( String name ) {
- return getParameter( name ).isReadOnlyParameter();
- }
+ private FormControl[] getPresetParameters() {
+ if (_presetParameters == null) {
+ _presets = new ArrayList();
+ loadDestinationParameters();
+ _presetParameters = (FormControl[]) _presets
+ .toArray(new FormControl[_presets.size()]);
+ }
+ return _presetParameters;
+ }
+ FormControl newFormControl(Node child) {
+ return FormControl.newFormParameter(this, child);
+ }
- /**
- * Returns true if the named parameter is disabled. If more than one control exists with the same name,
- * will return true only if all such controls are read-only.
- **/
- public boolean isDisabledParameter( String name ) {
- return getParameter( name ).isDisabledParameter();
- }
+ /**
+ * Returns an array of form parameter attributes for this form.
+ **/
+ private FormControl[] getFormControls() {
+ HTMLCollection controlElements = _domElement.getElements();
+ FormControl[] controls = new FormControl[controlElements.getLength()];
+ for (int i = 0; i < controls.length; i++) {
+ controls[i] = getControlForNode(controlElements.item(i));
+ }
+ return controls;
+ }
+ private FormControl getControlForNode(Node node) {
+ if (_registry.hasNode(node)) {
+ return (FormControl) _registry.getRegisteredElement(node);
+ } else {
+ return (FormControl) _registry.registerElement(node,
+ newFormControl(node));
+ }
+ }
- /**
- * Returns true if the named parameter is hidden. If more than one control exists with the same name,
- * will return true only if all such controls are hidden.
- **/
- public boolean isHiddenParameter( String name ) {
- return getParameter( name ).isHiddenParameter();
- }
+ /**
+ * get the form parameter with the given name
+ *
+ * @param name
+ * @return the form parameter with this name
+ */
+ public FormParameter getParameter(String name) {
+ final FormParameter parameter = ((FormParameter) getFormParameters()
+ .get(name));
+ return parameter != null ? parameter : FormParameter
+ .getUNKNOWN_PARAMETER();
+ }
+ /**
+ * Returns a map of parameter name to form parameter objects. Each form
+ * parameter object represents the set of form controls with a particular
+ * name. Unnamed parameters are ignored.
+ */
+ private Map getFormParameters() {
+ Map formParameters = new HashMap();
+ loadFormParameters(formParameters, getPresetParameters());
+ loadFormParameters(formParameters, getFormControls());
+ return formParameters;
+ }
- /**
- * Creates and returns a web request which will simulate the submission of this form with an unnamed submit button.
- **/
- public WebRequest getRequest() {
- return getRequest( (SubmitButton) null );
- }
+ private void loadFormParameters(Map formParameters, FormControl[] controls) {
+ for (int i = 0; i < controls.length; i++) {
+ if (controls[i].getName().length() == 0)
+ continue;
+ FormParameter parameter = (FormParameter) formParameters
+ .get(controls[i].getName());
+ if (parameter == null) {
+ parameter = new FormParameter();
+ formParameters.put(controls[i].getName(), parameter);
+ }
+ parameter.addControl(controls[i]);
+ }
+ }
+ static {
+ MATCH_NAME = new HTMLElementPredicate() {
+ public boolean matchesCriteria(Object htmlElement, Object criteria) {
+ return HttpUnitUtils.matches(((WebForm) htmlElement).getName(),
+ (String) criteria);
+ }
+ };
- /**
- * Creates and returns a web request based on the current state of this form. No parameter validation will be done
- * and there is no guarantee over the order of parameters transmitted.
- */
- public WebRequest newUnvalidatedRequest() {
- return newUnvalidatedRequest( null );
- }
+ }
+ // ===========================---===== exception class
+ // NoSuchParameterException =========================================
- /**
- * Records a parameter defined by including it in the destination URL. Ignores any parameters whose name matches
- * a form control.
- **/
- protected void addPresetParameter( String name, String value ) {
- FormControl[] formControls = getFormControls();
- for (int i = 0; i < formControls.length; i++) {
- if (formControls[i].getName().equals( name)) return;
- }
- _presets.add( new PresetFormParameter( this, name, value ) );
- }
+ /**
+ * This exception is thrown on an attempt to set a file parameter to a non
+ * file type
+ **/
+ class InvalidFileParameterException extends
+ IllegalRequestParameterException {
+ /**
+ * construct a new InvalidFileParameterException for the given parameter
+ * name and value list
+ *
+ * @param parameterName
+ * @param values
+ */
+ InvalidFileParameterException(String parameterName, String[] values) {
+ _parameterName = parameterName;
+ _values = values;
+ }
- protected String getEmptyParameterValue() {
- return null;
- }
+ /**
+ * get the message for this exception
+ */
+ public String getMessage() {
+ String valueList = "";
+ String delim = "";
+ for (int i = 0; i < _values.length; i++) {
+ valueList += delim + "'" + _values[i] + "'";
+ delim = ", ";
+ }
+ String msg = "The file parameter with the name '" + _parameterName
+ + "' must have type File but the string values "
+ + valueList + " where supplied";
+ return msg;
+ }
+ private String _parameterName;
+ private String[] _values;
+ }
-//---------------------------------- ParameterHolder methods --------------------------------
+ /**
+ * This exception is thrown on an attempt to set a parameter to a value not
+ * permitted to it by the form.
+ **/
+ class NoSuchParameterException extends IllegalRequestParameterException {
+ NoSuchParameterException(String parameterName) {
+ _parameterName = parameterName;
+ }
- /**
- * Specifies the position at which an image button (if any) was clicked.
- **/
- void selectImageButtonPosition( SubmitButton imageButton, int x, int y ) {
- imageButton.setLocation( x, y );
- }
+ public String getMessage() {
+ return "No parameter named '" + _parameterName
+ + "' is defined in the form";
+ }
+ private String _parameterName;
- /**
- * Iterates through the fixed, predefined parameters in this holder, recording them in the supplied parameter processor.\
- * These parameters always go on the URL, no matter what encoding method is used.
- **/
+ }
- void recordPredefinedParameters( ParameterProcessor processor ) throws IOException {
- FormControl[] controls = getPresetParameters();
- for (int i = 0; i < controls.length; i++) {
- controls[i].addValues( processor, getCharacterSet() );
- }
- }
+ // ============================= exception class
+ // IllegalUnnamedSubmitButtonException
+ // ======================================
+ /**
+ * This exception is thrown on an attempt to define a form request with a
+ * button not defined on that form.
+ **/
+ class IllegalUnnamedSubmitButtonException extends
+ IllegalRequestParameterException {
- /**
- * Iterates through the parameters in this holder, recording them in the supplied parameter processor.
- **/
- public void recordParameters( ParameterProcessor processor ) throws IOException {
- FormControl[] controls = getFormControls();
- for (int i = 0; i < controls.length; i++) {
- controls[i].addValues( processor, getCharacterSet() );
- }
- }
+ IllegalUnnamedSubmitButtonException() {
+ }
+ public String getMessage() {
+ return "This form has more than one submit button, none unnamed. You must specify the button to be used.";
+ }
- /**
- * Removes a parameter name from this collection.
- **/
- public void removeParameter( String name ) {
- setParameter( name, NO_VALUES );
- }
+ }
+ // ============================= exception class
+ // IllegalSubmitButtonException ======================================
- /**
- * Sets the value of a parameter in this form.
- * @param name - the name of the parameter
- * @param value - the value of the parameter
- **/
- public void setParameter( String name, String value ) {
- setParameter( name, new String[] { value } );
- }
+ /**
+ * This exception is thrown on an attempt to define a form request with a
+ * button not defined on that form.
+ **/
+ class IllegalSubmitButtonException extends IllegalRequestParameterException {
+ IllegalSubmitButtonException(SubmitButton button) {
+ _name = button.getName();
+ _value = button.getValue();
+ }
- /**
- * Sets the multiple values of a parameter in this form. This is generally used when there are multiple
- * controls with the same name in the form.
- */
- public void setParameter( String name, final String[] values ) {
- FormParameter parameter = getParameter( name );
- if (parameter.isUnknown()) throw new NoSuchParameterException( name );
- if (parameter.isFileParameter()) {
- throw new InvalidFileParameterException(name,values);
- }
- parameter.setValues( values );
- }
+ IllegalSubmitButtonException(String name, String value) {
+ _name = name;
+ _value = value;
+ }
+ public String getMessage() {
+ return "Specified submit button (name=\"" + _name + "\" value=\""
+ + _value + "\") not part of this form.";
+ }
- /**
- * Sets the multiple values of a file upload parameter in a web request.
- **/
- public void setParameter( String name, UploadFileSpec[] files ) {
- FormParameter parameter = getParameter( name );
- if ((parameter == null) || (!parameter.isFileParameter()))
- throw new NoSuchParameterException( name );
- parameter.setFiles( files );
- }
+ private String _name;
+ private String _value;
+ }
- /**
- * Sets the single value of a file upload parameter in this form.
- * A more convenient way to do this than using {@link #setParameter(String,com.meterware.httpunit.protocol.UploadFileSpec[])}
- * @since 1.6
- */
- public void setParameter( String name, File file ) {
- setParameter( name, new UploadFileSpec[] { new UploadFileSpec( file ) } );
- }
+ // ============================= exception class
+ // IllegalUnnamedSubmitButtonException
+ // ======================================
+}
- /**
- * Toggles the value of the specified checkbox parameter.
- * @param name the name of the checkbox parameter
- * @throws IllegalArgumentException if the specified parameter is not a checkbox or there is more than one
- * control with that name.
- * @since 1.5.4
- */
- public void toggleCheckbox( String name ) {
- FormParameter parameter = getParameter( name );
- if (parameter == null) throw new NoSuchParameterException( name );
- parameter.toggleCheckbox();
- }
+// ========================================== class PresetFormParameter
+// =================================================
+class PresetFormParameter extends FormControl {
- /**
- * Toggles the value of the specified checkbox parameter.
- * @param name the name of the checkbox parameter
- * @param value of the checkbox parameter
- * @throws IllegalArgumentException if the specified parameter is not a checkbox or if there is no checkbox
- * with the specified name and value.
- * @since 1.6
- */
- public void toggleCheckbox( String name, String value ) {
- FormParameter parameter = getParameter( name );
- if (parameter == null) throw new NoSuchParameterException( name );
- parameter.toggleCheckbox( value );
- }
+ PresetFormParameter(WebForm form, String name, String value) {
+ super(form);
+ _name = name;
+ _value = value;
+ }
+ /**
+ * Returns the name of this control..
+ **/
+ public String getName() {
+ return _name;
+ }
- /**
- * Sets the value of the specified checkbox parameter.
- * @param name the name of the checkbox parameter
- * @param state the new state of the checkbox
- * @throws IllegalArgumentException if the specified parameter is not a checkbox or there is more than one
- * control with that name.
- * @since 1.5.4
- */
- public void setCheckbox( String name, boolean state ) {
- FormParameter parameter = getParameter( name );
- if (parameter == null) throw new NoSuchParameterException( name );
- parameter.setValue( state );
- }
+ /**
+ * Returns true if this control is read-only.
+ **/
+ public boolean isReadOnly() {
+ return true;
+ }
+ /**
+ * Returns true if this control accepts free-form text.
+ **/
+ public boolean isTextControl() {
+ return true;
+ }
- /**
- * Sets the value of the specified checkbox parameter.
- * @param name the name of the checkbox parameter
- * @param value of the checkbox parameter
- * @param state the new state of the checkbox
- * @throws IllegalArgumentException if the specified parameter is not a checkbox or if there is no checkbox
- * with the specified name and value.
- * @since 1.6
- */
- public void setCheckbox( String name, String value, boolean state ) {
- FormParameter parameter = getParameter( name );
- if (parameter == null) throw new NoSuchParameterException( name );
- parameter.setValue( value, state );
- }
+ /**
+ * Remove any required values for this control from the list, throwing an
+ * exception if they are missing.
+ **/
+ void claimRequiredValues(List values) {
+ if (_value != null)
+ claimValueIsRequired(values, _value);
+ }
+ public String getType() {
+ return UNDEFINED_TYPE;
+ }
- /**
- *
- * Scriptable implementation for the WebForm
- ...
[truncated message content] |
|
From: <wol...@us...> - 2012-09-12 15:55:56
|
Revision: 1088
http://httpunit.svn.sourceforge.net/httpunit/?rev=1088&view=rev
Author: wolfgang_fahl
Date: 2012-09-12 15:55:44 +0000 (Wed, 12 Sep 2012)
Log Message:
-----------
modified for BR 2825872 Cookie domains not stored correctly - ID: 2825872
by aptivate
Modified Paths:
--------------
trunk/httpunit/src/main/java/com/meterware/httpunit/cookies/CookieJar.java
trunk/httpunit/src/test/java/com/meterware/httpunit/cookies/CookieTest.java
Modified: trunk/httpunit/src/main/java/com/meterware/httpunit/cookies/CookieJar.java
===================================================================
--- trunk/httpunit/src/main/java/com/meterware/httpunit/cookies/CookieJar.java 2012-09-12 13:26:44 UTC (rev 1087)
+++ trunk/httpunit/src/main/java/com/meterware/httpunit/cookies/CookieJar.java 2012-09-12 15:55:44 UTC (rev 1088)
@@ -1,8 +1,9 @@
package com.meterware.httpunit.cookies;
+
/********************************************************************************************************************
* $Id$
*
- * Copyright (c) 2002-2004,2008, Russell Gold
+ * Copyright (c) 2002-2004,2008,2012 Russell Gold
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
@@ -25,586 +26,620 @@
import java.net.URL;
import java.util.*;
-
/**
- * A collection of HTTP cookies, which can interact with cookie and set-cookie header values.
- *
+ * A collection of HTTP cookies, which can interact with cookie and set-cookie
+ * header values.
+ *
* @author <a href="mailto:rus...@ht...">Russell Gold</a>
* @author <a href="mailto:dre...@or...">Drew Varner</a>
**/
public class CookieJar {
- private static final int DEFAULT_HEADER_SIZE = 80;
+ private static final int DEFAULT_HEADER_SIZE = 80;
- private ArrayList _cookies = new ArrayList();
- private ArrayList _globalCookies = new ArrayList();
- private CookiePress _press;
+ private ArrayList _cookies = new ArrayList();
+ private ArrayList _globalCookies = new ArrayList();
+ private CookiePress _press;
+ /**
+ * Creates an empty cookie jar.
+ */
+ public CookieJar() {
+ _press = new CookiePress(null);
+ }
- /**
- * Creates an empty cookie jar.
- */
- public CookieJar() {
- _press = new CookiePress( null );
- }
+ /**
+ * Creates a cookie jar which is initially populated with cookies parsed
+ * from the <code>Set-Cookie</code> and <code>Set-Cookie2</code> header
+ * fields.
+ * <p>
+ * Note that the parsing does not strictly follow the specifications, but
+ * attempts to imitate the behavior of popular browsers. Specifically, it
+ * allows cookie values to contain commas, which the Netscape standard does
+ * not allow for, but which is required by some servers.
+ * </p>
+ */
+ public CookieJar(CookieSource source) {
+ _press = new CookiePress(source.getURL());
+ findCookies(source.getHeaderFields("Set-Cookie"),
+ new RFC2109CookieRecipe());
+ findCookies(source.getHeaderFields("Set-Cookie2"),
+ new RFC2965CookieRecipe());
+ }
+ /**
+ * find the cookies in the given Header String array
+ *
+ * @param cookieHeader
+ * - the strings to look for cookies
+ * @param recipe
+ * - the recipe to use
+ */
+ private void findCookies(String cookieHeader[], CookieRecipe recipe) {
+ for (int i = 0; i < cookieHeader.length; i++) {
+ recipe.findCookies(cookieHeader[i]);
+ }
+ }
- /**
- * Creates a cookie jar which is initially populated with cookies parsed from the <code>Set-Cookie</code> and
- * <code>Set-Cookie2</code> header fields.
- * <p>
- * Note that the parsing does not strictly follow the specifications, but
- * attempts to imitate the behavior of popular browsers. Specifically,
- * it allows cookie values to contain commas, which the
- * Netscape standard does not allow for, but which is required by some servers.
- * </p>
- */
- public CookieJar( CookieSource source ) {
- _press = new CookiePress( source.getURL() );
- findCookies( source.getHeaderFields( "Set-Cookie" ), new RFC2109CookieRecipe() );
- findCookies( source.getHeaderFields( "Set-Cookie2" ), new RFC2965CookieRecipe() );
- }
+ /**
+ * Empties this cookie jar of all contents.
+ */
+ public void clear() {
+ _cookies.clear();
+ _globalCookies.clear();
+ }
+ /**
+ * Defines a cookie to be sent to the server on every request. This bypasses
+ * the normal mechanism by which only certain cookies are sent based on
+ * their host and path.
+ *
+ * @deprecated as of 1.6, use #putCookie
+ **/
+ public void addCookie(String name, String value) {
+ _globalCookies.add(new Cookie(name, value));
+ }
- /**
- * find the cookies in the given Header String array
- * @param cookieHeader - the strings to look for cookies
- * @param recipe - the recipe to use
- */
- private void findCookies( String cookieHeader[], CookieRecipe recipe ) {
- for (int i = 0; i < cookieHeader.length; i++) {
- recipe.findCookies( cookieHeader[i] );
- }
- }
+ /**
+ * Defines a cookie to be sent to the server on every request. This bypasses
+ * the normal mechanism by which only certain cookies are sent based on
+ * their host and path.
+ *
+ * Values of null will result in the cookie being removed. Any other value
+ * will leave the cookie unchanged expect for the value.
+ *
+ * @since 1.6
+ **/
+ public void putCookie(String name, String value) {
+ boolean foundCookie = false;
+ for (Iterator iterator = _globalCookies.iterator(); iterator.hasNext();) {
+ Cookie cookie = (Cookie) iterator.next();
+ if (name.equals(cookie.getName())) {
+ foundCookie = true;
+ if (value != null) {
+ cookie.setValue(value);
+ } else {
+ iterator.remove();
+ }
+ }
+ }
+ for (Iterator iterator = _cookies.iterator(); iterator.hasNext();) {
+ Cookie cookie = (Cookie) iterator.next();
+ if (name.equals(cookie.getName())) {
+ foundCookie = true;
+ if (value != null) {
+ cookie.setValue(value);
+ } else {
+ iterator.remove();
+ }
+ }
+ }
- /**
- * Empties this cookie jar of all contents.
- */
- public void clear() {
- _cookies.clear();
- _globalCookies.clear();
- }
+ // only add it if it does not already exist
+ if (foundCookie == false) {
+ _globalCookies.add(new Cookie(name, value));
+ }
+ }
+ /**
+ * Define a non-global cookie. This cookie can be overwritten by subsequent
+ * cookie definitions in http headers. This cookie definition requires a
+ * domain and path. If a global cookie is defined with the same name, this
+ * cookie is not added.
+ */
+ public void putSingleUseCookie(String name, String value, String domain,
+ String path) {
+ for (Iterator iterator = _globalCookies.iterator(); iterator.hasNext();) {
+ Cookie cookie = (Cookie) iterator.next();
+ if (name.equals(cookie.getName()))
+ return;
+ }
- /**
- * Defines a cookie to be sent to the server on every request. This bypasses the normal mechanism by which only
- * certain cookies are sent based on their host and path.
- * @deprecated as of 1.6, use #putCookie
- **/
- public void addCookie( String name, String value ) {
- _globalCookies.add( new Cookie( name, value ) );
- }
+ for (Iterator iterator = _cookies.iterator(); iterator.hasNext();) {
+ Cookie cookie = (Cookie) iterator.next();
+ if (name.equals(cookie.getName()))
+ iterator.remove();
+ }
+ _cookies.add(new Cookie(name, value, domain, path));
+ }
- /**
- * Defines a cookie to be sent to the server on every request. This bypasses the normal mechanism by which only
- * certain cookies are sent based on their host and path.
- *
- * Values of null will result in the cookie being removed. Any other value will leave the
- * cookie unchanged expect for the value.
- *
- * @since 1.6
- **/
- public void putCookie( String name, String value ) {
- boolean foundCookie = false;
- for (Iterator iterator = _globalCookies.iterator(); iterator.hasNext();) {
- Cookie cookie = (Cookie) iterator.next();
- if (name.equals( cookie.getName() )) {
- foundCookie = true;
- if (value != null) {
- cookie.setValue(value);
- } else {
- iterator.remove();
- }
- }
- }
-
- for (Iterator iterator = _cookies.iterator(); iterator.hasNext();) {
- Cookie cookie = (Cookie) iterator.next();
- if (name.equals( cookie.getName() )) {
- foundCookie = true;
- if (value != null) {
- cookie.setValue(value);
- } else {
- iterator.remove();
- }
- }
- }
-
- // only add it if it does not already exist
- if (foundCookie == false) {
- _globalCookies.add( new Cookie( name, value ) );
- }
- }
+ /**
+ * Returns the name of all the active cookies in this cookie jar.
+ **/
+ public String[] getCookieNames() {
+ final int numGlobalCookies = _globalCookies.size();
+ String[] names = new String[_cookies.size() + numGlobalCookies];
+ for (int i = 0; i < numGlobalCookies; i++) {
+ names[i] = ((Cookie) _globalCookies.get(i)).getName();
+ }
+ for (int i = numGlobalCookies; i < names.length; i++) {
+ names[i] = ((Cookie) _cookies.get(i - numGlobalCookies)).getName();
+ }
+ return names;
+ }
- /**
- * Define a non-global cookie. This cookie can be overwritten by subsequent cookie definitions
- * in http headers. This cookie definition requires a domain and path. If a global cookie is
- * defined with the same name, this cookie is not added.
- */
- public void putSingleUseCookie(String name, String value, String domain, String path) {
- for (Iterator iterator = _globalCookies.iterator(); iterator.hasNext();) {
- Cookie cookie = (Cookie) iterator.next();
- if (name.equals( cookie.getName() )) return;
- }
-
- for (Iterator iterator = _cookies.iterator(); iterator.hasNext();) {
- Cookie cookie = (Cookie) iterator.next();
- if (name.equals( cookie.getName() )) iterator.remove();
- }
-
- _cookies.add( new Cookie( name, value, domain, path) );
- }
-
- /**
- * Returns the name of all the active cookies in this cookie jar.
- **/
- public String[] getCookieNames() {
- final int numGlobalCookies = _globalCookies.size();
- String[] names = new String[ _cookies.size() + numGlobalCookies ];
- for (int i = 0; i < numGlobalCookies; i++) {
- names[i] = ((Cookie) _globalCookies.get(i)).getName();
- }
- for (int i = numGlobalCookies; i < names.length; i++) {
- names[i] = ((Cookie) _cookies.get( i-numGlobalCookies )).getName();
- }
- return names;
- }
+ /**
+ * Returns a collection containing all of the cookies in this jar.
+ */
+ public Collection getCookies() {
+ final Collection collection = (Collection) _cookies.clone();
+ collection.addAll(_globalCookies);
+ return collection;
+ }
+ /**
+ * Returns the value of the specified cookie.
+ *
+ * @param name
+ * - the name of the cookie to get the value for
+ * @return the value of the cookie
+ **/
+ public String getCookieValue(String name) {
+ Cookie cookie = getCookie(name);
+ return cookie == null ? null : cookie.getValue();
+ }
- /**
- * Returns a collection containing all of the cookies in this jar.
- */
- public Collection getCookies() {
- final Collection collection = (Collection) _cookies.clone();
- collection.addAll( _globalCookies );
- return collection;
- }
+ /**
+ * Returns the value of the specified cookie.
+ **/
+ public Cookie getCookie(String name) {
+ if (name == null)
+ throw new IllegalArgumentException(
+ "getCookieValue: no name specified");
+ for (Iterator iterator = _cookies.iterator(); iterator.hasNext();) {
+ Cookie cookie = (Cookie) iterator.next();
+ if (name.equals(cookie.getName()))
+ return cookie;
+ }
+ for (Iterator iterator = _globalCookies.iterator(); iterator.hasNext();) {
+ Cookie cookie = (Cookie) iterator.next();
+ if (name.equals(cookie.getName()))
+ return cookie;
+ }
+ return null;
+ }
+ /**
+ * Returns the value of the cookie header to be sent to the specified URL.
+ * Will return null if no compatible cookie is defined.
+ **/
+ public String getCookieHeaderField(URL targetURL) {
+ if (_cookies.isEmpty() && _globalCookies.isEmpty())
+ return null;
+ StringBuffer sb = new StringBuffer(DEFAULT_HEADER_SIZE);
+ HashSet restrictedCookies = new HashSet();
+ for (Iterator i = _cookies.iterator(); i.hasNext();) {
+ Cookie cookie = (Cookie) i.next();
+ if (!cookie.mayBeSentTo(targetURL))
+ continue;
+ restrictedCookies.add(cookie.getName());
+ if (sb.length() != 0)
+ sb.append("; ");
+ sb.append(cookie.getName()).append('=').append(cookie.getValue());
+ }
+ for (Iterator i = _globalCookies.iterator(); i.hasNext();) {
+ Cookie cookie = (Cookie) i.next();
+ if (restrictedCookies.contains(cookie.getName()))
+ continue;
+ if (sb.length() != 0)
+ sb.append("; ");
+ sb.append(cookie.getName()).append('=').append(cookie.getValue());
+ }
+ return sb.length() == 0 ? null : sb.toString();
+ }
- /**
- * Returns the value of the specified cookie.
- * @param name - the name of the cookie to get the value for
- * @return the value of the cookie
- **/
- public String getCookieValue( String name ) {
- Cookie cookie = getCookie( name );
- return cookie == null ? null : cookie.getValue();
- }
+ /**
+ * Updates the cookies maintained in this cookie jar with those in another
+ * cookie jar. Any duplicate cookies in the new jar will replace those in
+ * this jar.
+ **/
+ public void updateCookies(CookieJar newJar) {
+ for (Iterator i = newJar._cookies.iterator(); i.hasNext();) {
+ addUniqueCookie((Cookie) i.next());
+ }
+ }
+ /**
+ * Add the cookie to this jar, replacing any previous matching cookie.
+ */
+ void addUniqueCookie(Cookie cookie) {
+ _cookies.remove(cookie);
+ for (Iterator i = _cookies.iterator(); i.hasNext();) {
+ Cookie c = (Cookie) i.next();
+ if (c.getName().equals(cookie.getName())) {
+ if (compareDomain(c.getDomain(), cookie.getDomain())) {
+ if (c.getPath() != null && cookie.getPath() != null
+ && c.getPath().equals(cookie.getPath())) {
+ i.remove();
+ }
+ }
+ }
+ }
+ _cookies.add(cookie);
+ }
- /**
- * Returns the value of the specified cookie.
- **/
- public Cookie getCookie( String name ) {
- if (name == null) throw new IllegalArgumentException( "getCookieValue: no name specified" );
- for (Iterator iterator = _cookies.iterator(); iterator.hasNext();) {
- Cookie cookie = (Cookie) iterator.next();
- if (name.equals( cookie.getName() )) return cookie;
- }
- for (Iterator iterator = _globalCookies.iterator(); iterator.hasNext();) {
- Cookie cookie = (Cookie) iterator.next();
- if (name.equals( cookie.getName() )) return cookie;
- }
- return null;
- }
+ /**
+ * compare the two domains given for "cookie-equality"
+ *
+ * @param domain
+ * @param newDomain
+ * @return
+ */
+ private boolean compareDomain(String domain, String newDomain) {
+ if (domain.charAt(0) == '.' && newDomain.endsWith(domain)) {
+ return true;
+ }
+ if (newDomain.charAt(0) == '.' && domain.endsWith(newDomain)) {
+ return true;
+ }
+ return domain.equals(newDomain);
+ }
- /**
- * Returns the value of the cookie header to be sent to the specified URL.
- * Will return null if no compatible cookie is defined.
- **/
- public String getCookieHeaderField( URL targetURL ) {
- if (_cookies.isEmpty() && _globalCookies.isEmpty()) return null;
- StringBuffer sb = new StringBuffer( DEFAULT_HEADER_SIZE );
- HashSet restrictedCookies = new HashSet();
- for (Iterator i = _cookies.iterator(); i.hasNext();) {
- Cookie cookie = (Cookie) i.next();
- if (!cookie.mayBeSentTo( targetURL )) continue;
- restrictedCookies.add( cookie.getName() );
- if (sb.length() != 0) sb.append( "; " );
- sb.append( cookie.getName() ).append( '=' ).append( cookie.getValue() );
- }
- for (Iterator i = _globalCookies.iterator(); i.hasNext();) {
- Cookie cookie = (Cookie) i.next();
- if (restrictedCookies.contains( cookie.getName() )) continue;
- if (sb.length() != 0) sb.append( "; " );
- sb.append( cookie.getName() ).append( '=' ).append( cookie.getValue() );
- }
- return sb.length() == 0 ? null : sb.toString();
- }
+ /**
+ * base class for the cookie recipies - there are two different
+ * implementations of this
+ */
+ abstract class CookieRecipe {
+ /**
+ * Extracts cookies from a cookie header. Works in conjunction with a
+ * cookie press class, which actually creates the cookies and adds them
+ * to the jar as appropriate.
+ *
+ * 1. Parse the header into tokens, separated by ',' and ';' (respecting
+ * single and double quotes) 2. Process tokens from the end: a. if the
+ * token contains an '=' we have a name/value pair. Add them to the
+ * cookie press, which will decide if it is a cookie name or an
+ * attribute name. b. if the token is a reserved word, flush the cookie
+ * press and continue. c. otherwise, add the token to the cookie press,
+ * passing along the last character of the previous token.
+ */
+ void findCookies(String cookieHeader) {
+ Vector tokens = getCookieTokens(cookieHeader);
- /**
- * Updates the cookies maintained in this cookie jar with those in another cookie jar. Any duplicate cookies in
- * the new jar will replace those in this jar.
- **/
- public void updateCookies( CookieJar newJar ) {
- for (Iterator i = newJar._cookies.iterator(); i.hasNext();) {
- addUniqueCookie( (Cookie) i.next() );
- }
- }
+ for (int i = tokens.size() - 1; i >= 0; i--) {
+ String token = (String) tokens.elementAt(i);
+ int equalsIndex = getEqualsIndex(token);
+ if (equalsIndex != -1) {
+ _press.addTokenWithEqualsSign(this, token, equalsIndex);
+ } else if (isCookieReservedWord(token)) {
+ _press.clear();
+ } else {
+ _press.addToken(token, lastCharOf((i == 0) ? ""
+ : (String) tokens.elementAt(i - 1)));
+ }
+ }
+ }
- /**
- * Add the cookie to this jar, replacing any previous matching cookie.
- */
- void addUniqueCookie( Cookie cookie ) {
- _cookies.remove( cookie );
- for (Iterator i = _cookies.iterator(); i.hasNext();) {
- Cookie c = (Cookie) i.next();
- if (c.getName().equals(cookie.getName())) {
- if (compareDomain(c.getDomain(), cookie.getDomain())) {
- if (c.getPath() != null && cookie.getPath() != null
- && c.getPath().equals(cookie.getPath())) {
- i.remove();
- }
- }
- }
- }
- _cookies.add( cookie );
- }
+ private char lastCharOf(String string) {
+ return (string.length() == 0) ? ' ' : string
+ .charAt(string.length() - 1);
+ }
- /**
- * compare the two domains given for "cookie-equality"
- *
- * @param domain
- * @param newDomain
- * @return
+ /**
+ * Returns the index (if any) of the equals sign separating a cookie
+ * name from the its value. Equals signs at the end of the token are
+ * ignored in this calculation, since they may be part of a
+ * Base64-encoded value.
*/
- private boolean compareDomain(String domain, String newDomain) {
- if (domain.charAt(0) == '.' && newDomain.endsWith(domain)) {
- return true;
+ private int getEqualsIndex(String token) {
+ if (!token.endsWith("==")) {
+ return token.indexOf('=');
+ } else {
+ return getEqualsIndex(token.substring(0, token.length() - 2));
}
- if (newDomain.charAt(0) == '.' && domain.endsWith(newDomain)) {
- return true;
- }
-
- return domain.equals(newDomain);
}
- /**
- * base class for the cookie recipies - there are two different
- * implementations of this
- */
- abstract class CookieRecipe {
+ /**
+ * Tokenizes a cookie header and returns the tokens in a
+ * <code>Vector</code>. handles the broken syntax for expires= fields
+ * ...
+ *
+ * @param cookieHeader
+ * - the header to read
+ * @return a Vector of cookieTokens as name=value pairs
+ **/
+ private Vector getCookieTokens(String cookieHeader) {
+ StringReader sr = new StringReader(cookieHeader);
+ StreamTokenizer st = new StreamTokenizer(sr);
+ Vector tokens = new Vector();
- /**
- * Extracts cookies from a cookie header. Works in conjunction with a cookie press class, which actually creates
- * the cookies and adds them to the jar as appropriate.
- *
- * 1. Parse the header into tokens, separated by ',' and ';' (respecting single and double quotes)
- * 2. Process tokens from the end:
- * a. if the token contains an '=' we have a name/value pair. Add them to the cookie press, which
- * will decide if it is a cookie name or an attribute name.
- * b. if the token is a reserved word, flush the cookie press and continue.
- * c. otherwise, add the token to the cookie press, passing along the last character of the previous token.
- */
- void findCookies( String cookieHeader ) {
- Vector tokens = getCookieTokens( cookieHeader );
+ // clear syntax tables of the StreamTokenizer
+ st.resetSyntax();
- for (int i = tokens.size() - 1; i >= 0; i--) {
- String token = (String) tokens.elementAt( i );
+ // set all characters as word characters
+ st.wordChars(0, Character.MAX_VALUE);
- int equalsIndex = getEqualsIndex( token );
- if (equalsIndex != -1) {
- _press.addTokenWithEqualsSign( this, token, equalsIndex );
- } else if (isCookieReservedWord( token )) {
- _press.clear();
- } else {
- _press.addToken( token, lastCharOf( (i == 0) ? "" : (String) tokens.elementAt( i - 1 ) ) );
- }
- }
- }
+ // set up characters for quoting
+ st.quoteChar('"'); // double quotes
+ st.quoteChar('\''); // single quotes
+ // set up characters to separate tokens
+ st.whitespaceChars(59, 59); // semicolon
+ // and here we run into trouble ...
+ // see http://www.mnot.net/blog/2006/10/27/cookie_fun
+ // ... Notice something about the above? It uses a comma inside of
+ // the date,
+ // without quoting the value. This makes it difficult for generic
+ // processors to handle the Set-Cookie header.
+ st.whitespaceChars(44, 44); // comma
- private char lastCharOf( String string ) {
- return (string.length() == 0) ? ' ' : string.charAt( string.length()-1 );
- }
+ try {
+ while (st.nextToken() != StreamTokenizer.TT_EOF) {
+ String tokenContent = st.sval;
+ // fix expires comma delimiter token problem
+ if (tokenContent.toLowerCase().startsWith("expires=")) {
+ if (st.nextToken() != StreamTokenizer.TT_EOF) {
+ tokenContent += "," + st.sval;
+ } // if
+ } // if
+ tokenContent = tokenContent.trim();
+ tokens.addElement(tokenContent);
+ }
+ } catch (IOException ioe) {
+ // this will never happen with a StringReader
+ }
+ sr.close();
+ return tokens;
+ }
+ abstract protected boolean isCookieAttribute(String stringLowercase);
- /**
- * Returns the index (if any) of the equals sign separating a cookie name from the its value.
- * Equals signs at the end of the token are ignored in this calculation, since they may be
- * part of a Base64-encoded value.
- */
- private int getEqualsIndex( String token ) {
- if (!token.endsWith( "==" )) {
- return token.indexOf( '=' );
- } else {
- return getEqualsIndex( token.substring( 0, token.length()-2 ) );
- }
- }
+ abstract protected boolean isCookieReservedWord(String token);
+ }
- /**
- * Tokenizes a cookie header and returns the tokens in a
- * <code>Vector</code>.
- * handles the broken syntax for expires= fields ...
- * @param cookieHeader - the header to read
- * @return a Vector of cookieTokens as name=value pairs
- **/
- private Vector getCookieTokens(String cookieHeader) {
- StringReader sr = new StringReader(cookieHeader);
- StreamTokenizer st = new StreamTokenizer(sr);
- Vector tokens = new Vector();
+ /**
+ * cookie Factory - creates cookies for URL s
+ *
+ */
+ class CookiePress {
- // clear syntax tables of the StreamTokenizer
- st.resetSyntax();
+ // the current value
+ private StringBuffer _value = new StringBuffer();
+ private HashMap _attributes = new HashMap();
+ private URL _sourceURL;
- // set all characters as word characters
- st.wordChars(0,Character.MAX_VALUE);
+ /**
+ * create a cookie press for the given URL
+ *
+ * @param sourceURL
+ */
+ public CookiePress(URL sourceURL) {
+ _sourceURL = sourceURL;
+ }
- // set up characters for quoting
- st.quoteChar( '"' ); //double quotes
- st.quoteChar( '\'' ); //single quotes
+ /**
+ * clear the attributes and the cookie value
+ */
+ void clear() {
+ _value.setLength(0);
+ _attributes.clear();
+ }
- // set up characters to separate tokens
- st.whitespaceChars(59,59); //semicolon
- // and here we run into trouble ...
- // see http://www.mnot.net/blog/2006/10/27/cookie_fun
- // ... Notice something about the above? It uses a comma inside of the date,
- // without quoting the value. This makes it difficult for generic processors to handle the Set-Cookie header.
- st.whitespaceChars(44,44); //comma
+ /**
+ * add the token content
+ *
+ * @param token
+ * @param lastChar
+ */
+ void addToken(String token, char lastChar) {
+ _value.insert(0, token);
+ if (lastChar != '=')
+ _value.insert(0, ',');
+ }
- try {
- while (st.nextToken() != StreamTokenizer.TT_EOF) {
- String tokenContent=st.sval;
- // fix expires comma delimiter token problem
- if (tokenContent.toLowerCase().startsWith("expires=")) {
- if (st.nextToken() != StreamTokenizer.TT_EOF) {
- tokenContent+=","+st.sval;
- } // if
- } // if
- tokenContent=tokenContent.trim();
- tokens.addElement( tokenContent );
- }
- }
- catch (IOException ioe) {
- // this will never happen with a StringReader
- }
- sr.close();
- return tokens;
- }
+ /**
+ * add from a token
+ *
+ * @param recipe
+ * - the recipe to use
+ * @param token
+ * - the token to use
+ * @param equalsIndex
+ * - the position of the equal sign
+ */
+ void addTokenWithEqualsSign(CookieRecipe recipe, String token,
+ int equalsIndex) {
+ final String name = token.substring(0, equalsIndex).trim();
+ final String value = token.substring(equalsIndex + 1).trim();
+ _value.insert(0, value);
+ final String fvalue = _value.toString();
+ if (recipe.isCookieAttribute(name.toLowerCase())) {
+ _attributes.put(name.toLowerCase(), value);
+ } else {
+ addCookieIfValid(new Cookie(name, fvalue, _attributes));
+ _attributes.clear();
+ }
+ _value.setLength(0);
+ }
+ /**
+ * add the given cookie if it is valid
+ *
+ * @param cookie
+ */
+ private void addCookieIfValid(Cookie cookie) {
+ if (acceptCookie(cookie))
+ addUniqueCookie(cookie);
+ }
- abstract protected boolean isCookieAttribute( String stringLowercase );
+ /**
+ * accept the given cookie
+ *
+ * @param cookie
+ * @return
+ */
+ private boolean acceptCookie(Cookie cookie) {
+ if (cookie.getPath() == null) {
+ cookie.setPath(getParentPath(_sourceURL.getPath()));
+ } else {
+ int status = getPathAttributeStatus(cookie.getPath(),
+ _sourceURL.getPath());
+ if (status != CookieListener.ACCEPTED) {
+ reportCookieRejected(status, cookie.getPath(),
+ cookie.getName());
+ return false;
+ }
+ }
+ if (cookie.getDomain() == null) {
+ cookie.setDomain(_sourceURL.getHost());
+ } else if (!CookieProperties.isDomainMatchingStrict()
+ && cookie.getDomain()
+ .equalsIgnoreCase(_sourceURL.getHost())) {
+ cookie.setDomain(_sourceURL.getHost());
+ } else {
+ int status = getDomainAttributeStatus(cookie,
+ _sourceURL.getHost());
+ if (status != CookieListener.ACCEPTED) {
+ reportCookieRejected(status, cookie.getDomain(),
+ cookie.getName());
+ return false;
+ }
+ }
- abstract protected boolean isCookieReservedWord( String token );
+ return true;
+ }
- }
+ private String getParentPath(String path) {
+ int rightmostSlashIndex = path.lastIndexOf('/');
+ return rightmostSlashIndex < 0 ? "/" : path.substring(0,
+ rightmostSlashIndex);
+ }
+ private int getPathAttributeStatus(String pathAttribute,
+ String sourcePath) {
+ if (!CookieProperties.isPathMatchingStrict()
+ || sourcePath.length() == 0
+ || sourcePath.startsWith(pathAttribute)) {
+ return CookieListener.ACCEPTED;
+ } else {
+ return CookieListener.PATH_NOT_PREFIX;
+ }
+ }
- /**
- * cookie Factory - creates cookies for URL s
- *
- */
- class CookiePress {
+ /**
+ * get the domainAttribute Status for the given cookie with the
+ * given sourceHost
+ *
+ * @see http://wp.netscape.com/newsref/std/cookie_spec.html
+ * @param cookie - the cookie to use
+ * @param sourceHost
+ * @return
+ */
+ private int getDomainAttributeStatus(Cookie cookie, String sourceHost) {
+ String domainAttribute = cookie.getDomain();
+ // patch according to [ 1476380 ] Cookies incorrectly rejected
+ // despite valid domain
+ if (domainAttribute.equals(sourceHost)) {
+ return CookieListener.ACCEPTED;
+ }
+ if (!domainAttribute.startsWith("."))
+ domainAttribute = '.' + domainAttribute;
- // the current value
- private StringBuffer _value = new StringBuffer();
- private HashMap _attributes = new HashMap();
- private URL _sourceURL;
+ if (domainAttribute.lastIndexOf('.') == 0) {
+ return CookieListener.DOMAIN_ONE_DOT;
+ } else if (!sourceHost.endsWith(domainAttribute)) {
+ return CookieListener.DOMAIN_NOT_SOURCE_SUFFIX;
+ } else if (CookieProperties.isDomainMatchingStrict()
+ && sourceHost.lastIndexOf(domainAttribute) > sourceHost
+ .indexOf('.')) {
+ return CookieListener.DOMAIN_TOO_MANY_LEVELS;
+ } else {
+ // modified for Bugreport 2825872 Cookie domains not stored correctly - ID: 2825872
+ // http://sourceforge.net/tracker/?func=detail&aid=2825872&group_id=6550&atid=106550
+ cookie.setDomain(domainAttribute);
+ return CookieListener.ACCEPTED;
+ }
+ }
+ private boolean reportCookieRejected(int reason, String attribute,
+ String source) {
+ CookieProperties.reportCookieRejected(reason, attribute, source);
+ return false;
+ }
- /**
- * create a cookie press for the given URL
- * @param sourceURL
- */
- public CookiePress( URL sourceURL ) {
- _sourceURL = sourceURL;
- }
+ }
+ /**
+ * Parses cookies according to <a
+ * href="http://www.ietf.org/rfc/rfc2109.txt">RFC 2109</a>
+ *
+ * <br />
+ * These cookies come from the <code>Set-Cookie:</code> header
+ **/
+ class RFC2109CookieRecipe extends CookieRecipe {
- /**
- * clear the attributes and the cookie value
- */
- void clear() {
- _value.setLength(0);
- _attributes.clear();
- }
+ /**
+ * check whether the given lower case String is a cookie attribute
+ *
+ * @param stringLowercase
+ * - the string to check
+ * @return true - if the string is the name of a valid cookie attribute
+ */
+ protected boolean isCookieAttribute(String stringLowercase) {
+ return stringLowercase.equals("path")
+ || stringLowercase.equals("domain")
+ || stringLowercase.equals("expires")
+ || stringLowercase.equals("comment")
+ || stringLowercase.equals("max-age")
+ || stringLowercase.equals("version");
+ }
+ protected boolean isCookieReservedWord(String token) {
+ return token.equalsIgnoreCase("secure");
+ }
+ }
- /**
- * add the token content
- * @param token
- * @param lastChar
- */
- void addToken( String token, char lastChar ) {
- _value.insert( 0, token );
- if (lastChar != '=') _value.insert( 0, ',' );
- }
+ /**
+ * Parses cookies according to <a
+ * href="http://www.ietf.org/rfc/rfc2965.txt">RFC 2965</a>
+ *
+ * <br />
+ * These cookies come from the <code>Set-Cookie2:</code> header
+ **/
+ class RFC2965CookieRecipe extends CookieRecipe {
+ protected boolean isCookieAttribute(String stringLowercase) {
+ return stringLowercase.equals("path")
+ || stringLowercase.equals("domain")
+ || stringLowercase.equals("comment")
+ || stringLowercase.equals("commenturl")
+ || stringLowercase.equals("max-age")
+ || stringLowercase.equals("version")
+ || stringLowercase.equals("$version")
+ || stringLowercase.equals("port");
+ }
- /**
- * add from a token
- * @param recipe - the recipe to use
- * @param token - the token to use
- * @param equalsIndex - the position of the equal sign
- */
- void addTokenWithEqualsSign( CookieRecipe recipe, String token, int equalsIndex ) {
- final String name = token.substring( 0, equalsIndex ).trim();
- final String value= token.substring( equalsIndex + 1 ).trim();
- _value.insert( 0, value );
- final String fvalue=_value.toString();
- if (recipe.isCookieAttribute( name.toLowerCase() )) {
- _attributes.put( name.toLowerCase(), value );
- } else {
- addCookieIfValid( new Cookie( name, fvalue, _attributes ) );
- _attributes.clear();
- }
- _value.setLength(0);
- }
+ protected boolean isCookieReservedWord(String token) {
+ return token.equalsIgnoreCase("discard")
+ || token.equalsIgnoreCase("secure");
+ }
+ }
-
- /**
- * add the given cookie if it is valid
- * @param cookie
- */
- private void addCookieIfValid( Cookie cookie ) {
- if (acceptCookie( cookie )) addUniqueCookie( cookie );
- }
-
-
- /**
- * accept the given cookie
- * @param cookie
- * @return
- */
- private boolean acceptCookie( Cookie cookie ) {
- if (cookie.getPath() == null) {
- cookie.setPath( getParentPath( _sourceURL.getPath() ) );
- } else {
- int status = getPathAttributeStatus( cookie.getPath(), _sourceURL.getPath() );
- if (status != CookieListener.ACCEPTED) {
- reportCookieRejected( status, cookie.getPath(), cookie.getName() );
- return false;
- }
- }
-
- if (cookie.getDomain() == null) {
- cookie.setDomain( _sourceURL.getHost() );
- } else if (!CookieProperties.isDomainMatchingStrict() && cookie.getDomain().equalsIgnoreCase( _sourceURL.getHost() )) {
- cookie.setDomain( _sourceURL.getHost() );
- } else {
- int status = getDomainAttributeStatus( cookie.getDomain(), _sourceURL.getHost() );
- if (status != CookieListener.ACCEPTED) {
- reportCookieRejected( status, cookie.getDomain(), cookie.getName() );
- return false;
- }
- }
-
- return true;
- }
-
-
- private String getParentPath( String path ) {
- int rightmostSlashIndex = path.lastIndexOf( '/' );
- return rightmostSlashIndex < 0 ? "/" : path.substring( 0, rightmostSlashIndex );
- }
-
-
- private int getPathAttributeStatus( String pathAttribute, String sourcePath ) {
- if (!CookieProperties.isPathMatchingStrict() || sourcePath.length() == 0 || sourcePath.startsWith( pathAttribute )) {
- return CookieListener.ACCEPTED;
- } else {
- return CookieListener.PATH_NOT_PREFIX;
- }
- }
-
-
- /**
- * get the domainAttribute Status for the given domainAttribute with the given sourceHost
- * @see http://wp.netscape.com/newsref/std/cookie_spec.html
- * @param domainAttribute
- * @param sourceHost
- * @return
- */
- private int getDomainAttributeStatus( String domainAttribute, String sourceHost ) {
- // patch according to [ 1476380 ] Cookies incorrectly rejected despite valid domain
- if (domainAttribute.equals(sourceHost)) {
- return CookieListener.ACCEPTED;
- }
- if (!domainAttribute.startsWith("."))
- domainAttribute = '.' + domainAttribute;
-
- if (domainAttribute.lastIndexOf('.') == 0) {
- return CookieListener.DOMAIN_ONE_DOT;
- } else if (!sourceHost.endsWith( domainAttribute )) {
- return CookieListener.DOMAIN_NOT_SOURCE_SUFFIX;
- } else if (CookieProperties.isDomainMatchingStrict() &&
- sourceHost.lastIndexOf( domainAttribute ) > sourceHost.indexOf( '.' )) {
- return CookieListener.DOMAIN_TOO_MANY_LEVELS;
- } else {
- return CookieListener.ACCEPTED;
- }
- }
-
- private boolean reportCookieRejected( int reason, String attribute, String source ) {
- CookieProperties.reportCookieRejected( reason, attribute, source );
- return false;
- }
-
- }
-
-
- /**
- * Parses cookies according to
- * <a href="http://www.ietf.org/rfc/rfc2109.txt">RFC 2109</a>
- *
- * <br />
- * These cookies come from the <code>Set-Cookie:</code> header
- **/
- class RFC2109CookieRecipe extends CookieRecipe {
-
- /**
- * check whether the given lower case String is a cookie attribute
- * @param stringLowercase - the string to check
- * @return true - if the string is the name of a valid cookie attribute
- */
- protected boolean isCookieAttribute( String stringLowercase ) {
- return stringLowercase.equals("path") ||
- stringLowercase.equals("domain") ||
- stringLowercase.equals("expires") ||
- stringLowercase.equals("comment") ||
- stringLowercase.equals("max-age") ||
- stringLowercase.equals("version");
- }
-
-
- protected boolean isCookieReservedWord( String token ) {
- return token.equalsIgnoreCase( "secure" );
- }
- }
-
-
- /**
- * Parses cookies according to
- * <a href="http://www.ietf.org/rfc/rfc2965.txt">RFC 2965</a>
- *
- * <br />
- * These cookies come from the <code>Set-Cookie2:</code> header
- **/
- class RFC2965CookieRecipe extends CookieRecipe {
-
- protected boolean isCookieAttribute( String stringLowercase ) {
- return stringLowercase.equals("path") ||
- stringLowercase.equals("domain") ||
- stringLowercase.equals("comment") ||
- stringLowercase.equals("commenturl") ||
- stringLowercase.equals("max-age") ||
- stringLowercase.equals("version") ||
- stringLowercase.equals("$version") ||
- stringLowercase.equals("port");
- }
-
-
- protected boolean isCookieReservedWord( String token ) {
- return token.equalsIgnoreCase( "discard" ) || token.equalsIgnoreCase( "secure" );
- }
- }
-
-
}
Modified: trunk/httpunit/src/test/java/com/meterware/httpunit/cookies/CookieTest.java
===================================================================
--- trunk/httpunit/src/test/java/com/meterware/httpunit/cookies/CookieTest.java 2012-09-12 13:26:44 UTC (rev 1087)
+++ trunk/httpunit/src/test/java/com/meterware/httpunit/cookies/CookieTest.java 2012-09-12 15:55:44 UTC (rev 1088)
@@ -141,10 +141,17 @@
private void checkAcceptance(int index, boolean shouldAccept, String urlString,
String specifiedDomain, String specifiedPath) throws MalformedURLException {
+
CookieJar jar = newJar(urlString, specifiedDomain, specifiedPath);
if (shouldAccept) {
- assertNotNull("Rejected cookie " + index + "( " + specifiedDomain + " from " + urlString + ") should have been accepted", jar.getCookie("name"));
+ // modified for Bugreport 2825872 Cookie domains not stored correctly - ID: 2825872
+ // http://sourceforge.net/tracker/?func=detail&aid=2825872&group_id=6550&atid=106550
+ Cookie cookie = jar.getCookie( "name" );
+ assertNotNull( "Rejected cookie " + index + "( " + specifiedDomain + " from " + urlString + ") should have been accepted", cookie );
+ URL url = new URL( "http://" + urlString );
+ assertTrue( "Cookie " + index + " should be sent to the url ", cookie.mayBeSentTo(url));
+
} else {
assertNull("Cookie " + index + " should have been rejected", jar.getCookie("name"));
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <wol...@us...> - 2012-09-12 13:26:54
|
Revision: 1087
http://httpunit.svn.sourceforge.net/httpunit/?rev=1087&view=rev
Author: wolfgang_fahl
Date: 2012-09-12 13:26:44 +0000 (Wed, 12 Sep 2012)
Log Message:
-----------
add checks for InvocationContextFactory - clearly ServletAccessTest can not be run on it's own with this change
Modified Paths:
--------------
trunk/httpunit/src/main/java/com/meterware/servletunit/ServletTestCase.java
trunk/httpunit/src/main/java/com/meterware/servletunit/ServletUnitClient.java
trunk/httpunit/src/test/java/com/meterware/servletunit/HttpServletRequestTest.java
trunk/httpunit/src/test/java/com/meterware/servletunit/JUnitServletTest.java
trunk/httpunit/src/test/java/com/meterware/servletunit/ServletAccessTest.java
Modified: trunk/httpunit/src/main/java/com/meterware/servletunit/ServletTestCase.java
===================================================================
--- trunk/httpunit/src/main/java/com/meterware/servletunit/ServletTestCase.java 2012-09-12 12:21:19 UTC (rev 1086)
+++ trunk/httpunit/src/main/java/com/meterware/servletunit/ServletTestCase.java 2012-09-12 13:26:44 UTC (rev 1087)
@@ -30,20 +30,31 @@
abstract
public class ServletTestCase extends TestCase {
+ /**
+ * construct a ServletTestCase with the given name
+ * @param name
+ */
protected ServletTestCase( String name ) {
super( name );
}
-
/**
* Returns a client object which can access the servlet context in which this test is running.
*/
final protected ServletUnitClient newClient() {
+ if (_invocationContextFactory==null)
+ throw new RuntimeException("ServletTestCase.newClient called before setInvocationContextFactory was called");
return ServletUnitClient.newClient( _invocationContextFactory );
}
+ /**
+ * set the invocation context factory to be used
+ * @param invocationContextFactory
+ */
static void setInvocationContextFactory( InvocationContextFactory invocationContextFactory ) {
+ if (invocationContextFactory==null)
+ throw new RuntimeException("setInvocationContextFactory called with null invocationContextFactory parameter");
_invocationContextFactory = invocationContextFactory;
}
Modified: trunk/httpunit/src/main/java/com/meterware/servletunit/ServletUnitClient.java
===================================================================
--- trunk/httpunit/src/main/java/com/meterware/servletunit/ServletUnitClient.java 2012-09-12 12:21:19 UTC (rev 1086)
+++ trunk/httpunit/src/main/java/com/meterware/servletunit/ServletUnitClient.java 2012-09-12 13:26:44 UTC (rev 1087)
@@ -45,6 +45,10 @@
public class ServletUnitClient extends WebClient {
+ private ServletUnitClient() {
+ throw new RuntimeException("ServletUnitClient constructor needs InvocationContextFactory parameter");
+ }
+
/**
* Creates and returns a new servlet unit client instance.
**/
@@ -77,8 +81,18 @@
}
+ /**
+ * get a new Invocation Context based on a request and a frame
+ * @param request
+ * @param frame
+ * @return
+ * @throws IOException
+ * @throws MalformedURLException
+ */
InvocationContext newInvocation( WebRequest request, FrameSelector frame ) throws IOException, MalformedURLException {
ByteArrayOutputStream baos = getMessageBody( request );
+ if (_invocationContextFactory==null)
+ throw new RuntimeException("newInvocation called with null _invocationContextFactory");
return _invocationContextFactory.newInvocation( this, frame, request, getHeaderFields( request.getURL() ), baos.toByteArray() );
}
@@ -141,6 +155,8 @@
private ServletUnitClient( InvocationContextFactory factory ) {
+ if (factory==null)
+ throw new RuntimeException("constructor for ServletUnitClient called with null factory parameter");
_invocationContextFactory = factory;
}
}
Modified: trunk/httpunit/src/test/java/com/meterware/servletunit/HttpServletRequestTest.java
===================================================================
--- trunk/httpunit/src/test/java/com/meterware/servletunit/HttpServletRequestTest.java 2012-09-12 12:21:19 UTC (rev 1086)
+++ trunk/httpunit/src/test/java/com/meterware/servletunit/HttpServletRequestTest.java 2012-09-12 13:26:44 UTC (rev 1087)
@@ -20,6 +20,7 @@
*
*******************************************************************************************************************/
+import com.meterware.httpunit.FrameSelector;
import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.HttpUnitOptions;
import com.meterware.httpunit.HttpUnitUtils;
@@ -38,9 +39,11 @@
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
+import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.Date;
+import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Locale;
@@ -788,7 +791,16 @@
assertEquals("param1 value", "red", request.getParameter("param1"));
assertEquals("param2 value", hebrewValue, request.getParameter("param2"));
}
+
+ private InvocationContextFactory _dummyfactory = new InvocationContextFactory() {
+ public InvocationContext newInvocation( ServletUnitClient client, FrameSelector targetFrame, WebRequest request, Dictionary clientHeaders, byte[] messageBody ) throws IOException, MalformedURLException {
+ return new InvocationContextImpl( client, null, targetFrame, request, clientHeaders, messageBody );
+ }
+ public HttpSession getSession( String sessionId, boolean create ) {
+ return _context.getValidSession( sessionId, null, create );
+ }
+ };
@Test
public void testSpecifiedCharEncoding2() throws Exception {
@@ -798,7 +810,7 @@
wr.setParameter("param1", "red");
wr.setParameter("param2", hebrewValue);
wr.setHeaderField("Content-Type", "application/x-www-form-urlencoded; charset=ISO-8859-8");
- ServletUnitClient client = ServletUnitClient.newClient(null);
+ ServletUnitClient client = ServletUnitClient.newClient(_dummyfactory);
ByteArrayOutputStream messageBody = client.getMessageBody(wr);
ServletUnitHttpRequest request = new ServletUnitHttpRequest(NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), messageBody.toByteArray());
String parameter = request.getParameter("param2");
Modified: trunk/httpunit/src/test/java/com/meterware/servletunit/JUnitServletTest.java
===================================================================
--- trunk/httpunit/src/test/java/com/meterware/servletunit/JUnitServletTest.java 2012-09-12 12:21:19 UTC (rev 1086)
+++ trunk/httpunit/src/test/java/com/meterware/servletunit/JUnitServletTest.java 2012-09-12 13:26:44 UTC (rev 1087)
@@ -247,7 +247,7 @@
}
- static class MyFactory implements InvocationContextFactory {
+ protected static class MyFactory implements InvocationContextFactory {
private static ServletRunner _runner;
public InvocationContext newInvocation(ServletUnitClient client, FrameSelector targetFrame, WebRequest request, Dictionary clientHeaders, byte[] messageBody) throws IOException, MalformedURLException {
Modified: trunk/httpunit/src/test/java/com/meterware/servletunit/ServletAccessTest.java
===================================================================
--- trunk/httpunit/src/test/java/com/meterware/servletunit/ServletAccessTest.java 2012-09-12 12:21:19 UTC (rev 1086)
+++ trunk/httpunit/src/test/java/com/meterware/servletunit/ServletAccessTest.java 2012-09-12 13:26:44 UTC (rev 1087)
@@ -31,6 +31,10 @@
*/
public class ServletAccessTest extends ServletTestCase {
+ /**
+ * construct a ServletAccessTest
+ * @param name
+ */
public ServletAccessTest(String name) {
super(name);
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <wol...@us...> - 2012-09-12 12:21:29
|
Revision: 1086
http://httpunit.svn.sourceforge.net/httpunit/?rev=1086&view=rev
Author: wolfgang_fahl
Date: 2012-09-12 12:21:19 +0000 (Wed, 12 Sep 2012)
Log Message:
-----------
converted to m2eclipse project
Modified Paths:
--------------
trunk/httpunit/.classpath
trunk/httpunit/.project
trunk/httpunit/.settings/org.eclipse.jdt.core.prefs
Added Paths:
-----------
trunk/httpunit/.settings/org.eclipse.core.resources.prefs
trunk/httpunit/.settings/org.eclipse.m2e.core.prefs
Modified: trunk/httpunit/.classpath
===================================================================
--- trunk/httpunit/.classpath 2012-09-10 01:42:55 UTC (rev 1085)
+++ trunk/httpunit/.classpath 2012-09-12 12:21:19 UTC (rev 1086)
@@ -1,22 +1,9 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="src" path="src"/>
- <classpathentry kind="src" path="test"/>
- <classpathentry kind="src" path="pending-tests"/>
- <classpathentry kind="src" path="examples"/>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
- <classpathentry kind="lib" path="jars/quicksite.jar"/>
- <classpathentry kind="var" path="MAVEN_REPOSITORY/jtidy/jtidy/4aug2000r7-dev/jtidy-4aug2000r7-dev.jar"/>
- <classpathentry kind="var" path="MAVEN_REPOSITORY/junit/junit/3.8.1/junit-3.8.1.jar"/>
- <classpathentry kind="var" path="MAVEN_REPOSITORY/nekohtml/nekohtml/0.9.5/nekohtml-0.9.5.jar"/>
- <classpathentry kind="var" path="MAVEN_REPOSITORY/rhino/js/1.6R5/js-1.6R5.jar" sourcepath="/pub/2008/rhino1_6R5.zip"/>
- <classpathentry kind="var" path="MAVEN_REPOSITORY/javax/servlet/servlet-api/2.4/servlet-api-2.4.jar"/>
- <classpathentry kind="var" path="MAVEN_REPOSITORY/xerces/xmlParserAPIs/2.6.1/xmlParserAPIs-2.6.1.jar" sourcepath="/pub/2008/Xerces-J-src.2.6.1.zip"/>
- <classpathentry kind="var" path="MAVEN_REPOSITORY/xerces/xercesImpl/2.6.1/xercesImpl-2.6.1.jar"/>
- <classpathentry kind="lib" path="META-INF"/>
- <classpathentry kind="var" path="MAVEN_REPOSITORY/javax/activation/activation/1.1/activation-1.1.jar"/>
- <classpathentry kind="var" path="MAVEN_REPOSITORY/javax/mail/mail/1.4/mail-1.4.jar"/>
- <classpathentry kind="lib" path="jars/maven-ant-tasks-2.0.9.jar"/>
- <classpathentry kind="var" path="MAVEN_REPOSITORY"/>
- <classpathentry kind="output" path="bin"/>
-</classpath>
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="src" output="target/classes" path="src/main/java"/>
+ <classpathentry kind="src" output="target/test-classes" path="src/test/java"/>
+ <classpathentry excluding="**" kind="src" output="target/test-classes" path="META-INF"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"/>
+ <classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER"/>
+ <classpathentry kind="output" path="target/classes"/>
+</classpath>
Modified: trunk/httpunit/.project
===================================================================
--- trunk/httpunit/.project 2012-09-10 01:42:55 UTC (rev 1085)
+++ trunk/httpunit/.project 2012-09-12 12:21:19 UTC (rev 1086)
@@ -1,17 +1,23 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>httpunit</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>httpunit</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.m2e.core.maven2Builder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.m2e.core.maven2Nature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
Added: trunk/httpunit/.settings/org.eclipse.core.resources.prefs
===================================================================
--- trunk/httpunit/.settings/org.eclipse.core.resources.prefs (rev 0)
+++ trunk/httpunit/.settings/org.eclipse.core.resources.prefs 2012-09-12 12:21:19 UTC (rev 1086)
@@ -0,0 +1,6 @@
+#Wed Sep 12 14:20:08 CEST 2012
+eclipse.preferences.version=1
+encoding//src/main/java=UTF-8
+encoding//src/test/java=UTF-8
+encoding/<project>=UTF-8
+encoding/META-INF=UTF-8
Property changes on: trunk/httpunit/.settings/org.eclipse.core.resources.prefs
___________________________________________________________________
Added: svn:mime-type
+ text/plain
Modified: trunk/httpunit/.settings/org.eclipse.jdt.core.prefs
===================================================================
--- trunk/httpunit/.settings/org.eclipse.jdt.core.prefs 2012-09-10 01:42:55 UTC (rev 1085)
+++ trunk/httpunit/.settings/org.eclipse.jdt.core.prefs 2012-09-12 12:21:19 UTC (rev 1086)
@@ -1,70 +1,70 @@
-#Mon Jun 29 17:49:25 CEST 2009
-eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2
-org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
-org.eclipse.jdt.core.compiler.compliance=1.4
-org.eclipse.jdt.core.compiler.debug.lineNumber=generate
-org.eclipse.jdt.core.compiler.debug.localVariable=generate
-org.eclipse.jdt.core.compiler.debug.sourceFile=generate
-org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
-org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning
-org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
-org.eclipse.jdt.core.compiler.problem.deprecation=ignore
-org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
-org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
-org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
-org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
-org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning
-org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore
-org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled
-org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore
-org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
-org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
-org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
-org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
-org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
-org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore
-org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
-org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore
-org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
-org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore
-org.eclipse.jdt.core.compiler.problem.missingSerialVersion=ignore
-org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
-org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
-org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
-org.eclipse.jdt.core.compiler.problem.nullReference=warning
-org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
-org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
-org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore
-org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore
-org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore
-org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
-org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=ignore
-org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
-org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
-org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning
-org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
-org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
-org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
-org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore
-org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
-org.eclipse.jdt.core.compiler.problem.unusedImport=ignore
-org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
-org.eclipse.jdt.core.compiler.problem.unusedLocal=ignore
-org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
-org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
-org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=ignore
-org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
-org.eclipse.jdt.core.compiler.source=1.3
+#Wed Sep 12 14:20:08 CEST 2012
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
+org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
+org.eclipse.jdt.core.compiler.compliance=1.5
+org.eclipse.jdt.core.compiler.debug.lineNumber=generate
+org.eclipse.jdt.core.compiler.debug.localVariable=generate
+org.eclipse.jdt.core.compiler.debug.sourceFile=generate
+org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning
+org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
+org.eclipse.jdt.core.compiler.problem.deprecation=ignore
+org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
+org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
+org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
+org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning
+org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore
+org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled
+org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore
+org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
+org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
+org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
+org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
+org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
+org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore
+org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
+org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore
+org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
+org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore
+org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore
+org.eclipse.jdt.core.compiler.problem.missingSerialVersion=ignore
+org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
+org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
+org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
+org.eclipse.jdt.core.compiler.problem.nullReference=warning
+org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
+org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
+org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore
+org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore
+org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
+org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
+org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore
+org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
+org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=ignore
+org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
+org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
+org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning
+org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
+org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
+org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
+org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
+org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore
+org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
+org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore
+org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
+org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
+org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
+org.eclipse.jdt.core.compiler.problem.unusedImport=ignore
+org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
+org.eclipse.jdt.core.compiler.problem.unusedLocal=ignore
+org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
+org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
+org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
+org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
+org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=ignore
+org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
+org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
+org.eclipse.jdt.core.compiler.source=1.5
Added: trunk/httpunit/.settings/org.eclipse.m2e.core.prefs
===================================================================
--- trunk/httpunit/.settings/org.eclipse.m2e.core.prefs (rev 0)
+++ trunk/httpunit/.settings/org.eclipse.m2e.core.prefs 2012-09-12 12:21:19 UTC (rev 1086)
@@ -0,0 +1,5 @@
+#Wed Sep 12 14:20:07 CEST 2012
+activeProfiles=
+eclipse.preferences.version=1
+resolveWorkspaceProjects=true
+version=1
Property changes on: trunk/httpunit/.settings/org.eclipse.m2e.core.prefs
___________________________________________________________________
Added: svn:mime-type
+ text/plain
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <rus...@us...> - 2012-09-10 01:43:01
|
Revision: 1085
http://httpunit.svn.sourceforge.net/httpunit/?rev=1085&view=rev
Author: russgold
Date: 2012-09-10 01:42:55 +0000 (Mon, 10 Sep 2012)
Log Message:
-----------
[maven-release-plugin] prepare for next development iteration
Modified Paths:
--------------
trunk/httpunit/pom.xml
Modified: trunk/httpunit/pom.xml
===================================================================
--- trunk/httpunit/pom.xml 2012-09-10 01:42:51 UTC (rev 1084)
+++ trunk/httpunit/pom.xml 2012-09-10 01:42:55 UTC (rev 1085)
@@ -11,7 +11,7 @@
<groupId>org.httpunit</groupId>
<artifactId>httpunit</artifactId>
<name>HttpUnit</name>
- <version>1.7.1</version>
+ <version>1.7.2-SNAPSHOT</version>
<description>A library for testing websites programmatically</description>
<url>http://www.httpunit.org</url>
@@ -25,9 +25,9 @@
<scm>
- <url>http://httpunit.svn.sourceforge.net/viewvc/httpunit/tags/httpunit-1.7.1</url>
- <developerConnection>scm:svn:https://httpunit.svn.sourceforge.net/svnroot/httpunit/tags/httpunit-1.7.1</developerConnection>
- <connection>scm:svn:http://httpunit.svn.sourceforge.net/svnroot/httpunit/tags/httpunit-1.7.1</connection>
+ <url>http://httpunit.svn.sourceforge.net/viewvc/httpunit</url>
+ <developerConnection>scm:svn:https://httpunit.svn.sourceforge.net/svnroot/httpunit</developerConnection>
+ <connection>scm:svn:http://httpunit.svn.sourceforge.net/svnroot/httpunit</connection>
</scm>
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <rus...@us...> - 2012-09-10 01:42:57
|
Revision: 1084
http://httpunit.svn.sourceforge.net/httpunit/?rev=1084&view=rev
Author: russgold
Date: 2012-09-10 01:42:51 +0000 (Mon, 10 Sep 2012)
Log Message:
-----------
[maven-release-plugin] copy for tag httpunit-1.7.1
Added Paths:
-----------
tags/httpunit-1.7.1/
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <rus...@us...> - 2012-09-10 01:42:51
|
Revision: 1083
http://httpunit.svn.sourceforge.net/httpunit/?rev=1083&view=rev
Author: russgold
Date: 2012-09-10 01:42:44 +0000 (Mon, 10 Sep 2012)
Log Message:
-----------
[maven-release-plugin] prepare release httpunit-1.7.1
Modified Paths:
--------------
trunk/httpunit/pom.xml
Modified: trunk/httpunit/pom.xml
===================================================================
--- trunk/httpunit/pom.xml 2012-09-10 01:35:14 UTC (rev 1082)
+++ trunk/httpunit/pom.xml 2012-09-10 01:42:44 UTC (rev 1083)
@@ -1,271 +1,271 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<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/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.sonatype.oss</groupId>
- <artifactId>oss-parent</artifactId>
- <version>7</version>
- </parent>
-
- <groupId>org.httpunit</groupId>
- <artifactId>httpunit</artifactId>
- <name>HttpUnit</name>
- <version>1.7.1-SNAPSHOT</version>
- <description>A library for testing websites programmatically</description>
-
- <url>http://www.httpunit.org</url>
-
- <licenses>
- <license>
- <name>MIT</name>
- <url>http://www.opensource.org/licenses/mit-license.php</url>
- </license>
- </licenses>
-
-
- <scm>
- <url>http://httpunit.svn.sourceforge.net/viewvc/httpunit</url>
- <developerConnection>scm:svn:https://httpunit.svn.sourceforge.net/svnroot/httpunit</developerConnection>
- <connection>scm:svn:http://httpunit.svn.sourceforge.net/svnroot/httpunit</connection>
- </scm>
-
-
- <developers>
- <developer>
- <id>russgold</id>
- <name>Russell Gold</name>
- <organization>Oracle, Inc.</organization>
- <roles>
- <role>lead</role>
- <role>developer</role>
- </roles>
- </developer>
- <developer>
- <id>wolfgang_fahl</id>
- <name>Wolfgang Fahl</name>
- <organization>BitPlan</organization>
- <roles>
- <role>lead</role>
- <role>developer</role>
- </roles>
- </developer>
- </developers>
-
- <issueManagement>
- <system>Sourceforge</system>
- <url>http://sourceforge.net/tracker/?group_id=6550&atid=106550</url>
- </issueManagement>
-
- <dependencies>
- <dependency>
- <groupId>rhino</groupId>
- <artifactId>js</artifactId>
- <version>1.6R5</version>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.7</version>
- </dependency>
- <dependency>
- <groupId>nekohtml</groupId>
- <artifactId>nekohtml</artifactId>
- <version>0.9.5</version>
- </dependency>
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>servlet-api</artifactId>
- <version>2.4</version>
- </dependency>
- <dependency>
- <groupId>jtidy</groupId>
- <artifactId>jtidy</artifactId>
- <version>4aug2000r7-dev</version>
- </dependency>
- <dependency>
- <groupId>xerces</groupId>
- <artifactId>xercesImpl</artifactId>
- <version>2.6.1</version>
- </dependency>
- <dependency>
- <groupId>xerces</groupId>
- <artifactId>xmlParserAPIs</artifactId>
- <version>2.6.1</version>
- </dependency>
- <dependency>
- <groupId>javax.mail</groupId>
- <artifactId>mail</artifactId>
- <version>1.4</version>
- <scope>test</scope>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
- <version>2.3.2</version>
- <configuration>
- <source>1.5</source>
- <target>1.5</target>
- <compilerArgument>-proc:none</compilerArgument>
- </configuration>
- </plugin>
- </plugins>
- <testResources>
- <testResource>
- <directory>META-INF</directory>
- </testResource>
- </testResources>
- </build>
-
- <reporting>
- <plugins>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>findbugs-maven-plugin</artifactId>
- <version>2.5.1</version>
- </plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>cobertura-maven-plugin</artifactId>
- <version>2.5.1</version>
- </plugin>
- </plugins>
- </reporting>
-
-<!--
-
- <build>
- <sourceDirectory>src</sourceDirectory>
- <testSourceDirectory>test</testSourceDirectory>
- <testResources>
- <testResource>
- <directory>META-INF</directory>
- </testResource>
- </testResources>
- <resources>
- <resource>
- <directory>META-INF</directory>
- </resource>
- </resources>
- <plugins>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>cobertura-maven-plugin</artifactId>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-source-plugin</artifactId>
- <executions>
- <execution>
- <id>attach-sources</id>
- <phase>package</phase>
- <goals>
- <goal>jar</goal>
- <goal>test-jar</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>build-helper-maven-plugin</artifactId>
- <version>1.0</version>
- <executions>
- <execution>
- <id>add-source</id>
- <phase>generate-sources</phase>
- <goals>
- <goal>add-source</goal>
- </goals>
- <configuration>
- <sources>
- <source>src-1.4</source>
- </sources>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-jar-plugin</artifactId>
-
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- <configuration>
- <forkMode>never</forkMode>
- <!- Assertions diasabled due to a bug in xmlbeans
- https://issues.apache.org/jira/browse/XMLBEANS-317 ->
- <enableAssertions>false</enableAssertions>
- <excludes>
- <exclude>**/TestSuite$1.class</exclude>
- <exclude>**/EventAwareTestBase.class</exclude>
- <exclude>**/WebClientTest.class</exclude>
- <exclude>**/WebPageTest.class</exclude>
- </excludes>
- </configuration>
- </plugin>
- </plugins>
-
- </build>
- <reporting>
- <plugins>
- <plugin>
- <artifactId>maven-javadoc-plugin</artifactId>
- </plugin>
- <plugin>
- <artifactId>maven-surefire-report-plugin</artifactId>
- <configuration>
- <additionalClasspathElements>
- <additionalClasspathElement>
- META-INF
- </additionalClasspathElement>
- </additionalClasspathElements>
- </configuration>
- </plugin>
- <plugin>
- <artifactId>maven-jxr-plugin</artifactId>
- </plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>findbugs-maven-plugin</artifactId>
- <configuration>
- <threshold>Normal</threshold>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.codehaus.mojo</groupId>
- <artifactId>cobertura-maven-plugin</artifactId>
- </plugin>
- </plugins>
-
- </reporting>
--->
-
- <!-- Jetty libraries needed for Testing BR [ 2264431 ] form.submit() sends multiple HTTP POSTS
- <dependency>
- <groupId>org.mortbay.jetty</groupId>
- <artifactId>jetty</artifactId>
- <version>6.1.4</version>
- </dependency>
- <dependency>
- <groupId>org.mortbay.jetty</groupId>
- <artifactId>jetty-naming</artifactId>
- <version>6.1.4</version>
- </dependency>
- <dependency>
- <groupId>org.mortbay.jetty</groupId>
- <artifactId>jetty-plus</artifactId>
- <version>6.1.4</version>
- </dependency>
- <dependency>
- <groupId>org.mortbay.jetty</groupId>
- <artifactId>jetty-util</artifactId>
- <version>6.1.4</version>
- </dependency> -->
-</project>
+<?xml version="1.0" encoding="UTF-8"?>
+<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/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.sonatype.oss</groupId>
+ <artifactId>oss-parent</artifactId>
+ <version>7</version>
+ </parent>
+
+ <groupId>org.httpunit</groupId>
+ <artifactId>httpunit</artifactId>
+ <name>HttpUnit</name>
+ <version>1.7.1</version>
+ <description>A library for testing websites programmatically</description>
+
+ <url>http://www.httpunit.org</url>
+
+ <licenses>
+ <license>
+ <name>MIT</name>
+ <url>http://www.opensource.org/licenses/mit-license.php</url>
+ </license>
+ </licenses>
+
+
+ <scm>
+ <url>http://httpunit.svn.sourceforge.net/viewvc/httpunit/tags/httpunit-1.7.1</url>
+ <developerConnection>scm:svn:https://httpunit.svn.sourceforge.net/svnroot/httpunit/tags/httpunit-1.7.1</developerConnection>
+ <connection>scm:svn:http://httpunit.svn.sourceforge.net/svnroot/httpunit/tags/httpunit-1.7.1</connection>
+ </scm>
+
+
+ <developers>
+ <developer>
+ <id>russgold</id>
+ <name>Russell Gold</name>
+ <organization>Oracle, Inc.</organization>
+ <roles>
+ <role>lead</role>
+ <role>developer</role>
+ </roles>
+ </developer>
+ <developer>
+ <id>wolfgang_fahl</id>
+ <name>Wolfgang Fahl</name>
+ <organization>BitPlan</organization>
+ <roles>
+ <role>lead</role>
+ <role>developer</role>
+ </roles>
+ </developer>
+ </developers>
+
+ <issueManagement>
+ <system>Sourceforge</system>
+ <url>http://sourceforge.net/tracker/?group_id=6550&atid=106550</url>
+ </issueManagement>
+
+ <dependencies>
+ <dependency>
+ <groupId>rhino</groupId>
+ <artifactId>js</artifactId>
+ <version>1.6R5</version>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>4.7</version>
+ </dependency>
+ <dependency>
+ <groupId>nekohtml</groupId>
+ <artifactId>nekohtml</artifactId>
+ <version>0.9.5</version>
+ </dependency>
+ <dependency>
+ <groupId>javax.servlet</groupId>
+ <artifactId>servlet-api</artifactId>
+ <version>2.4</version>
+ </dependency>
+ <dependency>
+ <groupId>jtidy</groupId>
+ <artifactId>jtidy</artifactId>
+ <version>4aug2000r7-dev</version>
+ </dependency>
+ <dependency>
+ <groupId>xerces</groupId>
+ <artifactId>xercesImpl</artifactId>
+ <version>2.6.1</version>
+ </dependency>
+ <dependency>
+ <groupId>xerces</groupId>
+ <artifactId>xmlParserAPIs</artifactId>
+ <version>2.6.1</version>
+ </dependency>
+ <dependency>
+ <groupId>javax.mail</groupId>
+ <artifactId>mail</artifactId>
+ <version>1.4</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>2.3.2</version>
+ <configuration>
+ <source>1.5</source>
+ <target>1.5</target>
+ <compilerArgument>-proc:none</compilerArgument>
+ </configuration>
+ </plugin>
+ </plugins>
+ <testResources>
+ <testResource>
+ <directory>META-INF</directory>
+ </testResource>
+ </testResources>
+ </build>
+
+ <reporting>
+ <plugins>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>findbugs-maven-plugin</artifactId>
+ <version>2.5.1</version>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>cobertura-maven-plugin</artifactId>
+ <version>2.5.1</version>
+ </plugin>
+ </plugins>
+ </reporting>
+
+<!--
+
+ <build>
+ <sourceDirectory>src</sourceDirectory>
+ <testSourceDirectory>test</testSourceDirectory>
+ <testResources>
+ <testResource>
+ <directory>META-INF</directory>
+ </testResource>
+ </testResources>
+ <resources>
+ <resource>
+ <directory>META-INF</directory>
+ </resource>
+ </resources>
+ <plugins>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>cobertura-maven-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-source-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>attach-sources</id>
+ <phase>package</phase>
+ <goals>
+ <goal>jar</goal>
+ <goal>test-jar</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>build-helper-maven-plugin</artifactId>
+ <version>1.0</version>
+ <executions>
+ <execution>
+ <id>add-source</id>
+ <phase>generate-sources</phase>
+ <goals>
+ <goal>add-source</goal>
+ </goals>
+ <configuration>
+ <sources>
+ <source>src-1.4</source>
+ </sources>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jar-plugin</artifactId>
+
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <forkMode>never</forkMode>
+ <!- Assertions diasabled due to a bug in xmlbeans
+ https://issues.apache.org/jira/browse/XMLBEANS-317 ->
+ <enableAssertions>false</enableAssertions>
+ <excludes>
+ <exclude>**/TestSuite$1.class</exclude>
+ <exclude>**/EventAwareTestBase.class</exclude>
+ <exclude>**/WebClientTest.class</exclude>
+ <exclude>**/WebPageTest.class</exclude>
+ </excludes>
+ </configuration>
+ </plugin>
+ </plugins>
+
+ </build>
+ <reporting>
+ <plugins>
+ <plugin>
+ <artifactId>maven-javadoc-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <artifactId>maven-surefire-report-plugin</artifactId>
+ <configuration>
+ <additionalClasspathElements>
+ <additionalClasspathElement>
+ META-INF
+ </additionalClasspathElement>
+ </additionalClasspathElements>
+ </configuration>
+ </plugin>
+ <plugin>
+ <artifactId>maven-jxr-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>findbugs-maven-plugin</artifactId>
+ <configuration>
+ <threshold>Normal</threshold>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>cobertura-maven-plugin</artifactId>
+ </plugin>
+ </plugins>
+
+ </reporting>
+-->
+
+ <!-- Jetty libraries needed for Testing BR [ 2264431 ] form.submit() sends multiple HTTP POSTS
+ <dependency>
+ <groupId>org.mortbay.jetty</groupId>
+ <artifactId>jetty</artifactId>
+ <version>6.1.4</version>
+ </dependency>
+ <dependency>
+ <groupId>org.mortbay.jetty</groupId>
+ <artifactId>jetty-naming</artifactId>
+ <version>6.1.4</version>
+ </dependency>
+ <dependency>
+ <groupId>org.mortbay.jetty</groupId>
+ <artifactId>jetty-plus</artifactId>
+ <version>6.1.4</version>
+ </dependency>
+ <dependency>
+ <groupId>org.mortbay.jetty</groupId>
+ <artifactId>jetty-util</artifactId>
+ <version>6.1.4</version>
+ </dependency> -->
+</project>
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <rus...@us...> - 2012-09-10 01:35:21
|
Revision: 1082
http://httpunit.svn.sourceforge.net/httpunit/?rev=1082&view=rev
Author: russgold
Date: 2012-09-10 01:35:14 +0000 (Mon, 10 Sep 2012)
Log Message:
-----------
fix jetty comment
Modified Paths:
--------------
trunk/httpunit/pom.xml
Modified: trunk/httpunit/pom.xml
===================================================================
--- trunk/httpunit/pom.xml 2012-09-09 17:16:39 UTC (rev 1081)
+++ trunk/httpunit/pom.xml 2012-09-10 01:35:14 UTC (rev 1082)
@@ -247,7 +247,7 @@
</reporting>
-->
- <!--- Jetty libraries needed for Testing BR [ 2264431 ] form.submit() sends multiple HTTP POSTS
+ <!-- Jetty libraries needed for Testing BR [ 2264431 ] form.submit() sends multiple HTTP POSTS
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty</artifactId>
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <rus...@us...> - 2012-09-09 17:16:48
|
Revision: 1081
http://httpunit.svn.sourceforge.net/httpunit/?rev=1081&view=rev
Author: russgold
Date: 2012-09-09 17:16:39 +0000 (Sun, 09 Sep 2012)
Log Message:
-----------
switch to JUnit4
Modified Paths:
--------------
trunk/httpunit/pending-tests/com/meterware/httpunit/NewParsingTests.java
trunk/httpunit/pending-tests/com/meterware/httpunit/javascript/NewScriptingEngineTests.java
trunk/httpunit/pending-tests/com/meterware/httpunit/javascript/NewScriptingTests.java
trunk/httpunit/src/main/java/com/meterware/pseudoserver/HttpUserAgentTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/Base64Test.java
trunk/httpunit/src/test/java/com/meterware/httpunit/EncodingTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/FileUploadTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/FormParametersTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/FormSubmitTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/HtmlTablesTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/HttpUnitTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/MessageBodyRequestTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/NormalizeURLTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/RequestTargetTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/TextBlockTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/WebAppletTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/WebClientTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/WebFormTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/WebFrameTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/WebImageTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/WebLinkTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/WebPageTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/WebWindowTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/XMLPageTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/cookies/CookieTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/dom/AbstractHTMLElementTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/dom/AttributesTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/dom/DocumentImportTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/dom/DomEventScriptingTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/dom/DomScriptingTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/dom/DomWindowTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/dom/HTMLDocumentTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/dom/HTMLElementTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/dom/HTMLFormSubmitTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/dom/HTMLFormTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/dom/HTMLSelectTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/dom/HTMLTableTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/dom/NodeTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/dom/TestWindowProxy.java
trunk/httpunit/src/test/java/com/meterware/httpunit/javascript/AbstractJavaScriptTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/javascript/DocumentScriptingTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/javascript/EventHandlingTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/javascript/FormScriptingTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/javascript/FrameScriptingTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/javascript/HTMLElementTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/javascript/NekoEnhancedScriptingTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/javascript/ScriptingTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/parsing/HTMLParserListenerTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/parsing/ParserPropertiesTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/ssl/HttpsProtocolSupportTest.java
trunk/httpunit/src/test/java/com/meterware/pseudoserver/PseudoServerTest.java
trunk/httpunit/src/test/java/com/meterware/servletunit/ConfigTest.java
trunk/httpunit/src/test/java/com/meterware/servletunit/ErrorTests.java
trunk/httpunit/src/test/java/com/meterware/servletunit/EventAwareTestBase.java
trunk/httpunit/src/test/java/com/meterware/servletunit/FailingTests.java
trunk/httpunit/src/test/java/com/meterware/servletunit/HttpServletRequestTest.java
trunk/httpunit/src/test/java/com/meterware/servletunit/HttpServletResponseTest.java
trunk/httpunit/src/test/java/com/meterware/servletunit/JUnitServletTest.java
trunk/httpunit/src/test/java/com/meterware/servletunit/ListenersTest.java
trunk/httpunit/src/test/java/com/meterware/servletunit/NavigationTest.java
trunk/httpunit/src/test/java/com/meterware/servletunit/PassingTests.java
trunk/httpunit/src/test/java/com/meterware/servletunit/PostTest.java
trunk/httpunit/src/test/java/com/meterware/servletunit/RequestContextTest.java
trunk/httpunit/src/test/java/com/meterware/servletunit/RequestDispatcherTest.java
trunk/httpunit/src/test/java/com/meterware/servletunit/ServletAccessTest.java
trunk/httpunit/src/test/java/com/meterware/servletunit/ServletUnitTest.java
trunk/httpunit/src/test/java/com/meterware/servletunit/SessionTest.java
trunk/httpunit/src/test/java/com/meterware/servletunit/StatefulTest.java
trunk/httpunit/src/test/java/com/meterware/servletunit/StatelessTest.java
trunk/httpunit/src/test/java/com/meterware/servletunit/WebXMLString.java
trunk/httpunit/src/test/java/com/meterware/servletunit/WebXMLTest.java
Added Paths:
-----------
trunk/httpunit/src/main/java/com/meterware/pseudoserver/PseudoServerTestSupport.java
trunk/httpunit/src/test/java/com/meterware/servletunit/FiltersTestCase.java
Removed Paths:
-------------
trunk/httpunit/src/test/java/com/meterware/httpunit/ConditionalTestSuite.java
trunk/httpunit/src/test/java/com/meterware/httpunit/HttpUnitSuite.java
trunk/httpunit/src/test/java/com/meterware/httpunit/dom/DomTestSuite.java
trunk/httpunit/src/test/java/com/meterware/httpunit/javascript/JavaScriptTestSuite.java
trunk/httpunit/src/test/java/com/meterware/httpunit/parsing/ParsingTestSuite.java
trunk/httpunit/src/test/java/com/meterware/servletunit/FiltersTest.java
trunk/httpunit/src/test/java/com/meterware/servletunit/ServletUnitSuite.java
Modified: trunk/httpunit/pending-tests/com/meterware/httpunit/NewParsingTests.java
===================================================================
--- trunk/httpunit/pending-tests/com/meterware/httpunit/NewParsingTests.java 2012-09-07 12:36:13 UTC (rev 1080)
+++ trunk/httpunit/pending-tests/com/meterware/httpunit/NewParsingTests.java 2012-09-09 17:16:39 UTC (rev 1081)
@@ -19,12 +19,6 @@
* DEALINGS IN THE SOFTWARE.
*
*******************************************************************************************************************/
-import com.meterware.httpunit.HttpUnitTest;
-import com.meterware.httpunit.WebClient;
-import com.meterware.httpunit.WebConversation;
-import com.meterware.httpunit.WebForm;
-import com.meterware.httpunit.WebLink;
-import com.meterware.httpunit.WebResponse;
import junit.framework.Test;
import junit.framework.TestSuite;
@@ -62,10 +56,10 @@
*/
public void testLinkUrlAcrossLineBreaks() throws Exception {
WebConversation wc = new WebConversation();
- defineWebPage( "Initial", "<a id='midbreak' href='http://loc\nalhost/somewhere'</a>" +
- "<a id='endbreak' href='http://localhost/somewhere\n'</a>" );
+ pseudoServerTestSupport.defineWebPage("Initial", "<a id='midbreak' href='http://loc\nalhost/somewhere'</a>" +
+ "<a id='endbreak' href='http://localhost/somewhere\n'</a>");
- WebResponse response = wc.getResponse( getHostPath() + "/Initial.html" );
+ WebResponse response = wc.getResponse(pseudoServerTestSupport.getHostPath() + "/Initial.html" );
String endbreak=response.getLinkWithID( "endbreak" ).getRequest().getURL().toExternalForm() ;
assertEquals( "URL with break at end", endbreak,"http://localhost/somewhere");
//System.err.println("endbreak='"+endbreak+"'");
@@ -83,8 +77,8 @@
public void testParamReplacement() throws Exception {
String expected = "/cgi-bin/bar?foo=a";
String nogood = "/cgi-bin/bar?arg=replaced&foo=a";
- defineResource( nogood, "not good" );
- defineResource( expected, "excellent" );
+ pseudoServerTestSupport.defineResource(nogood, "not good");
+ pseudoServerTestSupport.defineResource(expected, "excellent");
String html =
"<FORM NAME=Bethsheba METHOD=GET ACTION=/cgi-bin/bar?arg=replaced>" +
"<INPUT TYPE=TEXT NAME=foo>" +
@@ -94,8 +88,8 @@
"<!--JavaScript submit:" +
"<a href=\"javascript:document.Bethsheba.submit()\">go</a>" +
"-->";
- defineWebPage( "test", html );
- WebResponse resp = _wc.getResponse( getHostPath() + "/test.html" );
+ pseudoServerTestSupport.defineWebPage("test", html);
+ WebResponse resp = _wc.getResponse(pseudoServerTestSupport.getHostPath() + "/test.html" );
WebForm form = resp.getFormWithName( "Bethsheba" );
form.setParameter( "foo", "a" );
resp = form.submit();
@@ -115,7 +109,7 @@
"</SCRIPT>\n" +
"<iframe name=\"iframe_after_lessthan_in_javascript\"\n" +
"src=\"c.html\"></iframe>";
- defineWebPage( "iframe", html );
+ pseudoServerTestSupport.defineWebPage("iframe", html);
WebResponse response = _wc.getFrameContents( "iframe_after_lessthan_in_javascript" );
assertNotNull( "Iframe was not recognized", response );
}
@@ -127,11 +121,11 @@
* @throws Exception on anuncaught error
*/
public void testFindNonHrefLinks() throws Exception {
- defineResource( "NonHref.html", "<html><head><title>NonHref Links</title></head><body>\n" +
+ pseudoServerTestSupport.defineResource("NonHref.html", "<html><head><title>NonHref Links</title></head><body>\n" +
"<a onclick='javascript:followlink()'>I am a clickable link after all</a>\n" +
- "</body></html>" );
+ "</body></html>");
WebConversation wc = new WebConversation();
- WebResponse response = wc.getResponse( getHostPath() + "/NonHref.html" );
+ WebResponse response = wc.getResponse(pseudoServerTestSupport.getHostPath() + "/NonHref.html" );
WebLink[] links = response.getLinks();
assertNotNull( links );
assertEquals( "number of non-href anchor tags", 1, links.length );
Modified: trunk/httpunit/pending-tests/com/meterware/httpunit/javascript/NewScriptingEngineTests.java
===================================================================
--- trunk/httpunit/pending-tests/com/meterware/httpunit/javascript/NewScriptingEngineTests.java 2012-09-07 12:36:13 UTC (rev 1080)
+++ trunk/httpunit/pending-tests/com/meterware/httpunit/javascript/NewScriptingEngineTests.java 2012-09-09 17:16:39 UTC (rev 1081)
@@ -20,7 +20,6 @@
*
*******************************************************************************************************************/
import com.meterware.httpunit.*;
-import com.meterware.httpunit.javascript.AbstractJavaScriptTest;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
@@ -52,13 +51,13 @@
* @throws Exception on uncaught problem
*/
public void testCreateElement() throws Exception {
- defineResource( "OnCommand.html",
+ pseudoServerTestSupport.defineResource("OnCommand.html",
"<html><head><title>Amazing!</title></head>" +
- "<body onLoad='var elem=document.createElement(\"input\");elem.id=\"hellothere\";alert(elem.id);'></body>" );
+ "<body onLoad='var elem=document.createElement(\"input\");elem.id=\"hellothere\";alert(elem.id);'></body>");
WebConversation wc = new WebConversation();
boolean oldDebug = HttpUnitUtils.setEXCEPTION_DEBUG( false );
try {
- wc.getResponse( getHostPath() + "/OnCommand.html" );
+ wc.getResponse(pseudoServerTestSupport.getHostPath() + "/OnCommand.html" );
// used to throw:
// com.meterware.httpunit.ScriptException: Event 'var elem=document.createElement("input");elem.id="hellothere";alert(elem.id);' failed: org.mozilla.javascript.EcmaError: TypeError: Cannot find function createElement.
assertEquals( "Alert message", "hellothere", wc.popNextAlert() );
@@ -87,7 +86,7 @@
* @throws Exception on any uncaught problem
*/
public void testDOM() throws Exception {
- defineResource( "testSelect.html", "<html><head><script type='text/javascript'>\n" +
+ pseudoServerTestSupport.defineResource("testSelect.html", "<html><head><script type='text/javascript'>\n" +
"<!--\n" +
"function testDOM() {\n" +
" var sel = document.getElementById('the_select');\n" +
@@ -112,9 +111,9 @@
" </table>" +
"</form>" +
"<script type='text/javascript'>testDOM();</script>" +
- "</body></html>" );
+ "</body></html>");
WebConversation wc = new WebConversation();
- wc.getResponse( getHostPath() + "/testSelect.html" );
+ wc.getResponse(pseudoServerTestSupport.getHostPath() + "/testSelect.html" );
assertEquals( "Message 1", "TD", wc.popNextAlert().toUpperCase() );
assertEquals( "Message 2", "SELECT", wc.popNextAlert().toUpperCase() );
}
Modified: trunk/httpunit/pending-tests/com/meterware/httpunit/javascript/NewScriptingTests.java
===================================================================
--- trunk/httpunit/pending-tests/com/meterware/httpunit/javascript/NewScriptingTests.java 2012-09-07 12:36:13 UTC (rev 1080)
+++ trunk/httpunit/pending-tests/com/meterware/httpunit/javascript/NewScriptingTests.java 2012-09-09 17:16:39 UTC (rev 1081)
@@ -22,7 +22,6 @@
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.HttpUnitOptions;
-import com.meterware.httpunit.javascript.AbstractJavaScriptTest;
import junit.textui.TestRunner;
import junit.framework.TestSuite;
@@ -68,9 +67,9 @@
"<body onload=\"dumpargs('a','b')\"> " +
"</body></html> ";
- defineResource( "OnCommand.html", html );
+ pseudoServerTestSupport.defineResource("OnCommand.html", html);
WebConversation wc = new WebConversation();
- wc.getResponse( getHostPath() + "/OnCommand.html" );
+ wc.getResponse(pseudoServerTestSupport.getHostPath() + "/OnCommand.html" );
assertEquals( "alert message 1", "2 arguments", wc.popNextAlert() );
assertEquals( "alert message 2", "0: a", wc.popNextAlert() );
assertEquals( "alert message 3", "1: b", wc.popNextAlert() );
Modified: trunk/httpunit/src/main/java/com/meterware/pseudoserver/HttpUserAgentTest.java
===================================================================
--- trunk/httpunit/src/main/java/com/meterware/pseudoserver/HttpUserAgentTest.java 2012-09-07 12:36:13 UTC (rev 1080)
+++ trunk/httpunit/src/main/java/com/meterware/pseudoserver/HttpUserAgentTest.java 2012-09-09 17:16:39 UTC (rev 1081)
@@ -24,68 +24,66 @@
import java.util.StringTokenizer;
import java.io.IOException;
-import junit.framework.TestCase;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import static org.junit.Assert.fail;
+import static org.junit.Assert.assertEquals;
+
/**
* A base class for test cases that use the pseudo server.
* @author <a href="mailto:rus...@ht...">Russell Gold</a>
**/
-public class HttpUserAgentTest extends TestCase {
+public class HttpUserAgentTest {
- private String _hostPath;
- private PseudoServer _server;
+ private static final PseudoServerTestSupport testSupport = new PseudoServerTestSupport();
- public HttpUserAgentTest( String name ) {
- super( name );
+ @BeforeClass
+ static public void setUpHttpUserAgentTest() throws Exception {
+ testSupport.setUpServer();
}
- public void setUp() throws Exception {
- _server = new PseudoServer();
- _hostPath = "http://localhost:" + _server.getConnectedPort();
+ @AfterClass
+ static public void tearDownHttpUserAgentTest() throws Exception {
+ testSupport.tearDownServer();
}
- public void tearDown() throws Exception {
- if (_server != null) _server.shutDown();
- }
-
-
protected void defineResource( String resourceName, PseudoServlet servlet ) {
- _server.setResource( resourceName, servlet );
+ testSupport.defineResource(resourceName, servlet);
}
protected void defineResource( String resourceName, String value ) {
- _server.setResource( resourceName, value );
+ testSupport.defineResource(resourceName, value);
}
protected void defineResource( String resourceName, byte[] value, String contentType ) {
- _server.setResource( resourceName, value, contentType );
+ testSupport.defineResource(resourceName, value, contentType);
}
protected void defineResource( String resourceName, String value, int statusCode ) {
- _server.setErrorResource( resourceName, statusCode, value );
+ testSupport.defineResource(resourceName, value, statusCode);
}
protected void defineResource( String resourceName, String value, String contentType ) {
- _server.setResource( resourceName, value, contentType );
+ testSupport.defineResource(resourceName, value, contentType);
}
protected void addResourceHeader( String resourceName, String header ) {
- _server.addResourceHeader( resourceName, header );
+ testSupport.addResourceHeader(resourceName, header);
}
protected void setResourceCharSet( String resourceName, String setName, boolean reportCharSet ) {
- _server.setCharacterSet( resourceName, setName );
- _server.setSendCharacterSet( resourceName, reportCharSet );
+ testSupport.setResourceCharSet(resourceName, setName, reportCharSet);
}
/**
@@ -96,17 +94,8 @@
* @param body
*/
protected void defineWebPage( String xmlns,String pageName, String body ) {
- String preamble="";
- if (xmlns==null)
- xmlns="";
- else {
- preamble ="<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n";
- preamble+="<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n";
- xmlns=" xmlns=\""+xmlns+"\"";
- }
- defineResource( pageName + ".html", preamble+"<html"+xmlns+">\n<head><title>" + pageName + "</title></head>\n" +
- "<body>\n" + body + "\n</body>\n</html>" );
- }
+ testSupport.defineWebPage(xmlns, pageName, body);
+ }
/**
* define a Web Page with the given page name and boy adding the html and body tags with pageName as the title of the page
@@ -114,32 +103,32 @@
* @param body
*/
protected void defineWebPage( String pageName, String body ) {
- defineWebPage(null,pageName,body);
+ testSupport.defineWebPage(pageName, body);
}
protected void mapToClasspath( String directory ) {
- _server.mapToClasspath( directory );
+ testSupport.mapToClasspath(directory);
}
protected PseudoServer getServer() {
- return _server;
+ return testSupport.getServer();
}
protected void setServerDebug( boolean enabled ) {
- _server.setDebug( enabled );
+ testSupport.setServerDebug(enabled);
}
protected String getHostPath() {
- return _hostPath;
+ return testSupport.getHostPath();
}
protected int getHostPort() throws IOException {
- return _server.getConnectedPort();
+ return testSupport.getHostPort();
}
@@ -148,23 +137,6 @@
}
-
- protected void assertEquals( String comment, Object[] expected, Object[] found ) {
- if (!equals( expected, found )) {
- fail( comment + " expected: " + asText( expected ) + " but found " + asText( found ) );
- }
- }
-
-
- private boolean equals( Object[] first, Object[] second ) {
- if (first.length != second.length) return false;
- for (int i = 0; i < first.length; i++) {
- if (!first[ i ].equals( second[ i ] )) return false;
- }
- return true;
- }
-
-
protected void assertImplement( String comment, Object[] objects, Class expectedClass ) {
if (objects.length == 0) fail( "No " + comment + " found." );
for (int i = 0; i < objects.length; i++) {
@@ -254,11 +226,6 @@
}
- protected void assertEquals( String comment, byte[] expected, byte[] actual ) {
- assertEquals(comment,toString(expected),toString(actual));
- }
-
-
private boolean equals( byte[] first, byte[] second ) {
if (first.length != second.length) return false;
for (int i = 0; i < first.length; i++) {
Added: trunk/httpunit/src/main/java/com/meterware/pseudoserver/PseudoServerTestSupport.java
===================================================================
--- trunk/httpunit/src/main/java/com/meterware/pseudoserver/PseudoServerTestSupport.java (rev 0)
+++ trunk/httpunit/src/main/java/com/meterware/pseudoserver/PseudoServerTestSupport.java 2012-09-09 17:16:39 UTC (rev 1081)
@@ -0,0 +1,98 @@
+package com.meterware.pseudoserver;
+
+import java.io.IOException;
+
+public class PseudoServerTestSupport {
+ private String _hostPath;
+ private PseudoServer _server;
+
+ public void setUpServer() throws IOException {
+ _server = new PseudoServer();
+ _hostPath = "http://localhost:" + _server.getConnectedPort();
+ }
+
+ public void tearDownServer() {
+ if (_server != null) _server.shutDown();
+ }
+
+
+ public void mapToClasspath( String directory ) {
+ _server.mapToClasspath(directory);
+ }
+
+ public void defineResource(String resourceName, PseudoServlet servlet) {
+ _server.setResource(resourceName, servlet);
+ }
+
+ public void defineResource(String resourceName, String value) {
+ _server.setResource(resourceName, value);
+ }
+
+ public void defineResource(String resourceName, byte[] value, String contentType) {
+ _server.setResource(resourceName, value, contentType);
+ }
+
+ public void defineResource(String resourceName, String value, int statusCode) {
+ _server.setErrorResource(resourceName, statusCode, value);
+ }
+
+ public void defineResource(String resourceName, String value, String contentType) {
+ _server.setResource(resourceName, value, contentType);
+ }
+
+ public void addResourceHeader(String resourceName, String header) {
+ _server.addResourceHeader(resourceName, header);
+ }
+
+ public void setResourceCharSet(String resourceName, String setName, boolean reportCharSet) {
+ _server.setCharacterSet(resourceName, setName);
+ _server.setSendCharacterSet(resourceName, reportCharSet);
+ }
+
+ /**
+ * define a Web Page with the given page name and boy adding the html and body tags with pageName as the title of the page
+ * use the given xml names space if it is not null
+ *
+ * @param xmlns
+ * @param pageName
+ * @param body
+ */
+ public void defineWebPage(String xmlns, String pageName, String body) {
+ String preamble = "";
+ if (xmlns == null)
+ xmlns = "";
+ else {
+ preamble = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n";
+ preamble += "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n";
+ xmlns = " xmlns=\"" + xmlns + "\"";
+ }
+ defineResource(pageName + ".html", preamble + "<html" + xmlns + ">\n<head><title>" + pageName + "</title></head>\n" +
+ "<body>\n" + body + "\n</body>\n</html>");
+ }
+
+ /**
+ * define a Web Page with the given page name and boy adding the html and body tags with pageName as the title of the page
+ *
+ * @param pageName
+ * @param body
+ */
+ public void defineWebPage(String pageName, String body) {
+ defineWebPage(null, pageName, body);
+ }
+
+ public PseudoServer getServer() {
+ return _server;
+ }
+
+ public void setServerDebug(boolean enabled) {
+ _server.setDebug(enabled);
+ }
+
+ public String getHostPath() {
+ return _hostPath;
+ }
+
+ public int getHostPort() throws IOException {
+ return _server.getConnectedPort();
+ }
+}
\ No newline at end of file
Modified: trunk/httpunit/src/test/java/com/meterware/httpunit/Base64Test.java
===================================================================
--- trunk/httpunit/src/test/java/com/meterware/httpunit/Base64Test.java 2012-09-07 12:36:13 UTC (rev 1080)
+++ trunk/httpunit/src/test/java/com/meterware/httpunit/Base64Test.java 2012-09-09 17:16:39 UTC (rev 1081)
@@ -1,71 +1,60 @@
package com.meterware.httpunit;
/********************************************************************************************************************
-* $Id$
-*
-* Copyright (c) 2000-2001, Russell Gold
-*
-* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
-* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
-* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
-* to permit persons to whom the Software is furnished to do so, subject to the following conditions:
-*
-* The above copyright notice and this permission notice shall be included in all copies or substantial portions
-* of the Software.
-*
-* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
-* THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
-* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-* DEALINGS IN THE SOFTWARE.
-*
-*******************************************************************************************************************/
-import junit.framework.Test;
-import junit.framework.TestCase;
-import junit.framework.TestSuite;
+ * $Id$
+ *
+ * Copyright (c) 2000-2001, Russell Gold
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
+ * documentation files (the "Software"), to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
+ * to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions
+ * of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+ * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ *******************************************************************************************************************/
+import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+
/**
* Tests the base64 converter.
*
* @author <a href="mailto:rus...@ac...">Russell Gold</a>
- * @author <a href="mailto:mta...@si...">Marcos Tarruella</a>
- **/
-public class Base64Test extends TestCase {
+ * @author <a href="mailto:mta...@si...">Marcos Tarruella</a>
+ */
+public class Base64Test {
- public static void main( String[] args ) {
- junit.textui.TestRunner.run( suite() );
- }
-
-
- public static Test suite() {
- return new TestSuite( Base64Test.class );
- }
-
-
- public Base64Test( String name ) {
- super( name );
- }
-
-
+ @Test
public void testEncode() {
- assertEquals( "Result of encoding", "QWxhZGRpbjpvcGVuIHNlc2FtZQ==", Base64.encode( "Aladdin:open sesame" ) );
- assertEquals( "Result of encoding", "QWRtaW46Zm9vYmFy", Base64.encode( "Admin:foobar" ) );
+ assertEquals("Result of encoding", "QWxhZGRpbjpvcGVuIHNlc2FtZQ==", Base64.encode("Aladdin:open sesame"));
+ assertEquals("Result of encoding", "QWRtaW46Zm9vYmFy", Base64.encode("Admin:foobar"));
}
+ @Test
public void testDecode() {
- assertEquals( "Result of decoding", "Aladdin:open sesame", Base64.decode( "QWxhZGRpbjpvcGVuIHNlc2FtZQ==" ) );
- assertEquals( "Result of decoding", "Admin:foobar", Base64.decode( "QWRtaW46Zm9vYmFy" ) );
+ assertEquals("Result of decoding", "Aladdin:open sesame", Base64.decode("QWxhZGRpbjpvcGVuIHNlc2FtZQ=="));
+ assertEquals("Result of decoding", "Admin:foobar", Base64.decode("QWRtaW46Zm9vYmFy"));
}
+ @Test
public void testExceptionDecoding() {
try {
- Base64.decode( "123");
+ Base64.decode("123");
fail("valid Base64 codes have a multiple of 4 characters");
} catch (Exception e) {
assertEquals("valid Base64 codes have a multiple of 4 characters",
- e.getMessage());
+ e.getMessage());
}
}
Deleted: trunk/httpunit/src/test/java/com/meterware/httpunit/ConditionalTestSuite.java
===================================================================
--- trunk/httpunit/src/test/java/com/meterware/httpunit/ConditionalTestSuite.java 2012-09-07 12:36:13 UTC (rev 1080)
+++ trunk/httpunit/src/test/java/com/meterware/httpunit/ConditionalTestSuite.java 2012-09-09 17:16:39 UTC (rev 1081)
@@ -1,54 +0,0 @@
-package com.meterware.httpunit;
-/********************************************************************************************************************
- * $Id$
- *
- * Copyright (c) 2002-2004, Russell Gold
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
- * documentation files (the "Software"), to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
- * to permit persons to whom the Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in all copies or substantial portions
- * of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
- * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- *
- *******************************************************************************************************************/
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-
-import junit.framework.TestSuite;
-import junit.framework.TestCase;
-
-/**
- *
- * @author <a href="mailto:rus...@ht...">Russell Gold</a>
- **/
-public class ConditionalTestSuite {
-
- private static Class[] NO_PARAMETERS = new Class[ 0 ];
-
-
- protected static void addOptionalTestCase( TestSuite testSuite, String testCaseName ) {
- try {
- final Class testClass = Class.forName( testCaseName );
- Method suiteMethod = testClass.getMethod( "suite", ConditionalTestSuite.NO_PARAMETERS );
- if (suiteMethod != null && Modifier.isStatic( suiteMethod.getModifiers() )) {
- testSuite.addTest( (TestSuite) suiteMethod.invoke( null, ConditionalTestSuite.NO_PARAMETERS ) );
- } else if (TestCase.class.isAssignableFrom( testClass )) {
- testSuite.addTest( new TestSuite( testClass ) );
- } else {
- System.out.println( "Note: test suite " + testCaseName + " not a TestClass and has no suite() method" );
- }
- } catch (ClassNotFoundException e) {
- System.out.println( "Note: skipping optional test suite " + testCaseName + " since it was not built." );
- } catch (Exception e) {
- System.out.println( "Note: unable to add " + testCaseName + ": " + e );
- }
- }
-}
Modified: trunk/httpunit/src/test/java/com/meterware/httpunit/EncodingTest.java
===================================================================
--- trunk/httpunit/src/test/java/com/meterware/httpunit/EncodingTest.java 2012-09-07 12:36:13 UTC (rev 1080)
+++ trunk/httpunit/src/test/java/com/meterware/httpunit/EncodingTest.java 2012-09-09 17:16:39 UTC (rev 1081)
@@ -2,7 +2,7 @@
/********************************************************************************************************************
* $Id$
*
- * Copyright (c) 2004, Russell Gold
+ * Copyright (c) 2004-2012, Russell Gold
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
@@ -19,270 +19,275 @@
* DEALINGS IN THE SOFTWARE.
*
*******************************************************************************************************************/
-import junit.framework.TestSuite;
+
import com.meterware.pseudoserver.PseudoServlet;
import com.meterware.pseudoserver.WebResource;
+import org.junit.Test;
+import java.io.UnsupportedEncodingException;
+import static org.junit.Assert.assertEquals;
+
+
/**
* Tests handling of non-Latin scripts.
*
* @author <a href="mailto:rus...@ht...">Russell Gold</a>
* @author <a href="mailto:mat...@qu...">Kazuaki Matsuhashi</a>
- **/
+ */
public class EncodingTest extends HttpUnitTest {
- public static void main( String args[] ) {
- junit.textui.TestRunner.run( suite() );
- }
-
-
- public static TestSuite suite() {
- return new TestSuite( EncodingTest.class );
- }
-
-
- public EncodingTest( String name ) {
- super( name );
- }
-
-
+ @Test
public void testDecodeWithCharacterSetAsArg() throws Exception {
String expected = "newpage\u30b5\u30f3\u30d7\u30eb"; // "\u30b5\u30f3\u30d7\u30eb" means "SAMPLE" in Japanese EUC-JP characterSet
String encodedString = "newpage%A5%B5%A5%F3%A5%D7%A5%EB";
- String actual = HttpUnitUtils.decode( encodedString , "EUC-JP" );
- assertEquals( "decoded string" , expected , actual);
+ String actual = HttpUnitUtils.decode(encodedString, "EUC-JP");
+ assertEquals("decoded string", expected, actual);
}
-
+
/**
* test parseContentHeader
+ *
* @throws Exception
*/
+ @Test
public void testParseContentHeader() throws Exception {
- String headers[]={
- "",
- "text/plain",
- "text/html; charset=Cp1252",
- "text/html; charset=iso-8859-8",
- "text/html; charset=EUC-JP",
- "text/html charset=windows-1251",
- "text/html; charset=utf-8",
- "text/html; charset = utf-8",
- "text/html; charset=\"iso-8859-8\""
- };
- String expected[][]={
- {"text/plain",null},
- {"text/plain",null},
- {"text/html","Cp1252"},
- {"text/html","iso-8859-8"},
- {"text/html","EUC-JP"},
- {"text/html","windows-1251"},
- {"text/html","utf-8"},
- {"text/html","utf-8"},
- {"text/html","iso-8859-8"}
- };
- for (int i=0;i<headers.length;i++) {
- String result[]=HttpUnitUtils.parseContentTypeHeader(headers[i]);
- assertEquals(2, result.length);
- assertEquals( "header "+i , expected[i][0] , result[0]);
- assertEquals( "header "+i , expected[i][1] , result[1]);
- } // for
+ String headers[] = {
+ "",
+ "text/plain",
+ "text/html; charset=Cp1252",
+ "text/html; charset=iso-8859-8",
+ "text/html; charset=EUC-JP",
+ "text/html charset=windows-1251",
+ "text/html; charset=utf-8",
+ "text/html; charset = utf-8",
+ "text/html; charset=\"iso-8859-8\""
+ };
+ String expected[][] = {
+ {"text/plain", null},
+ {"text/plain", null},
+ {"text/html", "Cp1252"},
+ {"text/html", "iso-8859-8"},
+ {"text/html", "EUC-JP"},
+ {"text/html", "windows-1251"},
+ {"text/html", "utf-8"},
+ {"text/html", "utf-8"},
+ {"text/html", "iso-8859-8"}
+ };
+ for (int i = 0; i < headers.length; i++) {
+ String result[] = HttpUnitUtils.parseContentTypeHeader(headers[i]);
+ assertEquals(2, result.length);
+ assertEquals("header " + i, expected[i][0], result[0]);
+ assertEquals("header " + i, expected[i][1], result[1]);
+ } // for
}
+ @Test
public void testSpecifiedEncoding() throws Exception {
String hebrewTitle = "\u05d0\u05d1\u05d2\u05d3";
String page = "<html><head><title>" + hebrewTitle + "</title></head>\n" +
- "<body>This has no data\n" +
- "</body></html>\n";
- defineResource( "SimplePage.html", page );
- setResourceCharSet( "SimplePage.html", "iso-8859-8", true );
+ "<body>This has no data\n" +
+ "</body></html>\n";
+ defineResource("SimplePage.html", page);
+ setResourceCharSet("SimplePage.html", "iso-8859-8", true);
WebConversation wc = new WebConversation();
- WebRequest request = new GetMethodWebRequest( getHostPath() + "/SimplePage.html" );
- WebResponse simplePage = wc.getResponse( request );
+ WebRequest request = new GetMethodWebRequest(getHostPath() + "/SimplePage.html");
+ WebResponse simplePage = wc.getResponse(request);
- assertEquals( "Title", hebrewTitle, simplePage.getTitle() );
- assertEquals( "Character set", "iso-8859-8", simplePage.getCharacterSet() );
+ assertEquals("Title", hebrewTitle, simplePage.getTitle());
+ assertEquals("Character set", "iso-8859-8", simplePage.getCharacterSet());
}
+ @Test
public void testQuotedEncoding() throws Exception {
String hebrewTitle = "\u05d0\u05d1\u05d2\u05d3";
String page = "<html><head><title>" + hebrewTitle + "</title></head>\n" +
- "<body>This has no data\n" +
- "</body></html>\n";
- defineResource( "SimplePage.html", page );
- setResourceCharSet( "SimplePage.html", "\"iso-8859-8\"", true );
+ "<body>This has no data\n" +
+ "</body></html>\n";
+ defineResource("SimplePage.html", page);
+ setResourceCharSet("SimplePage.html", "\"iso-8859-8\"", true);
WebConversation wc = new WebConversation();
- WebRequest request = new GetMethodWebRequest( getHostPath() + "/SimplePage.html" );
- WebResponse simplePage = wc.getResponse( request );
+ WebRequest request = new GetMethodWebRequest(getHostPath() + "/SimplePage.html");
+ WebResponse simplePage = wc.getResponse(request);
- assertEquals( "Title", hebrewTitle, simplePage.getTitle() );
- assertEquals( "Character set", "iso-8859-8", simplePage.getCharacterSet() );
+ assertEquals("Title", hebrewTitle, simplePage.getTitle());
+ assertEquals("Character set", "iso-8859-8", simplePage.getCharacterSet());
}
+ @Test
public void testUnspecifiedEncoding() throws Exception {
String hebrewTitle = "\u05d0\u05d1\u05d2\u05d3";
String page = "<html><head><title>" + hebrewTitle + "</title></head>\n" +
- "<body>This has no data\n" +
- "</body></html>\n";
- defineResource( "SimplePage.html", page );
- setResourceCharSet( "SimplePage.html", "iso-8859-8", false );
+ "<body>This has no data\n" +
+ "</body></html>\n";
+ defineResource("SimplePage.html", page);
+ setResourceCharSet("SimplePage.html", "iso-8859-8", false);
- HttpUnitOptions.setDefaultCharacterSet( "iso-8859-8" );
+ HttpUnitOptions.setDefaultCharacterSet("iso-8859-8");
WebConversation wc = new WebConversation();
- WebRequest request = new GetMethodWebRequest( getHostPath() + "/SimplePage.html" );
- WebResponse simplePage = wc.getResponse( request );
+ WebRequest request = new GetMethodWebRequest(getHostPath() + "/SimplePage.html");
+ WebResponse simplePage = wc.getResponse(request);
- assertEquals( "Character set", "iso-8859-8", simplePage.getCharacterSet() );
- assertEquals( "Title", hebrewTitle, simplePage.getTitle() );
+ assertEquals("Character set", "iso-8859-8", simplePage.getCharacterSet());
+ assertEquals("Title", hebrewTitle, simplePage.getTitle());
}
- public void testMetaEncoding() throws Exception {
- String hebrewTitle = "\u05d0\u05d1\u05d2\u05d3";
- String page = "<html><head><title>" + hebrewTitle + "</title>" +
- "<meta Http_equiv=content-type content=\"text/html; charset=iso-8859-8\"></head>\n" +
- "<body>This has no data\n" +
- "</body></html>\n";
- defineResource( "SimplePage.html", page );
- setResourceCharSet( "SimplePage.html", "iso-8859-8", false );
+ @Test
+ public void testMetaEncoding() throws Exception {
+ String hebrewTitle = "\u05d0\u05d1\u05d2\u05d3";
+ String page = "<html><head><title>" + hebrewTitle + "</title>" +
+ "<meta Http_equiv=content-type content=\"text/html; charset=iso-8859-8\"></head>\n" +
+ "<body>This has no data\n" +
+ "</body></html>\n";
+ defineResource("SimplePage.html", page);
+ setResourceCharSet("SimplePage.html", "iso-8859-8", false);
- WebConversation wc = new WebConversation();
- WebRequest request = new GetMethodWebRequest( getHostPath() + "/SimplePage.html" );
- WebResponse simplePage = wc.getResponse( request );
+ WebConversation wc = new WebConversation();
+ WebRequest request = new GetMethodWebRequest(getHostPath() + "/SimplePage.html");
+ WebResponse simplePage = wc.getResponse(request);
- assertEquals( "Character set", "iso-8859-8", simplePage.getCharacterSet() );
- assertEquals( "Title", hebrewTitle, simplePage.getTitle() );
+ assertEquals("Character set", "iso-8859-8", simplePage.getCharacterSet());
+ assertEquals("Title", hebrewTitle, simplePage.getTitle());
}
+ @Test
public void testHebrewForm() throws Exception {
String hebrewName = "\u05d0\u05d1\u05d2\u05d3";
- defineResource( "HebrewForm.html",
- "<html><head></head>" +
+ defineResource("HebrewForm.html",
+ "<html><head></head>" +
"<form method=POST action=\"SayHello\">" +
- "<input type=text name=name><input type=submit></form></body></html>" );
- setResourceCharSet( "HebrewForm.html", "iso-8859-8", true );
- defineResource( "SayHello", new PseudoServlet() {
+ "<input type=text name=name><input type=submit></form></body></html>");
+ setResourceCharSet("HebrewForm.html", "iso-8859-8", true);
+ defineResource("SayHello", new PseudoServlet() {
public WebResource getPostResponse() {
try {
- String name = getParameter( "name" )[0];
- WebResource result = new WebResource( "<html><body><table><tr><td>Hello, " +
- new String( name.getBytes( "iso-8859-1" ), "iso-8859-8" ) +
- "</td></tr></table></body></html>" );
- result.setCharacterSet( "iso-8859-8" );
- result.setSendCharacterSet( true );
+ String name = getParameter("name")[0];
+ WebResource result = new WebResource("<html><body><table><tr><td>Hello, " +
+ new String(name.getBytes("iso-8859-1"), "iso-8859-8") +
+ "</td></tr></table></body></html>");
+ result.setCharacterSet("iso-8859-8");
+ result.setSendCharacterSet(true);
return result;
- } catch (java.io.UnsupportedEncodingException e) {
+ } catch (UnsupportedEncodingException e) {
return null;
}
}
- } );
+ });
WebConversation wc = new WebConversation();
- WebResponse formPage = wc.getResponse( getHostPath() + "/HebrewForm.html" );
+ WebResponse formPage = wc.getResponse(getHostPath() + "/HebrewForm.html");
WebForm form = formPage.getForms()[0];
WebRequest request = form.getRequest();
- request.setParameter( "name", hebrewName );
+ request.setParameter("name", hebrewName);
- WebResponse answer = wc.getResponse( request );
+ WebResponse answer = wc.getResponse(request);
String[][] cells = answer.getTables()[0].asText();
- assertEquals( "Message", "Hello, " + hebrewName, cells[0][0] );
- assertEquals( "Character set", "iso-8859-8", answer.getCharacterSet() );
+ assertEquals("Message", "Hello, " + hebrewName, cells[0][0]);
+ assertEquals("Character set", "iso-8859-8", answer.getCharacterSet());
}
+ @Test
public void testEncodedRequestWithoutForm() throws Exception {
String hebrewName = "\u05d0\u05d1\u05d2\u05d3";
- defineResource( "SayHello", new PseudoServlet() {
+ defineResource("SayHello", new PseudoServlet() {
public WebResource getPostResponse() {
try {
- String name = getParameter( "name" )[0];
- WebResource result = new WebResource( "<html><body><table><tr><td>Hello, " +
- new String( name.getBytes( "iso-8859-1" ), "iso-8859-8" ) +
- "</td></tr></table></body></html>" );
- result.setCharacterSet( "iso-8859-8" );
- result.setSendCharacterSet( true );
+ String name = getParameter("name")[0];
+ WebResource result = new WebResource("<html><body><table><tr><td>Hello, " +
+ new String(name.getBytes("iso-8859-1"), "iso-8859-8") +
+ "</td></tr></table></body></html>");
+ result.setCharacterSet("iso-8859-8");
+ result.setSendCharacterSet(true);
return result;
- } catch (java.io.UnsupportedEncodingException e) {
+ } catch (UnsupportedEncodingException e) {
return null;
}
}
- } );
+ });
WebConversation wc = new WebConversation();
- HttpUnitOptions.setDefaultCharacterSet( "iso-8859-8" );
- WebRequest request = new PostMethodWebRequest( getHostPath() + "/SayHello" );
- request.setParameter( "name", hebrewName );
+ HttpUnitOptions.setDefaultCharacterSet("iso-8859-8");
+ WebRequest request = new PostMethodWebRequest(getHostPath() + "/SayHello");
+ request.setParameter("name", hebrewName);
- WebResponse answer = wc.getResponse( request );
+ WebResponse answer = wc.getResponse(request);
String[][] cells = answer.getTables()[0].asText();
- assertEquals( "Message", "Hello, " + hebrewName, cells[0][0] );
- assertEquals( "Character set", "iso-8859-8", answer.getCharacterSet() );
+ assertEquals("Message", "Hello, " + hebrewName, cells[0][0]);
+ assertEquals("Character set", "iso-8859-8", answer.getCharacterSet());
}
+ @Test
public void testUnsupportedEncoding() throws Exception {
- defineResource( "SimplePage.html", "not much here" );
- addResourceHeader( "SimplePage.html", "Content-type: text/plain; charset=BOGUS");
+ defineResource("SimplePage.html", "not much here");
+ addResourceHeader("SimplePage.html", "Content-type: text/plain; charset=BOGUS");
WebConversation wc = new WebConversation();
- WebRequest request = new GetMethodWebRequest( getHostPath() + "/SimplePage.html" );
- WebResponse simplePage = wc.getResponse( request );
+ WebRequest request = new GetMethodWebRequest(getHostPath() + "/SimplePage.html");
+ WebResponse simplePage = wc.getResponse(request);
- assertEquals( "Text", "not much here", simplePage.getText() );
- assertEquals( "Character set", WebResponse.getDefaultEncoding(), simplePage.getCharacterSet() );
+ assertEquals("Text", "not much here", simplePage.getText());
+ assertEquals("Character set", WebResponse.getDefaultEncoding(), simplePage.getCharacterSet());
}
+ @Test
public void testJapaneseLinkParamNameWithValue() throws Exception {
String japaneseUrl = "request?%A5%D8%A5%EB%A5%D7=2";
- defineWebPage( "Linker", "<a id='link' href='" + japaneseUrl + "'>goThere</a>" );
- setResourceCharSet( "Linker.html", "EUC-JP", true );
- defineResource( japaneseUrl, "You made it!" );
+ defineWebPage("Linker", "<a id='link' href='" + japaneseUrl + "'>goThere</a>");
+ setResourceCharSet("Linker.html", "EUC-JP", true);
+ defineResource(japaneseUrl, "You made it!");
WebConversation wc = new WebConversation();
- WebResponse formPage = wc.getResponse( getHostPath() + "/Linker.html" );
- WebResponse target = formPage.getLinkWithID( "link" ).click();
- assertEquals( "Resultant page", "You made it!", target.getText() );
+ WebResponse formPage = wc.getResponse(getHostPath() + "/Linker.html");
+ WebResponse target = formPage.getLinkWithID("link").click();
+ assertEquals("Resultant page", "You made it!", target.getText());
}
+ @Test
public void testJapaneseLinkParamNameWithoutValue() throws Exception {
String japaneseUrl = "request?%A5%D8%A5%EB%A5%D7";
- defineWebPage( "Linker", "<a id='link' href='" + japaneseUrl + "'>goThere</a>" );
- setResourceCharSet( "Linker.html", "EUC-JP", true );
- defineResource( japaneseUrl, "You made it!" );
+ defineWebPage("Linker", "<a id='link' href='" + japaneseUrl + "'>goThere</a>");
+ setResourceCharSet("Linker.html", "EUC-JP", true);
+ defineResource(japaneseUrl, "You made it!");
WebConversation wc = new WebConversation();
- WebResponse formPage = wc.getResponse( getHostPath() + "/Linker.html" );
- WebResponse target = formPage.getLinkWithID( "link" ).click();
- assertEquals( "Resultant page", "You made it!", target.getText() );
+ WebResponse formPage = wc.getResponse(getHostPath() + "/Linker.html");
+ WebResponse target = formPage.getLinkWithID("link").click();
+ assertEquals("Resultant page", "You made it!", target.getText());
}
+ @Test
public void testSimpleEntityReplacement() throws Exception {
String rawString = "Cox&&Forkum";
- assertEquals( "After substitution", "Cox&&Forkum", HttpUnitUtils.replaceEntities( rawString ) );
+ assertEquals("After substitution", "Cox&&Forkum", HttpUnitUtils.replaceEntities(rawString));
}
+ @Test
public void testSkipEntityReplacementOnBadString() throws Exception {
String rawString = "Cox&Forkum";
- assertEquals( "After substitution", "Cox&Forkum", HttpUnitUtils.replaceEntities( rawString ) );
+ assertEquals("After substitution", "Cox&Forkum", HttpUnitUtils.replaceEntities(rawString));
}
+ @Test
public void testSkipEntityReplacementOnUnhandledEntity() throws Exception {
String rawString = "<something>";
- assertEquals( "After substitution", "<something>", HttpUnitUtils.replaceEntities( rawString ) );
+ assertEquals("After substitution", "<something>", HttpUnitUtils.replaceEntities(rawString));
}
Modified: trunk/httpunit/src/test/java/com/meterware/httpunit/FileUploadTest.java
===================================================================
--- trunk/httpunit/src/test/java/com/meterware/httpunit/FileUploadTest.java 2012-09-07 12:36:13 UTC (rev 1080)
+++ trunk/httpunit/src/test/java/com/meterware/httpunit/FileUploadTest.java 2012-09-09 17:16:39 UTC (rev 1081)
@@ -1,31 +1,32 @@
package com.meterware.httpunit;
/********************************************************************************************************************
-* $Id$
-*
-* Copyright (c) 2000-2002, 2007, Russell Gold
-*
-* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
-* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
-* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
-* to permit persons to whom the Software is furnished to do so, subject to the following conditions:
-*
-* The above copyright notice and this permission notice shall be included in all copies or substantial portions
-* of the Software.
-*
-* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
-* THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
-* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-* DEALINGS IN THE SOFTWARE.
-*
-*******************************************************************************************************************/
+ * $Id$
+ *
+ * Copyright (c) 2000-2002, 2007, Russell Gold
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
+ * documentation files (the "Software"), to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
+ * to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions
+ * of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+ * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ *******************************************************************************************************************/
+
import com.meterware.pseudoserver.PseudoServlet;
import com.meterware.pseudoserver.WebResource;
import com.meterware.httpunit.protocol.UploadFileSpec;
+import org.junit.Test;
import java.io.*;
import java.util.StringTokenizer;
-import java.net.URL;
import java.net.URLEncoder;
import javax.activation.DataSource;
@@ -34,192 +35,180 @@
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
-import junit.framework.Test;
-import junit.framework.TestSuite;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
/**
* A unit test of the file upload simulation capability.
- **/
+ */
public class FileUploadTest extends HttpUnitTest {
- public static void main(String args[]) {
- junit.textui.TestRunner.run( suite() );
- }
-
-
- public static Test suite() {
- return new TestSuite( FileUploadTest.class );
- }
-
-
- public FileUploadTest( String name ) {
- super( name );
- }
-
-
- public void setUp() throws Exception {
- super.setUp();
- }
-
-
+ @Test
public void testParametersMultipartEncoding() throws Exception {
- defineResource( "ListParams", new MimeEcho() );
- defineWebPage( "Default", "<form method=POST action = \"ListParams\" enctype=\"multipart/form-data\"> " +
- "<Input type=text name=age value=12>" +
- "<Textarea name=comment>first\nsecond</textarea>" +
- "<Input type=submit name=update value=age>" +
- "</form>" );
+ defineResource("ListParams", new MimeEcho());
+ defineWebPage("Default", "<form method=POST action = \"ListParams\" enctype=\"multipart/form-data\"> " +
+ "<Input type=text name=age value=12>" +
+ "<Textarea name=comment>first\nsecond</textarea>" +
+ "<Input type=submit name=update value=age>" +
+ "</form>");
WebConversation wc = new WebConversation();
- WebRequest request = new GetMethodWebRequest( getHostPath() + "/Default.html" );
- WebResponse simplePage = wc.getResponse( request );
+ WebRequest request = new GetMethodWebRequest(getHostPath() + "/Default.html");
+ WebResponse simplePage = wc.getResponse(request);
WebRequest formSubmit = simplePage.getForms()[0].getRequest();
- WebResponse encoding = wc.getResponse( formSubmit );
- assertEquals( "http://dummy?age=12&comment=first%0D%0Asecond&update=age", "http://dummy?" + encoding.getText().trim() );
+ WebResponse encoding = wc.getResponse(formSubmit);
+ assertEquals("http://dummy?age=12&comment=first%0D%0Asecond&update=age", "http://dummy?" + encoding.getText().trim());
}
+ @Test
public void testFileParameterValidation() throws Exception {
- defineWebPage( "Default", "<form method=POST action = \"ListParams\" enctype=\"multipart/form-data\"> " +
- "<Input type=file name=message>" +
- "<Input type=submit name=update value=age>" +
- "...
[truncated message content] |
|
From: <rus...@us...> - 2012-09-07 12:36:21
|
Revision: 1080
http://httpunit.svn.sourceforge.net/httpunit/?rev=1080&view=rev
Author: russgold
Date: 2012-09-07 12:36:13 +0000 (Fri, 07 Sep 2012)
Log Message:
-----------
switch to full maven build to prepare for sync to maven central
Modified Paths:
--------------
trunk/httpunit/build.xml
trunk/httpunit/pom.xml
trunk/httpunit/src/main/java/com/meterware/httpunit/HttpUnitOptions.java
trunk/httpunit/src/main/java/com/meterware/httpunit/HttpWebResponse.java
trunk/httpunit/src/main/java/com/meterware/httpunit/WebResponse.java
trunk/httpunit/src/main/java/com/meterware/pseudoserver/PseudoServer.java
trunk/httpunit/src/main/java/com/meterware/servletunit/JUnitServlet.java
trunk/httpunit/src/main/java/com/meterware/servletunit/ServletUnitServletContext.java
trunk/httpunit/src/test/java/com/meterware/httpunit/WebClientTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/WebFrameTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/WebPageTest.java
trunk/httpunit/src/test/java/com/meterware/httpunit/javascript/FormScriptingTest.java
trunk/httpunit/src/test/java/com/meterware/servletunit/ListenersTest.java
trunk/quicksite/src/test/java/com/meterware/website/PageFragmentTest.java
trunk/quicksite/src/test/java/com/meterware/website/WebPageTest.java
Added Paths:
-----------
trunk/httpunit/src/main/
trunk/httpunit/src/main/java/
trunk/httpunit/src/main/java/com/
trunk/httpunit/src/test/
trunk/httpunit/src/test/java/
trunk/httpunit/src/test/java/com/meterware/servletunit/EventAwareTestBase.java
trunk/quicksite/pom.xml
trunk/quicksite/src/main/
trunk/quicksite/src/main/java/
trunk/quicksite/src/main/java/com/
trunk/quicksite/src/test/
trunk/quicksite/src/test/java/
trunk/quicksite/src/test/java/com/meterware/website/QuickSiteTestBase.java
Removed Paths:
-------------
trunk/httpunit/src/com/
trunk/httpunit/src/test/java/com/meterware/servletunit/EventAwareTestCase.java
trunk/httpunit/test/
trunk/quicksite/src/com/
trunk/quicksite/src/test/java/com/meterware/website/BBCodeTestCase.java
trunk/quicksite/src/test/java/com/meterware/website/QuickSiteTestCase.java
trunk/quicksite/test/
Modified: trunk/httpunit/build.xml
===================================================================
--- trunk/httpunit/build.xml 2011-12-19 06:59:41 UTC (rev 1079)
+++ trunk/httpunit/build.xml 2012-09-07 12:36:13 UTC (rev 1080)
@@ -35,26 +35,26 @@
<property name="deprecation" value="off" />
<property name="optimize" value="off" />
- <property name="src.dir" value="src" />
- <property name="tstsrc.dir" value="test" />
+ <property name="src.dir" value="src/main/java" />
+ <property name="tstsrc.dir" value="test/main/java" />
<property name="examples.dir" value="examples" />
<property name="website.dir" value="site" />
<property name="quicksite.dir" value="../quicksite/src" />
<property name="lib.dir" value="lib" />
<property name="jars.dir" value="jars" />
- <property name="docs.dir" value="doc" />
- <property name="build.dir" value="build" />
+ <property name="docs.dir" value="target/doc" />
+ <property name="build.dir" value="target" />
<property name="build.classes" value="${build.dir}/classes" />
<property name="test.classes" value="${build.dir}/testclasses" />
<property name="website.classes" value="${build.dir}/siteclasses" />
<property name="example.classes" value="${build.dir}/examples" />
<property name="javadoc.dir" value="${docs.dir}/api" />
- <property name="dist.dir" value="dist" />
+ <property name="dist.dir" value="target/dist" />
<property name="archive.dir" value="${dist.dir}/${name}-${version}" />
<property name="classpath" value="" />
- <property name="web.dir" value="web" />
+ <property name="web.dir" value="target/web" />
<property name="packages" value="com.meterware.httpunit,com.meterware.servletunit,com.meterware.pseudoserver,com.meterware.httpunit.cookies,com.meterware.httpunit.scripting,com.meterware.httpunit.parsing" />
<property name="test.class" value="com.meterware.httpunit.HttpUnitSuite" />
<property name="servlet.test.class" value="com.meterware.servletunit.ServletUnitSuite" />
Modified: trunk/httpunit/pom.xml
===================================================================
--- trunk/httpunit/pom.xml 2011-12-19 06:59:41 UTC (rev 1079)
+++ trunk/httpunit/pom.xml 2012-09-07 12:36:13 UTC (rev 1080)
@@ -1,24 +1,143 @@
<?xml version="1.0" encoding="UTF-8"?>
-<!---
- $Id$
- This file is a contribution by Matt Smith as of 2008-05-14:
-
- I have created and attached a POM for building httpunit using Maven2.
- It also runs FindBugs and cobertura, a code coverage tool, as well.
- It uses the current project structure. It excludes the following tests:
- EventAwareTestCase
- WebClientTest
- WebPageTest
+<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/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
-Also, if you run out of memory on the FindBugs, try upping the memory thusly
-export MAVEN_OPTS=-Xmx384M
--->
-<project>
- <modelVersion>4.0.0</modelVersion>
- <groupId>httpunit</groupId>
- <artifactId>httpunit</artifactId>
- <version>1.7.1</version>
- <description>A library for testing websites programmatically</description>
+ <parent>
+ <groupId>org.sonatype.oss</groupId>
+ <artifactId>oss-parent</artifactId>
+ <version>7</version>
+ </parent>
+
+ <groupId>org.httpunit</groupId>
+ <artifactId>httpunit</artifactId>
+ <name>HttpUnit</name>
+ <version>1.7.1-SNAPSHOT</version>
+ <description>A library for testing websites programmatically</description>
+
+ <url>http://www.httpunit.org</url>
+
+ <licenses>
+ <license>
+ <name>MIT</name>
+ <url>http://www.opensource.org/licenses/mit-license.php</url>
+ </license>
+ </licenses>
+
+
+ <scm>
+ <url>http://httpunit.svn.sourceforge.net/viewvc/httpunit</url>
+ <developerConnection>scm:svn:https://httpunit.svn.sourceforge.net/svnroot/httpunit</developerConnection>
+ <connection>scm:svn:http://httpunit.svn.sourceforge.net/svnroot/httpunit</connection>
+ </scm>
+
+
+ <developers>
+ <developer>
+ <id>russgold</id>
+ <name>Russell Gold</name>
+ <organization>Oracle, Inc.</organization>
+ <roles>
+ <role>lead</role>
+ <role>developer</role>
+ </roles>
+ </developer>
+ <developer>
+ <id>wolfgang_fahl</id>
+ <name>Wolfgang Fahl</name>
+ <organization>BitPlan</organization>
+ <roles>
+ <role>lead</role>
+ <role>developer</role>
+ </roles>
+ </developer>
+ </developers>
+
+ <issueManagement>
+ <system>Sourceforge</system>
+ <url>http://sourceforge.net/tracker/?group_id=6550&atid=106550</url>
+ </issueManagement>
+
+ <dependencies>
+ <dependency>
+ <groupId>rhino</groupId>
+ <artifactId>js</artifactId>
+ <version>1.6R5</version>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>4.7</version>
+ </dependency>
+ <dependency>
+ <groupId>nekohtml</groupId>
+ <artifactId>nekohtml</artifactId>
+ <version>0.9.5</version>
+ </dependency>
+ <dependency>
+ <groupId>javax.servlet</groupId>
+ <artifactId>servlet-api</artifactId>
+ <version>2.4</version>
+ </dependency>
+ <dependency>
+ <groupId>jtidy</groupId>
+ <artifactId>jtidy</artifactId>
+ <version>4aug2000r7-dev</version>
+ </dependency>
+ <dependency>
+ <groupId>xerces</groupId>
+ <artifactId>xercesImpl</artifactId>
+ <version>2.6.1</version>
+ </dependency>
+ <dependency>
+ <groupId>xerces</groupId>
+ <artifactId>xmlParserAPIs</artifactId>
+ <version>2.6.1</version>
+ </dependency>
+ <dependency>
+ <groupId>javax.mail</groupId>
+ <artifactId>mail</artifactId>
+ <version>1.4</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>2.3.2</version>
+ <configuration>
+ <source>1.5</source>
+ <target>1.5</target>
+ <compilerArgument>-proc:none</compilerArgument>
+ </configuration>
+ </plugin>
+ </plugins>
+ <testResources>
+ <testResource>
+ <directory>META-INF</directory>
+ </testResource>
+ </testResources>
+ </build>
+
+ <reporting>
+ <plugins>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>findbugs-maven-plugin</artifactId>
+ <version>2.5.1</version>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>cobertura-maven-plugin</artifactId>
+ <version>2.5.1</version>
+ </plugin>
+ </plugins>
+ </reporting>
+
+<!--
+
<build>
<sourceDirectory>src</sourceDirectory>
<testSourceDirectory>test</testSourceDirectory>
@@ -80,12 +199,12 @@
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<forkMode>never</forkMode>
- <!-- Assertions diasabled due to a bug in xmlbeans
- https://issues.apache.org/jira/browse/XMLBEANS-317 -->
+ <!- Assertions diasabled due to a bug in xmlbeans
+ https://issues.apache.org/jira/browse/XMLBEANS-317 ->
<enableAssertions>false</enableAssertions>
<excludes>
<exclude>**/TestSuite$1.class</exclude>
- <exclude>**/EventAwareTestCase.class</exclude>
+ <exclude>**/EventAwareTestBase.class</exclude>
<exclude>**/WebClientTest.class</exclude>
<exclude>**/WebPageTest.class</exclude>
</excludes>
@@ -126,49 +245,8 @@
</plugins>
</reporting>
+-->
- <dependencies>
- <dependency>
- <groupId>rhino</groupId>
- <artifactId>js</artifactId>
- <version>1.6R5</version>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>3.8.1</version>
- </dependency>
- <dependency>
- <groupId>nekohtml</groupId>
- <artifactId>nekohtml</artifactId>
- <version>0.9.5</version>
- </dependency>
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>servlet-api</artifactId>
- <version>2.4</version>
- </dependency>
- <dependency>
- <groupId>jtidy</groupId>
- <artifactId>jtidy</artifactId>
- <version>4aug2000r7-dev</version>
- </dependency>
- <dependency>
- <groupId>xerces</groupId>
- <artifactId>xercesImpl</artifactId>
- <version>2.6.1</version>
- </dependency>
- <dependency>
- <groupId>xerces</groupId>
- <artifactId>xmlParserAPIs</artifactId>
- <version>2.6.1</version>
- </dependency>
- <dependency>
- <groupId>javax.mail</groupId>
- <artifactId>mail</artifactId>
- <version>1.4</version>
- <scope>test</scope>
- </dependency>
<!--- Jetty libraries needed for Testing BR [ 2264431 ] form.submit() sends multiple HTTP POSTS
<dependency>
<groupId>org.mortbay.jetty</groupId>
@@ -190,18 +268,4 @@
<artifactId>jetty-util</artifactId>
<version>6.1.4</version>
</dependency> -->
- </dependencies>
-
- <pluginRepositories>
- <pluginRepository>
- <id>repo1</id>
- <url>http://repo1.maven.org/maven2/</url>
- <snapshots>
- <enabled>true</enabled>
- </snapshots>
- <releases>
- <enabled>true</enabled>
- </releases>
- </pluginRepository>
- </pluginRepositories>
</project>
Modified: trunk/httpunit/src/main/java/com/meterware/httpunit/HttpUnitOptions.java
===================================================================
--- trunk/httpunit/src/com/meterware/httpunit/HttpUnitOptions.java 2011-12-19 06:59:41 UTC (rev 1079)
+++ trunk/httpunit/src/main/java/com/meterware/httpunit/HttpUnitOptions.java 2012-09-07 12:36:13 UTC (rev 1080)
@@ -72,7 +72,8 @@
_postIncludesCharset = false;
_exceptionsThrownOnScriptError = true;
_customAttributes = null;
- _javaScriptOptimizationLevel = -1;
+ _javaScriptOptimizationLevel = -1;
+ _checkHtmlContentType = false;
setScriptEngineClassName( DEFAULT_SCRIPT_ENGINE_FACTORY );
setScriptingEnabled( true );
}
@@ -312,6 +313,22 @@
/**
+ * Returns true if HttpUnit throws an exception when attempting to parse as HTML a response whose content type
+ * is not HTML. The default is false (content type is ignored).
+ **/
+ public static boolean isCheckHtmlContentType() {
+ return _checkHtmlContentType;
+ }
+
+ /**
+ * If true, HttpUnit throws an exception when attempting to parse as HTML a response whose content type
+ * is not HTML. The default is false (content type is ignored).
+ **/
+ public static void setCheckHtmlContentType(boolean checkHtmlContentType) {
+ _checkHtmlContentType = checkHtmlContentType;
+ }
+
+ /**
* Returns true if HttpUnit should automatically follow page redirect requests (status 3xx).
* By default, this is true.
* @deprecated as of 1.5.3, use ClientProperties#isAutoRedirect();
@@ -563,9 +580,11 @@
private static boolean _exceptionsThrownOnScriptError = true;
- private static int _javaScriptOptimizationLevel = -1;
+ private static int _javaScriptOptimizationLevel = -1;
+ private static boolean _checkHtmlContentType = false;
+
static {
reset();
Modified: trunk/httpunit/src/main/java/com/meterware/httpunit/HttpWebResponse.java
===================================================================
--- trunk/httpunit/src/com/meterware/httpunit/HttpWebResponse.java 2011-12-19 06:59:41 UTC (rev 1079)
+++ trunk/httpunit/src/main/java/com/meterware/httpunit/HttpWebResponse.java 2012-09-07 12:36:13 UTC (rev 1080)
@@ -94,7 +94,7 @@
} catch (java.io.FileNotFoundException fnfe) {
// as of JDK 1.5 a null inputstream might have been returned here
// see bug report [ 1283878 ] FileNotFoundException using Sun JDK 1.5 on empty error pages
- // by Roger Lindsj\xF6
+ // by Roger Lindsj?
if (isErrorResponse(connection)) {
// fake an empty error stream
result=new ByteArrayInputStream(new byte[0]);
Modified: trunk/httpunit/src/main/java/com/meterware/httpunit/WebResponse.java
===================================================================
--- trunk/httpunit/src/com/meterware/httpunit/WebResponse.java 2011-12-19 06:59:41 UTC (rev 1079)
+++ trunk/httpunit/src/main/java/com/meterware/httpunit/WebResponse.java 2012-09-07 12:36:13 UTC (rev 1080)
@@ -91,7 +91,7 @@
/**
* set the parsing switch
- * @param doparse
+ * @param doParse
* @return
*/
public void setWithParse(boolean doParse) {
@@ -1341,7 +1341,7 @@
if (_page == null) {
try {
_parsingPage = true;
- if (!isHTML()) throw new NotHTMLException( getContentType() );
+ if (HttpUnitOptions.isCheckHtmlContentType() && !isHTML()) throw new NotHTMLException( getContentType() );
_page = new HTMLPage( this, _frame, _baseURL, _baseTarget, getCharacterSet() );
if (_withParse) {
_page.parse( getText(), _pageURL );
Modified: trunk/httpunit/src/main/java/com/meterware/pseudoserver/PseudoServer.java
===================================================================
--- trunk/httpunit/src/com/meterware/pseudoserver/PseudoServer.java 2011-12-19 06:59:41 UTC (rev 1079)
+++ trunk/httpunit/src/main/java/com/meterware/pseudoserver/PseudoServer.java 2012-09-07 12:36:13 UTC (rev 1080)
@@ -266,7 +266,7 @@
private boolean _active = true;
- private boolean _debug=true;
+ private boolean _debug=false;
private String asResourceName( String rawName ) {
Modified: trunk/httpunit/src/main/java/com/meterware/servletunit/JUnitServlet.java
===================================================================
--- trunk/httpunit/src/com/meterware/servletunit/JUnitServlet.java 2011-12-19 06:59:41 UTC (rev 1079)
+++ trunk/httpunit/src/main/java/com/meterware/servletunit/JUnitServlet.java 2012-09-07 12:36:13 UTC (rev 1080)
@@ -29,8 +29,6 @@
import javax.servlet.ServletException;
import junit.runner.BaseTestRunner;
-import junit.runner.TestSuiteLoader;
-import junit.runner.StandardTestSuiteLoader;
import junit.framework.Test;
import junit.framework.AssertionFailedError;
import junit.framework.TestResult;
@@ -147,15 +145,6 @@
public void testFailed( int i, Test test, Throwable throwable ) {
}
-
- /**
- * Always use the StandardTestSuiteLoader. Overridden from
- * BaseTestRunner.
- */
- public TestSuiteLoader getLoader() {
- return new StandardTestSuiteLoader();
- }
-
}
Modified: trunk/httpunit/src/main/java/com/meterware/servletunit/ServletUnitServletContext.java
===================================================================
--- trunk/httpunit/src/com/meterware/servletunit/ServletUnitServletContext.java 2011-12-19 06:59:41 UTC (rev 1079)
+++ trunk/httpunit/src/main/java/com/meterware/servletunit/ServletUnitServletContext.java 2012-09-07 12:36:13 UTC (rev 1080)
@@ -125,7 +125,7 @@
File resourceFile = _application.getResourceFile(path);
// PATCH proposal [ 1592532 ] Invalid
// ServletUnitServletContext#getResource(String path)
- // by Timo Westk\xE4mper
+ // by Timo Westkemper
// return !resourceFile.exists() ? null : resourceFile.toURL();
return resourceFile == null ? null : resourceFile.toURL();
} catch (MalformedURLException e) {
Modified: trunk/httpunit/src/test/java/com/meterware/httpunit/WebClientTest.java
===================================================================
--- trunk/httpunit/test/com/meterware/httpunit/WebClientTest.java 2011-12-19 06:59:41 UTC (rev 1079)
+++ trunk/httpunit/src/test/java/com/meterware/httpunit/WebClientTest.java 2012-09-07 12:36:13 UTC (rev 1080)
@@ -35,8 +35,6 @@
import java.util.*;
import java.util.zip.GZIPOutputStream;
-import org.xml.sax.SAXException;
-
//import HTTPClient.HTTPConnection;
//import HTTPClient.HTTPResponse;
@@ -47,6 +45,8 @@
**/
public class WebClientTest extends HttpUnitTest {
+ private static final boolean DNSOVERRIDE_TEST_DISABLED = true;
+
public static void main( String args[] ) {
junit.textui.TestRunner.run( suite() );
}
@@ -511,17 +511,17 @@
* @throws Exception if an unexpected exception is thrown during the test.
*/
public void testRfc2069DigestAuthentication() throws Exception {
- defineResource( "/dir/index.html", new PseudoServlet() {
+ defineResource("/dir/index.html", new PseudoServlet() {
public WebResource getGetResponse() {
- String header = getHeader( "Authorization" );
+ String header = getHeader("Authorization");
if (header == null) {
- WebResource resource = new WebResource( "not authorized", HttpURLConnection.HTTP_UNAUTHORIZED );
- resource.addHeader( "WWW-Authenticate: Digest realm=\"tes...@ho...\"," +
- " nonce=\"dcd98b7102dd2f0e8b11d0f600bfb0c093\"," +
- " opaque=\"5ccc069c403ebaf9f0171e9517f40e41\"" );
+ WebResource resource = new WebResource("not authorized", HttpURLConnection.HTTP_UNAUTHORIZED);
+ resource.addHeader("WWW-Authenticate: Digest realm=\"tes...@ho...\"," +
+ " nonce=\"dcd98b7102dd2f0e8b11d0f600bfb0c093\"," +
+ " opaque=\"5ccc069c403ebaf9f0171e9517f40e41\"");
return resource;
} else {
- return new WebResource( getHeader( "Authorization" ), "text/plain" );
+ return new WebResource(getHeader("Authorization"), "text/plain");
}
}
});
@@ -851,7 +851,7 @@
/**
* test for bug report [ 1283878 ] FileNotFoundException using Sun JDK 1.5 on empty error pages
- * by Roger Lindsj\xF6
+ * by Roger Lindsj
* @throws Exception
*/
public void testEmptyErrorPage() throws Exception {
@@ -1093,32 +1093,36 @@
public void testDNSOverride() throws Exception {
- WebConversation wc = new WebConversation();
- wc.getClientProperties().setDnsListener( new DNSListener() {
- public String getIpAddress( String hostName ) { return "127.0.0.1"; }
- });
+ if (DNSOVERRIDE_TEST_DISABLED) {
+ System.out.println("WARNING: testDNSOverride test disabled because of JDK change");
+ } else {
+ WebConversation wc = new WebConversation();
+ wc.getClientProperties().setDnsListener( new DNSListener() {
+ public String getIpAddress( String hostName ) { return "127.0.0.1"; }
+ });
- defineResource( "whereAmI", new PseudoServlet() {
- public WebResource getGetResponse() {
- WebResource webResource = new WebResource( "found host header: " + getHeader( "Host" ) );
- webResource.addHeader( "Set-Cookie: type=short" );
- return webResource;
- }
- } );
+ defineResource( "whereAmI", new PseudoServlet() {
+ public WebResource getGetResponse() {
+ WebResource webResource = new WebResource( "found host header: " + getHeader( "Host" ) );
+ webResource.addHeader( "Set-Cookie: type=short" );
+ return webResource;
+ }
+ } );
- defineResource( "checkCookies", new PseudoServlet() {
- public WebResource getGetResponse() {
- return new WebResource( "found cookies: " + getHeader( "Cookie" ) );
- }
- } );
+ defineResource( "checkCookies", new PseudoServlet() {
+ public WebResource getGetResponse() {
+ return new WebResource( "found cookies: " + getHeader( "Cookie" ) );
+ }
+ } );
- WebResponse wr = wc.getResponse( "http://meterware.com:" + getHostPort() + "/whereAmI" );
- assertEquals( "Submitted host header", "found host header: meterware.com:" + getHostPort(), wr.getText() );
- assertEquals( "Returned cookie 'type'", "short", wc.getCookieValue( "type" ) );
+ WebResponse wr = wc.getResponse( "http://meterware.com:" + getHostPort() + "/whereAmI" );
+ assertEquals( "Submitted host header", "found host header: meterware.com:" + getHostPort(), wr.getText() );
+ assertEquals( "Returned cookie 'type'", "short", wc.getCookieValue( "type" ) );
- wr = wc.getResponse( "http://meterware.com:" + getHostPort() + "/checkCookies" );
- assertEquals( "Submitted cookie header", "found cookies: type=short", wr.getText() );
+ wr = wc.getResponse( "http://meterware.com:" + getHostPort() + "/checkCookies" );
+ assertEquals( "Submitted cookie header", "found cookies: type=short", wr.getText() );
+ }
}
Modified: trunk/httpunit/src/test/java/com/meterware/httpunit/WebFrameTest.java
===================================================================
--- trunk/httpunit/test/com/meterware/httpunit/WebFrameTest.java 2011-12-19 06:59:41 UTC (rev 1079)
+++ trunk/httpunit/src/test/java/com/meterware/httpunit/WebFrameTest.java 2012-09-07 12:36:13 UTC (rev 1080)
@@ -521,16 +521,16 @@
*/
public void xtestIFrameForm() throws Exception {
String login="//Login.html (main page that is loaded - this page embed the IFrame).\n"+
- "\xA0\n"+
+ "\n"+
"<html>\n"+
"<Head>\n"+
"<Script>\n"+
"<!--\n"+
"function SetLoginForm(name, password, Submit) {\n"+
- "\xA0 document.loginForm.name.value = name;\n"+
- "\xA0 document.loginForm.password.value = password;\n"+
- "\xA0\n"+
- "\xA0 document.loginForm.submit();\n"+
+ " document.loginForm.name.value = name;\n"+
+ " document.loginForm.password.value = password;\n"+
+ "\n"+
+ " document.loginForm.submit();\n"+
"}\n"+
"-->\n"+
"</Script>\n"+
@@ -547,13 +547,13 @@
"</html>\n";
String loginDialog="// LoginDialog.html - IFrame\n"+
- "\xA0\n"+
+ "\n"+
"<html>\n"+
"<Head>\n"+
"<Script>\n"+
"<!--\n"+
"function SubmitToParent(action) {\n"+
- "\xA0 parent.SetLoginForm(document.submit_to_parent.name.value,document.submit_to_parent.password.value);\n"+
+ " parent.SetLoginForm(document.submit_to_parent.name.value,document.submit_to_parent.password.value);\n"+
"}\n"+
"-->\n"+
"</Script>\n"+
Modified: trunk/httpunit/src/test/java/com/meterware/httpunit/WebPageTest.java
===================================================================
--- trunk/httpunit/test/com/meterware/httpunit/WebPageTest.java 2011-12-19 06:59:41 UTC (rev 1079)
+++ trunk/httpunit/src/test/java/com/meterware/httpunit/WebPageTest.java 2012-09-07 12:36:13 UTC (rev 1080)
@@ -98,6 +98,7 @@
// see http://www.xmlrpc.com/spec
defineResource( "XMLRPC.html","<?xml version=\"1.0\"?><methodCall><methodName>stock.getQuote</methodName><params><param><value>JAVA</value></param></params></methodCall>","text/xml");
WebConversation wc = new WebConversation();
+ HttpUnitOptions.setCheckHtmlContentType(true);
try {
wc.getResponse( getHostPath() + "/TextPage.txt" ).getReceivedPage().getTitle();
fail( "Should have rejected attempt to get a title from a text page" );
@@ -128,6 +129,7 @@
* @throws Exception if an unexpected exception occurs during the test.
*/
public void testForceAsHtml() throws Exception {
+ HttpUnitOptions.setCheckHtmlContentType(true);
defineResource( "SimplePage.html", "<html><head><title>A Sample Page</title></head><body>Something here</body></html>", "text" );
WebConversation wc = new WebConversation();
try {
Modified: trunk/httpunit/src/test/java/com/meterware/httpunit/javascript/FormScriptingTest.java
===================================================================
--- trunk/httpunit/test/com/meterware/httpunit/javascript/FormScriptingTest.java 2011-12-19 06:59:41 UTC (rev 1079)
+++ trunk/httpunit/src/test/java/com/meterware/httpunit/javascript/FormScriptingTest.java 2012-09-07 12:36:13 UTC (rev 1080)
@@ -808,7 +808,7 @@
/**
* test for onMouseDownEvent support patch 884146
- * by Bj\xF6rn Beskow - bbeskow
+ * by Bjoern Beskow - bbeskow
* @throws Exception
*/
public void testCheckboxOnMouseDownEvent() throws Exception {
Added: trunk/httpunit/src/test/java/com/meterware/servletunit/EventAwareTestBase.java
===================================================================
--- trunk/httpunit/src/test/java/com/meterware/servletunit/EventAwareTestBase.java (rev 0)
+++ trunk/httpunit/src/test/java/com/meterware/servletunit/EventAwareTestBase.java 2012-09-07 12:36:13 UTC (rev 1080)
@@ -0,0 +1,108 @@
+package com.meterware.servletunit;
+/********************************************************************************************************************
+ * $Id$
+ *
+ * Copyright (c) 2004, Russell Gold
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
+ * documentation files (the "Software"), to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
+ * to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions
+ * of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+ * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ *******************************************************************************************************************/
+import junit.framework.TestCase;
+import junit.framework.Assert;
+
+import java.util.ArrayList;
+
+/**
+ *
+ * @author <a href="mailto:rus...@ht...">Russell Gold</a>
+ **/
+class EventAwareTestBase extends TestCase {
+
+ private static ArrayList _events;
+
+
+ public EventAwareTestBase(String name) {
+ super( name );
+ }
+
+
+ protected static void expectEvent( String eventName, Class listenerClass ) {
+ _events.add( new EventData( eventName, listenerClass ) );
+ }
+
+
+ protected static void expectEvent( String eventName, Class listenerClass, EventVerifier verifier ) {
+ _events.add( new EventData( eventName, listenerClass, verifier ) );
+ }
+
+
+ protected static void sendEvent( String eventName, Object listener, Object eventObject ) {
+ assertFalse( "Unexpected event: " + EventData.toEventString( eventName, listener.getClass() ), _events.isEmpty() );
+ ((EventData) _events.remove( 0 )).verifyEvent( eventName, listener, eventObject );
+ }
+
+
+ protected static void verifyEvents() {
+ if (!_events.isEmpty()) fail( "Did not receive event " + _events.get(0) );
+ }
+
+
+ protected static void clearEvents() {
+ _events = new ArrayList();
+ }
+
+
+ interface EventVerifier {
+ public void verifyEvent( String eventLabel, Object eventObject );
+ }
+
+}
+
+
+
+
+class EventData {
+ private String _eventName;
+ private Class _listenerClass;
+ private EventAwareTestBase.EventVerifier _verifier;
+
+ static String toEventString( String eventName, Class listenerClass ) {
+ return eventName + " from " + listenerClass.getName();
+ }
+
+
+ EventData( String eventName, Class listenerClass ) {
+ this( eventName, listenerClass, null );
+ }
+
+
+ EventData( String eventName, Class listenerClass, EventAwareTestBase.EventVerifier verifier ) {
+ _eventName = eventName;
+ _listenerClass = listenerClass;
+ _verifier = verifier;
+ }
+
+
+ void verifyEvent( String eventName, Object listener, Object event ) {
+ Assert.assertEquals( "Event", toString(), toEventString( eventName, listener.getClass() ) );
+ if (_verifier != null) _verifier.verifyEvent( toString(), event );
+ }
+
+
+ public String toString() {
+ return toEventString( _eventName, _listenerClass );
+ }
+
+}
Property changes on: trunk/httpunit/src/test/java/com/meterware/servletunit/EventAwareTestBase.java
___________________________________________________________________
Added: svn:keywords
+ Id Author HeadURL
Added: svn:eol-style
+ native
Deleted: trunk/httpunit/src/test/java/com/meterware/servletunit/EventAwareTestCase.java
===================================================================
--- trunk/httpunit/test/com/meterware/servletunit/EventAwareTestCase.java 2011-12-19 06:59:41 UTC (rev 1079)
+++ trunk/httpunit/src/test/java/com/meterware/servletunit/EventAwareTestCase.java 2012-09-07 12:36:13 UTC (rev 1080)
@@ -1,108 +0,0 @@
-package com.meterware.servletunit;
-/********************************************************************************************************************
- * $Id$
- *
- * Copyright (c) 2004, Russell Gold
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
- * documentation files (the "Software"), to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
- * to permit persons to whom the Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in all copies or substantial portions
- * of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
- * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
- * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
- * DEALINGS IN THE SOFTWARE.
- *
- *******************************************************************************************************************/
-import junit.framework.TestCase;
-import junit.framework.Assert;
-
-import java.util.ArrayList;
-
-/**
- *
- * @author <a href="mailto:rus...@ht...">Russell Gold</a>
- **/
-class EventAwareTestCase extends TestCase {
-
- private static ArrayList _events;
-
-
- public EventAwareTestCase( String name ) {
- super( name );
- }
-
-
- protected static void expectEvent( String eventName, Class listenerClass ) {
- _events.add( new EventData( eventName, listenerClass ) );
- }
-
-
- protected static void expectEvent( String eventName, Class listenerClass, EventVerifier verifier ) {
- _events.add( new EventData( eventName, listenerClass, verifier ) );
- }
-
-
- protected static void sendEvent( String eventName, Object listener, Object eventObject ) {
- assertFalse( "Unexpected event: " + EventData.toEventString( eventName, listener.getClass() ), _events.isEmpty() );
- ((EventData) _events.remove( 0 )).verifyEvent( eventName, listener, eventObject );
- }
-
-
- protected static void verifyEvents() {
- if (!_events.isEmpty()) fail( "Did not receive event " + _events.get(0) );
- }
-
-
- protected static void clearEvents() {
- _events = new ArrayList();
- }
-
-
- interface EventVerifier {
- public void verifyEvent( String eventLabel, Object eventObject );
- }
-
-}
-
-
-
-
-class EventData {
- private String _eventName;
- private Class _listenerClass;
- private EventAwareTestCase.EventVerifier _verifier;
-
- static String toEventString( String eventName, Class listenerClass ) {
- return eventName + " from " + listenerClass.getName();
- }
-
-
- EventData( String eventName, Class listenerClass ) {
- this( eventName, listenerClass, null );
- }
-
-
- EventData( String eventName, Class listenerClass, EventAwareTestCase.EventVerifier verifier ) {
- _eventName = eventName;
- _listenerClass = listenerClass;
- _verifier = verifier;
- }
-
-
- void verifyEvent( String eventName, Object listener, Object event ) {
- Assert.assertEquals( "Event", toString(), toEventString( eventName, listener.getClass() ) );
- if (_verifier != null) _verifier.verifyEvent( toString(), event );
- }
-
-
- public String toString() {
- return toEventString( _eventName, _listenerClass );
- }
-
-}
Modified: trunk/httpunit/src/test/java/com/meterware/servletunit/ListenersTest.java
===================================================================
--- trunk/httpunit/test/com/meterware/servletunit/ListenersTest.java 2011-12-19 06:59:41 UTC (rev 1079)
+++ trunk/httpunit/src/test/java/com/meterware/servletunit/ListenersTest.java 2012-09-07 12:36:13 UTC (rev 1080)
@@ -29,7 +29,7 @@
*
* @author <a href="mailto:rus...@ht...">Russell Gold</a>
**/
-public class ListenersTest extends EventAwareTestCase {
+public class ListenersTest extends EventAwareTestBase {
public static void main(String args[]) {
junit.textui.TestRunner.run( suite() );
Added: trunk/quicksite/pom.xml
===================================================================
--- trunk/quicksite/pom.xml (rev 0)
+++ trunk/quicksite/pom.xml 2012-09-07 12:36:13 UTC (rev 1080)
@@ -0,0 +1,65 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<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/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <groupId>org.httpunit</groupId>
+ <artifactId>quicksite</artifactId>
+ <version>0.8</version>
+ <packaging>jar</packaging>
+ <name>QuickSite</name>
+ <description>A tool to generate web sites from xml</description>
+
+ <url>http://java.net/projects/simplestub</url>
+
+ <dependencies>
+ <dependency>
+ <groupId>xerces</groupId>
+ <artifactId>xmlParserAPIs</artifactId>
+ <version>2.2.1</version>
+ </dependency>
+ <dependency>
+ <groupId>xerces</groupId>
+ <artifactId>xercesImpl</artifactId>
+ <version>2.6.2</version>
+ </dependency>
+ <dependency>
+ <groupId>nekohtml</groupId>
+ <artifactId>nekohtml</artifactId>
+ <version>0.9.1</version>
+ </dependency>
+ <dependency>
+ <groupId>httpunit</groupId>
+ <artifactId>httpunit</artifactId>
+ <version>1.6</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>jmock</groupId>
+ <artifactId>jmock</artifactId>
+ <version>1.0.1</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>3.8.1</version>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>2.3.2</version>
+ <configuration>
+ <source>1.6</source>
+ <target>1.6</target>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+
+</project>
+
Deleted: trunk/quicksite/src/test/java/com/meterware/website/BBCodeTestCase.java
===================================================================
--- trunk/quicksite/test/com/meterware/website/BBCodeTestCase.java 2011-12-19 06:59:41 UTC (rev 1079)
+++ trunk/quicksite/src/test/java/com/meterware/website/BBCodeTestCase.java 2012-09-07 12:36:13 UTC (rev 1080)
@@ -1,13 +0,0 @@
-package com.meterware.website;
-
-/**
- * Test case for bbcode processing.
- */
-public class BBCodeTestCase extends TestCase {
-
-
- public static TestSuite suite() {
- return new TestSuite( BBCodeTestCase.class );
- }
-
-}
Modified: trunk/quicksite/src/test/java/com/meterware/website/PageFragmentTest.java
===================================================================
--- trunk/quicksite/test/com/meterware/website/PageFragmentTest.java 2011-12-19 06:59:41 UTC (rev 1079)
+++ trunk/quicksite/src/test/java/com/meterware/website/PageFragmentTest.java 2012-09-07 12:36:13 UTC (rev 1080)
@@ -13,7 +13,7 @@
*
* @author <a href="mailto:rus...@ht...">Russell Gold</a>
**/
-public class PageFragmentTest extends QuickSiteTestCase {
+public class PageFragmentTest extends QuickSiteTestBase {
public static void main( String[] args ) {
Added: trunk/quicksite/src/test/java/com/meterware/website/QuickSiteTestBase.java
===================================================================
--- trunk/quicksite/src/test/java/com/meterware/website/QuickSiteTestBase.java (rev 0)
+++ trunk/quicksite/src/test/java/com/meterware/website/QuickSiteTestBase.java 2012-09-07 12:36:13 UTC (rev 1080)
@@ -0,0 +1,78 @@
+package com.meterware.website;
+/********************************************************************************************************************
+ * $Id$
+ *
+ * Copyright (c) 2005, Russell Gold
+ *
+ *******************************************************************************************************************/
+import org.jmock.MockObjectTestCase;
+
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+
+/**
+ * @author <a href="mailto:rus...@me...">Russell Gold</a>
+ */
+public class QuickSiteTestBase extends MockObjectTestCase {
+
+
+ private static File _temporaryDirectory;
+
+
+ /**
+ * Creates a temporary text file with the specified contents.
+ * @param contents
+ * @return the created file
+ */
+ protected static File createTextFile( String contents ) throws IOException {
+ File file = File.createTempFile( "fragment", ".txt" );
+ if (_temporaryDirectory == null) _temporaryDirectory = file.getParentFile();
+ return writeFileContents( file, contents );
+ }
+
+
+ /**
+ * Creates a temporary text file with the specified contents.
+ * @param contents
+ * @return the created file
+ */
+ protected static File createTextFile( String directory, String contents ) throws IOException {
+ File file = createTextFile( contents );
+ File path = new File( new File( file.getParentFile(), directory ), file.getName() );
+ path.mkdir();
+ file.renameTo( path );
+ return path;
+ }
+
+
+ protected File createTextFile( File groupDir, String contents ) throws IOException {
+ File file = File.createTempFile( "fragment", ".txt", groupDir );
+ return writeFileContents( file, contents );
+ }
+
+
+ protected File createTextFile( File groupDir, String fileName, String contents ) throws IOException {
+ File file = new File( groupDir, fileName );
+ return writeFileContents( file, contents );
+ }
+
+
+ private static File writeFileContents( File file, String contents ) throws IOException {
+ FileWriter writer = new FileWriter( file );
+ writer.write( contents );
+ writer.close();
+ return file;
+ }
+
+
+ protected void clearDir( File dir ) {
+ File[] entries = dir.listFiles();
+ for (int i = 0; i < entries.length; i++) {
+ File entry = entries[i];
+ if (!entry.exists()) continue;
+ if (entry.isDirectory()) clearDir( entry );
+ entry.delete();
+ }
+ }
+}
Property changes on: trunk/quicksite/src/test/java/com/meterware/website/QuickSiteTestBase.java
___________________________________________________________________
Added: svn:executable
+ *
Added: svn:keywords
+ Author Date Id Revision
Added: svn:eol-style
+ native
Deleted: trunk/quicksite/src/test/java/com/meterware/website/QuickSiteTestCase.java
===================================================================
--- trunk/quicksite/test/com/meterware/website/QuickSiteTestCase.java 2011-12-19 06:59:41 UTC (rev 1079)
+++ trunk/quicksite/src/test/java/com/meterware/website/QuickSiteTestCase.java 2012-09-07 12:36:13 UTC (rev 1080)
@@ -1,78 +0,0 @@
-package com.meterware.website;
-/********************************************************************************************************************
- * $Id$
- *
- * Copyright (c) 2005, Russell Gold
- *
- *******************************************************************************************************************/
-import org.jmock.MockObjectTestCase;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-
-/**
- * @author <a href="mailto:rus...@me...">Russell Gold</a>
- */
-public class QuickSiteTestCase extends MockObjectTestCase {
-
-
- private static File _temporaryDirectory;
-
-
- /**
- * Creates a temporary text file with the specified contents.
- * @param contents
- * @return the created file
- */
- protected static File createTextFile( String contents ) throws IOException {
- File file = File.createTempFile( "fragment", ".txt" );
- if (_temporaryDirectory == null) _temporaryDirectory = file.getParentFile();
- return writeFileContents( file, contents );
- }
-
-
- /**
- * Creates a temporary text file with the specified contents.
- * @param contents
- * @return the created file
- */
- protected static File createTextFile( String directory, String contents ) throws IOException {
- File file = createTextFile( contents );
- File path = new File( new File( file.getParentFile(), directory ), file.getName() );
- path.mkdir();
- file.renameTo( path );
- return path;
- }
-
-
- protected File createTextFile( File groupDir, String contents ) throws IOException {
- File file = File.createTempFile( "fragment", ".txt", groupDir );
- return writeFileContents( file, contents );
- }
-
-
- protected File createTextFile( File groupDir, String fileName, String contents ) throws IOException {
- File file = new File( groupDir, fileName );
- return writeFileContents( file, contents );
- }
-
-
- private static File writeFileContents( File file, String contents ) throws IOException {
- FileWriter writer = new FileWriter( file );
- writer.write( contents );
- writer.close();
- return file;
- }
-
-
- protected void clearDir( File dir ) {
- File[] entries = dir.listFiles();
- for (int i = 0; i < entries.length; i++) {
- File entry = entries[i];
- if (!entry.exists()) continue;
- if (entry.isDirectory()) clearDir( entry );
- entry.delete();
- }
- }
-}
Modified: trunk/quicksite/src/test/java/com/meterware/website/WebPageTest.java
===================================================================
--- trunk/quicksite/test/com/meterware/website/WebPageTest.java 2011-12-19 06:59:41 UTC (rev 1079)
+++ trunk/quicksite/src/test/java/com/meterware/website/WebPageTest.java 2012-09-07 12:36:13 UTC (rev 1080)
@@ -17,7 +17,7 @@
/**
* @author <a href="mailto:rus...@me...">Russell Gold</a>
*/
-public class WebPageTest extends QuickSiteTestCase {
+public class WebPageTest extends QuickSiteTestBase {
public static void main( String[] args ) {
TestRunner.run( suite() );
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <wol...@us...> - 2011-12-19 06:59:48
|
Revision: 1079
http://httpunit.svn.sourceforge.net/httpunit/?rev=1079&view=rev
Author: wolfgang_fahl
Date: 2011-12-19 06:59:41 +0000 (Mon, 19 Dec 2011)
Log Message:
-----------
modified version number to 1.7.1 for maven builds
Modified Paths:
--------------
trunk/httpunit/pom.xml
Modified: trunk/httpunit/pom.xml
===================================================================
--- trunk/httpunit/pom.xml 2011-04-07 14:36:09 UTC (rev 1078)
+++ trunk/httpunit/pom.xml 2011-12-19 06:59:41 UTC (rev 1079)
@@ -17,7 +17,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>httpunit</groupId>
<artifactId>httpunit</artifactId>
- <version>1.7</version>
+ <version>1.7.1</version>
<description>A library for testing websites programmatically</description>
<build>
<sourceDirectory>src</sourceDirectory>
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <wol...@us...> - 2011-04-07 14:36:15
|
Revision: 1078
http://httpunit.svn.sourceforge.net/httpunit/?rev=1078&view=rev
Author: wolfgang_fahl
Date: 2011-04-07 14:36:09 +0000 (Thu, 07 Apr 2011)
Log Message:
-----------
removed unused import
Modified Paths:
--------------
trunk/httpunit/.classpath
trunk/httpunit/examples/MultiDownload.java
trunk/httpunit/examples/YouTubeVisitor.java
Modified: trunk/httpunit/.classpath
===================================================================
--- trunk/httpunit/.classpath 2011-01-29 08:26:57 UTC (rev 1077)
+++ trunk/httpunit/.classpath 2011-04-07 14:36:09 UTC (rev 1078)
@@ -1,21 +1,22 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="src" path="src"/>
- <classpathentry kind="src" path="test"/>
- <classpathentry kind="src" path="pending-tests"/>
- <classpathentry kind="src" path="examples"/>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
- <classpathentry kind="lib" path="jars/quicksite.jar"/>
- <classpathentry kind="var" path="MAVEN_REPOSITORY/jtidy/jtidy/4aug2000r7-dev/jtidy-4aug2000r7-dev.jar"/>
- <classpathentry kind="var" path="MAVEN_REPOSITORY/junit/junit/3.8.1/junit-3.8.1.jar"/>
- <classpathentry kind="var" path="MAVEN_REPOSITORY/nekohtml/nekohtml/0.9.5/nekohtml-0.9.5.jar"/>
- <classpathentry kind="var" path="MAVEN_REPOSITORY/rhino/js/1.6R5/js-1.6R5.jar" sourcepath="/pub/2008/rhino1_6R5.zip"/>
- <classpathentry kind="var" path="MAVEN_REPOSITORY/javax/servlet/servlet-api/2.4/servlet-api-2.4.jar"/>
- <classpathentry kind="var" path="MAVEN_REPOSITORY/xerces/xmlParserAPIs/2.6.1/xmlParserAPIs-2.6.1.jar" sourcepath="/pub/2008/Xerces-J-src.2.6.1.zip"/>
- <classpathentry kind="var" path="MAVEN_REPOSITORY/xerces/xercesImpl/2.6.1/xercesImpl-2.6.1.jar"/>
- <classpathentry kind="lib" path="META-INF"/>
- <classpathentry kind="var" path="MAVEN_REPOSITORY/javax/activation/activation/1.1/activation-1.1.jar"/>
- <classpathentry kind="var" path="MAVEN_REPOSITORY/javax/mail/mail/1.4/mail-1.4.jar"/>
- <classpathentry kind="lib" path="jars/maven-ant-tasks-2.0.9.jar"/>
- <classpathentry kind="output" path="bin"/>
-</classpath>
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="src" path="test"/>
+ <classpathentry kind="src" path="pending-tests"/>
+ <classpathentry kind="src" path="examples"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
+ <classpathentry kind="lib" path="jars/quicksite.jar"/>
+ <classpathentry kind="var" path="MAVEN_REPOSITORY/jtidy/jtidy/4aug2000r7-dev/jtidy-4aug2000r7-dev.jar"/>
+ <classpathentry kind="var" path="MAVEN_REPOSITORY/junit/junit/3.8.1/junit-3.8.1.jar"/>
+ <classpathentry kind="var" path="MAVEN_REPOSITORY/nekohtml/nekohtml/0.9.5/nekohtml-0.9.5.jar"/>
+ <classpathentry kind="var" path="MAVEN_REPOSITORY/rhino/js/1.6R5/js-1.6R5.jar" sourcepath="/pub/2008/rhino1_6R5.zip"/>
+ <classpathentry kind="var" path="MAVEN_REPOSITORY/javax/servlet/servlet-api/2.4/servlet-api-2.4.jar"/>
+ <classpathentry kind="var" path="MAVEN_REPOSITORY/xerces/xmlParserAPIs/2.6.1/xmlParserAPIs-2.6.1.jar" sourcepath="/pub/2008/Xerces-J-src.2.6.1.zip"/>
+ <classpathentry kind="var" path="MAVEN_REPOSITORY/xerces/xercesImpl/2.6.1/xercesImpl-2.6.1.jar"/>
+ <classpathentry kind="lib" path="META-INF"/>
+ <classpathentry kind="var" path="MAVEN_REPOSITORY/javax/activation/activation/1.1/activation-1.1.jar"/>
+ <classpathentry kind="var" path="MAVEN_REPOSITORY/javax/mail/mail/1.4/mail-1.4.jar"/>
+ <classpathentry kind="lib" path="jars/maven-ant-tasks-2.0.9.jar"/>
+ <classpathentry kind="var" path="MAVEN_REPOSITORY"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
Modified: trunk/httpunit/examples/MultiDownload.java
===================================================================
--- trunk/httpunit/examples/MultiDownload.java 2011-01-29 08:26:57 UTC (rev 1077)
+++ trunk/httpunit/examples/MultiDownload.java 2011-04-07 14:36:09 UTC (rev 1078)
@@ -13,8 +13,8 @@
import org.xml.sax.SAXException;
-import sun.tools.tree.ThisExpression;
+
/**
* an example that shows how to automate downloads
*
Modified: trunk/httpunit/examples/YouTubeVisitor.java
===================================================================
--- trunk/httpunit/examples/YouTubeVisitor.java 2011-01-29 08:26:57 UTC (rev 1077)
+++ trunk/httpunit/examples/YouTubeVisitor.java 2011-04-07 14:36:09 UTC (rev 1078)
@@ -12,8 +12,8 @@
import org.xml.sax.SAXException;
-import sun.tools.tree.ThisExpression;
+
/**
* an example that shows how to automate visits you tube
* please see
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <wol...@us...> - 2011-01-29 08:27:03
|
Revision: 1077
http://httpunit.svn.sourceforge.net/httpunit/?rev=1077&view=rev
Author: wolfgang_fahl
Date: 2011-01-29 08:26:57 +0000 (Sat, 29 Jan 2011)
Log Message:
-----------
fix of BR2822484 by gcc with supplied patch file httpunit-textarea-090923.patch
Modified Paths:
--------------
trunk/httpunit/src/com/meterware/httpunit/dom/HTMLTextAreaElementImpl.java
trunk/httpunit/src/com/meterware/httpunit/protocol/MimeEncodedMessageBody.java
trunk/httpunit/test/com/meterware/servletunit/PostTest.java
Modified: trunk/httpunit/src/com/meterware/httpunit/dom/HTMLTextAreaElementImpl.java
===================================================================
--- trunk/httpunit/src/com/meterware/httpunit/dom/HTMLTextAreaElementImpl.java 2011-01-29 08:17:17 UTC (rev 1076)
+++ trunk/httpunit/src/com/meterware/httpunit/dom/HTMLTextAreaElementImpl.java 2011-01-29 08:26:57 UTC (rev 1077)
@@ -64,7 +64,17 @@
public String getDefaultValue() {
Node node = getFirstChild();
- if (node == null || node.getNodeType() != Node.TEXT_NODE) return null;
+
+ if (node == null)
+ {
+ return "";
+ }
+
+ if (node.getNodeType() != Node.TEXT_NODE)
+ {
+ return null;
+ }
+
return node.getNodeValue();
}
Modified: trunk/httpunit/src/com/meterware/httpunit/protocol/MimeEncodedMessageBody.java
===================================================================
--- trunk/httpunit/src/com/meterware/httpunit/protocol/MimeEncodedMessageBody.java 2011-01-29 08:17:17 UTC (rev 1076)
+++ trunk/httpunit/src/com/meterware/httpunit/protocol/MimeEncodedMessageBody.java 2011-01-29 08:26:57 UTC (rev 1077)
@@ -102,7 +102,7 @@
*/
public void addParameter( String name, String value, String characterSet ) throws IOException {
if (name == null || name.length() == 0) return;
- if (value == null || value.length() == 0) return;
+ if (value == null) return;
writeLn( _outputStream, "--" + BOUNDARY );
writeLn( _outputStream, "Content-Disposition: form-data; name=\"" + name + '"' ); // XXX need to handle non-ascii names here
writeLn( _outputStream, "Content-Type: text/plain; charset=" + getCharacterSet() );
Modified: trunk/httpunit/test/com/meterware/servletunit/PostTest.java
===================================================================
--- trunk/httpunit/test/com/meterware/servletunit/PostTest.java 2011-01-29 08:17:17 UTC (rev 1076)
+++ trunk/httpunit/test/com/meterware/servletunit/PostTest.java 2011-01-29 08:26:57 UTC (rev 1077)
@@ -126,6 +126,23 @@
}
}
+ public void testMultiPartPost() throws Exception {
+ TestServlet.location="http://localhost/";
+
+ ServletRunner sr = new ServletRunner();
+ sr.registerServlet(resourceName, TestServlet.class.getName());
+
+ WebRequest request = new GetMethodWebRequest(TestServlet.location+resourceName);
+ WebResponse response = sr.getResponse(request);
+
+ WebForm form = response.getFormWithID("multipart-bug");
+ response = form.submit();
+
+ assertEquals(true, response.getText().contains("name=\"empty\""));
+ assertEquals(true, response.getText().contains("name=\"empty_textarea\""));
+ //check(response);
+ }
+
/**
* a Servlet that counts the posts being done
*/
@@ -139,7 +156,19 @@
response
.getWriter()
.println(
- "<html><body><form action='"+location+resourceName+"' method='post' id='bug'><input name='handle'/><input name='brainz'/></form></body></html>");
+ "<html>" +
+ "<body>" +
+ "<form action='"+location+resourceName+"' method='post' id='bug'>" +
+ "<input name='handle'/>" +
+ "<input name='brainz'/>" +
+ "</form>" +
+ "<form id='multipart-bug' method='post' action='"+location+resourceName+"' enctype='multipart/form-data'>" +
+ "<input name='empty' value=''>" +
+ "<input name='notempty' value='1'>" +
+ "<textarea name='empty_textarea'></textarea>" +
+ "</form>" +
+ "</body>" +
+ "</html>");
/*
if (request instanceof Request)
((Request) request).setHandled(true);
@@ -149,6 +178,13 @@
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
postCount++;
+ InputStream is = request.getInputStream();
+ OutputStream os = response.getOutputStream();
+ byte [] buffer = new byte [4096];
+ for (int length = is.read(buffer); length > 0; length = is.read(buffer))
+ {
+ os.write(buffer, 0, length);
+ }
}
}
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <wol...@us...> - 2011-01-29 08:17:23
|
Revision: 1076
http://httpunit.svn.sourceforge.net/httpunit/?rev=1076&view=rev
Author: wolfgang_fahl
Date: 2011-01-29 08:17:17 +0000 (Sat, 29 Jan 2011)
Log Message:
-----------
removed superfluous call - added comment
Modified Paths:
--------------
trunk/httpunit/src/com/meterware/httpunit/ParsedHTML.java
Modified: trunk/httpunit/src/com/meterware/httpunit/ParsedHTML.java
===================================================================
--- trunk/httpunit/src/com/meterware/httpunit/ParsedHTML.java 2011-01-11 15:30:21 UTC (rev 1075)
+++ trunk/httpunit/src/com/meterware/httpunit/ParsedHTML.java 2011-01-29 08:17:17 UTC (rev 1076)
@@ -30,6 +30,8 @@
import java.util.*;
import java.io.IOException;
+import javax.management.RuntimeErrorException;
+
import com.meterware.httpunit.scripting.ScriptableDelegate;
import com.meterware.httpunit.dom.HTMLContainerElement;
import com.meterware.httpunit.dom.HTMLDocumentImpl;
@@ -215,16 +217,16 @@
**/
public WebTable[] getTables() {
loadElements();
- if (_tables == null) {
- loadElements();
- _tables = (WebTable[]) _tableList.toArray( new WebTable[ _tableList.size() ] );
- }
- return _tables;
+ if (_tables == null) {
+ _tables = (WebTable[]) _tableList.toArray( new WebTable[ _tableList.size() ] );
+ }
+ return _tables;
}
-
/**
* Returns the HTMLElement with the specified ID.
+ * @param id - the id of the element to return
+ * @return the element looked for
*/
public HTMLElement getElementWithID( String id ) {
return (HTMLElement) getElementWithID( id, HTMLElement.class );
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <wol...@us...> - 2011-01-11 15:30:27
|
Revision: 1075
http://httpunit.svn.sourceforge.net/httpunit/?rev=1075&view=rev
Author: wolfgang_fahl
Date: 2011-01-11 15:30:21 +0000 (Tue, 11 Jan 2011)
Log Message:
-----------
new example
Added Paths:
-----------
trunk/httpunit/examples/MultiDownload.java
Added: trunk/httpunit/examples/MultiDownload.java
===================================================================
--- trunk/httpunit/examples/MultiDownload.java (rev 0)
+++ trunk/httpunit/examples/MultiDownload.java 2011-01-11 15:30:21 UTC (rev 1075)
@@ -0,0 +1,343 @@
+import com.meterware.httpunit.*;
+
+import java.awt.*;
+import java.awt.event.*;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.concurrent.ExecutionException;
+
+import javax.swing.*;
+import javax.swing.text.BadLocationException;
+
+import org.xml.sax.SAXException;
+
+import sun.tools.tree.ThisExpression;
+
+/**
+ * an example that shows how to automate downloads
+ *
+ * @author wf
+ *
+ */
+public class MultiDownload extends JPanel implements ActionListener {
+
+ // where all visited videos should go to
+ protected File targetFolder;
+
+ // UI elements for targetFolder selection
+ protected JLabel targetFolderLabel;
+
+ protected JTextField targetFolderField;
+
+ protected JButton FolderSelectButton;
+
+
+ // UI elements for selection of videos to visit
+ protected JLabel urlLabel;
+
+ protected JTextArea urlArea;
+
+ protected JButton downloadButton;
+
+ // progressbar for visits
+ protected JProgressBar progressBar;
+
+ // status message
+ protected JLabel statusMessage;
+ protected JCheckBox displayCheckbox;
+ private boolean withDisplay;
+
+ /**
+ * @return the withDisplay
+ */
+ public boolean isWithDisplay() {
+ return withDisplay;
+ }
+
+ /**
+ * @param withDisplay the withDisplay to set
+ */
+ public void setWithDisplay(boolean withDisplay) {
+ this.withDisplay = withDisplay;
+ this.displayCheckbox.setSelected(withDisplay);
+ }
+
+ final static String helpMessage = "Select Target Folder and cut&paste File URLs then click 'download'";
+
+ // Create a file chooser
+ protected JFileChooser fileChooser;
+
+ final static String chooserTitle = "Select Target Folder";
+
+ // Layout constraints
+ GridBagConstraints gbc = new GridBagConstraints();
+
+ /**
+ * place the given component add the given x, y position with the given weight
+ *
+ * @param c
+ * @param x
+ * @param y
+ * @param wx
+ * @param wy
+ */
+ public void place(Component c, int x, int y, double wx, double wy) {
+ gbc.gridx = x;
+ gbc.gridy = y;
+ gbc.weightx = wx;
+ gbc.weighty = wy;
+ add(c, gbc);
+ }
+
+ /**
+ * post a status message;
+ *
+ * @param msg
+ */
+ public void setStatus(String msg) {
+ statusMessage.setText(msg);
+ }
+
+ /**
+ * set default values for fields
+ */
+ public void initFields() {
+ // use current directory as default target folder
+ this.setTargetFolder(new File("."), true);
+ // default files to download
+ String[] urls = {
+ "http://downloads.sourceforge.net/project/httpunit/httpunit/1.7/httpunit-1.7.zip", // httpunit,
+ "http://downloads.sourceforge.net/project/junit/junit/4.8.1/junit-4.8.1.jar" // JUnit
+ };
+ String urlString = "";
+ for (int i = 0; i < urls.length; i++) {
+ urlString += urls[i] + "\n";
+ }
+ this.urlArea.setText(urlString);
+ // default for display in Browser is false
+ this.setWithDisplay(false);
+ }
+
+ /**
+ * When the worker needs to update the GUI we do so by queuing
+ * a Runnable for the event dispatching thread with
+ * SwingUtilities.invokeLater(). In this case we're just
+ * changing the progress bars value.
+ */
+ void updateStatus(final int progress, final String msg) {
+ Runnable doSetProgressBarValue = new Runnable() {
+ public void run() {
+ setStatus(msg);
+ progressBar.setValue(progress);
+ }
+ };
+ SwingUtilities.invokeLater(doSetProgressBarValue);
+ }
+
+
+ /**
+ * constructor
+ */
+ public MultiDownload() {
+ super(new GridBagLayout());
+
+ // Target Folder Selection
+ targetFolderLabel = new JLabel("Target Folder:");
+ targetFolderField = new JTextField(20);
+ targetFolderField.addActionListener(this);
+ FolderSelectButton = new JButton("...");
+ FolderSelectButton.addActionListener(this);
+ fileChooser = new JFileChooser();
+ fileChooser.setDialogTitle(chooserTitle);
+ fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
+ //
+ // disable the "All files" option.
+ //
+ fileChooser.setAcceptAllFileFilterUsed(false);
+
+ // File URL Selection
+ urlLabel = new JLabel("File-URLs:");
+
+ urlArea = new JTextArea(10, 40);
+ urlArea.setEditable(true);
+ JScrollPane urlScrollPane = new JScrollPane(urlArea);
+
+ downloadButton = new JButton("download");
+ downloadButton.addActionListener(this);
+
+ progressBar = new JProgressBar(0, 100);
+ progressBar.setValue(0);
+ progressBar.setStringPainted(true);
+
+ statusMessage = new JLabel(helpMessage);
+ displayCheckbox=new JCheckBox("Browser");
+
+
+ // Add Components to this panel.
+ gbc.gridwidth = 1;
+ gbc.gridheight = 1;
+
+ gbc.fill = GridBagConstraints.BOTH;
+ place(targetFolderLabel , 0, 0, 0.2, 0.10);
+ place(targetFolderField , 1, 0, 0.6, 0.10);
+ place(FolderSelectButton, 2, 0, 0.2, 0.10);
+
+
+ place(urlLabel , 0, 2, 0.2, 0.60);
+ place(urlScrollPane , 1, 2, 0.6, 0.60);
+ place(downloadButton , 2, 2, 0.2, 0.60);
+
+ gbc.gridwidth = 3;
+ place(progressBar , 0, 3, 1.0, 0.10);
+
+ gbc.gridwidth=2;
+ place(statusMessage , 0, 4, 0.8, 0.10);
+ gbc.gridwidth=1;
+ place(displayCheckbox , 2, 4, 0.2, 0.10);
+ initFields();
+ }
+
+ /**
+ * get the target Folder
+ * @return
+ */
+ public File getTargetFolder(){
+ return new File(targetFolderField.getText());
+ }
+
+ /**
+ * set a new target Folder
+ *
+ * @param targetFolder
+ * the targetFolder to set
+ * @param withField
+ * - shall the GUI display also be set?
+ */
+ public void setTargetFolder(File newTargetFolder, boolean withField) {
+ this.targetFolder = newTargetFolder;
+ if (!targetFolder.exists())
+ this.setStatus("target Folder " + newTargetFolder + " does not exist!");
+ if (withField)
+ try {
+ targetFolderField.setText(targetFolder.getCanonicalPath());
+ } catch (IOException e) {
+ setStatus(e.getMessage());
+ }
+ }
+
+
+ /**
+ * start downloading the Files asked for
+ */
+ public void downloadAll() {
+ String text = urlArea.getText();
+ int totalLines = urlArea.getLineCount();
+ int count=0;
+ String urls[] = new String[totalLines];
+ try {
+ for (int i = 0; i < totalLines; i++) {
+ int start;
+ start = urlArea.getLineStartOffset(i);
+ int end = urlArea.getLineEndOffset(i);
+ String line = text.substring(start, end);
+ if (!line.trim().equals(""))
+ urls[count++] = line.replace("\n","");
+ }
+ } catch (BadLocationException e) {
+ setStatus(e.getMessage());
+ }
+ String msg="downloading "+count+" Files";
+ this.progressBar.setMaximum(count);
+ this.updateStatus(0, msg);
+ for (int i=0;i<count;i++){
+ download(i+1,urls[i]);
+ }
+ }
+ private WebConversation conversation = new WebConversation();
+ private WebResponse response;
+
+ /**
+ * download a file from the given web link
+ * @param progress
+ * @param url - the link to get the file from
+ */
+ private void download(int progress, String url) {
+ try {
+ String msg="downloading "+url;
+ this.updateStatus(progress, msg);
+ response=conversation.getResponse(url);
+ byte[] download = response.getBytes();
+ int lastSlash=url.lastIndexOf("/");
+ String filePart=url.substring(lastSlash);
+ String targetFileName=this.getTargetFolder().getCanonicalPath()+"/"+filePart;
+ File targetFile=new File(targetFileName);
+ if (targetFile.exists())
+ setStatus(targetFileName+" exists");
+ else {
+ setStatus("downloading "+url+" ("+download.length/1024+" KByte)");
+ FileOutputStream fos=new FileOutputStream(targetFile);
+ fos.write(download);
+ fos.close();
+ }
+ } catch (Throwable th) {
+ setStatus(th.getMessage());
+ }
+ }
+
+ /**
+ * react on clicks
+ */
+ public void actionPerformed(ActionEvent evt) {
+ // Folder Selection
+ if (evt.getSource().equals(FolderSelectButton)) {
+ int returnVal = fileChooser.showOpenDialog(MultiDownload.this);
+
+ if (returnVal == JFileChooser.APPROVE_OPTION) {
+ setTargetFolder(fileChooser.getSelectedFile(), true);
+ }
+ } // download action
+ else if (evt.getSource().equals(this.downloadButton)) {
+ SwingUtilities.invokeLater(new Runnable() {
+ public void run() {
+ downloadAll();
+ }
+ });
+
+ }
+ }
+
+ /**
+ * Create the GUI and show it. For thread safety, this method should be
+ * invoked from the event dispatch thread.
+ */
+ private static void createAndShowGUI() {
+ // Create and set up the window.
+ JFrame frame = new JFrame("Multi-Download");
+ frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+
+ // Add contents to the window.
+ frame.add(new MultiDownload());
+
+ // Display the window.
+ frame.pack();
+ frame.setVisible(true);
+ }
+
+ /**
+ * main routine to startup the GUI
+ *
+ * @param args
+ */
+ public static void main(String[] args) {
+ // Schedule a job for the event dispatch thread:
+ // creating and showing this application's GUI.
+ javax.swing.SwingUtilities.invokeLater(new Runnable() {
+ public void run() {
+ createAndShowGUI();
+ }
+ });
+ }
+
+}
Property changes on: trunk/httpunit/examples/MultiDownload.java
___________________________________________________________________
Added: svn:mime-type
+ text/plain
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <wol...@us...> - 2011-01-11 14:34:57
|
Revision: 1074
http://httpunit.svn.sourceforge.net/httpunit/?rev=1074&view=rev
Author: wolfgang_fahl
Date: 2011-01-11 14:34:50 +0000 (Tue, 11 Jan 2011)
Log Message:
-----------
You Tube Visitor example
Added Paths:
-----------
trunk/httpunit/examples/YouTubeVisitor.java
Added: trunk/httpunit/examples/YouTubeVisitor.java
===================================================================
--- trunk/httpunit/examples/YouTubeVisitor.java (rev 0)
+++ trunk/httpunit/examples/YouTubeVisitor.java 2011-01-11 14:34:50 UTC (rev 1074)
@@ -0,0 +1,375 @@
+import com.meterware.httpunit.*;
+
+import java.awt.*;
+import java.awt.event.*;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+
+import javax.swing.*;
+import javax.swing.text.BadLocationException;
+
+import org.xml.sax.SAXException;
+
+import sun.tools.tree.ThisExpression;
+
+/**
+ * an example that shows how to automate visits you tube
+ * please see
+ * http://www.youtube.com/t/terms
+ * for the legal aspects of modifying this software to allow downloads
+ *
+ * @author wf
+ *
+ */
+public class YouTubeVisitor extends JPanel implements ActionListener {
+
+ // where all visited videos should go to
+ protected File targetFolder;
+
+ // UI elements for targetFolder selection
+ protected JLabel targetFolderLabel;
+
+ protected JTextField targetFolderField;
+
+ protected JButton FolderSelectButton;
+
+ // UI elements for format selection
+ String[] formats = {"mp4","flv (Low Quality)","flv (High Quality (320p))","flv (High Quality (480p)",
+ "3gp","mp3","mpeg","mov"};
+ protected JLabel formatLabel;
+ protected JComboBox formatComboBox = new JComboBox(formats);
+ protected String videoFormat;
+
+ /**
+ * @return the videoFormat
+ */
+ public String getVideoFormat() {
+ videoFormat =formatComboBox.getSelectedItem().toString();
+ return videoFormat;
+ }
+
+ // UI elements for selection of videos to visit
+ protected JLabel urlLabel;
+
+ protected JTextArea urlArea;
+
+ protected JButton visitButton;
+
+ // progressbar for visits
+ protected JProgressBar progressBar;
+
+ // status message
+ protected JLabel statusMessage;
+ protected JCheckBox displayCheckbox;
+ private boolean withDisplay;
+
+ /**
+ * @return the withDisplay
+ */
+ public boolean isWithDisplay() {
+ return withDisplay;
+ }
+
+ /**
+ * @param withDisplay the withDisplay to set
+ */
+ public void setWithDisplay(boolean withDisplay) {
+ this.withDisplay = withDisplay;
+ this.displayCheckbox.setSelected(withDisplay);
+ }
+ final static String helpMessage = "Select Target Folder and cut&paste Video URLs then click 'visit'";
+
+ // Create a file chooser
+ protected JFileChooser fileChooser;
+
+ final static String chooserTitle = "Select Target Folder";
+
+ // Layout constraints
+ GridBagConstraints gbc = new GridBagConstraints();
+
+ /**
+ * place the given component add the given x, y position with the given weight
+ *
+ * @param c
+ * @param x
+ * @param y
+ * @param wx
+ * @param wy
+ */
+ public void place(Component c, int x, int y, double wx, double wy) {
+ gbc.gridx = x;
+ gbc.gridy = y;
+ gbc.weightx = wx;
+ gbc.weighty = wy;
+ add(c, gbc);
+ }
+
+ /**
+ * post a status message;
+ *
+ * @param msg
+ */
+ public void setStatus(String msg) {
+ statusMessage.setText(msg);
+ }
+
+ /**
+ * set default values for fields
+ */
+ public void initFields() {
+ // use current directory as default target folder
+ this.setTargetFolder(new File("."), true);
+ // guitar rock
+ // seven Videos of Jean Michel Jarre's millenium concert in Egypt at the
+ // pyramids
+ String[] urls = {
+ "http://www.youtube.com/watch?v=QjA5faZF1A8", // guitar
+ "http://www.youtube.com/watch?v=7jCotM1m8yE",
+ "http://www.youtube.com/watch?v=1GWPOjtSFk0",
+ "http://www.youtube.com/watch?v=GlUcctk4pQA",
+ "http://www.youtube.com/watch?v=P7eFIzgjveU",
+ "http://www.youtube.com/watch?v=CXIjLwhkG4g",
+ "http://www.youtube.com/watch?v=ekCotwVbzcI",
+ "http://www.youtube.com/watch?v=AQE7IKcQJTs" };
+ String urlString = "";
+ for (int i = 0; i < urls.length; i++) {
+ urlString += urls[i] + "\n";
+ }
+ this.urlArea.setText(urlString);
+ // default for display in Browser is true
+ this.setWithDisplay(true);
+ }
+
+ /**
+ * constructor
+ */
+ public YouTubeVisitor() {
+ super(new GridBagLayout());
+
+ // Target Folder Selection
+ targetFolderLabel = new JLabel("Target Folder:");
+ targetFolderField = new JTextField(20);
+ targetFolderField.addActionListener(this);
+ FolderSelectButton = new JButton("...");
+ FolderSelectButton.addActionListener(this);
+ fileChooser = new JFileChooser();
+ fileChooser.setDialogTitle(chooserTitle);
+ fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
+ //
+ // disable the "All files" option.
+ //
+ fileChooser.setAcceptAllFileFilterUsed(false);
+
+ // formatSelection
+ formatLabel=new JLabel("Format:");
+
+ // Video URL Selection
+ urlLabel = new JLabel("Videos-URLs:");
+
+ urlArea = new JTextArea(10, 40);
+ urlArea.setEditable(true);
+ JScrollPane urlScrollPane = new JScrollPane(urlArea);
+
+ visitButton = new JButton("visit");
+ visitButton.addActionListener(this);
+
+ progressBar = new JProgressBar(0, 100);
+ progressBar.setValue(0);
+ progressBar.setStringPainted(true);
+
+ statusMessage = new JLabel(helpMessage);
+ displayCheckbox=new JCheckBox("Browser");
+
+ // Add Components to this panel.
+ gbc.gridwidth = 1;
+ gbc.gridheight = 1;
+
+ gbc.fill = GridBagConstraints.BOTH;
+ place(targetFolderLabel , 0, 0, 0.2, 0.10);
+ place(targetFolderField , 1, 0, 0.6, 0.10);
+ place(FolderSelectButton, 2, 0, 0.2, 0.10);
+
+ place(formatLabel , 0, 1, 0.2, 0.10);
+ place(formatComboBox , 1, 1, 0.2, 0.10);
+
+ place(urlLabel , 0, 2, 0.2, 0.60);
+ place(urlScrollPane , 1, 2, 0.6, 0.60);
+ place(visitButton , 2, 2, 0.2, 0.60);
+
+ gbc.gridwidth = 3;
+ place(progressBar , 0, 3, 1.0, 0.10);
+
+ gbc.gridwidth=2;
+ place(statusMessage , 0, 4, 0.8, 0.10);
+ gbc.gridwidth=1;
+ place(displayCheckbox , 2, 4, 0.2, 0.10);
+ initFields();
+ }
+
+ /**
+ * set a new target Folder
+ *
+ * @param targetFolder
+ * the targetFolder to set
+ * @param withField
+ * - shall the GUI display also be set?
+ */
+ public void setTargetFolder(File newTargetFolder, boolean withField) {
+ this.targetFolder = newTargetFolder;
+ if (!targetFolder.exists())
+ this.setStatus("target Folder " + newTargetFolder + " does not exist!");
+ if (withField)
+ try {
+ targetFolderField.setText(targetFolder.getCanonicalPath());
+ } catch (IOException e) {
+ setStatus(e.getMessage());
+ }
+ }
+
+ /**
+ * start visiting the videos asked for
+ */
+ public void visitAll() {
+ String text = urlArea.getText();
+ int totalLines = urlArea.getLineCount();
+ int count=0;
+ String urls[] = new String[totalLines];
+ try {
+ for (int i = 0; i < totalLines; i++) {
+ int start;
+ start = urlArea.getLineStartOffset(i);
+ int end = urlArea.getLineEndOffset(i);
+ String line = text.substring(start, end);
+ if (!line.trim().equals(""))
+ urls[count++] = line;
+ }
+ } catch (BadLocationException e) {
+ setStatus(e.getMessage());
+ }
+ String msg="visiting "+count+" Videos";
+ this.progressBar.setMaximum(count);
+ setStatus(msg);
+ for (int i=0;i<count;i++){
+ this.progressBar.setValue(i+1);
+ visit(urls[i]);
+ }
+ }
+ private WebConversation conversation = new WebConversation();
+ private WebResponse response;
+
+ /**
+ * visit the youtube Video from the given URL to the targetFolder
+ * @param videourl
+ */
+ private void visit(String videourl) {
+ // website service to use
+ // String url="http://www.visitfreeyoutube.com/";
+ // String url="http://www.videovisitx.com/";
+ // String url="http://www.share-tube.eu/";
+ // String url="http://www.videogetting.com/download-youtube.php";
+ // disable javascript
+ HttpUnitOptions.setScriptingEnabled(false);
+ System.out.println("visiting " + videourl);
+ WebRequest request = new GetMethodWebRequest(videourl);
+ try {
+ response = conversation.getResponse(request);
+ //if (this.isWithDisplay())
+ // BrowserDisplayer.showResponseInBrowser(response);
+ //WebForm lookupForm = response.getFormWithID("frmSearch");
+ //WebForm lookupForm=response.getForms()[0];
+ //lookupForm.setParameter("q",videourl);
+ //response=lookupForm.submit();
+ if (this.isWithDisplay())
+ BrowserDisplayer.showResponseInBrowser(response);
+
+ WebLink[] links = response.getLinks();
+ ArrayList result = new ArrayList();
+ for (int i = 0; i < links.length; i++) {
+ WebLink link = links[i];
+ String linkText=link.getText();
+ if (linkText.indexOf("videoplayback")>0) {
+ System.out.println(linkText+"=>"+link.getURLString());
+ download(link);
+ }
+ }
+ } catch (Throwable th) {
+ setStatus(th.getMessage());
+ }
+ }
+
+ /**
+ * download a file from the given web link
+ * @param link - the link to get the file from
+ */
+ private void download(WebLink link) {
+ try {
+ setStatus("visiting "+link.getText());
+ response=link.click();
+ byte[] visit = response.getBytes();
+ String targetFileName=targetFolder.getCanonicalPath()+"/"+link.getText();
+ File targetFile=new File(targetFileName);
+ if (targetFile.exists())
+ setStatus(targetFileName+" exists");
+ else {
+ setStatus("visiting "+link.getText()+" ("+visit.length/1024/1024+" MByte");
+ FileOutputStream fos=new FileOutputStream(targetFile);
+ fos.write(visit);
+ fos.close();
+ }
+ } catch (Throwable th) {
+ setStatus(th.getMessage());
+ }
+ }
+
+ /**
+ * react on clicks
+ */
+ public void actionPerformed(ActionEvent evt) {
+ // Folder Selection
+ if (evt.getSource().equals(FolderSelectButton)) {
+ int returnVal = fileChooser.showOpenDialog(YouTubeVisitor.this);
+
+ if (returnVal == JFileChooser.APPROVE_OPTION) {
+ setTargetFolder(fileChooser.getSelectedFile(), true);
+ }
+ } // visit action
+ else if (evt.getSource().equals(this.visitButton)) {
+ visitAll();
+ }
+ }
+
+ /**
+ * Create the GUI and show it. For thread safety, this method should be
+ * invoked from the event dispatch thread.
+ */
+ private static void createAndShowGUI() {
+ // Create and set up the window.
+ JFrame frame = new JFrame("YouTubevisit");
+ frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+
+ // Add contents to the window.
+ frame.add(new YouTubeVisitor());
+
+ // Display the window.
+ frame.pack();
+ frame.setVisible(true);
+ }
+
+ /**
+ * main routine to startup the GUI
+ *
+ * @param args
+ */
+ public static void main(String[] args) {
+ // Schedule a job for the event dispatch thread:
+ // creating and showing this application's GUI.
+ javax.swing.SwingUtilities.invokeLater(new Runnable() {
+ public void run() {
+ createAndShowGUI();
+ }
+ });
+ }
+
+}
Property changes on: trunk/httpunit/examples/YouTubeVisitor.java
___________________________________________________________________
Added: svn:mime-type
+ text/plain
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <wol...@us...> - 2011-01-10 16:09:47
|
Revision: 1073
http://httpunit.svn.sourceforge.net/httpunit/?rev=1073&view=rev
Author: wolfgang_fahl
Date: 2011-01-10 16:09:41 +0000 (Mon, 10 Jan 2011)
Log Message:
-----------
leave xml output untouched
Modified Paths:
--------------
trunk/httpunit/examples/BrowserDisplayer.java
Modified: trunk/httpunit/examples/BrowserDisplayer.java
===================================================================
--- trunk/httpunit/examples/BrowserDisplayer.java 2011-01-10 16:07:57 UTC (rev 1072)
+++ trunk/httpunit/examples/BrowserDisplayer.java 2011-01-10 16:09:41 UTC (rev 1073)
@@ -33,7 +33,9 @@
File f = File.createTempFile("httpUnit", ".html");
f.deleteOnExit();
PrintWriter fod = new PrintWriter(new FileOutputStream(f));
- fod.print("<head><base href=\"'http://localhost'/\"> </head>");
+ if (!text.startsWith("<?xml")) {
+ fod.print("<head><base href=\"'http://localhost'/\"> </head>");
+ }
fod.print(text);
fod.close();
URL url = f.toURL();
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <wol...@us...> - 2011-01-10 16:08:04
|
Revision: 1072
http://httpunit.svn.sourceforge.net/httpunit/?rev=1072&view=rev
Author: wolfgang_fahl
Date: 2011-01-10 16:07:57 +0000 (Mon, 10 Jan 2011)
Log Message:
-----------
fixed to use Google Maps direction API
Modified Paths:
--------------
trunk/httpunit/examples/GoogleMapsExample.java
Modified: trunk/httpunit/examples/GoogleMapsExample.java
===================================================================
--- trunk/httpunit/examples/GoogleMapsExample.java 2011-01-10 15:30:39 UTC (rev 1071)
+++ trunk/httpunit/examples/GoogleMapsExample.java 2011-01-10 16:07:57 UTC (rev 1072)
@@ -17,8 +17,10 @@
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
+import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
+import java.io.FileReader;
import java.io.FileWriter;
import java.io.StringReader;
import java.io.Writer;
@@ -43,6 +45,13 @@
* get a Route from Google Maps and convert it as a GPX file useable by Garmin
* tracking devices - can be imported in MapSource software then ...
*
+ * As of 2011-01 the old example did not work properly any more. Tricks for
+ * accessing Google Maps via HTML / Javascript can be found at:
+ * http://www.codeproject.com/KB/scripting/Use_of_Google_Map.aspx
+ *
+ * this example was modified to use the Google Directions API now
+ * @see http://code.google.com/intl/de-DE/apis/maps/documentation/directions/
+ *
*/
public class GoogleMapsExample {
@@ -50,7 +59,27 @@
* shall we show debug information?
*/
private boolean DEBUG = true;
+
+ /**
+ * @param filePath the name of the file to open. Not sure if it can accept URLs or just filenames. Path handling could be better, and buffer sizes are hardcoded
+ */
+ private static String readFileAsString(String filePath)
+ throws java.io.IOException{
+ StringBuffer fileData = new StringBuffer(1000);
+ BufferedReader reader = new BufferedReader(
+ new FileReader(filePath));
+ char[] buf = new char[1024];
+ int numRead=0;
+ while((numRead=reader.read(buf)) != -1){
+ String readData = String.valueOf(buf, 0, numRead);
+ fileData.append(readData);
+ buf = new char[1024];
+ }
+ reader.close();
+ return fileData.toString();
+ }
+
/**
* get a Route description as a Garmin compatible GPX file
*
@@ -69,7 +98,17 @@
// http://www.fish-track.com/?page_id=3
Document gpxdoc = convertKMLtoGPX(kml);
// output the result
+ boolean tostdout=filename==null;
+ if (tostdout){
+ File f = File.createTempFile("httpUnit", ".xml");
+ f.deleteOnExit();
+ filename=f.getAbsolutePath();
+ }
xmlSerialize(gpxdoc, filename);
+ if (tostdout){
+ String xmltext=this.readFileAsString(filename);
+ System.out.println(xmltext);
+ }
}
/**
@@ -79,8 +118,7 @@
* @param filename
* @throws Exception
*/
- public void xmlSerialize(Document document, String filename)
- throws Exception {
+ public void xmlSerialize(Document document, String filename) throws Exception {
OutputFormat outputOptions = new OutputFormat();
// outputOptions.setOmitXMLDeclaration(true);
outputOptions.setIndent(4);
@@ -106,8 +144,8 @@
if (subNodes.getLength() != 1) {
if (throwException)
throw new RuntimeException("getSubNode failed for " + parent
- + " expected 1 child with tag name '" + tagName
- + "' but got " + subNodes.getLength());
+ + " expected 1 child with tag name '" + tagName + "' but got "
+ + subNodes.getLength());
else
return null;
}
@@ -115,41 +153,16 @@
}
/**
- * get the latitude and longitude from a route point
+ * convert the given Google Map Direction API file to gpx format
*
- * @param kmlRoutePoint
+ * @param xml
+ * - the xml version of the file
* @return
*/
- public String[] extractCoordinates(Element kmlRoutePoint) {
- String[] result = new String[2];
- Element point = getSubNode(kmlRoutePoint, "Point", false);
- if (point == null)
- return null;
- Element coordNode = getSubNode(point, "coordinates", true);
- String coords = coordNode.getTextContent();
- StringTokenizer coordSplitter = new StringTokenizer(coords, ",", false);
- if (coordSplitter.countTokens() <= 2) {
- throw new RuntimeException("extract coordinates failed for "
- + kmlRoutePoint
- + " expected at least two coordinates but got "
- + coordSplitter.countTokens() + " '" + coords + "'");
- }
- result[0] = coordSplitter.nextToken();
- result[1] = coordSplitter.nextToken();
- return result;
- }
-
- /**
- * convert the given kml file to gpx format
- *
- * @param kml
- * - the kml version of the file
- * @return
- */
- public Document convertKMLtoGPX(String kml) throws Exception {
+ public Document convertKMLtoGPX(String googlexml) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
- Document kmldoc = builder.parse(new InputSource(new StringReader(kml)));
+ Document kmldoc = builder.parse(new InputSource(new StringReader(googlexml)));
Document gpxdoc = builder.newDocument();
String comment = "Converted by httpunit GoogleMapsExample";
gpxdoc.appendChild(gpxdoc.createComment(comment));
@@ -157,7 +170,7 @@
org.w3c.dom.Element root = gpxdoc.createElement("gpx");
root.setAttribute("xmlns", "http://www.topografix.com/GPX/1/1");
root.setAttribute("creator", "KML2GPX Example by BITPlan");
- root.setAttribute("version", "1.1");
+ root.setAttribute("version", "1.2");
gpxdoc.appendChild(root);
org.w3c.dom.Element metadata = gpxdoc.createElement("metadata");
@@ -171,22 +184,22 @@
org.w3c.dom.Element route = gpxdoc.createElement("rte");
root.appendChild(route);
- NodeList routePoints = kmldoc.getElementsByTagName("Placemark");
+ NodeList routePoints = kmldoc.getElementsByTagName("step");
for (int i = 0; i < routePoints.getLength(); i++) {
- Element kmlRoutePoint = (Element) routePoints.item(i);
- String name = getSubNode(kmlRoutePoint, "name", true)
- .getTextContent();
+ Element stepNode = (Element) routePoints.item(i);
+ String instructions = getSubNode(stepNode, "html_instructions", true).getTextContent();
if (DEBUG)
- System.out.println("found route point " + i + ": " + name);
+ System.out.println("found route point " + i + ": " + instructions);
- String coords[] = extractCoordinates(kmlRoutePoint);
- if (coords != null) {
+ Element endNode=getSubNode(stepNode,"end_location",true);
+ Element latNode=getSubNode(endNode, "lat",true);
+ Element lonNode=getSubNode(endNode,"lng",true);
+ if (latNode != null && lonNode!=null) {
org.w3c.dom.Element routePoint = gpxdoc.createElement("rtept");
- routePoint.setAttribute("lon", coords[0]);
- routePoint.setAttribute("lat", coords[1]);
- org.w3c.dom.Element routePointName = gpxdoc
- .createElement("name");
- routePointName.setTextContent(name);
+ routePoint.setAttribute("lon", lonNode.getTextContent());
+ routePoint.setAttribute("lat", latNode.getTextContent());
+ org.w3c.dom.Element routePointName = gpxdoc.createElement("name");
+ routePointName.setTextContent("step"+i);
routePoint.appendChild(routePointName);
route.appendChild(routePoint);
}
@@ -197,11 +210,20 @@
/**
* the url to use
*/
- public static String url = "http://maps.google.com/maps";
+ public static String url = "http://maps.google.com/maps/api/directions/xml";
+
+
/**
- * the directions string to look for
+ * error handling in case the Google Maps WebPage has changed
+ *
+ * @throws Exception
*/
- public static String directions = "directions";
+ public void notifyGoogleMapsHasChanged(String msg) throws Exception {
+ throw new Exception(
+ "GoogleMaps lookupForm at "
+ + msg
+ + "\n has changed - please notify the author of this example via the httpunit-develop mailing list");
+ }
/**
* get a route from google maps with the given start and destination points
@@ -219,57 +241,41 @@
// Obtain the main page on the google maps web site
WebRequest request = new GetMethodWebRequest(url);
- request.setParameter("output", "html");
- WebResponse response = wc.getResponse(request);
- if (withDisplay && DEBUG)
- BrowserDisplayer.showResponseInBrowser(response);
-
- // find the link which contains the string for directions and click it
- WebLink directionsLink = response.getFirstMatchingLink(
- WebLink.MATCH_CONTAINED_TEXT, directions);
- if (directionsLink == null) {
- System.err.println("could not find " + directions + " in response");
- if (DEBUG)
- BrowserDisplayer.showResponseInBrowser(response);
- System.exit(1);
- }
- response = directionsLink.click();
- if (withDisplay && DEBUG)
- BrowserDisplayer.showResponseInBrowser(response);
- WebForm lookupForm = response.getFormWithID("q_form");
- if (lookupForm == null) {
- throw new Exception(
- "GoogleMaps lookupForm at "
- + request.toString()
- + "\n has changed - please notify the author if this example via the httpunit-develop mailing list");
- }
- request = lookupForm.getRequest();
- request.setParameter("saddr", startPoint);
- request.setParameter("daddr", destPoint);
- response = wc.getResponse(request);
- if (withDisplay)
- BrowserDisplayer.showResponseInBrowser(response);
- if (asKML) {
- // request.setParameter("output", "kml");
- FormParameter parameter = lookupForm.getParameter("output");
- FormControl outputControl = parameter.getControl();
- outputControl.setAttribute("value", "kml");
+ request.setParameter("origin", startPoint);
+ request.setParameter("destination", destPoint);
+ request.setParameter("sensor", "false");
+ if (DEBUG)
+ System.out.println("requesting "+url+"?"+request.getQueryString());
+ WebResponse response=null;
+ try {
response = wc.getResponse(request);
- if (withDisplay && DEBUG)
- BrowserDisplayer.showResponseInBrowser(response);
+ } catch (Throwable th) {
+ String[] paramnames = request.getRequestParameterNames();
+ System.err.print("valid parameter names are: ");
+ String delim = "";
+ for (int i = 0; i < paramnames.length; i++) {
+ System.err.print(delim + i + ":" + paramnames[i]);
+ delim = ",";
+ }
+ System.err.println();
+ this.notifyGoogleMapsHasChanged(request.toString() + ":"
+ + th.getMessage());
}
+ //if (withDisplay)
+ // BrowserDisplayer.showResponseInBrowser(response);
return (response.getText());
}
/**
- * get the distance between two given locations
+ * get the distance between two given locations from the Google Maps API xml
+ * file
*
* @param
*/
public String getDistance(String startPoint, String endPoint,
boolean withDisplay) throws Exception {
- String route = getRouteFromGoogleMaps(startPoint, endPoint,
- withDisplay, false);
+ String route = getRouteFromGoogleMaps(startPoint, endPoint, withDisplay,
+ false);
String[] driveLocale = { "Driving directions", "Route" };
String[] unitLocale = { "mi", "km" };
for (int i = 0; i < driveLocale.length; i++) {
@@ -303,20 +309,18 @@
try {
if (params.length < 3) {
System.out
- .println("Usage: java RouteAsGPX [from] [to] ([filename]|'distance') [nodisplay]");
+ .println("Usage: java RouteAsGPX [from] [to] [filename] [nodisplay]");
System.out
.println(" e.g. java RouteAsGPX sfo CA-94526 sfoexample.gpx");
System.out
.println(" to get the route as a Garmin compatible GPX file");
- System.out
- .println(" e.g. java RouteAsGPX sfo CA-94526 distance");
- System.out.println(" to calculate the distance");
- String[] defaultParams = { "sfo", "CA-94526", "distance" };
+ System.out.println(" e.g. java RouteAsGPX sfo CA-94526");
+ System.out.println(" to output to stdout/screen");
+ String[] defaultParams = { "sfo", "CA-94526", };
// defaultParams={"sfo","CA-94526","sfoexample.gpx"};
params = defaultParams;
System.out.println("will demonstrate usage with the route "
- + defaultParams[0] + " - " + defaultParams[1]
- + " and store to " + defaultParams[2]);
+ + defaultParams[0] + " - " + defaultParams[1] + " to stdout ");
}
/**
* This is how to use the example in germany:
@@ -331,17 +335,10 @@
withDisplay = false;
String startPoint = params[0];
String endPoint = params[1];
- String filename = params[2];
- if (filename.equals("distance")) {
- String distanceS = routeAsGPX.getDistance(startPoint, endPoint,
- withDisplay);
- // String distanceS=NumberFormat.getInstance().format(distance);
- System.out.println("The distance between " + startPoint
- + " and " + endPoint + " is " + distanceS);
- } else {
- routeAsGPX.getRouteAsGPX(startPoint, endPoint, filename,
- withDisplay);
- }
+ String filename = null;
+ if (params.length>2)
+ filename=params[2];
+ routeAsGPX.getRouteAsGPX(startPoint, endPoint, filename, withDisplay);
} catch (Exception e) {
System.err.println("Exception: " + e);
e.printStackTrace();
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <wol...@us...> - 2011-01-10 15:30:46
|
Revision: 1071
http://httpunit.svn.sourceforge.net/httpunit/?rev=1071&view=rev
Author: wolfgang_fahl
Date: 2011-01-10 15:30:39 +0000 (Mon, 10 Jan 2011)
Log Message:
-----------
add suport for getDesktop if available
Modified Paths:
--------------
trunk/httpunit/examples/BrowserDisplayer.java
Modified: trunk/httpunit/examples/BrowserDisplayer.java
===================================================================
--- trunk/httpunit/examples/BrowserDisplayer.java 2011-01-10 13:56:24 UTC (rev 1070)
+++ trunk/httpunit/examples/BrowserDisplayer.java 2011-01-10 15:30:39 UTC (rev 1071)
@@ -1,123 +1,166 @@
import com.meterware.httpunit.*;
+import java.awt.Desktop;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
+import java.net.URI;
import java.net.URL;
-
/**
- * This example is from http://m0smith.freeshell.org/blog-portletunit/2008/05/bare-bones-browser-launch-for-java-use
- * @author Matthew O. Smith
- *
+ * This example is influenced from
+ * http://m0smith.freeshell.org/blog-portletunit/2008/05/bare
+ * -bones-browser-launch-for-java-use
+ *
+ * @author Matthew O. Smith
+ *
*/
public class BrowserDisplayer {
/**
- * Show the response in a browser.
- *
- * @param response
- * the response
- * @throws Exception
- * on error
- */
- public static void showResponseInBrowser(WebResponse response) throws Exception {
- String text = response.getText();
- File f = File.createTempFile("httpUnit", ".html");
- f.deleteOnExit();
- PrintWriter fod = new PrintWriter(new FileOutputStream(f));
- fod.print("<head><base href=\"'http://localhost'/\"> </head>");
- fod.print(text);
- fod.close();
- URL url = f.toURL();
- openURL(url);
- }
+ * Show the response in a browser.
+ *
+ * @param response
+ * the response
+ * @throws Exception
+ * on error
+ */
+ public static void showResponseInBrowser(WebResponse response)
+ throws Exception {
+ String text = response.getText();
+ File f = File.createTempFile("httpUnit", ".html");
+ f.deleteOnExit();
+ PrintWriter fod = new PrintWriter(new FileOutputStream(f));
+ fod.print("<head><base href=\"'http://localhost'/\"> </head>");
+ fod.print(text);
+ fod.close();
+ URL url = f.toURL();
+ openURL(url);
+ }
- /**
- * Bare Bones Browser Launch Version 1.5 (December 10, 2005) By Dem
- * Pilafian. Supports: Mac OS X, GNU/Linux, Unix, Windows XP
- *
- * Example Usage: String url = "http://www.centerkey.com/";
- * BareBonesBrowserLaunch.openURL(url); Public Domain Software -- Free to
- * Use as You Like
- *
- * @param url
- * the url to open
- * @throws ClassNotFoundException
- * getting class
- * @throws NoSuchMethodException
- * yes
- * @throws SecurityException
- * well
- * @throws InvocationTargetException
- * trying to invloke
- * @throws IllegalAccessException
- * trying to access
- * @throws IllegalArgumentException
- * bad arguement
- * @throws IOException
- * opening window
- * @throws InterruptedException waiting
- */
- public static void openURL(URL url) throws ClassNotFoundException, NoSuchMethodException,
- IllegalAccessException, InvocationTargetException, IOException, InterruptedException {
- String osName = System.getProperty("os.name");
+ static final String[] browsers = { "google-chrome", "firefox", "opera",
+ "epiphany", "konqueror", "conkeror", "midori", "kazehakase", "mozilla" };
- if (osName.startsWith("Mac OS")) {
- Class fileMgr = Class.forName("com.apple.eio.FileManager");
- Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[] {String.class });
- openURL.invoke(null, new Object[] {url.toString() });
- } else if (osName.startsWith("Windows")) {
- String cmdLine = "rundll32 url.dll,FileProtocolHandler " + url.toString();
- Process exec = Runtime.getRuntime().exec(cmdLine);
- exec.waitFor();
- } else { // assume Unix or Linux
- String[] browsers = {"firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape" };
- String browser = null;
- for (int count = 0; count < browsers.length && browser == null; count++) { if (Runtime.getRuntime().exec(new String[] {"which", browsers[count] }).waitFor() == 0) { browser = browsers[count]; } } if (browser == null) { throw new IllegalStateException("Could not find web browser"); } else { Runtime.getRuntime().exec(new String[] {browser, url.toString() });
- }
- }
- }
-
- /**
- * open a given url indirectly
- * @param params
- */
- public static void main( String[] params ) {
- try {
- if (params.length < 1) {
- System.out.println( "Usage: java BrowserDisplay [url]" );
- System.out.println( "");
- System.out.println( "will demonstrate usage with the url 'http://www.meterware.com' now ...");
- String[] defaultParams={"http://www.meterware.com"};
- params=defaultParams;
- }
- // direct call first
- String url=params[0];
- openURL(new URL(url));
- // and now indirectly
- // create the conversation object which will maintain state for us
- WebConversation wc = new WebConversation();
+ static final String errMsg = "Error attempting to launch web browser";
- // Obtain the main page on the meterware web site
- WebRequest request = new GetMethodWebRequest( url );
- WebResponse response = wc.getResponse( request );
- showResponseInBrowser(response);
-
- // find the link which contains the string "HttpUnit" and click it
- WebLink httpunitLink = response.getFirstMatchingLink( WebLink.MATCH_CONTAINED_TEXT, "HttpUnit" );
- response = httpunitLink.click();
- showResponseInBrowser(response);
- System.out.println("Your browser should show three pages now:");
- System.out.println("1. a direct invocation of "+url);
- System.out.println("2. an indirect invocation of "+url+" via httpunit");
- System.out.println("3. the result httpunit clicking the httpunit link on 2.");
+ /**
+ * Bare Bones Browser Launch Version 1.5 (December 10, 2005) By Dem Pilafian.
+ * Supports: Mac OS X, GNU/Linux, Unix, Windows XP
+ *
+ * Example Usage: String url = "http://www.centerkey.com/";
+ * BareBonesBrowserLaunch.openURL(url); Public Domain Software -- Free to Use
+ * as You Like
+ *
+ * @see http://www.centerkey.com/java/browser/
+ *
+ * @param url
+ * the url to open
+ * @throws ClassNotFoundException
+ * getting class
+ * @throws NoSuchMethodException
+ * yes
+ * @throws SecurityException
+ * well
+ * @throws InvocationTargetException
+ * trying to invloke
+ * @throws IllegalAccessException
+ * trying to access
+ * @throws IllegalArgumentException
+ * bad arguement
+ * @throws IOException
+ * opening window
+ * @throws InterruptedException
+ * waiting
+ */
+ public static void openURL(URL url) throws ClassNotFoundException,
+ NoSuchMethodException, IllegalAccessException, InvocationTargetException,
+ IOException, InterruptedException {
+ String osName = System.getProperty("os.name");
+ String urltext=url.toString();
+ // Try java desktop API first (new in Java 1.6)
+ // basically: java.awt.Desktop.getDesktop().browse(new URI(url));
+ try {
+ Class desktop = Class.forName("java.awt.Desktop");
+ Method getDesktop = desktop.getDeclaredMethod("getDesktop", new Class[] {});
+ Object desktopInstance = getDesktop.invoke(null, new Object[] {});
+ Method browse = desktop.getDeclaredMethod("browse", new Class[] {URI.class});
+ URI uri = new URI(urltext);
+ //logger.fine("Using Java Desktop API to open URL '"+url+"'");
+ browse.invoke(desktopInstance, new Object[] {uri});
+ return;
+ } catch(Exception e) { }
+
+ // Failed, resort to executing the browser manually
+
+ if (osName.startsWith("Mac OS")) {
+ Class fileMgr = Class.forName("com.apple.eio.FileManager");
+ Method openURL = fileMgr.getDeclaredMethod("openURL",
+ new Class[] { String.class });
+ openURL.invoke(null, new Object[] { urltext });
+ } else if (osName.startsWith("Windows")) {
+ String cmdLine = "rundll32 url.dll,FileProtocolHandler " + urltext;
+ Process exec = Runtime.getRuntime().exec(cmdLine);
+ exec.waitFor();
+ } else { // assume Unix or Linux
+ String browser = null;
+ for (int count = 0; count < browsers.length && browser == null; count++) {
+ if (Runtime.getRuntime()
+ .exec(new String[] { "which", browsers[count] }).waitFor() == 0) {
+ browser = browsers[count];
+ }
+ }
+ if (browser == null) {
+ throw new IllegalStateException(errMsg);
+ } else {
+ Runtime.getRuntime().exec(new String[] { browser, urltext });
+ }
+ }
+ }
- } catch (Exception e) {
- System.err.println( "Exception: " + e );
- }
-}
+ /**
+ * open a given url indirectly
+ *
+ * @param params
+ */
+ public static void main(String[] params) {
+ try {
+ if (params.length < 1) {
+ System.out.println("Usage: java BrowserDisplay [url]");
+ System.out.println("");
+ System.out
+ .println("will demonstrate usage with the url 'http://www.meterware.com' now ...");
+ String[] defaultParams = { "http://www.meterware.com" };
+ params = defaultParams;
+ }
+ // direct call first
+ String url = params[0];
+ openURL(new URL(url));
+ // and now indirectly
+ // create the conversation object which will maintain state for us
+ WebConversation wc = new WebConversation();
+
+ // Obtain the main page on the meterware web site
+ WebRequest request = new GetMethodWebRequest(url);
+ WebResponse response = wc.getResponse(request);
+ showResponseInBrowser(response);
+
+ // find the link which contains the string "HttpUnit" and click it
+ WebLink httpunitLink = response.getFirstMatchingLink(
+ WebLink.MATCH_CONTAINED_TEXT, "HttpUnit");
+ response = httpunitLink.click();
+ showResponseInBrowser(response);
+ System.out.println("Your browser should show three pages now:");
+ System.out.println("1. a direct invocation of " + url);
+ System.out.println("2. an indirect invocation of " + url
+ + " via httpunit");
+ System.out
+ .println("3. the result httpunit clicking the httpunit link on 2.");
+
+ } catch (Exception e) {
+ System.err.println("Exception: " + e);
+ }
+ }
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <wol...@us...> - 2011-01-10 13:56:30
|
Revision: 1070
http://httpunit.svn.sourceforge.net/httpunit/?rev=1070&view=rev
Author: wolfgang_fahl
Date: 2011-01-10 13:56:24 +0000 (Mon, 10 Jan 2011)
Log Message:
-----------
fixed according to changes on simple.wiktionary.org
Modified Paths:
--------------
trunk/httpunit/examples/NearWords.java
Modified: trunk/httpunit/examples/NearWords.java
===================================================================
--- trunk/httpunit/examples/NearWords.java 2011-01-10 13:39:48 UTC (rev 1069)
+++ trunk/httpunit/examples/NearWords.java 2011-01-10 13:56:24 UTC (rev 1070)
@@ -8,8 +8,9 @@
/**
* This class demonstrates using httpunit to use the functionality of a web set
- * from a command line. To use it, specify a single word to be searched.
- * The program will use the Wiktionary web site to find all links which match the pattern.
+ * from a command line. To use it, specify a single word to be searched. The
+ * program will use the Wiktionary web site to find all links which match the
+ * pattern.
*
* Note: this program is not robust, but should work if used properly.
**/
@@ -17,6 +18,7 @@
/***
* start a search for the given word
+ *
* @param params
*/
public static void main(String[] params) {
@@ -43,18 +45,18 @@
}
/**
- * subclass to seek words from the Wiktionary as of 2009-08-21
+ * subclass to seek words from the Wiktionary as of 2010-01-10
*
*/
class WordSeeker {
-
+ String url = "http://simple.wiktionary.org/";
+
/**
* create a word seeker that visits wiktionary.org
*/
public WordSeeker() {
try {
HttpUnitOptions.setScriptingEnabled(false);
- String url = "http://simple.wiktionary.org/";
System.out.println("visiting " + url);
WebRequest request = new GetMethodWebRequest(url);
response = conversation.getResponse(request);
@@ -73,43 +75,53 @@
public String[] getWordsMatching(String pattern) throws Exception {
System.out.println("getting Words matching '" + pattern + "'");
WebForm lookupForm = response.getFormWithID("searchform");
- SubmitButton fulltextButton = lookupForm.getSubmitButton("fulltext");
+ SubmitButton fulltextButton = lookupForm.getSubmitButton("button");
+ if (fulltextButton==null){
+ System.err.println("Could not find the fulltext submit button on webpage "+url);
+ System.err.println("You might want to fix the source code and submit a patch to the httpunit Developer team");
+ String [] result={"No result"};
+ return result;
+ }
System.out.println("Clicking " + fulltextButton.getName());
WebRequest request = lookupForm.getRequest(fulltextButton);
request.setParameter("search", pattern);
response = lookupForm.submit(fulltextButton);
// alternative: goButton.click();
- return getOptionsFromResponse();
+ return getOptionsFromResponse(pattern);
}
private WebConversation conversation = new WebConversation();
+
private WebResponse response;
/**
*
+ * @param pattern
* @return
* @throws Exception
*/
- private String[] getOptionsFromResponse() throws Exception {
+ private String[] getOptionsFromResponse(String pattern) throws Exception {
String[] words;
BrowserDisplayer.showResponseInBrowser(response);
WebLink[] links = response.getLinks();
- ArrayList result=new ArrayList();
+ ArrayList result = new ArrayList();
// start from the "Advanced" link section
- boolean start=false;
+ boolean start = false;
for (int i = 0; i < links.length; i++) {
WebLink link = links[i];
- if (link.getText().startsWith("Advanced"))
- start=true;
- else if (link.getText().startsWith("next 20"))
- break;
- else if (start && !link.getText().startsWith("(more"))
+ String linkText=link.getText();
+ //if (linkText.startsWith("Advanced"))
+ // start = true;
+ //else if (link.getText().startsWith("next 20"))
+ // break;
+ //else if (start && !link.getText().startsWith("(more"))
+ if (linkText.indexOf(pattern)>=0)
result.add(link);
}
words = new String[result.size()];
- for (int i=0;i<result.size();i++) {
- WebLink link=(WebLink) result.get(i);
- words[i]=link.getText()+" => "+link.getURLString();
+ for (int i = 0; i < result.size(); i++) {
+ WebLink link = (WebLink) result.get(i);
+ words[i] = link.getText() + " => " + link.getURLString();
}
return words;
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|