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