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