1 package org.andromda.core.common; 2 3 import java.io.IOException; 4 import java.io.StringReader; 5 import java.util.ArrayList; 6 import java.util.Collection; 7 8 import javax.swing.text.MutableAttributeSet; 9 import javax.swing.text.html.HTML.Tag; 10 import javax.swing.text.html.HTMLEditorKit.ParserCallback; 11 import javax.swing.text.html.parser.ParserDelegator; 12 13 14 /*** 15 * A utility object useful for reading an HTML string (originating 16 * from the contents of an XMI documentation element) and for translating 17 * that string into an HTML paragraph. 18 * 19 * <p> The list of paragraphs can be used in a Velocity template 20 * to generate JavaDoc documentation for a class, an attribute or a 21 * method. </p> 22 * 23 * <p> This is a very simple HTML analyzer class that builds upon the 24 * Swing HTMLEditor toolkit. </p> 25 * 26 * @author Matthias Bohlen 27 * 28 */ 29 public class HTMLAnalyzer 30 { 31 /*** 32 * <p>Translates an HTML string into a list of HTMLParagraphs.</p> 33 * @param html the HTML string to be analyzed 34 * @return Collection the list of paragraphs found in the HTML string 35 * @throws IOException if something goes wrong 36 */ 37 public Collection htmlToParagraphs(String html) throws IOException 38 { 39 ParserDelegator pd = new ParserDelegator(); 40 pd.parse(new StringReader(html), new MyParserCallback(), true); 41 return paragraphs; 42 } 43 44 private ArrayList paragraphs = new ArrayList(); 45 46 private class MyParserCallback extends ParserCallback 47 { 48 private HTMLParagraph currentParagraph = null; 49 50 public void handleSimpleTag( 51 Tag tag, 52 MutableAttributeSet attribs, 53 int pos) 54 { 55 appendWord("<" + tag + ">"); 56 } 57 58 public void handleStartTag( 59 Tag tag, 60 MutableAttributeSet attribs, 61 int pos) 62 { 63 if (tag.equals(Tag.P)) 64 { 65 currentParagraph = new HTMLParagraph(66); 66 } 67 else 68 { 69 appendWord("<" + tag + ">"); 70 } 71 } 72 73 public void handleEndTag(Tag tag, int pos) 74 { 75 if (tag.equals(Tag.P)) 76 { 77 paragraphs.add(currentParagraph); 78 currentParagraph = null; 79 } 80 else 81 { 82 appendWord("</" + tag + ">"); 83 } 84 } 85 86 public void handleText(char[] text, int pos) 87 { 88 appendText(text); 89 } 90 91 private void appendWord(String string) 92 { 93 if (currentParagraph != null) 94 { 95 currentParagraph.appendWord(string); 96 } 97 } 98 99 private void appendText(String string) 100 { 101 if (currentParagraph != null) 102 { 103 currentParagraph.appendText(string); 104 } 105 } 106 107 private void appendText(char[] text) 108 { 109 if (currentParagraph != null) 110 { 111 currentParagraph.appendText(new String(text)); 112 } 113 } 114 } 115 }