View Javadoc
1   /*
2    * Copyright (c) 2002-2026 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 Mike Bowler
28   * @author Ronald Brill
29   */
30  public class JavaScriptURLConnection extends URLConnection {
31  
32      /** The JavaScript "URL" prefix. */
33      public static final String JAVASCRIPT_PREFIX = "javascript:";
34  
35      /** The JavaScript code. */
36      private final String content_;
37  
38      /**
39       * Creates an instance.
40       * @param newUrl the JavaScript URL
41       */
42      public JavaScriptURLConnection(final URL newUrl) {
43          super(newUrl);
44          content_ = newUrl.toExternalForm().substring(JAVASCRIPT_PREFIX.length());
45      }
46  
47      /**
48       * This method does nothing in this implementation but is required to be implemented.
49       */
50      @Override
51      public void connect() {
52          // Empty.
53      }
54  
55      /**
56       * Returns the input stream - in this case the content of the URL.
57       * @return the input stream
58       */
59      @Override
60      public InputStream getInputStream() {
61          return IOUtils.toInputStream(content_, StandardCharsets.ISO_8859_1);
62      }
63  
64  }