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