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