- Fix unit tests both for Mac and Windows environment.

- Replace Html Parser with one that is based on Jericho (require running ./fetch_libraries.sh on cast.js project. 

git-svn-id: https://wala.svn.sourceforge.net/svnroot/wala/trunk@3942 f5eafffb-2e1d-0410-98e4-8ec43c5233c4
This commit is contained in:
yinnon_haviv 2010-09-27 15:15:03 +00:00
parent 4740f7a16a
commit 2fea4f6e4f
27 changed files with 702 additions and 109 deletions

View File

@ -0,0 +1,196 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<script>
var g_image_number = 0;
</script>
<script>
function test_function_base_crawling()
{
var href;
href = "results.html?";
href += "function_base_crawling_";
href += (12*document.location.href.length) ? "worked" : "/strange_behaviour";
document.location.href = href;
}
</script>
<script>
function test_event_element()
{
var href;
href = "results.html?";
href += "event_element_";
if (window.event == undefined) {
href += (12*document.location.href.length) ? "unsupported" : "strange_behaviour";
} else if (!isNaN(window.event.srcElement)) {
href += (12*document.location.href.length) ? "srcElement_unsupported" : "strange_behaviour";
} else if (!isNaN(window.event.srcElement)) {
href += (12*document.location.href.length) ? "srcElement_attr_unsupported" : "strange_behaviour";
} else {
href += (12*document.location.href.length) ? "worked" : "strange_behaviour";
}
document.location.href = href;
}
</script>
<script>
function test_isNaN()
{
var href;
href = "results.html?";
href += "isNaN_";
if (!isNaN(window.asghdaa)) {
href += (12*document.location.href.length) ? "unsupported" : "strange_behaviour";
} else {
href += (12*document.location.href.length) ? "worked" : "strange_behaviour";
}
document.location.href = href;
}
</script>
<script>
function test_first_phase()
{
var href;
href = "results.html?";
href += "first_phase_";
href += (12*document.location.href.length) ? "worked" : "/strange_behaviour";
document.location.href = href;
}
</script>
<script>
function test_second_phase()
{
var button = document.createElement("button");
button.innerText = "go to second phase html";
document.body.appendChild(button);
button.onclick = function () {
var href;
href = "results.html?";
href += "second_phase_";
href += (12*document.location.href.length) ? "worked" : "/strange_behaviour";
document.location.href = href;
};
var thirdButton = document.createElement("button");
thirdButton.innerText = 'Test "Third Phase Competability"';
thirdButton.onclick = test_third_phase;
document.body.appendChild(thirdButton);
}
</script>
<script>
function test_third_phase()
{
var button = document.createElement("button");
button.innerText = "go to third phase html";
document.body.appendChild(button);
button.onclick = function () {
var href;
href = "results.html?";
href += "third_phase_";
href += (12*document.location.href.length) ? "worked" : "/strange_behaviour";
document.location.href = href;
}
}
</script>
<script>
function test_n_phase()
{
var button = document.createElement("button");
button.tag = isNaN(event.srcElement.tag) ? 1 : Number(event.srcElement.tag) + 1;
button.innerText = "go to "+button.tag+" phase html";
button.onclick = function () {
var href;
href = "results.html?";
href += "n_phase_"+button.tag+"_";
href += (12*document.location.href.length) ? "worked" : "/strange_behaviour";
document.location.href = href;
};
var linkButton = document.createElement("button");
linkButton.tag = button.tag;
linkButton.innerText = "create "+linkButton.tag+" phase button";
linkButton.onclick = test_n_phase;
document.body.appendChild(linkButton);
document.body.appendChild(button);
}
</script>
<script>
var differentOrder = "/differnet_order_";
</script>
<script>
function test_both_order2()
{
differentOrder += "2";
test_both_order_button.innerText = 'Test "Different Order Competability 2"';
}
</script>
<script>
function test_both_order()
{
var href;
href = "results.html?";
href += "both_order_";
href += (test_both_order_button.innerText.substr(test_both_order_button.innerText.length-2,1));
href += ".html";
document.location.href = href;
}
</script>
<script>
function send_unique_dom_request()
{
var href;
href = "results.html?";
href += "dom_unique";
href += ".html";
document.location.href = href;
}
</script>
<script>
function send_same_dom_request()
{
var href;
href = "results.html?";
href += "dom_same";
href += ".html";
document.location.href = href;
}
</script>
<script>
function test_unique_dom_button2()
{
test_unique_dom_button.onclick = send_same_dom_request;
}
</script>
<body>
<BR><BR><BR><HR><BR><BR><BR>
<BR><button onclick = "test_event_element()">Test "Event Element"</button>
<BR><button onclick = "test_isNaN()">Test "isNaN Competability"</button>
<BR><button onclick = "test_first_phase()">Test "First Phase Competability"</button>
<BR><button onclick = "test_second_phase()">Test "Second Phase Competability"</button>
<BR><button onclick = "test_n_phase()">Test "N Phase Competability"</button>
<BR><button id=test_both_order_button onclick = "test_both_order()">Test "Different Order Competability 1"</button>
<button onclick = "test_both_order2()">Change Different Order Location</button>
<BR><button onclick = "test_unique_dom_button2()">Change Next element onclick Method</button>
<button id=test_unique_dom_button onclick = "send_unique_dom_request()">Test "Unique Dom Competability"</button>
<BR>
</body>
</html>

View File

@ -0,0 +1,4 @@
function changeUrls()
{
document.links[0].href = "page15.php?a=ok";
}

View File

@ -0,0 +1,4 @@
function changeUrls()
{
document.links[0].href = "page16.php?a=ok";
}

View File

@ -0,0 +1,4 @@
function changeUrls()
{
document.links[0].href = "page17.php?a=ok";
}

View File

@ -0,0 +1,25 @@
<html>
<body>
<script>
var myForm = document.createElement("form");
myForm.setAttribute("action","page11.php");
myForm.setAttribute("method","GET");
var myHiddenA = document.createElement("input");
myHiddenA.setAttribute("type","hidden");
myHiddenA.setAttribute("name","a");
myHiddenA.setAttribute("value","ok");
var myHiddenB = document.createElement("input");
myHiddenB.setAttribute("type","hidden");
myHiddenB.setAttribute("name","b");
myHiddenB.setAttribute("value","ok");
var mySubmit = document.createElement("input");
mySubmit.setAttribute("type","submit");
mySubmit.setAttribute("name","submit");
mySubmit.setAttribute("value","submit");
myForm.appendChild(myHiddenA);
myForm.appendChild(myHiddenB);
myForm.appendChild(mySubmit);
document.body.appendChild(myForm);
</script>
</body>
</html>

View File

@ -0,0 +1,31 @@
<html>
<head>
<script>
function handler()
{
if(this.readyState == 4)
{
var contents = this.responseText;
document.getElementById("myDiv").innerHTML = contents;
}
return;
}
function callXHR()
{
var textBoxValue = document.getElementById("freeTextField").value;
var client = new XMLHttpRequest();
client.onreadystatechange = handler;
client.open("GET", "page12.php?freeTextField="+textBoxValue, true);
client.send(null);
return;
}
</script>
</head>
<body>
<div id="myDiv" style="location: absolute; top: 100px; left: 100px; height: 400px; width: 400px; background-color: #ff0000;"></div>
<input type="text" id="freeTextField" name="freeTextField" value="DEFAULT_SHOULD_BE_CHANGED"></input>
<button onclick="return callXHR();">SUBMIT</button>
</body>
</html>

View File

@ -0,0 +1,32 @@
<html>
<head>
<script>
function handler()
{
if(this.readyState == 4)
{
var contents = this.responseText;
document.getElementById("myDiv").innerHTML = contents;
}
return;
}
function callXHR()
{
var textBoxValue = document.getElementById("freeTextField").value;
var client = new XMLHttpRequest();
client.onreadystatechange = handler;
client.open("POST", "page13.php", true);
client.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
client.send("freeTextField="+textBoxValue);
return;
}
</script>
</head>
<body>
<div id="myDiv" style="location: absolute; top: 100px; left: 100px; height: 400px; width: 400px; background-color: #ff0000;"></div>
<input type="text" id="freeTextField" name="freeTextField" value="DEFAULT_SHOULD_BE_CHANGED"></input>
<button onclick="return callXHR();">SUBMIT</button>
</body>
</html>

View File

@ -0,0 +1,8 @@
<html>
<head>
<script src="15.js"></script>
</head>
<body onload="return changeUrls();">
<a href="#">Link to be changed onload</a>
</body>
</html>

View File

@ -0,0 +1,8 @@
<html>
<head>
<script src="16.js"></script>
</head>
<body>
<a href="#" onclick="return changeUrls();">Link to be changed onload</a>
</body>
</html>

View File

@ -0,0 +1,37 @@
<html>
<head>
<script>
function loadScript(url, callback)
{
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.src = url;
var done = false;
script.onload = script.onreadystatechange = function _page17_handler()
{
if( !done && ( !this.readyState || this.readyState == "loaded" || this.readyState == "complete"))
{
done = true;
callback();
script.onload = script.onreadystatechange = null;
head.removeChild( script );
}
};
head.appendChild(script);
}
function callFunction()
{
changeUrls();
}
</script>
</head>
<body>
<a href="#">Test Link</a>
<script>
loadScript("17.js", callFunction);
</script>
</body>
</html>

View File

@ -0,0 +1,29 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>SBMjs Basic24</title>
</head>
<body>
<a id ="x" href ="javascript:alert(1)"/>
<script>
var Enumerable = {
each: function(iterator, context) {
var index = 0;
iterator = iterator.bind(context);
try {
this._each(function(value) {
iterator(value, index++);
});
} catch (e) {
if (e != $break) throw e;
}
return this;
}
}
</script>
</body>
</html>

View File

@ -51,8 +51,8 @@ public abstract class TestSimplePageCallGraphShape extends TestJSCallGraphShape
verifyGraphAssertions(CG, assertionsForPage2);
}
@Test public void testWatchfire1() throws IOException, IllegalArgumentException, CancelException {
URL url = getClass().getClassLoader().getResource("pages/watchfire1.html");
@Test public void testCrawl() throws IOException, IllegalArgumentException, CancelException {
URL url = getClass().getClassLoader().getResource("pages/crawl.html");
CallGraph CG = Util.makeHTMLCG(url);
verifyGraphAssertions(CG, null);
}

View File

@ -5,5 +5,6 @@
<classpathentry kind="src" path="dat"/>
<classpathentry exported="true" kind="lib" path="bin" sourcepath="bin"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="lib" path="lib/jericho-html-2.6.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@ -26,5 +26,6 @@ Require-Bundle: com.ibm.wala.cast,
com.ibm.wala.cast,
com.ibm.wala.shrike;bundle-version="1.1.3",
org.eclipse.equinox.common;bundle-version="3.4.0",
org.eclipse.core.runtime;bundle-version="3.4.0"
org.eclipse.core.runtime;bundle-version="3.4.0",
org.apache.commons.logging
Bundle-ActivationPolicy: lazy

View File

@ -34,3 +34,18 @@ if [[ ! -e $MY_DIR/xalan.jar ]]; then
cd $MY_DIR
rm -rf $TMP
fi
if [[ ! -e $MY_DIR/jericho-html-2.6.jar ]]; then
mkdir -p $TMP
cd $TMP
wget -O jericho-html-2.6.zip http://sourceforge.net/projects/jerichohtml/files/jericho-html/2.6/jericho-html-2.6.zip/download
jar xf jericho-html-2.6.zip jericho-html-2.6/lib/jericho-html-2.6.jar
cp jericho-html-2.6/lib/jericho-html-2.6.jar $MY_DIR/jericho-html-2.6.jar
cd $MY_DIR
rm -rf $TMP
fi

Binary file not shown.

View File

@ -0,0 +1,16 @@
package com.ibm.wala.cast.js.html;
/**
* Callback which is implemented by users of the IHtmlParser. The parser traverses the dom-nodes in an in-order.
* @author danielk
* @author yinnonh
*
*/
public interface IHtmlCallback {
void handleStartTag(ITag tag);
void handleEndTag(ITag tag);
}

View File

@ -0,0 +1,20 @@
package com.ibm.wala.cast.js.html;
import java.io.Reader;
/**
* @author danielk
* @author yinnonh
* Parses an HTML file using call backs
*/
public interface IHtmlParser {
/**
* Parses a given HTML, calling the given callback.
* @param reader
* @param callback
* @param fileName
*/
public void parse(Reader reader, IHtmlCallback callback, String fileName);
}

View File

@ -0,0 +1,44 @@
package com.ibm.wala.cast.js.html;
import java.util.Map;
import com.ibm.wala.util.collections.Pair;
/**
* @author danielk
* Data structure representing an HTML tag, with its attributes and content. Used by the HTML parser when calling the callback.
*/
public interface ITag {
/**
* @return tag's name (e.g., "HEAD" / "HTML" / "FORM")
*/
public String getName();
/**
* Retrieves a specific attribute
* @param name
* @return null if there is no such attribute
*/
public String getAttributeByName(String name);
public Map<String, String> getAllAttributes();
/**
* @return a pair containing the start line of the tag's body and the actual body as a string
*/
public Pair<Integer, String> getBodyText();
/**
* Returns the starting line number of the tag.
* @return null if no known
*/
public int getStartingLineNum();
/**
* @return path to the file containing the tag.
*/
public String getFilePath();
}

View File

@ -0,0 +1,68 @@
package com.ibm.wala.cast.js.html.jericho;
import java.io.IOException;
import java.io.Reader;
import java.util.Iterator;
import java.util.List;
import au.id.jericho.lib.html.Config;
import au.id.jericho.lib.html.Element;
import au.id.jericho.lib.html.LoggerProvider;
import au.id.jericho.lib.html.Source;
import com.ibm.wala.cast.js.html.IHtmlCallback;
import com.ibm.wala.cast.js.html.IHtmlParser;
/**
* @author danielk
* Uses the Jericho parser to go over the HTML
*/
public class HTMLJerichoParser implements IHtmlParser{
static{
Config.LoggerProvider = LoggerProvider.STDERR;
}
@SuppressWarnings("unchecked")
public void parse(Reader reader, IHtmlCallback callback, String fileName) {
Parser parser = new Parser(callback, fileName);
Source src;
try {
src = new Source(reader);
List<Element> childElements = src.getChildElements();
for (Iterator<Element> nodeIterator = childElements.iterator(); nodeIterator.hasNext();) {
Element e = nodeIterator.next();
parser.parse(e);
}
} catch (IOException e) {
System.err.println("Error parsing file: " + e.getMessage());
}
}
/**
* @author danielk
* Inner class does the actual traversal of the HTML using recursion
*/
private static class Parser {
private final IHtmlCallback handler;
private final String fileName;
public Parser(IHtmlCallback handler, String fileName) {
this.handler = handler;
this.fileName = fileName;
}
@SuppressWarnings("unchecked")
private void parse(Element root) {
JerichoTag tag = new JerichoTag(root, fileName);
handler.handleStartTag(tag);
List<Element> childElements = root.getChildElements();
for (Iterator<Element> nodeIterator = childElements.iterator(); nodeIterator.hasNext();) {
Element child = nodeIterator.next();
parse(child);
}
handler.handleEndTag(tag);
}
}
}

View File

@ -0,0 +1,65 @@
package com.ibm.wala.cast.js.html.jericho;
import java.util.Map;
import au.id.jericho.lib.html.Attributes;
import au.id.jericho.lib.html.Element;
import au.id.jericho.lib.html.Segment;
import com.ibm.wala.cast.js.html.ITag;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.Pair;
/**
* ITag impel for Jericho generated tags
* @author danielk
*/
public class JerichoTag implements ITag {
private final Element innerElement;
private final String sourceFile;
private Map<String, String> attributesMap;
@SuppressWarnings("unchecked")
public JerichoTag(Element root, String sourceFile) {
this.innerElement = root;
Attributes attributes = innerElement.getStartTag().getAttributes();
attributesMap = HashMapFactory.make();
if (attributes != null) {
attributesMap = attributes.populateMap(attributesMap, false);
}
this.sourceFile = sourceFile;
}
public Map<String, String> getAllAttributes() {
return attributesMap;
}
public String getAttributeByName(String name) {
return attributesMap.get(name);
}
public Pair<Integer, String> getBodyText() {
Segment content = innerElement.getContent();
Integer lineNum = innerElement.getSource().getRow(content.getBegin());
String body = content.toString();
return Pair.make(lineNum, body);
}
public String getFilePath() {
return sourceFile;
}
public String getName() {
return innerElement.getName();
}
@Override
public String toString() {
return innerElement.toString();
}
public int getStartingLineNum() {
return innerElement.getSource().getRow(innerElement.getStartTag().getBegin());
}
}

View File

@ -13,8 +13,8 @@ package com.ibm.wala.cast.js.ipa.callgraph;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.Set;
import com.ibm.wala.cast.js.ipa.summaries.JavaScriptSummarizedFunction;
import com.ibm.wala.cast.js.ipa.summaries.JavaScriptSummary;
@ -418,9 +418,10 @@ public class JavaScriptConstructTargetSelector implements MethodTargetSelector {
FO.write(fun.toString());
FO.close();
Util.loadAdditionalFile(cha, cl, fileName, new URL("file://" + f.getAbsolutePath()));
IClass fcls = cl.lookupClass("L" + f.getAbsolutePath() + "/_fromctor", cha);
Set<String> fnNames = Util.loadAdditionalFile(cha, cl, fileName, f.toURI().toURL(), f.getAbsolutePath());
assert fnNames.size() == 1;
String fnName = fnNames.iterator().next();
IClass fcls = cl.lookupClass(fnName + "/_fromctor", cha);
f.delete();

View File

@ -20,8 +20,6 @@ import com.ibm.wala.ipa.callgraph.MethodTargetSelector;
import com.ibm.wala.ipa.callgraph.propagation.ConstantKey;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.cha.IClassHierarchy;
import com.ibm.wala.ssa.SSAInstruction;
import com.ibm.wala.types.MethodReference;
import com.ibm.wala.types.TypeName;
@ -60,7 +58,7 @@ public class LoadFileTargetSelector implements MethodTargetSelector {
try {
JavaScriptLoader cl = (JavaScriptLoader) builder.getClassHierarchy().getLoader(JavaScriptTypes.jsLoader);
URL url = new URL(builder.scriptBaseURL, str);
Util.loadAdditionalFile(builder.getClassHierarchy() , cl, str, url);
Util.loadAdditionalFile(builder.getClassHierarchy() , cl, str, url, url.getFile());
IClass script = builder.getClassHierarchy().lookupClass(TypeReference.findOrCreate(cl.getReference(), "L" + url.getFile()));
return script.getMethod(JavaScriptMethods.fnSelector);
} catch (MalformedURLException e1) {

View File

@ -49,6 +49,7 @@ import com.ibm.wala.types.TypeReference;
public class Util extends com.ibm.wala.cast.ipa.callgraph.Util {
private static final boolean DEBUG = false;
private static JavaScriptTranslatorFactory translatorFactory;
public static void setTranslatorFactory(JavaScriptTranslatorFactory translatorFactory) {
@ -111,9 +112,18 @@ public class Util extends com.ibm.wala.cast.ipa.callgraph.Util {
}
}
public static void loadAdditionalFile(IClassHierarchy cha, JavaScriptLoader cl, String fileName, URL f) throws IOException {
SourceURLModule M = new SourceURLModule(f);
TranslatorToCAst toCAst = getTranslatorFactory().make(new CAstImpl(), M, f, f.getFile());
/**
* @param cha
* @param cl
* @param fileName
* @param url
* @param file
* @return The set of class names that where defined in the CHA as a result loading process.
* @throws IOException
*/
public static Set<String> loadAdditionalFile(IClassHierarchy cha, JavaScriptLoader cl, String fileName, URL url, String file) throws IOException {
SourceURLModule M = new SourceURLModule(url);
TranslatorToCAst toCAst = getTranslatorFactory().make(new CAstImpl(), M, url, file);
final Set<String> names = new HashSet<String>();
JSAstTranslator toIR = new JSAstTranslator(cl) {
protected void defineFunction(CAstEntity N,
@ -132,11 +142,14 @@ public class Util extends com.ibm.wala.cast.ipa.callgraph.Util {
}
};
CAstEntity tree = toCAst.translateToCAst();
CAstPrinter.printTo(tree, new PrintWriter(System.err));
if (DEBUG){
CAstPrinter.printTo(tree, new PrintWriter(System.err));
}
toIR.translate(tree, fileName);
for(String name : names) {
IClass fcls = cl.lookupClass(name, cha);
cha.addClass(fcls);
}
return names;
}
}

View File

@ -19,18 +19,19 @@ import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;
import com.ibm.wala.cast.js.html.IHtmlParser;
import com.ibm.wala.cast.js.html.IHtmlCallback;
import com.ibm.wala.cast.js.html.jericho.HTMLJerichoParser;
public class Generator {
public static final String preamble = "preamble.js", temp1 = "temp1.js", temp2 = "temp2.js", temp3 = "temp3.js";
public static interface CallbackFactory {
HTMLCallback createCallback(URL input, FileWriter domTreeFile, FileWriter embeddedScriptFile, FileWriter entrypointFile);
IHtmlCallback createCallback(URL input, FileWriter domTreeFile, FileWriter embeddedScriptFile, FileWriter entrypointFile);
}
public static class HTMLCallbackFactory implements CallbackFactory {
public HTMLCallback createCallback(URL input, FileWriter domTreeFile, FileWriter embeddedScriptFile, FileWriter entrypointFile) {
public IHtmlCallback createCallback(URL input, FileWriter domTreeFile, FileWriter embeddedScriptFile, FileWriter entrypointFile) {
return new HTMLCallback(input, domTreeFile, embeddedScriptFile, entrypointFile);
}
}
@ -90,9 +91,9 @@ public class Generator {
FileWriter out2 = new FileWriter(temp2);
FileWriter out3 = new FileWriter(temp3);
ParserDelegator pd = new ParserDelegator();
HTMLCallback cb = callbackFactory.createCallback(input, out1, out2, out3);
pd.parse(fr, cb, ignoreCharset);
IHtmlParser parser = new HTMLJerichoParser();
IHtmlCallback parseHandler = callbackFactory.createCallback(input, out1, out2, out3);
parser.parse(fr, parseHandler, input.getFile());
out1.flush();
out1.close();
out2.flush();
@ -114,7 +115,7 @@ public class Generator {
out.write("\n}\n\n");
generateTrailer(out, cb);
generateTrailer(out, parseHandler);
out.close();
}
@ -134,7 +135,7 @@ public class Generator {
}
*/
protected void generateTrailer(FileWriter out, HTMLEditorKit.ParserCallback cb) throws IOException {
protected void generateTrailer(FileWriter out, IHtmlCallback parseHandler) throws IOException {
out.write("//Trailer Begin\n");
out.write("//Trailer End\n");
}

View File

@ -14,31 +14,24 @@ import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import javax.swing.text.BadLocationException;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLEditorKit;
import com.ibm.wala.cast.js.html.IHtmlCallback;
import com.ibm.wala.cast.js.html.ITag;
import com.ibm.wala.util.collections.HashMapFactory;
public class HTMLCallback extends HTMLEditorKit.ParserCallback {
public class HTMLCallback implements IHtmlCallback {
private final URL input;
private final FileWriter domTreeFile, embeddedScriptFile, entrypointFile;
private int counter=0;
private boolean script = false;
private final HashMap<String, String> constructors = HashMapFactory.make();
protected final Stack<String> stack;
private int scriptStart;
public HTMLCallback(URL input, FileWriter out, FileWriter out2, FileWriter entrypointFile) {
this.input = input;
this.domTreeFile = out;
@ -55,10 +48,6 @@ public class HTMLCallback extends HTMLEditorKit.ParserCallback {
}
}
public void flush() throws BadLocationException {
}
private void writeEmbeddedScript(char[] text, int length) throws IOException {
embeddedScriptFile.write(text, 0, length);
}
@ -67,17 +56,17 @@ public class HTMLCallback extends HTMLEditorKit.ParserCallback {
embeddedScriptFile.write(text);
}
protected String createElement(HTML.Tag t, MutableAttributeSet a, int pos) {
String tag = t.toString().toUpperCase();
if(tag.equals("SCRIPT")) {
Object l = a.getAttribute(HTML.Attribute.LANGUAGE);
if (l == null || l.toString().toUpperCase().indexOf("VB") < 0) {
Object value = a.getAttribute( HTML.Attribute.SRC );
protected String createElement(ITag tag) {
// String tag = t.toString().toUpperCase();
if(tag.getName().equalsIgnoreCase("SCRIPT")) {
String lang = tag.getAttributeByName("language");
if (lang == null || lang.toUpperCase().indexOf("VB") < 0) {
String src = tag.getAttributeByName("src");
// script is out-of-line
if (value != null) {
if (src != null) {
try {
URL scriptSrc = new URL(input, value.toString());
URL scriptSrc = new URL(input, src);
InputStreamReader scriptReader =
new InputStreamReader(
scriptSrc.openConnection().getInputStream());
@ -90,23 +79,41 @@ public class HTMLCallback extends HTMLEditorKit.ParserCallback {
embeddedScriptFile.flush();
scriptReader.close();
} catch (IOException e) {
System.out.println("bad input script " + value);
System.out.println("bad input script " + src);
}
// script is inline
} else {
script = true;
scriptStart = pos;
String content = tag.getBodyText().snd;
try {
writeEmbeddedScript(content);
} catch (IOException e) {
System.err.println("Cannot write embedded script " + content);
}
}
}
}
String varName = getVarNameForTag(tag);
String cons = constructors.get(tag.getName().toUpperCase());
if(cons == null) cons = "DOMHTMLElement";
try {
writeElement(tag, cons, varName);
domTreeFile.write("\n");
} catch (IOException e) {
System.out.println("Error writing to file");
System.exit(1);
}
return varName;
}
private String getVarNameForTag(ITag tag) {
String varName = null;
Enumeration enu = a.getAttributeNames();
while(enu.hasMoreElements()) {
Object attrObj = enu.nextElement();
String attr = attrObj.toString();
String value = a.getAttribute(attrObj).toString();
for (Map.Entry<String, String> e : tag.getAllAttributes().entrySet()){
String attr = e.getKey();
String value = e.getValue();
if (attr.equalsIgnoreCase("id")) {
varName = value;
break;
@ -115,31 +122,19 @@ public class HTMLCallback extends HTMLEditorKit.ParserCallback {
if (varName == null) {
varName = "node" + (counter++);
}
String cons = constructors.get(tag);
if(cons == null) cons = "DOMHTMLElement";
try {
writeElement(t, a, tag, cons, varName);
domTreeFile.write("\n");
} catch (IOException e) {
System.out.println("Error writing to file");
System.exit(1);
}
return varName;
}
}
protected void writeElement(HTML.Tag t, MutableAttributeSet a, String tag, String cons, String varName) throws IOException {
Enumeration enu = a.getAttributeNames();
protected void writeElement(ITag tag, String cons, String varName) throws IOException {
indent(); domTreeFile.write("function make_" + varName + "(parent) {\n");
indent(); domTreeFile.write(" this.temp = " + cons + ";\n");
indent(); domTreeFile.write(" this.temp(" + tag + ");\n");
while(enu.hasMoreElements()) {
Object attrObj = enu.nextElement();
String attr = attrObj.toString();
String value = a.getAttribute(attrObj).toString();
indent(); domTreeFile.write(" this.temp(" + tag.getName() + ");\n");
for (Map.Entry<String, String> e : tag.getAllAttributes().entrySet()){
String attr = e.getKey();
String value = e.getValue();
domTreeFile.write(" ");
writeAttribute(t, a, attr, value, "this", varName);
writeAttribute(tag, attr, value, "this", varName);
}
indent(); domTreeFile.write(" " + varName + " = this;\n");
@ -147,12 +142,12 @@ public class HTMLCallback extends HTMLEditorKit.ParserCallback {
indent(); domTreeFile.write(" parent.appendChild(this);\n");
}
protected void writeAttribute(HTML.Tag t, MutableAttributeSet a, String attr, String value, String varName, String varName2) throws IOException {
writePortletAttribute(t, a, attr, value, varName);
writeEventAttribute(t, a, attr, value, varName, varName2);
protected void writeAttribute(ITag tag, String attr, String value, String varName, String varName2) throws IOException {
writePortletAttribute(tag, attr, value, varName);
writeEventAttribute(tag, attr, value, varName, varName2);
}
protected void writeEventAttribute(HTML.Tag t, MutableAttributeSet a, String attr, String value, String varName, String varName2) throws IOException {
protected void writeEventAttribute(ITag tag, String attr, String value, String varName, String varName2) throws IOException {
if(attr.substring(0,2).equals("on")) {
indent(); domTreeFile.write("function " + attr + "_" + varName2 + "(event) {" + value + "};\n");
indent(); domTreeFile.write(varName + "." + attr + " = " + attr + "_" + varName2 + ";\n");
@ -171,7 +166,7 @@ public class HTMLCallback extends HTMLEditorKit.ParserCallback {
}
}
protected void writePortletAttribute(HTML.Tag t, MutableAttributeSet a, String attr, String value, String varName) throws IOException {
protected void writePortletAttribute(ITag tag, String attr, String value, String varName) throws IOException {
if(attr.equals("portletid")) {
if(value.substring(value.length()-4).equals("vice")) {
indent(); domTreeFile.write("\n\nfunction cVice() { var contextVice = " + varName + "; }\ncVice();\n\n");
@ -181,10 +176,6 @@ public class HTMLCallback extends HTMLEditorKit.ParserCallback {
}
}
public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) {
String varName = createElement(t,a,pos);
stack.push(varName);
}
private void endElement(String name) {
try {
@ -200,32 +191,13 @@ public class HTMLCallback extends HTMLEditorKit.ParserCallback {
}
}
public void handleEndTag(HTML.Tag t, int pos) {
if(t.toString().toUpperCase().equals("SCRIPT")) {
if (script) try {
int scriptEnd = pos;
InputStreamReader script = new InputStreamReader(input.openStream());
char[] buf = new char[ scriptEnd ];
script.read(buf);
String s = String.valueOf(buf, scriptStart, scriptEnd-scriptStart);
writeEmbeddedScript(s.substring(s.indexOf('>')+1));
} catch (IOException e) {
}
script = false;
}
endElement(stack.pop());
}
public void handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos) {
if (! script) {
String nm = createElement(t, a, pos);
endElement(nm);
}
public void handleEndTag(ITag tag) {
endElement(stack.pop());
}
public void handleError(String errorMsg, int pos) {
System.out.println("Error" + errorMsg);
public void handleStartTag(ITag tag) {
String varName = createElement(tag);
stack.push(varName);
}
}

View File

@ -77,7 +77,7 @@ public abstract class CAstAbstractModuleLoader extends CAstAbstractLoader {
File f = ((SourceFileModule) moduleEntry).getFile();
String fn = f.toString();
TranslatorToCAst xlatorToCAst = getTranslatorToCAst(ast, moduleEntry, new URL("file://" + f), fn);
TranslatorToCAst xlatorToCAst = getTranslatorToCAst(ast, moduleEntry, f.toURI().toURL(), fn);
CAstEntity fileEntity = xlatorToCAst.translateToCAst();