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