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