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