Statistics
| Branch: | Tag: | Revision:

root / src / gr / grnet / pithos / web / client / FileUploadGearsDialog.java @ 63366925

History | View | Annotate | Download (14.4 kB)

1
/*
2
 * Copyright 2011 GRNET S.A. All rights reserved.
3
 *
4
 * Redistribution and use in source and binary forms, with or
5
 * without modification, are permitted provided that the following
6
 * conditions are met:
7
 *
8
 *   1. Redistributions of source code must retain the above
9
 *      copyright notice, this list of conditions and the following
10
 *      disclaimer.
11
 *
12
 *   2. Redistributions in binary form must reproduce the above
13
 *      copyright notice, this list of conditions and the following
14
 *      disclaimer in the documentation and/or other materials
15
 *      provided with the distribution.
16
 *
17
 * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
18
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
21
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
24
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
25
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28
 * POSSIBILITY OF SUCH DAMAGE.
29
 *
30
 * The views and conclusions contained in the software and
31
 * documentation are those of the authors and should not be
32
 * interpreted as representing official policies, either expressed
33
 * or implied, of GRNET S.A.
34
 */
35
package gr.grnet.pithos.web.client;
36

    
37
import gr.grnet.pithos.web.client.rest.PostCommand;
38
import gr.grnet.pithos.web.client.rest.RestCommand;
39
import gr.grnet.pithos.web.client.rest.RestException;
40
import gr.grnet.pithos.web.client.rest.resource.FileResource;
41
import gr.grnet.pithos.web.client.rest.resource.RestResourceWrapper;
42

    
43
import java.util.ArrayList;
44
import java.util.Arrays;
45
import java.util.HashMap;
46
import java.util.List;
47
import java.util.Map;
48

    
49
import com.google.gwt.core.client.GWT;
50
import com.google.gwt.event.dom.client.ClickEvent;
51
import com.google.gwt.event.dom.client.ClickHandler;
52
import com.google.gwt.gears.client.Factory;
53
import com.google.gwt.gears.client.desktop.Desktop;
54
import com.google.gwt.gears.client.desktop.File;
55
import com.google.gwt.gears.client.desktop.OpenFilesHandler;
56
import com.google.gwt.gears.client.httprequest.HttpRequest;
57
import com.google.gwt.gears.client.httprequest.ProgressEvent;
58
import com.google.gwt.gears.client.httprequest.ProgressHandler;
59
import com.google.gwt.gears.client.httprequest.RequestCallback;
60
import com.google.gwt.http.client.URL;
61
import com.google.gwt.json.client.JSONObject;
62
import com.google.gwt.json.client.JSONString;
63
import com.google.gwt.user.client.DeferredCommand;
64
import com.google.gwt.user.client.ui.Button;
65
import com.google.gwt.user.client.ui.FlexTable;
66
import com.google.gwt.user.client.ui.HTML;
67
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
68
import com.google.gwt.user.client.ui.HorizontalPanel;
69
import com.google.gwt.user.client.ui.VerticalPanel;
70

    
71
/**
72
 * The 'File upload' dialog box implementation with Google Gears support.
73
 */
74
public class FileUploadGearsDialog extends FileUploadDialog implements Updateable {
75

    
76
        protected final Factory factory = Factory.getInstance();
77

    
78
        /**
79
         * The array of files to upload.
80
         */
81
        private File[] fileObjects;
82

    
83
        /**
84
         * A list of files to upload, created from files array. Used to signal
85
         * finished state when empty.
86
         */
87
        protected List<File> selectedFiles = new ArrayList<File>();
88

    
89
        /**
90
         * The list of progress bars for individual files.
91
         */
92
        protected List<ProgressBar> progressBars = new ArrayList<ProgressBar>();
93

    
94
        private Button browse;
95

    
96
        private Button submit;
97

    
98
        private FlexTable generalTable;
99

    
100
        private Map<String, FileResource> toRename;
101

    
102
        protected List<HttpRequest> requests = new ArrayList<HttpRequest>();
103
        
104
        private boolean canContinue = true;
105

    
106
        /**
107
         * The widget's constructor.
108
         */
109
        public FileUploadGearsDialog() {
110
                // Set the dialog's caption.
111
                setText("File upload");
112
                setAnimationEnabled(true);
113
                // Create a panel to hold all of the dialog widgets.
114
                VerticalPanel panel = new VerticalPanel();
115
                final HTML info = new HTML("You may select one or more files to upload.");
116
                info.addStyleName("pithos-uploadNote");
117
                panel.add(info);
118
                // Add an informative label with the folder name.
119
                Object selection = GSS.get().getTreeView().getSelection();
120
                folder = ((RestResourceWrapper) selection).getResource();
121

    
122
                browse = new Button("Browse...");
123

    
124
                HorizontalPanel fileUploadPanel = new HorizontalPanel();
125
                fileUploadPanel.add(browse);
126

    
127
                generalTable = new FlexTable();
128
                generalTable.setText(0, 0, "Folder");
129
                generalTable.setText(1, 0, "File");
130
                generalTable.setText(0, 1, folder.getName());
131
                generalTable.setWidget(1, 1, fileUploadPanel);
132
                generalTable.getCellFormatter().setStyleName(0, 0, "props-labels");
133
                generalTable.getCellFormatter().setStyleName(1, 0, "props-labels");
134
                generalTable.getCellFormatter().setStyleName(0, 1, "props-values");
135
                generalTable.getCellFormatter().setStyleName(1, 1, "props-values");
136
                generalTable.setCellSpacing(4);
137

    
138
                panel.add(generalTable);
139

    
140
                // Create a panel to hold the buttons.
141
                HorizontalPanel buttons = new HorizontalPanel();
142

    
143
                submit = new Button("Upload");
144
                submit.addClickHandler(new ClickHandler() {
145
                        @Override
146
                        public void onClick(ClickEvent event) {
147
                                prepareAndSubmit();
148
                        }
149
                });
150
                submit.setEnabled(false);
151
                buttons.add(submit);
152
                buttons.setCellHorizontalAlignment(submit, HasHorizontalAlignment.ALIGN_CENTER);
153
                // Create the 'Cancel' button, along with a listener that hides the
154
                // dialog when the button is clicked.
155
                Button cancel = new Button("Cancel", new ClickHandler() {
156
                        @Override
157
                        public void onClick(ClickEvent event) {
158
                                canContinue = false;                                
159
                                cancelUpload();                                
160
                                GSS.get().showFileList(true);
161
                        }
162
                });
163
                buttons.add(cancel);
164
                buttons.setCellHorizontalAlignment(cancel, HasHorizontalAlignment.ALIGN_CENTER);
165
                buttons.setSpacing(8);
166
                buttons.addStyleName("pithos-DialogBox");
167

    
168
                browse.addClickHandler(new ClickHandler() {
169
                        @Override
170
                        public void onClick(ClickEvent event) {
171
                                Desktop desktop = factory.createDesktop();
172
                                desktop.openFiles(new OpenFilesHandler() {
173

    
174
                                        @Override
175
                                        public void onOpenFiles(OpenFilesEvent ofevent) {
176
                                                fileObjects = ofevent.getFiles();
177
                                                selectedFiles.addAll(Arrays.asList(fileObjects));
178
                                                for (int i = 0; i< selectedFiles.size(); i++) {
179
                                                        generalTable.setText(i+1, 0, "File");
180
                                                        generalTable.setText(i+1, 1, selectedFiles.get(i).getName());
181
                                                        ProgressBar progress = new ProgressBar(20, 0);
182
                                                        generalTable.setWidget(i+1, 2, progress);
183
                                                        progressBars.add(progress);
184
                                                        generalTable.getCellFormatter().setStyleName(i+1, 0, "props-labels");
185
                                                        generalTable.getCellFormatter().setStyleName(i+1, 1, "props-values");
186
                                                }
187
                                                submit.setEnabled(true);
188
                                        }
189
                                });
190
                        }
191
                });
192

    
193
                panel.add(buttons);
194
                panel.setCellHorizontalAlignment(buttons, HasHorizontalAlignment.ALIGN_CENTER);
195
                panel.addStyleName("pithos-DialogBox");
196
                addStyleName("pithos-DialogBox");
197
                setWidget(panel);
198
        }
199

    
200
        /**
201
         * Cancels the file upload.
202
         */
203
        private void cancelUpload() {
204
                for (HttpRequest request: requests)
205
                        request.abort();
206
                hide();                
207
        }
208

    
209
        /**
210
         * Check whether the specified file name exists in the selected folder.
211
         */
212
        private boolean canContinue(File file) {
213
                String fileName = getFilename(file.getName());
214
                if (getFileForName(fileName) == null)
215
                        // For file creation, check to see if the file already exists.
216
                        for (FileResource fileRes : files)
217
                                if (!fileRes.isDeleted() && fileRes.getName().equals(fileName))
218
                                        return false;
219
                return true;
220
        }
221

    
222
        @Override
223
        public void prepareAndSubmit() {
224
                GSS app = GSS.get();
225
                if (selectedFiles.size() == 0) {
226
                        app.displayError("You must select a file!");
227
                        hide();
228
                        return;
229
                }
230
                for (File file: selectedFiles)
231
                        if (!canContinue(file)) {
232
                                app.displayError("The file name " + file.getName() +
233
                                                        " already exists in this folder");
234
                                hide();
235
                                return;
236
                        }
237
                submit.setEnabled(false);
238
                browse.setVisible(false);
239
                List<String> toUpdate = new ArrayList<String>();
240
                toRename = new HashMap<String, FileResource>();
241
                for (File file: selectedFiles) {
242
                        String fname = getFilename(file.getName());
243
                        if (getFileForName(fname) == null) {
244
                                // We are going to create a file, so we check to see if there is a
245
                                // trashed file with the same name.
246
                                FileResource same = null;
247
                                for (FileResource fres : folder.getFiles())
248
                                        if (fres.isDeleted() && fres.getName().equals(fname))
249
                                                same = fres;
250
                                // In that case add it to the list of files to rename.
251
                                if (same != null)
252
                                        toRename.put(getBackupFilename(fname), same);
253
                        } else
254
                                // If we are updating a file add it to the list of files to update.
255
                                toUpdate.add(fname);
256
                }
257

    
258
                if (!toUpdate.isEmpty()) {
259
                        StringBuffer sb = new StringBuffer();
260
                        for (String name: toUpdate)
261
                                sb.append(name).append("<br/>");
262
                        // We are going to update existing files, so show a confirmation dialog.
263
                        ConfirmationDialog confirm = new ConfirmationDialog("Are you sure " +
264
                                        "you want to update the following files?<br/><i>" + sb +
265
                                        "</i>", "Update") {
266

    
267
                                @Override
268
                                public void cancel() {
269
                                        hide();
270
                                }
271

    
272
                                @Override
273
                                public void confirm() {
274
                                        confirmRename();
275
                                }
276

    
277
                        };
278
                        confirm.center();
279
                } else
280
                        confirmRename();
281
        }
282

    
283
        /**
284
         * Confirm the renames of synonymous files already in the trash.
285
         */
286
        private void confirmRename() {
287
                if (!toRename.isEmpty()) {
288
                        StringBuffer sb = new StringBuffer();
289
                        for (FileResource file: toRename.values())
290
                                sb.append(file.getName()).append("<br/>");
291
                        ConfirmationDialog confirm = new ConfirmationDialog("Files " +
292
                                        "with the following names already exist in the trash. If" +
293
                                        " you continue,<br/>the trashed files will be renamed " +
294
                                        "automatically for you:<br/><i>" + sb + "</i>", "Continue") {
295

    
296
                                @Override
297
                                public void cancel() {
298
                                        hide();
299
                                }
300

    
301
                                @Override
302
                                public void confirm() {
303
                                        updateTrashedFiles();
304
                                }
305

    
306
                        };
307
                        confirm.center();
308
                } else
309
                        uploadFiles();
310
        }
311

    
312
        /**
313
         * Rename the conflicting trashed files with the supplied new names.
314
         */
315
        private void updateTrashedFiles() {
316
                for (final String name: toRename.keySet()) {
317
                        JSONObject json = new JSONObject();
318
                        json.put("name", new JSONString(name));
319
                        PostCommand cf = new PostCommand(toRename.get(name).getUri() + "?update=", json.toString(), 200) {
320

    
321
                                @Override
322
                                public void onComplete() {
323
                                        toRename.remove(name);
324
                                        uploadFiles();
325
                                }
326

    
327
                                @Override
328
                                public void onError(Throwable t) {
329
                                        GSS app = GSS.get();
330
                                        GWT.log("", t);
331
                                        if (t instanceof RestException) {
332
                                                int statusCode = ((RestException) t).getHttpStatusCode();
333
                                                if (statusCode == 405)
334
                                                        app.displayError("You don't have the necessary permissions");
335
                                                else if (statusCode == 404)
336
                                                        app.displayError("User in permissions does not exist");
337
                                                else if (statusCode == 409)
338
                                                        app.displayError("A file with the same name already exists");
339
                                                else if (statusCode == 413)
340
                                                        app.displayError("Your quota has been exceeded");
341
                                                else
342
                                                        app.displayError("Unable to modify file:" + ((RestException) t).getHttpStatusText());
343
                                        } else
344
                                                app.displayError("System error modifying file:" + t.getMessage());
345
                                }
346

    
347
                        };
348
                        DeferredCommand.addCommand(cf);
349
                }
350
        }
351

    
352
        /**
353
         * Checks if the renaming step for already trashed files is complete and
354
         * starts file uploads.
355
         */
356
        private void uploadFiles() {                
357
                if (!toRename.isEmpty()) return;
358
                if (canContinue){                                                
359
                        doSend(selectedFiles);
360
                }
361
        }
362

    
363
        /**
364
         * Perform the HTTP request to upload the specified file.
365
         */
366
        protected void doSend(final List<File> filesRemaining) {
367
                final GSS app = GSS.get();
368
                HttpRequest request = factory.createHttpRequest();
369
                requests.add(request);
370
                String method = "PUT";
371

    
372
                String path;
373
                final String filename = getFilename(filesRemaining.get(0).getName());
374
                path = folder.getUri();
375
                if (!path.endsWith("/"))
376
                        path = path + "/";
377
                path = path + encode(filename);
378

    
379
                String token = app.getToken();
380
                String resource = path.substring(app.getApiPath().length()-1, path.length());
381
                String date = RestCommand.getDate();
382
                String sig = RestCommand.calculateSig(method, date, resource, RestCommand.base64decode(token));
383
                request.open(method, path);
384
                request.setRequestHeader("X-GSS-Date", date);
385
                request.setRequestHeader("Authorization", app.getCurrentUserResource().getUsername() + " " + sig);
386
                request.setRequestHeader("Accept", "application/json; charset=utf-8");
387
                request.setCallback(new RequestCallback() {
388
                        @Override
389
                        public void onResponseReceived(HttpRequest req) {
390
                                int state = req.getReadyState();
391
                                if (state != 4) return;
392
                                switch(req.getStatus()) {
393
                                        case 201: // Created falls through to updated.
394
                                        case 204:
395
                                                filesRemaining.remove(0);
396
                                                if(filesRemaining.isEmpty()){                                                        
397
                                                        finish();
398
                                                        break;
399
                                                }                                                
400
                                                doSend(filesRemaining);                                
401
                                                break;
402
                                        case 403:
403
                                                SessionExpiredDialog dlg = new SessionExpiredDialog();
404
                                                dlg.center();
405
                                                break;
406
                                        case 405:
407
                                                app.displayError("You don't have permission to " +
408
                                                                "upload file " + filename);
409
                                                break;
410
                                        case 409:
411
                                                app.displayError("A folder with the name " + filename +
412
                                                                " already exists at this level");
413
                                                break;
414
                                        case 413:
415
                                                app.displayError("There is not enough free space " +
416
                                                                "available for uploading " + filename);
417
                                                break;
418
                                        default:
419
                                                app.displayError("Error uploading file " + filename +
420
                                                                        ": " + req.getStatus());
421
                                }
422
                        }
423
                });
424
                request.getUpload().setProgressHandler(new ProgressHandler() {
425
                        @Override
426
                        public void onProgress(ProgressEvent event) {
427
                                double pcnt = (double) event.getLoaded() / event.getTotal();
428
                                progressBars.get(0).setProgress((int) Math.floor(pcnt * 100));
429
                                if(pcnt*100 == 100)
430
                                        progressBars.remove(0);
431
                        }
432
                });
433
                request.send(filesRemaining.get(0).getBlob());
434
        }
435

    
436
        /**
437
         * Perform the final actions after the files are uploaded.
438
         */
439
        protected void finish() {
440
                hide();
441
                //GSS.get().showFileList(true);
442
                GSS.get().getTreeView().updateNode(GSS.get().getTreeView().getSelection());//showFileList(true);
443
                GSS.get().getStatusPanel().updateStats();
444
        }
445

    
446
        /**
447
         * Same as URL.encode, but also encode apostrophe since browsers aren't
448
         * consistent about it (FF encodes, IE does not).
449
         */
450
        protected String encode(String decodedURL) {
451
                String retv = decodedURL.replaceAll("@", "_"); // Replace bad character
452
                retv = URL.encodeComponent(retv);
453
                retv = retv.replaceAll("'", "%27");
454
                return retv;
455
        }
456

    
457
}