View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    * 
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   * 
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.jetspeed.layout.impl;
18  
19  import java.io.File;
20  import java.io.FileInputStream;
21  import java.io.FileOutputStream;
22  import java.util.Iterator;
23  import java.util.Map;
24  import java.util.zip.ZipEntry;
25  import java.util.zip.ZipOutputStream;
26  
27  import org.apache.commons.logging.Log;
28  import org.apache.commons.logging.LogFactory;
29  import org.apache.jetspeed.JetspeedActions;
30  import org.apache.jetspeed.ajax.AjaxAction;
31  import org.apache.jetspeed.ajax.AjaxBuilder;
32  import org.apache.jetspeed.exception.JetspeedException;
33  import org.apache.jetspeed.layout.PortletActionSecurityBehavior;
34  import org.apache.jetspeed.om.folder.Folder;
35  import org.apache.jetspeed.om.page.Link;
36  import org.apache.jetspeed.om.page.Page;
37  import org.apache.jetspeed.page.PageManager;
38  import org.apache.jetspeed.request.RequestContext;
39  /***
40   * Exporting the object using Ajax command
41   * 
42   * @author <a href="mailto:firevelocity@gmail.com">Vivek Kumar</a>
43   * @version $Id$
44   */
45  public class ExportObject extends BaseGetResourceAction implements AjaxAction, AjaxBuilder, Constants {
46  	protected Log log = LogFactory.getLog(GetFolderAction.class);
47  
48  	protected PageManager castorPageManager;
49  
50  	protected String pageRoot;
51  
52  	private static final String OBJECT_NAME = "objName";
53  
54  	private static final String OBJECT_TYPE = "objType";
55  
56  	private static final String OBJECT_PATH = "objPath";
57  
58  	private static final String RECURSIVE = "exptRecusive";
59  	String pathSeprator = System.getProperty("file.separator");
60  	public ExportObject(String template, String errorTemplate, PageManager pageManager,
61  			PortletActionSecurityBehavior securityBehavior, PageManager castorpagemanager, String dir) {
62  		super(template, errorTemplate, pageManager, securityBehavior);
63  		this.castorPageManager = castorpagemanager;
64  		this.pageRoot = dir;
65  	}
66  
67  	public boolean run(RequestContext requestContext, Map resultMap) {
68  		boolean success = true;
69  		String status = "success";
70  		String userName = requestContext.getUserPrincipal().toString();
71  		try {
72  			resultMap.put(ACTION, "export");
73  			if (false == checkAccess(requestContext, JetspeedActions.VIEW)) {
74  				success = false;
75  				resultMap.put(REASON, "Insufficient access to get portlets");
76  				return success;
77  			}
78  			String objectName = getActionParameter(requestContext, OBJECT_NAME);
79  			String objectType = getActionParameter(requestContext, OBJECT_TYPE);
80  			String objectPath = getActionParameter(requestContext, OBJECT_PATH);
81  			String recursive = getActionParameter(requestContext, RECURSIVE);
82  			boolean isRecursive = recursive != null && recursive.equals("1") ? true : false;
83  
84  			if (!cleanUserFolder(userName))
85  				success = false;
86  			if (success) {
87  				if (objectType.equalsIgnoreCase("folder")) {
88  					Folder folder = pageManager.getFolder(objectPath);
89  					if (isRecursive) {
90  							importFolder(folder,userName,getRealPath(folder.getPath()));
91  					} else {
92  						Folder destFolder = castorPageManager.copyFolder(folder, getUserFolder(userName, true)
93  								+ objectName);
94  						castorPageManager.updateFolder(destFolder);
95  					}
96  				} else if (objectType.equalsIgnoreCase("page")) {
97  					objectPath = getParentPath(objectPath);
98  					Folder folder = pageManager.getFolder(objectPath);
99  					Page page = folder.getPage(objectName);
100 					Page destPage = castorPageManager.copyPage(page, getUserFolder(userName, true) + objectName);
101 					castorPageManager.updatePage(destPage);
102 				} else if (objectType.equalsIgnoreCase("link")) {
103 					objectPath = getParentPath(objectPath);
104 					Folder folder = pageManager.getFolder(objectPath);
105 					Link link = folder.getLink(objectName);
106 					Link destLink = castorPageManager.copyLink(link, getUserFolder(userName, true) + objectName);
107 					castorPageManager.updateLink(destLink);
108 				}
109 				String link = userName + "_" + objectName;
110 				if (objectType.equalsIgnoreCase("folder")) link = userName + ".zip";
111 				requestContext.getRequest().getSession().setAttribute("file", link);
112 				resultMap.put("link", getDownloadLink(requestContext, objectName, userName, objectType));
113 			}
114 			if (!success)
115 				status = "failure";
116 
117 			resultMap.put(STATUS, status);
118 		} catch (Exception e) {
119 			// Log the exception
120 			e.printStackTrace();
121 			log.error("exception while getting folder info", e);
122 
123 			// Return a failure indicator
124 			success = false;
125 		}
126 
127 		return success;
128 	}
129 
130 	private String getDownloadLink(RequestContext requestContext, String ObjectName, String userName, String objectType)
131 			throws Exception {
132 		String link = "";
133 		String basePath = requestContext.getRequest().getContextPath() + "/fileserver/_content/";
134 		if (objectType.equalsIgnoreCase("folder")) {
135 			String sourcePath = getUserFolder(userName, false);
136 			String target = sourcePath + ".zip";
137 			boolean success = zipObject(sourcePath, target);
138 			if (!success)
139 				throw new Exception("Error Occurered in zipping the file");
140 
141 			link = basePath + ObjectName+".zip";
142 		} else {
143 			link = basePath + userName + "/" +  ObjectName;
144 		}
145 		return link;
146 	}
147 
148 	private boolean cleanUserFolder(String userName) {
149 		boolean success = false;
150 		synchronized (this) {
151 			String folder = getUserFolder(userName, false);
152 			File dir = new File(pageRoot+pathSeprator+userName+".zip");
153 			if(dir.exists()) dir.delete();
154 			
155 			dir = new File(folder);
156 			if (dir.exists()) {
157                 success = deleteDir(dir);
158 			} 
159             success = dir.mkdir();
160 		}
161 		return success;
162 	}
163 
164     private boolean deleteDir(File dir) {
165         if( dir.exists() ) {
166             File[] files = dir.listFiles();
167             for(int i=0; i<files.length; i++) {
168                if(files[i].isDirectory()) {
169                    deleteDir(files[i]);
170                }
171                else {
172                  files[i].delete();
173                }
174             }
175           }
176           return( dir.delete() );
177 	}
178 
179 	private String getUserFolder(String userName, boolean fullPath) {
180 		if (pathSeprator == null || pathSeprator.equals(""))
181 			pathSeprator = "/";
182 		if (fullPath) {
183 			return userName + pathSeprator;
184 		} else {
185 			return pageRoot + pathSeprator + userName;
186 		}
187 	}
188 
189 	private String getParentPath(String path) {
190 		int index = path.lastIndexOf("/");
191 
192 		if (index == 0) {
193 			return "/";
194 		} else {
195 			return path.substring(0, index);
196 		}
197 	}
198 
199 	private boolean zipObject(String sourcePath, String target) {
200 		ZipOutputStream cpZipOutputStream = null;
201 		try {
202 			File cpFile = new File(sourcePath);
203 			if (!cpFile.isDirectory()) {
204 				return false;
205 			}
206 			cpZipOutputStream = new ZipOutputStream(new FileOutputStream(target));
207 			cpZipOutputStream.setLevel(9);
208 			zipFiles(cpFile, sourcePath, cpZipOutputStream);
209 			cpZipOutputStream.finish();
210 			cpZipOutputStream.close();
211 		} catch (Exception e) {	
212 			e.printStackTrace();
213 			return false;
214 		}
215 		finally{
216 		}
217 		return true;
218 	}
219 
220 	private void zipFiles(File cpFile, String sourcePath, ZipOutputStream cpZipOutputStream) {
221 
222 		if (cpFile.isDirectory()) {
223 			File[] fList = cpFile.listFiles();
224 			for (int i = 0; i < fList.length; i++) {
225 				zipFiles(fList[i], sourcePath, cpZipOutputStream);
226 			}
227 		} else {
228 			try {
229 				String strAbsPath = cpFile.getAbsolutePath();
230 				String strZipEntryName = strAbsPath.substring(sourcePath.length() + 1, strAbsPath.length());
231 				byte[] b = new byte[(int) (cpFile.length())];
232 				FileInputStream cpFileInputStream = new FileInputStream(cpFile);
233 				int i = cpFileInputStream.read(b, 0, (int) cpFile.length());
234 				ZipEntry cpZipEntry = new ZipEntry(strZipEntryName);
235 				cpZipOutputStream.putNextEntry(cpZipEntry);
236 				cpZipOutputStream.write(b, 0, (int) cpFile.length());
237 				cpZipOutputStream.closeEntry();
238 				cpFileInputStream.close();
239 			} catch (Exception e) {
240 				e.printStackTrace();
241 			}
242 		}
243 	}
244 
245 	private Folder importFolder(Folder srcFolder,String userName,String destination) throws JetspeedException {
246         String newPath="";
247         Folder dstFolder = lookupFolder(srcFolder.getPath());
248 		dstFolder = castorPageManager.copyFolder(srcFolder, getUserFolder(userName, true) + destination);
249 		castorPageManager.updateFolder(dstFolder);
250 
251 		Iterator pages = srcFolder.getPages().iterator();
252 		while (pages.hasNext()) {
253 			Page srcPage = (Page) pages.next();
254 			Page dstPage = lookupPage(srcPage.getPath());
255             newPath = getUserFolder(userName, true) +destination+ getRealPath(srcPage.getPath()); 
256 			dstPage = castorPageManager.copyPage(srcPage, newPath);
257 			castorPageManager.updatePage(dstPage);
258 		}
259 
260 		Iterator links = srcFolder.getLinks().iterator();
261 		while (links.hasNext()) {
262 			Link srcLink = (Link) links.next();
263 			Link dstLink = lookupLink(srcLink.getPath());
264             newPath = getUserFolder(userName, true) +destination+ getRealPath(srcLink.getPath());
265 			dstLink = castorPageManager.copyLink(srcLink,newPath);
266 			castorPageManager.updateLink(dstLink);
267 		}
268 		Iterator folders = srcFolder.getFolders().iterator();
269 		while (folders.hasNext()) {
270 			Folder folder = (Folder) folders.next();
271             newPath = destination+getRealPath(folder.getPath());
272 			importFolder(folder,userName,newPath);
273 		}
274 
275 		return dstFolder;
276 	}
277 
278 	private Page lookupPage(String path) {
279 		try {
280 			return castorPageManager.getPage(path);
281 		} catch (Exception e) {
282 			return null;
283 		}
284 	}
285 
286 	private Link lookupLink(String path) {
287 		try {
288 			return castorPageManager.getLink(path);
289 		} catch (Exception e) {
290 			return null;
291 		}
292 	}
293 
294 	private Folder lookupFolder(String path) {
295 		try {
296 			return castorPageManager.getFolder(path);
297 		} catch (Exception e) {
298 			return null;
299 		}
300 	}
301     private String getRealPath(String path){
302         int index = path.lastIndexOf("/");
303         if (index>0)
304         {
305             return path.substring(index);
306         }
307         return path;
308          
309     }
310 }