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