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