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