2 * Copyright 2009 Electronic Business Systems Ltd.
4 * This file is part of GSS.
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.
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.
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/>.
19 package gr.ebs.gss.client;
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 import gr.ebs.gss.client.rest.resource.RestResourceWrapper;
28 import java.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.HashMap;
31 import java.util.List;
34 import com.google.gwt.core.client.GWT;
35 import com.google.gwt.event.dom.client.ClickEvent;
36 import com.google.gwt.event.dom.client.ClickHandler;
37 import com.google.gwt.gears.client.Factory;
38 import com.google.gwt.gears.client.desktop.Desktop;
39 import com.google.gwt.gears.client.desktop.File;
40 import com.google.gwt.gears.client.desktop.OpenFilesHandler;
41 import com.google.gwt.gears.client.httprequest.HttpRequest;
42 import com.google.gwt.gears.client.httprequest.ProgressEvent;
43 import com.google.gwt.gears.client.httprequest.ProgressHandler;
44 import com.google.gwt.gears.client.httprequest.RequestCallback;
45 import com.google.gwt.http.client.URL;
46 import com.google.gwt.json.client.JSONObject;
47 import com.google.gwt.json.client.JSONString;
48 import com.google.gwt.user.client.DeferredCommand;
49 import com.google.gwt.user.client.ui.Button;
50 import com.google.gwt.user.client.ui.FlexTable;
51 import com.google.gwt.user.client.ui.HTML;
52 import com.google.gwt.user.client.ui.HasHorizontalAlignment;
53 import com.google.gwt.user.client.ui.HorizontalPanel;
54 import com.google.gwt.user.client.ui.VerticalPanel;
57 * The 'File upload' dialog box implementation with Google Gears support.
59 public class FileUploadGearsDialog extends FileUploadDialog implements Updateable {
61 protected final Factory factory = Factory.getInstance();
64 * The array of files to upload.
66 private File[] fileObjects;
69 * A list of files to upload, created from files array. Used to signal
70 * finished state when empty.
72 protected List<File> selectedFiles = new ArrayList<File>();
75 * The list of progress bars for individual files.
77 protected List<ProgressBar> progressBars = new ArrayList<ProgressBar>();
79 private Button browse;
81 private Button submit;
83 private FlexTable generalTable;
85 private Map<String, FileResource> toRename;
87 protected List<HttpRequest> requests = new ArrayList<HttpRequest>();
89 private boolean canContinue = true;
92 * The widget's constructor.
94 public FileUploadGearsDialog() {
95 // Set the dialog's caption.
96 setText("File upload");
97 setAnimationEnabled(true);
98 // Create a panel to hold all of the dialog widgets.
99 VerticalPanel panel = new VerticalPanel();
100 final HTML info = new HTML("You may select one or more files to upload.");
101 info.addStyleName("gss-uploadNote");
103 // Add an informative label with the folder name.
104 Object selection = GSS.get().getTreeView().getSelection();
105 folder = ((RestResourceWrapper) selection).getResource();
107 browse = new Button("Browse...");
109 HorizontalPanel fileUploadPanel = new HorizontalPanel();
110 fileUploadPanel.add(browse);
112 generalTable = new FlexTable();
113 generalTable.setText(0, 0, "Folder");
114 generalTable.setText(1, 0, "File");
115 generalTable.setText(0, 1, folder.getName());
116 generalTable.setWidget(1, 1, fileUploadPanel);
117 generalTable.getCellFormatter().setStyleName(0, 0, "props-labels");
118 generalTable.getCellFormatter().setStyleName(1, 0, "props-labels");
119 generalTable.getCellFormatter().setStyleName(0, 1, "props-values");
120 generalTable.getCellFormatter().setStyleName(1, 1, "props-values");
121 generalTable.setCellSpacing(4);
123 panel.add(generalTable);
125 // Create a panel to hold the buttons.
126 HorizontalPanel buttons = new HorizontalPanel();
128 submit = new Button("Upload");
129 submit.addClickHandler(new ClickHandler() {
131 public void onClick(ClickEvent event) {
135 submit.setEnabled(false);
137 buttons.setCellHorizontalAlignment(submit, HasHorizontalAlignment.ALIGN_CENTER);
138 // Create the 'Cancel' button, along with a listener that hides the
139 // dialog when the button is clicked.
140 Button cancel = new Button("Cancel", new ClickHandler() {
142 public void onClick(ClickEvent event) {
145 GSS.get().showFileList(true);
149 buttons.setCellHorizontalAlignment(cancel, HasHorizontalAlignment.ALIGN_CENTER);
150 buttons.setSpacing(8);
151 buttons.addStyleName("gss-DialogBox");
153 browse.addClickHandler(new ClickHandler() {
155 public void onClick(ClickEvent event) {
156 Desktop desktop = factory.createDesktop();
157 desktop.openFiles(new OpenFilesHandler() {
160 public void onOpenFiles(OpenFilesEvent ofevent) {
161 fileObjects = ofevent.getFiles();
162 selectedFiles.addAll(Arrays.asList(fileObjects));
163 for (int i = 0; i< selectedFiles.size(); i++) {
164 generalTable.setText(i+1, 0, "File");
165 generalTable.setText(i+1, 1, selectedFiles.get(i).getName());
166 ProgressBar progress = new ProgressBar(20, 0);
167 generalTable.setWidget(i+1, 2, progress);
168 progressBars.add(progress);
169 generalTable.getCellFormatter().setStyleName(i+1, 0, "props-labels");
170 generalTable.getCellFormatter().setStyleName(i+1, 1, "props-values");
172 submit.setEnabled(true);
179 panel.setCellHorizontalAlignment(buttons, HasHorizontalAlignment.ALIGN_CENTER);
180 panel.addStyleName("gss-DialogBox");
181 addStyleName("gss-DialogBox");
186 * Cancels the file upload.
188 private void cancelUpload() {
189 for (HttpRequest request: requests)
195 * Check whether the specified file name exists in the selected folder.
197 private boolean canContinue(File file) {
198 String fileName = getFilename(file.getName());
199 if (getFileForName(fileName) == null)
200 // For file creation, check to see if the file already exists.
201 for (FileResource fileRes : files)
202 if (!fileRes.isDeleted() && fileRes.getName().equals(fileName))
208 public void prepareAndSubmit() {
210 if (selectedFiles.size() == 0) {
211 app.displayError("You must select a file!");
215 for (File file: selectedFiles)
216 if (!canContinue(file)) {
217 app.displayError("The file name " + file.getName() +
218 " already exists in this folder");
222 submit.setEnabled(false);
223 browse.setVisible(false);
224 List<String> toUpdate = new ArrayList<String>();
225 toRename = new HashMap<String, FileResource>();
226 for (File file: selectedFiles) {
227 String fname = getFilename(file.getName());
228 if (getFileForName(fname) == null) {
229 // We are going to create a file, so we check to see if there is a
230 // trashed file with the same name.
231 FileResource same = null;
232 for (FileResource fres : folder.getFiles())
233 if (fres.isDeleted() && fres.getName().equals(fname))
235 // In that case add it to the list of files to rename.
237 toRename.put(getBackupFilename(fname), same);
239 // If we are updating a file add it to the list of files to update.
243 if (!toUpdate.isEmpty()) {
244 StringBuffer sb = new StringBuffer();
245 for (String name: toUpdate)
246 sb.append(name).append("<br/>");
247 // We are going to update existing files, so show a confirmation dialog.
248 ConfirmationDialog confirm = new ConfirmationDialog("Are you sure " +
249 "you want to update the following files?<br/><i>" + sb +
253 public void cancel() {
258 public void confirm() {
269 * Confirm the renames of synonymous files already in the trash.
271 private void confirmRename() {
272 if (!toRename.isEmpty()) {
273 StringBuffer sb = new StringBuffer();
274 for (FileResource file: toRename.values())
275 sb.append(file.getName()).append("<br/>");
276 ConfirmationDialog confirm = new ConfirmationDialog("Files " +
277 "with the following names already exist in the trash. If" +
278 " you continue,<br/>the trashed files will be renamed " +
279 "automatically for you:<br/><i>" + sb + "</i>", "Continue") {
282 public void cancel() {
287 public void confirm() {
288 updateTrashedFiles();
298 * Rename the conflicting trashed files with the supplied new names.
300 private void updateTrashedFiles() {
301 for (final String name: toRename.keySet()) {
302 JSONObject json = new JSONObject();
303 json.put("name", new JSONString(name));
304 PostCommand cf = new PostCommand(toRename.get(name).getUri() + "?update=", json.toString(), 200) {
307 public void onComplete() {
308 toRename.remove(name);
313 public void onError(Throwable t) {
316 if (t instanceof RestException) {
317 int statusCode = ((RestException) t).getHttpStatusCode();
318 if (statusCode == 405)
319 app.displayError("You don't have the necessary permissions");
320 else if (statusCode == 404)
321 app.displayError("User in permissions does not exist");
322 else if (statusCode == 409)
323 app.displayError("A file with the same name already exists");
324 else if (statusCode == 413)
325 app.displayError("Your quota has been exceeded");
327 app.displayError("Unable to modify file:" + ((RestException) t).getHttpStatusText());
329 app.displayError("System error modifying file:" + t.getMessage());
333 DeferredCommand.addCommand(cf);
338 * Checks if the renaming step for already trashed files is complete and
339 * starts file uploads.
341 private void uploadFiles() {
342 if (!toRename.isEmpty()) return;
344 doSend(selectedFiles);
349 * Perform the HTTP request to upload the specified file.
351 protected void doSend(final List<File> filesRemaining) {
352 final GSS app = GSS.get();
353 HttpRequest request = factory.createHttpRequest();
354 requests.add(request);
355 String method = "PUT";
358 final String filename = getFilename(filesRemaining.get(0).getName());
359 path = folder.getUri();
360 if (!path.endsWith("/"))
362 path = path + encode(filename);
364 String token = app.getToken();
365 String resource = path.substring(app.getApiPath().length()-1, path.length());
366 String date = RestCommand.getDate();
367 String sig = RestCommand.calculateSig(method, date, resource, RestCommand.base64decode(token));
368 request.open(method, path);
369 request.setRequestHeader("X-GSS-Date", date);
370 request.setRequestHeader("Authorization", app.getCurrentUserResource().getUsername() + " " + sig);
371 request.setRequestHeader("Accept", "application/json; charset=utf-8");
372 request.setCallback(new RequestCallback() {
374 public void onResponseReceived(HttpRequest req) {
375 int state = req.getReadyState();
376 if (state != 4) return;
377 switch(req.getStatus()) {
378 case 201: // Created falls through to updated.
380 filesRemaining.remove(0);
381 if(filesRemaining.isEmpty()){
385 doSend(filesRemaining);
388 SessionExpiredDialog dlg = new SessionExpiredDialog();
392 app.displayError("You don't have permission to " +
393 "upload file " + filename);
396 app.displayError("A folder with the name " + filename +
397 " already exists at this level");
400 app.displayError("There is not enough free space " +
401 "available for uploading " + filename);
404 app.displayError("Error uploading file " + filename +
405 ": " + req.getStatus());
409 request.getUpload().setProgressHandler(new ProgressHandler() {
411 public void onProgress(ProgressEvent event) {
412 double pcnt = (double) event.getLoaded() / event.getTotal();
413 progressBars.get(0).setProgress((int) Math.floor(pcnt * 100));
415 progressBars.remove(0);
418 request.send(filesRemaining.get(0).getBlob());
422 * Perform the final actions after the files are uploaded.
424 protected void finish() {
426 //GSS.get().showFileList(true);
427 GSS.get().getTreeView().updateNode(folder);//showFileList(true);
428 GSS.get().getStatusPanel().updateStats();
432 * Same as URL.encode, but also encode apostrophe since browsers aren't
433 * consistent about it (FF encodes, IE does not).
435 protected String encode(String decodedURL) {
436 String retv = decodedURL.replaceAll("@", "_"); // Replace bad character
437 retv = URL.encodeComponent(retv);
438 retv = retv.replaceAll("'", "%27");