Skip to content

Instantly share code, notes, and snippets.

@trygvis
Created September 19, 2009 13:40
Show Gist options
  • Save trygvis/189485 to your computer and use it in GitHub Desktop.
Save trygvis/189485 to your computer and use it in GitHub Desktop.
How do you like my JQuery implementation in Java?
String result = $(document).find("#result").text();
package no.java.incogito.tcs;
import fj.F;
import fj.pre.Show;
import fj.data.List;
import fj.data.Option;
import static fj.data.Option.some;
import fj.data.Tree;
import no.java.incogito.tcs.XmlTree.XmlElement;
import no.java.incogito.tcs.XmlTree.XmlNode;
import org.w3c.dom.Document;
/**
* @author <a href="mailto:trygvis@java.no">Trygve Laugst&oslash;l</a>
* @version $Id$
*/
public class JQuery {
private final XmlTree document;
private final List<Tree<XmlNode>> matches;
public JQuery(XmlTree document, List<Tree<XmlNode>> matches) {
this.document = document;
this.matches = matches;
}
public JQuery(XmlTree document, Option<Tree<XmlNode>> match) {
this.document = document;
this.matches = match.toList();
}
public JQuery find(String selector) {
if (!selector.startsWith("#")) {
throw new RuntimeException("Unable to parse selector: '" + selector + "'.");
}
final String id = selector.substring(1);
F<Tree<XmlNode>, Boolean> f;
f = new F<Tree<XmlNode>, Boolean>() {
public Boolean f(Tree<XmlNode> tree) {
System.out.println("tree.root().getClass() = " + tree.root().getClass());
if (!(tree.root() instanceof XmlElement)) {
return false;
}
XmlElement element = (XmlElement) tree.root();
Option<String> idOption = element.attributes.get("id");
Show.optionShow(Show.stringShow).println(idOption);
return idOption.isSome() && idOption.some().equals(id);
}
};
// Option<TreeZipper<XmlNode>> child = document.tree.findChild(f);
Option<Tree<XmlNode>> child = findChild(document.tree, f);
return new JQuery(document, child);
}
private Option<Tree<XmlNode>> findChild(Tree<XmlNode> zipper, F<Tree<XmlNode>, Boolean> f) {
for (Tree<XmlNode> current : zipper.subForest()) {
if(f.f(current)) {
return some(current);
}
Option<Tree<XmlNode>> zipperOption = findChild(current, f);
if(zipperOption.isSome()) {
return zipperOption;
}
}
return Option.none();
}
public String text() {
StringBuilder text = new StringBuilder();
for (Tree<XmlNode> match : matches) {
text.append(match.root().getTextContent());
}
return text.toString();
}
// -----------------------------------------------------------------------
//
// -----------------------------------------------------------------------
public static JQuery $(Document document) {
return new JQuery(XmlTree.fromDocument(document), List.<Tree<XmlNode>>nil());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment