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