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