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