View Javadoc
1   /*
2    * Copyright (C) 2003-2008 eXo Platform SAS.
3    *
4    * This program is free software; you can redistribute it and/or
5    * modify it under the terms of the GNU Affero General Public License
6    * as published by the Free Software Foundation; either version 3
7    * of the License, or (at your option) any later version.
8    *
9    * This program is distributed in the hope that it will be useful,
10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12   * GNU General Public License for more details.
13   *
14   * You should have received a copy of the GNU General Public License
15   * along with this program; if not, see<http://www.gnu.org/licenses/>.
16   */
17  package org.exoplatform.services.wcm.webcontent;
18  
19  import java.io.InputStream;
20  import java.util.Date;
21  import java.util.Iterator;
22  import java.util.Map;
23  
24  import javax.jcr.ImportUUIDBehavior;
25  import javax.jcr.Node;
26  import javax.jcr.NodeIterator;
27  import javax.jcr.Session;
28  import javax.jcr.query.Query;
29  import javax.jcr.query.QueryManager;
30  
31  import org.apache.commons.lang.StringUtils;
32  import org.exoplatform.commons.utils.IOUtil;
33  import org.exoplatform.container.configuration.ConfigurationManager;
34  import org.exoplatform.container.xml.InitParams;
35  import org.exoplatform.container.xml.ObjectParameter;
36  import org.exoplatform.services.cache.CacheService;
37  import org.exoplatform.services.cache.ExoCache;
38  import org.exoplatform.services.deployment.DeploymentDescriptor;
39  import org.exoplatform.services.deployment.Utils;
40  import org.exoplatform.services.jcr.RepositoryService;
41  import org.exoplatform.services.jcr.core.ManageableRepository;
42  import org.exoplatform.services.jcr.ext.common.SessionProvider;
43  import org.exoplatform.services.log.ExoLogger;
44  import org.exoplatform.services.log.Log;
45  import org.exoplatform.services.wcm.portal.LivePortalManagerService;
46  import org.exoplatform.services.wcm.portal.artifacts.CreatePortalPlugin;
47  import org.exoplatform.services.wcm.utils.WCMCoreUtils;
48  
49  /**
50   * Created by The eXo Platform SAS
51   * Author : Hoa Pham
52   * hoa.phamvu@exoplatform.com
53   * Oct 22, 2008
54   */
55  public class InitialWebContentPlugin extends CreatePortalPlugin {
56  
57    private static final Log LOG = ExoLogger.getLogger(InitialWebContentPlugin.class.getName());
58    private InitParams initParams;
59    private ConfigurationManager configurationManager;
60    private RepositoryService repositoryService;
61    private ExoCache<String, String> artifactsCache;
62    private LivePortalManagerService livePortalManagerService;
63  
64    private final static String CACHE_NAME = "ecms.InitialWebContentPlugin";
65    /**
66     * Instantiates a new initial web content plugin.
67     *
68     * @param initParams the init params
69     * @param configurationManager the configuration manager
70     * @param repositoryService the repository service
71     */
72    public InitialWebContentPlugin(InitParams initParams,
73                                   ConfigurationManager configurationManager,
74                                   RepositoryService repositoryService,
75                                   CacheService cacheService,
76                                   LivePortalManagerService livePortalManagerService) throws Exception {
77      super(initParams, configurationManager, repositoryService);
78      this.initParams = initParams;
79      this.configurationManager = configurationManager;
80      this.repositoryService = repositoryService;
81      this.artifactsCache = cacheService.getCacheInstance(CACHE_NAME);
82      this.livePortalManagerService = livePortalManagerService;
83    }
84  
85    /*
86     * (non-Javadoc)
87     * @see
88     * org.exoplatform.services.wcm.portal.artifacts.BasePortalArtifactsPlugin
89     * #deployToPortal(java.lang.String,
90     * org.exoplatform.services.jcr.ext.common.SessionProvider)
91     */
92    public void deployToPortal(SessionProvider sessionProvider, String portalName) throws Exception {
93      Iterator iterator = initParams.getObjectParamIterator();
94      DeploymentDescriptor deploymentDescriptor = null;
95      try {
96        while (iterator.hasNext()) {
97          ObjectParameter objectParameter = (ObjectParameter) iterator.next();
98          deploymentDescriptor = (DeploymentDescriptor) objectParameter.getObject();
99          Boolean cleanupPublication = deploymentDescriptor.getCleanupPublication();
100         String sourcePath = deploymentDescriptor.getSourcePath();
101         String versionHistoryPath = deploymentDescriptor.getVersionHistoryPath();
102         // sourcePath should start with: war:/, jar:/, classpath:/, file:/
103         String xmlData = (String) artifactsCache.get(sourcePath);
104         if (xmlData == null) {
105           InputStream stream = configurationManager.getInputStream(sourcePath);
106           xmlData = IOUtil.getStreamContentAsString(stream);
107           artifactsCache.put(sourcePath, xmlData);
108         }
109         ManageableRepository repository = repositoryService.getCurrentRepository();
110         Session session = sessionProvider.getSession(deploymentDescriptor.getTarget()
111                                                                          .getWorkspace(),
112                                                      repository);
113         String targetPath = deploymentDescriptor.getTarget().getNodePath();
114         String realTargetFolder = StringUtils.replace(targetPath, "{portalName}", portalName);
115         InputStream inputStream = configurationManager.getInputStream(sourcePath);
116         session.importXML(realTargetFolder, inputStream, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);
117         if (cleanupPublication) {
118             /**
119              * This code allows to cleanup the publication lifecycle in the target
120              * folder after importing the data. By using this, the publication
121              * live revision property will be re-initialized and the content will
122              * be set as published directly. Thus, the content will be visible in
123              * front side.
124              */
125             QueryManager manager = session.getWorkspace().getQueryManager();
126             String statement = "select * from nt:base where jcr:path LIKE '"+ realTargetFolder +"/%'";
127             Query query = manager.createQuery(statement.toString(), Query.SQL);
128             NodeIterator iter = query.execute().getNodes();
129             while (iter.hasNext()) {
130               Node node = iter.nextNode();
131               if (node.hasProperty("publication:liveRevision")
132                   && node.hasProperty("publication:currentState")) {
133                 if (LOG.isInfoEnabled()) {
134                   LOG.info("\"" + node.getName() + "\" publication lifecycle has been cleaned up");
135                 }
136                 node.setProperty("publication:liveRevision", (javax.jcr.Value)null);
137                 node.setProperty("publication:currentState", "published");
138               }
139 
140             }
141 
142           }
143 
144           if (versionHistoryPath != null && versionHistoryPath.length() > 0) {
145             // process import version history
146             Node currentNode = (Node) session.getItem(deploymentDescriptor.getTarget().getNodePath());
147 
148             Map<String, String> mapHistoryValue =
149               Utils.getMapImportHistory(configurationManager.getInputStream(versionHistoryPath));
150             Utils.processImportHistory(currentNode,
151                                        configurationManager.getInputStream(versionHistoryPath),
152                                        mapHistoryValue);
153           }
154         session.save();
155       }
156       Node portalNode = livePortalManagerService.getLivePortal(sessionProvider, portalName);
157       configure(portalNode, portalName);
158       portalNode.save();
159     } catch (Exception ex) {
160       if (LOG.isErrorEnabled()) {
161         LOG.error("deploy the portal "
162                     + portalName
163                     + " from "
164                     + deploymentDescriptor.getSourcePath()
165                     + " into "
166                     + StringUtils.replace(deploymentDescriptor.getTarget().getNodePath(),
167                                           "{portalName}",
168                                           portalName) + " is FAILURE at " + new Date().toString()
169                     + "\n",
170                 ex);
171       }
172       throw ex;
173     }
174   }
175 
176   private void configure(Node targetNode, String siteName) throws Exception{
177     String statement = "select * from nt:resource where jcr:path like '" + targetNode.getPath()
178         + "/%' order by jcr:dateModified ASC";
179     QueryManager queryManager = targetNode.getSession().getWorkspace().getQueryManager();
180     Query query = queryManager.createQuery(statement,Query.SQL);
181     NodeIterator iterator = query.execute().getNodes();
182     for(;iterator.hasNext();) {
183       Node ntResource = iterator.nextNode();
184       String mimeType = ntResource.getProperty("jcr:mimeType").getString();
185       if(!mimeType.startsWith("text") && !mimeType.startsWith("application/x-javascript")) continue;
186       String jcrData = ntResource.getProperty("jcr:data").getString();
187       
188       jcrData = replace(jcrData, "{portalName}", WCMCoreUtils.getPortalName());
189       jcrData = replace(jcrData, "{restContextName}", WCMCoreUtils.getRestContextName());
190       jcrData = replace(jcrData, "{repositoryName}", WCMCoreUtils.getRepository().getConfiguration().getName());
191       jcrData = replace(jcrData, "{workspaceName}", targetNode.getSession().getWorkspace().getName());
192       jcrData = replace(jcrData, "{siteName}", siteName);
193       
194       ntResource.setProperty("jcr:data", jcrData);
195     }
196   }
197   
198   private String replace(String source, String pattern, String replacingValue) {
199     return source.contains(pattern) ? source.replace(pattern, replacingValue) : source;
200   }
201 }