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