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