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