Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (15 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

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

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

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

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

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

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

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

    
93
        private Button browse;
94

    
95
        private Button submit;
96

    
97
        private FlexTable generalTable;
98

    
99
        private Map<String, gr.grnet.pithos.web.client.foldertree.File> toRename;
100

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

    
105
    protected FileUploadGearsDialog() {
106
    }
107

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

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

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

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

    
141
                panel.add(generalTable);
142

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
460
        return filename + " " + i;
461
    }
462
}