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