KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > MakeManual


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 import java.io.File JavaDoc;
21 import java.io.FileOutputStream JavaDoc;
22 import java.io.FileReader JavaDoc;
23 import java.io.OutputStream JavaDoc;
24 import java.io.PrintStream JavaDoc;
25 import java.io.Reader JavaDoc;
26 import java.io.StringReader JavaDoc;
27 import java.net.URI JavaDoc;
28 import java.util.ArrayList JavaDoc;
29 import java.util.Date JavaDoc;
30 import java.util.HashMap JavaDoc;
31 import java.util.HashSet JavaDoc;
32 import java.util.Iterator JavaDoc;
33 import java.util.List JavaDoc;
34 import java.util.Locale JavaDoc;
35 import java.util.Map JavaDoc;
36 import java.util.Properties JavaDoc;
37 import java.util.Set JavaDoc;
38 import java.util.regex.Matcher JavaDoc;
39 import java.util.regex.Pattern JavaDoc;
40 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
41 import javax.xml.transform.OutputKeys JavaDoc;
42 import javax.xml.transform.Result JavaDoc;
43 import javax.xml.transform.Source JavaDoc;
44 import javax.xml.transform.Transformer JavaDoc;
45 import javax.xml.transform.TransformerFactory JavaDoc;
46 import javax.xml.transform.dom.DOMSource JavaDoc;
47 import javax.xml.transform.stream.StreamResult JavaDoc;
48 import javax.xml.transform.stream.StreamSource JavaDoc;
49 import org.apache.tools.ant.BuildException;
50 import org.apache.tools.ant.Project;
51 import org.apache.tools.ant.Task;
52 import org.w3c.dom.DOMImplementation JavaDoc;
53 import org.w3c.dom.Document JavaDoc;
54 import org.w3c.dom.DocumentType JavaDoc;
55 import org.w3c.dom.Element JavaDoc;
56
57 /**
58  * Creates Ant manual in JavaHelp format.
59  * @author Jesse Glick
60  * @see <a HREF="http://svn.apache.org/repos/asf/ant/sandbox/antlibs/manual4eclipse/src/main/org/apache/ant/manual4eclipse/Manual4EclipseTask.java">Eclipse version</a>
61  */

62 public class MakeManual extends Task {
63
64     private File JavaDoc dir;
65     public void setDir(File JavaDoc d) {
66         dir = d;
67     }
68
69     private File JavaDoc hs;
70     public void setHS(File JavaDoc f) {
71         hs = f;
72     }
73
74     public void execute() throws BuildException {
75         if (dir == null || hs == null) {
76             throw new BuildException();
77         }
78         File JavaDoc antdocs = new File JavaDoc(dir, "ant-docs");
79         if (!antdocs.isDirectory()) {
80             throw new BuildException();
81         }
82         try {
83             String JavaDoc[] stylesheets = {"antmanual.css", "style.css"};
84             for (int i = 0; i < stylesheets.length; i++) {
85                 OutputStream JavaDoc os = new FileOutputStream JavaDoc(new File JavaDoc(antdocs, "stylesheets/" + stylesheets[i]));
86                 try {
87                     PrintStream JavaDoc ps = new PrintStream JavaDoc(os);
88                     ps.println("/* This document was modified on " + new Date JavaDoc() + " by ant.netbeans.org to meet accessibility guidelines. */");
89                     ps.println("@import \"../../../../../../../netbeans/modules/usersguide/ide.css\";");
90                     ps.flush();
91                 } finally {
92                     os.close();
93                 }
94             }
95             Properties JavaDoc taskdefs = new Properties JavaDoc();
96             taskdefs.load(Project.class.getResourceAsStream("/org/apache/tools/ant/taskdefs/defaults.properties"));
97             Properties JavaDoc typedefs = new Properties JavaDoc();
98             typedefs.load(Project.class.getResourceAsStream("/org/apache/tools/ant/types/defaults.properties"));
99             TocItem top = tockify(antdocs, "toc.html", null, null, new HashSet JavaDoc/*<String>*/(), taskdefs.keySet(), typedefs.keySet());
100             writeMapAndToc(top);
101         } catch (Exception JavaDoc x) {
102             throw new BuildException(x);
103         }
104         // XXX delete old TOC.toc and Map.jhm when done
105
}
106
107     private static int depth = 0;
108     private TocItem tockify(File JavaDoc antdocs, String JavaDoc path, String JavaDoc anchor, String JavaDoc linktext, Set JavaDoc/*<String>*/ files, Set JavaDoc/*<String>*/ tasknames, Set JavaDoc/*<String>*/ typenames) throws Exception JavaDoc {
109         String JavaDoc file = anchor != null ? path + "#" + anchor : path;
110         if (!files.add(file)) {
111             return null;
112         }
113         File JavaDoc f = new File JavaDoc(antdocs, path.replace('/', File.separatorChar));
114         if (!f.isFile()) {
115             return null;
116         }
117         String JavaDoc id;
118         String JavaDoc token = anchor != null ? anchor : path.replaceFirst("\\.html$", "").replaceFirst("^.+/", "");
119         String JavaDoc linktextlower = linktext != null ? linktext.toLowerCase(Locale.US) : "";
120         if (tasknames.contains(token)) {
121             id = "org.apache.tools.ant.module.tasks." + token;
122         } else if (tasknames.contains(linktextlower)) {
123             id = "org.apache.tools.ant.module.tasks." + linktextlower;
124         } else if (typenames.contains(token)) {
125             id = "org.apache.tools.ant.module.types." + token;
126         } else if (typenames.contains(linktextlower)) {
127             id = "org.apache.tools.ant.module.types." + linktextlower;
128         } else {
129             id = "org.apache.tools.ant.module.ant-docs." + path.replaceFirst("\\.html$", "").replace('/', '.');
130             if (anchor != null) {
131                 id += "." + anchor;
132             }
133         }
134         String JavaDoc title = linktext != null ? linktext : "Ant 1.7.0 Manual";
135         String JavaDoc log = "";
136         for (int i = 0; i < depth; i++) {
137             log += "\t";
138         }
139         log(log + path + " as " + id + ": \"" + title + "\"");
140         StringBuffer JavaDoc contents = new StringBuffer JavaDoc();
141         Reader JavaDoc r = new FileReader JavaDoc(f);
142         try {
143             int c;
144             while ((c = r.read()) != -1) {
145                 contents.append((char) c);
146             }
147         } finally {
148             r.close();
149         }
150         /*
151         boolean irrelevantForNb =
152                 path.matches("(ide|running|proxy|cover)\\.html|Integration/\\.*") |
153                 (path.equals("install.html") && !"librarydependencies".equals(anchor));
154         if (irrelevantForNb) {
155             title = "(" + title + ")";
156         }
157          */

158         TocItem ti = new TocItem(id, file, title);
159         if (path.matches("(toc|.+list|tutorials)\\.html")) {
160             depth++;
161             Matcher JavaDoc m = Pattern.compile("<a HREF=\"([^\"#]+)(#([^\"]+))?\".*?>(.+?)</a>", Pattern.CASE_INSENSITIVE).matcher(contents);
162             while (m.find()) {
163                 String JavaDoc relurl = m.group(1);
164                 String JavaDoc newanchor = m.group(3);
165                 String JavaDoc newpath = URI.create(path).resolve(relurl).toString();
166                 if (path.equals("coretasklist.html") && newpath.equals("optionaltasklist.html")) {
167                     // Wait until the next link to it.
168
continue;
169                 }
170                 if (path.equals("developlist.html") && newpath.startsWith("tutorial-")) {
171                     // Ditto.
172
continue;
173                 }
174                 String JavaDoc newlinktext = m.group(4).replaceAll("<[iI]>(.+?)</[iI]>", "($1)").replace("&amp;", "&");
175                 TocItem subitem = tockify(antdocs, newpath, newanchor, newlinktext, files, tasknames, typenames);
176                 if (subitem != null) {
177                     ti.subitems.add(subitem);
178                 }
179             }
180             depth--;
181         }
182         return ti;
183     }
184
185     private void writeMapAndToc(TocItem top) throws Exception JavaDoc {
186         Document JavaDoc mapXml = createDocument("map", "-//Sun Microsystems Inc.//DTD JavaHelp Map Version 2.0//EN", "http://java.sun.com/products/javahelp/map_2_0.dtd");
187         mapXml.getDocumentElement().setAttribute("version", "2.0");
188         Document JavaDoc tocXml = createDocument("toc", "-//Sun Microsystems Inc.//DTD JavaHelp TOC Version 2.0//EN", "http://java.sun.com/products/javahelp/toc_2_0.dtd");
189         tocXml.getDocumentElement().setAttribute("version", "2.0");
190         insertTocItem(top, mapXml, tocXml.getDocumentElement(), new HashMap JavaDoc());
191         write(new File JavaDoc(dir, "map.xml"), mapXml);
192         write(new File JavaDoc(dir, "toc.xml"), tocXml);
193     }
194     private static Element JavaDoc insertTocItem(TocItem ti, Document JavaDoc mapXml, Element JavaDoc toc, Map JavaDoc mapEntries) {
195         Element JavaDoc el = toc.getOwnerDocument().createElement("tocitem");
196         if (ti.id != null) {
197             if (mapEntries.containsKey(ti.id) && !mapEntries.get(ti.id).equals(ti.file)) {
198                 throw new IllegalArgumentException JavaDoc("Dupes: " + ti.id + " " + ti.file + " " + mapEntries.get(ti.id));
199             }
200             mapEntries.put(ti.id, ti.file);
201             el.setAttribute("target", ti.id);
202             Element JavaDoc map = mapXml.createElement("mapID");
203             map.setAttribute("target", ti.id);
204             map.setAttribute("url", "ant-docs/" + ti.file);
205             mapXml.getDocumentElement().appendChild(map);
206         }
207         toc.appendChild(el);
208         el.setAttribute("text", ti.text);
209         Iterator JavaDoc it = ti.subitems.iterator();
210         while (it.hasNext()) {
211             insertTocItem((TocItem) it.next(), mapXml, el, mapEntries);
212         }
213         return el;
214     }
215     private static class TocItem {
216         final String JavaDoc id;
217         final String JavaDoc file;
218         final String JavaDoc text;
219         final List JavaDoc subitems = new ArrayList JavaDoc();
220         public TocItem(String JavaDoc id, String JavaDoc file, String JavaDoc text) {
221             assert id != null ^ file == null;
222             assert text != null;
223             this.id = id;
224             this.file = file;
225             this.text = text;
226         }
227     }
228
229     // The below loosely copied from org.openide.xml.XMLUtil.
230

231     private static final String JavaDoc IDENTITY_XSLT_WITH_INDENT =
232             "<xsl:stylesheet version='1.0' " +
233             "xmlns:xsl='http://www.w3.org/1999/XSL/Transform' " +
234             "xmlns:xalan='http://xml.apache.org/xslt' " +
235             "exclude-result-prefixes='xalan'>" +
236             "<xsl:output method='xml' indent='yes' xalan:indent-amount='4'/>" +
237             "<xsl:template match='@*|node()'>" +
238             "<xsl:copy>" +
239             "<xsl:apply-templates select='@*|node()'/>" +
240             "</xsl:copy>" +
241             "</xsl:template>" +
242             "</xsl:stylesheet>";
243     private static void write(File JavaDoc xml, Document JavaDoc doc) throws Exception JavaDoc {
244         OutputStream JavaDoc out = new FileOutputStream JavaDoc(xml);
245         try {
246             Transformer JavaDoc t = TransformerFactory.newInstance().newTransformer(
247                     new StreamSource JavaDoc(new StringReader JavaDoc(IDENTITY_XSLT_WITH_INDENT)));
248             DocumentType JavaDoc dt = doc.getDoctype();
249             if (dt != null) {
250                 String JavaDoc pub = dt.getPublicId();
251                 if (pub != null) {
252                     t.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, pub);
253                 }
254                 t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, dt.getSystemId());
255             }
256             t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
257             Source JavaDoc source = new DOMSource JavaDoc(doc);
258             Result JavaDoc result = new StreamResult JavaDoc(out);
259             t.transform(source, result);
260         } finally {
261             out.close();
262         }
263     }
264
265     private static Document JavaDoc createDocument(String JavaDoc root, String JavaDoc doctypePublicID, String JavaDoc doctypeSystemID) throws Exception JavaDoc {
266         DOMImplementation JavaDoc impl = DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation();
267         DocumentType JavaDoc dtd = null;
268         if (doctypeSystemID != null) {
269             dtd = impl.createDocumentType(root, doctypePublicID, doctypeSystemID);
270         }
271         return impl.createDocument(null, root, dtd);
272     }
273
274 }
275
Popular Tags