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