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