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.protocol.javascript;
16  
17  import java.io.InputStream;
18  import java.net.URL;
19  import java.net.URLConnection;
20  import java.nio.charset.StandardCharsets;
21  
22  import org.apache.commons.io.IOUtils;
23  
24  /**
25   * A URLConnection for supporting JavaScript URLs.
26   *
27   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
28   */
29  public class JavaScriptURLConnection extends URLConnection {
30  
31      /** The JavaScript "URL" prefix. */
32      public static final String JAVASCRIPT_PREFIX = "javascript:";
33  
34      /** The JavaScript code. */
35      private final String content_;
36  
37      /**
38       * Creates an instance.
39       * @param newUrl the JavaScript URL
40       */
41      public JavaScriptURLConnection(final URL newUrl) {
42          super(newUrl);
43          content_ = newUrl.toExternalForm().substring(JAVASCRIPT_PREFIX.length());
44      }
45  
46      /**
47       * This method does nothing in this implementation but is required to be implemented.
48       */
49      @Override
50      public void connect() {
51          // Empty.
52      }
53  
54      /**
55       * Returns the input stream - in this case the content of the URL.
56       * @return the input stream
57       */
58      @Override
59      public InputStream getInputStream() {
60          return IOUtils.toInputStream(content_, StandardCharsets.ISO_8859_1);
61      }
62  
63  }