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