Removed no longer needed line (since previous fix).
[pithos] / gss / src / gr / ebs / gss / client / FileUploadDialog.java
1 /*\r
2  * Copyright 2007, 2008, 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.FileMenu.Images;\r
22 import gr.ebs.gss.client.rest.GetCommand;\r
23 import gr.ebs.gss.client.rest.PostCommand;\r
24 import gr.ebs.gss.client.rest.RestCommand;\r
25 import gr.ebs.gss.client.rest.RestException;\r
26 import gr.ebs.gss.client.rest.resource.FileResource;\r
27 import gr.ebs.gss.client.rest.resource.FolderResource;\r
28 import gr.ebs.gss.client.rest.resource.UploadStatusResource;\r
29 \r
30 import java.util.ArrayList;\r
31 import java.util.List;\r
32 \r
33 import com.google.gwt.core.client.GWT;\r
34 import com.google.gwt.http.client.URL;\r
35 import com.google.gwt.json.client.JSONObject;\r
36 import com.google.gwt.json.client.JSONString;\r
37 import com.google.gwt.user.client.DeferredCommand;\r
38 import com.google.gwt.user.client.Timer;\r
39 import com.google.gwt.user.client.ui.Button;\r
40 import com.google.gwt.user.client.ui.ClickListener;\r
41 import com.google.gwt.user.client.ui.DialogBox;\r
42 import com.google.gwt.user.client.ui.FileUpload;\r
43 import com.google.gwt.user.client.ui.FormHandler;\r
44 import com.google.gwt.user.client.ui.FormPanel;\r
45 import com.google.gwt.user.client.ui.FormSubmitCompleteEvent;\r
46 import com.google.gwt.user.client.ui.FormSubmitEvent;\r
47 import com.google.gwt.user.client.ui.Grid;\r
48 import com.google.gwt.user.client.ui.HasHorizontalAlignment;\r
49 import com.google.gwt.user.client.ui.Hidden;\r
50 import com.google.gwt.user.client.ui.HorizontalPanel;\r
51 import com.google.gwt.user.client.ui.KeyboardListener;\r
52 import com.google.gwt.user.client.ui.Label;\r
53 import com.google.gwt.user.client.ui.VerticalPanel;\r
54 import com.google.gwt.user.client.ui.Widget;\r
55 \r
56 /**\r
57  * The 'File upload' dialog box implementation.\r
58  */\r
59 public class FileUploadDialog extends DialogBox implements Updateable {\r
60 \r
61         private int prgBarInterval = 1500;\r
62 \r
63         private ProgressBar progressBar;\r
64 \r
65         private RepeatingTimer repeater = new RepeatingTimer(this, prgBarInterval);\r
66 \r
67         public static final boolean DONE = true;\r
68 \r
69         /**\r
70          * The Form element that performs the file upload.\r
71          */\r
72         final FormPanel form = new FormPanel();\r
73 \r
74         final FileUpload upload = new FileUpload();\r
75 \r
76         final Label filenameLabel = new Label("");\r
77 \r
78         private List<FileResource> files;\r
79 \r
80         boolean cancelEvent = false;\r
81 \r
82         private String fileNameToUse;\r
83 \r
84         final FolderResource folder;\r
85         final Images images;\r
86 \r
87         /**\r
88          * The widget's constructor.\r
89          * @param _images\r
90          * @param _files\r
91          */\r
92         public FileUploadDialog(final Images _images, List<FileResource> _files) {\r
93                 images = _images;\r
94                 files = _files;\r
95                 // Set the dialog's caption.\r
96                 setText("File upload");\r
97                 setAnimationEnabled(true);\r
98                 // Since we're going to add a FileUpload widget, we'll need to set the\r
99                 // form to use the POST method, and multipart MIME encoding.\r
100                 form.setEncoding(FormPanel.ENCODING_MULTIPART);\r
101                 form.setMethod(FormPanel.METHOD_POST);\r
102 \r
103                 // Create a panel to hold all of the form widgets.\r
104                 VerticalPanel panel = new VerticalPanel();\r
105                 form.setWidget(panel);\r
106                 final Hidden date = new Hidden("Date", "");\r
107                 panel.add(date);\r
108                 final Hidden auth = new Hidden("Authorization", "");\r
109                 panel.add(auth);\r
110                 // Add an informative label with the folder name.\r
111                 Object selection = GSS.get().getFolders().getCurrent().getUserObject();\r
112                 folder = (FolderResource) selection;\r
113                 upload.setName("file");\r
114                 filenameLabel.setText("");\r
115                 filenameLabel.setVisible(false);\r
116                 filenameLabel.setStyleName("props-labels");\r
117                 HorizontalPanel fileUloadPanel = new HorizontalPanel();\r
118                 fileUloadPanel.add(filenameLabel);\r
119                 fileUloadPanel.add(upload);\r
120                 Grid generalTable = new Grid(2, 2);\r
121                 generalTable.setText(0, 0, "Folder");\r
122                 generalTable.setText(1, 0, "File");\r
123                 generalTable.setText(0, 1, folder.getName());\r
124                 generalTable.setWidget(1, 1, fileUloadPanel);\r
125                 generalTable.getCellFormatter().setStyleName(0, 0, "props-labels");\r
126                 generalTable.getCellFormatter().setStyleName(1, 0, "props-labels");\r
127                 generalTable.getCellFormatter().setStyleName(0, 1, "props-values");\r
128                 generalTable.getCellFormatter().setStyleName(1, 1, "props-values");\r
129                 generalTable.setCellSpacing(4);\r
130 \r
131                 panel.add(generalTable);\r
132 \r
133                 // Create a panel to hold the buttons.\r
134                 HorizontalPanel buttons = new HorizontalPanel();\r
135 \r
136                 // Create the 'upload' button, along with a listener that submits the\r
137                 // form.\r
138                 final Button submit = new Button("Upload", new ClickListener() {\r
139                         public void onClick(Widget sender) {\r
140                                 prepareAndSubmit();\r
141                         }\r
142                 });\r
143                 buttons.add(submit);\r
144                 buttons.setCellHorizontalAlignment(submit, HasHorizontalAlignment.ALIGN_CENTER);\r
145                 // Create the 'Cancel' button, along with a listener that hides the\r
146                 // dialog when the button is clicked.\r
147                 final Button cancel = new Button("Cancel", new ClickListener() {\r
148 \r
149                         public void onClick(Widget sender) {\r
150                                 repeater.finish();\r
151                                 hide();\r
152                         }\r
153                 });\r
154                 buttons.add(cancel);\r
155                 buttons.setCellHorizontalAlignment(cancel, HasHorizontalAlignment.ALIGN_CENTER);\r
156                 buttons.setSpacing(8);\r
157                 buttons.addStyleName("gss-DialogBox");\r
158 \r
159                 // Add an event handler to the form.\r
160                 form.addFormHandler(new FormHandler() {\r
161 \r
162                         public void onSubmit(final FormSubmitEvent event) {\r
163                                 GSS app = GSS.get();\r
164                                 // This event is fired just before the form is submitted. We can\r
165                                 // take this opportunity to perform validation.\r
166                                 if (upload.getFilename().length() == 0) {\r
167                                         app.displayError("You must select a file!");\r
168                                         event.setCancelled(true);\r
169                                         hide();\r
170                                 } else {\r
171 \r
172                                         canContinue();\r
173                                         GWT.log("Cancel:" + cancelEvent, null);\r
174                                         if (cancelEvent) {\r
175                                                 cancelEvent = false;\r
176                                                 app.displayError("The specified file name already exists in this folder");\r
177                                                 event.setCancelled(true);\r
178                                                 hide();\r
179                                         } else {\r
180 \r
181                                                 fileNameToUse = getFilename(upload.getFilename());\r
182                                                 String apath;\r
183                                                 FileResource selectedFile = getFileForName(fileNameToUse);\r
184                                                 if (selectedFile == null ) {\r
185                                                         //we are going to create a file\r
186                                                         apath = folder.getUri();\r
187                                                         if (!apath.endsWith("/"))\r
188                                                                 apath = apath + "/";\r
189                                                         apath = apath + encodeComponent(fileNameToUse);\r
190                                                 } else\r
191                                                         apath = selectedFile.getUri();\r
192                                                 form.setAction(apath);\r
193                                                 String dateString = RestCommand.getDate();\r
194                                                 String resource = apath.substring(app.getApiPath().length() - 1, apath.length());\r
195                                                 String sig = RestCommand.calculateSig("POST", dateString, resource, RestCommand.base64decode(app.getToken()));\r
196                                                 date.setValue(dateString);\r
197                                                 auth.setValue(app.getCurrentUserResource().getUsername() + " " + sig);\r
198                                                 GWT.log("FolderPATH:" + folder.getUri(), null);\r
199                                                 submit.setEnabled(false);\r
200                                                 upload.setVisible(false);\r
201                                                 filenameLabel.setText(fileNameToUse);\r
202                                                 filenameLabel.setVisible(true);\r
203                                                 repeater.start();\r
204                                                 progressBar.setVisible(true);\r
205                                         }\r
206                                 }\r
207                         }\r
208 \r
209                         public void onSubmitComplete(final FormSubmitCompleteEvent event) {\r
210                                 // When the form submission is successfully completed, this\r
211                                 // event is fired. Assuming the service returned a response\r
212                                 // of type text/html, we can get the result text here (see\r
213                                 // the FormPanel documentation for further explanation).\r
214                                 String results = event.getResults();\r
215 \r
216                                 // Unfortunately the results are never empty, even in\r
217                                 // the absense of errors, so we have to check for '<pre></pre>'.\r
218                                 if (!results.equalsIgnoreCase("<pre></pre>")) {\r
219                                         GWT.log(results, null);\r
220                                         GSS.get().displayError(results);\r
221                                 }\r
222                                 progressBar.setProgress(100);\r
223                                 repeater.finish();\r
224                                 hide();\r
225                                 GSS.get().showFileList(true);\r
226                                 GSS.get().getStatusPanel().updateStats();\r
227                         }\r
228                 });\r
229 \r
230                 panel.add(buttons);\r
231                 progressBar = new ProgressBar(50, ProgressBar.SHOW_TIME_REMAINING);\r
232                 panel.add(progressBar);\r
233                 progressBar.setVisible(false);\r
234                 panel.setCellHorizontalAlignment(buttons, HasHorizontalAlignment.ALIGN_CENTER);\r
235                 panel.addStyleName("gss-DialogBox");\r
236                 addStyleName("gss-DialogBox");\r
237                 setWidget(form);\r
238         }\r
239 \r
240         @Override\r
241         public boolean onKeyDownPreview(char key, int modifiers) {\r
242                 // Use the popup's key preview hooks to close the dialog when either\r
243                 // enter or escape is pressed.\r
244                 switch (key) {\r
245                         case KeyboardListener.KEY_ENTER:\r
246                                 prepareAndSubmit();\r
247                                 break;\r
248                         case KeyboardListener.KEY_ESCAPE:\r
249                                 repeater.finish();\r
250                                 hide();\r
251                                 break;\r
252                 }\r
253 \r
254                 return true;\r
255         }\r
256 \r
257 \r
258         public void prepareAndSubmit(){\r
259                 final String fname = getFilename(upload.getFilename());\r
260                 if (getFileForName(fname) == null) {\r
261                         //we are going to create a file, so we check to see if there is a trashed file with the same name\r
262                         FileResource same = null;\r
263                         for (FileResource fres : folder.getFiles())\r
264                                 if (fres.isDeleted() && fres.getName().equals(fname))\r
265                                         same = fres;\r
266                         if (same == null)\r
267                                 form.submit();\r
268                         else {\r
269                                 final FileResource sameFile = same;\r
270                                 GWT.log("Same deleted file", null);\r
271                                 ConfirmationDialog confirm = new ConfirmationDialog(images, "A file with " +\r
272                                                 "the same name exists in the trash. If you continue,<br/>the trashed " +\r
273                                                 "file  '" + fname + "' will be renamed automatically for you.", "Continue"){\r
274 \r
275                                         @Override\r
276                                         public void cancel() {\r
277                                                 FileUploadDialog.this.hide();\r
278                                         }\r
279 \r
280                                         @Override\r
281                                         public void confirm() {\r
282                                                 updateTrashedFile(getBackupFilename(fname), sameFile);\r
283                                         }\r
284 \r
285                                 };\r
286                                 confirm.center();\r
287                         }\r
288                 }\r
289                 else {\r
290                         // We are going to update an existing file, so show a confirmation dialog.\r
291                         ConfirmationDialog confirm = new ConfirmationDialog(images, "Are you sure " +\r
292                                         "you want to update " + fname + "?", "Update"){\r
293 \r
294                                 @Override\r
295                                 public void cancel() {\r
296                                         FileUploadDialog.this.hide();\r
297                                 }\r
298 \r
299                                 @Override\r
300                                 public void confirm() {\r
301                                         form.submit();\r
302                                 }\r
303 \r
304                         };\r
305                         confirm.center();\r
306                 }\r
307         }\r
308 \r
309         /**\r
310          * Returns the file name from a potential full path argument. Apparently IE\r
311          * insists on sending the full path name of a file when uploading, forcing\r
312          * us to trim the extra path info. Since this is only observed on Windows we\r
313          * get to check for a single path separator value.\r
314          *\r
315          * @param name the potentially full path name of a file\r
316          * @return the file name without extra path information\r
317          */\r
318         private String getFilename(String name) {\r
319                 int pathSepIndex = name.lastIndexOf("\\");\r
320                 if (pathSepIndex == -1) {\r
321                         pathSepIndex = name.lastIndexOf("/");\r
322                         if (pathSepIndex == -1)\r
323                                 return name;\r
324                 }\r
325                 return name.substring(pathSepIndex + 1);\r
326         }\r
327 \r
328         /**\r
329          * Check whether the file name exists in selected folder.\r
330          *\r
331          * @return\r
332          */\r
333         private boolean canContinue() {\r
334                 if (files == null)\r
335                         return false;\r
336                 String fileName = getFilename(upload.getFilename());\r
337                 if (getFileForName(fileName) == null) {\r
338                         // For file creation, check to see if the file already exists.\r
339                         GWT.log("filename to upload:" + fileName, null);\r
340                         for (FileResource dto : files) {\r
341                                 GWT.log("Check:" + dto.getName() + "/" + fileName, null);\r
342                                 if (!dto.isDeleted() && dto.getName().equals(fileName)) {\r
343                                         cancelEvent = true;\r
344                                         return true;\r
345                                 }\r
346                         }\r
347                 }\r
348                 return true;\r
349         }\r
350 \r
351         class RepeatingTimer extends Timer {\r
352 \r
353                 private Updateable updateable;\r
354 \r
355                 private int interval = 1500;\r
356 \r
357                 private boolean running = true;\r
358 \r
359                 RepeatingTimer(Updateable _updateable, int _interval) {\r
360                         updateable = _updateable;\r
361                         interval = _interval;\r
362                 }\r
363 \r
364                 @Override\r
365                 public void run() {\r
366                         updateable.update();\r
367                 }\r
368 \r
369                 public void start() {\r
370                         running = true;\r
371 \r
372                         scheduleRepeating(interval);\r
373                 }\r
374 \r
375                 public void finish() {\r
376                         running = false;\r
377                         cancel();\r
378                 }\r
379 \r
380                 public int getInterval() {\r
381                         return interval;\r
382                 }\r
383 \r
384                 public void setInterval(int anInterval) {\r
385                         if (interval != anInterval) {\r
386                                 interval = anInterval;\r
387                                 if (running) {\r
388                                         finish();\r
389                                         start();\r
390                                 }\r
391                         }\r
392                 }\r
393         }\r
394 \r
395         /* (non-Javadoc)\r
396          * @see gr.ebs.gss.client.Updateable#update()\r
397          */\r
398         public void update() {\r
399                 String apath = folder.getUri();\r
400                 if (!apath.endsWith("/"))\r
401                         apath = apath + "/";\r
402                 apath = apath + encodeComponent(fileNameToUse) + "?progress=" + encodeComponent(fileNameToUse);\r
403                 GetCommand eg = new GetCommand<UploadStatusResource>(UploadStatusResource.class, apath, false) {\r
404 \r
405                         @Override\r
406                         public void onComplete() {\r
407                                 UploadStatusResource res = getResult();\r
408                                 progressBar.setProgress(res.percent());\r
409                         }\r
410 \r
411                         @Override\r
412                         public void onError(Throwable t) {\r
413                                 GWT.log("", t);\r
414 \r
415                         }\r
416 \r
417                 };\r
418                 DeferredCommand.addCommand(eg);\r
419         }\r
420 \r
421         private String getBackupFilename(String filename) {\r
422                 List<FileResource> filesInSameFolder = new ArrayList<FileResource>();\r
423                 for (FileResource deleted : folder.getFiles())\r
424                         if (deleted.isDeleted())\r
425                                 filesInSameFolder.add(deleted);\r
426                 int i = 1;\r
427                 for (FileResource same : filesInSameFolder)\r
428                         if (same.getName().startsWith(filename)) {\r
429                                 String toCheck = same.getName().substring(filename.length(), same.getName().length());\r
430                                 if (toCheck.startsWith(" ")) {\r
431                                         int test = -1;\r
432                                         try {\r
433                                                 test = Integer.valueOf(toCheck.replace(" ", ""));\r
434                                         } catch (NumberFormatException e) {\r
435                                                 // Do nothing since string is not a number.\r
436                                         }\r
437                                         if (test >= i)\r
438                                                 i = test + 1;\r
439                                 }\r
440                         }\r
441 \r
442                 return filename + " " + i;\r
443         }\r
444 \r
445         private void updateTrashedFile(String newName, FileResource trashedFile) {\r
446                 JSONObject json = new JSONObject();\r
447                 json.put("name", new JSONString(newName));\r
448                 PostCommand cf = new PostCommand(trashedFile.getUri() + "?update=", json.toString(), 200) {\r
449 \r
450                         @Override\r
451                         public void onComplete() {\r
452                                 form.submit();\r
453                         }\r
454 \r
455                         @Override\r
456                         public void onError(Throwable t) {\r
457                                 GWT.log("", t);\r
458                                 if (t instanceof RestException) {\r
459                                         int statusCode = ((RestException) t).getHttpStatusCode();\r
460                                         if (statusCode == 405)\r
461                                                 GSS.get().displayError("You don't have the necessary permissions");\r
462                                         else if (statusCode == 404)\r
463                                                 GSS.get().displayError("User in permissions does not exist");\r
464                                         else if (statusCode == 409)\r
465                                                 GSS.get().displayError("A file with the same name already exists");\r
466                                         else if (statusCode == 413)\r
467                                                 GSS.get().displayError("Your quota has been exceeded");\r
468                                         else\r
469                                                 GSS.get().displayError("Unable to modify file:" +((RestException)t).getHttpStatusText());\r
470                                 } else\r
471                                         GSS.get().displayError("System error modifying file:" + t.getMessage());\r
472                         }\r
473 \r
474                 };\r
475                 DeferredCommand.addCommand(cf);\r
476         }\r
477 \r
478         private FileResource getFileForName(String name){\r
479                 for (FileResource f : folder.getFiles())\r
480                         if (!f.isDeleted() && f.getName().equals(name))\r
481                                 return f;\r
482                 return null;\r
483         }\r
484 \r
485 \r
486         /**\r
487          * Same as URL.encodeComponent, but also\r
488          * encode apostrophe since browsers aren't consistent about it\r
489          * (FF encodes, IE does not).\r
490          *\r
491          * @param decodedURLComponent\r
492          * @return\r
493          */\r
494         private String encodeComponent(String decodedURLComponent) {\r
495                 String retv = URL.encodeComponent(decodedURLComponent);\r
496                 retv = retv.replaceAll("'", "%27");\r
497                 return retv;\r
498         }\r
499 }\r