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