Statistics
| Branch: | Tag: | Revision:

root / src / gr / ebs / gss / client / FileUploadGearsDialog.java @ a73b1e75

History | View | Annotate | Download (13.7 kB)

1
/*
2
 * Copyright 2009 Electronic Business Systems Ltd.
3
 *
4
 * This file is part of GSS.
5
 *
6
 * GSS is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * GSS is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with GSS.  If not, see <http://www.gnu.org/licenses/>.
18
 */
19
package gr.ebs.gss.client;
20

    
21
import gr.ebs.gss.client.rest.PostCommand;
22
import gr.ebs.gss.client.rest.RestCommand;
23
import gr.ebs.gss.client.rest.RestException;
24
import gr.ebs.gss.client.rest.resource.FileResource;
25
import gr.ebs.gss.client.rest.resource.FolderResource;
26

    
27
import java.util.ArrayList;
28
import java.util.Arrays;
29
import java.util.HashMap;
30
import java.util.List;
31
import java.util.Map;
32

    
33
import com.google.gwt.core.client.GWT;
34
import com.google.gwt.gears.client.Factory;
35
import com.google.gwt.gears.client.desktop.Desktop;
36
import com.google.gwt.gears.client.desktop.File;
37
import com.google.gwt.gears.client.desktop.OpenFilesHandler;
38
import com.google.gwt.gears.client.httprequest.HttpRequest;
39
import com.google.gwt.gears.client.httprequest.ProgressEvent;
40
import com.google.gwt.gears.client.httprequest.ProgressHandler;
41
import com.google.gwt.gears.client.httprequest.RequestCallback;
42
import com.google.gwt.http.client.URL;
43
import com.google.gwt.json.client.JSONObject;
44
import com.google.gwt.json.client.JSONString;
45
import com.google.gwt.user.client.Command;
46
import com.google.gwt.user.client.DeferredCommand;
47
import com.google.gwt.user.client.ui.Button;
48
import com.google.gwt.user.client.ui.ClickListener;
49
import com.google.gwt.user.client.ui.FlexTable;
50
import com.google.gwt.user.client.ui.HTML;
51
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
52
import com.google.gwt.user.client.ui.HorizontalPanel;
53
import com.google.gwt.user.client.ui.VerticalPanel;
54
import com.google.gwt.user.client.ui.Widget;
55

    
56
/**
57
 * The 'File upload' dialog box implementation with Google Gears support.
58
 */
59
public class FileUploadGearsDialog extends FileUploadDialog implements Updateable {
60

    
61
        protected final Factory factory = Factory.getInstance();
62

    
63
        /**
64
         * The array of files to upload.
65
         */
66
        private File[] fileObjects;
67

    
68
        /**
69
         * A list of files to upload, created from files array. Used to signal
70
         * finished state when empty.
71
         */
72
        protected List<File> selectedFiles = new ArrayList<File>();
73

    
74
        /**
75
         * The list of progress bars for individual files.
76
         */
77
        protected List<ProgressBar> progressBars = new ArrayList<ProgressBar>();
78

    
79
        private Button browse;
80

    
81
        private Button submit;
82

    
83
        private FlexTable generalTable;
84

    
85
        private Map<String, FileResource> toRename;
86

    
87
        protected List<HttpRequest> requests = new ArrayList<HttpRequest>();
88

    
89
        /**
90
         * The widget's constructor.
91
         */
92
        public FileUploadGearsDialog() {
93
                // Set the dialog's caption.
94
                setText("File upload");
95
                setAnimationEnabled(true);
96
                // Create a panel to hold all of the dialog widgets.
97
                VerticalPanel panel = new VerticalPanel();
98
                final HTML info = new HTML("You may select one or more files to upload.");
99
                info.addStyleName("gss-uploadNote");
100
                panel.add(info);
101
                // Add an informative label with the folder name.
102
                Object selection = GSS.get().getFolders().getCurrent().getUserObject();
103
                folder = (FolderResource) selection;
104

    
105
                browse = new Button("Browse...");
106

    
107
                HorizontalPanel fileUploadPanel = new HorizontalPanel();
108
                fileUploadPanel.add(browse);
109

    
110
                generalTable = new FlexTable();
111
                generalTable.setText(0, 0, "Folder");
112
                generalTable.setText(1, 0, "File");
113
                generalTable.setText(0, 1, folder.getName());
114
                generalTable.setWidget(1, 1, fileUploadPanel);
115
                generalTable.getCellFormatter().setStyleName(0, 0, "props-labels");
116
                generalTable.getCellFormatter().setStyleName(1, 0, "props-labels");
117
                generalTable.getCellFormatter().setStyleName(0, 1, "props-values");
118
                generalTable.getCellFormatter().setStyleName(1, 1, "props-values");
119
                generalTable.setCellSpacing(4);
120

    
121
                panel.add(generalTable);
122

    
123
                // Create a panel to hold the buttons.
124
                HorizontalPanel buttons = new HorizontalPanel();
125

    
126
                submit = new Button("Upload");
127
                submit.addClickListener(new ClickListener() {
128

    
129
                        public void onClick(Widget sender) {
130
                                prepareAndSubmit();
131
                        }
132
                });
133
                submit.setEnabled(false);
134
                buttons.add(submit);
135
                buttons.setCellHorizontalAlignment(submit, HasHorizontalAlignment.ALIGN_CENTER);
136
                // Create the 'Cancel' button, along with a listener that hides the
137
                // dialog when the button is clicked.
138
                Button cancel = new Button("Cancel", new ClickListener() {
139

    
140
                        public void onClick(Widget sender) {
141
                                cancelUpload();
142
                        }
143
                });
144
                buttons.add(cancel);
145
                buttons.setCellHorizontalAlignment(cancel, HasHorizontalAlignment.ALIGN_CENTER);
146
                buttons.setSpacing(8);
147
                buttons.addStyleName("gss-DialogBox");
148

    
149
                browse.addClickListener(new ClickListener() {
150
                        public void onClick(Widget sender) {
151
                                Desktop desktop = factory.createDesktop();
152
                                desktop.openFiles(new OpenFilesHandler() {
153

    
154
                                        public void onOpenFiles(OpenFilesEvent event) {
155
                                                fileObjects = event.getFiles();
156
                                                selectedFiles.addAll(Arrays.asList(fileObjects));
157
                                                for (int i = 0; i< selectedFiles.size(); i++) {
158
                                                        generalTable.setText(i+1, 0, "File");
159
                                                        generalTable.setText(i+1, 1, selectedFiles.get(i).getName());
160
                                                        ProgressBar progress = new ProgressBar(20, 0);
161
                                                        generalTable.setWidget(i+1, 2, progress);
162
                                                        progressBars.add(progress);
163
                                                        generalTable.getCellFormatter().setStyleName(i+1, 0, "props-labels");
164
                                                        generalTable.getCellFormatter().setStyleName(i+1, 1, "props-values");
165
                                                }
166
                                                submit.setEnabled(true);
167
                                        }
168
                                });
169
                        }
170
                });
171

    
172
                panel.add(buttons);
173
                panel.setCellHorizontalAlignment(buttons, HasHorizontalAlignment.ALIGN_CENTER);
174
                panel.addStyleName("gss-DialogBox");
175
                addStyleName("gss-DialogBox");
176
                setWidget(panel);
177
        }
178

    
179
        /**
180
         * Cancels the file upload.
181
         */
182
        private void cancelUpload() {
183
                for (HttpRequest request: requests)
184
                        request.abort();
185
                hide();
186
        }
187

    
188
        /**
189
         * Check whether the specified file name exists in the selected folder.
190
         */
191
        private boolean canContinue(File file) {
192
                String fileName = getFilename(file.getName());
193
                if (getFileForName(fileName) == null)
194
                        // For file creation, check to see if the file already exists.
195
                        for (FileResource fileRes : files)
196
                                if (!fileRes.isDeleted() && fileRes.getName().equals(fileName))
197
                                        return false;
198
                return true;
199
        }
200

    
201
        @Override
202
        public void prepareAndSubmit() {
203
                GSS app = GSS.get();
204
                if (selectedFiles.size() == 0) {
205
                        app.displayError("You must select a file!");
206
                        hide();
207
                        return;
208
                }
209
                for (File file: selectedFiles)
210
                        if (!canContinue(file)) {
211
                                app.displayError("The file name " + file.getName() +
212
                                                        " already exists in this folder");
213
                                hide();
214
                                return;
215
                        }
216
                submit.setEnabled(false);
217
                browse.setVisible(false);
218
                List<String> toUpdate = new ArrayList<String>();
219
                toRename = new HashMap<String, FileResource>();
220
                for (File file: selectedFiles) {
221
                        String fname = getFilename(file.getName());
222
                        if (getFileForName(fname) == null) {
223
                                // We are going to create a file, so we check to see if there is a
224
                                // trashed file with the same name.
225
                                FileResource same = null;
226
                                for (FileResource fres : folder.getFiles())
227
                                        if (fres.isDeleted() && fres.getName().equals(fname))
228
                                                same = fres;
229
                                // In that case add it to the list of files to rename.
230
                                if (same != null)
231
                                        toRename.put(getBackupFilename(fname), same);
232
                        } else
233
                                // If we are updating a file add it to the list of files to update.
234
                                toUpdate.add(fname);
235
                }
236

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

    
246
                                @Override
247
                                public void cancel() {
248
                                        hide();
249
                                }
250

    
251
                                @Override
252
                                public void confirm() {
253
                                        confirmRename();
254
                                }
255

    
256
                        };
257
                        confirm.center();
258
                } else
259
                        confirmRename();
260
        }
261

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

    
275
                                @Override
276
                                public void cancel() {
277
                                        hide();
278
                                }
279

    
280
                                @Override
281
                                public void confirm() {
282
                                        updateTrashedFiles();
283
                                }
284

    
285
                        };
286
                        confirm.center();
287
                } else
288
                        uploadFiles();
289
        }
290

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

    
300
                                @Override
301
                                public void onComplete() {
302
                                        toRename.remove(name);
303
                                        uploadFiles();
304
                                }
305

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

    
326
                        };
327
                        DeferredCommand.addCommand(cf);
328
                }
329
        }
330

    
331
        /**
332
         * Checks if the renaming step for already trashed files is complete and
333
         * starts file uploads.
334
         */
335
        private void uploadFiles() {
336
                if (!toRename.isEmpty()) return;
337
                for (int i = 0; i< fileObjects.length; i++) {
338
                        final int index = i;
339
                        DeferredCommand.addCommand(new Command() {
340
                                public void execute() {
341
                                        doSend(fileObjects[index], index);
342
                                }
343
                        });
344
                }
345
        }
346

    
347
        /**
348
         * Perform the HTTP request to upload the specified file.
349
         */
350
        protected void doSend(final File file, final int index) {
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(file.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
                        public void onResponseReceived(HttpRequest req) {
373
                                int state = req.getReadyState();
374
                                if (state != 4) return;
375
                                switch(req.getStatus()) {
376
                                        case 201: // Created falls through to updated.
377
                                        case 204:
378
                                                selectedFiles.remove(file);
379
                                                finish();
380
                                                break;
381
                                        case 403:
382
                                                SessionExpiredDialog dlg = new SessionExpiredDialog();
383
                                                dlg.center();
384
                                                break;
385
                                        case 405:
386
                                                app.displayError("You don't have permission to " +
387
                                                                "upload file " + filename);
388
                                                break;
389
                                        case 409:
390
                                                app.displayError("A folder with the name " + filename +
391
                                                                " already exists at this level");
392
                                                break;
393
                                        case 413:
394
                                                app.displayError("There is not enough free space " +
395
                                                                "available for uploading " + filename);
396
                                                break;
397
                                        default:
398
                                                app.displayError("Error uploading file " + filename +
399
                                                                        ": " + req.getStatus());
400
                                }
401
                        }
402
                });
403
                request.getUpload().setProgressHandler(new ProgressHandler() {
404
                        public void onProgress(ProgressEvent event) {
405
                                double pcnt = (double) event.getLoaded() / event.getTotal();
406
                                progressBars.get(index).setProgress((int) Math.floor(pcnt * 100));
407
                        }
408
                });
409
                request.send(file.getBlob());
410
        }
411

    
412
        /**
413
         * Perform the final actions after the files are uploaded.
414
         */
415
        protected void finish() {
416
                if (!selectedFiles.isEmpty()) return;
417
                hide();
418
                GSS.get().showFileList(true);
419
                GSS.get().getStatusPanel().updateStats();
420
        }
421

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

    
433
}