Salome HOME
54aaeb826546dbb1ae15e79b5e93bfa87cf9775e
[tools/siman.git] / Workspace / DaoGenerator / src / org / siman / generator / DaoGenerator.java
1 /*****************************************************************************
2  * Company         EURIWARE
3  * Application     SIMAN
4  * File            $Id$ 
5  * Creation date   15.10.2012
6  * @author         $Author$
7  * @version        $Revision$
8  *****************************************************************************/
9
10 package org.siman.generator;
11
12 import java.io.File;
13 import java.io.FileWriter;
14 import java.io.IOException;
15 import java.util.ResourceBundle;
16
17 import java.io.StringWriter;
18 import java.util.ArrayList;
19 import java.util.Date;
20 import java.util.List;
21 import java.util.Properties;
22
23 import javax.xml.parsers.DocumentBuilder;
24 import javax.xml.parsers.DocumentBuilderFactory;
25 import javax.xml.parsers.ParserConfigurationException;
26
27 import org.apache.velocity.Template;
28 import org.apache.velocity.VelocityContext;
29 import org.apache.velocity.app.Velocity;
30 import org.apache.velocity.app.VelocityEngine;
31 import org.apache.velocity.exception.MethodInvocationException;
32 import org.apache.velocity.exception.ParseErrorException;
33 import org.apache.velocity.exception.ResourceNotFoundException;
34 import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
35 import org.w3c.dom.Document;
36 import org.w3c.dom.Element;
37 import org.w3c.dom.NodeList;
38 import org.xml.sax.SAXException;
39
40 /**
41  * @author rkv
42  * 
43  */
44 public class DaoGenerator {
45
46         final static String SRC_CTX = "datasource.context";
47         final static String SRC_PATH = "source.path";
48         final static String OUT_PATH = "output.path";
49         final static String FACTORY_ID = "factory.id";
50         final static String DAO_PACKAGE = "DAOPackage";
51         final static String ENTITY_PACKAGE = "EntityPackage";
52         final static String ENTITY_CLASS = "EntityClass";
53         final static String DAO_BEAN = "beanName";
54         final static String DAO_CLASS = "implClass";
55
56         /**
57          * @param args
58          * @throws ParserConfigurationException
59          * @throws IOException
60          * @throws SAXException
61          */
62         public static void main(String[] args) throws ParserConfigurationException,
63                         SAXException, IOException {
64                 ResourceBundle bundle = ResourceBundle.getBundle("config");
65                 String srcCtx = bundle.getString(SRC_CTX);
66                 String srcPath = bundle.getString(SRC_PATH);
67                 String outPath = bundle.getString(OUT_PATH);
68                 String sessionFactoryId = bundle.getString(FACTORY_ID);
69
70                 // Velocity initialization
71                 Properties veloProps = new Properties();
72                 veloProps.setProperty(VelocityEngine.RESOURCE_LOADER, "classpath");
73                 veloProps.setProperty("classpath." + VelocityEngine.RESOURCE_LOADER
74                                 + ".class", ClasspathResourceLoader.class.getName());
75                 Velocity.init(veloProps);
76
77                 List<Properties> daos = new ArrayList<Properties>();
78
79                 // Parse spring context config file
80                 DocumentBuilderFactory dfactory = javax.xml.parsers.DocumentBuilderFactory
81                                 .newInstance();
82                 DocumentBuilder dBuilder = dfactory.newDocumentBuilder();
83                 Document ctxDoc = dBuilder.parse(srcCtx);
84                 System.out.println("Looking for an element with id = "
85                                 + sessionFactoryId);
86                 Element sessionFactory;
87                 String resourceName;
88                 NodeList beans = ctxDoc.getElementsByTagName("bean");
89                 for (int k = 0; k < beans.getLength(); k++) {
90                         sessionFactory = (Element) beans.item(k);
91                         if (sessionFactoryId.equalsIgnoreCase(sessionFactory
92                                         .getAttribute("id"))) {
93                                 NodeList props = sessionFactory
94                                                 .getElementsByTagName("property");
95                                 Element mappings, mappingFile;
96                                 for (int i = 0; i < props.getLength(); i++) {
97                                         mappings = (Element) props.item(i);
98                                         if ("mappingResources".equalsIgnoreCase(mappings
99                                                         .getAttribute("name"))) {
100                                                 NodeList mappingFiles = mappings
101                                                                 .getElementsByTagName("value");
102                                                 for (int j = 0; j < mappingFiles.getLength(); j++) {
103                                                         mappingFile = (Element) mappingFiles.item(j);
104                                                         resourceName = mappingFile.getTextContent().trim();
105                                                         System.out.println("Processing resource: "
106                                                                         + resourceName);
107                                                         processMappingResource(daos, dfactory,
108                                                                         resourceName, srcPath, outPath);
109                                                 }
110                                         }
111                                 }
112                                 generateDaoContext(daos, outPath);
113                         }
114                 }
115         }
116
117         /**
118          * @param daos
119          * @param dfactory
120          * @param resourceName
121          * @param outPath
122          * @param srcPath
123          * @throws ParserConfigurationException
124          * @throws IOException
125          * @throws SAXException
126          */
127         private static void processMappingResource(List<Properties> daos,
128                         DocumentBuilderFactory dfactory, String resourceName,
129                         String srcPath, String outPath)
130                         throws ParserConfigurationException, SAXException, IOException {
131                 // dfactory.setValidating(false);
132                 // dfactory.setFeature("http://xml.org/sax/features/namespaces", false);
133                 // dfactory.setFeature("http://xml.org/sax/features/validation", false);
134                 // // parser.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation", schemaLocation);
135                 // dfactory.setFeature("http://apache.org/xml/features/validation/schema", false);
136                 // dfactory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
137                 dfactory
138                                 .setFeature(
139                                                 "http://apache.org/xml/features/nonvalidating/load-external-dtd",
140                                                 false);
141                 // dfactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
142                 // dfactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
143
144                 DocumentBuilder dBuilder = dfactory.newDocumentBuilder();
145                 Document resDoc = dBuilder.parse(srcPath + resourceName);
146                 processClasses(daos, resDoc, "class", outPath);
147                 processClasses(daos, resDoc, "union-subclass", outPath);
148                 processClasses(daos, resDoc, "joined-subclass", outPath);
149         }
150
151         /**
152          * @param daos
153          * @param resDoc
154          * @param string
155          * @param outPath
156          */
157         private static void processClasses(List<Properties> daos, Document resDoc,
158                         String elementName, String outPath) {
159                 NodeList classes = resDoc.getElementsByTagName(elementName);
160                 Element classElem;
161                 for (int i = 0; i < classes.getLength(); i++) {
162                         classElem = (Element) classes.item(i);
163                         String abstractAttr = "";
164                         if ("true".equalsIgnoreCase(classElem.getAttribute("abstract")
165                                         .trim())) {
166                                 abstractAttr = ": abstract = true";
167                         }
168                         System.out.println("    " + elementName + ": "
169                                         + classElem.getAttribute("name") + abstractAttr);
170                         if (!"true".equalsIgnoreCase(classElem.getAttribute("abstract")
171                                         .trim())) {
172                                 String entityName = classElem.getAttribute("name");
173                                 String itfClass = entityName.replace(".dal.bo.", ".dal.dao.")
174                                                 + "DAO";
175                                 String implClass = entityName.replace(".dal.bo.", ".dal.dao.")
176                                                 + "DAOImpl";
177                                 System.out.println("    Generating DAO interface class: "
178                                                 + itfClass);
179                                 generateClass(entityName, itfClass, "templates/DAO.java.vm",
180                                                 outPath);
181                                 System.out.println("    Generating DAO implementation class: "
182                                                 + implClass);
183                                 generateClass(entityName, implClass,
184                                                 "templates/DAOImpl.java.vm", outPath);
185                                 Properties dao = new Properties();
186                                 String beanName = itfClass
187                                                 .substring(itfClass.lastIndexOf('.') + 1);
188                                 beanName = beanName.substring(0, 1).toLowerCase()
189                                                 + beanName.substring(1);
190                                 dao.put(DAO_BEAN, beanName);
191                                 dao.put(DAO_CLASS, implClass);
192                                 daos.add(dao);
193                         }
194                 }
195         }
196
197         /**
198          * @param entityName
199          * @param string
200          * @param outPath
201          */
202         private static void generateClass(String entityName, String className,
203                         String templatePath, String outPath) {
204                 String resultPath = outPath + className.replace(".", "/") + ".java";
205                 System.out.println("Generating file: " + resultPath);
206                 VelocityContext context = new VelocityContext();
207
208                 context.put(DAO_PACKAGE, className.substring(0, className
209                                 .lastIndexOf('.')));
210                 context.put(ENTITY_PACKAGE, entityName.substring(0, entityName
211                                 .lastIndexOf('.')));
212                 context.put(ENTITY_CLASS, entityName.substring(entityName
213                                 .lastIndexOf('.') + 1));
214
215                 generateFile(context, templatePath, resultPath);
216         }
217
218         /**
219          * @param entityName
220          * @param string
221          * @param outPath
222          */
223         private static void generateDaoContext(List<Properties> daos, String outPath) {
224                 String resultPath = outPath + "spring/daoContext.xml";
225                 String templatePath = "templates/daoContext.xml.vm";
226                 System.out.println("Generating file: " + resultPath);
227                 VelocityContext context = new VelocityContext();
228
229                 context.put("daos", daos);
230
231                 generateFile(context, templatePath, resultPath);
232         }
233
234         /**
235          * @param context
236          * @param templatePath
237          * @param resultPath
238          */
239         private static void generateFile(VelocityContext context,
240                         String templatePath, String resultPath) {
241                 Template template = null;
242                 context.put("date", new Date());
243
244                 try {
245                         template = Velocity.getTemplate(templatePath);
246                 } catch (ResourceNotFoundException rnfe) {
247                         // couldn't find the template
248                         System.out.println(rnfe.getMessage());
249                 } catch (ParseErrorException pee) {
250                         // syntax error: problem parsing the template
251                         System.out.println(pee.getMessage());
252                 } catch (MethodInvocationException mie) {
253                         // something invoked in the template
254                         // threw an exception
255                         System.out.println(mie.getMessage());
256                 } catch (Exception e) {
257                         System.out.println(e.getMessage());
258                 }
259
260                 try {
261                         FileWriter fw = new FileWriter(resultPath);
262                         template.merge(context, fw);
263                         fw.close();
264                 } catch (IOException e) {
265                         e.printStackTrace();
266                 }
267         }
268 }