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.FileMenu.Images;
\r
22 import gr.ebs.gss.client.rest.GetCommand;
\r
23 import gr.ebs.gss.client.rest.PostCommand;
\r
24 import gr.ebs.gss.client.rest.RestCommand;
\r
25 import gr.ebs.gss.client.rest.RestException;
\r
26 import gr.ebs.gss.client.rest.resource.FileResource;
\r
27 import gr.ebs.gss.client.rest.resource.FolderResource;
\r
28 import gr.ebs.gss.client.rest.resource.UploadStatusResource;
\r
30 import java.util.ArrayList;
\r
31 import java.util.List;
\r
33 import com.google.gwt.core.client.GWT;
\r
34 import com.google.gwt.http.client.URL;
\r
35 import com.google.gwt.json.client.JSONObject;
\r
36 import com.google.gwt.json.client.JSONString;
\r
37 import com.google.gwt.user.client.DeferredCommand;
\r
38 import com.google.gwt.user.client.Timer;
\r
39 import com.google.gwt.user.client.ui.Button;
\r
40 import com.google.gwt.user.client.ui.ClickListener;
\r
41 import com.google.gwt.user.client.ui.DialogBox;
\r
42 import com.google.gwt.user.client.ui.FileUpload;
\r
43 import com.google.gwt.user.client.ui.FormHandler;
\r
44 import com.google.gwt.user.client.ui.FormPanel;
\r
45 import com.google.gwt.user.client.ui.FormSubmitCompleteEvent;
\r
46 import com.google.gwt.user.client.ui.FormSubmitEvent;
\r
47 import com.google.gwt.user.client.ui.Grid;
\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 private int prgBarInterval = 1500;
\r
63 private ProgressBar progressBar;
\r
65 private 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 final FormPanel form = new FormPanel();
\r
74 final FileUpload upload = new FileUpload();
\r
76 final Label filenameLabel = new Label("");
\r
78 private List<FileResource> files;
\r
80 boolean cancelEvent = false;
\r
82 private String fileNameToUse;
\r
84 final FolderResource folder;
\r
85 final Images images;
\r
88 * The widget's constructor.
\r
92 public FileUploadDialog(final Images _images, List<FileResource> _files) {
\r
95 // Set the dialog's caption.
\r
96 setText("File upload");
\r
97 setAnimationEnabled(true);
\r
98 // Since we're going to add a FileUpload widget, we'll need to set the
\r
99 // form to use the POST method, and multipart MIME encoding.
\r
100 form.setEncoding(FormPanel.ENCODING_MULTIPART);
\r
101 form.setMethod(FormPanel.METHOD_POST);
\r
103 // Create a panel to hold all of the form widgets.
\r
104 VerticalPanel panel = new VerticalPanel();
\r
105 form.setWidget(panel);
\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
225 GSS.get().showFileList(true);
\r
226 GSS.get().getStatusPanel().updateStats();
\r
230 panel.add(buttons);
\r
231 progressBar = new ProgressBar(50, ProgressBar.SHOW_TIME_REMAINING);
\r
232 panel.add(progressBar);
\r
233 progressBar.setVisible(false);
\r
234 panel.setCellHorizontalAlignment(buttons, 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
258 public void prepareAndSubmit(){
\r
259 final String fname = getFilename(upload.getFilename());
\r
260 if (getFileForName(fname) == null) {
\r
261 //we are going to create a file, so we check to see if there is a trashed file with the same name
\r
262 FileResource same = null;
\r
263 for (FileResource fres : folder.getFiles())
\r
264 if (fres.isDeleted() && fres.getName().equals(fname))
\r
269 final FileResource sameFile = same;
\r
270 GWT.log("Same deleted file", null);
\r
271 ConfirmationDialog confirm = new ConfirmationDialog(images, "A file with " +
\r
272 "the same name exists in the trash. If you continue,<br/>the trashed " +
\r
273 "file '" + fname + "' will be renamed automatically for you.", "Continue"){
\r
276 public void cancel() {
\r
277 FileUploadDialog.this.hide();
\r
281 public void confirm() {
\r
282 updateTrashedFile(getBackupFilename(fname), sameFile);
\r
290 // We are going to update an existing file, so show a confirmation dialog.
\r
291 ConfirmationDialog confirm = new ConfirmationDialog(images, "Are you sure " +
\r
292 "you want to update " + fname + "?", "Update"){
\r
295 public void cancel() {
\r
296 FileUploadDialog.this.hide();
\r
300 public void confirm() {
\r
310 * Returns the file name from a potential full path argument. Apparently IE
\r
311 * insists on sending the full path name of a file when uploading, forcing
\r
312 * us to trim the extra path info. Since this is only observed on Windows we
\r
313 * get to check for a single path separator value.
\r
315 * @param name the potentially full path name of a file
\r
316 * @return the file name without extra path information
\r
318 private String getFilename(String name) {
\r
319 int pathSepIndex = name.lastIndexOf("\\");
\r
320 if (pathSepIndex == -1) {
\r
321 pathSepIndex = name.lastIndexOf("/");
\r
322 if (pathSepIndex == -1)
\r
325 return name.substring(pathSepIndex + 1);
\r
329 * Check whether the file name exists in selected folder.
\r
333 private boolean canContinue() {
\r
336 String fileName = getFilename(upload.getFilename());
\r
337 if (getFileForName(fileName) == null) {
\r
338 // For file creation, check to see if the file already exists.
\r
339 GWT.log("filename to upload:" + fileName, null);
\r
340 for (FileResource dto : files) {
\r
341 GWT.log("Check:" + dto.getName() + "/" + fileName, null);
\r
342 if (!dto.isDeleted() && dto.getName().equals(fileName)) {
\r
343 cancelEvent = true;
\r
351 class RepeatingTimer extends Timer {
\r
353 private Updateable updateable;
\r
355 private int interval = 1500;
\r
357 private boolean running = true;
\r
359 RepeatingTimer(Updateable _updateable, int _interval) {
\r
360 updateable = _updateable;
\r
361 interval = _interval;
\r
365 public void run() {
\r
366 updateable.update();
\r
369 public void start() {
\r
372 scheduleRepeating(interval);
\r
375 public void finish() {
\r
380 public int getInterval() {
\r
384 public void setInterval(int anInterval) {
\r
385 if (interval != anInterval) {
\r
386 interval = anInterval;
\r
396 * @see gr.ebs.gss.client.Updateable#update()
\r
398 public void update() {
\r
399 String apath = folder.getUri();
\r
400 if (!apath.endsWith("/"))
\r
401 apath = apath + "/";
\r
402 apath = apath + encodeComponent(fileNameToUse) + "?progress=" + encodeComponent(fileNameToUse);
\r
403 GetCommand eg = new GetCommand<UploadStatusResource>(UploadStatusResource.class, apath, false) {
\r
406 public void onComplete() {
\r
407 UploadStatusResource res = getResult();
\r
408 progressBar.setProgress(res.percent());
\r
412 public void onError(Throwable t) {
\r
418 DeferredCommand.addCommand(eg);
\r
421 private String getBackupFilename(String filename) {
\r
422 List<FileResource> filesInSameFolder = new ArrayList<FileResource>();
\r
423 for (FileResource deleted : folder.getFiles())
\r
424 if (deleted.isDeleted())
\r
425 filesInSameFolder.add(deleted);
\r
427 for (FileResource same : filesInSameFolder)
\r
428 if (same.getName().startsWith(filename)) {
\r
429 String toCheck = same.getName().substring(filename.length(), same.getName().length());
\r
430 if (toCheck.startsWith(" ")) {
\r
433 test = Integer.valueOf(toCheck.replace(" ", ""));
\r
434 } catch (NumberFormatException e) {
\r
435 // Do nothing since string is not a number.
\r
442 return filename + " " + i;
\r
445 private void updateTrashedFile(String newName, FileResource trashedFile) {
\r
446 JSONObject json = new JSONObject();
\r
447 json.put("name", new JSONString(newName));
\r
448 PostCommand cf = new PostCommand(trashedFile.getUri() + "?update=", json.toString(), 200) {
\r
451 public void onComplete() {
\r
456 public void onError(Throwable t) {
\r
458 if (t instanceof RestException) {
\r
459 int statusCode = ((RestException) t).getHttpStatusCode();
\r
460 if (statusCode == 405)
\r
461 GSS.get().displayError("You don't have the necessary permissions");
\r
462 else if (statusCode == 404)
\r
463 GSS.get().displayError("User in permissions does not exist");
\r
464 else if (statusCode == 409)
\r
465 GSS.get().displayError("A file with the same name already exists");
\r
466 else if (statusCode == 413)
\r
467 GSS.get().displayError("Your quota has been exceeded");
\r
469 GSS.get().displayError("Unable to modify file:" +((RestException)t).getHttpStatusText());
\r
471 GSS.get().displayError("System error modifying file:" + t.getMessage());
\r
475 DeferredCommand.addCommand(cf);
\r
478 private FileResource getFileForName(String name){
\r
479 for (FileResource f : folder.getFiles())
\r
480 if (!f.isDeleted() && f.getName().equals(name))
\r
487 * Same as URL.encodeComponent, but also
\r
488 * encode apostrophe since browsers aren't consistent about it
\r
489 * (FF encodes, IE does not).
\r
491 * @param decodedURLComponent
\r
494 private String encodeComponent(String decodedURLComponent) {
\r
495 String retv = URL.encodeComponent(decodedURLComponent);
\r
496 retv = retv.replaceAll("'", "%27");
\r