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