Use Lytebox (a Lightbox clone) for quick viewing images.
[pithos] / src / gr / ebs / gss / client / FileUploadGearsDialog.java
1 /*\r
2  * Copyright 2009 Electronic Business Systems Ltd.\r
3  *\r
4  * This file is part of GSS.\r
5  *\r
6  * GSS is free software: you can redistribute it and/or modify\r
7  * it under the terms of the GNU General Public License as published by\r
8  * the Free Software Foundation, either version 3 of the License, or\r
9  * (at your option) any later version.\r
10  *\r
11  * GSS is distributed in the hope that it will be useful,\r
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
14  * GNU General Public License for more details.\r
15  *\r
16  * You should have received a copy of the GNU General Public License\r
17  * along with GSS.  If not, see <http://www.gnu.org/licenses/>.\r
18  */\r
19 package gr.ebs.gss.client;\r
20 \r
21 import gr.ebs.gss.client.rest.PostCommand;\r
22 import gr.ebs.gss.client.rest.RestCommand;\r
23 import gr.ebs.gss.client.rest.RestException;\r
24 import gr.ebs.gss.client.rest.resource.FileResource;\r
25 import gr.ebs.gss.client.rest.resource.FolderResource;\r
26 \r
27 import java.util.ArrayList;\r
28 import java.util.Arrays;\r
29 import java.util.HashMap;\r
30 import java.util.List;\r
31 import java.util.Map;\r
32 \r
33 import com.google.gwt.core.client.GWT;\r
34 import com.google.gwt.gears.client.Factory;\r
35 import com.google.gwt.gears.client.desktop.Desktop;\r
36 import com.google.gwt.gears.client.desktop.File;\r
37 import com.google.gwt.gears.client.desktop.OpenFilesHandler;\r
38 import com.google.gwt.gears.client.httprequest.HttpRequest;\r
39 import com.google.gwt.gears.client.httprequest.ProgressEvent;\r
40 import com.google.gwt.gears.client.httprequest.ProgressHandler;\r
41 import com.google.gwt.gears.client.httprequest.RequestCallback;\r
42 import com.google.gwt.http.client.URL;\r
43 import com.google.gwt.json.client.JSONObject;\r
44 import com.google.gwt.json.client.JSONString;\r
45 import com.google.gwt.user.client.Command;\r
46 import com.google.gwt.user.client.DeferredCommand;\r
47 import com.google.gwt.user.client.ui.Button;\r
48 import com.google.gwt.user.client.ui.ClickListener;\r
49 import com.google.gwt.user.client.ui.FlexTable;\r
50 import com.google.gwt.user.client.ui.HTML;\r
51 import com.google.gwt.user.client.ui.HasHorizontalAlignment;\r
52 import com.google.gwt.user.client.ui.HorizontalPanel;\r
53 import com.google.gwt.user.client.ui.VerticalPanel;\r
54 import com.google.gwt.user.client.ui.Widget;\r
55 \r
56 /**\r
57  * The 'File upload' dialog box implementation with Google Gears support.\r
58  */\r
59 public class FileUploadGearsDialog extends FileUploadDialog implements Updateable {\r
60 \r
61         private final Factory factory = Factory.getInstance();\r
62 \r
63         /**\r
64          * The array of files to upload.\r
65          */\r
66         private File[] fileObjects;\r
67 \r
68         /**\r
69          * A list of files to upload, created from files array. Used to signal\r
70          * finished state when empty.\r
71          */\r
72         private List<File> selectedFiles = new ArrayList<File>();\r
73 \r
74         /**\r
75          * The list of progress bars for individual files.\r
76          */\r
77         private List<ProgressBar> progressBars = new ArrayList<ProgressBar>();\r
78 \r
79         private Button browse;\r
80 \r
81         private Button submit;\r
82 \r
83         private FlexTable generalTable;\r
84 \r
85         private Map<String, FileResource> toRename;\r
86 \r
87         private List<HttpRequest> requests = new ArrayList<HttpRequest>();\r
88 \r
89         /**\r
90          * The widget's constructor.\r
91          */\r
92         public FileUploadGearsDialog() {\r
93                 // Set the dialog's caption.\r
94                 setText("File upload");\r
95                 setAnimationEnabled(true);\r
96                 // Create a panel to hold all of the dialog widgets.\r
97                 VerticalPanel panel = new VerticalPanel();\r
98                 final HTML info = new HTML("You may select one or more files to upload.");\r
99                 info.addStyleName("gss-uploadNote");\r
100                 panel.add(info);\r
101                 // Add an informative label with the folder name.\r
102                 Object selection = GSS.get().getFolders().getCurrent().getUserObject();\r
103                 folder = (FolderResource) selection;\r
104 \r
105                 browse = new Button("Browse...");\r
106 \r
107                 HorizontalPanel fileUploadPanel = new HorizontalPanel();\r
108                 fileUploadPanel.add(browse);\r
109 \r
110                 generalTable = new FlexTable();\r
111                 generalTable.setText(0, 0, "Folder");\r
112                 generalTable.setText(1, 0, "File");\r
113                 generalTable.setText(0, 1, folder.getName());\r
114                 generalTable.setWidget(1, 1, fileUploadPanel);\r
115                 generalTable.getCellFormatter().setStyleName(0, 0, "props-labels");\r
116                 generalTable.getCellFormatter().setStyleName(1, 0, "props-labels");\r
117                 generalTable.getCellFormatter().setStyleName(0, 1, "props-values");\r
118                 generalTable.getCellFormatter().setStyleName(1, 1, "props-values");\r
119                 generalTable.setCellSpacing(4);\r
120 \r
121                 panel.add(generalTable);\r
122 \r
123                 // Create a panel to hold the buttons.\r
124                 HorizontalPanel buttons = new HorizontalPanel();\r
125 \r
126                 submit = new Button("Upload");\r
127                 submit.addClickListener(new ClickListener() {\r
128 \r
129                         public void onClick(Widget sender) {\r
130                                 prepareAndSubmit();\r
131                         }\r
132                 });\r
133                 submit.setEnabled(false);\r
134                 buttons.add(submit);\r
135                 buttons.setCellHorizontalAlignment(submit, HasHorizontalAlignment.ALIGN_CENTER);\r
136                 // Create the 'Cancel' button, along with a listener that hides the\r
137                 // dialog when the button is clicked.\r
138                 Button cancel = new Button("Cancel", new ClickListener() {\r
139 \r
140                         public void onClick(Widget sender) {\r
141                                 cancelUpload();\r
142                         }\r
143                 });\r
144                 buttons.add(cancel);\r
145                 buttons.setCellHorizontalAlignment(cancel, HasHorizontalAlignment.ALIGN_CENTER);\r
146                 buttons.setSpacing(8);\r
147                 buttons.addStyleName("gss-DialogBox");\r
148 \r
149                 browse.addClickListener(new ClickListener() {\r
150                         public void onClick(Widget sender) {\r
151                                 Desktop desktop = factory.createDesktop();\r
152                                 desktop.openFiles(new OpenFilesHandler() {\r
153 \r
154                                         public void onOpenFiles(OpenFilesEvent event) {\r
155                                                 fileObjects = event.getFiles();\r
156                                                 selectedFiles.addAll(Arrays.asList(fileObjects));\r
157                                                 for (int i = 0; i< selectedFiles.size(); i++) {\r
158                                                         generalTable.setText(i+1, 0, "File");\r
159                                                         generalTable.setText(i+1, 1, selectedFiles.get(i).getName());\r
160                                                         ProgressBar progress = new ProgressBar(20, 0);\r
161                                                         generalTable.setWidget(i+1, 2, progress);\r
162                                                         progressBars.add(progress);\r
163                                                         generalTable.getCellFormatter().setStyleName(i+1, 0, "props-labels");\r
164                                                         generalTable.getCellFormatter().setStyleName(i+1, 1, "props-values");\r
165                                                 }\r
166                                                 submit.setEnabled(true);\r
167                                         }\r
168                                 });\r
169                         }\r
170                 });\r
171 \r
172                 panel.add(buttons);\r
173                 panel.setCellHorizontalAlignment(buttons, HasHorizontalAlignment.ALIGN_CENTER);\r
174                 panel.addStyleName("gss-DialogBox");\r
175                 addStyleName("gss-DialogBox");\r
176                 setWidget(panel);\r
177         }\r
178 \r
179         /**\r
180          * Cancels the file upload.\r
181          */\r
182         private void cancelUpload() {\r
183                 for (HttpRequest request: requests)\r
184                         request.abort();\r
185                 hide();\r
186         }\r
187 \r
188         /**\r
189          * Check whether the specified file name exists in the selected folder.\r
190          */\r
191         private boolean canContinue(File file) {\r
192                 String fileName = getFilename(file.getName());\r
193                 if (getFileForName(fileName) == null)\r
194                         // For file creation, check to see if the file already exists.\r
195                         for (FileResource fileRes : files)\r
196                                 if (!fileRes.isDeleted() && fileRes.getName().equals(fileName))\r
197                                         return false;\r
198                 return true;\r
199         }\r
200 \r
201         @Override\r
202         public void prepareAndSubmit() {\r
203                 GSS app = GSS.get();\r
204                 if (selectedFiles.size() == 0) {\r
205                         app.displayError("You must select a file!");\r
206                         hide();\r
207                         return;\r
208                 }\r
209                 for (File file: selectedFiles)\r
210                         if (!canContinue(file)) {\r
211                                 app.displayError("The file name " + file.getName() +\r
212                                                         " already exists in this folder");\r
213                                 hide();\r
214                                 return;\r
215                         }\r
216                 submit.setEnabled(false);\r
217                 browse.setVisible(false);\r
218                 List<String> toUpdate = new ArrayList<String>();\r
219                 toRename = new HashMap<String, FileResource>();\r
220                 for (File file: selectedFiles) {\r
221                         String fname = getFilename(file.getName());\r
222                         if (getFileForName(fname) == null) {\r
223                                 // We are going to create a file, so we check to see if there is a\r
224                                 // trashed file with the same name.\r
225                                 FileResource same = null;\r
226                                 for (FileResource fres : folder.getFiles())\r
227                                         if (fres.isDeleted() && fres.getName().equals(fname))\r
228                                                 same = fres;\r
229                                 // In that case add it to the list of files to rename.\r
230                                 if (same != null)\r
231                                         toRename.put(getBackupFilename(fname), same);\r
232                         } else\r
233                                 // If we are updating a file add it to the list of files to update.\r
234                                 toUpdate.add(fname);\r
235                 }\r
236 \r
237                 if (!toUpdate.isEmpty()) {\r
238                         StringBuffer sb = new StringBuffer();\r
239                         for (String name: toUpdate)\r
240                                 sb.append(name).append("<br/>");\r
241                         // We are going to update existing files, so show a confirmation dialog.\r
242                         ConfirmationDialog confirm = new ConfirmationDialog("Are you sure " +\r
243                                         "you want to update the following files?<br/><i>" + sb +\r
244                                         "</i>", "Update") {\r
245 \r
246                                 @Override\r
247                                 public void cancel() {\r
248                                         hide();\r
249                                 }\r
250 \r
251                                 @Override\r
252                                 public void confirm() {\r
253                                         confirmRename();\r
254                                 }\r
255 \r
256                         };\r
257                         confirm.center();\r
258                 } else\r
259                         confirmRename();\r
260         }\r
261 \r
262         /**\r
263          * Confirm the renames of synonymous files already in the trash.\r
264          */\r
265         private void confirmRename() {\r
266                 if (!toRename.isEmpty()) {\r
267                         StringBuffer sb = new StringBuffer();\r
268                         for (FileResource file: toRename.values())\r
269                                 sb.append(file.getName()).append("<br/>");\r
270                         ConfirmationDialog confirm = new ConfirmationDialog("Files " +\r
271                                         "with the following names already exist in the trash. If" +\r
272                                         " you continue,<br/>the trashed files will be renamed " +\r
273                                         "automatically for you:<br/><i>" + sb + "</i>", "Continue") {\r
274 \r
275                                 @Override\r
276                                 public void cancel() {\r
277                                         hide();\r
278                                 }\r
279 \r
280                                 @Override\r
281                                 public void confirm() {\r
282                                         updateTrashedFiles();\r
283                                 }\r
284 \r
285                         };\r
286                         confirm.center();\r
287                 } else\r
288                         uploadFiles();\r
289         }\r
290 \r
291         /**\r
292          * Rename the conflicting trashed files with the supplied new names.\r
293          */\r
294         private void updateTrashedFiles() {\r
295                 for (final String name: toRename.keySet()) {\r
296                         JSONObject json = new JSONObject();\r
297                         json.put("name", new JSONString(name));\r
298                         PostCommand cf = new PostCommand(toRename.get(name).getUri() + "?update=", json.toString(), 200) {\r
299 \r
300                                 @Override\r
301                                 public void onComplete() {\r
302                                         toRename.remove(name);\r
303                                         uploadFiles();\r
304                                 }\r
305 \r
306                                 @Override\r
307                                 public void onError(Throwable t) {\r
308                                         GSS app = GSS.get();\r
309                                         GWT.log("", t);\r
310                                         if (t instanceof RestException) {\r
311                                                 int statusCode = ((RestException) t).getHttpStatusCode();\r
312                                                 if (statusCode == 405)\r
313                                                         app.displayError("You don't have the necessary permissions");\r
314                                                 else if (statusCode == 404)\r
315                                                         app.displayError("User in permissions does not exist");\r
316                                                 else if (statusCode == 409)\r
317                                                         app.displayError("A file with the same name already exists");\r
318                                                 else if (statusCode == 413)\r
319                                                         app.displayError("Your quota has been exceeded");\r
320                                                 else\r
321                                                         app.displayError("Unable to modify file:" + ((RestException) t).getHttpStatusText());\r
322                                         } else\r
323                                                 app.displayError("System error modifying file:" + t.getMessage());\r
324                                 }\r
325 \r
326                         };\r
327                         DeferredCommand.addCommand(cf);\r
328                 }\r
329         }\r
330 \r
331         /**\r
332          * Checks if the renaming step for already trashed files is complete and\r
333          * starts file uploads.\r
334          */\r
335         private void uploadFiles() {\r
336                 if (!toRename.isEmpty()) return;\r
337                 for (int i = 0; i< fileObjects.length; i++) {\r
338                         final int index = i;\r
339                         DeferredCommand.addCommand(new Command() {\r
340                                 public void execute() {\r
341                                         doPut(fileObjects[index], index);\r
342                                 }\r
343                         });\r
344                 }\r
345         }\r
346 \r
347         /**\r
348          * Perform the HTTP PUT requests to upload the specified file.\r
349          */\r
350         protected void doPut(final File file, final int index) {\r
351                 final GSS app = GSS.get();\r
352                 HttpRequest request = factory.createHttpRequest();\r
353                 requests.add(request);\r
354                 String method = "PUT";\r
355 \r
356                 String path;\r
357                 final String filename = getFilename(file.getName());\r
358                 path = folder.getUri();\r
359                 if (!path.endsWith("/"))\r
360                         path = path + "/";\r
361                 path = path + encode(filename);\r
362 \r
363                 String token = app.getToken();\r
364                 String resource = path.substring(app.getApiPath().length()-1, path.length());\r
365                 String date = RestCommand.getDate();\r
366                 String sig = RestCommand.calculateSig(method, date, resource, RestCommand.base64decode(token));\r
367                 request.open(method, path);\r
368                 request.setRequestHeader("X-GSS-Date", date);\r
369                 request.setRequestHeader("Authorization", app.getCurrentUserResource().getUsername() + " " + sig);\r
370                 request.setRequestHeader("Accept", "application/json; charset=utf-8");\r
371                 request.setCallback(new RequestCallback() {\r
372                         public void onResponseReceived(HttpRequest req) {\r
373                                 switch(req.getStatus()) {\r
374                                         case 201: // Created falls through to updated.\r
375                                         case 204:\r
376                                                 selectedFiles.remove(file);\r
377                                                 finish();\r
378                                                 break;\r
379                                         case 403:\r
380                                                 SessionExpiredDialog dlg = new SessionExpiredDialog();\r
381                                                 dlg.center();\r
382                                                 break;\r
383                                         case 405:\r
384                                                 app.displayError("You don't have permission to " +\r
385                                                                 "upload file " + filename);\r
386                                                 break;\r
387                                         case 409:\r
388                                                 app.displayError("A folder with the name " + filename +\r
389                                                                 " already exists at this level");\r
390                                                 break;\r
391                                         case 413:\r
392                                                 app.displayError("There is not enough free space " +\r
393                                                                 "available for uploading " + filename);\r
394                                                 break;\r
395                                         default:\r
396                                                 app.displayError("Error uploading file " + filename +\r
397                                                                         ": " + req.getStatus());\r
398                                                 DisplayHelper.log(req.getStatus() + ":" + req.getStatusText());\r
399                                 }\r
400                         }\r
401                 });\r
402                 request.getUpload().setProgressHandler(new ProgressHandler() {\r
403                         public void onProgress(ProgressEvent event) {\r
404                                 double pcnt = (double) event.getLoaded() / event.getTotal();\r
405                                 progressBars.get(index).setProgress((int) Math.floor(pcnt * 100));\r
406                         }\r
407                 });\r
408                 request.send(file.getBlob());\r
409         }\r
410 \r
411         /**\r
412          * Perform the final actions after the files are uploaded.\r
413          */\r
414         private void finish() {\r
415                 if (!selectedFiles.isEmpty()) return;\r
416                 hide();\r
417                 GSS.get().showFileList(true);\r
418                 GSS.get().getStatusPanel().updateStats();\r
419         }\r
420 \r
421         /**\r
422          * Same as URL.encode, but also encode apostrophe since browsers aren't\r
423          * consistent about it (FF encodes, IE does not).\r
424          */\r
425         private String encode(String decodedURL) {\r
426                 String retv = URL.encode(decodedURL);\r
427                 retv = retv.replaceAll("'", "%27");\r
428                 return retv;\r
429         }\r
430 \r
431 }\r