View Javadoc
1   /*
2    * Copyright (C) 2003-2007 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.cms.impl;
18  
19  import org.apache.commons.lang.StringUtils;
20  import org.exoplatform.container.configuration.ConfigurationManager;
21  import org.exoplatform.services.cache.CacheService;
22  import org.exoplatform.services.cache.ExoCache;
23  import org.exoplatform.services.cms.actions.ActionServiceContainer;
24  import org.exoplatform.services.cms.jcrext.activity.ActivityCommonService;
25  import org.exoplatform.services.cms.scripts.CmsScript;
26  import org.exoplatform.services.jcr.RepositoryService;
27  import org.exoplatform.services.jcr.core.ManageableRepository;
28  import org.exoplatform.services.jcr.ext.common.SessionProvider;
29  import org.exoplatform.services.jcr.ext.hierarchy.NodeHierarchyCreator;
30  import org.exoplatform.services.wcm.core.NodetypeConstant;
31  import org.exoplatform.services.wcm.utils.WCMCoreUtils;
32  import org.picocontainer.Startable;
33  
34  import javax.jcr.Node;
35  import javax.jcr.NodeIterator;
36  import javax.jcr.PathNotFoundException;
37  import javax.jcr.Session;
38  import javax.jcr.nodetype.NodeType;
39  import javax.jcr.nodetype.PropertyDefinition;
40  import java.io.ByteArrayInputStream;
41  import java.io.InputStream;
42  import java.util.Collection;
43  import java.util.GregorianCalendar;
44  import java.util.List;
45  
46  public abstract class BaseResourceLoaderService implements Startable{
47  
48    protected NodeHierarchyCreator nodeHierarchyCreator_;
49  
50    protected RepositoryService    repositoryService_;
51  
52    protected ConfigurationManager cservice_;
53  
54    protected ExoCache<String, CmsScript>  resourceCache_;
55    
56    private ActivityCommonService activityService = null;
57  
58    private static final String EDITED_CONFIGURED_SCRIPTS = "EditedConfiguredScripts";
59  
60    private static final String CACHE_NAME = "ecms.BaseResourceCache";
61  
62    /**
63     * DMS configuration which used to store informations
64     */
65    private DMSConfiguration       dmsConfiguration_;
66  
67    /**
68     * Constructor method
69     * Init cservice, nodeHierarchyCreator, repositoryService, cacheService, dmsConfiguration
70     * @param cservice                ConfigurationManager
71     * @param nodeHierarchyCreator    NodeHierarchyCreator
72     * @param repositoryService       RepositoryService
73     * @param cacheService            CacheService
74     * @param dmsConfiguration        DMSConfiguration
75     * @throws Exception
76     */
77    public BaseResourceLoaderService(ConfigurationManager cservice,
78        NodeHierarchyCreator nodeHierarchyCreator, RepositoryService repositoryService,
79        CacheService cacheService, DMSConfiguration dmsConfiguration) throws Exception {
80      nodeHierarchyCreator_ = nodeHierarchyCreator;
81      repositoryService_ = repositoryService;
82      cservice_ = cservice;
83      resourceCache_ = cacheService.getCacheInstance(CACHE_NAME);
84      dmsConfiguration_ = dmsConfiguration;
85    }
86  
87    /**
88     * get BasePath
89     * @return
90     */
91    abstract protected String getBasePath();
92  
93    /**
94     * remove From Cache
95     * @param resourceName    String
96     *                        The name of resource
97     */
98    abstract protected void removeFromCache(String resourceName);
99  
100   /**
101    * {@inheritDoc}
102    */
103   public void start(){};
104 
105   /**
106    * {@inheritDoc}
107    */
108   public void stop(){};
109 
110   /**
111    * init
112    * @param session           Session
113    * @param resourceConfig    ResourceConfig
114    * @param location          String
115    *                          The code of location
116    * @see                     Session
117    * @see                     ResourceConfig
118    * @throws Exception
119    */
120   protected void init(Session session, ResourceConfig resourceConfig, String location) throws Exception {
121     addScripts(session, resourceConfig.getRessources(),location) ;
122   }
123 
124   /**
125    * add Script with following param
126    * @param session       Session
127    * @param resources     List
128    * @param location      String
129    * @see                 ResourceConfig
130    * @throws Exception
131    */
132   protected void addScripts(Session session, List<ResourceConfig.Resource> resources, String location) throws Exception{
133     String resourcesPath = getBasePath();
134     if (resources.size() == 0) return;
135     try {
136       String firstResourceName = resources.get(0).getName();
137       session.getItem(resourcesPath + "/" + firstResourceName);
138       return;
139     } catch (PathNotFoundException e) {
140       Node resourcesHome = (Node) session.getItem(resourcesPath);
141       String warPath = location + resourcesPath.substring(resourcesPath.lastIndexOf("/")) ;
142       for (ResourceConfig.Resource resource : resources) {
143         String name = resource.getName();
144         if(Utils.getAllEditedConfiguredData(this.getClass().getSimpleName(), EDITED_CONFIGURED_SCRIPTS, true).contains(name)) {
145           continue;
146         }
147         String description = resource.getDescription();
148         String path = warPath + "/" + name;
149         InputStream in = cservice_.getInputStream(path);
150         addResource(resourcesHome, name, description, in);
151       }
152       resourcesHome.save();
153     }
154   }
155 
156   /**
157    * add Resource
158    * @param resourcesHome     Node
159    * @param resourceName      String
160    * @param in                InputStream
161    * @throws Exception
162    */
163   public void addResource(Node resourcesHome, String resourceName, InputStream in)
164   throws Exception {
165     addResource(resourcesHome, resourceName, resourceName, in);
166   }
167   
168   /**
169    * add Resource
170    * @param resourcesHome     Node
171    * @param resourceName      String
172    * @param in                InputStream
173    * @throws Exception
174    */
175   public void addResource(Node resourcesHome, String resourceName, String resourceDescription, InputStream in)
176   throws Exception {
177     Node contentNode = null;
178     if(resourceName.lastIndexOf("/")>-1) {
179       String realParenPath = StringUtils.substringBeforeLast(resourceName,"/") ;
180       Node parentResource = resourcesHome.getNode(realParenPath) ;
181       resourcesHome = parentResource ;
182       resourceName = StringUtils.substringAfterLast(resourceName,"/") ;
183     }
184     Node script = null;
185     try {
186       script = resourcesHome.getNode(resourceName);
187       contentNode = script.getNode(NodetypeConstant.JCR_CONTENT);
188       if(!contentNode.isCheckedOut()) contentNode.checkout() ;
189     } catch (PathNotFoundException e) {
190       script = resourcesHome.addNode(resourceName, NodetypeConstant.NT_FILE);
191       contentNode = script.addNode(NodetypeConstant.JCR_CONTENT, NodetypeConstant.EXO_RESOURCES);
192       contentNode.setProperty(NodetypeConstant.JCR_ENCODING, "UTF-8");
193       contentNode.setProperty(NodetypeConstant.JCR_MIME_TYPE, "application/x-groovy");
194     }
195     if (activityService==null) {
196       activityService = WCMCoreUtils.getService(ActivityCommonService.class);
197     }
198     activityService.setCreating(script, true);
199     contentNode.setProperty(NodetypeConstant.JCR_DATA, in);
200     contentNode.setProperty(NodetypeConstant.DC_DESCRIPTION, new String[] { resourceDescription });
201     contentNode.setProperty(NodetypeConstant.JCR_LAST_MODIFIED, new GregorianCalendar());
202     activityService.setCreating(script, false);
203     resourcesHome.save() ;
204   }  
205 
206   /**
207    * get ResourcesHome
208    * @param sessionProvider   SessionProvider
209    * @see                     SessionProvider
210    * @see                     DMSRepositoryConfiguration
211    * @see                     ManageableRepository
212    * @return
213    * @throws Exception
214    */
215   protected Node getResourcesHome(SessionProvider sessionProvider) throws Exception {
216     ManageableRepository manageableRepository = null;
217     manageableRepository = repositoryService_.getCurrentRepository();
218     DMSRepositoryConfiguration dmsRepoConfig = dmsConfiguration_.getConfig();
219     Session session = sessionProvider.getSession(dmsRepoConfig.getSystemWorkspace(),
220                                                  manageableRepository);
221     String resourcesPath = getBasePath();
222     return (Node) session.getItem(resourcesPath);
223   }
224   
225   /**
226    * get Resource As Text
227    * @param resourceName    String
228    * @return                String
229    * @throws Exception
230    */
231   public String getResourceAsText(String resourceName) throws Exception {
232     SessionProvider systemProvider = SessionProvider.createSystemProvider();
233     try {
234       Node resourceNode = getResourceByName(systemProvider, resourceName);
235       String text = resourceNode.getNode("jcr:content").getProperty("jcr:data").getString();
236       return text;
237     } finally {
238       systemProvider.close();
239     }
240   }
241   
242   /**
243    * get Resource By Name
244    * @param resourceName    String
245    * @return                Node
246    * @throws Exception
247    */  
248   public Node getResourceByName(SessionProvider systemProvider, String resourceName) throws Exception {
249     Node resourcesHome = getResourcesHome(systemProvider);
250     return resourcesHome.getNode(resourceName);
251   }
252   
253   /**
254    * Get resource name from Node Type
255    * @param nodeType
256    * @return
257    * @throws Exception
258    */
259   public String getResourceNameByNodeType(NodeType nodeType) throws Exception {
260     if(nodeType.isNodeType("exo:scriptAction")) {
261       PropertyDefinition[] arrProperties = nodeType.getPropertyDefinitions();
262       for(PropertyDefinition property : arrProperties) {
263         if(property.getName().equals("exo:script")) {
264           return property.getDefaultValues()[0].getString();
265         }
266       }
267     }
268     return StringUtils.EMPTY;
269   }
270   
271   /**
272    * Get NodeType by the given resource name
273    * @param resourceName Name of resource
274    * @return NodeType object
275    * @throws Exception
276    */
277   public NodeType getNodeTypeByResourceName(String resourceName) throws Exception {
278     ActionServiceContainer actionsServiceContainer = WCMCoreUtils.getService(ActionServiceContainer.class) ;
279     Collection<NodeType> actionList = actionsServiceContainer.getCreatedActionTypes(
280             WCMCoreUtils.getRepository().getConfiguration().getName()) ;
281     for(NodeType nodeType : actionList) {
282       if(nodeType.isNodeType("exo:scriptAction")) {
283         PropertyDefinition[] arrProperties = nodeType.getPropertyDefinitions();
284         for(PropertyDefinition property : arrProperties) {
285           if(property.getName().equals("exo:script") && property.getDefaultValues()[0].getString().equals(resourceName)) {
286             return nodeType;
287           }
288         }
289       }
290     }
291     return null;
292   }
293   
294   /**
295    * get Resource Description
296    * @param resourceName    String
297    * @return                String
298    * @throws Exception
299    */  
300   public String getResourceDescription(String resourceName) throws Exception {
301     Node resource = getResourceByName(WCMCoreUtils.getSystemSessionProvider(), resourceName);
302     return resource.getNode(NodetypeConstant.JCR_CONTENT).getProperty(NodetypeConstant.DC_DESCRIPTION).getValues()[0].getString();
303   }
304   
305   /**
306    * get Resource As Stream
307    * @param resourceName    String
308    * @return                SessionProvider
309    * @throws Exception
310    */
311   public InputStream getResourceAsStream(String resourceName) throws Exception {
312     SessionProvider systemProvider = SessionProvider.createSystemProvider();
313     try {
314       Node resourceNode = getResourceByName(systemProvider, resourceName);
315       InputStream stream = resourceNode.getNode("jcr:content").getProperty("jcr:data").getStream();
316       return stream;
317     } finally {
318       systemProvider.close();
319     }
320   }  
321   
322   /**
323    * get Resources
324    * @param sessionProvider     SessionProvider
325    * @see                       SessionProvider
326    * @return
327    * @throws Exception
328    */
329   public NodeIterator getResources(SessionProvider sessionProvider) throws Exception {
330     Node resourcesHome = getResourcesHome(sessionProvider);
331     return resourcesHome.getNodes();
332   }
333   
334   /**
335    * Check has Resources
336    * @param sessionProvider   SessionProvider
337    * @see                     SessionProvider
338    * @return
339    * @throws Exception
340    */
341   public boolean hasResources(SessionProvider sessionProvider) throws Exception {
342     Node resourcesHome = getResourcesHome(sessionProvider);
343     return resourcesHome.hasNodes();
344   }  
345   
346   /**
347    * add Resource
348    * @param name          String
349    *                      The name of resource
350    * @param text          String
351    * @param provider      SessionProvider
352    * @see                 SessionProvider
353    * @throws Exception
354    */
355   public void addResource(String name, String text,SessionProvider provider) throws Exception {
356     Node resourcesHome = getResourcesHome(provider);
357     InputStream in = new ByteArrayInputStream(text.getBytes());
358     addResource(resourcesHome, name, in);
359     resourcesHome.save();
360   }  
361 
362   /**
363    * remove Resource
364    * @param resourceName    String
365    *                        The name of resource
366    * @param provider        SessionProvider
367    * @see                   SessionProvider
368    * @throws Exception
369    */
370   public void removeResource(String resourceName,SessionProvider provider) throws Exception {
371     removeFromCache(resourceName);
372     Node resourcesHome = getResourcesHome(provider);
373     Node resource2remove = resourcesHome.getNode(resourceName);
374     resource2remove.remove();
375     resourcesHome.save();
376   }  
377 }