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