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