File: bug7165725.java

package info (click to toggle)
openjdk-21 21.0.8%2B9-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 823,976 kB
  • sloc: java: 5,613,338; xml: 1,643,607; cpp: 1,296,296; ansic: 420,291; asm: 404,850; objc: 20,994; sh: 15,271; javascript: 11,245; python: 6,895; makefile: 2,362; perl: 357; awk: 351; sed: 172; jsp: 24; csh: 3
file content (307 lines) | stat: -rw-r--r-- 12,663 bytes parent folder | download | duplicates (17)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
/*
 * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/*
 * @test
 * @key headful
 * @bug 7165725
 * @summary  Tests if HTML parser can handle successive script tags in a line
 *           and it does not call false text callback after script tags.
 * @run main bug7165725
 */

import java.awt.BorderLayout;
import java.awt.Robot;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.*;
import javax.swing.text.AbstractDocument.AbstractElement;
import javax.swing.text.AbstractDocument;
import javax.swing.text.Document;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;

public class bug7165725 extends JFrame {
    private static class GoldenElement {

        private String goldenName;
        private List<GoldenElement> goldenChildren;

        GoldenElement(String goldenName, GoldenElement... goldenChildren){
            this.goldenName = goldenName;
            if (goldenChildren != null) {
                this.goldenChildren = Arrays.asList(goldenChildren);
            } else {
                this.goldenChildren = new ArrayList<>();
            }
        }

        // throws RuntimeException if not ok
        public void checkStructureEquivalence(AbstractDocument.AbstractElement elem) {
            String name = elem.getName();
            if (!goldenName.equals(name)) {
                throw new RuntimeException("Bad structure: expected element name is '" + goldenName + "' but the actual name was '" + name + "'.");
            }
            int goldenChildCount = goldenChildren.size();
            int childCount = elem.getChildCount();
            if (childCount != goldenChildCount) {
                System.out.print("D: children: ");
                for (int i = 0; i < childCount; i++) {
                    System.out.print(" " + elem.getElement(i).getName());
                }
                System.out.println("");
                System.out.print("D: goldenChildren: ");
                for (GoldenElement ge : goldenChildren) {
                    System.out.print(" " + ge.goldenName);
                }
                System.out.println("");

                throw new RuntimeException("Bad structure: expected child count of element '" + goldenName + "' is '" + goldenChildCount + "' but the actual count was '" + childCount + "'.");
            }
            for (int i = 0; i < childCount; i++) {
                AbstractDocument.AbstractElement nextElem = (AbstractDocument.AbstractElement) elem.getElement(i);
                GoldenElement goldenElement = goldenChildren.get(i);
                goldenElement.checkStructureEquivalence(nextElem);
            }
        }
    }

    private JEditorPane editorPane;
    public void execute(final String urlStr, final GoldenElement goldenElement) throws Exception {
        System.out.println();
        System.out.println("***** TEST: " + urlStr + " *****");
        System.out.println();

        SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
                try {
                    editorPane = new JEditorPane();
                    editorPane.setEditorKit(new HTMLEditorKit() {
                        public Document createDefaultDocument() {
                            AbstractDocument doc =
                                    (AbstractDocument) super.createDefaultDocument();
                            doc.setAsynchronousLoadPriority(-1);
                            return doc;
                        }
                    });
                    editorPane.setPage(new URL(urlStr));
                } catch (IOException ex) {
                    throw new RuntimeException("Test failed", ex);
                }
                editorPane.setEditable(false);
                JScrollPane scroller = new JScrollPane();
                JViewport vp = scroller.getViewport();
                vp.add(editorPane);
                add(scroller, BorderLayout.CENTER);
                setDefaultCloseOperation(EXIT_ON_CLOSE);
                setSize(400, 400);
                setLocationRelativeTo(null);
                setVisible(true);
            }
        });

        Robot robot = new Robot();
        robot.waitForIdle();

        SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
                HTMLDocument doc = (HTMLDocument) editorPane.getDocument();
                doc.dump(System.out);
                goldenElement.checkStructureEquivalence((AbstractElement) doc.getDefaultRootElement());
                dispose();
            }
        });

        System.out.println();
        System.out.println("*********************************");
        System.out.println();
    }

    public static void main(String[] args) throws Exception {

        String dirURL = getDirURL();

        System.out.println("dirURL = " + dirURL);

        new bug7165725().execute(dirURL + "successive-script-tag.html", createSuccessiveScriptTags());
        new bug7165725().execute(dirURL + "false-text-after-script.html", createFalseTextAfterScript());

        checkByCallbackForSuccessiveScript();
        checkByCallbackForFalseTextAfterScript();

        System.out.println();
        System.out.println();
        System.out.println("Test passed.");
    }

    static String getDirURL() {
        return "file:///" +
                new File(System.getProperty("test.src", ".")).getAbsolutePath() +
                File.separator;
    }

    static String getParsedContentOneLine(String path) throws Exception {
        File f = new File(path);
        FileReader fr = new FileReader(f);
        ParserDelegator pd = new ParserDelegator();
        SBParserCallback sbcallback = new SBParserCallback();
        pd.parse(fr, sbcallback, true);
        fr.close();
        return sbcallback.getStringOneLine();
    }

    static String getParsedContentOneLine(URL url) throws Exception {
        return getParsedContentOneLine(url.getPath());
    }

    static void checkByCallbackForSuccessiveScript() throws Exception {
        String content = getParsedContentOneLine(new URL(getDirURL() + "successive-script-tag.html"));
        if (!content.matches(".*<script .*/js/js1\\.js.*<script .*/js/js2\\.js.*<script .*/js/js3\\.js.*"))
            throw new RuntimeException("Failed to lookup script tags/attributes.");
        if (!content.matches(".*<style .*stylesheets/base\\.css.*<style .*stylesheets/adv\\.css.*"))
            throw new RuntimeException("Failed to lookup style tags.");
    }

    static void checkByCallbackForFalseTextAfterScript() throws Exception {
        String content = getParsedContentOneLine(new URL(getDirURL() + "false-text-after-script.html"));
        final int bodyIdx = content.indexOf("<body ");
        if (bodyIdx > 0) {
            String sbody = content.substring(bodyIdx);
            // There should be no Text(...) in this html
            if (sbody.indexOf("Text(") >= 0)
                throw new RuntimeException("Unexpected text found.");
        } else {
            throw new RuntimeException("Failed to find body tag.");
        }
    }

    private static GoldenElement createSuccessiveScriptTags() {
        return new GoldenElement("html",
                new GoldenElement("head",
                        new GoldenElement("p-implied",
                                new GoldenElement("title"),
                                new GoldenElement("title"),
                                new GoldenElement("script"),
                                new GoldenElement("comment"),
                                new GoldenElement("script"),
                                new GoldenElement("script"),
                                new GoldenElement("comment"),
                                new GoldenElement("script"),
                                new GoldenElement("script"),
                                new GoldenElement("comment"),
                                new GoldenElement("script"),
                                new GoldenElement("content"))),
                new GoldenElement("body",
                        new GoldenElement("p-implied",
                                new GoldenElement("content"))));
    }

    private static GoldenElement createFalseTextAfterScript() {
        return new GoldenElement("html",
                new GoldenElement("head",
                        new GoldenElement("p-implied",
                                new GoldenElement("title"),
                                new GoldenElement("title"),
                                new GoldenElement("content"))),
                new GoldenElement("body",
                        new GoldenElement("form",
                                new GoldenElement("p-implied",
                                        new GoldenElement("input"),
                                        new GoldenElement("input"),
                                        new GoldenElement("content"))),
                        new GoldenElement("p-implied",
                                new GoldenElement("script"),
                                new GoldenElement("comment"),
                                new GoldenElement("script"),
                                new GoldenElement("script"),
                                new GoldenElement("comment"),
                                new GoldenElement("script"),
                                new GoldenElement("content"))));
    }

    static class SBParserCallback extends HTMLEditorKit.ParserCallback
    {
        private int indentSize = 0;
        private ArrayList<String> elist = new ArrayList<>();

        public String getStringOneLine() {
            StringBuilder sb = new StringBuilder();
            for (String s : elist) sb.append(s);
            return sb.toString();
        }

        public String toString() {
            StringBuffer sb = new StringBuffer();
            for (String s : elist) sb.append(s + "\n");
            return sb.toString();
        }

        protected void indent() {
            indentSize += 3;
        }
        protected void unIndent() {
            indentSize -= 3; if (indentSize < 0) indentSize = 0;
        }

        protected String pIndent() {
            StringBuilder sb = new StringBuilder();
            for(int i = 0; i < indentSize; i++) sb.append(" ");
            return sb.toString();
        }

        public void handleText(char[] data, int pos) {
            elist.add(pIndent() + "Text(" + data.length + " chars) \"" + new String(data) + "\"");
        }

        public void handleComment(char[] data, int pos) {
            elist.add(pIndent() + "Comment(" + data.length + " chars)");
        }

        public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) {
            elist.add(pIndent() + "Tag start(<" + t.toString() + " " + a + ">, " +
                    a.getAttributeCount() + " attrs)");
            indent();
        }

        public void handleEndTag(HTML.Tag t, int pos) {
            unIndent();
            elist.add(pIndent() + "Tag end(</" + t.toString() + ">)");
        }

        public void handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos) {
            elist.add(pIndent() + "Tag(<" + t.toString() + ">, " +
                    a.getAttributeCount() + " attrs)");
        }

        public void handleError(String errorMsg, int pos){
        }
    }
}