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