- Check when renaming file that name doesn't already exist.
[pithos] / src / gr / ebs / gss / server / rest / TrashHandler.java
1 /*
2  * Copyright 2008, 2009 Electronic Business Systems Ltd.
3  *
4  * This file is part of GSS.
5  *
6  * GSS is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * GSS is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with GSS.  If not, see <http://www.gnu.org/licenses/>.
18  */
19 package gr.ebs.gss.server.rest;
20
21 import gr.ebs.gss.client.exceptions.InsufficientPermissionsException;
22 import gr.ebs.gss.client.exceptions.ObjectNotFoundException;
23 import gr.ebs.gss.client.exceptions.RpcException;
24 import gr.ebs.gss.server.domain.User;
25 import gr.ebs.gss.server.domain.dto.FileHeaderDTO;
26 import gr.ebs.gss.server.domain.dto.FolderDTO;
27 import gr.ebs.gss.server.ejb.TransactionHelper;
28
29 import java.io.IOException;
30 import java.net.URLEncoder;
31 import java.util.ArrayList;
32 import java.util.List;
33 import java.util.concurrent.Callable;
34
35 import javax.servlet.ServletException;
36 import javax.servlet.http.HttpServletRequest;
37 import javax.servlet.http.HttpServletResponse;
38
39 import org.apache.commons.logging.Log;
40 import org.apache.commons.logging.LogFactory;
41 import org.json.JSONException;
42 import org.json.JSONObject;
43
44
45 /**
46  * A class that handles operations on the 'trash' namespace.
47  *
48  * @author past
49  */
50 public class TrashHandler extends RequestHandler {
51         /**
52          * The logger.
53          */
54         private static Log logger = LogFactory.getLog(TrashHandler.class);
55
56         /**
57          * Return the files and folders that are in the trash can.
58          *
59      * @param req The servlet request we are processing
60      * @param resp The servlet response we are processing
61          * @throws IOException if the response cannot be sent
62          * @throws ServletException
63          */
64         void serveTrash(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
65         String path = getInnerPath(req, PATH_TRASH);
66                 if (path.equals(""))
67                         path = "/";
68
69         if (!path.equals("/")) {
70                         resp.sendError(HttpServletResponse.SC_NOT_FOUND);
71                         return;
72         }
73
74         List<FileHeaderDTO> files = null;
75                 List<FolderDTO> folders = null;
76         User user = getUser(req);
77         User owner = getOwner(req);
78         if (!owner.equals(user)) {
79                 resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
80                 return;
81         }
82                 try {
83                         files = getService().getDeletedFiles(user.getId());
84                         folders = getService().getDeletedRootFolders(user.getId());
85                 } catch (ObjectNotFoundException e) {
86                         resp.sendError(HttpServletResponse.SC_NOT_FOUND);
87                         return;
88                 } catch (RpcException e) {
89                         logger.error("", e);
90                         resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
91                         return;
92                 }
93
94                 if (files.isEmpty() && folders.isEmpty()) {
95                         resp.sendError(HttpServletResponse.SC_NO_CONTENT);
96                         return;
97                 }
98
99                 JSONObject json = new JSONObject();
100         try {
101                 List<JSONObject> trashFolders = new ArrayList<JSONObject>();
102                 for (FolderDTO f: folders) {
103                         JSONObject j = new JSONObject();
104                         j.put("name", f.getName()).
105                                 put("uri", getApiRoot() + f.getURI());
106                         if (f.getParent() != null)
107                                 j.put("parent", getApiRoot() + f.getParent().getURI());
108                                 trashFolders.add(j);
109                 }
110                 json.put("folders", trashFolders);
111                 List<JSONObject> trashFiles = new ArrayList<JSONObject>();
112                 for (FileHeaderDTO f: files) {
113                         JSONObject j = new JSONObject();
114                                 j.put("name", f.getName()).
115                                         put("owner", f.getOwner().getUsername()).
116                                         put("deleted", f.isDeleted()).
117                                         put("version", f.getVersion()).
118                                         put("size", f.getFileSize()).
119                                         put("content", f.getMimeType()).
120                                         put("path", f.getFolder().getPath()).
121                                         put("creationDate", f.getAuditInfo().getCreationDate().getTime()).
122                                         put("modificationDate", f.getAuditInfo().getModificationDate().getTime()).
123                                 put("uri", getApiRoot() + f.getURI());
124                                 JSONObject p = new JSONObject();
125                                 p.put("uri", getApiRoot() + f.getFolder().getURI()).
126                                                 put("name", URLEncoder.encode(f.getFolder().getName(),"UTF-8"));
127                                 j.put("folder", p);
128                                 trashFiles.add(j);
129                 }
130                 json.put("files", trashFiles);
131                 } catch (JSONException e) {
132                         logger.error("", e);
133                         resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
134                         return;
135                 }
136
137                 // Workaround for IE's broken caching behavior.
138                 resp.setHeader("Expires", "-1");
139         sendJson(req, resp, json.toString());
140         }
141
142         /**
143          * Empties the trash can from any currently stored resource,
144          * making all trashed files and folders permanently deleted.
145          *
146      * @param req The HTTP request we are processing
147      * @param resp The HTTP response we are processing
148          * @throws IOException
149      * @throws IOException if an input/output error occurs
150          */
151         public void emptyTrash(HttpServletRequest req, HttpServletResponse resp) throws IOException {
152         String path = getInnerPath(req, PATH_TRASH);
153                 if (path.equals(""))
154                         path = "/";
155
156         if (!path.equals("/")) {
157                         resp.sendError(HttpServletResponse.SC_NOT_FOUND);
158                         return;
159         }
160                 try {
161                         User user = getUser(req);
162                         final User owner = getOwner(req);
163                         if (!owner.equals(user))
164                                 throw new InsufficientPermissionsException("User " + user.getUsername()
165                                                         + " does not have permission to empty the trash can owned by "
166                                                         + owner.getUsername());
167                         if (logger.isDebugEnabled())
168                                 logger.debug("Emptying trash for user " + owner.getUsername());
169                         new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
170                                 @Override
171                                 public Void call() throws Exception {
172                                         getService().emptyTrash(owner.getId());
173                                         return null;
174                                 }
175                         });
176                         resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
177                 } catch (RpcException e) {
178                         logger.error("", e);
179                         resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
180                 } catch (ObjectNotFoundException e) {
181                         resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
182                 } catch (InsufficientPermissionsException e) {
183                         resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, e.getMessage());
184                 } catch (Exception e) {
185                         logger.error("", e);
186                         resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
187                 }
188         }
189
190 }