Moved all web client files to their folder. Updated ignored files
[pithos-web-client] / src / org / gss_project / gss / web / client / FileList.java
1 /*
2  * Copyright 2007, 2008, 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 org.gss_project.gss.web.client;
20
21 import static com.google.gwt.query.client.GQuery.$;
22
23 import org.gss_project.gss.web.client.commands.UploadFileCommand;
24 import org.gss_project.gss.web.client.rest.GetCommand;
25 import org.gss_project.gss.web.client.rest.RestCommand;
26 import org.gss_project.gss.web.client.rest.resource.FileResource;
27 import org.gss_project.gss.web.client.rest.resource.OtherUserResource;
28 import org.gss_project.gss.web.client.rest.resource.OthersFolderResource;
29 import org.gss_project.gss.web.client.rest.resource.OthersResource;
30 import org.gss_project.gss.web.client.rest.resource.RestResource;
31 import org.gss_project.gss.web.client.rest.resource.RestResourceWrapper;
32 import org.gss_project.gss.web.client.rest.resource.SharedResource;
33 import org.gss_project.gss.web.client.rest.resource.TrashFolderResource;
34 import org.gss_project.gss.web.client.rest.resource.TrashResource;
35 import org.gss_project.gss.web.client.rest.resource.UserResource;
36 import org.gss_project.gss.web.client.rest.resource.UserSearchResource;
37 import gwtquery.plugins.draggable.client.DraggableOptions;
38 import gwtquery.plugins.draggable.client.StopDragException;
39 import gwtquery.plugins.draggable.client.DraggableOptions.DragFunction;
40 import gwtquery.plugins.draggable.client.DraggableOptions.RevertOption;
41 import gwtquery.plugins.draggable.client.events.DragContext;
42 import gwtquery.plugins.draggable.client.events.DragStartEvent;
43 import gwtquery.plugins.draggable.client.events.DragStopEvent;
44 import gwtquery.plugins.draggable.client.events.DragStartEvent.DragStartEventHandler;
45 import gwtquery.plugins.draggable.client.events.DragStopEvent.DragStopEventHandler;
46 import gwtquery.plugins.droppable.client.gwt.DragAndDropCellTable;
47 import gwtquery.plugins.droppable.client.gwt.DragAndDropColumn;
48
49 import java.util.ArrayList;
50 import java.util.Collections;
51 import java.util.Comparator;
52 import java.util.Iterator;
53 import java.util.List;
54
55 import com.google.gwt.cell.client.AbstractCell;
56 import com.google.gwt.cell.client.ImageResourceCell;
57 import com.google.gwt.cell.client.SafeHtmlCell;
58 import com.google.gwt.cell.client.TextCell;
59 import com.google.gwt.cell.client.ValueUpdater;
60 import com.google.gwt.core.client.GWT;
61 import com.google.gwt.core.client.Scheduler;
62 import com.google.gwt.core.client.Scheduler.RepeatingCommand;
63 import com.google.gwt.dom.client.Style.Cursor;
64 import com.google.gwt.event.dom.client.ClickEvent;
65 import com.google.gwt.event.dom.client.ClickHandler;
66 import com.google.gwt.http.client.URL;
67 import com.google.gwt.i18n.client.DateTimeFormat;
68 import com.google.gwt.resources.client.ClientBundle;
69 import com.google.gwt.resources.client.ImageResource;
70 import com.google.gwt.safehtml.client.SafeHtmlTemplates;
71 import com.google.gwt.safehtml.shared.SafeHtml;
72 import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
73 import com.google.gwt.user.cellview.client.CellTable;
74 import com.google.gwt.user.cellview.client.GssSimplePager;
75 import com.google.gwt.user.client.DOM;
76 import com.google.gwt.user.client.DeferredCommand;
77 import com.google.gwt.user.client.Event;
78 import com.google.gwt.user.client.Window;
79 import com.google.gwt.user.client.ui.AbstractImagePrototype;
80 import com.google.gwt.user.client.ui.Button;
81 import com.google.gwt.user.client.ui.Composite;
82 import com.google.gwt.user.client.ui.HorizontalPanel;
83 import com.google.gwt.user.client.ui.VerticalPanel;
84 import com.google.gwt.view.client.ListDataProvider;
85 import com.google.gwt.view.client.MultiSelectionModel;
86 import com.google.gwt.view.client.ProvidesKey;
87 import com.google.gwt.view.client.SelectionChangeEvent;
88 import com.google.gwt.view.client.SelectionChangeEvent.Handler;
89
90 /**
91  * A composite that displays the list of files in a particular folder.
92  */
93 public class FileList extends Composite {
94         ListDataProvider<FileResource> provider = new ListDataProvider<FileResource>();
95         interface TableResources extends DragAndDropCellTable.Resources {
96             @Source({CellTable.Style.DEFAULT_CSS, "GssCellTable.css"})
97             TableStyle cellTableStyle();
98           }
99         
100         static interface Templates extends SafeHtmlTemplates {
101             Templates INSTANCE = GWT.create(Templates.class);
102
103             @Template("<div id='dragHelper' style='border:1px solid black; background-color:#ffffff; color:black; width:150px;z-index:100'></div>")
104             SafeHtml outerHelper();
105
106         @Template("<span id='{0}'>{0}</span>")
107         public SafeHtml filenameSpan(String filename);
108
109         @Template("<a href='{0}' title='{1}' rel='lytebox[mnf]' onclick='myLytebox.start(this, false, false); return false;'>(view)</a>")
110         public SafeHtml viewLink(String link, String title);
111
112         @Template("<table><tr><td rowspan='3'>{0}</td><td style='font-size:95%;' id='{1}'>{1}</td></tr><tr><td>{2}</td></tr></table>")
113         public SafeHtml rendelContactCell(String imageHtml, String name, String fileSize);
114
115         @Template("<span id='{0}' class='{1}'>{2}</span>")
116         public SafeHtml spanWithIdAndClass(String id, String cssClass, String content);
117           }
118         
119         
120         /**
121            * The styles applied to the table.
122            */
123           interface TableStyle extends CellTable.Style {
124           }
125
126         private String showingStats = "";
127
128         private int startIndex = 0;
129
130         /**
131          * A constant that denotes the completion of an IncrementalCommand.
132          */
133         public static final boolean DONE = false;
134
135         
136         
137         private final DateTimeFormat formatter = DateTimeFormat.getFormat("d/M/yyyy h:mm a");
138
139         /**
140          * Specifies that the images available for this composite will be the ones
141          * available in FileContextMenu.
142          */
143         public interface Images extends ClientBundle,FileContextMenu.Images, CellTreeView.Images {
144
145                 @Source("org/gss_project/gss/resources/blank.gif")
146                 ImageResource blank();
147
148                 @Source("org/gss_project/gss/resources/asc.png")
149                 ImageResource asc();
150
151                 @Source("org/gss_project/gss/resources/desc.png")
152                 ImageResource desc();
153
154                 @Source("org/gss_project/gss/resources/mimetypes/document_shared.png")
155                 ImageResource documentShared();
156
157                 @Source("org/gss_project/gss/resources/mimetypes/kcmfontinst.png")
158                 ImageResource wordprocessor();
159
160                 @Source("org/gss_project/gss/resources/mimetypes/log.png")
161                 ImageResource spreadsheet();
162
163                 @Source("org/gss_project/gss/resources/mimetypes/kpresenter_kpr.png")
164                 ImageResource presentation();
165
166                 @Source("org/gss_project/gss/resources/mimetypes/acroread.png")
167                 ImageResource pdf();
168
169                 @Source("org/gss_project/gss/resources/mimetypes/image.png")
170                 ImageResource image();
171
172                 @Source("org/gss_project/gss/resources/mimetypes/video2.png")
173                 ImageResource video();
174
175                 @Source("org/gss_project/gss/resources/mimetypes/knotify.png")
176                 ImageResource audio();
177
178                 @Source("org/gss_project/gss/resources/mimetypes/html.png")
179                 ImageResource html();
180
181                 @Source("org/gss_project/gss/resources/mimetypes/txt.png")
182                 ImageResource txt();
183
184                 @Source("org/gss_project/gss/resources/mimetypes/ark2.png")
185                 ImageResource zip();
186
187                 @Source("org/gss_project/gss/resources/mimetypes/kcmfontinst_shared.png")
188                 ImageResource wordprocessorShared();
189
190                 @Source("org/gss_project/gss/resources/mimetypes/log_shared.png")
191                 ImageResource spreadsheetShared();
192
193                 @Source("org/gss_project/gss/resources/mimetypes/kpresenter_kpr_shared.png")
194                 ImageResource presentationShared();
195
196                 @Source("org/gss_project/gss/resources/mimetypes/acroread_shared.png")
197                 ImageResource pdfShared();
198
199                 @Source("org/gss_project/gss/resources/mimetypes/image_shared.png")
200                 ImageResource imageShared();
201
202                 @Source("org/gss_project/gss/resources/mimetypes/video2_shared.png")
203                 ImageResource videoShared();
204
205                 @Source("org/gss_project/gss/resources/mimetypes/knotify_shared.png")
206                 ImageResource audioShared();
207
208                 @Source("org/gss_project/gss/resources/mimetypes/html_shared.png")
209                 ImageResource htmlShared();
210
211                 @Source("org/gss_project/gss/resources/mimetypes/txt_shared.png")
212                 ImageResource txtShared();
213
214                 @Source("org/gss_project/gss/resources/mimetypes/ark2_shared.png")
215                 ImageResource zipShared();
216
217         }
218         
219         DragStopEventHandler dragStop = new DragStopEventHandler() {
220                 
221                 @Override
222                 public void onDragStop(DragStopEvent event) {
223                         GWT.log("DRAG STOPPED");
224                         
225                 }
226         };
227         
228         private static class ContactCell extends AbstractCell<org.gss_project.gss.web.client.rest.resource.FileResource> {
229
230             /**
231              * The html of the image used for contacts.
232              * 
233              */
234             private final String imageHtml;
235
236             public ContactCell(ImageResource image) {
237               this.imageHtml = AbstractImagePrototype.create(image).getHTML();
238             }
239
240             
241
242                 
243
244             @Override
245             public void render(Context context, FileResource value, SafeHtmlBuilder sb) {
246               // Value can be null, so do a null check..
247               if (value == null) {
248                 return;
249               }
250
251           sb.append(Templates.INSTANCE.rendelContactCell(imageHtml, value.getName(), value.getFileSizeAsString()));
252             }
253
254
255           }
256         /**
257          * Retrieve the celltable.
258          *
259          * @return the celltable
260          */
261         public DragAndDropCellTable<FileResource> getCelltable() {
262                 return celltable;
263         }
264         
265         
266         /**
267          * The number of files in this folder.
268          */
269         int folderFileCount;
270
271         /**
272          * Total folder size
273          */
274         long folderTotalSize;
275
276         /**
277          * A cache of the files in the list.
278          */
279         private List<FileResource> files;
280
281         /**
282          * The widget's image bundle.
283          */
284         private final Images images;
285         
286         private FileContextMenu menuShowing;
287         private DragAndDropCellTable<FileResource> celltable;
288         private final MultiSelectionModel<FileResource> selectionModel;
289         private final List<SortableHeader> allHeaders = new ArrayList<SortableHeader>();
290         SortableHeader nameHeader;
291         GssSimplePager pagerBottom;
292         GssSimplePager pagerTop;
293         Button uploadButtonBottom;
294         Button uploadButtonTop;
295         /**
296          * Construct the file list widget. This entails setting up the widget
297          * layout, fetching the number of files in the current folder from the
298          * server and filling the local file cache of displayed files with data from
299          * the server, as well.
300          *
301          * @param _images
302          */
303         public FileList(Images _images) {
304                 images = _images;
305                 DragAndDropCellTable.Resources resources = GWT.create(TableResources.class);
306                 ProvidesKey<FileResource> keyProvider = new ProvidesKey<FileResource>(){
307
308                         @Override
309                         public Object getKey(FileResource item) {
310                                 return item.getUri();
311                         }
312                         
313                 };
314                 celltable = new DragAndDropCellTable<FileResource>(GSS.VISIBLE_FILE_COUNT,resources,keyProvider);
315                 
316                 DragAndDropColumn<FileResource, ImageResource> status = new DragAndDropColumn<FileResource, ImageResource>(new ImageResourceCell(){
317                         @Override
318                   public boolean handlesSelection() {
319                             return false;
320                           }
321                 }) {
322                   @Override
323                   public ImageResource getValue(FileResource entity) {
324                     return getFileIcon(entity);
325                   }
326                   
327                };
328             celltable.addColumn(status,"");
329             
330             initDragOperation(status);
331                 final DragAndDropColumn<FileResource,SafeHtml> nameColumn = new DragAndDropColumn<FileResource,SafeHtml>(new SafeHtmlCell()) {
332
333                         @Override
334                         public SafeHtml getValue(FileResource object) {
335                                 SafeHtmlBuilder sb = new SafeHtmlBuilder();
336                 sb.append(Templates.INSTANCE.filenameSpan(object.getName()));
337                                 if (object.getContentType().endsWith("png") || object.getContentType().endsWith("gif") || object.getContentType().endsWith("jpeg") ){
338                                         sb.appendHtmlConstant("&nbsp;").append(Templates.INSTANCE.viewLink(GSS.get().getTopPanel().getFileMenu().getDownloadURL(object), object.getOwner() + " : " + object.getPath() + object.getName()));
339                                 }
340                                 
341                                 return sb.toSafeHtml();
342                         }
343                         
344                 };
345                 initDragOperation(nameColumn);
346                 celltable.addColumn(nameColumn,nameHeader = new SortableHeader("Name"));
347                 allHeaders.add(nameHeader);
348                 //nameHeader.setSorted(true);
349                 //nameHeader.toggleReverseSort();
350                 nameHeader.setUpdater(new FileValueUpdater(nameHeader, "name"));
351                 celltable.redrawHeaders();
352                 
353                 
354             
355             
356             SortableHeader aheader;
357             DragAndDropColumn<FileResource,String> aColumn;
358                 celltable.addColumn(aColumn=new DragAndDropColumn<FileResource,String>(new TextCell()) {
359                         @Override
360                         public String getValue(FileResource object) {
361                                 return GSS.get().findUserFullName(object.getOwner());
362                         }                       
363                 },aheader = new SortableHeader("Owner"));
364                 initDragOperation(aColumn);
365                 allHeaders.add(aheader);
366                 aheader.setUpdater(new FileValueUpdater(aheader, "owner"));
367                 celltable.addColumn(aColumn=new DragAndDropColumn<FileResource,String>(new TextCell()) {
368                         @Override
369                         public String getValue(FileResource object) {
370                                 // TODO Auto-generated method stub
371                                 return object.getPath();
372                         }                       
373                 },aheader = new SortableHeader("Path"));
374                 initDragOperation(aColumn);
375                 allHeaders.add(aheader);
376                 
377                 aheader.setUpdater(new FileValueUpdater(aheader, "path"));      
378                 celltable.addColumn(aColumn=new DragAndDropColumn<FileResource,String>(new TextCell()) {
379                         @Override
380                         public String getValue(FileResource object) {
381                                 if(object.isVersioned())
382                                         return object.getVersion().toString();
383                                 return "-";
384                         }                       
385                 },aheader = new SortableHeader("Version"));
386                 initDragOperation(aColumn);
387                 allHeaders.add(aheader);
388                 aheader.setUpdater(new FileValueUpdater(aheader, "version"));
389                 celltable.addColumn(aColumn=new DragAndDropColumn<FileResource,String>(new TextCell()) {
390                         @Override
391                         public String getValue(FileResource object) {
392                                 // TODO Auto-generated method stub
393                                 return object.getFileSizeAsString();
394                         }                       
395                 },aheader = new SortableHeader("Size"));
396                 initDragOperation(aColumn);
397                 allHeaders.add(aheader);
398                 aheader.setUpdater(new FileValueUpdater(aheader, "size"));      
399                 celltable.addColumn(aColumn=new DragAndDropColumn<FileResource,String>(new TextCell()) {
400                         @Override
401                         public String getValue(FileResource object) {
402                                 return formatter.format(object.getModificationDate());
403                         }                       
404                 },aheader = new SortableHeader("Last Modified"));
405                 allHeaders.add(aheader);
406                 aheader.setUpdater(new FileValueUpdater(aheader, "date"));
407                
408                 
409                 provider.addDataDisplay(celltable);
410                 celltable.addDragStopHandler(dragStop);
411                 celltable.addDragStartHandler(new DragStartEventHandler() {
412
413                       public void onDragStart(DragStartEvent event) {
414                         FileResource value = event.getDraggableData();
415                         
416                         com.google.gwt.dom.client.Element helper = event.getHelper();
417                         SafeHtmlBuilder sb = new SafeHtmlBuilder();
418                         sb.appendHtmlConstant("<b>");
419                         DisplayHelper.log(value.getName());
420                         if(getSelectedFiles().size()==1)
421                                 sb.appendEscaped(value.getName());
422                         else
423                                 sb.appendEscaped(getSelectedFiles().size()+" files");
424                         sb.appendHtmlConstant("</b>");
425                         helper.setInnerHTML(sb.toSafeHtml().asString());
426
427                       }
428                     });
429                 
430                 
431                 
432                 
433                 
434                 
435                 VerticalPanel vp = new VerticalPanel();
436                 vp.setWidth("100%");
437                 pagerTop = new GssSimplePager(GssSimplePager.TextLocation.CENTER);
438                 pagerTop.setDisplay(celltable); 
439                 uploadButtonTop=new Button("<span id='topMenu.file.upload'>" + AbstractImagePrototype.create(images.fileUpdate()).getHTML() + "&nbsp;Upload</span>");
440                 uploadButtonTop.addClickHandler(new ClickHandler() {
441                         
442                         @Override
443                         public void onClick(ClickEvent event) {
444                                 new UploadFileCommand(null).execute();
445                         }
446                 });
447                 HorizontalPanel topPanel = new HorizontalPanel();
448                 topPanel.add(pagerTop);
449                 topPanel.add(uploadButtonTop);
450                 vp.add(topPanel);
451                 celltable.setWidth("100%");
452                 vp.add(celltable);
453                 pagerBottom = new GssSimplePager(GssSimplePager.TextLocation.CENTER);
454                 pagerBottom.setDisplay(celltable);
455                 HorizontalPanel bottomPanel = new HorizontalPanel();
456                 bottomPanel.add(pagerBottom);
457                 uploadButtonBottom=new Button("<span id='topMenu.file.upload'>" + AbstractImagePrototype.create(images.fileUpdate()).getHTML() + "&nbsp;Upload</span>");
458                 uploadButtonBottom.addClickHandler(new ClickHandler() {
459                         
460                         @Override
461                         public void onClick(ClickEvent event) {
462                                 new UploadFileCommand(null).execute();
463                         }
464                 });
465                 bottomPanel.add(uploadButtonBottom);
466                 vp.add(bottomPanel);
467                 vp.setCellWidth(celltable, "100%");
468                 
469                 initWidget(vp);
470                 pagerBottom.setVisible(false);
471                 pagerTop.setVisible(false);
472
473                 celltable.setStyleName("gss-List");
474                 selectionModel = new MultiSelectionModel<FileResource>(keyProvider);
475                 
476
477                  Handler selectionHandler = new SelectionChangeEvent.Handler() { 
478              @Override 
479              public void onSelectionChange(com.google.gwt.view.client.SelectionChangeEvent event) {
480                  if(getSelectedFiles().size()==1)
481                          GSS.get().setCurrentSelection(getSelectedFiles().get(0));
482                  else
483                          GSS.get().setCurrentSelection(getSelectedFiles());
484              }
485          };
486          selectionModel.addSelectionChangeHandler(selectionHandler);
487          
488                 celltable.setSelectionModel(selectionModel,GSSSelectionEventManager.<FileResource>createDefaultManager());
489                 celltable.setPageSize(GSS.VISIBLE_FILE_COUNT);
490                 
491                 //celltable.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
492                 Scheduler.get().scheduleIncremental(new RepeatingCommand() {
493
494                         @Override
495                         public boolean execute() {
496                                 return fetchRootFolder();
497                         }
498                 });
499                 sinkEvents(Event.ONCONTEXTMENU);
500                 sinkEvents(Event.ONMOUSEUP);
501                 sinkEvents(Event.ONMOUSEDOWN);
502                 sinkEvents(Event.ONCLICK);
503                 sinkEvents(Event.ONKEYDOWN);
504                 sinkEvents(Event.ONDBLCLICK);
505                 GSS.preventIESelection();
506         }
507         
508         //public native void fireClickEvent(Element element) /*-{
509           //  var evObj = $doc.createEvent('MouseEvents');
510             //evObj.initEvent('click', true, true);
511             //element.dispatchEvent(evObj);
512         //}-*/;
513         
514         
515         
516          public List<FileResource> getSelectedFiles() {
517          return new ArrayList<FileResource>(selectionModel.getSelectedSet());
518          }
519         
520          private void initDragOperation(DragAndDropColumn<?, ?> column) {
521
522                     // retrieve draggableOptions on the column
523                     DraggableOptions draggableOptions = column.getDraggableOptions();
524                     // use template to construct the helper. The content of the div will be set
525                     // after
526                     draggableOptions.setHelper($(Templates.INSTANCE.outerHelper().asString()));
527                     //draggableOptions.setZIndex(100);
528                     // opacity of the helper
529                     draggableOptions.setAppendTo("body"); 
530                     //draggableOptions.setOpacity((float) 0.8);
531                     draggableOptions.setContainment("document");
532                     // cursor to use during the drag operation
533                     draggableOptions.setCursor(Cursor.MOVE);
534                     // set the revert option
535                     draggableOptions.setRevert(RevertOption.ON_INVALID_DROP);
536                     // prevents dragging when user click on the category drop-down list
537                     draggableOptions.setCancel("select");
538                     
539                     
540                     draggableOptions.setOnBeforeDragStart(new DragFunction() {
541                                 
542                                 @Override
543                                 public void f(DragContext context) {
544                                          FileResource value = context.getDraggableData();
545                                      if(!selectionModel.isSelected(value)){
546                                         throw new StopDragException();
547                                       }
548                                         
549                                 }
550                         });
551                   }
552         
553          public void showContextMenu(Event event){
554                  menuShowing = new FileContextMenu(images, false, true);
555                         menuShowing=menuShowing.onEmptyEvent(event);
556          }
557         @Override
558         public void onBrowserEvent(Event event) {
559                 
560                 if (files == null || files.size() == 0) {
561                         if (DOM.eventGetType(event) == Event.ONCONTEXTMENU && getSelectedFiles().size() == 0) {
562                                 menuShowing = new FileContextMenu(images, false, true);
563                                 menuShowing=menuShowing.onEmptyEvent(event);
564                                 event.preventDefault();
565                                 event.cancelBubble(true);
566                         }
567                         return;
568                 }
569                 if (DOM.eventGetType(event) == Event.ONCONTEXTMENU && getSelectedFiles().size() != 0) {
570                         GWT.log("*****GOING TO SHOW CONTEXT MENU ****", null);
571                         menuShowing =  new FileContextMenu(images, false, false);
572                         menuShowing=menuShowing.onEvent(event);
573                         event.cancelBubble(true);
574                         event.preventDefault();
575                 } else if (DOM.eventGetType(event) == Event.ONCONTEXTMENU && getSelectedFiles().size() == 0) {
576                         menuShowing = new FileContextMenu(images, false, true);
577                         menuShowing=menuShowing.onEmptyEvent(event);
578                         event.cancelBubble(true);
579                         event.preventDefault();
580                 } else if (DOM.eventGetType(event) == Event.ONDBLCLICK)
581                         if (getSelectedFiles().size() == 1) {
582                                 GSS app = GSS.get();
583                                 FileResource file = getSelectedFiles().get(0);
584                                 String dateString = RestCommand.getDate();
585                                 String resource = file.getUri().substring(app.getApiPath().length() - 1, file.getUri().length());
586                                 String sig = app.getCurrentUserResource().getUsername() + " " +
587                                                 RestCommand.calculateSig("GET", dateString, resource,
588                                                 RestCommand.base64decode(app.getToken()));
589                                 Window.open(file.getUri() + "?Authorization=" + URL.encodeComponent(sig) + "&Date=" + URL.encodeComponent(dateString), "_blank", "");
590                                 event.preventDefault();
591                                 return;
592                         }
593                 super.onBrowserEvent(event);
594         }
595
596         /**
597          * Retrieve the root folder for the current user.
598          *
599          * @return true if the retrieval was successful
600          */
601         protected boolean fetchRootFolder() {
602                 UserResource user = GSS.get().getCurrentUserResource();
603                 if (user == null)
604                         return !DONE;
605                 // Update cache and clear selection.
606                 updateFileCache(true);
607                 return DONE;
608         }
609
610
611         /**
612          * Update the display of the file list.
613          */
614         void update(boolean sort) {
615                 int count = folderFileCount;
616                 int max = startIndex + GSS.VISIBLE_FILE_COUNT;
617                 if (max > count)
618                         max = count;
619                 folderTotalSize = 0;
620                 
621                 copyListAndContinue(files);
622                 for(FileResource f : files){
623                         folderTotalSize += f.getContentLength();
624                 }
625                 if (folderFileCount == 0) {
626                         showingStats = "no files";
627                 } else if (folderFileCount < GSS.VISIBLE_FILE_COUNT) {
628                         if (folderFileCount == 1)
629                                 showingStats = "1 file";
630                         else
631                                 showingStats = folderFileCount + " files";
632                         showingStats += " (" + FileResource.getFileSizeAsString(folderTotalSize) + ")";
633                 } else {
634                         showingStats = "" + (startIndex + 1) + " - " + max + " of " + count + " files" + " (" + FileResource.getFileSizeAsString(folderTotalSize) + ")";
635                 }
636                 showCellTable();
637                 updateCurrentlyShowingStats();
638
639         }
640
641         /**
642          * Return the proper icon based on the MIME type of the file.
643          *
644          * @param file
645          * @return the icon
646          */
647         private ImageResource getFileIcon(FileResource file) {
648                 String mimetype = file.getContentType();
649                 boolean shared = false;
650                 if(GSS.get().getTreeView().getSelection()!=null && (GSS.get().getTreeView().getSelection() instanceof OtherUserResource || GSS.get().getTreeView().getSelection() instanceof OthersFolderResource)){
651                         OtherUserResource otherUser = null;
652                         if(GSS.get().getTreeView().getSelection() instanceof OtherUserResource)
653                                 otherUser = (OtherUserResource) GSS.get().getTreeView().getSelection();
654                         else if (GSS.get().getTreeView().getSelection() instanceof OthersFolderResource){
655                                 otherUser = GSS.get().getTreeView().getOtherUserResourceOfOtherFolder((OthersFolderResource) GSS.get().getTreeView().getSelection());
656                         }
657                         if(otherUser ==null)
658                                 shared=false;
659                         else{
660                                 String uname = otherUser.getUsername();
661                                 if(uname==null)
662                                         uname = GSS.get().getTreeView().getOthers().getUsernameOfUri(otherUser.getUri());
663                                 if(uname != null)
664                                         shared = file.isShared();
665                         }
666                 }
667                 else
668                         shared = file.isShared();
669                 if (mimetype == null)
670                         return shared ? images.documentShared() : images.document();
671                 mimetype = mimetype.toLowerCase();
672                 if (mimetype.startsWith("application/pdf"))
673                         return shared ? images.pdfShared() : images.pdf();
674                 else if (mimetype.endsWith("excel"))
675                         return shared ? images.spreadsheetShared() : images.spreadsheet();
676                 else if (mimetype.endsWith("msword"))
677                         return shared ? images.wordprocessorShared() : images.wordprocessor();
678                 else if (mimetype.endsWith("powerpoint"))
679                         return shared ? images.presentationShared() : images.presentation();
680                 else if (mimetype.startsWith("application/zip") ||
681                                         mimetype.startsWith("application/gzip") ||
682                                         mimetype.startsWith("application/x-gzip") ||
683                                         mimetype.startsWith("application/x-tar") ||
684                                         mimetype.startsWith("application/x-gtar"))
685                         return shared ? images.zipShared() : images.zip();
686                 else if (mimetype.startsWith("text/html"))
687                         return shared ? images.htmlShared() : images.html();
688                 else if (mimetype.startsWith("text/plain"))
689                         return shared ? images.txtShared() : images.txt();
690                 else if (mimetype.startsWith("image/"))
691                         return shared ? images.imageShared() : images.image();
692                 else if (mimetype.startsWith("video/"))
693                         return shared ? images.videoShared() : images.video();
694                 else if (mimetype.startsWith("audio/"))
695                         return shared ? images.audioShared() : images.audio();
696                 return shared ? images.documentShared() : images.document();
697         }
698
699         /**
700          * Update status panel with currently showing file stats.
701          */
702         public void updateCurrentlyShowingStats() {
703                 GSS.get().getStatusPanel().updateCurrentlyShowing(showingStats);
704         }
705         
706         public void updateFileCache(boolean clearSelection){
707                 if(clearSelection){
708                         clearSelectedRows();
709                 }
710                 
711                 final RestResource folderItem = GSS.get().getTreeView().getSelection();
712                 // Validation.
713                 if (folderItem == null || folderItem.equals(GSS.get().getTreeView().getOthers())) {
714                         setFiles(new ArrayList<FileResource>());
715                         update(true);
716                         return;
717                 }
718                 else if (folderItem instanceof RestResourceWrapper) {
719                         setFiles(((RestResourceWrapper) folderItem).getResource().getFiles());
720                         update(true);
721                 }
722                 else if (folderItem instanceof SharedResource) {
723                         setFiles(((SharedResource) folderItem).getFiles());
724                         update(true);
725                 }
726                 else if (folderItem instanceof OtherUserResource) {
727                         setFiles(((OtherUserResource) folderItem).getFiles());
728                         update(true);
729                 }
730                 else if (folderItem instanceof TrashResource) {
731                         setFiles(((TrashResource) folderItem).getFiles());
732                         update(true);
733                 }
734         }
735         
736
737         /**
738          * Fill the file cache with data.
739          */
740         public void setFiles(final List<FileResource> _files) {
741                 if (_files.size() > 0 && ! (GSS.get().getTreeView().getSelection() instanceof TrashResource)) {
742                         files = new ArrayList<FileResource>();
743                         for (FileResource fres : _files)
744                                 if (!fres.isDeleted())
745                                         files.add(fres);
746                 }
747                 else
748                         files = _files;
749                 Collections.sort(files, new Comparator<FileResource>() {
750
751                         @Override
752                         public int compare(FileResource arg0, FileResource arg1) {
753                                 return arg0.getName().compareTo(arg1.getName());
754                         }
755
756                 });
757                 folderFileCount = files.size();
758                 
759                 nameHeader.setSorted(true);
760                 nameHeader.toggleReverseSort();
761                 for (SortableHeader otherHeader : allHeaders) {
762                   if (otherHeader != nameHeader) {
763                     otherHeader.setSorted(false);
764                     otherHeader.setReverseSort(true);
765                   }
766                 }
767                 //
768         }
769
770         
771
772         
773         /**
774          * Does the list contains the requested filename
775          *
776          * @param fileName
777          * @return true/false
778          */
779         public boolean contains(String fileName) {
780                 for (int i = 0; i < files.size(); i++)
781                         if (files.get(i).getName().equals(fileName))
782                                 return true;
783                 return false;
784         }
785
786         public void clearSelectedRows() {
787                 Iterator<FileResource> it = selectionModel.getSelectedSet().iterator();
788                 while(it.hasNext()){
789                         selectionModel.setSelected(it.next(),false);
790                 }
791         }
792         
793
794         /**
795          *
796          */
797         public void selectAllRows() {
798                 Iterator<FileResource> it = provider.getList().iterator();
799                 while(it.hasNext()){
800                         selectionModel.setSelected(it.next(),true);
801                 }
802
803
804         }
805
806         
807         private void sortFiles(final String sortingProperty, final boolean sortingType){
808                 Collections.sort(files, new Comparator<FileResource>() {
809
810             @Override
811             public int compare(FileResource arg0, FileResource arg1) {
812                     AbstractImagePrototype descPrototype = AbstractImagePrototype.create(images.desc());
813                     AbstractImagePrototype ascPrototype = AbstractImagePrototype.create(images.asc());
814                     if (sortingType){
815                             if (sortingProperty.equals("version")) {
816                                     return arg0.getVersion().compareTo(arg1.getVersion());
817                             } else if (sortingProperty.equals("owner")) {
818                                     return arg0.getOwner().compareTo(arg1.getOwner());
819                             } else if (sortingProperty.equals("date")) {
820                                     return arg0.getModificationDate().compareTo(arg1.getModificationDate());
821                             } else if (sortingProperty.equals("size")) {
822                                     return arg0.getContentLength().compareTo(arg1.getContentLength());
823                             } else if (sortingProperty.equals("name")) {
824                                     return arg0.getName().compareTo(arg1.getName());
825                             } else if (sortingProperty.equals("path")) {
826                                     return arg0.getUri().compareTo(arg1.getUri());
827                             } else {
828                                     return arg0.getName().compareTo(arg1.getName());
829                             }
830                     }
831                     else if (sortingProperty.equals("version")) {
832                             
833                             return arg1.getVersion().compareTo(arg0.getVersion());
834                     } else if (sortingProperty.equals("owner")) {
835                             
836                             return arg1.getOwner().compareTo(arg0.getOwner());
837                     } else if (sortingProperty.equals("date")) {
838                             
839                             return arg1.getModificationDate().compareTo(arg0.getModificationDate());
840                     } else if (sortingProperty.equals("size")) {
841                             
842                             return arg1.getContentLength().compareTo(arg0.getContentLength());
843                     } else if (sortingProperty.equals("name")) {
844                             
845                             return arg1.getName().compareTo(arg0.getName());
846                     } else if (sortingProperty.equals("path")) {
847                             
848                             return arg1.getUri().compareTo(arg0.getUri());
849                     } else {
850                             
851                             return arg1.getName().compareTo(arg0.getName());
852                     }
853             }
854
855                 });
856         }
857         
858         final class FileValueUpdater implements ValueUpdater<String>{
859                 private String property;
860                 private SortableHeader header;
861                 /**
862                  * 
863                  */
864                 public FileValueUpdater(SortableHeader header,String property) {
865                         this.property=property;
866                         this.header=header;
867                 }
868                 @Override
869                 public void update(String value) {
870                         header.setSorted(true);
871                         header.toggleReverseSort();
872
873                 for (SortableHeader otherHeader : allHeaders) {
874                   if (otherHeader != header) {
875                     otherHeader.setSorted(false);
876                     otherHeader.setReverseSort(true);
877                   }
878                 }
879                 celltable.redrawHeaders();
880                 sortFiles(property, header.getReverseSort());
881                 FileList.this.update(true);                     
882                 }
883                 
884         }
885         /**
886          * Creates a new ArrayList<FileResources> from the given files ArrayList 
887          * in order that the input files remain untouched 
888          * and continues to find user's full names of each FileResource element
889          * in the new ArrayList
890          *    
891          * @param filesInput
892          */
893         private void copyListAndContinue(List<FileResource> filesInput){
894                 List<FileResource> copiedFiles = new ArrayList<FileResource>();         
895                 for(FileResource file : filesInput) {
896                         copiedFiles.add(file);
897                 }
898                 handleFullNames(copiedFiles);
899         }
900         
901         /**
902          * Examines whether or not the user's full name exists in the 
903          * userFullNameMap in the GSS.java for every element of the input list.
904          * If the user's full name does not exist in the map then a command is being made.  
905          * 
906          * @param filesInput
907          */
908         private void handleFullNames(List<FileResource> filesInput){            
909                 if(filesInput.size() == 0){
910                         showCellTable();
911                         return;
912                 }               
913
914                 if(GSS.get().findUserFullName(filesInput.get(0).getOwner()) == null){
915                         findFullNameAndUpdate(filesInput);              
916                         return;
917                 }
918                                 
919                 if(filesInput.size() >= 1){
920                         filesInput.remove(filesInput.get(0));
921                         if(filesInput.isEmpty()){
922                                 showCellTable();                                
923                         }else{
924                                 handleFullNames(filesInput);
925                         }
926                 }               
927         }
928         
929         /**
930          * Makes a command to search for full name from a given username. 
931          * Only after the completion of the command the celltable is shown
932          * or the search for the next full name continues.
933          *  
934          * @param filesInput
935          */
936         private void findFullNameAndUpdate(final List<FileResource> filesInput){                
937                 String aUserName = filesInput.get(0).getOwner();
938                 String path = GSS.get().getApiPath() + "users/" + aUserName; 
939
940                 GetCommand<UserSearchResource> gg = new GetCommand<UserSearchResource>(UserSearchResource.class, path, false,null) {
941                         @Override
942                         public void onComplete() {
943                                 final UserSearchResource result = getResult();
944                                 for (UserResource user : result.getUsers()){
945                                         String username = user.getUsername();
946                                         String userFullName = user.getName();
947                                         GSS.get().putUserToMap(username, userFullName);
948                                         if(filesInput.size() >= 1){
949                                                 filesInput.remove(filesInput.get(0));
950                                                 if(filesInput.isEmpty()){
951                                                         showCellTable();
952                                                 }else{
953                                                         handleFullNames(filesInput);
954                                                 }                                                                                               
955                                         }                                                                       
956                                 }
957                         }
958                         @Override
959                         public void onError(Throwable t) {
960                                 GWT.log("", t);
961                                 GSS.get().displayError("Unable to fetch user's full name from the given username " + filesInput.get(0).getOwner());
962                                 if(filesInput.size() >= 1){
963                                         filesInput.remove(filesInput.get(0));
964                                         handleFullNames(filesInput);                                    
965                                 }
966                         }
967                 };
968                 DeferredCommand.addCommand(gg);
969         
970         }
971         /**
972          * Shows the files in the cellTable 
973          */
974
975         private void showCellTable(){
976                 if(files.size()>GSS.VISIBLE_FILE_COUNT){
977                         pagerBottom.setVisible(true);
978                         pagerTop.setVisible(true);
979                 }
980                 else{
981                         pagerTop.setVisible(false);
982                         pagerBottom.setVisible(false);
983                 }
984                 RestResource selectedItem = GSS.get().getTreeView().getSelection();
985                 boolean uploadVisible = !(selectedItem != null && (selectedItem instanceof TrashResource || selectedItem instanceof TrashFolderResource || selectedItem instanceof SharedResource || selectedItem instanceof OthersResource || selectedItem instanceof OtherUserResource));
986                 uploadButtonBottom.setVisible(uploadVisible&&files.size()>=GSS.VISIBLE_FILE_COUNT);
987                 uploadButtonTop.setVisible(uploadVisible&&files.size()>=GSS.VISIBLE_FILE_COUNT);
988                 provider.setList(files);
989                 
990                 provider.refresh();
991                 
992                 //celltable.redraw();
993                 celltable.redrawHeaders();              
994         }
995
996         
997 }