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