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