2 * Copyright 2008, 2009 Electronic Business Systems Ltd.
4 * This file is part of GSS.
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.
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.
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/>.
19 package gr.ebs.gss.server.rest;
21 import gr.ebs.gss.client.exceptions.DuplicateNameException;
22 import gr.ebs.gss.client.exceptions.GSSIOException;
23 import gr.ebs.gss.client.exceptions.InsufficientPermissionsException;
24 import gr.ebs.gss.client.exceptions.ObjectNotFoundException;
25 import gr.ebs.gss.client.exceptions.QuotaExceededException;
26 import gr.ebs.gss.client.exceptions.RpcException;
27 import gr.ebs.gss.server.domain.FileUploadStatus;
28 import gr.ebs.gss.server.domain.User;
29 import gr.ebs.gss.server.domain.dto.FileBodyDTO;
30 import gr.ebs.gss.server.domain.dto.FileHeaderDTO;
31 import gr.ebs.gss.server.domain.dto.FolderDTO;
32 import gr.ebs.gss.server.domain.dto.GroupDTO;
33 import gr.ebs.gss.server.domain.dto.PermissionDTO;
34 import gr.ebs.gss.server.ejb.ExternalAPI;
35 import gr.ebs.gss.server.ejb.TransactionHelper;
36 import gr.ebs.gss.server.webdav.Range;
38 import java.io.BufferedReader;
39 import java.io.ByteArrayInputStream;
40 import java.io.ByteArrayOutputStream;
42 import java.io.FileInputStream;
43 import java.io.FileNotFoundException;
44 import java.io.IOException;
45 import java.io.InputStream;
46 import java.io.InputStreamReader;
47 import java.io.OutputStreamWriter;
48 import java.io.PrintWriter;
49 import java.io.UnsupportedEncodingException;
51 import java.net.URISyntaxException;
52 import java.net.URLDecoder;
53 import java.net.URLEncoder;
54 import java.util.ArrayList;
55 import java.util.Collection;
56 import java.util.Date;
57 import java.util.HashSet;
58 import java.util.List;
60 import java.util.StringTokenizer;
61 import java.util.concurrent.Callable;
63 import javax.servlet.ServletContext;
64 import javax.servlet.ServletException;
65 import javax.servlet.ServletOutputStream;
66 import javax.servlet.http.HttpServletRequest;
67 import javax.servlet.http.HttpServletResponse;
69 import org.apache.commons.fileupload.FileItemIterator;
70 import org.apache.commons.fileupload.FileItemStream;
71 import org.apache.commons.fileupload.FileUploadException;
72 import org.apache.commons.fileupload.ProgressListener;
73 import org.apache.commons.fileupload.servlet.ServletFileUpload;
74 import org.apache.commons.fileupload.util.Streams;
75 import org.apache.commons.httpclient.util.DateParseException;
76 import org.apache.commons.httpclient.util.DateUtil;
77 import org.apache.commons.logging.Log;
78 import org.apache.commons.logging.LogFactory;
79 import org.json.JSONArray;
80 import org.json.JSONException;
81 import org.json.JSONObject;
85 * A class that handles operations on the 'files' namespace.
89 public class FilesHandler extends RequestHandler {
91 * The request parameter name for fetching a different version.
93 private static final String VERSION_PARAM = "version";
96 * The request attribute containing the owner of the destination URI
97 * in a copy or move request.
99 private static final String DESTINATION_OWNER_ATTRIBUTE = "destOwner";
101 private static final int TRACK_PROGRESS_PERCENT = 5;
104 * The form parameter name that contains the signature in a browser POST upload.
106 private static final String AUTHORIZATION_PARAMETER = "Authorization";
109 * The form parameter name that contains the date in a browser POST upload.
111 private static final String DATE_PARAMETER = "Date";
114 * The request parameter name for making an upload progress request.
116 private static final String PROGRESS_PARAMETER = "progress";
119 * The request parameter name for restoring a previous version of a file.
121 private static final String RESTORE_VERSION_PARAMETER = "restoreVersion";
126 private static Log logger = LogFactory.getLog(FilesHandler.class);
129 * The servlet context provided by the call site.
131 private ServletContext context;
134 * @param servletContext
136 public FilesHandler(ServletContext servletContext) {
137 context = servletContext;
140 private void updateAccounting(final User user, final Date date, final long bandwidthDiff) {
142 new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
144 public Void call() throws Exception {
145 getService().updateAccounting(user, date, bandwidthDiff);
149 } catch (RuntimeException e) {
151 } catch (Exception e) {
152 // updateAccounting() doesn't throw any checked exceptions
158 * Serve the specified resource, optionally including the data content.
160 * @param req The servlet request we are processing
161 * @param resp The servlet response we are creating
162 * @param content Should the content be included?
164 * @exception IOException if an input/output error occurs
165 * @exception ServletException if a servlet-specified error occurs
166 * @throws RpcException
167 * @throws InsufficientPermissionsException
168 * @throws ObjectNotFoundException
171 protected void serveResource(HttpServletRequest req, HttpServletResponse resp, boolean content)
172 throws IOException, ServletException {
173 boolean authDeferred = getAuthDeferred(req);
174 String path = getInnerPath(req, PATH_FILES);
178 path = URLDecoder.decode(path, "UTF-8");
179 } catch (IllegalArgumentException e) {
180 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
183 String progress = req.getParameter(PROGRESS_PARAMETER);
185 if (logger.isDebugEnabled())
187 logger.debug("Serving resource '" + path + "' headers and data");
189 logger.debug("Serving resource '" + path + "' headers only");
191 User user = getUser(req);
192 User owner = getOwner(req);
193 if (user == null) user = owner;
194 boolean exists = true;
195 Object resource = null;
196 FileHeaderDTO file = null;
197 FolderDTO folder = null;
199 resource = getService().getResourceAtPath(owner.getId(), path, false);
200 } catch (ObjectNotFoundException e) {
202 } catch (RpcException e) {
203 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
209 // We do not want to leak information if the request
210 // was not authenticated.
211 resp.sendError(HttpServletResponse.SC_FORBIDDEN);
214 // A request for upload progress.
215 if (progress != null && content) {
216 serveProgress(req, resp, progress, user, null);
220 resp.sendError(HttpServletResponse.SC_NOT_FOUND, req.getRequestURI());
224 if (resource instanceof FolderDTO)
225 folder = (FolderDTO) resource;
227 file = (FileHeaderDTO) resource;
229 // Now it's time to perform the deferred authentication check.
230 // Since regular signature checking was already performed,
231 // we need to check the read-all flag or the signature-in-parameters.
233 if (file != null && !file.isReadForAll() && content) {
234 // Check for GET with the signature in the request parameters.
235 String auth = req.getParameter(AUTHORIZATION_PARAMETER);
236 String dateParam = req.getParameter(DATE_PARAMETER);
237 if (auth == null || dateParam == null) {
238 resp.sendError(HttpServletResponse.SC_FORBIDDEN);
244 timestamp = DateUtil.parseDate(dateParam).getTime();
245 } catch (DateParseException e) {
246 resp.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
249 if (!isTimeValid(timestamp)) {
250 resp.sendError(HttpServletResponse.SC_FORBIDDEN);
254 // Fetch the Authorization parameter and find the user specified in it.
255 String[] authParts = auth.split(" ");
256 if (authParts.length != 2) {
257 resp.sendError(HttpServletResponse.SC_FORBIDDEN);
260 String username = authParts[0];
261 String signature = authParts[1];
264 user = getService().findUser(username);
265 } catch (RpcException e) {
266 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
270 resp.sendError(HttpServletResponse.SC_FORBIDDEN);
273 req.setAttribute(USER_ATTRIBUTE, user);
275 // Remove the servlet path from the request URI.
276 String p = req.getRequestURI();
277 String servletPath = req.getContextPath() + req.getServletPath();
278 p = p.substring(servletPath.length());
279 // Validate the signature in the Authorization parameter.
280 String data = req.getMethod() + dateParam + p;
281 if (!isSignatureValid(signature, user, data)) {
282 resp.sendError(HttpServletResponse.SC_FORBIDDEN);
285 } else if (file != null && !file.isReadForAll() || file == null) {
286 // Check for a read-for-all file request.
287 resp.sendError(HttpServletResponse.SC_FORBIDDEN);
291 // If the resource is not a collection, and the resource path
292 // ends with "/" or "\", return NOT FOUND.
294 if (path.endsWith("/") || path.endsWith("\\")) {
295 resp.sendError(HttpServletResponse.SC_NOT_FOUND, req.getRequestURI());
299 // Workaround for IE's broken caching behavior.
301 resp.setHeader("Expires", "-1");
303 // A request for upload progress.
304 if (progress != null && content) {
306 resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
309 serveProgress(req, resp, progress, user, file);
313 // Fetch the version to retrieve, if specified.
314 String verStr = req.getParameter(VERSION_PARAM);
316 FileBodyDTO oldBody = null;
317 if (verStr != null && file != null)
319 version = Integer.valueOf(verStr);
320 } catch (NumberFormatException e) {
321 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, req.getRequestURI());
326 oldBody = getService().getFileVersion(user.getId(), file.getId(), version);
327 } catch (RpcException e) {
328 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
330 } catch (ObjectNotFoundException e) {
331 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
333 } catch (InsufficientPermissionsException e) {
334 resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
338 // Check if the conditions specified in the optional If headers are
339 // satisfied. Doing this for folders would require recursive checking
340 // for all of their children, which in turn would defy the purpose of
343 // Checking If headers.
344 if (!checkIfHeaders(req, resp, file, oldBody))
347 // Find content type.
348 String contentType = null;
350 contentType = version>0 ? oldBody.getMimeType() : file.getMimeType();
351 if (contentType == null) {
352 contentType = context.getMimeType(file.getName());
353 file.setMimeType(contentType);
356 contentType = "application/json;charset=UTF-8";
358 ArrayList ranges = null;
359 long contentLength = -1L;
362 // Parse range specifier.
363 ranges = parseRange(req, resp, file, oldBody);
365 resp.setHeader("ETag", getETag(file, oldBody));
366 // Last-Modified header.
367 String lastModified = oldBody == null ?
368 getLastModifiedHttp(file.getAuditInfo()) :
369 getLastModifiedHttp(oldBody.getAuditInfo());
370 resp.setHeader("Last-Modified", lastModified);
371 // X-GSS-Metadata header.
373 resp.setHeader("X-GSS-Metadata", renderJson(user, file, oldBody));
374 } catch (InsufficientPermissionsException e) {
375 resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
378 // Get content length.
379 contentLength = version>0 ? oldBody.getFileSize() : file.getFileSize();
380 // Special case for zero length files, which would cause a
381 // (silent) ISE when setting the output buffer size.
382 if (contentLength == 0L)
385 // Set the folder X-GSS-Metadata header.
387 resp.setHeader("X-GSS-Metadata", renderJsonMetadata(user, folder));
388 } catch (InsufficientPermissionsException e) {
389 resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
393 ServletOutputStream ostream = null;
394 PrintWriter writer = null;
398 ostream = resp.getOutputStream();
399 } catch (IllegalStateException e) {
400 // If it fails, we try to get a Writer instead if we're
401 // trying to serve a text file
402 if ( contentType == null
403 || contentType.startsWith("text")
404 || contentType.endsWith("xml") )
405 writer = resp.getWriter();
411 || (ranges == null || ranges.isEmpty())
412 && req.getHeader("Range") == null
414 // Set the appropriate output headers
415 if (contentType != null) {
416 if (logger.isDebugEnabled())
417 logger.debug("contentType='" + contentType + "'");
418 resp.setContentType(contentType);
420 if (file != null && contentLength >= 0) {
421 if (logger.isDebugEnabled())
422 logger.debug("contentLength=" + contentLength);
423 if (contentLength < Integer.MAX_VALUE)
424 resp.setContentLength((int) contentLength);
426 // Set the content-length as String to be able to use a long
427 resp.setHeader("content-length", "" + contentLength);
430 InputStream renderResult = null;
433 // Serve the directory browser
435 renderResult = renderJson(user, folder);
436 } catch (InsufficientPermissionsException e) {
437 resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
440 // Copy the input stream to our output stream (if requested)
443 resp.setBufferSize(output);
444 } catch (IllegalStateException e) {
449 if (needsContentDisposition(req))
450 resp.setHeader("Content-Disposition","attachment; filename*=UTF-8''"+URLEncoder.encode(file.getName(),"UTF-8"));
452 resp.setHeader("Content-Disposition","inline; filename*=UTF-8''"+URLEncoder.encode(file.getName(),"UTF-8"));
454 copy(file, renderResult, ostream, req, oldBody);
456 copy(file, renderResult, writer, req, oldBody);
457 if (file!=null) updateAccounting(owner, new Date(), contentLength);
458 } catch (ObjectNotFoundException e) {
459 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
461 } catch (InsufficientPermissionsException e) {
462 resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
464 } catch (RpcException e) {
465 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
470 if (ranges == null || ranges.isEmpty())
472 // Partial content response.
473 resp.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
475 if (ranges.size() == 1) {
476 Range range = (Range) ranges.get(0);
477 resp.addHeader("Content-Range", "bytes "
479 + "-" + range.end + "/"
481 long length = range.end - range.start + 1;
482 if (length < Integer.MAX_VALUE)
483 resp.setContentLength((int) length);
485 // Set the content-length as String to be able to use a long
486 resp.setHeader("content-length", "" + length);
488 if (contentType != null) {
489 if (logger.isDebugEnabled())
490 logger.debug("contentType='" + contentType + "'");
491 resp.setContentType(contentType);
496 resp.setBufferSize(output);
497 } catch (IllegalStateException e) {
502 copy(file, ostream, range, req, oldBody);
504 copy(file, writer, range, req, oldBody);
505 updateAccounting(owner, new Date(), contentLength);
506 } catch (ObjectNotFoundException e) {
507 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
509 } catch (InsufficientPermissionsException e) {
510 resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
512 } catch (RpcException e) {
513 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
518 resp.setContentType("multipart/byteranges; boundary=" + mimeSeparation);
521 resp.setBufferSize(output);
522 } catch (IllegalStateException e) {
527 copy(file, ostream, ranges.iterator(), contentType, req, oldBody);
529 copy(file, writer, ranges.iterator(), contentType, req, oldBody);
530 updateAccounting(owner, new Date(), contentLength);
531 } catch (ObjectNotFoundException e) {
532 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
534 } catch (InsufficientPermissionsException e) {
535 resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
537 } catch (RpcException e) {
538 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
547 * Determines whether the user agent needs the Content-Disposition
548 * header to be set, in order to properly download a file.
550 * @param req the HTTP request
551 * @return true if the Content-Disposition HTTP header must be set
553 private boolean needsContentDisposition(HttpServletRequest req) {
554 /*String agent = req.getHeader("user-agent");
555 if (agent != null && agent.contains("MSIE"))
557 String dl = req.getParameter("dl");
564 * Sends a progress update on the amount of bytes received until now for
565 * a file that the current user is currently uploading.
567 * @param req the HTTP request
568 * @param resp the HTTP response
569 * @param parameter the value for the progress request parameter
570 * @param user the current user
571 * @param file the file being uploaded, or null if the request is about a new file
572 * @throws IOException if an I/O error occurs
574 private void serveProgress(HttpServletRequest req, HttpServletResponse resp,
575 String parameter, User user, FileHeaderDTO file) throws IOException {
576 String filename = file == null ? parameter : file.getName();
578 FileUploadStatus status = getService().getFileUploadStatus(user.getId(), filename);
579 if (status == null) {
580 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
583 JSONObject json = new JSONObject();
584 json.put("bytesUploaded", status.getBytesUploaded()).
585 put("bytesTotal", status.getFileSize());
586 sendJson(req, resp, json.toString());
588 // Workaround for IE's broken caching behavior.
589 resp.setHeader("Expires", "-1");
591 } catch (RpcException e) {
592 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
594 } catch (JSONException e) {
595 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
601 * Server a POST request to create/modify a file or folder.
603 * @param req the HTTP request
604 * @param resp the HTTP response
605 * @exception IOException if an input/output error occurs
607 void postResource(HttpServletRequest req, HttpServletResponse resp) throws IOException {
608 boolean authDeferred = getAuthDeferred(req);
609 if (!authDeferred && req.getParameterMap().size() > 1) {
610 resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
613 String path = getInnerPath(req, PATH_FILES);
614 path = path.endsWith("/")? path: path + '/';
616 path = URLDecoder.decode(path, "UTF-8");
617 } catch (IllegalArgumentException e) {
618 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
621 // We only defer authenticating multipart POST requests.
623 if (!ServletFileUpload.isMultipartContent(req)) {
624 resp.sendError(HttpServletResponse.SC_FORBIDDEN);
627 handleMultipart(req, resp, path);
631 String newName = req.getParameter(NEW_FOLDER_PARAMETER);
632 boolean hasUpdateParam = req.getParameterMap().containsKey(RESOURCE_UPDATE_PARAMETER);
633 boolean hasTrashParam = req.getParameterMap().containsKey(RESOURCE_TRASH_PARAMETER);
634 boolean hasRestoreParam = req.getParameterMap().containsKey(RESOURCE_RESTORE_PARAMETER);
635 String copyTo = req.getParameter(RESOURCE_COPY_PARAMETER);
636 String moveTo = req.getParameter(RESOURCE_MOVE_PARAMETER);
637 String restoreVersion = req.getParameter(RESTORE_VERSION_PARAMETER);
640 createFolder(req, resp, path, newName);
641 else if (hasUpdateParam)
642 updateResource(req, resp, path);
643 else if (hasTrashParam)
644 trashResource(req, resp, path);
645 else if (hasRestoreParam)
646 restoreResource(req, resp, path);
647 else if (copyTo != null)
648 copyResource(req, resp, path, copyTo);
649 else if (moveTo != null)
650 moveResource(req, resp, path, moveTo);
651 else if (restoreVersion != null)
652 restoreVersion(req, resp, path, restoreVersion);
654 // IE with Gears uses POST for multiple uploads.
655 putResource(req, resp);
659 * Restores a previous version for a file.
661 * @param req the HTTP request
662 * @param resp the HTTP response
663 * @param path the resource path
664 * @param version the version number to restore
665 * @throws IOException if an I/O error occurs
667 private void restoreVersion(HttpServletRequest req, HttpServletResponse resp, String path, String version) throws IOException {
668 final User user = getUser(req);
669 User owner = getOwner(req);
670 Object resource = null;
672 resource = getService().getResourceAtPath(owner.getId(), path, true);
673 } catch (ObjectNotFoundException e) {
674 resp.sendError(HttpServletResponse.SC_NOT_FOUND, path);
676 } catch (RpcException e) {
677 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
680 if (resource instanceof FolderDTO) {
681 resp.sendError(HttpServletResponse.SC_CONFLICT);
686 final FileHeaderDTO file = (FileHeaderDTO) resource;
687 final int oldVersion = Integer.parseInt(version);
689 new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
691 public Void call() throws Exception {
692 getService().restoreVersion(user.getId(), file.getId(), oldVersion);
696 } catch (InsufficientPermissionsException e) {
697 resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
698 } catch (ObjectNotFoundException e) {
699 resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
700 } catch (RpcException e) {
701 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
702 } catch (GSSIOException e) {
703 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
704 } catch (QuotaExceededException e) {
705 resp.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, e.getMessage());
706 } catch (NumberFormatException e) {
707 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
708 } catch (Exception e) {
709 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
714 * A method for handling multipart POST requests for uploading
715 * files from browser-based JavaScript clients.
717 * @param request the HTTP request
718 * @param response the HTTP response
719 * @param path the resource path
720 * @throws IOException in case an error occurs writing to the
723 private void handleMultipart(HttpServletRequest request, HttpServletResponse response, String path) throws IOException {
724 if (logger.isDebugEnabled())
725 logger.debug("Multipart POST for resource: " + path);
727 User owner = getOwner(request);
728 boolean exists = true;
729 Object resource = null;
730 FileHeaderDTO file = null;
732 resource = getService().getResourceAtPath(owner.getId(), path, false);
733 } catch (ObjectNotFoundException e) {
735 } catch (RpcException e) {
736 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
741 if (resource instanceof FileHeaderDTO) {
742 file = (FileHeaderDTO) resource;
743 if (file.isDeleted()) {
744 response.sendError(HttpServletResponse.SC_CONFLICT, file.getName() + " is in the trash");
748 response.sendError(HttpServletResponse.SC_CONFLICT, path + " is a folder");
753 String parentPath = null;
755 parentPath = getParentPath(path);
756 parent = getService().getResourceAtPath(owner.getId(), parentPath, true);
757 } catch (ObjectNotFoundException e) {
758 response.sendError(HttpServletResponse.SC_NOT_FOUND, parentPath);
760 } catch (RpcException e) {
761 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
764 if (!(parent instanceof FolderDTO)) {
765 response.sendError(HttpServletResponse.SC_CONFLICT);
768 final FolderDTO folder = (FolderDTO) parent;
769 final String fileName = getLastElement(path);
771 FileItemIterator iter;
772 File uploadedFile = null;
774 // Create a new file upload handler.
775 ServletFileUpload upload = new ServletFileUpload();
776 StatusProgressListener progressListener = new StatusProgressListener(getService());
777 upload.setProgressListener(progressListener);
778 iter = upload.getItemIterator(request);
779 String dateParam = null;
781 while (iter.hasNext()) {
782 FileItemStream item = iter.next();
783 String name = item.getFieldName();
784 InputStream stream = item.openStream();
785 if (item.isFormField()) {
786 final String value = Streams.asString(stream);
787 if (name.equals(DATE_PARAMETER))
789 else if (name.equals(AUTHORIZATION_PARAMETER))
792 if (logger.isDebugEnabled())
793 logger.debug(name + ":" + value);
795 // Fetch the timestamp used to guard against replay attacks.
796 if (dateParam == null) {
797 response.sendError(HttpServletResponse.SC_FORBIDDEN, "No Date parameter");
803 timestamp = DateUtil.parseDate(dateParam).getTime();
804 } catch (DateParseException e) {
805 response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
808 if (!isTimeValid(timestamp)) {
809 response.sendError(HttpServletResponse.SC_FORBIDDEN);
813 // Fetch the Authorization parameter and find the user specified in it.
815 response.sendError(HttpServletResponse.SC_FORBIDDEN, "No Authorization parameter");
818 String[] authParts = auth.split(" ");
819 if (authParts.length != 2) {
820 response.sendError(HttpServletResponse.SC_FORBIDDEN);
823 String username = authParts[0];
824 String signature = authParts[1];
827 user = getService().findUser(username);
828 } catch (RpcException e) {
829 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
833 response.sendError(HttpServletResponse.SC_FORBIDDEN);
836 request.setAttribute(USER_ATTRIBUTE, user);
838 // Remove the servlet path from the request URI.
839 String p = request.getRequestURI();
840 String servletPath = request.getContextPath() + request.getServletPath();
841 p = p.substring(servletPath.length());
842 // Validate the signature in the Authorization parameter.
843 String data = request.getMethod() + dateParam + p;
844 if (!isSignatureValid(signature, user, data)) {
845 response.sendError(HttpServletResponse.SC_FORBIDDEN);
849 progressListener.setUserId(user.getId());
850 progressListener.setFilename(fileName);
851 final String contentType = item.getContentType();
854 uploadedFile = getService().uploadFile(stream, user.getId());
855 } catch (IOException ex) {
856 throw new GSSIOException(ex, false);
858 FileHeaderDTO fileDTO = null;
859 final File upf = uploadedFile;
860 final FileHeaderDTO f = file;
863 fileDTO = new TransactionHelper<FileHeaderDTO>().tryExecute(new Callable<FileHeaderDTO>() {
865 public FileHeaderDTO call() throws Exception {
866 return getService().createFile(u.getId(), folder.getId(), fileName, contentType, upf.getCanonicalFile().length(), upf.getAbsolutePath());
870 fileDTO = new TransactionHelper<FileHeaderDTO>().tryExecute(new Callable<FileHeaderDTO>() {
872 public FileHeaderDTO call() throws Exception {
873 return getService().updateFileContents(u.getId(), f.getId(), contentType, upf.getCanonicalFile().length(), upf.getAbsolutePath());
876 updateAccounting(owner, new Date(), fileDTO.getFileSize());
877 getService().removeFileUploadProgress(user.getId(), fileName);
880 // We can't return 204 here since GWT's onSubmitComplete won't fire.
881 response.setContentType("text/html");
882 response.getWriter().print("<pre></pre>");
883 } catch (FileUploadException e) {
884 String error = "Error while uploading file";
885 logger.error(error, e);
886 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
887 } catch (GSSIOException e) {
888 if (uploadedFile != null && uploadedFile.exists())
889 uploadedFile.delete();
890 String error = "Error while uploading file";
892 logger.error(error, e);
894 logger.debug(error, e);
895 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
896 } catch (DuplicateNameException e) {
897 if (uploadedFile != null && uploadedFile.exists())
898 uploadedFile.delete();
899 String error = "The specified file name already exists in this folder";
900 logger.error(error, e);
901 response.sendError(HttpServletResponse.SC_CONFLICT, error);
903 } catch (InsufficientPermissionsException e) {
904 if (uploadedFile != null && uploadedFile.exists())
905 uploadedFile.delete();
906 String error = "You don't have the necessary permissions";
907 logger.error(error, e);
908 response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, error);
910 } catch (QuotaExceededException e) {
911 if (uploadedFile != null && uploadedFile.exists())
912 uploadedFile.delete();
913 String error = "Not enough free space available";
914 if (logger.isDebugEnabled())
915 logger.debug(error, e);
916 response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, error);
918 } catch (ObjectNotFoundException e) {
919 if (uploadedFile != null && uploadedFile.exists())
920 uploadedFile.delete();
921 String error = "A specified object was not found";
922 logger.error(error, e);
923 response.sendError(HttpServletResponse.SC_NOT_FOUND, error);
924 } catch (RpcException e) {
925 if (uploadedFile != null && uploadedFile.exists())
926 uploadedFile.delete();
927 String error = "An error occurred while communicating with the service";
928 logger.error(error, e);
929 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
930 } catch (Exception e) {
931 if (uploadedFile != null && uploadedFile.exists())
932 uploadedFile.delete();
933 String error = "An internal server error occurred";
934 logger.error(error, e);
935 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
940 * Move the resource in the specified path to the specified destination.
942 * @param req the HTTP request
943 * @param resp the HTTP response
944 * @param path the path of the resource
945 * @param moveTo the destination of the move procedure
946 * @throws IOException if an input/output error occurs
948 private void moveResource(HttpServletRequest req, HttpServletResponse resp, String path, String moveTo) throws IOException {
949 final User user = getUser(req);
950 User owner = getOwner(req);
951 Object resource = null;
953 resource = getService().getResourceAtPath(owner.getId(), path, true);
954 } catch (ObjectNotFoundException e) {
955 resp.sendError(HttpServletResponse.SC_NOT_FOUND, path);
957 } catch (RpcException e) {
958 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
962 String destination = null;
963 User destOwner = null;
964 boolean exists = true;
966 destination = getDestinationPath(req, encodePath(moveTo));
967 destination = URLDecoder.decode(destination, "UTF-8");
968 destOwner = getDestinationOwner(req);
969 getService().getResourceAtPath(destOwner.getId(), destination, true);
970 } catch (ObjectNotFoundException e) {
972 } catch (URISyntaxException e) {
973 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
975 } catch (RpcException e) {
976 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, destination);
980 resp.sendError(HttpServletResponse.SC_CONFLICT, destination + " already exists");
985 final User dOwner = destOwner;
986 final String dest = destination;
987 if (resource instanceof FolderDTO) {
988 final FolderDTO folder = (FolderDTO) resource;
989 new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
991 public Void call() throws Exception {
992 getService().moveFolderToPath(user.getId(), dOwner.getId(), folder.getId(), dest);
997 final FileHeaderDTO file = (FileHeaderDTO) resource;
998 new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
1000 public Void call() throws Exception {
1001 getService().moveFileToPath(user.getId(), dOwner.getId(), file.getId(), dest);
1007 } catch (InsufficientPermissionsException e) {
1008 resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
1009 } catch (ObjectNotFoundException e) {
1010 resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
1011 } catch (RpcException e) {
1012 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, destination);
1013 } catch (DuplicateNameException e) {
1014 resp.sendError(HttpServletResponse.SC_CONFLICT, e.getMessage());
1015 } catch (GSSIOException e) {
1016 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1017 } catch (QuotaExceededException e) {
1018 resp.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, e.getMessage());
1019 } catch (Exception e) {
1020 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, destination);
1025 * Copy the resource in the specified path to the specified destination.
1027 * @param req the HTTP request
1028 * @param resp the HTTP response
1029 * @param path the path of the resource
1030 * @param copyTo the destination of the copy procedure
1031 * @throws IOException if an input/output error occurs
1033 private void copyResource(HttpServletRequest req, HttpServletResponse resp, String path, String copyTo) throws IOException {
1034 final User user = getUser(req);
1035 User owner = getOwner(req);
1036 Object resource = null;
1038 resource = getService().getResourceAtPath(owner.getId(), path, true);
1039 } catch (ObjectNotFoundException e) {
1040 resp.sendError(HttpServletResponse.SC_NOT_FOUND, path);
1042 } catch (RpcException e) {
1043 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
1047 String destination = null;
1048 User destOwner = null;
1049 boolean exists = true;
1051 String destinationEncoded = getDestinationPath(req, encodePath(copyTo));
1052 destination = URLDecoder.decode(destinationEncoded, "UTF-8");
1053 destOwner = getDestinationOwner(req);
1054 getService().getResourceAtPath(destOwner.getId(), destinationEncoded, true);
1055 } catch (ObjectNotFoundException e) {
1057 } catch (URISyntaxException e) {
1058 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
1060 } catch (RpcException e) {
1061 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, destination);
1065 resp.sendError(HttpServletResponse.SC_CONFLICT, destination + " already exists");
1070 final User dOwner = destOwner;
1071 final String dest = destination;
1072 if (resource instanceof FolderDTO) {
1073 final FolderDTO folder = (FolderDTO) resource;
1074 new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
1076 public Void call() throws Exception {
1077 getService().copyFolderStructureToPath(user.getId(), dOwner.getId(), folder.getId(), dest);
1082 final FileHeaderDTO file = (FileHeaderDTO) resource;
1083 new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
1085 public Void call() throws Exception {
1086 getService().copyFileToPath(user.getId(), dOwner.getId(), file.getId(), dest);
1091 } catch (InsufficientPermissionsException e) {
1092 resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
1093 } catch (ObjectNotFoundException e) {
1094 resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
1095 } catch (RpcException e) {
1096 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, destination);
1097 } catch (DuplicateNameException e) {
1098 resp.sendError(HttpServletResponse.SC_CONFLICT, e.getMessage());
1099 } catch (GSSIOException e) {
1100 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
1101 } catch (QuotaExceededException e) {
1102 resp.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, e.getMessage());
1103 } catch (Exception e) {
1104 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, destination);
1108 private String encodePath(String path) throws UnsupportedEncodingException{
1109 StringTokenizer str = new StringTokenizer(path, "/:", true);
1110 String result = new String();
1111 while(str.hasMoreTokens()){
1112 String token = str.nextToken();
1113 if(!token.equals("/") && !token.equals(":"))
1114 token = URLEncoder.encode(token,"UTF-8");
1115 result = result + token;
1120 * A helper method that extracts the relative resource path,
1121 * after removing the 'files' namespace.
1122 * The path returned is <i>not</i> URL-decoded.
1124 * @param req the HTTP request
1125 * @param path the specified path
1126 * @return the path relative to the root folder
1127 * @throws URISyntaxException
1128 * @throws RpcException in case an error occurs while communicating
1130 * @throws UnsupportedEncodingException
1132 private String getDestinationPath(HttpServletRequest req, String path) throws URISyntaxException, RpcException, UnsupportedEncodingException {
1133 URI uri = new URI(path);
1134 String dest = uri.getRawPath();
1135 // Remove the context path from the destination URI.
1136 String contextPath = req.getContextPath();
1137 if (!dest.startsWith(contextPath))
1138 throw new URISyntaxException(dest, "Destination path does not start with " + contextPath);
1139 dest = dest.substring(contextPath.length());
1140 // Remove the servlet path from the destination URI.
1141 String servletPath = req.getServletPath();
1142 if (!dest.startsWith(servletPath))
1143 throw new URISyntaxException(dest, "Destination path does not start with " + servletPath);
1144 dest = dest.substring(servletPath.length());
1145 // Strip the username part
1146 if (dest.length() < 2)
1147 throw new URISyntaxException(dest, "No username in the destination URI");
1148 int slash = dest.substring(1).indexOf('/');
1150 throw new URISyntaxException(dest, "No username in the destination URI");
1151 // Decode the user to get the proper characters (mainly the @)
1152 String owner = URLDecoder.decode(dest.substring(1, slash + 1), "UTF-8");
1154 o = getService().findUser(owner);
1156 throw new URISyntaxException(dest, "User " + owner + " not found");
1158 req.setAttribute(DESTINATION_OWNER_ATTRIBUTE, o);
1159 dest = dest.substring(slash + 1);
1161 // Chop the resource namespace part
1162 dest = dest.substring(RequestHandler.PATH_FILES.length());
1164 dest = dest.endsWith("/")? dest: dest + '/';
1169 * Move the resource in the specified path to the trash bin.
1171 * @param req the HTTP request
1172 * @param resp the HTTP response
1173 * @param path the path of the resource
1174 * @throws IOException if an input/output error occurs
1176 private void trashResource(HttpServletRequest req, HttpServletResponse resp, String path) throws IOException {
1177 final User user = getUser(req);
1178 User owner = getOwner(req);
1179 Object resource = null;
1181 resource = getService().getResourceAtPath(owner.getId(), path, true);
1182 } catch (ObjectNotFoundException e) {
1183 resp.sendError(HttpServletResponse.SC_NOT_FOUND, path);
1185 } catch (RpcException e) {
1186 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
1191 if (resource instanceof FolderDTO) {
1192 final FolderDTO folder = (FolderDTO) resource;
1193 new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
1195 public Void call() throws Exception {
1196 getService().moveFolderToTrash(user.getId(), folder.getId());
1201 final FileHeaderDTO file = (FileHeaderDTO) resource;
1202 new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
1204 public Void call() throws Exception {
1205 getService().moveFileToTrash(user.getId(), file.getId());
1210 } catch (InsufficientPermissionsException e) {
1211 resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
1212 } catch (ObjectNotFoundException e) {
1213 resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
1214 } catch (RpcException e) {
1215 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
1216 } catch (Exception e) {
1217 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
1222 * Restore the resource in the specified path from the trash bin.
1224 * @param req the HTTP request
1225 * @param resp the HTTP response
1226 * @param path the path of the resource
1227 * @throws IOException if an input/output error occurs
1229 private void restoreResource(HttpServletRequest req, HttpServletResponse resp, String path) throws IOException {
1230 final User user = getUser(req);
1231 User owner = getOwner(req);
1232 Object resource = null;
1234 resource = getService().getResourceAtPath(owner.getId(), path, false);
1235 } catch (ObjectNotFoundException e) {
1236 resp.sendError(HttpServletResponse.SC_NOT_FOUND, path);
1238 } catch (RpcException e) {
1239 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
1244 if (resource instanceof FolderDTO) {
1245 final FolderDTO folder = (FolderDTO) resource;
1246 new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
1248 public Void call() throws Exception {
1249 getService().removeFolderFromTrash(user.getId(), folder.getId());
1254 final FileHeaderDTO file = (FileHeaderDTO) resource;
1255 new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
1257 public Void call() throws Exception {
1258 getService().removeFileFromTrash(user.getId(), file.getId());
1263 } catch (InsufficientPermissionsException e) {
1264 resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
1265 } catch (ObjectNotFoundException e) {
1266 resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
1267 } catch (RpcException e) {
1268 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
1269 } catch (Exception e) {
1270 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
1275 * Update the resource in the specified path.
1277 * @param req the HTTP request
1278 * @param resp the HTTP response
1279 * @param path the path of the resource
1280 * @throws IOException if an input/output error occurs
1282 private void updateResource(HttpServletRequest req, HttpServletResponse resp, String path) throws IOException {
1283 final User user = getUser(req);
1284 User owner = getOwner(req);
1285 Object resource = null;
1287 resource = getService().getResourceAtPath(owner.getId(), path, false);
1288 } catch (ObjectNotFoundException e) {
1289 resp.sendError(HttpServletResponse.SC_NOT_FOUND, path);
1291 } catch (RpcException e) {
1292 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
1295 //use utf-8 encoding for reading request
1296 BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream(),"UTF-8"));
1297 StringBuffer input = new StringBuffer();
1299 JSONObject json = null;
1300 while ((line = reader.readLine()) != null)
1304 json = new JSONObject(input.toString());
1305 if (logger.isDebugEnabled())
1306 logger.debug("JSON update: " + json);
1307 if (resource instanceof FolderDTO) {
1308 final FolderDTO folder = (FolderDTO) resource;
1309 String name = json.optString("name");
1310 if (!name.isEmpty())
1312 name = URLDecoder.decode(name, "UTF-8");
1313 } catch (IllegalArgumentException e) {
1314 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
1317 JSONArray permissions = json.optJSONArray("permissions");
1318 Set<PermissionDTO> perms = null;
1319 if (permissions != null)
1320 perms = parsePermissions(user, permissions);
1321 if (!name.isEmpty() || permissions != null) {
1322 final String fName = name.isEmpty()? null: name;
1323 final Set<PermissionDTO> fPerms = perms;
1324 FolderDTO folderUpdated = new TransactionHelper<FolderDTO>().tryExecute(new Callable<FolderDTO>() {
1326 public FolderDTO call() throws Exception {
1327 return getService().updateFolder(user.getId(), folder.getId(), fName, fPerms);
1331 String parentUrl =URLDecoder.decode(getContextPath(req, true),"UTF-8");
1332 String fpath = URLDecoder.decode(req.getPathInfo(), "UTF-8");
1333 parentUrl = parentUrl.replaceAll(fpath, "");
1334 if(!parentUrl.endsWith("/"))
1335 parentUrl = parentUrl+"/";
1336 parentUrl = parentUrl+folderUpdated.getOwner().getUsername()+PATH_FILES+folderUpdated.getPath();
1337 resp.getWriter().println(parentUrl);
1340 final FileHeaderDTO file = (FileHeaderDTO) resource;
1342 if (json.opt("name") != null)
1343 name = json.optString("name");
1344 Long modificationDate = null;
1345 if (json.optLong("modificationDate") != 0)
1346 modificationDate = json.optLong("modificationDate");
1347 Boolean versioned = null;
1348 if (json.opt("versioned") != null)
1349 versioned = json.getBoolean("versioned");
1350 JSONArray tagset = json.optJSONArray("tags");
1352 StringBuffer t = new StringBuffer();
1353 if (tagset != null) {
1354 for (int i = 0; i < tagset.length(); i++)
1355 t.append(tagset.getString(i) + ',');
1356 tags = t.toString();
1358 JSONArray permissions = json.optJSONArray("permissions");
1359 Set<PermissionDTO> perms = null;
1360 if (permissions != null)
1361 perms = parsePermissions(user, permissions);
1362 Boolean readForAll = null;
1363 if (json.opt("readForAll") != null)
1364 readForAll = json.optBoolean("readForAll");
1365 if (name != null || tags != null || modificationDate != null
1366 || versioned != null || perms != null
1367 || readForAll != null) {
1368 final String fName = name;
1369 final String fTags = tags;
1370 final Date mDate = modificationDate != null? new Date(modificationDate): null;
1371 final Boolean fVersioned = versioned;
1372 final Boolean fReadForAll = readForAll;
1373 final Set<PermissionDTO> fPerms = perms;
1374 new TransactionHelper<Object>().tryExecute(new Callable<Object>() {
1376 public Object call() throws Exception {
1377 getService().updateFile(user.getId(), file.getId(),
1378 fName, fTags, mDate, fVersioned,
1379 fReadForAll, fPerms);
1386 } catch (JSONException e) {
1387 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
1388 } catch (InsufficientPermissionsException e) {
1389 resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
1390 } catch (ObjectNotFoundException e) {
1391 resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
1392 } catch (DuplicateNameException e) {
1393 resp.sendError(HttpServletResponse.SC_CONFLICT, e.getMessage());
1394 } catch (RpcException e) {
1395 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
1396 } catch (Exception e) {
1397 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
1403 * Helper method to convert a JSON array of permissions into a set of
1404 * PermissionDTO objects.
1406 * @param user the current user
1407 * @param permissions the JSON array to parse
1408 * @return the parsed set of permissions
1409 * @throws JSONException if there was an error parsing the JSON object
1410 * @throws RpcException if there was an error communicating with the EJB
1411 * @throws ObjectNotFoundException if the user could not be found
1412 * @throws UnsupportedEncodingException
1414 private Set<PermissionDTO> parsePermissions(User user, JSONArray permissions)
1415 throws JSONException, RpcException, ObjectNotFoundException, UnsupportedEncodingException {
1416 if (permissions == null)
1418 Set<PermissionDTO> perms = new HashSet<PermissionDTO>();
1419 for (int i = 0; i < permissions.length(); i++) {
1420 JSONObject j = permissions.getJSONObject(i);
1421 PermissionDTO perm = new PermissionDTO();
1422 perm.setModifyACL(j.optBoolean("modifyACL"));
1423 perm.setRead(j.optBoolean("read"));
1424 perm.setWrite(j.optBoolean("write"));
1425 String permUser = j.optString("user");
1426 if (!permUser.isEmpty()) {
1427 User u = getService().findUser(permUser);
1429 throw new ObjectNotFoundException("User " + permUser + " not found");
1430 perm.setUser(u.getDTO());
1432 // 31/8/2009: Add optional groupUri which takes priority if it exists
1433 String permGroupUri = j.optString("groupUri");
1434 String permGroup = j.optString("group");
1435 if (!permGroupUri.isEmpty()) {
1436 String[] names = permGroupUri.split("/");
1437 String grp = URLDecoder.decode(names[names.length - 1], "UTF-8");
1438 String usr = URLDecoder.decode(names[names.length - 3], "UTF-8");
1439 User u = getService().findUser(usr);
1441 throw new ObjectNotFoundException("User " + permUser + " not found");
1442 GroupDTO g = getService().getGroup(u.getId(), grp);
1445 else if (!permGroup.isEmpty()) {
1446 GroupDTO g = getService().getGroup(user.getId(), permGroup);
1449 if (permUser.isEmpty() && permGroupUri.isEmpty() && permGroup.isEmpty())
1450 throw new JSONException("A permission must correspond to either a user or a group");
1457 * Creates a new folder with the specified name under the folder in the provided path.
1459 * @param req the HTTP request
1460 * @param resp the HTTP response
1461 * @param path the parent folder path
1462 * @param folderName the name of the new folder
1463 * @throws IOException if an input/output error occurs
1465 private void createFolder(HttpServletRequest req, HttpServletResponse resp, String path, final String folderName) throws IOException {
1466 if (logger.isDebugEnabled())
1467 logger.debug("Creating folder " + folderName + " in '" + path);
1469 final User user = getUser(req);
1470 User owner = getOwner(req);
1471 boolean exists = true;
1473 getService().getResourceAtPath(owner.getId(), path + folderName, false);
1474 } catch (ObjectNotFoundException e) {
1476 } catch (RpcException e) {
1477 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path + folderName);
1482 resp.addHeader("Allow", METHOD_GET + ", " + METHOD_DELETE +
1483 ", " + METHOD_HEAD);
1484 resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
1490 parent = getService().getResourceAtPath(owner.getId(), path, true);
1491 } catch (ObjectNotFoundException e) {
1492 resp.sendError(HttpServletResponse.SC_CONFLICT);
1494 } catch (RpcException e) {
1495 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path + folderName);
1499 if (parent instanceof FolderDTO) {
1500 final FolderDTO folder = (FolderDTO) parent;
1501 FolderDTO newFolder = new TransactionHelper<FolderDTO>().tryExecute(new Callable<FolderDTO>() {
1503 public FolderDTO call() throws Exception {
1504 return getService().createFolder(user.getId(), folder.getId(), folderName);
1508 String newResource = getApiRoot() + newFolder.getURI();
1509 resp.setHeader("Location", newResource);
1510 resp.setContentType("text/plain");
1511 PrintWriter out = resp.getWriter();
1512 out.println(newResource);
1514 resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
1517 } catch (DuplicateNameException e) {
1518 resp.sendError(HttpServletResponse.SC_CONFLICT);
1520 } catch (InsufficientPermissionsException e) {
1521 resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
1523 } catch (ObjectNotFoundException e) {
1524 resp.sendError(HttpServletResponse.SC_CONFLICT);
1526 } catch (RpcException e) {
1527 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path + folderName);
1529 } catch (Exception e) {
1530 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
1533 resp.setStatus(HttpServletResponse.SC_CREATED);
1539 * @throws IOException
1540 * @throws FileNotFoundException
1542 void putResource(HttpServletRequest req, HttpServletResponse resp) throws IOException, FileNotFoundException {
1543 String path = getInnerPath(req, PATH_FILES);
1545 path = URLDecoder.decode(path, "UTF-8");
1546 } catch (IllegalArgumentException e) {
1547 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
1550 if (logger.isDebugEnabled())
1551 logger.debug("Updating resource: " + path);
1553 final User user = getUser(req);
1554 User owner = getOwner(req);
1555 boolean exists = true;
1556 Object resource = null;
1557 FileHeaderDTO file = null;
1559 resource = getService().getResourceAtPath(owner.getId(), path, false);
1560 } catch (ObjectNotFoundException e) {
1562 } catch (RpcException e) {
1563 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
1568 if (resource instanceof FileHeaderDTO)
1569 file = (FileHeaderDTO) resource;
1571 resp.sendError(HttpServletResponse.SC_CONFLICT, path + " is a folder");
1574 boolean result = true;
1576 // Temporary content file used to support partial PUT.
1577 File contentFile = null;
1579 Range range = parseContentRange(req, resp);
1581 InputStream resourceInputStream = null;
1583 // Append data specified in ranges to existing content for this
1584 // resource - create a temporary file on the local filesystem to
1585 // perform this operation.
1586 // Assume just one range is specified for now
1587 if (range != null) {
1589 contentFile = executePartialPut(req, range, path);
1590 } catch (RpcException e) {
1591 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
1593 } catch (ObjectNotFoundException e) {
1594 resp.sendError(HttpServletResponse.SC_CONFLICT);
1596 } catch (InsufficientPermissionsException e) {
1597 resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
1600 resourceInputStream = new FileInputStream(contentFile);
1602 resourceInputStream = req.getInputStream();
1605 FolderDTO folder = null;
1606 Object parent = getService().getResourceAtPath(owner.getId(), getParentPath(path), true);
1607 if (!(parent instanceof FolderDTO)) {
1608 resp.sendError(HttpServletResponse.SC_CONFLICT);
1611 folder = (FolderDTO) parent;
1612 final String name = getLastElement(path);
1613 final String mimeType = context.getMimeType(name);
1614 File uploadedFile = null;
1616 uploadedFile = getService().uploadFile(resourceInputStream, user.getId());
1617 } catch (IOException ex) {
1618 throw new GSSIOException(ex, false);
1620 FileHeaderDTO fileDTO = null;
1621 final File uploadedf = uploadedFile;
1622 final FolderDTO parentf = folder;
1623 final FileHeaderDTO f = file;
1625 fileDTO = new TransactionHelper<FileHeaderDTO>().tryExecute(new Callable<FileHeaderDTO>() {
1627 public FileHeaderDTO call() throws Exception {
1628 return getService().updateFileContents(user.getId(), f.getId(), mimeType, uploadedf.getCanonicalFile().length(), uploadedf.getAbsolutePath());
1632 fileDTO = new TransactionHelper<FileHeaderDTO>().tryExecute(new Callable<FileHeaderDTO>() {
1634 public FileHeaderDTO call() throws Exception {
1635 return getService().createFile(user.getId(), parentf.getId(), name, mimeType, uploadedf.getCanonicalFile().length(), uploadedf.getAbsolutePath());
1639 updateAccounting(owner, new Date(), fileDTO.getFileSize());
1640 getService().removeFileUploadProgress(user.getId(), fileDTO.getName());
1641 } catch(ObjectNotFoundException e) {
1643 } catch (RpcException e) {
1644 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
1646 } catch (IOException e) {
1647 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
1649 } catch (GSSIOException e) {
1650 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
1652 } catch (DuplicateNameException e) {
1653 resp.sendError(HttpServletResponse.SC_CONFLICT);
1655 } catch (InsufficientPermissionsException e) {
1656 resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
1658 } catch (QuotaExceededException e) {
1659 resp.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, e.getMessage());
1661 } catch (Exception e) {
1662 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
1668 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
1670 resp.setStatus(HttpServletResponse.SC_CREATED);
1672 resp.sendError(HttpServletResponse.SC_CONFLICT);
1676 * Delete a resource.
1678 * @param req The servlet request we are processing
1679 * @param resp The servlet response we are processing
1680 * @throws IOException if the response cannot be sent
1682 void deleteResource(HttpServletRequest req, HttpServletResponse resp) throws IOException {
1683 String path = getInnerPath(req, PATH_FILES);
1684 if (logger.isDebugEnabled())
1685 logger.debug("Deleting resource '" + path);
1686 path = URLDecoder.decode(path, "UTF-8");
1687 final User user = getUser(req);
1688 User owner = getOwner(req);
1689 boolean exists = true;
1690 Object object = null;
1692 object = getService().getResourceAtPath(owner.getId(), path, false);
1693 } catch (ObjectNotFoundException e) {
1695 } catch (RpcException e) {
1696 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1701 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
1705 FolderDTO folder = null;
1706 FileHeaderDTO file = null;
1707 if (object instanceof FolderDTO)
1708 folder = (FolderDTO) object;
1710 file = (FileHeaderDTO) object;
1714 final FileHeaderDTO f = file;
1715 new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
1717 public Void call() throws Exception {
1718 getService().deleteFile(user.getId(), f.getId());
1722 } catch (InsufficientPermissionsException e) {
1723 resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
1725 } catch (ObjectNotFoundException e) {
1726 // Although we had already found the object, it was
1727 // probably deleted from another thread.
1728 resp.sendError(HttpServletResponse.SC_NOT_FOUND);
1730 } catch (RpcException e) {
1731 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1733 } catch (Exception e) {
1734 resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1737 else if (folder != null)
1739 final FolderDTO fo = folder;
1740 new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
1742 public Void call() throws Exception {
1743 getService().deleteFolder(user.getId(), fo.getId());
1747 } catch (InsufficientPermissionsException e) {
1748 resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
1750 } catch (ObjectNotFoundException e) {
1751 resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
1753 } catch (RpcException e) {
1754 resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1756 } catch (Exception e) {
1757 resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
1760 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
1765 * Return an InputStream to a JSON representation of the contents
1766 * of this directory.
1768 * @param user the user that made the request
1769 * @param folder the specified directory
1770 * @return an input stream with the rendered contents
1771 * @throws IOException if the response cannot be sent
1772 * @throws ServletException
1773 * @throws InsufficientPermissionsException if the user does not have
1774 * the necessary privileges to read the directory
1776 private InputStream renderJson(User user, FolderDTO folder) throws IOException,
1777 ServletException, InsufficientPermissionsException {
1778 JSONObject json = new JSONObject();
1780 json.put("name", folder.getName()).
1781 put("owner", folder.getOwner().getUsername()).
1782 put("createdBy", folder.getAuditInfo().getCreatedBy().getUsername()).
1783 put("creationDate", folder.getAuditInfo().getCreationDate().getTime()).
1784 put("deleted", folder.isDeleted());
1785 if (folder.getAuditInfo().getModifiedBy() != null)
1786 json.put("modifiedBy", folder.getAuditInfo().getModifiedBy().getUsername()).
1787 put("modificationDate", folder.getAuditInfo().getModificationDate().getTime());
1788 if (folder.getParent() != null) {
1789 JSONObject j = new JSONObject();
1790 j.put("uri", getApiRoot() + folder.getParent().getURI());
1791 j.put("name", folder.getParent().getName());
1792 json.put("parent", j);
1794 List<JSONObject> subfolders = new ArrayList<JSONObject>();
1795 for (FolderDTO f: folder.getSubfolders())
1796 if (!f.isDeleted()) {
1797 JSONObject j = new JSONObject();
1798 j.put("name", f.getName()).
1799 put("uri", getApiRoot() + f.getURI());
1802 json.put("folders", subfolders);
1803 List<JSONObject> files = new ArrayList<JSONObject>();
1804 List<FileHeaderDTO> fileHeaders = getService().getFiles(user.getId(), folder.getId(), false);
1805 for (FileHeaderDTO f: fileHeaders) {
1806 JSONObject j = new JSONObject();
1807 j.put("name", f.getName()).
1808 put("owner", f.getOwner().getUsername()).
1809 put("deleted", f.isDeleted()).
1810 put("version", f.getVersion()).
1811 put("content", f.getMimeType()).
1812 put("size", f.getFileSize()).
1813 put("creationDate", f.getAuditInfo().getCreationDate().getTime()).
1814 put("path", f.getFolder().getPath()).
1815 put("uri", getApiRoot() + f.getURI());
1816 if (f.getAuditInfo().getModificationDate() != null)
1817 j.put("modificationDate", f.getAuditInfo().getModificationDate().getTime());
1820 json.put("files", files);
1821 Set<PermissionDTO> perms = getService().getFolderPermissions(user.getId(), folder.getId());
1822 json.put("permissions", renderJson(perms));
1823 } catch (JSONException e) {
1824 throw new ServletException(e);
1825 } catch (ObjectNotFoundException e) {
1826 throw new ServletException(e);
1827 } catch (RpcException e) {
1828 throw new ServletException(e);
1831 // Prepare a writer to a buffered area
1832 ByteArrayOutputStream stream = new ByteArrayOutputStream();
1833 OutputStreamWriter osWriter = new OutputStreamWriter(stream, "UTF8");
1834 PrintWriter writer = new PrintWriter(osWriter);
1836 // Return an input stream to the underlying bytes
1837 writer.write(json.toString());
1839 return new ByteArrayInputStream(stream.toByteArray());
1843 * Return a String with a JSON representation of the metadata
1844 * of the specified folder.
1845 * @throws RpcException
1846 * @throws InsufficientPermissionsException
1847 * @throws ObjectNotFoundException
1849 private String renderJsonMetadata(User user, FolderDTO folder)
1850 throws ServletException, InsufficientPermissionsException {
1851 // Check if the user has read permission.
1853 if (!getService().canReadFolder(user.getId(), folder.getId()))
1854 throw new InsufficientPermissionsException();
1855 } catch (ObjectNotFoundException e) {
1856 throw new ServletException(e);
1857 } catch (RpcException e) {
1858 throw new ServletException(e);
1861 JSONObject json = new JSONObject();
1863 json.put("name", folder.getName()).
1864 put("owner", folder.getOwner().getUsername()).
1865 put("createdBy", folder.getAuditInfo().getCreatedBy().getUsername()).
1866 put("creationDate", folder.getAuditInfo().getCreationDate().getTime()).
1867 put("deleted", folder.isDeleted());
1868 if (folder.getAuditInfo().getModifiedBy() != null)
1869 json.put("modifiedBy", folder.getAuditInfo().getModifiedBy().getUsername()).
1870 put("modificationDate", folder.getAuditInfo().getModificationDate().getTime());
1871 } catch (JSONException e) {
1872 throw new ServletException(e);
1874 return json.toString();
1878 * Return a String with a JSON representation of the metadata
1879 * of the specified file. If an old file body is provided, then
1880 * the metadata of that particular version will be returned.
1882 * @param user the user that made the request
1883 * @param file the specified file header
1884 * @param oldBody the version number
1885 * @return the JSON-encoded file
1886 * @throws ServletException
1887 * @throws InsufficientPermissionsException if the user does not have
1888 * the necessary privileges to read the directory
1890 private String renderJson(User user, FileHeaderDTO file, FileBodyDTO oldBody)
1891 throws ServletException, InsufficientPermissionsException {
1892 JSONObject json = new JSONObject();
1894 // Need to encode file name in order to properly display it in the web client.
1895 json.put("name", URLEncoder.encode(file.getName(),"UTF-8")).
1896 put("owner", file.getOwner().getUsername()).
1897 put("versioned", file.isVersioned()).
1898 put("version", oldBody != null ? oldBody.getVersion() : file.getVersion()).
1899 put("readForAll", file.isReadForAll()).
1900 put("tags", renderJson(file.getTags())).
1901 put("path", file.getFolder().getPath()).
1902 put("uri", getApiRoot() + file.getURI()).
1903 put("deleted", file.isDeleted());
1904 JSONObject j = new JSONObject();
1905 j.put("uri", getApiRoot() + file.getFolder().getURI()).
1906 put("name", URLEncoder.encode(file.getFolder().getName(),"UTF-8"));
1907 json.put("folder", j);
1908 if (oldBody != null)
1909 json.put("createdBy", oldBody.getAuditInfo().getCreatedBy().getUsername()).
1910 put("creationDate", oldBody.getAuditInfo().getCreationDate().getTime()).
1911 put("modifiedBy", oldBody.getAuditInfo().getModifiedBy().getUsername()).
1912 put("modificationDate", oldBody.getAuditInfo().getModificationDate().getTime()).
1913 put("content", oldBody.getMimeType()).
1914 put("size", oldBody.getFileSize());
1916 json.put("createdBy", file.getAuditInfo().getCreatedBy().getUsername()).
1917 put("creationDate", file.getAuditInfo().getCreationDate().getTime()).
1918 put("modifiedBy", file.getAuditInfo().getModifiedBy().getUsername()).
1919 put("modificationDate", file.getAuditInfo().getModificationDate().getTime()).
1920 put("content", file.getMimeType()).
1921 put("size", file.getFileSize());
1922 Set<PermissionDTO> perms = getService().getFilePermissions(user.getId(), file.getId());
1923 json.put("permissions", renderJson(perms));
1924 } catch (JSONException e) {
1925 throw new ServletException(e);
1926 } catch (ObjectNotFoundException e) {
1927 throw new ServletException(e);
1928 } catch (RpcException e) {
1929 throw new ServletException(e);
1930 } catch (UnsupportedEncodingException e) {
1931 throw new ServletException(e);
1934 return json.toString();
1938 * Return a String with a JSON representation of the
1939 * specified set of permissions.
1941 * @param permissions the set of permissions
1942 * @return the JSON-encoded object
1943 * @throws JSONException
1944 * @throws UnsupportedEncodingException
1946 private JSONArray renderJson(Set<PermissionDTO> permissions) throws JSONException, UnsupportedEncodingException {
1947 JSONArray perms = new JSONArray();
1948 for (PermissionDTO p: permissions) {
1949 JSONObject permission = new JSONObject();
1950 permission.put("read", p.hasRead()).put("write", p.hasWrite()).put("modifyACL", p.hasModifyACL());
1951 if (p.getUser() != null)
1952 permission.put("user", p.getUser().getUsername());
1953 if (p.getGroup() != null) {
1954 GroupDTO group = p.getGroup();
1955 permission.put("groupUri", getApiRoot() + group.getOwner().getUsername() + PATH_GROUPS + "/" + URLEncoder.encode(group.getName(),"UTF-8"));
1956 permission.put("group", URLEncoder.encode(p.getGroup().getName(),"UTF-8"));
1958 perms.put(permission);
1964 * Return a String with a JSON representation of the
1965 * specified collection of tags.
1967 * @param tags the collection of tags
1968 * @return the JSON-encoded object
1969 * @throws JSONException
1970 * @throws UnsupportedEncodingException
1972 private JSONArray renderJson(Collection<String> tags) throws JSONException, UnsupportedEncodingException {
1973 JSONArray tagArray = new JSONArray();
1974 for (String t: tags)
1975 tagArray.put(URLEncoder.encode(t,"UTF-8"));
1980 * Retrieves the user who owns the destination namespace, for a
1981 * copy or move request.
1983 * @param req the HTTP request
1984 * @return the owner of the namespace
1986 protected User getDestinationOwner(HttpServletRequest req) {
1987 return (User) req.getAttribute(DESTINATION_OWNER_ATTRIBUTE);
1991 * A helper inner class for updating the progress status of a file upload.
1995 public static class StatusProgressListener implements ProgressListener {
1996 private int percentLogged = 0;
1997 private long bytesTransferred = 0;
1999 private long fileSize = -100;
2001 private Long userId;
2003 private String filename;
2005 private ExternalAPI service;
2007 public StatusProgressListener(ExternalAPI aService) {
2012 * Modify the userId.
2014 * @param aUserId the userId to set
2016 public void setUserId(Long aUserId) {
2021 * Modify the filename.
2023 * @param aFilename the filename to set
2025 public void setFilename(String aFilename) {
2026 filename = aFilename;
2029 public void update(long bytesRead, long contentLength, int items) {
2030 //monitoring per percent of bytes uploaded
2031 bytesTransferred = bytesRead;
2032 if (fileSize != contentLength)
2033 fileSize = contentLength;
2034 int percent = new Long(bytesTransferred * 100 / fileSize).intValue();
2036 if (percent < 5 || percent % TRACK_PROGRESS_PERCENT == 0 )
2037 if (percent != percentLogged){
2038 percentLogged = percent;
2040 if (userId != null && filename != null)
2041 service.createFileUploadProgress(userId, filename, bytesTransferred, fileSize);
2042 } catch (ObjectNotFoundException e) {
2043 // Swallow the exception since it is going to be caught
2044 // by previously called methods