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.annotation.Alerts;
34  import org.htmlunit.util.MimeType;
35  import org.htmlunit.util.ServletContentWrapper;
36  import org.junit.jupiter.api.Test;
37  
38  /**
39   * Tests for {@link HtmlPage}.
40   *
41   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
42   * @author Noboru Sinohara
43   * @author David K. Taylor
44   * @author Andreas Hangler
45   * @author <a href="mailto:cse@dynabean.de">Christian Sell</a>
46   * @author Marc Guillemot
47   * @author Ahmed Ashour
48   * @author Ronald Brill
49   */
50  public class HtmlPage4Test extends WebServerTestCase {
51  
52      /**
53       * @exception Exception If the test fails
54       */
55      @Test
56      public void refresh() throws Exception {
57          final Map<String, Class<? extends Servlet>> map = new HashMap<>();
58          map.put("/one.html", RefreshServlet.class);
59          map.put("/two.html", RefreshServlet.class);
60          startWebServer(".", null, map);
61          final WebClient client = getWebClient();
62          final HtmlPage page = client.getPage(URL_FIRST + "one.html");
63          final HtmlSubmitInput submit = page.getHtmlElementById("myButton");
64          final HtmlPage secondPage = submit.click();
65          assertEquals("0\nPOST\nsome_name some_value\n", secondPage.getWebResponse().getContentAsString());
66          final HtmlPage secondPage2 = (HtmlPage) secondPage.refresh();
67          assertEquals("1\nPOST\nsome_name some_value\n", secondPage2.getWebResponse().getContentAsString());
68      }
69  
70      /**
71       * Refresh servlet.
72       */
73      public static class RefreshServlet extends HttpServlet {
74  
75          private int counter_;
76  
77          /**
78           * {@inheritDoc}
79           */
80          @Override
81          protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
82              final Writer writer = resp.getWriter();
83              resp.setContentType(MimeType.TEXT_HTML);
84              final String response = DOCTYPE_HTML
85                      + "<html>\n"
86                      + "<body>\n"
87                      + "  <form action='two.html' method='post'>\n"
88                      + "  <input type='hidden' name='some_name' value='some_value'>\n"
89                      + "  <input id='myButton' type='submit'>\n"
90                      + "  </form>\n"
91                      + "</body>\n"
92                      + "</html>";
93              writer.write(response);
94          }
95  
96          /**
97           * {@inheritDoc}
98           */
99          @Override
100         protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
101             resp.setContentType(MimeType.TEXT_HTML);
102             final StringBuilder builder = new StringBuilder();
103             builder.append(counter_++).append("\n");
104             builder.append(req.getMethod()).append("\n");
105             for (final Enumeration<?> en = req.getParameterNames(); en.hasMoreElements();) {
106                 final String name = (String) en.nextElement();
107                 final String value = req.getParameter(name);
108                 builder.append(name).append(' ').append(value).append('\n');
109             }
110             resp.getWriter().write(builder.toString());
111         }
112     }
113 
114     /**
115      * @exception Exception if an error occurs
116      */
117     @Test
118     @Alerts("hello")
119     public void bigJavaScript() throws Exception {
120         final StringBuilder html = new StringBuilder(DOCTYPE_HTML
121                 + "<html><head>\n"
122                 + "<script src='two.js'></script>\n"
123                 + "<link rel='stylesheet' type='text/css' href='three.css'/>\n"
124                 + "</head>\n"
125                 + "<body onload='test()'></body></html>");
126 
127         final StringBuilder javaScript = new StringBuilder("function test() {\n"
128                 + "alert('hello');\n"
129                 + "}");
130 
131         final StringBuilder css = new StringBuilder("body {color: blue}");
132 
133         final long maxInMemory = getWebClient().getOptions().getMaxInMemory();
134 
135         for (int i = 0; i < maxInMemory; i++) {
136             html.append(' ');
137             javaScript.append(' ');
138             css.append(' ');
139         }
140 
141         BigJavaScriptServlet1.CONTENT_ = html.toString();
142         BigJavaScriptServlet2.CONTENT_ = javaScript.toString();
143         BigJavaScriptServlet3.CONTENT_ = css.toString();
144 
145         final int initialTempFiles = getTempFiles();
146         final Map<String, Class<? extends Servlet>> map = new HashMap<>();
147         map.put("/one.html", BigJavaScriptServlet1.class);
148         map.put("/two.js", BigJavaScriptServlet2.class);
149         map.put("/three.css", BigJavaScriptServlet3.class);
150         startWebServer(".", null, map);
151         try (WebClient client = getWebClient()) {
152             final CollectingAlertHandler alertHandler = new CollectingAlertHandler();
153             client.setAlertHandler(alertHandler);
154             final HtmlPage page = client.getPage(URL_FIRST + "one.html");
155             page.getEnclosingWindow().getComputedStyle(page.getBody(), null);
156 
157             assertEquals(getExpectedAlerts(), alertHandler.getCollectedAlerts());
158             assertEquals(initialTempFiles + 1, getTempFiles());
159         }
160         assertEquals(initialTempFiles, getTempFiles());
161     }
162 
163     /**
164      *  The HTML servlet for {@link #bigJavaScript()}.
165      */
166     public static class BigJavaScriptServlet1 extends ServletContentWrapper {
167         private static String CONTENT_;
168         /** The constructor. */
169         public BigJavaScriptServlet1() {
170             super(CONTENT_);
171         }
172     }
173 
174     /**
175      *  The JavaScript servlet for {@link #bigJavaScript()}.
176      */
177     public static class BigJavaScriptServlet2 extends ServletContentWrapper {
178         private static String CONTENT_;
179         /** The constructor. */
180         public BigJavaScriptServlet2() {
181             super(CONTENT_);
182         }
183     }
184 
185     /**
186      *  The CSS servlet for {@link #bigJavaScript()}.
187      */
188     public static class BigJavaScriptServlet3 extends ServletContentWrapper {
189         private static String CONTENT_;
190         /** The constructor. */
191         public BigJavaScriptServlet3() {
192             super(CONTENT_);
193         }
194     }
195 
196     private static int getTempFiles() {
197         final File file = new File(System.getProperty("java.io.tmpdir"));
198         final String[] list = file.list(new FilenameFilter() {
199             @Override
200             public boolean accept(final File dir, final String name) {
201                 return name.startsWith("htmlunit");
202             }
203         });
204         if (list == null) {
205             return 0;
206         }
207         return list.length;
208     }
209 }