Source Code Cross Referenced for WebClientTest.java in  » Testing » htmlunit » com » gargoylesoftware » htmlunit » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Testing » htmlunit » com.gargoylesoftware.htmlunit 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


0001:        /*
0002:         * Copyright (c) 2002-2008 Gargoyle Software Inc. All rights reserved.
0003:         *
0004:         * Redistribution and use in source and binary forms, with or without
0005:         * modification, are permitted provided that the following conditions are met:
0006:         *
0007:         * 1. Redistributions of source code must retain the above copyright notice,
0008:         *    this list of conditions and the following disclaimer.
0009:         * 2. Redistributions in binary form must reproduce the above copyright notice,
0010:         *    this list of conditions and the following disclaimer in the documentation
0011:         *    and/or other materials provided with the distribution.
0012:         * 3. The end-user documentation included with the redistribution, if any, must
0013:         *    include the following acknowledgment:
0014:         *
0015:         *       "This product includes software developed by Gargoyle Software Inc.
0016:         *        (http://www.GargoyleSoftware.com/)."
0017:         *
0018:         *    Alternately, this acknowledgment may appear in the software itself, if
0019:         *    and wherever such third-party acknowledgments normally appear.
0020:         * 4. The name "Gargoyle Software" must not be used to endorse or promote
0021:         *    products derived from this software without prior written permission.
0022:         *    For written permission, please contact info@GargoyleSoftware.com.
0023:         * 5. Products derived from this software may not be called "HtmlUnit", nor may
0024:         *    "HtmlUnit" appear in their name, without prior written permission of
0025:         *    Gargoyle Software Inc.
0026:         *
0027:         * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
0028:         * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
0029:         * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARGOYLE
0030:         * SOFTWARE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
0031:         * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
0032:         * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
0033:         * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
0034:         * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
0035:         * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
0036:         * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
0037:         */
0038:        package com.gargoylesoftware.htmlunit;
0039:
0040:        import java.io.ByteArrayOutputStream;
0041:        import java.io.File;
0042:        import java.io.FileInputStream;
0043:        import java.io.FileNotFoundException;
0044:        import java.io.IOException;
0045:        import java.io.OutputStreamWriter;
0046:        import java.net.URI;
0047:        import java.net.URL;
0048:        import java.util.ArrayList;
0049:        import java.util.Arrays;
0050:        import java.util.Collections;
0051:        import java.util.List;
0052:
0053:        import org.apache.commons.httpclient.HttpStatus;
0054:        import org.apache.commons.io.FileUtils;
0055:        import org.apache.commons.io.IOUtils;
0056:        import org.apache.commons.lang.StringUtils;
0057:
0058:        import com.gargoylesoftware.base.testing.EventCatcher;
0059:        import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
0060:        import com.gargoylesoftware.htmlunit.html.HtmlElement;
0061:        import com.gargoylesoftware.htmlunit.html.HtmlInlineFrame;
0062:        import com.gargoylesoftware.htmlunit.html.HtmlPage;
0063:        import com.gargoylesoftware.htmlunit.html.SubmittableElement;
0064:        import com.gargoylesoftware.htmlunit.xml.XmlPage;
0065:
0066:        /**
0067:         * Tests for {@link WebClient}.
0068:         *
0069:         * @version $Revision: 2161 $
0070:         * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
0071:         * @author <a href="mailto:cse@dynabean.de">Christian Sell</a>
0072:         * @author <a href="mailto:bcurren@esomnie.com">Ben Curren</a>
0073:         * @author Marc Guillemot
0074:         * @author David D. Kilzer
0075:         * @author Chris Erskine
0076:         * @author Hans Donner
0077:         * @author Paul King
0078:         * @author Ahmed Ashour
0079:         */
0080:        public class WebClientTest extends WebTestCase {
0081:
0082:            /**
0083:             * Create an instance
0084:             *
0085:             * @param name The name of the test
0086:             */
0087:            public WebClientTest(final String name) {
0088:                super (name);
0089:            }
0090:
0091:            /**
0092:             * Test the situation where credentials are required but they haven't been specified.
0093:             *
0094:             * @throws Exception If something goes wrong.
0095:             */
0096:            public void testCredentialProvider_NoCredentials() throws Exception {
0097:                final String htmlContent = "<html><head><title>foo</title></head><body>\n"
0098:                        + "No access</body></html>";
0099:                final WebClient client = new WebClient();
0100:                client.setPrintContentOnFailingStatusCode(false);
0101:
0102:                final MockWebConnection webConnection = new MockWebConnection(
0103:                        client);
0104:                webConnection
0105:                        .setDefaultResponse(htmlContent, 401,
0106:                                "Credentials missing or just plain wrong",
0107:                                "text/plain");
0108:                client.setWebConnection(webConnection);
0109:
0110:                try {
0111:                    client.getPage(new WebRequestSettings(URL_GARGOYLE,
0112:                            SubmitMethod.POST));
0113:                    fail("Expected FailingHttpStatusCodeException");
0114:                } catch (final FailingHttpStatusCodeException e) {
0115:                    assertEquals(401, e.getStatusCode());
0116:                }
0117:            }
0118:
0119:            /**
0120:             * Test that {@link WebClient#assertionFailed(String)} actually throws an exception.
0121:             * @deprecated
0122:             */
0123:            public void testAssertionFailed() {
0124:                final WebClient client = new WebClient();
0125:
0126:                try {
0127:                    client.assertionFailed("foobar");
0128:                    fail("Expected AssertionFailedError");
0129:                } catch (final junit.framework.AssertionFailedError e) {
0130:                    assertEquals("foobar", e.getMessage());
0131:                }
0132:            }
0133:
0134:            /**
0135:             * Test that the {@link WebWindowEvent#CHANGE} window event gets fired at the
0136:             * appropriate time.
0137:             * @throws Exception If something goes wrong.
0138:             */
0139:            public void testHtmlWindowEvents_changed() throws Exception {
0140:                final String htmlContent = "<html><head><title>foo</title></head><body>\n"
0141:                        + "<a href='http://www.foo2.com' id='a2'>link to foo2</a>\n"
0142:                        + "</body></html>";
0143:                final WebClient client = new WebClient();
0144:                final EventCatcher eventCatcher = new EventCatcher();
0145:                eventCatcher.listenTo(client);
0146:
0147:                final MockWebConnection webConnection = new MockWebConnection(
0148:                        client);
0149:                webConnection.setDefaultResponse(htmlContent);
0150:                client.setWebConnection(webConnection);
0151:
0152:                final HtmlPage firstPage = (HtmlPage) client
0153:                        .getPage(URL_GARGOYLE);
0154:                final HtmlAnchor anchor = (HtmlAnchor) firstPage
0155:                        .getHtmlElementById("a2");
0156:
0157:                final List firstExpectedEvents = Arrays
0158:                        .asList(new Object[] { new WebWindowEvent(client
0159:                                .getCurrentWindow(), WebWindowEvent.CHANGE,
0160:                                null, firstPage), });
0161:                assertEquals(firstExpectedEvents, eventCatcher.getEvents());
0162:
0163:                eventCatcher.clear();
0164:                final HtmlPage secondPage = (HtmlPage) anchor.click();
0165:
0166:                final List secondExpectedEvents = Arrays
0167:                        .asList(new Object[] { new WebWindowEvent(client
0168:                                .getCurrentWindow(), WebWindowEvent.CHANGE,
0169:                                firstPage, secondPage), });
0170:                assertEquals(secondExpectedEvents, eventCatcher.getEvents());
0171:            }
0172:
0173:            /**
0174:             * Test that the {@link WebWindowEvent#OPEN} window event gets fired at
0175:             * the appropriate time.
0176:             * @throws Exception If something goes wrong.
0177:             */
0178:            public void testHtmlWindowEvents_opened() throws Exception {
0179:                final String page1Content = "<html><head><title>foo</title>\n"
0180:                        + "<script>window.open('"
0181:                        + URL_SECOND
0182:                        + "', 'myNewWindow')</script>\n"
0183:                        + "</head><body>\n"
0184:                        + "<a href='http://www.foo2.com' id='a2'>link to foo2</a>\n"
0185:                        + "</body></html>";
0186:                final String page2Content = "<html><head><title>foo</title></head><body></body></html>";
0187:                final WebClient client = new WebClient();
0188:                final EventCatcher eventCatcher = new EventCatcher();
0189:                eventCatcher.listenTo(client);
0190:
0191:                final MockWebConnection webConnection = new MockWebConnection(
0192:                        client);
0193:                webConnection.setResponse(URL_FIRST, page1Content);
0194:                webConnection.setResponse(URL_SECOND, page2Content);
0195:
0196:                client.setWebConnection(webConnection);
0197:
0198:                final HtmlPage firstPage = (HtmlPage) client.getPage(URL_FIRST);
0199:                assertEquals("foo", firstPage.getTitleText());
0200:
0201:                final WebWindow firstWindow = client.getCurrentWindow();
0202:                final WebWindow secondWindow = client
0203:                        .getWebWindowByName("myNewWindow");
0204:                final List expectedEvents = Arrays.asList(new Object[] {
0205:                        new WebWindowEvent(secondWindow, WebWindowEvent.OPEN,
0206:                                null, null),
0207:                        new WebWindowEvent(secondWindow, WebWindowEvent.CHANGE,
0208:                                null, secondWindow.getEnclosedPage()),
0209:                        new WebWindowEvent(firstWindow, WebWindowEvent.CHANGE,
0210:                                null, firstPage), });
0211:                assertEquals(expectedEvents, eventCatcher.getEvents());
0212:            }
0213:
0214:            /**
0215:             * Test that the {@link WebWindowEvent#CLOSE} window event gets fired at
0216:             * the appropriate time.
0217:             * @throws Exception If something goes wrong.
0218:             */
0219:            public void testHtmlWindowEvents_closedFromFrame() throws Exception {
0220:                final String firstContent = "<html><head><title>first</title></head><body>\n"
0221:                        + "<iframe src='"
0222:                        + URL_THIRD
0223:                        + "' id='frame1'>\n"
0224:                        + "<a href='"
0225:                        + URL_SECOND
0226:                        + "' id='a2'>link to foo2</a>\n" + "</body></html>";
0227:                final String secondContent = "<html><head><title>second</title></head><body></body></html>";
0228:                final String thirdContent = "<html><head><title>third</title></head><body></body></html>";
0229:                final WebClient client = new WebClient();
0230:
0231:                final MockWebConnection webConnection = new MockWebConnection(
0232:                        client);
0233:                webConnection.setResponse(URL_FIRST, firstContent);
0234:                webConnection.setResponse(URL_SECOND, secondContent);
0235:                webConnection.setResponse(URL_THIRD, thirdContent);
0236:
0237:                client.setWebConnection(webConnection);
0238:
0239:                final HtmlPage firstPage = (HtmlPage) client.getPage(URL_FIRST);
0240:                assertEquals("first", firstPage.getTitleText());
0241:
0242:                final EventCatcher eventCatcher = new EventCatcher();
0243:                eventCatcher.listenTo(client);
0244:
0245:                final HtmlInlineFrame frame = (HtmlInlineFrame) firstPage
0246:                        .getHtmlElementById("frame1");
0247:                final HtmlPage thirdPage = (HtmlPage) frame.getEnclosedPage();
0248:
0249:                // Load the second page
0250:                final HtmlAnchor anchor = (HtmlAnchor) firstPage
0251:                        .getHtmlElementById("a2");
0252:                final HtmlPage secondPage = (HtmlPage) anchor.click();
0253:                assertEquals("second", secondPage.getTitleText());
0254:
0255:                final WebWindow firstWindow = client.getCurrentWindow();
0256:                final List expectedEvents = Arrays.asList(new Object[] {
0257:                        new WebWindowEvent(frame.getEnclosedWindow(),
0258:                                WebWindowEvent.CLOSE, thirdPage, null),
0259:                        new WebWindowEvent(firstWindow, WebWindowEvent.CHANGE,
0260:                                firstPage, secondPage), });
0261:                assertEquals(expectedEvents.get(0), eventCatcher.getEvents()
0262:                        .get(0));
0263:                assertEquals(expectedEvents, eventCatcher.getEvents());
0264:            }
0265:
0266:            /**
0267:             * Test a 301 redirection code where the original request was a GET.
0268:             * @throws Exception If something goes wrong.
0269:             */
0270:            public void testRedirection301_MovedPermanently_GetMethod()
0271:                    throws Exception {
0272:                final int statusCode = 301;
0273:                final SubmitMethod initialRequestMethod = SubmitMethod.GET;
0274:                final SubmitMethod expectedRedirectedRequestMethod = SubmitMethod.GET;
0275:
0276:                doTestRedirection(statusCode, initialRequestMethod,
0277:                        expectedRedirectedRequestMethod);
0278:            }
0279:
0280:            /**
0281:             * Common utility for GET after POST redirection on same urls
0282:             * @param statusCode The code to return from the initial request
0283:             * @throws Exception if the test fails.
0284:             */
0285:            private void doTestRedirectionSameUrlAfterPost(final int statusCode)
0286:                    throws Exception {
0287:
0288:                final String firstContent = "<html><head><title>First</title></head><body></body></html>";
0289:                final String secondContent = "<html><head><title>Second</title></head><body></body></html>";
0290:
0291:                final WebClient webClient = new WebClient();
0292:
0293:                final List headers = Collections
0294:                        .singletonList(new KeyValuePair("Location", URL_FIRST
0295:                                .toExternalForm()));
0296:
0297:                // builds a webconnection that first sends a redirect and then a "normal" response for
0298:                // the same requested url
0299:                final MockWebConnection webConnection = new MockWebConnection(
0300:                        webClient) {
0301:                    private int count_ = 0;
0302:
0303:                    public WebResponse getResponse(
0304:                            final WebRequestSettings webRequestSettings)
0305:                            throws IOException {
0306:                        ++count_;
0307:                        if (count_ == 1) {
0308:                            final WebResponse response = super 
0309:                                    .getResponse(webRequestSettings);
0310:                            setResponse(webRequestSettings.getURL(),
0311:                                    secondContent);
0312:                            return response;
0313:                        } else {
0314:                            return super .getResponse(webRequestSettings);
0315:                        }
0316:                    }
0317:                };
0318:                webConnection.setResponse(URL_FIRST, firstContent, statusCode,
0319:                        "Some error", "text/html", headers);
0320:                webClient.setWebConnection(webConnection);
0321:
0322:                final HtmlPage page = (HtmlPage) webClient
0323:                        .getPage(new WebRequestSettings(URL_FIRST,
0324:                                SubmitMethod.POST));
0325:                final WebResponse webResponse = page.getWebResponse();
0326:                // A redirect should have happened
0327:                assertEquals(200, webResponse.getStatusCode());
0328:                assertEquals(URL_FIRST, webResponse.getUrl());
0329:                assertEquals("Second", page.getTitleText());
0330:                assertEquals(SubmitMethod.GET, webResponse.getRequestMethod());
0331:            }
0332:
0333:            /**
0334:             * From the http spec:  If the 301 status code is received in response
0335:             * to a request other than GET or HEAD, the user agent MUST NOT automatically
0336:             * redirect the request unless it can be confirmed by the user, since this
0337:             * might change the conditions under which the request was issued.
0338:             * BUT Firefox follows the redirection
0339:             * @throws Exception If something goes wrong.
0340:             */
0341:            public void testRedirection301_MovedPermanently_PostMethod()
0342:                    throws Exception {
0343:                final int statusCode = 301;
0344:                final SubmitMethod initialRequestMethod = SubmitMethod.POST;
0345:                final SubmitMethod expectedRedirectedRequestMethod = SubmitMethod.GET;
0346:
0347:                doTestRedirection(statusCode, initialRequestMethod,
0348:                        expectedRedirectedRequestMethod);
0349:                doTestRedirectionSameUrlAfterPost(statusCode);
0350:            }
0351:
0352:            /**
0353:             * From the http spec:  Note: RFC 1945 and RFC 2068 specify that the client
0354:             * is not allowed to change the method on the redirected request.  However,
0355:             * most existing user agent implementations treat 302 as if it were a 303
0356:             * response, performing a GET on the Location field-value regardless
0357:             * of the original request method. The status codes 303 and 307 have
0358:             * been added for servers that wish to make unambiguously clear which
0359:             * kind of reaction is expected of the client.
0360:             * @throws Exception If something goes wrong.
0361:             */
0362:            public void testRedirection302_MovedTemporarily_PostMethod()
0363:                    throws Exception {
0364:                final int statusCode = 302;
0365:                final SubmitMethod initialRequestMethod = SubmitMethod.POST;
0366:                final SubmitMethod expectedRedirectedRequestMethod = SubmitMethod.GET;
0367:
0368:                doTestRedirection(statusCode, initialRequestMethod,
0369:                        expectedRedirectedRequestMethod);
0370:                doTestRedirectionSameUrlAfterPost(statusCode);
0371:            }
0372:
0373:            /**
0374:             * Test a 302 redirection code.
0375:             * @throws Exception If something goes wrong.
0376:             */
0377:            public void testRedirection302_MovedTemporarily_GetMethod()
0378:                    throws Exception {
0379:                final int statusCode = 302;
0380:                final SubmitMethod initialRequestMethod = SubmitMethod.GET;
0381:                final SubmitMethod expectedRedirectedRequestMethod = SubmitMethod.GET;
0382:
0383:                doTestRedirection(statusCode, initialRequestMethod,
0384:                        expectedRedirectedRequestMethod);
0385:            }
0386:
0387:            /**
0388:             * Test a 302 redirection code with "," in url parameters.
0389:             * @throws Exception If something goes wrong.
0390:             */
0391:            public void testRedirection302_MovedTemporarily_CommaInParameters()
0392:                    throws Exception {
0393:                doTestRedirection(302, SubmitMethod.GET, SubmitMethod.GET,
0394:                        URL_SECOND + "/foo.html?foo1=abc&foo2=1,2,3,4");
0395:            }
0396:
0397:            /**
0398:             * Tests a 303 redirection code.  This should be the same as a 302.
0399:             * @throws Exception If something goes wrong.
0400:             */
0401:            public void testRedirection303_SeeOther_GetMethod()
0402:                    throws Exception {
0403:                final int statusCode = 303;
0404:                final SubmitMethod initialRequestMethod = SubmitMethod.GET;
0405:                final SubmitMethod expectedRedirectedRequestMethod = SubmitMethod.GET;
0406:
0407:                doTestRedirection(statusCode, initialRequestMethod,
0408:                        expectedRedirectedRequestMethod);
0409:            }
0410:
0411:            /**
0412:             * Tests a 303 redirection code - this should be the same as a 302.
0413:             * @throws Exception If something goes wrong.
0414:             */
0415:            public void testRedirection303_SeeOther_PostMethod()
0416:                    throws Exception {
0417:                final int statusCode = 303;
0418:                final SubmitMethod initialRequestMethod = SubmitMethod.POST;
0419:                final SubmitMethod expectedRedirectedRequestMethod = SubmitMethod.GET;
0420:
0421:                doTestRedirection(statusCode, initialRequestMethod,
0422:                        expectedRedirectedRequestMethod);
0423:                doTestRedirectionSameUrlAfterPost(statusCode);
0424:            }
0425:
0426:            /**
0427:             * Tests a 307 redirection code.
0428:             * @throws Exception If something goes wrong.
0429:             */
0430:            public void testRedirection307_TemporaryRedirect_GetMethod()
0431:                    throws Exception {
0432:                final int statusCode = 307;
0433:                final SubmitMethod initialRequestMethod = SubmitMethod.GET;
0434:                final SubmitMethod expectedRedirectedRequestMethod = SubmitMethod.GET;
0435:
0436:                doTestRedirection(statusCode, initialRequestMethod,
0437:                        expectedRedirectedRequestMethod);
0438:            }
0439:
0440:            /**
0441:             * Tests a 307 redirection code.
0442:             * @throws Exception If something goes wrong.
0443:             */
0444:            public void testRedirection307_TemporaryRedirect_PostMethod()
0445:                    throws Exception {
0446:                final int statusCode = 307;
0447:                final SubmitMethod initialRequestMethod = SubmitMethod.POST;
0448:                final SubmitMethod expectedRedirectedRequestMethod = null;
0449:
0450:                doTestRedirection(statusCode, initialRequestMethod,
0451:                        expectedRedirectedRequestMethod);
0452:            }
0453:
0454:            /**
0455:             * Basic logic for all the redirection tests.
0456:             *
0457:             * @param statusCode The code to return from the initial request
0458:             * @param initialRequestMethod The initial request.
0459:             * @param expectedRedirectedRequestMethod The submit method of the second (redirected) request.
0460:             * If a redirect is not expected to happen then this must be null
0461:             * @throws Exception if the test fails.
0462:             */
0463:            private void doTestRedirection(final int statusCode,
0464:                    final SubmitMethod initialRequestMethod,
0465:                    final SubmitMethod expectedRedirectedRequestMethod)
0466:                    throws Exception {
0467:
0468:                doTestRedirection(statusCode, initialRequestMethod,
0469:                        expectedRedirectedRequestMethod, URL_SECOND
0470:                                .toExternalForm());
0471:            }
0472:
0473:            /**
0474:             * Basic logic for all the redirection tests.
0475:             *
0476:             * @param statusCode The code to return from the initial request
0477:             * @param initialRequestMethod The initial request.
0478:             * @param expectedRedirectedRequestMethod The submit method of the second (redirected) request.
0479:             * If a redirect is not expected to happen then this must be null
0480:             * @param newLocation the Location set in the redirection header
0481:             * @throws Exception if the test fails.
0482:             */
0483:            private void doTestRedirection(final int statusCode,
0484:                    final SubmitMethod initialRequestMethod,
0485:                    final SubmitMethod expectedRedirectedRequestMethod,
0486:                    final String newLocation) throws Exception {
0487:
0488:                doTestRedirection(statusCode, initialRequestMethod,
0489:                        expectedRedirectedRequestMethod, newLocation, false);
0490:                doTestRedirection(statusCode, initialRequestMethod,
0491:                        expectedRedirectedRequestMethod, newLocation, true);
0492:            }
0493:
0494:            /**
0495:             * Browsers allow many redirections to the same url before to stop redirections.
0496:             * See Bug 1619765 and feature request 1472343.
0497:             * @throws Exception if the test fails.
0498:             */
0499:            public void testRedirectionSameURL() throws Exception {
0500:                final HtmlPage page1 = getPageWithRedirectionsSameURL(1);
0501:                assertEquals("Second", page1.getTitleText());
0502:
0503:                final HtmlPage page2 = getPageWithRedirectionsSameURL(30);
0504:                assertEquals("Redirect needed 21", page2.getWebResponse()
0505:                        .getStatusMessage());
0506:            }
0507:
0508:            private HtmlPage getPageWithRedirectionsSameURL(
0509:                    final int nbRedirections) throws Exception {
0510:                final String firstContent = "<html><head><title>First</title></head><body></body></html>";
0511:                final String secondContent = "<html><head><title>Second</title></head><body></body></html>";
0512:
0513:                final WebClient webClient = new WebClient();
0514:
0515:                final URL url = URL_FIRST;
0516:                final List headers = Collections
0517:                        .singletonList(new KeyValuePair("Location", URL_FIRST
0518:                                .toExternalForm()));
0519:                final MockWebConnection webConnection = new MockWebConnection(
0520:                        webClient) {
0521:                    private int count_ = 0;
0522:
0523:                    public WebResponse getResponse(
0524:                            final WebRequestSettings webRequestSettings)
0525:                            throws IOException {
0526:                        ++count_;
0527:                        if (count_ < nbRedirections) {
0528:                            setResponse(url, firstContent, 302,
0529:                                    "Redirect needed " + count_, "text/html",
0530:                                    headers);
0531:                            return super .getResponse(webRequestSettings);
0532:                        } else if (count_ == nbRedirections) {
0533:                            final WebResponse response = super 
0534:                                    .getResponse(webRequestSettings);
0535:                            setResponse(webRequestSettings.getURL(),
0536:                                    secondContent);
0537:                            return response;
0538:                        } else {
0539:                            return super .getResponse(webRequestSettings);
0540:                        }
0541:                    }
0542:                };
0543:                webConnection.setResponse(url, firstContent, 302,
0544:                        "Redirect needed", "text/html", headers);
0545:                webClient.setWebConnection(webConnection);
0546:                webClient.setThrowExceptionOnFailingStatusCode(false);
0547:
0548:                return (HtmlPage) webClient.getPage(url);
0549:            }
0550:
0551:            /**
0552:             * Basic logic for all the redirection tests.
0553:             *
0554:             * @param statusCode The code to return from the initial request
0555:             * @param initialRequestMethod The initial request.
0556:             * @param expectedRedirectedRequestMethod The submit method of the second (redirected) request.
0557:             * If a redirect is not expected to happen then this must be null
0558:             * @param newLocation the Location set in the redirection header
0559:             * @param useProxy indicates if the test should be performed with a proxy
0560:             * @throws Exception if the test fails.
0561:             */
0562:            private void doTestRedirection(final int statusCode,
0563:                    final SubmitMethod initialRequestMethod,
0564:                    final SubmitMethod expectedRedirectedRequestMethod,
0565:                    final String newLocation, final boolean useProxy)
0566:                    throws Exception {
0567:
0568:                final String firstContent = "<html><head><title>First</title></head><body></body></html>";
0569:                final String secondContent = "<html><head><title>Second</title></head><body></body></html>";
0570:
0571:                final WebClient webClient;
0572:                final String proxyHost;
0573:                final int proxyPort;
0574:                if (useProxy) {
0575:                    proxyHost = "someHost";
0576:                    proxyPort = 12233345;
0577:                    webClient = new WebClient(BrowserVersion.getDefault(),
0578:                            proxyHost, proxyPort);
0579:                } else {
0580:                    proxyHost = null;
0581:                    proxyPort = 0;
0582:                    webClient = new WebClient();
0583:                }
0584:
0585:                webClient.setThrowExceptionOnFailingStatusCode(false);
0586:                webClient.setPrintContentOnFailingStatusCode(false);
0587:
0588:                final List headers = Collections
0589:                        .singletonList(new KeyValuePair("Location", newLocation));
0590:                final MockWebConnection webConnection = new MockWebConnection(
0591:                        webClient);
0592:                webConnection.setResponse(URL_FIRST, firstContent, statusCode,
0593:                        "Some error", "text/html", headers);
0594:                webConnection.setResponse(new URL(newLocation), secondContent);
0595:
0596:                webClient.setWebConnection(webConnection);
0597:
0598:                final URL url = URL_FIRST;
0599:
0600:                HtmlPage page;
0601:                WebResponse webResponse;
0602:
0603:                //
0604:                // Second time redirection is turned on (default setting)
0605:                //
0606:                page = (HtmlPage) webClient.getPage(new WebRequestSettings(url,
0607:                        initialRequestMethod));
0608:                webResponse = page.getWebResponse();
0609:                if (expectedRedirectedRequestMethod == null) {
0610:                    // No redirect should have happened
0611:                    assertEquals(statusCode, webResponse.getStatusCode());
0612:                    assertEquals(initialRequestMethod, webConnection
0613:                            .getLastMethod());
0614:                } else {
0615:                    // A redirect should have happened
0616:                    assertEquals(HttpStatus.SC_OK, webResponse.getStatusCode());
0617:                    assertEquals(newLocation, webResponse.getUrl());
0618:                    assertEquals("Second", page.getTitleText());
0619:                    assertEquals(expectedRedirectedRequestMethod, webConnection
0620:                            .getLastMethod());
0621:                }
0622:                assertEquals(proxyHost, webConnection
0623:                        .getLastWebRequestSettings().getProxyHost());
0624:                assertEquals(proxyPort, webConnection
0625:                        .getLastWebRequestSettings().getProxyPort());
0626:
0627:                //
0628:                // Second time redirection is turned off
0629:                //
0630:                webClient.setRedirectEnabled(false);
0631:                page = (HtmlPage) webClient.getPage(new WebRequestSettings(url,
0632:                        initialRequestMethod));
0633:                webResponse = page.getWebResponse();
0634:                assertEquals(statusCode, webResponse.getStatusCode());
0635:                assertEquals(initialRequestMethod, webConnection
0636:                        .getLastMethod());
0637:                assertEquals(proxyHost, webConnection
0638:                        .getLastWebRequestSettings().getProxyHost());
0639:                assertEquals(proxyPort, webConnection
0640:                        .getLastWebRequestSettings().getProxyPort());
0641:            }
0642:
0643:            /**
0644:             * Test passing in a null page creator.
0645:             */
0646:            public void testSetPageCreator_null() {
0647:                final WebClient webClient = new WebClient();
0648:                try {
0649:                    webClient.setPageCreator(null);
0650:                    fail("Expected NullPointerException");
0651:                } catch (final NullPointerException e) {
0652:                    // expected path
0653:                }
0654:            }
0655:
0656:            /**
0657:             * Test {@link WebClient#setPageCreator(PageCreator)}.
0658:             * @throws Exception If something goes wrong.
0659:             */
0660:            public void testSetPageCreator() throws Exception {
0661:                final String page1Content = "<html><head><title>foo</title>\n"
0662:                        + "</head><body>\n"
0663:                        + "<a href='http://www.foo2.com' id='a2'>link to foo2</a>\n"
0664:                        + "</body></html>";
0665:                final WebClient client = new WebClient();
0666:
0667:                final MockWebConnection webConnection = new MockWebConnection(
0668:                        client);
0669:                webConnection.setResponse(URL_FIRST, page1Content);
0670:
0671:                client.setWebConnection(webConnection);
0672:                final List collectedPageCreationItems = new ArrayList();
0673:                client.setPageCreator(new CollectingPageCreator(
0674:                        collectedPageCreationItems));
0675:
0676:                final Page page = client.getPage(URL_FIRST);
0677:                assertTrue("instanceof TextPage", page instanceof  TextPage);
0678:
0679:                final List expectedPageCreationItems = Arrays
0680:                        .asList(new Object[] { page });
0681:
0682:                assertEquals(expectedPageCreationItems,
0683:                        collectedPageCreationItems);
0684:            }
0685:
0686:            /** A PageCreator that collects data */
0687:            private class CollectingPageCreator implements  PageCreator {
0688:                private final List collectedPages_;
0689:
0690:                /**
0691:                 * Create an instance
0692:                 * @param list The list that will contain the data
0693:                 */
0694:                public CollectingPageCreator(final List list) {
0695:                    collectedPages_ = list;
0696:                }
0697:
0698:                /**
0699:                 * Create a page
0700:                 * @param webResponse The web response
0701:                 * @param webWindow The web window
0702:                 * @return The new page
0703:                 * @throws IOException If an IO problem occurs
0704:                 */
0705:                public Page createPage(final WebResponse webResponse,
0706:                        final WebWindow webWindow) throws IOException {
0707:                    final Page page = new TextPage(webResponse, webWindow);
0708:                    webWindow.setEnclosedPage(page);
0709:                    collectedPages_.add(page);
0710:                    return page;
0711:                }
0712:            }
0713:
0714:            /**
0715:             * Test loading a page with POST parameters.
0716:             * @throws Exception If something goes wrong.
0717:             */
0718:            public void testLoadPage_PostWithParameters() throws Exception {
0719:                final String htmlContent = "<html><head><title>foo</title></head><body>\n"
0720:                        + "</body></html>";
0721:                final WebClient client = new WebClient();
0722:
0723:                final MockWebConnection webConnection = new MockWebConnection(
0724:                        client);
0725:                webConnection.setDefaultResponse(htmlContent);
0726:                client.setWebConnection(webConnection);
0727:
0728:                final String urlString = "http://first?a=b";
0729:                final URL url = new URL(urlString);
0730:                final HtmlPage page = (HtmlPage) client
0731:                        .getPage(new WebRequestSettings(url, SubmitMethod.POST));
0732:
0733:                assertEquals(urlString, page.getWebResponse().getUrl());
0734:            }
0735:
0736:            /**
0737:             * Test that double / in query string are not changed.
0738:             * @throws Exception If something goes wrong.
0739:             */
0740:            public void testLoadPage_SlashesInQueryString() throws Exception {
0741:                final String htmlContent = "<html><head><title>foo</title></head>\n"
0742:                        + "<body><a href='foo.html?id=UYIUYTY//YTYUY..F'>to page 2</a>\n"
0743:                        + "</body></html>";
0744:
0745:                final WebClient client = new WebClient();
0746:
0747:                final MockWebConnection webConnection = new MockWebConnection(
0748:                        client);
0749:                webConnection.setDefaultResponse(htmlContent);
0750:                client.setWebConnection(webConnection);
0751:
0752:                final HtmlPage page = (HtmlPage) client.getPage(URL_FIRST);
0753:                final HtmlAnchor link = (HtmlAnchor) page.getAnchors().get(0);
0754:                final Page page2 = link.click();
0755:                assertEquals("http://first/foo.html?id=UYIUYTY//YTYUY..F",
0756:                        page2.getWebResponse().getUrl());
0757:            }
0758:
0759:            /**
0760:             * Test that the path and query string are encoded to be valid.
0761:             * @throws Exception If something goes wrong.
0762:             */
0763:            public void testLoadPage_EncodeRequest() throws Exception {
0764:                final String htmlContent = "<html><head><title>foo</title></head><body>\n"
0765:                        + "</body></html>";
0766:
0767:                final WebClient client = new WebClient();
0768:
0769:                final MockWebConnection webConnection = new MockWebConnection(
0770:                        client);
0771:                webConnection.setDefaultResponse(htmlContent);
0772:                client.setWebConnection(webConnection);
0773:
0774:                // with query string not encoded
0775:                HtmlPage page = (HtmlPage) client
0776:                        .getPage("http://first?a=b c&d=" + ((char) 0xE9)
0777:                                + ((char) 0xE8));
0778:                assertEquals("http://first?a=b%20c&d=%C3%A9%C3%A8", page
0779:                        .getWebResponse().getUrl());
0780:
0781:                // with query string already encoded
0782:                page = (HtmlPage) client
0783:                        .getPage("http://first?a=b%20c&d=%C3%A9%C3%A8");
0784:                assertEquals("http://first?a=b%20c&d=%C3%A9%C3%A8", page
0785:                        .getWebResponse().getUrl());
0786:
0787:                // with query string partially encoded
0788:                page = (HtmlPage) client.getPage("http://first?a=b%20c&d=e f");
0789:                assertEquals("http://first?a=b%20c&d=e%20f", page
0790:                        .getWebResponse().getUrl());
0791:
0792:                // with anchor
0793:                page = (HtmlPage) client.getPage("http://first?a=b c#myAnchor");
0794:                assertEquals("http://first?a=b%20c#myAnchor", page
0795:                        .getWebResponse().getUrl());
0796:
0797:                // with query string containing encoded "&", "=", "+", ",", and "$"
0798:                page = (HtmlPage) client
0799:                        .getPage("http://first?a=%26%3D%20%2C%24");
0800:                assertEquals("http://first?a=%26%3D%20%2C%24", page
0801:                        .getWebResponse().getUrl());
0802:
0803:                // with character to encode in path
0804:                page = (HtmlPage) client.getPage("http://first/page 1.html");
0805:                assertEquals("http://first/page%201.html", page
0806:                        .getWebResponse().getUrl());
0807:
0808:                // with character to encode in path
0809:                page = (HtmlPage) client.getPage("http://first/page 1.html");
0810:                assertEquals("http://first/page%201.html", page
0811:                        .getWebResponse().getUrl());
0812:            }
0813:
0814:            /**
0815:             * Test loading a file page.
0816:             *
0817:             * @throws Exception If something goes wrong.
0818:             */
0819:            public void testLoadFilePage() throws Exception {
0820:
0821:                // Create a real file to read.
0822:                // It could be useful to have existing files to test in a special location in filesystem.
0823:                // It will be really needed when we have to test binary files using the file protocol.
0824:
0825:                final String htmlContent = "<html><head><title>foo</title></head><body></body></html>";
0826:                final File currentDirectory = new File((new File(""))
0827:                        .getAbsolutePath());
0828:                final File tmpFile = File.createTempFile("test", ".html",
0829:                        currentDirectory);
0830:                tmpFile.deleteOnExit();
0831:                final String encoding = (new OutputStreamWriter(
0832:                        new ByteArrayOutputStream())).getEncoding();
0833:                FileUtils.writeStringToFile(tmpFile, htmlContent, encoding);
0834:
0835:                // Test a normal file URL.
0836:
0837:                final WebClient client = new WebClient();
0838:                final URL url = new URL("file://" + tmpFile.getCanonicalPath());
0839:                final HtmlPage page = (HtmlPage) client.getPage(url);
0840:
0841:                assertEquals(htmlContent, page.getWebResponse()
0842:                        .getContentAsString());
0843:                assertEquals("text/html", page.getWebResponse()
0844:                        .getContentType());
0845:                assertEquals(200, page.getWebResponse().getStatusCode());
0846:                assertEquals("foo", page.getTitleText());
0847:
0848:                // Test a file URL with a query portion (needs to work for Dojo, for example).
0849:
0850:                final URL url2 = new URL(url.toExternalForm() + "?with=query");
0851:                final HtmlPage page2 = (HtmlPage) client.getPage(url2);
0852:
0853:                assertEquals(htmlContent, page2.getWebResponse()
0854:                        .getContentAsString());
0855:                assertEquals("text/html", page2.getWebResponse()
0856:                        .getContentType());
0857:                assertEquals(200, page2.getWebResponse().getStatusCode());
0858:                assertEquals("foo", page2.getTitleText());
0859:
0860:                // Test a file URL with a ref portion (needs to work for Dojo, for example).
0861:
0862:                final URL url3 = new URL(url.toExternalForm() + "#reference");
0863:                final HtmlPage page3 = (HtmlPage) client.getPage(url3);
0864:
0865:                assertEquals(htmlContent, page3.getWebResponse()
0866:                        .getContentAsString());
0867:                assertEquals("text/html", page3.getWebResponse()
0868:                        .getContentType());
0869:                assertEquals(200, page3.getWebResponse().getStatusCode());
0870:                assertEquals("foo", page3.getTitleText());
0871:            }
0872:
0873:            /**
0874:             * Test loading a file page with xml content. Regression test for bug 1113487.
0875:             *
0876:             * @throws Exception If something goes wrong.
0877:             */
0878:            public void testLoadFilePageXml() throws Exception {
0879:                final String xmlContent = "<?xml version='1.0' encoding='UTF-8'?>\n"
0880:                        + "<dataset>\n"
0881:                        + "<table name=\"USER\">\n"
0882:                        + "<column>ID</column>\n"
0883:                        + "<row>\n"
0884:                        + "<value>116517</value>\n"
0885:                        + "</row>\n"
0886:                        + "</table>\n"
0887:                        + "</dataset>";
0888:                final File currentDirectory = new File((new File(""))
0889:                        .getAbsolutePath());
0890:                final File tmpFile = File.createTempFile("test", ".xml",
0891:                        currentDirectory);
0892:                tmpFile.deleteOnExit();
0893:                final String encoding = (new OutputStreamWriter(
0894:                        new ByteArrayOutputStream())).getEncoding();
0895:                FileUtils.writeStringToFile(tmpFile, xmlContent, encoding);
0896:
0897:                final URL fileURL = new URL("file://"
0898:                        + tmpFile.getCanonicalPath());
0899:
0900:                final WebClient client = new WebClient();
0901:                final XmlPage page = (XmlPage) client.getPage(fileURL);
0902:
0903:                assertEquals(xmlContent, page.getWebResponse()
0904:                        .getContentAsString());
0905:                // "text/xml" or "application/xml", it doesn't matter
0906:                assertEquals("/xml", StringUtils.substring(page
0907:                        .getWebResponse().getContentType(), -4));
0908:                assertEquals(200, page.getWebResponse().getStatusCode());
0909:            }
0910:
0911:            /**
0912:             * Test redirecting with javascript during page load.
0913:             * @throws Exception If something goes wrong.
0914:             */
0915:            public void testRedirectViaJavaScriptDuringInitialPageLoad()
0916:                    throws Exception {
0917:                final String firstContent = "<html><head><title>First</title><script>\n"
0918:                        + "location.href='"
0919:                        + URL_SECOND
0920:                        + "'\n"
0921:                        + "</script></head><body></body></html>";
0922:                final String secondContent = "<html><head><title>Second</title></head><body></body></html>";
0923:
0924:                final WebClient webClient = new WebClient();
0925:
0926:                final MockWebConnection webConnection = new MockWebConnection(
0927:                        webClient);
0928:                webConnection.setResponse(URL_FIRST, firstContent);
0929:                webConnection.setResponse(URL_SECOND, secondContent);
0930:
0931:                webClient.setWebConnection(webConnection);
0932:
0933:                final URL url = URL_FIRST;
0934:
0935:                final HtmlPage page = (HtmlPage) webClient.getPage(url);
0936:                assertEquals("Second", page.getTitleText());
0937:            }
0938:
0939:            /**
0940:             * Test tabbing where there are no tabbable elements.
0941:             * @throws Exception If something goes wrong.
0942:             */
0943:            public void testKeyboard_NoTabbableElements() throws Exception {
0944:                final WebClient webClient = new WebClient();
0945:                final HtmlPage page = getPageForKeyboardTest(webClient,
0946:                        new String[0]);
0947:                final List collectedAlerts = new ArrayList();
0948:                webClient.setAlertHandler(new CollectingAlertHandler(
0949:                        collectedAlerts));
0950:
0951:                assertNull("original", page.getElementWithFocus());
0952:                assertNull("next", page.tabToNextElement());
0953:                assertNull("previous", page.tabToPreviousElement());
0954:                assertNull("accesskey", page.pressAccessKey('a'));
0955:
0956:                final List expectedAlerts = Collections.EMPTY_LIST;
0957:                assertEquals(expectedAlerts, collectedAlerts);
0958:            }
0959:
0960:            /**
0961:             * Test tabbing where there is only one tabbable element.
0962:             * @throws Exception If something goes wrong.
0963:             */
0964:            public void testKeyboard_OneTabbableElement() throws Exception {
0965:                final WebClient webClient = new WebClient();
0966:                final List collectedAlerts = new ArrayList();
0967:                webClient.setAlertHandler(new CollectingAlertHandler(
0968:                        collectedAlerts));
0969:
0970:                final HtmlPage page = getPageForKeyboardTest(webClient,
0971:                        new String[] { null });
0972:                final HtmlElement element = page.getHtmlElementById("submit0");
0973:
0974:                assertNull("original", page.getElementWithFocus());
0975:                assertNull("accesskey", page.pressAccessKey('x'));
0976:
0977:                assertEquals("next", element, page.tabToNextElement());
0978:                assertEquals("nextAgain", element, page.tabToNextElement());
0979:
0980:                page.getElementWithFocus().blur();
0981:                assertNull("original", page.getElementWithFocus());
0982:
0983:                assertEquals("previous", element, page.tabToPreviousElement());
0984:                assertEquals("previousAgain", element, page
0985:                        .tabToPreviousElement());
0986:
0987:                assertEquals("accesskey", element, page.pressAccessKey('z'));
0988:
0989:                final String[] expectedAlerts = { "focus-0", "blur-0",
0990:                        "focus-0" };
0991:                assertEquals(expectedAlerts, collectedAlerts);
0992:            }
0993:
0994:            /**
0995:             * Test pressing an accesskey.
0996:             * @throws Exception If something goes wrong.
0997:             */
0998:            public void testAccessKeys() throws Exception {
0999:                final WebClient webClient = new WebClient();
1000:                final List collectedAlerts = new ArrayList();
1001:                webClient.setAlertHandler(new CollectingAlertHandler(
1002:                        collectedAlerts));
1003:
1004:                final HtmlPage page = getPageForKeyboardTest(webClient,
1005:                        new String[] { "1", "2", "3" });
1006:
1007:                assertEquals("submit0", page.pressAccessKey('a')
1008:                        .getAttributeValue("name"));
1009:                assertEquals("submit2", page.pressAccessKey('c')
1010:                        .getAttributeValue("name"));
1011:                assertEquals("submit1", page.pressAccessKey('b')
1012:                        .getAttributeValue("name"));
1013:
1014:                final String[] expectedAlerts = { "focus-0", "blur-0",
1015:                        "focus-2", "blur-2", "focus-1" };
1016:                assertEquals(expectedAlerts, collectedAlerts);
1017:            }
1018:
1019:            /**
1020:             * Test tabbing to the next element.
1021:             * @throws Exception If something goes wrong.
1022:             */
1023:            public void testTabNext() throws Exception {
1024:                final WebClient webClient = new WebClient();
1025:                final List collectedAlerts = new ArrayList();
1026:                webClient.setAlertHandler(new CollectingAlertHandler(
1027:                        collectedAlerts));
1028:
1029:                final HtmlPage page = getPageForKeyboardTest(webClient,
1030:                        new String[] { "1", "2", "3" });
1031:
1032:                assertEquals("submit0", page.tabToNextElement()
1033:                        .getAttributeValue("name"));
1034:                assertEquals("submit1", page.tabToNextElement()
1035:                        .getAttributeValue("name"));
1036:                assertEquals("submit2", page.tabToNextElement()
1037:                        .getAttributeValue("name"));
1038:
1039:                final String[] expectedAlerts = { "focus-0", "blur-0",
1040:                        "focus-1", "blur-1", "focus-2" };
1041:                assertEquals(expectedAlerts, collectedAlerts);
1042:            }
1043:
1044:            /**
1045:             * Test tabbing to the previous element.
1046:             * @throws Exception If something goes wrong.
1047:             */
1048:            public void testTabPrevious() throws Exception {
1049:                final WebClient webClient = new WebClient();
1050:                final List collectedAlerts = new ArrayList();
1051:                webClient.setAlertHandler(new CollectingAlertHandler(
1052:                        collectedAlerts));
1053:
1054:                final HtmlPage page = getPageForKeyboardTest(webClient,
1055:                        new String[] { "1", "2", "3" });
1056:
1057:                assertEquals("submit2", page.tabToPreviousElement()
1058:                        .getAttributeValue("name"));
1059:                assertEquals("submit1", page.tabToPreviousElement()
1060:                        .getAttributeValue("name"));
1061:                assertEquals("submit0", page.tabToPreviousElement()
1062:                        .getAttributeValue("name"));
1063:
1064:                final String[] expectedAlerts = { "focus-2", "blur-2",
1065:                        "focus-1", "blur-1", "focus-0" };
1066:                assertEquals(expectedAlerts, collectedAlerts);
1067:            }
1068:
1069:            /**
1070:             * Test that a button can be selected via accesskey.
1071:             * @throws Exception If something goes wrong.
1072:             */
1073:            public void testPressAccessKey_Button() throws Exception {
1074:                final WebClient webClient = new WebClient();
1075:                final List collectedAlerts = new ArrayList();
1076:                webClient.setAlertHandler(new CollectingAlertHandler(
1077:                        collectedAlerts));
1078:
1079:                final HtmlPage page = getPageForKeyboardTest(webClient,
1080:                        new String[] { "1", "2", "3" });
1081:                final HtmlElement button = page.getHtmlElementById("button1");
1082:
1083:                final String[] expectedAlerts = { "buttonPushed" };
1084:                collectedAlerts.clear();
1085:
1086:                button.removeAttribute("disabled");
1087:                page.pressAccessKey('1');
1088:
1089:                assertEquals(expectedAlerts, collectedAlerts);
1090:            }
1091:
1092:            /**
1093:             * Return a loaded page for one of the keyboard tests.
1094:             * @param webClient the WebClient to load the page from.
1095:             * @param tabIndexValues The tab index values.  One input will be created for each item
1096:             * in this list.
1097:             * @return The loaded page.
1098:             * @throws Exception If something goes wrong.
1099:             */
1100:            private HtmlPage getPageForKeyboardTest(final WebClient webClient,
1101:                    final String[] tabIndexValues) throws Exception {
1102:
1103:                final StringBuffer buffer = new StringBuffer();
1104:                buffer
1105:                        .append("<html><head><title>First</title></head><body><form name='form1' method='post' onsubmit='return false;'>");
1106:
1107:                for (int i = 0; i < tabIndexValues.length; i++) {
1108:                    buffer.append("<input type='submit' name='submit");
1109:                    buffer.append(i);
1110:                    buffer.append("' id='submit");
1111:                    buffer.append(i);
1112:                    buffer.append("'");
1113:                    if (tabIndexValues[i] != null) {
1114:                        buffer.append(" tabindex='");
1115:                        buffer.append(tabIndexValues[i]);
1116:                        buffer.append("'");
1117:                    }
1118:                    buffer.append(" onblur='alert(\"blur-" + i + "\")'");
1119:                    buffer.append(" onfocus='alert(\"focus-" + i + "\")'");
1120:                    buffer.append(" accesskey='" + (char) ('a' + i) + "'");
1121:                    buffer.append(">\n");
1122:                }
1123:                buffer.append("<div id='div1'>foo</div>\n"); // something that isn't tabbable
1124:
1125:                // Elements that are tabbable but are disabled
1126:                buffer
1127:                        .append("<button name='button1' id='button1' disabled onclick='alert(\"buttonPushed\")' ");
1128:                buffer.append("accesskey='1'>foo</button>\n");
1129:
1130:                buffer.append("</form></body></html>");
1131:
1132:                final MockWebConnection webConnection = new MockWebConnection(
1133:                        webClient);
1134:                webConnection.setResponse(URL_FIRST, buffer.toString());
1135:                webClient.setWebConnection(webConnection);
1136:
1137:                return (HtmlPage) webClient.getPage(URL_FIRST);
1138:            }
1139:
1140:            /**
1141:             * Test {@link WebClient#loadWebResponseInto(WebResponse,WebWindow)}
1142:             * @throws Exception If the test fails.
1143:             */
1144:            public void testLoadWebResponseInto() throws Exception {
1145:                final WebClient webClient = new WebClient();
1146:                final WebResponse webResponse = new StringWebResponse(
1147:                        "<html><head><title>first</title></head><body></body></html>");
1148:
1149:                final Page page = webClient.loadWebResponseInto(webResponse,
1150:                        webClient.getCurrentWindow());
1151:                assertInstanceOf(page, HtmlPage.class);
1152:
1153:                final HtmlPage htmlPage = (HtmlPage) page;
1154:                assertEquals("first", htmlPage.getTitleText());
1155:            }
1156:
1157:            /**
1158:             * Verifies that exceptions are thrown on failing status code and the returned page
1159:             * is still set as the current page in the WebWindow.
1160:             *
1161:             * @throws Exception if test fails
1162:             */
1163:            public void testGetPageFailingStatusCode() throws Exception {
1164:                final String firstContent = "<html><head><title>Hello World</title></head><body></body></html>";
1165:
1166:                final WebClient webClient = new WebClient();
1167:
1168:                final MockWebConnection webConnection = new MockWebConnection(
1169:                        webClient);
1170:                webConnection.setResponse(URL_FIRST, firstContent, 500, "BOOM",
1171:                        "text/html", Collections.EMPTY_LIST);
1172:                webClient.setWebConnection(webConnection);
1173:                webClient.setThrowExceptionOnFailingStatusCode(true);
1174:                webClient.setPrintContentOnFailingStatusCode(false);
1175:                try {
1176:                    webClient.getPage(URL_FIRST);
1177:                    fail("Should have thrown");
1178:                } catch (final FailingHttpStatusCodeException e) {
1179:                    assertEquals(e.getStatusCode(), 500);
1180:                    assertEquals(e.getStatusMessage(), "BOOM");
1181:                    assertEquals(firstContent, e.getResponse()
1182:                            .getContentAsString());
1183:                }
1184:                final HtmlPage page = (HtmlPage) webClient.getCurrentWindow()
1185:                        .getEnclosedPage();
1186:                assertEquals("Hello World", page.getTitleText());
1187:            }
1188:
1189:            /**
1190:             * @throws Exception If the test fails.
1191:             */
1192:            public void testProxyConfig() throws Exception {
1193:
1194:                final String defaultProxyHost = "defaultProxyHost";
1195:                final int defaultProxyPort = 777;
1196:                final String html = "<html><head><title>Hello World</title></head><body></body></html>";
1197:                final WebClient webClient = new WebClient(
1198:                        BrowserVersion.INTERNET_EXPLORER_6_0, defaultProxyHost,
1199:                        defaultProxyPort);
1200:                final MockWebConnection webConnection = new MockWebConnection(
1201:                        webClient);
1202:                webConnection.setResponse(URL_FIRST, html);
1203:                webClient.setWebConnection(webConnection);
1204:
1205:                // Make sure default proxy settings are used.
1206:                webClient.getPage(URL_FIRST);
1207:                assertEquals(defaultProxyHost, webConnection
1208:                        .getLastWebRequestSettings().getProxyHost());
1209:                assertEquals(defaultProxyPort, webConnection
1210:                        .getLastWebRequestSettings().getProxyPort());
1211:
1212:                // Make sure custom proxy settings are used.
1213:                final String customProxyHost = "customProxyHost";
1214:                final int customProxyPort = 1000;
1215:                final WebRequestSettings settings = new WebRequestSettings(
1216:                        URL_FIRST);
1217:                settings.setProxyHost(customProxyHost);
1218:                settings.setProxyPort(customProxyPort);
1219:                webClient.getPage(settings);
1220:                assertEquals(customProxyHost, webConnection
1221:                        .getLastWebRequestSettings().getProxyHost());
1222:                assertEquals(customProxyPort, webConnection
1223:                        .getLastWebRequestSettings().getProxyPort());
1224:
1225:                // Make sure proxy bypass works with default proxy settings.
1226:                webClient.addHostsToProxyBypass(URL_FIRST.getHost());
1227:                webClient.getPage(URL_FIRST);
1228:                assertEquals(null, webConnection.getLastWebRequestSettings()
1229:                        .getProxyHost());
1230:                assertEquals(0, webConnection.getLastWebRequestSettings()
1231:                        .getProxyPort());
1232:
1233:                // Make sure proxy bypass doesn't work with custom proxy settings.
1234:                webClient.getPage(settings);
1235:                assertEquals(customProxyHost, webConnection
1236:                        .getLastWebRequestSettings().getProxyHost());
1237:                assertEquals(customProxyPort, webConnection
1238:                        .getLastWebRequestSettings().getProxyPort());
1239:
1240:                // Make sure we can remove proxy bypass filters.
1241:                webClient.removeHostsFromProxyBypass(URL_FIRST.getHost());
1242:                webClient.getPage(URL_FIRST);
1243:                assertEquals(defaultProxyHost, webConnection
1244:                        .getLastWebRequestSettings().getProxyHost());
1245:                assertEquals(defaultProxyPort, webConnection
1246:                        .getLastWebRequestSettings().getProxyPort());
1247:            }
1248:
1249:            /**
1250:             * Regression test for
1251:             * https://sourceforge.net/tracker/index.php?func=detail&aid=1669097&group_id=47038&atid=448266
1252:             * @throws Exception If the test fails.
1253:             */
1254:            public void testProxyConfigWithRedirect() throws Exception {
1255:
1256:                final String defaultProxyHost = "defaultProxyHost";
1257:                final int defaultProxyPort = 777;
1258:                final String html = "<html><head><title>Hello World</title></head><body></body></html>";
1259:                final WebClient webClient = new WebClient(
1260:                        BrowserVersion.INTERNET_EXPLORER_6_0, defaultProxyHost,
1261:                        defaultProxyPort);
1262:
1263:                webClient.addHostsToProxyBypass("hostToByPass");
1264:
1265:                final String location2 = "http://hostToByPass/foo.html";
1266:                final List headers = Collections
1267:                        .singletonList(new KeyValuePair("Location", location2));
1268:                final MockWebConnection webConnection = new MockWebConnection(
1269:                        webClient);
1270:                webConnection.setResponse(URL_FIRST, html, 302, "Some error",
1271:                        "text/html", headers);
1272:                webConnection.setResponse(new URL(location2),
1273:                        "<html><head><title>2nd page</title></head></html>");
1274:                webClient.setWebConnection(webConnection);
1275:
1276:                final Page page2 = webClient.getPage(URL_FIRST);
1277:                webClient.getPage(URL_FIRST);
1278:                assertEquals(null, webConnection.getLastWebRequestSettings()
1279:                        .getProxyHost());
1280:                assertEquals(0, webConnection.getLastWebRequestSettings()
1281:                        .getProxyPort());
1282:                assertEquals(location2, page2.getWebResponse().getUrl());
1283:
1284:                // Make sure default proxy settings are used.
1285:                webClient.setThrowExceptionOnFailingStatusCode(false);
1286:                webClient.setRedirectEnabled(false);
1287:                final Page page1 = webClient.getPage(URL_FIRST);
1288:                assertEquals(defaultProxyHost, webConnection
1289:                        .getLastWebRequestSettings().getProxyHost());
1290:                assertEquals(defaultProxyPort, webConnection
1291:                        .getLastWebRequestSettings().getProxyPort());
1292:                assertEquals(URL_FIRST, page1.getWebResponse().getUrl());
1293:            }
1294:
1295:            /**
1296:             * @throws Exception If the test fails.
1297:             */
1298:            public void testProxyConfigForJS() throws Exception {
1299:
1300:                final String defaultProxyHost = "defaultProxyHost";
1301:                final int defaultProxyPort = 777;
1302:                final String html = "<html><head><title>Hello World</title>\n"
1303:                        + "<script language='javascript' type='text/javascript' src='foo.js'></script>\n"
1304:                        + "</head><body></body></html>";
1305:                final WebClient webClient = new WebClient(
1306:                        BrowserVersion.INTERNET_EXPLORER_6_0, defaultProxyHost,
1307:                        defaultProxyPort);
1308:                final MockWebConnection webConnection = new MockWebConnection(
1309:                        webClient);
1310:                webConnection.setResponse(URL_FIRST, html);
1311:                webConnection.setResponse(new URL(URL_FIRST, "foo.js"), "",
1312:                        "text/javascript");
1313:                webClient.setWebConnection(webConnection);
1314:
1315:                // Make sure default proxy settings are used.
1316:                webClient.getPage(URL_FIRST);
1317:                assertEquals(defaultProxyHost, webConnection
1318:                        .getLastWebRequestSettings().getProxyHost());
1319:                assertEquals(defaultProxyPort, webConnection
1320:                        .getLastWebRequestSettings().getProxyPort());
1321:
1322:                // Make sure proxy bypass works with default proxy settings.
1323:                webClient.addHostsToProxyBypass(URL_FIRST.getHost());
1324:                webClient.getPage(URL_FIRST);
1325:                assertEquals(null, webConnection.getLastWebRequestSettings()
1326:                        .getProxyHost());
1327:                assertEquals(0, webConnection.getLastWebRequestSettings()
1328:                        .getProxyPort());
1329:
1330:                // Make sure we can remove proxy bypass filters.
1331:                webClient.removeHostsFromProxyBypass(URL_FIRST.getHost());
1332:                webClient.getPage(URL_FIRST);
1333:                assertEquals(defaultProxyHost, webConnection
1334:                        .getLastWebRequestSettings().getProxyHost());
1335:                assertEquals(defaultProxyPort, webConnection
1336:                        .getLastWebRequestSettings().getProxyPort());
1337:            }
1338:
1339:            /**
1340:             * Test {@link WebClient#expandUrl(URL,String)} for the case where an anchor name
1341:             * was specified.
1342:             * @throws Exception If the test fails.
1343:             */
1344:            public void testExpandUrl() throws Exception {
1345:                assertEquals("http://first#second", WebClient.expandUrl(
1346:                        URL_FIRST, "#second"));
1347:                assertEquals("http://first?a=1&b=2", WebClient.expandUrl(
1348:                        new URL("http://first?a=1&b=2"), ""));
1349:                assertEquals("http://first?b=2&c=3", WebClient.expandUrl(
1350:                        new URL("http://first?a=1&b=2"), "?b=2&c=3"));
1351:                assertEquals("file:/home/myself/test.js", WebClient.expandUrl(
1352:                        new URL("file:/home/myself/myTest.html"), "test.js"));
1353:            }
1354:
1355:            /**
1356:             * @throws Exception If the test fails.
1357:             */
1358:            public void testExpandUrlWithFile() throws Exception {
1359:                final String urlString = "http://host/page.html";
1360:                final URL url = new URL(urlString);
1361:                assertEquals(urlString + "#second", WebClient.expandUrl(url,
1362:                        "#second"));
1363:            }
1364:
1365:            /** Test the accessors for refreshHandler */
1366:            public void testRefreshHandlerAccessors() {
1367:                final WebClient webClient = new WebClient();
1368:                assertInstanceOf(webClient.getRefreshHandler(),
1369:                        ImmediateRefreshHandler.class);
1370:
1371:                final RefreshHandler handler = new ImmediateRefreshHandler() {
1372:                    private static final long serialVersionUID = 5357553245330318812L;
1373:                };
1374:                webClient.setRefreshHandler(handler);
1375:                assertSame(handler, webClient.getRefreshHandler());
1376:            }
1377:
1378:            /**
1379:             * Test the script preprocessor
1380:             * @throws IOException if the test fails
1381:             */
1382:            public void testScriptPreProcessor() throws IOException {
1383:                final WebClient client = new WebClient();
1384:                final MockWebConnection webConnection = new MockWebConnection(
1385:                        client);
1386:                final String alertText = "content";
1387:                final String newAlertText = "newcontent";
1388:                final String content = "<html><head><title>foo</title><script>\n"
1389:                        + "<!--\n   alert('"
1390:                        + alertText
1391:                        + "');\n// -->\n"
1392:                        + "</script></head><body>\n"
1393:                        + "<p>hello world</p>\n"
1394:                        + "<form name='form1'>\n"
1395:                        + "    <input type='text' name='textfield1' id='textfield1' value='foo' />\n"
1396:                        + "    <input type='text' name='textfield2' id='textfield2'/>\n"
1397:                        + "</form>\n" + "</body></html>";
1398:
1399:                webConnection.setDefaultResponse(content);
1400:                client.setWebConnection(webConnection);
1401:
1402:                // Test null return from pre processor
1403:                client.setScriptPreProcessor(new ScriptPreProcessor() {
1404:                    public String preProcess(final HtmlPage htmlPage,
1405:                            final String sourceCode, final String sourceName,
1406:                            final HtmlElement htmlElement) {
1407:                        return null;
1408:                    }
1409:                });
1410:                client.setAlertHandler(new AlertHandler() {
1411:                    public void handleAlert(final Page page,
1412:                            final String message) {
1413:                        fail("The pre processor did not remove the javascript");
1414:                    }
1415:
1416:                });
1417:                client.getPage("http://www.yahoo.com");
1418:
1419:                // Test modify script in pre processor
1420:                client.setScriptPreProcessor(new ScriptPreProcessor() {
1421:                    public String preProcess(final HtmlPage htmlPage,
1422:                            final String sourceCode, final String sourceName,
1423:                            final HtmlElement htmlElement) {
1424:                        final int start = sourceCode.indexOf(alertText);
1425:                        final int end = start + alertText.length();
1426:
1427:                        return sourceCode.substring(0, start) + newAlertText
1428:                                + sourceCode.substring(end);
1429:                    }
1430:                });
1431:                client.setAlertHandler(new AlertHandler() {
1432:                    public void handleAlert(final Page page,
1433:                            final String message) {
1434:                        if (!message.equals(newAlertText)) {
1435:                            fail("The pre processor did not modify the javascript");
1436:                        }
1437:                    }
1438:
1439:                });
1440:                client.getPage("http://www.yahoo.com");
1441:            }
1442:
1443:            /**
1444:             * Test the ScriptPreProcessor's ability to filter out a javascript method
1445:             * that is not implemented without affecting the rest of the page.
1446:             *
1447:             * @throws Exception if the test fails
1448:             */
1449:            public void testScriptPreProcessor_UnimplementedJavascript()
1450:                    throws Exception {
1451:
1452:                final WebClient client = new WebClient();
1453:                final MockWebConnection webConnection = new MockWebConnection(
1454:                        client);
1455:                final String content = "<html><head><title>foo</title></head><body>\n"
1456:                        + "<p>hello world</p>\n"
1457:                        + "<script>document.unimplementedFunction();</script>\n"
1458:                        + "<script>alert('implemented function');</script>\n"
1459:                        + "</body></html>";
1460:
1461:                webConnection.setDefaultResponse(content);
1462:                client.setWebConnection(webConnection);
1463:
1464:                client.setScriptPreProcessor(new ScriptPreProcessor() {
1465:                    public String preProcess(final HtmlPage htmlPage,
1466:                            final String sourceCode, final String sourceName,
1467:                            final HtmlElement htmlElement) {
1468:                        if (sourceCode.indexOf("unimplementedFunction") > -1) {
1469:                            return "";
1470:                        }
1471:                        return sourceCode;
1472:                    }
1473:                });
1474:                final List alerts = new ArrayList();
1475:                client.setAlertHandler(new CollectingAlertHandler(alerts));
1476:                client.getPage("http://page");
1477:
1478:                assertEquals(1, alerts.size());
1479:                assertEquals("implemented function", alerts.get(0).toString());
1480:            }
1481:
1482:            /**
1483:             * Apparently if the browsers receive a charset that they don't understand, they ignore
1484:             * it and assume ISO-8895-1.  Ensure we do the same.
1485:             * @throws Exception If the test fails.
1486:             */
1487:            public void testBadCharset() throws Exception {
1488:                final String page1Content = "<html><head><title>foo</title>\n"
1489:                        + "</head><body></body></html>";
1490:                final WebClient client = new WebClient();
1491:
1492:                final MockWebConnection webConnection = new MockWebConnection(
1493:                        client);
1494:                webConnection.setResponse(URL_FIRST, page1Content,
1495:                        "text/html; charset=garbage");
1496:
1497:                client.setWebConnection(webConnection);
1498:
1499:                final Page page = client.getPage(URL_FIRST);
1500:                assertInstanceOf(page, HtmlPage.class);
1501:            }
1502:
1503:            /**
1504:             * Colons are legal in the path of a url but {@link WebClient#expandUrl(URL,String)} was
1505:             * blowing up on this case.  Ensure it's fixed.
1506:             * @throws Exception If the test fails.
1507:             */
1508:            public void testExpandUrlHandlesColonsInRelativeUrl()
1509:                    throws Exception {
1510:                final URL newUrl = WebClient.expandUrl(new URL(
1511:                        "http://host/foo"), "/bar/blah:de:blah");
1512:                assertEquals("http://host/bar/blah:de:blah", newUrl);
1513:            }
1514:
1515:            /**
1516:             * Test reuse of a single {@link HtmlPage} object to submit the same form multiple times.
1517:             *
1518:             * @throws Exception if test fails
1519:             */
1520:            public void testReusingHtmlPageToSubmitFormMultipleTimes()
1521:                    throws Exception {
1522:
1523:                final String firstContent = "<html><head><title>First</title></head>\n"
1524:                        + "<body onload='document.myform.mysubmit.focus()'>\n"
1525:                        + "<form action='"
1526:                        + URL_SECOND
1527:                        + "' name='myform'>\n"
1528:                        + "<input type='submit' name='mysubmit'>\n"
1529:                        + "</form></body></html>";
1530:                final String secondContent = "<html><head><title>Second</title></head><body>Second</body></html>";
1531:
1532:                final WebClient webClient = new WebClient();
1533:
1534:                final MockWebConnection webConnection = new MockWebConnection(
1535:                        webClient);
1536:                webConnection.setResponse(URL_FIRST, firstContent);
1537:                webConnection.setDefaultResponse(secondContent);
1538:
1539:                webClient.setWebConnection(webConnection);
1540:
1541:                final HtmlPage page = (HtmlPage) webClient.getPage(URL_FIRST);
1542:                for (int i = 0; i < 100; i++) {
1543:                    page.getFormByName("myform").submit(
1544:                            (SubmittableElement) null);
1545:                }
1546:            }
1547:
1548:            /**
1549:             * Test the value of window.opener when a link has target="_top"
1550:             * @throws Exception if test fails
1551:             */
1552:            public void testOpenerInFrameset() throws Exception {
1553:
1554:                final String firstContent = "<html><head><script>alert(window.opener)</script><frameset cols='*'>\n"
1555:                        + "<frame src='"
1556:                        + URL_SECOND
1557:                        + "'>\n"
1558:                        + "</frameset>\n" + "</html>";
1559:                final String secondContent = "<html><body><a href='"
1560:                        + URL_FIRST
1561:                        + "' target='_top'>to top</a></body></html>";
1562:
1563:                final WebClient webClient = new WebClient();
1564:
1565:                final MockWebConnection webConnection = new MockWebConnection(
1566:                        webClient);
1567:                webConnection.setResponse(URL_FIRST, firstContent);
1568:                webConnection.setResponse(URL_SECOND, secondContent);
1569:                webClient.setWebConnection(webConnection);
1570:
1571:                final List collectedAlerts = new ArrayList();
1572:                webClient.setAlertHandler(new CollectingAlertHandler(
1573:                        collectedAlerts));
1574:
1575:                final HtmlPage page = (HtmlPage) webClient.getPage(URL_FIRST);
1576:                final HtmlPage pageInFrame = (HtmlPage) ((WebWindow) page
1577:                        .getFrames().get(0)).getEnclosedPage();
1578:                ((HtmlAnchor) pageInFrame.getAnchors().get(0)).click();
1579:
1580:                final String[] expectedAlerts = { "null", "null" };
1581:                assertEquals(expectedAlerts, collectedAlerts);
1582:            }
1583:
1584:            /**
1585:             * Test setting the NekoHTML logging and parsing flags
1586:             *
1587:             * @throws Exception if test fails
1588:             */
1589:            public void testNekoFlagSetters() throws Exception {
1590:                assertEquals("Default ignore content is wrong", false,
1591:                        WebClient.getIgnoreOutsideContent());
1592:                WebClient.setIgnoreOutsideContent(true);
1593:                assertTrue("Ignore content did not get set", WebClient
1594:                        .getIgnoreOutsideContent());
1595:            }
1596:
1597:            /**
1598:             * Unset the static items set in tests here
1599:             * @throws Exception if superclass throws
1600:             */
1601:            protected void tearDown() throws Exception {
1602:                super .tearDown();
1603:                WebClient.setIgnoreOutsideContent(false);
1604:            }
1605:
1606:            /**
1607:             *
1608:             * @throws Exception if an error occurs
1609:             */
1610:            public void testGuessContentType() throws Exception {
1611:                final WebClient webClient = new WebClient();
1612:
1613:                // test real files with bad file suffix
1614:                assertEquals("tiny-png.img", "image/png", webClient
1615:                        .guessContentType(getTestFile("tiny-png.img")));
1616:                assertEquals("tiny-jpg.img", "image/jpeg", webClient
1617:                        .guessContentType(getTestFile("tiny-jpg.img")));
1618:                assertEquals("tiny-gif.img", "image/gif", webClient
1619:                        .guessContentType(getTestFile("tiny-gif.img")));
1620:
1621:                // tests empty files, type should be determined from file suffix
1622:                assertEquals("empty.png", "image/png", webClient
1623:                        .guessContentType(getTestFile("empty.png")));
1624:                assertEquals("empty.jpg", "image/jpeg", webClient
1625:                        .guessContentType(getTestFile("empty.jpg")));
1626:                assertEquals("empty.gif", "image/gif", webClient
1627:                        .guessContentType(getTestFile("empty.gif")));
1628:                assertEquals("empty.js", "text/javascript", webClient
1629:                        .guessContentType(getTestFile("empty.js")));
1630:            }
1631:
1632:            /**
1633:             * Test that no encoding disturb file reads from filesystem.
1634:             * For instance this test failed under Linux with LANG=de_DE.UTF-8 or LANG=C
1635:             * but worked for LANG=de_DE.ISO-8859-1
1636:             * @throws Exception if the test fails.
1637:             */
1638:            public void testBinaryFileFromFileSystem() throws Exception {
1639:                final String testfileName = "tiny-jpg.img";
1640:                final File testfile = getTestFile(testfileName);
1641:                final byte[] directBytes = IOUtils
1642:                        .toByteArray(new FileInputStream(testfile));
1643:                final String directStr = hexRepresentation(directBytes);
1644:                final WebClient client = new WebClient();
1645:                final Page testpage = client.getPage(testfile.toURI().toURL());
1646:                final byte[] webclientBytes = IOUtils.toByteArray(testpage
1647:                        .getWebResponse().getContentAsStream());
1648:                final String webclientStr = hexRepresentation(webclientBytes);
1649:                assertEquals(directStr, webclientStr);
1650:            }
1651:
1652:            /**
1653:             * Helper to make hex diff human easier to read for human eyes
1654:             * @param digest the bytes
1655:             * @return the hex representation
1656:             */
1657:            private static String hexRepresentation(final byte[] digest) {
1658:                final StringBuffer hexString = new StringBuffer();
1659:                for (int i = 0; i < digest.length; i++) {
1660:                    final byte b = digest[i];
1661:                    hexString.append(Integer.toHexString(0xFF & b));
1662:                    hexString.append(" ");
1663:                }
1664:                return hexString.toString().trim();
1665:            }
1666:
1667:            /**
1668:             * Gets the file located in testfiles from the file name
1669:             * @param fileName the file name
1670:             * @return the file
1671:             * @throws Exception if a pb occurs
1672:             */
1673:            private File getTestFile(final String fileName) throws Exception {
1674:                final URL url = getClass().getClassLoader().getResource(
1675:                        "testfiles/" + fileName);
1676:                if (url == null) {
1677:                    throw new FileNotFoundException(fileName);
1678:                }
1679:                final File file = new File(new URI(url.toString()));
1680:
1681:                return file;
1682:            }
1683:
1684:            /**
1685:             * Test that additional header are correctly transmitted to the web connection.
1686:             * @throws Exception If something goes wrong.
1687:             */
1688:            public void testRequestHeader() throws Exception {
1689:                final String content = "<html></html>";
1690:                final WebClient client = new WebClient();
1691:
1692:                final MockWebConnection webConnection = new MockWebConnection(
1693:                        client);
1694:                webConnection.setDefaultResponse(content);
1695:                client.setWebConnection(webConnection);
1696:
1697:                client.getPage(URL_FIRST);
1698:                assertNull(webConnection.getLastAdditionalHeaders().get(
1699:                        "foo-header"));
1700:
1701:                client.addRequestHeader("foo-header", "foo value");
1702:                client.getPage(URL_FIRST);
1703:                assertEquals("foo value", webConnection
1704:                        .getLastAdditionalHeaders().get("foo-header"));
1705:
1706:                client.removeRequestHeader("foo-header");
1707:                client.getPage(URL_FIRST);
1708:                assertNull(webConnection.getLastAdditionalHeaders().get(
1709:                        "foo-header"));
1710:            }
1711:
1712:            /**
1713:             * Test that content type is looked in a case insensitive way.
1714:             * Cf <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>:
1715:             * "All media type values, subtype values, and parameter names as defined
1716:             * are case-insensitive".
1717:             * @throws Exception If something goes wrong.
1718:             */
1719:            public void testContentTypeCaseInsensitive() throws Exception {
1720:                final String content = "<html><head>\n"
1721:                        + "<script type='Text/Javascript' src='foo.js'></script>\n"
1722:                        + "</head></html>";
1723:                final WebClient client = new WebClient();
1724:
1725:                final MockWebConnection webConnection = new MockWebConnection(
1726:                        client);
1727:                webConnection.setDefaultResponse("alert('foo')", 200, "OK",
1728:                        "Text/Javascript");
1729:                client.setWebConnection(webConnection);
1730:
1731:                final List collectedAlerts = new ArrayList();
1732:                client.setAlertHandler(new CollectingAlertHandler(
1733:                        collectedAlerts));
1734:                final String[] expectedAlerts = { "foo" };
1735:
1736:                webConnection.setResponse(URL_FIRST, content, "Text/Html");
1737:                assertInstanceOf(client.getPage(URL_FIRST), HtmlPage.class);
1738:                assertEquals(expectedAlerts, collectedAlerts);
1739:
1740:                webConnection.setResponse(URL_FIRST, content, "Text/XHtml");
1741:                collectedAlerts.clear();
1742:                assertInstanceOf(client.getPage(URL_FIRST), HtmlPage.class);
1743:                assertEquals(expectedAlerts, collectedAlerts);
1744:
1745:                webConnection.setResponse(URL_FIRST, content, "Text/Xml");
1746:                assertInstanceOf(client.getPage(URL_FIRST), XmlPage.class);
1747:                webConnection
1748:                        .setResponse(URL_FIRST, content, "ApplicaTion/Xml");
1749:                assertInstanceOf(client.getPage(URL_FIRST), XmlPage.class);
1750:
1751:                webConnection.setResponse(URL_FIRST, content, "Text/Plain");
1752:                assertInstanceOf(client.getPage(URL_FIRST), TextPage.class);
1753:
1754:                webConnection.setResponse(URL_FIRST, "", "Text/JavaScript");
1755:                assertInstanceOf(client.getPage(URL_FIRST),
1756:                        JavaScriptPage.class);
1757:            }
1758:
1759:            /**
1760:             * Load a javascript function from an external file using src references
1761:             * inside a script element.
1762:             *
1763:             * @throws Exception if the test fails
1764:             */
1765:            public void testLoadFilePageWithExternalJS() throws Exception {
1766:                final File currentDirectory = new File((new File(""))
1767:                        .getAbsolutePath());
1768:
1769:                final String encoding = (new OutputStreamWriter(
1770:                        new ByteArrayOutputStream())).getEncoding();
1771:
1772:                // javascript file
1773:                final File tmpFileJS = File.createTempFile("test", ".js",
1774:                        currentDirectory);
1775:                tmpFileJS.deleteOnExit();
1776:                FileUtils
1777:                        .writeStringToFile(tmpFileJS, "alert('foo')", encoding);
1778:
1779:                // html file
1780:                final String html = "<html><head></head><body>\n"
1781:                        + "<script language='javascript' type='text/javascript' src='"
1782:                        + tmpFileJS.getName() + "'></script>\n"
1783:                        + "</body></html>";
1784:                final File tmpFile = File.createTempFile("test", ".html",
1785:                        currentDirectory);
1786:                tmpFile.deleteOnExit();
1787:                FileUtils.writeStringToFile(tmpFile, html, encoding);
1788:
1789:                final URL fileURL = new URL("file://"
1790:                        + tmpFile.getCanonicalPath());
1791:                final WebClient webClient = new WebClient();
1792:                final List collectedAlerts = new ArrayList();
1793:                webClient.setAlertHandler(new CollectingAlertHandler(
1794:                        collectedAlerts));
1795:                webClient.getPage(fileURL);
1796:
1797:                final String[] expectedAlerts = { "foo" };
1798:                assertEquals(expectedAlerts, collectedAlerts);
1799:            }
1800:
1801:            /**
1802:             * Test that WebClient.getPage(String) calls WebClient.getPage(URL) with the right URL
1803:             * @throws Exception if the test fails
1804:             */
1805:            public void testGetPageWithStringArg() throws Exception {
1806:                final URL[] calledUrls = { null };
1807:                final WebClient wc = new WebClient() {
1808:                    private static final long serialVersionUID = -8065766721260679248L;
1809:
1810:                    public Page getPage(final URL url) throws IOException,
1811:                            FailingHttpStatusCodeException {
1812:                        calledUrls[0] = url;
1813:                        return null;
1814:                    }
1815:                };
1816:
1817:                wc.getPage(URL_GARGOYLE.toExternalForm());
1818:                assertEquals(URL_GARGOYLE, calledUrls[0]);
1819:            }
1820:
1821:            /**
1822:             * Verifies that {@link WebClient#getPage(WebWindow, WebRequestSettings)} calls OnBeforeUnload
1823:             * on the specified window's page, not on the client's "current" page.
1824:             * @throws Exception if an error occurs
1825:             */
1826:            public void testOnBeforeUnloadCalledOnCorrectPage()
1827:                    throws Exception {
1828:                final String html = "<html><body onbeforeunload='alert(7)'><iframe></iframe></body></html>";
1829:                final List alerts = new ArrayList();
1830:                loadPage(html, alerts);
1831:                assertTrue(alerts.isEmpty());
1832:            }
1833:
1834:            /**
1835:             * Test that '+' is not encoded in urls
1836:             * @throws Exception if the test fails
1837:             */
1838:            public void testPlusNotEncodedInUrl() throws Exception {
1839:                final URL url = new URL("http://host/search/my+category/");
1840:
1841:                final HtmlPage page = loadPage("<html></html>",
1842:                        new ArrayList(), url);
1843:                assertEquals("http://host/search/my+category/", page
1844:                        .getWebResponse().getUrl());
1845:            }
1846:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.