alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

What this is

This file is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Other links

The source code

// $Header: /home/cvs/jakarta-jmeter/src/htmlparser/org/htmlparser/tests/scannersTests/ScriptScannerTest.java,v 1.2 2004/02/11 02:16:58 woolfel Exp $
/*
 * ====================================================================
 * Copyright 2002-2004 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */

// The developers of JMeter and Apache are greatful to the developers
// of HTMLParser for giving Apache Software Foundation a non-exclusive
// license. The performance benefits of HTMLParser are clear and the
// users of JMeter will benefit from the hard work the HTMLParser
// team. For detailed information about HTMLParser, the project is
// hosted on sourceforge at http://htmlparser.sourceforge.net/.
//
// HTMLParser was originally created by Somik Raha in 2000. Since then
// a healthy community of users has formed and helped refine the
// design so that it is able to tackle the difficult task of parsing
// dirty HTML. Derrick Oswald is the current lead developer and was kind
// enough to assist JMeter.

package org.htmlparser.tests.scannersTests;

import java.util.Hashtable;

import org.htmlparser.Node;
import org.htmlparser.Parser;
import org.htmlparser.scanners.ScriptScanner;
import org.htmlparser.tags.ScriptTag;
import org.htmlparser.tests.ParserTestCase;
import org.htmlparser.util.ParserException;

public class ScriptScannerTest extends ParserTestCase
{

    public ScriptScannerTest(String name)
    {
        super(name);
    }

    public void testEvaluate()
    {
        ScriptScanner scanner = new ScriptScanner("-s");
        boolean retVal = scanner.evaluate("   script ", null);
        assertEquals(
            "Evaluation of SCRIPT tag",
            new Boolean(true),
            new Boolean(retVal));
    }

    public void testScan() throws ParserException
    {
        String testHtml = "";
        createParser(testHtml, "http://www.google.com/test/index.html");
        // Register the script scanner
        parser.addScanner(new ScriptScanner("-s"));
        parseAndAssertNodeCount(1);
        assertTrue("Node should be a script tag", node[0] instanceof ScriptTag);
        // Check the data in the applet tag
        ScriptTag scriptTag = (ScriptTag) node[0];
        assertStringEquals(
            "Expected Script Code",
            "document.write(d+\".com\")",
            scriptTag.getScriptCode());
        assertStringEquals("script tag html", testHtml, scriptTag.toHtml());
    }

    /**
     * Bug reported by Gordon Deudney 2002-03-27
     * Upon parsing :
     * <SCRIPT LANGUAGE="JavaScript" 
     * SRC="../js/DetermineBrowser.js"></SCRIPT>
     * the SRC data cannot be retrieved.
     */
    public void testScanBug() throws ParserException
    {
        createParser(
            "",
            "http://www.google.com/test/index.html");
        // Register the image scanner
        parser.addScanner(new ScriptScanner("-s"));
        parseAndAssertNodeCount(1);
        assertTrue("Node should be a script tag", node[0] instanceof ScriptTag);
        // Check the data in the applet tag
        ScriptTag scriptTag = (ScriptTag) node[0];
        Hashtable table = scriptTag.getAttributes();
        String srcExpected = (String) table.get("SRC");
        assertEquals(
            "Expected SRC value",
            "../js/DetermineBrowser.js",
            srcExpected);
    }

    /** 
     * Bug check by Wolfgang Germund 2002-06-02 
     * Upon parsing : 
     * <script language="javascript"> 
     * if(navigator.appName.indexOf("Netscape") != -1) 
     * document.write ('xxx'); 
     * else 
     * document.write ('yyy'); 
     * </script> 
     * check getScriptCode(). 
     */
    public void testScanBugWG() throws ParserException
    {
        StringBuffer sb1 = new StringBuffer();
        sb1.append("\r\n");
        String testHTML1 = new String(sb1.toString());

        createParser(testHTML1, "http://www.google.com/test/index.html");
        Parser.setLineSeparator("\r\n");
        // Register the image scanner 
        parser.addScanner(new ScriptScanner("-s"));

        parseAndAssertNodeCount(2);

        StringBuffer sb2 = new StringBuffer();
        sb2.append("if(navigator.appName.indexOf(\"Netscape\") != -1)\r\n");
        sb2.append(" document.write ('xxx');\r\n");
        sb2.append("else\r\n");
        sb2.append(" document.write ('yyy');\r\n");
        String testHTML2 = new String(sb2.toString());

        assertTrue("Node should be a script tag", node[1] instanceof ScriptTag);
        // Check the data in the applet tag 
        ScriptTag scriptTag = (ScriptTag) node[1];
        String s = scriptTag.getScriptCode();
        assertStringEquals("Expected Script Code", testHTML2, s);
    }

    public void testScanScriptWithLinks() throws ParserException
    {
        StringBuffer sb1 = new StringBuffer();
        sb1.append(
            "\r\n");
        String testHTML1 = new String(sb1.toString());

        createParser(testHTML1, "http://www.hardwareextreme.com/");
        // Register the image scanner 
        parser.registerScanners();
        //parser.addScanner(new HTMLScriptScanner("-s")); 

        parseAndAssertNodeCount(1);
        assertTrue("Node should be a script tag", node[0] instanceof ScriptTag);
        // Check the data in the applet tag 
        ScriptTag scriptTag = (ScriptTag) node[0];
        //assertStringEquals("Expected Script Code",testHTML2,scriptTag.getScriptCode()); 
    }

    public void testScanScriptWithComments() throws ParserException
    {
        createParser(
            "",
            "http://www.hardwareextreme.com/");
        // Register the image scanner 
        parser.registerScanners();
        parseAndAssertNodeCount(1);
        assertTrue("Node should be a script tag", node[0] instanceof ScriptTag);
        // Check the data in the applet tag 
        ScriptTag scriptTag = (ScriptTag) node[0];
        String scriptCode = scriptTag.getScriptCode();
        String expectedCode =
            "";
        assertStringEquals("Expected Code", expectedCode, scriptCode);
    }

    /**
     * Submitted by Dhaval Udani - reproducing bug 664404
     * @throws ParserException
     */
    public void testScriptTagComments() throws ParserException
    {
        String testHtml =
            "";
        createParser(testHtml);

        parser.addScanner(new ScriptScanner("-s"));
        parseAndAssertNodeCount(1);
        ScriptTag scriptTag = (ScriptTag) node[0];
        assertStringEquals("scriptag html", testHtml, scriptTag.toHtml());
    }

    /**
     * Duplicates bug reported by James Moliere - whereby,
     * if script tags are generated by script code, the parser
     * interprets them as real tags. The problem was that the
     * string parser was not moving to the ignore state on encountering double
     * quotes (only single quotes were previously accepted).
     * @throws Exception
     */
    public void testScriptTagsGeneratedByScriptCode() throws Exception
    {
        createParser(
            ""
                + ""
                + ""
                + "Untitled Document"
                + ""
                + ""
                + "\");"
                + ""
                + ""
                + ""
                + "");
        parser.registerScanners();
        Node scriptNodes[] = parser.extractAllNodesThatAre(ScriptTag.class);
        assertType("scriptnode", ScriptTag.class, scriptNodes[0]);
        ScriptTag scriptTag = (ScriptTag) scriptNodes[0];
        assertStringEquals(
            "script code",
            "document.write(\"\");",
            scriptTag.getScriptCode());

    }

    public void testScriptCodeExtraction() throws ParserException
    {
        createParser(
            "");
        parser.registerScanners();
        parseAndAssertNodeCount(1);
        assertType("script", ScriptTag.class, node[0]);
        ScriptTag scriptTag = (ScriptTag) node[0];
        assertStringEquals(
            "script code",
            "document.write(\"\");",
            scriptTag.getScriptCode());
    }

    public void testScriptCodeExtractionWithMultipleQuotes()
        throws ParserException
    {
        createParser(
            "");
        parser.registerScanners();
        parseAndAssertNodeCount(1);
        assertType("script", ScriptTag.class, node[0]);
        ScriptTag scriptTag = (ScriptTag) node[0];
        assertStringEquals(
            "script code",
            "document.write(\"\");",
            scriptTag.getScriptCode());
    }

    public void testScriptWithinComments() throws Exception
    {
        createParser(
            "");
        parser.registerScanners();
        parseAndAssertNodeCount(1);

    }

    /**
     * There was a bug in the ScriptScanner when there was multiline script and
     * the last line did not have a newline before the end script tag. For example:
     * 
     * <script>alert()
     * alert()</script>
     * 
     * Would generate the following "scriptCode()" result:
     * alert()alert()
     *
     * But should actually return:
     * alert()
     * alert() 
     *
     * This was fixed in ScriptScanner, which this test verifies
     */
    public void testScriptCodeExtractionWithNewlines() throws ParserException
    {
        String scriptContents = "alert()\r\nalert()";
        createParser("");
        parser.registerScanners();
        parseAndAssertNodeCount(1);
        assertType("script", ScriptTag.class, node[0]);
        ScriptTag scriptTag = (ScriptTag) node[0];
        assertStringEquals(
            "script code",
            scriptContents,
            scriptTag.getScriptCode());
    }

    /**
     * Tests a bug in ScriptScanner where a NPE would be thrown if the
     * script tag was not closed before the document ended.
     */
    public void testScanNoEndTag() throws ParserException
    {
        createParser(" tags
     */
    public void testScanQuotedEndTag() throws ParserException
    {
        createParser("');");
        parser.addScanner(new ScriptScanner("-s"));
        parseAndAssertNodeCount(1);
        String s = node[0].toHtml();
        assertEquals(
            "Parse error",
            "');",
            s);
    }
}
... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.