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