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