KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > dotmarketing > portal > struts > DotPortletAction


1 /*
2  * Created on Jun 25, 2004
3  *
4  */

5 package com.dotmarketing.portal.struts;
6
7 import java.util.ArrayList JavaDoc;
8 import java.util.List JavaDoc;
9
10 import javax.portlet.ActionRequest;
11 import javax.portlet.ActionResponse;
12 import javax.portlet.PortletConfig;
13 import javax.portlet.RenderRequest;
14 import javax.servlet.http.HttpServletRequest JavaDoc;
15 import javax.servlet.http.HttpSession JavaDoc;
16 import javax.servlet.jsp.PageContext JavaDoc;
17
18 import org.apache.commons.beanutils.BeanUtils;
19 import org.apache.struts.action.ActionForm;
20 import org.apache.struts.action.ActionForward;
21 import org.apache.struts.action.ActionMapping;
22
23 import com.dotmarketing.beans.Host;
24 import com.dotmarketing.beans.Identifier;
25 import com.dotmarketing.beans.Inode;
26 import com.dotmarketing.beans.Permission;
27 import com.dotmarketing.beans.WebAsset;
28 import com.dotmarketing.cache.IdentifierCache;
29 import com.dotmarketing.cache.PermissionCache;
30 import com.dotmarketing.cms.factories.PublicCompanyFactory;
31 import com.dotmarketing.db.DotHibernate;
32 import com.dotmarketing.factories.HostFactory;
33 import com.dotmarketing.factories.IdentifierFactory;
34 import com.dotmarketing.factories.InodeFactory;
35 import com.dotmarketing.factories.PermissionFactory;
36 import com.dotmarketing.factories.PublishFactory;
37 import com.dotmarketing.factories.RoleFactory;
38 import com.dotmarketing.factories.WebAssetFactory;
39 import com.dotmarketing.portlets.containers.model.Container;
40 import com.dotmarketing.portlets.contentlet.factories.ContentletFactory;
41 import com.dotmarketing.portlets.contentlet.model.Contentlet;
42 import com.dotmarketing.portlets.files.model.File;
43 import com.dotmarketing.portlets.folders.model.Folder;
44 import com.dotmarketing.portlets.htmlpages.model.HTMLPage;
45 import com.dotmarketing.portlets.links.model.Link;
46 import com.dotmarketing.portlets.structure.model.Structure;
47 import com.dotmarketing.portlets.templates.model.Template;
48 import com.dotmarketing.util.Config;
49 import com.dotmarketing.util.Logger;
50 import com.dotmarketing.util.UtilMethods;
51 import com.dotmarketing.util.WebKeys;
52 import com.liferay.portal.ejb.UserLocalManagerUtil;
53 import com.liferay.portal.language.LanguageUtil;
54 import com.liferay.portal.model.Company;
55 import com.liferay.portal.model.Role;
56 import com.liferay.portal.model.User;
57 import com.liferay.portal.struts.ActionException;
58 import com.liferay.portal.struts.PortletAction;
59 import com.liferay.portal.util.Constants;
60 import com.liferay.portlet.ActionRequestImpl;
61 import com.liferay.util.servlet.SessionMessages;
62
63 /**
64  * @author Maria
65  *
66  */

67 public class DotPortletAction extends PortletAction {
68     
69     /**
70      * Generic method to delete a WebAsset version
71      *
72      * @param req
73      * @param res
74      * @param config
75      * @param form
76      * @param user
77      * @param webKeyEdit
78      * @throws Exception
79      */

80     public void _deleteVersionWebAsset(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user, String JavaDoc webKeyEdit)
81     throws Exception JavaDoc {
82         
83         // wraps request to get session object
84
ActionRequestImpl reqImpl = (ActionRequestImpl) req;
85         HttpServletRequest JavaDoc httpReq = reqImpl.getHttpServletRequest();
86         
87         WebAsset webAsset = (WebAsset) req.getAttribute(webKeyEdit);
88         
89         // Checking permissions
90
_checkUserPermissions(webAsset, user, Config.getIntProperty("PERMISSION_WRITE"));
91         
92         // calls the webasset factory delete the container version
93
if (WebAssetFactory.deleteAssetVersion(webAsset)) {
94             SessionMessages.add(httpReq, "message", "message." + webAsset.getType() + ".delete");
95         } else {
96             // couldn't delete the container it's either working or live
97
SessionMessages.add(httpReq, "message", "message." + webAsset.getType() + ".delete.live_or_working");
98         }
99         
100     }
101     
102     /**
103      * Generic method to undelete a WebAsset
104      *
105      * @param req
106      * @param res
107      * @param config
108      * @param form
109      * @param user
110      * @param webKeyEdit
111      * @throws Exception
112      */

113     public void _undeleteWebAsset(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user, String JavaDoc webKeyEdit)
114     throws Exception JavaDoc {
115         
116         // wraps request to get session object
117
ActionRequestImpl reqImpl = (ActionRequestImpl) req;
118         HttpServletRequest JavaDoc httpReq = reqImpl.getHttpServletRequest();
119         
120         WebAsset webAsset = (WebAsset) req.getAttribute(webKeyEdit);
121         
122         // Checking permissions
123
_checkUserPermissions(webAsset, user, Config.getIntProperty("PERMISSION_WRITE"));
124         
125         WebAssetFactory.unDeleteAsset(webAsset);
126         SessionMessages.add(httpReq, "message", "message." + webAsset.getType() + ".undelete");
127         
128     }
129     
130     /**
131      * Generic method to delete a WebAsset
132      *
133      * @param req
134      * @param res
135      * @param config
136      * @param form
137      * @param user
138      * @param webKeyEdit
139      * @throws Exception
140      */

141     public void _deleteWebAsset(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user, String JavaDoc webKeyEdit)
142     throws Exception JavaDoc {
143         
144         // wraps request to get session object
145
ActionRequestImpl reqImpl = (ActionRequestImpl) req;
146         HttpServletRequest JavaDoc httpReq = reqImpl.getHttpServletRequest();
147         
148         WebAsset webAsset = (WebAsset) req.getAttribute(webKeyEdit);
149         
150         // Checking permissions
151
_checkUserPermissions(webAsset, user, Config.getIntProperty("PERMISSION_WRITE"));
152         
153         if (WebAssetFactory.deleteAsset(webAsset, user.getUserId())) {
154             SessionMessages.add(httpReq, "message", "message." + webAsset.getType() + ".delete");
155         } else {
156             SessionMessages.add(httpReq, "message", "message." + webAsset.getType() + ".delete.locked");
157         }
158         
159         
160     }
161     
162     /**
163      * Generic method to unpublish a WebAsset
164      *
165      * @param req
166      * @param res
167      * @param config
168      * @param form
169      * @param user
170      * @param webKeyEdit
171      * @throws Exception
172      */

173     public void _unPublishWebAsset(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user, String JavaDoc webKeyEdit)
174     throws Exception JavaDoc {
175         
176         // wraps request to get session object
177
ActionRequestImpl reqImpl = (ActionRequestImpl) req;
178         HttpServletRequest JavaDoc httpReq = reqImpl.getHttpServletRequest();
179         
180         WebAsset webAsset = (WebAsset) req.getAttribute(webKeyEdit);
181         
182         // Checking permissions
183
_checkUserPermissions(webAsset, user, Config.getIntProperty("PERMISSION_WRITE"));
184         
185         Folder parent = (Folder) InodeFactory.getParentOfClass(webAsset, Folder.class);
186         // gets user id from request for mod user
187
String JavaDoc userId = user.getUserId();
188         if (webAsset.getInode() > 0) {
189             // calls the asset factory edit
190
if (WebAssetFactory.unPublishAsset(webAsset, userId, parent)) {
191                 SessionMessages.add(httpReq, "message", "message." + webAsset.getType() + ".unpublished");
192             } else {
193                 SessionMessages.add(httpReq, "message", "message." + webAsset.getType() + ".unpublish.notlive_or_locked");
194             }
195         }
196         
197     }
198     
199     /**
200      * Generic Method to Get Versions of a WebAsset
201      *
202      * @param req
203      * @param res
204      * @param config
205      * @param form
206      * @param user
207      * @param webKeyEdit
208      * @param webKeyVersions
209      * @throws Exception
210      */

211     public void _getVersionsWebAsset(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user, String JavaDoc webKeyEdit,
212             String JavaDoc webKeyVersions) throws Exception JavaDoc {
213         
214         WebAsset webAsset = (WebAsset) req.getAttribute(webKeyEdit);
215         
216         if (webAsset.getInode() > 0) {
217             // calls the asset factory to get the version
218
req.setAttribute(webKeyVersions, WebAssetFactory.getAssetVersions(webAsset));
219         }
220         
221     }
222     
223     /**
224      * Generic Method to unlock a WebAsset
225      *
226      * @param req
227      * @param res
228      * @param config
229      * @param form
230      * @param user
231      * @param webKey
232      * @throws Exception
233      */

234     public void _unLockWebAsset(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user, String JavaDoc webKey)
235     throws Exception JavaDoc {
236         
237         // wraps request to get session object
238
ActionRequestImpl reqImpl = (ActionRequestImpl) req;
239         HttpServletRequest JavaDoc httpReq = reqImpl.getHttpServletRequest();
240         
241         WebAsset webAsset = (WebAsset) req.getAttribute(webKey);
242         
243         // Checking permissions
244
_checkUserPermissions(webAsset, user, Config.getIntProperty("PERMISSION_READ"));
245         
246         if (webAsset.getInode() > 0) {
247             // calls the asset factory edit
248
WebAssetFactory.unLockAsset(webAsset);
249             SessionMessages.add(httpReq, "message", "message." + webAsset.getType() + ".unlocked");
250         }
251         
252         httpReq.getSession().removeAttribute(WebKeys.CONTENTLET_RELATIONSHIPS_EDIT);
253         
254     }
255     
256     /**
257      * Generic method to move a WebAsset to another Folder
258      *
259      * @param req
260      * @param res
261      * @param config
262      * @param form
263      * @param user
264      * @param webAssetClass
265      * @param webKey
266      * @throws Exception
267      */

268     public void _moveWebAsset(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user, Class JavaDoc webAssetClass,
269             String JavaDoc webKey) throws Exception JavaDoc {
270         
271         Logger.debug(this, "I'm moving the webasset");
272         
273         // wraps request to get session object
274
ActionRequestImpl reqImpl = (ActionRequestImpl) req;
275         HttpServletRequest JavaDoc httpReq = reqImpl.getHttpServletRequest();
276         
277         // gets the current container being edited from the request object
278
WebAsset webAsset = (WebAsset) req.getAttribute(webKey);
279         Identifier identifier = com.dotmarketing.factories.IdentifierFactory.getParentIdentifier(webAsset);
280         
281         // gets working container
282
WebAsset workingWebAsset = (WebAsset) IdentifierFactory.getWorkingChildOfClass(identifier, webAssetClass);
283         // gets live container
284
WebAsset liveWebAsset = (WebAsset) IdentifierFactory.getLiveChildOfClass(identifier, webAssetClass);
285         
286         // gets folder parent
287
String JavaDoc parentInode = req.getParameter("parent");
288         
289         if (parentInode != null && parentInode.length() != 0 && !parentInode.equals("0")) {
290             // the new parent is being passed through the request
291
Folder parent = (Folder) InodeFactory.getInode(parentInode, Folder.class);
292             
293             // Checking permissions
294
_checkCopyAndMovePermissions(webAsset, parent, user, httpReq, "move");
295             
296             // gets old parent
297
Folder oldParent = (Folder) InodeFactory.getParentOfClass(workingWebAsset, Folder.class);
298             Logger.debug(this, "Old Parent Folder=" + oldParent.getInode());
299             oldParent.deleteChild(workingWebAsset);
300             if ((liveWebAsset != null) && (liveWebAsset.getInode() > 0)) {
301                 oldParent.deleteChild(liveWebAsset);
302             }
303             
304             // Adding to new parent
305
Logger.debug(this, "Parent Folder=" + parent.getInode());
306             parent.addChild(workingWebAsset);
307             if ((liveWebAsset != null) && (liveWebAsset.getInode() > 0)) {
308                 parent.addChild(liveWebAsset);
309             }
310             
311             // gets identifier for this webasset and changes the uri and
312
// persists it
313
Host newHost = HostFactory.getParentHost(parent);
314             identifier.setHostInode(newHost.getInode());
315             identifier.setURI(workingWebAsset.getURI(parent));
316             InodeFactory.saveInode(identifier);
317             
318             SessionMessages.add(httpReq, "message", "message." + webAsset.getType() + ".move");
319         }
320         
321     }
322     
323     /**
324      * Generic method to publish a WebAsset
325      *
326      * @param req
327      * @param res
328      * @param config
329      * @param form
330      * @param user
331      * @param formWebKey
332      * @throws Exception
333      */

334     public void _publishWebAsset(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user, String JavaDoc formWebKey)
335     throws Exception JavaDoc {
336         
337         // wraps request to get session object
338
ActionRequestImpl reqImpl = (ActionRequestImpl) req;
339         HttpServletRequest JavaDoc httpReq = reqImpl.getHttpServletRequest();
340         
341         WebAsset webAsset = (WebAsset) req.getAttribute(formWebKey);
342         Logger.debug(this, "WEB ASSET " + webAsset.getType() + " TO PUBLISH=" + webAsset.getInode());
343         
344         // Checking permissions
345
_checkUserPermissions(webAsset, user, Config.getIntProperty("PERMISSION_PUBLISH"));
346         
347         if (webAsset.getInode() > 0) {
348             // calls the asset factory edit
349
PublishFactory.publishAsset(webAsset, httpReq);
350             SessionMessages.add(httpReq, "message", "message." + webAsset.getType() + ".published");
351         }
352         
353     }
354     
355     /**
356      * Generic method to retrieve a WebAsset based on the inode on the request
357      *
358      * @param req
359      * @param res
360      * @param config
361      * @param form
362      * @param user
363      * @param myClass
364      * @param webkey
365      * @throws Exception
366      */

367     public void _retrieveWebAsset(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user, Class JavaDoc myClass,
368             String JavaDoc webkey) throws Exception JavaDoc {
369         
370         WebAsset webAsset = (WebAsset) InodeFactory.getInode(req.getParameter("inode"), myClass);
371         
372         // Permission variable
373
if (!(WebAssetFactory.isAbstractAsset(webAsset))) {
374             if (webAsset.getInode() > 0)
375                 req.setAttribute(WebKeys.PERMISSION_INODE_EDIT, webAsset);
376             else {
377                 Folder parentFolder = (Folder) InodeFactory.getInode(req.getParameter("parent"), Folder.class);
378                 
379                 // if the html page is new the parentfolder permissions are used
380
req.setAttribute(WebKeys.PERMISSION_INODE_EDIT, parentFolder);
381             }
382         } else {
383             req.setAttribute(WebKeys.PERMISSION_INODE_EDIT, webAsset);
384         }
385         
386         // Checking permissions
387
_checkUserPermissions(webAsset, user, Config.getIntProperty("PERMISSION_READ"));
388         
389         Logger.debug(this, "webAsset:" + webAsset.toString());
390         Logger.debug(this, "webAsset:" + webAsset.getInode());
391         req.setAttribute(webkey, webAsset);
392         
393         // Asset Versions to list in the versions tab
394
req.setAttribute(WebKeys.VERSIONS_INODE_EDIT, webAsset);
395         
396         // Permission variable
397
req.setAttribute(WebKeys.PERMISSION_INODE_EDIT, webAsset);
398         
399     }
400     
401     /**
402      * Generic Edit WebAsset method. Still needs to be implemented on the class,
403      * so it's still part of the interface
404      *
405      * @param req
406      * @param res
407      * @param config
408      * @param form
409      * @param user
410      * @param webKey
411      * @return Folder: parent Folder for this WebAsset if the webasset is a
412      * contentlet, a container or a template it returns a void (inode =
413      * 0) folder.
414      * @throws Exception
415      */

416     protected Folder _editWebAsset(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user, String JavaDoc webKey)
417     throws Exception JavaDoc {
418         
419         // wraps request to get session object
420
ActionRequestImpl reqImpl = (ActionRequestImpl) req;
421         HttpServletRequest JavaDoc httpReq = reqImpl.getHttpServletRequest();
422         
423         WebAsset webAsset = (WebAsset) req.getAttribute(webKey);
424         
425         // Checking permissions
426
_checkUserPermissions(webAsset, user, Config.getIntProperty("PERMISSION_READ"));
427         
428         if (webAsset.getInode() > 0) {
429             
430             // calls the asset factory edit
431
boolean editAsset = WebAssetFactory.editAsset(webAsset, user.getUserId());
432             if (!editAsset) {
433                 
434                 try {
435                     User userMod = UserLocalManagerUtil.getUserById(webAsset.getModUser());
436                     Company comp = PublicCompanyFactory.getDefaultCompany();
437                     String JavaDoc message = LanguageUtil.get(comp.getCompanyId(), user.getLocale(), "message." + webAsset.getType() + ".edit.locked");
438                     message += " (" + userMod.getEmailAddress() + ")";
439                     SessionMessages.add(httpReq, "custommessage", message);
440                 } catch (Exception JavaDoc e) {
441                     SessionMessages.add(httpReq, "message", "message." + webAsset.getType() + ".edit.locked");
442                 }
443                 
444                 throw (new ActionException(WebKeys.EDIT_ASSET_EXCEPTION));
445             }
446         }
447         
448         Folder parentFolder = new Folder();
449         
450         if (!(WebAssetFactory.isAbstractAsset(webAsset))) {
451             if (webAsset.getInode() > 0) {
452                 parentFolder = (Folder) com.dotmarketing.factories.InodeFactory.getParentOfClass(webAsset, Folder.class);
453             } else {
454                 parentFolder = (Folder) com.dotmarketing.factories.InodeFactory.getInode(req.getParameter("parent"), Folder.class);
455             }
456         }
457         
458         req.setAttribute(webKey, webAsset);
459         
460         BeanUtils.copyProperties(form, req.getAttribute(webKey));
461         
462         return parentFolder;
463     }
464     
465     /**
466      * Generic method to get a version back from an asset. Needs to be
467      * implemented on each class for the relations between assets Set in the
468      * <b>webKey </b> the new version created with the working information.
469      *
470      * @param req
471      * @param res
472      * @param config
473      * @param form
474      * @param user
475      * @param className
476      * @param webKey
477      * @return The new working asset
478      * @throws Exception
479      */

480     protected WebAsset _getVersionBackWebAsset(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user,
481             Class JavaDoc className, String JavaDoc webKey) throws Exception JavaDoc {
482         
483         WebAsset version = (WebAsset) InodeFactory.getInode(req.getParameter("inode_version"), className);
484         
485         // Checking permissions
486
_checkUserPermissions(version, user, Config.getIntProperty("PERMISSION_WRITE"));
487         
488         WebAsset workingAsset = (WebAsset) WebAssetFactory.getBackAssetVersion(version);
489         
490         version = (WebAsset) InodeFactory.getInode(version.getInode(), version.getClass());
491         
492         req.setAttribute(webKey, version);
493         
494         if (workingAsset instanceof Contentlet) {
495             // Upodating lucene index
496
ContentletFactory.reIndexContentlet((Contentlet) workingAsset);
497         }
498         
499         return workingAsset;
500         
501     }
502     
503     /**
504      * Generic method for View Assets Actions.
505      *
506      * @param req
507      * @param user
508      * @param className:
509      * Asset Class
510      * @param tableName:
511      * Table Name
512      * @param countWebKey:
513      * WebKey to store the Count
514      * @param viewWebKey:
515      * WebKey to store the Listings
516      * @throws Exception
517      */

518     protected void _viewWebAssets(RenderRequest req, User user, Class JavaDoc className, String JavaDoc tableName, String JavaDoc countWebKey, String JavaDoc viewWebKey,
519             String JavaDoc queryWebKey, String JavaDoc showDeletedWebKey) throws Exception JavaDoc {
520         
521         com.liferay.portlet.RenderRequestImpl reqImpl = (com.liferay.portlet.RenderRequestImpl) req;
522         HttpServletRequest JavaDoc httpReq = reqImpl.getHttpServletRequest();
523         // gets the session object for the messages
524
HttpSession JavaDoc session = httpReq.getSession();
525         
526         String JavaDoc hostId = (String JavaDoc) session.getAttribute(WebKeys.SEARCH_HOST_ID);
527         if (req.getParameter("host_id") != null)
528             hostId = req.getParameter("host_id");
529         if (hostId != null)
530             session.setAttribute(WebKeys.SEARCH_HOST_ID, hostId);
531         
532         String JavaDoc query = req.getParameter("query");
533         String JavaDoc resetQuery = req.getParameter("resetQuery");
534         
535         List JavaDoc l = new java.util.ArrayList JavaDoc();
536         
537         try {
538             // Gets roles
539
Role[] roles = (Role[]) RoleFactory.getAllRolesForUser(user.getUserId()).toArray(new Role[0]);
540             Logger.debug(this, "Inside _viewWebAssets Roles=" + roles.length);
541             
542             String JavaDoc condition = "";
543             String JavaDoc showDeleted = req.getParameter("showDeleted");
544             
545             if ((showDeleted == null) && (resetQuery == null)) {
546                 showDeleted = (String JavaDoc) session.getAttribute(showDeletedWebKey);
547             }
548             if ((showDeleted != null) && (showDeleted.equals("true"))) {
549                 condition = "working=" + com.dotmarketing.db.DbConnectionFactory.getDBTrue();
550                 session.setAttribute(showDeletedWebKey, "true");
551             } else {
552                 condition = "working=" + com.dotmarketing.db.DbConnectionFactory.getDBTrue() + " and deleted="
553                 + com.dotmarketing.db.DbConnectionFactory.getDBFalse();
554                 session.setAttribute(showDeletedWebKey, "false");
555             }
556             String JavaDoc orderby = req.getParameter("orderby");
557             if (!UtilMethods.isSet(orderby)) {
558                 orderby = "title";
559             }
560             
561             int pageNumber = 1;
562             
563             if (UtilMethods.isSet(req.getParameter("pageNumber"))) {
564                 pageNumber = Integer.parseInt(req.getParameter("pageNumber"));
565             }
566             
567             int limit = com.dotmarketing.util.Config.getIntProperty("PER_PAGE");
568             
569             int offset = (pageNumber - 1) * limit;
570             
571             if ((query == null) && (resetQuery == null)) {
572                 query = (String JavaDoc) session.getAttribute(queryWebKey);
573             }
574             session.setAttribute(queryWebKey, query);
575             
576             int count = 0;
577             
578             // Gets templates for this role
579
if (((query != null) && (query.length() != 0)) || (hostId != null && !hostId.equals("0"))) {
580                 if (query == null)
581                     query = "";
582                 condition += " and (lower(" + tableName + "_condition.title) " + "like '%" + query.toLowerCase() + "%' ";
583                 if ("file_asset".equals(tableName)) {
584                     condition += " or lower(" + tableName + "_condition.file_name) like '%" + query.toLowerCase() + "%' ";
585                 }
586                 condition += " or lower(" + tableName + "_condition.friendly_name) like '%" + query.toLowerCase() + "%')";
587                 Logger.debug(this, "Getting Assets based on condition=" + condition);
588                 limit = 0;
589                 if (hostId == null || hostId.equals("0")) {
590                     l = WebAssetFactory.getAssetsAndPermissionsPerRoleAndCondition(roles, condition, limit, offset, orderby, className, tableName);
591                     count = WebAssetFactory.getCountAssetsPerConditionWithPermission(condition, className, roles);
592                 } else {
593                     long hostIdL = Long.parseLong(hostId);
594                     l = WebAssetFactory.getAssetsAndPermissionsPerRoleAndCondition(hostIdL, roles, condition, limit, offset, orderby, className,
595                             tableName);
596                     count = WebAssetFactory.getCountAssetsPerConditionWithPermission(hostIdL, condition, className, roles);
597                 }
598             } else {
599                 Logger.debug(this, "Getting all Assets=" + condition);
600                 l = WebAssetFactory.getAssetsAndPermissionsPerRoleAndCondition(roles, condition, limit, offset, orderby, className, tableName);
601                 count = WebAssetFactory.getCountAssetsPerConditionWithPermission(condition, className, roles);
602                 
603             }
604             
605             req.setAttribute(countWebKey, new Integer JavaDoc(count));
606             req.setAttribute(viewWebKey, l);
607         } catch (Exception JavaDoc e) {
608             req.setAttribute(viewWebKey, l);
609             Logger.error(this, "Exception e =" + e.getMessage(), e);
610             throw new Exception JavaDoc(e.getMessage());
611         }
612         
613     }
614     
615     /**
616      * Method to handle an exception. Rollbacks the transaction and forwards to
617      * an error page.
618      *
619      * @param e
620      * @param req
621      */

622     protected void _handleException(Exception JavaDoc e, ActionRequest req) {
623         Logger.warn(this, e.toString(), e);
624         DotHibernate.rollbackTransaction();
625         req.setAttribute(PageContext.EXCEPTION, e);
626         setForward(req, Constants.COMMON_ERROR);
627     }
628     
629     /**
630      * Method to handle an exception. Rollbacks the transaction and forwards to
631      * an error page.
632      *
633      * @param e
634      * @param req
635      */

636     protected void _handleException(Exception JavaDoc e, ActionRequest req, boolean showStackTrace) {
637         if (!showStackTrace)
638             Logger.info(this, e.toString());
639         else
640             Logger.warn(this, e.toString(), e);
641         DotHibernate.rollbackTransaction();
642         req.setAttribute(PageContext.EXCEPTION, e);
643         setForward(req, Constants.COMMON_ERROR);
644     }
645     
646     /**
647      * Method to handle an exception. Rollbacks the transaction and forwards to
648      * an error page.
649      *
650      * @param e
651      * @param req
652      */

653     protected ActionForward _handleException(Exception JavaDoc e, RenderRequest req, ActionMapping mapping) {
654         Logger.warn(this, e.toString(), e);
655         DotHibernate.rollbackTransaction();
656         req.setAttribute(PageContext.EXCEPTION, e);
657         return mapping.findForward(Constants.COMMON_ERROR);
658     }
659     
660     /**
661      * Method to redirect to the referer if set, if not to the redirect. Closes
662      * the transaction before redirecting.
663      *
664      * @param req
665      * @param res
666      * @param referer
667      * @throws Exception
668      */

669     protected void _sendToReferral(ActionRequest req, ActionResponse res, String JavaDoc referer) throws Exception JavaDoc {
670         
671         String JavaDoc redirect = req.getParameter("redirect");
672         
673         if (UtilMethods.isSet(referer)) {
674             Logger.debug(this, "\n\nGoing to redirect to referer: " + referer);
675             res.sendRedirect(referer);
676         } else if (UtilMethods.isSet(redirect)) {
677             Logger.debug(this, "\n\nGoing to redirect to redirect : " + redirect);
678             res.sendRedirect(redirect);
679         }
680         Logger.debug(this, "End of _sendToReferral");
681     }
682     
683     /**
684      * Method to obtain the User from Liferay on an ActionRequest
685      *
686      * @param req
687      * @return
688      */

689     protected User _getUser(ActionRequest req) {
690         
691         // get the user
692
User user = null;
693         try {
694             user = com.liferay.portal.util.PortalUtil.getUser(req);
695         } catch (Exception JavaDoc e) {
696             _handleException(e, req);
697         }
698         return user;
699         
700     }
701     
702     /**
703      * Method to obtain the User from Liferay on a RenderRequest
704      *
705      * @param req
706      * @return
707      */

708     protected User _getUser(RenderRequest req) {
709         
710         // get the user
711
User user = null;
712         try {
713             user = com.liferay.portal.util.PortalUtil.getUser(req);
714         } catch (Exception JavaDoc e) {
715             req.setAttribute(PageContext.EXCEPTION, e);
716             return null;
717         }
718         return user;
719         
720     }
721     
722     // To check if Forward is being set on an action... wasn't implemented on
723
// Liferay's PortletAction
724
public String JavaDoc getForward(ActionRequest req) {
725         return getForward(req, null);
726     }
727     
728     public String JavaDoc getForward(ActionRequest req, String JavaDoc defaultValue) {
729         String JavaDoc forward = (String JavaDoc) req.getAttribute(com.liferay.portal.util.WebKeys.PORTLET_STRUTS_FORWARD);
730         
731         if (forward == null) {
732             return defaultValue;
733         } else {
734             return forward;
735         }
736     }
737     
738     public void _lockWebAsset(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user, String JavaDoc webKey)
739     throws Exception JavaDoc {
740         
741         // wraps request to get session object
742
ActionRequestImpl reqImpl = (ActionRequestImpl) req;
743         HttpServletRequest JavaDoc httpReq = reqImpl.getHttpServletRequest();
744         
745         WebAsset webAsset = (WebAsset) req.getAttribute(webKey);
746         
747         if (webAsset.getInode() > 0) {
748             // calls the asset factory edit
749
WebAssetFactory.editAsset(webAsset, user.getUserId());
750             SessionMessages.add(httpReq, "message", "message." + webAsset.getType() + ".locked");
751         }
752         
753         if (webAsset instanceof Contentlet) {
754             // Upodating lucene index
755
ContentletFactory.reIndexContentlet((Contentlet) webAsset);
756         }
757         
758     }
759     
760     public void _applyPermissions(ActionRequest req, String JavaDoc webKey) {
761         Inode inode = (Inode) req.getAttribute(webKey);
762         _applyPermissions(req, inode);
763     }
764     
765     @SuppressWarnings JavaDoc("unchecked")
766     public void _applyPermissions(ActionRequest req, Inode inode) {
767         // Obtain de parameter that indicate if the permissions has been changed
768
String JavaDoc permission_not_changed = req.getParameter(WebKeys.PERMISSION_NOT_CHANGED);
769         String JavaDoc permission_is_new = req.getParameter(WebKeys.PERMISSION_IS_NEW);
770         // If the permission has been changed, the method save the permission
771
// otherwise not
772
if ((UtilMethods.isSet(permission_not_changed) && Boolean.valueOf(permission_not_changed).booleanValue())
773                 || (UtilMethods.isSet(permission_is_new) && Boolean.valueOf(permission_is_new).booleanValue())) {
774             
775             Inode origInode = inode;
776             
777             if(inode instanceof WebAsset){
778                 Identifier id = new Identifier();
779                 if (inode.getIdentifier() > 0) {
780                     id.setInode(inode.getIdentifier());
781                 } else {
782                     id.setInode(IdentifierCache.getIdentifierByInodeFromCache(inode.getInode()).getInode());
783                 }
784                 
785                 inode = id;
786                 
787             }
788             
789             Permission permission = null;
790             
791             java.util.List JavaDoc<Permission> currentPerms = PermissionFactory.getPermissions(inode);
792             for(Permission perm : currentPerms){
793                 PermissionFactory.deletePermission(perm);
794             }
795             
796             // adds read permissions to the inode
797
String JavaDoc[] readPermissions = req.getParameterValues("read");
798             if (readPermissions != null) {
799                 for (int k = 0; k < readPermissions.length; k++) {
800                     
801                     Logger.debug(this, "_applyPermissions: Saving Read Permission for=" + readPermissions[k]);
802                     
803                     permission = new Permission(inode.getInode(), Long.parseLong(readPermissions[k]), Config.getIntProperty("PERMISSION_READ"));
804                     PermissionFactory.savePermission(permission);
805                 }
806             }
807             
808             // adds write permissions to the inode
809
String JavaDoc[] writePermissions = req.getParameterValues("write");
810             if (writePermissions != null) {
811                 for (int k = 0; k < writePermissions.length; k++) {
812                     
813                     Logger.debug(this, "_applyPermissions: Saving Write Permission for=" + writePermissions[k]);
814                     
815                     permission = new Permission(inode.getInode(), Long.parseLong(writePermissions[k]), Config.getIntProperty("PERMISSION_WRITE"));
816                     PermissionFactory.savePermission(permission);
817                 }
818             }
819             
820             // adds publish permissions to the inode
821
String JavaDoc[] publishPermissions = req.getParameterValues("publish");
822             if (publishPermissions != null) {
823                 for (int k = 0; k < publishPermissions.length; k++) {
824                     
825                     Logger.debug(this, "_applyPermissions: Saving Publish Permission for=" + publishPermissions[k]);
826                     
827                     permission = new Permission(inode.getInode(), Long.parseLong(publishPermissions[k]), Config.getIntProperty("PERMISSION_PUBLISH"));
828                     PermissionFactory.savePermission(permission);
829                 }
830             }
831             
832             // Update the permissions cache
833
if (origInode instanceof Folder) {
834                 Folder f = (Folder) origInode;
835                 PermissionCache.addToPermissionCache(f);
836             } else if (origInode instanceof Host) {
837                 Host host = (Host) origInode;
838                 PermissionCache.addToPermissionCache(host);
839             } else if (origInode instanceof WebAsset) {
840                 WebAsset asset = (WebAsset) origInode;
841                 PermissionCache.addToPermissionCache(asset);
842             }
843             
844             if(origInode instanceof Contentlet){
845                 Contentlet content = (Contentlet) origInode;
846                 ContentletFactory.reIndexContentlet(content);
847             }
848             
849             if ((req.getParameter("applyChildren") != null) && (req.getParameter("applyChildren").equals("on"))
850                     && (inode instanceof Folder || inode instanceof Host || inode instanceof Structure)) {
851                 
852                 Logger.debug(this, "_applyPermissions: applying permissions to children");
853
854                 /*Start apply child permission */
855                 ApplyChildrenPermissionThread thread = new DotPortletAction().new ApplyChildrenPermissionThread(req,inode);
856                 thread.start();
857                 
858             }
859         }
860     }
861     
862     protected void _checkUserPermissions(Inode webAsset, User user, int permission) throws ActionException {
863         // Checking permissions
864
if (webAsset.getInode() == 0)
865             return;
866         if (!PermissionFactory.doesUserHavePermission(webAsset, permission, user)) {
867             Logger.warn(this, "_checkUserPermissions: user does not have permissions ( " + permission + " ) over this asset: " + webAsset);
868             throw new ActionException(WebKeys.USER_PERMISSIONS_EXCEPTION);
869         }
870     }
871     
872     protected void _checkPermissions(Inode webAsset, Folder parentFolder, User user, HttpServletRequest JavaDoc httpReq) throws Exception JavaDoc {
873         String JavaDoc subcmd = httpReq.getParameter("subcmd");
874         boolean publish = (subcmd != null) && subcmd.equals(com.dotmarketing.util.Constants.PUBLISH);
875         
876         try {
877             if (webAsset.getInode() > 0) {
878                 _checkUserPermissions(webAsset, user, Config.getIntProperty("PERMISSION_WRITE"));
879                 if (publish)
880                     _checkUserPermissions(webAsset, user, Config.getIntProperty("PERMISSION_PUBLISH"));
881             } else {
882                 _checkUserPermissions(parentFolder, user, Config.getIntProperty("PERMISSION_WRITE"));
883                 if (publish)
884                     _checkUserPermissions(parentFolder, user, Config.getIntProperty("PERMISSION_PUBLISH"));
885             }
886         } catch (Exception JavaDoc ae) {
887             if (ae.getMessage().equals(WebKeys.USER_PERMISSIONS_EXCEPTION)) {
888                 if (publish)
889                     SessionMessages.add(httpReq, "message", "message.insufficient.permissions.to.save.and.publish");
890                 else
891                     SessionMessages.add(httpReq, "message", "message.insufficient.permissions.to.save");
892             }
893             throw ae;
894         }
895         
896     }
897     
898     protected void _checkPermissions(Inode webAsset, User user, HttpServletRequest JavaDoc httpReq) throws Exception JavaDoc {
899         String JavaDoc subcmd = httpReq.getParameter("subcmd");
900         boolean publish = (subcmd != null) && subcmd.equals(com.dotmarketing.util.Constants.PUBLISH);
901         
902         try {
903             if (webAsset.getInode() > 0) {
904                 _checkUserPermissions(webAsset, user, Config.getIntProperty("PERMISSION_WRITE"));
905                 if (publish)
906                     _checkUserPermissions(webAsset, user, Config.getIntProperty("PERMISSION_PUBLISH"));
907             }
908         } catch (Exception JavaDoc ae) {
909             if (ae.getMessage().equals(WebKeys.USER_PERMISSIONS_EXCEPTION)) {
910                 if (publish)
911                     SessionMessages.add(httpReq, "message", "message.insufficient.permissions.to.save.and.publish");
912                 else
913                     SessionMessages.add(httpReq, "message", "message.insufficient.permissions.to.save");
914             }
915             throw ae;
916         }
917         
918     }
919     
920     protected void _checkWritePermissions(Inode inode, User user, HttpServletRequest JavaDoc httpReq) throws Exception JavaDoc {
921         try {
922             _checkUserPermissions(inode, user, Config.getIntProperty("PERMISSION_WRITE"));
923         } catch (Exception JavaDoc ae) {
924             if (ae.getMessage().equals(WebKeys.USER_PERMISSIONS_EXCEPTION)) {
925                 SessionMessages.add(httpReq, "message", "message.insufficient.permissions.to.save");
926             }
927             throw ae;
928         }
929         
930     }
931     
932     protected void _checkDeletePermissions(Structure structure, User user, HttpServletRequest JavaDoc httpReq) throws Exception JavaDoc {
933         try {
934             _checkUserPermissions(structure, user, Config.getIntProperty("PERMISSION_WRITE"));
935         } catch (Exception JavaDoc ae) {
936             if (ae.getMessage().equals(WebKeys.USER_PERMISSIONS_EXCEPTION)) {
937                 SessionMessages.add(httpReq, "message", "message.insufficient.permissions.to.delete");
938             }
939             throw ae;
940         }
941         
942     }
943     
944     protected void _checkCopyAndMovePermissions(Inode webAsset, Folder parentFolder, User user, HttpServletRequest JavaDoc httpReq, String JavaDoc action)
945     throws Exception JavaDoc {
946         
947         try {
948             _checkUserPermissions(webAsset, user, Config.getIntProperty("PERMISSION_WRITE"));
949             _checkUserPermissions(parentFolder, user, Config.getIntProperty("PERMISSION_WRITE"));
950         } catch (Exception JavaDoc ae) {
951             if (ae.getMessage().equals(WebKeys.USER_PERMISSIONS_EXCEPTION)) {
952                 SessionMessages.add(httpReq, "message", "message.insufficient.permissions.to." + action);
953             }
954             throw ae;
955         }
956     }
957     
958     protected void _checkCopyAndMovePermissions(Inode webAsset, User user, HttpServletRequest JavaDoc httpReq, String JavaDoc action) throws Exception JavaDoc {
959         
960         try {
961             _checkUserPermissions(webAsset, user, Config.getIntProperty("PERMISSION_WRITE"));
962         } catch (Exception JavaDoc ae) {
963             if (ae.getMessage().equals(WebKeys.USER_PERMISSIONS_EXCEPTION)) {
964                 SessionMessages.add(httpReq, "message", "message.insufficient.permissions.to." + action);
965             }
966             throw ae;
967         }
968     }
969     
970     protected void _copyPermissions(Inode from, Inode to) throws ActionException {
971         PermissionFactory.copyPermissions(from, to);
972     }
973     
974     private class ApplyChildrenPermissionThread extends Thread JavaDoc {
975         
976         private Inode parentInode = null;
977         private ActionRequest req = null;
978         
979         /**
980          * Create a new ApplyChildPermissionThread to update
981          * in background child inode permissions
982          * @param req The ActionRequest
983          * @param inodeList The childs inode list
984          */

985         public ApplyChildrenPermissionThread(ActionRequest req, Inode inode) {
986             super("Apply Children Permission Thread");
987             this.parentInode = inode;
988             this.req = req;
989         }
990         
991         public void run() {
992             if (req == null || parentInode == null || parentInode.getInode() == 0)
993                 return;
994             
995             int counterTransaction = 0;
996             int commitEvery = com.dotmarketing.util.Constants.APPLY_CHILD_PERMISSION_THREAD_COMMIT;
997             
998             DotHibernate.startTransaction();
999             
1000            List JavaDoc<Inode> inodeList = getChildren(parentInode);
1001            
1002            for(Inode inode : inodeList){
1003                try {
1004                    //Apply permission for every child
1005
_applyPermissionsToChild( req, inode);
1006                    
1007                    //Commit every n transaction
1008
if(counterTransaction >= commitEvery){
1009                        counterTransaction = 0;
1010                        DotHibernate.commitTransaction();
1011                        DotHibernate.startTransaction();
1012                    }
1013                    
1014                    counterTransaction++;
1015                    //sleep 100 millisecond to free CPU
1016
Thread.sleep(com.dotmarketing.util.Constants.APPLY_CHILD_PERMISSION_THREAD_SLEEP);
1017                    
1018                }catch(Exception JavaDoc e){
1019                    Logger.debug(ApplyChildrenPermissionThread.class,e.getMessage());
1020                }
1021            }
1022            
1023            DotHibernate.commitTransaction();
1024            
1025        }
1026        
1027        /**
1028         * This method add the permission to the child inodes recursive
1029         * @param req
1030         * @param inode
1031         */

1032        public final void _applyPermissionsToChild(ActionRequest req, Inode inode) {
1033            // Obtain de parameter that indicate if the permissions has been changed
1034
String JavaDoc permission_not_changed = req.getParameter(WebKeys.PERMISSION_NOT_CHANGED);
1035            String JavaDoc permission_is_new = req.getParameter(WebKeys.PERMISSION_IS_NEW);
1036            // If the permission has been changed, the method save the permission
1037
// otherwise not
1038
if ((UtilMethods.isSet(permission_not_changed) && Boolean.valueOf(permission_not_changed).booleanValue())
1039                    || (UtilMethods.isSet(permission_is_new) && Boolean.valueOf(permission_is_new).booleanValue())) {
1040                Inode origInode = inode;
1041                
1042                if(inode instanceof WebAsset){
1043                    Identifier id = new Identifier();
1044                    if (inode.getIdentifier() > 0) {
1045                        id.setInode(inode.getIdentifier());
1046                    } else {
1047                        id.setInode(IdentifierCache.getIdentifierByInodeFromCache(inode.getInode()).getInode());
1048                    }
1049                    
1050                    inode = id;
1051                    
1052                }
1053                
1054                Permission permission = null;
1055                
1056                java.util.List JavaDoc<Permission> currentPerms = PermissionFactory.getPermissions(inode);
1057                for(Permission perm : currentPerms){
1058                    PermissionFactory.deletePermission(perm);
1059                }
1060                                
1061                // adds read permissions to the inode
1062
String JavaDoc[] readPermissions = req.getParameterValues("read");
1063                if (readPermissions != null) {
1064                    for (int k = 0; k < readPermissions.length; k++) {
1065                        
1066                        Logger.debug(this, "_applyChildPermissions: Saving Read Permission for=" + readPermissions[k]);
1067                        
1068                        permission = new Permission(inode.getInode(), Long.parseLong(readPermissions[k]), Config.getIntProperty("PERMISSION_READ"));
1069                        PermissionFactory.savePermission(permission);
1070                    }
1071                }
1072                
1073                // adds write permissions to the inode
1074
String JavaDoc[] writePermissions = req.getParameterValues("write");
1075                if (writePermissions != null) {
1076                    for (int k = 0; k < writePermissions.length; k++) {
1077                        
1078                        Logger.debug(this, "_applyChildPermissions: Saving Write Permission for=" + writePermissions[k]);
1079                        
1080                        permission = new Permission(inode.getInode(), Long.parseLong(writePermissions[k]), Config.getIntProperty("PERMISSION_WRITE"));
1081                        PermissionFactory.savePermission(permission);
1082                    }
1083                }
1084                
1085                // adds publish permissions to the inode
1086
String JavaDoc[] publishPermissions = req.getParameterValues("publish");
1087                if (publishPermissions != null) {
1088                    for (int k = 0; k < publishPermissions.length; k++) {
1089                        
1090                        Logger.debug(this, "_applyChildPermissions: Saving Publish Permission for=" + publishPermissions[k]);
1091                        
1092                        permission = new Permission(inode.getInode(), Long.parseLong(publishPermissions[k]), Config.getIntProperty("PERMISSION_PUBLISH"));
1093                        PermissionFactory.savePermission(permission);
1094                    }
1095                }
1096                
1097                // Update the permissions cache
1098
if (origInode instanceof Folder) {
1099                    Folder f = (Folder) origInode;
1100                    PermissionCache.addToPermissionCache(f);
1101                } else if (origInode instanceof Host) {
1102                    Host host = (Host) origInode;
1103                    PermissionCache.addToPermissionCache(host);
1104                } else if (origInode instanceof WebAsset) {
1105                    WebAsset asset = (WebAsset) origInode;
1106                    PermissionCache.addToPermissionCache(asset);
1107                }
1108                
1109                if(origInode instanceof Contentlet){
1110                    Contentlet content = (Contentlet) origInode;
1111                    ContentletFactory.reIndexContentlet(content);
1112                }
1113                
1114                if ((req.getParameter("applyChildren") != null) && (req.getParameter("applyChildren").equals("on"))
1115                        && (inode instanceof Folder || inode instanceof Host || inode instanceof Structure)) {
1116                    
1117                    Logger.debug(this, "_applyChildPermissions: applying permissions to children");
1118                    
1119                    List JavaDoc<Inode> children = getChildren (inode);
1120                    
1121                    for(Object JavaDoc child: children){
1122                        _applyPermissionsToChild(req, (Inode) child);
1123                    }
1124                    
1125                }
1126            }
1127        }
1128        
1129        @SuppressWarnings JavaDoc("unchecked")
1130        private List JavaDoc<Inode> getChildren (Inode parent) {
1131            
1132            java.util.List JavaDoc<Inode> children = new ArrayList JavaDoc<Inode>();
1133            
1134            if (parent instanceof Folder || parent instanceof Host) {
1135                children.addAll(InodeFactory.getChildrenClass(parent, Folder.class));
1136                children.addAll(InodeFactory.getChildrenClass(parent, Contentlet.class));
1137                children.addAll(InodeFactory.getChildrenClass(parent, Container.class));
1138                children.addAll(InodeFactory.getChildrenClass(parent, Template.class));
1139                children.addAll(InodeFactory.getChildrenClass(parent, HTMLPage.class));
1140                children.addAll(InodeFactory.getChildrenClass(parent, Link.class));
1141                children.addAll(InodeFactory.getChildrenClass(parent, File.class));
1142            } else if (parent instanceof Structure) {
1143                children.addAll(InodeFactory.getInodesOfClassByCondition(Contentlet.class, "structure_inode = " + parent.getInode()));
1144            }
1145            
1146            return children;
1147            
1148        }
1149        
1150    }
1151    
1152}
Popular Tags