Revision 26cbae7a web_client/src/gr/grnet/pithos/web/client/FileUploadDialog.java

b/web_client/src/gr/grnet/pithos/web/client/FileUploadDialog.java
34 34
 */
35 35
package gr.grnet.pithos.web.client;
36 36

  
37
import com.google.gwt.core.client.Scheduler;
38
import com.google.gwt.http.client.Response;
39
import gr.grnet.pithos.web.client.foldertree.File;
40
import gr.grnet.pithos.web.client.foldertree.Folder;
41
import gr.grnet.pithos.web.client.foldertree.Resource;
37 42
import gr.grnet.pithos.web.client.rest.GetCommand;
38 43
import gr.grnet.pithos.web.client.rest.PostCommand;
44
import gr.grnet.pithos.web.client.rest.PutRequest;
39 45
import gr.grnet.pithos.web.client.rest.RestCommand;
40 46
import gr.grnet.pithos.web.client.rest.RestException;
41 47
import gr.grnet.pithos.web.client.rest.resource.FileResource;
......
72 78
import com.google.gwt.user.client.ui.HorizontalPanel;
73 79
import com.google.gwt.user.client.ui.Label;
74 80
import com.google.gwt.user.client.ui.VerticalPanel;
81
import javax.xml.transform.Templates;
75 82

  
76 83
/**
77 84
 * The 'File upload' dialog box implementation.
78 85
 */
79
public class FileUploadDialog extends DialogBox implements Updateable {
86
public class FileUploadDialog extends DialogBox {
80 87

  
81
	protected int prgBarInterval = 1500;
82

  
83
	private ProgressBar progressBar;
84

  
85
	protected RepeatingTimer repeater = new RepeatingTimer(this, prgBarInterval);
86

  
87
	public static final boolean DONE = true;
88
    public static final boolean DONE = true;
88 89

  
89 90
	/**
90 91
	 * The Form element that performs the file upload.
......
93 94

  
94 95
	private final FileUpload upload = new FileUpload();
95 96

  
96
	protected final Label filenameLabel = new Label("");
97
	private final Label filenameLabel = new Label();
97 98

  
98
	protected List<FileResource> files;
99
    private final Label foldernameLabel = new Label();
99 100

  
100
	protected boolean cancelEvent = false;
101
    private Button submit;
101 102

  
102
	protected String fileNameToUse;
103
	protected Folder folder;
103 104

  
104
	protected FolderResource folder;
105
    protected GSS app;
105 106

  
106 107
	/**
107 108
	 * The widget's constructor.
......
123 124
				"Gears</a><br> for uploading multiple files simultaneously.");
124 125
		info.addStyleName("pithos-uploadNote");
125 126
		panel.add(info);
126
		final Hidden date = new Hidden("Date", "");
127
		panel.add(date);
128
		final Hidden auth = new Hidden("Authorization", "");
129
		panel.add(auth);
130
		// Add an informative label with the folder name.
131
		Object selection = GSS.get().getTreeView().getSelection();
132
		folder = ((RestResourceWrapper) selection).getResource();
127

  
128
        final Hidden auth = new Hidden("X-Auth-Token", "");
129
        panel.add(auth);
133 130
		upload.setName("file");
134 131
		filenameLabel.setText("");
135 132
		filenameLabel.setVisible(false);
136 133
		filenameLabel.setStyleName("props-labels");
137
		HorizontalPanel fileUloadPanel = new HorizontalPanel();
138
		fileUloadPanel.add(filenameLabel);
139
		fileUloadPanel.add(upload);
140
		upload.getElement().setId("fileUploadDiallog.uploadPanel");
134
		HorizontalPanel fileUploadPanel = new HorizontalPanel();
135
		fileUploadPanel.add(filenameLabel);
136
		fileUploadPanel.add(upload);
141 137
		Grid generalTable = new Grid(2, 2);
142 138
		generalTable.setText(0, 0, "Folder");
139
        generalTable.setWidget(0, 1, foldernameLabel);
143 140
		generalTable.setText(1, 0, "File");
144
		generalTable.setText(0, 1, folder.getName());
145
		generalTable.setWidget(1, 1, fileUloadPanel);
141
		generalTable.setWidget(1, 1, fileUploadPanel);
146 142
		generalTable.getCellFormatter().setStyleName(0, 0, "props-labels");
143
        generalTable.getCellFormatter().setStyleName(0, 1, "props-values");
147 144
		generalTable.getCellFormatter().setStyleName(1, 0, "props-labels");
148
		generalTable.getCellFormatter().setStyleName(0, 1, "props-values");
149 145
		generalTable.getCellFormatter().setStyleName(1, 1, "props-values");
150 146
		generalTable.setCellSpacing(4);
151 147

  
......
156 152

  
157 153
		// Create the 'upload' button, along with a listener that submits the
158 154
		// form.
159
		final Button submit = new Button("Upload", new ClickHandler() {
155
		submit = new Button("Upload", new ClickHandler() {
160 156
			@Override
161 157
			public void onClick(ClickEvent event) {
162 158
				prepareAndSubmit();
163 159
			}
164 160
		});
165
		submit.getElement().setId("fileUploadDialog.button.upload");
166 161
		buttons.add(submit);
167 162
		buttons.setCellHorizontalAlignment(submit, HasHorizontalAlignment.ALIGN_CENTER);
168 163
		// Create the 'Cancel' button, along with a listener that hides the
......
170 165
		final Button cancel = new Button("Cancel", new ClickHandler() {
171 166
			@Override
172 167
			public void onClick(ClickEvent event) {
173
				repeater.finish();
174 168
				hide();
175 169
			}
176 170
		});
177
		cancel.getElement().setId("fileUploadDialog.button.cancel");
178 171
		buttons.add(cancel);
179 172
		buttons.setCellHorizontalAlignment(cancel, HasHorizontalAlignment.ALIGN_CENTER);
180 173
		buttons.setSpacing(8);
181 174
		buttons.addStyleName("pithos-DialogBox");
175
        panel.add(buttons);
176
        panel.setCellHorizontalAlignment(buttons, HasHorizontalAlignment.ALIGN_CENTER);
182 177

  
183 178
		// Add an event handler to the form.
184 179
		form.addSubmitHandler(new SubmitHandler() {
185 180

  
186 181
			@Override
187 182
			public void onSubmit(SubmitEvent event) {
188
				GSS app = GSS.get();
189
				// This event is fired just before the form is submitted. We can
190
				// take this opportunity to perform validation.
191
				if (upload.getFilename().length() == 0) {
192
					app.displayError("You must select a file!");
193
					event.cancel();
194
					hide();
195
				} else {
196

  
197
					canContinue();
198
					GWT.log("Cancel:" + cancelEvent, null);
199
					if (cancelEvent) {
200
						cancelEvent = false;
201
						app.displayError("The specified file name already exists in this folder");
202
						event.cancel();
203
						hide();
204
					} else {
205

  
206
						fileNameToUse = getFilename(upload.getFilename());
207
						String apath;
208
						FileResource selectedFile = getFileForName(fileNameToUse);
209
						if (selectedFile == null ) {
210
							//we are going to create a file
211
							apath = folder.getUri();
212
							if (!apath.endsWith("/"))
213
								apath = apath + "/";
214
							apath = apath + encodeComponent(fileNameToUse);
215
						} else
216
							apath = selectedFile.getUri();
217
						form.setAction(apath);
218
						String dateString = RestCommand.getDate();
219
						String resource = apath.substring(app.getApiPath().length() - 1, apath.length());
220
						String sig = RestCommand.calculateSig("POST", dateString, resource, RestCommand.base64decode(app.getToken()));
221
						date.setValue(dateString);
222
						auth.setValue(app.getCurrentUserResource().getUsername() + " " + sig);
223
						GWT.log("FolderPATH:" + folder.getUri(), null);
224
						submit.setEnabled(false);
225
						upload.setVisible(false);
226
						filenameLabel.setText(fileNameToUse);
227
						filenameLabel.setVisible(true);
228
						repeater.start();
229
						progressBar.setVisible(true);
230
					}
231
				}
232

  
183
                auth.setValue(app.getToken()); //This is done here because the app object is not available in the constructor
233 184
			}
234 185
		});
235 186
		form.addSubmitCompleteHandler(new SubmitCompleteHandler() {
......
244 195

  
245 196
				// Unfortunately the results are never empty, even in
246 197
				// the absense of errors, so we have to check for '<pre></pre>'.
247
				if (!results.equalsIgnoreCase("<pre></pre>")) {
198
				if (results != null && !results.equalsIgnoreCase("<pre></pre>")) {
248 199
					GWT.log(results, null);
249
					GSS.get().displayError(results);
200
					app.displayError(results);
250 201
				}
251
				progressBar.setProgress(100);
252
				cancelUpload();
253
				GSS.get().getTreeView().updateNode(GSS.get().getTreeView().getSelection());
254
				GSS.get().getStatusPanel().updateStats();
255

  
202
                app.updateFolder(folder);
203
				hide();
256 204
			}
257 205
		});
258 206

  
259 207

  
260
		panel.add(buttons);
261
		progressBar = new ProgressBar(50, ProgressBar.SHOW_TIME_REMAINING);
262
		panel.add(progressBar);
263
		progressBar.setVisible(false);
264
		panel.setCellHorizontalAlignment(buttons, HasHorizontalAlignment.ALIGN_CENTER);
265
		panel.setCellHorizontalAlignment(progressBar, HasHorizontalAlignment.ALIGN_CENTER);
266 208
		panel.addStyleName("pithos-DialogBox");
267 209
		addStyleName("pithos-DialogBox");
268 210
		setWidget(form);
......
281 223
					prepareAndSubmit();
282 224
					break;
283 225
				case KeyCodes.KEY_ESCAPE:
284
					cancelUpload();
226
					hide();
285 227
					break;
286 228
			}
287 229
	}
288 230

  
289

  
290

  
291
	/**
292
	 * Cancels the file upload.
293
	 */
294
	private void cancelUpload() {
295
		repeater.finish();
296
		hide();
297
	}
298

  
299 231
	/**
300 232
	 * Make any last minute checks and start the upload.
301 233
	 */
302
	public void prepareAndSubmit() {
303
		final String fname = getFilename(upload.getFilename());
234
	protected void prepareAndSubmit() {
235
        if (upload.getFilename().length() == 0) {
236
            app.displayError("You must select a file!");
237
            return;
238
        }
239
        final String fname = getFilename(upload.getFilename());
240
        String apath = app.getApiPath() + app.getUsername() + folder.getUri() + "/" + fname;
241
        form.setAction(apath);
242
        submit.setEnabled(false);
243
        upload.setVisible(false);
244
        filenameLabel.setText(fname);
245
        filenameLabel.setVisible(true);
246

  
304 247
		if (getFileForName(fname) == null) {
305
			//we are going to create a file, so we check to see if there is a trashed file with the same name
306
			FileResource same = null;
307
			for (FileResource fres : folder.getFiles())
308
				if (fres.isDeleted() && fres.getName().equals(fname))
309
					same = fres;
310
			if (same == null)
311
				form.submit();
312
			else {
313
				final FileResource sameFile = same;
314
				GWT.log("Same deleted file", null);
315
				ConfirmationDialog confirm = new ConfirmationDialog("A file with " +
316
						"the same name exists in the trash. If you continue,<br/>the trashed " +
317
						"file  '" + fname + "' will be renamed automatically for you.", "Continue") {
318

  
319
					@Override
320
					public void cancel() {
321
						FileUploadDialog.this.hide();
322
					}
323

  
324
					@Override
325
					public void confirm() {
326
						updateTrashedFile(getBackupFilename(fname), sameFile);
327
					}
328

  
329
				};
330
				confirm.center();
331
			}
248
			doUpload(apath);
332 249
		}
333 250
		else {
334 251
			// We are going to update an existing file, so show a confirmation dialog.
......
350 267
		}
351 268
	}
352 269

  
353
	/**
270
    private void doUpload(String path) {
271
        PutRequest createFile = new PutRequest(path) {
272
            @Override
273
            public void onSuccess(Resource result) {
274
                form.submit();
275
            }
276

  
277
            @Override
278
            public void onError(Throwable t) {
279
                GWT.log("", t);
280
                if (t instanceof RestException) {
281
                    app.displayError("Unable to create file:" + ((RestException) t).getHttpStatusText());
282
                }
283
                else
284
                    app.displayError("System error creating file:" + t.getMessage());
285
            }
286
        };
287
        createFile.setHeader("X-Auth-Token", app.getToken());
288
        createFile.setHeader("Content-Length", "0");
289
        Scheduler.get().scheduleDeferred(createFile);
290
    }
291

  
292
    /**
354 293
	 * Returns the file name from a potential full path argument. Apparently IE
355 294
	 * insists on sending the full path name of a file when uploading, forcing
356 295
	 * us to trim the extra path info. Since this is only observed on Windows we
......
369 308
		return name.substring(pathSepIndex + 1);
370 309
	}
371 310

  
372
	/**
373
	 * Check whether the file name exists in selected folder.
374
	 *
375
	 * @return
376
	 */
377
	private boolean canContinue() {
378
		if (files == null)
379
			return false;
380
		String fileName = getFilename(upload.getFilename());
381
		if (getFileForName(fileName) == null) {
382
			// For file creation, check to see if the file already exists.
383
			GWT.log("filename to upload:" + fileName, null);
384
			for (FileResource dto : files) {
385
				GWT.log("Check:" + dto.getName() + "/" + fileName, null);
386
				if (!dto.isDeleted() && dto.getName().equals(fileName)) {
387
					cancelEvent = true;
388
					return true;
389
				}
390
			}
391
		}
392
		return true;
393
	}
394

  
395
	class RepeatingTimer extends Timer {
396

  
397
		private Updateable updateable;
398

  
399
		private int interval = 1500;
400

  
401
		private boolean running = true;
402

  
403
		RepeatingTimer(Updateable _updateable, int _interval) {
404
			updateable = _updateable;
405
			interval = _interval;
406
		}
407

  
408
		@Override
409
		public void run() {
410
			updateable.update();
411
		}
412

  
413
		public void start() {
414
			running = true;
415

  
416
			scheduleRepeating(interval);
417
		}
418

  
419
		public void finish() {
420
			running = false;
421
			cancel();
422
		}
423

  
424
		public int getInterval() {
425
			return interval;
426
		}
427

  
428
		public void setInterval(int anInterval) {
429
			if (interval != anInterval) {
430
				interval = anInterval;
431
				if (running) {
432
					finish();
433
					start();
434
				}
435
			}
436
		}
437
	}
438

  
439
	@Override
440
	public void update() {
441
		String apath = folder.getUri();
442
		if (!apath.endsWith("/"))
443
			apath = apath + "/";
444
		apath = apath + encodeComponent(fileNameToUse) + "?progress=" + encodeComponent(fileNameToUse);
445
		GetCommand eg = new GetCommand<UploadStatusResource>(UploadStatusResource.class, apath, false, null) {
446

  
447
			@Override
448
			public void onComplete() {
449
				UploadStatusResource res = getResult();
450
				progressBar.setProgress(res.percent());
451
			}
452

  
453
			@Override
454
			public void onError(Throwable t) {
455
				GWT.log("", t);
456
			}
457

  
458
		};
459
		DeferredCommand.addCommand(eg);
460
	}
461

  
462
	protected String getBackupFilename(String filename) {
463
		List<FileResource> filesInSameFolder = new ArrayList<FileResource>();
464
		for (FileResource deleted : folder.getFiles())
465
			if (deleted.isDeleted())
466
				filesInSameFolder.add(deleted);
467
		int i = 1;
468
		for (FileResource same : filesInSameFolder)
469
			if (same.getName().startsWith(filename)) {
470
				String toCheck = same.getName().substring(filename.length(), same.getName().length());
471
				if (toCheck.startsWith(" ")) {
472
					int test = -1;
473
					try {
474
						test = Integer.valueOf(toCheck.replace(" ", ""));
475
					} catch (NumberFormatException e) {
476
						// Do nothing since string is not a number.
477
					}
478
					if (test >= i)
479
						i = test + 1;
480
				}
481
			}
482

  
483
		return filename + " " + i;
484
	}
485

  
486
	/**
487
	 * Rename the conflicting trashed file with the supplied new name.
488
	 */
489
	private void updateTrashedFile(String newName, FileResource trashedFile) {
490
		JSONObject json = new JSONObject();
491
		json.put("name", new JSONString(newName));
492
		PostCommand cf = new PostCommand(trashedFile.getUri() + "?update=", json.toString(), 200) {
493

  
494
			@Override
495
			public void onComplete() {
496
				form.submit();
497
			}
498

  
499
			@Override
500
			public void onError(Throwable t) {
501
				GSS app = GSS.get();
502
				GWT.log("", t);
503
				if (t instanceof RestException) {
504
					int statusCode = ((RestException) t).getHttpStatusCode();
505
					if (statusCode == 405)
506
						app.displayError("You don't have the necessary permissions");
507
					else if (statusCode == 404)
508
						app.displayError("User in permissions does not exist");
509
					else if (statusCode == 409)
510
						app.displayError("A file with the same name already exists");
511
					else if (statusCode == 413)
512
						app.displayError("Your quota has been exceeded");
513
					else
514
						app.displayError("Unable to modify file:" + ((RestException) t).getHttpStatusText());
515
				} else
516
					app.displayError("System error modifying file:" + t.getMessage());
517
			}
518

  
519
		};
520
		DeferredCommand.addCommand(cf);
521
	}
522

  
523
	protected FileResource getFileForName(String name){
524
		for (FileResource f : folder.getFiles())
525
			if (!f.isDeleted() && f.getName().equals(name))
311
	protected File getFileForName(String name){
312
		for (File f : folder.getFiles())
313
			if (!f.isInTrash() && f.getName().equals(name))
526 314
				return f;
527 315
		return null;
528 316
	}
529 317

  
318
    public void setApp(GSS app) {
319
        this.app = app;
320
    }
530 321

  
531
	/**
532
	 * Same as URL.encodeComponent, but also
533
	 * encode apostrophe since browsers aren't consistent about it
534
	 * (FF encodes, IE does not).
535
	 */
536
	private String encodeComponent(String decodedURLComponent) {
537
		String retv = URL.encodeComponent(decodedURLComponent);
538
		retv = retv.replaceAll("'", "%27");
539
		return retv;
540
	}
541

  
542
	/**
543
	 * Modify the files.
544
	 *
545
	 * @param newFiles the files to set
546
	 */
547
	public void setFiles(List<FileResource> newFiles) {
548
		files = newFiles;
549
	}
322
    public void setFolder(Folder folder) {
323
        this.folder = folder;
324
        foldernameLabel.setText(folder.getName());
325
    }
550 326
}

Also available in: Unified diff