001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.tools.servicebuilder;
016    
017    import com.liferay.portal.freemarker.FreeMarkerUtil;
018    import com.liferay.portal.kernel.dao.db.IndexMetadata;
019    import com.liferay.portal.kernel.dao.db.IndexMetadataFactoryUtil;
020    import com.liferay.portal.kernel.exception.PortalException;
021    import com.liferay.portal.kernel.exception.SystemException;
022    import com.liferay.portal.kernel.io.unsync.UnsyncBufferedReader;
023    import com.liferay.portal.kernel.io.unsync.UnsyncStringReader;
024    import com.liferay.portal.kernel.util.ArrayUtil;
025    import com.liferay.portal.kernel.util.ArrayUtil_IW;
026    import com.liferay.portal.kernel.util.CharPool;
027    import com.liferay.portal.kernel.util.ClearThreadLocalUtil;
028    import com.liferay.portal.kernel.util.FileUtil;
029    import com.liferay.portal.kernel.util.GetterUtil;
030    import com.liferay.portal.kernel.util.ListUtil;
031    import com.liferay.portal.kernel.util.PropertiesUtil;
032    import com.liferay.portal.kernel.util.StringBundler;
033    import com.liferay.portal.kernel.util.StringPool;
034    import com.liferay.portal.kernel.util.StringUtil;
035    import com.liferay.portal.kernel.util.StringUtil_IW;
036    import com.liferay.portal.kernel.util.TextFormatter;
037    import com.liferay.portal.kernel.util.Time;
038    import com.liferay.portal.kernel.util.Validator;
039    import com.liferay.portal.kernel.util.Validator_IW;
040    import com.liferay.portal.kernel.xml.Document;
041    import com.liferay.portal.kernel.xml.Element;
042    import com.liferay.portal.kernel.xml.SAXReaderUtil;
043    import com.liferay.portal.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("String")) {
1384                            Map<String, String> hints = ModelHintsUtil.getHints(model, field);
1385    
1386                            if (hints != null) {
1387                                    int maxLength = GetterUtil.getInteger(hints.get("max-length"));
1388    
1389                                    if (maxLength == 2000000) {
1390                                            return "CLOB";
1391                                    }
1392                            }
1393    
1394                            return "VARCHAR";
1395                    }
1396                    else {
1397                            return null;
1398                    }
1399            }
1400    
1401            public String getTypeGenericsName(Type type) {
1402                    StringBundler sb = new StringBundler();
1403    
1404                    sb.append(type.getValue());
1405    
1406                    Type[] actualTypeArguments = type.getActualTypeArguments();
1407    
1408                    if (actualTypeArguments != null) {
1409                            sb.append(StringPool.LESS_THAN);
1410    
1411                            for (int i = 0; i < actualTypeArguments.length; i++) {
1412                                    if (i > 0) {
1413                                            sb.append(", ");
1414                                    }
1415    
1416                                    sb.append(getTypeGenericsName(actualTypeArguments[i]));
1417                            }
1418    
1419                            sb.append(StringPool.GREATER_THAN);
1420                    }
1421    
1422                    sb.append(getDimensions(type.getDimensions()));
1423    
1424                    return sb.toString();
1425            }
1426    
1427            public String getVariableName(JavaField field) {
1428                    String fieldName = field.getName();
1429    
1430                    if ((fieldName.length() > 0) && (fieldName.charAt(0) == '_')) {
1431                            fieldName = fieldName.substring(1);
1432                    }
1433    
1434                    return fieldName;
1435            }
1436    
1437            public boolean hasEntityByGenericsName(String genericsName) {
1438                    if (Validator.isNull(genericsName)) {
1439                            return false;
1440                    }
1441    
1442                    if (!genericsName.contains(".model.")) {
1443                            return false;
1444                    }
1445    
1446                    if (getEntityByGenericsName(genericsName) == null) {
1447                            return false;
1448                    }
1449                    else {
1450                            return true;
1451                    }
1452            }
1453    
1454            public boolean hasEntityByParameterTypeValue(String parameterTypeValue) {
1455                    if (Validator.isNull(parameterTypeValue)) {
1456                            return false;
1457                    }
1458    
1459                    if (!parameterTypeValue.contains(".model.")) {
1460                            return false;
1461                    }
1462    
1463                    if (getEntityByParameterTypeValue(parameterTypeValue) == null) {
1464                            return false;
1465                    }
1466                    else {
1467                            return true;
1468                    }
1469            }
1470    
1471            public boolean isBasePersistenceMethod(JavaMethod method) {
1472                    String methodName = method.getName();
1473    
1474                    if (methodName.equals("clearCache") ||
1475                            methodName.equals("findWithDynamicQuery")) {
1476    
1477                            return true;
1478                    }
1479                    else if (methodName.equals("findByPrimaryKey") ||
1480                                     methodName.equals("fetchByPrimaryKey") ||
1481                                     methodName.equals("remove")) {
1482    
1483                            JavaParameter[] parameters = method.getParameters();
1484    
1485                            if ((parameters.length == 1) &&
1486                                    parameters[0].getName().equals("primaryKey")) {
1487    
1488                                    return true;
1489                            }
1490    
1491                            if (methodName.equals("remove")) {
1492                                    Type[] methodExceptions = method.getExceptions();
1493    
1494                                    for (Type methodException : methodExceptions) {
1495                                            String exception = methodException.getValue();
1496    
1497                                            if (exception.contains("NoSuch")) {
1498                                                    return false;
1499                                            }
1500                                    }
1501    
1502                                    return true;
1503                            }
1504                    }
1505    
1506                    return false;
1507            }
1508    
1509            public boolean isCustomMethod(JavaMethod method) {
1510                    String methodName = method.getName();
1511    
1512                    if (methodName.equals("afterPropertiesSet") ||
1513                            methodName.equals("destroy") ||
1514                            methodName.equals("equals") ||
1515                            methodName.equals("getClass") ||
1516                            methodName.equals("hashCode") ||
1517                            methodName.equals("notify") ||
1518                            methodName.equals("notifyAll") ||
1519                            methodName.equals("toString") ||
1520                            methodName.equals("wait")) {
1521    
1522                            return false;
1523                    }
1524                    else if (methodName.equals("getPermissionChecker")) {
1525                            return false;
1526                    }
1527                    else if (methodName.equals("getUser") &&
1528                                     (method.getParameters().length == 0)) {
1529    
1530                            return false;
1531                    }
1532                    else if (methodName.equals("getUserId") &&
1533                                     (method.getParameters().length == 0)) {
1534    
1535                            return false;
1536                    }
1537                    else if (methodName.endsWith("Finder") &&
1538                                     (methodName.startsWith("get") ||
1539                                      methodName.startsWith("set"))) {
1540    
1541                            return false;
1542                    }
1543                    else if (methodName.endsWith("Persistence") &&
1544                                     (methodName.startsWith("get") ||
1545                                      methodName.startsWith("set"))) {
1546    
1547                            return false;
1548                    }
1549                    else if (methodName.endsWith("Service") &&
1550                                     (methodName.startsWith("get") ||
1551                                      methodName.startsWith("set"))) {
1552    
1553                            return false;
1554                    }
1555                    else {
1556                            return true;
1557                    }
1558            }
1559    
1560            public boolean isDuplicateMethod(
1561                    JavaMethod method, Map<String, Object> tempMap) {
1562    
1563                    StringBundler sb = new StringBundler();
1564    
1565                    sb.append("isDuplicateMethod ");
1566                    sb.append(getTypeGenericsName(method.getReturns()));
1567                    sb.append(StringPool.SPACE);
1568                    sb.append(method.getName());
1569                    sb.append(StringPool.OPEN_PARENTHESIS);
1570    
1571                    JavaParameter[] parameters = method.getParameters();
1572    
1573                    for (int i = 0; i < parameters.length; i++) {
1574                            JavaParameter javaParameter = parameters[i];
1575    
1576                            sb.append(getTypeGenericsName(javaParameter.getType()));
1577    
1578                            if ((i + 1) != parameters.length) {
1579                                    sb.append(StringPool.COMMA);
1580                            }
1581                    }
1582    
1583                    sb.append(StringPool.CLOSE_PARENTHESIS);
1584    
1585                    String key = sb.toString();
1586    
1587                    if (tempMap.put(key, key) != null) {
1588                            return true;
1589                    }
1590                    else {
1591                            return false;
1592                    }
1593            }
1594    
1595            public boolean isHBMCamelCasePropertyAccessor(String propertyName) {
1596                    if (propertyName.length() < 3) {
1597                            return false;
1598                    }
1599    
1600                    char[] chars = propertyName.toCharArray();
1601    
1602                    char c0 = chars[0];
1603                    char c1 = chars[1];
1604                    char c2 = chars[2];
1605    
1606                    if (Character.isLowerCase(c0) && Character.isUpperCase(c1) &&
1607                            Character.isLowerCase(c2)) {
1608    
1609                            return true;
1610                    }
1611    
1612                    return false;
1613            }
1614    
1615            public boolean isReadOnlyMethod(
1616                    JavaMethod method, List<String> txRequiredList, String[] prefixes) {
1617    
1618                    String methodName = method.getName();
1619    
1620                    if (isTxRequiredMethod(method, txRequiredList)) {
1621                            return false;
1622                    }
1623    
1624                    for (String prefix : prefixes) {
1625                            if (methodName.startsWith(prefix)) {
1626                                    return true;
1627                            }
1628                    }
1629    
1630                    return false;
1631            }
1632    
1633            public boolean isServiceReadOnlyMethod(
1634                    JavaMethod method, List<String> txRequiredList) {
1635    
1636                    return isReadOnlyMethod(
1637                            method, txRequiredList,
1638                            PropsValues.SERVICE_BUILDER_SERVICE_READ_ONLY_PREFIXES);
1639            }
1640    
1641            public boolean isSoapMethod(JavaMethod method) {
1642                    Type returnType = method.getReturns();
1643    
1644                    String returnTypeGenericsName = getTypeGenericsName(returnType);
1645                    String returnValueName = returnType.getValue();
1646    
1647                    if (returnTypeGenericsName.contains(
1648                                    "com.liferay.portal.kernel.search.") ||
1649                            returnTypeGenericsName.contains("com.liferay.portal.model.Theme") ||
1650                            returnTypeGenericsName.contains(
1651                                    "com.liferay.portlet.social.model.SocialActivityDefinition") ||
1652                            returnTypeGenericsName.equals("java.util.List<java.lang.Object>") ||
1653                            returnValueName.equals("com.liferay.portal.model.Lock") ||
1654                            returnValueName.equals(
1655                                    "com.liferay.portlet.messageboards.model.MBMessageDisplay") ||
1656                            returnValueName.startsWith("java.io") ||
1657                            returnValueName.equals("java.util.Map") ||
1658                            returnValueName.equals("java.util.Properties") ||
1659                            returnValueName.startsWith("javax")) {
1660    
1661                            return false;
1662                    }
1663    
1664                    if (returnTypeGenericsName.contains(
1665                                    "com.liferay.portal.kernel.repository.model.FileEntry") ||
1666                            returnTypeGenericsName.contains(
1667                                    "com.liferay.portal.kernel.repository.model.Folder")) {
1668                    }
1669                    else if (returnTypeGenericsName.contains(
1670                                            "com.liferay.portal.kernel.repository.")) {
1671    
1672                            return false;
1673                    }
1674    
1675                    JavaParameter[] parameters = method.getParameters();
1676    
1677                    for (JavaParameter javaParameter : parameters) {
1678                            Type type = javaParameter.getType();
1679    
1680                            String parameterTypeName = type.getValue() + _getDimensions(type);
1681    
1682                            if (parameterTypeName.equals(
1683                                            "com.liferay.portal.kernel.util.UnicodeProperties") ||
1684                                    parameterTypeName.equals(
1685                                            "com.liferay.portal.theme.ThemeDisplay") ||
1686                                    parameterTypeName.equals(
1687                                            "com.liferay.portlet.PortletPreferencesImpl") ||
1688                                    parameterTypeName.equals(
1689                                            "com.liferay.portlet.dynamicdatamapping.storage.Fields") ||
1690                                    parameterTypeName.startsWith("java.io") ||
1691                                    parameterTypeName.startsWith("java.util.LinkedHashMap") ||
1692                                    //parameterTypeName.startsWith("java.util.List") ||
1693                                    //parameterTypeName.startsWith("java.util.Locale") ||
1694                                    (parameterTypeName.startsWith("java.util.Map") &&
1695                                     !_isStringLocaleMap(javaParameter)) ||
1696                                    parameterTypeName.startsWith("java.util.Properties") ||
1697                                    parameterTypeName.startsWith("javax")) {
1698    
1699                                    return false;
1700                            }
1701                    }
1702    
1703                    return true;
1704            }
1705    
1706            public boolean isTxRequiredMethod(
1707                    JavaMethod method, List<String> txRequiredList) {
1708    
1709                    if (txRequiredList == null) {
1710                            return false;
1711                    }
1712    
1713                    if (txRequiredList.contains(method.getName())) {
1714                            return true;
1715                    }
1716    
1717                    return false;
1718            }
1719    
1720            private static void _addElements(
1721                    Element element, Map<String, Element> elements) {
1722    
1723                    for (Map.Entry<String, Element> entry : elements.entrySet()) {
1724                            Element childElement = entry.getValue();
1725    
1726                            element.add(childElement);
1727                    }
1728            }
1729    
1730            private static Document _getContentDocument(String fileName)
1731                    throws Exception {
1732    
1733                    String content = FileUtil.read(new File(fileName));
1734    
1735                    Document document = UnsecureSAXReaderUtil.read(content);
1736    
1737                    Element rootElement = document.getRootElement();
1738    
1739                    for (Element element : rootElement.elements()) {
1740                            String elementName = element.getName();
1741    
1742                            if (!elementName.equals("service-builder-import")) {
1743                                    continue;
1744                            }
1745    
1746                            element.detach();
1747    
1748                            String dirName = fileName.substring(
1749                                    0, fileName.lastIndexOf(StringPool.SLASH) + 1);
1750                            String serviceBuilderImportFileName = element.attributeValue(
1751                                    "file");
1752    
1753                            Document serviceBuilderImportDocument = _getContentDocument(
1754                                    dirName + serviceBuilderImportFileName);
1755    
1756                            Element serviceBuilderImportRootElement =
1757                                    serviceBuilderImportDocument.getRootElement();
1758    
1759                            for (Element serviceBuilderImportElement :
1760                                            serviceBuilderImportRootElement.elements()) {
1761    
1762                                    serviceBuilderImportElement.detach();
1763    
1764                                    rootElement.add(serviceBuilderImportElement);
1765                            }
1766                    }
1767    
1768                    return document;
1769            }
1770    
1771            private static String _getPackagePath(File file) {
1772                    String fileName = StringUtil.replace(file.toString(), "\\", "/");
1773    
1774                    int x = fileName.indexOf("src/");
1775    
1776                    if (x == -1) {
1777                            x = fileName.indexOf("test/");
1778                    }
1779    
1780                    int y = fileName.lastIndexOf("/");
1781    
1782                    fileName = fileName.substring(x + 4, y);
1783    
1784                    return StringUtil.replace(fileName, "/", ".");
1785            }
1786    
1787            private void _createActionableDynamicQuery(Entity entity) throws Exception {
1788                    Map<String, Object> context = _getContext();
1789    
1790                    context.put("entity", entity);
1791    
1792                    // Content
1793    
1794                    String content = _processTemplate(_tplActionableDynamicQuery, context);
1795    
1796                    // Write file
1797    
1798                    File ejbFile = new File(
1799                            _serviceOutputPath + "/service/persistence/" +
1800                                    entity.getName() + "ActionableDynamicQuery.java");
1801    
1802                    writeFile(ejbFile, content, _author);
1803            }
1804    
1805            private void _createBlobModels(Entity entity) throws Exception {
1806                    List<EntityColumn> blobList = new ArrayList<EntityColumn>(
1807                            entity.getBlobList());
1808    
1809                    Iterator<EntityColumn> itr = blobList.iterator();
1810    
1811                    while (itr.hasNext()) {
1812                            EntityColumn col = itr.next();
1813    
1814                            if (!col.isLazy()) {
1815                                    itr.remove();
1816                            }
1817                    }
1818    
1819                    if (blobList.isEmpty()) {
1820                            return;
1821                    }
1822    
1823                    Map<String, Object> context = _getContext();
1824    
1825                    context.put("entity", entity);
1826    
1827                    for (EntityColumn col : blobList) {
1828                            context.put("column", col);
1829    
1830                            // Content
1831    
1832                            String content = _processTemplate(_tplBlobModel, context);
1833    
1834                            // Write file
1835    
1836                            File blobModelFile = new File(
1837                                    _serviceOutputPath + "/model/" + entity.getName() +
1838                                            col.getMethodName() + "BlobModel.java");
1839    
1840                            writeFile(blobModelFile, content, _author);
1841                    }
1842            }
1843    
1844            private void _createEJBPK(Entity entity) throws Exception {
1845                    Map<String, Object> context = _getContext();
1846    
1847                    context.put("entity", entity);
1848    
1849                    // Content
1850    
1851                    String content = _processTemplate(_tplEjbPk, context);
1852    
1853                    // Write file
1854    
1855                    File ejbFile = new File(
1856                            _serviceOutputPath + "/service/persistence/" +
1857                                    entity.getPKClassName() + ".java");
1858    
1859                    writeFile(ejbFile, content, _author);
1860            }
1861    
1862            private void _createExceptions(List<String> exceptions) throws Exception {
1863                    for (int i = 0; i < _ejbList.size(); i++) {
1864                            Entity entity = _ejbList.get(i);
1865    
1866                            if (!_isTargetEntity(entity)) {
1867                                    continue;
1868                            }
1869    
1870                            if (entity.hasColumns()) {
1871                                    exceptions.add(getNoSuchEntityException(entity));
1872                            }
1873                    }
1874    
1875                    for (String exception : exceptions) {
1876                            File exceptionFile = new File(
1877                                    _serviceOutputPath + "/" + exception + "Exception.java");
1878    
1879                            if (!exceptionFile.exists()) {
1880                                    Map<String, Object> context = _getContext();
1881    
1882                                    context.put("exception", exception);
1883    
1884                                    String content = _processTemplate(_tplException, context);
1885    
1886                                    if (exception.startsWith("NoSuch")) {
1887                                            content = StringUtil.replace(
1888                                                    content, "PortalException", "NoSuchModelException");
1889                                            content = StringUtil.replace(
1890                                                    content, "kernel.exception.NoSuchModelException",
1891                                                    "NoSuchModelException");
1892                                    }
1893    
1894                                    content = StringUtil.replace(content, "\r\n", "\n");
1895    
1896                                    FileUtil.write(exceptionFile, content);
1897                            }
1898    
1899                            if (exception.startsWith("NoSuch")) {
1900                                    String content = FileUtil.read(exceptionFile);
1901    
1902                                    if (!content.contains("NoSuchModelException")) {
1903                                            content = StringUtil.replace(
1904                                                    content, "PortalException", "NoSuchModelException");
1905                                            content = StringUtil.replace(
1906                                                    content, "kernel.exception.NoSuchModelException",
1907                                                    "NoSuchModelException");
1908    
1909                                            FileUtil.write(exceptionFile, content);
1910                                    }
1911                            }
1912    
1913                            if (!_serviceOutputPath.equals(_outputPath)) {
1914                                    exceptionFile = new File(
1915                                            _outputPath + "/" + exception + "Exception.java");
1916    
1917                                    if (exceptionFile.exists()) {
1918                                            System.out.println("Relocating " + exceptionFile);
1919    
1920                                            exceptionFile.delete();
1921                                    }
1922                            }
1923                    }
1924            }
1925    
1926            private void _createExportActionableDynamicQuery(Entity entity)
1927                    throws Exception {
1928    
1929                    Map<String, Object> context = _getContext();
1930    
1931                    context.put("entity", entity);
1932    
1933                    // Content
1934    
1935                    String content = _processTemplate(
1936                            _tplExportActionableDynamicQuery, context);
1937    
1938                    // Write file
1939    
1940                    File ejbFile = new File(
1941                            _serviceOutputPath + "/service/persistence/" +
1942                                    entity.getName() + "ExportActionableDynamicQuery.java");
1943    
1944                    writeFile(ejbFile, content, _author);
1945            }
1946    
1947            private void _createExtendedModel(Entity entity) throws Exception {
1948                    JavaClass modelImplJavaClass = _getJavaClass(
1949                            _outputPath + "/model/impl/" + entity.getName() + "Impl.java");
1950    
1951                    List<JavaMethod> methods = ListUtil.fromArray(
1952                            _getMethods(modelImplJavaClass));
1953    
1954                    Iterator<JavaMethod> itr = methods.iterator();
1955    
1956                    while (itr.hasNext()) {
1957                            JavaMethod method = itr.next();
1958    
1959                            String methodName = method.getName();
1960    
1961                            if (methodName.equals("getStagedModelType")) {
1962                                    itr.remove();
1963                            }
1964                    }
1965    
1966                    JavaClass modelJavaClass = _getJavaClass(
1967                            _serviceOutputPath + "/model/" + entity.getName() + "Model.java");
1968    
1969                    for (JavaMethod method : _getMethods(modelJavaClass)) {
1970                            methods.remove(method);
1971                    }
1972    
1973                    Map<String, Object> context = _getContext();
1974    
1975                    context.put("entity", entity);
1976                    context.put("methods", methods.toArray(new Object[methods.size()]));
1977    
1978                    // Content
1979    
1980                    String content = _processTemplate(_tplExtendedModel, context);
1981    
1982                    // Write file
1983    
1984                    File modelFile = new File(
1985                            _serviceOutputPath + "/model/" + entity.getName() + ".java");
1986    
1987                    writeFile(modelFile, content, _author);
1988    
1989                    if (!_serviceOutputPath.equals(_outputPath)) {
1990                            modelFile = new File(
1991                                    _outputPath + "/model/" + entity.getName() + ".java");
1992    
1993                            if (modelFile.exists()) {
1994                                    System.out.println("Relocating " + modelFile);
1995    
1996                                    modelFile.delete();
1997                            }
1998                    }
1999            }
2000    
2001            private void _createExtendedModelBaseImpl(Entity entity) throws Exception {
2002                    Map<String, Object> context = _getContext();
2003    
2004                    context.put("entity", entity);
2005    
2006                    // Content
2007    
2008                    String content = _processTemplate(_tplExtendedModelBaseImpl, context);
2009    
2010                    // Write file
2011    
2012                    File modelFile = new File(
2013                            _outputPath + "/model/impl/" + entity.getName() + "BaseImpl.java");
2014    
2015                    writeFile(modelFile, content, _author);
2016            }
2017    
2018            private void _createExtendedModelImpl(Entity entity) throws Exception {
2019                    Map<String, Object> context = _getContext();
2020    
2021                    context.put("entity", entity);
2022    
2023                    // Content
2024    
2025                    String content = _processTemplate(_tplExtendedModelImpl, context);
2026    
2027                    // Write file
2028    
2029                    File modelFile = new File(
2030                            _outputPath + "/model/impl/" + entity.getName() + "Impl.java");
2031    
2032                    if (modelFile.exists()) {
2033                            content = FileUtil.read(modelFile);
2034    
2035                            content = content.replaceAll(
2036                                    "extends\\s+" + entity.getName() +
2037                                            "ModelImpl\\s+implements\\s+" + entity.getName(),
2038                                    "extends " + entity.getName() + "BaseImpl");
2039    
2040                            writeFileRaw(modelFile, content);
2041                    }
2042                    else {
2043                            writeFile(modelFile, content, _author);
2044                    }
2045            }
2046    
2047            private void _createFinder(Entity entity) throws Exception {
2048                    if (!entity.hasFinderClass()) {
2049                            return;
2050                    }
2051    
2052                    JavaClass javaClass = _getJavaClass(
2053                            _outputPath + "/service/persistence/" + entity.getName() +
2054                                    "FinderImpl.java");
2055    
2056                    Map<String, Object> context = _getContext();
2057    
2058                    context.put("entity", entity);
2059                    context.put("methods", _getMethods(javaClass));
2060    
2061                    // Content
2062    
2063                    String content = _processTemplate(_tplFinder, context);
2064    
2065                    // Write file
2066    
2067                    File ejbFile = new File(
2068                            _serviceOutputPath + "/service/persistence/" + entity.getName() +
2069                                    "Finder.java");
2070    
2071                    writeFile(ejbFile, content, _author);
2072    
2073                    if (!_serviceOutputPath.equals(_outputPath)) {
2074                            ejbFile = new File(
2075                                    _outputPath + "/service/persistence/" + entity.getName() +
2076                                            "Finder.java");
2077    
2078                            if (ejbFile.exists()) {
2079                                    System.out.println("Relocating " + ejbFile);
2080    
2081                                    ejbFile.delete();
2082                            }
2083                    }
2084            }
2085    
2086            private void _createFinderUtil(Entity entity) throws Exception {
2087                    if (!entity.hasFinderClass()) {
2088                            return;
2089                    }
2090    
2091                    JavaClass javaClass = _getJavaClass(
2092                            _outputPath + "/service/persistence/" + entity.getName() +
2093                                    "FinderImpl.java");
2094    
2095                    Map<String, Object> context = _getContext();
2096    
2097                    context.put("entity", entity);
2098                    context.put("methods", _getMethods(javaClass));
2099    
2100                    // Content
2101    
2102                    String content = _processTemplate(_tplFinderUtil, context);
2103    
2104                    // Write file
2105    
2106                    File ejbFile = new File(
2107                            _serviceOutputPath + "/service/persistence/" + entity.getName() +
2108                                    "FinderUtil.java");
2109    
2110                    writeFile(ejbFile, content, _author);
2111    
2112                    if (!_serviceOutputPath.equals(_outputPath)) {
2113                            ejbFile = new File(
2114                                    _outputPath + "/service/persistence/" + entity.getName() +
2115                                            "FinderUtil.java");
2116    
2117                            if (ejbFile.exists()) {
2118                                    System.out.println("Relocating " + ejbFile);
2119    
2120                                    ejbFile.delete();
2121                            }
2122                    }
2123            }
2124    
2125            private void _createHbm(Entity entity) {
2126                    File ejbFile = new File(
2127                            _outputPath + "/service/persistence/" + entity.getName() +
2128                                    "HBM.java");
2129    
2130                    if (ejbFile.exists()) {
2131                            System.out.println("Removing deprecated " + ejbFile);
2132    
2133                            ejbFile.delete();
2134                    }
2135            }
2136    
2137            private void _createHbmUtil(Entity entity) {
2138                    File ejbFile = new File(
2139                            _outputPath + "/service/persistence/" + entity.getName() +
2140                                    "HBMUtil.java");
2141    
2142                    if (ejbFile.exists()) {
2143                            System.out.println("Removing deprecated " + ejbFile);
2144    
2145                            ejbFile.delete();
2146                    }
2147            }
2148    
2149            private void _createHbmXml() throws Exception {
2150                    Map<String, Object> context = _getContext();
2151    
2152                    context.put("entities", _ejbList);
2153    
2154                    // Content
2155    
2156                    String content = _processTemplate(_tplHbmXml, context);
2157    
2158                    int lastImportStart = content.lastIndexOf("<import class=");
2159                    int lastImportEnd = content.indexOf("/>", lastImportStart) + 3;
2160    
2161                    String imports = content.substring(0, lastImportEnd);
2162    
2163                    content = content.substring(lastImportEnd + 1);
2164    
2165                    File xmlFile = new File(_hbmFileName);
2166    
2167                    if (!xmlFile.exists()) {
2168                            String xml =
2169                                    "<?xml version=\"1.0\"?>\n" +
2170                                    "<!DOCTYPE hibernate-mapping PUBLIC \"-//Hibernate/Hibernate Mapping DTD 3.0//EN\" \"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd\">\n" +
2171                                    "\n" +
2172                                    "<hibernate-mapping default-lazy=\"false\" auto-import=\"false\">\n" +
2173                                    "</hibernate-mapping>";
2174    
2175                            FileUtil.write(xmlFile, xml);
2176                    }
2177    
2178                    String oldContent = FileUtil.read(xmlFile);
2179                    String newContent = _fixHbmXml(oldContent);
2180    
2181                    int firstImport = newContent.indexOf(
2182                            "<import class=\"" + _packagePath + ".model.");
2183                    int lastImport = newContent.lastIndexOf(
2184                            "<import class=\"" + _packagePath + ".model.");
2185    
2186                    if (firstImport == -1) {
2187                            int x = newContent.indexOf("<class");
2188    
2189                            if (x != -1) {
2190                                    newContent =
2191                                            newContent.substring(0, x) + imports +
2192                                                    newContent.substring(x);
2193                            }
2194                            else {
2195                                    content = imports + content;
2196                            }
2197                    }
2198                    else {
2199                            firstImport = newContent.indexOf("<import", firstImport) - 1;
2200                            lastImport = newContent.indexOf("/>", lastImport) + 3;
2201    
2202                            newContent =
2203                                    newContent.substring(0, firstImport) + imports +
2204                                            newContent.substring(lastImport);
2205                    }
2206    
2207                    int firstClass = newContent.indexOf(
2208                            "<class name=\"" + _packagePath + ".model.");
2209                    int lastClass = newContent.lastIndexOf(
2210                            "<class name=\"" + _packagePath + ".model.");
2211    
2212                    if (firstClass == -1) {
2213                            int x = newContent.indexOf("</hibernate-mapping>");
2214    
2215                            if (x != -1) {
2216                                    newContent =
2217                                            newContent.substring(0, x) + content +
2218                                                    newContent.substring(x);
2219                            }
2220                    }
2221                    else {
2222                            firstClass = newContent.lastIndexOf("<class", firstClass) - 1;
2223                            lastClass = newContent.indexOf("</class>", lastClass) + 9;
2224    
2225                            newContent =
2226                                    newContent.substring(0, firstClass) + content +
2227                                            newContent.substring(lastClass);
2228                    }
2229    
2230                    newContent = _formatXml(newContent);
2231    
2232                    if (!oldContent.equals(newContent)) {
2233                            FileUtil.write(xmlFile, newContent);
2234                    }
2235            }
2236    
2237            private void _createModel(Entity entity) throws Exception {
2238                    Map<String, Object> context = _getContext();
2239    
2240                    context.put("entity", entity);
2241    
2242                    // Content
2243    
2244                    String content = _processTemplate(_tplModel, context);
2245    
2246                    // Write file
2247    
2248                    File modelFile = new File(
2249                            _serviceOutputPath + "/model/" + entity.getName() + "Model.java");
2250    
2251                    writeFile(modelFile, content, _author);
2252    
2253                    if (!_serviceOutputPath.equals(_outputPath)) {
2254                            modelFile = new File(
2255                                    _outputPath + "/model/" + entity.getName() + "Model.java");
2256    
2257                            if (modelFile.exists()) {
2258                                    System.out.println("Relocating " + modelFile);
2259    
2260                                    modelFile.delete();
2261                            }
2262                    }
2263            }
2264    
2265            private void _createModelCache(Entity entity) throws Exception {
2266                    JavaClass javaClass = _getJavaClass(
2267                            _outputPath + "/model/impl/" + entity.getName() + "Impl.java");
2268    
2269                    Map<String, Object> context = _getContext();
2270    
2271                    context.put("entity", entity);
2272                    context.put("cacheFields", _getCacheFields(javaClass));
2273    
2274                    // Content
2275    
2276                    String content = _processTemplate(_tplModelCache, context);
2277    
2278                    // Write file
2279    
2280                    File modelFile = new File(
2281                            _outputPath + "/model/impl/" + entity.getName() +
2282                                    "CacheModel.java");
2283    
2284                    writeFile(modelFile, content, _author);
2285            }
2286    
2287            private void _createModelClp(Entity entity) throws Exception {
2288                    if (Validator.isNull(_pluginName)) {
2289                            return;
2290                    }
2291    
2292                    JavaClass javaClass = _getJavaClass(
2293                            _outputPath + "/model/impl/" + entity.getName() + "Impl.java");
2294    
2295                    Map<String, JavaMethod> methods = new HashMap<String, JavaMethod>();
2296    
2297                    for (JavaMethod method : javaClass.getMethods()) {
2298                            methods.put(method.getDeclarationSignature(false), method);
2299                    }
2300    
2301                    Type superClass = javaClass.getSuperClass();
2302    
2303                    String superClassValue = superClass.getValue();
2304    
2305                    while (!superClassValue.endsWith("BaseModelImpl")) {
2306                            int pos = superClassValue.lastIndexOf(StringPool.PERIOD);
2307    
2308                            if (pos > 0) {
2309                                    superClassValue = superClassValue.substring(pos + 1);
2310                            }
2311    
2312                            javaClass = _getJavaClass(
2313                                    _outputPath + "/model/impl/" + superClassValue + ".java");
2314    
2315                            for (JavaMethod method : _getMethods(javaClass)) {
2316                                    methods.remove(method.getDeclarationSignature(false));
2317                            }
2318    
2319                            superClass = javaClass.getSuperClass();
2320                            superClassValue = superClass.getValue();
2321                    }
2322    
2323                    Map<String, Object> context = _getContext();
2324    
2325                    context.put("entity", entity);
2326                    context.put("methods", methods.values());
2327    
2328                    // Content
2329    
2330                    String content = _processTemplate(_tplModelClp, context);
2331    
2332                    // Write file
2333    
2334                    File modelFile = new File(
2335                            _serviceOutputPath + "/model/" + entity.getName() + "Clp.java");
2336    
2337                    writeFile(modelFile, content, _author);
2338            }
2339    
2340            private void _createModelHintsXml() throws Exception {
2341                    Map<String, Object> context = _getContext();
2342    
2343                    context.put("entities", _ejbList);
2344    
2345                    // Content
2346    
2347                    String content = _processTemplate(_tplModelHintsXml, context);
2348    
2349                    File xmlFile = new File(_modelHintsFileName);
2350    
2351                    if (!xmlFile.exists()) {
2352                            String xml =
2353                                    "<?xml version=\"1.0\"?>\n" +
2354                                    "\n" +
2355                                    "<model-hints>\n" +
2356                                    "</model-hints>";
2357    
2358                            FileUtil.write(xmlFile, xml);
2359                    }
2360    
2361                    String oldContent = FileUtil.read(xmlFile);
2362                    String newContent = oldContent;
2363    
2364                    int firstModel = newContent.indexOf(
2365                            "<model name=\"" + _packagePath + ".model.");
2366                    int lastModel = newContent.lastIndexOf(
2367                            "<model name=\"" + _packagePath + ".model.");
2368    
2369                    if (firstModel == -1) {
2370                            int x = newContent.indexOf("</model-hints>");
2371    
2372                            newContent =
2373                                    newContent.substring(0, x) + content +
2374                                            newContent.substring(x);
2375                    }
2376                    else {
2377                            firstModel = newContent.lastIndexOf("<model", firstModel) - 1;
2378                            lastModel = newContent.indexOf("</model>", lastModel) + 9;
2379    
2380                            newContent =
2381                                    newContent.substring(0, firstModel) + content +
2382                                            newContent.substring(lastModel);
2383                    }
2384    
2385                    newContent = _formatXml(newContent);
2386    
2387                    if (!oldContent.equals(newContent)) {
2388                            FileUtil.write(xmlFile, newContent);
2389                    }
2390            }
2391    
2392            private void _createModelImpl(Entity entity) throws Exception {
2393                    JavaClass javaClass = _getJavaClass(
2394                            _outputPath + "/model/impl/" + entity.getName() + "Impl.java");
2395    
2396                    Map<String, Object> context = _getContext();
2397    
2398                    context.put("entity", entity);
2399                    context.put("cacheFields", _getCacheFields(javaClass));
2400    
2401                    // Content
2402    
2403                    String content = _processTemplate(_tplModelImpl, context);
2404    
2405                    // Write file
2406    
2407                    File modelFile = new File(
2408                            _outputPath + "/model/impl/" + entity.getName() + "ModelImpl.java");
2409    
2410                    writeFile(modelFile, content, _author);
2411            }
2412    
2413            private void _createModelSoap(Entity entity) throws Exception {
2414                    File modelFile = null;
2415    
2416                    if (!_serviceOutputPath.equals(_outputPath)) {
2417                            modelFile = new File(
2418                                    _outputPath + "/model/" + entity.getName() + "Soap.java");
2419    
2420                            if (modelFile.exists()) {
2421                                    System.out.println("Relocating " + modelFile);
2422    
2423                                    modelFile.delete();
2424                            }
2425                    }
2426    
2427                    modelFile = new File(
2428                            _serviceOutputPath + "/model/" + entity.getName() + "Soap.java");
2429    
2430                    Map<String, Object> context = _getContext();
2431    
2432                    context.put("entity", entity);
2433    
2434                    // Content
2435    
2436                    String content = _processTemplate(_tplModelSoap, context);
2437    
2438                    // Write file
2439    
2440                    writeFile(modelFile, content, _author);
2441            }
2442    
2443            private void _createModelWrapper(Entity entity) throws Exception {
2444                    JavaClass modelJavaClass = _getJavaClass(
2445                            _serviceOutputPath + "/model/" + entity.getName() + "Model.java");
2446    
2447                    Object[] methods = _getMethods(modelJavaClass);
2448    
2449                    JavaClass extendedModelBaseImplJavaClass = _getJavaClass(
2450                            _outputPath + "/model/impl/" + entity.getName() + "BaseImpl.java");
2451    
2452                    methods = ArrayUtil.append(
2453                            methods, _getMethods(extendedModelBaseImplJavaClass));
2454    
2455                    JavaClass extendedModelJavaClass = _getJavaClass(
2456                            _serviceOutputPath + "/model/" + entity.getName() + ".java");
2457    
2458                    methods = ArrayUtil.append(
2459                            methods, _getMethods(extendedModelJavaClass));
2460    
2461                    Map<String, Object> context = _getContext();
2462    
2463                    context.put("entity", entity);
2464                    context.put("methods", methods);
2465    
2466                    // Content
2467    
2468                    String content = _processTemplate(_tplModelWrapper, context);
2469    
2470                    // Write file
2471    
2472                    File modelFile = new File(
2473                            _serviceOutputPath + "/model/" + entity.getName() + "Wrapper.java");
2474    
2475                    writeFile(modelFile, content, _author);
2476            }
2477    
2478            private void _createOrmXml() throws Exception {
2479                    Map<String, Object> context = _getContext();
2480    
2481                    context.put("entities", _ejbList);
2482    
2483                    // Content
2484    
2485                    String content = _processTemplate(_tplOrmXml, context);
2486    
2487                    String mappedClasses = "";
2488    
2489                    int lastMappedClassStart = content.lastIndexOf("<mapped-superclass");
2490    
2491                    if (lastMappedClassStart != -1) {
2492                            int lastMappedClassEnd = content.indexOf(
2493                                    "</mapped-superclass>", lastMappedClassStart) + 20;
2494    
2495                            mappedClasses = content.substring(0, lastMappedClassEnd);
2496    
2497                            content = content.substring(lastMappedClassEnd + 1);
2498                    }
2499    
2500                    File xmlFile = new File(_ormFileName);
2501    
2502                    if (!xmlFile.exists()) {
2503                            String xml =
2504                                    "<?xml version=\"1.0\"?>\n" +
2505                                    "<entity-mappings version=\"1.0\" xmlns=\"http://java.sun.com/xml/ns/persistence/orm\"\n" +
2506                                    "\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
2507                                    "\txsi:schemaLocation=\"http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_1_0.xsd\"\n" +
2508                                    ">\n" +
2509                                    "<persistence-unit-metadata>\n" +
2510                                    "\t<xml-mapping-metadata-complete />\n" +
2511                                    "\t<persistence-unit-defaults>\n" +
2512                                    "\t\t<access>PROPERTY</access>\n" +
2513                                    "\t</persistence-unit-defaults>\n" +
2514                                    "</persistence-unit-metadata>\n" +
2515                                    "</entity-mappings>";
2516    
2517                            FileUtil.write(xmlFile, xml);
2518                    }
2519    
2520                    String oldContent = FileUtil.read(xmlFile);
2521                    String newContent = oldContent;
2522    
2523                    int firstMappedClass = newContent.indexOf(
2524                            "<mapped-superclass class=\"" + _packagePath + ".model.");
2525                    int lastMappedClass = newContent.lastIndexOf(
2526                            "<mapped-superclass class=\"" + _packagePath + ".model.");
2527    
2528                    if (firstMappedClass == -1) {
2529                            int x = newContent.indexOf("<entity class=");
2530    
2531                            if (x != -1) {
2532                                    newContent =
2533                                            newContent.substring(0, x) + mappedClasses +
2534                                                    newContent.substring(x);
2535                            }
2536                            else {
2537                                    content = mappedClasses + content;
2538                            }
2539                    }
2540                    else {
2541                            firstMappedClass = newContent.indexOf(
2542                                    "<mapped-superclass", firstMappedClass) - 1;
2543                            lastMappedClass = newContent.indexOf(
2544                                    "</mapped-superclass>", lastMappedClass) + 20;
2545    
2546                            newContent =
2547                                    newContent.substring(0, firstMappedClass) + mappedClasses +
2548                                            newContent.substring(lastMappedClass);
2549                    }
2550    
2551                    int firstEntity = newContent.indexOf(
2552                            "<entity class=\"" + _packagePath + ".model.impl.");
2553                    int lastEntity = newContent.lastIndexOf(
2554                            "<entity class=\"" + _packagePath + ".model.impl.");
2555    
2556                    if (firstEntity == -1) {
2557                            int x = newContent.indexOf("</entity-mappings>");
2558    
2559                            if (x != -1) {
2560                                    newContent =
2561                                            newContent.substring(0, x) + content +
2562                                                    newContent.substring(x);
2563                            }
2564                    }
2565                    else {
2566                            firstEntity = newContent.lastIndexOf("<entity", firstEntity) - 1;
2567                            lastEntity = newContent.indexOf("</entity>", lastEntity) + 9;
2568    
2569                            newContent =
2570                                    newContent.substring(0, firstEntity) + content +
2571                                            newContent.substring(lastEntity);
2572                    }
2573    
2574                    newContent = _formatXml(newContent);
2575    
2576                    newContent = StringUtil.replace(
2577                            newContent,
2578                            new String[] {"<attributes></attributes>", "<attributes/>"},
2579                            new String[] {"<attributes />", "<attributes />"});
2580    
2581                    if (!oldContent.equals(newContent)) {
2582                            FileUtil.write(xmlFile, newContent);
2583                    }
2584            }
2585    
2586            private void _createPersistence(Entity entity) throws Exception {
2587                    JavaClass javaClass = _getJavaClass(
2588                            _outputPath + "/service/persistence/" + entity.getName() +
2589                                    "PersistenceImpl.java");
2590    
2591                    Map<String, Object> context = _getContext();
2592    
2593                    context.put("entity", entity);
2594                    context.put("methods", _getMethods(javaClass));
2595    
2596                    // Content
2597    
2598                    String content = _processTemplate(_tplPersistence, context);
2599    
2600                    // Write file
2601    
2602                    File ejbFile = new File(
2603                            _serviceOutputPath + "/service/persistence/" + entity.getName() +
2604                                    "Persistence.java");
2605    
2606                    writeFile(ejbFile, content, _author);
2607    
2608                    if (!_serviceOutputPath.equals(_outputPath)) {
2609                            ejbFile = new File(
2610                                    _outputPath + "/service/persistence/" + entity.getName() +
2611                                            "Persistence.java");
2612    
2613                            if (ejbFile.exists()) {
2614                                    System.out.println("Relocating " + ejbFile);
2615    
2616                                    ejbFile.delete();
2617                            }
2618                    }
2619            }
2620    
2621            private void _createPersistenceImpl(Entity entity) throws Exception {
2622                    Map<String, Object> context = _getContext();
2623    
2624                    context.put("entity", entity);
2625                    context.put(
2626                            "referenceList", _mergeReferenceList(entity.getReferenceList()));
2627    
2628                    // Content
2629    
2630                    Logger.selectLoggerLibrary(Logger.LIBRARY_NONE);
2631    
2632                    String content = _processTemplate(_tplPersistenceImpl, context);
2633    
2634                    Logger.selectLoggerLibrary(Logger.LIBRARY_AUTO);
2635    
2636                    // Write file
2637    
2638                    File ejbFile = new File(
2639                            _outputPath + "/service/persistence/" + entity.getName() +
2640                                    "PersistenceImpl.java");
2641    
2642                    writeFile(ejbFile, content, _author);
2643            }
2644    
2645            private void _createPersistenceTest(Entity entity) throws Exception {
2646                    Map<String, Object> context = _getContext();
2647    
2648                    context.put("entity", entity);
2649    
2650                    // Content
2651    
2652                    String content = _processTemplate(_tplPersistenceTest, context);
2653    
2654                    // Write file
2655    
2656                    File ejbFile = new File(
2657                            _testOutputPath + "/service/persistence/" + entity.getName() +
2658                                    "PersistenceTest.java");
2659    
2660                    writeFile(ejbFile, content, _author);
2661            }
2662    
2663            private void _createPersistenceUtil(Entity entity) throws Exception {
2664                    JavaClass javaClass = _getJavaClass(
2665                            _outputPath + "/service/persistence/" + entity.getName() +
2666                                    "PersistenceImpl.java");
2667    
2668                    Map<String, Object> context = _getContext();
2669    
2670                    context.put("entity", entity);
2671                    context.put("methods", _getMethods(javaClass));
2672    
2673                    // Content
2674    
2675                    String content = _processTemplate(_tplPersistenceUtil, context);
2676    
2677                    // Write file
2678    
2679                    File ejbFile = new File(
2680                            _serviceOutputPath + "/service/persistence/" + entity.getName() +
2681                                    "Util.java");
2682    
2683                    writeFile(ejbFile, content, _author);
2684    
2685                    if (!_serviceOutputPath.equals(_outputPath)) {
2686                            ejbFile = new File(
2687                                    _outputPath + "/service/persistence/" + entity.getName() +
2688                                            "Util.java");
2689    
2690                            if (ejbFile.exists()) {
2691                                    System.out.println("Relocating " + ejbFile);
2692    
2693                                    ejbFile.delete();
2694                            }
2695                    }
2696            }
2697    
2698            private void _createPool(Entity entity) {
2699                    File ejbFile = new File(
2700                            _outputPath + "/service/persistence/" + entity.getName() +
2701                                    "Pool.java");
2702    
2703                    if (ejbFile.exists()) {
2704                            System.out.println("Removing deprecated " + ejbFile);
2705    
2706                            ejbFile.delete();
2707                    }
2708            }
2709    
2710            private void _createProps() throws Exception {
2711                    if (Validator.isNull(_pluginName)) {
2712                            return;
2713                    }
2714    
2715                    // Content
2716    
2717                    File propsFile = new File(_implDir + "/service.properties");
2718    
2719                    long buildNumber = 1;
2720                    long buildDate = System.currentTimeMillis();
2721    
2722                    if (propsFile.exists()) {
2723                            Properties properties = PropertiesUtil.load(
2724                                    FileUtil.read(propsFile));
2725    
2726                            if (!_buildNumberIncrement) {
2727                                    buildDate = GetterUtil.getLong(
2728                                            properties.getProperty("build.date"));
2729                                    buildNumber = GetterUtil.getLong(
2730                                            properties.getProperty("build.number"));
2731                            }
2732                            else {
2733                                    buildNumber = GetterUtil.getLong(
2734                                            properties.getProperty("build.number")) + 1;
2735                            }
2736                    }
2737    
2738                    if (!_buildNumberIncrement && (buildNumber < _buildNumber)) {
2739                            buildNumber = _buildNumber;
2740                            buildDate = System.currentTimeMillis();
2741                    }
2742    
2743                    Map<String, Object> context = _getContext();
2744    
2745                    context.put("buildNumber", buildNumber);
2746                    context.put("currentTimeMillis", buildDate);
2747    
2748                    String content = _processTemplate(_tplProps, context);
2749    
2750                    // Write file
2751    
2752                    FileUtil.write(propsFile, content, true);
2753            }
2754    
2755            private void _createRemotingXml() throws Exception {
2756                    StringBundler sb = new StringBundler();
2757    
2758                    Document document = UnsecureSAXReaderUtil.read(new File(_springFileName));
2759    
2760                    Element rootElement = document.getRootElement();
2761    
2762                    List<Element> beanElements = rootElement.elements("bean");
2763    
2764                    for (Element beanElement : beanElements) {
2765                            String beanId = beanElement.attributeValue("id");
2766    
2767                            if (beanId.endsWith("Service") &&
2768                                    !beanId.endsWith("LocalService")) {
2769    
2770                                    String entityName = beanId;
2771    
2772                                    entityName = StringUtil.replaceLast(
2773                                            entityName, ".service.", ".");
2774    
2775                                    int pos = entityName.lastIndexOf("Service");
2776    
2777                                    entityName = entityName.substring(0, pos);
2778    
2779                                    Entity entity = getEntity(entityName);
2780    
2781                                    String serviceName = beanId;
2782    
2783                                    String serviceMapping = serviceName;
2784    
2785                                    serviceMapping = StringUtil.replaceLast(
2786                                            serviceMapping, ".service.", ".service.spring.");
2787                                    serviceMapping = StringUtil.replace(
2788                                            serviceMapping, StringPool.PERIOD, StringPool.UNDERLINE);
2789    
2790                                    Map<String, Object> context = _getContext();
2791    
2792                                    context.put("entity", entity);
2793                                    context.put("serviceName", serviceName);
2794                                    context.put("serviceMapping", serviceMapping);
2795    
2796                                    sb.append(_processTemplate(_tplRemotingXml, context));
2797                            }
2798                    }
2799    
2800                    File outputFile = new File(_remotingFileName);
2801    
2802                    if (!outputFile.exists()) {
2803                            return;
2804                    }
2805    
2806                    String content = FileUtil.read(outputFile);
2807                    String newContent = content;
2808    
2809                    int x = content.indexOf("<bean ");
2810                    int y = content.lastIndexOf("</bean>") + 8;
2811    
2812                    if (x != -1) {
2813                            newContent =
2814                                    content.substring(0, x - 1) + sb.toString() +
2815                                            content.substring(y);
2816                    }
2817                    else {
2818                            x = content.indexOf("</beans>");
2819    
2820                            if (x != -1) {
2821                                    newContent =
2822                                            content.substring(0, x) + sb.toString() +
2823                                                    content.substring(x);
2824                            }
2825                            else {
2826                                    x = content.indexOf("<beans/>");
2827                                    y = x + 8;
2828    
2829                                    newContent =
2830                                            content.substring(0, x) + "<beans>" + sb.toString() +
2831                                                    "</beans>" + content.substring(y);
2832                            }
2833                    }
2834    
2835                    newContent = _formatXml(newContent);
2836    
2837                    if (!content.equals(newContent)) {
2838                            FileUtil.write(outputFile, newContent);
2839    
2840                            System.out.println(outputFile.toString());
2841                    }
2842            }
2843    
2844            private void _createService(Entity entity, int sessionType)
2845                    throws Exception {
2846    
2847                    Set<String> imports = new HashSet<String>();
2848    
2849                    JavaClass javaClass = _getJavaClass(
2850                            _outputPath + "/service/impl/" + entity.getName() +
2851                                    _getSessionTypeName(sessionType) + "ServiceImpl.java");
2852    
2853                    JavaSource javaSource = javaClass.getSource();
2854    
2855                    imports.addAll(Arrays.asList(javaSource.getImports()));
2856    
2857                    JavaMethod[] methods = _getMethods(javaClass);
2858    
2859                    Type superClass = javaClass.getSuperClass();
2860    
2861                    String superClassValue = superClass.getValue();
2862    
2863                    if (superClassValue.endsWith(
2864                                    entity.getName() + _getSessionTypeName(sessionType) +
2865                                            "ServiceBaseImpl")) {
2866    
2867                            JavaClass parentJavaClass = _getJavaClass(
2868                                    _outputPath + "/service/base/" + entity.getName() +
2869                                            _getSessionTypeName(sessionType) + "ServiceBaseImpl.java");
2870    
2871                            JavaSource parentJavaSource = parentJavaClass.getSource();
2872    
2873                            imports.addAll(Arrays.asList(parentJavaSource.getImports()));
2874    
2875                            methods = ArrayUtil.append(
2876                                    parentJavaClass.getMethods(), methods);
2877                    }
2878    
2879                    Map<String, Object> context = _getContext();
2880    
2881                    context.put("entity", entity);
2882                    context.put("imports", imports);
2883                    context.put("methods", methods);
2884                    context.put("sessionTypeName", _getSessionTypeName(sessionType));
2885    
2886                    context = _putDeprecatedKeys(context, javaClass);
2887    
2888                    // Content
2889    
2890                    String content = _processTemplate(_tplService, context);
2891    
2892                    // Write file
2893    
2894                    File ejbFile = new File(
2895                            _serviceOutputPath + "/service/" + entity.getName() +
2896                                    _getSessionTypeName(sessionType) + "Service.java");
2897    
2898                    writeFile(ejbFile, content, _author);
2899    
2900                    if (!_serviceOutputPath.equals(_outputPath)) {
2901                            ejbFile = new File(
2902                                    _outputPath + "/service/" + entity.getName() +
2903                                            _getSessionTypeName(sessionType) + "Service.java");
2904    
2905                            if (ejbFile.exists()) {
2906                                    System.out.println("Relocating " + ejbFile);
2907    
2908                                    ejbFile.delete();
2909                            }
2910                    }
2911            }
2912    
2913            private void _createServiceBaseImpl(Entity entity, int sessionType)
2914                    throws Exception {
2915    
2916                    JavaClass javaClass = _getJavaClass(
2917                            _outputPath + "/service/impl/" + entity.getName() +
2918                                    (sessionType != _SESSION_TYPE_REMOTE ? "Local" : "") +
2919                                            "ServiceImpl.java");
2920    
2921                    JavaMethod[] methods = _getMethods(javaClass);
2922    
2923                    Map<String, Object> context = _getContext();
2924    
2925                    context.put("entity", entity);
2926                    context.put("methods", methods);
2927                    context.put("sessionTypeName",_getSessionTypeName(sessionType));
2928                    context.put(
2929                            "referenceList", _mergeReferenceList(entity.getReferenceList()));
2930    
2931                    context = _putDeprecatedKeys(context, javaClass);
2932    
2933                    // Content
2934    
2935                    String content = _processTemplate(_tplServiceBaseImpl, context);
2936    
2937                    // Write file
2938    
2939                    File ejbFile = new File(
2940                            _outputPath + "/service/base/" + entity.getName() +
2941                                    _getSessionTypeName(sessionType) + "ServiceBaseImpl.java");
2942    
2943                    writeFile(ejbFile, content, _author);
2944            }
2945    
2946            private void _createServiceClp(Entity entity, int sessionType)
2947                    throws Exception {
2948    
2949                    if (Validator.isNull(_pluginName)) {
2950                            return;
2951                    }
2952    
2953                    JavaClass javaClass = _getJavaClass(
2954                            _serviceOutputPath + "/service/" + entity.getName() +
2955                                    _getSessionTypeName(sessionType) + "Service.java");
2956    
2957                    Map<String, Object> context = _getContext();
2958    
2959                    context.put("entity", entity);
2960                    context.put("methods", _getMethods(javaClass));
2961                    context.put("sessionTypeName", _getSessionTypeName(sessionType));
2962    
2963                    context = _putDeprecatedKeys(context, javaClass);
2964    
2965                    // Content
2966    
2967                    String content = _processTemplate(_tplServiceClp, context);
2968    
2969                    // Write file
2970    
2971                    File ejbFile = new File(
2972                            _serviceOutputPath + "/service/" + entity.getName() +
2973                                    _getSessionTypeName(sessionType) + "ServiceClp.java");
2974    
2975                    writeFile(ejbFile, content, _author);
2976            }
2977    
2978            private void _createServiceClpInvoker(Entity entity, int sessionType)
2979                    throws Exception {
2980    
2981                    if (Validator.isNull(_pluginName)) {
2982                            return;
2983                    }
2984    
2985                    JavaClass javaClass = _getJavaClass(
2986                            _outputPath + "/service/impl/" + entity.getName() +
2987                                    _getSessionTypeName(sessionType) + "ServiceImpl.java");
2988    
2989                    JavaMethod[] methods = _getMethods(javaClass);
2990    
2991                    Type superClass = javaClass.getSuperClass();
2992    
2993                    String superClassValue = superClass.getValue();
2994    
2995                    if (superClassValue.endsWith(
2996                                    entity.getName() + _getSessionTypeName(sessionType) +
2997                                            "ServiceBaseImpl")) {
2998    
2999                            JavaClass parentJavaClass = _getJavaClass(
3000                                    _outputPath + "/service/base/" + entity.getName() +
3001                                            _getSessionTypeName(sessionType) + "ServiceBaseImpl.java");
3002    
3003                            methods = ArrayUtil.append(
3004                                    parentJavaClass.getMethods(), methods);
3005                    }
3006    
3007                    Map<String, Object> context = _getContext();
3008    
3009                    context.put("entity", entity);
3010                    context.put("methods", methods);
3011                    context.put("sessionTypeName", _getSessionTypeName(sessionType));
3012    
3013                    context = _putDeprecatedKeys(context, javaClass);
3014    
3015                    // Content
3016    
3017                    String content = _processTemplate(_tplServiceClpInvoker, context);
3018    
3019                    // Write file
3020    
3021                    File ejbFile = new File(
3022                            _outputPath + "/service/base/" + entity.getName() +
3023                                    _getSessionTypeName(sessionType) + "ServiceClpInvoker.java");
3024    
3025                    writeFile(ejbFile, content, _author);
3026            }
3027    
3028            private void _createServiceClpMessageListener() throws Exception {
3029                    if (Validator.isNull(_pluginName)) {
3030                            return;
3031                    }
3032    
3033                    Map<String, Object> context = _getContext();
3034    
3035                    context.put("entities", _ejbList);
3036    
3037                    // Content
3038    
3039                    String content = _processTemplate(
3040                            _tplServiceClpMessageListener, context);
3041    
3042                    // Write file
3043    
3044                    File ejbFile = new File(
3045                            _serviceOutputPath + "/service/messaging/ClpMessageListener.java");
3046    
3047                    writeFile(ejbFile, content, _author);
3048            }
3049    
3050            private void _createServiceClpSerializer(List<String> exceptions)
3051                    throws Exception {
3052    
3053                    if (Validator.isNull(_pluginName)) {
3054                            return;
3055                    }
3056    
3057                    Map<String, Object> context = _getContext();
3058    
3059                    context.put("entities", _ejbList);
3060                    context.put("exceptions", exceptions);
3061    
3062                    // Content
3063    
3064                    String content = _processTemplate(_tplServiceClpSerializer, context);
3065    
3066                    // Write file
3067    
3068                    File ejbFile = new File(
3069                            _serviceOutputPath + "/service/ClpSerializer.java");
3070    
3071                    writeFile(ejbFile, content, _author);
3072            }
3073    
3074            private void _createServiceFactory(Entity entity, int sessionType) {
3075                    File ejbFile = new File(
3076                            _serviceOutputPath + "/service/" + entity.getName() +
3077                                    _getSessionTypeName(sessionType) + "ServiceFactory.java");
3078    
3079                    if (ejbFile.exists()) {
3080                            System.out.println("Removing deprecated " + ejbFile);
3081    
3082                            ejbFile.delete();
3083                    }
3084    
3085                    ejbFile = new File(
3086                            _outputPath + "/service/" + entity.getName() +
3087                                    _getSessionTypeName(sessionType) + "ServiceFactory.java");
3088    
3089                    if (ejbFile.exists()) {
3090                            System.out.println("Removing deprecated " + ejbFile);
3091    
3092                            ejbFile.delete();
3093                    }
3094            }
3095    
3096            private void _createServiceHttp(Entity entity) throws Exception {
3097                    JavaClass javaClass = _getJavaClass(
3098                            _outputPath + "/service/impl/" + entity.getName() +
3099                                    "ServiceImpl.java");
3100    
3101                    Map<String, Object> context = _getContext();
3102    
3103                    context.put("entity", entity);
3104                    context.put("methods", _getMethods(javaClass));
3105                    context.put("hasHttpMethods", new Boolean(_hasHttpMethods(javaClass)));
3106    
3107                    context = _putDeprecatedKeys(context, javaClass);
3108    
3109                    // Content
3110    
3111                    String content = _processTemplate(_tplServiceHttp, context);
3112    
3113                    // Write file
3114    
3115                    File ejbFile = new File(
3116                            _outputPath + "/service/http/" + entity.getName() +
3117                                    "ServiceHttp.java");
3118    
3119                    writeFile(ejbFile, content, _author);
3120            }
3121    
3122            private void _createServiceImpl(Entity entity, int sessionType)
3123                    throws Exception {
3124    
3125                    Map<String, Object> context = _getContext();
3126    
3127                    context.put("entity", entity);
3128                    context.put("sessionTypeName", _getSessionTypeName(sessionType));
3129    
3130                    // Content
3131    
3132                    String content = _processTemplate(_tplServiceImpl, context);
3133    
3134                    // Write file
3135    
3136                    File ejbFile = new File(
3137                            _outputPath + "/service/impl/" + entity.getName() +
3138                                    _getSessionTypeName(sessionType) + "ServiceImpl.java");
3139    
3140                    if (!ejbFile.exists()) {
3141                            writeFile(ejbFile, content, _author);
3142                    }
3143            }
3144    
3145            private void _createServiceJson(Entity entity) {
3146                    File ejbFile = new File(
3147                            _outputPath + "/service/http/" + entity.getName() +
3148                                    "ServiceJSON.java");
3149    
3150                    if (ejbFile.exists()) {
3151                            System.out.println("Removing deprecated " + ejbFile);
3152    
3153                            ejbFile.delete();
3154                    }
3155            }
3156    
3157            private void _createServiceJsonSerializer(Entity entity) {
3158                    File ejbFile = new File(
3159                            _serviceOutputPath + "/service/http/" + entity.getName() +
3160                                    "JSONSerializer.java");
3161    
3162                    if (ejbFile.exists()) {
3163                            System.out.println("Removing deprecated " + ejbFile);
3164    
3165                            ejbFile.delete();
3166                    }
3167    
3168                    if (!_serviceOutputPath.equals(_outputPath)) {
3169                            ejbFile = new File(
3170                                    _outputPath + "/service/http/" + entity.getName() +
3171                                            "JSONSerializer.java");
3172    
3173                            if (ejbFile.exists()) {
3174                                    System.out.println("Removing deprecated " + ejbFile);
3175    
3176                                    ejbFile.delete();
3177                            }
3178                    }
3179            }
3180    
3181            private void _createServiceSoap(Entity entity) throws Exception {
3182                    JavaClass javaClass = _getJavaClass(
3183                            _outputPath + "/service/impl/" + entity.getName() +
3184                                    "ServiceImpl.java");
3185    
3186                    Map<String, Object> context = _getContext();
3187    
3188                    context.put("entity", entity);
3189                    context.put("methods", _getMethods(javaClass));
3190    
3191                    context = _putDeprecatedKeys(context, javaClass);
3192    
3193                    // Content
3194    
3195                    String content = _processTemplate(_tplServiceSoap, context);
3196    
3197                    // Write file
3198    
3199                    File ejbFile = new File(
3200                            _outputPath + "/service/http/" + entity.getName() +
3201                                    "ServiceSoap.java");
3202    
3203                    writeFile(ejbFile, content, _author);
3204            }
3205    
3206            private void _createServiceUtil(Entity entity, int sessionType)
3207                    throws Exception {
3208    
3209                    JavaClass javaClass = _getJavaClass(
3210                            _serviceOutputPath + "/service/" + entity.getName() +
3211                                    _getSessionTypeName(sessionType) + "Service.java");
3212    
3213                    Map<String, Object> context = _getContext();
3214    
3215                    context.put("entity", entity);
3216                    context.put("methods", _getMethods(javaClass));
3217                    context.put("sessionTypeName", _getSessionTypeName(sessionType));
3218    
3219                    context = _putDeprecatedKeys(context, javaClass);
3220    
3221                    // Content
3222    
3223                    String content = _processTemplate(_tplServiceUtil, context);
3224    
3225                    // Write file
3226    
3227                    File ejbFile = new File(
3228                            _serviceOutputPath + "/service/" + entity.getName() +
3229                                    _getSessionTypeName(sessionType) + "ServiceUtil.java");
3230    
3231                    writeFile(ejbFile, content, _author);
3232    
3233                    if (!_serviceOutputPath.equals(_outputPath)) {
3234                            ejbFile = new File(
3235                                    _outputPath + "/service/" + entity.getName() +
3236                                            _getSessionTypeName(sessionType) + "ServiceUtil.java");
3237    
3238                            if (ejbFile.exists()) {
3239                                    System.out.println("Relocating " + ejbFile);
3240    
3241                                    ejbFile.delete();
3242                            }
3243                    }
3244            }
3245    
3246            private void _createServiceWrapper(Entity entity, int sessionType)
3247                    throws Exception {
3248    
3249                    JavaClass javaClass = _getJavaClass(
3250                            _serviceOutputPath + "/service/" + entity.getName() +
3251                                    _getSessionTypeName(sessionType) + "Service.java");
3252    
3253                    Map<String, Object> context = _getContext();
3254    
3255                    context.put("entity", entity);
3256                    context.put("methods", _getMethods(javaClass));
3257                    context.put("sessionTypeName", _getSessionTypeName(sessionType));
3258    
3259                    context = _putDeprecatedKeys(context, javaClass);
3260    
3261                    // Content
3262    
3263                    String content = _processTemplate(_tplServiceWrapper, context);
3264    
3265                    // Write file
3266    
3267                    File ejbFile = new File(
3268                            _serviceOutputPath + "/service/" + entity.getName() +
3269                                    _getSessionTypeName(sessionType) + "ServiceWrapper.java");
3270    
3271                    writeFile(ejbFile, content, _author);
3272            }
3273    
3274            private void _createSpringBaseXml() throws Exception {
3275                    if (Validator.isNull(_springBaseFileName)) {
3276                            return;
3277                    }
3278    
3279                    // Content
3280    
3281                    String content = _processTemplate(_tplSpringBaseXml);
3282    
3283                    // Write file
3284    
3285                    File ejbFile = new File(_springBaseFileName);
3286    
3287                    FileUtil.write(ejbFile, content, true);
3288    
3289                    if (Validator.isNotNull(_pluginName)) {
3290                            FileUtil.delete(
3291                                    "docroot/WEB-INF/src/META-INF/data-source-spring.xml");
3292                            FileUtil.delete("docroot/WEB-INF/src/META-INF/misc-spring.xml");
3293                    }
3294            }
3295    
3296            private void _createSpringClusterXml() throws Exception {
3297                    if (Validator.isNull(_springClusterFileName)) {
3298                            return;
3299                    }
3300    
3301                    // Content
3302    
3303                    String content = _processTemplate(_tplSpringClusterXml);
3304    
3305                    // Write file
3306    
3307                    File ejbFile = new File(_springClusterFileName);
3308    
3309                    FileUtil.write(ejbFile, content, true);
3310            }
3311    
3312            private void _createSpringDynamicDataSourceXml() throws Exception {
3313                    if (Validator.isNull(_springDynamicDataSourceFileName)) {
3314                            return;
3315                    }
3316    
3317                    File ejbFile = new File(_springDynamicDataSourceFileName);
3318    
3319                    if (ejbFile.exists()) {
3320                            System.out.println("Removing deprecated " + ejbFile);
3321    
3322                            ejbFile.delete();
3323                    }
3324            }
3325    
3326            private void _createSpringHibernateXml() throws Exception {
3327                    if (Validator.isNull(_springHibernateFileName)) {
3328                            return;
3329                    }
3330    
3331                    // Content
3332    
3333                    String content = _processTemplate(_tplSpringHibernateXml);
3334    
3335                    // Write file
3336    
3337                    File ejbFile = new File(_springHibernateFileName);
3338    
3339                    FileUtil.write(ejbFile, content, true);
3340            }
3341    
3342            private void _createSpringInfrastructureXml() throws Exception {
3343                    if (Validator.isNull(_springInfrastructureFileName)) {
3344                            return;
3345                    }
3346    
3347                    // Content
3348    
3349                    String content = _processTemplate(_tplSpringInfrastructureXml);
3350    
3351                    // Write file
3352    
3353                    File ejbFile = new File(_springInfrastructureFileName);
3354    
3355                    FileUtil.write(ejbFile, content, true);
3356            }
3357    
3358            private void _createSpringShardDataSourceXml() throws Exception {
3359                    if (Validator.isNull(_springShardDataSourceFileName)) {
3360                            return;
3361                    }
3362    
3363                    // Content
3364    
3365                    String content = _processTemplate(_tplSpringShardDataSourceXml);
3366    
3367                    // Write file
3368    
3369                    File ejbFile = new File(_springShardDataSourceFileName);
3370    
3371                    FileUtil.write(ejbFile, content, true);
3372            }
3373    
3374            private void _createSpringXml() throws Exception {
3375                    if (_packagePath.equals("com.liferay.counter")) {
3376                            return;
3377                    }
3378    
3379                    Map<String, Object> context = _getContext();
3380    
3381                    context.put("entities", _ejbList);
3382    
3383                    // Content
3384    
3385                    String content = _processTemplate(_tplSpringXml, context);
3386    
3387                    File xmlFile = new File(_springFileName);
3388    
3389                    String xml =
3390                            "<?xml version=\"1.0\"?>\n" +
3391                            "\n" +
3392                            "<beans\n" +
3393                            "\tdefault-destroy-method=\"destroy\"\n" +
3394                            "\tdefault-init-method=\"afterPropertiesSet\"\n" +
3395                            "\txmlns=\"http://www.springframework.org/schema/beans\"\n" +
3396                            "\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
3397                            "\txsi:schemaLocation=\"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\"\n" +
3398                            ">\n" +
3399                            "</beans>";
3400    
3401                    if (!xmlFile.exists()) {
3402                            FileUtil.write(xmlFile, xml);
3403                    }
3404    
3405                    String oldContent = FileUtil.read(xmlFile);
3406    
3407                    if (Validator.isNotNull(_pluginName) &&
3408                            oldContent.contains("DOCTYPE beans PUBLIC")) {
3409    
3410                            oldContent = xml;
3411                    }
3412    
3413                    String newContent = _fixSpringXml(oldContent);
3414    
3415                    int x = oldContent.indexOf("<beans");
3416                    int y = oldContent.lastIndexOf("</beans>");
3417    
3418                    int firstSession = newContent.indexOf(
3419                            "<bean id=\"" + _packagePath + ".service.", x);
3420    
3421                    int lastSession = newContent.lastIndexOf(
3422                            "<bean id=\"" + _packagePath + ".service.", y);
3423    
3424                    if ((firstSession == -1) || (firstSession > y)) {
3425                            x = newContent.indexOf("</beans>");
3426    
3427                            newContent =
3428                                    newContent.substring(0, x) + content + newContent.substring(x);
3429                    }
3430                    else {
3431                            firstSession = newContent.lastIndexOf("<bean", firstSession) - 1;
3432    
3433                            int tempLastSession = newContent.indexOf(
3434                                    "<bean id=\"", lastSession + 1);
3435    
3436                            if (tempLastSession == -1) {
3437                                    tempLastSession = newContent.indexOf("</beans>", lastSession);
3438                            }
3439    
3440                            lastSession = tempLastSession;
3441    
3442                            newContent =
3443                                    newContent.substring(0, firstSession) + content +
3444                                            newContent.substring(lastSession);
3445                    }
3446    
3447                    newContent = _formatXml(newContent);
3448    
3449                    if (!oldContent.equals(newContent)) {
3450                            FileUtil.write(xmlFile, newContent);
3451                    }
3452            }
3453    
3454            private void _createSQLIndexes() throws IOException {
3455                    if (!FileUtil.exists(_sqlDir)) {
3456                            return;
3457                    }
3458    
3459                    // indexes.sql
3460    
3461                    File sqlFile = new File(_sqlDir + "/" + _sqlIndexesFileName);
3462    
3463                    if (!sqlFile.exists()) {
3464                            FileUtil.write(sqlFile, "");
3465                    }
3466    
3467                    Map<String, String> indexSQLs = new TreeMap<String, String>();
3468    
3469                    UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(
3470                            new FileReader(sqlFile));
3471    
3472                    while (true) {
3473                            String indexSQL = unsyncBufferedReader.readLine();
3474    
3475                            if (indexSQL == null) {
3476                                    break;
3477                            }
3478    
3479                            if (Validator.isNotNull(indexSQL.trim())) {
3480                                    int pos = indexSQL.indexOf(" on ");
3481    
3482                                    String indexSpec = indexSQL.substring(pos + 4);
3483    
3484                                    indexSQLs.put(indexSpec, indexSQL);
3485                            }
3486                    }
3487    
3488                    unsyncBufferedReader.close();
3489    
3490                    // indexes.properties
3491    
3492                    File propsFile = new File(
3493                            _sqlDir + "/" + _sqlIndexesPropertiesFileName);
3494    
3495                    if (!propsFile.exists()) {
3496                            FileUtil.write(propsFile, "");
3497                    }
3498    
3499                    Map<String, String> indexProps = new TreeMap<String, String>();
3500    
3501                    unsyncBufferedReader = new UnsyncBufferedReader(
3502                            new FileReader(propsFile));
3503    
3504                    while (true) {
3505                            String indexMapping = unsyncBufferedReader.readLine();
3506    
3507                            if (indexMapping == null) {
3508                                    break;
3509                            }
3510    
3511                            if (Validator.isNotNull(indexMapping.trim())) {
3512                                    String[] splitIndexMapping = indexMapping.split("\\=");
3513    
3514                                    indexProps.put(splitIndexMapping[1], splitIndexMapping[0]);
3515                            }
3516                    }
3517    
3518                    unsyncBufferedReader.close();
3519    
3520                    // indexes.sql
3521    
3522                    for (int i = 0; i < _ejbList.size(); i++) {
3523                            Entity entity = _ejbList.get(i);
3524    
3525                            if (!_isTargetEntity(entity)) {
3526                                    continue;
3527                            }
3528    
3529                            if (!entity.isDefaultDataSource()) {
3530                                    continue;
3531                            }
3532    
3533                            List<EntityFinder> finderList = entity.getFinderList();
3534    
3535                            for (int j = 0; j < finderList.size(); j++) {
3536                                    EntityFinder finder = finderList.get(j);
3537    
3538                                    if (finder.isDBIndex()) {
3539                                            List<String> finderColsNames = new ArrayList<String>();
3540    
3541                                            List<EntityColumn> finderColsList = finder.getColumns();
3542    
3543                                            for (int k = 0; k < finderColsList.size(); k++) {
3544                                                    EntityColumn col = finderColsList.get(k);
3545    
3546                                                    finderColsNames.add(col.getDBName());
3547                                            }
3548    
3549                                            IndexMetadata indexMetadata =
3550                                                    IndexMetadataFactoryUtil.createIndexMetadata(
3551                                                            finder.isUnique(), entity.getTable(),
3552                                                            finderColsNames.toArray(
3553                                                                    new String[finderColsNames.size()]));
3554    
3555                                            indexSQLs.put(
3556                                                    indexMetadata.getSpecification(),
3557                                                    indexMetadata.getCreateSQL());
3558    
3559                                            String finderName =
3560                                                    entity.getTable() + StringPool.PERIOD +
3561                                                            finder.getName();
3562    
3563                                            indexProps.put(finderName, indexMetadata.getIndexName());
3564                                    }
3565                            }
3566                    }
3567    
3568                    for (Map.Entry<String, EntityMapping> entry :
3569                                    _entityMappings.entrySet()) {
3570    
3571                            EntityMapping entityMapping = entry.getValue();
3572    
3573                            _getCreateMappingTableIndex(entityMapping, indexSQLs, indexProps);
3574                    }
3575    
3576                    StringBundler sb = new StringBundler();
3577    
3578                    String prevEntityName = null;
3579    
3580                    for (String indexSQL : indexSQLs.values()) {
3581                            int pos = indexSQL.indexOf(" on ");
3582    
3583                            String indexSQLSuffix = indexSQL.substring(pos + 4);
3584    
3585                            String entityName = indexSQLSuffix.split(" ")[0];
3586    
3587                            if ((prevEntityName != null) &&
3588                                    !prevEntityName.equals(entityName)) {
3589    
3590                                    sb.append("\n");
3591                            }
3592    
3593                            sb.append(indexSQL);
3594                            sb.append("\n");
3595    
3596                            prevEntityName = entityName;
3597                    }
3598    
3599                    if (!indexSQLs.isEmpty()) {
3600                            sb.setIndex(sb.index() - 1);
3601                    }
3602    
3603                    FileUtil.write(sqlFile, sb.toString(), true);
3604    
3605                    // indexes.properties
3606    
3607                    sb.setIndex(0);
3608    
3609                    prevEntityName = null;
3610    
3611                    for (String finderName : indexProps.keySet()) {
3612                            String indexName = indexProps.get(finderName);
3613    
3614                            String entityName = finderName.split("\\.")[0];
3615    
3616                            if ((prevEntityName != null) &&
3617                                    !prevEntityName.equals(entityName)) {
3618    
3619                                    sb.append("\n");
3620                            }
3621    
3622                            sb.append(indexName);
3623                            sb.append(StringPool.EQUAL);
3624                            sb.append(finderName);
3625                            sb.append("\n");
3626    
3627                            prevEntityName = entityName;
3628                    }
3629    
3630                    if (!indexProps.isEmpty()) {
3631                            sb.setIndex(sb.index() - 1);
3632                    }
3633    
3634                    FileUtil.write(propsFile, sb.toString(), true);
3635            }
3636    
3637            private void _createSQLMappingTables(
3638                            File sqlFile, String newCreateTableString,
3639                            EntityMapping entityMapping, boolean addMissingTables)
3640                    throws IOException {
3641    
3642                    if (!sqlFile.exists()) {
3643                            FileUtil.write(sqlFile, StringPool.BLANK);
3644                    }
3645    
3646                    String content = FileUtil.read(sqlFile);
3647    
3648                    int x = content.indexOf(
3649                            _SQL_CREATE_TABLE + entityMapping.getTable() + " (");
3650                    int y = content.indexOf(");", x);
3651    
3652                    if (x != -1) {
3653                            String oldCreateTableString = content.substring(x + 1, y);
3654    
3655                            if (!oldCreateTableString.equals(newCreateTableString)) {
3656                                    content =
3657                                            content.substring(0, x) + newCreateTableString +
3658                                                    content.substring(y + 2);
3659    
3660                                    FileUtil.write(sqlFile, content);
3661                            }
3662                    }
3663                    else if (addMissingTables) {
3664                            StringBundler sb = new StringBundler();
3665    
3666                            UnsyncBufferedReader unsyncBufferedReader =
3667                                    new UnsyncBufferedReader(new UnsyncStringReader(content));
3668    
3669                            String line = null;
3670                            boolean appendNewTable = true;
3671    
3672                            while ((line = unsyncBufferedReader.readLine()) != null) {
3673                                    if (appendNewTable && line.startsWith(_SQL_CREATE_TABLE)) {
3674                                            x = _SQL_CREATE_TABLE.length();
3675                                            y = line.indexOf(" ", x);
3676    
3677                                            String tableName = line.substring(x, y);
3678    
3679                                            if (tableName.compareTo(entityMapping.getTable()) > 0) {
3680                                                    sb.append(newCreateTableString);
3681                                                    sb.append("\n\n");
3682    
3683                                                    appendNewTable = false;
3684                                            }
3685                                    }
3686    
3687                                    sb.append(line);
3688                                    sb.append("\n");
3689                            }
3690    
3691                            if (appendNewTable) {
3692                                    sb.append("\n");
3693                                    sb.append(newCreateTableString);
3694                            }
3695    
3696                            unsyncBufferedReader.close();
3697    
3698                            FileUtil.write(sqlFile, sb.toString(), true);
3699                    }
3700            }
3701    
3702            private void _createSQLSequences() throws IOException {
3703                    if (!FileUtil.exists(_sqlDir)) {
3704                            return;
3705                    }
3706    
3707                    File sqlFile = new File(_sqlDir + "/" + _sqlSequencesFileName);
3708    
3709                    if (!sqlFile.exists()) {
3710                            FileUtil.write(sqlFile, "");
3711                    }
3712    
3713                    Set<String> sequenceSQLs = new TreeSet<String>();
3714    
3715                    UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(
3716                            new FileReader(sqlFile));
3717    
3718                    while (true) {
3719                            String sequenceSQL = unsyncBufferedReader.readLine();
3720    
3721                            if (sequenceSQL == null) {
3722                                    break;
3723                            }
3724    
3725                            if (Validator.isNotNull(sequenceSQL)) {
3726                                    sequenceSQLs.add(sequenceSQL);
3727                            }
3728                    }
3729    
3730                    unsyncBufferedReader.close();
3731    
3732                    for (int i = 0; i < _ejbList.size(); i++) {
3733                            Entity entity = _ejbList.get(i);
3734    
3735                            if (!_isTargetEntity(entity)) {
3736                                    continue;
3737                            }
3738    
3739                            if (!entity.isDefaultDataSource()) {
3740                                    continue;
3741                            }
3742    
3743                            List<EntityColumn> columnList = entity.getColumnList();
3744    
3745                            for (int j = 0; j < columnList.size(); j++) {
3746                                    EntityColumn column = columnList.get(j);
3747    
3748                                    if ("sequence".equals(column.getIdType())) {
3749                                            StringBundler sb = new StringBundler();
3750    
3751                                            String sequenceName = column.getIdParam();
3752    
3753                                            if (sequenceName.length() > 30) {
3754                                                    sequenceName = sequenceName.substring(0, 30);
3755                                            }
3756    
3757                                            sb.append("create sequence ");
3758                                            sb.append(sequenceName);
3759                                            sb.append(";");
3760    
3761                                            String sequenceSQL = sb.toString();
3762    
3763                                            if (!sequenceSQLs.contains(sequenceSQL)) {
3764                                                    sequenceSQLs.add(sequenceSQL);
3765                                            }
3766                                    }
3767                            }
3768                    }
3769    
3770                    StringBundler sb = new StringBundler(sequenceSQLs.size() * 2);
3771    
3772                    for (String sequenceSQL : sequenceSQLs) {
3773                            sb.append(sequenceSQL);
3774                            sb.append("\n");
3775                    }
3776    
3777                    if (!sequenceSQLs.isEmpty()) {
3778                            sb.setIndex(sb.index() - 1);
3779                    }
3780    
3781                    FileUtil.write(sqlFile, sb.toString(), true);
3782            }
3783    
3784            private void _createSQLTables() throws IOException {
3785                    if (!FileUtil.exists(_sqlDir)) {
3786                            return;
3787                    }
3788    
3789                    File sqlFile = new File(_sqlDir + "/" + _sqlFileName);
3790    
3791                    if (!sqlFile.exists()) {
3792                            FileUtil.write(sqlFile, StringPool.BLANK);
3793                    }
3794    
3795                    for (int i = 0; i < _ejbList.size(); i++) {
3796                            Entity entity = _ejbList.get(i);
3797    
3798                            if (!_isTargetEntity(entity)) {
3799                                    continue;
3800                            }
3801    
3802                            if (!entity.isDefaultDataSource()) {
3803                                    continue;
3804                            }
3805    
3806                            String createTableSQL = _getCreateTableSQL(entity);
3807    
3808                            if (Validator.isNotNull(createTableSQL)) {
3809                                    _createSQLTables(sqlFile, createTableSQL, entity, true);
3810    
3811                                    _updateSQLFile(
3812                                            "update-6.1.1-6.2.0.sql", createTableSQL, entity);
3813                            }
3814                    }
3815    
3816                    for (Map.Entry<String, EntityMapping> entry :
3817                                    _entityMappings.entrySet()) {
3818    
3819                            EntityMapping entityMapping = entry.getValue();
3820    
3821                            String createMappingTableSQL = _getCreateMappingTableSQL(
3822                                    entityMapping);
3823    
3824                            if (Validator.isNotNull(createMappingTableSQL)) {
3825                                    _createSQLMappingTables(
3826                                            sqlFile, createMappingTableSQL, entityMapping, true);
3827                            }
3828                    }
3829    
3830                    String content = FileUtil.read(sqlFile);
3831    
3832                    FileUtil.write(sqlFile, content.trim());
3833            }
3834    
3835            private void _createSQLTables(
3836                            File sqlFile, String newCreateTableString, Entity entity,
3837                            boolean addMissingTables)
3838                    throws IOException {
3839    
3840                    if (!sqlFile.exists()) {
3841                            FileUtil.write(sqlFile, StringPool.BLANK);
3842                    }
3843    
3844                    String content = FileUtil.read(sqlFile);
3845    
3846                    int x = content.indexOf(_SQL_CREATE_TABLE + entity.getTable() + " (");
3847                    int y = content.indexOf(");", x);
3848    
3849                    if (x != -1) {
3850                            String oldCreateTableString = content.substring(x + 1, y);
3851    
3852                            if (!oldCreateTableString.equals(newCreateTableString)) {
3853                                    content =
3854                                            content.substring(0, x) + newCreateTableString +
3855                                                    content.substring(y + 2);
3856    
3857                                    FileUtil.write(sqlFile, content);
3858                            }
3859                    }
3860                    else if (addMissingTables) {
3861                            StringBundler sb = new StringBundler();
3862    
3863                            UnsyncBufferedReader unsyncBufferedReader =
3864                                    new UnsyncBufferedReader(new UnsyncStringReader(content));
3865    
3866                            String line = null;
3867                            boolean appendNewTable = true;
3868    
3869                            while ((line = unsyncBufferedReader.readLine()) != null) {
3870                                    if (appendNewTable && line.startsWith(_SQL_CREATE_TABLE)) {
3871                                            x = _SQL_CREATE_TABLE.length();
3872                                            y = line.indexOf(" ", x);
3873    
3874                                            String tableName = line.substring(x, y);
3875    
3876                                            if (tableName.compareTo(entity.getTable()) > 0) {
3877                                                    sb.append(newCreateTableString);
3878                                                    sb.append("\n\n");
3879    
3880                                                    appendNewTable = false;
3881                                            }
3882                                    }
3883    
3884                                    sb.append(line);
3885                                    sb.append("\n");
3886                            }
3887    
3888                            if (appendNewTable) {
3889                                    sb.append("\n");
3890                                    sb.append(newCreateTableString);
3891                            }
3892    
3893                            unsyncBufferedReader.close();
3894    
3895                            FileUtil.write(sqlFile, sb.toString(), true);
3896                    }
3897            }
3898    
3899            private String _fixHbmXml(String content) throws IOException {
3900                    StringBundler sb = new StringBundler();
3901    
3902                    UnsyncBufferedReader unsyncBufferedReader = new UnsyncBufferedReader(
3903                            new UnsyncStringReader(content));
3904    
3905                    String line = null;
3906    
3907                    while ((line = unsyncBufferedReader.readLine()) != null) {
3908                            if (line.startsWith("\t<class name=\"")) {
3909                                    line = StringUtil.replace(
3910                                            line,
3911                                            new String[] {
3912                                                    ".service.persistence.", "HBM\" table=\""
3913                                            },
3914                                            new String[] {
3915                                                    ".model.", "\" table=\""
3916                                            });
3917    
3918                                    if (!line.contains(".model.impl.") &&
3919                                            !line.contains("BlobModel")) {
3920    
3921                                            line = StringUtil.replace(
3922                                                    line,
3923                                                    new String[] {
3924                                                            ".model.", "\" table=\""
3925                                                    },
3926                                                    new String[] {
3927                                                            ".model.impl.", "Impl\" table=\""
3928                                                    });
3929                                    }
3930                            }
3931    
3932                            sb.append(line);
3933                            sb.append('\n');
3934                    }
3935    
3936                    unsyncBufferedReader.close();
3937    
3938                    return sb.toString().trim();
3939            }
3940    
3941            private String _fixSpringXml(String content) {
3942                    return StringUtil.replace(content, ".service.spring.", ".service.");
3943            }
3944    
3945            private String _formatComment(
3946                    String comment, DocletTag[] tags, String indentation) {
3947    
3948                    StringBundler sb = new StringBundler();
3949    
3950                    if (Validator.isNull(comment) && (tags.length <= 0)) {
3951                            return sb.toString();
3952                    }
3953    
3954                    sb.append(indentation);
3955                    sb.append("/**\n");
3956    
3957                    if (Validator.isNotNull(comment)) {
3958                            comment = comment.replaceAll("(?m)^", indentation + " * ");
3959    
3960                            sb.append(comment);
3961                            sb.append("\n");
3962    
3963                            if (tags.length > 0) {
3964                                    sb.append(indentation);
3965                                    sb.append(" *\n");
3966                            }
3967                    }
3968    
3969                    for (DocletTag tag : tags) {
3970                            sb.append(indentation);
3971                            sb.append(" * @");
3972                            sb.append(tag.getName());
3973                            sb.append(" ");
3974                            sb.append(tag.getValue());
3975                            sb.append("\n");
3976                    }
3977    
3978                    sb.append(indentation);
3979                    sb.append(" */\n");
3980    
3981                    return sb.toString();
3982            }
3983    
3984            private String _formatXml(String xml)
3985                    throws DocumentException, IOException {
3986    
3987                    String doctype = null;
3988    
3989                    int x = xml.indexOf("<!DOCTYPE");
3990    
3991                    if (x != -1) {
3992                            int y = xml.indexOf(">", x) + 1;
3993    
3994                            doctype = xml.substring(x, y);
3995    
3996                            xml = xml.substring(0, x) + "\n" + xml.substring(y);
3997                    }
3998    
3999                    xml = StringUtil.replace(xml, '\r', "");
4000                    xml = XMLFormatter.toString(xml);
4001                    xml = StringUtil.replace(xml, "\"/>", "\" />");
4002    
4003                    if (Validator.isNotNull(doctype)) {
4004                            x = xml.indexOf("?>") + 2;
4005    
4006                            xml = xml.substring(0, x) + "\n" + doctype + xml.substring(x);
4007                    }
4008    
4009                    return xml;
4010            }
4011    
4012            private JavaField[] _getCacheFields(JavaClass javaClass) {
4013                    if (javaClass == null) {
4014                            return new JavaField[0];
4015                    }
4016    
4017                    List<JavaField> javaFields = new ArrayList<JavaField>();
4018    
4019                    for (JavaField javaField : javaClass.getFields()) {
4020                            Annotation[] annotations = javaField.getAnnotations();
4021    
4022                            for (Annotation annotation : annotations) {
4023                                    Type type = annotation.getType();
4024    
4025                                    String className = type.getFullyQualifiedName();
4026    
4027                                    if (className.equals(CacheField.class.getName())) {
4028                                            javaFields.add(javaField);
4029    
4030                                            break;
4031                                    }
4032                            }
4033                    }
4034    
4035                    return javaFields.toArray(new JavaField[javaFields.size()]);
4036            }
4037    
4038            private Map<String, Object> _getContext() throws TemplateModelException {
4039                    BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
4040    
4041                    TemplateHashModel staticModels = wrapper.getStaticModels();
4042    
4043                    Map<String, Object> context = new HashMap<String, Object>();
4044    
4045                    context.put("hbmFileName", _hbmFileName);
4046                    context.put("ormFileName", _ormFileName);
4047                    context.put("modelHintsFileName", _modelHintsFileName);
4048                    context.put("springFileName", _springFileName);
4049                    context.put("springBaseFileName", _springBaseFileName);
4050                    context.put("springHibernateFileName", _springHibernateFileName);
4051                    context.put(
4052                            "springInfrastructureFileName", _springInfrastructureFileName);
4053                    context.put("apiDir", _apiDir);
4054                    context.put("implDir", _implDir);
4055                    context.put("sqlDir", _sqlDir);
4056                    context.put("sqlFileName", _sqlFileName);
4057                    context.put("beanLocatorUtil", _beanLocatorUtil);
4058                    context.put("beanLocatorUtilShortName", _beanLocatorUtilShortName);
4059                    context.put("propsUtil", _propsUtil);
4060                    context.put("portletName", _portletName);
4061                    context.put("portletShortName", _portletShortName);
4062                    context.put("portletPackageName", _portletPackageName);
4063                    context.put("outputPath", _outputPath);
4064                    context.put("serviceOutputPath", _serviceOutputPath);
4065                    context.put("packagePath", _packagePath);
4066                    context.put("pluginName", _pluginName);
4067                    context.put("author", _author);
4068                    context.put("serviceBuilder", this);
4069    
4070                    context.put("arrayUtil", ArrayUtil_IW.getInstance());
4071                    context.put("modelHintsUtil", ModelHintsUtil.getModelHints());
4072                    context.put(
4073                            "resourceActionsUtil", ResourceActionsUtil.getResourceActions());
4074                    context.put("stringUtil", StringUtil_IW.getInstance());
4075                    context.put("system", staticModels.get("java.lang.System"));
4076                    context.put("tempMap", wrapper.wrap(new HashMap<String, Object>()));
4077                    context.put(
4078                            "textFormatter", staticModels.get(TextFormatter.class.getName()));
4079                    context.put("validator", Validator_IW.getInstance());
4080    
4081                    return context;
4082            }
4083    
4084            private void _getCreateMappingTableIndex(
4085                            EntityMapping entityMapping, Map<String, String> indexSQLs,
4086                            Map<String, String> indexProps)
4087                    throws IOException {
4088    
4089                    Entity[] entities = new Entity[2];
4090    
4091                    for (int i = 0; i < entities.length; i++) {
4092                            entities[i] = getEntity(entityMapping.getEntity(i));
4093    
4094                            if (entities[i] == null) {
4095                                    return;
4096                            }
4097                    }
4098    
4099                    for (Entity entity : entities) {
4100                            List<EntityColumn> pkList = entity.getPKList();
4101    
4102                            for (int j = 0; j < pkList.size(); j++) {
4103                                    EntityColumn col = pkList.get(j);
4104    
4105                                    String colDBName = col.getDBName();
4106    
4107                                    String indexSpec =
4108                                            entityMapping.getTable() + " (" + colDBName + ");";
4109    
4110                                    String indexHash = StringUtil.toHexString(indexSpec.hashCode());
4111    
4112                                    indexHash = StringUtil.toUpperCase(indexHash);
4113    
4114                                    String indexName = "IX_" + indexHash;
4115    
4116                                    StringBundler sb = new StringBundler();
4117    
4118                                    sb.append("create index ");
4119                                    sb.append(indexName);
4120                                    sb.append(" on ");
4121                                    sb.append(indexSpec);
4122    
4123                                    indexSQLs.put(indexSpec, sb.toString());
4124    
4125                                    String finderName =
4126                                            entityMapping.getTable() + StringPool.PERIOD + colDBName;
4127    
4128                                    indexProps.put(finderName, indexName);
4129                            }
4130                    }
4131            }
4132    
4133            private String _getCreateMappingTableSQL(EntityMapping entityMapping)
4134                    throws IOException {
4135    
4136                    Entity[] entities = new Entity[2];
4137    
4138                    for (int i = 0; i < entities.length; i++) {
4139                            entities[i] = getEntity(entityMapping.getEntity(i));
4140    
4141                            if (entities[i] == null) {
4142                                    return null;
4143                            }
4144                    }
4145    
4146                    Arrays.sort(
4147                            entities,
4148                            new Comparator<Entity>() {
4149    
4150                                    @Override
4151                                    public int compare(Entity entity1, Entity entity2) {
4152                                            String name1 = entity1.getName();
4153                                            String name2 = entity2.getName();
4154    
4155                                            return name1.compareTo(name2);
4156                                    }
4157    
4158                            });
4159    
4160                    StringBundler sb = new StringBundler();
4161    
4162                    sb.append(_SQL_CREATE_TABLE);
4163                    sb.append(entityMapping.getTable());
4164                    sb.append(" (\n");
4165    
4166                    for (Entity entity : entities) {
4167                            List<EntityColumn> pkList = entity.getPKList();
4168    
4169                            for (int i = 0; i < pkList.size(); i++) {
4170                                    EntityColumn col = pkList.get(i);
4171    
4172                                    String colName = col.getName();
4173                                    String colType = col.getType();
4174    
4175                                    sb.append("\t");
4176                                    sb.append(col.getDBName());
4177                                    sb.append(" ");
4178    
4179                                    if (StringUtil.equalsIgnoreCase(colType, "boolean")) {
4180                                            sb.append("BOOLEAN");
4181                                    }
4182                                    else if (StringUtil.equalsIgnoreCase(colType, "double") ||
4183                                                     StringUtil.equalsIgnoreCase(colType, "float")) {
4184    
4185                                            sb.append("DOUBLE");
4186                                    }
4187                                    else if (colType.equals("int") ||
4188                                                     colType.equals("Integer") ||
4189                                                     StringUtil.equalsIgnoreCase(colType, "short")) {
4190    
4191                                            sb.append("INTEGER");
4192                                    }
4193                                    else if (StringUtil.equalsIgnoreCase(colType, "long")) {
4194                                            sb.append("LONG");
4195                                    }
4196                                    else if (colType.equals("String")) {
4197                                            Map<String, String> hints = ModelHintsUtil.getHints(
4198                                                    _packagePath + ".model." + entity.getName(), colName);
4199    
4200                                            int maxLength = 75;
4201    
4202                                            if (hints != null) {
4203                                                    maxLength = GetterUtil.getInteger(
4204                                                            hints.get("max-length"), maxLength);
4205                                            }
4206    
4207                                            if (col.isLocalized()) {
4208                                                    maxLength = 4000;
4209                                            }
4210    
4211                                            if (maxLength < 4000) {
4212                                                    sb.append("VARCHAR(");
4213                                                    sb.append(maxLength);
4214                                                    sb.append(")");
4215                                            }
4216                                            else if (maxLength == 4000) {
4217                                                    sb.append("STRING");
4218                                            }
4219                                            else if (maxLength > 4000) {
4220                                                    sb.append("TEXT");
4221                                            }
4222                                    }
4223                                    else if (colType.equals("Date")) {
4224                                            sb.append("DATE");
4225                                    }
4226                                    else {
4227                                            sb.append("invalid");
4228                                    }
4229    
4230                                    if (col.isPrimary()) {
4231                                            sb.append(" not null");
4232                                    }
4233                                    else if (colType.equals("Date") || colType.equals("String")) {
4234                                            sb.append(" null");
4235                                    }
4236    
4237                                    sb.append(",\n");
4238                            }
4239                    }
4240    
4241                    sb.append("\tprimary key (");
4242    
4243                    for (int i = 0; i < entities.length; i++) {
4244                            Entity entity = entities[i];
4245    
4246                            List<EntityColumn> pkList = entity.getPKList();
4247    
4248                            for (int j = 0; j < pkList.size(); j++) {
4249                                    EntityColumn col = pkList.get(j);
4250    
4251                                    String colDBName = col.getDBName();
4252    
4253                                    if ((i != 0) || (j != 0)) {
4254                                            sb.append(", ");
4255                                    }
4256    
4257                                    sb.append(colDBName);
4258                            }
4259                    }
4260    
4261                    sb.append(")\n");
4262                    sb.append(");");
4263    
4264                    return sb.toString();
4265            }
4266    
4267            private String _getCreateTableSQL(Entity entity) {
4268                    List<EntityColumn> pkList = entity.getPKList();
4269                    List<EntityColumn> regularColList = entity.getRegularColList();
4270    
4271                    if (regularColList.size() == 0) {
4272                            return null;
4273                    }
4274    
4275                    StringBundler sb = new StringBundler();
4276    
4277                    sb.append(_SQL_CREATE_TABLE);
4278                    sb.append(entity.getTable());
4279                    sb.append(" (\n");
4280    
4281                    for (int i = 0; i < regularColList.size(); i++) {
4282                            EntityColumn col = regularColList.get(i);
4283    
4284                            String colName = col.getName();
4285                            String colType = col.getType();
4286                            String colIdType = col.getIdType();
4287    
4288                            sb.append("\t");
4289                            sb.append(col.getDBName());
4290                            sb.append(" ");
4291    
4292                            if (StringUtil.equalsIgnoreCase(colType, "boolean")) {
4293                                    sb.append("BOOLEAN");
4294                            }
4295                            else if (StringUtil.equalsIgnoreCase(colType, "double") ||
4296                                             StringUtil.equalsIgnoreCase(colType, "float")) {
4297    
4298                                    sb.append("DOUBLE");
4299                            }
4300                            else if (colType.equals("int") ||
4301                                             colType.equals("Integer") ||
4302                                             StringUtil.equalsIgnoreCase(colType, "short")) {
4303    
4304                                    sb.append("INTEGER");
4305                            }
4306                            else if (StringUtil.equalsIgnoreCase(colType, "long")) {
4307                                    sb.append("LONG");
4308                            }
4309                            else if (colType.equals("Blob")) {
4310                                    sb.append("BLOB");
4311                            }
4312                            else if (colType.equals("Date")) {
4313                                    sb.append("DATE");
4314                            }
4315                            else if (colType.equals("String")) {
4316                                    Map<String, String> hints = ModelHintsUtil.getHints(
4317                                            _packagePath + ".model." + entity.getName(), colName);
4318    
4319                                    int maxLength = 75;
4320    
4321                                    if (hints != null) {
4322                                            maxLength = GetterUtil.getInteger(
4323                                                    hints.get("max-length"), maxLength);
4324                                    }
4325    
4326                                    if (col.isLocalized() && (maxLength < 4000)) {
4327                                            maxLength = 4000;
4328                                    }
4329    
4330                                    if (maxLength < 4000) {
4331                                            sb.append("VARCHAR(");
4332                                            sb.append(maxLength);
4333                                            sb.append(")");
4334                                    }
4335                                    else if (maxLength == 4000) {
4336                                            sb.append("STRING");
4337                                    }
4338                                    else if (maxLength > 4000) {
4339                                            sb.append("TEXT");
4340                                    }
4341                            }
4342                            else {
4343                                    sb.append("invalid");
4344                            }
4345    
4346                            if (col.isPrimary()) {
4347                                    sb.append(" not null");
4348    
4349                                    if (!entity.hasCompoundPK()) {
4350                                            sb.append(" primary key");
4351                                    }
4352                            }
4353                            else if (colType.equals("Date") || colType.equals("String")) {
4354                                    sb.append(" null");
4355                            }
4356    
4357                            if (Validator.isNotNull(colIdType) &&
4358                                    colIdType.equals("identity")) {
4359    
4360                                    sb.append(" IDENTITY");
4361                            }
4362    
4363                            if (((i + 1) != regularColList.size()) ||
4364                                    entity.hasCompoundPK()) {
4365    
4366                                    sb.append(",");
4367                            }
4368    
4369                            sb.append("\n");
4370                    }
4371    
4372                    if (entity.hasCompoundPK()) {
4373                            sb.append("\tprimary key (");
4374    
4375                            for (int j = 0; j < pkList.size(); j++) {
4376                                    EntityColumn pk = pkList.get(j);
4377    
4378                                    sb.append(pk.getDBName());
4379    
4380                                    if ((j + 1) != pkList.size()) {
4381                                            sb.append(", ");
4382                                    }
4383                            }
4384    
4385                            sb.append(")\n");
4386                    }
4387    
4388                    sb.append(");");
4389    
4390                    return sb.toString();
4391            }
4392    
4393            private String _getDimensions(Type type) {
4394                    String dimensions = "";
4395    
4396                    for (int i = 0; i < type.getDimensions(); i++) {
4397                            dimensions += "[]";
4398                    }
4399    
4400                    return dimensions;
4401            }
4402    
4403            private JavaClass _getJavaClass(String fileName) throws IOException {
4404                    int pos = fileName.indexOf(_implDir + "/");
4405    
4406                    if (pos != -1) {
4407                            pos += _implDir.length();
4408                    }
4409                    else {
4410                            pos = fileName.indexOf(_apiDir + "/") + _apiDir.length();
4411                    }
4412    
4413                    String srcFile = fileName.substring(pos + 1);
4414                    String className = StringUtil.replace(
4415                            srcFile.substring(0, srcFile.length() - 5), "/", ".");
4416    
4417                    JavaClass javaClass = _javaClasses.get(className);
4418    
4419                    if (javaClass == null) {
4420                            ClassLibrary classLibrary = new ClassLibrary();
4421    
4422                            classLibrary.addClassLoader(getClass().getClassLoader());
4423    
4424                            JavaDocBuilder builder = new JavaDocBuilder(classLibrary);
4425    
4426                            File file = new File(fileName);
4427    
4428                            if (!file.exists()) {
4429                                    return null;
4430                            }
4431    
4432                            builder.addSource(file);
4433    
4434                            javaClass = builder.getClassByName(className);
4435    
4436                            _javaClasses.put(className, javaClass);
4437                    }
4438    
4439                    return javaClass;
4440            }
4441    
4442            private JavaMethod[] _getMethods(JavaClass javaClass) {
4443                    return _getMethods(javaClass, false);
4444            }
4445    
4446            private JavaMethod[] _getMethods(
4447                    JavaClass javaClass, boolean superclasses) {
4448    
4449                    JavaMethod[] methods = javaClass.getMethods(superclasses);
4450    
4451                    for (JavaMethod method : methods) {
4452                            Arrays.sort(method.getExceptions());
4453                    }
4454    
4455                    return methods;
4456            }
4457    
4458            private String _getSessionTypeName(int sessionType) {
4459                    if (sessionType == _SESSION_TYPE_LOCAL) {
4460                            return "Local";
4461                    }
4462                    else {
4463                            return "";
4464                    }
4465            }
4466    
4467            private String _getTplProperty(String key, String defaultValue) {
4468                    return System.getProperty("service.tpl." + key, defaultValue);
4469            }
4470    
4471            private List<String> _getTransients(Entity entity, boolean parent)
4472                    throws Exception {
4473    
4474                    File modelFile = null;
4475    
4476                    if (parent) {
4477                            modelFile = new File(
4478                                    _outputPath + "/model/impl/" + entity.getName() +
4479                                            "ModelImpl.java");
4480                    }
4481                    else {
4482                            modelFile = new File(
4483                                    _outputPath + "/model/impl/" + entity.getName() + "Impl.java");
4484                    }
4485    
4486                    String content = FileUtil.read(modelFile);
4487    
4488                    Matcher matcher = _getterPattern.matcher(content);
4489    
4490                    Set<String> getters = new HashSet<String>();
4491    
4492                    while (!matcher.hitEnd()) {
4493                            boolean found = matcher.find();
4494    
4495                            if (found) {
4496                                    String property = matcher.group();
4497    
4498                                    if (property.contains("get")) {
4499                                            property = property.substring(
4500                                                    property.indexOf("get") + 3, property.length() - 1);
4501                                    }
4502                                    else {
4503                                            property = property.substring(
4504                                                    property.indexOf("is") + 2, property.length() - 1);
4505                                    }
4506    
4507                                    if (!entity.hasColumn(property) &&
4508                                            !entity.hasColumn(Introspector.decapitalize(property))) {
4509    
4510                                            property = Introspector.decapitalize(property);
4511    
4512                                            getters.add(property);
4513                                    }
4514                            }
4515                    }
4516    
4517                    matcher = _setterPattern.matcher(content);
4518    
4519                    Set<String> setters = new HashSet<String>();
4520    
4521                    while (!matcher.hitEnd()) {
4522                            boolean found = matcher.find();
4523    
4524                            if (found) {
4525                                    String property = matcher.group();
4526    
4527                                    property = property.substring(
4528                                            property.indexOf("set") + 3, property.length() - 1);
4529    
4530                                    if (!entity.hasColumn(property) &&
4531                                            !entity.hasColumn(Introspector.decapitalize(property))) {
4532    
4533                                            property = Introspector.decapitalize(property);
4534    
4535                                            setters.add(property);
4536                                    }
4537                            }
4538                    }
4539    
4540                    getters.retainAll(setters);
4541    
4542                    List<String> transients = new ArrayList<String>(getters);
4543    
4544                    Collections.sort(transients);
4545    
4546                    return transients;
4547            }
4548    
4549            private boolean _hasHttpMethods(JavaClass javaClass) {
4550                    JavaMethod[] methods = _getMethods(javaClass);
4551    
4552                    for (JavaMethod javaMethod : methods) {
4553                            if (!javaMethod.isConstructor() && javaMethod.isPublic() &&
4554                                    isCustomMethod(javaMethod)) {
4555    
4556                                    return true;
4557                            }
4558                    }
4559    
4560                    return false;
4561            }
4562    
4563            private boolean _isStringLocaleMap(JavaParameter javaParameter) {
4564                    Type type = javaParameter.getType();
4565    
4566                    Type[] actualArgumentTypes = type.getActualTypeArguments();
4567    
4568                    if (actualArgumentTypes.length != 2) {
4569                            return false;
4570                    }
4571    
4572                    if (!_isTypeValue(actualArgumentTypes[0], Locale.class.getName()) ||
4573                            !_isTypeValue(actualArgumentTypes[1], String.class.getName())) {
4574    
4575                            return false;
4576                    }
4577    
4578                    return true;
4579            }
4580    
4581            private boolean _isTargetEntity(Entity entity) {
4582                    if ((_targetEntityName == null) || _targetEntityName.startsWith("$")) {
4583                            return true;
4584                    }
4585    
4586                    return _targetEntityName.equals(entity.getName());
4587            }
4588    
4589            private boolean _isTypeValue(Type type, String value) {
4590                    return value.equals(type.getValue());
4591            }
4592    
4593            private List<Entity> _mergeReferenceList(List<Entity> referenceList) {
4594                    List<Entity> list = new ArrayList<Entity>(
4595                            _ejbList.size() + referenceList.size());
4596    
4597                    list.addAll(_ejbList);
4598                    list.addAll(referenceList);
4599    
4600                    return list;
4601            }
4602    
4603            private void _parseEntity(Element entityElement) throws Exception {
4604                    String ejbName = entityElement.attributeValue("name");
4605                    String humanName = entityElement.attributeValue("human-name");
4606    
4607                    String table = entityElement.attributeValue("table");
4608    
4609                    if (Validator.isNull(table)) {
4610                            table = ejbName;
4611    
4612                            if (_badTableNames.contains(ejbName)) {
4613                                    table += StringPool.UNDERLINE;
4614                            }
4615    
4616                            if (_autoNamespaceTables) {
4617                                    table = _portletShortName + StringPool.UNDERLINE + ejbName;
4618                            }
4619                    }
4620    
4621                    boolean uuid = GetterUtil.getBoolean(
4622                            entityElement.attributeValue("uuid"));
4623                    boolean uuidAccessor = GetterUtil.getBoolean(
4624                            entityElement.attributeValue("uuid-accessor"));
4625                    boolean localService = GetterUtil.getBoolean(
4626                            entityElement.attributeValue("local-service"));
4627                    boolean remoteService = GetterUtil.getBoolean(
4628                            entityElement.attributeValue("remote-service"), true);
4629                    String persistenceClass = GetterUtil.getString(
4630                            entityElement.attributeValue("persistence-class"),
4631                            _packagePath + ".service.persistence." + ejbName +
4632                                    "PersistenceImpl");
4633    
4634                    String finderClass = "";
4635    
4636                    if (FileUtil.exists(
4637                                    _outputPath + "/service/persistence/" + ejbName +
4638                                            "FinderImpl.java")) {
4639    
4640                            finderClass =
4641                                    _packagePath + ".service.persistence." + ejbName + "FinderImpl";
4642                    }
4643    
4644                    String dataSource = entityElement.attributeValue("data-source");
4645                    String sessionFactory = entityElement.attributeValue("session-factory");
4646                    String txManager = entityElement.attributeValue("tx-manager");
4647                    boolean cacheEnabled = GetterUtil.getBoolean(
4648                            entityElement.attributeValue("cache-enabled"), true);
4649                    boolean jsonEnabled = GetterUtil.getBoolean(
4650                            entityElement.attributeValue("json-enabled"), remoteService);
4651                    boolean trashEnabled = GetterUtil.getBoolean(
4652                            entityElement.attributeValue("trash-enabled"));
4653                    boolean deprecated = GetterUtil.getBoolean(
4654                            entityElement.attributeValue("deprecated"));
4655    
4656                    List<EntityColumn> pkList = new ArrayList<EntityColumn>();
4657                    List<EntityColumn> regularColList = new ArrayList<EntityColumn>();
4658                    List<EntityColumn> blobList = new ArrayList<EntityColumn>();
4659                    List<EntityColumn> collectionList = new ArrayList<EntityColumn>();
4660                    List<EntityColumn> columnList = new ArrayList<EntityColumn>();
4661    
4662                    List<Element> columnElements = entityElement.elements("column");
4663    
4664                    boolean permissionedModel = false;
4665    
4666                    if (uuid) {
4667                            Element columnElement = SAXReaderUtil.createElement("column");
4668    
4669                            columnElement.addAttribute("name", "uuid");
4670                            columnElement.addAttribute("type", "String");
4671    
4672                            columnElements.add(0, columnElement);
4673                    }
4674    
4675                    for (Element columnElement : columnElements) {
4676                            String columnName = columnElement.attributeValue("name");
4677    
4678                            if (columnName.equals("resourceBlockId") &&
4679                                    !ejbName.equals("ResourceBlock")) {
4680    
4681                                    permissionedModel = true;
4682                            }
4683    
4684                            String columnDBName = columnElement.attributeValue("db-name");
4685    
4686                            if (Validator.isNull(columnDBName)) {
4687                                    columnDBName = columnName;
4688    
4689                                    if (_badColumnNames.contains(columnName)) {
4690                                            columnDBName += StringPool.UNDERLINE;
4691                                    }
4692                            }
4693    
4694                            String columnType = columnElement.attributeValue("type");
4695                            boolean primary = GetterUtil.getBoolean(
4696                                    columnElement.attributeValue("primary"));
4697                            boolean accessor = GetterUtil.getBoolean(
4698                                    columnElement.attributeValue("accessor"));
4699                            boolean filterPrimary = GetterUtil.getBoolean(
4700                                    columnElement.attributeValue("filter-primary"));
4701                            String collectionEntity = columnElement.attributeValue("entity");
4702    
4703                            String mappingTable = columnElement.attributeValue("mapping-table");
4704    
4705                            if (Validator.isNotNull(mappingTable)) {
4706                                    if (_badTableNames.contains(mappingTable)) {
4707                                            mappingTable += StringPool.UNDERLINE;
4708                                    }
4709    
4710                                    if (_autoNamespaceTables) {
4711                                            mappingTable =
4712                                                    _portletShortName + StringPool.UNDERLINE + mappingTable;
4713                                    }
4714                            }
4715    
4716                            String idType = columnElement.attributeValue("id-type");
4717                            String idParam = columnElement.attributeValue("id-param");
4718                            boolean convertNull = GetterUtil.getBoolean(
4719                                    columnElement.attributeValue("convert-null"), true);
4720                            boolean lazy = GetterUtil.getBoolean(
4721                                    columnElement.attributeValue("lazy"), true);
4722                            boolean localized = GetterUtil.getBoolean(
4723                                    columnElement.attributeValue("localized"));
4724                            boolean colJsonEnabled = GetterUtil.getBoolean(
4725                                    columnElement.attributeValue("json-enabled"), jsonEnabled);
4726                            boolean containerModel = GetterUtil.getBoolean(
4727                                    columnElement.attributeValue("container-model"));
4728                            boolean parentContainerModel = GetterUtil.getBoolean(
4729                                    columnElement.attributeValue("parent-container-model"));
4730    
4731                            EntityColumn col = new EntityColumn(
4732                                    columnName, columnDBName, columnType, primary, accessor,
4733                                    filterPrimary, collectionEntity, mappingTable, idType, idParam,
4734                                    convertNull, lazy, localized, colJsonEnabled, containerModel,
4735                                    parentContainerModel);
4736    
4737                            if (primary) {
4738                                    pkList.add(col);
4739                            }
4740    
4741                            if (columnType.equals("Collection")) {
4742                                    collectionList.add(col);
4743                            }
4744                            else {
4745                                    regularColList.add(col);
4746    
4747                                    if (columnType.equals("Blob")) {
4748                                            blobList.add(col);
4749                                    }
4750                            }
4751    
4752                            columnList.add(col);
4753    
4754                            if (Validator.isNotNull(collectionEntity) &&
4755                                    Validator.isNotNull(mappingTable)) {
4756    
4757                                    EntityMapping entityMapping = new EntityMapping(
4758                                            mappingTable, ejbName, collectionEntity);
4759    
4760                                    if (!_entityMappings.containsKey(mappingTable)) {
4761                                            _entityMappings.put(mappingTable, entityMapping);
4762                                    }
4763                            }
4764                    }
4765    
4766                    EntityOrder order = null;
4767    
4768                    Element orderElement = entityElement.element("order");
4769    
4770                    if (orderElement != null) {
4771                            boolean asc = true;
4772    
4773                            if ((orderElement.attribute("by") != null) &&
4774                                    orderElement.attributeValue("by").equals("desc")) {
4775    
4776                                    asc = false;
4777                            }
4778    
4779                            List<EntityColumn> orderColsList = new ArrayList<EntityColumn>();
4780    
4781                            order = new EntityOrder(asc, orderColsList);
4782    
4783                            List<Element> orderColumnElements = orderElement.elements(
4784                                    "order-column");
4785    
4786                            for (Element orderColElement : orderColumnElements) {
4787                                    String orderColName = orderColElement.attributeValue("name");
4788                                    boolean orderColCaseSensitive = GetterUtil.getBoolean(
4789                                            orderColElement.attributeValue("case-sensitive"), true);
4790    
4791                                    boolean orderColByAscending = asc;
4792    
4793                                    String orderColBy = GetterUtil.getString(
4794                                            orderColElement.attributeValue("order-by"));
4795    
4796                                    if (orderColBy.equals("asc")) {
4797                                            orderColByAscending = true;
4798                                    }
4799                                    else if (orderColBy.equals("desc")) {
4800                                            orderColByAscending = false;
4801                                    }
4802    
4803                                    EntityColumn col = Entity.getColumn(orderColName, columnList);
4804    
4805                                    col.setOrderColumn(true);
4806    
4807                                    col = (EntityColumn)col.clone();
4808    
4809                                    col.setCaseSensitive(orderColCaseSensitive);
4810                                    col.setOrderByAscending(orderColByAscending);
4811    
4812                                    orderColsList.add(col);
4813                            }
4814                    }
4815    
4816                    List<EntityFinder> finderList = new ArrayList<EntityFinder>();
4817    
4818                    List<Element> finderElements = entityElement.elements("finder");
4819    
4820                    if (uuid) {
4821                            if (columnList.contains(new EntityColumn("companyId"))) {
4822                                    Element finderElement = SAXReaderUtil.createElement("finder");
4823    
4824                                    finderElement.addAttribute("name", "Uuid_C");
4825                                    finderElement.addAttribute("return-type", "Collection");
4826    
4827                                    Element finderColumnElement = finderElement.addElement(
4828                                            "finder-column");
4829    
4830                                    finderColumnElement.addAttribute("name", "uuid");
4831    
4832                                    finderColumnElement = finderElement.addElement("finder-column");
4833    
4834                                    finderColumnElement.addAttribute("name", "companyId");
4835    
4836                                    finderElements.add(0, finderElement);
4837                            }
4838    
4839                            if (columnList.contains(new EntityColumn("groupId"))) {
4840                                    Element finderElement = SAXReaderUtil.createElement("finder");
4841    
4842                                    if (ejbName.equals("Layout")) {
4843                                            finderElement.addAttribute("name", "UUID_G_P");
4844                                    }
4845                                    else {
4846                                            finderElement.addAttribute("name", "UUID_G");
4847                                    }
4848    
4849                                    finderElement.addAttribute("return-type", ejbName);
4850                                    finderElement.addAttribute("unique", "true");
4851    
4852                                    Element finderColumnElement = finderElement.addElement(
4853                                            "finder-column");
4854    
4855                                    finderColumnElement.addAttribute("name", "uuid");
4856    
4857                                    finderColumnElement = finderElement.addElement("finder-column");
4858    
4859                                    finderColumnElement.addAttribute("name", "groupId");
4860    
4861                                    if (ejbName.equals("Layout")) {
4862                                            finderColumnElement = finderElement.addElement(
4863                                                    "finder-column");
4864    
4865                                            finderColumnElement.addAttribute("name", "privateLayout");
4866                                    }
4867    
4868                                    finderElements.add(0, finderElement);
4869                            }
4870    
4871                            Element finderElement = SAXReaderUtil.createElement("finder");
4872    
4873                            finderElement.addAttribute("name", "Uuid");
4874                            finderElement.addAttribute("return-type", "Collection");
4875    
4876                            Element finderColumnElement = finderElement.addElement(
4877                                    "finder-column");
4878    
4879                            finderColumnElement.addAttribute("name", "uuid");
4880    
4881                            finderElements.add(0, finderElement);
4882                    }
4883    
4884                    if (permissionedModel) {
4885                            Element finderElement = SAXReaderUtil.createElement("finder");
4886    
4887                            finderElement.addAttribute("name", "ResourceBlockId");
4888                            finderElement.addAttribute("return-type", "Collection");
4889    
4890                            Element finderColumnElement = finderElement.addElement(
4891                                    "finder-column");
4892    
4893                            finderColumnElement.addAttribute("name", "resourceBlockId");
4894    
4895                            finderElements.add(0, finderElement);
4896                    }
4897    
4898                    String alias = TextFormatter.format(ejbName, TextFormatter.I);
4899    
4900                    if (_badAliasNames.contains(StringUtil.toLowerCase(alias))) {
4901                            alias += StringPool.UNDERLINE;
4902                    }
4903    
4904                    for (Element finderElement : finderElements) {
4905                            String finderName = finderElement.attributeValue("name");
4906                            String finderReturn = finderElement.attributeValue("return-type");
4907                            boolean finderUnique = GetterUtil.getBoolean(
4908                                    finderElement.attributeValue("unique"));
4909    
4910                            String finderWhere = finderElement.attributeValue("where");
4911    
4912                            if (Validator.isNotNull(finderWhere)) {
4913                                    for (EntityColumn column : columnList) {
4914                                            String name = column.getName();
4915    
4916                                            if (finderWhere.contains(name)) {
4917                                                    finderWhere = finderWhere.replaceAll(
4918                                                            name, alias + "." + name);
4919                                            }
4920                                    }
4921                            }
4922    
4923                            boolean finderDBIndex = GetterUtil.getBoolean(
4924                                    finderElement.attributeValue("db-index"), true);
4925    
4926                            List<EntityColumn> finderColsList = new ArrayList<EntityColumn>();
4927    
4928                            List<Element> finderColumnElements = finderElement.elements(
4929                                    "finder-column");
4930    
4931                            for (Element finderColumnElement : finderColumnElements) {
4932                                    String finderColName = finderColumnElement.attributeValue(
4933                                            "name");
4934                                    boolean finderColCaseSensitive = GetterUtil.getBoolean(
4935                                            finderColumnElement.attributeValue("case-sensitive"), true);
4936                                    String finderColComparator = GetterUtil.getString(
4937                                            finderColumnElement.attributeValue("comparator"), "=");
4938                                    String finderColArrayableOperator =
4939                                            GetterUtil.getString(
4940                                                    finderColumnElement.attributeValue(
4941                                                    "arrayable-operator"));
4942    
4943                                    EntityColumn col = Entity.getColumn(finderColName, columnList);
4944    
4945                                    if (!col.isFinderPath()) {
4946                                            col.setFinderPath(true);
4947                                    }
4948    
4949                                    col = (EntityColumn)col.clone();
4950    
4951                                    col.setCaseSensitive(finderColCaseSensitive);
4952                                    col.setComparator(finderColComparator);
4953                                    col.setArrayableOperator(finderColArrayableOperator);
4954    
4955                                    finderColsList.add(col);
4956                            }
4957    
4958                            finderList.add(
4959                                    new EntityFinder(
4960                                            finderName, finderReturn, finderUnique, finderWhere,
4961                                            finderDBIndex, finderColsList));
4962                    }
4963    
4964                    List<Entity> referenceList = new ArrayList<Entity>();
4965    
4966                    if (_build) {
4967                            if (Validator.isNotNull(_pluginName)) {
4968                                    for (String config : PropsValues.RESOURCE_ACTIONS_CONFIGS) {
4969                                            File file = new File(_implDir + "/" + config);
4970    
4971                                            if (file.exists()) {
4972                                                    InputStream inputStream = new FileInputStream(file);
4973    
4974                                                    ResourceActionsUtil.read(_pluginName, inputStream);
4975                                            }
4976                                    }
4977                            }
4978    
4979                            List<Element> referenceElements = entityElement.elements(
4980                                    "reference");
4981    
4982                            Set<String> referenceSet = new TreeSet<String>();
4983    
4984                            for (Element referenceElement : referenceElements) {
4985                                    String referencePackage = referenceElement.attributeValue(
4986                                            "package-path");
4987                                    String referenceEntity = referenceElement.attributeValue(
4988                                            "entity");
4989    
4990                                    referenceSet.add(referencePackage + "." + referenceEntity);
4991                            }
4992    
4993                            if (!_packagePath.equals("com.liferay.counter")) {
4994                                    referenceSet.add("com.liferay.counter.Counter");
4995                            }
4996    
4997                            if (!_packagePath.equals("com.liferay.portal")) {
4998                                    referenceSet.add("com.liferay.portal.Resource");
4999                                    referenceSet.add("com.liferay.portal.User");
5000                            }
5001    
5002                            for (String referenceName : referenceSet) {
5003                                    referenceList.add(getEntity(referenceName));
5004                            }
5005                    }
5006    
5007                    List<String> txRequiredList = new ArrayList<String>();
5008    
5009                    List<Element> txRequiredElements = entityElement.elements(
5010                            "tx-required");
5011    
5012                    for (Element txRequiredEl : txRequiredElements) {
5013                            String txRequired = txRequiredEl.getText();
5014    
5015                            txRequiredList.add(txRequired);
5016                    }
5017    
5018                    _ejbList.add(
5019                            new Entity(
5020                                    _packagePath, _portletName, _portletShortName, ejbName,
5021                                    humanName, table, alias, uuid, uuidAccessor, localService,
5022                                    remoteService, persistenceClass, finderClass, dataSource,
5023                                    sessionFactory, txManager, cacheEnabled, jsonEnabled,
5024                                    trashEnabled, deprecated, pkList, regularColList, blobList,
5025                                    collectionList, columnList, order, finderList, referenceList,
5026                                    txRequiredList));
5027            }
5028    
5029            private String _processTemplate(String name) throws Exception {
5030                    return _processTemplate(name, _getContext());
5031            }
5032    
5033            private String _processTemplate(String name, Map<String, Object> context)
5034                    throws Exception {
5035    
5036                    return StringUtil.strip(FreeMarkerUtil.process(name, context), '\r');
5037            }
5038    
5039            private Map<String, Object> _putDeprecatedKeys(
5040                    Map<String, Object> context, JavaClass javaClass) {
5041    
5042                    context.put("classDeprecated", false);
5043    
5044                    DocletTag tag = javaClass.getTagByName("deprecated");
5045    
5046                    if (tag != null) {
5047                            context.put("classDeprecated", true);
5048                            context.put("classDeprecatedComment", tag.getValue());
5049                    }
5050    
5051                    return context;
5052            }
5053    
5054            private Set<String> _readLines(String fileName) throws Exception {
5055                    ClassLoader classLoader = getClass().getClassLoader();
5056    
5057                    Set<String> lines = new HashSet<String>();
5058    
5059                    StringUtil.readLines(classLoader.getResourceAsStream(fileName), lines);
5060    
5061                    return lines;
5062            }
5063    
5064            private void _updateSQLFile(
5065                            String sqlFileName, String createTableSQL, Entity entity)
5066                    throws IOException {
5067    
5068                    File updateSQLFile = new File(_sqlDir + "/" + sqlFileName);
5069    
5070                    if (updateSQLFile.exists()) {
5071                            _createSQLTables(updateSQLFile, createTableSQL, entity, false);
5072                    }
5073            }
5074    
5075            private static final int _SESSION_TYPE_LOCAL = 1;
5076    
5077            private static final int _SESSION_TYPE_REMOTE = 0;
5078    
5079            private static final String _SQL_CREATE_TABLE = "create table ";
5080    
5081            private static final String _TPL_ROOT =
5082                    "com/liferay/portal/tools/servicebuilder/dependencies/";
5083    
5084            private static Pattern _getterPattern = Pattern.compile(
5085                    "public .* get.*" + Pattern.quote("(") + "|public boolean is.*" +
5086                            Pattern.quote("("));
5087            private static Pattern _setterPattern = Pattern.compile(
5088                    "public void set.*" + Pattern.quote("("));
5089    
5090            private String _apiDir;
5091            private String _author;
5092            private boolean _autoNamespaceTables;
5093            private Set<String> _badAliasNames;
5094            private Set<String> _badColumnNames;
5095            private Set<String> _badTableNames;
5096            private String _beanLocatorUtil;
5097            private String _beanLocatorUtilShortName;
5098            private boolean _build;
5099            private long _buildNumber;
5100            private boolean _buildNumberIncrement;
5101            private List<Entity> _ejbList;
5102            private Map<String, EntityMapping> _entityMappings;
5103            private Map<String, Entity> _entityPool = new HashMap<String, Entity>();
5104            private String _hbmFileName;
5105            private String _implDir;
5106            private Map<String, JavaClass> _javaClasses =
5107                    new HashMap<String, JavaClass>();
5108            private String _modelHintsFileName;
5109            private String _ormFileName;
5110            private String _outputPath;
5111            private String _packagePath;
5112            private String _pluginName;
5113            private String _portletName = StringPool.BLANK;
5114            private String _portletPackageName = StringPool.BLANK;
5115            private String _portletShortName = StringPool.BLANK;
5116            private String _propsUtil;
5117            private String _remotingFileName;
5118            private String _serviceOutputPath;
5119            private String _springBaseFileName;
5120            private String _springClusterFileName;
5121            private String _springDynamicDataSourceFileName;
5122            private String _springFileName;
5123            private String _springHibernateFileName;
5124            private String _springInfrastructureFileName;
5125            private String _springShardDataSourceFileName;
5126            private String _sqlDir;
5127            private String _sqlFileName;
5128            private String _sqlIndexesFileName;
5129            private String _sqlIndexesPropertiesFileName;
5130            private String _sqlSequencesFileName;
5131            private String _targetEntityName;
5132            private String _testDir;
5133            private String _testOutputPath;
5134            private String _tplActionableDynamicQuery =
5135                    _TPL_ROOT + "actionable_dynamic_query.ftl";
5136            private String _tplBadAliasNames = _TPL_ROOT + "bad_alias_names.txt";
5137            private String _tplBadColumnNames = _TPL_ROOT + "bad_column_names.txt";
5138            private String _tplBadTableNames = _TPL_ROOT + "bad_table_names.txt";
5139            private String _tplBlobModel = _TPL_ROOT + "blob_model.ftl";
5140            private String _tplEjbPk = _TPL_ROOT + "ejb_pk.ftl";
5141            private String _tplException = _TPL_ROOT + "exception.ftl";
5142            private String _tplExportActionableDynamicQuery =
5143                    _TPL_ROOT + "export_actionable_dynamic_query.ftl";
5144            private String _tplExtendedModel = _TPL_ROOT + "extended_model.ftl";
5145            private String _tplExtendedModelBaseImpl =
5146                    _TPL_ROOT + "extended_model_base_impl.ftl";
5147            private String _tplExtendedModelImpl =
5148                    _TPL_ROOT + "extended_model_impl.ftl";
5149            private String _tplFinder = _TPL_ROOT + "finder.ftl";
5150            private String _tplFinderUtil = _TPL_ROOT + "finder_util.ftl";
5151            private String _tplHbmXml = _TPL_ROOT + "hbm_xml.ftl";
5152            private String _tplJsonJs = _TPL_ROOT + "json_js.ftl";
5153            private String _tplJsonJsMethod = _TPL_ROOT + "json_js_method.ftl";
5154            private String _tplModel = _TPL_ROOT + "model.ftl";
5155            private String _tplModelCache = _TPL_ROOT + "model_cache.ftl";
5156            private String _tplModelClp = _TPL_ROOT + "model_clp.ftl";
5157            private String _tplModelHintsXml = _TPL_ROOT + "model_hints_xml.ftl";
5158            private String _tplModelImpl = _TPL_ROOT + "model_impl.ftl";
5159            private String _tplModelSoap = _TPL_ROOT + "model_soap.ftl";
5160            private String _tplModelWrapper = _TPL_ROOT + "model_wrapper.ftl";
5161            private String _tplOrmXml = _TPL_ROOT + "orm_xml.ftl";
5162            private String _tplPersistence = _TPL_ROOT + "persistence.ftl";
5163            private String _tplPersistenceImpl = _TPL_ROOT + "persistence_impl.ftl";
5164            private String _tplPersistenceTest = _TPL_ROOT + "persistence_test.ftl";
5165            private String _tplPersistenceUtil = _TPL_ROOT + "persistence_util.ftl";
5166            private String _tplProps = _TPL_ROOT + "props.ftl";
5167            private String _tplRemotingXml = _TPL_ROOT + "remoting_xml.ftl";
5168            private String _tplService = _TPL_ROOT + "service.ftl";
5169            private String _tplServiceBaseImpl = _TPL_ROOT + "service_base_impl.ftl";
5170            private String _tplServiceClp = _TPL_ROOT + "service_clp.ftl";
5171            private String _tplServiceClpInvoker =
5172                    _TPL_ROOT + "service_clp_invoker.ftl";
5173            private String _tplServiceClpMessageListener =
5174                    _TPL_ROOT + "service_clp_message_listener.ftl";
5175            private String _tplServiceClpSerializer =
5176                    _TPL_ROOT + "service_clp_serializer.ftl";
5177            private String _tplServiceHttp = _TPL_ROOT + "service_http.ftl";
5178            private String _tplServiceImpl = _TPL_ROOT + "service_impl.ftl";
5179            private String _tplServiceSoap = _TPL_ROOT + "service_soap.ftl";
5180            private String _tplServiceUtil = _TPL_ROOT + "service_util.ftl";
5181            private String _tplServiceWrapper = _TPL_ROOT + "service_wrapper.ftl";
5182            private String _tplSpringBaseXml = _TPL_ROOT + "spring_base_xml.ftl";
5183            private String _tplSpringClusterXml = _TPL_ROOT + "spring_cluster_xml.ftl";
5184            private String _tplSpringHibernateXml =
5185                    _TPL_ROOT + "spring_hibernate_xml.ftl";
5186            private String _tplSpringInfrastructureXml =
5187                    _TPL_ROOT + "spring_infrastructure_xml.ftl";
5188            private String _tplSpringShardDataSourceXml =
5189                    _TPL_ROOT + "spring_shard_data_source_xml.ftl";
5190            private String _tplSpringXml = _TPL_ROOT + "spring_xml.ftl";
5191    
5192    }