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