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