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