KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > caucho > ant > jaxb > SchemaGenerator


1 /*
2  * Copyright (c) 1998-2006 Caucho Technology -- all rights reserved
3  *
4  * This file is part of Resin(R) Open Source
5  *
6  * Each copy or derived work must preserve the copyright notice and this
7  * notice unmodified.
8  *
9  * Resin Open Source is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * Resin Open Source is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
17  * of NON-INFRINGEMENT. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with Resin Open Source; if not, write to the
22  * Free SoftwareFoundation, Inc.
23  * 59 Temple Place, Suite 330
24  * Boston, MA 02111-1307 USA
25  *
26  * @author Emil Ong
27  */

28
29 package com.caucho.ant.jaxb;
30
31 import java.io.*;
32 import java.util.*;
33
34 import javax.xml.stream.*;
35 import javax.xml.transform.dom.*;
36
37 import com.caucho.java.*;
38 import com.caucho.jaxb.*;
39 import com.caucho.loader.*;
40 import com.caucho.vfs.*;
41 import com.caucho.xml.*;
42
43 /**
44  * Command-line tool and ant task to generate Xml Schema from
45  * annotated classes.
46  */

47 public class SchemaGenerator extends org.apache.tools.ant.Task {
48   private List<String JavaDoc> _sourceFiles = new ArrayList<String JavaDoc>();
49   private List<String JavaDoc> _classFiles = new ArrayList<String JavaDoc>();
50   private String JavaDoc _outputDir; // == _destDir + _package
51
private String JavaDoc _destDir;
52   private String JavaDoc _package;
53   private boolean _verbose;
54   private boolean _debug;
55   private boolean _fork;
56
57   /**
58    * For ant.
59    **/

60   public SchemaGenerator()
61   {
62   }
63
64   public SchemaGenerator(String JavaDoc[] args)
65   {
66     for (int i = 0; i < args.length; i++) {
67       if (args[i].equals("-p")) {
68         if (i + 1 == args.length)
69           usage();
70
71         _package = args[++i];
72       }
73       else if (args[i].equals("-d")) {
74         if (i + 1 == args.length)
75           usage();
76
77         _destDir = args[++i];
78       }
79       else {
80         if (args[i].endsWith(".java"))
81           _sourceFiles.add(args[i]);
82         else if (args[i].endsWith(".class"))
83           _classFiles.add(args[i]);
84         else
85           usage();
86       }
87     }
88
89     if (_destDir == null)
90       usage();
91
92     if (_package == null)
93       usage();
94
95     _outputDir = _destDir + File.separator +
96                  _package.replace('.', File.separatorChar);
97   }
98
99   private static void error(String JavaDoc msg)
100   {
101     System.err.print(msg);
102     System.exit(1);
103   }
104
105   private static void error(String JavaDoc msg, Exception JavaDoc e)
106   {
107     System.err.print(msg + ":" );
108     e.printStackTrace();
109     System.exit(1);
110   }
111
112   private static void usage()
113   {
114     error("usage: schema-gen -p <package> -d <output dir> -cp <classpath> " +
115                  "<Java files>");
116   }
117
118   public void setDestdir(String JavaDoc destDir)
119   {
120     _destDir = destDir;
121   }
122
123   /*
124   public void setClasspath(String classpath)
125   {
126     _classpath = classpath;
127   }
128
129   public void setCp(String classpath)
130   {
131     setClasspath(classpath);
132   }
133
134   public void addClasspath(ClassPath classPath)
135   {
136     _classpath = classPath.getPath();
137   }*/

138
139   public void setVerbose(boolean verbose)
140   {
141     _verbose = verbose;
142   }
143
144   public void setDebug(boolean debug)
145   {
146     _debug = debug;
147   }
148
149   public void setFork(boolean fork)
150   {
151     _fork = fork;
152   }
153
154   /**
155    * Executes the ant task.
156    **/

157   public void execute()
158     throws org.apache.tools.ant.BuildException
159   {
160     FileWriter fileWriter = null;
161
162     try {
163       int i = 0;
164       Class JavaDoc[] classes = new Class JavaDoc[_sourceFiles.size() + _classFiles.size()];
165
166       ClassLoader JavaDoc parentLoader = Thread.currentThread().getContextClassLoader();
167       GreedyClassLoader classLoader = new GreedyClassLoader(parentLoader);
168       Thread.currentThread().setContextClassLoader(classLoader);
169
170       if (_sourceFiles.size() > 0) {
171         Path outputDirPath = Vfs.lookup(_outputDir);
172
173         if (outputDirPath.exists()) {
174           if (! outputDirPath.isDirectory())
175             throw new org.apache.tools.ant.BuildException("Output path specified is not a directory: " + outputDirPath);
176         }
177         else if (! outputDirPath.mkdir()) {
178           throw new org.apache.tools.ant.BuildException("Unable to create directory at output path: " + outputDirPath);
179         }
180
181         JavaCompiler compiler = JavaCompiler.create();
182         compiler.setClassDir(outputDirPath);
183         compiler.setSourceDir(Vfs.lookup());
184
185         LineMap lineMap = new LineMap();
186
187         for (String JavaDoc sourceFile : _sourceFiles)
188           compiler.compile(sourceFile, lineMap);
189
190         classLoader.loadClassFiles(new File(_outputDir));
191       }
192
193       /* XXX: TCK doesn't use classes, but schemagen.sh allows them.
194       for (String classFile : _classFiles)
195         classes[i++] = classLoader.loadClassFile(classFile);
196         */

197
198       JAXBContextImpl context =
199         new JAXBContextImpl(classLoader.getLoadedClasses(), null);
200       
201       XMLOutputFactory factory = XMLOutputFactory.newInstance();
202
203       DOMResult result = new DOMResult();
204       XMLStreamWriter out = factory.createXMLStreamWriter(result);
205
206       out.writeStartDocument("UTF-8", "1.0");
207       context.generateSchemaWithoutHeader(out);
208       out.close();
209
210       fileWriter = new FileWriter(_outputDir + "/schema1.xsd");
211
212       XmlPrinter xmlPrinter = new XmlPrinter(fileWriter);
213       xmlPrinter.setPrintDeclaration(true);
214       xmlPrinter.setEncoding("UTF-8");
215       xmlPrinter.setStandalone("yes");
216       xmlPrinter.printPrettyXml(result.getNode());
217     }
218     catch (Exception JavaDoc e) {
219       throw new org.apache.tools.ant.BuildException(e);
220     }
221     finally {
222       try {
223         if (fileWriter != null)
224           fileWriter.close();
225       }
226       catch (IOException e) {
227         throw new org.apache.tools.ant.BuildException(e);
228       }
229     }
230   }
231   
232   public static void main(String JavaDoc[] args)
233   {
234     if (args.length < 1)
235       usage();
236
237     try {
238       new SchemaGenerator(args).execute();
239     }
240     catch (org.apache.tools.ant.BuildException e) {
241       error("Unable to generate schema", e);
242     }
243   }
244
245   public static class ClassPath {
246     private List<PathElement> _pathElements = new ArrayList<PathElement>();
247     private String JavaDoc _path;
248
249     public String JavaDoc getPath()
250     {
251       return _path;
252     }
253
254     public void setPath(String JavaDoc path)
255     {
256       _path = path;
257
258       String JavaDoc[] elements = _path.split(":");
259
260       for (String JavaDoc element : elements)
261         _pathElements.add(new PathElement(element));
262     }
263
264     public List<PathElement> getPathElements()
265     {
266       return _pathElements;
267     }
268
269     public void addPathelement(PathElement pathElement)
270     {
271       _pathElements.add(pathElement);
272     }
273
274     public static class PathElement {
275       private String JavaDoc _path;
276
277       public PathElement()
278       {
279       }
280
281       public PathElement(String JavaDoc path)
282       {
283         _path = path;
284       }
285
286       public String JavaDoc getPath()
287       {
288         return _path;
289       }
290
291       public void setPath(String JavaDoc path)
292       {
293         _path = path;
294       }
295     }
296   }
297 }
298
299
300
Popular Tags