View Javadoc
1   /*
2    * Copyright (c) 2002-2025 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit.html;
16  
17  import java.io.File;
18  import java.io.FilenameFilter;
19  import java.io.IOException;
20  import java.io.Writer;
21  import java.util.Enumeration;
22  import java.util.HashMap;
23  import java.util.Map;
24  
25  import javax.servlet.Servlet;
26  import javax.servlet.http.HttpServlet;
27  import javax.servlet.http.HttpServletRequest;
28  import javax.servlet.http.HttpServletResponse;
29  
30  import org.htmlunit.CollectingAlertHandler;
31  import org.htmlunit.WebClient;
32  import org.htmlunit.WebServerTestCase;
33  import org.htmlunit.junit.BrowserRunner;
34  import org.htmlunit.junit.annotation.Alerts;
35  import org.htmlunit.util.MimeType;
36  import org.htmlunit.util.ServletContentWrapper;
37  import org.junit.Test;
38  import org.junit.runner.RunWith;
39  
40  /**
41   * Tests for {@link HtmlPage}.
42   *
43   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
44   * @author Noboru Sinohara
45   * @author David K. Taylor
46   * @author Andreas Hangler
47   * @author <a href="mailto:cse@dynabean.de">Christian Sell</a>
48   * @author Marc Guillemot
49   * @author Ahmed Ashour
50   * @author Ronald Brill
51   */
52  @RunWith(BrowserRunner.class)
53  public class HtmlPage4Test extends WebServerTestCase {
54  
55      /**
56       * @exception Exception If the test fails
57       */
58      @Test
59      public void refresh() throws Exception {
60          final Map<String, Class<? extends Servlet>> map = new HashMap<>();
61          map.put("/one.html", RefreshServlet.class);
62          map.put("/two.html", RefreshServlet.class);
63          startWebServer(".", null, map);
64          final WebClient client = getWebClient();
65          final HtmlPage page = client.getPage(URL_FIRST + "one.html");
66          final HtmlSubmitInput submit = page.getHtmlElementById("myButton");
67          final HtmlPage secondPage = submit.click();
68          assertEquals("0\nPOST\nsome_name some_value\n", secondPage.getWebResponse().getContentAsString());
69          final HtmlPage secondPage2 = (HtmlPage) secondPage.refresh();
70          assertEquals("1\nPOST\nsome_name some_value\n", secondPage2.getWebResponse().getContentAsString());
71      }
72  
73      /**
74       * Refresh servlet.
75       */
76      public static class RefreshServlet extends HttpServlet {
77  
78          private int counter_;
79  
80          /**
81           * {@inheritDoc}
82           */
83          @Override
84          protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
85              final Writer writer = resp.getWriter();
86              resp.setContentType(MimeType.TEXT_HTML);
87              final String response = DOCTYPE_HTML
88                      + "<html>\n"
89                      + "<body>\n"
90                      + "  <form action='two.html' method='post'>\n"
91                      + "  <input type='hidden' name='some_name' value='some_value'>\n"
92                      + "  <input id='myButton' type='submit'>\n"
93                      + "  </form>\n"
94                      + "</body>\n"
95                      + "</html>";
96              writer.write(response);
97          }
98  
99          /**
100          * {@inheritDoc}
101          */
102         @Override
103         protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
104             resp.setContentType(MimeType.TEXT_HTML);
105             final StringBuilder builder = new StringBuilder();
106             builder.append(counter_++).append("\n");
107             builder.append(req.getMethod()).append("\n");
108             for (final Enumeration<?> en = req.getParameterNames(); en.hasMoreElements();) {
109                 final String name = (String) en.nextElement();
110                 final String value = req.getParameter(name);
111                 builder.append(name).append(' ').append(value).append('\n');
112             }
113             resp.getWriter().write(builder.toString());
114         }
115     }
116 
117     /**
118      * @exception Exception if an error occurs
119      */
120     @Test
121     @Alerts("hello")
122     public void bigJavaScript() throws Exception {
123         final StringBuilder html = new StringBuilder(DOCTYPE_HTML
124                 + "<html><head>\n"
125                 + "<script src='two.js'></script>\n"
126                 + "<link rel='stylesheet' type='text/css' href='three.css'/>\n"
127                 + "</head>\n"
128                 + "<body onload='test()'></body></html>");
129 
130         final StringBuilder javaScript = new StringBuilder("function test() {\n"
131                 + "alert('hello');\n"
132                 + "}");
133 
134         final StringBuilder css = new StringBuilder("body {color: blue}");
135 
136         final long maxInMemory = getWebClient().getOptions().getMaxInMemory();
137 
138         for (int i = 0; i < maxInMemory; i++) {
139             html.append(' ');
140             javaScript.append(' ');
141             css.append(' ');
142         }
143 
144         BigJavaScriptServlet1.CONTENT_ = html.toString();
145         BigJavaScriptServlet2.CONTENT_ = javaScript.toString();
146         BigJavaScriptServlet3.CONTENT_ = css.toString();
147 
148         final int initialTempFiles = getTempFiles();
149         final Map<String, Class<? extends Servlet>> map = new HashMap<>();
150         map.put("/one.html", BigJavaScriptServlet1.class);
151         map.put("/two.js", BigJavaScriptServlet2.class);
152         map.put("/three.css", BigJavaScriptServlet3.class);
153         startWebServer(".", null, map);
154         try (WebClient client = getWebClient()) {
155             final CollectingAlertHandler alertHandler = new CollectingAlertHandler();
156             client.setAlertHandler(alertHandler);
157             final HtmlPage page = client.getPage(URL_FIRST + "one.html");
158             page.getEnclosingWindow().getComputedStyle(page.getBody(), null);
159 
160             assertEquals(getExpectedAlerts(), alertHandler.getCollectedAlerts());
161             assertEquals(initialTempFiles + 1, getTempFiles());
162         }
163         assertEquals(initialTempFiles, getTempFiles());
164     }
165 
166     /**
167      *  The HTML servlet for {@link #bigJavaScript()}.
168      */
169     public static class BigJavaScriptServlet1 extends ServletContentWrapper {
170         private static String CONTENT_;
171         /** The constructor. */
172         public BigJavaScriptServlet1() {
173             super(CONTENT_);
174         }
175     }
176 
177     /**
178      *  The JavaScript servlet for {@link #bigJavaScript()}.
179      */
180     public static class BigJavaScriptServlet2 extends ServletContentWrapper {
181         private static String CONTENT_;
182         /** The constructor. */
183         public BigJavaScriptServlet2() {
184             super(CONTENT_);
185         }
186     }
187 
188     /**
189      *  The CSS servlet for {@link #bigJavaScript()}.
190      */
191     public static class BigJavaScriptServlet3 extends ServletContentWrapper {
192         private static String CONTENT_;
193         /** The constructor. */
194         public BigJavaScriptServlet3() {
195             super(CONTENT_);
196         }
197     }
198 
199     private static int getTempFiles() {
200         final File file = new File(System.getProperty("java.io.tmpdir"));
201         final String[] list = file.list(new FilenameFilter() {
202             @Override
203             public boolean accept(final File dir, final String name) {
204                 return name.startsWith("htmlunit");
205             }
206         });
207         if (list == null) {
208             return 0;
209         }
210         return list.length;
211     }
212 }