2 * Copyright 2007, 2008, 2009 Electronic Business Systems Ltd.
\r
4 * This file is part of GSS.
\r
6 * GSS is free software: you can redistribute it and/or modify
\r
7 * it under the terms of the GNU General Public License as published by
\r
8 * the Free Software Foundation, either version 3 of the License, or
\r
9 * (at your option) any later version.
\r
11 * GSS is distributed in the hope that it will be useful,
\r
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
\r
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
\r
14 * GNU General Public License for more details.
\r
16 * You should have received a copy of the GNU General Public License
\r
17 * along with GSS. If not, see <http://www.gnu.org/licenses/>.
\r
19 package gr.ebs.gss.client;
\r
21 import gr.ebs.gss.client.rest.GetCommand;
\r
22 import gr.ebs.gss.client.rest.PostCommand;
\r
23 import gr.ebs.gss.client.rest.RestCommand;
\r
24 import gr.ebs.gss.client.rest.RestException;
\r
25 import gr.ebs.gss.client.rest.resource.FileResource;
\r
26 import gr.ebs.gss.client.rest.resource.FolderResource;
\r
27 import gr.ebs.gss.client.rest.resource.UploadStatusResource;
\r
29 import java.util.ArrayList;
\r
30 import java.util.List;
\r
32 import com.google.gwt.core.client.GWT;
\r
33 import com.google.gwt.http.client.URL;
\r
34 import com.google.gwt.json.client.JSONObject;
\r
35 import com.google.gwt.json.client.JSONString;
\r
36 import com.google.gwt.user.client.DeferredCommand;
\r
37 import com.google.gwt.user.client.Timer;
\r
38 import com.google.gwt.user.client.ui.Button;
\r
39 import com.google.gwt.user.client.ui.ClickListener;
\r
40 import com.google.gwt.user.client.ui.DialogBox;
\r
41 import com.google.gwt.user.client.ui.FileUpload;
\r
42 import com.google.gwt.user.client.ui.FormHandler;
\r
43 import com.google.gwt.user.client.ui.FormPanel;
\r
44 import com.google.gwt.user.client.ui.FormSubmitCompleteEvent;
\r
45 import com.google.gwt.user.client.ui.FormSubmitEvent;
\r
46 import com.google.gwt.user.client.ui.Grid;
\r
47 import com.google.gwt.user.client.ui.HTML;
\r
48 import com.google.gwt.user.client.ui.HasHorizontalAlignment;
\r
49 import com.google.gwt.user.client.ui.Hidden;
\r
50 import com.google.gwt.user.client.ui.HorizontalPanel;
\r
51 import com.google.gwt.user.client.ui.KeyboardListener;
\r
52 import com.google.gwt.user.client.ui.Label;
\r
53 import com.google.gwt.user.client.ui.VerticalPanel;
\r
54 import com.google.gwt.user.client.ui.Widget;
\r
57 * The 'File upload' dialog box implementation.
\r
59 public class FileUploadDialog extends DialogBox implements Updateable {
\r
61 protected int prgBarInterval = 1500;
\r
63 private ProgressBar progressBar;
\r
65 protected RepeatingTimer repeater = new RepeatingTimer(this, prgBarInterval);
\r
67 public static final boolean DONE = true;
\r
70 * The Form element that performs the file upload.
\r
72 private final FormPanel form = new FormPanel();
\r
74 private final FileUpload upload = new FileUpload();
\r
76 protected final Label filenameLabel = new Label("");
\r
78 protected List<FileResource> files;
\r
80 protected boolean cancelEvent = false;
\r
82 protected String fileNameToUse;
\r
84 protected FolderResource folder;
\r
87 * The widget's constructor.
\r
89 public FileUploadDialog() {
\r
90 // Set the dialog's caption.
\r
91 setText("File upload");
\r
92 setAnimationEnabled(true);
\r
93 // Since we're going to add a FileUpload widget, we'll need to set the
\r
94 // form to use the POST method, and multipart MIME encoding.
\r
95 form.setEncoding(FormPanel.ENCODING_MULTIPART);
\r
96 form.setMethod(FormPanel.METHOD_POST);
\r
98 // Create a panel to hold all of the form widgets.
\r
99 VerticalPanel panel = new VerticalPanel();
\r
100 form.setWidget(panel);
\r
101 final HTML info = new HTML("You may select a file to upload. Install" +
\r
102 " <a href='http://gears.google.com/' target='_blank'>Google " +
\r
103 "Gears</a><br> for uploading multiple files simultaneously.");
\r
104 info.addStyleName("gss-uploadNote");
\r
106 final Hidden date = new Hidden("Date", "");
\r
108 final Hidden auth = new Hidden("Authorization", "");
\r
110 // Add an informative label with the folder name.
\r
111 Object selection = GSS.get().getFolders().getCurrent().getUserObject();
\r
112 folder = (FolderResource) selection;
\r
113 upload.setName("file");
\r
114 filenameLabel.setText("");
\r
115 filenameLabel.setVisible(false);
\r
116 filenameLabel.setStyleName("props-labels");
\r
117 HorizontalPanel fileUloadPanel = new HorizontalPanel();
\r
118 fileUloadPanel.add(filenameLabel);
\r
119 fileUloadPanel.add(upload);
\r
120 Grid generalTable = new Grid(2, 2);
\r
121 generalTable.setText(0, 0, "Folder");
\r
122 generalTable.setText(1, 0, "File");
\r
123 generalTable.setText(0, 1, folder.getName());
\r
124 generalTable.setWidget(1, 1, fileUloadPanel);
\r
125 generalTable.getCellFormatter().setStyleName(0, 0, "props-labels");
\r
126 generalTable.getCellFormatter().setStyleName(1, 0, "props-labels");
\r
127 generalTable.getCellFormatter().setStyleName(0, 1, "props-values");
\r
128 generalTable.getCellFormatter().setStyleName(1, 1, "props-values");
\r
129 generalTable.setCellSpacing(4);
\r
131 panel.add(generalTable);
\r
133 // Create a panel to hold the buttons.
\r
134 HorizontalPanel buttons = new HorizontalPanel();
\r
136 // Create the 'upload' button, along with a listener that submits the
\r
138 final Button submit = new Button("Upload", new ClickListener() {
\r
139 public void onClick(Widget sender) {
\r
140 prepareAndSubmit();
\r
143 buttons.add(submit);
\r
144 buttons.setCellHorizontalAlignment(submit, HasHorizontalAlignment.ALIGN_CENTER);
\r
145 // Create the 'Cancel' button, along with a listener that hides the
\r
146 // dialog when the button is clicked.
\r
147 final Button cancel = new Button("Cancel", new ClickListener() {
\r
149 public void onClick(Widget sender) {
\r
154 buttons.add(cancel);
\r
155 buttons.setCellHorizontalAlignment(cancel, HasHorizontalAlignment.ALIGN_CENTER);
\r
156 buttons.setSpacing(8);
\r
157 buttons.addStyleName("gss-DialogBox");
\r
159 // Add an event handler to the form.
\r
160 form.addFormHandler(new FormHandler() {
\r
162 public void onSubmit(final FormSubmitEvent event) {
\r
163 GSS app = GSS.get();
\r
164 // This event is fired just before the form is submitted. We can
\r
165 // take this opportunity to perform validation.
\r
166 if (upload.getFilename().length() == 0) {
\r
167 app.displayError("You must select a file!");
\r
168 event.setCancelled(true);
\r
173 GWT.log("Cancel:" + cancelEvent, null);
\r
175 cancelEvent = false;
\r
176 app.displayError("The specified file name already exists in this folder");
\r
177 event.setCancelled(true);
\r
181 fileNameToUse = getFilename(upload.getFilename());
\r
183 FileResource selectedFile = getFileForName(fileNameToUse);
\r
184 if (selectedFile == null ) {
\r
185 //we are going to create a file
\r
186 apath = folder.getUri();
\r
187 if (!apath.endsWith("/"))
\r
188 apath = apath + "/";
\r
189 apath = apath + encodeComponent(fileNameToUse);
\r
191 apath = selectedFile.getUri();
\r
192 form.setAction(apath);
\r
193 String dateString = RestCommand.getDate();
\r
194 String resource = apath.substring(app.getApiPath().length() - 1, apath.length());
\r
195 String sig = RestCommand.calculateSig("POST", dateString, resource, RestCommand.base64decode(app.getToken()));
\r
196 date.setValue(dateString);
\r
197 auth.setValue(app.getCurrentUserResource().getUsername() + " " + sig);
\r
198 GWT.log("FolderPATH:" + folder.getUri(), null);
\r
199 submit.setEnabled(false);
\r
200 upload.setVisible(false);
\r
201 filenameLabel.setText(fileNameToUse);
\r
202 filenameLabel.setVisible(true);
\r
204 progressBar.setVisible(true);
\r
209 public void onSubmitComplete(final FormSubmitCompleteEvent event) {
\r
210 // When the form submission is successfully completed, this
\r
211 // event is fired. Assuming the service returned a response
\r
212 // of type text/html, we can get the result text here (see
\r
213 // the FormPanel documentation for further explanation).
\r
214 String results = event.getResults();
\r
216 // Unfortunately the results are never empty, even in
\r
217 // the absense of errors, so we have to check for '<pre></pre>'.
\r
218 if (!results.equalsIgnoreCase("<pre></pre>")) {
\r
219 GWT.log(results, null);
\r
220 GSS.get().displayError(results);
\r
222 progressBar.setProgress(100);
\r
224 GSS.get().showFileList(true);
\r
225 GSS.get().getStatusPanel().updateStats();
\r
229 panel.add(buttons);
\r
230 progressBar = new ProgressBar(50, ProgressBar.SHOW_TIME_REMAINING);
\r
231 panel.add(progressBar);
\r
232 progressBar.setVisible(false);
\r
233 panel.setCellHorizontalAlignment(buttons, HasHorizontalAlignment.ALIGN_CENTER);
\r
234 panel.setCellHorizontalAlignment(progressBar, HasHorizontalAlignment.ALIGN_CENTER);
\r
235 panel.addStyleName("gss-DialogBox");
\r
236 addStyleName("gss-DialogBox");
\r
241 public boolean onKeyDownPreview(char key, int modifiers) {
\r
242 // Use the popup's key preview hooks to close the dialog when either
\r
243 // enter or escape is pressed.
\r
245 case KeyboardListener.KEY_ENTER:
\r
246 prepareAndSubmit();
\r
248 case KeyboardListener.KEY_ESCAPE:
\r
257 * Cancels the file upload.
\r
259 private void cancelUpload() {
\r
265 * Make any last minute checks and start the upload.
\r
267 public void prepareAndSubmit() {
\r
268 final String fname = getFilename(upload.getFilename());
\r
269 if (getFileForName(fname) == null) {
\r
270 //we are going to create a file, so we check to see if there is a trashed file with the same name
\r
271 FileResource same = null;
\r
272 for (FileResource fres : folder.getFiles())
\r
273 if (fres.isDeleted() && fres.getName().equals(fname))
\r
278 final FileResource sameFile = same;
\r
279 GWT.log("Same deleted file", null);
\r
280 ConfirmationDialog confirm = new ConfirmationDialog("A file with " +
\r
281 "the same name exists in the trash. If you continue,<br/>the trashed " +
\r
282 "file '" + fname + "' will be renamed automatically for you.", "Continue") {
\r
285 public void cancel() {
\r
286 FileUploadDialog.this.hide();
\r
290 public void confirm() {
\r
291 updateTrashedFile(getBackupFilename(fname), sameFile);
\r
299 // We are going to update an existing file, so show a confirmation dialog.
\r
300 ConfirmationDialog confirm = new ConfirmationDialog("Are you sure " +
\r
301 "you want to update " + fname + "?", "Update") {
\r
304 public void cancel() {
\r
305 FileUploadDialog.this.hide();
\r
309 public void confirm() {
\r
319 * Returns the file name from a potential full path argument. Apparently IE
\r
320 * insists on sending the full path name of a file when uploading, forcing
\r
321 * us to trim the extra path info. Since this is only observed on Windows we
\r
322 * get to check for a single path separator value.
\r
324 * @param name the potentially full path name of a file
\r
325 * @return the file name without extra path information
\r
327 protected String getFilename(String name) {
\r
328 int pathSepIndex = name.lastIndexOf("\\");
\r
329 if (pathSepIndex == -1) {
\r
330 pathSepIndex = name.lastIndexOf("/");
\r
331 if (pathSepIndex == -1)
\r
334 return name.substring(pathSepIndex + 1);
\r
338 * Check whether the file name exists in selected folder.
\r
342 private boolean canContinue() {
\r
345 String fileName = getFilename(upload.getFilename());
\r
346 if (getFileForName(fileName) == null) {
\r
347 // For file creation, check to see if the file already exists.
\r
348 GWT.log("filename to upload:" + fileName, null);
\r
349 for (FileResource dto : files) {
\r
350 GWT.log("Check:" + dto.getName() + "/" + fileName, null);
\r
351 if (!dto.isDeleted() && dto.getName().equals(fileName)) {
\r
352 cancelEvent = true;
\r
360 class RepeatingTimer extends Timer {
\r
362 private Updateable updateable;
\r
364 private int interval = 1500;
\r
366 private boolean running = true;
\r
368 RepeatingTimer(Updateable _updateable, int _interval) {
\r
369 updateable = _updateable;
\r
370 interval = _interval;
\r
374 public void run() {
\r
375 updateable.update();
\r
378 public void start() {
\r
381 scheduleRepeating(interval);
\r
384 public void finish() {
\r
389 public int getInterval() {
\r
393 public void setInterval(int anInterval) {
\r
394 if (interval != anInterval) {
\r
395 interval = anInterval;
\r
405 * @see gr.ebs.gss.client.Updateable#update()
\r
407 public void update() {
\r
408 String apath = folder.getUri();
\r
409 if (!apath.endsWith("/"))
\r
410 apath = apath + "/";
\r
411 apath = apath + encodeComponent(fileNameToUse) + "?progress=" + encodeComponent(fileNameToUse);
\r
412 GetCommand eg = new GetCommand<UploadStatusResource>(UploadStatusResource.class, apath, false) {
\r
415 public void onComplete() {
\r
416 UploadStatusResource res = getResult();
\r
417 progressBar.setProgress(res.percent());
\r
421 public void onError(Throwable t) {
\r
426 DeferredCommand.addCommand(eg);
\r
429 protected String getBackupFilename(String filename) {
\r
430 List<FileResource> filesInSameFolder = new ArrayList<FileResource>();
\r
431 for (FileResource deleted : folder.getFiles())
\r
432 if (deleted.isDeleted())
\r
433 filesInSameFolder.add(deleted);
\r
435 for (FileResource same : filesInSameFolder)
\r
436 if (same.getName().startsWith(filename)) {
\r
437 String toCheck = same.getName().substring(filename.length(), same.getName().length());
\r
438 if (toCheck.startsWith(" ")) {
\r
441 test = Integer.valueOf(toCheck.replace(" ", ""));
\r
442 } catch (NumberFormatException e) {
\r
443 // Do nothing since string is not a number.
\r
450 return filename + " " + i;
\r
454 * Rename the conflicting trashed file with the supplied new name.
\r
456 private void updateTrashedFile(String newName, FileResource trashedFile) {
\r
457 JSONObject json = new JSONObject();
\r
458 json.put("name", new JSONString(newName));
\r
459 PostCommand cf = new PostCommand(trashedFile.getUri() + "?update=", json.toString(), 200) {
\r
462 public void onComplete() {
\r
467 public void onError(Throwable t) {
\r
468 GSS app = GSS.get();
\r
470 if (t instanceof RestException) {
\r
471 int statusCode = ((RestException) t).getHttpStatusCode();
\r
472 if (statusCode == 405)
\r
473 app.displayError("You don't have the necessary permissions");
\r
474 else if (statusCode == 404)
\r
475 app.displayError("User in permissions does not exist");
\r
476 else if (statusCode == 409)
\r
477 app.displayError("A file with the same name already exists");
\r
478 else if (statusCode == 413)
\r
479 app.displayError("Your quota has been exceeded");
\r
481 app.displayError("Unable to modify file:" + ((RestException) t).getHttpStatusText());
\r
483 app.displayError("System error modifying file:" + t.getMessage());
\r
487 DeferredCommand.addCommand(cf);
\r
490 protected FileResource getFileForName(String name){
\r
491 for (FileResource f : folder.getFiles())
\r
492 if (!f.isDeleted() && f.getName().equals(name))
\r
499 * Same as URL.encodeComponent, but also
\r
500 * encode apostrophe since browsers aren't consistent about it
\r
501 * (FF encodes, IE does not).
\r
503 private String encodeComponent(String decodedURLComponent) {
\r
504 String retv = URL.encodeComponent(decodedURLComponent);
\r
505 retv = retv.replaceAll("'", "%27");
\r
510 * Modify the files.
\r
512 * @param newFiles the files to set
\r
514 public void setFiles(List<FileResource> newFiles) {
\r