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