Statistics
| Branch: | Tag: | Revision:

root / web_client / src / gr / grnet / pithos / web / client / FileUploadGearsDialog.java @ 26cbae7a

History | View | Annotate | Download (15.1 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.foldertree.Folder;
38
import gr.grnet.pithos.web.client.rest.PostCommand;
39
import gr.grnet.pithos.web.client.rest.RestCommand;
40
import gr.grnet.pithos.web.client.rest.RestException;
41
import gr.grnet.pithos.web.client.rest.resource.FileResource;
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 {
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, gr.grnet.pithos.web.client.foldertree.File> toRename;
101

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

    
106
    protected FileUploadGearsDialog() {
107
    }
108

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

    
126
                browse = new Button("Browse...");
127

    
128
                HorizontalPanel fileUploadPanel = new HorizontalPanel();
129
                fileUploadPanel.add(browse);
130

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

    
142
                panel.add(generalTable);
143

    
144
                // Create a panel to hold the buttons.
145
                HorizontalPanel buttons = new HorizontalPanel();
146

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

    
172
                browse.addClickHandler(new ClickHandler() {
173
                        @Override
174
                        public void onClick(ClickEvent event) {
175
                                Desktop desktop = factory.createDesktop();
176
                                desktop.openFiles(new OpenFilesHandler() {
177

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

    
197
                panel.add(buttons);
198
                panel.setCellHorizontalAlignment(buttons, HasHorizontalAlignment.ALIGN_CENTER);
199
                panel.addStyleName("pithos-DialogBox");
200
                addStyleName("pithos-DialogBox");
201
                setWidget(panel);
202
        }
203

    
204
        /**
205
         * Cancels the file upload.
206
         */
207
        private void cancelUpload() {
208
                for (HttpRequest request: requests)
209
                        request.abort();
210
                hide();                
211
        }
212

    
213
        @Override
214
        public void prepareAndSubmit() {
215
                GSS app = GSS.get();
216
                if (selectedFiles.size() == 0) {
217
                        app.displayError("You must select a file!");
218
                        hide();
219
                        return;
220
                }
221
                submit.setEnabled(false);
222
                browse.setVisible(false);
223
                List<String> toUpdate = new ArrayList<String>();
224
                toRename = new HashMap<String, gr.grnet.pithos.web.client.foldertree.File>();
225
                for (File file: selectedFiles) {
226
                        String fname = getFilename(file.getName());
227
                        if (getFileForName(fname) == null) {
228
                                // We are going to create a file, so we check to see if there is a
229
                                // trashed file with the same name.
230
                                gr.grnet.pithos.web.client.foldertree.File same = null;
231
                                for (gr.grnet.pithos.web.client.foldertree.File fres : folder.getFiles())
232
                                        if (fres.isInTrash() && fres.getName().equals(fname))
233
                                                same = fres;
234
                                // In that case add it to the list of files to rename.
235
                                if (same != null)
236
                                        toRename.put(getBackupFilename(fname), same);
237
                        } else
238
                                // If we are updating a file add it to the list of files to update.
239
                                toUpdate.add(fname);
240
                }
241

    
242
                if (!toUpdate.isEmpty()) {
243
                        StringBuffer sb = new StringBuffer();
244
                        for (String name: toUpdate)
245
                                sb.append(name).append("<br/>");
246
                        // We are going to update existing files, so show a confirmation dialog.
247
                        ConfirmationDialog confirm = new ConfirmationDialog("Are you sure " +
248
                                        "you want to update the following files?<br/><i>" + sb +
249
                                        "</i>", "Update") {
250

    
251
                                @Override
252
                                public void cancel() {
253
                                        hide();
254
                                }
255

    
256
                                @Override
257
                                public void confirm() {
258
                                        confirmRename();
259
                                }
260

    
261
                        };
262
                        confirm.center();
263
                } else
264
                        confirmRename();
265
        }
266

    
267
        /**
268
         * Confirm the renames of synonymous files already in the trash.
269
         */
270
        private void confirmRename() {
271
                if (!toRename.isEmpty()) {
272
                        StringBuffer sb = new StringBuffer();
273
                        for (gr.grnet.pithos.web.client.foldertree.File file: toRename.values())
274
                                sb.append(file.getName()).append("<br/>");
275
                        ConfirmationDialog confirm = new ConfirmationDialog("Files " +
276
                                        "with the following names already exist in the trash. If" +
277
                                        " you continue,<br/>the trashed files will be renamed " +
278
                                        "automatically for you:<br/><i>" + sb + "</i>", "Continue") {
279

    
280
                                @Override
281
                                public void cancel() {
282
                                        hide();
283
                                }
284

    
285
                                @Override
286
                                public void confirm() {
287
                                        updateTrashedFiles();
288
                                }
289

    
290
                        };
291
                        confirm.center();
292
                } else
293
                        uploadFiles();
294
        }
295

    
296
        /**
297
         * Rename the conflicting trashed files with the supplied new names.
298
         */
299
        private void updateTrashedFiles() {
300
                for (final String name: toRename.keySet()) {
301
                        JSONObject json = new JSONObject();
302
                        json.put("name", new JSONString(name));
303
                        PostCommand cf = new PostCommand(toRename.get(name).getUri() + "?update=", json.toString(), 200) {
304

    
305
                                @Override
306
                                public void onComplete() {
307
                                        toRename.remove(name);
308
                                        uploadFiles();
309
                                }
310

    
311
                                @Override
312
                                public void onError(Throwable t) {
313
                                        GSS app = GSS.get();
314
                                        GWT.log("", t);
315
                                        if (t instanceof RestException) {
316
                                                int statusCode = ((RestException) t).getHttpStatusCode();
317
                                                if (statusCode == 405)
318
                                                        app.displayError("You don't have the necessary permissions");
319
                                                else if (statusCode == 404)
320
                                                        app.displayError("User in permissions does not exist");
321
                                                else if (statusCode == 409)
322
                                                        app.displayError("A file with the same name already exists");
323
                                                else if (statusCode == 413)
324
                                                        app.displayError("Your quota has been exceeded");
325
                                                else
326
                                                        app.displayError("Unable to modify file:" + ((RestException) t).getHttpStatusText());
327
                                        } else
328
                                                app.displayError("System error modifying file:" + t.getMessage());
329
                                }
330

    
331
                        };
332
                        DeferredCommand.addCommand(cf);
333
                }
334
        }
335

    
336
        /**
337
         * Checks if the renaming step for already trashed files is complete and
338
         * starts file uploads.
339
         */
340
        private void uploadFiles() {                
341
                if (!toRename.isEmpty()) return;
342
                if (canContinue){                                                
343
                        doSend(selectedFiles);
344
                }
345
        }
346

    
347
        /**
348
         * Perform the HTTP request to upload the specified file.
349
         */
350
        protected void doSend(final List<File> filesRemaining) {
351
                final GSS app = GSS.get();
352
                HttpRequest request = factory.createHttpRequest();
353
                requests.add(request);
354
                String method = "PUT";
355

    
356
                String path;
357
                final String filename = getFilename(filesRemaining.get(0).getName());
358
                path = folder.getUri();
359
                if (!path.endsWith("/"))
360
                        path = path + "/";
361
                path = path + encode(filename);
362

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

    
420
        /**
421
         * Perform the final actions after the files are uploaded.
422
         */
423
        protected void finish() {
424
                hide();
425
                //GSS.get().showFileList(true);
426
                GSS.get().getTreeView().updateNode(GSS.get().getTreeView().getSelection());//showFileList(true);
427
                GSS.get().getStatusPanel().updateStats();
428
        }
429

    
430
        /**
431
         * Same as URL.encode, but also encode apostrophe since browsers aren't
432
         * consistent about it (FF encodes, IE does not).
433
         */
434
        protected String encode(String decodedURL) {
435
                String retv = decodedURL.replaceAll("@", "_"); // Replace bad character
436
                retv = URL.encodeComponent(retv);
437
                retv = retv.replaceAll("'", "%27");
438
                return retv;
439
        }
440

    
441
    protected String getBackupFilename(String filename) {
442
        List<gr.grnet.pithos.web.client.foldertree.File> filesInSameFolder = new ArrayList<gr.grnet.pithos.web.client.foldertree.File>();
443
        for (gr.grnet.pithos.web.client.foldertree.File deleted : folder.getFiles())
444
            if (deleted.isInTrash())
445
                filesInSameFolder.add(deleted);
446
        int i = 1;
447
        for (gr.grnet.pithos.web.client.foldertree.File same : filesInSameFolder)
448
            if (same.getName().startsWith(filename)) {
449
                String toCheck = same.getName().substring(filename.length(), same.getName().length());
450
                if (toCheck.startsWith(" ")) {
451
                    int test = -1;
452
                    try {
453
                        test = Integer.valueOf(toCheck.replace(" ", ""));
454
                    } catch (NumberFormatException e) {
455
                        // Do nothing since string is not a number.
456
                    }
457
                    if (test >= i)
458
                        i = test + 1;
459
                }
460
            }
461

    
462
        return filename + " " + i;
463
    }
464
}