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