1   /**
2    * Copyright (c) 2000-2008 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portal.tools.servicebuilder;
24  
25  import com.liferay.portal.freemarker.FreeMarkerUtil;
26  import com.liferay.portal.kernel.util.ArrayUtil;
27  import com.liferay.portal.kernel.util.ArrayUtil_IW;
28  import com.liferay.portal.kernel.util.GetterUtil;
29  import com.liferay.portal.kernel.util.PropertiesUtil;
30  import com.liferay.portal.kernel.util.StringMaker;
31  import com.liferay.portal.kernel.util.StringPool;
32  import com.liferay.portal.kernel.util.StringUtil;
33  import com.liferay.portal.kernel.util.StringUtil_IW;
34  import com.liferay.portal.kernel.util.Validator;
35  import com.liferay.portal.model.ModelHintsUtil;
36  import com.liferay.portal.tools.SourceFormatter;
37  import com.liferay.portal.util.DocumentUtil;
38  import com.liferay.util.FileUtil;
39  import com.liferay.util.SetUtil;
40  import com.liferay.util.TextFormatter;
41  import com.liferay.util.Time;
42  import com.liferay.util.log4j.Log4JUtil;
43  import com.liferay.util.xml.XMLFormatter;
44  
45  import com.thoughtworks.qdox.JavaDocBuilder;
46  import com.thoughtworks.qdox.model.JavaClass;
47  import com.thoughtworks.qdox.model.JavaMethod;
48  import com.thoughtworks.qdox.model.JavaParameter;
49  import com.thoughtworks.qdox.model.Type;
50  
51  import de.hunsicker.io.FileFormat;
52  import de.hunsicker.jalopy.Jalopy;
53  import de.hunsicker.jalopy.storage.Convention;
54  import de.hunsicker.jalopy.storage.ConventionKeys;
55  import de.hunsicker.jalopy.storage.Environment;
56  
57  import freemarker.ext.beans.BeansWrapper;
58  import freemarker.template.TemplateHashModel;
59  import freemarker.template.TemplateModelException;
60  
61  import java.io.BufferedReader;
62  import java.io.File;
63  import java.io.FileNotFoundException;
64  import java.io.FileReader;
65  import java.io.IOException;
66  import java.io.StringReader;
67  
68  import java.util.ArrayList;
69  import java.util.HashMap;
70  import java.util.Iterator;
71  import java.util.LinkedHashSet;
72  import java.util.List;
73  import java.util.Map;
74  import java.util.Properties;
75  import java.util.Set;
76  import java.util.TreeMap;
77  import java.util.TreeSet;
78  
79  import org.dom4j.Document;
80  import org.dom4j.DocumentException;
81  import org.dom4j.DocumentHelper;
82  import org.dom4j.Element;
83  
84  /**
85   * <a href="ServiceBuilder.java.html"><b><i>View Source</i></b></a>
86   *
87   * @author Brian Wing Shun Chan
88   * @author Charles May
89   * @author Alexander Chow
90   * @author Harry Mark
91   * @author Tariq Dweik
92   * @author Glenn Powell
93   *
94   */
95  public class ServiceBuilder {
96  
97      public static void main(String[] args) {
98          ClassLoader classLoader = ClassLoader.getSystemClassLoader();
99  
100         Log4JUtil.configureLog4J(
101             classLoader.getResource("META-INF/portal-log4j.xml"));
102         Log4JUtil.configureLog4J(
103             classLoader.getResource("META-INF/portal-log4j-ext.xml"));
104 
105         ServiceBuilder serviceBuilder = null;
106 
107         if (args.length == 7) {
108             String fileName = args[0];
109             String hbmFileName = args[1];
110             String modelHintsFileName = args[2];
111             String springFileName = args[3];
112             String springDataSourceFileName = "";
113             String apiDir = args[5];
114             String implDir = "src";
115             String jsonFileName = args[6];
116             String remotingFileName = "../tunnel-web/docroot/WEB-INF/remoting-servlet.xml";
117             String sqlDir = "../sql";
118             String sqlFileName = "portal-tables.sql";
119             String sqlIndexesFileName = "indexes.sql";
120             String sqlIndexesPropertiesFileName = "indexes.properties";
121             String sqlSequencesFileName = "sequences.sql";
122             boolean autoNamespaceTables = false;
123             String baseModelImplPackage = "com.liferay.portal.model.impl";
124             String basePersistencePackage = "com.liferay.portal.service.persistence";
125             String beanLocatorUtilPackage = "com.liferay.portal.kernel.bean";
126             String principalBeanPackage = "com.liferay.portal.service.impl";
127             String propsUtilPackage = "com.liferay.portal.util";
128             String springHibernatePackage = "com.liferay.portal.spring.hibernate";
129             String springUtilPackage = "com.liferay.portal.spring.util";
130             String testDir = "";
131 
132             serviceBuilder = new ServiceBuilder(
133                 fileName, hbmFileName, modelHintsFileName, springFileName,
134                 springDataSourceFileName, apiDir, implDir, jsonFileName,
135                 remotingFileName, sqlDir, sqlFileName, sqlIndexesFileName,
136                 sqlIndexesPropertiesFileName, sqlSequencesFileName,
137                 autoNamespaceTables, baseModelImplPackage,
138                 basePersistencePackage, beanLocatorUtilPackage,
139                 principalBeanPackage, propsUtilPackage, springHibernatePackage,
140                 springUtilPackage, testDir);
141         }
142         else if (args.length == 0) {
143             String fileName = System.getProperty("service.input.file");
144             String hbmFileName = System.getProperty("service.hbm.file");
145             String modelHintsFileName = System.getProperty("service.model.hints.file");
146             String springFileName = System.getProperty("service.spring.file");
147             String springDataSourceFileName = System.getProperty("service.spring.data.source.file");
148             String apiDir = System.getProperty("service.api.dir");
149             String implDir = System.getProperty("service.impl.dir");
150             String jsonFileName = System.getProperty("service.json.file");
151             String remotingFileName = System.getProperty("service.remoting.file");
152             String sqlDir = System.getProperty("service.sql.dir");
153             String sqlFileName = System.getProperty("service.sql.file");
154             String sqlIndexesFileName = System.getProperty("service.sql.indexes.file");
155             String sqlIndexesPropertiesFileName = System.getProperty("service.sql.indexes.properties.file");
156             String sqlSequencesFileName = System.getProperty("service.sql.sequences.file");
157             boolean autoNamespaceTables = GetterUtil.getBoolean(System.getProperty("service.auto.namespace.tables"));
158             String baseModelImplPackage = System.getProperty("service.base.model.impl.package");
159             String basePersistencePackage = System.getProperty("service.base.persistence.package");
160             String beanLocatorUtilPackage = System.getProperty("service.bean.locator.util.package");
161             String principalBeanPackage = System.getProperty("service.principal.bean.package");
162             String propsUtilPackage = System.getProperty("service.props.util.package");
163             String springHibernatePackage = System.getProperty("service.spring.hibernate.package");
164             String springUtilPackage = System.getProperty("service.spring.util.package");
165             String testDir = System.getProperty("service.test.dir");
166 
167             serviceBuilder = new ServiceBuilder(
168                 fileName, hbmFileName, modelHintsFileName, springFileName,
169                 springDataSourceFileName, apiDir, implDir, jsonFileName,
170                 remotingFileName, sqlDir, sqlFileName, sqlIndexesFileName,
171                 sqlIndexesPropertiesFileName, sqlSequencesFileName,
172                 autoNamespaceTables, baseModelImplPackage,
173                 basePersistencePackage, beanLocatorUtilPackage,
174                 principalBeanPackage, propsUtilPackage, springHibernatePackage,
175                 springUtilPackage, testDir);
176         }
177 
178         if (serviceBuilder == null) {
179             System.out.println(
180                 "Please set these required system properties. Sample values are:\n" +
181                 "\n" +
182                 "\t-Dservice.input.file=${service.file}\n" +
183                 "\t-Dservice.hbm.file=src/META-INF/portal-hbm.xml\n" +
184                 "\t-Dservice.model.hints.file=src/META-INF/portal-model-hints.xml\n" +
185                 "\t-Dservice.spring.file=src/META-INF/portal-spring.xml\n" +
186                 "\t-Dservice.api.dir=${project.dir}/portal-service/src\n" +
187                 "\t-Dservice.impl.dir=src\n" +
188                 "\t-Dservice.json.file=${project.dir}/portal-web/docroot/html/js/liferay/service_unpacked.js\n" +
189                 "\t-Dservice.remoting.file=${project.dir}/tunnel-web/docroot/WEB-INF/remoting-servlet.xml\n" +
190                 "\t-Dservice.sql.dir=../sql\n" +
191                 "\t-Dservice.sql.file=portal-tables.sql\n" +
192                 "\t-Dservice.sql.indexes.file=indexes.sql\n" +
193                 "\t-Dservice.sql.indexes.properties.file=indexes.properties\n" +
194                 "\t-Dservice.sql.sequences.file=sequences.sql\n" +
195                 "\t-Dservice.base.model.impl.package=com.liferay.portal.model.impl\n" +
196                 "\t-Dservice.base.persistence.package=com.liferay.portal.service.persistence\n" +
197                 "\t-Dservice.bean.locator.util.package=com.liferay.portal.kernel.bean\n" +
198                 "\t-Dservice.principal.bean.package=com.liferay.portal.service.impl\n" +
199                 "\t-Dservice.props.util.package=com.liferay.portal.util\n" +
200                 "\t-Dservice.spring.hibernate.package=com.liferay.portal.spring.hibernate\n" +
201                 "\t-Dservice.spring.util.package=com.liferay.portal.spring.util\n" +
202                 "\n" +
203                 "You can also customize the generated code by overriding the default templates with these optional properties:\n" +
204                 "\n" +
205                 "\t-Dservice.tpl.bad_column_names=" + _TPL_ROOT + "bad_column_names.txt\n"+
206                 "\t-Dservice.tpl.bad_table_names=" + _TPL_ROOT + "bad_table_names.txt\n"+
207                 "\t-Dservice.tpl.base_mode_impl=" + _TPL_ROOT + "base_mode_impl.ftl\n"+
208                 "\t-Dservice.tpl.base_persistence=" + _TPL_ROOT + "base_persistence.ftl\n"+
209                 "\t-Dservice.tpl.bean_locator_util=" + _TPL_ROOT + "bean_locator_util.ftl\n"+
210                 "\t-Dservice.tpl.copyright.txt=copyright.txt\n"+
211                 "\t-Dservice.tpl.dynamic_dialect=" + _TPL_ROOT + "dynamic_dialect.ftl\n"+
212                 "\t-Dservice.tpl.ejb_pk=" + _TPL_ROOT + "ejb_pk.ftl\n"+
213                 "\t-Dservice.tpl.exception=" + _TPL_ROOT + "exception.ftl\n"+
214                 "\t-Dservice.tpl.extended_model=" + _TPL_ROOT + "extended_model.ftl\n"+
215                 "\t-Dservice.tpl.extended_model_impl=" + _TPL_ROOT + "extended_model_impl.ftl\n"+
216                 "\t-Dservice.tpl.finder=" + _TPL_ROOT + "finder.ftl\n"+
217                 "\t-Dservice.tpl.finder_cache=" + _TPL_ROOT + "finder_cache.ftl\n"+
218                 "\t-Dservice.tpl.finder_util=" + _TPL_ROOT + "finder_util.ftl\n"+
219                 "\t-Dservice.tpl.hbm_xml=" + _TPL_ROOT + "hbm_xml.ftl\n"+
220                 "\t-Dservice.tpl.hibernate_configuration=" + _TPL_ROOT + "hibernate_configuration.ftl\n"+
221                 "\t-Dservice.tpl.hibernate_util=" + _TPL_ROOT + "hibernate_util.ftl\n"+
222                 "\t-Dservice.tpl.json_js=" + _TPL_ROOT + "json_js.ftl\n"+
223                 "\t-Dservice.tpl.json_js_method=" + _TPL_ROOT + "json_js_method.ftl\n"+
224                 "\t-Dservice.tpl.model=" + _TPL_ROOT + "model.ftl\n"+
225                 "\t-Dservice.tpl.model_hints_xml=" + _TPL_ROOT + "model_hints_xml.ftl\n"+
226                 "\t-Dservice.tpl.model_impl=" + _TPL_ROOT + "model_impl.ftl\n"+
227                 "\t-Dservice.tpl.model_soap=" + _TPL_ROOT + "model_soap.ftl\n"+
228                 "\t-Dservice.tpl.persistence=" + _TPL_ROOT + "persistence.ftl\n"+
229                 "\t-Dservice.tpl.persistence_impl=" + _TPL_ROOT + "persistence_impl.ftl\n"+
230                 "\t-Dservice.tpl.persistence_util=" + _TPL_ROOT + "persistence_util.ftl\n"+
231                 "\t-Dservice.tpl.principal_bean=" + _TPL_ROOT + "principal_bean.ftl\n"+
232                 "\t-Dservice.tpl.props=" + _TPL_ROOT + "props.ftl\n"+
233                 "\t-Dservice.tpl.props_util=" + _TPL_ROOT + "props_util.ftl\n"+
234                 "\t-Dservice.tpl.remoting_xml=" + _TPL_ROOT + "remoting_xml.ftl\n"+
235                 "\t-Dservice.tpl.service=" + _TPL_ROOT + "service.ftl\n"+
236                 "\t-Dservice.tpl.service_base_impl=" + _TPL_ROOT + "service_base_impl.ftl\n"+
237                 "\t-Dservice.tpl.service_factory=" + _TPL_ROOT + "service_factory.ftl\n"+
238                 "\t-Dservice.tpl.service_http=" + _TPL_ROOT + "service_http.ftl\n"+
239                 "\t-Dservice.tpl.service_impl=" + _TPL_ROOT + "service_impl.ftl\n"+
240                 "\t-Dservice.tpl.service_json=" + _TPL_ROOT + "service_json.ftl\n"+
241                 "\t-Dservice.tpl.service_json_serializer=" + _TPL_ROOT + "service_json_serializer.ftl\n"+
242                 "\t-Dservice.tpl.service_soap=" + _TPL_ROOT + "service_soap.ftl\n"+
243                 "\t-Dservice.tpl.service_util=" + _TPL_ROOT + "service_util.ftl\n"+
244                 "\t-Dservice.tpl.spring_data_source_xml=" + _TPL_ROOT + "spring_data_source_xml.ftl\n"+
245                 "\t-Dservice.tpl.spring_util=" + _TPL_ROOT + "spring_util.ftl\n"+
246                 "\t-Dservice.tpl.spring_xml=" + _TPL_ROOT + "spring_xml.ftl\n"+
247                 "\t-Dservice.tpl.spring_xml_session=" + _TPL_ROOT + "spring_xml_session.ftl");
248         }
249     }
250 
251     public static void writeFile(File file, String content) throws IOException {
252         writeFile(file, content, null);
253     }
254 
255     public static void writeFile(
256             File file, String content, Map<String, Object> jalopySettings)
257         throws IOException {
258 
259         String packagePath = _getPackagePath(file);
260 
261         String className = file.getName();
262 
263         className = className.substring(0, className.length() - 5);
264 
265         content = SourceFormatter.stripImports(content, packagePath, className);
266 
267         File tempFile = new File("ServiceBuilder.temp");
268 
269         FileUtil.write(tempFile, content);
270 
271         // Beautify
272 
273         StringBuffer sb = new StringBuffer();
274 
275         Jalopy jalopy = new Jalopy();
276 
277         jalopy.setFileFormat(FileFormat.UNIX);
278         jalopy.setInput(tempFile);
279         jalopy.setOutput(sb);
280 
281         try {
282             Jalopy.setConvention("../tools/jalopy.xml");
283         }
284         catch (FileNotFoundException fnne) {
285         }
286 
287         try {
288             Jalopy.setConvention("../../misc/jalopy.xml");
289         }
290         catch (FileNotFoundException fnne) {
291         }
292 
293         if (jalopySettings == null) {
294             jalopySettings = new HashMap<String, Object>();
295         }
296 
297         Environment env = Environment.getInstance();
298 
299         // Author
300 
301         String author = GetterUtil.getString(
302             (String)jalopySettings.get("author"), "Brian Wing Shun Chan");
303 
304         env.set("author", author);
305 
306         // File name
307 
308         env.set("fileName", file.getName());
309 
310         Convention convention = Convention.getInstance();
311 
312         String classMask =
313             "/**\n" +
314             " * <a href=\"$fileName$.html\"><b><i>View Source</i></b></a>\n" +
315             " *\n" +
316             " * @author $author$\n" +
317             " *\n" +
318             "*/";
319 
320         convention.put(
321             ConventionKeys.COMMENT_JAVADOC_TEMPLATE_CLASS,
322             env.interpolate(classMask));
323 
324         convention.put(
325             ConventionKeys.COMMENT_JAVADOC_TEMPLATE_INTERFACE,
326             env.interpolate(classMask));
327 
328         jalopy.format();
329 
330         String newContent = sb.toString();
331 
332         /*
333         // Remove blank lines after try {
334 
335         newContent = StringUtil.replace(newContent, "try {\n\n", "try {\n");
336 
337         // Remove blank lines after ) {
338 
339         newContent = StringUtil.replace(newContent, ") {\n\n", ") {\n");
340 
341         // Remove blank lines empty braces { }
342 
343         newContent = StringUtil.replace(newContent, "\n\n\t}", "\n\t}");
344 
345         // Add space to last }
346 
347         newContent = newContent.substring(0, newContent.length() - 2) + "\n\n}";
348         */
349 
350         // Write file if and only if the file has changed
351 
352         String oldContent = null;
353 
354         if (file.exists()) {
355 
356             // Read file
357 
358             oldContent = FileUtil.read(file);
359 
360             // Keep old version number
361 
362             int x = oldContent.indexOf("@version $Revision:");
363 
364             if (x != -1) {
365                 int y = oldContent.indexOf("$", x);
366                 y = oldContent.indexOf("$", y + 1);
367 
368                 String oldVersion = oldContent.substring(x, y + 1);
369 
370                 newContent = StringUtil.replace(
371                     newContent, "@version $Rev: $", oldVersion);
372             }
373         }
374         else {
375             newContent = StringUtil.replace(
376                 newContent, "@version $Rev: $", "@version $Revision: 1.183 $");
377         }
378 
379         if (oldContent == null || !oldContent.equals(newContent)) {
380             FileUtil.write(file, newContent);
381 
382             System.out.println("Writing " + file);
383 
384             // Workaround for bug with XJavaDoc
385 
386             file.setLastModified(
387                 System.currentTimeMillis() - (Time.SECOND * 5));
388         }
389 
390         tempFile.deleteOnExit();
391     }
392 
393     public ServiceBuilder(
394         String fileName, String hbmFileName, String modelHintsFileName,
395         String springFileName, String springDataSourceFileName, String apiDir,
396         String implDir, String jsonFileName, String remotingFileName,
397         String sqlDir, String sqlFileName, String sqlIndexesFileName,
398         String sqlIndexesPropertiesFileName, String sqlSequencesFileName,
399         boolean autoNamespaceTables, String baseModelImplPackage,
400         String basePersistencePackage, String beanLocatorUtilPackage,
401         String principalBeanPackage, String propsUtilPackage,
402         String springHibernatePackage, String springUtilPackage,
403         String testDir) {
404 
405         new ServiceBuilder(
406             fileName, hbmFileName, modelHintsFileName, springFileName,
407             springDataSourceFileName, apiDir, implDir, jsonFileName,
408             remotingFileName, sqlDir, sqlFileName, sqlIndexesFileName,
409             sqlIndexesPropertiesFileName, sqlSequencesFileName,
410             autoNamespaceTables, baseModelImplPackage, basePersistencePackage,
411             beanLocatorUtilPackage, principalBeanPackage, propsUtilPackage,
412             springHibernatePackage, springUtilPackage, testDir, true);
413     }
414 
415     public ServiceBuilder(
416         String fileName, String hbmFileName, String modelHintsFileName,
417         String springFileName, String springDataSourceFileName, String apiDir,
418         String implDir, String jsonFileName, String remotingFileName,
419         String sqlDir, String sqlFileName, String sqlIndexesFileName,
420         String sqlIndexesPropertiesFileName, String sqlSequencesFileName,
421         boolean autoNamespaceTables, String baseModelImplPackage,
422         String basePersistencePackage, String beanLocatorUtilPackage,
423         String principalBeanPackage, String propsUtilPackage,
424         String springHibernatePackage, String springUtilPackage, String testDir,
425         boolean build) {
426 
427         _tplBadColumnNames = _getTplProperty(
428             "bad_column_names", _tplBadColumnNames);
429         _tplBadTableNames = _getTplProperty(
430             "bad_table_names", _tplBadTableNames);
431         _tplBaseModeImpl = _getTplProperty("base_mode_impl", _tplBaseModeImpl);
432         _tplBasePersistence = _getTplProperty(
433             "base_persistence", _tplBasePersistence);
434         _tplBeanLocatorUtil = _getTplProperty(
435             "bean_locator_util", _tplBeanLocatorUtil);
436         _tplDynamicDialect = _getTplProperty(
437             "dynamic_dialect", _tplDynamicDialect);
438         _tplEjbPk = _getTplProperty("ejb_pk", _tplEjbPk);
439         _tplException = _getTplProperty("exception", _tplException);
440         _tplExtendedModel = _getTplProperty(
441             "extended_model", _tplExtendedModel);
442         _tplExtendedModelImpl = _getTplProperty(
443             "extended_model_impl", _tplExtendedModelImpl);
444         _tplFinder = _getTplProperty("finder", _tplFinder);
445         _tplFinderCache = _getTplProperty("finder_cache", _tplFinderCache);
446         _tplFinderUtil = _getTplProperty("finder_util", _tplFinderUtil);
447         _tplHbmXml = _getTplProperty("hbm_xml", _tplHbmXml);
448         _tplHibernateConfiguration = _getTplProperty(
449             "hibernate_configuration", _tplHibernateConfiguration);
450         _tplHibernateUtil = _getTplProperty(
451             "hibernate_util", _tplHibernateUtil);
452         _tplJsonJs = _getTplProperty("json_js", _tplJsonJs);
453         _tplJsonJsMethod = _getTplProperty("json_js_method", _tplJsonJsMethod);
454         _tplModel = _getTplProperty("model", _tplModel);
455         _tplModelHintsXml = _getTplProperty(
456             "model_hints_xml", _tplModelHintsXml);
457         _tplModelImpl = _getTplProperty("model_impl", _tplModelImpl);
458         _tplModelSoap = _getTplProperty("model_soap", _tplModelSoap);
459         _tplPersistence = _getTplProperty("persistence", _tplPersistence);
460         _tplPersistenceImpl = _getTplProperty(
461             "persistence_impl", _tplPersistenceImpl);
462         _tplPersistenceUtil = _getTplProperty(
463             "persistence_util", _tplPersistenceUtil);
464         _tplPrincipalBean = _getTplProperty(
465             "principal_bean", _tplPrincipalBean);
466         _tplProps = _getTplProperty("props", _tplProps);
467         _tplPropsUtil = _getTplProperty("props_util", _tplPropsUtil);
468         _tplRemotingXml = _getTplProperty("remoting_xml", _tplRemotingXml);
469         _tplService = _getTplProperty("service", _tplService);
470         _tplServiceBaseImpl = _getTplProperty(
471             "service_base_impl", _tplServiceBaseImpl);
472         _tplServiceFactory = _getTplProperty(
473             "service_factory", _tplServiceFactory);
474         _tplServiceHttp = _getTplProperty("service_http", _tplServiceHttp);
475         _tplServiceImpl = _getTplProperty("service_impl", _tplServiceImpl);
476         _tplServiceJson = _getTplProperty("service_json", _tplServiceJson);
477         _tplServiceJsonSerializer = _getTplProperty(
478             "service_json_serializer", _tplServiceJsonSerializer);
479         _tplServiceSoap = _getTplProperty("service_soap", _tplServiceSoap);
480         _tplServiceUtil = _getTplProperty("service_util", _tplServiceUtil);
481         _tplSpringDataSourceXml = _getTplProperty(
482             "spring_data_source_xml", _tplSpringDataSourceXml);
483         _tplSpringUtil = _getTplProperty("spring_util", _tplSpringUtil);
484         _tplSpringXml = _getTplProperty("spring_xml", _tplSpringXml);
485 
486         try {
487             _badTableNames = SetUtil.fromString(StringUtil.read(
488                 getClass().getClassLoader(), _tplBadTableNames));
489             _badColumnNames = SetUtil.fromString(StringUtil.read(
490                 getClass().getClassLoader(), _tplBadColumnNames));
491             _hbmFileName = hbmFileName;
492             _modelHintsFileName = modelHintsFileName;
493             _springFileName = springFileName;
494             _springDataSourceFileName = springDataSourceFileName;
495             _apiDir = apiDir;
496             _implDir = implDir;
497             _jsonFileName = jsonFileName;
498             _remotingFileName = remotingFileName;
499             _sqlDir = sqlDir;
500             _sqlFileName = sqlFileName;
501             _sqlIndexesFileName = sqlIndexesFileName;
502             _sqlIndexesPropertiesFileName = sqlIndexesPropertiesFileName;
503             _sqlSequencesFileName = sqlSequencesFileName;
504             _autoNamespaceTables = autoNamespaceTables;
505             _baseModelImplPackage = baseModelImplPackage;
506             _basePersistencePackage = basePersistencePackage;
507             _beanLocatorUtilPackage = beanLocatorUtilPackage;
508             _principalBeanPackage = principalBeanPackage;
509             _propsUtilPackage = propsUtilPackage;
510             _springHibernatePackage = springHibernatePackage;
511             _springUtilPackage = springUtilPackage;
512             _testDir = testDir;
513 
514             Document doc = DocumentUtil.readDocumentFromFile(
515                 new File(fileName), true);
516 
517             Element root = doc.getRootElement();
518 
519             String packagePath = root.attributeValue("package-path");
520 
521             _outputPath =
522                 _implDir + "/" + StringUtil.replace(packagePath, ".", "/");
523 
524             _serviceOutputPath =
525                 _apiDir + "/" + StringUtil.replace(packagePath, ".", "/");
526 
527             if (Validator.isNotNull(_testDir)) {
528                 _testOutputPath =
529                     _testDir + "/" + StringUtil.replace(packagePath, ".", "/");
530             }
531 
532             _packagePath = packagePath;
533 
534             Element portlet = root.element("portlet");
535             Element namespace = root.element("namespace");
536 
537             if (portlet != null) {
538                 _portletName = portlet.attributeValue("name");
539 
540                 _portletShortName = portlet.attributeValue("short-name");
541 
542                 _portletPackageName =
543                     TextFormatter.format(_portletName, TextFormatter.B);
544 
545                 _outputPath += "/" + _portletPackageName;
546 
547                 _serviceOutputPath += "/" + _portletPackageName;
548 
549                 _testOutputPath += "/" + _portletPackageName;
550 
551                 _packagePath += "." + _portletPackageName;
552             }
553             else {
554                 _portletShortName = namespace.getText();
555             }
556 
557             _portletShortName = _portletShortName.trim();
558 
559             if (!Validator.isChar(_portletShortName)) {
560                 throw new RuntimeException(
561                     "The namespace element must be a valid keyword");
562             }
563 
564             _ejbList = new ArrayList<Entity>();
565             _entityMappings = new HashMap<String, EntityMapping>();
566 
567             List<Element> entities = root.elements("entity");
568 
569             Iterator<Element> itr1 = entities.iterator();
570 
571             while (itr1.hasNext()) {
572                 Element entityEl = itr1.next();
573 
574                 String ejbName = entityEl.attributeValue("name");
575 
576                 String table = entityEl.attributeValue("table");
577 
578                 if (Validator.isNull(table)) {
579                     table = ejbName;
580 
581                     if (_badTableNames.contains(ejbName)) {
582                         table += "_";
583                     }
584                 }
585 
586                 if (_autoNamespaceTables) {
587                     table = _portletShortName + "_" + table;
588                 }
589 
590                 boolean uuid = GetterUtil.getBoolean(
591                     entityEl.attributeValue("uuid"), false);
592                 boolean localService = GetterUtil.getBoolean(
593                     entityEl.attributeValue("local-service"), false);
594                 boolean remoteService = GetterUtil.getBoolean(
595                     entityEl.attributeValue("remote-service"), true);
596                 String persistenceClass = GetterUtil.getString(
597                     entityEl.attributeValue("persistence-class"),
598                     _packagePath + ".service.persistence." + ejbName +
599                         "PersistenceImpl");
600 
601                 String finderClass = "";
602 
603                 if (FileUtil.exists(
604                     _outputPath + "/service/persistence/" + ejbName +
605                         "FinderImpl.java")) {
606 
607                     finderClass =
608                         _packagePath + ".service.persistence." + ejbName +
609                             "FinderImpl";
610                 }
611 
612                 String dataSource = entityEl.attributeValue("data-source");
613                 String sessionFactory = entityEl.attributeValue(
614                     "session-factory");
615                 String txManager = entityEl.attributeValue(
616                     "tx-manager");
617 
618                 List<EntityColumn> pkList = new ArrayList<EntityColumn>();
619                 List<EntityColumn> regularColList =
620                     new ArrayList<EntityColumn>();
621                 List<EntityColumn> collectionList =
622                     new ArrayList<EntityColumn>();
623                 List<EntityColumn> columnList = new ArrayList<EntityColumn>();
624 
625                 List<Element> columns = entityEl.elements("column");
626 
627                 if (uuid) {
628                     Element column = DocumentHelper.createElement("column");
629 
630                     column.addAttribute("name", "uuid");
631                     column.addAttribute("type", "String");
632 
633                     columns.add(0, column);
634                 }
635 
636                 Iterator<Element> itr2 = columns.iterator();
637 
638                 while (itr2.hasNext()) {
639                     Element column = itr2.next();
640 
641                     String columnName = column.attributeValue("name");
642 
643                     String columnDBName = column.attributeValue("db-name");
644 
645                     if (Validator.isNull(columnDBName)) {
646                         columnDBName = columnName;
647 
648                         if (_badColumnNames.contains(columnName)) {
649                             columnDBName += "_";
650                         }
651                     }
652 
653                     String columnType = column.attributeValue("type");
654                     boolean primary = GetterUtil.getBoolean(
655                         column.attributeValue("primary"), false);
656                     String collectionEntity = column.attributeValue("entity");
657                     String mappingKey = column.attributeValue("mapping-key");
658                     String mappingTable = column.attributeValue(
659                         "mapping-table");
660                     String idType = column.attributeValue("id-type");
661                     String idParam = column.attributeValue("id-param");
662                     boolean convertNull = GetterUtil.getBoolean(
663                         column.attributeValue("convert-null"), true);
664 
665                     EntityColumn col = new EntityColumn(
666                         columnName, columnDBName, columnType, primary,
667                         collectionEntity, mappingKey, mappingTable, idType,
668                         idParam, convertNull);
669 
670                     if (primary) {
671                         pkList.add(col);
672                     }
673 
674                     if (columnType.equals("Collection")) {
675                         collectionList.add(col);
676                     }
677                     else {
678                         regularColList.add(col);
679                     }
680 
681                     columnList.add(col);
682 
683                     if (Validator.isNotNull(collectionEntity) &&
684                         Validator.isNotNull(mappingTable)) {
685 
686                         EntityMapping entityMapping = new EntityMapping(
687                             mappingTable, ejbName, collectionEntity);
688 
689                         int ejbNameWeight = StringUtil.startsWithWeight(
690                             mappingTable, ejbName);
691                         int collectionEntityWeight =
692                             StringUtil.startsWithWeight(mappingTable,
693                                 collectionEntity);
694 
695                         if (ejbNameWeight > collectionEntityWeight) {
696                             _entityMappings.put(mappingTable, entityMapping);
697                         }
698                     }
699                 }
700 
701                 EntityOrder order = null;
702 
703                 Element orderEl = entityEl.element("order");
704 
705                 if (orderEl != null) {
706                     boolean asc = true;
707 
708                     if ((orderEl.attribute("by") != null) &&
709                         (orderEl.attributeValue("by").equals("desc"))) {
710 
711                         asc = false;
712                     }
713 
714                     List<EntityColumn> orderColsList =
715                         new ArrayList<EntityColumn>();
716 
717                     order = new EntityOrder(asc, orderColsList);
718 
719                     List<Element> orderCols = orderEl.elements("order-column");
720 
721                     Iterator<Element> itr3 = orderCols.iterator();
722 
723                     while (itr3.hasNext()) {
724                         Element orderColEl = itr3.next();
725 
726                         String orderColName =
727                             orderColEl.attributeValue("name");
728                         boolean orderColCaseSensitive = GetterUtil.getBoolean(
729                             orderColEl.attributeValue("case-sensitive"),
730                             true);
731 
732                         boolean orderColByAscending = asc;
733 
734                         String orderColBy = GetterUtil.getString(
735                             orderColEl.attributeValue("order-by"));
736 
737                         if (orderColBy.equals("asc")) {
738                             orderColByAscending = true;
739                         }
740                         else if (orderColBy.equals("desc")) {
741                             orderColByAscending = false;
742                         }
743 
744                         EntityColumn col = Entity.getColumn(
745                             orderColName, columnList);
746 
747                         col = (EntityColumn)col.clone();
748 
749                         col.setCaseSensitive(orderColCaseSensitive);
750                         col.setOrderByAscending(orderColByAscending);
751 
752                         orderColsList.add(col);
753                     }
754                 }
755 
756                 List<EntityFinder> finderList = new ArrayList<EntityFinder>();
757 
758                 List<Element> finders = entityEl.elements("finder");
759 
760                 if (uuid) {
761                     Element finderEl = DocumentHelper.createElement("finder");
762 
763                     finderEl.addAttribute("name", "Uuid");
764                     finderEl.addAttribute("return-type", "Collection");
765 
766                     Element finderColEl = finderEl.addElement("finder-column");
767 
768                     finderColEl.addAttribute("name", "uuid");
769 
770                     finders.add(0, finderEl);
771 
772                     if (columnList.contains(new EntityColumn("groupId"))) {
773                         finderEl = DocumentHelper.createElement("finder");
774 
775                         finderEl.addAttribute("name", "UUID_G");
776                         finderEl.addAttribute("return-type", ejbName);
777 
778                         finderColEl = finderEl.addElement("finder-column");
779 
780                         finderColEl.addAttribute("name", "uuid");
781 
782                         finderColEl = finderEl.addElement("finder-column");
783 
784                         finderColEl.addAttribute("name", "groupId");
785 
786                         finders.add(1, finderEl);
787                     }
788                 }
789 
790                 itr2 = finders.iterator();
791 
792                 while (itr2.hasNext()) {
793                     Element finderEl = itr2.next();
794 
795                     String finderName = finderEl.attributeValue("name");
796                     String finderReturn =
797                         finderEl.attributeValue("return-type");
798                     String finderWhere =
799                         finderEl.attributeValue("where");
800                     boolean finderDBIndex = GetterUtil.getBoolean(
801                         finderEl.attributeValue("db-index"), true);
802 
803                     List<EntityColumn> finderColsList =
804                         new ArrayList<EntityColumn>();
805 
806                     List<Element> finderCols = finderEl.elements("finder-column");
807 
808                     Iterator<Element> itr3 = finderCols.iterator();
809 
810                     while (itr3.hasNext()) {
811                         Element finderColEl = itr3.next();
812 
813                         String finderColName =
814                             finderColEl.attributeValue("name");
815 
816                         String finderColDBName =
817                             finderColEl.attributeValue("db-name");
818 
819                         if (Validator.isNull(finderColDBName)) {
820                             finderColDBName = finderColName;
821 
822                             if (_badColumnNames.contains(finderColName)) {
823                                 finderColDBName += "_";
824                             }
825                         }
826 
827                         boolean finderColCaseSensitive = GetterUtil.getBoolean(
828                             finderColEl.attributeValue("case-sensitive"),
829                             true);
830 
831                         String finderColComparator = GetterUtil.getString(
832                             finderColEl.attributeValue("comparator"), "=");
833 
834                         EntityColumn col = Entity.getColumn(
835                             finderColName, columnList);
836 
837                         col = (EntityColumn)col.clone();
838 
839                         col.setDBName(finderColDBName);
840                         col.setCaseSensitive(finderColCaseSensitive);
841                         col.setComparator(finderColComparator);
842 
843                         finderColsList.add(col);
844                     }
845 
846                     finderList.add(
847                         new EntityFinder(
848                             finderName, finderReturn, finderColsList,
849                             finderWhere, finderDBIndex));
850                 }
851 
852                 List<Entity> referenceList = new ArrayList<Entity>();
853 
854                 if (build) {
855                     List<Element> references = entityEl.elements("reference");
856 
857                     itr2 = references.iterator();
858 
859                     while (itr2.hasNext()) {
860                         Element reference = itr2.next();
861 
862                         String refPackage =
863                             reference.attributeValue("package-path");
864                         String refEntity = reference.attributeValue("entity");
865 
866                         referenceList.add(
867                             getEntity(refPackage + "." + refEntity));
868                     }
869                 }
870 
871                 List<String> txRequiredList = new ArrayList<String>();
872 
873                 itr2 = entityEl.elements("tx-required").iterator();
874 
875                 while (itr2.hasNext()) {
876                     Element txRequiredEl = itr2.next();
877 
878                     String txRequired = txRequiredEl.getText();
879 
880                     txRequiredList.add(txRequired);
881                 }
882 
883                 _ejbList.add(
884                     new Entity(
885                         _packagePath, _portletName, _portletShortName, ejbName,
886                         table, uuid, localService, remoteService,
887                         persistenceClass, finderClass, dataSource,
888                         sessionFactory, txManager, pkList, regularColList,
889                         collectionList, columnList, order, finderList,
890                         referenceList, txRequiredList));
891             }
892 
893             List<String> exceptionList = new ArrayList<String>();
894 
895             if (root.element("exceptions") != null) {
896                 List<Element> exceptions =
897                     root.element("exceptions").elements("exception");
898 
899                 itr1 = exceptions.iterator();
900 
901                 while (itr1.hasNext()) {
902                     Element exception = itr1.next();
903 
904                     exceptionList.add(exception.getText());
905                 }
906             }
907 
908             if (build) {
909                 for (int x = 0; x < _ejbList.size(); x++) {
910                     Entity entity = _ejbList.get(x);
911 
912                     System.out.println("Building " + entity.getName());
913 
914                     if (true ||
915                         entity.getName().equals("EmailAddress") ||
916                         entity.getName().equals("User")) {
917 
918                         if (entity.hasColumns()) {
919                             _createHBM(entity);
920                             _createHBMUtil(entity);
921 
922                             _createPersistenceImpl(entity);
923                             _createPersistence(entity);
924                             _createPersistenceUtil(entity);
925 
926                             if (Validator.isNotNull(_testDir)) {
927                                 _createPersistenceTest(entity);
928                             }
929 
930                             _createModelImpl(entity);
931                             _createExtendedModelImpl(entity);
932 
933                             _createModel(entity);
934                             _createExtendedModel(entity);
935 
936                             _createModelSoap(entity);
937 
938                             _createPool(entity);
939 
940                             if (entity.getPKList().size() > 1) {
941                                 _createEJBPK(entity);
942                             }
943                         }
944 
945                         _createFinder(entity);
946                         _createFinderUtil(entity);
947 
948                         if (entity.hasLocalService()) {
949                             _createServiceBaseImpl(entity, _LOCAL);
950                             _createServiceImpl(entity, _LOCAL);
951                             _createService(entity, _LOCAL);
952                             _createServiceFactory(entity, _LOCAL);
953                             _createServiceUtil(entity, _LOCAL);
954                         }
955 
956                         if (entity.hasRemoteService()) {
957                             _createServiceBaseImpl(entity, _REMOTE);
958                             _createServiceImpl(entity, _REMOTE);
959                             _createService(entity, _REMOTE);
960                             _createServiceFactory(entity, _REMOTE);
961                             _createServiceUtil(entity, _REMOTE);
962 
963                             if (Validator.isNotNull(_jsonFileName)) {
964                                 _createServiceHttp(entity);
965                                 _createServiceJSON(entity);
966 
967                                 if (entity.hasColumns()) {
968                                     _createServiceJSONSerializer(entity);
969                                 }
970 
971                                 _createServiceSoap(entity);
972                             }
973                         }
974                     }
975                 }
976 
977                 _createHBMXML();
978                 _createModelHintsXML();
979                 _createSpringXML();
980 
981                 if (Validator.isNotNull(_jsonFileName)) {
982                     _createJSONJS();
983                 }
984 
985                 if (Validator.isNotNull(_remotingFileName)) {
986                     _createRemotingXML();
987                 }
988 
989                 _createSQLIndexes();
990                 _createSQLTables();
991                 _createSQLSequences();
992 
993                 _createExceptions(exceptionList);
994 
995                 _createBaseModelImpl();
996                 _createBasePersistence();
997                 _createBeanLocatorUtil();
998                 _createDynamicDialect();
999                 _createFinderCache();
1000                _createHibernateConfiguration();
1001                _createHibernateUtil();
1002                _createPrincipalBean();
1003                _createProps();
1004                _createPropsUtil();
1005                _createSpringDataSourceXML();
1006                _createSpringUtil();
1007            }
1008        }
1009        catch (Exception e) {
1010            e.printStackTrace();
1011        }
1012    }
1013
1014    public String getClassName(Type type) {
1015        int dimensions = type.getDimensions();
1016        String name = type.getValue();
1017
1018        if (dimensions > 0) {
1019            StringMaker sm = new StringMaker();
1020
1021            for (int i = 0; i < dimensions; i++) {
1022                sm.append("[");
1023            }
1024
1025            if (name.equals("boolean")) {
1026                return sm.toString() + "Z";
1027            }
1028            else if (name.equals("byte")) {
1029                return sm.toString() + "B";
1030            }
1031            else if (name.equals("char")) {
1032                return sm.toString() + "C";
1033            }
1034            else if (name.equals("double")) {
1035                return sm.toString() + "D";
1036            }
1037            else if (name.equals("float")) {
1038                return sm.toString() + "F";
1039            }
1040            else if (name.equals("int")) {
1041                return sm.toString() + "I";
1042            }
1043            else if (name.equals("long")) {
1044                return sm.toString() + "J";
1045            }
1046            else if (name.equals("short")) {
1047                return sm.toString() + "S";
1048            }
1049            else {
1050                return sm.toString() + "L" + name + ";";
1051            }
1052        }
1053
1054        return name;
1055    }
1056
1057    public String getCreateTableSQL(Entity entity){
1058        String createTableSQL = _getCreateTableSQL(entity);
1059
1060        createTableSQL = StringUtil.replace(createTableSQL, "\n", "");
1061        createTableSQL = StringUtil.replace(createTableSQL, "\t", "");
1062        createTableSQL = createTableSQL.substring(
1063            0, createTableSQL.length() - 1);
1064
1065        return createTableSQL;
1066    }
1067
1068    public String getDimensions(String dims) {
1069        return getDimensions(Integer.parseInt(dims));
1070    }
1071
1072    public String getDimensions(int dims) {
1073        String dimensions = "";
1074
1075        for (int i = 0; i < dims; i++) {
1076            dimensions += "[]";
1077        }
1078
1079        return dimensions;
1080    }
1081
1082    public Entity getEntity(String name) throws IOException {
1083        Entity entity = _entityPool.get(name);
1084
1085        if (entity != null) {
1086            return entity;
1087        }
1088
1089        int pos = name.lastIndexOf(".");
1090
1091        if (pos == -1) {
1092            pos = _ejbList.indexOf(new Entity(name));
1093
1094            entity = _ejbList.get(pos);
1095
1096            _entityPool.put(name, entity);
1097
1098            return entity;
1099        }
1100        else {
1101            String refPackage = name.substring(0, pos);
1102            String refPackageDir = StringUtil.replace(refPackage, ".", "/");
1103            String refEntity = name.substring(pos + 1, name.length());
1104            String refFileName =
1105                _implDir + "/" + refPackageDir + "/service.xml";
1106
1107            File refFile = new File(refFileName);
1108
1109            boolean useTempFile = false;
1110
1111            if (!refFile.exists()) {
1112                refFileName = Time.getTimestamp();
1113                refFile = new File(refFileName);
1114
1115                ClassLoader classLoader = getClass().getClassLoader();
1116
1117                FileUtil.write(
1118                    refFileName,
1119                    StringUtil.read(
1120                        classLoader, refPackageDir + "/service.xml"));
1121
1122                useTempFile = true;
1123            }
1124
1125            ServiceBuilder serviceBuilder = new ServiceBuilder(
1126                refFileName, _hbmFileName, _modelHintsFileName, _springFileName,
1127                _springDataSourceFileName, _apiDir, _implDir, _jsonFileName,
1128                _remotingFileName, _sqlDir, _sqlFileName, _sqlIndexesFileName,
1129                _sqlIndexesPropertiesFileName, _sqlSequencesFileName,
1130                _autoNamespaceTables, _baseModelImplPackage,
1131                _basePersistencePackage, _beanLocatorUtilPackage,
1132                _principalBeanPackage, _propsUtilPackage,
1133                _springHibernatePackage, _springUtilPackage, _testDir, false);
1134
1135            entity = serviceBuilder.getEntity(refEntity);
1136
1137            _entityPool.put(name, entity);
1138
1139            if (useTempFile) {
1140                refFile.deleteOnExit();
1141            }
1142
1143            return entity;
1144        }
1145    }
1146
1147    public Entity getEntityByGenericsName(String genericsName) {
1148        try {
1149            String name = genericsName.substring(1, genericsName.length() - 1);
1150
1151            name = StringUtil.replace(name, ".model.", ".");
1152
1153            return getEntity(name);
1154        }
1155        catch (Exception e) {
1156            return null;
1157        }
1158    }
1159
1160    public Entity getEntityByParameterTypeValue(String parameterTypeValue) {
1161        try {
1162            String name = parameterTypeValue;
1163
1164            name = StringUtil.replace(name, ".model.", ".");
1165
1166            return getEntity(name);
1167        }
1168        catch (Exception e) {
1169            return null;
1170        }
1171    }
1172
1173    public String getGeneratorClass(String idType) {
1174        if (Validator.isNull(idType)) {
1175            idType = "assigned";
1176        }
1177
1178        return idType;
1179    }
1180
1181    public String getNoSuchEntityException(Entity entity) {
1182        String noSuchEntityException = entity.getName();
1183
1184        if (Validator.isNull(entity.getPortletShortName()) ||
1185            noSuchEntityException.startsWith(entity.getPortletShortName())) {
1186
1187            noSuchEntityException = noSuchEntityException.substring(
1188                entity.getPortletShortName().length());
1189        }
1190
1191        noSuchEntityException = "NoSuch" + noSuchEntityException;
1192
1193        return noSuchEntityException;
1194    }
1195
1196    public String getPrimitiveObj(String type) {
1197        if (type.equals("boolean")) {
1198            return "Boolean";
1199        }
1200        else if (type.equals("double")) {
1201            return "Double";
1202        }
1203        else if (type.equals("float")) {
1204            return "Float";
1205        }
1206        else if (type.equals("int")) {
1207            return "Integer";
1208        }
1209        else if (type.equals("long")) {
1210            return "Long";
1211        }
1212        else if (type.equals("short")) {
1213            return "Short";
1214        }
1215        else {
1216            return type;
1217        }
1218    }
1219
1220    public String getPrimitiveObjValue(String colType){
1221        if (colType.equals("Boolean")) {
1222            return ".booleanValue()";
1223        }
1224        else if (colType.equals("Double")) {
1225            return ".doubleValue()";
1226        }
1227        else if (colType.equals("Float")) {
1228            return ".floatValue()";
1229        }
1230        else if (colType.equals("Integer")) {
1231            return ".intValue()";
1232        }
1233        else if (colType.equals("Long")) {
1234            return ".longValue()";
1235        }
1236        else if (colType.equals("Short")) {
1237            return ".shortValue()";
1238        }
1239
1240        return StringPool.BLANK;
1241    }
1242
1243    public String getSqlType(String model, String field, String type) {
1244        if (type.equals("boolean") || type.equals("Boolean")) {
1245            return "BOOLEAN";
1246        }
1247        else if (type.equals("double") || type.equals("Double")) {
1248            return "DOUBLE";
1249        }
1250        else if (type.equals("float") || type.equals("Float")) {
1251            return "FLOAT";
1252        }
1253        else if (type.equals("int") || type.equals("Integer")) {
1254            return "INTEGER";
1255        }
1256        else if (type.equals("long") || type.equals("Long")) {
1257            return "BIGINT";
1258        }
1259        else if (type.equals("short") || type.equals("Short")) {
1260            return "INTEGER";
1261        }
1262        else if (type.equals("Date")) {
1263            return "TIMESTAMP";
1264        }
1265        else if (type.equals("String")) {
1266            Map<String, String> hints = ModelHintsUtil.getHints(model, field);
1267
1268            if (hints != null) {
1269                int maxLength = GetterUtil.getInteger(hints.get("max-length"));
1270
1271                if (maxLength == 2000000) {
1272                    return "CLOB";
1273                }
1274            }
1275
1276            return "VARCHAR";
1277        }
1278        else {
1279            return null;
1280        }
1281    }
1282
1283    public boolean hasEntityByGenericsName(String genericsName) {
1284        if (Validator.isNull(genericsName)) {
1285            return false;
1286        }
1287
1288        if (genericsName.indexOf(".model.") == -1) {
1289            return false;
1290        }
1291
1292        if (getEntityByGenericsName(genericsName) == null) {
1293            return false;
1294        }
1295        else {
1296            return true;
1297        }
1298    }
1299
1300    public boolean hasEntityByParameterTypeValue(String parameterTypeValue) {
1301        if (Validator.isNull(parameterTypeValue)) {
1302            return false;
1303        }
1304
1305        if (parameterTypeValue.indexOf(".model.") == -1) {
1306            return false;
1307        }
1308
1309        if (getEntityByParameterTypeValue(parameterTypeValue) == null) {
1310            return false;
1311        }
1312        else {
1313            return true;
1314        }
1315    }
1316
1317    public boolean isCustomMethod(JavaMethod method) {
1318        String methodName = method.getName();
1319
1320        if (methodName.equals("afterPropertiesSet") ||
1321            methodName.equals("equals") ||
1322            methodName.equals("getClass") ||
1323            methodName.equals("hashCode") ||
1324            methodName.equals("notify") ||
1325            methodName.equals("notifyAll") ||
1326            methodName.equals("toString") ||
1327            methodName.equals("wait")) {
1328
1329            return false;
1330        }
1331        else if (methodName.equals("getPermissionChecker")) {
1332            return false;
1333        }
1334        else if (methodName.equals("getUser") &&
1335                 method.getParameters().length == 0) {
1336
1337            return false;
1338        }
1339        else if (methodName.equals("getUserId") &&
1340                 method.getParameters().length == 0) {
1341
1342            return false;
1343        }
1344        else if ((methodName.endsWith("Finder")) &&
1345                 (methodName.startsWith("get") ||
1346                  methodName.startsWith("set"))) {
1347
1348            return false;
1349        }
1350        else if ((methodName.endsWith("Persistence")) &&
1351                 (methodName.startsWith("get") ||
1352                  methodName.startsWith("set"))) {
1353
1354            return false;
1355        }
1356        else if ((methodName.endsWith("Service")) &&
1357                 (methodName.startsWith("get") ||
1358                  methodName.startsWith("set"))) {
1359
1360            return false;
1361        }
1362        else {
1363            return true;
1364        }
1365    }
1366
1367    public boolean isDuplicateMethod(
1368        JavaMethod method, Map<String, Object> tempMap) {
1369
1370        StringMaker sm = new StringMaker();
1371
1372        sm.append("isDuplicateMethod ");
1373        sm.append(method.getReturns().getValue());
1374        sm.append(method.getReturnsGenericsName());
1375        sm.append(getDimensions(method.getReturns().getDimensions()));
1376        sm.append(StringPool.SPACE);
1377        sm.append(method.getName());
1378        sm.append(StringPool.OPEN_PARENTHESIS);
1379
1380        JavaParameter[] parameters = method.getParameters();
1381
1382        for (int i = 0; i < parameters.length; i++) {
1383            JavaParameter javaParameter = parameters[i];
1384
1385            sm.append(javaParameter.getType().getValue());
1386            sm.append(javaParameter.getGenericsName());
1387            sm.append(getDimensions(javaParameter.getType().getDimensions()));
1388
1389            if ((i + 1) != parameters.length) {
1390                sm.append(StringPool.COMMA);
1391            }
1392        }
1393
1394        sm.append(StringPool.CLOSE_PARENTHESIS);
1395
1396        String key = sm.toString();
1397
1398        if (tempMap.containsKey(key)) {
1399            return true;
1400        }
1401        else {
1402            tempMap.put(key, key);
1403
1404            return false;
1405        }
1406    }
1407
1408    public boolean isSoapMethod(JavaMethod method) {
1409        String returnValueName = method.getReturns().getValue();
1410
1411        if (returnValueName.startsWith("java.io") ||
1412            returnValueName.equals("java.util.Map") ||
1413            returnValueName.equals("java.util.Properties") ||
1414            returnValueName.startsWith("javax")) {
1415
1416            return false;
1417        }
1418
1419        JavaParameter[] parameters = method.getParameters();
1420
1421        for (int i = 0; i < parameters.length; i++) {
1422            JavaParameter javaParameter = parameters[i];
1423
1424            String parameterTypeName =
1425                javaParameter.getType().getValue() +
1426                    _getDimensions(javaParameter.getType());
1427
1428            if (parameterTypeName.equals(
1429                    "com.liferay.portal.theme.ThemeDisplay") ||
1430                parameterTypeName.equals(
1431                    "com.liferay.portlet.PortletPreferencesImpl") ||
1432                parameterTypeName.startsWith("java.io") ||
1433                //parameterTypeName.startsWith("java.util.List") ||
1434                //parameterTypeName.startsWith("java.util.Locale") ||
1435                parameterTypeName.startsWith("java.util.Map") ||
1436                parameterTypeName.startsWith("java.util.Properties") ||
1437                parameterTypeName.startsWith("javax")) {
1438
1439                return false;
1440            }
1441        }
1442
1443        return true;
1444    }
1445
1446    private static String _getPackagePath(File file) throws IOException {
1447        String fileName = StringUtil.replace(file.toString(), "\\", "/");
1448
1449        int x = fileName.indexOf("src/");
1450
1451        if (x == -1) {
1452            x = fileName.indexOf("test/");
1453        }
1454
1455        int y = fileName.lastIndexOf("/");
1456
1457        fileName = fileName.substring(x + 4, y);
1458
1459        return StringUtil.replace(fileName, "/", ".");
1460    }
1461
1462    private void _createBaseModelImpl() throws Exception {
1463        if (_baseModelImplPackage.equals("com.liferay.portal.model.impl")) {
1464            return;
1465        }
1466
1467        // Content
1468
1469        String content = _processTemplate(_tplBaseModeImpl);
1470
1471        // Write file
1472
1473        File ejbFile = new File(
1474            _implDir + "/" +
1475                StringUtil.replace(_baseModelImplPackage, ".", "/") +
1476                    "/BaseModelImpl.java");
1477
1478        FileUtil.write(ejbFile, content, true);
1479    }
1480
1481    private void _createBasePersistence() throws Exception {
1482        if (_basePersistencePackage.equals(
1483                "com.liferay.portal.service.persistence")) {
1484
1485            return;
1486        }
1487
1488        // Content
1489
1490        String content = _processTemplate(_tplBasePersistence);
1491
1492        // Write file
1493
1494        File ejbFile = new File(
1495            _implDir + "/" +
1496                StringUtil.replace(_basePersistencePackage, ".", "/") +
1497                    "/BasePersistence.java");
1498
1499        FileUtil.write(ejbFile, content, true);
1500    }
1501
1502    private void _createBeanLocatorUtil() throws Exception {
1503        if (_beanLocatorUtilPackage.equals("com.liferay.portal.kernel.bean")) {
1504            return;
1505        }
1506
1507        // Content
1508
1509        String content = _processTemplate(_tplBeanLocatorUtil);
1510
1511        // Write file
1512
1513        File ejbFile = new File(
1514            _implDir + "/" +
1515                StringUtil.replace(_beanLocatorUtilPackage, ".", "/") +
1516                    "/BeanLocatorUtil.java");
1517
1518        writeFile(ejbFile, content);
1519    }
1520
1521    private void _createDynamicDialect() throws Exception {
1522        if (_springHibernatePackage.equals(
1523                "com.liferay.portal.spring.hibernate")) {
1524
1525            return;
1526        }
1527
1528        // Content
1529
1530        String content = _processTemplate(_tplDynamicDialect);
1531
1532        // Write file
1533
1534        File ejbFile = new File(
1535            _implDir + "/" +
1536                StringUtil.replace(_springHibernatePackage, ".", "/") +
1537                    "/DynamicDialect.java");
1538
1539        FileUtil.write(ejbFile, content, true);
1540    }
1541
1542    private void _createEJBPK(Entity entity) throws Exception {
1543        Map<String, Object> context = _getContext();
1544
1545        context.put("entity", entity);
1546
1547        // Content
1548
1549        String content = _processTemplate(_tplEjbPk, context);
1550
1551        // Write file
1552
1553        File ejbFile = new File(
1554            _serviceOutputPath + "/service/persistence/" +
1555                entity.getPKClassName() + ".java");
1556
1557        writeFile(ejbFile, content);
1558    }
1559
1560    private void _createExceptions(List<String> exceptions) throws Exception {
1561        for (int i = 0; i < _ejbList.size(); i++) {
1562            Entity entity = _ejbList.get(i);
1563
1564            if (entity.hasColumns()) {
1565                exceptions.add(getNoSuchEntityException(entity));
1566            }
1567        }
1568
1569        for (String exception : exceptions) {
1570            File exceptionFile = new File(
1571                _serviceOutputPath + "/" + exception + "Exception.java");
1572
1573            if (!exceptionFile.exists()) {
1574                Map<String, Object> context = _getContext();
1575
1576                context.put("exception", exception);
1577
1578                String content = _processTemplate(_tplException, context);
1579
1580                FileUtil.write(exceptionFile, content);
1581            }
1582        }
1583    }
1584
1585    private void _createExtendedModel(Entity entity) throws Exception {
1586        JavaClass javaClass = _getJavaClass(
1587            _outputPath + "/model/impl/" + entity.getName() + "Impl.java");
1588
1589        Map<String, Object> context = _getContext();
1590
1591        context.put("entity", entity);
1592        context.put("methods", javaClass.getMethods());
1593
1594        // Content
1595
1596        String content = _processTemplate(_tplExtendedModel, context);
1597
1598        // Write file
1599
1600        File modelFile = new File(
1601            _serviceOutputPath + "/model/" + entity.getName() + ".java");
1602
1603        Map<String, Object> jalopySettings = new HashMap<String, Object>();
1604
1605        jalopySettings.put("keepJavadoc", Boolean.TRUE);
1606
1607        writeFile(modelFile, content, jalopySettings);
1608    }
1609
1610    private void _createExtendedModelImpl(Entity entity) throws Exception {
1611        Map<String, Object> context = _getContext();
1612
1613        context.put("entity", entity);
1614
1615        // Content
1616
1617        String content = _processTemplate(_tplExtendedModelImpl, context);
1618
1619        // Write file
1620
1621        File modelFile = new File(
1622            _outputPath + "/model/impl/" + entity.getName() + "Impl.java");
1623
1624        if (!modelFile.exists()) {
1625            writeFile(modelFile, content);
1626        }
1627    }
1628
1629    private void _createFinder(Entity entity) throws Exception {
1630        if (!entity.hasFinderClass()) {
1631            return;
1632        }
1633
1634        JavaClass javaClass = _getJavaClass(
1635            _outputPath + "/service/persistence/" + entity.getName() +
1636                "FinderImpl.java");
1637
1638        Map<String, Object> context = _getContext();
1639
1640        context.put("entity", entity);
1641        context.put("methods", javaClass.getMethods());
1642
1643        // Content
1644
1645        String content = _processTemplate(_tplFinder, context);
1646
1647        // Write file
1648
1649        File ejbFile = new File(
1650            _serviceOutputPath + "/service/persistence/" + entity.getName() +
1651                "Finder.java");
1652
1653        writeFile(ejbFile, content);
1654    }
1655
1656    private void _createFinderCache() throws Exception {
1657        if (_springHibernatePackage.equals("com.liferay.portal.spring.hibernate")) {
1658            return;
1659        }
1660
1661        // Content
1662
1663        String content = _processTemplate(_tplFinderCache);
1664
1665        // Write file
1666
1667        File ejbFile = new File(
1668            _implDir + "/" +
1669                StringUtil.replace(_springHibernatePackage, ".", "/") +
1670                "/FinderCache.java");
1671
1672        FileUtil.write(ejbFile, content, true);
1673    }
1674
1675    private void _createFinderUtil(Entity entity) throws Exception {
1676        if (!entity.hasFinderClass()) {
1677            return;
1678        }
1679
1680        JavaClass javaClass = _getJavaClass(
1681            _outputPath + "/service/persistence/" + entity.getName() +
1682                "FinderImpl.java");
1683
1684        Map<String, Object> context = _getContext();
1685
1686        context.put("entity", entity);
1687        context.put("methods", javaClass.getMethods());
1688
1689        // Content
1690
1691        String content = _processTemplate(_tplFinderUtil, context);
1692
1693        // Write file
1694
1695        File ejbFile = new File(
1696            _serviceOutputPath + "/service/persistence/" + entity.getName() +
1697                "FinderUtil.java");
1698
1699        writeFile(ejbFile, content);
1700    }
1701
1702    private void _createHBM(Entity entity) throws IOException {
1703        File ejbFile = new File(
1704            _outputPath + "/service/persistence/" + entity.getName() +
1705                "HBM.java");
1706
1707        if (ejbFile.exists()) {
1708            System.out.println("Removing deprecated " + ejbFile);
1709
1710            ejbFile.delete();
1711        }
1712    }
1713
1714    private void _createHBMUtil(Entity entity) throws IOException {
1715        File ejbFile = new File(
1716            _outputPath + "/service/persistence/" + entity.getName() +
1717                "HBMUtil.java");
1718
1719        if (ejbFile.exists()) {
1720            System.out.println("Removing deprecated " + ejbFile);
1721
1722            ejbFile.delete();
1723        }
1724    }
1725
1726    private void _createHBMXML() throws Exception {
1727        Map<String, Object> context = _getContext();
1728
1729        context.put("entities", _ejbList);
1730
1731        // Content
1732
1733        String content = _processTemplate(_tplHbmXml, context);
1734
1735        File xmlFile = new File(_hbmFileName);
1736
1737        if (!xmlFile.exists()) {
1738            String xml =
1739                "<?xml version=\"1.0\"?>\n" +
1740                "<!DOCTYPE hibernate-mapping PUBLIC \"-//Hibernate/Hibernate Mapping DTD 3.0//EN\" \"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd\">\n" +
1741                "\n" +
1742                "<hibernate-mapping default-lazy=\"false\" auto-import=\"false\">\n" +
1743                "</hibernate-mapping>";
1744
1745            FileUtil.write(xmlFile, xml);
1746        }
1747
1748        String oldContent = FileUtil.read(xmlFile);
1749        String newContent = _fixHBMXML(oldContent);
1750
1751        int firstClass = newContent.indexOf(
1752            "<class name=\"" + _packagePath + ".model.impl.");
1753        int lastClass = newContent.lastIndexOf(
1754            "<class name=\"" + _packagePath + ".model.impl.");
1755
1756        if (firstClass == -1) {
1757            int x = newContent.indexOf("</hibernate-mapping>");
1758
1759            newContent =
1760                newContent.substring(0, x) + content +
1761                newContent.substring(x, newContent.length());
1762        }
1763        else {
1764            firstClass = newContent.lastIndexOf("<class", firstClass) - 1;
1765            lastClass = newContent.indexOf("</class>", lastClass) + 9;
1766
1767            newContent =
1768                newContent.substring(0, firstClass) + content +
1769                    newContent.substring(lastClass, newContent.length());
1770        }
1771
1772        newContent = _formatXML(newContent);
1773
1774        if (!oldContent.equals(newContent)) {
1775            FileUtil.write(xmlFile, newContent);
1776        }
1777    }
1778
1779    private void _createHibernateConfiguration() throws Exception {
1780        if (_springHibernatePackage.equals(
1781                "com.liferay.portal.spring.hibernate")) {
1782
1783            return;
1784        }
1785
1786        // Content
1787
1788        String content = _processTemplate(_tplHibernateConfiguration);
1789
1790        // Write file
1791
1792        File ejbFile = new File(
1793            _implDir + "/" +
1794                StringUtil.replace(_springHibernatePackage, ".", "/") +
1795                    "/HibernateConfiguration.java");
1796
1797        FileUtil.write(ejbFile, content, true);
1798    }
1799
1800    private void _createHibernateUtil() throws Exception {
1801        if (_springHibernatePackage.equals(
1802                "com.liferay.portal.spring.hibernate")) {
1803
1804            return;
1805        }
1806
1807        // Content
1808
1809        String content = _processTemplate(_tplHibernateUtil);
1810
1811        // Write file
1812
1813        File ejbFile = new File(
1814            _implDir + "/" +
1815                StringUtil.replace(_springHibernatePackage, ".", "/") +
1816                "/HibernateUtil.java");
1817
1818        FileUtil.write(ejbFile, content, true);
1819    }
1820
1821    private void _createJSONJS() throws Exception {
1822        StringMaker content = new StringMaker();
1823
1824        if (_ejbList.size() > 0) {
1825            content.append(_processTemplate(_tplJsonJs));
1826        }
1827
1828        for (int i = 0; i < _ejbList.size(); i++) {
1829            Entity entity = _ejbList.get(i);
1830
1831            if (entity.hasRemoteService()) {
1832                JavaClass javaClass = _getJavaClass(
1833                    _outputPath + "/service/http/" + entity.getName() +
1834                        "ServiceJSON.java");
1835
1836                JavaMethod[] methods = javaClass.getMethods();
1837
1838                Set<String> jsonMethods = new LinkedHashSet<String>();
1839
1840                for (int j = 0; j < methods.length; j++) {
1841                    JavaMethod javaMethod = methods[j];
1842
1843                    String methodName = javaMethod.getName();
1844
1845                    if (javaMethod.isPublic()) {
1846                        jsonMethods.add(methodName);
1847                    }
1848                }
1849
1850                if (jsonMethods.size() > 0) {
1851                    Map<String, Object> context = _getContext();
1852
1853                    context.put("entity", entity);
1854                    context.put("methods", jsonMethods);
1855
1856                    content.append("\n\n");
1857                    content.append(_processTemplate(_tplJsonJsMethod, context));
1858                }
1859            }
1860        }
1861
1862        File jsonFile = new File(_jsonFileName);
1863
1864        if (!jsonFile.exists()) {
1865            FileUtil.write(jsonFile, "");
1866        }
1867
1868        String oldContent = FileUtil.read(jsonFile);
1869        String newContent = new String(oldContent);
1870
1871        int oldBegin = oldContent.indexOf(
1872            "Liferay.Service." + _portletShortName);
1873
1874        int oldEnd = oldContent.lastIndexOf(
1875            "Liferay.Service." + _portletShortName);
1876
1877        oldEnd = oldContent.indexOf("};", oldEnd);
1878
1879        int newBegin = newContent.indexOf(
1880            "Liferay.Service." + _portletShortName);
1881
1882        int newEnd = newContent.lastIndexOf(
1883            "Liferay.Service." + _portletShortName);
1884
1885        newEnd = newContent.indexOf("};", newEnd);
1886
1887        if (newBegin == -1) {
1888            newContent = oldContent + "\n\n" + content.toString().trim();
1889        }
1890        else {
1891            newContent =
1892                newContent.substring(0, oldBegin) + content.toString().trim() +
1893                    newContent.substring(oldEnd + 2, newContent.length());
1894        }
1895
1896        if (!oldContent.equals(newContent)) {
1897            FileUtil.write(jsonFile, newContent);
1898        }
1899    }
1900
1901    private void _createModel(Entity entity) throws Exception {
1902        Map<String, Object> context = _getContext();
1903
1904        context.put("entity", entity);
1905
1906        // Content
1907
1908        String content = _processTemplate(_tplModel, context);
1909
1910        // Write file
1911
1912        File modelFile = new File(
1913            _serviceOutputPath + "/model/" + entity.getName() + "Model.java");
1914
1915        Map<String, Object> jalopySettings = new HashMap<String, Object>();
1916
1917        jalopySettings.put("keepJavadoc", Boolean.TRUE);
1918
1919        writeFile(modelFile, content, jalopySettings);
1920    }
1921
1922    private void _createModelHintsXML() throws Exception {
1923        Map<String, Object> context = _getContext();
1924
1925        context.put("entities", _ejbList);
1926
1927        // Content
1928
1929        String content = _processTemplate(_tplModelHintsXml, context);
1930
1931        File xmlFile = new File(_modelHintsFileName);
1932
1933        if (!xmlFile.exists()) {
1934            String xml =
1935                "<?xml version=\"1.0\"?>\n" +
1936                "\n" +
1937                "<model-hints>\n" +
1938                "</model-hints>";
1939
1940            FileUtil.write(xmlFile, xml);
1941        }
1942
1943        String oldContent = FileUtil.read(xmlFile);
1944        String newContent = new String(oldContent);
1945
1946        int firstModel = newContent.indexOf(
1947            "<model name=\"" + _packagePath + ".model.");
1948        int lastModel = newContent.lastIndexOf(
1949            "<model name=\"" + _packagePath + ".model.");
1950
1951        if (firstModel == -1) {
1952            int x = newContent.indexOf("</model-hints>");
1953
1954            newContent =
1955                newContent.substring(0, x) + content +
1956                    newContent.substring(x, newContent.length());
1957        }
1958        else {
1959            firstModel = newContent.lastIndexOf("<model", firstModel) - 1;
1960            lastModel = newContent.indexOf("</model>", lastModel) + 9;
1961
1962            newContent =
1963                newContent.substring(0, firstModel) + content +
1964                newContent.substring(lastModel, newContent.length());
1965        }
1966
1967        newContent = _formatXML(newContent);
1968
1969        if (!oldContent.equals(newContent)) {
1970            FileUtil.write(xmlFile, newContent);
1971        }
1972    }
1973
1974    private void _createModelImpl(Entity entity) throws Exception {
1975        Map<String, Object> context = _getContext();
1976
1977        context.put("entity", entity);
1978
1979        // Content
1980
1981        String content = _processTemplate(_tplModelImpl, context);
1982
1983        // Write file
1984
1985        File modelFile = new File(
1986            _outputPath + "/model/impl/" + entity.getName() + "ModelImpl.java");
1987
1988        Map<String, Object> jalopySettings = new HashMap<String, Object>();
1989
1990        jalopySettings.put("keepJavadoc", Boolean.TRUE);
1991
1992        writeFile(modelFile, content, jalopySettings);
1993    }
1994
1995    private void _createModelSoap(Entity entity) throws Exception {
1996        Map<String, Object> context = _getContext();
1997
1998        context.put("entity", entity);
1999
2000        // Content
2001
2002        String content = _processTemplate(_tplModelSoap, context);
2003
2004        // Write file
2005
2006        File modelFile = new File(
2007            _serviceOutputPath + "/model/" + entity.getName() + "Soap.java");
2008
2009        Map<String, Object> jalopySettings = new HashMap<String, Object>();
2010
2011        jalopySettings.put("keepJavadoc", Boolean.TRUE);
2012
2013        writeFile(modelFile, content, jalopySettings);
2014    }
2015
2016    private void _createPersistence(Entity entity) throws Exception {
2017        JavaClass javaClass = _getJavaClass(
2018            _outputPath + "/service/persistence/" + entity.getName() +
2019                "PersistenceImpl.java");
2020
2021        Map<String, Object> context = _getContext();
2022
2023        context.put("entity", entity);
2024        context.put("methods", javaClass.getMethods());
2025
2026        // Content
2027
2028        String content = _processTemplate(_tplPersistence, context);
2029
2030        // Write file
2031
2032        File ejbFile = new File(
2033            _serviceOutputPath + "/service/persistence/" + entity.getName() +
2034                "Persistence.java");
2035
2036        writeFile(ejbFile, content);
2037
2038        if (!_serviceOutputPath.equals(_outputPath)) {
2039            ejbFile = new File(
2040                _outputPath + "/service/persistence/" + entity.getName() +
2041                    "Persistence.java");
2042
2043            if (ejbFile.exists()) {
2044                System.out.println("Relocating " + ejbFile);
2045
2046                ejbFile.delete();
2047            }
2048        }
2049    }
2050
2051    private void _createPersistenceImpl(Entity entity) throws Exception {
2052        Map<String, Object> context = _getContext();
2053
2054        context.put("entity", entity);
2055
2056        // Content
2057
2058        String content = _processTemplate(_tplPersistenceImpl, context);
2059
2060        // Write file
2061
2062        File ejbFile = new File(
2063            _outputPath + "/service/persistence/" + entity.getName() +
2064                "PersistenceImpl.java");
2065
2066        writeFile(ejbFile, content);
2067    }
2068
2069    private void _createPersistenceTest(Entity entity) throws Exception {
2070        Map<String, Object> context = _getContext();
2071
2072        context.put("entity", entity);
2073
2074        // Content
2075
2076        String content = _processTemplate(_tplPersistenceTest, context);
2077
2078        // Write file
2079
2080        File ejbFile = new File(
2081            _testOutputPath + "/service/persistence/" + entity.getName() +
2082                "PersistenceTest.java");
2083
2084        writeFile(ejbFile, content);
2085    }
2086
2087    private void _createPersistenceUtil(Entity entity) throws Exception {
2088        JavaClass javaClass = _getJavaClass(
2089            _outputPath + "/service/persistence/" + entity.getName() +
2090                "PersistenceImpl.java");
2091
2092        Map<String, Object> context = _getContext();
2093
2094        context.put("entity", entity);
2095        context.put("methods", javaClass.getMethods());
2096
2097        // Content
2098
2099        String content = _processTemplate(_tplPersistenceUtil, context);
2100
2101        // Write file
2102
2103        File ejbFile = new File(
2104            _serviceOutputPath + "/service/persistence/" + entity.getName() +
2105                "Util.java");
2106
2107        writeFile(ejbFile, content);
2108
2109        if (!_serviceOutputPath.equals(_outputPath)) {
2110            ejbFile = new File(
2111                _outputPath + "/service/persistence/" + entity.getName() +
2112                    "Util.java");
2113
2114            if (ejbFile.exists()) {
2115                System.out.println("Relocating " + ejbFile);
2116
2117                ejbFile.delete();
2118            }
2119        }
2120    }
2121
2122    private void _createPool(Entity entity) throws IOException {
2123        File ejbFile = new File(
2124            _outputPath + "/service/persistence/" + entity.getName() +
2125                "Pool.java");
2126
2127        if (ejbFile.exists()) {
2128            System.out.println("Removing deprecated " + ejbFile);
2129
2130            ejbFile.delete();
2131        }
2132    }
2133
2134    private void _createPrincipalBean() throws Exception {
2135        if (_principalBeanPackage.equals("com.liferay.portal.service.impl")) {
2136            return;
2137        }
2138
2139        // Content
2140
2141        String content = _processTemplate(_tplPrincipalBean);
2142
2143        // Write file
2144
2145        File ejbFile = new File(
2146            _implDir + "/" +
2147                StringUtil.replace(_principalBeanPackage, ".", "/") +
2148                    "/PrincipalBean.java");
2149
2150        FileUtil.write(ejbFile, content, true);
2151    }
2152
2153    private void _createProps() throws Exception {
2154        if (_propsUtilPackage.equals("com.liferay.portal.util")) {
2155            return;
2156        }
2157
2158        // Content
2159
2160        File propsFile = new File(_implDir + "/portlet-service.properties");
2161
2162        long buildNumber = 1;
2163
2164        if (propsFile.exists()) {
2165            Properties props = PropertiesUtil.load(FileUtil.read(propsFile));
2166
2167            buildNumber = GetterUtil.getLong(
2168                props.getProperty("build.number")) + 1;
2169        }
2170
2171        Map<String, Object> context = _getContext();
2172
2173        context.put("buildNumber", new Long(buildNumber));
2174        context.put("currentTimeMillis", new Long(System.currentTimeMillis()));
2175
2176        String content = _processTemplate(_tplProps, context);
2177
2178        // Write file
2179
2180        FileUtil.write(propsFile, content, true);
2181    }
2182
2183    private void _createPropsUtil() throws Exception {
2184        if (_propsUtilPackage.equals("com.liferay.portal.util")) {
2185            return;
2186        }
2187
2188        // Content
2189
2190        String content = _processTemplate(_tplPropsUtil);
2191
2192        // Write file
2193
2194        File ejbFile = new File(
2195            _implDir + "/" + StringUtil.replace(_propsUtilPackage, ".", "/") +
2196                "/PropsUtil.java");
2197
2198        writeFile(ejbFile, content);
2199    }
2200
2201    private void _createRemotingXML() throws Exception {
2202        StringMaker sm = new StringMaker();
2203
2204        Document doc = DocumentUtil.readDocumentFromFile(
2205            new File(_springFileName), true);
2206
2207        Iterator<Element> itr = doc.getRootElement().elements(
2208            "bean").iterator();
2209
2210        while (itr.hasNext()) {
2211            Element beanEl = itr.next();
2212
2213            String beanId = beanEl.attributeValue("id");
2214
2215            if (beanId.endsWith("ServiceFactory") &&
2216                !beanId.endsWith("LocalServiceFactory")) {
2217
2218                String serviceName = beanId.substring(0, beanId.length() - 7);
2219
2220                String serviceMapping = serviceName;
2221                serviceMapping = StringUtil.replace(
2222                    serviceMapping, ".service.", ".service.spring.");
2223                serviceMapping = StringUtil.replace(
2224                    serviceMapping, ".", "_");
2225
2226                Map<String, Object> context = _getContext();
2227
2228                context.put("serviceName", serviceName);
2229                context.put("serviceMapping", serviceMapping);
2230
2231                sm.append(_processTemplate(_tplRemotingXml, context));
2232            }
2233        }
2234
2235        File outputFile = new File(_remotingFileName);
2236
2237        if (!outputFile.exists()) {
2238            return;
2239        }
2240
2241        String content = FileUtil.read(outputFile);
2242        String newContent = content;
2243
2244        int x = content.indexOf("<bean ");
2245        int y = content.lastIndexOf("</bean>") + 8;
2246
2247        if (x != -1) {
2248            newContent =
2249                content.substring(0, x - 1) + sm.toString() +
2250                    content.substring(y, content.length());
2251        }
2252        else {
2253            x = content.indexOf("</beans>");
2254
2255            newContent =
2256                content.substring(0, x) + sm.toString() +
2257                    content.substring(x, content.length());
2258        }
2259
2260        newContent = _formatXML(newContent);
2261
2262        if (!content.equals(newContent)) {
2263            FileUtil.write(outputFile, newContent);
2264
2265            System.out.println(outputFile.toString());
2266        }
2267    }
2268
2269    private void _createService(Entity entity, int sessionType)
2270        throws Exception {
2271
2272        String serviceComments = "This is a remote service. Methods of this service are expected to have security checks based on the propagated JAAS credentials because this service can be accessed remotely.";
2273
2274        JavaClass javaClass = _getJavaClass(_outputPath + "/service/impl/" + entity.getName() + (sessionType != _REMOTE ? "Local" : "") + "ServiceImpl.java");
2275
2276        JavaMethod[] methods = javaClass.getMethods();
2277
2278        if (sessionType == _LOCAL) {
2279            if (javaClass.getSuperClass().getValue().endsWith(
2280                    entity.getName() + "LocalServiceBaseImpl")) {
2281
2282                JavaClass parentJavaClass = _getJavaClass(
2283                    _outputPath + "/service/base/" + entity.getName() +
2284                        "LocalServiceBaseImpl.java");
2285
2286                JavaMethod[] parentMethods = parentJavaClass.getMethods();
2287
2288                JavaMethod[] allMethods = new JavaMethod[parentMethods.length + methods.length];
2289
2290                ArrayUtil.combine(parentMethods, methods, allMethods);
2291
2292                methods = allMethods;
2293            }
2294
2295            serviceComments = "This is a local service. Methods of this service will not have security checks based on the propagated JAAS credentials because this service can only be accessed from within the same VM.";
2296        }
2297
2298        Map<String, Object> context = _getContext();
2299
2300        context.put("entity", entity);
2301        context.put("methods", methods);
2302        context.put("sessionTypeName",_getSessionTypeName(sessionType));
2303        context.put("serviceComments", serviceComments);
2304
2305        // Content
2306
2307        String content = _processTemplate(_tplService, context);
2308
2309        // Write file
2310
2311        File ejbFile = new File(
2312            _serviceOutputPath + "/service/" + entity.getName() +
2313                _getSessionTypeName(sessionType) + "Service.java");
2314
2315        Map<String, Object> jalopySettings = new HashMap<String, Object>();
2316
2317        jalopySettings.put("keepJavadoc", Boolean.TRUE);
2318
2319        writeFile(ejbFile, content, jalopySettings);
2320    }
2321
2322    private void _createServiceBaseImpl(Entity entity, int sessionType)
2323        throws Exception {
2324
2325        Map<String, Object> context = _getContext();
2326
2327        context.put("entity", entity);
2328        context.put("sessionTypeName",_getSessionTypeName(sessionType));
2329        context.put(
2330            "referenceList", _mergeReferenceList(entity.getReferenceList()));
2331
2332        // Content
2333
2334        String content = _processTemplate(_tplServiceBaseImpl, context);
2335
2336        // Write file
2337
2338        File ejbFile = new File(
2339            _outputPath + "/service/base/" + entity.getName() +
2340                _getSessionTypeName(sessionType) + "ServiceBaseImpl.java");
2341
2342        writeFile(ejbFile, content);
2343    }
2344
2345    private void _createServiceFactory(Entity entity, int sessionType)
2346        throws Exception {
2347
2348        Map<String, Object> context = _getContext();
2349
2350        context.put("entity", entity);
2351        context.put("sessionTypeName", _getSessionTypeName(sessionType));
2352
2353        // Content
2354
2355        String content = _processTemplate(_tplServiceFactory, context);
2356
2357        // Write file
2358
2359        File ejbFile = new File(
2360            _serviceOutputPath + "/service/" + entity.getName() +
2361                _getSessionTypeName(sessionType) + "ServiceFactory.java");
2362
2363        Map<String, Object> jalopySettings = new HashMap<String, Object>();
2364
2365        jalopySettings.put("keepJavadoc", Boolean.TRUE);
2366
2367        writeFile(ejbFile, content, jalopySettings);
2368    }
2369
2370    private void _createServiceHttp(Entity entity) throws Exception {
2371        JavaClass javaClass = _getJavaClass(
2372            _outputPath + "/service/impl/" + entity.getName() +
2373                "ServiceImpl.java");
2374
2375        Map<String, Object> context = _getContext();
2376
2377        context.put("entity", entity);
2378        context.put("methods", javaClass.getMethods());
2379        context.put("hasHttpMethods", new Boolean(_hasHttpMethods(javaClass)));
2380
2381        // Content
2382
2383        String content = _processTemplate(_tplServiceHttp, context);
2384
2385        // Write file
2386
2387        File ejbFile = new File(
2388            _outputPath + "/service/http/" + entity.getName() +
2389                "ServiceHttp.java");
2390
2391        Map<String, Object> jalopySettings = new HashMap<String, Object>();
2392
2393        jalopySettings.put("keepJavadoc", Boolean.TRUE);
2394
2395        writeFile(ejbFile, content, jalopySettings);
2396    }
2397
2398    private void _createServiceImpl(Entity entity, int sessionType)
2399        throws Exception {
2400
2401        Map<String, Object> context = _getContext();
2402
2403        context.put("entity", entity);
2404        context.put("sessionTypeName", _getSessionTypeName(sessionType));
2405
2406        // Content
2407
2408        String content = _processTemplate(_tplServiceImpl, context);
2409
2410        // Write file
2411
2412        File ejbFile = new File(
2413            _outputPath + "/service/impl/" + entity.getName() +
2414                _getSessionTypeName(sessionType) + "ServiceImpl.java");
2415
2416        if (!ejbFile.exists()) {
2417            writeFile(ejbFile, content);
2418        }
2419    }
2420
2421    private void _createServiceJSON(Entity entity) throws Exception {
2422        JavaClass javaClass = _getJavaClass(
2423            _outputPath + "/service/impl/" + entity.getName() +
2424                "ServiceImpl.java");
2425
2426        Map<String, Object> context = _getContext();
2427
2428        context.put("entity", entity);
2429        context.put("methods", javaClass.getMethods());
2430
2431        // Content
2432
2433        String content = _processTemplate(_tplServiceJson, context);
2434
2435        // Write file
2436
2437        File ejbFile = new File(
2438            _outputPath + "/service/http/" + entity.getName() +
2439                "ServiceJSON.java");
2440
2441        Map<String, Object> jalopySettings = new HashMap<String, Object>();
2442
2443        jalopySettings.put("keepJavadoc", Boolean.TRUE);
2444
2445        writeFile(ejbFile, content, jalopySettings);
2446    }
2447
2448    private void _createServiceJSONSerializer(Entity entity) throws Exception {
2449        Map<String, Object> context = _getContext();
2450
2451        context.put("entity", entity);
2452
2453        // Content
2454
2455        String content = _processTemplate(_tplServiceJsonSerializer, context);
2456
2457        // Write file
2458
2459        File ejbFile = new File(
2460            _outputPath + "/service/http/" + entity.getName() +
2461                "JSONSerializer.java");
2462
2463        Map<String, Object> jalopySettings = new HashMap<String, Object>();
2464
2465        jalopySettings.put("keepJavadoc", Boolean.TRUE);
2466
2467        writeFile(ejbFile, content, jalopySettings);
2468    }
2469
2470    private void _createServiceSoap(Entity entity) throws Exception {
2471        JavaClass javaClass = _getJavaClass(
2472            _outputPath + "/service/impl/" + entity.getName() +
2473                "ServiceImpl.java");
2474
2475        Map<String, Object> context = _getContext();
2476
2477        context.put("entity", entity);
2478        context.put("methods", javaClass.getMethods());
2479
2480        // Content
2481
2482        String content = _processTemplate(_tplServiceSoap, context);
2483
2484        // Write file
2485
2486        File ejbFile = new File(
2487            _outputPath + "/service/http/" + entity.getName() +
2488                "ServiceSoap.java");
2489
2490        Map<String, Object> jalopySettings = new HashMap<String, Object>();
2491
2492        jalopySettings.put("keepJavadoc", Boolean.TRUE);
2493
2494        writeFile(ejbFile, content, jalopySettings);
2495    }
2496
2497    private void _createServiceUtil(Entity entity, int sessionType)
2498        throws Exception {
2499
2500        JavaClass javaClass = _getJavaClass(
2501            _serviceOutputPath + "/service/" + entity.getName() +
2502                (sessionType != _REMOTE ? "Local" : "") + "Service.java");
2503
2504        Map<String, Object> context = _getContext();
2505
2506        context.put("entity", entity);
2507        context.put("methods", javaClass.getMethods());
2508        context.put("sessionTypeName", _getSessionTypeName(sessionType));
2509
2510        // Content
2511
2512        String content = _processTemplate(_tplServiceUtil, context);
2513
2514        // Write file
2515
2516        File ejbFile = new File(
2517            _serviceOutputPath + "/service/" + entity.getName() +
2518                _getSessionTypeName(sessionType) + "ServiceUtil.java");
2519
2520        Map<String, Object> jalopySettings = new HashMap<String, Object>();
2521
2522        jalopySettings.put("keepJavadoc", Boolean.TRUE);
2523
2524        writeFile(ejbFile, content, jalopySettings);
2525    }
2526
2527    private void _createSpringDataSourceXML() throws Exception {
2528        if (Validator.isNull(_springDataSourceFileName)) {
2529            return;
2530        }
2531
2532        // Content
2533
2534        String content = _processTemplate(_tplSpringDataSourceXml);
2535
2536        // Write file
2537
2538        File ejbFile = new File(_springDataSourceFileName);
2539
2540        FileUtil.write(ejbFile, content, true);
2541    }
2542
2543    private void _createSpringUtil() throws Exception {
2544        if (_springUtilPackage.equals("com.liferay.portal.spring.util")) {
2545            return;
2546        }
2547
2548        // Content
2549
2550        String content = _processTemplate(_tplSpringUtil);
2551
2552        // Write file
2553
2554        File ejbFile = new File(
2555            _implDir + "/" + StringUtil.replace(_springUtilPackage, ".", "/") +
2556                "/SpringUtil.java");
2557
2558        FileUtil.write(ejbFile, content, true);
2559    }
2560
2561    private void _createSpringXML() throws Exception {
2562        Map<String, Object> context = _getContext();
2563
2564        context.put("entities", _ejbList);
2565
2566        // Content
2567
2568        String content = _processTemplate(_tplSpringXml, context);
2569
2570        File xmlFile = new File(_springFileName);
2571
2572        if (!xmlFile.exists()) {
2573            String xml =
2574                "<?xml version=\"1.0\"?>\n" +
2575                "<!DOCTYPE beans PUBLIC \"-//SPRING//DTD BEAN//EN\" \"http://www.springframework.org/dtd/spring-beans.dtd\">\n" +
2576                "\n" +
2577                "<beans>\n" +
2578                "</beans>";
2579
2580            FileUtil.write(xmlFile, xml);
2581        }
2582
2583        String oldContent = FileUtil.read(xmlFile);
2584        String newContent = _fixSpringXML(oldContent);
2585
2586        int x = oldContent.indexOf("<beans>");
2587        int y = oldContent.lastIndexOf("</beans>");
2588
2589        int firstSession = newContent.indexOf(
2590            "<bean id=\"" + _packagePath + ".service.", x);
2591
2592        int lastSession = newContent.lastIndexOf(
2593            "<bean id=\"" + _packagePath + ".service.", y);
2594
2595        if (firstSession == -1 || firstSession > y) {
2596            x = newContent.indexOf("</beans>");
2597            newContent =
2598                newContent.substring(0, x) + content +
2599                newContent.substring(x, newContent.length());
2600        }
2601        else {
2602            firstSession = newContent.lastIndexOf("<bean", firstSession) - 1;
2603            lastSession = newContent.indexOf("</bean>", lastSession) + 8;
2604
2605            newContent =
2606                newContent.substring(0, firstSession) + content +
2607                newContent.substring(lastSession, newContent.length());
2608        }
2609
2610        newContent = _formatXML(newContent);
2611
2612        if (!oldContent.equals(newContent)) {
2613            FileUtil.write(xmlFile, newContent);
2614        }
2615    }
2616
2617    private void _createSQLIndexes() throws IOException {
2618        if (!FileUtil.exists(_sqlDir)) {
2619            return;
2620        }
2621
2622        // indexes.sql
2623
2624        File sqlFile = new File(_sqlDir + "/" + _sqlIndexesFileName);
2625
2626        if (!sqlFile.exists()) {
2627            FileUtil.write(sqlFile, "");
2628        }
2629
2630        Map<String, String> indexSQLs = new TreeMap<String, String>();
2631
2632        BufferedReader br = new BufferedReader(new FileReader(sqlFile));
2633
2634        while (true) {
2635            String indexSQL = br.readLine();
2636
2637            if (indexSQL == null) {
2638                break;
2639            }
2640
2641            if (Validator.isNotNull(indexSQL.trim())) {
2642                int pos = indexSQL.indexOf(" on ");
2643
2644                String indexSpec = indexSQL.substring(pos + 4);
2645
2646                indexSQLs.put(indexSpec, indexSQL);
2647            }
2648        }
2649
2650        br.close();
2651
2652        // indexes.properties
2653
2654        File propsFile = new File(
2655            _sqlDir + "/" + _sqlIndexesPropertiesFileName);
2656
2657        if (!propsFile.exists()) {
2658            FileUtil.write(propsFile, "");
2659        }
2660
2661        Map<String, String> indexProps = new TreeMap<String, String>();
2662
2663        br = new BufferedReader(new FileReader(propsFile));
2664
2665        while (true) {
2666            String indexMapping = br.readLine();
2667
2668            if (indexMapping == null) {
2669                break;
2670            }
2671
2672            if (Validator.isNotNull(indexMapping.trim())) {
2673                String[] splitIndexMapping = indexMapping.split("\\=");
2674
2675                indexProps.put(splitIndexMapping[1], splitIndexMapping[0]);
2676            }
2677        }
2678
2679        br.close();
2680
2681        // indexes.sql
2682
2683        for (int i = 0; i < _ejbList.size(); i++) {
2684            Entity entity = _ejbList.get(i);
2685
2686            List<EntityFinder> finderList = entity.getFinderList();
2687
2688            for (int j = 0; j < finderList.size(); j++) {
2689                EntityFinder finder = finderList.get(j);
2690
2691                if (finder.isDBIndex()) {
2692                    StringMaker sm = new StringMaker();
2693
2694                    sm.append(entity.getTable() + " (");
2695
2696                    List<EntityColumn> finderColsList = finder.getColumns();
2697
2698                    for (int k = 0; k < finderColsList.size(); k++) {
2699                        EntityColumn col = finderColsList.get(k);
2700
2701                        sm.append(col.getDBName());
2702
2703                        if ((k + 1) != finderColsList.size()) {
2704                            sm.append(", ");
2705                        }
2706                    }
2707
2708                    sm.append(");");
2709
2710                    String indexSpec = sm.toString();
2711
2712                    String indexHash =
2713                        Integer.toHexString(indexSpec.hashCode()).toUpperCase();
2714
2715                    String indexName = "IX_" + indexHash;
2716
2717                    sm = new StringMaker();
2718
2719                    sm.append("create index " + indexName + " on ");
2720                    sm.append(indexSpec);
2721
2722                    indexSQLs.put(indexSpec, sm.toString());
2723
2724                    String finderName =
2725                        entity.getTable() + StringPool.PERIOD +
2726                            finder.getName();
2727
2728                    indexProps.put(finderName, indexName);
2729                }
2730            }
2731        }
2732
2733        StringMaker sm = new StringMaker();
2734
2735        Iterator<String> itr = indexSQLs.values().iterator();
2736
2737        String prevEntityName = null;
2738
2739        while (itr.hasNext()) {
2740            String indexSQL = itr.next();
2741
2742            String entityName = indexSQL.split(" ")[4];
2743
2744            if ((prevEntityName != null) &&
2745                (!prevEntityName.equals(entityName))) {
2746
2747                sm.append("\n");
2748            }
2749
2750            sm.append(indexSQL);
2751
2752            if (itr.hasNext()) {
2753                sm.append("\n");
2754            }
2755
2756            prevEntityName = entityName;
2757        }
2758
2759        FileUtil.write(sqlFile, sm.toString(), true);
2760
2761        // indexes.properties
2762
2763        sm = new StringMaker();
2764
2765        itr = indexProps.keySet().iterator();
2766
2767        prevEntityName = null;
2768
2769        while (itr.hasNext()) {
2770            String finderName = itr.next();
2771
2772            String indexName = indexProps.get(finderName);
2773
2774            String entityName = finderName.split("\\.")[0];
2775
2776            if ((prevEntityName != null) &&
2777                (!prevEntityName.equals(entityName))) {
2778
2779                sm.append("\n");
2780            }
2781
2782            sm.append(indexName + StringPool.EQUAL + finderName);
2783
2784            if (itr.hasNext()) {
2785                sm.append("\n");
2786            }
2787
2788            prevEntityName = entityName;
2789        }
2790
2791        FileUtil.write(propsFile, sm.toString(), true);
2792    }
2793
2794    private void _createSQLMappingTables(
2795            File sqlFile, String newCreateTableString,
2796            EntityMapping entityMapping, boolean addMissingTables)
2797        throws IOException {
2798
2799        if (!sqlFile.exists()) {
2800            FileUtil.write(sqlFile, StringPool.BLANK);
2801        }
2802
2803        String content = FileUtil.read(sqlFile);
2804
2805        int x = content.indexOf(
2806            _CREATE_TABLE + entityMapping.getTable() + " (");
2807        int y = content.indexOf(");", x);
2808
2809        if (x != -1) {
2810            String oldCreateTableString = content.substring(x + 1, y);
2811
2812            if (!oldCreateTableString.equals(newCreateTableString)) {
2813                content =
2814                    content.substring(0, x) + newCreateTableString +
2815                        content.substring(y + 2, content.length());
2816
2817                FileUtil.write(sqlFile, content);
2818            }
2819        }
2820        else if (addMissingTables) {
2821            StringMaker sm = new StringMaker();
2822
2823            BufferedReader br = new BufferedReader(new StringReader(content));
2824
2825            String line = null;
2826            boolean appendNewTable = true;
2827
2828            while ((line = br.readLine()) != null) {
2829                if (appendNewTable && line.startsWith(_CREATE_TABLE)) {
2830                    x = _CREATE_TABLE.length();
2831                    y = line.indexOf(" ", x);
2832
2833                    String tableName = line.substring(x, y);
2834
2835                    if (tableName.compareTo(entityMapping.getTable()) > 0) {
2836                        sm.append(newCreateTableString + "\n\n");
2837
2838                        appendNewTable = false;
2839                    }
2840                }
2841
2842                sm.append(line);
2843                sm.append("\n");
2844            }
2845
2846            if (appendNewTable) {
2847                sm.append("\n" + newCreateTableString);
2848            }
2849
2850            br.close();
2851
2852            FileUtil.write(sqlFile, sm.toString(), true);
2853        }
2854    }
2855
2856    private void _createSQLSequences() throws IOException {
2857        if (!FileUtil.exists(_sqlDir)) {
2858            return;
2859        }
2860
2861        File sqlFile = new File(_sqlDir + "/" + _sqlSequencesFileName);
2862
2863        if (!sqlFile.exists()) {
2864            FileUtil.write(sqlFile, "");
2865        }
2866
2867        Set<String> sequenceSQLs = new TreeSet<String>();
2868
2869        BufferedReader br = new BufferedReader(new FileReader(sqlFile));
2870
2871        while (true) {
2872            String sequenceSQL = br.readLine();
2873
2874            if (sequenceSQL == null) {
2875                break;
2876            }
2877
2878            if (Validator.isNotNull(sequenceSQL)) {
2879                sequenceSQLs.add(sequenceSQL);
2880            }
2881        }
2882
2883        br.close();
2884
2885        for (int i = 0; i < _ejbList.size(); i++) {
2886            Entity entity = _ejbList.get(i);
2887
2888            List<EntityColumn> columnList = entity.getColumnList();
2889
2890            for (int j = 0; j < columnList.size(); j++) {
2891                EntityColumn column = columnList.get(j);
2892
2893                if ("sequence".equals(column.getIdType())) {
2894                    StringMaker sm = new StringMaker();
2895
2896                    String sequenceName = column.getIdParam();
2897
2898                    if (sequenceName.length() > 30) {
2899                        sequenceName = sequenceName.substring(0, 30);
2900                    }
2901
2902                    sm.append("create sequence " + sequenceName + ";");
2903
2904                    String sequenceSQL = sm.toString();
2905
2906                    if (!sequenceSQLs.contains(sequenceSQL)) {
2907                        sequenceSQLs.add(sequenceSQL);
2908                    }
2909                }
2910            }
2911        }
2912
2913        StringMaker sm = new StringMaker();
2914
2915        Iterator<String> itr = sequenceSQLs.iterator();
2916
2917        while (itr.hasNext()) {
2918            String sequenceSQL = itr.next();
2919
2920            sm.append(sequenceSQL);
2921
2922            if (itr.hasNext()) {
2923                sm.append("\n");
2924            }
2925        }
2926
2927        FileUtil.write(sqlFile, sm.toString(), true);
2928    }
2929
2930    private void _createSQLTables() throws IOException {
2931        if (!FileUtil.exists(_sqlDir)) {
2932            return;
2933        }
2934
2935        File sqlFile = new File(_sqlDir + "/" + _sqlFileName);
2936
2937        if (!sqlFile.exists()) {
2938            FileUtil.write(sqlFile, StringPool.BLANK);
2939        }
2940
2941        for (int i = 0; i < _ejbList.size(); i++) {
2942            Entity entity = _ejbList.get(i);
2943
2944            String createTableSQL = _getCreateTableSQL(entity);
2945
2946            if (Validator.isNotNull(createTableSQL)) {
2947                _createSQLTables(sqlFile, createTableSQL, entity, true);
2948
2949                File updateSQLFile = new File(
2950                    _sqlDir + "/update-4.4.0-5.0.0.sql");
2951
2952                if (updateSQLFile.exists()) {
2953                    _createSQLTables(
2954                        updateSQLFile, createTableSQL, entity, false);
2955                }
2956            }
2957        }
2958
2959        for (Map.Entry<String, EntityMapping> entry :
2960                _entityMappings.entrySet()) {
2961
2962            EntityMapping entityMapping = entry.getValue();
2963
2964            String createMappingTableSQL = _getCreateMappingTableSQL(
2965                entityMapping);
2966
2967            if (Validator.isNotNull(createMappingTableSQL)) {
2968                _createSQLMappingTables(
2969                    sqlFile, createMappingTableSQL, entityMapping, true);
2970            }
2971        }
2972    }
2973
2974    private void _createSQLTables(
2975            File sqlFile, String newCreateTableString, Entity entity,
2976            boolean addMissingTables)
2977        throws IOException {
2978
2979        if (!sqlFile.exists()) {
2980            FileUtil.write(sqlFile, StringPool.BLANK);
2981        }
2982
2983        String content = FileUtil.read(sqlFile);
2984
2985        int x = content.indexOf(_CREATE_TABLE + entity.getTable() + " (");
2986        int y = content.indexOf(");", x);
2987
2988        if (x != -1) {
2989            String oldCreateTableString = content.substring(x + 1, y);
2990
2991            if (!oldCreateTableString.equals(newCreateTableString)) {
2992                content =
2993                    content.substring(0, x) + newCreateTableString +
2994                        content.substring(y + 2, content.length());
2995
2996                FileUtil.write(sqlFile, content);
2997            }
2998        }
2999        else if (addMissingTables) {
3000            StringMaker sm = new StringMaker();
3001
3002            BufferedReader br = new BufferedReader(new StringReader(content));
3003
3004            String line = null;
3005            boolean appendNewTable = true;
3006
3007            while ((line = br.readLine()) != null) {
3008                if (appendNewTable && line.startsWith(_CREATE_TABLE)) {
3009                    x = _CREATE_TABLE.length();
3010                    y = line.indexOf(" ", x);
3011
3012                    String tableName = line.substring(x, y);
3013
3014                    if (tableName.compareTo(entity.getTable()) > 0) {
3015                        sm.append(newCreateTableString + "\n\n");
3016
3017                        appendNewTable = false;
3018                    }
3019                }
3020
3021                sm.append(line);
3022                sm.append("\n");
3023            }
3024
3025            if (appendNewTable) {
3026                sm.append("\n" + newCreateTableString);
3027            }
3028
3029            br.close();
3030
3031            FileUtil.write(sqlFile, sm.toString(), true);
3032        }
3033    }
3034
3035    private String _fixHBMXML(String content) throws IOException {
3036        StringMaker sm = new StringMaker();
3037
3038        BufferedReader br = new BufferedReader(new StringReader(content));
3039
3040        String line = null;
3041
3042        while ((line = br.readLine()) != null) {
3043            if (line.startsWith("\t<class name=\"")) {
3044                line = StringUtil.replace(
3045                    line,
3046                    new String[] {
3047                        ".service.persistence.", "HBM\" table=\""
3048                    },
3049                    new String[] {
3050                        ".model.", "\" table=\""
3051                    });
3052
3053                if (line.indexOf(".model.impl.") == -1) {
3054                    line = StringUtil.replace(
3055                        line,
3056                        new String[] {
3057                            ".model.", "\" table=\""
3058                        },
3059                        new String[] {
3060                            ".model.impl.", "Impl\" table=\""
3061                        });
3062                }
3063            }
3064
3065            sm.append(line);
3066            sm.append('\n');
3067        }
3068
3069        br.close();
3070
3071        return sm.toString().trim();
3072    }
3073
3074    private String _fixSpringXML(String content) throws IOException {
3075        return StringUtil.replace(content, ".service.spring.", ".service.");
3076    }
3077
3078    private String _formatXML(String xml)
3079        throws DocumentException, IOException {
3080
3081        String doctype = null;
3082
3083        int x = xml.indexOf("<!DOCTYPE");
3084
3085        if (x != -1) {
3086            int y = xml.indexOf(">", x) + 1;
3087
3088            doctype = xml.substring(x, y);
3089
3090            xml = xml.substring(0, x) + "\n" + xml.substring(y);
3091        }
3092
3093        xml = StringUtil.replace(xml, '\r', "");
3094        xml = XMLFormatter.toString(xml);
3095        xml = StringUtil.replace(xml, "\"/>", "\" />");
3096
3097        if (Validator.isNotNull(doctype)) {
3098            x = xml.indexOf("?>") + 2;
3099
3100            xml = xml.substring(0, x) + "\n" + doctype + xml.substring(x);
3101        }
3102
3103        return xml;
3104    }
3105
3106    private Map<String, Object> _getContext() throws TemplateModelException {
3107        BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
3108
3109        TemplateHashModel staticModels = wrapper.getStaticModels();
3110
3111        Map<String, Object> context = new HashMap<String, Object>();
3112
3113        context.put("hbmFileName", _hbmFileName);
3114        context.put("modelHintsFileName", _modelHintsFileName);
3115        context.put("springFileName", _springFileName);
3116        context.put("springDataSourceFileName", _springDataSourceFileName);
3117        context.put("apiDir", _apiDir);
3118        context.put("implDir", _implDir);
3119        context.put("jsonFileName", _jsonFileName);
3120        context.put("sqlDir", _sqlDir);
3121        context.put("sqlFileName", _sqlFileName);
3122        context.put("baseModelImplPackage", _baseModelImplPackage);
3123        context.put("basePersistencePackage", _basePersistencePackage);
3124        context.put("beanLocatorUtilPackage", _beanLocatorUtilPackage);
3125        context.put("principalBeanPackage", _principalBeanPackage);
3126        context.put("propsUtilPackage", _propsUtilPackage);
3127        context.put("springHibernatePackage", _springHibernatePackage);
3128        context.put("springUtilPackage", _springUtilPackage);
3129        context.put("portletName", _portletName);
3130        context.put("portletShortName", _portletShortName);
3131        context.put("portletPackageName", _portletPackageName);
3132        context.put("outputPath", _outputPath);
3133        context.put("serviceOutputPath", _serviceOutputPath);
3134        context.put("packagePath", _packagePath);
3135        context.put("serviceBuilder", this);
3136
3137        context.put("arrayUtil", ArrayUtil_IW.getInstance());
3138        context.put(
3139            "modelHintsUtil",
3140            staticModels.get("com.liferay.portal.model.ModelHintsUtil"));
3141        context.put("stringUtil", StringUtil_IW.getInstance());
3142        context.put("system", staticModels.get("java.lang.System"));
3143        context.put("tempMap", wrapper.wrap(new HashMap<String, Object>()));
3144        context.put(
3145            "validator",
3146            staticModels.get("com.liferay.portal.kernel.util.Validator"));
3147
3148        return context;
3149    }
3150
3151    private String _getCreateMappingTableSQL(EntityMapping entityMapping)
3152        throws IOException {
3153
3154        Entity[] entities = new Entity[2];
3155
3156        for (int i = 0; i < entities.length; i++) {
3157            entities[i] = getEntity(entityMapping.getEntity(i));
3158
3159            if (entities[i] == null) {
3160                return null;
3161            }
3162        }
3163
3164        StringMaker sm = new StringMaker();
3165
3166        sm.append(_CREATE_TABLE + entityMapping.getTable() + " (\n");
3167
3168        for (Entity entity : entities) {
3169            List<EntityColumn> pkList = entity.getPKList();
3170
3171            for (int i = 0; i < pkList.size(); i++) {
3172                EntityColumn col = pkList.get(i);
3173
3174                String colName = col.getName();
3175                String colType = col.getType();
3176
3177                sm.append("\t" + col.getDBName());
3178                sm.append(" ");
3179
3180                if (colType.equalsIgnoreCase("boolean")) {
3181                    sm.append("BOOLEAN");
3182                }
3183                else if (colType.equalsIgnoreCase("double") ||
3184                         colType.equalsIgnoreCase("float")) {
3185
3186                    sm.append("DOUBLE");
3187                }
3188                else if (colType.equals("int") ||
3189                         colType.equals("Integer") ||
3190                         colType.equalsIgnoreCase("short")) {
3191
3192                    sm.append("INTEGER");
3193                }
3194                else if (colType.equalsIgnoreCase("long")) {
3195                    sm.append("LONG");
3196                }
3197                else if (colType.equals("String")) {
3198                    Map<String, String> hints = ModelHintsUtil.getHints(
3199                        _packagePath + ".model." + entity.getName(), colName);
3200
3201                    int maxLength = 75;
3202
3203                    if (hints != null) {
3204                        maxLength = GetterUtil.getInteger(
3205                            hints.get("max-length"), maxLength);
3206                    }
3207
3208                    if (maxLength < 4000) {
3209                        sm.append("VARCHAR(" + maxLength + ")");
3210                    }
3211                    else if (maxLength == 4000) {
3212                        sm.append("STRING");
3213                    }
3214                    else if (maxLength > 4000) {
3215                        sm.append("TEXT");
3216                    }
3217                }
3218                else if (colType.equals("Date")) {
3219                    sm.append("DATE null");
3220                }
3221                else {
3222                    sm.append("invalid");
3223                }
3224
3225                if (col.isPrimary()) {
3226                    sm.append(" not null");
3227                }
3228
3229                sm.append(",\n");
3230            }
3231        }
3232
3233        sm.append("\tprimary key (");
3234
3235        for (int i = 0; i < entities.length; i++) {
3236            Entity entity = entities[i];
3237
3238            List<EntityColumn> pkList = entity.getPKList();
3239
3240            for (int j = 0; j < pkList.size(); j++) {
3241                EntityColumn col = pkList.get(j);
3242
3243                String colName = col.getName();
3244
3245                if ((i != 0) || (j != 0)) {
3246                    sm.append(", ");
3247                }
3248
3249                sm.append(colName);
3250            }
3251        }
3252
3253        sm.append(")\n");
3254        sm.append(");");
3255
3256        return sm.toString();
3257    }
3258
3259    private String _getCreateTableSQL(Entity entity) {
3260        List<EntityColumn> pkList = entity.getPKList();
3261        List<EntityColumn> regularColList = entity.getRegularColList();
3262
3263        if (regularColList.size() == 0) {
3264            return null;
3265        }
3266
3267        StringMaker sm = new StringMaker();
3268
3269        sm.append(_CREATE_TABLE + entity.getTable() + " (\n");
3270
3271        for (int i = 0; i < regularColList.size(); i++) {
3272            EntityColumn col = regularColList.get(i);
3273
3274            String colName = col.getName();
3275            String colType = col.getType();
3276            String colIdType = col.getIdType();
3277
3278            sm.append("\t" + col.getDBName());
3279            sm.append(" ");
3280
3281            if (colType.equalsIgnoreCase("boolean")) {
3282                sm.append("BOOLEAN");
3283            }
3284            else if (colType.equalsIgnoreCase("double") ||
3285                     colType.equalsIgnoreCase("float")) {
3286
3287                sm.append("DOUBLE");
3288            }
3289            else if (colType.equals("int") ||
3290                     colType.equals("Integer") ||
3291                     colType.equalsIgnoreCase("short")) {
3292
3293                sm.append("INTEGER");
3294            }
3295            else if (colType.equalsIgnoreCase("long")) {
3296                sm.append("LONG");
3297            }
3298            else if (colType.equals("String")) {
3299                Map<String, String> hints = ModelHintsUtil.getHints(
3300                    _packagePath + ".model." + entity.getName(), colName);
3301
3302                int maxLength = 75;
3303
3304                if (hints != null) {
3305                    maxLength = GetterUtil.getInteger(
3306                        hints.get("max-length"), maxLength);
3307                }
3308
3309                if (maxLength < 4000) {
3310                    sm.append("VARCHAR(" + maxLength + ")");
3311                }
3312                else if (maxLength == 4000) {
3313                    sm.append("STRING");
3314                }
3315                else if (maxLength > 4000) {
3316                    sm.append("TEXT");
3317                }
3318            }
3319            else if (colType.equals("Date")) {
3320                sm.append("DATE null");
3321            }
3322            else {
3323                sm.append("invalid");
3324            }
3325
3326            if (col.isPrimary()) {
3327                sm.append(" not null");
3328
3329                if (!entity.hasCompoundPK()) {
3330                    sm.append(" primary key");
3331                }
3332            }
3333            else if (colType.equals("String")) {
3334                sm.append(" null");
3335            }
3336
3337            if (Validator.isNotNull(colIdType) &&
3338                colIdType.equals("identity")) {
3339
3340                sm.append(" IDENTITY");
3341            }
3342
3343            if (((i + 1) != regularColList.size()) ||
3344                (entity.hasCompoundPK())) {
3345
3346                sm.append(",");
3347            }
3348
3349            sm.append("\n");
3350        }
3351
3352        if (entity.hasCompoundPK()) {
3353            sm.append("\tprimary key (");
3354
3355            for (int j = 0; j < pkList.size(); j++) {
3356                EntityColumn pk = pkList.get(j);
3357
3358                sm.append(pk.getDBName());
3359
3360                if ((j + 1) != pkList.size()) {
3361                    sm.append(", ");
3362                }
3363            }
3364
3365            sm.append(")\n");
3366        }
3367
3368        sm.append(");");
3369
3370        return sm.toString();
3371    }
3372
3373    private String _getDimensions(Type type) {
3374        String dimensions = "";
3375
3376        for (int i = 0; i < type.getDimensions(); i++) {
3377            dimensions += "[]";
3378        }
3379
3380        return dimensions;
3381    }
3382
3383    private JavaClass _getJavaClass(String fileName) throws IOException {
3384        int pos = fileName.indexOf(_implDir + "/") + _implDir.length();
3385
3386        String srcFile = fileName.substring(pos + 1, fileName.length());
3387        String className = StringUtil.replace(
3388            srcFile.substring(0, srcFile.length() - 5), "/", ".");
3389
3390        JavaDocBuilder builder = new JavaDocBuilder();
3391
3392        File file = new File(fileName);
3393
3394        if (!file.exists()) {
3395            return null;
3396        }
3397
3398        builder.addSource(file);
3399
3400        return builder.getClassByName(className);
3401    }
3402
3403    private String _getSessionTypeName(int sessionType) {
3404        if (sessionType == _LOCAL) {
3405            return "Local";
3406        }
3407        else {
3408            return "";
3409        }
3410    }
3411
3412    private String _getTplProperty(String key, String defaultValue) {
3413        return System.getProperty("service.tpl." + key, defaultValue);
3414    }
3415
3416    private boolean _hasHttpMethods(JavaClass javaClass) {
3417        JavaMethod[] methods = javaClass.getMethods();
3418
3419        for (int i = 0; i < methods.length; i++) {
3420            JavaMethod javaMethod = methods[i];
3421
3422            if (!javaMethod.isConstructor() && javaMethod.isPublic() &&
3423                isCustomMethod(javaMethod)) {
3424
3425                return true;
3426            }
3427        }
3428
3429        return false;
3430    }
3431
3432    private List<Entity> _mergeReferenceList(List<Entity> referenceList) {
3433        List<Entity> list = new ArrayList<Entity>(
3434            _ejbList.size() + referenceList.size());
3435
3436        list.addAll(_ejbList);
3437        list.addAll(referenceList);
3438
3439        return list;
3440    }
3441
3442    private String _processTemplate(String name) throws Exception {
3443        return _processTemplate(name, _getContext());
3444    }
3445
3446    private String _processTemplate(String name, Map<String, Object> context)
3447        throws Exception {
3448
3449        return FreeMarkerUtil.process(name, context);
3450    }
3451
3452    private static final int _REMOTE = 0;
3453
3454    private static final int _LOCAL = 1;
3455
3456    private static final String _CREATE_TABLE = "create table ";
3457
3458    private static final String _TPL_ROOT = "com/liferay/portal/tools/servicebuilder/dependencies/";
3459
3460    private String _tplBadColumnNames = _TPL_ROOT + "bad_column_names.txt";
3461    private String _tplBadTableNames = _TPL_ROOT + "bad_table_names.txt";
3462    private String _tplBaseModeImpl = _TPL_ROOT + "base_mode_impl.ftl";
3463    private String _tplBasePersistence = _TPL_ROOT + "base_persistence.ftl";
3464    private String _tplBeanLocatorUtil = _TPL_ROOT + "bean_locator_util.ftl";
3465    private String _tplDynamicDialect = _TPL_ROOT + "dynamic_dialect.ftl";
3466    private String _tplEjbPk = _TPL_ROOT + "ejb_pk.ftl";
3467    private String _tplException = _TPL_ROOT + "exception.ftl";
3468    private String _tplExtendedModel = _TPL_ROOT + "extended_model.ftl";
3469    private String _tplExtendedModelImpl =
3470        _TPL_ROOT + "extended_model_impl.ftl";
3471    private String _tplFinder = _TPL_ROOT + "finder.ftl";
3472    private String _tplFinderCache = _TPL_ROOT + "finder_cache.ftl";
3473    private String _tplFinderUtil = _TPL_ROOT + "finder_util.ftl";
3474    private String _tplHbmXml = _TPL_ROOT + "hbm_xml.ftl";
3475    private String _tplHibernateConfiguration =
3476        _TPL_ROOT + "hibernate_configuration.ftl";
3477    private String _tplHibernateUtil = _TPL_ROOT + "hibernate_util.ftl";
3478    private String _tplJsonJs = _TPL_ROOT + "json_js.ftl";
3479    private String _tplJsonJsMethod = _TPL_ROOT + "json_js_method.ftl";
3480    private String _tplModel = _TPL_ROOT + "model.ftl";
3481    private String _tplModelHintsXml = _TPL_ROOT + "model_hints_xml.ftl";
3482    private String _tplModelImpl = _TPL_ROOT + "model_impl.ftl";
3483    private String _tplModelSoap = _TPL_ROOT + "model_soap.ftl";
3484    private String _tplPersistence = _TPL_ROOT + "persistence.ftl";
3485    private String _tplPersistenceImpl = _TPL_ROOT + "persistence_impl.ftl";
3486    private String _tplPersistenceTest = _TPL_ROOT + "persistence_test.ftl";
3487    private String _tplPersistenceUtil = _TPL_ROOT + "persistence_util.ftl";
3488    private String _tplPrincipalBean = _TPL_ROOT + "principal_bean.ftl";
3489    private String _tplProps = _TPL_ROOT + "props.ftl";
3490    private String _tplPropsUtil = _TPL_ROOT + "props_util.ftl";
3491    private String _tplRemotingXml = _TPL_ROOT + "remoting_xml.ftl";
3492    private String _tplService = _TPL_ROOT + "service.ftl";
3493    private String _tplServiceBaseImpl = _TPL_ROOT + "service_base_impl.ftl";
3494    private String _tplServiceFactory = _TPL_ROOT + "service_factory.ftl";
3495    private String _tplServiceHttp = _TPL_ROOT + "service_http.ftl";
3496    private String _tplServiceImpl = _TPL_ROOT + "service_impl.ftl";
3497    private String _tplServiceJson = _TPL_ROOT + "service_json.ftl";
3498    private String _tplServiceJsonSerializer =
3499        _TPL_ROOT + "service_json_serializer.ftl";
3500    private String _tplServiceSoap = _TPL_ROOT + "service_soap.ftl";
3501    private String _tplServiceUtil = _TPL_ROOT + "service_util.ftl";
3502    private String _tplSpringDataSourceXml =
3503        _TPL_ROOT + "spring_data_source_xml.ftl";
3504    private String _tplSpringUtil = _TPL_ROOT + "spring_util.ftl";
3505    private String _tplSpringXml = _TPL_ROOT + "spring_xml.ftl";
3506    private Set<String> _badTableNames;
3507    private Set<String> _badColumnNames;
3508    private String _hbmFileName;
3509    private String _modelHintsFileName;
3510    private String _springFileName;
3511    private String _springDataSourceFileName;
3512    private String _apiDir;
3513    private String _implDir;
3514    private String _jsonFileName;
3515    private String _remotingFileName;
3516    private String _sqlDir;
3517    private String _sqlFileName;
3518    private String _sqlIndexesFileName;
3519    private String _sqlIndexesPropertiesFileName;
3520    private String _sqlSequencesFileName;
3521    private boolean _autoNamespaceTables;
3522    private String _baseModelImplPackage;
3523    private String _basePersistencePackage;
3524    private String _beanLocatorUtilPackage;
3525    private String _principalBeanPackage;
3526    private String _propsUtilPackage;
3527    private String _springHibernatePackage;
3528    private String _springUtilPackage;
3529    private String _testDir;
3530    private String _portletName = StringPool.BLANK;
3531    private String _portletShortName = StringPool.BLANK;
3532    private String _portletPackageName = StringPool.BLANK;
3533    private String _outputPath;
3534    private String _serviceOutputPath;
3535    private String _testOutputPath;
3536    private String _packagePath;
3537    private List<Entity> _ejbList;
3538    private Map<String, EntityMapping> _entityMappings;
3539    private Map<String, Entity> _entityPool = new HashMap<String, Entity>();
3540
3541}