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