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