001 /** 002 * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. 003 * 004 * This library is free software; you can redistribute it and/or modify it under 005 * the terms of the GNU Lesser General Public License as published by the Free 006 * Software Foundation; either version 2.1 of the License, or (at your option) 007 * any later version. 008 * 009 * This library is distributed in the hope that it will be useful, but WITHOUT 010 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 011 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more 012 * details. 013 */ 014 015 package com.liferay.portal.tools.servicebuilder; 016 017 import com.liferay.portal.freemarker.FreeMarkerUtil; 018 import com.liferay.portal.kernel.dao.db.IndexMetadata; 019 import com.liferay.portal.kernel.dao.db.IndexMetadataFactoryUtil; 020 import com.liferay.portal.kernel.exception.PortalException; 021 import com.liferay.portal.kernel.exception.SystemException; 022 import com.liferay.portal.kernel.io.unsync.UnsyncBufferedReader; 023 import com.liferay.portal.kernel.io.unsync.UnsyncStringReader; 024 import com.liferay.portal.kernel.util.ArrayUtil; 025 import com.liferay.portal.kernel.util.ArrayUtil_IW; 026 import com.liferay.portal.kernel.util.CharPool; 027 import com.liferay.portal.kernel.util.ClearThreadLocalUtil; 028 import com.liferay.portal.kernel.util.FileUtil; 029 import com.liferay.portal.kernel.util.GetterUtil; 030 import com.liferay.portal.kernel.util.ListUtil; 031 import com.liferay.portal.kernel.util.PropertiesUtil; 032 import com.liferay.portal.kernel.util.StringBundler; 033 import com.liferay.portal.kernel.util.StringPool; 034 import com.liferay.portal.kernel.util.StringUtil; 035 import com.liferay.portal.kernel.util.StringUtil_IW; 036 import com.liferay.portal.kernel.util.TextFormatter; 037 import com.liferay.portal.kernel.util.Time; 038 import com.liferay.portal.kernel.util.Validator; 039 import com.liferay.portal.kernel.util.Validator_IW; 040 import com.liferay.portal.kernel.xml.Document; 041 import com.liferay.portal.kernel.xml.Element; 042 import com.liferay.portal.kernel.xml.SAXReaderUtil; 043 import com.liferay.portal.model.CacheField; 044 import com.liferay.portal.model.ModelHintsUtil; 045 import com.liferay.portal.security.permission.ResourceActionsUtil; 046 import com.liferay.portal.tools.ArgumentsUtil; 047 import com.liferay.portal.tools.SourceFormatter; 048 import com.liferay.portal.util.InitUtil; 049 import com.liferay.portal.util.PropsValues; 050 import com.liferay.util.xml.XMLFormatter; 051 052 import com.thoughtworks.qdox.JavaDocBuilder; 053 import com.thoughtworks.qdox.model.Annotation; 054 import com.thoughtworks.qdox.model.ClassLibrary; 055 import com.thoughtworks.qdox.model.DocletTag; 056 import com.thoughtworks.qdox.model.JavaClass; 057 import com.thoughtworks.qdox.model.JavaField; 058 import com.thoughtworks.qdox.model.JavaMethod; 059 import com.thoughtworks.qdox.model.JavaParameter; 060 import com.thoughtworks.qdox.model.Type; 061 062 import de.hunsicker.io.FileFormat; 063 import de.hunsicker.jalopy.Jalopy; 064 import de.hunsicker.jalopy.storage.Convention; 065 import de.hunsicker.jalopy.storage.ConventionKeys; 066 import de.hunsicker.jalopy.storage.Environment; 067 068 import freemarker.ext.beans.BeansWrapper; 069 070 import freemarker.log.Logger; 071 072 import freemarker.template.TemplateHashModel; 073 import freemarker.template.TemplateModelException; 074 075 import java.beans.Introspector; 076 077 import java.io.File; 078 import java.io.FileInputStream; 079 import java.io.FileNotFoundException; 080 import java.io.FileReader; 081 import java.io.IOException; 082 import java.io.InputStream; 083 084 import java.util.ArrayList; 085 import java.util.Arrays; 086 import java.util.Collections; 087 import java.util.HashMap; 088 import java.util.HashSet; 089 import java.util.Iterator; 090 import java.util.List; 091 import java.util.Locale; 092 import java.util.Map; 093 import java.util.Properties; 094 import java.util.Set; 095 import java.util.TreeMap; 096 import java.util.TreeSet; 097 import java.util.regex.Matcher; 098 import java.util.regex.Pattern; 099 100 import org.dom4j.DocumentException; 101 102 /** 103 * @author Brian Wing Shun Chan 104 * @author Charles May 105 * @author Alexander Chow 106 * @author Harry Mark 107 * @author Tariq Dweik 108 * @author Glenn Powell 109 * @author Raymond Augé 110 * @author Prashant Dighe 111 * @author Shuyang Zhou 112 * @author James Lefeu 113 */ 114 public class ServiceBuilder { 115 116 public static final String AUTHOR = "Brian Wing Shun Chan"; 117 118 public static String getContent(String fileName) throws Exception { 119 Document document = _getContentDocument(fileName); 120 121 Element rootElement = document.getRootElement(); 122 123 Element authorElement = null; 124 Element namespaceElement = null; 125 Map<String, Element> entityElements = new TreeMap<String, Element>(); 126 Map<String, Element> exceptionElements = new TreeMap<String, Element>(); 127 128 for (Element element : rootElement.elements()) { 129 String elementName = element.getName(); 130 131 if (elementName.equals("author")) { 132 element.detach(); 133 134 if (authorElement != null) { 135 throw new IllegalArgumentException( 136 "There can only be one author element"); 137 } 138 139 authorElement = element; 140 } 141 else if (elementName.equals("namespace")) { 142 element.detach(); 143 144 if (namespaceElement != null) { 145 throw new IllegalArgumentException( 146 "There can only be one namespace element"); 147 } 148 149 namespaceElement = element; 150 } 151 else if (elementName.equals("entity")) { 152 element.detach(); 153 154 String name = element.attributeValue("name"); 155 156 entityElements.put(name.toLowerCase(), element); 157 } 158 else if (elementName.equals("exceptions")) { 159 element.detach(); 160 161 for (Element exceptionElement : element.elements("exception")) { 162 exceptionElement.detach(); 163 164 exceptionElements.put( 165 exceptionElement.getText(), exceptionElement); 166 } 167 } 168 } 169 170 if (authorElement != null) { 171 rootElement.add(authorElement); 172 } 173 174 if (namespaceElement == null) { 175 throw new IllegalArgumentException( 176 "The namespace element is required"); 177 } 178 else { 179 rootElement.add(namespaceElement); 180 } 181 182 _addElements(rootElement, entityElements); 183 184 if (!exceptionElements.isEmpty()) { 185 Element exceptionsElement = rootElement.addElement("exceptions"); 186 187 _addElements(exceptionsElement, exceptionElements); 188 } 189 190 return document.asXML(); 191 } 192 193 public static void main(String[] args) { 194 Map<String, String> arguments = ArgumentsUtil.parseArguments(args); 195 196 InitUtil.initWithSpring(true); 197 198 String fileName = arguments.get("service.input.file"); 199 String hbmFileName = arguments.get("service.hbm.file"); 200 String ormFileName = arguments.get("service.orm.file"); 201 String modelHintsFileName = arguments.get("service.model.hints.file"); 202 String springFileName = arguments.get("service.spring.file"); 203 String springBaseFileName = arguments.get("service.spring.base.file"); 204 String springClusterFileName = arguments.get("service.spring.cluster.file"); 205 String springDynamicDataSourceFileName = arguments.get("service.spring.dynamic.data.source.file"); 206 String springHibernateFileName = arguments.get("service.spring.hibernate.file"); 207 String springInfrastructureFileName = arguments.get("service.spring.infrastructure.file"); 208 String springShardDataSourceFileName = arguments.get("service.spring.shard.data.source.file"); 209 String apiDir = arguments.get("service.api.dir"); 210 String implDir = arguments.get("service.impl.dir"); 211 String remotingFileName = arguments.get("service.remoting.file"); 212 String sqlDir = arguments.get("service.sql.dir"); 213 String sqlFileName = arguments.get("service.sql.file"); 214 String sqlIndexesFileName = arguments.get("service.sql.indexes.file"); 215 String sqlIndexesPropertiesFileName = arguments.get("service.sql.indexes.properties.file"); 216 String sqlSequencesFileName = arguments.get("service.sql.sequences.file"); 217 boolean autoNamespaceTables = GetterUtil.getBoolean(arguments.get("service.auto.namespace.tables")); 218 String beanLocatorUtil = arguments.get("service.bean.locator.util"); 219 String propsUtil = arguments.get("service.props.util"); 220 String pluginName = arguments.get("service.plugin.name"); 221 String targetEntityName = arguments.get("service.target.entity.name"); 222 String testDir = arguments.get("service.test.dir"); 223 long buildNumber = GetterUtil.getLong(arguments.get("service.build.number"), 1); 224 boolean buildNumberIncrement = GetterUtil.getBoolean(arguments.get("service.build.number.increment"), true); 225 226 try { 227 new ServiceBuilder( 228 fileName, hbmFileName, ormFileName, modelHintsFileName, 229 springFileName, springBaseFileName, springClusterFileName, 230 springDynamicDataSourceFileName, springHibernateFileName, 231 springInfrastructureFileName, springShardDataSourceFileName, 232 apiDir, implDir, remotingFileName, sqlDir, 233 sqlFileName, sqlIndexesFileName, sqlIndexesPropertiesFileName, 234 sqlSequencesFileName, autoNamespaceTables, beanLocatorUtil, 235 propsUtil, pluginName, targetEntityName, testDir, true, 236 buildNumber, buildNumberIncrement); 237 } 238 catch (RuntimeException re) { 239 System.out.println( 240 "Please set these required arguments. Sample values are:\n" + 241 "\n" + 242 "\tservice.input.file=${service.file}\n" + 243 "\tservice.hbm.file=${basedir}/src/META-INF/portal-hbm.xml\n" + 244 "\tservice.orm.file=${basedir}/src/META-INF/portal-orm.xml\n" + 245 "\tservice.model.hints.file=${basedir}/src/META-INF/portal-model-hints.xml\n" + 246 "\tservice.spring.file=${basedir}/src/META-INF/portal-spring.xml\n" + 247 "\tservice.api.dir=${basedir}/../portal-service/src\n" + 248 "\tservice.impl.dir=${basedir}/src\n" + 249 "\tservice.remoting.file=${basedir}/../portal-web/docroot/WEB-INF/remoting-servlet.xml\n" + 250 "\tservice.sql.dir=${basedir}/../sql\n" + 251 "\tservice.sql.file=portal-tables.sql\n" + 252 "\tservice.sql.indexes.file=indexes.sql\n" + 253 "\tservice.sql.indexes.properties.file=indexes.properties\n" + 254 "\tservice.sql.sequences.file=sequences.sql\n" + 255 "\tservice.bean.locator.util=com.liferay.portal.kernel.bean.PortalBeanLocatorUtil\n" + 256 "\tservice.props.util=com.liferay.portal.util.PropsUtil\n" + 257 "\tservice.target.entity.name=${service.target.entity.name}\n" + 258 "\tservice.test.dir=${basedir}/test/integration\n" + 259 "\tservice.build.number=1\n" + 260 "\tservice.build.number.increment=true\n" + 261 "\n" + 262 "You can also customize the generated code by overriding the default templates with these optional system properties:\n" + 263 "\n" + 264 "\t-Dservice.tpl.bad_alias_names=" + _TPL_ROOT + "bad_alias_names.txt\n"+ 265 "\t-Dservice.tpl.bad_column_names=" + _TPL_ROOT + "bad_column_names.txt\n"+ 266 "\t-Dservice.tpl.bad_json_types=" + _TPL_ROOT + "bad_json_types.txt\n"+ 267 "\t-Dservice.tpl.bad_table_names=" + _TPL_ROOT + "bad_table_names.txt\n"+ 268 "\t-Dservice.tpl.base_mode_impl=" + _TPL_ROOT + "base_mode_impl.ftl\n"+ 269 "\t-Dservice.tpl.blob_model=" + _TPL_ROOT + "blob_model.ftl\n"+ 270 "\t-Dservice.tpl.copyright.txt=copyright.txt\n"+ 271 "\t-Dservice.tpl.ejb_pk=" + _TPL_ROOT + "ejb_pk.ftl\n"+ 272 "\t-Dservice.tpl.exception=" + _TPL_ROOT + "exception.ftl\n"+ 273 "\t-Dservice.tpl.extended_model=" + _TPL_ROOT + "extended_model.ftl\n"+ 274 "\t-Dservice.tpl.extended_model_base_impl=" + _TPL_ROOT + "extended_model_base_impl.ftl\n"+ 275 "\t-Dservice.tpl.extended_model_impl=" + _TPL_ROOT + "extended_model_impl.ftl\n"+ 276 "\t-Dservice.tpl.finder=" + _TPL_ROOT + "finder.ftl\n"+ 277 "\t-Dservice.tpl.finder_util=" + _TPL_ROOT + "finder_util.ftl\n"+ 278 "\t-Dservice.tpl.hbm_xml=" + _TPL_ROOT + "hbm_xml.ftl\n"+ 279 "\t-Dservice.tpl.orm_xml=" + _TPL_ROOT + "orm_xml.ftl\n"+ 280 "\t-Dservice.tpl.json_js=" + _TPL_ROOT + "json_js.ftl\n"+ 281 "\t-Dservice.tpl.json_js_method=" + _TPL_ROOT + "json_js_method.ftl\n"+ 282 "\t-Dservice.tpl.model=" + _TPL_ROOT + "model.ftl\n"+ 283 "\t-Dservice.tpl.model_cache=" + _TPL_ROOT + "model_cache.ftl\n"+ 284 "\t-Dservice.tpl.model_hints_xml=" + _TPL_ROOT + "model_hints_xml.ftl\n"+ 285 "\t-Dservice.tpl.model_impl=" + _TPL_ROOT + "model_impl.ftl\n"+ 286 "\t-Dservice.tpl.model_soap=" + _TPL_ROOT + "model_soap.ftl\n"+ 287 "\t-Dservice.tpl.model_wrapper=" + _TPL_ROOT + "model_wrapper.ftl\n"+ 288 "\t-Dservice.tpl.persistence=" + _TPL_ROOT + "persistence.ftl\n"+ 289 "\t-Dservice.tpl.persistence_impl=" + _TPL_ROOT + "persistence_impl.ftl\n"+ 290 "\t-Dservice.tpl.persistence_util=" + _TPL_ROOT + "persistence_util.ftl\n"+ 291 "\t-Dservice.tpl.props=" + _TPL_ROOT + "props.ftl\n"+ 292 "\t-Dservice.tpl.remoting_xml=" + _TPL_ROOT + "remoting_xml.ftl\n"+ 293 "\t-Dservice.tpl.service=" + _TPL_ROOT + "service.ftl\n"+ 294 "\t-Dservice.tpl.service_base_impl=" + _TPL_ROOT + "service_base_impl.ftl\n"+ 295 "\t-Dservice.tpl.service_clp=" + _TPL_ROOT + "service_clp.ftl\n"+ 296 "\t-Dservice.tpl.service_clp_invoker=" + _TPL_ROOT + "service_clp_invoker.ftl\n"+ 297 "\t-Dservice.tpl.service_clp_message_listener=" + _TPL_ROOT + "service_clp_message_listener.ftl\n"+ 298 "\t-Dservice.tpl.service_clp_serializer=" + _TPL_ROOT + "service_clp_serializer.ftl\n"+ 299 "\t-Dservice.tpl.service_http=" + _TPL_ROOT + "service_http.ftl\n"+ 300 "\t-Dservice.tpl.service_impl=" + _TPL_ROOT + "service_impl.ftl\n"+ 301 "\t-Dservice.tpl.service_soap=" + _TPL_ROOT + "service_soap.ftl\n"+ 302 "\t-Dservice.tpl.service_util=" + _TPL_ROOT + "service_util.ftl\n"+ 303 "\t-Dservice.tpl.service_wrapper=" + _TPL_ROOT + "service_wrapper.ftl\n"+ 304 "\t-Dservice.tpl.spring_base_xml=" + _TPL_ROOT + "spring_base_xml.ftl\n"+ 305 "\t-Dservice.tpl.spring_dynamic_data_source_xml=" + _TPL_ROOT + "spring_dynamic_data_source_xml.ftl\n"+ 306 "\t-Dservice.tpl.spring_hibernate_xml=" + _TPL_ROOT + "spring_hibernate_xml.ftl\n"+ 307 "\t-Dservice.tpl.spring_infrastructure_xml=" + _TPL_ROOT + "spring_infrastructure_xml.ftl\n"+ 308 "\t-Dservice.tpl.spring_xml=" + _TPL_ROOT + "spring_xml.ftl\n"+ 309 "\t-Dservice.tpl.spring_xml_session=" + _TPL_ROOT + "spring_xml_session.ftl"); 310 311 throw re; 312 } 313 314 try { 315 ClearThreadLocalUtil.clearThreadLocal(); 316 } 317 catch (Exception e) { 318 e.printStackTrace(); 319 } 320 321 Introspector.flushCaches(); 322 } 323 324 public static String toHumanName(String name) { 325 if (name == null) { 326 return null; 327 } 328 329 String humanName = TextFormatter.format(name, TextFormatter.H); 330 331 if (humanName.equals("id")) { 332 humanName = "ID"; 333 } 334 else if (humanName.equals("ids")) { 335 humanName = "IDs"; 336 } 337 338 if (humanName.endsWith(" id")) { 339 humanName = humanName.substring(0, humanName.length() - 3) + " ID"; 340 } 341 else if (humanName.endsWith(" ids")) { 342 humanName = humanName.substring(0, humanName.length() - 4) + " IDs"; 343 } 344 345 if (humanName.contains(" id ")) { 346 humanName = StringUtil.replace(humanName, " id ", " ID "); 347 } 348 else if (humanName.contains(" ids ")) { 349 humanName = StringUtil.replace(humanName, " ids ", " IDs "); 350 } 351 352 return humanName; 353 } 354 355 public static void writeFile(File file, String content) 356 throws IOException { 357 358 writeFile(file, content, AUTHOR); 359 } 360 361 public static void writeFile(File file, String content, String author) 362 throws IOException { 363 364 writeFile(file, content, author, null); 365 } 366 367 public static void writeFile( 368 File file, String content, String author, 369 Map<String, Object> jalopySettings) 370 throws IOException { 371 372 String packagePath = _getPackagePath(file); 373 374 String className = file.getName(); 375 376 className = className.substring(0, className.length() - 5); 377 378 content = SourceFormatter.stripJavaImports( 379 content, packagePath, className); 380 381 File tempFile = new File("ServiceBuilder.temp"); 382 383 FileUtil.write(tempFile, content); 384 385 // Beautify 386 387 StringBuffer sb = new StringBuffer(); 388 389 Jalopy jalopy = new Jalopy(); 390 391 jalopy.setFileFormat(FileFormat.UNIX); 392 jalopy.setInput(tempFile); 393 jalopy.setOutput(sb); 394 395 File jalopyXmlFile = new File("tools/jalopy.xml"); 396 397 if (!jalopyXmlFile.exists()) { 398 jalopyXmlFile = new File("../tools/jalopy.xml"); 399 } 400 401 if (!jalopyXmlFile.exists()) { 402 jalopyXmlFile = new File("misc/jalopy.xml"); 403 } 404 405 if (!jalopyXmlFile.exists()) { 406 jalopyXmlFile = new File("../misc/jalopy.xml"); 407 } 408 409 if (!jalopyXmlFile.exists()) { 410 jalopyXmlFile = new File("../../misc/jalopy.xml"); 411 } 412 413 try { 414 Jalopy.setConvention(jalopyXmlFile); 415 } 416 catch (FileNotFoundException fnfe) { 417 } 418 419 if (jalopySettings == null) { 420 jalopySettings = new HashMap<String, Object>(); 421 } 422 423 Environment env = Environment.getInstance(); 424 425 // Author 426 427 author = GetterUtil.getString( 428 (String)jalopySettings.get("author"), author); 429 430 env.set("author", author); 431 432 // File name 433 434 env.set("fileName", file.getName()); 435 436 Convention convention = Convention.getInstance(); 437 438 String classMask = "/**\n * @author $author$\n*/"; 439 440 convention.put( 441 ConventionKeys.COMMENT_JAVADOC_TEMPLATE_CLASS, 442 env.interpolate(classMask)); 443 444 convention.put( 445 ConventionKeys.COMMENT_JAVADOC_TEMPLATE_INTERFACE, 446 env.interpolate(classMask)); 447 448 jalopy.format(); 449 450 String newContent = sb.toString(); 451 452 // Remove double blank lines after the package or last import 453 454 newContent = newContent.replaceFirst( 455 "(?m)^[ \t]*((?:package|import) .*;)\\s*^[ \t]*/\\*\\*", 456 "$1\n\n/**"); 457 458 /* 459 // Remove blank lines after try { 460 461 newContent = StringUtil.replace(newContent, "try {\n\n", "try {\n"); 462 463 // Remove blank lines after ) { 464 465 newContent = StringUtil.replace(newContent, ") {\n\n", ") {\n"); 466 467 // Remove blank lines empty braces { } 468 469 newContent = StringUtil.replace(newContent, "\n\n\t}", "\n\t}"); 470 471 // Add space to last } 472 473 newContent = newContent.substring(0, newContent.length() - 2) + "\n\n}"; 474 */ 475 476 writeFileRaw(file, newContent); 477 478 tempFile.deleteOnExit(); 479 } 480 481 public static void writeFileRaw(File file, String content) 482 throws IOException { 483 484 // Write file if and only if the file has changed 485 486 if (!file.exists() || !FileUtil.isSameContent(file, content)) { 487 FileUtil.write(file, content); 488 489 System.out.println("Writing " + file); 490 } 491 } 492 493 public ServiceBuilder( 494 String fileName, String hbmFileName, String ormFileName, 495 String modelHintsFileName, String springFileName, 496 String springBaseFileName, String springClusterFileName, 497 String springDynamicDataSourceFileName, String springHibernateFileName, 498 String springInfrastructureFileName, 499 String springShardDataSourceFileName, String apiDir, String implDir, 500 String remotingFileName, String sqlDir, String sqlFileName, 501 String sqlIndexesFileName, String sqlIndexesPropertiesFileName, 502 String sqlSequencesFileName, boolean autoNamespaceTables, 503 String beanLocatorUtil, String propsUtil, String pluginName, 504 String targetEntityName, String testDir) { 505 506 this( 507 fileName, hbmFileName, ormFileName, modelHintsFileName, 508 springFileName, springBaseFileName, springClusterFileName, 509 springDynamicDataSourceFileName, springHibernateFileName, 510 springInfrastructureFileName, springShardDataSourceFileName, apiDir, 511 implDir, remotingFileName, sqlDir, sqlFileName, sqlIndexesFileName, 512 sqlIndexesPropertiesFileName, sqlSequencesFileName, 513 autoNamespaceTables, beanLocatorUtil, propsUtil, pluginName, 514 targetEntityName, testDir, true, 1, true); 515 } 516 517 public ServiceBuilder( 518 String fileName, String hbmFileName, String ormFileName, 519 String modelHintsFileName, String springFileName, 520 String springBaseFileName, String springClusterFileName, 521 String springDynamicDataSourceFileName, String springHibernateFileName, 522 String springInfrastructureFileName, 523 String springShardDataSourceFileName, String apiDir, String implDir, 524 String remotingFileName, String sqlDir, String sqlFileName, 525 String sqlIndexesFileName, String sqlIndexesPropertiesFileName, 526 String sqlSequencesFileName, boolean autoNamespaceTables, 527 String beanLocatorUtil, String propsUtil, String pluginName, 528 String targetEntityName, String testDir, boolean build, 529 long buildNumber, boolean buildNumberIncrement) { 530 531 _tplBadAliasNames = _getTplProperty( 532 "bad_alias_names", _tplBadAliasNames); 533 _tplBadColumnNames = _getTplProperty( 534 "bad_column_names", _tplBadColumnNames); 535 _tplBadTableNames = _getTplProperty( 536 "bad_table_names", _tplBadTableNames); 537 _tplBlobModel = _getTplProperty("blob_model", _tplBlobModel); 538 _tplEjbPk = _getTplProperty("ejb_pk", _tplEjbPk); 539 _tplException = _getTplProperty("exception", _tplException); 540 _tplExtendedModel = _getTplProperty( 541 "extended_model", _tplExtendedModel); 542 _tplExtendedModelBaseImpl = _getTplProperty( 543 "extended_model_base_impl", _tplExtendedModelBaseImpl); 544 _tplExtendedModelImpl = _getTplProperty( 545 "extended_model_impl", _tplExtendedModelImpl); 546 _tplFinder = _getTplProperty("finder", _tplFinder); 547 _tplFinderUtil = _getTplProperty("finder_util", _tplFinderUtil); 548 _tplHbmXml = _getTplProperty("hbm_xml", _tplHbmXml); 549 _tplOrmXml = _getTplProperty("orm_xml", _tplOrmXml); 550 _tplJsonJs = _getTplProperty("json_js", _tplJsonJs); 551 _tplJsonJsMethod = _getTplProperty("json_js_method", _tplJsonJsMethod); 552 _tplModel = _getTplProperty("model", _tplModel); 553 _tplModelCache = _getTplProperty("model_cache", _tplModelCache); 554 _tplModelClp = _getTplProperty("model", _tplModelClp); 555 _tplModelHintsXml = _getTplProperty( 556 "model_hints_xml", _tplModelHintsXml); 557 _tplModelImpl = _getTplProperty("model_impl", _tplModelImpl); 558 _tplModelSoap = _getTplProperty("model_soap", _tplModelSoap); 559 _tplModelWrapper = _getTplProperty("model_wrapper", _tplModelWrapper); 560 _tplPersistence = _getTplProperty("persistence", _tplPersistence); 561 _tplPersistenceImpl = _getTplProperty( 562 "persistence_impl", _tplPersistenceImpl); 563 _tplPersistenceUtil = _getTplProperty( 564 "persistence_util", _tplPersistenceUtil); 565 _tplProps = _getTplProperty("props", _tplProps); 566 _tplRemotingXml = _getTplProperty("remoting_xml", _tplRemotingXml); 567 _tplService = _getTplProperty("service", _tplService); 568 _tplServiceBaseImpl = _getTplProperty( 569 "service_base_impl", _tplServiceBaseImpl); 570 _tplServiceClp = _getTplProperty("service_clp", _tplServiceClp); 571 _tplServiceClpInvoker = _getTplProperty( 572 "service_clp_invoker", _tplServiceClpInvoker); 573 _tplServiceClpMessageListener = _getTplProperty( 574 "service_clp_message_listener", _tplServiceClpMessageListener); 575 _tplServiceClpSerializer = _getTplProperty( 576 "service_clp_serializer", _tplServiceClpSerializer); 577 _tplServiceHttp = _getTplProperty("service_http", _tplServiceHttp); 578 _tplServiceImpl = _getTplProperty("service_impl", _tplServiceImpl); 579 _tplServiceSoap = _getTplProperty("service_soap", _tplServiceSoap); 580 _tplServiceUtil = _getTplProperty("service_util", _tplServiceUtil); 581 _tplServiceWrapper = _getTplProperty( 582 "service_wrapper", _tplServiceWrapper); 583 _tplSpringBaseXml = _getTplProperty( 584 "spring_base_xml", _tplSpringBaseXml); 585 _tplSpringClusterXml = _getTplProperty( 586 "spring_cluster_xml", _tplSpringClusterXml); 587 _tplSpringDynamicDataSourceXml = _getTplProperty( 588 "spring_dynamic_data_source_xml", _tplSpringDynamicDataSourceXml); 589 _tplSpringHibernateXml = _getTplProperty( 590 "spring_hibernate_xml", _tplSpringHibernateXml); 591 _tplSpringInfrastructureXml = _getTplProperty( 592 "spring_infrastructure_xml", _tplSpringInfrastructureXml); 593 _tplSpringShardDataSourceXml = _getTplProperty( 594 "spring_shard_data_source_xml", _tplSpringShardDataSourceXml); 595 _tplSpringXml = _getTplProperty("spring_xml", _tplSpringXml); 596 597 try { 598 _badTableNames = _readLines(_tplBadTableNames); 599 _badAliasNames = _readLines(_tplBadAliasNames); 600 _badColumnNames = _readLines(_tplBadColumnNames); 601 _hbmFileName = hbmFileName; 602 _ormFileName = ormFileName; 603 _modelHintsFileName = modelHintsFileName; 604 _springFileName = springFileName; 605 _springBaseFileName = springBaseFileName; 606 _springClusterFileName = springClusterFileName; 607 _springDynamicDataSourceFileName = springDynamicDataSourceFileName; 608 _springHibernateFileName = springHibernateFileName; 609 _springInfrastructureFileName = springInfrastructureFileName; 610 _springShardDataSourceFileName = springShardDataSourceFileName; 611 _apiDir = apiDir; 612 _implDir = implDir; 613 _remotingFileName = remotingFileName; 614 _sqlDir = sqlDir; 615 _sqlFileName = sqlFileName; 616 _sqlIndexesFileName = sqlIndexesFileName; 617 _sqlIndexesPropertiesFileName = sqlIndexesPropertiesFileName; 618 _sqlSequencesFileName = sqlSequencesFileName; 619 _autoNamespaceTables = autoNamespaceTables; 620 _beanLocatorUtil = beanLocatorUtil; 621 _beanLocatorUtilShortName = _beanLocatorUtil.substring( 622 _beanLocatorUtil.lastIndexOf(".") + 1); 623 _propsUtil = propsUtil; 624 _pluginName = GetterUtil.getString(pluginName); 625 _targetEntityName = targetEntityName; 626 _testDir = testDir; 627 _build = build; 628 _buildNumber = buildNumber; 629 _buildNumberIncrement = buildNumberIncrement; 630 631 String content = getContent(fileName); 632 633 Document document = SAXReaderUtil.read(content, true); 634 635 Element rootElement = document.getRootElement(); 636 637 String packagePath = rootElement.attributeValue("package-path"); 638 639 if (Validator.isNull(packagePath)) { 640 throw new IllegalArgumentException( 641 "The package-path attribute is required"); 642 } 643 644 _outputPath = 645 _implDir + "/" + StringUtil.replace(packagePath, ".", "/"); 646 647 _serviceOutputPath = 648 _apiDir + "/" + StringUtil.replace(packagePath, ".", "/"); 649 650 if (Validator.isNotNull(_testDir)) { 651 _testOutputPath = 652 _testDir + "/" + StringUtil.replace(packagePath, ".", "/"); 653 } 654 655 _packagePath = packagePath; 656 657 _autoNamespaceTables = GetterUtil.getBoolean( 658 rootElement.attributeValue("auto-namespace-tables"), 659 _autoNamespaceTables); 660 661 Element authorElement = rootElement.element("author"); 662 663 if (authorElement != null) { 664 _author = authorElement.getText(); 665 } 666 else { 667 _author = AUTHOR; 668 } 669 670 Element portletElement = rootElement.element("portlet"); 671 Element namespaceElement = rootElement.element("namespace"); 672 673 if (portletElement != null) { 674 _portletName = portletElement.attributeValue("name"); 675 676 _portletShortName = portletElement.attributeValue("short-name"); 677 678 _portletPackageName = TextFormatter.format( 679 _portletName, TextFormatter.B); 680 681 _outputPath += "/" + _portletPackageName; 682 683 _serviceOutputPath += "/" + _portletPackageName; 684 685 _testOutputPath += "/" + _portletPackageName; 686 687 _packagePath += "." + _portletPackageName; 688 } 689 else { 690 _portletShortName = namespaceElement.getText(); 691 } 692 693 _portletShortName = _portletShortName.trim(); 694 695 for (char c : _portletShortName.toCharArray()) { 696 if (!Validator.isChar(c) && (c != CharPool.UNDERLINE)) { 697 throw new RuntimeException( 698 "The namespace element must be a valid keyword"); 699 } 700 } 701 702 _ejbList = new ArrayList<Entity>(); 703 _entityMappings = new HashMap<String, EntityMapping>(); 704 705 List<Element> entityElements = rootElement.elements("entity"); 706 707 for (Element entityElement : entityElements) { 708 _parseEntity(entityElement); 709 } 710 711 List<String> exceptionList = new ArrayList<String>(); 712 713 Element exceptionsElement = rootElement.element("exceptions"); 714 715 if (exceptionsElement != null) { 716 List<Element> exceptionElements = exceptionsElement.elements( 717 "exception"); 718 719 for (Element exceptionElement : exceptionElements) { 720 exceptionList.add(exceptionElement.getText()); 721 } 722 } 723 724 if (build) { 725 for (int x = 0; x < _ejbList.size(); x++) { 726 Entity entity = _ejbList.get(x); 727 728 if (_isTargetEntity(entity)) { 729 System.out.println("Building " + entity.getName()); 730 731 if (entity.hasColumns()) { 732 if (entity.hasLocalService()) { 733 _createActionableDynamicQuery(entity); 734 } 735 736 _createHbm(entity); 737 _createHbmUtil(entity); 738 739 _createPersistenceImpl(entity); 740 _createPersistence(entity); 741 _createPersistenceUtil(entity); 742 743 if (Validator.isNotNull(_testDir)) { 744 _createPersistenceTest(entity); 745 } 746 747 _createModelImpl(entity); 748 _createExtendedModelBaseImpl(entity); 749 _createExtendedModelImpl(entity); 750 751 entity.setTransients(_getTransients(entity, false)); 752 entity.setParentTransients( 753 _getTransients(entity, true)); 754 755 _createModel(entity); 756 _createExtendedModel(entity); 757 758 _createModelCache(entity); 759 _createModelClp(entity); 760 _createModelWrapper(entity); 761 762 _createModelSoap(entity); 763 764 _createBlobModels(entity); 765 766 _createPool(entity); 767 768 if (entity.getPKList().size() > 1) { 769 _createEJBPK(entity); 770 } 771 } 772 773 _createFinder(entity); 774 _createFinderUtil(entity); 775 776 if (entity.hasLocalService()) { 777 _createServiceImpl(entity, _SESSION_TYPE_LOCAL); 778 _createServiceBaseImpl(entity, _SESSION_TYPE_LOCAL); 779 _createService(entity, _SESSION_TYPE_LOCAL); 780 _createServiceFactory(entity, _SESSION_TYPE_LOCAL); 781 _createServiceUtil(entity, _SESSION_TYPE_LOCAL); 782 783 _createServiceClp(entity, _SESSION_TYPE_LOCAL); 784 _createServiceClpInvoker( 785 entity, _SESSION_TYPE_LOCAL); 786 _createServiceWrapper(entity, _SESSION_TYPE_LOCAL); 787 } 788 789 if (entity.hasRemoteService()) { 790 _createServiceImpl(entity, _SESSION_TYPE_REMOTE); 791 _createServiceBaseImpl( 792 entity, _SESSION_TYPE_REMOTE); 793 _createService(entity, _SESSION_TYPE_REMOTE); 794 _createServiceFactory(entity, _SESSION_TYPE_REMOTE); 795 _createServiceUtil(entity, _SESSION_TYPE_REMOTE); 796 797 _createServiceClp(entity, _SESSION_TYPE_REMOTE); 798 _createServiceClpInvoker( 799 entity, _SESSION_TYPE_REMOTE); 800 _createServiceWrapper(entity, _SESSION_TYPE_REMOTE); 801 802 if (Validator.isNotNull(_remotingFileName)) { 803 _createServiceHttp(entity); 804 } 805 806 _createServiceJson(entity); 807 808 if (entity.hasColumns()) { 809 _createServiceJsonSerializer(entity); 810 } 811 812 _createServiceSoap(entity); 813 } 814 } 815 else { 816 if (entity.hasColumns()) { 817 entity.setTransients(_getTransients(entity, false)); 818 entity.setParentTransients( 819 _getTransients(entity, true)); 820 } 821 } 822 } 823 824 _createHbmXml(); 825 _createOrmXml(); 826 _createModelHintsXml(); 827 _createSpringXml(); 828 829 _createExceptions(exceptionList); 830 831 _createServiceClpMessageListener(); 832 _createServiceClpSerializer(exceptionList); 833 834 if (Validator.isNotNull(_remotingFileName)) { 835 _createRemotingXml(); 836 } 837 838 _createSQLIndexes(); 839 _createSQLTables(); 840 _createSQLSequences(); 841 842 _createProps(); 843 _createSpringBaseXml(); 844 _createSpringClusterXml(); 845 _createSpringDynamicDataSourceXml(); 846 _createSpringHibernateXml(); 847 _createSpringInfrastructureXml(); 848 _createSpringShardDataSourceXml(); 849 } 850 } 851 catch (FileNotFoundException fnfe) { 852 System.out.println(fnfe.getMessage()); 853 } 854 catch (Exception e) { 855 e.printStackTrace(); 856 } 857 } 858 859 public String getClassName(Type type) { 860 int dimensions = type.getDimensions(); 861 String name = type.getValue(); 862 863 if (dimensions > 0) { 864 StringBundler sb = new StringBundler(); 865 866 for (int i = 0; i < dimensions; i++) { 867 sb.append("["); 868 } 869 870 if (name.equals("boolean")) { 871 return sb.append("Z").toString(); 872 } 873 else if (name.equals("byte")) { 874 return sb.append("B").toString(); 875 } 876 else if (name.equals("char")) { 877 return sb.append("C").toString(); 878 } 879 else if (name.equals("double")) { 880 return sb.append("D").toString(); 881 } 882 else if (name.equals("float")) { 883 return sb.append("F").toString(); 884 } 885 else if (name.equals("int")) { 886 return sb.append("I").toString(); 887 } 888 else if (name.equals("long")) { 889 return sb.append("J").toString(); 890 } 891 else if (name.equals("short")) { 892 return sb.append("S").toString(); 893 } 894 else { 895 return sb.append("L").append(name).append(";").toString(); 896 } 897 } 898 899 return name; 900 } 901 902 public String getCreateMappingTableSQL(EntityMapping entityMapping) 903 throws IOException { 904 905 String createMappingTableSQL = _getCreateMappingTableSQL(entityMapping); 906 907 createMappingTableSQL = StringUtil.replace( 908 createMappingTableSQL, "\n", ""); 909 createMappingTableSQL = StringUtil.replace( 910 createMappingTableSQL, "\t", ""); 911 createMappingTableSQL = createMappingTableSQL.substring( 912 0, createMappingTableSQL.length() - 1); 913 914 return createMappingTableSQL; 915 } 916 917 public String getCreateTableSQL(Entity entity) { 918 String createTableSQL = _getCreateTableSQL(entity); 919 920 createTableSQL = StringUtil.replace(createTableSQL, "\n", ""); 921 createTableSQL = StringUtil.replace(createTableSQL, "\t", ""); 922 createTableSQL = createTableSQL.substring( 923 0, createTableSQL.length() - 1); 924 925 return createTableSQL; 926 } 927 928 public String getDimensions(int dims) { 929 String dimensions = ""; 930 931 for (int i = 0; i < dims; i++) { 932 dimensions += "[]"; 933 } 934 935 return dimensions; 936 } 937 938 public String getDimensions(String dims) { 939 return getDimensions(GetterUtil.getInteger(dims)); 940 } 941 942 public Entity getEntity(String name) throws IOException { 943 Entity entity = _entityPool.get(name); 944 945 if (entity != null) { 946 return entity; 947 } 948 949 int pos = name.lastIndexOf("."); 950 951 if (pos == -1) { 952 pos = _ejbList.indexOf(new Entity(name)); 953 954 if (pos == -1) { 955 throw new RuntimeException( 956 "Cannot find " + name + " in " + 957 ListUtil.toString(_ejbList, Entity.NAME_ACCESSOR)); 958 } 959 960 entity = _ejbList.get(pos); 961 962 _entityPool.put(name, entity); 963 964 return entity; 965 } 966 else { 967 String refPackage = name.substring(0, pos); 968 String refEntity = name.substring(pos + 1); 969 970 if (refPackage.equals(_packagePath)) { 971 pos = _ejbList.indexOf(new Entity(refEntity)); 972 973 if (pos == -1) { 974 throw new RuntimeException( 975 "Cannot find " + refEntity + " in " + 976 ListUtil.toString(_ejbList, Entity.NAME_ACCESSOR)); 977 } 978 979 entity = _ejbList.get(pos); 980 981 _entityPool.put(name, entity); 982 983 return entity; 984 } 985 986 String refPackageDir = StringUtil.replace(refPackage, ".", "/"); 987 988 String refFileName = 989 _implDir + "/" + refPackageDir + "/service.xml"; 990 991 File refFile = new File(refFileName); 992 993 boolean useTempFile = false; 994 995 if (!refFile.exists()) { 996 refFileName = Time.getTimestamp(); 997 refFile = new File(refFileName); 998 999 ClassLoader classLoader = getClass().getClassLoader(); 1000 1001 FileUtil.write( 1002 refFileName, 1003 StringUtil.read( 1004 classLoader, refPackageDir + "/service.xml")); 1005 1006 useTempFile = true; 1007 } 1008 1009 ServiceBuilder serviceBuilder = new ServiceBuilder( 1010 refFileName, _hbmFileName, _ormFileName, _modelHintsFileName, 1011 _springFileName, _springBaseFileName, _springClusterFileName, 1012 _springDynamicDataSourceFileName, _springHibernateFileName, 1013 _springInfrastructureFileName, _springShardDataSourceFileName, 1014 _apiDir, _implDir, _remotingFileName, _sqlDir, _sqlFileName, 1015 _sqlIndexesFileName, _sqlIndexesPropertiesFileName, 1016 _sqlSequencesFileName, _autoNamespaceTables, _beanLocatorUtil, 1017 _propsUtil, _pluginName, _targetEntityName, _testDir, false, 1018 _buildNumber, _buildNumberIncrement); 1019 1020 entity = serviceBuilder.getEntity(refEntity); 1021 1022 entity.setPortalReference(useTempFile); 1023 1024 _entityPool.put(name, entity); 1025 1026 if (useTempFile) { 1027 refFile.deleteOnExit(); 1028 } 1029 1030 return entity; 1031 } 1032 } 1033 1034 public Entity getEntityByGenericsName(String genericsName) { 1035 try { 1036 String name = genericsName; 1037 1038 if (name.startsWith("<")) { 1039 name = name.substring(1, name.length() - 1); 1040 } 1041 1042 name = StringUtil.replace(name, ".model.", "."); 1043 1044 return getEntity(name); 1045 } 1046 catch (Exception e) { 1047 return null; 1048 } 1049 } 1050 1051 public Entity getEntityByParameterTypeValue(String parameterTypeValue) { 1052 try { 1053 String name = parameterTypeValue; 1054 1055 name = StringUtil.replace(name, ".model.", "."); 1056 1057 return getEntity(name); 1058 } 1059 catch (Exception e) { 1060 return null; 1061 } 1062 } 1063 1064 public EntityMapping getEntityMapping(String mappingTable) { 1065 return _entityMappings.get(mappingTable); 1066 } 1067 1068 public String getGeneratorClass(String idType) { 1069 if (Validator.isNull(idType)) { 1070 idType = "assigned"; 1071 } 1072 1073 return idType; 1074 } 1075 1076 public String getJavadocComment(JavaClass javaClass) { 1077 return _formatComment( 1078 javaClass.getComment(), javaClass.getTags(), StringPool.BLANK); 1079 } 1080 1081 public String getJavadocComment(JavaMethod javaMethod) { 1082 return _formatComment( 1083 javaMethod.getComment(), javaMethod.getTags(), StringPool.TAB); 1084 } 1085 1086 public String getListActualTypeArguments(Type type) { 1087 if (type.getValue().equals("java.util.List")) { 1088 Type[] types = type.getActualTypeArguments(); 1089 1090 if (types != null) { 1091 return getTypeGenericsName(types[0]); 1092 } 1093 } 1094 1095 return getTypeGenericsName(type); 1096 } 1097 1098 public String getLiteralClass(Type type) { 1099 StringBundler sb = new StringBundler(type.getDimensions() + 2); 1100 1101 sb.append(type.getValue()); 1102 1103 for (int i = 0; i < type.getDimensions(); i++) { 1104 sb.append("[]"); 1105 } 1106 1107 sb.append(".class"); 1108 1109 return sb.toString(); 1110 } 1111 1112 public List<EntityColumn> getMappingEntities(String mappingTable) 1113 throws IOException { 1114 1115 List<EntityColumn> mappingEntitiesPKList = 1116 new ArrayList<EntityColumn>(); 1117 1118 EntityMapping entityMapping = _entityMappings.get(mappingTable); 1119 1120 for (int i = 0; i < 2; i++) { 1121 Entity entity = getEntity(entityMapping.getEntity(i)); 1122 1123 if (entity == null) { 1124 return null; 1125 } 1126 1127 mappingEntitiesPKList.addAll(entity.getPKList()); 1128 } 1129 1130 return mappingEntitiesPKList; 1131 } 1132 1133 public String getNoSuchEntityException(Entity entity) { 1134 String noSuchEntityException = entity.getName(); 1135 1136 if (Validator.isNull(entity.getPortletShortName()) || 1137 (noSuchEntityException.startsWith(entity.getPortletShortName()) && 1138 !noSuchEntityException.equals(entity.getPortletShortName()))) { 1139 1140 noSuchEntityException = noSuchEntityException.substring( 1141 entity.getPortletShortName().length()); 1142 } 1143 1144 noSuchEntityException = "NoSuch" + noSuchEntityException; 1145 1146 return noSuchEntityException; 1147 } 1148 1149 public String getParameterType(JavaParameter parameter) { 1150 Type returnType = parameter.getType(); 1151 1152 return getTypeGenericsName(returnType); 1153 } 1154 1155 public String getPrimitiveObj(String type) { 1156 if (type.equals("boolean")) { 1157 return "Boolean"; 1158 } 1159 else if (type.equals("double")) { 1160 return "Double"; 1161 } 1162 else if (type.equals("float")) { 1163 return "Float"; 1164 } 1165 else if (type.equals("int")) { 1166 return "Integer"; 1167 } 1168 else if (type.equals("long")) { 1169 return "Long"; 1170 } 1171 else if (type.equals("short")) { 1172 return "Short"; 1173 } 1174 else { 1175 return type; 1176 } 1177 } 1178 1179 public String getPrimitiveObjValue(String colType) { 1180 if (colType.equals("Boolean")) { 1181 return ".booleanValue()"; 1182 } 1183 else if (colType.equals("Double")) { 1184 return ".doubleValue()"; 1185 } 1186 else if (colType.equals("Float")) { 1187 return ".floatValue()"; 1188 } 1189 else if (colType.equals("Integer")) { 1190 return ".intValue()"; 1191 } 1192 else if (colType.equals("Long")) { 1193 return ".longValue()"; 1194 } 1195 else if (colType.equals("Short")) { 1196 return ".shortValue()"; 1197 } 1198 1199 return StringPool.BLANK; 1200 } 1201 1202 public String getReturnType(JavaMethod method) { 1203 Type returnType = method.getReturns(); 1204 1205 return getTypeGenericsName(returnType); 1206 } 1207 1208 public List<String> getServiceBaseExceptions( 1209 List<JavaMethod> methods, String methodName, List<String> args, 1210 List<String> exceptions) { 1211 1212 boolean foundMethod = false; 1213 1214 for (JavaMethod method : methods) { 1215 JavaParameter[] parameters = method.getParameters(); 1216 1217 if (method.getName().equals(methodName) && 1218 (parameters.length == args.size())) { 1219 1220 for (int i = 0; i < parameters.length; i++) { 1221 JavaParameter parameter = parameters[i]; 1222 1223 String arg = args.get(i); 1224 1225 if (getParameterType(parameter).equals(arg)) { 1226 exceptions = ListUtil.copy(exceptions); 1227 1228 Type[] methodExceptions = method.getExceptions(); 1229 1230 for (Type methodException : methodExceptions) { 1231 String exception = methodException.getValue(); 1232 1233 if (exception.equals( 1234 PortalException.class.getName())) { 1235 1236 exception = "PortalException"; 1237 } 1238 1239 if (exception.equals( 1240 SystemException.class.getName())) { 1241 1242 exception = "SystemException"; 1243 } 1244 1245 if (!exceptions.contains(exception)) { 1246 exceptions.add(exception); 1247 } 1248 } 1249 1250 Collections.sort(exceptions); 1251 1252 foundMethod = true; 1253 1254 break; 1255 } 1256 } 1257 } 1258 1259 if (foundMethod) { 1260 break; 1261 } 1262 } 1263 1264 if (!exceptions.isEmpty()) { 1265 return exceptions; 1266 } 1267 else { 1268 return Collections.emptyList(); 1269 } 1270 } 1271 1272 public String getSqlType(String type) { 1273 if (type.equals("boolean") || type.equals("Boolean")) { 1274 return "BOOLEAN"; 1275 } 1276 else if (type.equals("double") || type.equals("Double")) { 1277 return "DOUBLE"; 1278 } 1279 else if (type.equals("float") || type.equals("Float")) { 1280 return "FLOAT"; 1281 } 1282 else if (type.equals("int") || type.equals("Integer")) { 1283 return "INTEGER"; 1284 } 1285 else if (type.equals("long") || type.equals("Long")) { 1286 return "BIGINT"; 1287 } 1288 else if (type.equals("short") || type.equals("Short")) { 1289 return "INTEGER"; 1290 } 1291 else if (type.equals("Date")) { 1292 return "TIMESTAMP"; 1293 } 1294 else { 1295 return null; 1296 } 1297 } 1298 1299 public String getSqlType(String model, String field, String type) { 1300 if (type.equals("boolean") || type.equals("Boolean")) { 1301 return "BOOLEAN"; 1302 } 1303 else if (type.equals("double") || type.equals("Double")) { 1304 return "DOUBLE"; 1305 } 1306 else if (type.equals("float") || type.equals("Float")) { 1307 return "FLOAT"; 1308 } 1309 else if (type.equals("int") || type.equals("Integer")) { 1310 return "INTEGER"; 1311 } 1312 else if (type.equals("long") || type.equals("Long")) { 1313 return "BIGINT"; 1314 } 1315 else if (type.equals("short") || type.equals("Short")) { 1316 return "INTEGER"; 1317 } 1318 else if (type.equals("Blob")) { 1319 return "BLOB"; 1320 } 1321 else if (type.equals("Date")) { 1322 return "TIMESTAMP"; 1323 } 1324 else if (type.equals("String")) { 1325 Map<String, String> hints = ModelHintsUtil.getHints(model, field); 1326 1327 if (hints != null) { 1328 int maxLength = GetterUtil.getInteger(hints.get("max-length")); 1329 1330 if (maxLength == 2000000) { 1331 return "CLOB"; 1332 } 1333 } 1334 1335 return "VARCHAR"; 1336 } 1337 else { 1338 return null; 1339 } 1340 } 1341 1342 public String getTypeGenericsName(Type type) { 1343 StringBundler sb = new StringBundler(); 1344 1345 sb.append(type.getValue()); 1346 1347 Type[] actualTypeArguments = type.getActualTypeArguments(); 1348 1349 if (actualTypeArguments != null) { 1350 sb.append(StringPool.LESS_THAN); 1351 1352 for (int i = 0; i < actualTypeArguments.length; i++) { 1353 if (i > 0) { 1354 sb.append(", "); 1355 } 1356 1357 sb.append(getTypeGenericsName(actualTypeArguments[i])); 1358 } 1359 1360 sb.append(StringPool.GREATER_THAN); 1361 } 1362 1363 sb.append(getDimensions(type.getDimensions())); 1364 1365 return sb.toString(); 1366 } 1367 1368 public String getVariableName(JavaField field) { 1369 String fieldName = field.getName(); 1370 1371 if ((fieldName.length() > 0) && (fieldName.charAt(0) == '_')) { 1372 fieldName = fieldName.substring(1); 1373 } 1374 1375 return fieldName; 1376 } 1377 1378 public boolean hasEntityByGenericsName(String genericsName) { 1379 if (Validator.isNull(genericsName)) { 1380 return false; 1381 } 1382 1383 if (!genericsName.contains(".model.")) { 1384 return false; 1385 } 1386 1387 if (getEntityByGenericsName(genericsName) == null) { 1388 return false; 1389 } 1390 else { 1391 return true; 1392 } 1393 } 1394 1395 public boolean hasEntityByParameterTypeValue(String parameterTypeValue) { 1396 if (Validator.isNull(parameterTypeValue)) { 1397 return false; 1398 } 1399 1400 if (!parameterTypeValue.contains(".model.")) { 1401 return false; 1402 } 1403 1404 if (getEntityByParameterTypeValue(parameterTypeValue) == null) { 1405 return false; 1406 } 1407 else { 1408 return true; 1409 } 1410 } 1411 1412 public boolean isBasePersistenceMethod(JavaMethod method) { 1413 String methodName = method.getName(); 1414 1415 if (methodName.equals("clearCache") || 1416 methodName.equals("findWithDynamicQuery")) { 1417 1418 return true; 1419 } 1420 else if (methodName.equals("findByPrimaryKey") || 1421 methodName.equals("fetchByPrimaryKey") || 1422 methodName.equals("remove")) { 1423 1424 JavaParameter[] parameters = method.getParameters(); 1425 1426 if ((parameters.length == 1) && 1427 parameters[0].getName().equals("primaryKey")) { 1428 1429 return true; 1430 } 1431 1432 if (methodName.equals("remove")) { 1433 Type[] methodExceptions = method.getExceptions(); 1434 1435 for (Type methodException : methodExceptions) { 1436 String exception = methodException.getValue(); 1437 1438 if (exception.contains("NoSuch")) { 1439 return false; 1440 } 1441 } 1442 1443 return true; 1444 } 1445 } 1446 1447 return false; 1448 } 1449 1450 public boolean isCustomMethod(JavaMethod method) { 1451 String methodName = method.getName(); 1452 1453 if (methodName.equals("afterPropertiesSet") || 1454 methodName.equals("destroy") || 1455 methodName.equals("equals") || 1456 methodName.equals("getClass") || 1457 methodName.equals("hashCode") || 1458 methodName.equals("notify") || 1459 methodName.equals("notifyAll") || 1460 methodName.equals("toString") || 1461 methodName.equals("wait")) { 1462 1463 return false; 1464 } 1465 else if (methodName.equals("getPermissionChecker")) { 1466 return false; 1467 } 1468 else if (methodName.equals("getUser") && 1469 (method.getParameters().length == 0)) { 1470 1471 return false; 1472 } 1473 else if (methodName.equals("getUserId") && 1474 (method.getParameters().length == 0)) { 1475 1476 return false; 1477 } 1478 else if (methodName.endsWith("Finder") && 1479 (methodName.startsWith("get") || 1480 methodName.startsWith("set"))) { 1481 1482 return false; 1483 } 1484 else if (methodName.endsWith("Persistence") && 1485 (methodName.startsWith("get") || 1486 methodName.startsWith("set"))) { 1487 1488 return false; 1489 } 1490 else if (methodName.endsWith("Service") && 1491 (methodName.startsWith("get") || 1492 methodName.startsWith("set"))) { 1493 1494 return false; 1495 } 1496 else { 1497 return true; 1498 } 1499 } 1500 1501 public boolean isDuplicateMethod( 1502 JavaMethod method, Map<String, Object> tempMap) { 1503 1504 StringBundler sb = new StringBundler(); 1505 1506 sb.append("isDuplicateMethod "); 1507 sb.append(getTypeGenericsName(method.getReturns())); 1508 sb.append(StringPool.SPACE); 1509 sb.append(method.getName()); 1510 sb.append(StringPool.OPEN_PARENTHESIS); 1511 1512 JavaParameter[] parameters = method.getParameters(); 1513 1514 for (int i = 0; i < parameters.length; i++) { 1515 JavaParameter javaParameter = parameters[i]; 1516 1517 sb.append(getTypeGenericsName(javaParameter.getType())); 1518 1519 if ((i + 1) != parameters.length) { 1520 sb.append(StringPool.COMMA); 1521 } 1522 } 1523 1524 sb.append(StringPool.CLOSE_PARENTHESIS); 1525 1526 String key = sb.toString(); 1527 1528 if (tempMap.put(key, key) != null) { 1529 return true; 1530 } 1531 else { 1532 return false; 1533 } 1534 } 1535 1536 public boolean isHBMCamelCasePropertyAccessor(String propertyName) { 1537 if (propertyName.length() < 3) { 1538 return false; 1539 } 1540 1541 char[] chars = propertyName.toCharArray(); 1542 1543 char c0 = chars[0]; 1544 char c1 = chars[1]; 1545 char c2 = chars[2]; 1546 1547 if (Character.isLowerCase(c0) && Character.isUpperCase(c1) && 1548 Character.isLowerCase(c2)) { 1549 1550 return true; 1551 } 1552 1553 return false; 1554 } 1555 1556 public boolean isReadOnlyMethod( 1557 JavaMethod method, List<String> txRequiredList, String[] prefixes) { 1558 1559 String methodName = method.getName(); 1560 1561 if (isTxRequiredMethod(method, txRequiredList)) { 1562 return false; 1563 } 1564 1565 for (String prefix : prefixes) { 1566 if (methodName.startsWith(prefix)) { 1567 return true; 1568 } 1569 } 1570 1571 return false; 1572 } 1573 1574 public boolean isServiceReadOnlyMethod( 1575 JavaMethod method, List<String> txRequiredList) { 1576 1577 return isReadOnlyMethod( 1578 method, txRequiredList, 1579 PropsValues.SERVICE_BUILDER_SERVICE_READ_ONLY_PREFIXES); 1580 } 1581 1582 public boolean isSoapMethod(JavaMethod method) { 1583 Type returnType = method.getReturns(); 1584 1585 String returnTypeGenericsName = getTypeGenericsName(returnType); 1586 String returnValueName = returnType.getValue(); 1587 1588 if (returnTypeGenericsName.contains( 1589 "com.liferay.portal.kernel.search.") || 1590 returnTypeGenericsName.contains("com.liferay.portal.model.Theme") || 1591 returnTypeGenericsName.contains( 1592 "com.liferay.portlet.social.model.SocialActivityDefinition") || 1593 returnTypeGenericsName.equals("java.util.List<java.lang.Object>") || 1594 returnValueName.equals("com.liferay.portal.model.Lock") || 1595 returnValueName.equals( 1596 "com.liferay.portlet.messageboards.model.MBMessageDisplay") || 1597 returnValueName.startsWith("java.io") || 1598 returnValueName.equals("java.util.Map") || 1599 returnValueName.equals("java.util.Properties") || 1600 returnValueName.startsWith("javax")) { 1601 1602 return false; 1603 } 1604 1605 if (returnTypeGenericsName.contains( 1606 "com.liferay.portal.kernel.repository.model.FileEntry") || 1607 returnTypeGenericsName.contains( 1608 "com.liferay.portal.kernel.repository.model.Folder")) { 1609 } 1610 else if (returnTypeGenericsName.contains( 1611 "com.liferay.portal.kernel.repository.")) { 1612 1613 return false; 1614 } 1615 1616 JavaParameter[] parameters = method.getParameters(); 1617 1618 for (JavaParameter javaParameter : parameters) { 1619 Type type = javaParameter.getType(); 1620 1621 String parameterTypeName = type.getValue() + _getDimensions(type); 1622 1623 if (parameterTypeName.equals( 1624 "com.liferay.portal.kernel.util.UnicodeProperties") || 1625 parameterTypeName.equals( 1626 "com.liferay.portal.theme.ThemeDisplay") || 1627 parameterTypeName.equals( 1628 "com.liferay.portlet.PortletPreferencesImpl") || 1629 parameterTypeName.equals( 1630 "com.liferay.portlet.dynamicdatamapping.storage.Fields") || 1631 parameterTypeName.startsWith("java.io") || 1632 //parameterTypeName.startsWith("java.util.List") || 1633 //parameterTypeName.startsWith("java.util.Locale") || 1634 (parameterTypeName.startsWith("java.util.Map") && 1635 !_isStringLocaleMap(javaParameter)) || 1636 parameterTypeName.startsWith("java.util.Properties") || 1637 parameterTypeName.startsWith("javax")) { 1638 1639 return false; 1640 } 1641 } 1642 1643 return true; 1644 } 1645 1646 public boolean isTxRequiredMethod( 1647 JavaMethod method, List<String> txRequiredList) { 1648 1649 if (txRequiredList == null) { 1650 return false; 1651 } 1652 1653 if (txRequiredList.contains(method.getName())) { 1654 return true; 1655 } 1656 1657 return false; 1658 } 1659 1660 private static void _addElements( 1661 Element element, Map<String, Element> elements) { 1662 1663 for (Map.Entry<String, Element> entry : elements.entrySet()) { 1664 Element childElement = entry.getValue(); 1665 1666 element.add(childElement); 1667 } 1668 } 1669 1670 private static Document _getContentDocument(String fileName) 1671 throws Exception { 1672 1673 String content = FileUtil.read(new File(fileName)); 1674 1675 Document document = SAXReaderUtil.read(content); 1676 1677 Element rootElement = document.getRootElement(); 1678 1679 for (Element element : rootElement.elements()) { 1680 String elementName = element.getName(); 1681 1682 if (!elementName.equals("service-builder-import")) { 1683 continue; 1684 } 1685 1686 element.detach(); 1687 1688 String dirName = fileName.substring( 1689 0, fileName.lastIndexOf(StringPool.SLASH) + 1); 1690 String serviceBuilderImportFileName = element.attributeValue( 1691 "file"); 1692 1693 Document serviceBuilderImportDocument = _getContentDocument( 1694 dirName + serviceBuilderImportFileName); 1695 1696 Element serviceBuilderImportRootElement = 1697 serviceBuilderImportDocument.getRootElement(); 1698 1699 for (Element serviceBuilderImportElement : 1700 serviceBuilderImportRootElement.elements()) { 1701 1702 serviceBuilderImportElement.detach(); 1703 1704 rootElement.add(serviceBuilderImportElement); 1705 } 1706 } 1707 1708 return document; 1709 } 1710 1711 private static String _getPackagePath(File file) { 1712 String fileName = StringUtil.replace(file.toString(), "\\", "/"); 1713 1714 int x = fileName.indexOf("src/"); 1715 1716 if (x == -1) { 1717 x = fileName.indexOf("test/"); 1718 } 1719 1720 int y = fileName.lastIndexOf("/"); 1721 1722 fileName = fileName.substring(x + 4, y); 1723 1724 return StringUtil.replace(fileName, "/", "."); 1725 } 1726 1727 private void _createActionableDynamicQuery(Entity entity) throws Exception { 1728 Map<String, Object> context = _getContext(); 1729 1730 context.put("entity", entity); 1731 1732 // Content 1733 1734 String content = _processTemplate(_tplActionableDynamicQuery, context); 1735 1736 // Write file 1737 1738 File ejbFile = new File( 1739 _serviceOutputPath + "/service/persistence/" + 1740 entity.getName() + "ActionableDynamicQuery.java"); 1741 1742 writeFile(ejbFile, content, _author); 1743 } 1744 1745 private void _createBlobModels(Entity entity) throws Exception { 1746 List<EntityColumn> blobList = new ArrayList<EntityColumn>( 1747 entity.getBlobList()); 1748 1749 Iterator<EntityColumn> itr = blobList.iterator(); 1750 1751 while (itr.hasNext()) { 1752 EntityColumn col = itr.next(); 1753 1754 if (!col.isLazy()) { 1755 itr.remove(); 1756 } 1757 } 1758 1759 if (blobList.isEmpty()) { 1760 return; 1761 } 1762 1763 Map<String, Object> context = _getContext(); 1764 1765 context.put("entity", entity); 1766 1767 for (EntityColumn col : blobList) { 1768 context.put("column", col); 1769 1770 // Content 1771 1772 String content = _processTemplate(_tplBlobModel, context); 1773 1774 // Write file 1775 1776 File blobModelFile = new File( 1777 _serviceOutputPath + "/model/" + entity.getName() + 1778 col.getMethodName() + "BlobModel.java"); 1779 1780 writeFile(blobModelFile, content, _author); 1781 } 1782 } 1783 1784 private void _createEJBPK(Entity entity) throws Exception { 1785 Map<String, Object> context = _getContext(); 1786 1787 context.put("entity", entity); 1788 1789 // Content 1790 1791 String content = _processTemplate(_tplEjbPk, context); 1792 1793 // Write file 1794 1795 File ejbFile = new File( 1796 _serviceOutputPath + "/service/persistence/" + 1797 entity.getPKClassName() + ".java"); 1798 1799 writeFile(ejbFile, content, _author); 1800 } 1801 1802 private void _createExceptions(List<String> exceptions) throws Exception { 1803 for (int i = 0; i < _ejbList.size(); i++) { 1804 Entity entity = _ejbList.get(i); 1805 1806 if (!_isTargetEntity(entity)) { 1807 continue; 1808 } 1809 1810 if (entity.hasColumns()) { 1811 exceptions.add(getNoSuchEntityException(entity)); 1812 } 1813 } 1814 1815 for (String exception : exceptions) { 1816 File exceptionFile = new File( 1817 _serviceOutputPath + "/" + exception + "Exception.java"); 1818 1819 if (!exceptionFile.exists()) { 1820 Map<String, Object> context = _getContext(); 1821 1822 context.put("exception", exception); 1823 1824 String content = _processTemplate(_tplException, context); 1825 1826 if (exception.startsWith("NoSuch")) { 1827 content = StringUtil.replace( 1828 content, "PortalException", "NoSuchModelException"); 1829 content = StringUtil.replace( 1830 content, "kernel.exception.NoSuchModelException", 1831 "NoSuchModelException"); 1832 } 1833 1834 content = StringUtil.replace(content, "\r\n", "\n"); 1835 1836 FileUtil.write(exceptionFile, content); 1837 } 1838 1839 if (exception.startsWith("NoSuch")) { 1840 String content = FileUtil.read(exceptionFile); 1841 1842 if (!content.contains("NoSuchModelException")) { 1843 content = StringUtil.replace( 1844 content, "PortalException", "NoSuchModelException"); 1845 content = StringUtil.replace( 1846 content, "kernel.exception.NoSuchModelException", 1847 "NoSuchModelException"); 1848 1849 FileUtil.write(exceptionFile, content); 1850 } 1851 } 1852 1853 if (!_serviceOutputPath.equals(_outputPath)) { 1854 exceptionFile = new File( 1855 _outputPath + "/" + exception + "Exception.java"); 1856 1857 if (exceptionFile.exists()) { 1858 System.out.println("Relocating " + exceptionFile); 1859 1860 exceptionFile.delete(); 1861 } 1862 } 1863 } 1864 } 1865 1866 private void _createExtendedModel(Entity entity) throws Exception { 1867 JavaClass javaClass = _getJavaClass( 1868 _outputPath + "/model/impl/" + entity.getName() + "Impl.java"); 1869 1870 Map<String, Object> context = _getContext(); 1871 1872 context.put("entity", entity); 1873 context.put("methods", _getMethods(javaClass)); 1874 1875 // Content 1876 1877 String content = _processTemplate(_tplExtendedModel, context); 1878 1879 // Write file 1880 1881 File modelFile = new File( 1882 _serviceOutputPath + "/model/" + entity.getName() + ".java"); 1883 1884 writeFile(modelFile, content, _author); 1885 1886 if (!_serviceOutputPath.equals(_outputPath)) { 1887 modelFile = new File( 1888 _outputPath + "/model/" + entity.getName() + ".java"); 1889 1890 if (modelFile.exists()) { 1891 System.out.println("Relocating " + modelFile); 1892 1893 modelFile.delete(); 1894 } 1895 } 1896 } 1897 1898 private void _createExtendedModelBaseImpl(Entity entity) throws Exception { 1899 Map<String, Object> context = _getContext(); 1900 1901 context.put("entity", entity); 1902 1903 // Content 1904 1905 String content = _processTemplate(_tplExtendedModelBaseImpl, context); 1906 1907 // Write file 1908 1909 File modelFile = new File( 1910 _outputPath + "/model/impl/" + entity.getName() + "BaseImpl.java"); 1911 1912 writeFile(modelFile, content, _author); 1913 } 1914 1915 private void _createExtendedModelImpl(Entity entity) throws Exception { 1916 Map<String, Object> context = _getContext(); 1917 1918 context.put("entity", entity); 1919 1920 // Content 1921 1922 String content = _processTemplate(_tplExtendedModelImpl, context); 1923 1924 // Write file 1925 1926 File modelFile = new File( 1927 _outputPath + "/model/impl/" + entity.getName() + "Impl.java"); 1928 1929 if (modelFile.exists()) { 1930 content = FileUtil.read(modelFile); 1931 1932 content = content.replaceAll( 1933 "extends\\s+" + entity.getName() + 1934 "ModelImpl\\s+implements\\s+" + entity.getName(), 1935 "extends " + entity.getName() + "BaseImpl"); 1936 1937 writeFileRaw(modelFile, content); 1938 } 1939 else { 1940 writeFile(modelFile, content, _author); 1941 } 1942 } 1943 1944 private void _createFinder(Entity entity) throws Exception { 1945 if (!entity.hasFinderClass()) { 1946 return; 1947 } 1948 1949 JavaClass javaClass = _getJavaClass( 1950 _outputPath + "/service/persistence/" + entity.getName() + 1951 "FinderImpl.java"); 1952 1953 Map<String, Object> context = _getContext(); 1954 1955 context.put("entity", entity); 1956 context.put("methods", _getMethods(javaClass)); 1957 1958 // Content 1959 1960 String content = _processTemplate(_tplFinder, context); 1961 1962 // Write file 1963 1964 File ejbFile = new File( 1965 _serviceOutputPath + "/service/persistence/" + entity.getName() + 1966 "Finder.java"); 1967 1968 writeFile(ejbFile, content, _author); 1969 1970 if (!_serviceOutputPath.equals(_outputPath)) { 1971 ejbFile = new File( 1972 _outputPath + "/service/persistence/" + entity.getName() + 1973 "Finder.java"); 1974 1975 if (ejbFile.exists()) { 1976 System.out.println("Relocating " + ejbFile); 1977 1978 ejbFile.delete(); 1979 } 1980 } 1981 } 1982 1983 private void _createFinderUtil(Entity entity) throws Exception { 1984 if (!entity.hasFinderClass()) { 1985 return; 1986 } 1987 1988 JavaClass javaClass = _getJavaClass( 1989 _outputPath + "/service/persistence/" + entity.getName() + 1990 "FinderImpl.java"); 1991 1992 Map<String, Object> context = _getContext(); 1993 1994 context.put("entity", entity); 1995 context.put("methods", _getMethods(javaClass)); 1996 1997 // Content 1998 1999 String content = _processTemplate(_tplFinderUtil, context); 2000 2001 // Write file 2002 2003 File ejbFile = new File( 2004 _serviceOutputPath + "/service/persistence/" + entity.getName() + 2005 "FinderUtil.java"); 2006 2007 writeFile(ejbFile, content, _author); 2008 2009 if (!_serviceOutputPath.equals(_outputPath)) { 2010 ejbFile = new File( 2011 _outputPath + "/service/persistence/" + entity.getName() + 2012 "FinderUtil.java"); 2013 2014 if (ejbFile.exists()) { 2015 System.out.println("Relocating " + ejbFile); 2016 2017 ejbFile.delete(); 2018 } 2019 } 2020 } 2021 2022 private void _createHbm(Entity entity) { 2023 File ejbFile = new File( 2024 _outputPath + "/service/persistence/" + entity.getName() + 2025 "HBM.java"); 2026 2027 if (ejbFile.exists()) { 2028 System.out.println("Removing deprecated " + ejbFile); 2029 2030 ejbFile.delete(); 2031 } 2032 } 2033 2034 private void _createHbmUtil(Entity entity) { 2035 File ejbFile = new File( 2036 _outputPath + "/service/persistence/" + entity.getName() + 2037 "HBMUtil.java"); 2038 2039 if (ejbFile.exists()) { 2040 System.out.println("Removing deprecated " + ejbFile); 2041 2042 ejbFile.delete(); 2043 } 2044 } 2045 2046 private void _createHbmXml() throws Exception { 2047 Map<String, Object> context = _getContext(); 2048 2049 context.put("entities", _ejbList); 2050 2051 // Content 2052 2053 String content = _processTemplate(_tplHbmXml, context); 2054 2055 int lastImportStart = content.lastIndexOf("<import class="); 2056 int lastImportEnd = content.indexOf("/>", lastImportStart) + 3; 2057 2058 String imports = content.substring(0, lastImportEnd); 2059 2060 content = content.substring(lastImportEnd + 1); 2061 2062 File xmlFile = new File(_hbmFileName); 2063 2064 if (!xmlFile.exists()) { 2065 String xml = 2066 "<?xml version=\"1.0\"?>\n" + 2067 "<!DOCTYPE hibernate-mapping PUBLIC \"-//Hibernate/Hibernate Mapping DTD 3.0//EN\" \"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd\">\n" + 2068 "\n" + 2069 "<hibernate-mapping default-lazy=\"false\" auto-import=\"false\">\n" + 2070 "</hibernate-mapping>"; 2071 2072 FileUtil.write(xmlFile, xml); 2073 } 2074 2075 String oldContent = FileUtil.read(xmlFile); 2076 String newContent = _fixHbmXml(oldContent); 2077 2078 int firstImport = newContent.indexOf( 2079 "<import class=\"" + _packagePath + ".model."); 2080 int lastImport = newContent.lastIndexOf( 2081 "<import class=\"" + _packagePath + ".model."); 2082 2083 if (firstImport == -1) { 2084 int x = newContent.indexOf("<class"); 2085 2086 if (x != -1) { 2087 newContent = 2088 newContent.substring(0, x) + imports + 2089 newContent.substring(x); 2090 } 2091 else { 2092 content = imports + content; 2093 } 2094 } 2095 else { 2096 firstImport = newContent.indexOf("<import", firstImport) - 1; 2097 lastImport = newContent.indexOf("/>", lastImport) + 3; 2098 2099 newContent = 2100 newContent.substring(0, firstImport) + imports + 2101 newContent.substring(lastImport); 2102 } 2103 2104 int firstClass = newContent.indexOf( 2105 "<class name=\"" + _packagePath + ".model.impl."); 2106 int lastClass = newContent.lastIndexOf( 2107 "<class name=\"" + _packagePath + ".model.impl."); 2108 2109 if (firstClass == -1) { 2110 int x = newContent.indexOf("</hibernate-mapping>"); 2111 2112 if (x != -1) { 2113 newContent = 2114 newContent.substring(0, x) + content + 2115 newContent.substring(x); 2116 } 2117 } 2118 else { 2119 firstClass = newContent.lastIndexOf("<class", firstClass) - 1; 2120 lastClass = newContent.indexOf("</class>", lastClass) + 9; 2121 2122 newContent = 2123 newContent.substring(0, firstClass) + content + 2124 newContent.substring(lastClass); 2125 } 2126 2127 newContent = _formatXml(newContent); 2128 2129 if (!oldContent.equals(newContent)) { 2130 FileUtil.write(xmlFile, newContent); 2131 } 2132 } 2133 2134 private void _createModel(Entity entity) throws Exception { 2135 Map<String, Object> context = _getContext(); 2136 2137 context.put("entity", entity); 2138 2139 // Content 2140 2141 String content = _processTemplate(_tplModel, context); 2142 2143 // Write file 2144 2145 File modelFile = new File( 2146 _serviceOutputPath + "/model/" + entity.getName() + "Model.java"); 2147 2148 writeFile(modelFile, content, _author); 2149 2150 if (!_serviceOutputPath.equals(_outputPath)) { 2151 modelFile = new File( 2152 _outputPath + "/model/" + entity.getName() + "Model.java"); 2153 2154 if (modelFile.exists()) { 2155 System.out.println("Relocating " + modelFile); 2156 2157 modelFile.delete(); 2158 } 2159 } 2160 } 2161 2162 private void _createModelCache(Entity entity) throws Exception { 2163 JavaClass javaClass = _getJavaClass( 2164 _outputPath + "/model/impl/" + entity.getName() + "Impl.java"); 2165 2166 Map<String, Object> context = _getContext(); 2167 2168 context.put("entity", entity); 2169 context.put("cacheFields", _getCacheFields(javaClass)); 2170 2171 // Content 2172 2173 String content = _processTemplate(_tplModelCache, context); 2174 2175 // Write file 2176 2177 File modelFile = new File( 2178 _outputPath + "/model/impl/" + entity.getName() + 2179 "CacheModel.java"); 2180 2181 writeFile(modelFile, content, _author); 2182 } 2183 2184 private void _createModelClp(Entity entity) throws Exception { 2185 if (Validator.isNull(_pluginName)) { 2186 return; 2187 } 2188 2189 JavaClass javaClass = _getJavaClass( 2190 _outputPath + "/model/impl/" + entity.getName() + "Impl.java"); 2191 2192 Map<String, JavaMethod> methods = new HashMap<String, JavaMethod>(); 2193 2194 for (JavaMethod method : javaClass.getMethods()) { 2195 methods.put(method.getDeclarationSignature(false), method); 2196 } 2197 2198 Type superClass = javaClass.getSuperClass(); 2199 2200 String superClassValue = superClass.getValue(); 2201 2202 while (!superClassValue.endsWith("BaseModelImpl")) { 2203 int pos = superClassValue.lastIndexOf(StringPool.PERIOD); 2204 2205 if (pos > 0) { 2206 superClassValue = superClassValue.substring(pos + 1); 2207 } 2208 2209 javaClass = _getJavaClass( 2210 _outputPath + "/model/impl/" + superClassValue + ".java"); 2211 2212 for (JavaMethod method : _getMethods(javaClass)) { 2213 methods.remove(method.getDeclarationSignature(false)); 2214 } 2215 2216 superClass = javaClass.getSuperClass(); 2217 superClassValue = superClass.getValue(); 2218 } 2219 2220 Map<String, Object> context = _getContext(); 2221 2222 context.put("entity", entity); 2223 context.put("methods", methods.values()); 2224 2225 // Content 2226 2227 String content = _processTemplate(_tplModelClp, context); 2228 2229 // Write file 2230 2231 File modelFile = new File( 2232 _serviceOutputPath + "/model/" + entity.getName() + "Clp.java"); 2233 2234 writeFile(modelFile, content, _author); 2235 } 2236 2237 private void _createModelHintsXml() throws Exception { 2238 Map<String, Object> context = _getContext(); 2239 2240 context.put("entities", _ejbList); 2241 2242 // Content 2243 2244 String content = _processTemplate(_tplModelHintsXml, context); 2245 2246 File xmlFile = new File(_modelHintsFileName); 2247 2248 if (!xmlFile.exists()) { 2249 String xml = 2250 "<?xml version=\"1.0\"?>\n" + 2251 "\n" + 2252 "<model-hints>\n" + 2253 "</model-hints>"; 2254 2255 FileUtil.write(xmlFile, xml); 2256 } 2257 2258 String oldContent = FileUtil.read(xmlFile); 2259 String newContent = oldContent; 2260 2261 int firstModel = newContent.indexOf( 2262 "<model name=\"" + _packagePath + ".model."); 2263 int lastModel = newContent.lastIndexOf( 2264 "<model name=\"" + _packagePath + ".model."); 2265 2266 if (firstModel == -1) { 2267 int x = newContent.indexOf("</model-hints>"); 2268 2269 newContent = 2270 newContent.substring(0, x) + content + 2271 newContent.substring(x); 2272 } 2273 else { 2274 firstModel = newContent.lastIndexOf("<model", firstModel) - 1; 2275 lastModel = newContent.indexOf("</model>", lastModel) + 9; 2276 2277 newContent = 2278 newContent.substring(0, firstModel) + content + 2279 newContent.substring(lastModel); 2280 } 2281 2282 newContent = _formatXml(newContent); 2283 2284 if (!oldContent.equals(newContent)) { 2285 FileUtil.write(xmlFile, newContent); 2286 } 2287 } 2288 2289 private void _createModelImpl(Entity entity) throws Exception { 2290 JavaClass javaClass = _getJavaClass( 2291 _outputPath + "/model/impl/" + entity.getName() + "Impl.java"); 2292 2293 Map<String, Object> context = _getContext(); 2294 2295 context.put("entity", entity); 2296 context.put("cacheFields", _getCacheFields(javaClass)); 2297 2298 // Content 2299 2300 String content = _processTemplate(_tplModelImpl, context); 2301 2302 // Write file 2303 2304 File modelFile = new File( 2305 _outputPath + "/model/impl/" + entity.getName() + "ModelImpl.java"); 2306 2307 writeFile(modelFile, content, _author); 2308 } 2309 2310 private void _createModelSoap(Entity entity) throws Exception { 2311 File modelFile = null; 2312 2313 if (!_serviceOutputPath.equals(_outputPath)) { 2314 modelFile = new File( 2315 _outputPath + "/model/" + entity.getName() + "Soap.java"); 2316 2317 if (modelFile.exists()) { 2318 System.out.println("Relocating " + modelFile); 2319 2320 modelFile.delete(); 2321 } 2322 } 2323 2324 modelFile = new File( 2325 _serviceOutputPath + "/model/" + entity.getName() + "Soap.java"); 2326 2327 Map<String, Object> context = _getContext(); 2328 2329 context.put("entity", entity); 2330 2331 // Content 2332 2333 String content = _processTemplate(_tplModelSoap, context); 2334 2335 // Write file 2336 2337 writeFile(modelFile, content, _author); 2338 } 2339 2340 private void _createModelWrapper(Entity entity) throws Exception { 2341 JavaClass modelJavaClass = _getJavaClass( 2342 _serviceOutputPath + "/model/" + entity.getName() + "Model.java"); 2343 2344 Object[] methods = _getMethods(modelJavaClass); 2345 2346 JavaClass extendedModelBaseImplJavaClass = _getJavaClass( 2347 _outputPath + "/model/impl/" + entity.getName() + "BaseImpl.java"); 2348 2349 methods = ArrayUtil.append( 2350 methods, _getMethods(extendedModelBaseImplJavaClass)); 2351 2352 JavaClass extendedModelJavaClass = _getJavaClass( 2353 _serviceOutputPath + "/model/" + entity.getName() + ".java"); 2354 2355 methods = ArrayUtil.append( 2356 methods, _getMethods(extendedModelJavaClass)); 2357 2358 Map<String, Object> context = _getContext(); 2359 2360 context.put("entity", entity); 2361 context.put("methods", methods); 2362 2363 // Content 2364 2365 String content = _processTemplate(_tplModelWrapper, context); 2366 2367 // Write file 2368 2369 File modelFile = new File( 2370 _serviceOutputPath + "/model/" + entity.getName() + "Wrapper.java"); 2371 2372 writeFile(modelFile, content, _author); 2373 } 2374 2375 private void _createOrmXml() throws Exception { 2376 Map<String, Object> context = _getContext(); 2377 2378 context.put("entities", _ejbList); 2379 2380 // Content 2381 2382 String content = _processTemplate(_tplOrmXml, context); 2383 2384 String mappedClasses = ""; 2385 2386 int lastMappedClassStart = content.lastIndexOf("<mapped-superclass"); 2387 2388 if (lastMappedClassStart != -1) { 2389 int lastMappedClassEnd = content.indexOf( 2390 "</mapped-superclass>", lastMappedClassStart) + 20; 2391 2392 mappedClasses = content.substring(0, lastMappedClassEnd); 2393 2394 content = content.substring(lastMappedClassEnd + 1); 2395 } 2396 2397 File xmlFile = new File(_ormFileName); 2398 2399 if (!xmlFile.exists()) { 2400 String xml = 2401 "<?xml version=\"1.0\"?>\n" + 2402 "<entity-mappings version=\"1.0\" xmlns=\"http://java.sun.com/xml/ns/persistence/orm\"\n" + 2403 "\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + 2404 "\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_1_0.xsd\"\n" + 2405 ">\n" + 2406 "<persistence-unit-metadata>\n" + 2407 "\t<xml-mapping-metadata-complete />\n" + 2408 "\t<persistence-unit-defaults>\n" + 2409 "\t\t<access>PROPERTY</access>\n" + 2410 "\t</persistence-unit-defaults>\n" + 2411 "</persistence-unit-metadata>\n" + 2412 "</entity-mappings>"; 2413 2414 FileUtil.write(xmlFile, xml); 2415 } 2416 2417 String oldContent = FileUtil.read(xmlFile); 2418 String newContent = oldContent; 2419 2420 int firstMappedClass = newContent.indexOf( 2421 "<mapped-superclass class=\"" + _packagePath + ".model."); 2422 int lastMappedClass = newContent.lastIndexOf( 2423 "<mapped-superclass class=\"" + _packagePath + ".model."); 2424 2425 if (firstMappedClass == -1) { 2426 int x = newContent.indexOf("<entity class="); 2427 2428 if (x != -1) { 2429 newContent = 2430 newContent.substring(0, x) + mappedClasses + 2431 newContent.substring(x); 2432 } 2433 else { 2434 content = mappedClasses + content; 2435 } 2436 } 2437 else { 2438 firstMappedClass = newContent.indexOf( 2439 "<mapped-superclass", firstMappedClass) - 1; 2440 lastMappedClass = newContent.indexOf( 2441 "</mapped-superclass>", lastMappedClass) + 20; 2442 2443 newContent = 2444 newContent.substring(0, firstMappedClass) + mappedClasses + 2445 newContent.substring(lastMappedClass); 2446 } 2447 2448 int firstEntity = newContent.indexOf( 2449 "<entity class=\"" + _packagePath + ".model.impl."); 2450 int lastEntity = newContent.lastIndexOf( 2451 "<entity class=\"" + _packagePath + ".model.impl."); 2452 2453 if (firstEntity == -1) { 2454 int x = newContent.indexOf("</entity-mappings>"); 2455 2456 if (x != -1) { 2457 newContent = 2458 newContent.substring(0, x) + content + 2459 newContent.substring(x); 2460 } 2461 } 2462 else { 2463 firstEntity = newContent.lastIndexOf("<entity", firstEntity) - 1; 2464 lastEntity = newContent.indexOf("</entity>", lastEntity) + 9; 2465 2466 newContent = 2467 newContent.substring(0, firstEntity) + content + 2468 newContent.substring(lastEntity); 2469 } 2470 2471 newContent = _formatXml(newContent); 2472 2473 newContent = StringUtil.replace( 2474 newContent, 2475 new String[] {"<attributes></attributes>", "<attributes/>"}, 2476 new String[] {"<attributes />", "<attributes />"}); 2477 2478 if (!oldContent.equals(newContent)) { 2479 FileUtil.write(xmlFile, newContent); 2480 } 2481 } 2482 2483 private void _createPersistence(Entity entity) throws Exception { 2484 JavaClass javaClass = _getJavaClass( 2485 _outputPath + "/service/persistence/" + entity.getName() + 2486 "PersistenceImpl.java"); 2487 2488 Map<String, Object> context = _getContext(); 2489 2490 context.put("entity", entity); 2491 context.put("methods", _getMethods(javaClass)); 2492 2493 // Content 2494 2495 String content = _processTemplate(_tplPersistence, context); 2496 2497 // Write file 2498 2499 File ejbFile = new File( 2500 _serviceOutputPath + "/service/persistence/" + entity.getName() + 2501 "Persistence.java"); 2502 2503 writeFile(ejbFile, content, _author); 2504 2505 if (!_serviceOutputPath.equals(_outputPath)) { 2506 ejbFile = new File( 2507 _outputPath + "/service/persistence/" + entity.getName() + 2508 "Persistence.java"); 2509 2510 if (ejbFile.exists()) { 2511 System.out.println("Relocating " + ejbFile); 2512 2513 ejbFile.delete(); 2514 } 2515 } 2516 } 2517 2518 private void _createPersistenceImpl(Entity entity) throws Exception { 2519 Map<String, Object> context = _getContext(); 2520 2521 context.put("entity", entity); 2522 context.put( 2523 "referenceList", _mergeReferenceList(entity.getReferenceList())); 2524 2525 // Content 2526 2527 Logger.selectLoggerLibrary(Logger.LIBRARY_NONE); 2528 2529 String content = _processTemplate(_tplPersistenceImpl, context); 2530 2531 Logger.selectLoggerLibrary(Logger.LIBRARY_AUTO); 2532 2533 // Write file 2534 2535 File ejbFile = new File( 2536 _outputPath + "/service/persistence/" + entity.getName() + 2537 "PersistenceImpl.java"); 2538 2539 writeFile(ejbFile, content, _author); 2540 } 2541 2542 private void _createPersistenceTest(Entity entity) throws Exception { 2543 Map<String, Object> context = _getContext(); 2544 2545 context.put("entity", entity); 2546 2547 // Content 2548 2549 String content = _processTemplate(_tplPersistenceTest, context); 2550 2551 // Write file 2552 2553 File ejbFile = new File( 2554 _testOutputPath + "/service/persistence/" + entity.getName() + 2555 "PersistenceTest.java"); 2556 2557 writeFile(ejbFile, content, _author); 2558 } 2559 2560 private void _createPersistenceUtil(Entity entity) throws Exception { 2561 JavaClass javaClass = _getJavaClass( 2562 _outputPath + "/service/persistence/" + entity.getName() + 2563 "PersistenceImpl.java"); 2564 2565 Map<String, Object> context = _getContext(); 2566 2567 context.put("entity", entity); 2568 context.put("methods", _getMethods(javaClass)); 2569 2570 // Content 2571 2572 String content = _processTemplate(_tplPersistenceUtil, context); 2573 2574 // Write file 2575 2576 File ejbFile = new File( 2577 _serviceOutputPath + "/service/persistence/" + entity.getName() + 2578 "Util.java"); 2579 2580 writeFile(ejbFile, content, _author); 2581 2582 if (!_serviceOutputPath.equals(_outputPath)) { 2583 ejbFile = new File( 2584 _outputPath + "/service/persistence/" + entity.getName() + 2585 "Util.java"); 2586 2587 if (ejbFile.exists()) { 2588 System.out.println("Relocating " + ejbFile); 2589 2590 ejbFile.delete(); 2591 } 2592 } 2593 } 2594 2595 private void _createPool(Entity entity) { 2596 File ejbFile = new File( 2597 _outputPath + "/service/persistence/" + entity.getName() + 2598 "Pool.java"); 2599 2600 if (ejbFile.exists()) { 2601 System.out.println("Removing deprecated " + ejbFile); 2602 2603 ejbFile.delete(); 2604 } 2605 } 2606 2607 private void _createProps() throws Exception { 2608 if (Validator.isNull(_pluginName)) { 2609 return; 2610 } 2611 2612 // Content 2613 2614 File propsFile = new File(_implDir + "/service.properties"); 2615 2616 long buildNumber = 1; 2617 long buildDate = System.currentTimeMillis(); 2618 2619 if (propsFile.exists()) { 2620 Properties properties = PropertiesUtil.load( 2621 FileUtil.read(propsFile)); 2622 2623 if (!_buildNumberIncrement) { 2624 buildDate = GetterUtil.getLong( 2625 properties.getProperty("build.date")); 2626 buildNumber = GetterUtil.getLong( 2627 properties.getProperty("build.number")); 2628 } 2629 else { 2630 buildNumber = GetterUtil.getLong( 2631 properties.getProperty("build.number")) + 1; 2632 } 2633 } 2634 2635 if (!_buildNumberIncrement && (buildNumber < _buildNumber)) { 2636 buildNumber = _buildNumber; 2637 buildDate = System.currentTimeMillis(); 2638 } 2639 2640 Map<String, Object> context = _getContext(); 2641 2642 context.put("buildNumber", buildNumber); 2643 context.put("currentTimeMillis", buildDate); 2644 2645 String content = _processTemplate(_tplProps, context); 2646 2647 // Write file 2648 2649 FileUtil.write(propsFile, content, true); 2650 } 2651 2652 private void _createRemotingXml() throws Exception { 2653 StringBundler sb = new StringBundler(); 2654 2655 Document document = SAXReaderUtil.read(new File(_springFileName)); 2656 2657 Element rootElement = document.getRootElement(); 2658 2659 List<Element> beanElements = rootElement.elements("bean"); 2660 2661 for (Element beanElement : beanElements) { 2662 String beanId = beanElement.attributeValue("id"); 2663 2664 if (beanId.endsWith("Service") && 2665 !beanId.endsWith("LocalService")) { 2666 2667 String entityName = beanId; 2668 2669 entityName = StringUtil.replaceLast( 2670 entityName, ".service.", "."); 2671 2672 int pos = entityName.lastIndexOf("Service"); 2673 2674 entityName = entityName.substring(0, pos); 2675 2676 Entity entity = getEntity(entityName); 2677 2678 String serviceName = beanId; 2679 2680 String serviceMapping = serviceName; 2681 2682 serviceMapping = StringUtil.replaceLast( 2683 serviceMapping, ".service.", ".service.spring."); 2684 serviceMapping = StringUtil.replace( 2685 serviceMapping, StringPool.PERIOD, StringPool.UNDERLINE); 2686 2687 Map<String, Object> context = _getContext(); 2688 2689 context.put("entity", entity); 2690 context.put("serviceName", serviceName); 2691 context.put("serviceMapping", serviceMapping); 2692 2693 sb.append(_processTemplate(_tplRemotingXml, context)); 2694 } 2695 } 2696 2697 File outputFile = new File(_remotingFileName); 2698 2699 if (!outputFile.exists()) { 2700 return; 2701 } 2702 2703 String content = FileUtil.read(outputFile); 2704 String newContent = content; 2705 2706 int x = content.indexOf("<bean "); 2707 int y = content.lastIndexOf("</bean>") + 8; 2708 2709 if (x != -1) { 2710 newContent = 2711 content.substring(0, x - 1) + sb.toString() + 2712 content.substring(y); 2713 } 2714 else { 2715 x = content.indexOf("</beans>"); 2716 2717 if (x != -1) { 2718 newContent = 2719 content.substring(0, x) + sb.toString() + 2720 content.substring(x); 2721 } 2722 else { 2723 x = content.indexOf("<beans/>"); 2724 y = x + 8; 2725 2726 newContent = 2727 content.substring(0, x) + "<beans>" + sb.toString() + 2728 "</beans>" + content.substring(y); 2729 } 2730 } 2731 2732 newContent = _formatXml(newContent); 2733 2734 if (!content.equals(newContent)) { 2735 FileUtil.write(outputFile, newContent); 2736 2737 System.out.println(outputFile.toString()); 2738 } 2739 } 2740 2741 private void _createService(Entity entity, int sessionType) 2742 throws Exception { 2743 2744 JavaClass javaClass = _getJavaClass( 2745 _outputPath + "/service/impl/" + entity.getName() + 2746 _getSessionTypeName(sessionType) + "ServiceImpl.java"); 2747 2748 JavaMethod[] methods = _getMethods(javaClass); 2749 2750 Type superClass = javaClass.getSuperClass(); 2751 2752 String superClassValue = superClass.getValue(); 2753 2754 if (superClassValue.endsWith( 2755 entity.getName() + _getSessionTypeName(sessionType) + 2756 "ServiceBaseImpl")) { 2757 2758 JavaClass parentJavaClass = _getJavaClass( 2759 _outputPath + "/service/base/" + entity.getName() + 2760 _getSessionTypeName(sessionType) + "ServiceBaseImpl.java"); 2761 2762 methods = ArrayUtil.append( 2763 parentJavaClass.getMethods(), methods); 2764 } 2765 2766 Map<String, Object> context = _getContext(); 2767 2768 context.put("entity", entity); 2769 context.put("methods", methods); 2770 context.put("sessionTypeName", _getSessionTypeName(sessionType)); 2771 2772 // Content 2773 2774 String content = _processTemplate(_tplService, context); 2775 2776 // Write file 2777 2778 File ejbFile = new File( 2779 _serviceOutputPath + "/service/" + entity.getName() + 2780 _getSessionTypeName(sessionType) + "Service.java"); 2781 2782 writeFile(ejbFile, content, _author); 2783 2784 if (!_serviceOutputPath.equals(_outputPath)) { 2785 ejbFile = new File( 2786 _outputPath + "/service/" + entity.getName() + 2787 _getSessionTypeName(sessionType) + "Service.java"); 2788 2789 if (ejbFile.exists()) { 2790 System.out.println("Relocating " + ejbFile); 2791 2792 ejbFile.delete(); 2793 } 2794 } 2795 } 2796 2797 private void _createServiceBaseImpl(Entity entity, int sessionType) 2798 throws Exception { 2799 2800 JavaClass javaClass = _getJavaClass( 2801 _outputPath + "/service/impl/" + entity.getName() + 2802 (sessionType != _SESSION_TYPE_REMOTE ? "Local" : "") + 2803 "ServiceImpl.java"); 2804 2805 JavaMethod[] methods = _getMethods(javaClass); 2806 2807 Map<String, Object> context = _getContext(); 2808 2809 context.put("entity", entity); 2810 context.put("methods", methods); 2811 context.put("sessionTypeName",_getSessionTypeName(sessionType)); 2812 context.put( 2813 "referenceList", _mergeReferenceList(entity.getReferenceList())); 2814 2815 // Content 2816 2817 String content = _processTemplate(_tplServiceBaseImpl, context); 2818 2819 // Write file 2820 2821 File ejbFile = new File( 2822 _outputPath + "/service/base/" + entity.getName() + 2823 _getSessionTypeName(sessionType) + "ServiceBaseImpl.java"); 2824 2825 writeFile(ejbFile, content, _author); 2826 } 2827 2828 private void _createServiceClp(Entity entity, int sessionType) 2829 throws Exception { 2830 2831 if (Validator.isNull(_pluginName)) { 2832 return; 2833 } 2834 2835 JavaClass javaClass = _getJavaClass( 2836 _serviceOutputPath + "/service/" + entity.getName() + 2837 _getSessionTypeName(sessionType) + "Service.java"); 2838 2839 Map<String, Object> context = _getContext(); 2840 2841 context.put("entity", entity); 2842 context.put("methods", _getMethods(javaClass)); 2843 context.put("sessionTypeName", _getSessionTypeName(sessionType)); 2844 2845 // Content 2846 2847 String content = _processTemplate(_tplServiceClp, context); 2848 2849 // Write file 2850 2851 File ejbFile = new File( 2852 _serviceOutputPath + "/service/" + entity.getName() + 2853 _getSessionTypeName(sessionType) + "ServiceClp.java"); 2854 2855 writeFile(ejbFile, content, _author); 2856 } 2857 2858 private void _createServiceClpInvoker(Entity entity, int sessionType) 2859 throws Exception { 2860 2861 if (Validator.isNull(_pluginName)) { 2862 return; 2863 } 2864 2865 JavaClass javaClass = _getJavaClass( 2866 _outputPath + "/service/impl/" + entity.getName() + 2867 _getSessionTypeName(sessionType) + "ServiceImpl.java"); 2868 2869 JavaMethod[] methods = _getMethods(javaClass); 2870 2871 Type superClass = javaClass.getSuperClass(); 2872 2873 String superClassValue = superClass.getValue(); 2874 2875 if (superClassValue.endsWith( 2876 entity.getName() + _getSessionTypeName(sessionType) + 2877 "ServiceBaseImpl")) { 2878 2879 JavaClass parentJavaClass = _getJavaClass( 2880 _outputPath + "/service/base/" + entity.getName() + 2881 _getSessionTypeName(sessionType) + "ServiceBaseImpl.java"); 2882 2883 methods = ArrayUtil.append( 2884 parentJavaClass.getMethods(), methods); 2885 } 2886 2887 Map<String, Object> context = _getContext(); 2888 2889 context.put("entity", entity); 2890 context.put("methods", methods); 2891 context.put("sessionTypeName", _getSessionTypeName(sessionType)); 2892 2893 // Content 2894 2895 String content = _processTemplate(_tplServiceClpInvoker, context); 2896 2897 // Write file 2898 2899 File ejbFile = new File( 2900 _outputPath + "/service/base/" + entity.getName() + 2901 _getSessionTypeName(sessionType) + "ServiceClpInvoker.java"); 2902 2903 writeFile(ejbFile, content); 2904 } 2905 2906 private void _createServiceClpMessageListener() throws Exception { 2907 if (Validator.isNull(_pluginName)) { 2908 return; 2909 } 2910 2911 Map<String, Object> context = _getContext(); 2912 2913 context.put("entities", _ejbList); 2914 2915 // Content 2916 2917 String content = _processTemplate( 2918 _tplServiceClpMessageListener, context); 2919 2920 // Write file 2921 2922 File ejbFile = new File( 2923 _serviceOutputPath + "/service/messaging/ClpMessageListener.java"); 2924 2925 writeFile(ejbFile, content); 2926 } 2927 2928 private void _createServiceClpSerializer(List<String> exceptions) 2929 throws Exception { 2930 2931 if (Validator.isNull(_pluginName)) { 2932 return; 2933 } 2934 2935 Map<String, Object> context = _getContext(); 2936 2937 context.put("entities", _ejbList); 2938 context.put("exceptions", exceptions); 2939 2940 // Content 2941 2942 String content = _processTemplate(_tplServiceClpSerializer, context); 2943 2944 // Write file 2945 2946 File ejbFile = new File( 2947 _serviceOutputPath + "/service/ClpSerializer.java"); 2948 2949 writeFile(ejbFile, content); 2950 } 2951 2952 private void _createServiceFactory(Entity entity, int sessionType) { 2953 File ejbFile = new File( 2954 _serviceOutputPath + "/service/" + entity.getName() + 2955 _getSessionTypeName(sessionType) + "ServiceFactory.java"); 2956 2957 if (ejbFile.exists()) { 2958 System.out.println("Removing deprecated " + ejbFile); 2959 2960 ejbFile.delete(); 2961 } 2962 2963 ejbFile = new File( 2964 _outputPath + "/service/" + entity.getName() + 2965 _getSessionTypeName(sessionType) + "ServiceFactory.java"); 2966 2967 if (ejbFile.exists()) { 2968 System.out.println("Removing deprecated " + ejbFile); 2969 2970 ejbFile.delete(); 2971 } 2972 } 2973 2974 private void _createServiceHttp(Entity entity) throws Exception { 2975 JavaClass javaClass = _getJavaClass( 2976 _outputPath + "/service/impl/" + entity.getName() + 2977 "ServiceImpl.java"); 2978 2979 Map<String, Object> context = _getContext(); 2980 2981 context.put("entity", entity); 2982 context.put("methods", _getMethods(javaClass)); 2983 context.put("hasHttpMethods", new Boolean(_hasHttpMethods(javaClass))); 2984 2985 // Content 2986 2987 String content = _processTemplate(_tplServiceHttp, context); 2988 2989 // Write file 2990 2991 File ejbFile = new File( 2992 _outputPath + "/service/http/" + entity.getName() + 2993 "ServiceHttp.java"); 2994 2995 writeFile(ejbFile, content, _author); 2996 } 2997 2998 private void _createServiceImpl(Entity entity, int sessionType) 2999 throws Exception { 3000 3001 Map<String, Object> context = _getContext(); 3002 3003 context.put("entity", entity); 3004 context.put("sessionTypeName", _getSessionTypeName(sessionType)); 3005 3006 // Content 3007 3008 String content = _processTemplate(_tplServiceImpl, context); 3009 3010 // Write file 3011 3012 File ejbFile = new File( 3013 _outputPath + "/service/impl/" + entity.getName() + 3014 _getSessionTypeName(sessionType) + "ServiceImpl.java"); 3015 3016 if (!ejbFile.exists()) { 3017 writeFile(ejbFile, content, _author); 3018 } 3019 } 3020 3021 private void _createServiceJson(Entity entity) { 3022 File ejbFile = new File( 3023 _outputPath + "/service/http/" + entity.getName() + 3024 "ServiceJSON.java"); 3025 3026 if (ejbFile.exists()) { 3027 System.out.println("Removing deprecated " + ejbFile); 3028 3029 ejbFile.delete(); 3030 } 3031 } 3032 3033 private void _createServiceJsonSerializer(Entity entity) { 3034 File ejbFile = new File( 3035 _serviceOutputPath + "/service/http/" + entity.getName() + 3036 "JSONSerializer.java"); 3037 3038 if (ejbFile.exists()) { 3039 System.out.println("Removing deprecated " + ejbFile); 3040 3041 ejbFile.delete(); 3042 } 3043 3044 if (!_serviceOutputPath.equals(_outputPath)) { 3045 ejbFile = new File( 3046 _outputPath + "/service/http/" + entity.getName() + 3047 "JSONSerializer.java"); 3048 3049 if (ejbFile.exists()) { 3050 System.out.println("Removing deprecated " + ejbFile); 3051 3052 ejbFile.delete(); 3053 } 3054 } 3055 } 3056 3057 private void _createServiceSoap(Entity entity) throws Exception { 3058 JavaClass javaClass = _getJavaClass( 3059 _outputPath + "/service/impl/" + entity.getName() + 3060 "ServiceImpl.java"); 3061 3062 Map<String, Object> context = _getContext(); 3063 3064 context.put("entity", entity); 3065 context.put("methods", _getMethods(javaClass)); 3066 3067 // Content 3068 3069 String content = _processTemplate(_tplServiceSoap, context); 3070 3071 // Write file 3072 3073 File ejbFile = new File( 3074 _outputPath + "/service/http/" + entity.getName() + 3075 "ServiceSoap.java"); 3076 3077 writeFile(ejbFile, content, _author); 3078 } 3079 3080 private void _createServiceUtil(Entity entity, int sessionType) 3081 throws Exception { 3082 3083 JavaClass javaClass = _getJavaClass( 3084 _serviceOutputPath + "/service/" + entity.getName() + 3085 _getSessionTypeName(sessionType) + "Service.java"); 3086 3087 Map<String, Object> context = _getContext(); 3088 3089 context.put("entity", entity); 3090 context.put("methods", _getMethods(javaClass)); 3091 context.put("sessionTypeName", _getSessionTypeName(sessionType)); 3092 3093 // Content 3094 3095 String content = _processTemplate(_tplServiceUtil, context); 3096 3097 // Write file 3098 3099 File ejbFile = new File( 3100 _serviceOutputPath + "/service/" + entity.getName() + 3101 _getSessionTypeName(sessionType) + "ServiceUtil.java"); 3102 3103 writeFile(ejbFile, content, _author); 3104 3105 if (!_serviceOutputPath.equals(_outputPath)) { 3106 ejbFile = new File( 3107 _outputPath + "/service/" + entity.getName() + 3108 _getSessionTypeName(sessionType) + "ServiceUtil.java"); 3109 3110 if (ejbFile.exists()) { 3111 System.out.println("Relocating " + ejbFile); 3112 3113 ejbFile.delete(); 3114 } 3115 } 3116 } 3117 3118 private void _createServiceWrapper(Entity entity, int sessionType) 3119 throws Exception { 3120 3121 JavaClass javaClass = _getJavaClass( 3122 _serviceOutputPath + "/service/" + entity.getName() + 3123 _getSessionTypeName(sessionType) + "Service.java"); 3124 3125 Map<String, Object> context = _getContext(); 3126 3127 context.put("entity", entity); 3128 context.put("methods", _getMethods(javaClass)); 3129 context.put("sessionTypeName", _getSessionTypeName(sessionType)); 3130 3131 // Content 3132 3133 String content = _processTemplate(_tplServiceWrapper, context); 3134 3135 // Write file 3136 3137 File ejbFile = new File( 3138 _serviceOutputPath + "/service/" + entity.getName() + 3139 _getSessionTypeName(sessionType) + "ServiceWrapper.java"); 3140 3141 writeFile(ejbFile, content, _author); 3142 } 3143 3144 private void _createSpringBaseXml() throws Exception { 3145 if (Validator.isNull(_springBaseFileName)) { 3146 return; 3147 } 3148 3149 // Content 3150 3151 String content = _processTemplate(_tplSpringBaseXml); 3152 3153 // Write file 3154 3155 File ejbFile = new File(_springBaseFileName); 3156 3157 FileUtil.write(ejbFile, content, true); 3158 3159 if (Validator.isNotNull(_pluginName)) { 3160 FileUtil.delete( 3161 "docroot/WEB-INF/src/META-INF/data-source-spring.xml"); 3162 FileUtil.delete("docroot/WEB-INF/src/META-INF/misc-spring.xml"); 3163 } 3164 } 3165 3166 private void _createSpringClusterXml() throws Exception { 3167 if (Validator.isNull(_springClusterFileName)) { 3168 return; 3169 } 3170 3171 // Content 3172 3173 String content = _processTemplate(_tplSpringClusterXml); 3174 3175 // Write file 3176 3177 File ejbFile = new File(_springClusterFileName); 3178 3179 FileUtil.write(ejbFile, content, true); 3180 } 3181 3182 private void _createSpringDynamicDataSourceXml() throws Exception { 3183 if (Validator.isNull(_springDynamicDataSourceFileName)) { 3184 return; 3185 } 3186 3187 // Content 3188 3189 String content = _processTemplate(_tplSpringDynamicDataSourceXml); 3190 3191 // Write file 3192 3193 File ejbFile = new File(_springDynamicDataSourceFileName); 3194 3195 FileUtil.write(ejbFile, content, true); 3196 } 3197 3198 private void _createSpringHibernateXml() throws Exception { 3199 if (Validator.isNull(_springHibernateFileName)) { 3200 return; 3201 } 3202 3203 // Content 3204 3205 String content = _processTemplate(_tplSpringHibernateXml); 3206 3207 // Write file 3208 3209 File ejbFile = new File(_springHibernateFileName); 3210 3211 FileUtil.write(ejbFile, content, true); 3212 } 3213 3214 private void _createSpringInfrastructureXml() throws Exception { 3215 if (Validator.isNull(_springInfrastructureFileName)) { 3216 return; 3217 } 3218 3219 // Content 3220 3221 String content = _processTemplate(_tplSpringInfrastructureXml); 3222 3223 // Write file 3224 3225 File ejbFile = new File(_springInfrastructureFileName); 3226 3227 FileUtil.write(ejbFile, content, true); 3228 } 3229 3230 private void _createSpringShardDataSourceXml() throws Exception { 3231 if (Validator.isNull(_springShardDataSourceFileName)) { 3232 return; 3233 } 3234 3235 // Content 3236 3237 String content = _processTemplate(_tplSpringShardDataSourceXml); 3238 3239 // Write file 3240 3241 File ejbFile = new File(_springShardDataSourceFileName); 3242 3243 FileUtil.write(ejbFile, content, true); 3244 } 3245 3246 private void _createSpringXml() throws Exception { 3247 if (_packagePath.equals("com.liferay.counter")) { 3248 return; 3249 } 3250 3251 Map<String, Object> context = _getContext(); 3252 3253 context.put("entities", _ejbList); 3254 3255 // Content 3256 3257 String content = _processTemplate(_tplSpringXml, context); 3258 3259 File xmlFile = new File(_springFileName); 3260 3261 String xml = 3262 "<?xml version=\"1.0\"?>\n" + 3263 "\n" + 3264 "<beans\n" + 3265 "\tdefault-destroy-method=\"destroy\"\n" + 3266 "\tdefault-init-method=\"afterPropertiesSet\"\n" + 3267 "\txmlns=\"http://www.springframework.org/schema/beans\"\n" + 3268 "\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + 3269 "\txsi:schemaLocation=\"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\"\n" + 3270 ">\n" + 3271 "</beans>"; 3272 3273 if (!xmlFile.exists()) { 3274 FileUtil.write(xmlFile, xml); 3275 } 3276 3277 String oldContent = FileUtil.read(xmlFile); 3278 3279 if (Validator.isNotNull(_pluginName) && 3280 oldContent.contains("DOCTYPE beans PUBLIC")) { 3281 3282 oldContent = xml; 3283 } 3284 3285 String newContent = _fixSpringXml(oldContent); 3286 3287 int x = oldContent.indexOf("<beans"); 3288 int y = oldContent.lastIndexOf("</beans>"); 3289 3290 int firstSession = newContent.indexOf( 3291 "<bean id=\"" + _packagePath + ".service.", x); 3292 3293 int lastSession = newContent.lastIndexOf( 3294 "<bean id=\"" + _packagePath + ".service.", y); 3295 3296 if ((firstSession == -1) || (firstSession > y)) { 3297 x = newContent.indexOf("</beans>"); 3298 3299 newContent = 3300 newContent.substring(0, x) + content + newContent.substring(x); 3301 } 3302 else { 3303 firstSession = newContent.lastIndexOf("<bean", firstSession) - 1; 3304 3305 int tempLastSession = newContent.indexOf( 3306 "<bean id=\"", lastSession + 1); 3307 3308 if (tempLastSession == -1) { 3309 tempLastSession = newContent.indexOf("</beans>", lastSession); 3310 } 3311 3312 lastSession = tempLastSession; 3313 3314 newContent = 3315 newContent.substring(0, firstSession) + content + 3316 newContent.substring(lastSession); 3317 } 3318 3319 newContent = _formatXml(newContent); 3320 3321 if (!oldContent.equals(newContent)) { 3322 FileUtil.write(xmlFile, newContent); 3323 } 3324 } 3325 3326 private void _createSQLIndexes() throws IOException { 3327 if (!FileUtil.exists(_sqlDir)) { 3328 return; 3329 } 3330 3331 // indexes.sql 3332 3333 File sqlFile = new File(_sqlDir + "/" + _sqlIndexesFileName); 3334 3335 if (!sqlFile.exists()) { 3336 FileUtil.write(sqlFile, ""); 3337 } 3338 3339 Map<String, String> indexSQLs = new TreeMap<String, String>(); 3340 3341 UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader( 3342 new FileReader(sqlFile)); 3343 3344 while (true) { 3345 String indexSQL = unsyncBufferedReader.readLine(); 3346 3347 if (indexSQL == null) { 3348 break; 3349 } 3350 3351 if (Validator.isNotNull(indexSQL.trim())) { 3352 int pos = indexSQL.indexOf(" on "); 3353 3354 String indexSpec = indexSQL.substring(pos + 4); 3355 3356 indexSQLs.put(indexSpec, indexSQL); 3357 } 3358 } 3359 3360 unsyncBufferedReader.close(); 3361 3362 // indexes.properties 3363 3364 File propsFile = new File( 3365 _sqlDir + "/" + _sqlIndexesPropertiesFileName); 3366 3367 if (!propsFile.exists()) { 3368 FileUtil.write(propsFile, ""); 3369 } 3370 3371 Map<String, String> indexProps = new TreeMap<String, String>(); 3372 3373 unsyncBufferedReader = new UnsyncBufferedReader( 3374 new FileReader(propsFile)); 3375 3376 while (true) { 3377 String indexMapping = unsyncBufferedReader.readLine(); 3378 3379 if (indexMapping == null) { 3380 break; 3381 } 3382 3383 if (Validator.isNotNull(indexMapping.trim())) { 3384 String[] splitIndexMapping = indexMapping.split("\\="); 3385 3386 indexProps.put(splitIndexMapping[1], splitIndexMapping[0]); 3387 } 3388 } 3389 3390 unsyncBufferedReader.close(); 3391 3392 // indexes.sql 3393 3394 for (int i = 0; i < _ejbList.size(); i++) { 3395 Entity entity = _ejbList.get(i); 3396 3397 if (!_isTargetEntity(entity)) { 3398 continue; 3399 } 3400 3401 if (!entity.isDefaultDataSource()) { 3402 continue; 3403 } 3404 3405 List<EntityFinder> finderList = entity.getFinderList(); 3406 3407 for (int j = 0; j < finderList.size(); j++) { 3408 EntityFinder finder = finderList.get(j); 3409 3410 if (finder.isDBIndex()) { 3411 List<String> finderColsNames = new ArrayList<String>(); 3412 3413 List<EntityColumn> finderColsList = finder.getColumns(); 3414 3415 for (int k = 0; k < finderColsList.size(); k++) { 3416 EntityColumn col = finderColsList.get(k); 3417 3418 finderColsNames.add(col.getDBName()); 3419 } 3420 3421 IndexMetadata indexMetadata = 3422 IndexMetadataFactoryUtil.createIndexMetadata( 3423 finder.isUnique(), entity.getTable(), 3424 finderColsNames.toArray( 3425 new String[finderColsNames.size()])); 3426 3427 indexSQLs.put( 3428 indexMetadata.getSpecification(), 3429 indexMetadata.getCreateSQL()); 3430 3431 String finderName = 3432 entity.getTable() + StringPool.PERIOD + 3433 finder.getName(); 3434 3435 indexProps.put(finderName, indexMetadata.getIndexName()); 3436 } 3437 } 3438 } 3439 3440 for (Map.Entry<String, EntityMapping> entry : 3441 _entityMappings.entrySet()) { 3442 3443 EntityMapping entityMapping = entry.getValue(); 3444 3445 _getCreateMappingTableIndex(entityMapping, indexSQLs, indexProps); 3446 } 3447 3448 StringBundler sb = new StringBundler(); 3449 3450 String prevEntityName = null; 3451 3452 for (String indexSQL : indexSQLs.values()) { 3453 int pos = indexSQL.indexOf(" on "); 3454 3455 String indexSQLSuffix = indexSQL.substring(pos + 4); 3456 3457 String entityName = indexSQLSuffix.split(" ")[0]; 3458 3459 if ((prevEntityName != null) && 3460 !prevEntityName.equals(entityName)) { 3461 3462 sb.append("\n"); 3463 } 3464 3465 sb.append(indexSQL); 3466 sb.append("\n"); 3467 3468 prevEntityName = entityName; 3469 } 3470 3471 if (!indexSQLs.isEmpty()) { 3472 sb.setIndex(sb.index() - 1); 3473 } 3474 3475 FileUtil.write(sqlFile, sb.toString(), true); 3476 3477 // indexes.properties 3478 3479 sb.setIndex(0); 3480 3481 prevEntityName = null; 3482 3483 for (String finderName : indexProps.keySet()) { 3484 String indexName = indexProps.get(finderName); 3485 3486 String entityName = finderName.split("\\.")[0]; 3487 3488 if ((prevEntityName != null) && 3489 !prevEntityName.equals(entityName)) { 3490 3491 sb.append("\n"); 3492 } 3493 3494 sb.append(indexName + StringPool.EQUAL + finderName); 3495 sb.append("\n"); 3496 3497 prevEntityName = entityName; 3498 } 3499 3500 if (!indexProps.isEmpty()) { 3501 sb.setIndex(sb.index() - 1); 3502 } 3503 3504 FileUtil.write(propsFile, sb.toString(), true); 3505 } 3506 3507 private void _createSQLMappingTables( 3508 File sqlFile, String newCreateTableString, 3509 EntityMapping entityMapping, boolean addMissingTables) 3510 throws IOException { 3511 3512 if (!sqlFile.exists()) { 3513 FileUtil.write(sqlFile, StringPool.BLANK); 3514 } 3515 3516 String content = FileUtil.read(sqlFile); 3517 3518 int x = content.indexOf( 3519 _SQL_CREATE_TABLE + entityMapping.getTable() + " ("); 3520 int y = content.indexOf(");", x); 3521 3522 if (x != -1) { 3523 String oldCreateTableString = content.substring(x + 1, y); 3524 3525 if (!oldCreateTableString.equals(newCreateTableString)) { 3526 content = 3527 content.substring(0, x) + newCreateTableString + 3528 content.substring(y + 2); 3529 3530 FileUtil.write(sqlFile, content); 3531 } 3532 } 3533 else if (addMissingTables) { 3534 StringBundler sb = new StringBundler(); 3535 3536 UnsyncBufferedReader unsyncBufferedReader = 3537 new UnsyncBufferedReader(new UnsyncStringReader(content)); 3538 3539 String line = null; 3540 boolean appendNewTable = true; 3541 3542 while ((line = unsyncBufferedReader.readLine()) != null) { 3543 if (appendNewTable && line.startsWith(_SQL_CREATE_TABLE)) { 3544 x = _SQL_CREATE_TABLE.length(); 3545 y = line.indexOf(" ", x); 3546 3547 String tableName = line.substring(x, y); 3548 3549 if (tableName.compareTo(entityMapping.getTable()) > 0) { 3550 sb.append(newCreateTableString + "\n\n"); 3551 3552 appendNewTable = false; 3553 } 3554 } 3555 3556 sb.append(line); 3557 sb.append("\n"); 3558 } 3559 3560 if (appendNewTable) { 3561 sb.append("\n" + newCreateTableString); 3562 } 3563 3564 unsyncBufferedReader.close(); 3565 3566 FileUtil.write(sqlFile, sb.toString(), true); 3567 } 3568 } 3569 3570 private void _createSQLSequences() throws IOException { 3571 if (!FileUtil.exists(_sqlDir)) { 3572 return; 3573 } 3574 3575 File sqlFile = new File(_sqlDir + "/" + _sqlSequencesFileName); 3576 3577 if (!sqlFile.exists()) { 3578 FileUtil.write(sqlFile, ""); 3579 } 3580 3581 Set<String> sequenceSQLs = new TreeSet<String>(); 3582 3583 UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader( 3584 new FileReader(sqlFile)); 3585 3586 while (true) { 3587 String sequenceSQL = unsyncBufferedReader.readLine(); 3588 3589 if (sequenceSQL == null) { 3590 break; 3591 } 3592 3593 if (Validator.isNotNull(sequenceSQL)) { 3594 sequenceSQLs.add(sequenceSQL); 3595 } 3596 } 3597 3598 unsyncBufferedReader.close(); 3599 3600 for (int i = 0; i < _ejbList.size(); i++) { 3601 Entity entity = _ejbList.get(i); 3602 3603 if (!_isTargetEntity(entity)) { 3604 continue; 3605 } 3606 3607 if (!entity.isDefaultDataSource()) { 3608 continue; 3609 } 3610 3611 List<EntityColumn> columnList = entity.getColumnList(); 3612 3613 for (int j = 0; j < columnList.size(); j++) { 3614 EntityColumn column = columnList.get(j); 3615 3616 if ("sequence".equals(column.getIdType())) { 3617 StringBundler sb = new StringBundler(); 3618 3619 String sequenceName = column.getIdParam(); 3620 3621 if (sequenceName.length() > 30) { 3622 sequenceName = sequenceName.substring(0, 30); 3623 } 3624 3625 sb.append("create sequence " + sequenceName + ";"); 3626 3627 String sequenceSQL = sb.toString(); 3628 3629 if (!sequenceSQLs.contains(sequenceSQL)) { 3630 sequenceSQLs.add(sequenceSQL); 3631 } 3632 } 3633 } 3634 } 3635 3636 StringBundler sb = new StringBundler(sequenceSQLs.size() * 2); 3637 3638 for (String sequenceSQL : sequenceSQLs) { 3639 sb.append(sequenceSQL); 3640 sb.append("\n"); 3641 } 3642 3643 if (!sequenceSQLs.isEmpty()) { 3644 sb.setIndex(sb.index() - 1); 3645 } 3646 3647 FileUtil.write(sqlFile, sb.toString(), true); 3648 } 3649 3650 private void _createSQLTables() throws IOException { 3651 if (!FileUtil.exists(_sqlDir)) { 3652 return; 3653 } 3654 3655 File sqlFile = new File(_sqlDir + "/" + _sqlFileName); 3656 3657 if (!sqlFile.exists()) { 3658 FileUtil.write(sqlFile, StringPool.BLANK); 3659 } 3660 3661 for (int i = 0; i < _ejbList.size(); i++) { 3662 Entity entity = _ejbList.get(i); 3663 3664 if (!_isTargetEntity(entity)) { 3665 continue; 3666 } 3667 3668 if (!entity.isDefaultDataSource()) { 3669 continue; 3670 } 3671 3672 String createTableSQL = _getCreateTableSQL(entity); 3673 3674 if (Validator.isNotNull(createTableSQL)) { 3675 _createSQLTables(sqlFile, createTableSQL, entity, true); 3676 3677 _updateSQLFile( 3678 "update-6.1.1-6.2.0.sql", createTableSQL, entity); 3679 } 3680 } 3681 3682 for (Map.Entry<String, EntityMapping> entry : 3683 _entityMappings.entrySet()) { 3684 3685 EntityMapping entityMapping = entry.getValue(); 3686 3687 String createMappingTableSQL = _getCreateMappingTableSQL( 3688 entityMapping); 3689 3690 if (Validator.isNotNull(createMappingTableSQL)) { 3691 _createSQLMappingTables( 3692 sqlFile, createMappingTableSQL, entityMapping, true); 3693 } 3694 } 3695 3696 String content = FileUtil.read(sqlFile); 3697 3698 FileUtil.write(sqlFile, content.trim()); 3699 } 3700 3701 private void _createSQLTables( 3702 File sqlFile, String newCreateTableString, Entity entity, 3703 boolean addMissingTables) 3704 throws IOException { 3705 3706 if (!sqlFile.exists()) { 3707 FileUtil.write(sqlFile, StringPool.BLANK); 3708 } 3709 3710 String content = FileUtil.read(sqlFile); 3711 3712 int x = content.indexOf(_SQL_CREATE_TABLE + entity.getTable() + " ("); 3713 int y = content.indexOf(");", x); 3714 3715 if (x != -1) { 3716 String oldCreateTableString = content.substring(x + 1, y); 3717 3718 if (!oldCreateTableString.equals(newCreateTableString)) { 3719 content = 3720 content.substring(0, x) + newCreateTableString + 3721 content.substring(y + 2); 3722 3723 FileUtil.write(sqlFile, content); 3724 } 3725 } 3726 else if (addMissingTables) { 3727 StringBundler sb = new StringBundler(); 3728 3729 UnsyncBufferedReader unsyncBufferedReader = 3730 new UnsyncBufferedReader(new UnsyncStringReader(content)); 3731 3732 String line = null; 3733 boolean appendNewTable = true; 3734 3735 while ((line = unsyncBufferedReader.readLine()) != null) { 3736 if (appendNewTable && line.startsWith(_SQL_CREATE_TABLE)) { 3737 x = _SQL_CREATE_TABLE.length(); 3738 y = line.indexOf(" ", x); 3739 3740 String tableName = line.substring(x, y); 3741 3742 if (tableName.compareTo(entity.getTable()) > 0) { 3743 sb.append(newCreateTableString + "\n\n"); 3744 3745 appendNewTable = false; 3746 } 3747 } 3748 3749 sb.append(line); 3750 sb.append("\n"); 3751 } 3752 3753 if (appendNewTable) { 3754 sb.append("\n" + newCreateTableString); 3755 } 3756 3757 unsyncBufferedReader.close(); 3758 3759 FileUtil.write(sqlFile, sb.toString(), true); 3760 } 3761 } 3762 3763 private String _fixHbmXml(String content) throws IOException { 3764 StringBundler sb = new StringBundler(); 3765 3766 UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader( 3767 new UnsyncStringReader(content)); 3768 3769 String line = null; 3770 3771 while ((line = unsyncBufferedReader.readLine()) != null) { 3772 if (line.startsWith("\t<class name=\"")) { 3773 line = StringUtil.replace( 3774 line, 3775 new String[] { 3776 ".service.persistence.", "HBM\" table=\"" 3777 }, 3778 new String[] { 3779 ".model.", "\" table=\"" 3780 }); 3781 3782 if (!line.contains(".model.impl.") && 3783 !line.contains("BlobModel")) { 3784 3785 line = StringUtil.replace( 3786 line, 3787 new String[] { 3788 ".model.", "\" table=\"" 3789 }, 3790 new String[] { 3791 ".model.impl.", "Impl\" table=\"" 3792 }); 3793 } 3794 } 3795 3796 sb.append(line); 3797 sb.append('\n'); 3798 } 3799 3800 unsyncBufferedReader.close(); 3801 3802 return sb.toString().trim(); 3803 } 3804 3805 private String _fixSpringXml(String content) { 3806 return StringUtil.replace(content, ".service.spring.", ".service."); 3807 } 3808 3809 private String _formatComment( 3810 String comment, DocletTag[] tags, String indentation) { 3811 3812 StringBundler sb = new StringBundler(); 3813 3814 if (Validator.isNull(comment) && (tags.length <= 0)) { 3815 return sb.toString(); 3816 } 3817 3818 sb.append(indentation); 3819 sb.append("/**\n"); 3820 3821 if (Validator.isNotNull(comment)) { 3822 comment = comment.replaceAll("(?m)^", indentation + " * "); 3823 3824 sb.append(comment); 3825 sb.append("\n"); 3826 3827 if (tags.length > 0) { 3828 sb.append(indentation); 3829 sb.append(" *\n"); 3830 } 3831 } 3832 3833 for (DocletTag tag : tags) { 3834 sb.append(indentation); 3835 sb.append(" * @"); 3836 sb.append(tag.getName()); 3837 sb.append(" "); 3838 sb.append(tag.getValue()); 3839 sb.append("\n"); 3840 } 3841 3842 sb.append(indentation); 3843 sb.append(" */\n"); 3844 3845 return sb.toString(); 3846 } 3847 3848 private String _formatXml(String xml) 3849 throws DocumentException, IOException { 3850 3851 String doctype = null; 3852 3853 int x = xml.indexOf("<!DOCTYPE"); 3854 3855 if (x != -1) { 3856 int y = xml.indexOf(">", x) + 1; 3857 3858 doctype = xml.substring(x, y); 3859 3860 xml = xml.substring(0, x) + "\n" + xml.substring(y); 3861 } 3862 3863 xml = StringUtil.replace(xml, '\r', ""); 3864 xml = XMLFormatter.toString(xml); 3865 xml = StringUtil.replace(xml, "\"/>", "\" />"); 3866 3867 if (Validator.isNotNull(doctype)) { 3868 x = xml.indexOf("?>") + 2; 3869 3870 xml = xml.substring(0, x) + "\n" + doctype + xml.substring(x); 3871 } 3872 3873 return xml; 3874 } 3875 3876 private JavaField[] _getCacheFields(JavaClass javaClass) { 3877 if (javaClass == null) { 3878 return new JavaField[0]; 3879 } 3880 3881 List<JavaField> javaFields = new ArrayList<JavaField>(); 3882 3883 for (JavaField javaField : javaClass.getFields()) { 3884 Annotation[] annotations = javaField.getAnnotations(); 3885 3886 for (Annotation annotation : annotations) { 3887 Type type = annotation.getType(); 3888 3889 String className = type.getFullyQualifiedName(); 3890 3891 if (className.equals(CacheField.class.getName())) { 3892 javaFields.add(javaField); 3893 3894 break; 3895 } 3896 } 3897 } 3898 3899 return javaFields.toArray(new JavaField[javaFields.size()]); 3900 } 3901 3902 private Map<String, Object> _getContext() throws TemplateModelException { 3903 BeansWrapper wrapper = BeansWrapper.getDefaultInstance(); 3904 3905 TemplateHashModel staticModels = wrapper.getStaticModels(); 3906 3907 Map<String, Object> context = new HashMap<String, Object>(); 3908 3909 context.put("hbmFileName", _hbmFileName); 3910 context.put("ormFileName", _ormFileName); 3911 context.put("modelHintsFileName", _modelHintsFileName); 3912 context.put("springFileName", _springFileName); 3913 context.put("springBaseFileName", _springBaseFileName); 3914 context.put("springHibernateFileName", _springHibernateFileName); 3915 context.put( 3916 "springInfrastructureFileName", _springInfrastructureFileName); 3917 context.put("apiDir", _apiDir); 3918 context.put("implDir", _implDir); 3919 context.put("sqlDir", _sqlDir); 3920 context.put("sqlFileName", _sqlFileName); 3921 context.put("beanLocatorUtil", _beanLocatorUtil); 3922 context.put("beanLocatorUtilShortName", _beanLocatorUtilShortName); 3923 context.put("propsUtil", _propsUtil); 3924 context.put("portletName", _portletName); 3925 context.put("portletShortName", _portletShortName); 3926 context.put("portletPackageName", _portletPackageName); 3927 context.put("outputPath", _outputPath); 3928 context.put("serviceOutputPath", _serviceOutputPath); 3929 context.put("packagePath", _packagePath); 3930 context.put("pluginName", _pluginName); 3931 context.put("author", _author); 3932 context.put("serviceBuilder", this); 3933 3934 context.put("arrayUtil", ArrayUtil_IW.getInstance()); 3935 context.put("modelHintsUtil", ModelHintsUtil.getModelHints()); 3936 context.put( 3937 "resourceActionsUtil", ResourceActionsUtil.getResourceActions()); 3938 context.put("stringUtil", StringUtil_IW.getInstance()); 3939 context.put("system", staticModels.get("java.lang.System")); 3940 context.put("tempMap", wrapper.wrap(new HashMap<String, Object>())); 3941 context.put( 3942 "textFormatter", staticModels.get(TextFormatter.class.getName())); 3943 context.put("validator", Validator_IW.getInstance()); 3944 3945 return context; 3946 } 3947 3948 private void _getCreateMappingTableIndex( 3949 EntityMapping entityMapping, Map<String, String> indexSQLs, 3950 Map<String, String> indexProps) 3951 throws IOException { 3952 3953 Entity[] entities = new Entity[2]; 3954 3955 for (int i = 0; i < entities.length; i++) { 3956 entities[i] = getEntity(entityMapping.getEntity(i)); 3957 3958 if (entities[i] == null) { 3959 return; 3960 } 3961 } 3962 3963 for (Entity entity : entities) { 3964 List<EntityColumn> pkList = entity.getPKList(); 3965 3966 for (int j = 0; j < pkList.size(); j++) { 3967 EntityColumn col = pkList.get(j); 3968 3969 String colDBName = col.getDBName(); 3970 3971 String indexSpec = 3972 entityMapping.getTable() + " (" + colDBName + ");"; 3973 3974 String indexHash = StringUtil.toHexString( 3975 indexSpec.hashCode()).toUpperCase(); 3976 3977 String indexName = "IX_" + indexHash; 3978 3979 StringBundler sb = new StringBundler(); 3980 3981 sb.append("create index "); 3982 sb.append(indexName); 3983 sb.append(" on "); 3984 sb.append(indexSpec); 3985 3986 indexSQLs.put(indexSpec, sb.toString()); 3987 3988 String finderName = 3989 entityMapping.getTable() + StringPool.PERIOD + colDBName; 3990 3991 indexProps.put(finderName, indexName); 3992 } 3993 } 3994 } 3995 3996 private String _getCreateMappingTableSQL(EntityMapping entityMapping) 3997 throws IOException { 3998 3999 Entity[] entities = new Entity[2]; 4000 4001 for (int i = 0; i < entities.length; i++) { 4002 entities[i] = getEntity(entityMapping.getEntity(i)); 4003 4004 if (entities[i] == null) { 4005 return null; 4006 } 4007 } 4008 4009 StringBundler sb = new StringBundler(); 4010 4011 sb.append(_SQL_CREATE_TABLE); 4012 sb.append(entityMapping.getTable()); 4013 sb.append(" (\n"); 4014 4015 for (Entity entity : entities) { 4016 List<EntityColumn> pkList = entity.getPKList(); 4017 4018 for (int i = 0; i < pkList.size(); i++) { 4019 EntityColumn col = pkList.get(i); 4020 4021 String colName = col.getName(); 4022 String colType = col.getType(); 4023 4024 sb.append("\t" + col.getDBName()); 4025 sb.append(" "); 4026 4027 if (colType.equalsIgnoreCase("boolean")) { 4028 sb.append("BOOLEAN"); 4029 } 4030 else if (colType.equalsIgnoreCase("double") || 4031 colType.equalsIgnoreCase("float")) { 4032 4033 sb.append("DOUBLE"); 4034 } 4035 else if (colType.equals("int") || 4036 colType.equals("Integer") || 4037 colType.equalsIgnoreCase("short")) { 4038 4039 sb.append("INTEGER"); 4040 } 4041 else if (colType.equalsIgnoreCase("long")) { 4042 sb.append("LONG"); 4043 } 4044 else if (colType.equals("String")) { 4045 Map<String, String> hints = ModelHintsUtil.getHints( 4046 _packagePath + ".model." + entity.getName(), colName); 4047 4048 int maxLength = 75; 4049 4050 if (hints != null) { 4051 maxLength = GetterUtil.getInteger( 4052 hints.get("max-length"), maxLength); 4053 } 4054 4055 if (col.isLocalized()) { 4056 maxLength = 4000; 4057 } 4058 4059 if (maxLength < 4000) { 4060 sb.append("VARCHAR(" + maxLength + ")"); 4061 } 4062 else if (maxLength == 4000) { 4063 sb.append("STRING"); 4064 } 4065 else if (maxLength > 4000) { 4066 sb.append("TEXT"); 4067 } 4068 } 4069 else if (colType.equals("Date")) { 4070 sb.append("DATE"); 4071 } 4072 else { 4073 sb.append("invalid"); 4074 } 4075 4076 if (col.isPrimary()) { 4077 sb.append(" not null"); 4078 } 4079 else if (colType.equals("Date") || colType.equals("String")) { 4080 sb.append(" null"); 4081 } 4082 4083 sb.append(",\n"); 4084 } 4085 } 4086 4087 sb.append("\tprimary key ("); 4088 4089 for (int i = 0; i < entities.length; i++) { 4090 Entity entity = entities[i]; 4091 4092 List<EntityColumn> pkList = entity.getPKList(); 4093 4094 for (int j = 0; j < pkList.size(); j++) { 4095 EntityColumn col = pkList.get(j); 4096 4097 String colDBName = col.getDBName(); 4098 4099 if ((i != 0) || (j != 0)) { 4100 sb.append(", "); 4101 } 4102 4103 sb.append(colDBName); 4104 } 4105 } 4106 4107 sb.append(")\n"); 4108 sb.append(");"); 4109 4110 return sb.toString(); 4111 } 4112 4113 private String _getCreateTableSQL(Entity entity) { 4114 List<EntityColumn> pkList = entity.getPKList(); 4115 List<EntityColumn> regularColList = entity.getRegularColList(); 4116 4117 if (regularColList.size() == 0) { 4118 return null; 4119 } 4120 4121 StringBundler sb = new StringBundler(); 4122 4123 sb.append(_SQL_CREATE_TABLE); 4124 sb.append(entity.getTable()); 4125 sb.append(" (\n"); 4126 4127 for (int i = 0; i < regularColList.size(); i++) { 4128 EntityColumn col = regularColList.get(i); 4129 4130 String colName = col.getName(); 4131 String colType = col.getType(); 4132 String colIdType = col.getIdType(); 4133 4134 sb.append("\t" + col.getDBName()); 4135 sb.append(" "); 4136 4137 if (colType.equalsIgnoreCase("boolean")) { 4138 sb.append("BOOLEAN"); 4139 } 4140 else if (colType.equalsIgnoreCase("double") || 4141 colType.equalsIgnoreCase("float")) { 4142 4143 sb.append("DOUBLE"); 4144 } 4145 else if (colType.equals("int") || 4146 colType.equals("Integer") || 4147 colType.equalsIgnoreCase("short")) { 4148 4149 sb.append("INTEGER"); 4150 } 4151 else if (colType.equalsIgnoreCase("long")) { 4152 sb.append("LONG"); 4153 } 4154 else if (colType.equals("Blob")) { 4155 sb.append("BLOB"); 4156 } 4157 else if (colType.equals("Date")) { 4158 sb.append("DATE"); 4159 } 4160 else if (colType.equals("String")) { 4161 Map<String, String> hints = ModelHintsUtil.getHints( 4162 _packagePath + ".model." + entity.getName(), colName); 4163 4164 int maxLength = 75; 4165 4166 if (hints != null) { 4167 maxLength = GetterUtil.getInteger( 4168 hints.get("max-length"), maxLength); 4169 } 4170 4171 if (col.isLocalized()) { 4172 maxLength = 4000; 4173 } 4174 4175 if (maxLength < 4000) { 4176 sb.append("VARCHAR(" + maxLength + ")"); 4177 } 4178 else if (maxLength == 4000) { 4179 sb.append("STRING"); 4180 } 4181 else if (maxLength > 4000) { 4182 sb.append("TEXT"); 4183 } 4184 } 4185 else { 4186 sb.append("invalid"); 4187 } 4188 4189 if (col.isPrimary()) { 4190 sb.append(" not null"); 4191 4192 if (!entity.hasCompoundPK()) { 4193 sb.append(" primary key"); 4194 } 4195 } 4196 else if (colType.equals("Date") || colType.equals("String")) { 4197 sb.append(" null"); 4198 } 4199 4200 if (Validator.isNotNull(colIdType) && 4201 colIdType.equals("identity")) { 4202 4203 sb.append(" IDENTITY"); 4204 } 4205 4206 if (((i + 1) != regularColList.size()) || 4207 entity.hasCompoundPK()) { 4208 4209 sb.append(","); 4210 } 4211 4212 sb.append("\n"); 4213 } 4214 4215 if (entity.hasCompoundPK()) { 4216 sb.append("\tprimary key ("); 4217 4218 for (int j = 0; j < pkList.size(); j++) { 4219 EntityColumn pk = pkList.get(j); 4220 4221 sb.append(pk.getDBName()); 4222 4223 if ((j + 1) != pkList.size()) { 4224 sb.append(", "); 4225 } 4226 } 4227 4228 sb.append(")\n"); 4229 } 4230 4231 sb.append(");"); 4232 4233 return sb.toString(); 4234 } 4235 4236 private String _getDimensions(Type type) { 4237 String dimensions = ""; 4238 4239 for (int i = 0; i < type.getDimensions(); i++) { 4240 dimensions += "[]"; 4241 } 4242 4243 return dimensions; 4244 } 4245 4246 private JavaClass _getJavaClass(String fileName) throws IOException { 4247 int pos = fileName.indexOf(_implDir + "/"); 4248 4249 if (pos != -1) { 4250 pos += _implDir.length(); 4251 } 4252 else { 4253 pos = fileName.indexOf(_apiDir + "/") + _apiDir.length(); 4254 } 4255 4256 String srcFile = fileName.substring(pos + 1); 4257 String className = StringUtil.replace( 4258 srcFile.substring(0, srcFile.length() - 5), "/", "."); 4259 4260 JavaClass javaClass = _javaClasses.get(className); 4261 4262 if (javaClass == null) { 4263 ClassLibrary classLibrary = new ClassLibrary(); 4264 4265 classLibrary.addClassLoader(getClass().getClassLoader()); 4266 4267 JavaDocBuilder builder = new JavaDocBuilder(classLibrary); 4268 4269 File file = new File(fileName); 4270 4271 if (!file.exists()) { 4272 return null; 4273 } 4274 4275 builder.addSource(file); 4276 4277 javaClass = builder.getClassByName(className); 4278 4279 _javaClasses.put(className, javaClass); 4280 } 4281 4282 return javaClass; 4283 } 4284 4285 private JavaMethod[] _getMethods(JavaClass javaClass) { 4286 return _getMethods(javaClass, false); 4287 } 4288 4289 private JavaMethod[] _getMethods( 4290 JavaClass javaClass, boolean superclasses) { 4291 4292 JavaMethod[] methods = javaClass.getMethods(superclasses); 4293 4294 for (JavaMethod method : methods) { 4295 Arrays.sort(method.getExceptions()); 4296 } 4297 4298 return methods; 4299 } 4300 4301 private String _getSessionTypeName(int sessionType) { 4302 if (sessionType == _SESSION_TYPE_LOCAL) { 4303 return "Local"; 4304 } 4305 else { 4306 return ""; 4307 } 4308 } 4309 4310 private String _getTplProperty(String key, String defaultValue) { 4311 return System.getProperty("service.tpl." + key, defaultValue); 4312 } 4313 4314 private List<String> _getTransients(Entity entity, boolean parent) 4315 throws Exception { 4316 4317 File modelFile = null; 4318 4319 if (parent) { 4320 modelFile = new File( 4321 _outputPath + "/model/impl/" + entity.getName() + 4322 "ModelImpl.java"); 4323 } 4324 else { 4325 modelFile = new File( 4326 _outputPath + "/model/impl/" + entity.getName() + "Impl.java"); 4327 } 4328 4329 String content = FileUtil.read(modelFile); 4330 4331 Matcher matcher = _getterPattern.matcher(content); 4332 4333 Set<String> getters = new HashSet<String>(); 4334 4335 while (!matcher.hitEnd()) { 4336 boolean found = matcher.find(); 4337 4338 if (found) { 4339 String property = matcher.group(); 4340 4341 if (property.contains("get")) { 4342 property = property.substring( 4343 property.indexOf("get") + 3, property.length() - 1); 4344 } 4345 else { 4346 property = property.substring( 4347 property.indexOf("is") + 2, property.length() - 1); 4348 } 4349 4350 if (!entity.hasColumn(property) && 4351 !entity.hasColumn(Introspector.decapitalize(property))) { 4352 4353 property = Introspector.decapitalize(property); 4354 4355 getters.add(property); 4356 } 4357 } 4358 } 4359 4360 matcher = _setterPattern.matcher(content); 4361 4362 Set<String> setters = new HashSet<String>(); 4363 4364 while (!matcher.hitEnd()) { 4365 boolean found = matcher.find(); 4366 4367 if (found) { 4368 String property = matcher.group(); 4369 4370 property = property.substring( 4371 property.indexOf("set") + 3, property.length() - 1); 4372 4373 if (!entity.hasColumn(property) && 4374 !entity.hasColumn(Introspector.decapitalize(property))) { 4375 4376 property = Introspector.decapitalize(property); 4377 4378 setters.add(property); 4379 } 4380 } 4381 } 4382 4383 getters.retainAll(setters); 4384 4385 List<String> transients = new ArrayList<String>(getters); 4386 4387 Collections.sort(transients); 4388 4389 return transients; 4390 } 4391 4392 private boolean _hasHttpMethods(JavaClass javaClass) { 4393 JavaMethod[] methods = _getMethods(javaClass); 4394 4395 for (JavaMethod javaMethod : methods) { 4396 if (!javaMethod.isConstructor() && javaMethod.isPublic() && 4397 isCustomMethod(javaMethod)) { 4398 4399 return true; 4400 } 4401 } 4402 4403 return false; 4404 } 4405 4406 private boolean _isStringLocaleMap(JavaParameter javaParameter) { 4407 Type type = javaParameter.getType(); 4408 4409 Type[] actualArgumentTypes = type.getActualTypeArguments(); 4410 4411 if (actualArgumentTypes.length != 2) { 4412 return false; 4413 } 4414 4415 if (!_isTypeValue(actualArgumentTypes[0], Locale.class.getName()) || 4416 !_isTypeValue(actualArgumentTypes[1], String.class.getName())) { 4417 4418 return false; 4419 } 4420 4421 return true; 4422 } 4423 4424 private boolean _isTargetEntity(Entity entity) { 4425 if ((_targetEntityName == null) || _targetEntityName.startsWith("$")) { 4426 return true; 4427 } 4428 4429 return _targetEntityName.equals(entity.getName()); 4430 } 4431 4432 private boolean _isTypeValue(Type type, String value) { 4433 return value.equals(type.getValue()); 4434 } 4435 4436 private List<Entity> _mergeReferenceList(List<Entity> referenceList) { 4437 List<Entity> list = new ArrayList<Entity>( 4438 _ejbList.size() + referenceList.size()); 4439 4440 list.addAll(_ejbList); 4441 list.addAll(referenceList); 4442 4443 return list; 4444 } 4445 4446 private void _parseEntity(Element entityElement) throws Exception { 4447 String ejbName = entityElement.attributeValue("name"); 4448 String humanName = entityElement.attributeValue("human-name"); 4449 4450 String table = entityElement.attributeValue("table"); 4451 4452 if (Validator.isNull(table)) { 4453 table = ejbName; 4454 4455 if (_badTableNames.contains(ejbName)) { 4456 table += StringPool.UNDERLINE; 4457 } 4458 4459 if (_autoNamespaceTables) { 4460 table = _portletShortName + StringPool.UNDERLINE + ejbName; 4461 } 4462 } 4463 4464 boolean uuid = GetterUtil.getBoolean( 4465 entityElement.attributeValue("uuid")); 4466 boolean uuidAccessor = GetterUtil.getBoolean( 4467 entityElement.attributeValue("uuid-accessor")); 4468 boolean localService = GetterUtil.getBoolean( 4469 entityElement.attributeValue("local-service")); 4470 boolean remoteService = GetterUtil.getBoolean( 4471 entityElement.attributeValue("remote-service"), true); 4472 String persistenceClass = GetterUtil.getString( 4473 entityElement.attributeValue("persistence-class"), 4474 _packagePath + ".service.persistence." + ejbName + 4475 "PersistenceImpl"); 4476 4477 String finderClass = ""; 4478 4479 if (FileUtil.exists( 4480 _outputPath + "/service/persistence/" + ejbName + 4481 "FinderImpl.java")) { 4482 4483 finderClass = 4484 _packagePath + ".service.persistence." + ejbName + "FinderImpl"; 4485 } 4486 4487 String dataSource = entityElement.attributeValue("data-source"); 4488 String sessionFactory = entityElement.attributeValue("session-factory"); 4489 String txManager = entityElement.attributeValue("tx-manager"); 4490 boolean cacheEnabled = GetterUtil.getBoolean( 4491 entityElement.attributeValue("cache-enabled"), true); 4492 boolean jsonEnabled = GetterUtil.getBoolean( 4493 entityElement.attributeValue("json-enabled"), remoteService); 4494 4495 List<EntityColumn> pkList = new ArrayList<EntityColumn>(); 4496 List<EntityColumn> regularColList = new ArrayList<EntityColumn>(); 4497 List<EntityColumn> blobList = new ArrayList<EntityColumn>(); 4498 List<EntityColumn> collectionList = new ArrayList<EntityColumn>(); 4499 List<EntityColumn> columnList = new ArrayList<EntityColumn>(); 4500 4501 List<Element> columnElements = entityElement.elements("column"); 4502 4503 boolean permissionedModel = false; 4504 4505 if (uuid) { 4506 Element columnElement = SAXReaderUtil.createElement("column"); 4507 4508 columnElement.addAttribute("name", "uuid"); 4509 columnElement.addAttribute("type", "String"); 4510 4511 columnElements.add(0, columnElement); 4512 } 4513 4514 for (Element columnElement : columnElements) { 4515 String columnName = columnElement.attributeValue("name"); 4516 4517 if (columnName.equals("resourceBlockId") && 4518 !ejbName.equals("ResourceBlock")) { 4519 4520 permissionedModel = true; 4521 } 4522 4523 String columnDBName = columnElement.attributeValue("db-name"); 4524 4525 if (Validator.isNull(columnDBName)) { 4526 columnDBName = columnName; 4527 4528 if (_badColumnNames.contains(columnName)) { 4529 columnDBName += StringPool.UNDERLINE; 4530 } 4531 } 4532 4533 String columnType = columnElement.attributeValue("type"); 4534 boolean primary = GetterUtil.getBoolean( 4535 columnElement.attributeValue("primary")); 4536 boolean accessor = GetterUtil.getBoolean( 4537 columnElement.attributeValue("accessor")); 4538 boolean filterPrimary = GetterUtil.getBoolean( 4539 columnElement.attributeValue("filter-primary")); 4540 String collectionEntity = columnElement.attributeValue("entity"); 4541 String mappingKey = columnElement.attributeValue("mapping-key"); 4542 4543 String mappingTable = columnElement.attributeValue("mapping-table"); 4544 4545 if (Validator.isNotNull(mappingTable)) { 4546 if (_badTableNames.contains(mappingTable)) { 4547 mappingTable += StringPool.UNDERLINE; 4548 } 4549 4550 if (_autoNamespaceTables) { 4551 mappingTable = 4552 _portletShortName + StringPool.UNDERLINE + mappingTable; 4553 } 4554 } 4555 4556 String idType = columnElement.attributeValue("id-type"); 4557 String idParam = columnElement.attributeValue("id-param"); 4558 boolean convertNull = GetterUtil.getBoolean( 4559 columnElement.attributeValue("convert-null"), true); 4560 boolean lazy = GetterUtil.getBoolean( 4561 columnElement.attributeValue("lazy"), true); 4562 boolean localized = GetterUtil.getBoolean( 4563 columnElement.attributeValue("localized")); 4564 boolean colJsonEnabled = GetterUtil.getBoolean( 4565 columnElement.attributeValue("json-enabled"), jsonEnabled); 4566 boolean containerModel = GetterUtil.getBoolean( 4567 columnElement.attributeValue("container-model")); 4568 boolean parentContainerModel = GetterUtil.getBoolean( 4569 columnElement.attributeValue("parent-container-model")); 4570 4571 EntityColumn col = new EntityColumn( 4572 columnName, columnDBName, columnType, primary, accessor, 4573 filterPrimary, collectionEntity, mappingKey, mappingTable, 4574 idType, idParam, convertNull, lazy, localized, colJsonEnabled, 4575 containerModel, parentContainerModel); 4576 4577 if (primary) { 4578 pkList.add(col); 4579 } 4580 4581 if (columnType.equals("Collection")) { 4582 collectionList.add(col); 4583 } 4584 else { 4585 regularColList.add(col); 4586 4587 if (columnType.equals("Blob")) { 4588 blobList.add(col); 4589 } 4590 } 4591 4592 columnList.add(col); 4593 4594 if (Validator.isNotNull(collectionEntity) && 4595 Validator.isNotNull(mappingTable)) { 4596 4597 EntityMapping entityMapping = new EntityMapping( 4598 mappingTable, ejbName, collectionEntity); 4599 4600 int ejbNameWeight = StringUtil.startsWithWeight( 4601 mappingTable, ejbName); 4602 int collectionEntityWeight = StringUtil.startsWithWeight( 4603 mappingTable, collectionEntity); 4604 4605 if ((ejbNameWeight > collectionEntityWeight) || 4606 ((ejbNameWeight == collectionEntityWeight) && 4607 (ejbName.compareTo(collectionEntity) > 0))) { 4608 4609 _entityMappings.put(mappingTable, entityMapping); 4610 } 4611 } 4612 } 4613 4614 EntityOrder order = null; 4615 4616 Element orderElement = entityElement.element("order"); 4617 4618 if (orderElement != null) { 4619 boolean asc = true; 4620 4621 if ((orderElement.attribute("by") != null) && 4622 orderElement.attributeValue("by").equals("desc")) { 4623 4624 asc = false; 4625 } 4626 4627 List<EntityColumn> orderColsList = new ArrayList<EntityColumn>(); 4628 4629 order = new EntityOrder(asc, orderColsList); 4630 4631 List<Element> orderColumnElements = orderElement.elements( 4632 "order-column"); 4633 4634 for (Element orderColElement : orderColumnElements) { 4635 String orderColName = orderColElement.attributeValue("name"); 4636 boolean orderColCaseSensitive = GetterUtil.getBoolean( 4637 orderColElement.attributeValue("case-sensitive"), true); 4638 4639 boolean orderColByAscending = asc; 4640 4641 String orderColBy = GetterUtil.getString( 4642 orderColElement.attributeValue("order-by")); 4643 4644 if (orderColBy.equals("asc")) { 4645 orderColByAscending = true; 4646 } 4647 else if (orderColBy.equals("desc")) { 4648 orderColByAscending = false; 4649 } 4650 4651 EntityColumn col = Entity.getColumn(orderColName, columnList); 4652 4653 col.setOrderColumn(true); 4654 4655 col = (EntityColumn)col.clone(); 4656 4657 col.setCaseSensitive(orderColCaseSensitive); 4658 col.setOrderByAscending(orderColByAscending); 4659 4660 orderColsList.add(col); 4661 } 4662 } 4663 4664 List<EntityFinder> finderList = new ArrayList<EntityFinder>(); 4665 4666 List<Element> finderElements = entityElement.elements("finder"); 4667 4668 if (uuid) { 4669 if (columnList.contains(new EntityColumn("companyId"))) { 4670 Element finderElement = SAXReaderUtil.createElement("finder"); 4671 4672 finderElement.addAttribute("name", "Uuid_C"); 4673 finderElement.addAttribute("return-type", "Collection"); 4674 4675 Element finderColumnElement = finderElement.addElement( 4676 "finder-column"); 4677 4678 finderColumnElement.addAttribute("name", "uuid"); 4679 4680 finderColumnElement = finderElement.addElement("finder-column"); 4681 4682 finderColumnElement.addAttribute("name", "companyId"); 4683 4684 finderElements.add(0, finderElement); 4685 } 4686 4687 if (columnList.contains(new EntityColumn("groupId"))) { 4688 Element finderElement = SAXReaderUtil.createElement("finder"); 4689 4690 finderElement.addAttribute("name", "UUID_G"); 4691 finderElement.addAttribute("return-type", ejbName); 4692 finderElement.addAttribute("unique", "true"); 4693 4694 Element finderColumnElement = finderElement.addElement( 4695 "finder-column"); 4696 4697 finderColumnElement.addAttribute("name", "uuid"); 4698 4699 finderColumnElement = finderElement.addElement("finder-column"); 4700 4701 finderColumnElement.addAttribute("name", "groupId"); 4702 4703 finderElements.add(0, finderElement); 4704 } 4705 4706 Element finderElement = SAXReaderUtil.createElement("finder"); 4707 4708 finderElement.addAttribute("name", "Uuid"); 4709 finderElement.addAttribute("return-type", "Collection"); 4710 4711 Element finderColumnElement = finderElement.addElement( 4712 "finder-column"); 4713 4714 finderColumnElement.addAttribute("name", "uuid"); 4715 4716 finderElements.add(0, finderElement); 4717 } 4718 4719 if (permissionedModel) { 4720 Element finderElement = SAXReaderUtil.createElement("finder"); 4721 4722 finderElement.addAttribute("name", "ResourceBlockId"); 4723 finderElement.addAttribute("return-type", "Collection"); 4724 4725 Element finderColumnElement = finderElement.addElement( 4726 "finder-column"); 4727 4728 finderColumnElement.addAttribute("name", "resourceBlockId"); 4729 4730 finderElements.add(0, finderElement); 4731 } 4732 4733 String alias = TextFormatter.format(ejbName, TextFormatter.I); 4734 4735 if (_badAliasNames.contains(alias.toLowerCase())) { 4736 alias += StringPool.UNDERLINE; 4737 } 4738 4739 for (Element finderElement : finderElements) { 4740 String finderName = finderElement.attributeValue("name"); 4741 String finderReturn = finderElement.attributeValue("return-type"); 4742 boolean finderUnique = GetterUtil.getBoolean( 4743 finderElement.attributeValue("unique")); 4744 4745 String finderWhere = finderElement.attributeValue("where"); 4746 4747 if (Validator.isNotNull(finderWhere)) { 4748 for (EntityColumn column : columnList) { 4749 String name = column.getName(); 4750 4751 if (finderWhere.contains(name)) { 4752 finderWhere = finderWhere.replaceAll( 4753 name, alias + "." + name); 4754 } 4755 } 4756 } 4757 4758 boolean finderDBIndex = GetterUtil.getBoolean( 4759 finderElement.attributeValue("db-index"), true); 4760 4761 List<EntityColumn> finderColsList = new ArrayList<EntityColumn>(); 4762 4763 List<Element> finderColumnElements = finderElement.elements( 4764 "finder-column"); 4765 4766 for (Element finderColumnElement : finderColumnElements) { 4767 String finderColName = finderColumnElement.attributeValue( 4768 "name"); 4769 boolean finderColCaseSensitive = GetterUtil.getBoolean( 4770 finderColumnElement.attributeValue("case-sensitive"), true); 4771 String finderColComparator = GetterUtil.getString( 4772 finderColumnElement.attributeValue("comparator"), "="); 4773 String finderColArrayableOperator = 4774 GetterUtil.getString( 4775 finderColumnElement.attributeValue( 4776 "arrayable-operator")); 4777 4778 EntityColumn col = Entity.getColumn(finderColName, columnList); 4779 4780 if (!col.isFinderPath()) { 4781 col.setFinderPath(true); 4782 } 4783 4784 col = (EntityColumn)col.clone(); 4785 4786 col.setCaseSensitive(finderColCaseSensitive); 4787 col.setComparator(finderColComparator); 4788 col.setArrayableOperator(finderColArrayableOperator); 4789 4790 finderColsList.add(col); 4791 } 4792 4793 finderList.add( 4794 new EntityFinder( 4795 finderName, finderReturn, finderUnique, finderWhere, 4796 finderDBIndex, finderColsList)); 4797 } 4798 4799 List<Entity> referenceList = new ArrayList<Entity>(); 4800 4801 if (_build) { 4802 if (Validator.isNotNull(_pluginName)) { 4803 for (String config : PropsValues.RESOURCE_ACTIONS_CONFIGS) { 4804 File file = new File(_implDir + "/" + config); 4805 4806 if (file.exists()) { 4807 InputStream inputStream = new FileInputStream(file); 4808 4809 ResourceActionsUtil.read(_pluginName, inputStream); 4810 } 4811 } 4812 } 4813 4814 List<Element> referenceElements = entityElement.elements( 4815 "reference"); 4816 4817 Set<String> referenceSet = new TreeSet<String>(); 4818 4819 for (Element referenceElement : referenceElements) { 4820 String referencePackage = referenceElement.attributeValue( 4821 "package-path"); 4822 String referenceEntity = referenceElement.attributeValue( 4823 "entity"); 4824 4825 referenceSet.add(referencePackage + "." + referenceEntity); 4826 } 4827 4828 if (!_packagePath.equals("com.liferay.counter")) { 4829 referenceSet.add("com.liferay.counter.Counter"); 4830 } 4831 4832 if (!_packagePath.equals("com.liferay.portal")) { 4833 referenceSet.add("com.liferay.portal.Resource"); 4834 referenceSet.add("com.liferay.portal.User"); 4835 } 4836 4837 for (String referenceName : referenceSet) { 4838 referenceList.add(getEntity(referenceName)); 4839 } 4840 } 4841 4842 List<String> txRequiredList = new ArrayList<String>(); 4843 4844 List<Element> txRequiredElements = entityElement.elements( 4845 "tx-required"); 4846 4847 for (Element txRequiredEl : txRequiredElements) { 4848 String txRequired = txRequiredEl.getText(); 4849 4850 txRequiredList.add(txRequired); 4851 } 4852 4853 _ejbList.add( 4854 new Entity( 4855 _packagePath, _portletName, _portletShortName, ejbName, 4856 humanName, table, alias, uuid, uuidAccessor, localService, 4857 remoteService, persistenceClass, finderClass, dataSource, 4858 sessionFactory, txManager, cacheEnabled, jsonEnabled, pkList, 4859 regularColList, blobList, collectionList, columnList, order, 4860 finderList, referenceList, txRequiredList)); 4861 } 4862 4863 private String _processTemplate(String name) throws Exception { 4864 return _processTemplate(name, _getContext()); 4865 } 4866 4867 private String _processTemplate(String name, Map<String, Object> context) 4868 throws Exception { 4869 4870 return StringUtil.strip(FreeMarkerUtil.process(name, context), '\r'); 4871 } 4872 4873 private Set<String> _readLines(String fileName) throws Exception { 4874 ClassLoader classLoader = getClass().getClassLoader(); 4875 4876 Set<String> lines = new HashSet<String>(); 4877 4878 StringUtil.readLines(classLoader.getResourceAsStream(fileName), lines); 4879 4880 return lines; 4881 } 4882 4883 private void _updateSQLFile( 4884 String sqlFileName, String createTableSQL, Entity entity) 4885 throws IOException { 4886 4887 File updateSQLFile = new File(_sqlDir + "/" + sqlFileName); 4888 4889 if (updateSQLFile.exists()) { 4890 _createSQLTables(updateSQLFile, createTableSQL, entity, false); 4891 } 4892 } 4893 4894 private static final int _SESSION_TYPE_LOCAL = 1; 4895 4896 private static final int _SESSION_TYPE_REMOTE = 0; 4897 4898 private static final String _SQL_CREATE_TABLE = "create table "; 4899 4900 private static final String _TPL_ROOT = 4901 "com/liferay/portal/tools/servicebuilder/dependencies/"; 4902 4903 private static Pattern _getterPattern = Pattern.compile( 4904 "public .* get.*" + Pattern.quote("(") + "|public boolean is.*" + 4905 Pattern.quote("(")); 4906 4907 private static Pattern _setterPattern = Pattern.compile( 4908 "public void set.*" + Pattern.quote("(")); 4909 4910 private String _apiDir; 4911 private String _author; 4912 private boolean _autoNamespaceTables; 4913 private Set<String> _badAliasNames; 4914 private Set<String> _badColumnNames; 4915 private Set<String> _badTableNames; 4916 private String _beanLocatorUtil; 4917 private String _beanLocatorUtilShortName; 4918 private boolean _build; 4919 private long _buildNumber; 4920 private boolean _buildNumberIncrement; 4921 private List<Entity> _ejbList; 4922 private Map<String, EntityMapping> _entityMappings; 4923 private Map<String, Entity> _entityPool = new HashMap<String, Entity>(); 4924 private String _hbmFileName; 4925 private String _implDir; 4926 private Map<String, JavaClass> _javaClasses = 4927 new HashMap<String, JavaClass>(); 4928 private String _modelHintsFileName; 4929 private String _ormFileName; 4930 private String _outputPath; 4931 private String _packagePath; 4932 private String _pluginName; 4933 private String _portletName = StringPool.BLANK; 4934 private String _portletPackageName = StringPool.BLANK; 4935 private String _portletShortName = StringPool.BLANK; 4936 private String _propsUtil; 4937 private String _remotingFileName; 4938 private String _serviceOutputPath; 4939 private String _springBaseFileName; 4940 private String _springClusterFileName; 4941 private String _springDynamicDataSourceFileName; 4942 private String _springFileName; 4943 private String _springHibernateFileName; 4944 private String _springInfrastructureFileName; 4945 private String _springShardDataSourceFileName; 4946 private String _sqlDir; 4947 private String _sqlFileName; 4948 private String _sqlIndexesFileName; 4949 private String _sqlIndexesPropertiesFileName; 4950 private String _sqlSequencesFileName; 4951 private String _targetEntityName; 4952 private String _testDir; 4953 private String _testOutputPath; 4954 private String _tplActionableDynamicQuery = 4955 _TPL_ROOT + "actionable_dynamic_query.ftl"; 4956 private String _tplBadAliasNames = _TPL_ROOT + "bad_alias_names.txt"; 4957 private String _tplBadColumnNames = _TPL_ROOT + "bad_column_names.txt"; 4958 private String _tplBadTableNames = _TPL_ROOT + "bad_table_names.txt"; 4959 private String _tplBlobModel = _TPL_ROOT + "blob_model.ftl"; 4960 private String _tplEjbPk = _TPL_ROOT + "ejb_pk.ftl"; 4961 private String _tplException = _TPL_ROOT + "exception.ftl"; 4962 private String _tplExtendedModel = _TPL_ROOT + "extended_model.ftl"; 4963 private String _tplExtendedModelBaseImpl = 4964 _TPL_ROOT + "extended_model_base_impl.ftl"; 4965 private String _tplExtendedModelImpl = 4966 _TPL_ROOT + "extended_model_impl.ftl"; 4967 private String _tplFinder = _TPL_ROOT + "finder.ftl"; 4968 private String _tplFinderUtil = _TPL_ROOT + "finder_util.ftl"; 4969 private String _tplHbmXml = _TPL_ROOT + "hbm_xml.ftl"; 4970 private String _tplJsonJs = _TPL_ROOT + "json_js.ftl"; 4971 private String _tplJsonJsMethod = _TPL_ROOT + "json_js_method.ftl"; 4972 private String _tplModel = _TPL_ROOT + "model.ftl"; 4973 private String _tplModelCache = _TPL_ROOT + "model_cache.ftl"; 4974 private String _tplModelClp = _TPL_ROOT + "model_clp.ftl"; 4975 private String _tplModelHintsXml = _TPL_ROOT + "model_hints_xml.ftl"; 4976 private String _tplModelImpl = _TPL_ROOT + "model_impl.ftl"; 4977 private String _tplModelSoap = _TPL_ROOT + "model_soap.ftl"; 4978 private String _tplModelWrapper = _TPL_ROOT + "model_wrapper.ftl"; 4979 private String _tplOrmXml = _TPL_ROOT + "orm_xml.ftl"; 4980 private String _tplPersistence = _TPL_ROOT + "persistence.ftl"; 4981 private String _tplPersistenceImpl = _TPL_ROOT + "persistence_impl.ftl"; 4982 private String _tplPersistenceTest = _TPL_ROOT + "persistence_test.ftl"; 4983 private String _tplPersistenceUtil = _TPL_ROOT + "persistence_util.ftl"; 4984 private String _tplProps = _TPL_ROOT + "props.ftl"; 4985 private String _tplRemotingXml = _TPL_ROOT + "remoting_xml.ftl"; 4986 private String _tplService = _TPL_ROOT + "service.ftl"; 4987 private String _tplServiceBaseImpl = _TPL_ROOT + "service_base_impl.ftl"; 4988 private String _tplServiceClp = _TPL_ROOT + "service_clp.ftl"; 4989 private String _tplServiceClpInvoker = 4990 _TPL_ROOT + "service_clp_invoker.ftl"; 4991 private String _tplServiceClpMessageListener = 4992 _TPL_ROOT + "service_clp_message_listener.ftl"; 4993 private String _tplServiceClpSerializer = 4994 _TPL_ROOT + "service_clp_serializer.ftl"; 4995 private String _tplServiceHttp = _TPL_ROOT + "service_http.ftl"; 4996 private String _tplServiceImpl = _TPL_ROOT + "service_impl.ftl"; 4997 private String _tplServiceSoap = _TPL_ROOT + "service_soap.ftl"; 4998 private String _tplServiceUtil = _TPL_ROOT + "service_util.ftl"; 4999 private String _tplServiceWrapper = _TPL_ROOT + "service_wrapper.ftl"; 5000 private String _tplSpringBaseXml = _TPL_ROOT + "spring_base_xml.ftl"; 5001 private String _tplSpringClusterXml = _TPL_ROOT + "spring_cluster_xml.ftl"; 5002 private String _tplSpringDynamicDataSourceXml = 5003 _TPL_ROOT + "spring_dynamic_data_source_xml.ftl"; 5004 private String _tplSpringHibernateXml = 5005 _TPL_ROOT + "spring_hibernate_xml.ftl"; 5006 private String _tplSpringInfrastructureXml = 5007 _TPL_ROOT + "spring_infrastructure_xml.ftl"; 5008 private String _tplSpringShardDataSourceXml = 5009 _TPL_ROOT + "spring_shard_data_source_xml.ftl"; 5010 private String _tplSpringXml = _TPL_ROOT + "spring_xml.ftl"; 5011 5012 }