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