1   /**
2    * Copyright (c) 2000-2008 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portal.tools.servicebuilder;
24  
25  import com.liferay.portal.freemarker.FreeMarkerUtil;
26  import com.liferay.portal.kernel.util.ArrayUtil;
27  import com.liferay.portal.kernel.util.GetterUtil;
28  import com.liferay.portal.kernel.util.PropertiesUtil;
29  import com.liferay.portal.kernel.util.StringMaker;
30  import com.liferay.portal.kernel.util.StringPool;
31  import com.liferay.portal.kernel.util.StringUtil;
32  import com.liferay.portal.kernel.util.StringUtil_IW;
33  import com.liferay.portal.kernel.util.Validator;
34  import com.liferay.portal.model.ModelHintsUtil;
35  import com.liferay.portal.tools.SourceFormatter;
36  import com.liferay.portal.util.PortalUtil;
37  import com.liferay.util.FileUtil;
38  import com.liferay.util.TextFormatter;
39  import com.liferay.util.Time;
40  import com.liferay.util.log4j.Log4JUtil;
41  import com.liferay.util.xml.XMLFormatter;
42  
43  import com.thoughtworks.qdox.JavaDocBuilder;
44  import com.thoughtworks.qdox.model.JavaClass;
45  import com.thoughtworks.qdox.model.JavaMethod;
46  import com.thoughtworks.qdox.model.JavaParameter;
47  import com.thoughtworks.qdox.model.Type;
48  
49  import de.hunsicker.io.FileFormat;
50  import de.hunsicker.jalopy.Jalopy;
51  import de.hunsicker.jalopy.storage.Convention;
52  import de.hunsicker.jalopy.storage.ConventionKeys;
53  import de.hunsicker.jalopy.storage.Environment;
54  
55  import freemarker.ext.beans.BeansWrapper;
56  import freemarker.template.TemplateHashModel;
57  import freemarker.template.TemplateModelException;
58  
59  import java.io.BufferedReader;
60  import java.io.File;
61  import java.io.FileNotFoundException;
62  import java.io.FileReader;
63  import java.io.IOException;
64  import java.io.StringReader;
65  
66  import java.util.ArrayList;
67  import java.util.HashMap;
68  import java.util.HashSet;
69  import java.util.Iterator;
70  import java.util.LinkedHashSet;
71  import java.util.List;
72  import java.util.Map;
73  import java.util.Properties;
74  import java.util.Set;
75  import java.util.TreeMap;
76  import java.util.TreeSet;
77  
78  import org.dom4j.Document;
79  import org.dom4j.DocumentException;
80  import org.dom4j.DocumentHelper;
81  import org.dom4j.Element;
82  
83  /**
84   * <a href="ServiceBuilder.java.html"><b><i>View Source</i></b></a>
85   *
86   * @author Brian Wing Shun Chan
87   * @author Charles May
88   * @author Alexander Chow
89   * @author Harry Mark
90   * @author Tariq Dweik
91   *
92   */
93  public class ServiceBuilder {
94  
95      public static void main(String[] args) {
96          ClassLoader classLoader = ClassLoader.getSystemClassLoader();
97  
98          Log4JUtil.configureLog4J(
99              classLoader.getResource("META-INF/portal-log4j.xml"));
100         Log4JUtil.configureLog4J(
101             classLoader.getResource("META-INF/portal-log4j-ext.xml"));
102 
103         ServiceBuilder serviceBuilder = null;
104 
105         if (args.length == 7) {
106             String fileName = args[0];
107             String hbmFileName = args[1];
108             String modelHintsFileName = args[2];
109             String springFileName = args[3];
110             String springDataSourceFileName = "";
111             String apiDir = args[5];
112             String implDir = "src";
113             String jsonFileName = args[6];
114             String remotingFileName = "../tunnel-web/docroot/WEB-INF/remoting-servlet.xml";
115             String sqlDir = "../sql";
116             String sqlFileName = "portal-tables.sql";
117             boolean autoNamespaceTables = false;
118             String baseModelImplPackage = "com.liferay.portal.model.impl";
119             String basePersistencePackage = "com.liferay.portal.service.persistence";
120             String beanLocatorUtilPackage = "com.liferay.portal.kernel.bean";
121             String principalBeanPackage = "com.liferay.portal.service.impl";
122             String propsUtilPackage = "com.liferay.portal.util";
123             String springHibernatePackage = "com.liferay.portal.spring.hibernate";
124             String springUtilPackage = "com.liferay.portal.spring.util";
125             String testDir = "";
126 
127             serviceBuilder = new ServiceBuilder(
128                 fileName, hbmFileName, modelHintsFileName, springFileName,
129                 springDataSourceFileName, apiDir, implDir, jsonFileName,
130                 remotingFileName, sqlDir, sqlFileName, autoNamespaceTables,
131                 baseModelImplPackage, basePersistencePackage,
132                 beanLocatorUtilPackage, principalBeanPackage, propsUtilPackage,
133                 springHibernatePackage, springUtilPackage, testDir);
134         }
135         else if (args.length == 0) {
136             String fileName = System.getProperty("service.input.file");
137             String hbmFileName = System.getProperty("service.hbm.file");
138             String modelHintsFileName = System.getProperty("service.model.hints.file");
139             String springFileName = System.getProperty("service.spring.file");
140             String springDataSourceFileName = System.getProperty("service.spring.data.source.file");
141             String apiDir = System.getProperty("service.api.dir");
142             String implDir = System.getProperty("service.impl.dir");
143             String jsonFileName = System.getProperty("service.json.file");
144             String remotingFileName = System.getProperty("service.remoting.file");
145             String sqlDir = System.getProperty("service.sql.dir");
146             String sqlFileName = System.getProperty("service.sql.file");
147             boolean autoNamespaceTables = GetterUtil.getBoolean(System.getProperty("service.auto.namespace.tables"));
148             String baseModelImplPackage = System.getProperty("service.base.model.impl.package");
149             String basePersistencePackage = System.getProperty("service.base.persistence.package");
150             String beanLocatorUtilPackage = System.getProperty("service.bean.locator.util.package");
151             String principalBeanPackage = System.getProperty("service.principal.bean.package");
152             String propsUtilPackage = System.getProperty("service.props.util.package");
153             String springHibernatePackage = System.getProperty("service.spring.hibernate.package");
154             String springUtilPackage = System.getProperty("service.spring.util.package");
155             String testDir = System.getProperty("service.test.dir");
156 
157             serviceBuilder = new ServiceBuilder(
158                 fileName, hbmFileName, modelHintsFileName, springFileName,
159                 springDataSourceFileName, apiDir, implDir, jsonFileName,
160                 remotingFileName, sqlDir, sqlFileName, autoNamespaceTables,
161                 baseModelImplPackage, basePersistencePackage,
162                 beanLocatorUtilPackage, principalBeanPackage, propsUtilPackage,
163                 springHibernatePackage, springUtilPackage, testDir);
164         }
165 
166         if (serviceBuilder == null) {
167             System.out.println(
168                 "Please set these required system properties. Sample values are:\n" +
169                 "\n" +
170                 "\t-Dservice.input.file=${service.file}\n" +
171                 "\t-Dservice.hbm.file=classes/META-INF/portal-hbm.xml\n" +
172                 "\t-Dservice.model.hints.file=classes/META-INF/portal-model-hints.xml\n" +
173                 "\t-Dservice.spring.file=classes/META-INF/portal-spring.xml\n" +
174                 "\t-Dservice.api.dir=${project.dir}/portal-service/src\n" +
175                 "\t-Dservice.impl.dir=src\n" +
176                 "\t-Dservice.json.file=${project.dir}/portal-web/docroot/html/js/liferay/service_unpacked.js\n" +
177                 "\t-Dservice.remoting.file=${project.dir}/tunnel-web/docroot/WEB-INF/remoting-servlet.xml\n" +
178                 "\t-Dservice.sql.dir=../sql\n" +
179                 "\t-Dservice.sql.file=portal-tables.sql\n" +
180                 "\t-Dservice.base.model.impl.package=com.liferay.portal.model.impl\n" +
181                 "\t-Dservice.base.persistence.package=com.liferay.portal.service.persistence\n" +
182                 "\t-Dservice.bean.locator.util.package=com.liferay.portal.kernel.bean\n" +
183                 "\t-Dservice.principal.bean.package=com.liferay.portal.service.impl\n" +
184                 "\t-Dservice.props.util.package=com.liferay.portal.util\n" +
185                 "\t-Dservice.spring.hibernate.package=com.liferay.portal.spring.hibernate\n" +
186                 "\t-Dservice.spring.util.package=com.liferay.portal.spring.util\n" +
187                 "\n" +
188                 "You can also customize the generated code by overriding the default templates with these optional properties:\n" +
189                 "\n" +
190                 "\t-Dservice.tpl.base_mode_impl.ftl=" + _TPL_ROOT + "base_mode_impl.ftl\n"+
191                 "\t-Dservice.tpl.base_persistence.ftl=" + _TPL_ROOT + "base_persistence.ftl\n"+
192                 "\t-Dservice.tpl.bean_locator_util.ftl=" + _TPL_ROOT + "bean_locator_util.ftl\n"+
193                 "\t-Dservice.tpl.copyright.txt=copyright.txt\n"+
194                 "\t-Dservice.tpl.dynamic_dialect.ftl=" + _TPL_ROOT + "dynamic_dialect.ftl\n"+
195                 "\t-Dservice.tpl.ejb_pk.ftl=" + _TPL_ROOT + "ejb_pk.ftl\n"+
196                 "\t-Dservice.tpl.exception.ftl=" + _TPL_ROOT + "exception.ftl\n"+
197                 "\t-Dservice.tpl.extended_model.ftl=" + _TPL_ROOT + "extended_model.ftl\n"+
198                 "\t-Dservice.tpl.extended_model_impl.ftl=" + _TPL_ROOT + "extended_model_impl.ftl\n"+
199                 "\t-Dservice.tpl.finder.ftl=" + _TPL_ROOT + "finder.ftl\n"+
200                 "\t-Dservice.tpl.finder_cache.ftl=" + _TPL_ROOT + "finder_cache.ftl\n"+
201                 "\t-Dservice.tpl.finder_util.ftl=" + _TPL_ROOT + "finder_util.ftl\n"+
202                 "\t-Dservice.tpl.hbm_xml.ftl=" + _TPL_ROOT + "hbm_xml.ftl\n"+
203                 "\t-Dservice.tpl.hibernate_configuration.ftl=" + _TPL_ROOT + "hibernate_configuration.ftl\n"+
204                 "\t-Dservice.tpl.hibernate_util.ftl=" + _TPL_ROOT + "hibernate_util.ftl\n"+
205                 "\t-Dservice.tpl.json_js.ftl=" + _TPL_ROOT + "json_js.ftl\n"+
206                 "\t-Dservice.tpl.json_js_method.ftl=" + _TPL_ROOT + "json_js_method.ftl\n"+
207                 "\t-Dservice.tpl.model.ftl=" + _TPL_ROOT + "model.ftl\n"+
208                 "\t-Dservice.tpl.model_hints_xml.ftl=" + _TPL_ROOT + "model_hints_xml.ftl\n"+
209                 "\t-Dservice.tpl.model_impl.ftl=" + _TPL_ROOT + "model_impl.ftl\n"+
210                 "\t-Dservice.tpl.model_soap.ftl=" + _TPL_ROOT + "model_soap.ftl\n"+
211                 "\t-Dservice.tpl.persistence.ftl=" + _TPL_ROOT + "persistence.ftl\n"+
212                 "\t-Dservice.tpl.persistence_impl.ftl=" + _TPL_ROOT + "persistence_impl.ftl\n"+
213                 "\t-Dservice.tpl.persistence_util.ftl=" + _TPL_ROOT + "persistence_util.ftl\n"+
214                 "\t-Dservice.tpl.principal_bean.ftl=" + _TPL_ROOT + "principal_bean.ftl\n"+
215                 "\t-Dservice.tpl.props.ftl=" + _TPL_ROOT + "props.ftl\n"+
216                 "\t-Dservice.tpl.props_util.ftl=" + _TPL_ROOT + "props_util.ftl\n"+
217                 "\t-Dservice.tpl.remoting_xml.ftl=" + _TPL_ROOT + "remoting_xml.ftl\n"+
218                 "\t-Dservice.tpl.service.ftl=" + _TPL_ROOT + "service.ftl\n"+
219                 "\t-Dservice.tpl.service_base_impl.ftl=" + _TPL_ROOT + "service_base_impl.ftl\n"+
220                 "\t-Dservice.tpl.service_factory.ftl=" + _TPL_ROOT + "service_factory.ftl\n"+
221                 "\t-Dservice.tpl.service_http.ftl=" + _TPL_ROOT + "service_http.ftl\n"+
222                 "\t-Dservice.tpl.service_impl.ftl=" + _TPL_ROOT + "service_impl.ftl\n"+
223                 "\t-Dservice.tpl.service_json.ftl=" + _TPL_ROOT + "service_json.ftl\n"+
224                 "\t-Dservice.tpl.service_json_serializer.ftl=" + _TPL_ROOT + "service_json_serializer.ftl\n"+
225                 "\t-Dservice.tpl.service_soap.ftl=" + _TPL_ROOT + "service_soap.ftl\n"+
226                 "\t-Dservice.tpl.service_util.ftl=" + _TPL_ROOT + "service_util.ftl\n"+
227                 "\t-Dservice.tpl.spring_data_source_xml.ftl=" + _TPL_ROOT + "spring_data_source_xml.ftl\n"+
228                 "\t-Dservice.tpl.spring_util.ftl=" + _TPL_ROOT + "spring_util.ftl\n"+
229                 "\t-Dservice.tpl.spring_xml.ftl=" + _TPL_ROOT + "spring_xml.ftl\n"+
230                 "\t-Dservice.tpl.spring_xml_session.ftl=" + _TPL_ROOT + "spring_xml_session.ftl");
231         }
232     }
233 
234     public static Set getBadCmpFields() {
235         Set badCmpFields = new HashSet();
236 
237         badCmpFields.add("access");
238         badCmpFields.add("active");
239         badCmpFields.add("alias");
240         badCmpFields.add("code");
241         badCmpFields.add("data");
242         badCmpFields.add("date");
243         badCmpFields.add("end");
244         badCmpFields.add("idd");
245         badCmpFields.add("featured");
246         badCmpFields.add("fields");
247         badCmpFields.add("from");
248         badCmpFields.add("hidden");
249         badCmpFields.add("id");
250         badCmpFields.add("index");
251         badCmpFields.add("internal");
252         badCmpFields.add("interval");
253         badCmpFields.add("join");
254         badCmpFields.add("key");
255         badCmpFields.add("log");
256         badCmpFields.add("number");
257         badCmpFields.add("password");
258         badCmpFields.add("path");
259         badCmpFields.add("primary");
260         badCmpFields.add("sale");
261         badCmpFields.add("settings");
262         badCmpFields.add("size");
263         badCmpFields.add("start");
264         badCmpFields.add("text");
265         badCmpFields.add("to");
266         badCmpFields.add("type");
267         badCmpFields.add("uuid");
268         badCmpFields.add("values");
269 
270         return badCmpFields;
271     }
272 
273     public static Set getBadTableNames() {
274         Set badTableNames = new HashSet();
275 
276         badTableNames.add("Account");
277         badTableNames.add("Action");
278         badTableNames.add("Cache");
279         badTableNames.add("ClassName");
280         badTableNames.add("Contact");
281         badTableNames.add("Group");
282         badTableNames.add("Organization");
283         badTableNames.add("Permission");
284         badTableNames.add("Release");
285         badTableNames.add("Resource");
286         badTableNames.add("Role");
287         badTableNames.add("User");
288 
289         return badTableNames;
290     }
291 
292     public static void writeFile(File file, String content) throws IOException {
293         writeFile(file, content, null);
294     }
295 
296     public static void writeFile(File file, String content, Map jalopySettings)
297         throws IOException {
298 
299         String packagePath = _getPackagePath(file);
300 
301         String className = file.getName();
302 
303         className = className.substring(0, className.length() - 5);
304 
305         content = SourceFormatter.stripImports(content, packagePath, className);
306 
307         File tempFile = new File("ServiceBuilder.temp");
308 
309         FileUtil.write(tempFile, content);
310 
311         // Beautify
312 
313         StringBuffer sb = new StringBuffer();
314 
315         Jalopy jalopy = new Jalopy();
316 
317         jalopy.setFileFormat(FileFormat.UNIX);
318         jalopy.setInput(tempFile);
319         jalopy.setOutput(sb);
320 
321         try {
322             Jalopy.setConvention("../tools/jalopy.xml");
323         }
324         catch (FileNotFoundException fnne) {
325         }
326 
327         try {
328             Jalopy.setConvention("../../misc/jalopy.xml");
329         }
330         catch (FileNotFoundException fnne) {
331         }
332 
333         if (jalopySettings == null) {
334             jalopySettings = new HashMap();
335         }
336 
337         Environment env = Environment.getInstance();
338 
339         // Author
340 
341         String author = GetterUtil.getString(
342             (String)jalopySettings.get("author"), "Brian Wing Shun Chan");
343 
344         env.set("author", author);
345 
346         // File name
347 
348         env.set("fileName", file.getName());
349 
350         Convention convention = Convention.getInstance();
351 
352         String classMask =
353             "/**\n" +
354             " * <a href=\"$fileName$.html\"><b><i>View Source</i></b></a>\n" +
355             " *\n";
356 
357         String[] classCommentsArray = (String[])jalopySettings.get("classComments");
358 
359         if ((classCommentsArray != null) && (classCommentsArray.length > 0)) {
360             for (int i = 0; i < classCommentsArray.length; i++) {
361                 String classComments = classCommentsArray[i];
362 
363                 //classComments = "The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.";
364                 classComments = StringUtil.wrap(classComments, 76, "\n * ");
365 
366                 if (classComments.startsWith("\n")) {
367                     classComments = classComments.substring(
368                         1, classComments.length());
369                 }
370 
371                 classMask += " * <p>\n" + classComments + "\n * </p>\n *\n";
372             }
373         }
374 
375         classMask +=
376             " * @author $author$\n" +
377             " *\n";
378 
379         String[] seeArray = (String[])jalopySettings.get("see");
380 
381         if ((classCommentsArray != null) && (classCommentsArray.length > 0)) {
382             for (int i = 0; i < seeArray.length; i++) {
383                 String see = seeArray[i];
384 
385                 classMask += " * @see " + see + "\n";
386             }
387 
388             classMask += " *\n";
389         }
390 
391         classMask += " */";
392 
393         convention.put(
394             ConventionKeys.COMMENT_JAVADOC_TEMPLATE_CLASS,
395             env.interpolate(classMask));
396 
397         convention.put(
398             ConventionKeys.COMMENT_JAVADOC_TEMPLATE_INTERFACE,
399             env.interpolate(classMask));
400 
401         if (jalopySettings.get("keepJavadoc") != null) {
402             convention.put(
403                 ConventionKeys.COMMENT_JAVADOC_REMOVE,
404                 Boolean.FALSE.toString());
405         }
406 
407         jalopy.format();
408 
409         String newContent = sb.toString();
410 
411         /*
412         // Remove blank lines after try {
413 
414         newContent = StringUtil.replace(newContent, "try {\n\n", "try {\n");
415 
416         // Remove blank lines after ) {
417 
418         newContent = StringUtil.replace(newContent, ") {\n\n", ") {\n");
419 
420         // Remove blank lines empty braces { }
421 
422         newContent = StringUtil.replace(newContent, "\n\n\t}", "\n\t}");
423 
424         // Add space to last }
425 
426         newContent = newContent.substring(0, newContent.length() - 2) + "\n\n}";
427         */
428 
429         // Write file if and only if the file has changed
430 
431         String oldContent = null;
432 
433         if (file.exists()) {
434 
435             // Read file
436 
437             oldContent = FileUtil.read(file);
438 
439             // Keep old version number
440 
441             int x = oldContent.indexOf("@version $Revision:");
442 
443             if (x != -1) {
444                 int y = oldContent.indexOf("$", x);
445                 y = oldContent.indexOf("$", y + 1);
446 
447                 String oldVersion = oldContent.substring(x, y + 1);
448 
449                 newContent = StringUtil.replace(
450                     newContent, "@version $Rev: $", oldVersion);
451             }
452         }
453         else {
454             newContent = StringUtil.replace(
455                 newContent, "@version $Rev: $", "@version $Revision: 1.183 $");
456         }
457 
458         if (oldContent == null || !oldContent.equals(newContent)) {
459             FileUtil.write(file, newContent);
460 
461             System.out.println("Writing " + file);
462 
463             // Workaround for bug with XJavaDoc
464 
465             file.setLastModified(
466                 System.currentTimeMillis() - (Time.SECOND * 5));
467         }
468 
469         tempFile.deleteOnExit();
470     }
471 
472     public ServiceBuilder(
473         String fileName, String hbmFileName, String modelHintsFileName,
474         String springFileName, String springDataSourceFileName, String apiDir,
475         String implDir, String jsonFileName, String remotingFileName,
476         String sqlDir, String sqlFileName, boolean autoNamespaceTables,
477         String baseModelImplPackage, String basePersistencePackage,
478         String beanLocatorUtilPackage, String principalBeanPackage,
479         String propsUtilPackage, String springHibernatePackage,
480         String springUtilPackage, String testDir) {
481 
482         new ServiceBuilder(
483             fileName, hbmFileName, modelHintsFileName, springFileName,
484             springDataSourceFileName, apiDir, implDir, jsonFileName,
485             remotingFileName, sqlDir, sqlFileName, autoNamespaceTables,
486             baseModelImplPackage, basePersistencePackage,
487             beanLocatorUtilPackage, principalBeanPackage, propsUtilPackage,
488             springHibernatePackage, springUtilPackage, testDir, true);
489     }
490 
491     public ServiceBuilder(
492         String fileName, String hbmFileName, String modelHintsFileName,
493         String springFileName, String springDataSourceFileName, String apiDir,
494         String implDir, String jsonFileName, String remotingFileName,
495         String sqlDir, String sqlFileName, boolean autoNamespaceTables,
496         String baseModelImplPackage, String basePersistencePackage,
497         String beanLocatorUtilPackage, String principalBeanPackage,
498         String propsUtilPackage, String springHibernatePackage,
499         String springUtilPackage, String testDir, boolean build) {
500 
501         _tplBaseModeImpl = _getTplProperty("base_mode_impl", _tplBaseModeImpl);
502         _tplBasePersistence = _getTplProperty(
503             "base_persistence", _tplBasePersistence);
504         _tplBeanLocatorUtil = _getTplProperty(
505             "bean_locator_util", _tplBeanLocatorUtil);
506         _tplDynamicDialect = _getTplProperty(
507             "dynamic_dialect", _tplDynamicDialect);
508         _tplEjbPk = _getTplProperty("ejb_pk", _tplEjbPk);
509         _tplException = _getTplProperty("exception", _tplException);
510         _tplExtendedModel = _getTplProperty(
511             "extended_model", _tplExtendedModel);
512         _tplExtendedModelImpl = _getTplProperty(
513             "extended_model_impl", _tplExtendedModelImpl);
514         _tplFinder = _getTplProperty("finder", _tplFinder);
515         _tplFinderCache = _getTplProperty("finder_cache", _tplFinderCache);
516         _tplFinderUtil = _getTplProperty("finder_util", _tplFinderUtil);
517         _tplHbmXml = _getTplProperty("hbm_xml", _tplHbmXml);
518         _tplHibernateConfiguration = _getTplProperty(
519             "hibernate_configuration", _tplHibernateConfiguration);
520         _tplHibernateUtil = _getTplProperty(
521             "hibernate_util", _tplHibernateUtil);
522         _tplJsonJs = _getTplProperty("json_js", _tplJsonJs);
523         _tplJsonJsMethod = _getTplProperty("json_js_method", _tplJsonJsMethod);
524         _tplModel = _getTplProperty("model", _tplModel);
525         _tplModelHintsXml = _getTplProperty(
526             "model_hints_xml", _tplModelHintsXml);
527         _tplModelImpl = _getTplProperty("model_impl", _tplModelImpl);
528         _tplModelSoap = _getTplProperty("model_soap", _tplModelSoap);
529         _tplPersistence = _getTplProperty("persistence", _tplPersistence);
530         _tplPersistenceImpl = _getTplProperty(
531             "persistence_impl", _tplPersistenceImpl);
532         _tplPersistenceUtil = _getTplProperty(
533             "persistence_util", _tplPersistenceUtil);
534         _tplPrincipalBean = _getTplProperty(
535             "principal_bean", _tplPrincipalBean);
536         _tplProps = _getTplProperty("props", _tplProps);
537         _tplPropsUtil = _getTplProperty("props_util", _tplPropsUtil);
538         _tplRemotingXml = _getTplProperty("remoting_xml", _tplRemotingXml);
539         _tplService = _getTplProperty("service", _tplService);
540         _tplServiceBaseImpl = _getTplProperty(
541             "service_base_impl", _tplServiceBaseImpl);
542         _tplServiceFactory = _getTplProperty(
543             "service_factory", _tplServiceFactory);
544         _tplServiceHttp = _getTplProperty("service_http", _tplServiceHttp);
545         _tplServiceImpl = _getTplProperty("service_impl", _tplServiceImpl);
546         _tplServiceJson = _getTplProperty("service_json", _tplServiceJson);
547         _tplServiceJsonSerializer = _getTplProperty(
548             "service_json_serializer", _tplServiceJsonSerializer);
549         _tplServiceSoap = _getTplProperty("service_soap", _tplServiceSoap);
550         _tplServiceUtil = _getTplProperty("service_util", _tplServiceUtil);
551         _tplSpringDataSourceXml = _getTplProperty(
552             "spring_data_source_xml", _tplSpringDataSourceXml);
553         _tplSpringUtil = _getTplProperty("spring_util", _tplSpringUtil);
554         _tplSpringXml = _getTplProperty("spring_xml", _tplSpringXml);
555 
556         try {
557             _badTableNames = ServiceBuilder.getBadTableNames();
558             _badCmpFields = ServiceBuilder.getBadCmpFields();
559 
560             _hbmFileName = hbmFileName;
561             _modelHintsFileName = modelHintsFileName;
562             _springFileName = springFileName;
563             _springDataSourceFileName = springDataSourceFileName;
564             _apiDir = apiDir;
565             _implDir = implDir;
566             _jsonFileName = jsonFileName;
567             _remotingFileName = remotingFileName;
568             _sqlDir = sqlDir;
569             _sqlFileName = sqlFileName;
570             _autoNamespaceTables = autoNamespaceTables;
571             _baseModelImplPackage = baseModelImplPackage;
572             _basePersistencePackage = basePersistencePackage;
573             _beanLocatorUtilPackage = beanLocatorUtilPackage;
574             _principalBeanPackage = principalBeanPackage;
575             _propsUtilPackage = propsUtilPackage;
576             _springHibernatePackage = springHibernatePackage;
577             _springUtilPackage = springUtilPackage;
578             _testDir = testDir;
579 
580             Document doc = PortalUtil.readDocumentFromFile(
581                 new File(fileName), true);
582 
583             Element root = doc.getRootElement();
584 
585             String packagePath = root.attributeValue("package-path");
586 
587             _outputPath =
588                 _implDir + "/" + StringUtil.replace(packagePath, ".", "/");
589 
590             _serviceOutputPath =
591                 _apiDir + "/" + StringUtil.replace(packagePath, ".", "/");
592 
593             if (Validator.isNotNull(_testDir)) {
594                 _testOutputPath =
595                     _testDir + "/" + StringUtil.replace(packagePath, ".", "/");
596             }
597 
598             _packagePath = packagePath;
599 
600             Element portlet = root.element("portlet");
601             Element namespace = root.element("namespace");
602 
603             if (portlet != null) {
604                 _portletName = portlet.attributeValue("name");
605 
606                 _portletShortName = portlet.attributeValue("short-name");
607 
608                 _portletPackageName =
609                     TextFormatter.format(_portletName, TextFormatter.B);
610 
611                 _outputPath += "/" + _portletPackageName;
612 
613                 _serviceOutputPath += "/" + _portletPackageName;
614 
615                 _testOutputPath += "/" + _portletPackageName;
616 
617                 _packagePath += "." + _portletPackageName;
618             }
619             else {
620                 _portletShortName = namespace.getText();
621             }
622 
623             _portletShortName = _portletShortName.trim();
624 
625             if (!Validator.isChar(_portletShortName)) {
626                 throw new RuntimeException(
627                     "The namespace element must be a valid keyword");
628             }
629 
630             _ejbList = new ArrayList();
631 
632             List entities = root.elements("entity");
633 
634             Iterator itr1 = entities.iterator();
635 
636             while (itr1.hasNext()) {
637                 Element entityEl = (Element)itr1.next();
638 
639                 String ejbName = entityEl.attributeValue("name");
640 
641                 String table = entityEl.attributeValue("table");
642 
643                 if (Validator.isNull(table)) {
644                     table = ejbName;
645 
646                     if (_badTableNames.contains(ejbName)) {
647                         table += "_";
648                     }
649                 }
650 
651                 if (_autoNamespaceTables) {
652                     table = _portletShortName + "_" + table;
653                 }
654 
655                 boolean uuid = GetterUtil.getBoolean(
656                     entityEl.attributeValue("uuid"), false);
657                 boolean localService = GetterUtil.getBoolean(
658                     entityEl.attributeValue("local-service"), false);
659                 boolean remoteService = GetterUtil.getBoolean(
660                     entityEl.attributeValue("remote-service"), true);
661                 String persistenceClass = GetterUtil.getString(
662                     entityEl.attributeValue("persistence-class"),
663                     _packagePath + ".service.persistence." + ejbName +
664                         "PersistenceImpl");
665 
666                 String finderClass = "";
667 
668                 if (FileUtil.exists(
669                     _outputPath + "/service/persistence/" + ejbName +
670                         "FinderImpl.java")) {
671 
672                     finderClass =
673                         _packagePath + ".service.persistence." + ejbName +
674                             "FinderImpl";
675                 }
676 
677                 String dataSource = entityEl.attributeValue("data-source");
678                 String sessionFactory = entityEl.attributeValue(
679                     "session-factory");
680                 String txManager = entityEl.attributeValue(
681                     "tx-manager");
682 
683                 Iterator itr2 = null;
684 
685                 List pkList = new ArrayList();
686                 List regularColList = new ArrayList();
687                 List collectionList = new ArrayList();
688                 List columnList = new ArrayList();
689 
690                 List columns = entityEl.elements("column");
691 
692                 if (uuid) {
693                     Element column = DocumentHelper.createElement("column");
694 
695                     column.addAttribute("name", "uuid");
696                     column.addAttribute("type", "String");
697 
698                     columns.add(0, column);
699                 }
700 
701                 itr2 = columns.iterator();
702 
703                 while (itr2.hasNext()) {
704                     Element column = (Element)itr2.next();
705 
706                     String columnName = column.attributeValue("name");
707 
708                     String columnDBName = column.attributeValue("db-name");
709 
710                     if (Validator.isNull(columnDBName)) {
711                         columnDBName = columnName;
712 
713                         if (_badCmpFields.contains(columnName)) {
714                             columnDBName += "_";
715                         }
716                     }
717 
718                     String columnType = column.attributeValue("type");
719                     boolean primary = GetterUtil.getBoolean(
720                         column.attributeValue("primary"), false);
721                     String collectionEntity = column.attributeValue("entity");
722                     String mappingKey = column.attributeValue("mapping-key");
723                     String mappingTable = column.attributeValue(
724                         "mapping-table");
725                     String idType = column.attributeValue("id-type");
726                     String idParam = column.attributeValue("id-param");
727                     boolean convertNull = GetterUtil.getBoolean(
728                         column.attributeValue("convert-null"), true);
729 
730                     EntityColumn col = new EntityColumn(
731                         columnName, columnDBName, columnType, primary,
732                         collectionEntity, mappingKey, mappingTable, idType,
733                         idParam, convertNull);
734 
735                     if (primary) {
736                         pkList.add(col);
737                     }
738 
739                     if (columnType.equals("Collection")) {
740                         collectionList.add(col);
741                     }
742                     else {
743                         regularColList.add(col);
744                     }
745 
746                     columnList.add(col);
747                 }
748 
749                 EntityOrder order = null;
750 
751                 Element orderEl = entityEl.element("order");
752 
753                 if (orderEl != null) {
754                     boolean asc = true;
755 
756                     if ((orderEl.attribute("by") != null) &&
757                         (orderEl.attributeValue("by").equals("desc"))) {
758 
759                         asc = false;
760                     }
761 
762                     List orderColsList = new ArrayList();
763 
764                     order = new EntityOrder(asc, orderColsList);
765 
766                     List orderCols = orderEl.elements("order-column");
767 
768                     Iterator itr3 = orderCols.iterator();
769 
770                     while (itr3.hasNext()) {
771                         Element orderColEl = (Element)itr3.next();
772 
773                         String orderColName =
774                             orderColEl.attributeValue("name");
775                         boolean orderColCaseSensitive = GetterUtil.getBoolean(
776                             orderColEl.attributeValue("case-sensitive"),
777                             true);
778 
779                         boolean orderColByAscending = asc;
780 
781                         String orderColBy = GetterUtil.getString(
782                             orderColEl.attributeValue("order-by"));
783 
784                         if (orderColBy.equals("asc")) {
785                             orderColByAscending = true;
786                         }
787                         else if (orderColBy.equals("desc")) {
788                             orderColByAscending = false;
789                         }
790 
791                         EntityColumn col = Entity.getColumn(
792                             orderColName, columnList);
793 
794                         col = (EntityColumn)col.clone();
795 
796                         col.setCaseSensitive(orderColCaseSensitive);
797                         col.setOrderByAscending(orderColByAscending);
798 
799                         orderColsList.add(col);
800                     }
801                 }
802 
803                 List finderList = new ArrayList();
804 
805                 List finders = entityEl.elements("finder");
806 
807                 if (uuid) {
808                     Element finderEl = DocumentHelper.createElement("finder");
809 
810                     finderEl.addAttribute("name", "Uuid");
811                     finderEl.addAttribute("return-type", "Collection");
812 
813                     Element finderColEl = finderEl.addElement("finder-column");
814 
815                     finderColEl.addAttribute("name", "uuid");
816 
817                     finders.add(0, finderEl);
818 
819                     if (columnList.contains(new EntityColumn("groupId"))) {
820                         finderEl = DocumentHelper.createElement("finder");
821 
822                         finderEl.addAttribute("name", "UUID_G");
823                         finderEl.addAttribute("return-type", ejbName);
824 
825                         finderColEl = finderEl.addElement("finder-column");
826 
827                         finderColEl.addAttribute("name", "uuid");
828 
829                         finderColEl = finderEl.addElement("finder-column");
830 
831                         finderColEl.addAttribute("name", "groupId");
832 
833                         finders.add(1, finderEl);
834                     }
835                 }
836 
837                 itr2 = finders.iterator();
838 
839                 while (itr2.hasNext()) {
840                     Element finderEl = (Element)itr2.next();
841 
842                     String finderName = finderEl.attributeValue("name");
843                     String finderReturn =
844                         finderEl.attributeValue("return-type");
845                     String finderWhere =
846                         finderEl.attributeValue("where");
847                     boolean finderDBIndex = GetterUtil.getBoolean(
848                         finderEl.attributeValue("db-index"), true);
849 
850                     List finderColsList = new ArrayList();
851 
852                     List finderCols = finderEl.elements("finder-column");
853 
854                     Iterator itr3 = finderCols.iterator();
855 
856                     while (itr3.hasNext()) {
857                         Element finderColEl = (Element)itr3.next();
858 
859                         String finderColName =
860                             finderColEl.attributeValue("name");
861 
862                         String finderColDBName =
863                             finderColEl.attributeValue("db-name");
864 
865                         if (Validator.isNull(finderColDBName)) {
866                             finderColDBName = finderColName;
867 
868                             if (_badCmpFields.contains(finderColName)) {
869                                 finderColDBName += "_";
870                             }
871                         }
872 
873                         boolean finderColCaseSensitive = GetterUtil.getBoolean(
874                             finderColEl.attributeValue("case-sensitive"),
875                             true);
876 
877                         String finderColComparator = GetterUtil.getString(
878                             finderColEl.attributeValue("comparator"), "=");
879 
880                         EntityColumn col = Entity.getColumn(
881                             finderColName, columnList);
882 
883                         col = (EntityColumn)col.clone();
884 
885                         col.setDBName(finderColDBName);
886                         col.setCaseSensitive(finderColCaseSensitive);
887                         col.setComparator(finderColComparator);
888 
889                         finderColsList.add(col);
890                     }
891 
892                     finderList.add(
893                         new EntityFinder(
894                             finderName, finderReturn, finderColsList,
895                             finderWhere, finderDBIndex));
896                 }
897 
898                 List referenceList = new ArrayList();
899 
900                 if (build) {
901                     List references = entityEl.elements("reference");
902 
903                     itr2 = references.iterator();
904 
905                     while (itr2.hasNext()) {
906                         Element reference = (Element)itr2.next();
907 
908                         String refPackage =
909                             reference.attributeValue("package-path");
910                         String refEntity = reference.attributeValue("entity");
911 
912                         referenceList.add(
913                             getEntity(refPackage + "." + refEntity));
914                     }
915                 }
916 
917                 List txRequiredList = new ArrayList();
918 
919                 itr2 = entityEl.elements("tx-required").iterator();
920 
921                 while (itr2.hasNext()) {
922                     Element txRequiredEl = (Element)itr2.next();
923 
924                     String txRequired = txRequiredEl.getText();
925 
926                     txRequiredList.add(txRequired);
927                 }
928 
929                 _ejbList.add(
930                     new Entity(
931                         _packagePath, _portletName, _portletShortName, ejbName,
932                         table, uuid, localService, remoteService,
933                         persistenceClass, finderClass, dataSource,
934                         sessionFactory, txManager, pkList, regularColList,
935                         collectionList, columnList, order, finderList,
936                         referenceList, txRequiredList));
937             }
938 
939             List exceptionList = new ArrayList();
940 
941             if (root.element("exceptions") != null) {
942                 List exceptions =
943                     root.element("exceptions").elements("exception");
944 
945                 itr1 = exceptions.iterator();
946 
947                 while (itr1.hasNext()) {
948                     Element exception = (Element)itr1.next();
949 
950                     exceptionList.add(exception.getText());
951                 }
952             }
953 
954             if (build) {
955                 for (int x = 0; x < _ejbList.size(); x++) {
956                     Entity entity = (Entity)_ejbList.get(x);
957 
958                     System.out.println("Building " + entity.getName());
959 
960                     if (true ||
961                         entity.getName().equals("EmailAddress") ||
962                         entity.getName().equals("User")) {
963 
964                         if (entity.hasColumns()) {
965                             _createHBM(entity);
966                             _createHBMUtil(entity);
967 
968                             _createPersistenceImpl(entity);
969                             _createPersistence(entity);
970                             _createPersistenceUtil(entity);
971 
972                             if (Validator.isNotNull(_testDir)) {
973                                 _createPersistenceTest(entity);
974                             }
975 
976                             _createModelImpl(entity);
977                             _createExtendedModelImpl(entity);
978 
979                             _createModel(entity);
980                             _createExtendedModel(entity);
981 
982                             _createModelSoap(entity);
983 
984                             _createPool(entity);
985 
986                             if (entity.getPKList().size() > 1) {
987                                 _createEJBPK(entity);
988                             }
989                         }
990 
991                         _createFinder(entity);
992                         _createFinderUtil(entity);
993 
994                         if (entity.hasLocalService()) {
995                             _createServiceBaseImpl(entity, _LOCAL);
996                             _createServiceImpl(entity, _LOCAL);
997                             _createService(entity, _LOCAL);
998                             _createServiceFactory(entity, _LOCAL);
999                             _createServiceUtil(entity, _LOCAL);
1000                        }
1001
1002                        if (entity.hasRemoteService()) {
1003                            _createServiceBaseImpl(entity, _REMOTE);
1004                            _createServiceImpl(entity, _REMOTE);
1005                            _createService(entity, _REMOTE);
1006                            _createServiceFactory(entity, _REMOTE);
1007                            _createServiceUtil(entity, _REMOTE);
1008
1009                            if (Validator.isNotNull(_jsonFileName)) {
1010                                _createServiceHttp(entity);
1011                                _createServiceJSON(entity);
1012
1013                                if (entity.hasColumns()) {
1014                                    _createServiceJSONSerializer(entity);
1015                                }
1016
1017                                _createServiceSoap(entity);
1018                            }
1019                        }
1020                    }
1021                }
1022
1023                _createHBMXML();
1024                _createModelHintsXML();
1025                _createSpringXML();
1026
1027                if (Validator.isNotNull(_jsonFileName)) {
1028                    _createJSONJS();
1029                }
1030
1031                if (Validator.isNotNull(_remotingFileName)) {
1032                    _createRemotingXML();
1033                }
1034
1035                _createSQLIndexes();
1036                _createSQLTables();
1037                _createSQLSequences();
1038
1039                _createExceptions(exceptionList);
1040
1041                _createBaseModelImpl();
1042                _createBasePersistence();
1043                _createBeanLocatorUtil();
1044                _createDynamicDialect();
1045                _createFinderCache();
1046                _createHibernateConfiguration();
1047                _createHibernateUtil();
1048                _createPrincipalBean();
1049                _createProps();
1050                _createPropsUtil();
1051                _createSpringDataSourceXML();
1052                _createSpringUtil();
1053            }
1054        }
1055        catch (Exception e) {
1056            e.printStackTrace();
1057        }
1058    }
1059
1060    public String getClassName(Type type) {
1061        int dimensions = type.getDimensions();
1062        String name = type.getValue();
1063
1064        if (dimensions > 0) {
1065            StringMaker sm = new StringMaker();
1066
1067            for (int i = 0; i < dimensions; i++) {
1068                sm.append("[");
1069            }
1070
1071            if (name.equals("boolean")) {
1072                return sm.toString() + "Z";
1073            }
1074            else if (name.equals("byte")) {
1075                return sm.toString() + "B";
1076            }
1077            else if (name.equals("char")) {
1078                return sm.toString() + "C";
1079            }
1080            else if (name.equals("double")) {
1081                return sm.toString() + "D";
1082            }
1083            else if (name.equals("float")) {
1084                return sm.toString() + "F";
1085            }
1086            else if (name.equals("int")) {
1087                return sm.toString() + "I";
1088            }
1089            else if (name.equals("long")) {
1090                return sm.toString() + "J";
1091            }
1092            else if (name.equals("short")) {
1093                return sm.toString() + "S";
1094            }
1095            else {
1096                return sm.toString() + "L" + name + ";";
1097            }
1098        }
1099
1100        return name;
1101    }
1102
1103    public String getCreateTableSQL(Entity entity){
1104        String createTableSQL = _getCreateTableSQL(entity);
1105
1106        createTableSQL = StringUtil.replace(createTableSQL, "\n", "");
1107        createTableSQL = StringUtil.replace(createTableSQL, "\t", "");
1108        createTableSQL = createTableSQL.substring(
1109            0, createTableSQL.length() - 1);
1110
1111        return createTableSQL;
1112    }
1113
1114    public String getDimensions(String dims) {
1115        return getDimensions(Integer.parseInt(dims));
1116    }
1117
1118    public String getDimensions(int dims) {
1119        String dimensions = "";
1120
1121        for (int i = 0; i < dims; i++) {
1122            dimensions += "[]";
1123        }
1124
1125        return dimensions;
1126    }
1127
1128    public Entity getEntity(String name) throws IOException {
1129        int pos = name.lastIndexOf(".");
1130
1131        if (pos == -1) {
1132            pos = _ejbList.indexOf(new Entity(name));
1133
1134            return (Entity)_ejbList.get(pos);
1135        }
1136        else {
1137            String refPackage = name.substring(0, pos);
1138            String refPackageDir = StringUtil.replace(refPackage, ".", "/");
1139            String refEntity = name.substring(pos + 1, name.length());
1140            String refFileName =
1141                _implDir + "/" + refPackageDir + "/service.xml";
1142
1143            File refFile = new File(refFileName);
1144
1145            boolean useTempFile = false;
1146
1147            if (!refFile.exists()) {
1148                refFileName = Time.getTimestamp();
1149                refFile = new File(refFileName);
1150
1151                ClassLoader classLoader = getClass().getClassLoader();
1152
1153                FileUtil.write(
1154                    refFileName,
1155                    StringUtil.read(
1156                        classLoader, refPackageDir + "/service.xml"));
1157
1158                useTempFile = true;
1159            }
1160
1161            ServiceBuilder serviceBuilder = new ServiceBuilder(
1162                refFileName, _hbmFileName, _modelHintsFileName, _springFileName,
1163                _springDataSourceFileName, _apiDir, _implDir, _jsonFileName,
1164                _remotingFileName, _sqlDir, _sqlFileName, _autoNamespaceTables,
1165                _baseModelImplPackage, _basePersistencePackage,
1166                _beanLocatorUtilPackage, _principalBeanPackage,
1167                _propsUtilPackage, _springHibernatePackage, _springUtilPackage,
1168                _testDir, false);
1169
1170            Entity entity = serviceBuilder.getEntity(refEntity);
1171
1172            if (useTempFile) {
1173                refFile.deleteOnExit();
1174            }
1175
1176            return entity;
1177        }
1178    }
1179
1180    public String getGeneratorClass(String idType) {
1181        if (Validator.isNull(idType)) {
1182            idType = "assigned";
1183        }
1184
1185        return idType;
1186    }
1187
1188    public String getNoSuchEntityException(Entity entity) {
1189        String noSuchEntityException = entity.getName();
1190
1191        if (Validator.isNull(entity.getPortletShortName()) ||
1192            noSuchEntityException.startsWith(entity.getPortletShortName())) {
1193
1194            noSuchEntityException = noSuchEntityException.substring(
1195                entity.getPortletShortName().length());
1196        }
1197
1198        noSuchEntityException = "NoSuch" + noSuchEntityException;
1199
1200        return noSuchEntityException;
1201    }
1202
1203    public String getPrimitiveObj(String type) {
1204        if (type.equals("boolean")) {
1205            return "Boolean";
1206        }
1207        else if (type.equals("double")) {
1208            return "Double";
1209        }
1210        else if (type.equals("float")) {
1211            return "Float";
1212        }
1213        else if (type.equals("int")) {
1214            return "Integer";
1215        }
1216        else if (type.equals("long")) {
1217            return "Long";
1218        }
1219        else if (type.equals("short")) {
1220            return "Short";
1221        }
1222        else {
1223            return type;
1224        }
1225    }
1226
1227    public String getPrimitiveObjValue(String colType){
1228        if (colType.equals("Boolean")) {
1229            return ".booleanValue()";
1230        }
1231        else if (colType.equals("Double")) {
1232            return ".doubleValue()";
1233        }
1234        else if (colType.equals("Float")) {
1235            return ".floatValue()";
1236        }
1237        else if (colType.equals("Integer")) {
1238            return ".intValue()";
1239        }
1240        else if (colType.equals("Long")) {
1241            return ".longValue()";
1242        }
1243        else if (colType.equals("Short")) {
1244            return ".shortValue()";
1245        }
1246
1247        return StringPool.BLANK;
1248    }
1249
1250    public String getSqlType(String model, String field, String type) {
1251        if (type.equals("boolean") || type.equals("Boolean")) {
1252            return "BOOLEAN";
1253        }
1254        else if (type.equals("double") || type.equals("Double")) {
1255            return "DOUBLE";
1256        }
1257        else if (type.equals("float") || type.equals("Float")) {
1258            return "FLOAT";
1259        }
1260        else if (type.equals("int") || type.equals("Integer")) {
1261            return "INTEGER";
1262        }
1263        else if (type.equals("long") || type.equals("Long")) {
1264            return "BIGINT";
1265        }
1266        else if (type.equals("short") || type.equals("Short")) {
1267            return "INTEGER";
1268        }
1269        else if (type.equals("Date")) {
1270            return "TIMESTAMP";
1271        }
1272        else if (type.equals("String")) {
1273            Map hints = ModelHintsUtil.getHints(model, field);
1274
1275            if (hints != null) {
1276                int maxLength = GetterUtil.getInteger(
1277                    (String)hints.get("max-length"));
1278
1279                if (maxLength == 2000000) {
1280                    return "CLOB";
1281                }
1282            }
1283
1284            return "VARCHAR";
1285        }
1286        else {
1287            return null;
1288        }
1289    }
1290
1291    public boolean isCustomMethod(JavaMethod method) {
1292        String methodName = method.getName();
1293
1294        if (methodName.equals("hasAdministrator") ||
1295            methodName.equals("ejbCreate") ||
1296            methodName.equals("ejbRemove") ||
1297            methodName.equals("ejbActivate") ||
1298            methodName.equals("ejbPassivate") ||
1299            methodName.equals("getSessionContext") ||
1300            methodName.equals("setSessionContext") ||
1301            methodName.equals("hashCode") ||
1302            methodName.equals("getClass") ||
1303            methodName.equals("wait") ||
1304            methodName.equals("equals") ||
1305            methodName.equals("toString") ||
1306            methodName.equals("notify") ||
1307            methodName.equals("notifyAll")) {
1308
1309            return false;
1310        }
1311        else if (methodName.equals("getPermissionChecker")) {
1312            return false;
1313        }
1314        else if (methodName.equals("getUser") &&
1315                 method.getParameters().length == 0) {
1316
1317            return false;
1318        }
1319        else if (methodName.equals("getUserId") &&
1320                 method.getParameters().length == 0) {
1321
1322            return false;
1323        }
1324        else if ((methodName.endsWith("Service")) &&
1325                 (methodName.startsWith("get") ||
1326                  methodName.startsWith("set"))) {
1327
1328            return false;
1329        }
1330        else {
1331            return true;
1332        }
1333    }
1334
1335    public boolean isSoapMethod(JavaMethod method) {
1336        String returnValueName = method.getReturns().getValue();
1337
1338        if (returnValueName.startsWith("java.io") ||
1339            returnValueName.equals("java.util.Map") ||
1340            returnValueName.equals("java.util.Properties") ||
1341            returnValueName.startsWith("javax")) {
1342
1343            return false;
1344        }
1345
1346        JavaParameter[] parameters = method.getParameters();
1347
1348        for (int i = 0; i < parameters.length; i++) {
1349            JavaParameter javaParameter = parameters[i];
1350
1351            String parameterTypeName =
1352                javaParameter.getType().getValue() +
1353                    _getDimensions(javaParameter.getType());
1354
1355            if ((parameterTypeName.indexOf(
1356                    "com.liferay.portal.model.") != -1) ||
1357                (parameterTypeName.equals(
1358                    "com.liferay.portal.theme.ThemeDisplay")) ||
1359                (parameterTypeName.equals(
1360                    "com.liferay.portlet.PortletPreferencesImpl")) ||
1361                 parameterTypeName.startsWith("java.io") ||
1362                 //parameterTypeName.startsWith("java.util.List") ||
1363                 //parameterTypeName.startsWith("java.util.Locale") ||
1364                 parameterTypeName.startsWith("java.util.Map") ||
1365                 parameterTypeName.startsWith("java.util.Properties") ||
1366                 parameterTypeName.startsWith("javax")) {
1367
1368                return false;
1369            }
1370        }
1371
1372        return true;
1373    }
1374
1375    private static String _getPackagePath(File file) throws IOException {
1376        String fileName = StringUtil.replace(file.toString(), "\\", "/");
1377
1378        int x = fileName.indexOf("src/");
1379
1380        if (x == -1) {
1381            x = fileName.indexOf("test/");
1382        }
1383
1384        int y = fileName.lastIndexOf("/");
1385
1386        fileName = fileName.substring(x + 4, y);
1387
1388        return StringUtil.replace(fileName, "/", ".");
1389    }
1390
1391    private void _createBaseModelImpl() throws Exception {
1392        if (_baseModelImplPackage.equals("com.liferay.portal.model.impl")) {
1393            return;
1394        }
1395
1396        // Content
1397
1398        String content = _processTemplate(_tplBaseModeImpl);
1399
1400        // Write file
1401
1402        File ejbFile = new File(
1403            _implDir + "/" +
1404                StringUtil.replace(_baseModelImplPackage, ".", "/") +
1405                    "/BaseModelImpl.java");
1406
1407        FileUtil.write(ejbFile, content, true);
1408    }
1409
1410    private void _createBasePersistence() throws Exception {
1411        if (_basePersistencePackage.equals(
1412                "com.liferay.portal.service.persistence")) {
1413
1414            return;
1415        }
1416
1417        // Content
1418
1419        String content = _processTemplate(_tplBasePersistence);
1420
1421        // Write file
1422
1423        File ejbFile = new File(
1424            _implDir + "/" +
1425                StringUtil.replace(_basePersistencePackage, ".", "/") +
1426                    "/BasePersistence.java");
1427
1428        FileUtil.write(ejbFile, content, true);
1429    }
1430
1431    private void _createBeanLocatorUtil() throws Exception {
1432        if (_beanLocatorUtilPackage.equals("com.liferay.portal.kernel.bean")) {
1433            return;
1434        }
1435
1436        // Content
1437
1438        String content = _processTemplate(_tplBeanLocatorUtil);
1439
1440        // Write file
1441
1442        File ejbFile = new File(
1443            _implDir + "/" +
1444                StringUtil.replace(_beanLocatorUtilPackage, ".", "/") +
1445                    "/BeanLocatorUtil.java");
1446
1447        writeFile(ejbFile, content);
1448    }
1449
1450    private void _createDynamicDialect() throws Exception {
1451        if (_springHibernatePackage.equals(
1452                "com.liferay.portal.spring.hibernate")) {
1453
1454            return;
1455        }
1456
1457        // Content
1458
1459        String content = _processTemplate(_tplDynamicDialect);
1460
1461        // Write file
1462
1463        File ejbFile = new File(
1464            _implDir + "/" +
1465                StringUtil.replace(_springHibernatePackage, ".", "/") +
1466                    "/DynamicDialect.java");
1467
1468        FileUtil.write(ejbFile, content, true);
1469    }
1470
1471    private void _createEJBPK(Entity entity) throws Exception {
1472        Map context = _getContext();
1473
1474        context.put("entity", entity);
1475
1476        // Content
1477
1478        String content = _processTemplate(_tplEjbPk, context);
1479
1480        // Write file
1481
1482        File ejbFile = new File(
1483            _serviceOutputPath + "/service/persistence/" +
1484                entity.getPKClassName() + ".java");
1485
1486        writeFile(ejbFile, content);
1487    }
1488
1489    private void _createExceptions(List exceptions) throws Exception {
1490        for (int i = 0; i < _ejbList.size(); i++) {
1491            Entity entity = (Entity) _ejbList.get(i);
1492
1493            if (entity.hasColumns()) {
1494                exceptions.add(getNoSuchEntityException(entity));
1495            }
1496        }
1497
1498        for (int i = 0; i < exceptions.size(); i++) {
1499            String exception = (String) exceptions.get(i);
1500
1501            File exceptionFile = new File(
1502                _serviceOutputPath + "/" + exception + "Exception.java");
1503
1504            if (!exceptionFile.exists()) {
1505                Map context = _getContext();
1506
1507                context.put("exception", exception);
1508
1509                String content = _processTemplate(_tplException, context);
1510
1511                FileUtil.write(exceptionFile, content);
1512            }
1513        }
1514    }
1515
1516    private void _createExtendedModel(Entity entity) throws Exception {
1517        JavaClass javaClass = _getJavaClass(
1518            _outputPath + "/model/impl/" + entity.getName() + "Impl.java");
1519
1520        Map context = _getContext();
1521
1522        context.put("entity", entity);
1523        context.put("methods", javaClass.getMethods());
1524
1525        // Content
1526
1527        String content = _processTemplate(_tplExtendedModel, context);
1528
1529        // Write file
1530
1531        File modelFile = new File(
1532            _serviceOutputPath + "/model/" + entity.getName() + ".java");
1533
1534        Map jalopySettings = new HashMap();
1535
1536        jalopySettings.put("keepJavadoc", Boolean.TRUE);
1537
1538        writeFile(modelFile, content, jalopySettings);
1539    }
1540
1541    private void _createExtendedModelImpl(Entity entity) throws Exception {
1542        Map context = _getContext();
1543
1544        context.put("entity", entity);
1545
1546        // Content
1547
1548        String content = _processTemplate(_tplExtendedModelImpl, context);
1549
1550        // Write file
1551
1552        File modelFile = new File(
1553            _outputPath + "/model/impl/" + entity.getName() + "Impl.java");
1554
1555        if (!modelFile.exists()) {
1556            writeFile(modelFile, content);
1557        }
1558    }
1559
1560    private void _createFinder(Entity entity) throws Exception {
1561        if (!entity.hasFinderClass()) {
1562            return;
1563        }
1564
1565        JavaClass javaClass = _getJavaClass(
1566            _outputPath + "/service/persistence/" + entity.getName() +
1567                "FinderImpl.java");
1568
1569        Map context = _getContext();
1570
1571        context.put("entity", entity);
1572        context.put("methods", javaClass.getMethods());
1573
1574        // Content
1575
1576        String content = _processTemplate(_tplFinder, context);
1577
1578        // Write file
1579
1580        File ejbFile = new File(
1581            _serviceOutputPath + "/service/persistence/" + entity.getName() +
1582                "Finder.java");
1583
1584        writeFile(ejbFile, content);
1585    }
1586
1587    private void _createFinderCache() throws Exception {
1588        if (_springHibernatePackage.equals("com.liferay.portal.spring.hibernate")) {
1589            return;
1590        }
1591
1592        // Content
1593
1594        String content = _processTemplate(_tplFinderCache);
1595
1596        // Write file
1597
1598        File ejbFile = new File(
1599            _implDir + "/" +
1600                StringUtil.replace(_springHibernatePackage, ".", "/") +
1601                "/FinderCache.java");
1602
1603        FileUtil.write(ejbFile, content, true);
1604    }
1605
1606    private void _createFinderUtil(Entity entity) throws Exception {
1607        if (!entity.hasFinderClass()) {
1608            return;
1609        }
1610
1611        JavaClass javaClass = _getJavaClass(
1612            _outputPath + "/service/persistence/" + entity.getName() +
1613                "FinderImpl.java");
1614
1615        Map context = _getContext();
1616
1617        context.put("entity", entity);
1618        context.put("methods", javaClass.getMethods());
1619
1620        // Content
1621
1622        String content = _processTemplate(_tplFinderUtil, context);
1623
1624        // Write file
1625
1626        File ejbFile = new File(
1627            _serviceOutputPath + "/service/persistence/" + entity.getName() +
1628                "FinderUtil.java");
1629
1630        writeFile(ejbFile, content);
1631    }
1632
1633    private void _createHBM(Entity entity) throws IOException {
1634        File ejbFile = new File(
1635            _outputPath + "/service/persistence/" + entity.getName() +
1636                "HBM.java");
1637
1638        if (ejbFile.exists()) {
1639            System.out.println("Removing deprecated " + ejbFile);
1640
1641            ejbFile.delete();
1642        }
1643    }
1644
1645    private void _createHBMUtil(Entity entity) throws IOException {
1646        File ejbFile = new File(
1647            _outputPath + "/service/persistence/" + entity.getName() +
1648                "HBMUtil.java");
1649
1650        if (ejbFile.exists()) {
1651            System.out.println("Removing deprecated " + ejbFile);
1652
1653            ejbFile.delete();
1654        }
1655    }
1656
1657    private void _createHBMXML() throws Exception {
1658        Map context = _getContext();
1659
1660        context.put("entities", _ejbList);
1661
1662        // Content
1663
1664        String content = _processTemplate(_tplHbmXml, context);
1665
1666        File xmlFile = new File(_hbmFileName);
1667
1668        if (!xmlFile.exists()) {
1669            String xml =
1670                "<?xml version=\"1.0\"?>\n" +
1671                "<!DOCTYPE hibernate-mapping PUBLIC \"-//Hibernate/Hibernate Mapping DTD 3.0//EN\" \"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd\">\n" +
1672                "\n" +
1673                "<hibernate-mapping default-lazy=\"false\" auto-import=\"false\">\n" +
1674                "</hibernate-mapping>";
1675
1676            FileUtil.write(xmlFile, xml);
1677        }
1678
1679        String oldContent = FileUtil.read(xmlFile);
1680        String newContent = _fixHBMXML(oldContent);
1681
1682        int firstClass = newContent.indexOf(
1683            "<class name=\"" + _packagePath + ".model.impl.");
1684        int lastClass = newContent.lastIndexOf(
1685            "<class name=\"" + _packagePath + ".model.impl.");
1686
1687        if (firstClass == -1) {
1688            int x = newContent.indexOf("</hibernate-mapping>");
1689
1690            newContent =
1691                newContent.substring(0, x) + content +
1692                newContent.substring(x, newContent.length());
1693        }
1694        else {
1695            firstClass = newContent.lastIndexOf("<class", firstClass) - 1;
1696            lastClass = newContent.indexOf("</class>", lastClass) + 9;
1697
1698            newContent =
1699                newContent.substring(0, firstClass) + content +
1700                    newContent.substring(lastClass, newContent.length());
1701        }
1702
1703        newContent = _formatXML(newContent);
1704
1705        if (!oldContent.equals(newContent)) {
1706            FileUtil.write(xmlFile, newContent);
1707        }
1708    }
1709
1710    private void _createHibernateConfiguration() throws Exception {
1711        if (_springHibernatePackage.equals(
1712                "com.liferay.portal.spring.hibernate")) {
1713
1714            return;
1715        }
1716
1717        // Content
1718
1719        String content = _processTemplate(_tplHibernateConfiguration);
1720
1721        // Write file
1722
1723        File ejbFile = new File(
1724            _implDir + "/" +
1725                StringUtil.replace(_springHibernatePackage, ".", "/") +
1726                    "/HibernateConfiguration.java");
1727
1728        FileUtil.write(ejbFile, content, true);
1729    }
1730
1731    private void _createHibernateUtil() throws Exception {
1732        if (_springHibernatePackage.equals(
1733                "com.liferay.portal.spring.hibernate")) {
1734
1735            return;
1736        }
1737
1738        // Content
1739
1740        String content = _processTemplate(_tplHibernateUtil);
1741
1742        // Write file
1743
1744        File ejbFile = new File(
1745            _implDir + "/" +
1746                StringUtil.replace(_springHibernatePackage, ".", "/") +
1747                "/HibernateUtil.java");
1748
1749        FileUtil.write(ejbFile, content, true);
1750    }
1751
1752    private void _createJSONJS() throws Exception {
1753        StringMaker content = new StringMaker();
1754
1755        if (_ejbList.size() > 0) {
1756            content.append(_processTemplate(_tplJsonJs));
1757        }
1758
1759        for (int i = 0; i < _ejbList.size(); i++) {
1760            Entity entity = (Entity)_ejbList.get(i);
1761
1762            if (entity.hasRemoteService()) {
1763                JavaClass javaClass = _getJavaClass(
1764                    _outputPath + "/service/http/" + entity.getName() +
1765                        "ServiceJSON.java");
1766
1767                JavaMethod[] methods = javaClass.getMethods();
1768
1769                Set jsonMethods = new LinkedHashSet();
1770
1771                for (int j = 0; j < methods.length; j++) {
1772                    JavaMethod javaMethod = methods[j];
1773
1774                    String methodName = javaMethod.getName();
1775
1776                    if (javaMethod.isPublic()) {
1777                        jsonMethods.add(methodName);
1778                    }
1779                }
1780
1781                if (jsonMethods.size() > 0) {
1782                    Map context = _getContext();
1783
1784                    context.put("entity", entity);
1785                    context.put("methods", jsonMethods);
1786
1787                    content.append("\n\n");
1788                    content.append(_processTemplate(_tplJsonJsMethod, context));
1789                }
1790            }
1791        }
1792
1793        File jsonFile = new File(_jsonFileName);
1794
1795        if (!jsonFile.exists()) {
1796            FileUtil.write(jsonFile, "");
1797        }
1798
1799        String oldContent = FileUtil.read(jsonFile);
1800        String newContent = new String(oldContent);
1801
1802        int oldBegin = oldContent.indexOf(
1803            "Liferay.Service." + _portletShortName);
1804
1805        int oldEnd = oldContent.lastIndexOf(
1806            "Liferay.Service." + _portletShortName);
1807
1808        oldEnd = oldContent.indexOf("};", oldEnd);
1809
1810        int newBegin = newContent.indexOf(
1811            "Liferay.Service." + _portletShortName);
1812
1813        int newEnd = newContent.lastIndexOf(
1814            "Liferay.Service." + _portletShortName);
1815
1816        newEnd = newContent.indexOf("};", newEnd);
1817
1818        if (newBegin == -1) {
1819            newContent = oldContent + "\n\n" + content.toString().trim();
1820        }
1821        else {
1822            newContent =
1823                newContent.substring(0, oldBegin) + content.toString().trim() +
1824                    newContent.substring(oldEnd + 2, newContent.length());
1825        }
1826
1827        if (!oldContent.equals(newContent)) {
1828            FileUtil.write(jsonFile, newContent);
1829        }
1830    }
1831
1832    private void _createModel(Entity entity) throws Exception {
1833        Map context = _getContext();
1834
1835        context.put("entity", entity);
1836
1837        // Content
1838
1839        String content = _processTemplate(_tplModel, context);
1840
1841        // Write file
1842
1843        File modelFile = new File(
1844            _serviceOutputPath + "/model/" + entity.getName() + "Model.java");
1845
1846        Map jalopySettings = new HashMap();
1847
1848        jalopySettings.put("keepJavadoc", Boolean.TRUE);
1849
1850        writeFile(modelFile, content, jalopySettings);
1851    }
1852
1853    private void _createModelHintsXML() throws Exception {
1854        Map context = _getContext();
1855
1856        context.put("entities", _ejbList);
1857
1858        // Content
1859
1860        String content = _processTemplate(_tplModelHintsXml, context);
1861
1862        File xmlFile = new File(_modelHintsFileName);
1863
1864        if (!xmlFile.exists()) {
1865            String xml =
1866                "<?xml version=\"1.0\"?>\n" +
1867                "\n" +
1868                "<model-hints>\n" +
1869                "</model-hints>";
1870
1871            FileUtil.write(xmlFile, xml);
1872        }
1873
1874        String oldContent = FileUtil.read(xmlFile);
1875        String newContent = new String(oldContent);
1876
1877        int firstModel = newContent.indexOf(
1878            "<model name=\"" + _packagePath + ".model.");
1879        int lastModel = newContent.lastIndexOf(
1880            "<model name=\"" + _packagePath + ".model.");
1881
1882        if (firstModel == -1) {
1883            int x = newContent.indexOf("</model-hints>");
1884
1885            newContent =
1886                newContent.substring(0, x) + content +
1887                    newContent.substring(x, newContent.length());
1888        }
1889        else {
1890            firstModel = newContent.lastIndexOf("<model", firstModel) - 1;
1891            lastModel = newContent.indexOf("</model>", lastModel) + 9;
1892
1893            newContent =
1894                newContent.substring(0, firstModel) + content +
1895                newContent.substring(lastModel, newContent.length());
1896        }
1897
1898        newContent = _formatXML(newContent);
1899
1900        if (!oldContent.equals(newContent)) {
1901            FileUtil.write(xmlFile, newContent);
1902        }
1903    }
1904
1905    private void _createModelImpl(Entity entity) throws Exception {
1906        Map context = _getContext();
1907
1908        context.put("entity", entity);
1909
1910        // Content
1911
1912        String content = _processTemplate(_tplModelImpl, context);
1913
1914        // Write file
1915
1916        File modelFile = new File(
1917            _outputPath + "/model/impl/" + entity.getName() + "ModelImpl.java");
1918
1919        Map jalopySettings = new HashMap();
1920
1921        jalopySettings.put("keepJavadoc", Boolean.TRUE);
1922
1923        writeFile(modelFile, content, jalopySettings);
1924    }
1925
1926    private void _createModelSoap(Entity entity) throws Exception {
1927        Map context = _getContext();
1928
1929        context.put("entity", entity);
1930
1931        // Content
1932
1933        String content = _processTemplate(_tplModelSoap, context);
1934
1935        // Write file
1936
1937        File modelFile = new File(
1938            _serviceOutputPath + "/model/" + entity.getName() + "Soap.java");
1939
1940        Map jalopySettings = new HashMap();
1941
1942        jalopySettings.put("keepJavadoc", Boolean.TRUE);
1943
1944        writeFile(modelFile, content, jalopySettings);
1945    }
1946
1947    private void _createPersistence(Entity entity) throws Exception {
1948        JavaClass javaClass = _getJavaClass(
1949            _outputPath + "/service/persistence/" + entity.getName() +
1950                "PersistenceImpl.java");
1951
1952        Map context = _getContext();
1953
1954        context.put("entity", entity);
1955        context.put("methods", javaClass.getMethods());
1956
1957        // Content
1958
1959        String content = _processTemplate(_tplPersistence, context);
1960
1961        // Write file
1962
1963        File ejbFile = new File(
1964            _serviceOutputPath + "/service/persistence/" + entity.getName() +
1965                "Persistence.java");
1966
1967        writeFile(ejbFile, content);
1968
1969        if (!_serviceOutputPath.equals(_outputPath)) {
1970            ejbFile = new File(
1971                _outputPath + "/service/persistence/" + entity.getName() +
1972                    "Persistence.java");
1973
1974            if (ejbFile.exists()) {
1975                System.out.println("Relocating " + ejbFile);
1976
1977                ejbFile.delete();
1978            }
1979        }
1980    }
1981
1982    private void _createPersistenceImpl(Entity entity) throws Exception {
1983        Map context = _getContext();
1984
1985        context.put("entity", entity);
1986
1987        // Content
1988
1989        String content = _processTemplate(_tplPersistenceImpl, context);
1990
1991        // Write file
1992
1993        File ejbFile = new File(
1994            _outputPath + "/service/persistence/" + entity.getName() +
1995                "PersistenceImpl.java");
1996
1997        writeFile(ejbFile, content);
1998    }
1999
2000    private void _createPersistenceTest(Entity entity) throws Exception {
2001        Map context = _getContext();
2002
2003        context.put("entity", entity);
2004
2005        // Content
2006
2007        String content = _processTemplate(_tplPersistenceTest, context);
2008
2009        // Write file
2010
2011        File ejbFile = new File(
2012            _testOutputPath + "/service/persistence/" + entity.getName() +
2013                "PersistenceTest.java");
2014
2015        writeFile(ejbFile, content);
2016    }
2017
2018    private void _createPersistenceUtil(Entity entity) throws Exception {
2019        JavaClass javaClass = _getJavaClass(
2020            _outputPath + "/service/persistence/" + entity.getName() +
2021                "PersistenceImpl.java");
2022
2023        Map context = _getContext();
2024
2025        context.put("entity", entity);
2026        context.put("methods", javaClass.getMethods());
2027
2028        // Content
2029
2030        String content = _processTemplate(_tplPersistenceUtil, context);
2031
2032        // Write file
2033
2034        File ejbFile = new File(
2035            _serviceOutputPath + "/service/persistence/" + entity.getName() +
2036                "Util.java");
2037
2038        writeFile(ejbFile, content);
2039
2040        if (!_serviceOutputPath.equals(_outputPath)) {
2041            ejbFile = new File(
2042                _outputPath + "/service/persistence/" + entity.getName() +
2043                    "Util.java");
2044
2045            if (ejbFile.exists()) {
2046                System.out.println("Relocating " + ejbFile);
2047
2048                ejbFile.delete();
2049            }
2050        }
2051    }
2052
2053    private void _createPool(Entity entity) throws IOException {
2054        File ejbFile = new File(
2055            _outputPath + "/service/persistence/" + entity.getName() +
2056                "Pool.java");
2057
2058        if (ejbFile.exists()) {
2059            System.out.println("Removing deprecated " + ejbFile);
2060
2061            ejbFile.delete();
2062        }
2063    }
2064
2065    private void _createPrincipalBean() throws Exception {
2066        if (_principalBeanPackage.equals("com.liferay.portal.service.impl")) {
2067            return;
2068        }
2069
2070        // Content
2071
2072        String content = _processTemplate(_tplPrincipalBean);
2073
2074        // Write file
2075
2076        File ejbFile = new File(
2077            _implDir + "/" +
2078                StringUtil.replace(_principalBeanPackage, ".", "/") +
2079                    "/PrincipalBean.java");
2080
2081        FileUtil.write(ejbFile, content, true);
2082    }
2083
2084    private void _createProps() throws Exception {
2085        if (_propsUtilPackage.equals("com.liferay.portal.util")) {
2086            return;
2087        }
2088
2089        // Content
2090
2091        File propsFile = new File(_implDir + "/portlet-service.properties");
2092
2093        long buildNumber = 1;
2094
2095        if (propsFile.exists()) {
2096            Properties props = PropertiesUtil.load(FileUtil.read(propsFile));
2097
2098            buildNumber = GetterUtil.getLong(
2099                props.getProperty("build.number")) + 1;
2100        }
2101
2102        Map context = _getContext();
2103
2104        context.put("buildNumber", new Long(buildNumber));
2105        context.put("currentTimeMillis", new Long(System.currentTimeMillis()));
2106
2107        String content = _processTemplate(_tplProps, context);
2108
2109        // Write file
2110
2111        FileUtil.write(propsFile, content, true);
2112    }
2113
2114    private void _createPropsUtil() throws Exception {
2115        if (_propsUtilPackage.equals("com.liferay.portal.util")) {
2116            return;
2117        }
2118
2119        // Content
2120
2121        String content = _processTemplate(_tplPropsUtil);
2122
2123        // Write file
2124
2125        File ejbFile = new File(
2126            _implDir + "/" + StringUtil.replace(_propsUtilPackage, ".", "/") +
2127                "/PropsUtil.java");
2128
2129        writeFile(ejbFile, content);
2130    }
2131
2132    private void _createRemotingXML() throws Exception {
2133        StringMaker sm = new StringMaker();
2134
2135        Document doc = PortalUtil.readDocumentFromFile(
2136            new File(_springFileName), true);
2137
2138        Iterator itr = doc.getRootElement().elements("bean").iterator();
2139
2140        while (itr.hasNext()) {
2141            Element beanEl = (Element)itr.next();
2142
2143            String beanId = beanEl.attributeValue("id");
2144
2145            if (beanId.endsWith("ServiceFactory") &&
2146                !beanId.endsWith("LocalServiceFactory")) {
2147
2148                String serviceName = beanId.substring(0, beanId.length() - 7);
2149
2150                String serviceMapping = serviceName;
2151                serviceMapping = StringUtil.replace(
2152                    serviceMapping, ".service.", ".service.spring.");
2153                serviceMapping = StringUtil.replace(
2154                    serviceMapping, ".", "_");
2155
2156                Map context = _getContext();
2157
2158                context.put("serviceName", serviceName);
2159                context.put("serviceMapping", serviceMapping);
2160
2161                sm.append(_processTemplate(_tplRemotingXml, context));
2162            }
2163        }
2164
2165        File outputFile = new File(_remotingFileName);
2166
2167        if (!outputFile.exists()) {
2168            return;
2169        }
2170
2171        String content = FileUtil.read(outputFile);
2172        String newContent = content;
2173
2174        int x = content.indexOf("<bean ");
2175        int y = content.lastIndexOf("</bean>") + 8;
2176
2177        if (x != -1) {
2178            newContent =
2179                content.substring(0, x - 1) + sm.toString() +
2180                    content.substring(y, content.length());
2181        }
2182        else {
2183            x = content.indexOf("</beans>");
2184
2185            newContent =
2186                content.substring(0, x) + sm.toString() +
2187                    content.substring(x, content.length());
2188        }
2189
2190        newContent = _formatXML(newContent);
2191
2192        if (!content.equals(newContent)) {
2193            FileUtil.write(outputFile, newContent);
2194
2195            System.out.println(outputFile.toString());
2196        }
2197    }
2198
2199    private void _createService(Entity entity, int sessionType)
2200        throws Exception {
2201
2202        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.";
2203
2204        JavaClass javaClass = _getJavaClass(_outputPath + "/service/impl/" + entity.getName() + (sessionType != _REMOTE ? "Local" : "") + "ServiceImpl.java");
2205
2206        JavaMethod[] methods = javaClass.getMethods();
2207
2208        if (sessionType == _LOCAL) {
2209            if (javaClass.getSuperClass().getValue().endsWith(
2210                    entity.getName() + "LocalServiceBaseImpl")) {
2211
2212                JavaClass parentJavaClass = _getJavaClass(
2213                    _outputPath + "/service/base/" + entity.getName() +
2214                        "LocalServiceBaseImpl.java");
2215
2216                JavaMethod[] parentMethods = parentJavaClass.getMethods();
2217
2218                JavaMethod[] allMethods = new JavaMethod[parentMethods.length + methods.length];
2219
2220                ArrayUtil.combine(parentMethods, methods, allMethods);
2221
2222                methods = allMethods;
2223            }
2224
2225            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.";
2226        }
2227
2228        Map context = _getContext();
2229
2230        context.put("entity", entity);
2231        context.put("methods", methods);
2232        context.put("sessionTypeName",_getSessionTypeName(sessionType));
2233        context.put("serviceComments", serviceComments);
2234
2235        // Content
2236
2237        String content = _processTemplate(_tplService, context);
2238
2239        // Write file
2240
2241        File ejbFile = new File(
2242            _serviceOutputPath + "/service/" + entity.getName() +
2243                _getSessionTypeName(sessionType) + "Service.java");
2244
2245        Map jalopySettings = new HashMap();
2246
2247        jalopySettings.put("keepJavadoc", Boolean.TRUE);
2248
2249        writeFile(ejbFile, content, jalopySettings);
2250    }
2251
2252    private void _createServiceBaseImpl(Entity entity, int sessionType)
2253        throws Exception {
2254
2255        Map context = _getContext();
2256
2257        context.put("entity", entity);
2258        context.put("sessionTypeName",_getSessionTypeName(sessionType));
2259        context.put(
2260            "referenceList", _mergeReferenceList(entity.getReferenceList()));
2261
2262        // Content
2263
2264        String content = _processTemplate(_tplServiceBaseImpl, context);
2265
2266        // Write file
2267
2268        File ejbFile = new File(
2269            _outputPath + "/service/base/" + entity.getName() +
2270                _getSessionTypeName(sessionType) + "ServiceBaseImpl.java");
2271
2272        writeFile(ejbFile, content);
2273    }
2274
2275    private void _createServiceFactory(Entity entity, int sessionType)
2276        throws Exception {
2277
2278        Map context = _getContext();
2279
2280        context.put("entity", entity);
2281        context.put("sessionTypeName", _getSessionTypeName(sessionType));
2282
2283        // Content
2284
2285        String content = _processTemplate(_tplServiceFactory, context);
2286
2287        // Write file
2288
2289        File ejbFile = new File(
2290            _serviceOutputPath + "/service/" + entity.getName() +
2291                _getSessionTypeName(sessionType) + "ServiceFactory.java");
2292
2293        Map jalopySettings = new HashMap();
2294
2295        jalopySettings.put("keepJavadoc", Boolean.TRUE);
2296
2297        writeFile(ejbFile, content, jalopySettings);
2298    }
2299
2300    private void _createServiceHttp(Entity entity) throws Exception {
2301        JavaClass javaClass = _getJavaClass(
2302            _outputPath + "/service/impl/" + entity.getName() +
2303                "ServiceImpl.java");
2304
2305        Map context = _getContext();
2306
2307        context.put("entity", entity);
2308        context.put("methods", javaClass.getMethods());
2309        context.put("hasHttpMethods", new Boolean(_hasHttpMethods(javaClass)));
2310
2311        // Content
2312
2313        String content = _processTemplate(_tplServiceHttp, context);
2314
2315        // Write file
2316
2317        File ejbFile = new File(
2318            _outputPath + "/service/http/" + entity.getName() +
2319                "ServiceHttp.java");
2320
2321        Map jalopySettings = new HashMap();
2322
2323        jalopySettings.put("keepJavadoc", Boolean.TRUE);
2324
2325        writeFile(ejbFile, content, jalopySettings);
2326    }
2327
2328    private void _createServiceImpl(Entity entity, int sessionType)
2329        throws Exception {
2330
2331        Map context = _getContext();
2332
2333        context.put("entity", entity);
2334        context.put("sessionTypeName", _getSessionTypeName(sessionType));
2335
2336        // Content
2337
2338        String content = _processTemplate(_tplServiceImpl, context);
2339
2340        // Write file
2341
2342        File ejbFile = new File(
2343            _outputPath + "/service/impl/" + entity.getName() +
2344                _getSessionTypeName(sessionType) + "ServiceImpl.java");
2345
2346        if (!ejbFile.exists()) {
2347            writeFile(ejbFile, content);
2348        }
2349    }
2350
2351    private void _createServiceJSON(Entity entity) throws Exception {
2352        JavaClass javaClass = _getJavaClass(
2353            _outputPath + "/service/impl/" + entity.getName() +
2354                "ServiceImpl.java");
2355
2356        Map context = _getContext();
2357
2358        context.put("entity", entity);
2359        context.put("methods", javaClass.getMethods());
2360
2361        // Content
2362
2363        String content = _processTemplate(_tplServiceJson, context);
2364
2365        // Write file
2366
2367        File ejbFile = new File(
2368            _outputPath + "/service/http/" + entity.getName() +
2369                "ServiceJSON.java");
2370
2371        Map jalopySettings = new HashMap();
2372
2373        jalopySettings.put("keepJavadoc", Boolean.TRUE);
2374
2375        writeFile(ejbFile, content, jalopySettings);
2376    }
2377
2378    private void _createServiceJSONSerializer(Entity entity) throws Exception {
2379        Map context = _getContext();
2380
2381        context.put("entity", entity);
2382
2383        // Content
2384
2385        String content = _processTemplate(_tplServiceJsonSerializer, context);
2386
2387        // Write file
2388
2389        File ejbFile = new File(
2390            _outputPath + "/service/http/" + entity.getName() +
2391                "JSONSerializer.java");
2392
2393        Map jalopySettings = new HashMap();
2394
2395        jalopySettings.put("keepJavadoc", Boolean.TRUE);
2396
2397        writeFile(ejbFile, content, jalopySettings);
2398    }
2399
2400    private void _createServiceSoap(Entity entity) throws Exception {
2401        JavaClass javaClass = _getJavaClass(
2402            _outputPath + "/service/impl/" + entity.getName() +
2403                "ServiceImpl.java");
2404
2405        Map context = _getContext();
2406
2407        context.put("entity", entity);
2408        context.put("methods", javaClass.getMethods());
2409
2410        // Content
2411
2412        String content = _processTemplate(_tplServiceSoap, context);
2413
2414        // Write file
2415
2416        File ejbFile = new File(
2417            _outputPath + "/service/http/" + entity.getName() +
2418                "ServiceSoap.java");
2419
2420        Map jalopySettings = new HashMap();
2421
2422        jalopySettings.put("keepJavadoc", Boolean.TRUE);
2423
2424        writeFile(ejbFile, content, jalopySettings);
2425    }
2426
2427    private void _createServiceUtil(Entity entity, int sessionType)
2428        throws Exception {
2429
2430        JavaClass javaClass = _getJavaClass(
2431            _serviceOutputPath + "/service/" + entity.getName() +
2432                (sessionType != _REMOTE ? "Local" : "") + "Service.java");
2433
2434        Map context = _getContext();
2435
2436        context.put("entity", entity);
2437        context.put("methods", javaClass.getMethods());
2438        context.put("sessionTypeName", _getSessionTypeName(sessionType));
2439
2440        // Content
2441
2442        String content = _processTemplate(_tplServiceUtil, context);
2443
2444        // Write file
2445
2446        File ejbFile = new File(
2447            _serviceOutputPath + "/service/" + entity.getName() +
2448                _getSessionTypeName(sessionType) + "ServiceUtil.java");
2449
2450        Map jalopySettings = new HashMap();
2451
2452        jalopySettings.put("keepJavadoc", Boolean.TRUE);
2453
2454        writeFile(ejbFile, content, jalopySettings);
2455    }
2456
2457    private void _createSpringDataSourceXML() throws Exception {
2458        if (Validator.isNull(_springDataSourceFileName)) {
2459            return;
2460        }
2461
2462        // Content
2463
2464        String content = _processTemplate(_tplSpringDataSourceXml);
2465
2466        // Write file
2467
2468        File ejbFile = new File(_springDataSourceFileName);
2469
2470        FileUtil.write(ejbFile, content, true);
2471    }
2472
2473    private void _createSpringUtil() throws Exception {
2474        if (_springUtilPackage.equals("com.liferay.portal.spring.util")) {
2475            return;
2476        }
2477
2478        // Content
2479
2480        String content = _processTemplate(_tplSpringUtil);
2481
2482        // Write file
2483
2484        File ejbFile = new File(
2485            _implDir + "/" + StringUtil.replace(_springUtilPackage, ".", "/") +
2486                "/SpringUtil.java");
2487
2488        FileUtil.write(ejbFile, content, true);
2489    }
2490
2491    private void _createSpringXML() throws Exception {
2492        Map context = _getContext();
2493
2494        context.put("entities", _ejbList);
2495
2496        // Content
2497
2498        String content = _processTemplate(_tplSpringXml, context);
2499
2500        File xmlFile = new File(_springFileName);
2501
2502        if (!xmlFile.exists()) {
2503            String xml =
2504                "<?xml version=\"1.0\"?>\n" +
2505                "<!DOCTYPE beans PUBLIC \"-//SPRING//DTD BEAN//EN\" \"http://www.springframework.org/dtd/spring-beans.dtd\">\n" +
2506                "\n" +
2507                "<beans>\n" +
2508                "</beans>";
2509
2510            FileUtil.write(xmlFile, xml);
2511        }
2512
2513        String oldContent = FileUtil.read(xmlFile);
2514        String newContent = _fixSpringXML(oldContent);
2515
2516        int x = oldContent.indexOf("<beans>");
2517        int y = oldContent.lastIndexOf("</beans>");
2518
2519        int firstSession = newContent.indexOf(
2520            "<bean id=\"" + _packagePath + ".service.", x);
2521
2522        int lastSession = newContent.lastIndexOf(
2523            "<bean id=\"" + _packagePath + ".service.", y);
2524
2525        if (firstSession == -1 || firstSession > y) {
2526            x = newContent.indexOf("</beans>");
2527            newContent =
2528                newContent.substring(0, x) + content +
2529                newContent.substring(x, newContent.length());
2530        }
2531        else {
2532            firstSession = newContent.lastIndexOf("<bean", firstSession) - 1;
2533            lastSession = newContent.indexOf("</bean>", lastSession) + 8;
2534
2535            newContent =
2536                newContent.substring(0, firstSession) + content +
2537                newContent.substring(lastSession, newContent.length());
2538        }
2539
2540        newContent = _formatXML(newContent);
2541
2542        if (!oldContent.equals(newContent)) {
2543            FileUtil.write(xmlFile, newContent);
2544        }
2545    }
2546
2547    private void _createSQLIndexes() throws IOException {
2548        if (!FileUtil.exists(_sqlDir)) {
2549            return;
2550        }
2551
2552        // indexes.sql
2553
2554        File sqlFile = new File(_sqlDir + "/indexes.sql");
2555
2556        if (!sqlFile.exists()) {
2557            FileUtil.write(sqlFile, "");
2558        }
2559
2560        Map indexSQLs = new TreeMap();
2561
2562        BufferedReader br = new BufferedReader(new FileReader(sqlFile));
2563
2564        while (true) {
2565            String indexSQL = br.readLine();
2566
2567            if (indexSQL == null) {
2568                break;
2569            }
2570
2571            if (Validator.isNotNull(indexSQL.trim())) {
2572                int pos = indexSQL.indexOf(" on ");
2573
2574                String indexSpec = indexSQL.substring(pos + 4);
2575
2576                indexSQLs.put(indexSpec, indexSQL);
2577            }
2578        }
2579
2580        br.close();
2581
2582        // indexes.properties
2583
2584        File propsFile = new File(_sqlDir + "/indexes.properties");
2585
2586        if (!propsFile.exists()) {
2587            FileUtil.write(propsFile, "");
2588        }
2589
2590        Map indexProps = new TreeMap();
2591
2592        br = new BufferedReader(new FileReader(propsFile));
2593
2594        while (true) {
2595            String indexMapping = br.readLine();
2596
2597            if (indexMapping == null) {
2598                break;
2599            }
2600
2601            if (Validator.isNotNull(indexMapping.trim())) {
2602                String[] splitIndexMapping = indexMapping.split("\\=");
2603
2604                indexProps.put(splitIndexMapping[1], splitIndexMapping[0]);
2605            }
2606        }
2607
2608        br.close();
2609
2610        // indexes.sql
2611
2612        for (int i = 0; i < _ejbList.size(); i++) {
2613            Entity entity = (Entity)_ejbList.get(i);
2614
2615            List finderList = entity.getFinderList();
2616
2617            for (int j = 0; j < finderList.size(); j++) {
2618                EntityFinder finder = (EntityFinder)finderList.get(j);
2619
2620                if (finder.isDBIndex()) {
2621                    StringMaker sm = new StringMaker();
2622
2623                    sm.append(entity.getTable() + " (");
2624
2625                    List finderColsList = finder.getColumns();
2626
2627                    for (int k = 0; k < finderColsList.size(); k++) {
2628                        EntityColumn col = (EntityColumn)finderColsList.get(k);
2629
2630                        sm.append(col.getDBName());
2631
2632                        if ((k + 1) != finderColsList.size()) {
2633                            sm.append(", ");
2634                        }
2635                    }
2636
2637                    sm.append(");");
2638
2639                    String indexSpec = sm.toString();
2640
2641                    String indexHash =
2642                        Integer.toHexString(indexSpec.hashCode()).toUpperCase();
2643
2644                    String indexName = "IX_" + indexHash;
2645
2646                    sm = new StringMaker();
2647
2648                    sm.append("create index " + indexName + " on ");
2649                    sm.append(indexSpec);
2650
2651                    indexSQLs.put(indexSpec, sm.toString());
2652
2653                    String finderName =
2654                        entity.getTable() + StringPool.PERIOD +
2655                            finder.getName();
2656
2657                    indexProps.put(finderName, indexName);
2658                }
2659            }
2660        }
2661
2662        StringMaker sm = new StringMaker();
2663
2664        Iterator itr = indexSQLs.values().iterator();
2665
2666        String prevEntityName = null;
2667
2668        while (itr.hasNext()) {
2669            String indexSQL = (String)itr.next();
2670
2671            String entityName = indexSQL.split(" ")[4];
2672
2673            if ((prevEntityName != null) &&
2674                (!prevEntityName.equals(entityName))) {
2675
2676                sm.append("\n");
2677            }
2678
2679            sm.append(indexSQL);
2680
2681            if (itr.hasNext()) {
2682                sm.append("\n");
2683            }
2684
2685            prevEntityName = entityName;
2686        }
2687
2688        FileUtil.write(sqlFile, sm.toString(), true);
2689
2690        // indexes.properties
2691
2692        sm = new StringMaker();
2693
2694        itr = indexProps.keySet().iterator();
2695
2696        prevEntityName = null;
2697
2698        while (itr.hasNext()) {
2699            String finderName = (String)itr.next();
2700
2701            String indexName = (String)indexProps.get(finderName);
2702
2703            String entityName = finderName.split("\\.")[0];
2704
2705            if ((prevEntityName != null) &&
2706                (!prevEntityName.equals(entityName))) {
2707
2708                sm.append("\n");
2709            }
2710
2711            sm.append(indexName + StringPool.EQUAL + finderName);
2712
2713            if (itr.hasNext()) {
2714                sm.append("\n");
2715            }
2716
2717            prevEntityName = entityName;
2718        }
2719
2720        FileUtil.write(propsFile, sm.toString(), true);
2721    }
2722
2723    private void _createSQLSequences() throws IOException {
2724        if (!FileUtil.exists(_sqlDir)) {
2725            return;
2726        }
2727
2728        File sqlFile = new File(_sqlDir + "/sequences.sql");
2729
2730        if (!sqlFile.exists()) {
2731            FileUtil.write(sqlFile, "");
2732        }
2733
2734        Set sequenceSQLs = new TreeSet();
2735
2736        BufferedReader br = new BufferedReader(new FileReader(sqlFile));
2737
2738        while (true) {
2739            String sequenceSQL = br.readLine();
2740
2741            if (sequenceSQL == null) {
2742                break;
2743            }
2744
2745            if (Validator.isNotNull(sequenceSQL)) {
2746                sequenceSQLs.add(sequenceSQL);
2747            }
2748        }
2749
2750        br.close();
2751
2752        for (int i = 0; i < _ejbList.size(); i++) {
2753            Entity entity = (Entity)_ejbList.get(i);
2754
2755            List columnList = entity.getColumnList();
2756
2757            for (int j = 0; j < columnList.size(); j++) {
2758                EntityColumn column = (EntityColumn)columnList.get(j);
2759
2760                if ("sequence".equals(column.getIdType())) {
2761                    StringMaker sm = new StringMaker();
2762
2763                    String sequenceName = column.getIdParam();
2764
2765                    if (sequenceName.length() > 30) {
2766                        sequenceName = sequenceName.substring(0, 30);
2767                    }
2768
2769                    sm.append("create sequence " + sequenceName + ";");
2770
2771                    String sequenceSQL = sm.toString();
2772
2773                    if (!sequenceSQLs.contains(sequenceSQL)) {
2774                        sequenceSQLs.add(sequenceSQL);
2775                    }
2776                }
2777            }
2778        }
2779
2780        StringMaker sm = new StringMaker();
2781
2782        Iterator itr = sequenceSQLs.iterator();
2783
2784        while (itr.hasNext()) {
2785            String sequenceSQL = (String)itr.next();
2786
2787            sm.append(sequenceSQL);
2788
2789            if (itr.hasNext()) {
2790                sm.append("\n");
2791            }
2792        }
2793
2794        FileUtil.write(sqlFile, sm.toString(), true);
2795    }
2796
2797    private void _createSQLTables() throws IOException {
2798        if (!FileUtil.exists(_sqlDir)) {
2799            return;
2800        }
2801
2802        File sqlFile = new File(_sqlDir + "/" + _sqlFileName);
2803
2804        if (!sqlFile.exists()) {
2805            FileUtil.write(sqlFile, StringPool.BLANK);
2806        }
2807
2808        for (int i = 0; i < _ejbList.size(); i++) {
2809            Entity entity = (Entity)_ejbList.get(i);
2810
2811            String createTableSQL = _getCreateTableSQL(entity);
2812
2813            if (Validator.isNotNull(createTableSQL)) {
2814                _createSQLTables(sqlFile, createTableSQL, entity, true);
2815
2816                File updateSQLFile = new File(
2817                    _sqlDir + "/update-4.3.6-4.4.0.sql");
2818
2819                if (updateSQLFile.exists()) {
2820                    _createSQLTables(
2821                        updateSQLFile, createTableSQL, entity, false);
2822                }
2823            }
2824        }
2825    }
2826
2827    private void _createSQLTables(
2828            File sqlFile, String newCreateTableString, Entity entity,
2829            boolean addMissingTables)
2830        throws IOException {
2831
2832        if (!sqlFile.exists()) {
2833            FileUtil.write(sqlFile, StringPool.BLANK);
2834        }
2835
2836        String content = FileUtil.read(sqlFile);
2837
2838        int x = content.indexOf(_CREATE_TABLE + entity.getTable() + " (");
2839        int y = content.indexOf(");", x);
2840
2841        if (x != -1) {
2842            String oldCreateTableString = content.substring(x + 1, y);
2843
2844            if (!oldCreateTableString.equals(newCreateTableString)) {
2845                content =
2846                    content.substring(0, x) + newCreateTableString +
2847                        content.substring(y + 2, content.length());
2848
2849                FileUtil.write(sqlFile, content);
2850            }
2851        }
2852        else if (addMissingTables) {
2853            StringMaker sm = new StringMaker();
2854
2855            BufferedReader br = new BufferedReader(new StringReader(content));
2856
2857            String line = null;
2858            boolean appendNewTable = true;
2859
2860            while ((line = br.readLine()) != null) {
2861                if (appendNewTable && line.startsWith(_CREATE_TABLE)) {
2862                    x = _CREATE_TABLE.length();
2863                    y = line.indexOf(" ", x);
2864
2865                    String tableName = line.substring(x, y);
2866
2867                    if (tableName.compareTo(entity.getTable()) > 0) {
2868                        sm.append(newCreateTableString + "\n\n");
2869
2870                        appendNewTable = false;
2871                    }
2872                }
2873
2874                sm.append(line).append('\n');
2875            }
2876
2877            if (appendNewTable) {
2878                sm.append("\n" + newCreateTableString);
2879            }
2880
2881            br.close();
2882
2883            FileUtil.write(sqlFile, sm.toString(), true);
2884        }
2885    }
2886
2887    private String _fixHBMXML(String content) throws IOException {
2888        StringMaker sm = new StringMaker();
2889
2890        BufferedReader br = new BufferedReader(new StringReader(content));
2891
2892        String line = null;
2893
2894        while ((line = br.readLine()) != null) {
2895            if (line.startsWith("\t<class name=\"")) {
2896                line = StringUtil.replace(
2897                    line,
2898                    new String[] {
2899                        ".service.persistence.", "HBM\" table=\""
2900                    },
2901                    new String[] {
2902                        ".model.", "\" table=\""
2903                    });
2904
2905                if (line.indexOf(".model.impl.") == -1) {
2906                    line = StringUtil.replace(
2907                        line,
2908                        new String[] {
2909                            ".model.", "\" table=\""
2910                        },
2911                        new String[] {
2912                            ".model.impl.", "Impl\" table=\""
2913                        });
2914                }
2915            }
2916
2917            sm.append(line);
2918            sm.append('\n');
2919        }
2920
2921        br.close();
2922
2923        return sm.toString().trim();
2924    }
2925
2926    private String _fixSpringXML(String content) throws IOException {
2927        return StringUtil.replace(content, ".service.spring.", ".service.");
2928    }
2929
2930    private String _formatXML(String xml)
2931        throws DocumentException, IOException {
2932
2933        String doctype = null;
2934
2935        int x = xml.indexOf("<!DOCTYPE");
2936
2937        if (x != -1) {
2938            int y = xml.indexOf(">", x) + 1;
2939
2940            doctype = xml.substring(x, y);
2941
2942            xml = xml.substring(0, x) + "\n" + xml.substring(y);
2943        }
2944
2945        xml = StringUtil.replace(xml, '\r', "");
2946        xml = XMLFormatter.toString(xml);
2947        xml = StringUtil.replace(xml, "\"/>", "\" />");
2948
2949        if (Validator.isNotNull(doctype)) {
2950            x = xml.indexOf("?>") + 2;
2951
2952            xml = xml.substring(0, x) + "\n" + doctype + xml.substring(x);
2953        }
2954
2955        return xml;
2956    }
2957
2958    private Map _getContext() {
2959        Map context = new HashMap();
2960
2961        context.put("hbmFileName", _hbmFileName);
2962        context.put("modelHintsFileName", _modelHintsFileName);
2963        context.put("springFileName", _springFileName);
2964        context.put("springDataSourceFileName", _springDataSourceFileName);
2965        context.put("apiDir", _apiDir);
2966        context.put("implDir", _implDir);
2967        context.put("jsonFileName", _jsonFileName);
2968        context.put("sqlDir", _sqlDir);
2969        context.put("sqlFileName", _sqlFileName);
2970        context.put("baseModelImplPackage", _baseModelImplPackage);
2971        context.put("basePersistencePackage", _basePersistencePackage);
2972        context.put("beanLocatorUtilPackage", _beanLocatorUtilPackage);
2973        context.put("principalBeanPackage", _principalBeanPackage);
2974        context.put("propsUtilPackage", _propsUtilPackage);
2975        context.put("springHibernatePackage", _springHibernatePackage);
2976        context.put("springUtilPackage", _springUtilPackage);
2977        context.put("portletName", _portletName);
2978        context.put("portletShortName", _portletShortName);
2979        context.put("portletPackageName", _portletPackageName);
2980        context.put("outputPath", _outputPath);
2981        context.put("serviceOutputPath", _serviceOutputPath);
2982        context.put("packagePath", _packagePath);
2983        context.put("serviceBuilder", this);
2984
2985        context.put("stringUtil", StringUtil_IW.getInstance());
2986
2987        try {
2988            BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
2989
2990            TemplateHashModel staticModels = wrapper.getStaticModels();
2991
2992            context.put(
2993                "modelHintsUtil",
2994                staticModels.get("com.liferay.portal.model.ModelHintsUtil"));
2995            context.put(
2996                "validator",
2997                staticModels.get("com.liferay.portal.kernel.util.Validator"));
2998        }
2999        catch (TemplateModelException tme) {
3000        }
3001
3002        return context;
3003    }
3004
3005    private String _getCreateTableSQL(Entity entity) {
3006        List pkList = entity.getPKList();
3007        List regularColList = entity.getRegularColList();
3008
3009        if (regularColList.size() == 0) {
3010            return null;
3011        }
3012
3013        StringMaker sm = new StringMaker();
3014
3015        sm.append(_CREATE_TABLE + entity.getTable() + " (\n");
3016
3017        for (int i = 0; i < regularColList.size(); i++) {
3018            EntityColumn col = (EntityColumn)regularColList.get(i);
3019
3020            String colName = col.getName();
3021            String colType = col.getType();
3022            String colIdType = col.getIdType();
3023
3024            sm.append("\t" + col.getDBName());
3025            sm.append(" ");
3026
3027            if (colType.equalsIgnoreCase("boolean")) {
3028                sm.append("BOOLEAN");
3029            }
3030            else if (colType.equalsIgnoreCase("double") ||
3031                     colType.equalsIgnoreCase("float")) {
3032
3033                sm.append("DOUBLE");
3034            }
3035            else if (colType.equals("int") ||
3036                     colType.equals("Integer") ||
3037                     colType.equalsIgnoreCase("short")) {
3038
3039                sm.append("INTEGER");
3040            }
3041            else if (colType.equalsIgnoreCase("long")) {
3042                sm.append("LONG");
3043            }
3044            else if (colType.equals("String")) {
3045                Map hints = ModelHintsUtil.getHints(
3046                    _packagePath + ".model." + entity.getName(), colName);
3047
3048                int maxLength = 75;
3049
3050                if (hints != null) {
3051                    maxLength = GetterUtil.getInteger(
3052                        (String)hints.get("max-length"), maxLength);
3053                }
3054
3055                if (maxLength < 4000) {
3056                    sm.append("VARCHAR(" + maxLength + ")");
3057                }
3058                else if (maxLength == 4000) {
3059                    sm.append("STRING");
3060                }
3061                else if (maxLength > 4000) {
3062                    sm.append("TEXT");
3063                }
3064            }
3065            else if (colType.equals("Date")) {
3066                sm.append("DATE null");
3067            }
3068            else {
3069                sm.append("invalid");
3070            }
3071
3072            if (col.isPrimary()) {
3073                sm.append(" not null");
3074
3075                if (!entity.hasCompoundPK()) {
3076                    sm.append(" primary key");
3077                }
3078            }
3079            else if (colType.equals("String")) {
3080                sm.append(" null");
3081            }
3082
3083            if (Validator.isNotNull(colIdType) &&
3084                colIdType.equals("identity")) {
3085
3086                sm.append(" IDENTITY");
3087            }
3088
3089            if (((i + 1) != regularColList.size()) ||
3090                (entity.hasCompoundPK())) {
3091
3092                sm.append(",");
3093            }
3094
3095            sm.append("\n");
3096        }
3097
3098        if (entity.hasCompoundPK()) {
3099            sm.append("\tprimary key (");
3100
3101            for (int j = 0; j < pkList.size(); j++) {
3102                EntityColumn pk = (EntityColumn)pkList.get(j);
3103
3104                sm.append(pk.getDBName());
3105
3106                if ((j + 1) != pkList.size()) {
3107                    sm.append(", ");
3108                }
3109            }
3110
3111            sm.append(")\n");
3112        }
3113
3114        sm.append(");");
3115
3116        return sm.toString();
3117    }
3118
3119    private String _getDimensions(Type type) {
3120        String dimensions = "";
3121
3122        for (int i = 0; i < type.getDimensions(); i++) {
3123            dimensions += "[]";
3124        }
3125
3126        return dimensions;
3127    }
3128
3129    private JavaClass _getJavaClass(String fileName) throws IOException {
3130        int pos = fileName.indexOf(_implDir + "/") + _implDir.length();
3131
3132        String srcFile = fileName.substring(pos + 1, fileName.length());
3133        String className = StringUtil.replace(
3134            srcFile.substring(0, srcFile.length() - 5), "/", ".");
3135
3136        JavaDocBuilder builder = new JavaDocBuilder();
3137
3138        File file = new File(fileName);
3139
3140        if (!file.exists()) {
3141            return null;
3142        }
3143
3144        builder.addSource(file);
3145
3146        return builder.getClassByName(className);
3147    }
3148
3149    private String _getSessionTypeName(int sessionType) {
3150        if (sessionType == _LOCAL) {
3151            return "Local";
3152        }
3153        else {
3154            return "";
3155        }
3156    }
3157
3158    private String _getTplProperty(String key, String defaultValue) {
3159        return System.getProperty("service.tpl." + key, defaultValue);
3160    }
3161
3162    private boolean _hasHttpMethods(JavaClass javaClass) {
3163        JavaMethod[] methods = javaClass.getMethods();
3164
3165        for (int i = 0; i < methods.length; i++) {
3166            JavaMethod javaMethod = methods[i];
3167
3168            if (!javaMethod.isConstructor() && javaMethod.isPublic() &&
3169                isCustomMethod(javaMethod)) {
3170
3171                return true;
3172            }
3173        }
3174
3175        return false;
3176    }
3177
3178    private List _mergeReferenceList(List referenceList) {
3179        List list = new ArrayList(_ejbList.size() + referenceList.size());
3180
3181        list.addAll(_ejbList);
3182        list.addAll(referenceList);
3183
3184        return list;
3185    }
3186
3187    private String _processTemplate(String name) throws Exception {
3188        return _processTemplate(name, _getContext());
3189    }
3190
3191    private String _processTemplate(String name, Map context) throws Exception {
3192        return FreeMarkerUtil.process(name, context);
3193    }
3194
3195    private static final int _REMOTE = 0;
3196
3197    private static final int _LOCAL = 1;
3198
3199    private static final String _CREATE_TABLE = "create table ";
3200
3201    private static final String _TPL_ROOT = "com/liferay/portal/tools/servicebuilder/dependencies/";
3202
3203    private String _tplBaseModeImpl = _TPL_ROOT + "base_mode_impl.ftl";
3204    private String _tplBasePersistence = _TPL_ROOT + "base_persistence.ftl";
3205    private String _tplBeanLocatorUtil = _TPL_ROOT + "bean_locator_util.ftl";
3206    private String _tplDynamicDialect = _TPL_ROOT + "dynamic_dialect.ftl";
3207    private String _tplEjbPk = _TPL_ROOT + "ejb_pk.ftl";
3208    private String _tplException = _TPL_ROOT + "exception.ftl";
3209    private String _tplExtendedModel = _TPL_ROOT + "extended_model.ftl";
3210    private String _tplExtendedModelImpl =
3211        _TPL_ROOT + "extended_model_impl.ftl";
3212    private String _tplFinder = _TPL_ROOT + "finder.ftl";
3213    private String _tplFinderCache = _TPL_ROOT + "finder_cache.ftl";
3214    private String _tplFinderUtil = _TPL_ROOT + "finder_util.ftl";
3215    private String _tplHbmXml = _TPL_ROOT + "hbm_xml.ftl";
3216    private String _tplHibernateConfiguration =
3217        _TPL_ROOT + "hibernate_configuration.ftl";
3218    private String _tplHibernateUtil = _TPL_ROOT + "hibernate_util.ftl";
3219    private String _tplJsonJs = _TPL_ROOT + "json_js.ftl";
3220    private String _tplJsonJsMethod = _TPL_ROOT + "json_js_method.ftl";
3221    private String _tplModel = _TPL_ROOT + "model.ftl";
3222    private String _tplModelHintsXml = _TPL_ROOT + "model_hints_xml.ftl";
3223    private String _tplModelImpl = _TPL_ROOT + "model_impl.ftl";
3224    private String _tplModelSoap = _TPL_ROOT + "model_soap.ftl";
3225    private String _tplPersistence = _TPL_ROOT + "persistence.ftl";
3226    private String _tplPersistenceImpl = _TPL_ROOT + "persistence_impl.ftl";
3227    private String _tplPersistenceTest = _TPL_ROOT + "persistence_test.ftl";
3228    private String _tplPersistenceUtil = _TPL_ROOT + "persistence_util.ftl";
3229    private String _tplPrincipalBean = _TPL_ROOT + "principal_bean.ftl";
3230    private String _tplProps = _TPL_ROOT + "props.ftl";
3231    private String _tplPropsUtil = _TPL_ROOT + "props_util.ftl";
3232    private String _tplRemotingXml = _TPL_ROOT + "remoting_xml.ftl";
3233    private String _tplService = _TPL_ROOT + "service.ftl";
3234    private String _tplServiceBaseImpl = _TPL_ROOT + "service_base_impl.ftl";
3235    private String _tplServiceFactory = _TPL_ROOT + "service_factory.ftl";
3236    private String _tplServiceHttp = _TPL_ROOT + "service_http.ftl";
3237    private String _tplServiceImpl = _TPL_ROOT + "service_impl.ftl";
3238    private String _tplServiceJson = _TPL_ROOT + "service_json.ftl";
3239    private String _tplServiceJsonSerializer =
3240        _TPL_ROOT + "service_json_serializer.ftl";
3241    private String _tplServiceSoap = _TPL_ROOT + "service_soap.ftl";
3242    private String _tplServiceUtil = _TPL_ROOT + "service_util.ftl";
3243    private String _tplSpringDataSourceXml =
3244        _TPL_ROOT + "spring_data_source_xml.ftl";
3245    private String _tplSpringUtil = _TPL_ROOT + "spring_util.ftl";
3246    private String _tplSpringXml = _TPL_ROOT + "spring_xml.ftl";
3247    private Set _badTableNames;
3248    private Set _badCmpFields;
3249    private String _hbmFileName;
3250    private String _modelHintsFileName;
3251    private String _springFileName;
3252    private String _springDataSourceFileName;
3253    private String _apiDir;
3254    private String _implDir;
3255    private String _jsonFileName;
3256    private String _remotingFileName;
3257    private String _sqlDir;
3258    private String _sqlFileName;
3259    private boolean _autoNamespaceTables;
3260    private String _baseModelImplPackage;
3261    private String _basePersistencePackage;
3262    private String _beanLocatorUtilPackage;
3263    private String _principalBeanPackage;
3264    private String _propsUtilPackage;
3265    private String _springHibernatePackage;
3266    private String _springUtilPackage;
3267    private String _testDir;
3268    private String _portletName = StringPool.BLANK;
3269    private String _portletShortName = StringPool.BLANK;
3270    private String _portletPackageName = StringPool.BLANK;
3271    private String _outputPath;
3272    private String _serviceOutputPath;
3273    private String _testOutputPath;
3274    private String _packagePath;
3275    private List _ejbList;
3276
3277}