001    /**
002     * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portal.tools.servicebuilder;
016    
017    import com.liferay.portal.freemarker.FreeMarkerUtil;
018    import com.liferay.portal.kernel.exception.PortalException;
019    import com.liferay.portal.kernel.exception.SystemException;
020    import com.liferay.portal.kernel.io.unsync.UnsyncBufferedReader;
021    import com.liferay.portal.kernel.io.unsync.UnsyncStringReader;
022    import com.liferay.portal.kernel.util.ArrayUtil;
023    import com.liferay.portal.kernel.util.ArrayUtil_IW;
024    import com.liferay.portal.kernel.util.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("destroy") ||
1687                            methodName.equals("equals") ||
1688                            methodName.equals("getClass") ||
1689                            methodName.equals("hashCode") ||
1690                            methodName.equals("notify") ||
1691                            methodName.equals("notifyAll") ||
1692                            methodName.equals("toString") ||
1693                            methodName.equals("wait")) {
1694    
1695                            return false;
1696                    }
1697                    else if (methodName.equals("getPermissionChecker")) {
1698                            return false;
1699                    }
1700                    else if ((methodName.equals("getUser")) &&
1701                                     (method.getParameters().length == 0)) {
1702    
1703                            return false;
1704                    }
1705                    else if (methodName.equals("getUserId") &&
1706                                     (method.getParameters().length == 0)) {
1707    
1708                            return false;
1709                    }
1710                    else if ((methodName.endsWith("Finder")) &&
1711                                     (methodName.startsWith("get") ||
1712                                      methodName.startsWith("set"))) {
1713    
1714                            return false;
1715                    }
1716                    else if ((methodName.endsWith("Persistence")) &&
1717                                     (methodName.startsWith("get") ||
1718                                      methodName.startsWith("set"))) {
1719    
1720                            return false;
1721                    }
1722                    else if ((methodName.endsWith("Service")) &&
1723                                     (methodName.startsWith("get") ||
1724                                      methodName.startsWith("set"))) {
1725    
1726                            return false;
1727                    }
1728                    else {
1729                            return true;
1730                    }
1731            }
1732    
1733            public boolean isDuplicateMethod(
1734                    JavaMethod method, Map<String, Object> tempMap) {
1735    
1736                    StringBuilder sb = new StringBuilder();
1737    
1738                    sb.append("isDuplicateMethod ");
1739                    sb.append(getTypeGenericsName(method.getReturns()));
1740                    sb.append(StringPool.SPACE);
1741                    sb.append(method.getName());
1742                    sb.append(StringPool.OPEN_PARENTHESIS);
1743    
1744                    JavaParameter[] parameters = method.getParameters();
1745    
1746                    for (int i = 0; i < parameters.length; i++) {
1747                            JavaParameter javaParameter = parameters[i];
1748    
1749                            sb.append(getTypeGenericsName(javaParameter.getType()));
1750    
1751                            if ((i + 1) != parameters.length) {
1752                                    sb.append(StringPool.COMMA);
1753                            }
1754                    }
1755    
1756                    sb.append(StringPool.CLOSE_PARENTHESIS);
1757    
1758                    String key = sb.toString();
1759    
1760                    if (tempMap.containsKey(key)) {
1761                            return true;
1762                    }
1763                    else {
1764                            tempMap.put(key, key);
1765    
1766                            return false;
1767                    }
1768            }
1769    
1770            public boolean isServiceReadOnlyMethod(
1771                    JavaMethod method, List<String> txRequiredList) {
1772    
1773                    return isReadOnlyMethod(
1774                            method, txRequiredList,
1775                            PropsValues.SERVICE_BUILDER_SERVICE_READ_ONLY_PREFIXES);
1776            }
1777    
1778            public boolean isReadOnlyMethod(
1779                    JavaMethod method, List<String> txRequiredList, String[] prefixes) {
1780    
1781                    String methodName = method.getName();
1782    
1783                    if (isTxRequiredMethod(method, txRequiredList)) {
1784                            return false;
1785                    }
1786    
1787                    for (String prefix : prefixes) {
1788                            if (methodName.startsWith(prefix)) {
1789                                    return true;
1790                            }
1791                    }
1792    
1793                    return false;
1794            }
1795    
1796            public boolean isSoapMethod(JavaMethod method) {
1797                    String returnTypeGenericsName = getTypeGenericsName(
1798                            method.getReturns());
1799                    String returnValueName = method.getReturns().getValue();
1800    
1801                    if (returnTypeGenericsName.equals("java.util.List<java.lang.Object>") ||
1802                            returnValueName.equals("com.liferay.portal.model.Lock") ||
1803                            returnValueName.equals(
1804                                    "com.liferay.portlet.messageboards.model.MBMessageDisplay") ||
1805                            returnValueName.startsWith("java.io") ||
1806                            returnValueName.equals("java.util.Map") ||
1807                            returnValueName.equals("java.util.Properties") ||
1808                            returnValueName.startsWith("javax")) {
1809    
1810                            return false;
1811                    }
1812    
1813                    JavaParameter[] parameters = method.getParameters();
1814    
1815                    for (JavaParameter javaParameter : parameters) {
1816                            String parameterTypeName =
1817                                    javaParameter.getType().getValue() +
1818                                            _getDimensions(javaParameter.getType());
1819    
1820                            if (parameterTypeName.equals(
1821                                            "com.liferay.portal.kernel.util.UnicodeProperties") ||
1822                                    parameterTypeName.equals(
1823                                            "com.liferay.portal.theme.ThemeDisplay") ||
1824                                    parameterTypeName.equals(
1825                                            "com.liferay.portlet.PortletPreferencesImpl") ||
1826                                    parameterTypeName.startsWith("java.io") ||
1827                                    //parameterTypeName.startsWith("java.util.List") ||
1828                                    //parameterTypeName.startsWith("java.util.Locale") ||
1829                                    parameterTypeName.startsWith("java.util.Map") ||
1830                                    parameterTypeName.startsWith("java.util.Properties") ||
1831                                    parameterTypeName.startsWith("javax")) {
1832    
1833                                    return false;
1834                            }
1835                    }
1836    
1837                    return true;
1838            }
1839    
1840            public boolean isTxRequiredMethod(
1841                    JavaMethod method, List<String> txRequiredList) {
1842    
1843                    if (txRequiredList == null) {
1844                            return false;
1845                    }
1846    
1847                    String methodName = method.getName();
1848    
1849                    for (String txRequired : txRequiredList) {
1850                            if (methodName.equals(txRequired)) {
1851                                    return true;
1852                            }
1853                    }
1854    
1855                    return false;
1856            }
1857    
1858            private static String _getPackagePath(File file) {
1859                    String fileName = StringUtil.replace(file.toString(), "\\", "/");
1860    
1861                    int x = fileName.indexOf("src/");
1862    
1863                    if (x == -1) {
1864                            x = fileName.indexOf("test/");
1865                    }
1866    
1867                    int y = fileName.lastIndexOf("/");
1868    
1869                    fileName = fileName.substring(x + 4, y);
1870    
1871                    return StringUtil.replace(fileName, "/", ".");
1872            }
1873    
1874            private void _createEJBPK(Entity entity) throws Exception {
1875                    Map<String, Object> context = _getContext();
1876    
1877                    context.put("entity", entity);
1878    
1879                    // Content
1880    
1881                    String content = _processTemplate(_tplEjbPk, context);
1882    
1883                    // Write file
1884    
1885                    File ejbFile = new File(
1886                            _serviceOutputPath + "/service/persistence/" +
1887                                    entity.getPKClassName() + ".java");
1888    
1889                    writeFile(ejbFile, content, _author);
1890            }
1891    
1892            private void _createExceptions(List<String> exceptions) throws Exception {
1893                    for (int i = 0; i < _ejbList.size(); i++) {
1894                            Entity entity = _ejbList.get(i);
1895    
1896                            if (entity.hasColumns()) {
1897                                    exceptions.add(getNoSuchEntityException(entity));
1898                            }
1899                    }
1900    
1901                    for (String exception : exceptions) {
1902                            File exceptionFile = new File(
1903                                    _serviceOutputPath + "/" + exception + "Exception.java");
1904    
1905                            if (!exceptionFile.exists()) {
1906                                    Map<String, Object> context = _getContext();
1907    
1908                                    context.put("exception", exception);
1909    
1910                                    String content = _processTemplate(_tplException, context);
1911    
1912                                    if (exception.startsWith("NoSuch")) {
1913                                            content = StringUtil.replace(
1914                                                    content, "PortalException", "NoSuchModelException");
1915                                            content = StringUtil.replace(
1916                                                    content, "kernel.exception.NoSuchModelException",
1917                                                    "NoSuchModelException");
1918                                    }
1919    
1920                                    content = StringUtil.replace(content, "\r\n", "\n");
1921    
1922                                    FileUtil.write(exceptionFile, content);
1923                            }
1924    
1925                            if (exception.startsWith("NoSuch")) {
1926                                    String content = FileUtil.read(exceptionFile);
1927    
1928                                    if (!content.contains("NoSuchModelException")) {
1929                                            content = StringUtil.replace(
1930                                                    content, "PortalException", "NoSuchModelException");
1931                                            content = StringUtil.replace(
1932                                                    content, "kernel.exception.NoSuchModelException",
1933                                                    "NoSuchModelException");
1934    
1935                                            FileUtil.write(exceptionFile, content);
1936                                    }
1937                            }
1938    
1939                            if (!_serviceOutputPath.equals(_outputPath)) {
1940                                    exceptionFile = new File(
1941                                            _outputPath + "/" + exception + "Exception.java");
1942    
1943                                    if (exceptionFile.exists()) {
1944                                            System.out.println("Relocating " + exceptionFile);
1945    
1946                                            exceptionFile.delete();
1947                                    }
1948                            }
1949                    }
1950            }
1951    
1952            private void _createExtendedModel(Entity entity) throws Exception {
1953                    JavaClass javaClass = _getJavaClass(
1954                            _outputPath + "/model/impl/" + entity.getName() + "Impl.java");
1955    
1956                    Map<String, Object> context = _getContext();
1957    
1958                    context.put("entity", entity);
1959                    context.put("methods", _getMethods(javaClass));
1960    
1961                    // Content
1962    
1963                    String content = _processTemplate(_tplExtendedModel, context);
1964    
1965                    // Write file
1966    
1967                    File modelFile = new File(
1968                            _serviceOutputPath + "/model/" + entity.getName() + ".java");
1969    
1970                    writeFile(modelFile, content, _author);
1971    
1972                    if (!_serviceOutputPath.equals(_outputPath)) {
1973                            modelFile = new File(
1974                                    _outputPath + "/model/" + entity.getName() + ".java");
1975    
1976                            if (modelFile.exists()) {
1977                                    System.out.println("Relocating " + modelFile);
1978    
1979                                    modelFile.delete();
1980                            }
1981                    }
1982            }
1983    
1984            private void _createExtendedModelImpl(Entity entity) throws Exception {
1985                    Map<String, Object> context = _getContext();
1986    
1987                    context.put("entity", entity);
1988    
1989                    // Content
1990    
1991                    String content = _processTemplate(_tplExtendedModelImpl, context);
1992    
1993                    // Write file
1994    
1995                    File modelFile = new File(
1996                            _outputPath + "/model/impl/" + entity.getName() + "Impl.java");
1997    
1998                    if (!modelFile.exists()) {
1999                            writeFile(modelFile, content, _author);
2000                    }
2001            }
2002    
2003            private void _createFinder(Entity entity) throws Exception {
2004                    if (!entity.hasFinderClass()) {
2005                            return;
2006                    }
2007    
2008                    JavaClass javaClass = _getJavaClass(
2009                            _outputPath + "/service/persistence/" + entity.getName() +
2010                                    "FinderImpl.java");
2011    
2012                    Map<String, Object> context = _getContext();
2013    
2014                    context.put("entity", entity);
2015                    context.put("methods", _getMethods(javaClass));
2016    
2017                    // Content
2018    
2019                    String content = _processTemplate(_tplFinder, context);
2020    
2021                    // Write file
2022    
2023                    File ejbFile = new File(
2024                            _serviceOutputPath + "/service/persistence/" + entity.getName() +
2025                                    "Finder.java");
2026    
2027                    writeFile(ejbFile, content, _author);
2028    
2029                    if (!_serviceOutputPath.equals(_outputPath)) {
2030                            ejbFile = new File(
2031                                    _outputPath + "/service/persistence/" + entity.getName() +
2032                                            "Finder.java");
2033    
2034                            if (ejbFile.exists()) {
2035                                    System.out.println("Relocating " + ejbFile);
2036    
2037                                    ejbFile.delete();
2038                            }
2039                    }
2040            }
2041    
2042            private void _createFinderUtil(Entity entity) throws Exception {
2043                    if (!entity.hasFinderClass()) {
2044                            return;
2045                    }
2046    
2047                    JavaClass javaClass = _getJavaClass(
2048                            _outputPath + "/service/persistence/" + entity.getName() +
2049                                    "FinderImpl.java");
2050    
2051                    Map<String, Object> context = _getContext();
2052    
2053                    context.put("entity", entity);
2054                    context.put("methods", _getMethods(javaClass));
2055    
2056                    // Content
2057    
2058                    String content = _processTemplate(_tplFinderUtil, context);
2059    
2060                    // Write file
2061    
2062                    File ejbFile = new File(
2063                            _serviceOutputPath + "/service/persistence/" + entity.getName() +
2064                                    "FinderUtil.java");
2065    
2066                    writeFile(ejbFile, content, _author);
2067    
2068                    if (!_serviceOutputPath.equals(_outputPath)) {
2069                            ejbFile = new File(
2070                                    _outputPath + "/service/persistence/" + entity.getName() +
2071                                            "FinderUtil.java");
2072    
2073                            if (ejbFile.exists()) {
2074                                    System.out.println("Relocating " + ejbFile);
2075    
2076                                    ejbFile.delete();
2077                            }
2078                    }
2079            }
2080    
2081            private void _createHbm(Entity entity) {
2082                    File ejbFile = new File(
2083                            _outputPath + "/service/persistence/" + entity.getName() +
2084                                    "HBM.java");
2085    
2086                    if (ejbFile.exists()) {
2087                            System.out.println("Removing deprecated " + ejbFile);
2088    
2089                            ejbFile.delete();
2090                    }
2091            }
2092    
2093            private void _createHbmUtil(Entity entity) {
2094                    File ejbFile = new File(
2095                            _outputPath + "/service/persistence/" + entity.getName() +
2096                                    "HBMUtil.java");
2097    
2098                    if (ejbFile.exists()) {
2099                            System.out.println("Removing deprecated " + ejbFile);
2100    
2101                            ejbFile.delete();
2102                    }
2103            }
2104    
2105            private void _createHbmXml() throws Exception {
2106                    Map<String, Object> context = _getContext();
2107    
2108                    context.put("entities", _ejbList);
2109    
2110                    // Content
2111    
2112                    String content = _processTemplate(_tplHbmXml, context);
2113    
2114                    int lastImportStart = content.lastIndexOf("<import class=");
2115                    int lastImportEnd = content.indexOf("/>", lastImportStart) + 3;
2116    
2117                    String imports = content.substring(0, lastImportEnd);
2118    
2119                    content = content.substring(lastImportEnd + 1);
2120    
2121                    File xmlFile = new File(_hbmFileName);
2122    
2123                    if (!xmlFile.exists()) {
2124                            String xml =
2125                                    "<?xml version=\"1.0\"?>\n" +
2126                                    "<!DOCTYPE hibernate-mapping PUBLIC \"-//Hibernate/Hibernate Mapping DTD 3.0//EN\" \"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd\">\n" +
2127                                    "\n" +
2128                                    "<hibernate-mapping default-lazy=\"false\" auto-import=\"false\">\n" +
2129                                    "</hibernate-mapping>";
2130    
2131                            FileUtil.write(xmlFile, xml);
2132                    }
2133    
2134                    String oldContent = FileUtil.read(xmlFile);
2135                    String newContent = _fixHbmXml(oldContent);
2136    
2137                    int firstImport = newContent.indexOf(
2138                            "<import class=\"" + _packagePath + ".model.");
2139                    int lastImport = newContent.lastIndexOf(
2140                            "<import class=\"" + _packagePath + ".model.");
2141    
2142                    if (firstImport == -1) {
2143                            int x = newContent.indexOf("<class");
2144    
2145                            if (x != -1) {
2146                                    newContent =
2147                                            newContent.substring(0, x) + imports +
2148                                                    newContent.substring(x);
2149                            }
2150                            else {
2151                                    content = imports + content;
2152                            }
2153                    }
2154                    else {
2155                            firstImport = newContent.indexOf("<import", firstImport) - 1;
2156                            lastImport = newContent.indexOf("/>", lastImport) + 3;
2157    
2158                            newContent =
2159                                    newContent.substring(0, firstImport) + imports +
2160                                            newContent.substring(lastImport);
2161                    }
2162    
2163                    int firstClass = newContent.indexOf(
2164                            "<class name=\"" + _packagePath + ".model.impl.");
2165                    int lastClass = newContent.lastIndexOf(
2166                            "<class name=\"" + _packagePath + ".model.impl.");
2167    
2168                    if (firstClass == -1) {
2169                            int x = newContent.indexOf("</hibernate-mapping>");
2170    
2171                            if (x != -1) {
2172                                    newContent =
2173                                            newContent.substring(0, x) + content +
2174                                                    newContent.substring(x, newContent.length());
2175                            }
2176                    }
2177                    else {
2178                            firstClass = newContent.lastIndexOf("<class", firstClass) - 1;
2179                            lastClass = newContent.indexOf("</class>", lastClass) + 9;
2180    
2181                            newContent =
2182                                    newContent.substring(0, firstClass) + content +
2183                                            newContent.substring(lastClass, newContent.length());
2184                    }
2185    
2186                    newContent = _formatXml(newContent);
2187    
2188                    if (!oldContent.equals(newContent)) {
2189                            FileUtil.write(xmlFile, newContent);
2190                    }
2191            }
2192    
2193            private void _createJsonJs() throws Exception {
2194                    if (_packagePath.equals("com.liferay.counter")) {
2195                            return;
2196                    }
2197    
2198                    if (Validator.isNotNull(_pluginName)) {
2199                            boolean hasRemoteService = false;
2200    
2201                            for (int i = 0; i < _ejbList.size(); i++) {
2202                                    Entity entity = _ejbList.get(i);
2203    
2204                                    if (entity.hasRemoteService()) {
2205                                            hasRemoteService = true;
2206    
2207                                            break;
2208                                    }
2209                            }
2210    
2211                            if (!hasRemoteService) {
2212                                    return;
2213                            }
2214                    }
2215    
2216                    StringBuilder sb = new StringBuilder();
2217    
2218                    if (_ejbList.size() > 0) {
2219                            sb.append(_processTemplate(_tplJsonJs));
2220                    }
2221    
2222                    for (int i = 0; i < _ejbList.size(); i++) {
2223                            Entity entity = _ejbList.get(i);
2224    
2225                            if (entity.hasRemoteService()) {
2226                                    JavaClass javaClass = _getJavaClass(
2227                                            _serviceOutputPath + "/service/" + entity.getName() +
2228                                                    "Service.java");
2229    
2230                                    JavaMethod[] methods = _getMethods(javaClass);
2231    
2232                                    Set<String> jsonMethods = new LinkedHashSet<String>();
2233    
2234                                    for (JavaMethod method : methods) {
2235                                            String methodName = method.getName();
2236                                            String returnValue = getReturnType(method);
2237    
2238                                            boolean badJsonType = false;
2239    
2240                                            for (JavaParameter parameter: method.getParameters()) {
2241                                                    String parameterType = getParameterType(parameter);
2242    
2243                                                    if (_badJsonTypes.contains(parameterType)) {
2244                                                            badJsonType = true;
2245                                                    }
2246                                            }
2247    
2248                                            if (method.isPublic() &&
2249                                                    !_badJsonTypes.contains(returnValue) && !badJsonType) {
2250    
2251                                                    jsonMethods.add(methodName);
2252                                            }
2253                                    }
2254    
2255                                    if (jsonMethods.size() > 0) {
2256                                            Map<String, Object> context = _getContext();
2257    
2258                                            context.put("entity", entity);
2259                                            context.put("methods", jsonMethods);
2260    
2261                                            sb.append("\n\n");
2262                                            sb.append(_processTemplate(_tplJsonJsMethod, context));
2263                                    }
2264                            }
2265                    }
2266    
2267                    File jsonFile = new File(_jsonFileName);
2268    
2269                    if (!jsonFile.exists()) {
2270                            FileUtil.write(jsonFile, "");
2271                    }
2272    
2273                    String oldContent = FileUtil.read(jsonFile);
2274                    String newContent = oldContent;
2275    
2276                    int oldBegin = oldContent.indexOf(
2277                            "Liferay.Service.register(\"Liferay.Service." + _portletShortName);
2278    
2279                    int oldEnd = oldContent.lastIndexOf(
2280                            "Liferay.Service." + _portletShortName);
2281    
2282                    oldEnd = oldContent.indexOf(");", oldEnd);
2283    
2284                    int newBegin = newContent.indexOf(
2285                            "Liferay.Service.register(\"Liferay.Service." + _portletShortName);
2286    
2287                    int newEnd = newContent.lastIndexOf(
2288                            "Liferay.Service." + _portletShortName);
2289    
2290                    newEnd = newContent.indexOf(");", newEnd);
2291    
2292                    if (newBegin == -1) {
2293                            newContent = oldContent + "\n\n" + sb.toString().trim();
2294                    }
2295                    else {
2296                            newContent =
2297                                    newContent.substring(0, oldBegin) + sb.toString().trim() +
2298                                            newContent.substring(oldEnd + 2, newContent.length());
2299                    }
2300    
2301                    newContent = newContent.trim();
2302    
2303                    if (!oldContent.equals(newContent)) {
2304                            FileUtil.write(jsonFile, newContent);
2305                    }
2306            }
2307    
2308            private void _createModel(Entity entity) throws Exception {
2309                    Map<String, Object> context = _getContext();
2310    
2311                    context.put("entity", entity);
2312    
2313                    // Content
2314    
2315                    String content = _processTemplate(_tplModel, context);
2316    
2317                    // Write file
2318    
2319                    File modelFile = new File(
2320                            _serviceOutputPath + "/model/" + entity.getName() + "Model.java");
2321    
2322                    writeFile(modelFile, content, _author);
2323    
2324                    if (!_serviceOutputPath.equals(_outputPath)) {
2325                            modelFile = new File(
2326                                    _outputPath + "/model/" + entity.getName() + "Model.java");
2327    
2328                            if (modelFile.exists()) {
2329                                    System.out.println("Relocating " + modelFile);
2330    
2331                                    modelFile.delete();
2332                            }
2333                    }
2334            }
2335    
2336            private void _createModelClp(Entity entity) throws Exception {
2337                    if (Validator.isNull(_pluginName)) {
2338                            return;
2339                    }
2340    
2341                    JavaClass javaClass = _getJavaClass(
2342                            _outputPath + "/model/impl/" + entity.getName() + "Impl.java");
2343    
2344                    Map<String, Object> context = _getContext();
2345    
2346                    context.put("entity", entity);
2347                    context.put("methods", _getMethods(javaClass));
2348    
2349                    // Content
2350    
2351                    String content = _processTemplate(_tplModelClp, context);
2352    
2353                    // Write file
2354    
2355                    File modelFile = new File(
2356                            _serviceOutputPath + "/model/" + entity.getName() + "Clp.java");
2357    
2358                    writeFile(modelFile, content, _author);
2359            }
2360    
2361            private void _createModelHintsXml() throws Exception {
2362                    Map<String, Object> context = _getContext();
2363    
2364                    context.put("entities", _ejbList);
2365    
2366                    // Content
2367    
2368                    String content = _processTemplate(_tplModelHintsXml, context);
2369    
2370                    File xmlFile = new File(_modelHintsFileName);
2371    
2372                    if (!xmlFile.exists()) {
2373                            String xml =
2374                                    "<?xml version=\"1.0\"?>\n" +
2375                                    "\n" +
2376                                    "<model-hints>\n" +
2377                                    "</model-hints>";
2378    
2379                            FileUtil.write(xmlFile, xml);
2380                    }
2381    
2382                    String oldContent = FileUtil.read(xmlFile);
2383                    String newContent = oldContent;
2384    
2385                    int firstModel = newContent.indexOf(
2386                            "<model name=\"" + _packagePath + ".model.");
2387                    int lastModel = newContent.lastIndexOf(
2388                            "<model name=\"" + _packagePath + ".model.");
2389    
2390                    if (firstModel == -1) {
2391                            int x = newContent.indexOf("</model-hints>");
2392    
2393                            newContent =
2394                                    newContent.substring(0, x) + content +
2395                                            newContent.substring(x, newContent.length());
2396                    }
2397                    else {
2398                            firstModel = newContent.lastIndexOf("<model", firstModel) - 1;
2399                            lastModel = newContent.indexOf("</model>", lastModel) + 9;
2400    
2401                            newContent =
2402                                    newContent.substring(0, firstModel) + content +
2403                                    newContent.substring(lastModel, newContent.length());
2404                    }
2405    
2406                    newContent = _formatXml(newContent);
2407    
2408                    if (!oldContent.equals(newContent)) {
2409                            FileUtil.write(xmlFile, newContent);
2410                    }
2411            }
2412    
2413            private void _createModelImpl(Entity entity) throws Exception {
2414                    Map<String, Object> context = _getContext();
2415    
2416                    context.put("entity", entity);
2417    
2418                    // Content
2419    
2420                    String content = _processTemplate(_tplModelImpl, context);
2421    
2422                    // Write file
2423    
2424                    File modelFile = new File(
2425                            _outputPath + "/model/impl/" + entity.getName() + "ModelImpl.java");
2426    
2427                    writeFile(modelFile, content, _author);
2428            }
2429    
2430            private void _createModelSoap(Entity entity) throws Exception {
2431                    File modelFile = null;
2432    
2433                    if (!_serviceOutputPath.equals(_outputPath)) {
2434                            modelFile = new File(
2435                                    _outputPath + "/model/" + entity.getName() + "Soap.java");
2436    
2437                            if (modelFile.exists()) {
2438                                    System.out.println("Relocating " + modelFile);
2439    
2440                                    modelFile.delete();
2441                            }
2442                    }
2443    
2444                    modelFile = new File(
2445                            _serviceOutputPath + "/model/" + entity.getName() + "Soap.java");
2446    
2447                    if (!entity.hasRemoteService()) {
2448                            if (modelFile.exists()) {
2449                                    System.out.println("Removing " + modelFile);
2450    
2451                                    modelFile.delete();
2452                            }
2453    
2454                            return;
2455                    }
2456    
2457                    Map<String, Object> context = _getContext();
2458    
2459                    context.put("entity", entity);
2460    
2461                    // Content
2462    
2463                    String content = _processTemplate(_tplModelSoap, context);
2464    
2465                    // Write file
2466    
2467                    writeFile(modelFile, content, _author);
2468            }
2469    
2470            private void _createModelWrapper(Entity entity) throws Exception {
2471                    JavaClass modelJavaClass = _getJavaClass(
2472                            _serviceOutputPath + "/model/" + entity.getName() + "Model.java");
2473                    JavaClass extendedModelJavaClass = _getJavaClass(
2474                            _serviceOutputPath + "/model/" + entity.getName() + ".java");
2475    
2476                    Object[] methods = _getMethods(modelJavaClass);
2477    
2478                    methods = ArrayUtil.append(
2479                            methods, _getMethods(extendedModelJavaClass));
2480    
2481                    Map<String, Object> context = _getContext();
2482    
2483                    context.put("entity", entity);
2484                    context.put("methods", methods);
2485    
2486                    // Content
2487    
2488                    String content = _processTemplate(_tplModelWrapper, context);
2489    
2490                    // Write file
2491    
2492                    File modelFile = new File(
2493                            _serviceOutputPath + "/model/" + entity.getName() + "Wrapper.java");
2494    
2495                    writeFile(modelFile, content, _author);
2496            }
2497    
2498            private void _createOrmXml() throws Exception {
2499                    Map<String, Object> context = _getContext();
2500    
2501                    context.put("entities", _ejbList);
2502    
2503                    // Content
2504    
2505                    String content = _processTemplate(_tplOrmXml, context);
2506    
2507                    String mappedClasses = "";
2508    
2509                    int lastMappedClassStart = content.lastIndexOf("<mapped-superclass");
2510    
2511                    if (lastMappedClassStart != -1) {
2512                            int lastMappedClassEnd = content.indexOf(
2513                                    "</mapped-superclass>", lastMappedClassStart) + 20;
2514    
2515                            mappedClasses  = content.substring(0, lastMappedClassEnd);
2516    
2517                            content = content.substring(lastMappedClassEnd + 1);
2518                    }
2519    
2520                    File xmlFile = new File(_ormFileName);
2521    
2522                    if (!xmlFile.exists()) {
2523                            String xml =
2524                                    "<?xml version=\"1.0\"?>\n" +
2525                                    "<entity-mappings version=\"1.0\" xmlns=\"http://java.sun.com/xml/ns/persistence/orm\"\n" +
2526                                    "\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
2527                                    "\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_1_0.xsd\"\n" +
2528                                    ">\n" +
2529                                    "<persistence-unit-metadata>\n" +
2530                                    "\t<xml-mapping-metadata-complete />\n" +
2531                                    "\t<persistence-unit-defaults>\n" +
2532                                    "\t\t<access>PROPERTY</access>\n" +
2533                                    "\t</persistence-unit-defaults>\n" +
2534                                    "</persistence-unit-metadata>\n" +
2535                                    "</entity-mappings>";
2536    
2537                            FileUtil.write(xmlFile, xml);
2538                    }
2539    
2540                    String oldContent = FileUtil.read(xmlFile);
2541                    String newContent = oldContent;
2542    
2543                    int firstMappedClass = newContent.indexOf(
2544                            "<mapped-superclass class=\"" + _packagePath + ".model.");
2545                    int lastMappedClass = newContent.lastIndexOf(
2546                            "<mapped-superclass class=\"" + _packagePath + ".model.");
2547    
2548                    if (firstMappedClass == -1) {
2549                            int x = newContent.indexOf("<entity class=");
2550    
2551                            if (x != -1) {
2552                                    newContent =
2553                                            newContent.substring(0, x) + mappedClasses +
2554                                                    newContent.substring(x);
2555                            }
2556                            else {
2557                                    content = mappedClasses + content;
2558                            }
2559                    }
2560                    else {
2561                            firstMappedClass = newContent.indexOf(
2562                                    "<mapped-superclass", firstMappedClass) - 1;
2563                            lastMappedClass = newContent.indexOf(
2564                                    "</mapped-superclass>", lastMappedClass) + 20;
2565    
2566                            newContent =
2567                                    newContent.substring(0, firstMappedClass) + mappedClasses +
2568                                            newContent.substring(lastMappedClass);
2569                    }
2570    
2571                    int firstEntity = newContent.indexOf(
2572                            "<entity class=\"" + _packagePath + ".model.impl.");
2573                    int lastEntity = newContent.lastIndexOf(
2574                            "<entity class=\"" + _packagePath + ".model.impl.");
2575    
2576                    if (firstEntity == -1) {
2577                            int x = newContent.indexOf("</entity-mappings>");
2578    
2579                            if (x != -1) {
2580                                    newContent =
2581                                            newContent.substring(0, x) + content +
2582                                                    newContent.substring(x, newContent.length());
2583                            }
2584                    }
2585                    else {
2586                            firstEntity = newContent.lastIndexOf("<entity", firstEntity) - 1;
2587                            lastEntity = newContent.indexOf("</entity>", lastEntity) + 9;
2588    
2589                            newContent =
2590                                    newContent.substring(0, firstEntity) + content +
2591                                            newContent.substring(lastEntity, newContent.length());
2592                    }
2593    
2594                    newContent = _formatXml(newContent);
2595    
2596                    newContent = StringUtil.replace(
2597                            newContent,
2598                            new String[] {"<attributes></attributes>", "<attributes/>"},
2599                            new String[] {"<attributes />", "<attributes />"});
2600    
2601                    if (!oldContent.equals(newContent)) {
2602                            FileUtil.write(xmlFile, newContent);
2603                    }
2604            }
2605    
2606            private void _createPersistence(Entity entity) throws Exception {
2607                    JavaClass javaClass = _getJavaClass(
2608                            _outputPath + "/service/persistence/" + entity.getName() +
2609                                    "PersistenceImpl.java");
2610    
2611                    Map<String, Object> context = _getContext();
2612    
2613                    context.put("entity", entity);
2614                    context.put("methods", _getMethods(javaClass));
2615    
2616                    // Content
2617    
2618                    String content = _processTemplate(_tplPersistence, context);
2619    
2620                    // Write file
2621    
2622                    File ejbFile = new File(
2623                            _serviceOutputPath + "/service/persistence/" + entity.getName() +
2624                                    "Persistence.java");
2625    
2626                    writeFile(ejbFile, content, _author);
2627    
2628                    if (!_serviceOutputPath.equals(_outputPath)) {
2629                            ejbFile = new File(
2630                                    _outputPath + "/service/persistence/" + entity.getName() +
2631                                            "Persistence.java");
2632    
2633                            if (ejbFile.exists()) {
2634                                    System.out.println("Relocating " + ejbFile);
2635    
2636                                    ejbFile.delete();
2637                            }
2638                    }
2639            }
2640    
2641            private void _createPersistenceImpl(Entity entity) throws Exception {
2642                    Map<String, Object> context = _getContext();
2643    
2644                    context.put("entity", entity);
2645                    context.put(
2646                            "referenceList", _mergeReferenceList(entity.getReferenceList()));
2647    
2648                    // Content
2649    
2650                    Logger.selectLoggerLibrary(Logger.LIBRARY_NONE);
2651    
2652                    String content = _processTemplate(_tplPersistenceImpl, context);
2653    
2654                    Logger.selectLoggerLibrary(Logger.LIBRARY_AUTO);
2655    
2656                    // Write file
2657    
2658                    File ejbFile = new File(
2659                            _outputPath + "/service/persistence/" + entity.getName() +
2660                                    "PersistenceImpl.java");
2661    
2662                    writeFile(ejbFile, content, _author);
2663            }
2664    
2665            private void _createPersistenceTest(Entity entity) throws Exception {
2666                    Map<String, Object> context = _getContext();
2667    
2668                    context.put("entity", entity);
2669    
2670                    // Content
2671    
2672                    String content = _processTemplate(_tplPersistenceTest, context);
2673    
2674                    // Write file
2675    
2676                    File ejbFile = new File(
2677                            _testOutputPath + "/service/persistence/" + entity.getName() +
2678                                    "PersistenceTest.java");
2679    
2680                    writeFile(ejbFile, content, _author);
2681            }
2682    
2683            private void _createPersistenceUtil(Entity entity) throws Exception {
2684                    JavaClass javaClass = _getJavaClass(
2685                            _outputPath + "/service/persistence/" + entity.getName() +
2686                                    "PersistenceImpl.java");
2687    
2688                    Map<String, Object> context = _getContext();
2689    
2690                    context.put("entity", entity);
2691                    context.put("methods", _getMethods(javaClass));
2692    
2693                    // Content
2694    
2695                    String content = _processTemplate(_tplPersistenceUtil, context);
2696    
2697                    // Write file
2698    
2699                    File ejbFile = new File(
2700                            _serviceOutputPath + "/service/persistence/" + entity.getName() +
2701                                    "Util.java");
2702    
2703                    writeFile(ejbFile, content, _author);
2704    
2705                    if (!_serviceOutputPath.equals(_outputPath)) {
2706                            ejbFile = new File(
2707                                    _outputPath + "/service/persistence/" + entity.getName() +
2708                                            "Util.java");
2709    
2710                            if (ejbFile.exists()) {
2711                                    System.out.println("Relocating " + ejbFile);
2712    
2713                                    ejbFile.delete();
2714                            }
2715                    }
2716            }
2717    
2718            private void _createPool(Entity entity) {
2719                    File ejbFile = new File(
2720                            _outputPath + "/service/persistence/" + entity.getName() +
2721                                    "Pool.java");
2722    
2723                    if (ejbFile.exists()) {
2724                            System.out.println("Removing deprecated " + ejbFile);
2725    
2726                            ejbFile.delete();
2727                    }
2728            }
2729    
2730            private void _createProps() throws Exception {
2731                    if (Validator.isNull(_pluginName)) {
2732                            return;
2733                    }
2734    
2735                    // Content
2736    
2737                    File propsFile = new File(_implDir + "/service.properties");
2738    
2739                    long buildNumber = 1;
2740    
2741                    if (propsFile.exists()) {
2742                            Properties props = PropertiesUtil.load(FileUtil.read(propsFile));
2743    
2744                            buildNumber = GetterUtil.getLong(
2745                                    props.getProperty("build.number")) + 1;
2746                    }
2747    
2748                    Map<String, Object> context = _getContext();
2749    
2750                    context.put("buildNumber", new Long(buildNumber));
2751                    context.put("currentTimeMillis", new Long(System.currentTimeMillis()));
2752    
2753                    String content = _processTemplate(_tplProps, context);
2754    
2755                    // Write file
2756    
2757                    FileUtil.write(propsFile, content, true);
2758            }
2759    
2760            private void _createRemotingXml() throws Exception {
2761                    StringBuilder sb = new StringBuilder();
2762    
2763                    Document doc = SAXReaderUtil.read(new File(_springFileName));
2764    
2765                    Iterator<Element> itr = doc.getRootElement().elements(
2766                            "bean").iterator();
2767    
2768                    while (itr.hasNext()) {
2769                            Element beanEl = itr.next();
2770    
2771                            String beanId = beanEl.attributeValue("id");
2772    
2773                            if (beanId.endsWith("Service") &&
2774                                    !beanId.endsWith("LocalService")) {
2775    
2776                                    String entityName = beanId;
2777    
2778                                    entityName = StringUtil.replaceLast(entityName, ".service.", ".");
2779    
2780                                    int pos = entityName.lastIndexOf("Service");
2781    
2782                                    entityName = entityName.substring(0, pos);
2783    
2784                                    Entity entity = getEntity(entityName);
2785    
2786                                    String serviceName = beanId;
2787    
2788                                    String serviceMapping = serviceName;
2789    
2790                                    serviceMapping = StringUtil.replaceLast(
2791                                            serviceMapping, ".service.", ".service.spring.");
2792                                    serviceMapping = StringUtil.replace(
2793                                            serviceMapping, StringPool.PERIOD, StringPool.UNDERLINE);
2794    
2795                                    Map<String, Object> context = _getContext();
2796    
2797                                    context.put("entity", entity);
2798                                    context.put("serviceName", serviceName);
2799                                    context.put("serviceMapping", serviceMapping);
2800    
2801                                    sb.append(_processTemplate(_tplRemotingXml, context));
2802                            }
2803                    }
2804    
2805                    File outputFile = new File(_remotingFileName);
2806    
2807                    if (!outputFile.exists()) {
2808                            return;
2809                    }
2810    
2811                    String content = FileUtil.read(outputFile);
2812                    String newContent = content;
2813    
2814                    int x = content.indexOf("<bean ");
2815                    int y = content.lastIndexOf("</bean>") + 8;
2816    
2817                    if (x != -1) {
2818                            newContent =
2819                                    content.substring(0, x - 1) + sb.toString() +
2820                                            content.substring(y, content.length());
2821                    }
2822                    else {
2823                            x = content.indexOf("</beans>");
2824    
2825                            if (x != -1) {
2826                                    newContent =
2827                                            content.substring(0, x) + sb.toString() +
2828                                                    content.substring(x, content.length());
2829                            }
2830                            else {
2831                                    x = content.indexOf("<beans/>");
2832                                    y = x + 8;
2833    
2834                                    newContent =
2835                                            content.substring(0, x) + "<beans>" + sb.toString() +
2836                                                    "</beans>" + content.substring(y, content.length());
2837                            }
2838                    }
2839    
2840                    newContent = _formatXml(newContent);
2841    
2842                    if (!content.equals(newContent)) {
2843                            FileUtil.write(outputFile, newContent);
2844    
2845                            System.out.println(outputFile.toString());
2846                    }
2847            }
2848    
2849            private void _createService(Entity entity, int sessionType)
2850                    throws Exception {
2851    
2852                    JavaClass javaClass = _getJavaClass(_outputPath + "/service/impl/" + entity.getName() + (sessionType != _SESSION_TYPE_REMOTE ? "Local" : "") + "ServiceImpl.java");
2853    
2854                    JavaMethod[] methods = _getMethods(javaClass);
2855    
2856                    if (sessionType == _SESSION_TYPE_LOCAL) {
2857                            if (javaClass.getSuperClass().getValue().endsWith(
2858                                            entity.getName() + "LocalServiceBaseImpl")) {
2859    
2860                                    JavaClass parentJavaClass = _getJavaClass(
2861                                            _outputPath + "/service/base/" + entity.getName() +
2862                                                    "LocalServiceBaseImpl.java");
2863    
2864                                    JavaMethod[] parentMethods = parentJavaClass.getMethods();
2865    
2866                                    JavaMethod[] allMethods = new JavaMethod[parentMethods.length + methods.length];
2867    
2868                                    ArrayUtil.combine(parentMethods, methods, allMethods);
2869    
2870                                    methods = allMethods;
2871                            }
2872                    }
2873    
2874                    Map<String, Object> context = _getContext();
2875    
2876                    context.put("entity", entity);
2877                    context.put("methods", methods);
2878                    context.put("sessionTypeName",_getSessionTypeName(sessionType));
2879    
2880                    // Content
2881    
2882                    String content = _processTemplate(_tplService, context);
2883    
2884                    // Write file
2885    
2886                    File ejbFile = new File(
2887                            _serviceOutputPath + "/service/" + entity.getName() +
2888                                    _getSessionTypeName(sessionType) + "Service.java");
2889    
2890                    writeFile(ejbFile, content, _author);
2891    
2892                    if (!_serviceOutputPath.equals(_outputPath)) {
2893                            ejbFile = new File(
2894                                    _outputPath + "/service/" + entity.getName() +
2895                                            _getSessionTypeName(sessionType) + "Service.java");
2896    
2897                            if (ejbFile.exists()) {
2898                                    System.out.println("Relocating " + ejbFile);
2899    
2900                                    ejbFile.delete();
2901                            }
2902                    }
2903            }
2904    
2905            private void _createServiceBaseImpl(Entity entity, int sessionType)
2906                    throws Exception {
2907    
2908                    JavaClass javaClass = _getJavaClass(_outputPath + "/service/impl/" + entity.getName() + (sessionType != _SESSION_TYPE_REMOTE ? "Local" : "") + "ServiceImpl.java");
2909    
2910                    JavaMethod[] methods = _getMethods(javaClass);
2911    
2912                    Map<String, Object> context = _getContext();
2913    
2914                    context.put("entity", entity);
2915                    context.put("methods", methods);
2916                    context.put("sessionTypeName",_getSessionTypeName(sessionType));
2917                    context.put(
2918                            "referenceList", _mergeReferenceList(entity.getReferenceList()));
2919    
2920                    // Content
2921    
2922                    String content = _processTemplate(_tplServiceBaseImpl, context);
2923    
2924                    // Write file
2925    
2926                    File ejbFile = new File(
2927                            _outputPath + "/service/base/" + entity.getName() +
2928                                    _getSessionTypeName(sessionType) + "ServiceBaseImpl.java");
2929    
2930                    writeFile(ejbFile, content, _author);
2931            }
2932    
2933            private void _createServiceClp(Entity entity, int sessionType)
2934                    throws Exception {
2935    
2936                    if (Validator.isNull(_pluginName)) {
2937                            return;
2938                    }
2939    
2940                    JavaClass javaClass = _getJavaClass(
2941                            _serviceOutputPath + "/service/" + entity.getName() +
2942                                    _getSessionTypeName(sessionType) + "Service.java");
2943    
2944                    Map<String, Object> context = _getContext();
2945    
2946                    context.put("entity", entity);
2947                    context.put("methods", _getMethods(javaClass));
2948                    context.put("sessionTypeName", _getSessionTypeName(sessionType));
2949    
2950                    // Content
2951    
2952                    String content = _processTemplate(_tplServiceClp, context);
2953    
2954                    // Write file
2955    
2956                    File ejbFile = new File(
2957                            _serviceOutputPath + "/service/" + entity.getName() +
2958                                    _getSessionTypeName(sessionType) + "ServiceClp.java");
2959    
2960                    writeFile(ejbFile, content, _author);
2961            }
2962    
2963            private void _createServiceClpMessageListener() throws Exception {
2964                    if (Validator.isNull(_pluginName)) {
2965                            return;
2966                    }
2967    
2968                    Map<String, Object> context = _getContext();
2969    
2970                    context.put("entities", _ejbList);
2971    
2972                    // Content
2973    
2974                    String content = _processTemplate(
2975                            _tplServiceClpMessageListener, context);
2976    
2977                    // Write file
2978    
2979                    File ejbFile = new File(
2980                            _serviceOutputPath + "/service/messaging/ClpMessageListener.java");
2981    
2982                    writeFile(ejbFile, content);
2983            }
2984    
2985            private void _createServiceClpSerializer() throws Exception {
2986                    if (Validator.isNull(_pluginName)) {
2987                            return;
2988                    }
2989    
2990                    Map<String, Object> context = _getContext();
2991    
2992                    context.put("entities", _ejbList);
2993    
2994                    // Content
2995    
2996                    String content = _processTemplate(_tplServiceClpSerializer, context);
2997    
2998                    // Write file
2999    
3000                    File ejbFile = new File(
3001                            _serviceOutputPath + "/service/ClpSerializer.java");
3002    
3003                    writeFile(ejbFile, content);
3004            }
3005    
3006            private void _createServiceFactory(Entity entity, int sessionType)
3007                    throws Exception {
3008    
3009                    File ejbFile = new File(
3010                            _serviceOutputPath + "/service/" + entity.getName() +
3011                                    _getSessionTypeName(sessionType) + "ServiceFactory.java");
3012    
3013                    if (ejbFile.exists()) {
3014                            System.out.println("Removing deprecated " + ejbFile);
3015    
3016                            ejbFile.delete();
3017                    }
3018    
3019                    ejbFile = new File(
3020                            _outputPath + "/service/" + entity.getName() +
3021                                    _getSessionTypeName(sessionType) + "ServiceFactory.java");
3022    
3023                    if (ejbFile.exists()) {
3024                            System.out.println("Removing deprecated " + ejbFile);
3025    
3026                            ejbFile.delete();
3027                    }
3028            }
3029    
3030            private void _createServiceHttp(Entity entity) throws Exception {
3031                    JavaClass javaClass = _getJavaClass(
3032                            _outputPath + "/service/impl/" + entity.getName() +
3033                                    "ServiceImpl.java");
3034    
3035                    Map<String, Object> context = _getContext();
3036    
3037                    context.put("entity", entity);
3038                    context.put("methods", _getMethods(javaClass));
3039                    context.put("hasHttpMethods", new Boolean(_hasHttpMethods(javaClass)));
3040    
3041                    // Content
3042    
3043                    String content = _processTemplate(_tplServiceHttp, context);
3044    
3045                    // Write file
3046    
3047                    File ejbFile = new File(
3048                            _outputPath + "/service/http/" + entity.getName() +
3049                                    "ServiceHttp.java");
3050    
3051                    writeFile(ejbFile, content, _author);
3052            }
3053    
3054            private void _createServiceImpl(Entity entity, int sessionType)
3055                    throws Exception {
3056    
3057                    Map<String, Object> context = _getContext();
3058    
3059                    context.put("entity", entity);
3060                    context.put("sessionTypeName", _getSessionTypeName(sessionType));
3061    
3062                    // Content
3063    
3064                    String content = _processTemplate(_tplServiceImpl, context);
3065    
3066                    // Write file
3067    
3068                    File ejbFile = new File(
3069                            _outputPath + "/service/impl/" + entity.getName() +
3070                                    _getSessionTypeName(sessionType) + "ServiceImpl.java");
3071    
3072                    if (!ejbFile.exists()) {
3073                            writeFile(ejbFile, content, _author);
3074                    }
3075            }
3076    
3077            private void _createServiceJson(Entity entity) throws Exception {
3078                    File ejbFile = new File(
3079                            _outputPath + "/service/http/" + entity.getName() +
3080                                    "ServiceJSON.java");
3081    
3082                    if (ejbFile.exists()) {
3083                            System.out.println("Removing deprecated " + ejbFile);
3084    
3085                            ejbFile.delete();
3086                    }
3087            }
3088    
3089            private void _createServiceJsonSerializer(Entity entity) throws Exception {
3090                    Map<String, Object> context = _getContext();
3091    
3092                    context.put("entity", entity);
3093    
3094                    // Content
3095    
3096                    String content = _processTemplate(_tplServiceJsonSerializer, context);
3097    
3098                    // Write file
3099    
3100                    File ejbFile = new File(
3101                            _outputPath + "/service/http/" + entity.getName() +
3102                                    "JSONSerializer.java");
3103    
3104                    writeFile(ejbFile, content, _author);
3105            }
3106    
3107            private void _createServiceSoap(Entity entity) throws Exception {
3108                    JavaClass javaClass = _getJavaClass(
3109                            _outputPath + "/service/impl/" + entity.getName() +
3110                                    "ServiceImpl.java");
3111    
3112                    Map<String, Object> context = _getContext();
3113    
3114                    context.put("entity", entity);
3115                    context.put("methods", _getMethods(javaClass));
3116    
3117                    // Content
3118    
3119                    String content = _processTemplate(_tplServiceSoap, context);
3120    
3121                    // Write file
3122    
3123                    File ejbFile = new File(
3124                            _outputPath + "/service/http/" + entity.getName() +
3125                                    "ServiceSoap.java");
3126    
3127                    writeFile(ejbFile, content, _author);
3128            }
3129    
3130            private void _createServiceUtil(Entity entity, int sessionType)
3131                    throws Exception {
3132    
3133                    JavaClass javaClass = _getJavaClass(
3134                            _serviceOutputPath + "/service/" + entity.getName() +
3135                                    _getSessionTypeName(sessionType) + "Service.java");
3136    
3137                    Map<String, Object> context = _getContext();
3138    
3139                    context.put("entity", entity);
3140                    context.put("methods", _getMethods(javaClass));
3141                    context.put("sessionTypeName", _getSessionTypeName(sessionType));
3142    
3143                    // Content
3144    
3145                    String content = _processTemplate(_tplServiceUtil, context);
3146    
3147                    // Write file
3148    
3149                    File ejbFile = new File(
3150                            _serviceOutputPath + "/service/" + entity.getName() +
3151                                    _getSessionTypeName(sessionType) + "ServiceUtil.java");
3152    
3153                    writeFile(ejbFile, content, _author);
3154    
3155                    if (!_serviceOutputPath.equals(_outputPath)) {
3156                            ejbFile = new File(
3157                                    _outputPath + "/service/" + entity.getName() +
3158                                            _getSessionTypeName(sessionType) + "ServiceUtil.java");
3159    
3160                            if (ejbFile.exists()) {
3161                                    System.out.println("Relocating " + ejbFile);
3162    
3163                                    ejbFile.delete();
3164                            }
3165                    }
3166            }
3167    
3168            private void _createServiceWrapper(Entity entity, int sessionType)
3169                    throws Exception {
3170    
3171                    JavaClass javaClass = _getJavaClass(
3172                            _serviceOutputPath + "/service/" + entity.getName() +
3173                                    _getSessionTypeName(sessionType) + "Service.java");
3174    
3175                    Map<String, Object> context = _getContext();
3176    
3177                    context.put("entity", entity);
3178                    context.put("methods", _getMethods(javaClass));
3179                    context.put("sessionTypeName", _getSessionTypeName(sessionType));
3180    
3181                    // Content
3182    
3183                    String content = _processTemplate(_tplServiceWrapper, context);
3184    
3185                    // Write file
3186    
3187                    File ejbFile = new File(
3188                            _serviceOutputPath + "/service/" + entity.getName() +
3189                                    _getSessionTypeName(sessionType) + "ServiceWrapper.java");
3190    
3191                    writeFile(ejbFile, content, _author);
3192            }
3193    
3194            private void _createSpringBaseXml() throws Exception {
3195                    if (Validator.isNull(_springBaseFileName)) {
3196                            return;
3197                    }
3198    
3199                    // Content
3200    
3201                    String content = _processTemplate(_tplSpringBaseXml);
3202    
3203                    // Write file
3204    
3205                    File ejbFile = new File(_springBaseFileName);
3206    
3207                    FileUtil.write(ejbFile, content, true);
3208    
3209                    if (Validator.isNotNull(_pluginName)) {
3210                            FileUtil.delete(
3211                                    "docroot/WEB-INF/src/META-INF/data-source-spring.xml");
3212                            FileUtil.delete("docroot/WEB-INF/src/META-INF/misc-spring.xml");
3213                    }
3214            }
3215    
3216            private void _createSpringClusterXml() throws Exception {
3217                    if (Validator.isNull(_springClusterFileName)) {
3218                            return;
3219                    }
3220    
3221                    // Content
3222    
3223                    String content = _processTemplate(_tplSpringClusterXml);
3224    
3225                    // Write file
3226    
3227                    File ejbFile = new File(_springClusterFileName);
3228    
3229                    FileUtil.write(ejbFile, content, true);
3230            }
3231    
3232            private void _createSpringDynamicDataSourceXml() throws Exception {
3233                    if (Validator.isNull(_springDynamicDataSourceFileName)) {
3234                            return;
3235                    }
3236    
3237                    // Content
3238    
3239                    String content = _processTemplate(_tplSpringDynamicDataSourceXml);
3240    
3241                    // Write file
3242    
3243                    File ejbFile = new File(_springDynamicDataSourceFileName);
3244    
3245                    FileUtil.write(ejbFile, content, true);
3246            }
3247    
3248            private void _createSpringHibernateXml() throws Exception {
3249                    if (Validator.isNull(_springHibernateFileName)) {
3250                            return;
3251                    }
3252    
3253                    // Content
3254    
3255                    String content = _processTemplate(_tplSpringHibernateXml);
3256    
3257                    // Write file
3258    
3259                    File ejbFile = new File(_springHibernateFileName);
3260    
3261                    FileUtil.write(ejbFile, content, true);
3262            }
3263    
3264            private void _createSpringInfrastructureXml() throws Exception {
3265                    if (Validator.isNull(_springInfrastructureFileName)) {
3266                            return;
3267                    }
3268    
3269                    // Content
3270    
3271                    String content = _processTemplate(_tplSpringInfrastructureXml);
3272    
3273                    // Write file
3274    
3275                    File ejbFile = new File(_springInfrastructureFileName);
3276    
3277                    FileUtil.write(ejbFile, content, true);
3278            }
3279    
3280            private void _createSpringShardDataSourceXml() throws Exception {
3281                    if (Validator.isNull(_springShardDataSourceFileName)) {
3282                            return;
3283                    }
3284    
3285                    // Content
3286    
3287                    String content = _processTemplate(_tplSpringShardDataSourceXml);
3288    
3289                    // Write file
3290    
3291                    File ejbFile = new File(_springShardDataSourceFileName);
3292    
3293                    FileUtil.write(ejbFile, content, true);
3294            }
3295    
3296            private void _createSpringXml() throws Exception {
3297                    if (_packagePath.equals("com.liferay.counter")) {
3298                            return;
3299                    }
3300    
3301                    Map<String, Object> context = _getContext();
3302    
3303                    context.put("entities", _ejbList);
3304    
3305                    // Content
3306    
3307                    String content = _processTemplate(_tplSpringXml, context);
3308    
3309                    File xmlFile = new File(_springFileName);
3310    
3311                    String xml =
3312                            "<?xml version=\"1.0\"?>\n" +
3313                            "\n" +
3314                            "<beans\n" +
3315                            "\tdefault-destroy-method=\"destroy\"\n" +
3316                            "\tdefault-init-method=\"afterPropertiesSet\"\n" +
3317                            "\txmlns=\"http://www.springframework.org/schema/beans\"\n" +
3318                            "\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
3319                            "\txsi:schemaLocation=\"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\"\n" +
3320                            ">\n" +
3321                            "</beans>";
3322    
3323                    if (!xmlFile.exists()) {
3324                            FileUtil.write(xmlFile, xml);
3325                    }
3326    
3327                    String oldContent = FileUtil.read(xmlFile);
3328    
3329                    if (Validator.isNotNull(_pluginName) &&
3330                            oldContent.contains("DOCTYPE beans PUBLIC")) {
3331    
3332                            oldContent = xml;
3333                    }
3334    
3335                    String newContent = _fixSpringXml(oldContent);
3336    
3337                    int x = oldContent.indexOf("<beans");
3338                    int y = oldContent.lastIndexOf("</beans>");
3339    
3340                    int firstSession = newContent.indexOf(
3341                            "<bean id=\"" + _packagePath + ".service.", x);
3342    
3343                    int lastSession = newContent.lastIndexOf(
3344                            "<bean id=\"" + _packagePath + ".service.", y);
3345    
3346                    if ((firstSession == -1) || (firstSession > y)) {
3347                            x = newContent.indexOf("</beans>");
3348    
3349                            newContent =
3350                                    newContent.substring(0, x) + content +
3351                                            newContent.substring(x, newContent.length());
3352                    }
3353                    else {
3354                            firstSession = newContent.lastIndexOf("<bean", firstSession) - 1;
3355    
3356                            int tempLastSession = newContent.indexOf(
3357                                    "<bean id=\"", lastSession + 1);
3358    
3359                            if (tempLastSession == -1) {
3360                                    tempLastSession = newContent.indexOf("</beans>", lastSession);
3361                            }
3362    
3363                            lastSession = tempLastSession;
3364    
3365                            newContent =
3366                                    newContent.substring(0, firstSession) + content +
3367                                            newContent.substring(lastSession, newContent.length());
3368                    }
3369    
3370                    newContent = _formatXml(newContent);
3371    
3372                    if (!oldContent.equals(newContent)) {
3373                            FileUtil.write(xmlFile, newContent);
3374                    }
3375            }
3376    
3377            private void _createSQLIndexes() throws IOException {
3378                    if (!FileUtil.exists(_sqlDir)) {
3379                            return;
3380                    }
3381    
3382                    // indexes.sql
3383    
3384                    File sqlFile = new File(_sqlDir + "/" + _sqlIndexesFileName);
3385    
3386                    if (!sqlFile.exists()) {
3387                            FileUtil.write(sqlFile, "");
3388                    }
3389    
3390                    Map<String, String> indexSQLs = new TreeMap<String, String>();
3391    
3392                    UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(
3393                            new FileReader(sqlFile));
3394    
3395                    while (true) {
3396                            String indexSQL = unsyncBufferedReader.readLine();
3397    
3398                            if (indexSQL == null) {
3399                                    break;
3400                            }
3401    
3402                            if (Validator.isNotNull(indexSQL.trim())) {
3403                                    int pos = indexSQL.indexOf(" on ");
3404    
3405                                    String indexSpec = indexSQL.substring(pos + 4);
3406    
3407                                    indexSQLs.put(indexSpec, indexSQL);
3408                            }
3409                    }
3410    
3411                    unsyncBufferedReader.close();
3412    
3413                    // indexes.properties
3414    
3415                    File propsFile = new File(
3416                            _sqlDir + "/" + _sqlIndexesPropertiesFileName);
3417    
3418                    if (!propsFile.exists()) {
3419                            FileUtil.write(propsFile, "");
3420                    }
3421    
3422                    Map<String, String> indexProps = new TreeMap<String, String>();
3423    
3424                    unsyncBufferedReader = new UnsyncBufferedReader(
3425                            new FileReader(propsFile));
3426    
3427                    while (true) {
3428                            String indexMapping = unsyncBufferedReader.readLine();
3429    
3430                            if (indexMapping == null) {
3431                                    break;
3432                            }
3433    
3434                            if (Validator.isNotNull(indexMapping.trim())) {
3435                                    String[] splitIndexMapping = indexMapping.split("\\=");
3436    
3437                                    indexProps.put(splitIndexMapping[1], splitIndexMapping[0]);
3438                            }
3439                    }
3440    
3441                    unsyncBufferedReader.close();
3442    
3443                    // indexes.sql
3444    
3445                    for (int i = 0; i < _ejbList.size(); i++) {
3446                            Entity entity = _ejbList.get(i);
3447    
3448                            if (!entity.isDefaultDataSource()) {
3449                                    continue;
3450                            }
3451    
3452                            List<EntityFinder> finderList = entity.getFinderList();
3453    
3454                            for (int j = 0; j < finderList.size(); j++) {
3455                                    EntityFinder finder = finderList.get(j);
3456    
3457                                    if (finder.isDBIndex()) {
3458                                            StringBuilder sb = new StringBuilder();
3459    
3460                                            sb.append(entity.getTable() + " (");
3461    
3462                                            List<EntityColumn> finderColsList = finder.getColumns();
3463    
3464                                            for (int k = 0; k < finderColsList.size(); k++) {
3465                                                    EntityColumn col = finderColsList.get(k);
3466    
3467                                                    sb.append(col.getDBName());
3468    
3469                                                    if ((k + 1) != finderColsList.size()) {
3470                                                            sb.append(", ");
3471                                                    }
3472                                            }
3473    
3474                                            sb.append(");");
3475    
3476                                            String indexSpec = sb.toString();
3477    
3478                                            String indexHash =
3479                                                    Integer.toHexString(indexSpec.hashCode()).toUpperCase();
3480    
3481                                            String indexName = "IX_" + indexHash;
3482    
3483                                            sb = new StringBuilder();
3484    
3485                                            sb.append("create ");
3486    
3487                                            if (finder.isUnique()) {
3488                                                    sb.append("unique ");
3489                                            }
3490    
3491                                            sb.append("index " + indexName + " on ");
3492                                            sb.append(indexSpec);
3493    
3494                                            indexSQLs.put(indexSpec, sb.toString());
3495    
3496                                            String finderName =
3497                                                    entity.getTable() + StringPool.PERIOD +
3498                                                            finder.getName();
3499    
3500                                            indexProps.put(finderName, indexName);
3501                                    }
3502                            }
3503                    }
3504    
3505                    for (Map.Entry<String, EntityMapping> entry :
3506                                    _entityMappings.entrySet()) {
3507    
3508                            EntityMapping entityMapping = entry.getValue();
3509    
3510                            _getCreateMappingTableIndex(entityMapping, indexSQLs, indexProps);
3511                    }
3512    
3513                    StringBuilder sb = new StringBuilder();
3514    
3515                    Iterator<String> itr = indexSQLs.values().iterator();
3516    
3517                    String prevEntityName = null;
3518    
3519                    while (itr.hasNext()) {
3520                            String indexSQL = itr.next();
3521    
3522                            int pos = indexSQL.indexOf(" on ");
3523    
3524                            String indexSQLSuffix = indexSQL.substring(pos + 4);
3525    
3526                            String entityName = indexSQLSuffix.split(" ")[0];
3527    
3528                            if ((prevEntityName != null) &&
3529                                    (!prevEntityName.equals(entityName))) {
3530    
3531                                    sb.append("\n");
3532                            }
3533    
3534                            sb.append(indexSQL);
3535    
3536                            if (itr.hasNext()) {
3537                                    sb.append("\n");
3538                            }
3539    
3540                            prevEntityName = entityName;
3541                    }
3542    
3543                    FileUtil.write(sqlFile, sb.toString(), true);
3544    
3545                    // indexes.properties
3546    
3547                    sb = new StringBuilder();
3548    
3549                    itr = indexProps.keySet().iterator();
3550    
3551                    prevEntityName = null;
3552    
3553                    while (itr.hasNext()) {
3554                            String finderName = itr.next();
3555    
3556                            String indexName = indexProps.get(finderName);
3557    
3558                            String entityName = finderName.split("\\.")[0];
3559    
3560                            if ((prevEntityName != null) &&
3561                                    (!prevEntityName.equals(entityName))) {
3562    
3563                                    sb.append("\n");
3564                            }
3565    
3566                            sb.append(indexName + StringPool.EQUAL + finderName);
3567    
3568                            if (itr.hasNext()) {
3569                                    sb.append("\n");
3570                            }
3571    
3572                            prevEntityName = entityName;
3573                    }
3574    
3575                    FileUtil.write(propsFile, sb.toString(), true);
3576            }
3577    
3578            private void _createSQLMappingTables(
3579                            File sqlFile, String newCreateTableString,
3580                            EntityMapping entityMapping, boolean addMissingTables)
3581                    throws IOException {
3582    
3583                    if (!sqlFile.exists()) {
3584                            FileUtil.write(sqlFile, StringPool.BLANK);
3585                    }
3586    
3587                    String content = FileUtil.read(sqlFile);
3588    
3589                    int x = content.indexOf(
3590                            _SQL_CREATE_TABLE + entityMapping.getTable() + " (");
3591                    int y = content.indexOf(");", x);
3592    
3593                    if (x != -1) {
3594                            String oldCreateTableString = content.substring(x + 1, y);
3595    
3596                            if (!oldCreateTableString.equals(newCreateTableString)) {
3597                                    content =
3598                                            content.substring(0, x) + newCreateTableString +
3599                                                    content.substring(y + 2, content.length());
3600    
3601                                    FileUtil.write(sqlFile, content);
3602                            }
3603                    }
3604                    else if (addMissingTables) {
3605                            StringBuilder sb = new StringBuilder();
3606    
3607                            UnsyncBufferedReader unsyncBufferedReader =
3608                                    new UnsyncBufferedReader(new UnsyncStringReader(content));
3609    
3610                            String line = null;
3611                            boolean appendNewTable = true;
3612    
3613                            while ((line = unsyncBufferedReader.readLine()) != null) {
3614                                    if (appendNewTable && line.startsWith(_SQL_CREATE_TABLE)) {
3615                                            x = _SQL_CREATE_TABLE.length();
3616                                            y = line.indexOf(" ", x);
3617    
3618                                            String tableName = line.substring(x, y);
3619    
3620                                            if (tableName.compareTo(entityMapping.getTable()) > 0) {
3621                                                    sb.append(newCreateTableString + "\n\n");
3622    
3623                                                    appendNewTable = false;
3624                                            }
3625                                    }
3626    
3627                                    sb.append(line);
3628                                    sb.append("\n");
3629                            }
3630    
3631                            if (appendNewTable) {
3632                                    sb.append("\n" + newCreateTableString);
3633                            }
3634    
3635                            unsyncBufferedReader.close();
3636    
3637                            FileUtil.write(sqlFile, sb.toString(), true);
3638                    }
3639            }
3640    
3641            private void _createSQLSequences() throws IOException {
3642                    if (!FileUtil.exists(_sqlDir)) {
3643                            return;
3644                    }
3645    
3646                    File sqlFile = new File(_sqlDir + "/" + _sqlSequencesFileName);
3647    
3648                    if (!sqlFile.exists()) {
3649                            FileUtil.write(sqlFile, "");
3650                    }
3651    
3652                    Set<String> sequenceSQLs = new TreeSet<String>();
3653    
3654                    UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(
3655                            new FileReader(sqlFile));
3656    
3657                    while (true) {
3658                            String sequenceSQL = unsyncBufferedReader.readLine();
3659    
3660                            if (sequenceSQL == null) {
3661                                    break;
3662                            }
3663    
3664                            if (Validator.isNotNull(sequenceSQL)) {
3665                                    sequenceSQLs.add(sequenceSQL);
3666                            }
3667                    }
3668    
3669                    unsyncBufferedReader.close();
3670    
3671                    for (int i = 0; i < _ejbList.size(); i++) {
3672                            Entity entity = _ejbList.get(i);
3673    
3674                            if (!entity.isDefaultDataSource()) {
3675                                    continue;
3676                            }
3677    
3678                            List<EntityColumn> columnList = entity.getColumnList();
3679    
3680                            for (int j = 0; j < columnList.size(); j++) {
3681                                    EntityColumn column = columnList.get(j);
3682    
3683                                    if ("sequence".equals(column.getIdType())) {
3684                                            StringBuilder sb = new StringBuilder();
3685    
3686                                            String sequenceName = column.getIdParam();
3687    
3688                                            if (sequenceName.length() > 30) {
3689                                                    sequenceName = sequenceName.substring(0, 30);
3690                                            }
3691    
3692                                            sb.append("create sequence " + sequenceName + ";");
3693    
3694                                            String sequenceSQL = sb.toString();
3695    
3696                                            if (!sequenceSQLs.contains(sequenceSQL)) {
3697                                                    sequenceSQLs.add(sequenceSQL);
3698                                            }
3699                                    }
3700                            }
3701                    }
3702    
3703                    StringBuilder sb = new StringBuilder();
3704    
3705                    Iterator<String> itr = sequenceSQLs.iterator();
3706    
3707                    while (itr.hasNext()) {
3708                            String sequenceSQL = itr.next();
3709    
3710                            sb.append(sequenceSQL);
3711    
3712                            if (itr.hasNext()) {
3713                                    sb.append("\n");
3714                            }
3715                    }
3716    
3717                    FileUtil.write(sqlFile, sb.toString(), true);
3718            }
3719    
3720            private void _createSQLTables() throws IOException {
3721                    if (!FileUtil.exists(_sqlDir)) {
3722                            return;
3723                    }
3724    
3725                    File sqlFile = new File(_sqlDir + "/" + _sqlFileName);
3726    
3727                    if (!sqlFile.exists()) {
3728                            FileUtil.write(sqlFile, StringPool.BLANK);
3729                    }
3730    
3731                    for (int i = 0; i < _ejbList.size(); i++) {
3732                            Entity entity = _ejbList.get(i);
3733    
3734                            if (!entity.isDefaultDataSource()) {
3735                                    continue;
3736                            }
3737    
3738                            String createTableSQL = _getCreateTableSQL(entity);
3739    
3740                            if (Validator.isNotNull(createTableSQL)) {
3741                                    _createSQLTables(sqlFile, createTableSQL, entity, true);
3742    
3743                                    File updateSQLFile = new File(
3744                                            _sqlDir + "/update-6.0.5-6.0.6.sql");
3745    
3746                                    if (updateSQLFile.exists()) {
3747                                            _createSQLTables(
3748                                                    updateSQLFile, createTableSQL, entity, false);
3749                                    }
3750                            }
3751                    }
3752    
3753                    for (Map.Entry<String, EntityMapping> entry :
3754                                    _entityMappings.entrySet()) {
3755    
3756                            EntityMapping entityMapping = entry.getValue();
3757    
3758                            String createMappingTableSQL = _getCreateMappingTableSQL(
3759                                    entityMapping);
3760    
3761                            if (Validator.isNotNull(createMappingTableSQL)) {
3762                                    _createSQLMappingTables(
3763                                            sqlFile, createMappingTableSQL, entityMapping, true);
3764                            }
3765                    }
3766    
3767                    String content = FileUtil.read(sqlFile);
3768    
3769                    FileUtil.write(sqlFile, content.trim());
3770            }
3771    
3772            private void _createSQLTables(
3773                            File sqlFile, String newCreateTableString, Entity entity,
3774                            boolean addMissingTables)
3775                    throws IOException {
3776    
3777                    if (!sqlFile.exists()) {
3778                            FileUtil.write(sqlFile, StringPool.BLANK);
3779                    }
3780    
3781                    String content = FileUtil.read(sqlFile);
3782    
3783                    int x = content.indexOf(_SQL_CREATE_TABLE + entity.getTable() + " (");
3784                    int y = content.indexOf(");", x);
3785    
3786                    if (x != -1) {
3787                            String oldCreateTableString = content.substring(x + 1, y);
3788    
3789                            if (!oldCreateTableString.equals(newCreateTableString)) {
3790                                    content =
3791                                            content.substring(0, x) + newCreateTableString +
3792                                                    content.substring(y + 2, content.length());
3793    
3794                                    FileUtil.write(sqlFile, content);
3795                            }
3796                    }
3797                    else if (addMissingTables) {
3798                            StringBuilder sb = new StringBuilder();
3799    
3800                            UnsyncBufferedReader unsyncBufferedReader =
3801                                    new UnsyncBufferedReader(new UnsyncStringReader(content));
3802    
3803                            String line = null;
3804                            boolean appendNewTable = true;
3805    
3806                            while ((line = unsyncBufferedReader.readLine()) != null) {
3807                                    if (appendNewTable && line.startsWith(_SQL_CREATE_TABLE)) {
3808                                            x = _SQL_CREATE_TABLE.length();
3809                                            y = line.indexOf(" ", x);
3810    
3811                                            String tableName = line.substring(x, y);
3812    
3813                                            if (tableName.compareTo(entity.getTable()) > 0) {
3814                                                    sb.append(newCreateTableString + "\n\n");
3815    
3816                                                    appendNewTable = false;
3817                                            }
3818                                    }
3819    
3820                                    sb.append(line);
3821                                    sb.append("\n");
3822                            }
3823    
3824                            if (appendNewTable) {
3825                                    sb.append("\n" + newCreateTableString);
3826                            }
3827    
3828                            unsyncBufferedReader.close();
3829    
3830                            FileUtil.write(sqlFile, sb.toString(), true);
3831                    }
3832            }
3833    
3834            private String _fixHbmXml(String content) throws IOException {
3835                    StringBuilder sb = new StringBuilder();
3836    
3837                    UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(
3838                            new UnsyncStringReader(content));
3839    
3840                    String line = null;
3841    
3842                    while ((line = unsyncBufferedReader.readLine()) != null) {
3843                            if (line.startsWith("\t<class name=\"")) {
3844                                    line = StringUtil.replace(
3845                                            line,
3846                                            new String[] {
3847                                                    ".service.persistence.", "HBM\" table=\""
3848                                            },
3849                                            new String[] {
3850                                                    ".model.", "\" table=\""
3851                                            });
3852    
3853                                    if (line.indexOf(".model.impl.") == -1) {
3854                                            line = StringUtil.replace(
3855                                                    line,
3856                                                    new String[] {
3857                                                            ".model.", "\" table=\""
3858                                                    },
3859                                                    new String[] {
3860                                                            ".model.impl.", "Impl\" table=\""
3861                                                    });
3862                                    }
3863                            }
3864    
3865                            sb.append(line);
3866                            sb.append('\n');
3867                    }
3868    
3869                    unsyncBufferedReader.close();
3870    
3871                    return sb.toString().trim();
3872            }
3873    
3874            private String _fixSpringXml(String content) {
3875                    return StringUtil.replace(content, ".service.spring.", ".service.");
3876            }
3877    
3878            private String _formatComment(
3879                    String comment, DocletTag[] tags, String indentation) {
3880    
3881                    StringBuilder sb = new StringBuilder();
3882    
3883                    if (Validator.isNull(comment) && (tags.length <= 0)) {
3884                            return sb.toString();
3885                    }
3886    
3887                    sb.append(indentation);
3888                    sb.append("/**\n");
3889    
3890                    if (Validator.isNotNull(comment)) {
3891                            comment = comment.replaceAll("(?m)^", indentation + " * ");
3892    
3893                            sb.append(comment);
3894                            sb.append("\n");
3895    
3896                            if (tags.length > 0) {
3897                                    sb.append(indentation);
3898                                    sb.append(" *\n");
3899                            }
3900                    }
3901    
3902                    for (DocletTag tag : tags) {
3903                            sb.append(indentation);
3904                            sb.append(" * @");
3905                            sb.append(tag.getName());
3906                            sb.append(" ");
3907                            sb.append(tag.getValue());
3908                            sb.append("\n");
3909                    }
3910    
3911                    sb.append(indentation);
3912                    sb.append(" */\n");
3913    
3914                    return sb.toString();
3915            }
3916    
3917            private String _formatXml(String xml)
3918                    throws DocumentException, IOException {
3919    
3920                    String doctype = null;
3921    
3922                    int x = xml.indexOf("<!DOCTYPE");
3923    
3924                    if (x != -1) {
3925                            int y = xml.indexOf(">", x) + 1;
3926    
3927                            doctype = xml.substring(x, y);
3928    
3929                            xml = xml.substring(0, x) + "\n" + xml.substring(y);
3930                    }
3931    
3932                    xml = StringUtil.replace(xml, '\r', "");
3933                    xml = XMLFormatter.toString(xml);
3934                    xml = StringUtil.replace(xml, "\"/>", "\" />");
3935    
3936                    if (Validator.isNotNull(doctype)) {
3937                            x = xml.indexOf("?>") + 2;
3938    
3939                            xml = xml.substring(0, x) + "\n" + doctype + xml.substring(x);
3940                    }
3941    
3942                    return xml;
3943            }
3944    
3945            private Map<String, Object> _getContext() throws TemplateModelException {
3946                    BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
3947    
3948                    TemplateHashModel staticModels = wrapper.getStaticModels();
3949    
3950                    Map<String, Object> context = new HashMap<String, Object>();
3951    
3952                    context.put("hbmFileName", _hbmFileName);
3953                    context.put("ormFileName", _ormFileName);
3954                    context.put("modelHintsFileName", _modelHintsFileName);
3955                    context.put("springFileName", _springFileName);
3956                    context.put("springBaseFileName", _springBaseFileName);
3957                    context.put("springHibernateFileName", _springHibernateFileName);
3958                    context.put(
3959                            "springInfrastructureFileName", _springInfrastructureFileName);
3960                    context.put("apiDir", _apiDir);
3961                    context.put("implDir", _implDir);
3962                    context.put("jsonFileName", _jsonFileName);
3963                    context.put("sqlDir", _sqlDir);
3964                    context.put("sqlFileName", _sqlFileName);
3965                    context.put("beanLocatorUtil", _beanLocatorUtil);
3966                    context.put("beanLocatorUtilShortName", _beanLocatorUtilShortName);
3967                    context.put("propsUtil", _propsUtil);
3968                    context.put("portletName", _portletName);
3969                    context.put("portletShortName", _portletShortName);
3970                    context.put("portletPackageName", _portletPackageName);
3971                    context.put("outputPath", _outputPath);
3972                    context.put("serviceOutputPath", _serviceOutputPath);
3973                    context.put("packagePath", _packagePath);
3974                    context.put("pluginName", _pluginName);
3975                    context.put("author", _author);
3976                    context.put("serviceBuilder", this);
3977    
3978                    context.put("arrayUtil", ArrayUtil_IW.getInstance());
3979                    context.put(
3980                            "modelHintsUtil",
3981                            staticModels.get("com.liferay.portal.model.ModelHintsUtil"));
3982                    context.put(
3983                            "resourceActionsUtil", ResourceActionsUtil_IW.getInstance());
3984                    context.put("stringUtil", StringUtil_IW.getInstance());
3985                    context.put("system", staticModels.get("java.lang.System"));
3986                    context.put("tempMap", wrapper.wrap(new HashMap<String, Object>()));
3987                    context.put(
3988                            "textFormatter",
3989                            staticModels.get("com.liferay.util.TextFormatter"));
3990                    context.put("validator", Validator_IW.getInstance());
3991    
3992                    return context;
3993            }
3994    
3995            private void _getCreateMappingTableIndex(
3996                            EntityMapping entityMapping, Map<String, String> indexSQLs,
3997                            Map<String, String> indexProps)
3998                    throws IOException {
3999    
4000                    Entity[] entities = new Entity[2];
4001    
4002                    for (int i = 0; i < entities.length; i++) {
4003                            entities[i] = getEntity(entityMapping.getEntity(i));
4004    
4005                            if (entities[i] == null) {
4006                                    return;
4007                            }
4008                    }
4009    
4010                    for (Entity entity : entities) {
4011                            List<EntityColumn> pkList = entity.getPKList();
4012    
4013                            for (int j = 0; j < pkList.size(); j++) {
4014                                    EntityColumn col = pkList.get(j);
4015    
4016                                    String colDBName = col.getDBName();
4017    
4018                                    String indexSpec =
4019                                            entityMapping.getTable() + " (" + colDBName + ");";
4020    
4021                                    String indexHash =
4022                                            Integer.toHexString(indexSpec.hashCode()).toUpperCase();
4023    
4024                                    String indexName = "IX_" + indexHash;
4025    
4026                                    StringBuilder sb = new StringBuilder();
4027    
4028                                    sb.append("create index " + indexName + " on ");
4029                                    sb.append(indexSpec);
4030    
4031                                    indexSQLs.put(indexSpec, sb.toString());
4032    
4033                                    String finderName =
4034                                            entityMapping.getTable() + StringPool.PERIOD + colDBName;
4035    
4036                                    indexProps.put(finderName, indexName);
4037                            }
4038                    }
4039            }
4040    
4041            private String _getCreateMappingTableSQL(EntityMapping entityMapping)
4042                    throws IOException {
4043    
4044                    Entity[] entities = new Entity[2];
4045    
4046                    for (int i = 0; i < entities.length; i++) {
4047                            entities[i] = getEntity(entityMapping.getEntity(i));
4048    
4049                            if (entities[i] == null) {
4050                                    return null;
4051                            }
4052                    }
4053    
4054                    StringBuilder sb = new StringBuilder();
4055    
4056                    sb.append(_SQL_CREATE_TABLE + entityMapping.getTable() + " (\n");
4057    
4058                    for (Entity entity : entities) {
4059                            List<EntityColumn> pkList = entity.getPKList();
4060    
4061                            for (int i = 0; i < pkList.size(); i++) {
4062                                    EntityColumn col = pkList.get(i);
4063    
4064                                    String colName = col.getName();
4065                                    String colType = col.getType();
4066    
4067                                    sb.append("\t" + col.getDBName());
4068                                    sb.append(" ");
4069    
4070                                    if (colType.equalsIgnoreCase("boolean")) {
4071                                            sb.append("BOOLEAN");
4072                                    }
4073                                    else if (colType.equalsIgnoreCase("double") ||
4074                                                     colType.equalsIgnoreCase("float")) {
4075    
4076                                            sb.append("DOUBLE");
4077                                    }
4078                                    else if (colType.equals("int") ||
4079                                                     colType.equals("Integer") ||
4080                                                     colType.equalsIgnoreCase("short")) {
4081    
4082                                            sb.append("INTEGER");
4083                                    }
4084                                    else if (colType.equalsIgnoreCase("long")) {
4085                                            sb.append("LONG");
4086                                    }
4087                                    else if (colType.equals("String")) {
4088                                            Map<String, String> hints = ModelHintsUtil.getHints(
4089                                                    _packagePath + ".model." + entity.getName(), colName);
4090    
4091                                            int maxLength = 75;
4092    
4093                                            if (hints != null) {
4094                                                    maxLength = GetterUtil.getInteger(
4095                                                            hints.get("max-length"), maxLength);
4096                                            }
4097    
4098                                            if (col.isLocalized()) {
4099                                                    maxLength = 4000;
4100                                            }
4101    
4102                                            if (maxLength < 4000) {
4103                                                    sb.append("VARCHAR(" + maxLength + ")");
4104                                            }
4105                                            else if (maxLength == 4000) {
4106                                                    sb.append("STRING");
4107                                            }
4108                                            else if (maxLength > 4000) {
4109                                                    sb.append("TEXT");
4110                                            }
4111                                    }
4112                                    else if (colType.equals("Date")) {
4113                                            sb.append("DATE null");
4114                                    }
4115                                    else {
4116                                            sb.append("invalid");
4117                                    }
4118    
4119                                    if (col.isPrimary()) {
4120                                            sb.append(" not null");
4121                                    }
4122    
4123                                    sb.append(",\n");
4124                            }
4125                    }
4126    
4127                    sb.append("\tprimary key (");
4128    
4129                    for (int i = 0; i < entities.length; i++) {
4130                            Entity entity = entities[i];
4131    
4132                            List<EntityColumn> pkList = entity.getPKList();
4133    
4134                            for (int j = 0; j < pkList.size(); j++) {
4135                                    EntityColumn col = pkList.get(j);
4136    
4137                                    String colDBName = col.getDBName();
4138    
4139                                    if ((i != 0) || (j != 0)) {
4140                                            sb.append(", ");
4141                                    }
4142    
4143                                    sb.append(colDBName);
4144                            }
4145                    }
4146    
4147                    sb.append(")\n");
4148                    sb.append(");");
4149    
4150                    return sb.toString();
4151            }
4152    
4153            private String _getCreateTableSQL(Entity entity) {
4154                    List<EntityColumn> pkList = entity.getPKList();
4155                    List<EntityColumn> regularColList = entity.getRegularColList();
4156    
4157                    if (regularColList.size() == 0) {
4158                            return null;
4159                    }
4160    
4161                    StringBuilder sb = new StringBuilder();
4162    
4163                    sb.append(_SQL_CREATE_TABLE + entity.getTable() + " (\n");
4164    
4165                    for (int i = 0; i < regularColList.size(); i++) {
4166                            EntityColumn col = regularColList.get(i);
4167    
4168                            String colName = col.getName();
4169                            String colType = col.getType();
4170                            String colIdType = col.getIdType();
4171    
4172                            sb.append("\t" + col.getDBName());
4173                            sb.append(" ");
4174    
4175                            if (colType.equalsIgnoreCase("boolean")) {
4176                                    sb.append("BOOLEAN");
4177                            }
4178                            else if (colType.equalsIgnoreCase("double") ||
4179                                             colType.equalsIgnoreCase("float")) {
4180    
4181                                    sb.append("DOUBLE");
4182                            }
4183                            else if (colType.equals("int") ||
4184                                             colType.equals("Integer") ||
4185                                             colType.equalsIgnoreCase("short")) {
4186    
4187                                    sb.append("INTEGER");
4188                            }
4189                            else if (colType.equalsIgnoreCase("long")) {
4190                                    sb.append("LONG");
4191                            }
4192                            else if (colType.equals("String")) {
4193                                    Map<String, String> hints = ModelHintsUtil.getHints(
4194                                            _packagePath + ".model." + entity.getName(), colName);
4195    
4196                                    int maxLength = 75;
4197    
4198                                    if (hints != null) {
4199                                            maxLength = GetterUtil.getInteger(
4200                                                    hints.get("max-length"), maxLength);
4201                                    }
4202    
4203                                    if (col.isLocalized()) {
4204                                            maxLength = 4000;
4205                                    }
4206    
4207                                    if (maxLength < 4000) {
4208                                            sb.append("VARCHAR(" + maxLength + ")");
4209                                    }
4210                                    else if (maxLength == 4000) {
4211                                            sb.append("STRING");
4212                                    }
4213                                    else if (maxLength > 4000) {
4214                                            sb.append("TEXT");
4215                                    }
4216                            }
4217                            else if (colType.equals("Date")) {
4218                                    sb.append("DATE null");
4219                            }
4220                            else {
4221                                    sb.append("invalid");
4222                            }
4223    
4224                            if (col.isPrimary()) {
4225                                    sb.append(" not null");
4226    
4227                                    if (!entity.hasCompoundPK()) {
4228                                            sb.append(" primary key");
4229                                    }
4230                            }
4231                            else if (colType.equals("String")) {
4232                                    sb.append(" null");
4233                            }
4234    
4235                            if (Validator.isNotNull(colIdType) &&
4236                                    colIdType.equals("identity")) {
4237    
4238                                    sb.append(" IDENTITY");
4239                            }
4240    
4241                            if (((i + 1) != regularColList.size()) ||
4242                                    (entity.hasCompoundPK())) {
4243    
4244                                    sb.append(",");
4245                            }
4246    
4247                            sb.append("\n");
4248                    }
4249    
4250                    if (entity.hasCompoundPK()) {
4251                            sb.append("\tprimary key (");
4252    
4253                            for (int j = 0; j < pkList.size(); j++) {
4254                                    EntityColumn pk = pkList.get(j);
4255    
4256                                    sb.append(pk.getDBName());
4257    
4258                                    if ((j + 1) != pkList.size()) {
4259                                            sb.append(", ");
4260                                    }
4261                            }
4262    
4263                            sb.append(")\n");
4264                    }
4265    
4266                    sb.append(");");
4267    
4268                    return sb.toString();
4269            }
4270    
4271            private String _getDimensions(Type type) {
4272                    String dimensions = "";
4273    
4274                    for (int i = 0; i < type.getDimensions(); i++) {
4275                            dimensions += "[]";
4276                    }
4277    
4278                    return dimensions;
4279            }
4280    
4281            private JavaClass _getJavaClass(String fileName) throws IOException {
4282                    int pos = fileName.indexOf(_implDir + "/");
4283    
4284                    if (pos != -1) {
4285                            pos += _implDir.length();
4286                    }
4287                    else {
4288                            pos = fileName.indexOf(_apiDir + "/") + _apiDir.length();
4289                    }
4290    
4291                    String srcFile = fileName.substring(pos + 1, fileName.length());
4292                    String className = StringUtil.replace(
4293                            srcFile.substring(0, srcFile.length() - 5), "/", ".");
4294    
4295                    JavaDocBuilder builder = new JavaDocBuilder();
4296    
4297                    File file = new File(fileName);
4298    
4299                    if (!file.exists()) {
4300                            return null;
4301                    }
4302    
4303                    builder.addSource(file);
4304    
4305                    return builder.getClassByName(className);
4306            }
4307    
4308            private JavaMethod[] _getMethods(JavaClass javaClass) {
4309                    return _getMethods(javaClass, false);
4310            }
4311    
4312            private JavaMethod[] _getMethods(
4313                    JavaClass javaClass, boolean superclasses) {
4314    
4315                    JavaMethod[] methods = javaClass.getMethods(superclasses);
4316    
4317                    for (JavaMethod method : methods) {
4318                            Arrays.sort(method.getExceptions());
4319                    }
4320    
4321                    return methods;
4322            }
4323    
4324            private String _getSessionTypeName(int sessionType) {
4325                    if (sessionType == _SESSION_TYPE_LOCAL) {
4326                            return "Local";
4327                    }
4328                    else {
4329                            return "";
4330                    }
4331            }
4332    
4333            private List<String> _getTransients(Entity entity, boolean parent)
4334                    throws Exception {
4335    
4336                    File modelFile = null;
4337    
4338                    if (parent) {
4339                            modelFile = new File(
4340                                    _outputPath + "/model/impl/" + entity.getName() +
4341                                            "ModelImpl.java");
4342                    }
4343                    else {
4344                            modelFile = new File(
4345                                    _outputPath + "/model/impl/" + entity.getName() + "Impl.java");
4346                    }
4347    
4348                    String content = FileUtil.read(modelFile);
4349    
4350                    Matcher matcher = _getterPattern.matcher(content);
4351    
4352                    Set<String> getters = new HashSet<String>();
4353    
4354                    while (!matcher.hitEnd()) {
4355                            boolean found = matcher.find();
4356    
4357                            if (found) {
4358                                    String property = matcher.group();
4359    
4360                                    if (property.indexOf("get") != -1) {
4361                                            property = property.substring(
4362                                                    property.indexOf("get") + 3, property.length() - 1);
4363                                    }
4364                                    else {
4365                                            property = property.substring(
4366                                                    property.indexOf("is") + 2, property.length() - 1);
4367                                    }
4368    
4369                                    if (!entity.hasColumn(property) &&
4370                                            !entity.hasColumn(Introspector.decapitalize(property))) {
4371    
4372                                            property = Introspector.decapitalize(property);
4373    
4374                                            getters.add(property);
4375                                    }
4376                            }
4377                    }
4378    
4379                    matcher = _setterPattern.matcher(content);
4380    
4381                    Set<String> setters = new HashSet<String>();
4382    
4383                    while (!matcher.hitEnd()) {
4384                            boolean found = matcher.find();
4385    
4386                            if (found) {
4387                                    String property = matcher.group();
4388    
4389                                    property = property.substring(
4390                                            property.indexOf("set") + 3, property.length() - 1);
4391    
4392                                    if (!entity.hasColumn(property) &&
4393                                            !entity.hasColumn(Introspector.decapitalize(property))) {
4394    
4395                                            property = Introspector.decapitalize(property);
4396    
4397                                            setters.add(property);
4398                                    }
4399                            }
4400                    }
4401    
4402                    getters.retainAll(setters);
4403    
4404                    List<String> transients = new ArrayList<String>(getters);
4405    
4406                    Collections.sort(transients);
4407    
4408                    return transients;
4409            }
4410    
4411            private String _getTplProperty(String key, String defaultValue) {
4412                    return System.getProperty("service.tpl." + key, defaultValue);
4413            }
4414    
4415            private boolean _hasHttpMethods(JavaClass javaClass) {
4416                    JavaMethod[] methods = _getMethods(javaClass);
4417    
4418                    for (JavaMethod javaMethod : methods) {
4419                            if (!javaMethod.isConstructor() && javaMethod.isPublic() &&
4420                                    isCustomMethod(javaMethod)) {
4421    
4422                                    return true;
4423                            }
4424                    }
4425    
4426                    return false;
4427            }
4428    
4429            private List<Entity> _mergeReferenceList(List<Entity> referenceList) {
4430                    List<Entity> list = new ArrayList<Entity>(
4431                            _ejbList.size() + referenceList.size());
4432    
4433                    list.addAll(_ejbList);
4434                    list.addAll(referenceList);
4435    
4436                    return list;
4437            }
4438    
4439            private String _processTemplate(String name) throws Exception {
4440                    return _processTemplate(name, _getContext());
4441            }
4442    
4443            private String _processTemplate(String name, Map<String, Object> context)
4444                    throws Exception {
4445    
4446                    return StringUtil.replace(
4447                            FreeMarkerUtil.process(name, context), '\r', "");
4448            }
4449    
4450            private static final int _SESSION_TYPE_REMOTE = 0;
4451    
4452            private static final int _SESSION_TYPE_LOCAL = 1;
4453    
4454            private static final String _SQL_CREATE_TABLE = "create table ";
4455    
4456            private static final String _TPL_ROOT =
4457                    "com/liferay/portal/tools/servicebuilder/dependencies/";
4458    
4459            private static Pattern _getterPattern = Pattern.compile(
4460                    "public .* get.*" + Pattern.quote("(") + "|public boolean is.*" +
4461                            Pattern.quote("("));
4462            private static Pattern _setterPattern = Pattern.compile(
4463                    "public void set.*" + Pattern.quote("("));
4464    
4465            private String _tplBadAliasNames =  _TPL_ROOT + "bad_alias_names.txt";
4466            private String _tplBadColumnNames = _TPL_ROOT + "bad_column_names.txt";
4467            private String _tplBadJsonTypes = _TPL_ROOT + "bad_json_types.txt";
4468            private String _tplBadTableNames = _TPL_ROOT + "bad_table_names.txt";
4469            private String _tplEjbPk = _TPL_ROOT + "ejb_pk.ftl";
4470            private String _tplException = _TPL_ROOT + "exception.ftl";
4471            private String _tplExtendedModel = _TPL_ROOT + "extended_model.ftl";
4472            private String _tplExtendedModelImpl =
4473                    _TPL_ROOT + "extended_model_impl.ftl";
4474            private String _tplFinder = _TPL_ROOT + "finder.ftl";
4475            private String _tplFinderUtil = _TPL_ROOT + "finder_util.ftl";
4476            private String _tplHbmXml = _TPL_ROOT + "hbm_xml.ftl";
4477            private String _tplJsonJs = _TPL_ROOT + "json_js.ftl";
4478            private String _tplJsonJsMethod = _TPL_ROOT + "json_js_method.ftl";
4479            private String _tplModel = _TPL_ROOT + "model.ftl";
4480            private String _tplModelClp = _TPL_ROOT + "model_clp.ftl";
4481            private String _tplModelHintsXml = _TPL_ROOT + "model_hints_xml.ftl";
4482            private String _tplModelImpl = _TPL_ROOT + "model_impl.ftl";
4483            private String _tplModelSoap = _TPL_ROOT + "model_soap.ftl";
4484            private String _tplModelWrapper = _TPL_ROOT + "model_wrapper.ftl";
4485            private String _tplOrmXml = _TPL_ROOT + "orm_xml.ftl";
4486            private String _tplPersistence = _TPL_ROOT + "persistence.ftl";
4487            private String _tplPersistenceImpl = _TPL_ROOT + "persistence_impl.ftl";
4488            private String _tplPersistenceTest = _TPL_ROOT + "persistence_test.ftl";
4489            private String _tplPersistenceUtil = _TPL_ROOT + "persistence_util.ftl";
4490            private String _tplProps = _TPL_ROOT + "props.ftl";
4491            private String _tplRemotingXml = _TPL_ROOT + "remoting_xml.ftl";
4492            private String _tplService = _TPL_ROOT + "service.ftl";
4493            private String _tplServiceBaseImpl = _TPL_ROOT + "service_base_impl.ftl";
4494            private String _tplServiceClp = _TPL_ROOT + "service_clp.ftl";
4495            private String _tplServiceClpMessageListener =
4496                    _TPL_ROOT + "service_clp_message_listener.ftl";
4497            private String _tplServiceClpSerializer =
4498                    _TPL_ROOT + "service_clp_serializer.ftl";
4499            private String _tplServiceHttp = _TPL_ROOT + "service_http.ftl";
4500            private String _tplServiceImpl = _TPL_ROOT + "service_impl.ftl";
4501            private String _tplServiceJsonSerializer =
4502                    _TPL_ROOT + "service_json_serializer.ftl";
4503            private String _tplServiceSoap = _TPL_ROOT + "service_soap.ftl";
4504            private String _tplServiceUtil = _TPL_ROOT + "service_util.ftl";
4505            private String _tplServiceWrapper = _TPL_ROOT + "service_wrapper.ftl";
4506            private String _tplSpringBaseXml = _TPL_ROOT + "spring_base_xml.ftl";
4507            private String _tplSpringClusterXml = _TPL_ROOT + "spring_cluster_xml.ftl";
4508            private String _tplSpringDynamicDataSourceXml =
4509                    _TPL_ROOT + "spring_dynamic_data_source_xml.ftl";
4510            private String _tplSpringHibernateXml =
4511                    _TPL_ROOT + "spring_hibernate_xml.ftl";
4512            private String _tplSpringInfrastructureXml =
4513                    _TPL_ROOT + "spring_infrastructure_xml.ftl";
4514            private String _tplSpringShardDataSourceXml =
4515                    _TPL_ROOT + "spring_shard_data_source_xml.ftl";
4516            private String _tplSpringXml = _TPL_ROOT + "spring_xml.ftl";
4517            private Set<String> _badTableNames;
4518            private Set<String> _badAliasNames;
4519            private Set<String> _badColumnNames;
4520            private Set<String> _badJsonTypes;
4521            private String _hbmFileName;
4522            private String _ormFileName;
4523            private String _modelHintsFileName;
4524            private String _springFileName;
4525            private String _springBaseFileName;
4526            private String _springClusterFileName;
4527            private String _springDynamicDataSourceFileName;
4528            private String _springHibernateFileName;
4529            private String _springInfrastructureFileName;
4530            private String _springShardDataSourceFileName;
4531            private String _apiDir;
4532            private String _implDir;
4533            private String _jsonFileName;
4534            private String _remotingFileName;
4535            private String _sqlDir;
4536            private String _sqlFileName;
4537            private String _sqlIndexesFileName;
4538            private String _sqlIndexesPropertiesFileName;
4539            private String _sqlSequencesFileName;
4540            private boolean _autoNamespaceTables;
4541            private String _beanLocatorUtil;
4542            private String _beanLocatorUtilShortName;
4543            private String _propsUtil;
4544            private String _pluginName;
4545            private String _testDir;
4546            private String _author;
4547            private String _portletName = StringPool.BLANK;
4548            private String _portletShortName = StringPool.BLANK;
4549            private String _portletPackageName = StringPool.BLANK;
4550            private String _outputPath;
4551            private String _serviceOutputPath;
4552            private String _testOutputPath;
4553            private String _packagePath;
4554            private List<Entity> _ejbList;
4555            private Map<String, EntityMapping> _entityMappings;
4556            private Map<String, Entity> _entityPool = new HashMap<String, Entity>();
4557    
4558    }