KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > dotmarketing > portlets > files > action > EditFileAction


1 package com.dotmarketing.portlets.files.action;
2
3 import java.awt.image.BufferedImage JavaDoc;
4 import java.io.FileInputStream JavaDoc;
5 import java.io.FileOutputStream JavaDoc;
6 import java.io.IOException JavaDoc;
7 import java.net.URLDecoder JavaDoc;
8 import java.net.URLEncoder JavaDoc;
9 import java.nio.ByteBuffer JavaDoc;
10 import java.nio.channels.FileChannel JavaDoc;
11
12 import javax.portlet.ActionRequest;
13 import javax.portlet.ActionResponse;
14 import javax.portlet.PortletConfig;
15 import javax.portlet.WindowState;
16 import javax.servlet.http.HttpServletRequest JavaDoc;
17
18 import org.apache.commons.beanutils.BeanUtils;
19 import org.apache.struts.action.ActionForm;
20 import org.apache.struts.action.ActionMapping;
21
22 import com.dotmarketing.beans.Host;
23 import com.dotmarketing.beans.Identifier;
24 import com.dotmarketing.beans.Tree;
25 import com.dotmarketing.cache.LiveCache;
26 import com.dotmarketing.cache.WorkingCache;
27 import com.dotmarketing.db.DotHibernate;
28 import com.dotmarketing.factories.HostFactory;
29 import com.dotmarketing.factories.IdentifierFactory;
30 import com.dotmarketing.factories.InodeFactory;
31 import com.dotmarketing.factories.TreeFactory;
32 import com.dotmarketing.factories.WebAssetFactory;
33 import com.dotmarketing.menubuilders.RefreshMenus;
34 import com.dotmarketing.portal.struts.DotPortletAction;
35 import com.dotmarketing.portal.struts.DotPortletActionInterface;
36 import com.dotmarketing.portlets.categories.model.Category;
37 import com.dotmarketing.portlets.files.factories.FileFactory;
38 import com.dotmarketing.portlets.files.model.File;
39 import com.dotmarketing.portlets.files.struts.FileForm;
40 import com.dotmarketing.portlets.folders.factories.FolderFactory;
41 import com.dotmarketing.portlets.folders.model.Folder;
42 import com.dotmarketing.util.Config;
43 import com.dotmarketing.util.Logger;
44 import com.dotmarketing.util.UtilMethods;
45 import com.dotmarketing.util.Validator;
46 import com.dotmarketing.util.WebKeys;
47 import com.liferay.portal.model.User;
48 import com.liferay.portal.struts.ActionException;
49 import com.liferay.portal.util.Constants;
50 import com.liferay.portal.util.PortalUtil;
51 import com.liferay.portlet.ActionRequestImpl;
52 import com.liferay.util.FileUtil;
53 import com.liferay.util.ParamUtil;
54 import com.liferay.util.servlet.SessionMessages;
55 import com.liferay.util.servlet.UploadPortletRequest;
56
57 /**
58  * @author Maria
59  */

60
61 public class EditFileAction extends DotPortletAction implements DotPortletActionInterface {
62     
63     public static boolean debug = true;
64     
65     public void processAction(ActionMapping mapping, ActionForm form, PortletConfig config, ActionRequest req,
66             ActionResponse res) throws Exception JavaDoc {
67         
68         String JavaDoc cmd = req.getParameter(Constants.CMD);
69         String JavaDoc referer = req.getParameter("referer");
70         
71         // wraps request to get session object
72
ActionRequestImpl reqImpl = (ActionRequestImpl) req;
73         HttpServletRequest JavaDoc httpReq = reqImpl.getHttpServletRequest();
74         
75         if ((referer != null) && (referer.length() != 0)) {
76             referer = URLDecoder.decode(referer, "UTF-8");
77         }
78         
79         Logger.debug(this, "EditFileAction cmd=" + cmd);
80         
81         DotHibernate.startTransaction();
82         
83         User user = _getUser(req);
84         
85         try {
86             Logger.debug(this, "Calling Retrieve method");
87             _retrieveWebAsset(req, res, config, form, user, File.class, WebKeys.FILE_EDIT);
88             
89         } catch (Exception JavaDoc ae) {
90             _handleException(ae, req);
91             return;
92         }
93         
94         /*
95          * We are editing the container
96          */

97         if ((cmd != null) && cmd.equals(Constants.EDIT)) {
98             try {
99                 Logger.debug(this, "Calling Edit method");
100                 _editWebAsset(req, res, config, form, user);
101                 
102             } catch (Exception JavaDoc ae) {
103                 if ((referer != null) && (referer.length() != 0)) {
104                     if (ae.getMessage().equals(WebKeys.EDIT_ASSET_EXCEPTION)) {
105                         
106                         // The web asset edit threw an exception because it's
107
// locked so it should redirect back with message
108
java.util.Map JavaDoc<String JavaDoc, String JavaDoc[]> params = new java.util.HashMap JavaDoc<String JavaDoc, String JavaDoc[]>();
109                         params.put("struts_action", new String JavaDoc[] { "/ext/director/direct" });
110                         params.put("cmd", new String JavaDoc[] { "editFile" });
111                         params.put("file", new String JavaDoc[] { req.getParameter("inode") });
112                         params.put("referer", new String JavaDoc[] { URLEncoder.encode(referer, "UTF-8") });
113                         
114                         String JavaDoc directorURL = com.dotmarketing.util.PortletURLUtil.getActionURL(httpReq,
115                                 WindowState.MAXIMIZED.toString(), params);
116                         
117                         _sendToReferral(req, res, directorURL);
118                         return;
119                     }
120                 }
121                 _handleException(ae, req);
122                 return;
123             }
124         }
125         
126         /*
127          * If we are updating the container, copy the information from the
128          * struts bean to the hbm inode and run the update action and return to
129          * the list
130          */

131         if ((cmd != null) && cmd.equals(Constants.ADD)) {
132             try {
133                 Logger.debug(this, "Calling Save method");
134                 
135                 if (Validator.validate(req, form, mapping)) {
136                     
137                     _saveWebAsset(req, res, config, form, user);
138                     
139                     String JavaDoc subcmd = req.getParameter("subcmd");
140                     
141                     if ((subcmd != null) && subcmd.equals(com.dotmarketing.util.Constants.PUBLISH)) {
142                         Logger.debug(this, "Calling Publish method");
143                         _publishWebAsset(req, res, config, form, user, WebKeys.FILE_FORM_EDIT);
144                         
145                     }
146                     _sendToReferral(req, res, referer);
147                 }
148                 
149             } catch (Exception JavaDoc ae) {
150                 _handleException(ae, req);
151             }
152             
153         }
154         /*
155          * If we are deleteing the container, run the delete action and return
156          * to the list
157          *
158          */

159         else if ((cmd != null) && cmd.equals(Constants.DELETE)) {
160             try {
161                 Logger.debug(this, "Calling Delete method");
162                 _deleteWebAsset(req, res, config, form, user, WebKeys.FILE_EDIT);
163                 
164             } catch (Exception JavaDoc ae) {
165                 _handleException(ae, req);
166                 return;
167             }
168             _sendToReferral(req, res, referer);
169         }
170         /*
171          * If we are undeleting the container, run the undelete action and
172          * return to the list
173          *
174          */

175         else if ((cmd != null) && cmd.equals(com.dotmarketing.util.Constants.UNDELETE)) {
176             try {
177                 Logger.debug(this, "Calling UnDelete method");
178                 _undeleteWebAsset(req, res, config, form, user, WebKeys.FILE_EDIT);
179                 
180             } catch (Exception JavaDoc ae) {
181                 _handleException(ae, req);
182                 return;
183             }
184             _sendToReferral(req, res, referer);
185             
186         }
187         /*
188          * If we are deleting the container version, run the deeleteversion
189          * action and return to the list
190          */

191         else if ((cmd != null) && cmd.equals(com.dotmarketing.util.Constants.DELETEVERSION)) {
192             try {
193                 Logger.debug(this, "Calling Delete Version Method");
194                 _deleteVersionWebAsset(req, res, config, form, user, WebKeys.FILE_EDIT);
195                 
196             } catch (Exception JavaDoc ae) {
197                 _handleException(ae, req);
198                 return;
199             }
200             _sendToReferral(req, res, referer);
201         }
202         /*
203          * If we are unpublishing the container, run the unpublish action and
204          * return to the list
205          */

206         else if ((cmd != null) && cmd.equals(com.dotmarketing.util.Constants.UNPUBLISH)) {
207             try {
208                 Logger.debug(this, "Calling Unpublish Method");
209                 _unPublishWebAsset(req, res, config, form, user, WebKeys.FILE_EDIT);
210                 
211             } catch (Exception JavaDoc ae) {
212                 _handleException(ae, req);
213                 return;
214             }
215             _sendToReferral(req, res, referer);
216             
217         }
218         /*
219          * If we are getting the container version back, run the getversionback
220          * action and return to the list
221          */

222         else if ((cmd != null) && cmd.equals(com.dotmarketing.util.Constants.GETVERSIONBACK)) {
223             try {
224                 Logger.debug(this, "Calling Get Version Back Method");
225                 _getVersionBackWebAsset(req, res, config, form, user);
226                 
227             } catch (Exception JavaDoc ae) {
228                 _handleException(ae, req);
229                 return;
230             }
231             _sendToReferral(req, res, referer);
232         }
233         /*
234          * If we are getting the container versions, run the assetversions
235          * action and return to the list
236          */

237         else if ((cmd != null) && cmd.equals(com.dotmarketing.util.Constants.ASSETVERSIONS)) {
238             try {
239                 Logger.debug(this, "Calling Get Versions Method");
240                 _getVersionsWebAsset(req, res, config, form, user, WebKeys.FILE_EDIT, WebKeys.FILE_VERSIONS);
241                 
242             } catch (Exception JavaDoc ae) {
243                 _handleException(ae, req);
244                 return;
245             }
246         }
247         /*
248          * If we are unlocking the container, run the unlock action and return
249          * to the list
250          */

251         else if ((cmd != null) && cmd.equals(com.dotmarketing.util.Constants.UNLOCK)) {
252             try {
253                 Logger.debug(this, "Calling Unlock Method");
254                 _unLockWebAsset(req, res, config, form, user, WebKeys.FILE_EDIT);
255                 
256             } catch (Exception JavaDoc ae) {
257                 _handleException(ae, req);
258                 return;
259             }
260             _sendToReferral(req, res, referer);
261             
262         }
263         /*
264          * If we are copying the container, run the copy action and return to
265          * the list
266          */

267         else if ((cmd != null) && cmd.equals(com.dotmarketing.util.Constants.COPY)) {
268             try {
269                 Logger.debug(this, "Calling Copy Method");
270                 _copyWebAsset(req, res, config, form, user);
271                 
272             } catch (Exception JavaDoc ae) {
273                 _handleException(ae, req);
274             }
275             _sendToReferral(req, res, referer);
276         }
277         /*
278          * If we are moving the container, run the copy action and return to the
279          * list
280          */

281         else if ((cmd != null) && cmd.equals(com.dotmarketing.util.Constants.MOVE)) {
282             try {
283                 Logger.debug(this, "Calling Move Method");
284                 _moveWebAsset(req, res, config, form, user);
285                 
286             } catch (Exception JavaDoc ae) {
287                 _handleException(ae, req);
288             }
289             _sendToReferral(req, res, referer);
290         } else
291             Logger.debug(this, "Unspecified Action");
292         
293         DotHibernate.commitTransaction();
294         setForward(req, "portlet.ext.files.edit_file");
295     }
296     
297     // /// ************** ALL METHODS HERE *************************** ////////
298
public void _moveWebAsset(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user)
299     throws Exception JavaDoc {
300         
301         Logger.debug(this, "I'm moving the webasset");
302         
303         // gets the current container being edited from the request object
304
File webAsset = (File) req.getAttribute(WebKeys.FILE_EDIT);
305         
306         // gets folder parent
307
String JavaDoc parentInode = req.getParameter("parent");
308         
309         if (parentInode != null && parentInode.length() != 0 && !parentInode.equals("0")) {
310             
311             // the new parent is being passed through the request
312
Folder parent = (Folder) InodeFactory.getInode(parentInode, Folder.class);
313
314             if(FileFactory.moveFile(webAsset, parent)) {
315                 SessionMessages.add(req, "message", "message.file_asset.move");
316             } else {
317                 SessionMessages.add(req, "message", "message.file_asset.error.filename.exists");
318                 throw new ActionException("message.file_asset.error.filename.exists");
319             }
320             
321         }
322         
323     }
324     
325     public void _editWebAsset(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user)
326     throws Exception JavaDoc {
327         
328         // calls edit method from super class that returns parent folder
329
Folder parentFolder = super._editWebAsset(req, res, config, form, user, WebKeys.FILE_EDIT);
330         
331         // setting parent folder path and inode on the form bean
332
FileForm cf = (FileForm) form;
333         cf.setSelectedparent(parentFolder.getName());
334         cf.setParent(parentFolder.getInode());
335         cf.setSelectedparentPath(parentFolder.getPath());
336         
337         // This can't be done on the WebAsset so it needs to be done here.
338
File container = (File) req.getAttribute(WebKeys.FILE_EDIT);
339         container.setParent(parentFolder.getInode());
340         
341         // Permission variable
342
if (container.getInode() > 0)
343             req.setAttribute(WebKeys.PERMISSION_INODE_EDIT, container);
344         else
345             // if the html page is new the parentfolder permissions are used
346
req.setAttribute(WebKeys.PERMISSION_INODE_EDIT, parentFolder);
347         
348     }
349     
350     private void _saveWorkingFileData(String JavaDoc filePath, File workingFileAsset, File newVersionFileAsset, String JavaDoc suffix,
351             String JavaDoc fileName, byte[] bytes) throws Exception JavaDoc {
352         
353         // never used long maxsize = 50;
354
// long maxwidth = 3000;
355
// long maxheight = 3000;
356
// never used long minheight = 10;
357

358         long workingFileInode = workingFileAsset.getInode();
359         long workingFileIdentifier = workingFileAsset.getIdentifier();
360         long newVersionInode = newVersionFileAsset == null ? 0 : newVersionFileAsset.getInode();
361         
362         // creates the path where to save the working file based on the inode
363
String JavaDoc workingFileInodePath = String.valueOf(workingFileInode);
364         if (workingFileInodePath.length() == 1) {
365             workingFileInodePath = workingFileInodePath + "0";
366         }
367         
368         // creates the path with inode{1} + inode{2}
369
workingFileInodePath = workingFileInodePath.substring(0, 1) + java.io.File.separator
370         + workingFileInodePath.substring(1, 2);
371         
372         // creates directory for first level directory in case it
373
// doesn't exist
374
new java.io.File JavaDoc(filePath + java.io.File.separator + workingFileInodePath.substring(0, 1)).mkdir();
375         // creates directory for second level directory in case it
376
// doesn't exist
377
new java.io.File JavaDoc(filePath + java.io.File.separator + workingFileInodePath).mkdir();
378         
379         String JavaDoc workingFilePath = filePath + java.io.File.separator + workingFileInodePath + java.io.File.separator
380         + workingFileInode + "." + suffix;
381         
382         // creates the new file as
383
// inode{1}/inode{2}/inode.file_extension
384
java.io.File JavaDoc workingFile = new java.io.File JavaDoc(workingFilePath);
385         workingFile.createNewFile();
386         
387         // If is a new version then retrieve the actual data
388
byte[] currentData = new byte[0];
389         if (newVersionInode > 0) {
390             FileInputStream JavaDoc is = new FileInputStream JavaDoc(workingFile);
391             int size = is.available();
392             currentData = new byte[size];
393             is.read(currentData);
394         }
395         
396         // Saving the new working data
397
FileChannel JavaDoc writeCurrentChannel = new FileOutputStream JavaDoc(workingFile).getChannel();
398         writeCurrentChannel.truncate(0);
399         ByteBuffer JavaDoc buffer = ByteBuffer.allocate(bytes.length);
400         buffer.put(bytes);
401         buffer.position(0);
402         writeCurrentChannel.write(buffer);
403         writeCurrentChannel.force(false);
404         writeCurrentChannel.close();
405         
406         // checks if it's an image
407
if (UtilMethods.isImage(workingFileAsset.getFileName())) {
408             
409             // gets image height
410
BufferedImage JavaDoc img = javax.imageio.ImageIO.read(workingFile);
411             int height = img.getHeight();
412             if (newVersionFileAsset != null)
413                 newVersionFileAsset.setHeight(height);
414             else
415                 workingFileAsset.setHeight(height);
416             // gets image width
417
int width = img.getWidth();
418             if (newVersionFileAsset != null)
419                 newVersionFileAsset.setWidth(width);
420             else
421                 workingFileAsset.setWidth(width);
422             
423             // gets image size
424
// never read long size = (workingFile.length() / 1024);
425

426             /*
427              * if (workingFileAsset.getMaxSize() != 0) maxsize =
428              * workingFileAsset.getMaxSize();
429              */

430             /*
431              * if (workingFileAsset.getMaxWidth() != 0) maxwidth =
432              * workingFileAsset.getMaxWidth(); if
433              * (workingFileAsset.getMaxHeight() != 0) maxheight =
434              * workingFileAsset.getMaxHeight();
435              */

436             /*
437              * if (workingFileAsset.getMinHeight() != 0) minheight =
438              * workingFileAsset.getMinHeight();
439              */

440             
441             /*
442              * if ((width > maxwidth) || (height > maxheight)) { String message =
443              * ""; if ((width > maxwidth)) message = "The uploaded file is too
444              * wide: " + width + "px. Maximum width allowed is: " + maxwidth +
445              * "px"; else message = "The uploaded file is too tall: " + height +
446              * "px. Maximum height allowed is: " + maxheight + "px"; //returning
447              * the old data ByteBuffer currentDataBuffer = ByteBuffer
448              * .allocate(currentData.length);
449              * currentDataBuffer.put(currentData);
450              * currentDataBuffer.position(0); writeCurrentChannel = new
451              * FileOutputStream(workingFile) .getChannel();
452              * writeCurrentChannel.truncate(0);
453              * writeCurrentChannel.write(buffer);
454              * writeCurrentChannel.force(false); writeCurrentChannel.close();
455              * throw new Exception(message); }
456              */

457         }
458         
459         // If is a new version then transfer the data form the current version
460
// to the new one
461
if (newVersionInode > 0) {
462             // creates the path where to save the working file based on the
463
// inode
464
String JavaDoc versionFileInodePath = String.valueOf(newVersionInode);
465             if (versionFileInodePath.length() == 1) {
466                 versionFileInodePath = versionFileInodePath + "0";
467             }
468             // creates the path with inode{1} + inode{2}
469
versionFileInodePath = versionFileInodePath.substring(0, 1) + java.io.File.separator
470             + versionFileInodePath.substring(1, 2);
471             
472             // creates directory for first level directory in case it
473
// doesn't exist
474
new java.io.File JavaDoc(filePath + java.io.File.separator + versionFileInodePath.substring(0, 1)).mkdir();
475             // creates directory for second level directory in case it
476
// doesn't exist
477
new java.io.File JavaDoc(filePath + java.io.File.separator + versionFileInodePath).mkdir();
478             
479             // creates the new file as
480
// inode{1}/inode{2}/inode.file_extension
481
java.io.File JavaDoc versionFile = new java.io.File JavaDoc(filePath + java.io.File.separator + versionFileInodePath
482                     + java.io.File.separator + newVersionInode + "." + suffix);
483             versionFile.createNewFile();
484             
485             FileChannel JavaDoc channelTo = new FileOutputStream JavaDoc(versionFile).getChannel();
486             
487             ByteBuffer JavaDoc currentDataBuffer = ByteBuffer.allocate(currentData.length);
488             currentDataBuffer.put(currentData);
489             currentDataBuffer.position(0);
490             channelTo.write(currentDataBuffer);
491             channelTo.force(false);
492             channelTo.close();
493             
494             java.io.File JavaDoc directory = new java.io.File JavaDoc(filePath + java.io.File.separator + workingFileInodePath);
495             java.io.File JavaDoc[] files = directory.listFiles();
496             
497             String JavaDoc thumbsIndex = workingFileInode + "_thumb_";
498             String JavaDoc resizeIndex = "resized_" + workingFileIdentifier;
499             
500             for (java.io.File JavaDoc file : files)
501             {
502                 String JavaDoc fileNameDelete = file.getName();
503                 if (fileNameDelete.indexOf(thumbsIndex) >= 0 || fileNameDelete.indexOf(resizeIndex) >= 0)
504                 {
505                     try
506                     {
507                         file.delete();
508                     } catch (SecurityException JavaDoc e) {
509                         Logger.info("EditFileAction._saveWorkingFileData(): " + file.getName()
510                                 + " cannot be erased. Please check the file permissions.");
511                     } catch (Exception JavaDoc e) {
512                         Logger.info("EditFileAction._saveWorkingFileData(): " + e.getMessage());
513                     }
514                 }
515             }
516             
517             try {
518                 // gets image height
519
int height = javax.imageio.ImageIO.read(versionFile).getHeight();
520                 workingFileAsset.setHeight(height);
521                 // gets image width
522
int width = javax.imageio.ImageIO.read(versionFile).getWidth();
523                 workingFileAsset.setWidth(width);
524                 
525             } catch (NullPointerException JavaDoc e) {
526             }
527             
528         }
529         
530     }
531     
532     private void _restoreWorkingFileData(String JavaDoc filePath, File workingFileAsset, File versionFileAsset, String JavaDoc suffix)
533     throws Exception JavaDoc {
534         long workingFileInode = workingFileAsset.getInode();
535         long newVersionInode = versionFileAsset.getInode();
536         
537         // creates the path where to save the working file based on the inode
538
String JavaDoc workingFileInodePath = String.valueOf(workingFileInode);
539         if (workingFileInodePath.length() == 1) {
540             workingFileInodePath = workingFileInodePath + "0";
541         }
542         // creates the path with inode{1} + inode{2}
543
workingFileInodePath = workingFileInodePath.substring(0, 1) + java.io.File.separator
544         + workingFileInodePath.substring(1, 2);
545         
546         // creates directory for first level directory in case it
547
// doesn't exist
548
new java.io.File JavaDoc(filePath + java.io.File.separator + workingFileInodePath.substring(0, 1)).mkdir();
549         // creates directory for second level directory in case it
550
// doesn't exist
551
new java.io.File JavaDoc(filePath + java.io.File.separator + workingFileInodePath).mkdir();
552         
553         String JavaDoc workingFilePath = filePath + java.io.File.separator + workingFileInodePath + java.io.File.separator
554         + workingFileInode + "." + suffix;
555         
556         // creates the new file as
557
// inode{1}/inode{2}/inode.file_extension
558
java.io.File JavaDoc workingFile = new java.io.File JavaDoc(workingFilePath);
559         workingFile.createNewFile();
560         
561         // creates the path where to save the working file based on the inode
562
String JavaDoc versionFileInodePath = String.valueOf(newVersionInode);
563         if (versionFileInodePath.length() == 1) {
564             versionFileInodePath = versionFileInodePath + "0";
565         }
566         // creates the path with inode{1} + inode{2}
567
versionFileInodePath = versionFileInodePath.substring(0, 1) + java.io.File.separator
568         + versionFileInodePath.substring(1, 2);
569         
570         // creates directory for first level directory in case it
571
// doesn't exist
572
new java.io.File JavaDoc(filePath + java.io.File.separator + versionFileInodePath.substring(0, 1)).mkdir();
573         // creates directory for second level directory in case it
574
// doesn't exist
575
new java.io.File JavaDoc(filePath + java.io.File.separator + versionFileInodePath).mkdir();
576         
577         // creates the new file as
578
// inode{1}/inode{2}/inode.file_extension
579
java.io.File JavaDoc versionFile = new java.io.File JavaDoc(filePath + java.io.File.separator + versionFileInodePath
580                 + java.io.File.separator + newVersionInode + "." + suffix);
581         versionFile.createNewFile();
582         
583         // If is a new version then retrieve the actual data
584
byte[] currentData = new byte[0];
585         FileInputStream JavaDoc is = new FileInputStream JavaDoc(workingFile);
586         int size = is.available();
587         currentData = new byte[size];
588         is.read(currentData);
589         is.close();
590         
591         FileChannel JavaDoc writeChannel = new FileOutputStream JavaDoc(workingFile).getChannel();
592         FileChannel JavaDoc readChannel = new FileInputStream JavaDoc(versionFile).getChannel();
593         
594         writeChannel.transferFrom(readChannel, 0, readChannel.size());
595         writeChannel.close();
596         readChannel.close();
597         
598         writeChannel = new FileOutputStream JavaDoc(versionFile).getChannel();
599         ByteBuffer JavaDoc buf = ByteBuffer.allocate(currentData.length);
600         buf.put(currentData);
601         buf.position(0);
602         writeChannel.write(buf);
603         writeChannel.close();
604         
605     }
606     
607     public void _saveWebAsset(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user)
608     throws Exception JavaDoc {
609         
610         try {
611             
612             // wraps request to get session object
613
ActionRequestImpl reqImpl = (ActionRequestImpl) req;
614             HttpServletRequest JavaDoc httpReq = reqImpl.getHttpServletRequest();
615             
616             // gets the new information for the container from the request
617
// object
618
req.setAttribute(WebKeys.FILE_FORM_EDIT, new File());
619             BeanUtils.copyProperties(req.getAttribute(WebKeys.FILE_FORM_EDIT), form);
620             FileForm fileForm = (FileForm) form;
621             
622             // gets the new information for the container from the request
623
// object
624
File file = (File) req.getAttribute(WebKeys.FILE_FORM_EDIT);
625             
626             boolean previousShowMenu = file.isShowOnMenu();
627             
628             UploadPortletRequest uploadReq = PortalUtil.getUploadPortletRequest(req);
629             
630             try {
631                 long uploadFileMaxSize = Long.parseLong(Config.getStringProperty("UPLOAD_FILE_MAX_SIZE"));
632                 
633                 if(uploadReq.getFile("uploadedFile")!= null && FileUtil.getBytes(uploadReq.getFile("uploadedFile")) != null) {
634                     if ((0 >= uploadFileMaxSize) ||
635                             (uploadFileMaxSize < FileUtil.getBytes(uploadReq.getFile("uploadedFile")).length)) {
636                         throw new ActionException();
637                     }
638                 }
639             } catch (Exception JavaDoc e) {
640                 if (!(e instanceof ActionException)) {
641                     SessionMessages.add(req, "message", "message.file_asset.error.invalid_file_max_size");
642                     throw new ActionException("message.file_asset.error.invalid_file_max_size");
643                 } else {
644                     SessionMessages.add(req, "message", "message.file_asset.error.file_greater_max_size");
645                     throw new ActionException("message.file_asset.error.file_greater_max_size");
646                 }
647             }
648             
649             // gets the current container being edited from the request object
650
File currentFile = (File) req.getAttribute(WebKeys.FILE_EDIT);
651             
652             String JavaDoc parent = ParamUtil.getString(req, "parent");
653             
654             // parent folder
655
Folder folder = (Folder) InodeFactory.getInode(parent, Folder.class);
656             
657             // CHECK THE FOLDER PATTERN
658
if (UtilMethods.isSet(file.getFileName()) && !FolderFactory.matchFilter(folder, file.getFileName())) {
659                 SessionMessages.add(req, "message", "message.file_asset.error.filename.filters");
660                 throw new ActionException("message.file_asset.error.filename.filters");
661             }
662             
663             // Checking permissions
664
_checkPermissions(currentFile, folder, user, httpReq);
665             
666             // gets categories
667
String JavaDoc categories = ParamUtil.getString(uploadReq, "categories");
668             String JavaDoc[] arr = categories.split(",");
669             
670             // gets user id from request for mod user
671
String JavaDoc userId = user.getUserId();
672             
673             boolean editFile = false;
674             boolean newUploadedFile = true;
675             
676             String JavaDoc fileName = fileForm.getFileName();
677             // gets the real path to the assets directory
678
String JavaDoc webInfPath = Config.CONTEXT.getRealPath("/META-INF");
679             
680             javax.activation.MimetypesFileTypeMap JavaDoc mimeTypeFileTypeMap = new javax.activation.MimetypesFileTypeMap JavaDoc(
681                     webInfPath + java.io.File.separator + "mime.types");
682             String JavaDoc mimeType = mimeTypeFileTypeMap.getContentType(fileName);
683             
684             // to check if a file is being uploaded
685
if (fileName.length() == 0) {
686                 newUploadedFile = false;
687             }
688             
689             // checks if the file is new or it's being edited
690
if (currentFile.getInode() > 0) {
691                 // edit an existing file
692
editFile = true;
693                 // if it's being edited it keeps the same file name as the
694
// current one
695
fileName = currentFile.getFileName();
696             }
697             
698             String JavaDoc URI = folder.getPath() + fileName;
699             String JavaDoc friendlyName = file.getFriendlyName();
700             
701             // gets file extension
702
String JavaDoc suffix = UtilMethods.getFileExtension(fileName);
703             // sets filename for this new file
704
file.setFileName(fileName);
705             file.setFriendlyName(friendlyName);
706             // persists the file
707
file.setModUser(userId);
708             InodeFactory.saveInode(file);
709             
710             // gets the real path to the assets directory
711
String JavaDoc filePath = FileFactory.getRealAssetsRootPath();
712             new java.io.File JavaDoc(filePath).mkdir();
713             byte[] bytes = null;
714             
715             if (newUploadedFile) {
716                 
717                 bytes = FileUtil.getBytes(uploadReq.getFile("uploadedFile"));
718                 
719                 // sets bytes size from reuqest uploaded object
720
file.setSize(bytes.length - 2);
721                 file.setMimeType(mimeType);
722             } else {
723                 long workingFileInode = currentFile.getInode();
724                 String JavaDoc workingFileInodePath = String.valueOf(workingFileInode);
725                 if (workingFileInodePath.length() == 1) {
726                     workingFileInodePath = workingFileInodePath + "0";
727                 }
728                 // creates the path with inode{1} + inode{2}
729
workingFileInodePath = workingFileInodePath.substring(0, 1) + java.io.File.separator
730                 + workingFileInodePath.substring(1, 2);
731                 String JavaDoc workingFilePath = filePath + java.io.File.separator + workingFileInodePath
732                 + java.io.File.separator + workingFileInode + "." + suffix;
733                 
734                 java.io.File JavaDoc workingFile = new java.io.File JavaDoc(workingFilePath);
735                 FileInputStream JavaDoc is = new FileInputStream JavaDoc(workingFile);
736                 bytes = new byte[is.available()];
737                 is.read(bytes);
738                 
739                 file.setMimeType(currentFile.getMimeType());
740                 // sets bytes size from reuqest uploaded object
741
file.setSize(currentFile.getSize());
742             }
743             
744             // get host based on the parent folder
745
Host host = HostFactory.getParentHost(folder);
746             
747             // get the file Identifier
748
Identifier ident = IdentifierFactory.getIdentifierByURI(URI, host);
749             
750             // checks if another identifer with the same name exists in the same
751
// folder
752
if ((!editFile) && (FileFactory.existsFileName(folder, fileName))) {
753                 InodeFactory.deleteInode(file);
754                 SessionMessages.add(req, "message", "message.file_asset.error.filename.exists");
755                 throw new ActionException("message.file_asset.error.filename.exists");
756             }
757             // checks if the edited file has the same content type as the new
758
// one
759
else if ((editFile) && (newUploadedFile) && (!mimeType.equals(currentFile.getMimeType()))) {
760                 InodeFactory.deleteInode(file);
761                 SessionMessages.add(req, "message", "message.file_asset.error.mimetype");
762                 // when there is an error saving should unlock working asset
763
WebAssetFactory.unLockAsset(currentFile);
764                 throw new ActionException("message.file_asset.error.mimetype");
765             } else {
766                 
767                 try {
768                     if (editFile) {
769                         _saveWorkingFileData(filePath, currentFile, file, suffix, fileName, bytes);
770                     } else {
771                         _saveWorkingFileData(filePath, file, null, suffix, fileName, bytes);
772                     }
773                 } catch (Exception JavaDoc e) {
774                     Logger.error(this, e.toString(), e);
775                     InodeFactory.deleteInode(file);
776                     SessionMessages.add(req, "custommessage", e.getMessage());
777                     WebAssetFactory.unLockAsset(currentFile);
778                     return;
779                 }
780                 
781                 // gets parent identifier
782
Identifier identifier = IdentifierFactory.getParentIdentifier(currentFile);
783                 
784                 File workingFile = null;
785                 // it's going to save this asset
786
if (editFile) {
787                     // saves an edited file
788
WebAssetFactory.createAsset(file, userId, folder, ident, false);
789                     workingFile = (File) WebAssetFactory.saveAsset(file, ident);
790                     currentFile = file;
791                     req.setAttribute(WebKeys.FILE_FORM_EDIT, workingFile);
792                     if (currentFile.isLive())
793                         LiveCache.addToLiveAssetToCache(currentFile);
794                 } else {
795                     // creates a new file
796
WebAssetFactory.createAsset(file, userId, folder);
797                     workingFile = file;
798                     currentFile = file;
799                     req.setAttribute(WebKeys.FILE_FORM_EDIT, workingFile);
800                 }
801                 
802                 // Get parents of the old version so you can update the working
803
// information to this new version.
804
java.util.List JavaDoc<Tree> parentTrees = TreeFactory.getTreesByChild(currentFile);
805                 
806                 // update parents to new version delete old versions parents if
807
// not live.
808
for (Tree tree : parentTrees) {
809                     // to keep relation types from parent only if it exists
810
Tree newTree = TreeFactory.getTree(tree.getParent(), workingFile.getInode());
811                     if (newTree.getChild() == 0) {
812                         newTree.setParent(tree.getParent());
813                         newTree.setChild(workingFile.getInode());
814                         newTree.setRelationType(tree.getRelationType());
815                         newTree.setTreeOrder(0);
816                         TreeFactory.saveTree(newTree);
817                     }
818                 }
819                 
820                 // SAVING CATEGORIES BEGINS
821

822                 // wipe out the old categories
823
java.util.List JavaDoc _cats = InodeFactory.getParentsOfClass(identifier, Category.class);
824                 java.util.Iterator JavaDoc it = _cats.iterator();
825                 
826                 Logger.debug(this, "Number of categories:" + _cats.size());
827                 
828                 while (it.hasNext()) {
829                     Category cat = (Category) it.next();
830                     cat.deleteChild(identifier);
831                 }
832                 
833                 // add the new categories
834
if (arr != null) {
835                     for (int i = 0; i < arr.length; i++) {
836                         if (UtilMethods.isSet(arr[i])) {
837                             Category node = (Category) InodeFactory.getInode(arr[i], Category.class);
838                             
839                             Logger.debug(this, "Categories selected" + node.getInode());
840                             
841                             node.addChild(identifier);
842                         }
843                     }
844                 }
845                 // SAVING CATEGORIES ENDS
846

847                 SessionMessages.add(req, "message", "message.file_asset.save");
848                 
849                 if (file.isLive())
850                     LiveCache.addToLiveAssetToCache(file);
851                 WorkingCache.addToWorkingAssetToCache(workingFile);
852                 
853                 SessionMessages.add(req, "message", "message.file_asset.save");
854                 
855             }
856             
857             // Saving page permissions
858
_applyPermissions(req, WebKeys.FILE_FORM_EDIT);
859             
860             // for file in a popup
861
if (req.getParameter("popup") != null) {
862                 req.setAttribute("fileInode", file.getInode() + "");
863                 req.setAttribute("fileName", file.getFileName() + "");
864             }
865             
866             // copies the information back into the form bean
867
BeanUtils.copyProperties(form, req.getAttribute(WebKeys.FILE_FORM_EDIT));
868             
869             //Refreshing the menues
870
if (previousShowMenu != file.isShowOnMenu()) {
871                 //existing folder with different show on menu ... need to regenerate menu
872
RefreshMenus.deleteMenus();
873             }
874             
875         } catch (IOException JavaDoc e) {
876             Logger.error(this, "\n\n\nEXCEPTION IN FILE SAVING!!! " + e.getMessage(), e);
877             throw new ActionException(e.getMessage());
878         }
879     }
880     
881     public void _copyWebAsset(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user)
882     throws Exception JavaDoc {
883         
884         // wraps request to get session object
885
ActionRequestImpl reqImpl = (ActionRequestImpl) req;
886         HttpServletRequest JavaDoc httpReq = reqImpl.getHttpServletRequest();
887         
888         Logger.debug(this, "I'm copying the File");
889         
890         try {
891             // gets the current template being edited from the request object
892
File file = (File) req.getAttribute(WebKeys.FILE_EDIT);
893             
894             // gets folder parent
895
String JavaDoc parentInode = req.getParameter("parent");
896             Folder parent = null;
897             if (parentInode != null && parentInode.length() != 0 && !parentInode.equals("0")) {
898                 // the parent is being passed through the request
899
parent = (Folder) InodeFactory.getInode(parentInode, Folder.class);
900                 Logger.debug(this, "Parent Folder=" + parent.getInode());
901             } else {
902                 parent = (Folder) InodeFactory.getParentOfClass(file, Folder.class);
903                 Logger.debug(this, "Parent Folder=" + parent.getInode());
904             }
905             
906             // Checking permissions
907
_checkCopyAndMovePermissions(file, parent, user, httpReq, "copy");
908             
909             FileFactory.copyFile(file, parent);
910             
911             SessionMessages.add(req, "message", "message.file_asset.copy");
912             
913         } catch (IOException JavaDoc e) {
914             Logger.error(this, e.toString(), e);
915             throw new ActionException(e.getMessage());
916         }
917     }
918     
919     public void _getVersionBackWebAsset(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form,
920             User user) throws Exception JavaDoc {
921         
922         File workingFile = (File) super._getVersionBackWebAsset(req, res, config, form, user, File.class,
923                 WebKeys.FILE_EDIT);
924         File fileVersion = (File) req.getAttribute(WebKeys.FILE_EDIT);
925         
926         String JavaDoc filePath = FileFactory.getRealAssetsRootPath();
927         String JavaDoc suffix = UtilMethods.getFileExtension(workingFile.getFileName());
928         _restoreWorkingFileData(filePath, workingFile, fileVersion, suffix);
929         
930         
931         // Get parents of the old version so you can update the working
932
// information to this new version.
933
java.util.List JavaDoc<Tree> parentTrees = TreeFactory.getTreesByChild(fileVersion);
934         
935         // update parents to new version delete old versions parents if
936
// not live.
937
for (Tree tree : parentTrees) {
938             Tree newTree = TreeFactory.getTree(tree.getParent(), fileVersion.getInode());
939             if (newTree.getChild() == 0) {
940                 newTree.setParent(tree.getParent());
941                 newTree.setChild(workingFile.getInode());
942                 newTree.setRelationType(tree.getRelationType());
943                 newTree.setTreeOrder(0);
944                 TreeFactory.saveTree(newTree);
945             }
946         }
947         
948         WorkingCache.addToWorkingAssetToCache(workingFile);
949         if (fileVersion.isLive()){
950             LiveCache.addToLiveAssetToCache(fileVersion);
951         }
952         
953         long workingFileInode = workingFile.getInode();
954         String JavaDoc workingFileInodePath = String.valueOf(workingFileInode);
955         if (workingFileInodePath.length() == 1) {
956             workingFileInodePath = workingFileInodePath + "0";
957         }
958         // creates the path with inode{1} + inode{2}
959
workingFileInodePath = workingFileInodePath.substring(0, 1) + java.io.File.separator
960         + workingFileInodePath.substring(1, 2);
961         
962         java.io.File JavaDoc directory = new java.io.File JavaDoc(filePath + java.io.File.separator + workingFileInodePath);
963         java.io.File JavaDoc[] files = directory.listFiles();
964         
965         String JavaDoc thumbsIndex = workingFile.getInode() + "_thumb_";
966         
967         for (java.io.File JavaDoc file : files)
968             if (file.getName().indexOf(thumbsIndex) >= 0) {
969                 try {
970                     file.delete();
971                 } catch (SecurityException JavaDoc e) {
972                     Logger.info("EditFileAction._saveWorkingFileData(): " + file.getName()
973                             + " cannot be erased. Please check the file permissions.");
974                 } catch (Exception JavaDoc e) {
975                     Logger.info("EditFileAction._saveWorkingFileData(): " + e.getMessage());
976                 }
977             }
978         
979         
980         thumbsIndex = "resized_" + workingFile.getIdentifier();
981         for (java.io.File JavaDoc file : files)
982             if (file.getName().indexOf(thumbsIndex) >= 0) {
983                 try {
984                     file.delete();
985                 } catch (SecurityException JavaDoc e) {
986                     Logger.info("EditFileAction._saveWorkingFileData(): " + file.getName()
987                             + " cannot be erased. Please check the file permissions.");
988                 } catch (Exception JavaDoc e) {
989                     Logger.info("EditFileAction._saveWorkingFileData(): " + e.getMessage());
990                 }
991             }
992         
993     }
994     
995 }
Popular Tags