KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > dotmarketing > portlets > contentlet > action > EditContentletAction


1 package com.dotmarketing.portlets.contentlet.action;
2
3 import java.io.IOException JavaDoc;
4 import java.sql.Timestamp JavaDoc;
5 import java.text.SimpleDateFormat JavaDoc;
6 import java.util.ArrayList JavaDoc;
7 import java.util.Date JavaDoc;
8 import java.util.GregorianCalendar JavaDoc;
9 import java.util.HashMap JavaDoc;
10 import java.util.HashSet JavaDoc;
11 import java.util.List JavaDoc;
12 import java.util.Map JavaDoc;
13 import java.util.Set JavaDoc;
14 import java.util.regex.Matcher JavaDoc;
15 import java.util.regex.Pattern JavaDoc;
16
17 import javax.portlet.ActionRequest;
18 import javax.portlet.ActionResponse;
19 import javax.portlet.PortletConfig;
20 import javax.portlet.WindowState;
21 import javax.servlet.ServletOutputStream JavaDoc;
22 import javax.servlet.http.HttpServletRequest JavaDoc;
23 import javax.servlet.http.HttpServletResponse JavaDoc;
24
25 import org.apache.commons.beanutils.BeanUtils;
26 import org.apache.lucene.document.Document;
27 import org.apache.struts.Globals;
28 import org.apache.struts.action.ActionErrors;
29 import org.apache.struts.action.ActionForm;
30 import org.apache.struts.action.ActionMapping;
31 import org.apache.struts.action.ActionMessage;
32
33 import com.dotmarketing.beans.Host;
34 import com.dotmarketing.beans.Identifier;
35 import com.dotmarketing.beans.MultiTree;
36 import com.dotmarketing.beans.Tree;
37 import com.dotmarketing.cache.FieldsCache;
38 import com.dotmarketing.db.DotHibernate;
39 import com.dotmarketing.factories.HostFactory;
40 import com.dotmarketing.factories.IdentifierFactory;
41 import com.dotmarketing.factories.InodeFactory;
42 import com.dotmarketing.factories.MultiTreeFactory;
43 import com.dotmarketing.factories.RoleFactory;
44 import com.dotmarketing.factories.TreeFactory;
45 import com.dotmarketing.factories.WebAssetFactory;
46 import com.dotmarketing.portal.struts.DotPortletAction;
47 import com.dotmarketing.portal.struts.DotPortletActionInterface;
48 import com.dotmarketing.portlets.categories.model.Category;
49 import com.dotmarketing.portlets.containers.model.Container;
50 import com.dotmarketing.portlets.contentlet.factories.ContentletFactory;
51 import com.dotmarketing.portlets.contentlet.model.Contentlet;
52 import com.dotmarketing.portlets.contentlet.struts.ContentletForm;
53 import com.dotmarketing.portlets.entities.factories.EntityFactory;
54 import com.dotmarketing.portlets.entities.model.Entity;
55 import com.dotmarketing.portlets.files.model.File;
56 import com.dotmarketing.portlets.htmlpages.model.HTMLPage;
57 import com.dotmarketing.portlets.links.model.Link;
58 import com.dotmarketing.portlets.structure.factories.FieldFactory;
59 import com.dotmarketing.portlets.structure.factories.RelationshipFactory;
60 import com.dotmarketing.portlets.structure.factories.StructureFactory;
61 import com.dotmarketing.portlets.structure.model.ContentletRelationships;
62 import com.dotmarketing.portlets.structure.model.Field;
63 import com.dotmarketing.portlets.structure.model.Relationship;
64 import com.dotmarketing.portlets.structure.model.Structure;
65 import com.dotmarketing.portlets.structure.model.ContentletRelationships.ContentletRelationshipRecords;
66 import com.dotmarketing.portlets.workflows.factories.WorkflowsFactory;
67 import com.dotmarketing.portlets.workflows.model.WorkflowHistory;
68 import com.dotmarketing.portlets.workflows.model.WorkflowTask;
69 import com.dotmarketing.services.ContentletMapServices;
70 import com.dotmarketing.services.ContentletServices;
71 import com.dotmarketing.util.Config;
72 import com.dotmarketing.util.Logger;
73 import com.dotmarketing.util.LuceneHits;
74 import com.dotmarketing.util.PortletURLUtil;
75 import com.dotmarketing.util.UtilMethods;
76 import com.dotmarketing.util.WebKeys;
77 import com.dotmarketing.util.WebKeys.WorkflowStatuses;
78 import com.liferay.portal.NoSuchRoleException;
79 import com.liferay.portal.model.User;
80 import com.liferay.portal.util.Constants;
81 import com.liferay.portlet.ActionRequestImpl;
82 import com.liferay.portlet.ActionResponseImpl;
83 import com.liferay.util.servlet.SessionMessages;
84
85 public class EditContentletAction extends DotPortletAction implements DotPortletActionInterface {
86     
87     @SuppressWarnings JavaDoc("unchecked")
88     public void processAction(ActionMapping mapping, ActionForm form, PortletConfig config, ActionRequest req,
89             ActionResponse res) throws Exception JavaDoc {
90         // wraps request to get session object
91
boolean validate = true;
92         ActionRequestImpl reqImpl = (ActionRequestImpl) req;
93         HttpServletRequest JavaDoc httpReq = reqImpl.getHttpServletRequest();
94         
95         Logger.debug(this, "############################# Contentlet");
96         
97         String JavaDoc cmd = req.getParameter(Constants.CMD);
98         String JavaDoc referer = req.getParameter("referer");
99         
100         Logger.debug(this, "EditContentletAction cmd=" + cmd);
101         
102         DotHibernate.startTransaction();
103         
104         User user = _getUser(req);
105         
106         
107         try {
108             Logger.debug(this, "Calling Retrieve method");
109             
110             _retrieveWebAsset(req, res, config, form, user);
111             
112             
113         } catch (Exception JavaDoc ae) {
114             _handleException(ae, req);
115             return;
116         }
117         
118         /*
119          * We are editing the contentlet
120          */

121         if ((cmd != null) && cmd.equals(Constants.EDIT)) {
122             try {
123                 Logger.debug(this, "Calling Edit Method");
124                 
125                 _editWebAsset(req, res, config, form, user);
126                 
127             } catch (Exception JavaDoc ae) {
128                 if ((referer != null) && (referer.length() != 0)) {
129                     if (ae.getMessage().equals(WebKeys.EDIT_ASSET_EXCEPTION)) {
130                         // The web asset edit threw an exception because it's
131
// locked so it should redirect back with message
132
java.util.Map JavaDoc<String JavaDoc, String JavaDoc[]> params = new java.util.HashMap JavaDoc<String JavaDoc, String JavaDoc[]>();
133                         params.put("struts_action", new String JavaDoc[] { "/ext/director/direct" });
134                         params.put("cmd", new String JavaDoc[] { "editContentlet" });
135                         params.put("contentlet", new String JavaDoc[] { req.getParameter("inode") });
136                         params.put("container",
137                                 new String JavaDoc[] { (req.getParameter("contentcontainer_inode") != null) ? req
138                                         .getParameter("contentcontainer_inode") : "0" });
139                         params.put("htmlPage", new String JavaDoc[] { (req.getParameter("htmlpage_inode") != null) ? req
140                                 .getParameter("htmlpage_inode") : "0" });
141                         params.put("referer", new String JavaDoc[] { java.net.URLEncoder.encode(referer, "UTF-8") });
142                         
143                         String JavaDoc directorURL = com.dotmarketing.util.PortletURLUtil.getActionURL(httpReq,
144                                 WindowState.MAXIMIZED.toString(), params);
145                         
146                         _sendToReferral(req, res, directorURL);
147                     } else {
148                         _handleException(ae, req);
149                     }
150                 } else
151                     _handleException(ae, req);
152                 return;
153             }
154         }
155         
156         /*
157          * We are editing the contentlet
158          */

159         if ((cmd != null)
160                 && (cmd.equals(com.dotmarketing.util.Constants.NEW) || cmd
161                         .equals(com.dotmarketing.util.Constants.NEW_EDIT))) {
162             try {
163                 Logger.debug(this, "Calling Edit Method");
164                 
165                 _newContent(req, res, config, form, user);
166                 
167             } catch (Exception JavaDoc ae) {
168                 if ((referer != null) && (referer.length() != 0)) {
169                     if (ae.getMessage().equals(WebKeys.EDIT_ASSET_EXCEPTION)) {
170                         // The web asset edit threw an exception because it's
171
// locked so it should redirect back with message
172
java.util.Map JavaDoc<String JavaDoc, String JavaDoc[]> params = new java.util.HashMap JavaDoc<String JavaDoc, String JavaDoc[]>();
173                         params.put("struts_action", new String JavaDoc[] { "/ext/director/direct" });
174                         params.put("cmd", new String JavaDoc[] { "editContentlet" });
175                         params.put("contentlet", new String JavaDoc[] { req.getParameter("inode") });
176                         params.put("container",
177                                 new String JavaDoc[] { (req.getParameter("contentcontainer_inode") != null) ? req
178                                         .getParameter("contentcontainer_inode") : "0" });
179                         params.put("htmlPage", new String JavaDoc[] { (req.getParameter("htmlpage_inode") != null) ? req
180                                 .getParameter("htmlpage_inode") : "0" });
181                         params.put("referer", new String JavaDoc[] { java.net.URLEncoder.encode(referer, "UTF-8") });
182                         
183                         String JavaDoc directorURL = com.dotmarketing.util.PortletURLUtil.getActionURL(httpReq,
184                                 WindowState.MAXIMIZED.toString(), params);
185                         
186                         _sendToReferral(req, res, directorURL);
187                     } else if (ae.getMessage().equals(WebKeys.USER_PERMISSIONS_EXCEPTION)) {
188                         _sendToReferral(req, res, referer);
189                     } else {
190                         _handleException(ae, req);
191                     }
192                 } else
193                     _handleException(ae, req);
194                 return;
195             }
196         }
197         
198         /*
199          * If we are updating the contentlet, copy the information from the
200          * struts bean to the hbm inode and run the update action and return to
201          * the list
202          */

203         if ((cmd != null) && cmd.equals(Constants.ADD)) {
204             try {
205                 validate = _validContent(req, res, config, form, user);
206                 if (validate) {
207                     Logger.debug(this, "Calling Save Method");
208                     
209                     _saveWebAsset(req, res, config, form, user);
210                     
211                     Logger.debug(this, "HTMLPage inode=" + req.getParameter("htmlpage_inode"));
212                     Logger.debug(this, "Container inode=" + req.getParameter("contentcontainer_inode"));
213                     
214                     if (req.getParameter("htmlpage_inode") != null
215                             && req.getParameter("contentcontainer_inode") != null) {
216                         try {
217                             Logger.debug(this, "I'm setting my contentlet parents");
218                             _addToParents(req, res, config, form, user);
219                             
220                         } catch (Exception JavaDoc ae) {
221                             _handleException(ae, req);
222                             return;
223                         }
224                     }
225                     
226                     BeanUtils.copyProperties(form, req.getAttribute(WebKeys.CONTENTLET_FORM_EDIT));
227                     
228                     try {
229                         String JavaDoc subcmd = req.getParameter("subcmd");
230                         if ((subcmd != null) && subcmd.equals(com.dotmarketing.util.Constants.PUBLISH)) {
231                             Logger.debug(this, "Calling Publish Method");
232                             _publishWebAsset(req, res, config, form, user, WebKeys.CONTENTLET_FORM_EDIT);
233                         }
234                         
235                         if ((subcmd != null) && subcmd.equals(com.dotmarketing.util.Constants.ASSIGNTO)) {
236                             Logger.debug(this, "Calling Publish Method");
237                             _assignWebAsset(req, res, config, form, user, WebKeys.CONTENTLET_FORM_EDIT);
238                         }
239                         
240                         String JavaDoc language = req.getParameter("languageId");
241                         Logger.debug(this, "AFTER PUBLISH LANGUAGE=" + language);
242                         
243                         if (UtilMethods.isSet(language) && referer.indexOf("language") > -1) {
244                             Logger.debug(this, "Replacing referer language=" + referer);
245                             referer = referer.replaceAll("language=([0-9])*", "language=" + language);
246                             Logger.debug(this, "Referer after being replaced=" + referer);
247                         }
248                         _sendToReferral(req, res, referer);
249                         
250                     }catch(Exception JavaDoc e){
251                         SessionMessages.add(req, "message","message.saved.but.not.publish");
252                         
253                     }
254                 }
255             } catch (Exception JavaDoc ae) {
256                 _handleException(ae, req);
257             }
258         }
259         /*
260          * If we are deleteing the contentlet, run the delete action and return
261          * to the list
262          *
263          */

264         else if ((cmd != null) && cmd.equals(Constants.DELETE)) {
265             try {
266                 Logger.debug(this, "Calling Delete Method");
267                 
268                 _deleteWebAsset(req, res, config, form, user, WebKeys.CONTENTLET_EDIT);
269                 
270             } catch (Exception JavaDoc ae) {
271                 _handleException(ae, req);
272                 return;
273             }
274             _sendToReferral(req, res, referer);
275         }
276         /*
277          * If we are undeleting the container, run the undelete action and
278          * return to the list
279          *
280          */

281         else if ((cmd != null) && cmd.equals(com.dotmarketing.util.Constants.UNDELETE)) {
282             try {
283                 Logger.debug(this, "Calling UnDelete Method");
284                 
285                 _undeleteWebAsset(req, res, config, form, user, WebKeys.CONTENTLET_EDIT);
286                 
287             } catch (Exception JavaDoc ae) {
288                 _handleException(ae, req);
289                 return;
290             }
291             _sendToReferral(req, res, referer);
292             
293         }
294         /*
295          * If we are deleting the container version, run the deeleteversion
296          * action and return to the list
297          */

298         else if ((cmd != null) && cmd.equals(com.dotmarketing.util.Constants.DELETEVERSION)) {
299             try {
300                 Logger.debug(this, "Calling Delete Version Method");
301                 
302                 _deleteVersionWebAsset(req, res, config, form, user, WebKeys.CONTENTLET_EDIT);
303                 
304             } catch (Exception JavaDoc ae) {
305                 _handleException(ae, req);
306                 return;
307             }
308             _sendToReferral(req, res, referer);
309         }
310         /*
311          * If we are unpublishing the container, run the unpublish action and
312          * return to the list
313          */

314         else if ((cmd != null) && cmd.equals(com.dotmarketing.util.Constants.UNPUBLISH)) {
315             try {
316                 Logger.debug(this, "Calling Unpublish Method");
317                 
318                 _unPublishWebAsset(req, res, config, form, user, WebKeys.CONTENTLET_EDIT);
319                 
320             } catch (Exception JavaDoc ae) {
321                 _handleException(ae, req);
322                 return;
323             }
324             _sendToReferral(req, res, referer);
325             
326         }
327         /*
328          * If we are getting the container version back, run the getversionback
329          * action and return to the list
330          */

331         else if ((cmd != null) && cmd.equals(com.dotmarketing.util.Constants.GETVERSIONBACK)) {
332             try {
333                 Logger.debug(this, "Calling Get Version Back Method");
334                 
335                 _getVersionBackWebAsset(req, res, config, form, user);
336             } catch (Exception JavaDoc ae) {
337                 _handleException(ae, req);
338                 return;
339             }
340             
341             Contentlet workingContentlet = (Contentlet) req.getAttribute(WebKeys.CONTENTLET_EDIT);
342             
343             /*
344              href = "<portlet:actionURL>";
345              href += "<portlet:param name='struts_action' value='/ext/contentlet/edit_contentlet' />";
346              href += "<portlet:param name='cmd' value='edit' />";
347              href += "<portlet:param name='referer' value='<%=referer%>' />";
348              href += "</portlet:actionURL>";
349              */

350             
351             HashMap JavaDoc params = new HashMap JavaDoc ();
352             params.put("struts_action", new String JavaDoc [] { "/ext/contentlet/edit_contentlet" });
353             params.put("inode", new String JavaDoc [] { String.valueOf(workingContentlet.getInode()) });
354             params.put("cmd", new String JavaDoc [] { "edit" });
355             params.put("referer", new String JavaDoc [] { referer });
356             referer = PortletURLUtil.getActionURL(req, WindowState.MAXIMIZED.toString(), params);
357             
358             _sendToReferral(req, res, referer);
359         }
360         /*
361          * If we are getting the container versions, run the assetversions
362          * action and return to the list
363          */

364         else if ((cmd != null) && cmd.equals(com.dotmarketing.util.Constants.ASSETVERSIONS)) {
365             try {
366                 Logger.debug(this, "Calling Get Versions Method");
367                 
368                 _getVersionsWebAsset(req, res, config, form, user, WebKeys.CONTENTLET_EDIT, WebKeys.CONTENTLET_VERSIONS);
369                 
370             } catch (Exception JavaDoc ae) {
371                 _handleException(ae, req);
372                 return;
373             }
374         }
375         /*
376          * If we are unlocking the container, run the unlock action and return
377          * to the list
378          */

379         else if ((cmd != null) && cmd.equals(com.dotmarketing.util.Constants.UNLOCK)) {
380             try {
381                 Logger.debug(this, "Calling Unlock Method");
382                 
383                 _unLockWebAsset(req, res, config, form, user, WebKeys.CONTENTLET_EDIT);
384                 
385             } catch (Exception JavaDoc ae) {
386                 _handleException(ae, req);
387                 return;
388             }
389             _sendToReferral(req, res, referer);
390             
391         }else if(cmd != null && cmd.equals("export")){
392             
393             boolean showDeleted = Boolean.parseBoolean( req.getParameter("showDeleted"));
394             String JavaDoc categories = req.getParameter("expCategoriesValues");
395             String JavaDoc fields = req.getParameter("expFieldsValues");
396             String JavaDoc structureInode = req.getParameter("expStructureInode");
397             
398             ActionResponseImpl resImpl = (ActionResponseImpl) res;
399             HttpServletResponse JavaDoc response = resImpl.getHttpServletResponse();
400             downloadToExcel(structureInode, fields, categories, showDeleted, response);
401             setForward(req,"portlet.ext.contentlet.view_contentlets");
402             
403         }
404         /*
405          * If we are copying the container, run the copy action and return to
406          * the list
407          */

408         else if ((cmd != null) && cmd.equals(com.dotmarketing.util.Constants.COPY)) {
409             try {
410                 Logger.debug(this, "Calling Copy Method");
411                 _copyWebAsset(req, res, config, form, user);
412             } catch (Exception JavaDoc ae) {
413                 _handleException(ae, req);
414             }
415             _sendToReferral(req, res, referer);
416         } else
417             Logger.debug(this, "Unspecified Action");
418         _loadForm(req, res, config, form, user, validate);
419         DotHibernate.commitTransaction();
420         setForward(req, "portlet.ext.contentlet.edit_contentlet");
421     }
422     
423     // /// ************** ALL METHODS HERE *************************** ////////
424

425     private void _retrieveWebAsset(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form,
426             User user) throws Exception JavaDoc {
427         String JavaDoc inode = req.getParameter("inode");
428         long inodeLong = (UtilMethods.isSet(inode) ? Long.parseLong(inode) : 0);
429         Contentlet contentlet = ContentletFactory.getContentlet(inodeLong);
430         
431         
432         req.setAttribute(WebKeys.FatContentlet.CONTENTLET, contentlet);
433         // Load the childs related to this contentlet
434
Structure structure = contentlet.getStructure();
435         List JavaDoc<Field> list = FieldsCache.getFieldsByStructureInode(structure.getInode());
436         for (Field field : list) {
437             if (field.getFieldType().equals(WebKeys.TypeField.IMAGE)
438                     || field.getFieldType().equals(WebKeys.TypeField.FILE)) {
439                 String JavaDoc relationName = field.getFieldRelationType();
440                 Identifier id = (Identifier) InodeFactory.getChildOfClassByRelationType(contentlet, Identifier.class,
441                         relationName);
442                 if (id.getInode() != 0) {
443                     File image = (File) IdentifierFactory.getWorkingChildOfClass(id, File.class);
444                     BeanUtils.setProperty(contentlet, field.getFieldContentlet(), image.getInode());
445                 }
446             } else if (field.getFieldType().equals(WebKeys.TypeField.LINK)) {
447                 String JavaDoc relationName = field.getFieldRelationType();
448                 Identifier id = (Identifier) InodeFactory.getChildOfClassByRelationType(contentlet, Identifier.class,
449                         relationName);
450                 if (id.getInode() != 0) {
451                     Link link = (Link) IdentifierFactory.getWorkingChildOfClass(id, Link.class);
452                     BeanUtils.setProperty(contentlet, field.getFieldContentlet(), link.getInode());
453                 }
454             }
455         }
456         
457         // OLD RETRIEVE WEB ASSETS
458
super._retrieveWebAsset(req, res, config, form, user, Contentlet.class, WebKeys.CONTENTLET_EDIT);
459         // gets the new information for the container from the request object
460
Contentlet sibblingContentlet = (Contentlet) InodeFactory.getInode(req.getParameter("sibbling"),
461                 Contentlet.class);
462         req.setAttribute(WebKeys.CONTENTLET_SIBBLING_EDIT, sibblingContentlet);
463         
464         // Contententlets Relationships
465
Structure st = contentlet.getStructure();
466         if (st == null || st.getInode() == 0) {
467             Long JavaDoc selectedStructure = 0L;
468             if (UtilMethods.isSet(req.getParameter("selectedStructure"))) {
469                 selectedStructure = Long.parseLong(req.getParameter("selectedStructure"));
470                 st = (Structure) InodeFactory.getInode(selectedStructure, Structure.class);
471             } else if (UtilMethods.isSet(req.getParameter("contentcontainer_inode"))) {
472                 Long JavaDoc containerInode = Long.parseLong(req.getParameter("contentcontainer_inode"));
473                 Container container = (Container) InodeFactory.getInode(containerInode, Container.class);
474                 st = (Structure) InodeFactory.getParentOfClass(container, Structure.class);
475             }
476             
477         }
478         
479         _loadContentletRelationshipsInRequest(req, contentlet, st);
480         
481         // Permission variable
482
if (contentlet.getInode() > 0){
483             req.setAttribute(WebKeys.PERMISSION_INODE_EDIT, contentlet);
484         }else if (sibblingContentlet.getInode() > 0){
485             // If the contentlet is a copy in other language we use the
486
// permissions of the sibbling contentlet
487
req.setAttribute(WebKeys.PERMISSION_INODE_EDIT, sibblingContentlet);
488         } else {
489             // Use the html page that we are on for permissions, if it is
490
// passed.
491
// else, use the structure.
492

493             HTMLPage permParent = (HTMLPage) InodeFactory.getInode(req.getParameter("htmlpage_inode"), HTMLPage.class);
494             if (permParent.getInode() == 0) {
495                 req.setAttribute(WebKeys.PERMISSION_INODE_EDIT, st);
496             } else {
497                 req.setAttribute(WebKeys.PERMISSION_INODE_EDIT, permParent);
498             }
499             
500             // if the html page is new the parentfolder permissions are used
501

502         }
503         // Asset Versions to list in the versions tab
504
req.setAttribute(WebKeys.VERSIONS_INODE_EDIT, contentlet);
505         
506     }
507     
508     private void _loadContentletRelationshipsInRequest(ActionRequest request, Contentlet contentlet, Structure structure) {
509         ContentletRelationships cRelationships = new ContentletRelationships(contentlet);
510         List JavaDoc<ContentletRelationshipRecords> matches = cRelationships.getRelationshipsRecords();
511         List JavaDoc<Relationship> relationships = RelationshipFactory.getAllRelationshipsByStructure(structure);
512         for (Relationship rel : relationships) {
513             if (RelationshipFactory.isASibblingRelationship(rel, structure)) {
514                 ContentletRelationshipRecords records = cRelationships.new ContentletRelationshipRecords(rel, false);
515                 Set JavaDoc<Contentlet> contSet = new HashSet JavaDoc ();
516                 contSet.addAll(RelationshipFactory.getAllRelationshipRecords(rel, contentlet, false));
517                 contSet.addAll(RelationshipFactory.getAllRelationshipRecords(rel, contentlet, true));
518                 List JavaDoc<Contentlet> conts = new ArrayList JavaDoc ();
519                 conts.addAll(contSet);
520                 records.setRecords(conts);
521                 matches.add(records);
522             }
523             if (RelationshipFactory.isChildOfTheRelationship(rel, structure)) {
524                 ContentletRelationshipRecords records = cRelationships.new ContentletRelationshipRecords(rel, false);
525                 List JavaDoc<Contentlet> conts = RelationshipFactory.getAllRelationshipRecords(rel, contentlet, false);
526                 records.setRecords(conts);
527                 matches.add(records);
528             }
529             if (RelationshipFactory.isParentOfTheRelationship(rel, structure)) {
530                 ContentletRelationshipRecords records = cRelationships.new ContentletRelationshipRecords(rel, true);
531                 List JavaDoc<Contentlet> conts = RelationshipFactory.getAllRelationshipRecords(rel, contentlet, true);
532                 records.setRecords(conts);
533                 matches.add(records);
534             }
535             
536         }
537         request.setAttribute(WebKeys.CONTENTLET_RELATIONSHIPS_EDIT, cRelationships);
538         
539     }
540     
541     private void _addToParents(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user)
542     throws Exception JavaDoc {
543         
544         // wraps request to get session object
545
ActionRequestImpl reqImpl = (ActionRequestImpl) req;
546         HttpServletRequest JavaDoc httpReq = reqImpl.getHttpServletRequest();
547         
548         Logger.debug(this, "Inside AddContentletToParentsAction");
549         
550         Contentlet contentlet = (Contentlet) req.getAttribute(WebKeys.CONTENTLET_FORM_EDIT);
551         // Contentlet currentContentlet = (Contentlet)
552
// req.getAttribute(WebKeys.CONTENTLET_EDIT);
553
Contentlet currentContentlet = (Contentlet) req.getAttribute(WebKeys.FatContentlet.CONTENTLET);
554         
555         Logger.debug(this, "currentContentlet inode=" + currentContentlet.getInode());
556         Logger.debug(this, "contentlet inode=" + contentlet.getInode());
557         
558         // it's a new contentlet. we should add to parents
559
// if it's a version the parents get copied on save asset method
560
if (currentContentlet.getInode() == contentlet.getInode()) {
561             String JavaDoc htmlpage_inode = req.getParameter("htmlpage_inode");
562             String JavaDoc contentcontainer_inode = req.getParameter("contentcontainer_inode");
563             HTMLPage htmlParent = (HTMLPage) InodeFactory.getInode(htmlpage_inode, HTMLPage.class);
564             Logger.debug(this, "Added Contentlet to parent=" + htmlParent.getInode());
565             Container containerParent = (Container) InodeFactory.getInode(contentcontainer_inode, Container.class);
566             Logger.debug(this, "Added Contentlet to parent=" + containerParent.getInode());
567             
568             Identifier iden = IdentifierFactory.getParentIdentifier(contentlet);
569             
570             if (htmlParent.getInode() != 0 && containerParent.getInode() != 0 && contentlet.getInode() != 0) {
571                 Identifier htmlPageIdentifier = IdentifierFactory.getIdentifierByWebAsset(htmlParent);
572                 Identifier containerIdentifier = IdentifierFactory.getIdentifierByWebAsset(containerParent);
573                 Identifier contenletIdentifier = IdentifierFactory.getIdentifierByWebAsset(contentlet);
574                 MultiTree multiTree = MultiTreeFactory.getMultiTree(htmlPageIdentifier, containerIdentifier,
575                         contenletIdentifier);
576                 Logger.debug(this, "Getting multitree for=" + htmlParent.getInode() + " ," + containerParent.getInode()
577                         + " ," + iden.getInode());
578                 Logger.debug(this, "Coming from multitree parent1=" + multiTree.getParent1() + " parent2="
579                         + multiTree.getParent2());
580                 
581                 if (multiTree.getParent1() == 0 && multiTree.getParent2() == 0 && multiTree.getChild() == 0) {
582                     
583                     Logger.debug(this, "MTree is null!!! Creating new one!");
584                     
585                     MultiTree mTree = new MultiTree(htmlPageIdentifier.getInode(), containerIdentifier.getInode(),
586                             contenletIdentifier.getInode());
587                     MultiTreeFactory.saveMultiTree(mTree);
588                 }
589             }
590             SessionMessages.add(httpReq, "message", "message.contentlet.add.parents");
591         }
592     }
593     
594     private void _newContent(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user)
595     throws Exception JavaDoc {
596         
597         // wraps request to get session object
598
ActionRequestImpl reqImpl = (ActionRequestImpl) req;
599         HttpServletRequest JavaDoc httpReq = reqImpl.getHttpServletRequest();
600         
601         //Contentlet Form
602
ContentletForm cf = (ContentletForm) form;
603         
604         String JavaDoc cmd = req.getParameter(Constants.CMD);
605         String JavaDoc inode = req.getParameter("inode");
606         long inodeLong = (UtilMethods.isSet(inode) ? Long.parseLong(inode) : 0);
607         Contentlet contentlet = ContentletFactory.getContentlet(inodeLong);
608         req.setAttribute(WebKeys.FatContentlet.CONTENTLET, contentlet);
609         Structure structure = contentlet.getStructure();
610         
611         Long JavaDoc selectedStructure = 0L;
612         if (UtilMethods.isSet(req.getParameter("selectedStructure"))) {
613             selectedStructure = Long.parseLong(req.getParameter("selectedStructure"));
614             structure = (Structure) InodeFactory.getInode(selectedStructure, Structure.class);
615         } else if (cmd.equals("newedit")) {
616             Long JavaDoc containerInode = Long.parseLong(req.getParameter("contentcontainer_inode"));
617             Container container = (Container) InodeFactory.getInode(containerInode, Container.class);
618             structure = (Structure) InodeFactory.getParentOfClass(container, Structure.class);
619             contentlet.setStructureInode(structure.getInode());
620         }
621         
622         // Checking permissions to add new of structure selected
623
_checkWritePermissions(structure, user, httpReq);
624         
625         List JavaDoc<Field> list = (List JavaDoc<Field>) FieldsCache.getFieldsByStructureInode(structure.getInode());
626         for (Field field : list) {
627             Object JavaDoc value = null;
628             String JavaDoc defaultValue = field.getDefaultValue();
629             if (UtilMethods.isSet(defaultValue)) {
630                 String JavaDoc typeField = field.getFieldContentlet();
631                 if (typeField.startsWith("bool")) {
632                     value = defaultValue;
633                 } else if (typeField.startsWith("date")) {
634                     SimpleDateFormat JavaDoc dateFormatter = new SimpleDateFormat JavaDoc("yyyy-MM-dd HH:mm:ss");
635                     String JavaDoc date = defaultValue;
636                     value = dateFormatter.parse(date);
637                 } else if (typeField.startsWith("float")) {
638                     value = defaultValue;
639                 } else if (typeField.startsWith("integer")) {
640                     value = defaultValue;
641                 } else if (typeField.startsWith("text")) {
642                     value = defaultValue;
643                 }
644                 
645                 if (field.getFieldType().equals(WebKeys.TypeField.IMAGE)
646                         || field.getFieldType().equals(WebKeys.TypeField.FILE)
647                         || field.getFieldType().equals(WebKeys.TypeField.LINK)) {
648                     try {
649                         Identifier id = (Identifier) InodeFactory.getInode((String JavaDoc) value, Identifier.class);
650                         if (id.getInode() != 0) {
651                             if (field.getFieldType().equals(WebKeys.TypeField.IMAGE)) {
652                                 File inodeAux = (File) IdentifierFactory.getWorkingChildOfClass(id, File.class);
653                                 value = inodeAux.getInode();
654                             } else if (field.getFieldType().equals(WebKeys.TypeField.FILE)) {
655                                 File inodeAux = (File) IdentifierFactory.getWorkingChildOfClass(id, File.class);
656                                 value = inodeAux.getInode();
657                             } else if (field.getFieldType().equals(WebKeys.TypeField.LINK)) {
658                                 Link inodeAux = (Link) IdentifierFactory.getWorkingChildOfClass(id, Link.class);
659                                 value = inodeAux.getInode();
660                             }
661                         }
662                     } catch (Exception JavaDoc ex) {
663                         Logger.debug(this, ex.toString());
664                     }
665                 }
666                 BeanUtils.setProperty(contentlet, typeField, value);
667             }
668         }
669         
670         //Setting review intervals form properties
671
if (structure.getReviewInterval() != null) {
672             String JavaDoc interval = structure.getReviewInterval();
673             Pattern JavaDoc p = Pattern.compile("(\\d+)([dmy])");
674             Matcher JavaDoc m = p.matcher(interval);
675             boolean b = m.matches();
676             if (b) {
677                 cf.setReviewContent(true);
678                 String JavaDoc g1 = m.group(1);
679                 String JavaDoc g2 = m.group(2);
680                 cf.setReviewIntervalNum(g1);
681                 cf.setReviewIntervalSelect(g2);
682             }
683         }
684         
685     }
686     
687     @SuppressWarnings JavaDoc("unchecked")
688     public void _editWebAsset(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user)
689     throws Exception JavaDoc {
690         
691         ContentletForm cf = (ContentletForm) form;
692         
693         Contentlet contentlet = (Contentlet) req.getAttribute(WebKeys.CONTENTLET_EDIT);
694         
695         GregorianCalendar JavaDoc cal = new GregorianCalendar JavaDoc();
696         if (contentlet.getModDate() == null) {
697             contentlet.setModDate(cal.getTime());
698         }
699         
700         super._editWebAsset(req, res, config, form, user, WebKeys.CONTENTLET_EDIT);
701         
702         Logger.debug(this, "EditContentletAction: contentletInode=" + contentlet.getInode());
703         
704         req.setAttribute(WebKeys.CONTENTLET_EDIT, contentlet);
705         
706         BeanUtils.copyProperties(form, req.getAttribute(WebKeys.CONTENTLET_EDIT));
707         
708         cf.setHostInode(HostFactory.getParentHost(contentlet).getInode());
709         
710         if (contentlet.getReviewInterval() != null) {
711             String JavaDoc interval = contentlet.getReviewInterval();
712             Pattern JavaDoc p = Pattern.compile("(\\d+)([dmy])");
713             Matcher JavaDoc m = p.matcher(interval);
714             boolean b = m.matches();
715             if (b) {
716                 cf.setReviewContent(true);
717                 String JavaDoc g1 = m.group(1);
718                 String JavaDoc g2 = m.group(2);
719                 cf.setReviewIntervalNum(g1);
720                 cf.setReviewIntervalSelect(g2);
721             }
722         }
723         
724     }
725     
726     private boolean _populateContent(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form,
727             User user, Contentlet contentlet) throws Exception JavaDoc {
728         try {
729             ActionErrors ae = new ActionErrors();
730             Structure structure = contentlet.getStructure();
731             if (structure.getInode() == 0) {
732                 String JavaDoc selectedStructure = req.getParameter("selectedStructure");
733                 if (UtilMethods.isSet(selectedStructure)) {
734                     structure = StructureFactory.getStructureByInode(Long.parseLong(selectedStructure));
735                 }
736             }
737             
738             List JavaDoc fields = FieldsCache.getFieldsByStructureInode(structure.getInode());
739             for (int i = 0; i < fields.size(); i++) {
740                 Field field = (Field) fields.get(i);
741                 if (_validate(req, field, ae)) {
742                     _saveField(req, field, contentlet);
743                 }
744             }
745             ContentletForm contentletForm = (ContentletForm) form;
746             contentlet.setTitle(contentletForm.getTitle());
747             contentlet.setFriendlyName(contentletForm.getTitle());
748             contentlet.setStructureInode(Long.parseLong(req.getParameter("selectedStructure")));
749             contentlet.setLanguageId(contentletForm.getLanguageId());
750             contentlet.setEnabledWysiwyg(contentletForm.getEnabledWysiwyg());
751             
752             contentlet.setModDate(new Date JavaDoc());
753             if (ae != null && ae.size() > 0) {
754                 req.setAttribute(Globals.ERROR_KEY, ae);
755                 return false;
756             }
757             ContentletFactory.save(contentlet);
758             for (int i = 0; i < fields.size(); i++) {
759                 Field field = (Field) fields.get(i);
760                 if (_validate(req, field, ae)) {
761                     _saveChildren(req, field, contentlet);
762                 }
763             }
764             return true;
765         } catch (Exception JavaDoc ex) {
766             return false;
767         }
768     }
769     
770     @SuppressWarnings JavaDoc("unchecked")
771     private boolean _validContent(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form,
772             User user) throws Exception JavaDoc {
773         try {
774             ActionErrors ae = new ActionErrors();
775             Contentlet contentlet = (Contentlet) req.getAttribute(WebKeys.FatContentlet.CONTENTLET);
776             Structure structure = contentlet.getStructure();
777             if (structure.getInode() == 0) {
778                 String JavaDoc selectedStructure = req.getParameter("selectedStructure");
779                 if (UtilMethods.isSet(selectedStructure)) {
780                     structure = StructureFactory.getStructureByInode(Long.parseLong(selectedStructure));
781                 }
782             }
783             
784             List JavaDoc fields = FieldsCache.getFieldsByStructureInode(structure.getInode());
785             ContentletForm contentletForm = (ContentletForm) form;
786             if (contentletForm.getHostInode() <= 0) {
787                 ae.add(Globals.ERROR_KEY, new ActionMessage("message.host.required", "host"));
788             }
789             
790             for (int i = 0; i < fields.size(); i++) {
791                 Field field = (Field) fields.get(i);
792                 _validate(req, field, ae);
793             }
794             
795             // Validating relationships
796
Set JavaDoc<String JavaDoc> keys = req.getParameterMap().keySet();
797             for (String JavaDoc key : keys) {
798                 if (key.startsWith("rel_") && key.endsWith("_inodes")) {
799                     boolean hasParent = key.indexOf("_P_") != -1;
800                     String JavaDoc inodesSt = (String JavaDoc) req.getParameter(key);
801                     String JavaDoc[] inodes = inodesSt.split(",");
802                     Relationship relationship = (Relationship) InodeFactory.getInode(inodes[0], Relationship.class);
803                     if (relationship.isChildRequired() && hasParent && inodes.length < 2) {
804                         ae.add(Globals.ERROR_KEY, new ActionMessage("message.relationship.required", "relationships"));
805                         break;
806                     }
807                     if (relationship.isParentRequired() && !hasParent && inodes.length < 2) {
808                         ae.add(Globals.ERROR_KEY, new ActionMessage("message.relationship.required", "relationships"));
809                         break;
810                     }
811                 }
812             }
813             
814             // Actual Date
815
contentlet.setModDate(new Date JavaDoc());
816             if (ae != null && ae.size() > 0) {
817                 req.setAttribute(Globals.ERROR_KEY, ae);
818                 return false;
819             }
820             
821             return true;
822         } catch (Exception JavaDoc ex) {
823             return false;
824         }
825     }
826     
827     private boolean _validate(ActionRequest req, Field field, ActionErrors ae) {
828         try {
829             
830             boolean validate = true;
831             String JavaDoc value = req.getParameter(field.getFieldContentlet());
832             if (field.isRequired()) {
833                 if (!UtilMethods.isSet(value)) {
834                     validate = false;
835                     ae.add(Globals.ERROR_KEY, new ActionMessage("message.contentlet.required", field.getFieldName()));
836                 }
837                 if(field.getFieldType().equals(WebKeys.TypeField.IMAGE))
838                     if (value.trim().equals("0"))
839                         ae.add(Globals.ERROR_KEY, new ActionMessage("message.contentlet.required", field.getFieldName()));
840                 if(field.getFieldType().equals(WebKeys.TypeField.LINK))
841                     if (value.trim().equals("0"))
842                         ae.add(Globals.ERROR_KEY, new ActionMessage("message.contentlet.required", field.getFieldName()));
843                 if(field.getFieldType().equals(WebKeys.TypeField.FILE))
844                     if (value.trim().equals("0"))
845                         ae.add(Globals.ERROR_KEY, new ActionMessage("message.contentlet.required", field.getFieldName()));
846                 //WYSIWYG patch for blank content
847
if(field.getFieldType().equals(WebKeys.TypeField.WYSIWYG))
848                     if (value.trim().toLowerCase().equals("<br>"))
849                         ae.add(Globals.ERROR_KEY, new ActionMessage("message.contentlet.required", field.getFieldName()));
850             }
851             
852             String JavaDoc dataType = (field.getFieldContentlet() != null) ? field.getFieldContentlet()
853                     .replaceAll("[0-9]*", "") : "";
854                     if (UtilMethods.isSet(value) && dataType.equals("text")) {
855                         if (value.length() > 255) {
856                             validate = false;
857                             ae.add(Globals.ERROR_KEY, new ActionMessage("message.contentlet.maxlength", field.getFieldName(),
858                             "255"));
859                         }
860                     }
861                     String JavaDoc regext = field.getRegexCheck();
862                     if (UtilMethods.isSet(regext)) {
863                         if (UtilMethods.isSet(value)) {
864                             boolean match = Pattern.matches(regext, value);
865                             if (!match) {
866                                 validate = false;
867                                 ae.add(Globals.ERROR_KEY, new ActionMessage("message.contentlet.format", field.getFieldName()));
868                             }
869                         }
870                     }
871                     return validate;
872         } catch (Exception JavaDoc ex) {
873             Logger.debug(this, ex.toString());
874             return false;
875         }
876     }
877     
878     private void _saveField(ActionRequest req, Field field, Contentlet contentlet) {
879         try {
880             String JavaDoc value = req.getParameter(field.getFieldContentlet());
881             String JavaDoc typeField = field.getFieldType();
882             if (!typeField.equals(WebKeys.TypeField.IMAGE) || !typeField.equals(WebKeys.TypeField.FILE)
883                     || !typeField.equals(WebKeys.TypeField.LINK)) {
884                 _setField(value, req, field, contentlet);
885             }
886         } catch (Exception JavaDoc ex) {
887             Logger.debug(this, ex.toString());
888         }
889     }
890     
891     private void _saveChildren(ActionRequest req, Field field, Contentlet contentlet) {
892         try {
893             String JavaDoc value = req.getParameter(field.getFieldContentlet());
894             String JavaDoc typeField = field.getFieldType();
895             if (typeField.equals(WebKeys.TypeField.IMAGE)) {
896                 String JavaDoc relationName = field.getFieldRelationType();
897                 if (UtilMethods.isSet(value)) {
898                     long imageInode = Long.parseLong(value);
899                     ContentletFactory.addImageToContentlet(contentlet, imageInode, relationName);
900                 }
901             } else if (typeField.equals(WebKeys.TypeField.FILE)) {
902                 String JavaDoc relationName = field.getFieldRelationType();
903                 // Create the new file
904
if (UtilMethods.isSet(value)) {
905                     long imageInode = Long.parseLong(value);
906                     ContentletFactory.addFileToContentlet(contentlet, imageInode, relationName);
907                 }
908             } else if (typeField.equals(WebKeys.TypeField.LINK)) {
909                 String JavaDoc relationName = field.getFieldRelationType();
910                 // Create the new link
911
if (UtilMethods.isSet(value)) {
912                     long imageInode = Long.parseLong(value);
913                     ContentletFactory.addLinkToContentlet(contentlet, imageInode, relationName);
914                 }
915             }
916         } catch (Exception JavaDoc ex) {
917             Logger.debug(this, ex.toString());
918         }
919     }
920     
921     private void _setField(Object JavaDoc value, ActionRequest req, Field field, Contentlet contentlet) {
922         try {
923             String JavaDoc typeField = field.getFieldContentlet();
924             if (typeField.startsWith("date")) {
925                 SimpleDateFormat JavaDoc dateFormatter = new SimpleDateFormat JavaDoc("yyyy-MM-dd HH:mm:ss");
926                 String JavaDoc parameter = field.getFieldContentlet();
927                 String JavaDoc date = req.getParameter(parameter);
928                 value = dateFormatter.parse(date);
929             } if (field.getFieldType().equals(WebKeys.TypeField.WYSIWYG)) {
930                 //WYSIWYG workaround beacause the WYSIWYG includes a <br> even if the field was left blank by the user
931
//we have to check the value to leave it blank in that case.
932
if (value instanceof String JavaDoc && ((String JavaDoc)value).trim().toLowerCase().equals("<br>")) {
933                     value = "";
934                 }
935             }
936             BeanUtils.setProperty(contentlet, typeField, value);
937         } catch (Exception JavaDoc ex) {
938             Logger.debug(this, ex.toString());
939         }
940     }
941     
942     @SuppressWarnings JavaDoc("unchecked")
943     public void _saveWebAsset(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user)
944     throws Exception JavaDoc {
945         
946         // wraps request to get session object
947
ActionRequestImpl reqImpl = (ActionRequestImpl) req;
948         HttpServletRequest JavaDoc httpReq = reqImpl.getHttpServletRequest();
949         
950         // Getting the contentlets variables to work
951
Contentlet currentContentlet = (Contentlet) req.getAttribute(WebKeys.FatContentlet.CONTENTLET);
952         req.setAttribute(WebKeys.CONTENTLET_FORM_EDIT, currentContentlet);
953         
954         ContentletForm contentletForm = (ContentletForm) form;
955         
956         boolean isNew = true;
957         
958         // Checking permissions
959
_checkPermissions(currentContentlet, user, httpReq);
960         
961         // Gets the information for the sibling contenlet
962
Contentlet sibblingContentlet = (Contentlet) req.getAttribute(WebKeys.CONTENTLET_SIBBLING_EDIT);
963         Contentlet workingContentlet = null;
964         
965         // Versioning the current contentlet
966
if (currentContentlet.getInode() > 0) {
967             
968             isNew = false;
969             
970             Contentlet newContentlet = new com.dotmarketing.portlets.contentlet.model.Contentlet();
971             
972             // Current identifier
973
Identifier identifier = IdentifierFactory.getParentIdentifier(currentContentlet);
974             
975             // Creation the version asset
976
WebAssetFactory.createAsset(newContentlet, user.getUserId(), identifier, false);
977             
978             // copying the properties to the new version contentlet
979
_populateContent(req, res, config, form, user, newContentlet);
980             
981             workingContentlet = (Contentlet) WebAssetFactory.saveAsset(newContentlet, identifier);
982             
983         } else if (currentContentlet.getInode() == 0) { // Is a new contentlet
984
// copying the properties to the new version contentlet
985
_populateContent(req, res, config, form, user, currentContentlet);
986             
987             if (sibblingContentlet.getInode() > 0) {
988                 // The new contentlet is another language copy from a sibbling
989
// contentlet
990
Identifier id = IdentifierFactory.getIdentifierByInode(sibblingContentlet);
991                 WebAssetFactory.createAsset(currentContentlet, user.getUserId(), id);
992                 
993             } else {
994                 WebAssetFactory.createAsset(currentContentlet, user.getUserId());
995             }
996             workingContentlet = currentContentlet;
997         }
998         
999         //Saving interval review properties
1000
if (contentletForm.isReviewContent()) {
1001            workingContentlet.setReviewInterval(contentletForm.getReviewIntervalNum() + contentletForm.getReviewIntervalSelect());
1002        } else {
1003            workingContentlet.setReviewInterval(null);
1004        }
1005        
1006        // saving the review dates
1007
workingContentlet.setLastReview(new Date JavaDoc ());
1008        if (workingContentlet.getReviewInterval() != null) {
1009            workingContentlet.setNextReview(ContentletFactory.calculateNextReviewDate(workingContentlet.getReviewInterval()));
1010        }
1011        
1012        // Saving current contentlet changes
1013
InodeFactory.saveInode(workingContentlet);
1014        
1015        // writes the contentlet to a working directory under velocity folder
1016
ContentletServices.writeContentletToFile(workingContentlet, true);
1017        
1018        //writes the contentlet object to a file
1019
ContentletMapServices.writeContentletMapToFile(workingContentlet, true);
1020        // Saving contentlet categories
1021
ContentletForm cf = (ContentletForm) form;
1022        String JavaDoc[] arr = cf.getCategories();
1023        if (arr != null) {
1024            for (int i = 0; i < arr.length; i++) {
1025                Category node = (Category) InodeFactory.getInode(arr[i], Category.class);
1026                node.addChild(workingContentlet);
1027            }
1028        }
1029        // Saving permissions
1030
_applyPermissions(req, workingContentlet);
1031        
1032        // updating relationships
1033
Set JavaDoc<String JavaDoc> keys = req.getParameterMap().keySet();
1034        for (String JavaDoc key : keys) {
1035            if (key.startsWith("rel_") && key.endsWith("_inodes")) {
1036                boolean hasParent = key.indexOf("_P_") != -1;
1037                String JavaDoc inodesSt = (String JavaDoc) req.getParameter(key);
1038                String JavaDoc[] inodes = inodesSt.split(",");
1039                Relationship relationship = (Relationship) InodeFactory.getInode(inodes[0], Relationship.class);
1040                
1041                List JavaDoc<Tree> trees = RelationshipFactory.getAllRelationshipTrees(relationship, workingContentlet,
1042                        hasParent);
1043                for (Tree tree : trees) {
1044                    TreeFactory.deleteTree(tree);
1045                }
1046                Identifier contIden = IdentifierFactory.getIdentifierByInode(workingContentlet);
1047                for (int i = 1; i < inodes.length; i++) {
1048                    String JavaDoc inode = inodes[i];
1049                    Identifier targetIden = IdentifierFactory.getIdentifierByInode(InodeFactory.getInode(inode,
1050                            Contentlet.class));
1051                    Tree newTree = null;
1052                    if (hasParent) {
1053                        newTree = new Tree(contIden.getInode(), targetIden.getInode(), relationship
1054                                .getRelationTypeValue(), i);
1055                    } else {
1056                        newTree = new Tree(targetIden.getInode(), contIden.getInode(), relationship
1057                                .getRelationTypeValue(), i);
1058                    }
1059                    TreeFactory.saveTree(newTree);
1060                }
1061            }
1062        }
1063        
1064        //Setting the host
1065
Host host = HostFactory.getHost (cf.getHostInode());
1066        workingContentlet.addParent(host);
1067        
1068        // Updating lucene index
1069
ContentletFactory.reIndexContentlet(workingContentlet);
1070        
1071        //SEnd content change notifications
1072
if (Config.getBooleanProperty("CONTENT_CHANGE_NOTIFICATIONS") && !isNew)
1073            ContentletFactory._sendContentletPublishNotification((Contentlet)workingContentlet, reqImpl.getHttpServletRequest());
1074        
1075    }
1076    
1077    public void _copyWebAsset(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user)
1078    throws Exception JavaDoc {
1079        
1080        // wraps request to get session object
1081
ActionRequestImpl reqImpl = (ActionRequestImpl) req;
1082        HttpServletRequest JavaDoc httpReq = reqImpl.getHttpServletRequest();
1083        
1084        Contentlet currentContentlet = (Contentlet) req.getAttribute(WebKeys.CONTENTLET_EDIT);
1085        
1086        Logger.debug(this, "currentContentlet Inode=" + currentContentlet.getInode());
1087        
1088        // Checking permissions
1089
_checkCopyAndMovePermissions(currentContentlet, user, httpReq, "copy");
1090        
1091        Contentlet newOne = ContentletFactory.copyContentlet(currentContentlet);
1092        
1093        // Upodating lucene index
1094
ContentletFactory.reIndexContentlet(newOne);
1095        
1096        // gets the session object for the messages
1097
SessionMessages.add(httpReq, "message", "message.contentlet.copy");
1098    }
1099    
1100    public void _getVersionBackWebAsset(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form,
1101            User user) throws Exception JavaDoc {
1102        
1103        Contentlet workingContentlet = (Contentlet) super._getVersionBackWebAsset(req, res, config, form, user,
1104                Contentlet.class, WebKeys.CONTENTLET_EDIT);
1105        ContentletServices.writeContentletToFile(workingContentlet, true);
1106        
1107        //writes the contentlet object to a file
1108
ContentletMapServices.writeContentletMapToFile(workingContentlet, true);
1109        // Upodating lucene index
1110
ContentletFactory.reIndexContentlet(workingContentlet);
1111        
1112        req.setAttribute(WebKeys.CONTENTLET_EDIT , workingContentlet);
1113    }
1114    
1115    private void _loadForm(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user,
1116            boolean validate) throws Exception JavaDoc {
1117        try {
1118            
1119            Contentlet contentlet = (Contentlet) req.getAttribute(WebKeys.FatContentlet.CONTENTLET);
1120            ContentletForm contentletForm = (ContentletForm) form;
1121            if (validate) {
1122                BeanUtils.copyProperties(contentletForm, contentlet);
1123            }
1124            Structure structure = contentlet.getStructure();
1125            
1126            if (structure.getInode() == 0) {
1127                String JavaDoc selectedStructure = req.getParameter("selectedStructure");
1128                if (UtilMethods.isSet(selectedStructure)) {
1129                    structure = StructureFactory.getStructureByInode(Long.parseLong(selectedStructure));
1130                }
1131            }
1132            contentletForm.setStructure(structure);
1133            List JavaDoc structures = StructureFactory.getStructuresWithWritePermissions(user);
1134            contentletForm.setAllStructures(structures);
1135            
1136            String JavaDoc cmd = req.getParameter(Constants.CMD);
1137            if ((cmd.equals("new") || contentletForm.getStructure().getInode() == 0) && contentletForm.isAllowChange()) {
1138                contentletForm.setAllowChange(true);
1139            } else {
1140                contentletForm.setAllowChange(false);
1141            }
1142            
1143            if (cmd != null && cmd.equals(Constants.EDIT)) {
1144                //Setting categories in the contentlet form
1145
List JavaDoc<String JavaDoc> categoriesArr = new ArrayList JavaDoc<String JavaDoc> ();
1146                List JavaDoc<Category> cats = InodeFactory.getParentsOfClass(contentlet, Category.class);
1147                
1148                for (Category cat : cats) {
1149                    categoriesArr.add(String.valueOf(cat.getInode()));
1150                }
1151                
1152                contentletForm.setCategories(categoriesArr.toArray(new String JavaDoc[0]));
1153                
1154            }
1155            
1156        } catch (Exception JavaDoc ex) {
1157            Logger.debug(this, ex.toString());
1158            throw ex;
1159        }
1160    }
1161    
1162    public String JavaDoc searchContentletsInodes(Structure st, String JavaDoc fields, String JavaDoc categories, boolean showDeleted, int page, String JavaDoc orderBy) {
1163        
1164        
1165        boolean desc = false;
1166        if (!UtilMethods.isSet(orderBy)) orderBy = "modDate desc";
1167        
1168        if (orderBy.trim().endsWith("desc")) {
1169            desc = true;
1170            orderBy = orderBy.substring(0, orderBy.indexOf("desc")).trim();
1171        }
1172        
1173        Field sortField = FieldFactory.getFieldByName(st.getInode(), orderBy);
1174        String JavaDoc sortFieldSt = sortField.getFieldContentlet() + (desc?" desc":"");
1175        
1176        if (orderBy.equals("modDate") || orderBy.equals("modUser")) {
1177            sortFieldSt = orderBy + (desc?" desc":"");
1178        }
1179        
1180        Map JavaDoc<String JavaDoc, String JavaDoc> fieldsSearch = new HashMap JavaDoc<String JavaDoc, String JavaDoc>();
1181        String JavaDoc[] tokens = fields.split(",");
1182        
1183        for (int i=0;i < tokens.length; i=i+2) {
1184            String JavaDoc fieldName = tokens[i];
1185            String JavaDoc fieldValue = tokens[i+1];
1186            if (UtilMethods.isSet(fieldValue))
1187                fieldsSearch.put(fieldName, fieldValue);
1188        }
1189        
1190        int perPage = Config.getIntProperty("PER_PAGE");
1191        int offset = perPage * (page - 1);
1192        
1193        List JavaDoc<String JavaDoc> cats = new ArrayList JavaDoc();
1194        if(UtilMethods.isSet(categories)){
1195            String JavaDoc[] categoriesSplit = categories.split(",");
1196            for (int i=0;i < categoriesSplit.length; i++) {
1197                cats.add(categoriesSplit[i] );
1198                
1199            }
1200        }
1201        
1202        LuceneHits hits = ContentletFactory.indexSearch(st, fieldsSearch, cats, showDeleted, offset, perPage, sortFieldSt, true, true);
1203        
1204        
1205        StringBuffer JavaDoc inodesList = new StringBuffer JavaDoc();
1206        for (int i = 0; i < hits.length(); i++) {
1207            Document doc = hits.doc(i);
1208            inodesList.append( ","+doc.get("inode"));
1209        }
1210        
1211        return inodesList.toString().substring(1);
1212    }
1213    
1214    public void downloadToExcel(String JavaDoc structureInode, String JavaDoc fields, String JavaDoc categories, boolean showDeleted, HttpServletResponse JavaDoc response) {
1215        
1216        Structure st = StructureFactory.getStructureByInode(structureInode);
1217        
1218        StringBuffer JavaDoc fieldsSearch = new StringBuffer JavaDoc();
1219        fieldsSearch.append(" structure_inode ="+st.getInode()+" and working="
1220                + com.dotmarketing.db.DbConnectionFactory.getDBTrue());
1221        if(showDeleted){
1222            fieldsSearch.append(" and deleted = "+ com.dotmarketing.db.DbConnectionFactory.getDBTrue());
1223        } else {
1224            fieldsSearch.append(" and deleted = "+ com.dotmarketing.db.DbConnectionFactory.getDBFalse());
1225        }
1226        
1227        String JavaDoc searchInodes = searchContentletsInodes(st, fields, categories, false, 0, "inode");
1228        
1229        fieldsSearch.append(" and inode in ("+searchInodes+")");
1230        List JavaDoc<Contentlet> contentletList = ContentletFactory.getContentletByCondition(fieldsSearch.toString());
1231        
1232        ServletOutputStream JavaDoc out = null;
1233        try {
1234            
1235            
1236            response.setContentType("application/octet-stream");
1237            response.setHeader("Content-Disposition", "attachment; filename=\""+st.getName()+"_contents_" + UtilMethods.dateToHTMLDate(new java.util.Date JavaDoc(),"M_d_yyyy") +".csv\"");
1238            
1239            out = response.getOutputStream();
1240            
1241            if(contentletList.size() > 0) {
1242                
1243                
1244                List JavaDoc<Field> stFields = FieldsCache.getFieldsByStructureInode(st.getInode());
1245                out.print("Identifier");
1246                for (Field f : stFields) {
1247                    //we cannot export fields of these types
1248
if (f.getFieldType().equals(WebKeys.TypeField.BUTTON) ||
1249                            f.getFieldType().equals(WebKeys.TypeField.FILE) ||
1250                            f.getFieldType().equals(WebKeys.TypeField.IMAGE) ||
1251                            f.getFieldType().equals(WebKeys.TypeField.LINK))
1252                        continue;
1253                    out.print(","+f.getFieldName());
1254                }
1255                
1256                List JavaDoc<Category> catTitles = getStructureCategories(st);
1257                for(Category cat : catTitles){
1258                    out.print(","+cat.getCategoryName());
1259                }
1260                
1261                out.print("\r\n");
1262                for(Contentlet content : contentletList ){
1263                    
1264                    out.print(""+content.getIdentifier()+"");
1265                    for (Field f : stFields) {
1266                        try {
1267                            //we cannot export fields of these types
1268
if (f.getFieldType().equals(WebKeys.TypeField.BUTTON) ||
1269                                    f.getFieldType().equals(WebKeys.TypeField.FILE) ||
1270                                    f.getFieldType().equals(WebKeys.TypeField.IMAGE) ||
1271                                    f.getFieldType().equals(WebKeys.TypeField.LINK))
1272                                continue;
1273                            
1274                            Object JavaDoc value = "";
1275                            if(ContentletFactory.getFieldValue(content,f) != null)
1276                                value = ContentletFactory.getFieldValue(content,f);
1277                            String JavaDoc text = "";
1278                            if (value instanceof Date JavaDoc || value instanceof Timestamp JavaDoc) {
1279                                if(f.getFieldType().equals(WebKeys.TypeField.DATE)) {
1280                                    SimpleDateFormat JavaDoc formatter = new SimpleDateFormat JavaDoc (WebKeys.DateFormats.EXP_IMP_DATE);
1281                                    text = formatter.format(value);
1282                                } else if(f.getFieldType().equals(WebKeys.TypeField.DATETIME)) {
1283                                    SimpleDateFormat JavaDoc formatter = new SimpleDateFormat JavaDoc (WebKeys.DateFormats.EXP_IMP_DATETIME);
1284                                    text = formatter.format(value);
1285                                } else if(f.getFieldType().equals(WebKeys.TypeField.TIME)) {
1286                                    SimpleDateFormat JavaDoc formatter = new SimpleDateFormat JavaDoc (WebKeys.DateFormats.EXP_IMP_TIME);
1287                                    text = formatter.format(value);
1288                                }
1289                            } else {
1290                                text = value.toString();
1291                            }
1292                            
1293                            text = text.replaceAll("\"","'");
1294                            
1295                            if(text.indexOf("\n") > -1)
1296                                out.print(",\""+text+"\"");
1297                            else
1298                                out.print("," + text);
1299                        }catch(Exception JavaDoc e){
1300                            out.print(",");
1301                            e.printStackTrace();
1302                        }
1303                    }
1304                    
1305                    for(Category catParent : catTitles){
1306                        List JavaDoc<Category> catList = InodeFactory.getParentsOfClassByCondition(content,Category.class, " tree.parent in( select tree.child from tree where tree.parent = "+catParent.getInode()+")");
1307                        if(catList.size() > 0){
1308                            out.print(",");
1309                            for(Category cat : catList){
1310                                out.print(cat.getCategoryName());
1311                            }
1312                        } else if(catTitles.size() > 0){
1313                            out.print(",");
1314                        }
1315                    }
1316                    out.print("\r\n");
1317                    
1318                }
1319                
1320                
1321            }else {
1322                //No Content to show");
1323
out.print("\r\n");
1324            }
1325            out.flush();
1326            out.close();
1327            DotHibernate.closeSession();
1328            
1329        }catch(Exception JavaDoc p){
1330            try {
1331                out.flush();
1332                out.close();
1333                DotHibernate.closeSession();
1334            } catch (IOException JavaDoc e) {
1335                // TODO Auto-generated catch block
1336
e.printStackTrace();
1337            }
1338            
1339            p.printStackTrace();
1340            
1341        }
1342        
1343    }
1344    
1345    public List JavaDoc<Category> getStructureCategories (Structure st) {
1346        Entity entity = EntityFactory.getEntity(st.getName());
1347        List JavaDoc<Category> cats = EntityFactory.getEntityCategories(entity);
1348        
1349        return cats;
1350    }
1351    
1352    // Workflow related methods
1353
public void _assignWebAsset(ActionRequest req, ActionResponse res,
1354            PortletConfig config, ActionForm form, User user, String JavaDoc formWebKey)
1355            throws Exception JavaDoc {
1356
1357        String JavaDoc systemUserId = "System";
1358        ContentletForm cForm = (ContentletForm) form;
1359        
1360        // Getting the contentlets variables to work
1361
Contentlet cont = (Contentlet) req.getAttribute(WebKeys.FatContentlet.CONTENTLET);
1362
1363
1364        WorkflowTask task = new WorkflowTask();
1365
1366        Identifier id = IdentifierFactory.getIdentifierByInode(cont);
1367        task.setTitle("Content: " + id.getInode() + " needs to be reviewed/published.");
1368
1369        String JavaDoc description = UtilMethods.isSet(cForm.getTaskComments())?cForm.getTaskComments():cont.toPrettyHTMLString();
1370        task.setDescription(description);
1371
1372        task.setBelongsTo(cForm.getTaskRole());
1373        task.setModDate(new Date JavaDoc());
1374        task.setCreationDate(new Date JavaDoc());
1375        task.setCreatedBy(systemUserId);
1376        task.setAssignedTo("Nobody");
1377        task.setDueDate(null);
1378        task.setWebasset(cont.getInode());
1379        task.setStatus(WorkflowStatuses.OPEN.toString());
1380        
1381        InodeFactory.saveInode(task);
1382
1383        WorkflowHistory hist = new WorkflowHistory();
1384        hist.setChangeDescription("Review/Publish Content Task Creation");
1385        hist.setCreationDate(new Date JavaDoc());
1386        hist.setMadeBy(systemUserId);
1387        InodeFactory.saveInode(hist);
1388        task.addChild(hist);
1389        
1390        String JavaDoc comments = UtilMethods.isSet(cForm.getTaskComments())?cForm.getTaskComments():"Review/Publish Task Request";
1391        String JavaDoc body = _buildWorkflowEmailBody (task, comments);
1392        WorkflowsFactory.sendWorkflowChangeEmails(task, "A new Review/Publish Content Task was created", body);
1393        
1394    }
1395
1396    private String JavaDoc _buildWorkflowEmailBody (WorkflowTask task, String JavaDoc change) {
1397
1398        Host host = HostFactory.getDefaultHost();
1399        String JavaDoc ref = "http://" + host.getHostname() + Config.getStringProperty("WORKFLOWS_URL") + "&inode=" + String.valueOf(task.getInode());
1400
1401        StringBuffer JavaDoc buffer = new StringBuffer JavaDoc ();
1402        try {
1403            String JavaDoc roleName = RoleFactory.getRoleById(task.getBelongsTo()).getName();
1404            buffer.append(
1405                  "<table align=\"center\" border=\"1\" width=\"50%\">" +
1406                  " <tr>" +
1407                  " <td align=\"center\" colspan=\"2\"><b>" + change + "</b></td>" +
1408                  " </tr>" +
1409                  " <tr>" +
1410                  " <td width=\"15%\" nowrap><b>Task</b></td><td><a HREF=\"" + ref + "\">" + task.getTitle() + "</a></td>" +
1411                  " </tr>" +
1412                  " <tr>" +
1413                  " <td nowrap><b>Created</b></td><td>" + UtilMethods.dateToHTMLDate(task.getCreationDate()) + "</td>" +
1414                  " </tr>" +
1415                  " <tr>" +
1416                  " <td nowrap><b>Author</b></td><td>" + UtilMethods.getUserFullName(task.getCreatedBy()) + "</td>" +
1417                  " </tr>" +
1418                  " <tr>" +
1419                  " <td nowrap><b>Asignee Group</b></td><td>" + roleName + "</td>" +
1420                  " </tr>" +
1421                  "</table>"
1422            );
1423        } catch (NoSuchRoleException e) {
1424            Logger.warn(this, "The task point to an unexisting role: " + task.getBelongsTo(), e);
1425        }
1426        
1427        return buffer.toString();
1428    }
1429    
1430}
Popular Tags