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.deploy;
016    
017    import com.liferay.portal.deploy.DeployUtil;
018    import com.liferay.portal.kernel.deploy.Deployer;
019    import com.liferay.portal.kernel.deploy.auto.AutoDeployException;
020    import com.liferay.portal.kernel.deploy.auto.AutoDeployer;
021    import com.liferay.portal.kernel.deploy.auto.context.AutoDeploymentContext;
022    import com.liferay.portal.kernel.log.Log;
023    import com.liferay.portal.kernel.log.LogFactoryUtil;
024    import com.liferay.portal.kernel.plugin.License;
025    import com.liferay.portal.kernel.plugin.PluginPackage;
026    import com.liferay.portal.kernel.servlet.PluginContextListener;
027    import com.liferay.portal.kernel.servlet.PortalClassLoaderServlet;
028    import com.liferay.portal.kernel.servlet.PortalDelegateServlet;
029    import com.liferay.portal.kernel.servlet.PortletServlet;
030    import com.liferay.portal.kernel.servlet.SecurePluginContextListener;
031    import com.liferay.portal.kernel.servlet.SecureServlet;
032    import com.liferay.portal.kernel.servlet.SerializableSessionAttributeListener;
033    import com.liferay.portal.kernel.servlet.filters.invoker.InvokerFilter;
034    import com.liferay.portal.kernel.util.ArrayUtil;
035    import com.liferay.portal.kernel.util.CharPool;
036    import com.liferay.portal.kernel.util.FileUtil;
037    import com.liferay.portal.kernel.util.GetterUtil;
038    import com.liferay.portal.kernel.util.HttpUtil;
039    import com.liferay.portal.kernel.util.OSDetector;
040    import com.liferay.portal.kernel.util.PropertiesUtil;
041    import com.liferay.portal.kernel.util.PropsKeys;
042    import com.liferay.portal.kernel.util.ServerDetector;
043    import com.liferay.portal.kernel.util.StreamUtil;
044    import com.liferay.portal.kernel.util.StringBundler;
045    import com.liferay.portal.kernel.util.StringPool;
046    import com.liferay.portal.kernel.util.StringUtil;
047    import com.liferay.portal.kernel.util.SystemProperties;
048    import com.liferay.portal.kernel.util.TextFormatter;
049    import com.liferay.portal.kernel.util.Time;
050    import com.liferay.portal.kernel.util.Validator;
051    import com.liferay.portal.kernel.xml.Document;
052    import com.liferay.portal.kernel.xml.Element;
053    import com.liferay.portal.kernel.xml.SAXReaderUtil;
054    import com.liferay.portal.plugin.PluginPackageUtil;
055    import com.liferay.portal.security.lang.SecurityManagerUtil;
056    import com.liferay.portal.tools.ToolDependencies;
057    import com.liferay.portal.tools.WebXMLBuilder;
058    import com.liferay.portal.util.ExtRegistry;
059    import com.liferay.portal.util.PortalUtil;
060    import com.liferay.portal.util.PrefsPropsUtil;
061    import com.liferay.portal.util.PropsUtil;
062    import com.liferay.portal.util.PropsValues;
063    import com.liferay.portal.webserver.DynamicResourceServlet;
064    import com.liferay.util.ant.CopyTask;
065    import com.liferay.util.ant.DeleteTask;
066    import com.liferay.util.ant.ExpandTask;
067    import com.liferay.util.ant.UpToDateTask;
068    import com.liferay.util.ant.WarTask;
069    import com.liferay.util.xml.DocUtil;
070    import com.liferay.util.xml.XMLFormatter;
071    
072    import java.io.File;
073    import java.io.FileInputStream;
074    import java.io.IOException;
075    import java.io.InputStream;
076    
077    import java.util.ArrayList;
078    import java.util.HashMap;
079    import java.util.List;
080    import java.util.Map;
081    import java.util.Properties;
082    import java.util.Set;
083    import java.util.zip.ZipEntry;
084    import java.util.zip.ZipFile;
085    
086    import org.apache.oro.io.GlobFilenameFilter;
087    
088    /**
089     * @author Brian Wing Shun Chan
090     * @author Sandeep Soni
091     */
092    public class BaseDeployer implements AutoDeployer, Deployer {
093    
094            public static final String DEPLOY_TO_PREFIX = "DEPLOY_TO__";
095    
096            public static void main(String[] args) {
097                    ToolDependencies.wireDeployers();
098    
099                    List<String> wars = new ArrayList<String>();
100                    List<String> jars = new ArrayList<String>();
101    
102                    for (String arg : args) {
103                            String fileName = StringUtil.toLowerCase(arg);
104    
105                            if (fileName.endsWith(".war")) {
106                                    wars.add(arg);
107                            }
108                            else if (fileName.endsWith(".jar")) {
109                                    jars.add(arg);
110                            }
111                    }
112    
113                    new BaseDeployer(wars, jars);
114            }
115    
116            public BaseDeployer() {
117            }
118    
119            public BaseDeployer(List<String> wars, List<String> jars) {
120                    baseDir = System.getProperty("deployer.base.dir");
121                    destDir = System.getProperty("deployer.dest.dir");
122                    appServerType = System.getProperty("deployer.app.server.type");
123                    auiTaglibDTD = System.getProperty("deployer.aui.taglib.dtd");
124                    portletTaglibDTD = System.getProperty("deployer.portlet.taglib.dtd");
125                    portletExtTaglibDTD = System.getProperty(
126                            "deployer.portlet.ext.taglib.dtd");
127                    securityTaglibDTD = System.getProperty("deployer.security.taglib.dtd");
128                    themeTaglibDTD = System.getProperty("deployer.theme.taglib.dtd");
129                    uiTaglibDTD = System.getProperty("deployer.ui.taglib.dtd");
130                    utilTaglibDTD = System.getProperty("deployer.util.taglib.dtd");
131                    unpackWar = GetterUtil.getBoolean(
132                            System.getProperty("deployer.unpack.war"), true);
133                    filePattern = System.getProperty("deployer.file.pattern");
134                    jbossPrefix = GetterUtil.getString(
135                            System.getProperty("deployer.jboss.prefix"));
136                    tomcatLibDir = System.getProperty("deployer.tomcat.lib.dir");
137                    this.wars = wars;
138                    this.jars = jars;
139    
140                    checkArguments();
141    
142                    String context = System.getProperty("deployer.context");
143    
144                    try {
145                            deploy(context);
146                    }
147                    catch (Exception e) {
148                            _log.error(e, e);
149                    }
150            }
151    
152            @Override
153            public void addExtJar(List<String> jars, String resource) throws Exception {
154                    Set<String> servletContextNames = ExtRegistry.getServletContextNames();
155    
156                    for (String servletContextName : servletContextNames) {
157                            String extResource =
158                                    "ext-" + servletContextName + resource.substring(3);
159    
160                            String path = DeployUtil.getResourcePath(extResource);
161    
162                            if (_log.isDebugEnabled()) {
163                                    if (path == null) {
164                                            _log.debug("Resource " + extResource + " is not available");
165                                    }
166                                    else {
167                                            _log.debug(
168                                                    "Resource " + extResource + " is available at " + path);
169                                    }
170                            }
171    
172                            if (path != null) {
173                                    jars.add(path);
174                            }
175                    }
176            }
177    
178            @Override
179            public void addRequiredJar(List<String> jars, String resource)
180                    throws Exception {
181    
182                    String path = DeployUtil.getResourcePath(resource);
183    
184                    if (path == null) {
185                            throw new RuntimeException(
186                                    "Resource " + resource + " does not exist");
187                    }
188    
189                    if (_log.isDebugEnabled()) {
190                            _log.debug("Resource " + resource + " is available at " + path);
191                    }
192    
193                    jars.add(path);
194            }
195    
196            @Override
197            public int autoDeploy(AutoDeploymentContext autoDeploymentContext)
198                    throws AutoDeployException {
199    
200                    List<String> wars = new ArrayList<String>();
201    
202                    File file = autoDeploymentContext.getFile();
203    
204                    wars.add(file.getName());
205    
206                    this.wars = wars;
207    
208                    try {
209                            return deployFile(autoDeploymentContext);
210                    }
211                    catch (Exception e) {
212                            throw new AutoDeployException(e);
213                    }
214            }
215    
216            @Override
217            public void checkArguments() {
218                    if (Validator.isNull(baseDir)) {
219                            throw new IllegalArgumentException(
220                                    "The system property deployer.base.dir is not set");
221                    }
222    
223                    if (Validator.isNull(destDir)) {
224                            throw new IllegalArgumentException(
225                                    "The system property deployer.dest.dir is not set");
226                    }
227    
228                    if (Validator.isNull(appServerType)) {
229                            throw new IllegalArgumentException(
230                                    "The system property deployer.app.server.type is not set");
231                    }
232    
233                    if (!appServerType.equals(ServerDetector.GERONIMO_ID) &&
234                            !appServerType.equals(ServerDetector.GLASSFISH_ID) &&
235                            !appServerType.equals(ServerDetector.JBOSS_ID) &&
236                            !appServerType.equals(ServerDetector.JONAS_ID) &&
237                            !appServerType.equals(ServerDetector.JETTY_ID) &&
238                            !appServerType.equals(ServerDetector.OC4J_ID) &&
239                            !appServerType.equals(ServerDetector.RESIN_ID) &&
240                            !appServerType.equals(ServerDetector.TOMCAT_ID) &&
241                            !appServerType.equals(ServerDetector.WEBLOGIC_ID) &&
242                            !appServerType.equals(ServerDetector.WEBSPHERE_ID)) {
243    
244                            throw new IllegalArgumentException(
245                                    appServerType + " is not a valid application server type");
246                    }
247    
248                    if (appServerType.equals(ServerDetector.GLASSFISH_ID) ||
249                            appServerType.equals(ServerDetector.WEBSPHERE_ID)) {
250    
251                            unpackWar = false;
252                    }
253    
254                    if (Validator.isNotNull(jbossPrefix) &&
255                            !Validator.isNumber(jbossPrefix)) {
256    
257                            jbossPrefix = "1";
258                    }
259            }
260    
261            @Override
262            public AutoDeployer cloneAutoDeployer() throws AutoDeployException {
263                    try {
264                            Class<?> clazz = getClass();
265    
266                            Deployer deployer = (Deployer)clazz.newInstance();
267    
268                            deployer.setAppServerType(appServerType);
269                            deployer.setAuiTaglibDTD(auiTaglibDTD);
270                            deployer.setBaseDir(baseDir);
271                            deployer.setDestDir(destDir);
272                            deployer.setFilePattern(filePattern);
273                            deployer.setJars(jars);
274                            deployer.setJbossPrefix(jbossPrefix);
275                            deployer.setPortletExtTaglibDTD(portletExtTaglibDTD);
276                            deployer.setPortletTaglibDTD(portletTaglibDTD);
277                            deployer.setSecurityTaglibDTD(securityTaglibDTD);
278                            deployer.setThemeTaglibDTD(themeTaglibDTD);
279                            deployer.setTomcatLibDir(tomcatLibDir);
280                            deployer.setUiTaglibDTD(uiTaglibDTD);
281                            deployer.setUnpackWar(unpackWar);
282                            deployer.setUtilTaglibDTD(utilTaglibDTD);
283                            deployer.setWars(wars);
284    
285                            return (AutoDeployer)deployer;
286                    }
287                    catch (Exception e) {
288                            throw new AutoDeployException(e);
289                    }
290            }
291    
292            @Override
293            public void copyDependencyXml(String fileName, String targetDir)
294                    throws Exception {
295    
296                    copyDependencyXml(fileName, targetDir, null);
297            }
298    
299            @Override
300            public void copyDependencyXml(
301                            String fileName, String targetDir, Map<String, String> filterMap)
302                    throws Exception {
303    
304                    copyDependencyXml(fileName, targetDir, filterMap, false);
305            }
306    
307            @Override
308            public void copyDependencyXml(
309                            String fileName, String targetDir, Map<String, String> filterMap,
310                            boolean overwrite)
311                    throws Exception {
312    
313                    DeployUtil.copyDependencyXml(
314                            fileName, targetDir, fileName, filterMap, overwrite);
315            }
316    
317            public void copyDtds(File srcFile, PluginPackage pluginPackage)
318                    throws Exception {
319    
320                    File portalLog4jXml = new File(
321                            srcFile.getAbsolutePath() +
322                                    "/WEB-INF/classes/META-INF/portal-log4j.xml");
323    
324                    if (!portalLog4jXml.exists()) {
325                            return;
326                    }
327    
328                    InputStream is = null;
329    
330                    try {
331                            Class<?> clazz = getClass();
332    
333                            ClassLoader classLoader = clazz.getClassLoader();
334    
335                            is = classLoader.getResourceAsStream("META-INF/log4j.dtd");
336    
337                            File file = new File(
338                                    srcFile.getAbsolutePath() +
339                                            "/WEB-INF/classes/META-INF/log4j.dtd");
340    
341                            FileUtil.write(file, is);
342                    }
343                    finally {
344                            StreamUtil.cleanUp(is);
345                    }
346            }
347    
348            @Override
349            public void copyJars(File srcFile, PluginPackage pluginPackage)
350                    throws Exception {
351    
352                    for (int i = 0; i < jars.size(); i++) {
353                            String jarFullName = jars.get(i);
354    
355                            String jarName = jarFullName.substring(
356                                    jarFullName.lastIndexOf("/") + 1);
357    
358                            if (!FileUtil.exists(jarFullName)) {
359                                    DeployUtil.getResourcePath(jarName);
360                            }
361    
362                            FileUtil.copyFile(
363                                    jarFullName, srcFile + "/WEB-INF/lib/" + jarName, false);
364                    }
365            }
366    
367            public void copyPortalDependencies(File srcFile) throws Exception {
368                    Properties properties = getPluginPackageProperties(srcFile);
369    
370                    if (properties == null) {
371                            return;
372                    }
373    
374                    // jars
375    
376                    String[] portalJars = StringUtil.split(
377                            properties.getProperty(
378                                    "portal-dependency-jars",
379                                    properties.getProperty("portal.dependency.jars")));
380    
381                    for (String portalJar : portalJars) {
382                            portalJar = portalJar.trim();
383    
384                            portalJar = fixPortalDependencyJar(portalJar);
385    
386                            if (_log.isDebugEnabled()) {
387                                    _log.debug("Copy portal JAR " + portalJar);
388                            }
389    
390                            try {
391                                    String portalJarPath = PortalUtil.getPortalLibDir() + portalJar;
392    
393                                    FileUtil.copyFile(
394                                            portalJarPath, srcFile + "/WEB-INF/lib/" + portalJar, true);
395                            }
396                            catch (Exception e) {
397                                    _log.error("Unable to copy portal JAR " + portalJar, e);
398                            }
399                    }
400    
401                    // tlds
402    
403                    String[] portalTlds = StringUtil.split(
404                            properties.getProperty(
405                                    "portal-dependency-tlds",
406                                    properties.getProperty("portal.dependency.tlds")));
407    
408                    for (String portalTld : portalTlds) {
409                            portalTld = portalTld.trim();
410    
411                            if (_log.isDebugEnabled()) {
412                                    _log.debug("Copy portal TLD " + portalTld);
413                            }
414    
415                            try {
416                                    String portalTldPath = DeployUtil.getResourcePath(portalTld);
417    
418                                    FileUtil.copyFile(
419                                            portalTldPath, srcFile + "/WEB-INF/tld/" + portalTld, true);
420                            }
421                            catch (Exception e) {
422                                    _log.error("Unable to copy portal TLD " + portalTld, e);
423                            }
424                    }
425    
426                    // commons-logging*.jar
427    
428                    File pluginLibDir = new File(srcFile + "/WEB-INF/lib/");
429    
430                    if (PropsValues.AUTO_DEPLOY_COPY_COMMONS_LOGGING) {
431                            String[] commonsLoggingJars = pluginLibDir.list(
432                                    new GlobFilenameFilter("commons-logging*.jar"));
433    
434                            if (ArrayUtil.isEmpty(commonsLoggingJars)) {
435                                    String portalJarPath =
436                                            PortalUtil.getPortalLibDir() + "commons-logging.jar";
437    
438                                    FileUtil.copyFile(
439                                            portalJarPath, srcFile + "/WEB-INF/lib/commons-logging.jar",
440                                            true);
441                            }
442                    }
443    
444                    // log4j*.jar
445    
446                    if (PropsValues.AUTO_DEPLOY_COPY_LOG4J) {
447                            String[] log4jJars = pluginLibDir.list(
448                                    new GlobFilenameFilter("log4j*.jar"));
449    
450                            if (ArrayUtil.isEmpty(log4jJars)) {
451                                    String portalJarPath =
452                                            PortalUtil.getPortalLibDir() + "log4j.jar";
453    
454                                    FileUtil.copyFile(
455                                            portalJarPath, srcFile + "/WEB-INF/lib/log4j.jar", true);
456    
457                                    portalJarPath =
458                                            PortalUtil.getPortalLibDir() + "log4j-extras.jar";
459    
460                                    FileUtil.copyFile(
461                                            portalJarPath, srcFile + "/WEB-INF/lib/log4j-extras.jar",
462                                            true);
463                            }
464                    }
465            }
466    
467            @Override
468            public void copyProperties(File srcFile, PluginPackage pluginPackage)
469                    throws Exception {
470    
471                    if (PropsValues.AUTO_DEPLOY_COPY_COMMONS_LOGGING) {
472                            copyDependencyXml(
473                                    "logging.properties", srcFile + "/WEB-INF/classes");
474                    }
475    
476                    if (PropsValues.AUTO_DEPLOY_COPY_LOG4J) {
477                            copyDependencyXml("log4j.properties", srcFile + "/WEB-INF/classes");
478                    }
479    
480                    File servicePropertiesFile = new File(
481                            srcFile.getAbsolutePath() + "/WEB-INF/classes/service.properties");
482    
483                    if (!servicePropertiesFile.exists()) {
484                            return;
485                    }
486    
487                    File portletPropertiesFile = new File(
488                            srcFile.getAbsolutePath() +
489                                    "/WEB-INF/classes/portlet.properties");
490    
491                    if (portletPropertiesFile.exists()) {
492                            return;
493                    }
494    
495                    String pluginPackageName = null;
496    
497                    if (pluginPackage != null) {
498                            pluginPackageName = pluginPackage.getName();
499                    }
500                    else {
501                            pluginPackageName = srcFile.getName();
502                    }
503    
504                    FileUtil.write(
505                            portletPropertiesFile, "plugin.package.name=" + pluginPackageName);
506            }
507    
508            @Override
509            public void copyTlds(File srcFile, PluginPackage pluginPackage)
510                    throws Exception {
511    
512                    if (Validator.isNotNull(auiTaglibDTD)) {
513                            FileUtil.copyFile(
514                                    auiTaglibDTD, srcFile + "/WEB-INF/tld/aui.tld", true);
515                    }
516    
517                    if (Validator.isNotNull(portletTaglibDTD)) {
518                            FileUtil.copyFile(
519                                    portletTaglibDTD, srcFile + "/WEB-INF/tld/liferay-portlet.tld",
520                                    true);
521                    }
522    
523                    if (Validator.isNotNull(portletExtTaglibDTD)) {
524                            FileUtil.copyFile(
525                                    portletExtTaglibDTD,
526                                    srcFile + "/WEB-INF/tld/liferay-portlet-ext.tld", true);
527                    }
528    
529                    if (Validator.isNotNull(securityTaglibDTD)) {
530                            FileUtil.copyFile(
531                                    securityTaglibDTD,
532                                    srcFile + "/WEB-INF/tld/liferay-security.tld", true);
533                    }
534    
535                    if (Validator.isNotNull(themeTaglibDTD)) {
536                            FileUtil.copyFile(
537                                    themeTaglibDTD, srcFile + "/WEB-INF/tld/liferay-theme.tld",
538                                    true);
539                    }
540    
541                    if (Validator.isNotNull(uiTaglibDTD)) {
542                            FileUtil.copyFile(
543                                    uiTaglibDTD, srcFile + "/WEB-INF/tld/liferay-ui.tld", true);
544                    }
545    
546                    if (Validator.isNotNull(utilTaglibDTD)) {
547                            FileUtil.copyFile(
548                                    utilTaglibDTD, srcFile + "/WEB-INF/tld/liferay-util.tld", true);
549                    }
550            }
551    
552            public void copyTomcatContextXml(File targetDir) throws Exception {
553                    if (!appServerType.equals(ServerDetector.TOMCAT_ID) ||
554                            SecurityManagerUtil.ENABLED) {
555    
556                            return;
557                    }
558    
559                    File targetFile = new File(targetDir, "META-INF/context.xml");
560    
561                    if (targetFile.exists()) {
562                            return;
563                    }
564    
565                    String contextPath = DeployUtil.getResourcePath("context.xml");
566    
567                    String content = FileUtil.read(contextPath);
568    
569                    if (!PropsValues.AUTO_DEPLOY_UNPACK_WAR) {
570                            content = StringUtil.replace(
571                                    content, "antiResourceLocking=\"true\"", StringPool.BLANK);
572                    }
573    
574                    FileUtil.write(targetFile, content);
575            }
576    
577            @Override
578            public void copyXmls(
579                            File srcFile, String displayName, PluginPackage pluginPackage)
580                    throws Exception {
581    
582                    if (appServerType.equals(ServerDetector.GERONIMO_ID)) {
583                            copyDependencyXml("geronimo-web.xml", srcFile + "/WEB-INF");
584                    }
585                    else if (appServerType.equals(ServerDetector.JBOSS_ID)) {
586                            if (ServerDetector.isJBoss5()) {
587                                    copyDependencyXml("jboss-web.xml", srcFile + "/WEB-INF");
588                            }
589                            else {
590                                    copyDependencyXml(
591                                            "jboss-deployment-structure.xml", srcFile + "/WEB-INF");
592                            }
593                    }
594                    else if (appServerType.equals(ServerDetector.WEBLOGIC_ID)) {
595                            copyDependencyXml("weblogic.xml", srcFile + "/WEB-INF");
596                    }
597                    else if (appServerType.equals(ServerDetector.WEBSPHERE_ID)) {
598                            copyDependencyXml("ibm-web-ext.xmi", srcFile + "/WEB-INF");
599                    }
600    
601                    copyDependencyXml("web.xml", srcFile + "/WEB-INF");
602            }
603    
604            public void deploy(String context) throws Exception {
605                    try {
606                            File baseDirFile = new File(baseDir);
607    
608                            File[] files = baseDirFile.listFiles();
609    
610                            if (files == null) {
611                                    return;
612                            }
613    
614                            files = FileUtil.sortFiles(files);
615    
616                            for (File srcFile : files) {
617                                    String fileName = StringUtil.toLowerCase(srcFile.getName());
618    
619                                    boolean deploy = false;
620    
621                                    if (fileName.endsWith(".war") || fileName.endsWith(".zip")) {
622                                            deploy = true;
623    
624                                            if (!wars.isEmpty()) {
625                                                    if (!wars.contains(srcFile.getName())) {
626                                                            deploy = false;
627                                                    }
628                                            }
629                                            else if (Validator.isNotNull(filePattern)) {
630                                                    if (!StringUtil.matchesIgnoreCase(
631                                                                    fileName, filePattern)) {
632    
633                                                            deploy = false;
634                                                    }
635                                            }
636                                    }
637    
638                                    if (deploy) {
639                                            AutoDeploymentContext autoDeploymentContext =
640                                                    new AutoDeploymentContext();
641    
642                                            autoDeploymentContext.setContext(context);
643                                            autoDeploymentContext.setFile(srcFile);
644    
645                                            deployFile(autoDeploymentContext);
646                                    }
647                            }
648                    }
649                    catch (Exception e) {
650                            _log.error(e, e);
651                    }
652            }
653    
654            public void deployDirectory(
655                            File srcFile, File mergeDir, File deployDir, String displayName,
656                            boolean overwrite, PluginPackage pluginPackage)
657                    throws Exception {
658    
659                    rewriteFiles(srcFile);
660    
661                    mergeDirectory(mergeDir, srcFile);
662    
663                    processPluginPackageProperties(srcFile, displayName, pluginPackage);
664    
665                    copyDtds(srcFile, pluginPackage);
666                    copyJars(srcFile, pluginPackage);
667                    copyProperties(srcFile, pluginPackage);
668                    copyTlds(srcFile, pluginPackage);
669                    copyXmls(srcFile, displayName, pluginPackage);
670                    copyPortalDependencies(srcFile);
671    
672                    updateGeronimoWebXml(srcFile, displayName, pluginPackage);
673    
674                    File webXml = new File(srcFile + "/WEB-INF/web.xml");
675    
676                    updateWebXml(webXml, srcFile, displayName, pluginPackage);
677    
678                    File extLibGlobalDir = new File(
679                            srcFile.getAbsolutePath() + "/WEB-INF/ext-lib/global");
680    
681                    if (extLibGlobalDir.exists()) {
682                            File globalLibDir = new File(PortalUtil.getGlobalLibDir());
683    
684                            CopyTask.copyDirectory(
685                                    extLibGlobalDir, globalLibDir, "*.jar", StringPool.BLANK,
686                                    overwrite, true);
687                    }
688    
689                    File extLibPortalDir = new File(
690                            srcFile.getAbsolutePath() + "/WEB-INF/ext-lib/portal");
691    
692                    if (extLibPortalDir.exists()) {
693                            File portalLibDir = new File(PortalUtil.getPortalLibDir());
694    
695                            CopyTask.copyDirectory(
696                                    extLibPortalDir, portalLibDir, "*.jar", StringPool.BLANK,
697                                    overwrite, true);
698                    }
699    
700                    if ((deployDir == null) || baseDir.equals(destDir)) {
701                            return;
702                    }
703    
704                    updateDeployDirectory(srcFile);
705    
706                    String excludes = StringPool.BLANK;
707    
708                    if (appServerType.equals(ServerDetector.JBOSS_ID)) {
709                            excludes += "**/WEB-INF/lib/log4j.jar,";
710                    }
711                    else if (appServerType.equals(ServerDetector.TOMCAT_ID)) {
712                            String[] libs = FileUtil.listFiles(tomcatLibDir);
713    
714                            for (String lib : libs) {
715                                    excludes += "**/WEB-INF/lib/" + lib + ",";
716                            }
717    
718                            File contextXml = new File(srcFile + "/META-INF/context.xml");
719    
720                            if (contextXml.exists()) {
721                                    String content = FileUtil.read(contextXml);
722    
723                                    if (content.contains(_PORTAL_CLASS_LOADER)) {
724                                            excludes += "**/WEB-INF/lib/util-bridges.jar,";
725                                            excludes += "**/WEB-INF/lib/util-java.jar,";
726                                            excludes += "**/WEB-INF/lib/util-taglib.jar,";
727                                    }
728                            }
729    
730                            try {
731    
732                                    // LEP-2990
733    
734                                    Class.forName("javax.el.ELContext");
735    
736                                    excludes += "**/WEB-INF/lib/el-api.jar,";
737                            }
738                            catch (ClassNotFoundException cnfe) {
739                            }
740                    }
741    
742                    // LPS-11268
743    
744                    Properties properties = getPluginPackageProperties(srcFile);
745    
746                    if (properties != null) {
747                            String deployExcludes = properties.getProperty("deploy-excludes");
748    
749                            if (deployExcludes != null) {
750                                    excludes += deployExcludes.trim();
751    
752                                    if (!excludes.endsWith(",")) {
753                                            excludes += ",";
754                                    }
755                            }
756    
757                            deployExcludes = properties.getProperty(
758                                    "deploy-excludes-" + appServerType);
759    
760                            if (deployExcludes != null) {
761                                    excludes += deployExcludes.trim();
762    
763                                    if (!excludes.endsWith(",")) {
764                                            excludes += ",";
765                                    }
766                            }
767                    }
768    
769                    if (_log.isDebugEnabled()) {
770                            _log.debug("Excludes " + excludes);
771                    }
772    
773                    if (!unpackWar) {
774                            File tempDir = new File(
775                                    SystemProperties.get(SystemProperties.TMP_DIR) +
776                                            File.separator + Time.getTimestamp());
777    
778                            excludes += "/WEB-INF/web.xml";
779    
780                            WarTask.war(srcFile, tempDir, excludes, webXml);
781    
782                            if (isJEEDeploymentEnabled()) {
783                                    File tempWarDir = new File(
784                                            tempDir.getParent(), deployDir.getName());
785    
786                                    if (tempWarDir.exists()) {
787                                            tempWarDir.delete();
788                                    }
789    
790                                    if (!tempDir.renameTo(tempWarDir)) {
791                                            tempWarDir = tempDir;
792                                    }
793    
794                                    DeploymentHandler deploymentHandler = getDeploymentHandler();
795    
796                                    deploymentHandler.deploy(tempWarDir, displayName);
797    
798                                    deploymentHandler.releaseDeploymentManager();
799    
800                                    DeleteTask.deleteDirectory(tempWarDir);
801                            }
802                            else {
803                                    if (!tempDir.renameTo(deployDir)) {
804                                            WarTask.war(srcFile, deployDir, excludes, webXml);
805                                    }
806    
807                                    if (tempDir.isDirectory()) {
808                                            DeleteTask.deleteDirectory(tempDir);
809                                    }
810                                    else {
811                                            tempDir.delete();
812                                    }
813                            }
814                    }
815                    else {
816    
817                            // The deployer might only copy files that have been modified.
818                            // However, the deployer always copies and overwrites web.xml after
819                            // the other files have been copied because application servers
820                            // usually detect that a WAR has been modified based on the web.xml
821                            // timestamp.
822    
823                            excludes += "**/WEB-INF/web.xml";
824    
825                            CopyTask.copyDirectory(
826                                    srcFile, deployDir, StringPool.BLANK, excludes, overwrite,
827                                    true);
828    
829                            CopyTask.copyDirectory(
830                                    srcFile, deployDir, "**/WEB-INF/web.xml", StringPool.BLANK,
831                                    true, false);
832    
833                            if (appServerType.equals(ServerDetector.TOMCAT_ID)) {
834    
835                                    // See org.apache.catalina.startup.HostConfig to see how Tomcat
836                                    // checks to make sure that web.xml was modified 5 seconds after
837                                    // WEB-INF
838    
839                                    File deployWebXml = new File(deployDir + "/WEB-INF/web.xml");
840    
841                                    deployWebXml.setLastModified(
842                                            System.currentTimeMillis() + (Time.SECOND * 6));
843                            }
844                    }
845    
846                    if (appServerType.equals(ServerDetector.JETTY_ID)) {
847                            DeployUtil.redeployJetty(displayName);
848                    }
849            }
850    
851            public void deployDirectory(
852                            File srcFile, String displayName, boolean override,
853                            PluginPackage pluginPackage)
854                    throws Exception {
855    
856                    deployDirectory(
857                            srcFile, null, null, displayName, override, pluginPackage);
858            }
859    
860            public int deployFile(AutoDeploymentContext autoDeploymentContext)
861                    throws Exception {
862    
863                    File srcFile = autoDeploymentContext.getFile();
864    
865                    PluginPackage pluginPackage = autoDeploymentContext.getPluginPackage();
866    
867                    if (pluginPackage == null) {
868                            pluginPackage = readPluginPackage(srcFile);
869    
870                            autoDeploymentContext.setPluginPackage(pluginPackage);
871                    }
872    
873                    if (_log.isInfoEnabled()) {
874                            _log.info("Deploying " + srcFile.getName());
875                    }
876    
877                    String autoDeploymentContextAppServerType =
878                            autoDeploymentContext.getAppServerType();
879    
880                    if (Validator.isNotNull(autoDeploymentContextAppServerType)) {
881                            appServerType = autoDeploymentContextAppServerType;
882                    }
883    
884                    String specifiedContext = autoDeploymentContext.getContext();
885    
886                    String displayName = specifiedContext;
887                    boolean overwrite = false;
888                    String preliminaryContext = specifiedContext;
889    
890                    // The order of priority of the context is: 1.) the specified context,
891                    // 2.) if the file name starts with DEPLOY_TO_PREFIX, use the file name
892                    // after the prefix, or 3.) the recommended deployment context as
893                    // specified in liferay-plugin-package.properties, or 4.) the file name.
894    
895                    if (Validator.isNull(specifiedContext) &&
896                            srcFile.getName().startsWith(DEPLOY_TO_PREFIX)) {
897    
898                            displayName = srcFile.getName().substring(
899                                    DEPLOY_TO_PREFIX.length(), srcFile.getName().length() - 4);
900    
901                            overwrite = true;
902                            preliminaryContext = displayName;
903                    }
904    
905                    if (preliminaryContext == null) {
906                            preliminaryContext = getDisplayName(srcFile);
907                    }
908    
909                    if (pluginPackage != null) {
910                            if (!PluginPackageUtil.isCurrentVersionSupported(
911                                            pluginPackage.getLiferayVersions())) {
912    
913                                    throw new AutoDeployException(
914                                            srcFile.getName() +
915                                                    " does not support this version of Liferay");
916                            }
917    
918                            if (displayName == null) {
919                                    displayName = pluginPackage.getRecommendedDeploymentContext();
920                            }
921    
922                            if (Validator.isNull(displayName)) {
923                                    displayName = getDisplayName(srcFile);
924                            }
925    
926                            pluginPackage.setContext(displayName);
927    
928                            PluginPackageUtil.updateInstallingPluginPackage(
929                                    preliminaryContext, pluginPackage);
930                    }
931    
932                    String deployDir = null;
933    
934                    if (Validator.isNotNull(displayName)) {
935                            deployDir = displayName + ".war";
936                    }
937                    else {
938                            deployDir = srcFile.getName();
939                            displayName = getDisplayName(srcFile);
940                    }
941    
942                    if (appServerType.equals(ServerDetector.JBOSS_ID)) {
943                            deployDir = jbossPrefix + deployDir;
944                    }
945                    else if (appServerType.equals(ServerDetector.GERONIMO_ID) ||
946                                     appServerType.equals(ServerDetector.GLASSFISH_ID) ||
947                                     appServerType.equals(ServerDetector.JETTY_ID) ||
948                                     appServerType.equals(ServerDetector.JONAS_ID) ||
949                                     appServerType.equals(ServerDetector.OC4J_ID) ||
950                                     appServerType.equals(ServerDetector.RESIN_ID) ||
951                                     appServerType.equals(ServerDetector.TOMCAT_ID) ||
952                                     appServerType.equals(ServerDetector.WEBLOGIC_ID)) {
953    
954                            if (unpackWar) {
955                                    deployDir = deployDir.substring(0, deployDir.length() - 4);
956                            }
957                    }
958    
959                    String destDir = this.destDir;
960    
961                    if (autoDeploymentContext.getDestDir() != null) {
962                            destDir = autoDeploymentContext.getDestDir();
963                    }
964    
965                    File deployDirFile = new File(destDir + "/" + deployDir);
966    
967                    try {
968                            PluginPackage previousPluginPackage = readPluginPackage(
969                                    deployDirFile);
970    
971                            if ((pluginPackage != null) && (previousPluginPackage != null)) {
972                                    String name = pluginPackage.getName();
973                                    String previousVersion = previousPluginPackage.getVersion();
974                                    String version = pluginPackage.getVersion();
975    
976                                    if (_log.isInfoEnabled()) {
977                                            _log.info(
978                                                    "Updating " + name + " from version " +
979                                                            previousVersion + " to version " + version);
980                                    }
981    
982                                    if (pluginPackage.isPreviousVersionThan(
983                                                    previousPluginPackage)) {
984    
985                                            if (_log.isInfoEnabled()) {
986                                                    _log.info(
987                                                            "Not updating " + name + " because version " +
988                                                                    previousVersion + " is newer than version " +
989                                                                            version);
990                                            }
991    
992                                            return AutoDeployer.CODE_SKIP_NEWER_VERSION;
993                                    }
994    
995                                    overwrite = true;
996                            }
997    
998                            File mergeDirFile = new File(
999                                    srcFile.getParent() + "/merge/" + srcFile.getName());
1000    
1001                            if (srcFile.isDirectory()) {
1002                                    deployDirectory(
1003                                            srcFile, mergeDirFile, deployDirFile, displayName,
1004                                            overwrite, pluginPackage);
1005                            }
1006                            else {
1007                                    boolean deployed = deployFile(
1008                                            srcFile, mergeDirFile, deployDirFile, displayName,
1009                                            overwrite, pluginPackage);
1010    
1011                                    if (!deployed) {
1012                                            String context = preliminaryContext;
1013    
1014                                            if (pluginPackage != null) {
1015                                                    context = pluginPackage.getContext();
1016                                            }
1017    
1018                                            PluginPackageUtil.endPluginPackageInstallation(context);
1019                                    }
1020                                    else {
1021                                            postDeploy(destDir, deployDir);
1022                                    }
1023                            }
1024    
1025                            return AutoDeployer.CODE_DEFAULT;
1026                    }
1027                    catch (Exception e) {
1028                            if (pluginPackage != null) {
1029                                    PluginPackageUtil.endPluginPackageInstallation(
1030                                            pluginPackage.getContext());
1031                            }
1032    
1033                            throw e;
1034                    }
1035            }
1036    
1037            public boolean deployFile(
1038                            File srcFile, File mergeDir, File deployDir, String displayName,
1039                            boolean overwrite, PluginPackage pluginPackage)
1040                    throws Exception {
1041    
1042                    boolean undeployOnRedeploy = false;
1043    
1044                    try {
1045                            undeployOnRedeploy = PrefsPropsUtil.getBoolean(
1046                                    PropsKeys.HOT_UNDEPLOY_ON_REDEPLOY,
1047                                    PropsValues.HOT_UNDEPLOY_ON_REDEPLOY);
1048                    }
1049                    catch (Exception e) {
1050    
1051                            // This will only happen when running the deploy tool in Ant in the
1052                            // classical way where the WAR file is actually massaged and
1053                            // packaged.
1054    
1055                    }
1056    
1057                    if (undeployOnRedeploy) {
1058                            DeployUtil.undeploy(appServerType, deployDir);
1059                    }
1060    
1061                    if (!overwrite && UpToDateTask.isUpToDate(srcFile, deployDir)) {
1062                            if (_log.isInfoEnabled()) {
1063                                    _log.info(deployDir + " is already up to date");
1064                            }
1065    
1066                            return false;
1067                    }
1068    
1069                    File tempDir = new File(
1070                            SystemProperties.get(SystemProperties.TMP_DIR) + File.separator +
1071                                    Time.getTimestamp());
1072    
1073                    ExpandTask.expand(srcFile, tempDir);
1074    
1075                    deployDirectory(
1076                            tempDir, mergeDir, deployDir, displayName, overwrite,
1077                            pluginPackage);
1078    
1079                    DeleteTask.deleteDirectory(tempDir);
1080    
1081                    return true;
1082            }
1083    
1084            public String downloadJar(String jar) throws Exception {
1085                    String tmpDir = SystemProperties.get(SystemProperties.TMP_DIR);
1086    
1087                    File file = new File(
1088                            tmpDir + "/liferay/com/liferay/portal/deploy/dependencies/" + jar);
1089    
1090                    if (!file.exists()) {
1091                            synchronized (this) {
1092                                    String url = PropsUtil.get(
1093                                            PropsKeys.LIBRARY_DOWNLOAD_URL + jar);
1094    
1095                                    if (_log.isInfoEnabled()) {
1096                                            _log.info("Downloading library from " + url);
1097                                    }
1098    
1099                                    byte[] bytes = HttpUtil.URLtoByteArray(url);
1100    
1101                                    FileUtil.write(file, bytes);
1102                            }
1103                    }
1104    
1105                    return FileUtil.getAbsolutePath(file);
1106            }
1107    
1108            public String fixPortalDependencyJar(String portalJar) {
1109                    if (portalJar.equals("antlr.jar")) {
1110                            portalJar = "antlr2.jar";
1111                    }
1112    
1113                    return portalJar;
1114            }
1115    
1116            public DeploymentHandler getDeploymentHandler() {
1117                    String prefix = "auto.deploy." + ServerDetector.getServerId() + ".jee.";
1118    
1119                    String dmId = PropsUtil.get(prefix + "dm.id");
1120                    String dmUser = PropsUtil.get(prefix + "dm.user");
1121                    String dmPassword = PropsUtil.get(prefix + "dm.passwd");
1122                    String dfClassName = PropsUtil.get(prefix + "df.classname");
1123    
1124                    return new DeploymentHandler(dmId, dmUser, dmPassword, dfClassName);
1125            }
1126    
1127            public String getDisplayName(File srcFile) {
1128                    String displayName = srcFile.getName();
1129    
1130                    if (StringUtil.endsWith(displayName, ".war") ||
1131                            StringUtil.endsWith(displayName, ".xml")) {
1132    
1133                            displayName = displayName.substring(0, displayName.length() - 4);
1134                    }
1135    
1136                    if (appServerType.equals(ServerDetector.JBOSS_ID) &&
1137                            Validator.isNotNull(jbossPrefix) &&
1138                            displayName.startsWith(jbossPrefix)) {
1139    
1140                            displayName = displayName.substring(1);
1141                    }
1142    
1143                    return displayName;
1144            }
1145    
1146            public String getDynamicResourceServletContent() {
1147                    StringBundler sb = new StringBundler();
1148    
1149                    sb.append("<servlet>");
1150                    sb.append("<servlet-name>");
1151                    sb.append("Dynamic Resource Servlet");
1152                    sb.append("</servlet-name>");
1153                    sb.append("<servlet-class>");
1154                    sb.append(PortalClassLoaderServlet.class.getName());
1155                    sb.append("</servlet-class>");
1156                    sb.append("<init-param>");
1157                    sb.append("<param-name>");
1158                    sb.append("servlet-class");
1159                    sb.append("</param-name>");
1160                    sb.append("<param-value>");
1161                    sb.append(DynamicResourceServlet.class.getName());
1162                    sb.append("</param-value>");
1163                    sb.append("</init-param>");
1164                    sb.append("<load-on-startup>1</load-on-startup>");
1165                    sb.append("</servlet>");
1166    
1167                    for (String allowedPath :
1168                                    PropsValues.DYNAMIC_RESOURCE_SERVLET_ALLOWED_PATHS) {
1169    
1170                            sb.append("<servlet-mapping>");
1171                            sb.append("<servlet-name>");
1172                            sb.append("Dynamic Resource Servlet");
1173                            sb.append("</servlet-name>");
1174                            sb.append("<url-pattern>");
1175                            sb.append(allowedPath);
1176    
1177                            if (!allowedPath.endsWith(StringPool.SLASH)) {
1178                                    sb.append(StringPool.SLASH);
1179                            }
1180    
1181                            sb.append(StringPool.STAR);
1182                            sb.append("</url-pattern>");
1183                            sb.append("</servlet-mapping>");
1184                    }
1185    
1186                    return sb.toString();
1187            }
1188    
1189            public String getExtraContent(
1190                            double webXmlVersion, File srcFile, String displayName)
1191                    throws Exception {
1192    
1193                    StringBundler sb = new StringBundler();
1194    
1195                    sb.append("<display-name>");
1196                    sb.append(displayName);
1197                    sb.append("</display-name>");
1198    
1199                    if (webXmlVersion < 2.4) {
1200                            sb.append("<context-param>");
1201                            sb.append("<param-name>liferay-invoker-enabled</param-name>");
1202                            sb.append("<param-value>false</param-value>");
1203                            sb.append("</context-param>");
1204                    }
1205    
1206                    if (PropsValues.SESSION_VERIFY_SERIALIZABLE_ATTRIBUTE) {
1207                            sb.append("<listener>");
1208                            sb.append("<listener-class>");
1209                            sb.append(SerializableSessionAttributeListener.class.getName());
1210                            sb.append("</listener-class>");
1211                            sb.append("</listener>");
1212                    }
1213    
1214                    sb.append(getDynamicResourceServletContent());
1215    
1216                    File serverConfigWsdd = new File(
1217                            srcFile + "/WEB-INF/server-config.wsdd");
1218    
1219                    if (serverConfigWsdd.exists()) {
1220                            File webXml = new File(srcFile + "/WEB-INF/web.xml");
1221    
1222                            String content = FileUtil.read(webXml);
1223    
1224                            if (!content.contains("axis.servicesPath")) {
1225                                    String remotingContent = FileUtil.read(
1226                                            DeployUtil.getResourcePath("remoting-web.xml"));
1227    
1228                                    sb.append(remotingContent);
1229                            }
1230                    }
1231    
1232                    boolean hasTaglib = false;
1233    
1234                    if (Validator.isNotNull(auiTaglibDTD) ||
1235                            Validator.isNotNull(portletTaglibDTD) ||
1236                            Validator.isNotNull(portletExtTaglibDTD) ||
1237                            Validator.isNotNull(securityTaglibDTD) ||
1238                            Validator.isNotNull(themeTaglibDTD) ||
1239                            Validator.isNotNull(uiTaglibDTD) ||
1240                            Validator.isNotNull(utilTaglibDTD)) {
1241    
1242                            hasTaglib = true;
1243                    }
1244    
1245                    if (hasTaglib && (webXmlVersion > 2.3)) {
1246                            sb.append("<jsp-config>");
1247                    }
1248    
1249                    if (Validator.isNotNull(auiTaglibDTD)) {
1250                            sb.append("<taglib>");
1251                            sb.append("<taglib-uri>http://liferay.com/tld/aui</taglib-uri>");
1252                            sb.append("<taglib-location>");
1253                            sb.append("/WEB-INF/tld/aui.tld");
1254                            sb.append("</taglib-location>");
1255                            sb.append("</taglib>");
1256                    }
1257    
1258                    if (Validator.isNotNull(portletTaglibDTD)) {
1259                            sb.append("<taglib>");
1260                            sb.append(
1261                                    "<taglib-uri>http://java.sun.com/portlet_2_0</taglib-uri>");
1262                            sb.append("<taglib-location>");
1263                            sb.append("/WEB-INF/tld/liferay-portlet.tld");
1264                            sb.append("</taglib-location>");
1265                            sb.append("</taglib>");
1266                    }
1267    
1268                    if (Validator.isNotNull(portletExtTaglibDTD)) {
1269                            sb.append("<taglib>");
1270                            sb.append("<taglib-uri>");
1271                            sb.append("http://liferay.com/tld/portlet");
1272                            sb.append("</taglib-uri>");
1273                            sb.append("<taglib-location>");
1274                            sb.append("/WEB-INF/tld/liferay-portlet-ext.tld");
1275                            sb.append("</taglib-location>");
1276                            sb.append("</taglib>");
1277                    }
1278    
1279                    if (Validator.isNotNull(securityTaglibDTD)) {
1280                            sb.append("<taglib>");
1281                            sb.append("<taglib-uri>");
1282                            sb.append("http://liferay.com/tld/security");
1283                            sb.append("</taglib-uri>");
1284                            sb.append("<taglib-location>");
1285                            sb.append("/WEB-INF/tld/liferay-security.tld");
1286                            sb.append("</taglib-location>");
1287                            sb.append("</taglib>");
1288                    }
1289    
1290                    if (Validator.isNotNull(themeTaglibDTD)) {
1291                            sb.append("<taglib>");
1292                            sb.append("<taglib-uri>http://liferay.com/tld/theme</taglib-uri>");
1293                            sb.append("<taglib-location>");
1294                            sb.append("/WEB-INF/tld/liferay-theme.tld");
1295                            sb.append("</taglib-location>");
1296                            sb.append("</taglib>");
1297                    }
1298    
1299                    if (Validator.isNotNull(uiTaglibDTD)) {
1300                            sb.append("<taglib>");
1301                            sb.append("<taglib-uri>http://liferay.com/tld/ui</taglib-uri>");
1302                            sb.append("<taglib-location>");
1303                            sb.append("/WEB-INF/tld/liferay-ui.tld");
1304                            sb.append("</taglib-location>");
1305                            sb.append("</taglib>");
1306                    }
1307    
1308                    if (Validator.isNotNull(utilTaglibDTD)) {
1309                            sb.append("<taglib>");
1310                            sb.append("<taglib-uri>http://liferay.com/tld/util</taglib-uri>");
1311                            sb.append("<taglib-location>");
1312                            sb.append("/WEB-INF/tld/liferay-util.tld");
1313                            sb.append("</taglib-location>");
1314                            sb.append("</taglib>");
1315                    }
1316    
1317                    if (hasTaglib && (webXmlVersion > 2.3)) {
1318                            sb.append("</jsp-config>");
1319                    }
1320    
1321                    return sb.toString();
1322            }
1323    
1324            public String getExtraFiltersContent(double webXmlVersion, File srcFile)
1325                    throws Exception {
1326    
1327                    return getSessionFiltersContent();
1328            }
1329    
1330            public String getIgnoreFiltersContent(File srcFile) throws Exception {
1331                    boolean ignoreFiltersEnabled = true;
1332    
1333                    Properties properties = getPluginPackageProperties(srcFile);
1334    
1335                    if (properties != null) {
1336                            ignoreFiltersEnabled = GetterUtil.getBoolean(
1337                                    properties.getProperty("ignore-filters-enabled"), true);
1338                    }
1339    
1340                    if (ignoreFiltersEnabled) {
1341                            String ignoreFiltersContent = FileUtil.read(
1342                                    DeployUtil.getResourcePath("ignore-filters-web.xml"));
1343    
1344                            return ignoreFiltersContent;
1345                    }
1346                    else {
1347                            return StringPool.BLANK;
1348                    }
1349            }
1350    
1351            public String getInvokerFilterContent() {
1352                    StringBundler sb = new StringBundler(4);
1353    
1354                    sb.append(getInvokerFilterContent("ERROR"));
1355                    sb.append(getInvokerFilterContent("FORWARD"));
1356                    sb.append(getInvokerFilterContent("INCLUDE"));
1357                    sb.append(getInvokerFilterContent("REQUEST"));
1358    
1359                    return sb.toString();
1360            }
1361    
1362            public String getInvokerFilterContent(String dispatcher) {
1363                    StringBundler sb = new StringBundler(23);
1364    
1365                    sb.append("<filter>");
1366                    sb.append("<filter-name>Invoker Filter - ");
1367                    sb.append(dispatcher);
1368                    sb.append("</filter-name>");
1369                    sb.append("<filter-class>");
1370                    sb.append(InvokerFilter.class.getName());
1371                    sb.append("</filter-class>");
1372                    sb.append("<init-param>");
1373                    sb.append("<param-name>dispatcher</param-name>");
1374                    sb.append("<param-value>");
1375                    sb.append(dispatcher);
1376                    sb.append("</param-value>");
1377                    sb.append("</init-param>");
1378                    sb.append("</filter>");
1379    
1380                    sb.append("<filter-mapping>");
1381                    sb.append("<filter-name>Invoker Filter - ");
1382                    sb.append(dispatcher);
1383                    sb.append("</filter-name>");
1384                    sb.append("<url-pattern>/*</url-pattern>");
1385                    sb.append("<dispatcher>");
1386                    sb.append(dispatcher);
1387                    sb.append("</dispatcher>");
1388                    sb.append("</filter-mapping>");
1389    
1390                    return sb.toString();
1391            }
1392    
1393            public String getPluginPackageLicensesXml(List<License> licenses) {
1394                    if (licenses.isEmpty()) {
1395                            return StringPool.BLANK;
1396                    }
1397    
1398                    StringBundler sb = new StringBundler(5 * licenses.size() + 2);
1399    
1400                    for (int i = 0; i < licenses.size(); i++) {
1401                            License license = licenses.get(i);
1402    
1403                            if (i == 0) {
1404                                    sb.append("\r\n");
1405                            }
1406    
1407                            sb.append("\t\t<license osi-approved=\"");
1408                            sb.append(license.isOsiApproved());
1409                            sb.append("\">");
1410                            sb.append(license.getName());
1411                            sb.append("</license>\r\n");
1412    
1413                            if ((i + 1) == licenses.size()) {
1414                                    sb.append("\t");
1415                            }
1416                    }
1417    
1418                    return sb.toString();
1419            }
1420    
1421            public String getPluginPackageLiferayVersionsXml(
1422                    List<String> liferayVersions) {
1423    
1424                    if (liferayVersions.isEmpty()) {
1425                            return StringPool.BLANK;
1426                    }
1427    
1428                    StringBundler sb = new StringBundler(liferayVersions.size() * 3 + 2);
1429    
1430                    for (int i = 0; i < liferayVersions.size(); i++) {
1431                            String liferayVersion = liferayVersions.get(i);
1432    
1433                            if (i == 0) {
1434                                    sb.append("\r\n");
1435                            }
1436    
1437                            sb.append("\t\t<liferay-version>");
1438                            sb.append(liferayVersion);
1439                            sb.append("</liferay-version>\r\n");
1440    
1441                            if ((i + 1) == liferayVersions.size()) {
1442                                    sb.append("\t");
1443                            }
1444                    }
1445    
1446                    return sb.toString();
1447            }
1448    
1449            public Properties getPluginPackageProperties(File srcFile)
1450                    throws Exception {
1451    
1452                    File propertiesFile = new File(
1453                            srcFile + "/WEB-INF/liferay-plugin-package.properties");
1454    
1455                    if (!propertiesFile.exists()) {
1456                            return null;
1457                    }
1458    
1459                    String propertiesString = FileUtil.read(propertiesFile);
1460    
1461                    return PropertiesUtil.load(propertiesString);
1462            }
1463    
1464            public String getPluginPackageRequiredDeploymentContextsXml(
1465                    List<String> requiredDeploymentContexts) {
1466    
1467                    if (requiredDeploymentContexts.isEmpty()) {
1468                            return StringPool.BLANK;
1469                    }
1470    
1471                    StringBundler sb = new StringBundler(
1472                            requiredDeploymentContexts.size() * 3 + 2);
1473    
1474                    for (int i = 0; i < requiredDeploymentContexts.size(); i++) {
1475                            String requiredDeploymentContext = requiredDeploymentContexts.get(
1476                                    i);
1477    
1478                            if (i == 0) {
1479                                    sb.append("\r\n");
1480                            }
1481    
1482                            sb.append("\t\t<required-deployment-context>");
1483                            sb.append(requiredDeploymentContext);
1484                            sb.append("</required-deployment-context>\r\n");
1485    
1486                            if ((i + 1) == requiredDeploymentContexts.size()) {
1487                                    sb.append("\t");
1488                            }
1489                    }
1490    
1491                    return sb.toString();
1492            }
1493    
1494            public String getPluginPackageTagsXml(List<String> tags) {
1495                    if (tags.isEmpty()) {
1496                            return StringPool.BLANK;
1497                    }
1498    
1499                    StringBundler sb = new StringBundler(tags.size() * 3 + 2);
1500    
1501                    for (int i = 0; i < tags.size(); i++) {
1502                            String tag = tags.get(i);
1503    
1504                            if (i == 0) {
1505                                    sb.append("\r\n");
1506                            }
1507    
1508                            sb.append("\t\t<tag>");
1509                            sb.append(tag);
1510                            sb.append("</tag>\r\n");
1511    
1512                            if ((i + 1) == tags.size()) {
1513                                    sb.append("\t");
1514                            }
1515                    }
1516    
1517                    return sb.toString();
1518            }
1519    
1520            public Map<String, String> getPluginPackageXmlFilterMap(
1521                    PluginPackage pluginPackage) {
1522    
1523                    List<String> pluginTypes = pluginPackage.getTypes();
1524    
1525                    String pluginType = pluginTypes.get(0);
1526    
1527                    if (!pluginType.equals(getPluginType())) {
1528                            return null;
1529                    }
1530    
1531                    Map<String, String> filterMap = new HashMap<String, String>();
1532    
1533                    filterMap.put("author", wrapCDATA(pluginPackage.getAuthor()));
1534                    filterMap.put("change_log", wrapCDATA(pluginPackage.getChangeLog()));
1535                    filterMap.put(
1536                            "licenses",
1537                            getPluginPackageLicensesXml(pluginPackage.getLicenses()));
1538                    filterMap.put(
1539                            "liferay_versions",
1540                            getPluginPackageLiferayVersionsXml(
1541                                    pluginPackage.getLiferayVersions()));
1542                    filterMap.put(
1543                            "long_description", wrapCDATA(pluginPackage.getLongDescription()));
1544                    filterMap.put("module_artifact_id", pluginPackage.getArtifactId());
1545                    filterMap.put("module_group_id", pluginPackage.getGroupId());
1546                    filterMap.put("module_version", pluginPackage.getVersion());
1547                    filterMap.put("page_url", pluginPackage.getPageURL());
1548                    filterMap.put("plugin_name", wrapCDATA(pluginPackage.getName()));
1549                    filterMap.put("plugin_type", pluginType);
1550                    filterMap.put(
1551                            "plugin_type_name",
1552                            TextFormatter.format(pluginType, TextFormatter.J));
1553                    filterMap.put(
1554                            "recommended_deployment_context",
1555                            pluginPackage.getRecommendedDeploymentContext());
1556                    filterMap.put(
1557                            "required_deployment_contexts",
1558                            getPluginPackageRequiredDeploymentContextsXml(
1559                                    pluginPackage.getRequiredDeploymentContexts()));
1560                    filterMap.put(
1561                            "short_description",
1562                            wrapCDATA(pluginPackage.getShortDescription()));
1563                    filterMap.put("tags", getPluginPackageTagsXml(pluginPackage.getTags()));
1564    
1565                    return filterMap;
1566            }
1567    
1568            public String getPluginType() {
1569                    return null;
1570            }
1571    
1572            public String getServletContextIncludeFiltersContent(
1573                            double webXmlVersion, File srcFile)
1574                    throws Exception {
1575    
1576                    if (webXmlVersion < 2.4) {
1577                            return StringPool.BLANK;
1578                    }
1579    
1580                    Properties properties = getPluginPackageProperties(srcFile);
1581    
1582                    if (properties == null) {
1583                            return StringPool.BLANK;
1584                    }
1585    
1586                    if (!GetterUtil.getBoolean(
1587                                    properties.getProperty(
1588                                            "servlet-context-include-filters-enabled"),
1589                                    true)) {
1590    
1591                            return StringPool.BLANK;
1592                    }
1593    
1594                    return FileUtil.read(
1595                            DeployUtil.getResourcePath(
1596                                    "servlet-context-include-filters-web.xml"));
1597            }
1598    
1599            public String getSessionFiltersContent() throws Exception {
1600                    String sessionFiltersContent = FileUtil.read(
1601                            DeployUtil.getResourcePath("session-filters-web.xml"));
1602    
1603                    return sessionFiltersContent;
1604            }
1605    
1606            public String getSpeedFiltersContent(File srcFile) throws Exception {
1607                    boolean speedFiltersEnabled = true;
1608    
1609                    Properties properties = getPluginPackageProperties(srcFile);
1610    
1611                    if (properties != null) {
1612                            speedFiltersEnabled = GetterUtil.getBoolean(
1613                                    properties.getProperty("speed-filters-enabled"), true);
1614                    }
1615    
1616                    if (speedFiltersEnabled) {
1617                            String speedFiltersContent = FileUtil.read(
1618                                    DeployUtil.getResourcePath("speed-filters-web.xml"));
1619    
1620                            return speedFiltersContent;
1621                    }
1622                    else {
1623                            return StringPool.BLANK;
1624                    }
1625            }
1626    
1627            public boolean isJEEDeploymentEnabled() {
1628                    return GetterUtil.getBoolean(
1629                            PropsUtil.get(
1630                                    "auto.deploy." + ServerDetector.getServerId() +
1631                                            ".jee.deployment.enabled"));
1632            }
1633    
1634            public void mergeDirectory(File mergeDir, File targetDir) {
1635                    if ((mergeDir == null) || !mergeDir.exists()) {
1636                            return;
1637                    }
1638    
1639                    CopyTask.copyDirectory(mergeDir, targetDir, null, null, true, false);
1640            }
1641    
1642            public void postDeploy(String destDir, String deployDir) throws Exception {
1643                    if (appServerType.equals(ServerDetector.GLASSFISH_ID)) {
1644                            postDeployGlassfish(destDir, deployDir);
1645                    }
1646                    else if (appServerType.equals(ServerDetector.JBOSS_ID)) {
1647                            postDeployJBoss(destDir, deployDir);
1648                    }
1649                    else if (appServerType.equals(ServerDetector.WEBSPHERE_ID)) {
1650                            postDeployWebSphere(destDir, deployDir);
1651                    }
1652            }
1653    
1654            public void postDeployGlassfish(String destDir, String deployDir)
1655                    throws Exception {
1656    
1657                    FileUtil.delete(destDir + "/.autodeploystatus/" + deployDir);
1658            }
1659    
1660            public void postDeployJBoss(String destDir, String deployDir)
1661                    throws Exception {
1662    
1663                    FileUtil.write(
1664                            destDir + "/" + deployDir + ".dodeploy", StringPool.BLANK);
1665            }
1666    
1667            public void postDeployWebSphere(String destDir, String deployDir)
1668                    throws Exception {
1669    
1670                    if (Validator.isNull(
1671                                    PropsValues.AUTO_DEPLOY_WEBSPHERE_WSADMIN_APP_MANAGER_QUERY)) {
1672    
1673                            if (_log.isInfoEnabled()) {
1674                                    StringBundler sb = new StringBundler();
1675    
1676                                    sb.append("Do not install the plugin with wsadmin since the ");
1677                                    sb.append("property \"");
1678                                    sb.append(
1679                                            PropsKeys.AUTO_DEPLOY_WEBSPHERE_WSADMIN_APP_MANAGER_QUERY);
1680                                    sb.append("\"is not configured");
1681    
1682                                    _log.info(sb.toString());
1683                            }
1684    
1685                            return;
1686                    }
1687    
1688                    String wsadminContent = FileUtil.read(
1689                            DeployUtil.getResourcePath("wsadmin.py"));
1690    
1691                    String adminAppListOptions =
1692                            PropsValues.AUTO_DEPLOY_WEBSPHERE_WSADMIN_APP_MANAGER_LIST_OPTIONS;
1693    
1694                    if (Validator.isNotNull(adminAppListOptions)) {
1695                            adminAppListOptions =
1696                                    StringPool.APOSTROPHE + adminAppListOptions +
1697                                            StringPool.APOSTROPHE;
1698                    }
1699    
1700                    wsadminContent = StringUtil.replace(
1701                            wsadminContent,
1702                            new String[] {
1703                                    "${auto.deploy.websphere.wsadmin.app.manager.install.options}",
1704                                    "${auto.deploy.websphere.wsadmin.app.manager.list.options}",
1705                                    "${auto.deploy.websphere.wsadmin.app.manager.query}",
1706                                    "${auto.deploy.websphere.wsadmin.app.manager.update.options}"
1707                            },
1708                            new String[] {
1709                                    PropsValues.
1710                                            AUTO_DEPLOY_WEBSPHERE_WSADMIN_APP_MANAGER_INSTALL_OPTIONS,
1711                                    adminAppListOptions,
1712                                    PropsValues.AUTO_DEPLOY_WEBSPHERE_WSADMIN_APP_MANAGER_QUERY,
1713                                    PropsValues.
1714                                            AUTO_DEPLOY_WEBSPHERE_WSADMIN_APP_MANAGER_UPDATE_OPTIONS
1715                            });
1716    
1717                    String pluginServletContextName = deployDir.substring(
1718                            0, deployDir.length() - 4);
1719    
1720                    String pluginApplicationName = pluginServletContextName;
1721    
1722                    if (Validator.isNotNull(
1723                                    PropsValues.AUTO_DEPLOY_WEBSPHERE_WSADMIN_APP_NAME_SUFFIX)) {
1724    
1725                            pluginApplicationName +=
1726                                    PropsValues.AUTO_DEPLOY_WEBSPHERE_WSADMIN_APP_NAME_SUFFIX;
1727                    }
1728    
1729                    wsadminContent = StringUtil.replace(
1730                            wsadminContent,
1731                            new String[] {
1732                                    "${auto.deploy.dest.dir}",
1733                                    "${auto.deploy.websphere.wsadmin.app.name}",
1734                                    "${plugin.servlet.context.name}"
1735                            },
1736                            new String[] {
1737                                    destDir, pluginApplicationName, pluginServletContextName
1738                            });
1739    
1740                    String wsadminFileName = FileUtil.createTempFileName("py");
1741    
1742                    FileUtil.write(wsadminFileName, wsadminContent);
1743    
1744                    String webSphereHome = System.getenv("WAS_HOME");
1745    
1746                    List<String> commands = new ArrayList<String>();
1747    
1748                    if (OSDetector.isWindows()) {
1749                            commands.add(webSphereHome + "\\bin\\wsadmin.bat");
1750                    }
1751                    else {
1752                            commands.add(webSphereHome + "/bin/wsadmin.sh");
1753                    }
1754    
1755                    if (Validator.isNotNull(
1756                                    PropsValues.AUTO_DEPLOY_WEBSPHERE_WSADMIN_PROPERTIES_FILE)) {
1757    
1758                            commands.add("-p");
1759                            commands.add(
1760                                    PropsValues.AUTO_DEPLOY_WEBSPHERE_WSADMIN_PROPERTIES_FILE);
1761                    }
1762    
1763                    commands.add("-f");
1764                    commands.add(wsadminFileName);
1765    
1766                    if (_log.isInfoEnabled()) {
1767                            StringBundler sb = new StringBundler(commands.size() + 1);
1768    
1769                            sb.append("Installing plugin by executing");
1770    
1771                            for (String command : commands) {
1772                                    sb.append(StringPool.SPACE);
1773                                    sb.append(command);
1774                            }
1775    
1776                            _log.info(sb.toString());
1777                    }
1778    
1779                    ProcessBuilder processBuilder = new ProcessBuilder(commands);
1780    
1781                    processBuilder.redirectErrorStream(true);
1782    
1783                    Process process = processBuilder.start();
1784    
1785                    if (_log.isInfoEnabled()) {
1786                            InputStream inputStream = process.getInputStream();
1787    
1788                            String output = StringUtil.read(inputStream);
1789    
1790                            for (String line : StringUtil.split(output, CharPool.NEW_LINE)) {
1791                                    _log.info("Process output: " + line);
1792                            }
1793    
1794                            int exitValue = process.exitValue();
1795    
1796                            if (exitValue == 0) {
1797                                    _log.info(
1798                                            "Successfully executed command with an exit value of " +
1799                                                    exitValue);
1800                            }
1801                            else {
1802                                    _log.info(
1803                                            "Unsuccessfully executed command with an exit value of " +
1804                                                    exitValue);
1805                            }
1806                    }
1807    
1808                    FileUtil.delete(wsadminFileName);
1809            }
1810    
1811            @Override
1812            public Map<String, String> processPluginPackageProperties(
1813                            File srcFile, String displayName, PluginPackage pluginPackage)
1814                    throws Exception {
1815    
1816                    if (pluginPackage == null) {
1817                            return null;
1818                    }
1819    
1820                    Properties properties = getPluginPackageProperties(srcFile);
1821    
1822                    if ((properties == null) || properties.isEmpty()) {
1823                            return null;
1824                    }
1825    
1826                    Map<String, String> filterMap = getPluginPackageXmlFilterMap(
1827                            pluginPackage);
1828    
1829                    if (filterMap == null) {
1830                            return null;
1831                    }
1832    
1833                    copyDependencyXml(
1834                            "liferay-plugin-package.xml", srcFile + "/WEB-INF", filterMap,
1835                            true);
1836    
1837                    return filterMap;
1838            }
1839    
1840            /**
1841             * @see PluginPackageUtil#_readPluginPackageServletContext(
1842             *      javax.servlet.ServletContext)
1843             */
1844            @Override
1845            public PluginPackage readPluginPackage(File file) {
1846                    if (!file.exists()) {
1847                            return null;
1848                    }
1849    
1850                    InputStream is = null;
1851                    ZipFile zipFile = null;
1852    
1853                    try {
1854                            boolean parseProps = false;
1855    
1856                            if (file.isDirectory()) {
1857                                    String path = file.getPath();
1858    
1859                                    File pluginPackageXmlFile = new File(
1860                                            file.getParent() + "/merge/" + file.getName() +
1861                                                    "/WEB-INF/liferay-plugin-package.xml");
1862    
1863                                    if (pluginPackageXmlFile.exists()) {
1864                                            is = new FileInputStream(pluginPackageXmlFile);
1865                                    }
1866                                    else {
1867                                            pluginPackageXmlFile = new File(
1868                                                    path + "/WEB-INF/liferay-plugin-package.xml");
1869    
1870                                            if (pluginPackageXmlFile.exists()) {
1871                                                    is = new FileInputStream(pluginPackageXmlFile);
1872                                            }
1873                                    }
1874    
1875                                    File pluginPackagePropertiesFile = new File(
1876                                            file.getParent() + "/merge/" + file.getName() +
1877                                                    "/WEB-INF/liferay-plugin-package.properties");
1878    
1879                                    if ((is == null) && pluginPackagePropertiesFile.exists()) {
1880                                            is = new FileInputStream(pluginPackagePropertiesFile);
1881    
1882                                            parseProps = true;
1883                                    }
1884                                    else {
1885                                            pluginPackagePropertiesFile = new File(
1886                                                    path + "/WEB-INF/liferay-plugin-package.properties");
1887    
1888                                            if ((is == null) && pluginPackagePropertiesFile.exists()) {
1889                                                    is = new FileInputStream(pluginPackagePropertiesFile);
1890    
1891                                                    parseProps = true;
1892                                            }
1893                                    }
1894                            }
1895                            else {
1896                                    zipFile = new ZipFile(file);
1897    
1898                                    File pluginPackageXmlFile = new File(
1899                                            file.getParent() + "/merge/" + file.getName() +
1900                                                    "/WEB-INF/liferay-plugin-package.xml");
1901    
1902                                    if (pluginPackageXmlFile.exists()) {
1903                                            is = new FileInputStream(pluginPackageXmlFile);
1904                                    }
1905                                    else {
1906                                            ZipEntry zipEntry = zipFile.getEntry(
1907                                                    "WEB-INF/liferay-plugin-package.xml");
1908    
1909                                            if (zipEntry != null) {
1910                                                    is = zipFile.getInputStream(zipEntry);
1911                                            }
1912                                    }
1913    
1914                                    File pluginPackagePropertiesFile = new File(
1915                                            file.getParent() + "/merge/" + file.getName() +
1916                                                    "/WEB-INF/liferay-plugin-package.properties");
1917    
1918                                    if ((is == null) && pluginPackagePropertiesFile.exists()) {
1919                                            is = new FileInputStream(pluginPackagePropertiesFile);
1920    
1921                                            parseProps = true;
1922                                    }
1923                                    else {
1924                                            ZipEntry zipEntry = zipFile.getEntry(
1925                                                    "WEB-INF/liferay-plugin-package.properties");
1926    
1927                                            if ((is == null) && (zipEntry != null)) {
1928                                                    is = zipFile.getInputStream(zipEntry);
1929    
1930                                                    parseProps = true;
1931                                            }
1932                                    }
1933                            }
1934    
1935                            if (is == null) {
1936                                    if (_log.isInfoEnabled()) {
1937                                            _log.info(
1938                                                    file.getPath() + " does not have a " +
1939                                                            "WEB-INF/liferay-plugin-package.xml or " +
1940                                                                    "WEB-INF/liferay-plugin-package.properties");
1941                                    }
1942    
1943                                    return null;
1944                            }
1945    
1946                            if (parseProps) {
1947                                    String displayName = getDisplayName(file);
1948    
1949                                    String propertiesString = StringUtil.read(is);
1950    
1951                                    Properties properties = PropertiesUtil.load(propertiesString);
1952    
1953                                    return PluginPackageUtil.readPluginPackageProperties(
1954                                            displayName, properties);
1955                            }
1956                            else {
1957                                    String xml = StringUtil.read(is);
1958    
1959                                    xml = XMLFormatter.fixProlog(xml);
1960    
1961                                    return PluginPackageUtil.readPluginPackageXml(xml);
1962                            }
1963                    }
1964                    catch (Exception e) {
1965                            _log.error(file.getPath() + ": " + e.toString());
1966                    }
1967                    finally {
1968                            if (is != null) {
1969                                    try {
1970                                            is.close();
1971                                    }
1972                                    catch (IOException ioe) {
1973                                    }
1974                            }
1975    
1976                            if (zipFile != null) {
1977                                    try {
1978                                            zipFile.close();
1979                                    }
1980                                    catch (IOException ioe) {
1981                                    }
1982                            }
1983                    }
1984    
1985                    return null;
1986            }
1987    
1988            public void rewriteFiles(File srcDir) throws Exception {
1989                    String[] fileNames = FileUtil.listFiles(srcDir + "/WEB-INF/");
1990    
1991                    for (String fileName : fileNames) {
1992                            String shortFileName = GetterUtil.getString(
1993                                    FileUtil.getShortFileName(fileName));
1994    
1995                            // LEP-6415
1996    
1997                            if (StringUtil.equalsIgnoreCase(shortFileName, "mule-config.xml")) {
1998                                    continue;
1999                            }
2000    
2001                            String ext = GetterUtil.getString(FileUtil.getExtension(fileName));
2002    
2003                            if (!StringUtil.equalsIgnoreCase(ext, "xml")) {
2004                                    continue;
2005                            }
2006    
2007                            // Make sure to rewrite any XML files to include external entities
2008                            // into same file. See LEP-3142.
2009    
2010                            File file = new File(srcDir + "/WEB-INF/" + fileName);
2011    
2012                            try {
2013                                    Document doc = SAXReaderUtil.read(file);
2014    
2015                                    String content = doc.formattedString(StringPool.TAB, true);
2016    
2017                                    FileUtil.write(file, content);
2018                            }
2019                            catch (Exception e) {
2020                                    if (_log.isWarnEnabled()) {
2021                                            _log.warn(
2022                                                    "Unable to format " + file + ": " + e.getMessage());
2023                                    }
2024                            }
2025                    }
2026            }
2027    
2028            public String secureWebXml(
2029                            String content, boolean hasCustomServletListener,
2030                            boolean securityManagerEnabled)
2031                    throws Exception {
2032    
2033                    if (!hasCustomServletListener && !securityManagerEnabled) {
2034                            return content;
2035                    }
2036    
2037                    Document document = SAXReaderUtil.read(content);
2038    
2039                    Element rootElement = document.getRootElement();
2040    
2041                    List<String> listenerClasses = new ArrayList<String>();
2042    
2043                    List<Element> listenerElements = rootElement.elements("listener");
2044    
2045                    for (Element listenerElement : listenerElements) {
2046                            String listenerClass = GetterUtil.getString(
2047                                    listenerElement.elementText("listener-class"));
2048    
2049                            if (listenerClass.equals(PluginContextListener.class.getName()) ||
2050                                    listenerClass.equals(
2051                                            SecurePluginContextListener.class.getName())) {
2052    
2053                                    continue;
2054                            }
2055    
2056                            listenerClasses.add(listenerClass);
2057    
2058                            listenerElement.detach();
2059                    }
2060    
2061                    Element contextParamElement = rootElement.addElement("context-param");
2062    
2063                    DocUtil.add(contextParamElement, "param-name", "portalListenerClasses");
2064                    DocUtil.add(
2065                            contextParamElement, "param-value",
2066                            StringUtil.merge(listenerClasses));
2067    
2068                    if (!securityManagerEnabled) {
2069                            return document.compactString();
2070                    }
2071    
2072                    List<Element> servletElements = rootElement.elements("servlet");
2073    
2074                    for (Element servletElement : servletElements) {
2075                            Element servletClassElement = servletElement.element(
2076                                    "servlet-class");
2077    
2078                            String servletClass = GetterUtil.getString(
2079                                    servletClassElement.getText());
2080    
2081                            if (servletClass.equals(
2082                                            PortalClassLoaderServlet.class.getName()) ||
2083                                    servletClass.equals(PortalDelegateServlet.class.getName()) ||
2084                                    servletClass.equals(PortletServlet.class.getName())) {
2085    
2086                                    continue;
2087                            }
2088    
2089                            servletClassElement.setText(SecureServlet.class.getName());
2090    
2091                            Element initParamElement = servletElement.addElement("init-param");
2092    
2093                            DocUtil.add(initParamElement, "param-name", "servlet-class");
2094                            DocUtil.add(initParamElement, "param-value", servletClass);
2095                    }
2096    
2097                    return document.compactString();
2098            }
2099    
2100            @Override
2101            public void setAppServerType(String appServerType) {
2102                    this.appServerType = appServerType;
2103            }
2104    
2105            @Override
2106            public void setAuiTaglibDTD(String auiTaglibDTD) {
2107                    this.auiTaglibDTD = auiTaglibDTD;
2108            }
2109    
2110            @Override
2111            public void setBaseDir(String baseDir) {
2112                    this.baseDir = baseDir;
2113            }
2114    
2115            @Override
2116            public void setDestDir(String destDir) {
2117                    this.destDir = destDir;
2118            }
2119    
2120            @Override
2121            public void setFilePattern(String filePattern) {
2122                    this.filePattern = filePattern;
2123            }
2124    
2125            @Override
2126            public void setJars(List<String> jars) {
2127                    this.jars = jars;
2128            }
2129    
2130            @Override
2131            public void setJbossPrefix(String jbossPrefix) {
2132                    this.jbossPrefix = jbossPrefix;
2133            }
2134    
2135            @Override
2136            public void setPortletExtTaglibDTD(String portletExtTaglibDTD) {
2137                    this.portletExtTaglibDTD = portletExtTaglibDTD;
2138            }
2139    
2140            @Override
2141            public void setPortletTaglibDTD(String portletTaglibDTD) {
2142                    this.portletTaglibDTD = portletTaglibDTD;
2143            }
2144    
2145            @Override
2146            public void setSecurityTaglibDTD(String securityTaglibDTD) {
2147                    this.securityTaglibDTD = securityTaglibDTD;
2148            }
2149    
2150            @Override
2151            public void setThemeTaglibDTD(String themeTaglibDTD) {
2152                    this.themeTaglibDTD = themeTaglibDTD;
2153            }
2154    
2155            @Override
2156            public void setTomcatLibDir(String tomcatLibDir) {
2157                    this.tomcatLibDir = tomcatLibDir;
2158            }
2159    
2160            @Override
2161            public void setUiTaglibDTD(String uiTaglibDTD) {
2162                    this.uiTaglibDTD = uiTaglibDTD;
2163            }
2164    
2165            @Override
2166            public void setUnpackWar(boolean unpackWar) {
2167                    this.unpackWar = unpackWar;
2168            }
2169    
2170            @Override
2171            public void setUtilTaglibDTD(String utilTaglibDTD) {
2172                    this.utilTaglibDTD = utilTaglibDTD;
2173            }
2174    
2175            @Override
2176            public void setWars(List<String> wars) {
2177                    this.wars = wars;
2178            }
2179    
2180            public void updateDeployDirectory(File srcFile) throws Exception {
2181            }
2182    
2183            public void updateGeronimoWebXml(
2184                            File srcFile, String displayName, PluginPackage pluginPackage)
2185                    throws Exception {
2186    
2187                    if (!appServerType.equals(ServerDetector.GERONIMO_ID)) {
2188                            return;
2189                    }
2190    
2191                    File geronimoWebXml = new File(srcFile + "/WEB-INF/geronimo-web.xml");
2192    
2193                    Document document = SAXReaderUtil.read(geronimoWebXml);
2194    
2195                    Element rootElement = document.getRootElement();
2196    
2197                    Element environmentElement = rootElement.element("environment");
2198    
2199                    Element moduleIdElement = environmentElement.element("moduleId");
2200    
2201                    Element artifactIdElement = moduleIdElement.element("artifactId");
2202    
2203                    artifactIdElement.setText(displayName);
2204    
2205                    Element versionElement = moduleIdElement.element("version");
2206    
2207                    versionElement.setText(pluginPackage.getVersion());
2208    
2209                    String content = document.formattedString();
2210    
2211                    FileUtil.write(geronimoWebXml, content);
2212    
2213                    if (_log.isInfoEnabled()) {
2214                            _log.info("Modifying Geronimo " + geronimoWebXml);
2215                    }
2216            }
2217    
2218            public String updateLiferayWebXml(
2219                            double webXmlVersion, File srcFile, String webXmlContent)
2220                    throws Exception {
2221    
2222                    boolean liferayWebXmlEnabled = true;
2223    
2224                    Properties properties = getPluginPackageProperties(srcFile);
2225    
2226                    if (properties != null) {
2227                            liferayWebXmlEnabled = GetterUtil.getBoolean(
2228                                    properties.getProperty("liferay-web-xml-enabled"), true);
2229                    }
2230    
2231                    webXmlContent = WebXMLBuilder.organizeWebXML(webXmlContent);
2232    
2233                    int x = webXmlContent.indexOf("<filter>");
2234                    int y = webXmlContent.lastIndexOf("</filter-mapping>");
2235    
2236                    String webXmlFiltersContent = StringPool.BLANK;
2237    
2238                    if ((x == -1) || (y == -1)) {
2239                            x = webXmlContent.lastIndexOf("</display-name>") + 15;
2240                            y = x;
2241                    }
2242                    else {
2243                            if (liferayWebXmlEnabled && (webXmlVersion > 2.3)) {
2244                                    webXmlFiltersContent = webXmlContent.substring(x, y + 17);
2245    
2246                                    y = y + 17;
2247                            }
2248                            else {
2249                                    x = y + 17;
2250                                    y = y + 17;
2251                            }
2252                    }
2253    
2254                    if (webXmlVersion < 2.4) {
2255                            webXmlContent =
2256                                    webXmlContent.substring(0, x) +
2257                                            getExtraFiltersContent(webXmlVersion, srcFile) +
2258                                                    webXmlContent.substring(y);
2259    
2260                            return webXmlContent;
2261                    }
2262    
2263                    String filtersContent =
2264                            webXmlFiltersContent +
2265                                    getExtraFiltersContent(webXmlVersion, srcFile);
2266    
2267                    String liferayWebXmlContent = FileUtil.read(
2268                            DeployUtil.getResourcePath("web.xml"));
2269    
2270                    int z = liferayWebXmlContent.indexOf("</web-app>");
2271    
2272                    liferayWebXmlContent =
2273                            liferayWebXmlContent.substring(0, z) + filtersContent +
2274                                    liferayWebXmlContent.substring(z);
2275    
2276                    liferayWebXmlContent = WebXMLBuilder.organizeWebXML(
2277                            liferayWebXmlContent);
2278    
2279                    FileUtil.write(
2280                            srcFile + "/WEB-INF/liferay-web.xml", liferayWebXmlContent);
2281    
2282                    webXmlContent =
2283                            webXmlContent.substring(0, x) + getInvokerFilterContent() +
2284                                    webXmlContent.substring(y);
2285    
2286                    return webXmlContent;
2287            }
2288    
2289            @Override
2290            public void updateWebXml(
2291                            File webXml, File srcFile, String displayName,
2292                            PluginPackage pluginPackage)
2293                    throws Exception {
2294    
2295                    // Check version
2296    
2297                    String content = FileUtil.read(webXml);
2298    
2299                    content = WebXMLBuilder.organizeWebXML(content);
2300    
2301                    int x = content.indexOf("<display-name>");
2302    
2303                    if (x != -1) {
2304                            int y = content.indexOf("</display-name>", x);
2305    
2306                            y = content.indexOf(">", y) + 1;
2307    
2308                            content = content.substring(0, x) + content.substring(y);
2309                    }
2310    
2311                    Document document = SAXReaderUtil.read(content);
2312    
2313                    Element rootElement = document.getRootElement();
2314    
2315                    double webXmlVersion = GetterUtil.getDouble(
2316                            rootElement.attributeValue("version"), 2.3);
2317    
2318                    if (!PropsValues.TCK_URL && (webXmlVersion <= 2.3)) {
2319                            throw new AutoDeployException(
2320                                    webXml.getName() +
2321                                            " must be updated to the Servlet 2.4 specification");
2322                    }
2323    
2324                    // Plugin context listener
2325    
2326                    StringBundler sb = new StringBundler(5);
2327    
2328                    sb.append("<listener>");
2329                    sb.append("<listener-class>");
2330    
2331                    boolean hasCustomServletListener = false;
2332    
2333                    List<Element> listenerElements = rootElement.elements("listener");
2334    
2335                    for (Element listenerElement : listenerElements) {
2336                            String listenerClass = GetterUtil.getString(
2337                                    listenerElement.elementText("listener-class"));
2338    
2339                            if (listenerClass.equals(PluginContextListener.class.getName()) ||
2340                                    listenerClass.equals(
2341                                            SerializableSessionAttributeListener.class.getName()) ||
2342                                    listenerClass.equals(
2343                                            SecurePluginContextListener.class.getName())) {
2344    
2345                                    continue;
2346                            }
2347    
2348                            hasCustomServletListener = true;
2349    
2350                            break;
2351                    }
2352    
2353                    boolean securityManagerEnabled = false;
2354    
2355                    Properties properties = getPluginPackageProperties(srcFile);
2356    
2357                    if (properties != null) {
2358                            securityManagerEnabled = GetterUtil.getBoolean(
2359                                    properties.getProperty("security-manager-enabled"));
2360                    }
2361    
2362                    if (hasCustomServletListener || securityManagerEnabled) {
2363                            sb.append(SecurePluginContextListener.class.getName());
2364                    }
2365                    else {
2366                            sb.append(PluginContextListener.class.getName());
2367                    }
2368    
2369                    sb.append("</listener-class>");
2370                    sb.append("</listener>");
2371    
2372                    String pluginContextListenerContent = sb.toString();
2373    
2374                    // Merge content
2375    
2376                    String extraContent = getExtraContent(
2377                            webXmlVersion, srcFile, displayName);
2378    
2379                    int pos = content.indexOf("<listener>");
2380    
2381                    if (pos == -1) {
2382                            pos = content.indexOf("</web-app>");
2383                    }
2384    
2385                    String newContent =
2386                            content.substring(0, pos) + pluginContextListenerContent +
2387                                    extraContent + content.substring(pos);
2388    
2389                    // Update liferay-web.xml
2390    
2391                    newContent = updateLiferayWebXml(webXmlVersion, srcFile, newContent);
2392    
2393                    // Update web.xml
2394    
2395                    newContent = secureWebXml(
2396                            newContent, hasCustomServletListener, securityManagerEnabled);
2397    
2398                    newContent = WebXMLBuilder.organizeWebXML(newContent);
2399    
2400                    FileUtil.write(webXml, newContent, true);
2401    
2402                    if (_log.isInfoEnabled()) {
2403                            _log.info("Modifying Servlet " + webXmlVersion + " " + webXml);
2404                    }
2405            }
2406    
2407            @Override
2408            public String wrapCDATA(String string) {
2409                    return StringPool.CDATA_OPEN + string + StringPool.CDATA_CLOSE;
2410            }
2411    
2412            protected String appServerType;
2413            protected String auiTaglibDTD;
2414            protected String baseDir;
2415            protected String destDir;
2416            protected String filePattern;
2417            protected List<String> jars;
2418            protected String jbossPrefix;
2419            protected String portletExtTaglibDTD;
2420            protected String portletTaglibDTD;
2421            protected String securityTaglibDTD;
2422            protected String themeTaglibDTD;
2423            protected String tomcatLibDir;
2424            protected String uiTaglibDTD;
2425            protected boolean unpackWar;
2426            protected String utilTaglibDTD;
2427            protected List<String> wars;
2428    
2429            private static final String _PORTAL_CLASS_LOADER =
2430                    "com.liferay.support.tomcat.loader.PortalClassLoader";
2431    
2432            private static Log _log = LogFactoryUtil.getLog(BaseDeployer.class);
2433    
2434    }