01: package org.andromda.maven.site;
02:
03: import org.apache.commons.jelly.JellyTagException;
04: import org.apache.commons.jelly.MissingAttributeException;
05: import org.apache.commons.jelly.TagSupport;
06: import org.apache.commons.jelly.XMLOutput;
07: import org.apache.commons.lang.StringEscapeUtils;
08: import org.dom4j.Element;
09: import org.dom4j.Node;
10: import org.dom4j.io.XMLWriter;
11: import org.xml.sax.SAXException;
12: import org.xml.sax.helpers.AttributesImpl;
13:
14: import java.io.IOException;
15: import java.io.StringWriter;
16: import java.util.Collection;
17: import java.util.Iterator;
18:
19: public abstract class AbstractHighlightTag extends TagSupport {
20: private String value = null;
21:
22: protected abstract void highlight(XMLOutput output, String text)
23: throws SAXException;
24:
25: public void doTag(XMLOutput xmlOutput)
26: throws MissingAttributeException, JellyTagException {
27: Object content = context.getVariable(getValue());
28:
29: if (content instanceof Collection) {
30: final Collection collection = (Collection) content;
31: if (!collection.isEmpty()) {
32: content = collection.iterator().next();
33: }
34: }
35:
36: if (content instanceof Element) {
37: try {
38: String bodyText = getSourceCode((Element) content);
39: highlight(xmlOutput, StringEscapeUtils
40: .unescapeXml(bodyText));
41: } catch (SAXException e) {
42: throw new JellyTagException(
43: "Unable to print out highlighted body text: "
44: + e);
45: }
46: } else {
47: throw new JellyTagException("Not an XML element: "
48: + getValue());
49: }
50: }
51:
52: private String getSourceCode(Element element)
53: throws JellyTagException {
54: StringWriter stringWriter = new StringWriter();
55:
56: try {
57: XMLWriter xmlWriter = new XMLWriter(stringWriter);
58:
59: for (final Iterator iterator = element.nodeIterator(); iterator
60: .hasNext();) {
61: Node childElement = (Node) iterator.next();
62: xmlWriter.write(childElement.getText());
63: }
64:
65: xmlWriter.flush();
66: xmlWriter.close();
67: } catch (IOException ioe) {
68: throw new JellyTagException(
69: "Unable parse source for syntax highlighting: ");
70: }
71:
72: return stringWriter.getBuffer().toString();
73: }
74:
75: protected void startTokenHighlight(XMLOutput output, String cssClass)
76: throws SAXException {
77: if (cssClass != null) {
78: AttributesImpl attributes = new AttributesImpl();
79: attributes.addAttribute("", "class", "class", "string",
80: cssClass);
81: output.startElement("div", attributes);
82: }
83: }
84:
85: protected void endTokenHighlight(XMLOutput output)
86: throws SAXException {
87: output.endElement("div");
88: }
89:
90: public String getValue() {
91: return value;
92: }
93:
94: public void setValue(String value) {
95: this.value = value;
96: }
97: }
|