Statistics
| Branch: | Tag: | Revision:

root / src / gr / ebs / gss / web / client / SearchResults.java @ d0e0cb57

History | View | Annotate | Download (28.1 kB)

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.web.client;
20

    
21

    
22
import static com.google.gwt.query.client.GQuery.$;
23

    
24
import gr.ebs.gss.web.client.rest.GetCommand;
25
import gr.ebs.gss.web.client.rest.RestCommand;
26
import gr.ebs.gss.web.client.rest.RestException;
27
import gr.ebs.gss.web.client.rest.resource.FileResource;
28
import gr.ebs.gss.web.client.rest.resource.SearchResource;
29
import gr.ebs.gss.web.client.rest.resource.TrashResource;
30
import gr.ebs.gss.web.client.rest.resource.UserResource;
31
import gr.ebs.gss.web.client.rest.resource.UserSearchResource;
32
import gwtquery.plugins.draggable.client.DraggableOptions;
33
import gwtquery.plugins.draggable.client.StopDragException;
34
import gwtquery.plugins.draggable.client.DraggableOptions.DragFunction;
35
import gwtquery.plugins.draggable.client.DraggableOptions.RevertOption;
36
import gwtquery.plugins.draggable.client.events.DragContext;
37
import gwtquery.plugins.draggable.client.events.DragStartEvent;
38
import gwtquery.plugins.draggable.client.events.DragStopEvent;
39
import gwtquery.plugins.draggable.client.events.DragStartEvent.DragStartEventHandler;
40
import gwtquery.plugins.draggable.client.events.DragStopEvent.DragStopEventHandler;
41
import gwtquery.plugins.droppable.client.gwt.DragAndDropCellTable;
42
import gwtquery.plugins.droppable.client.gwt.DragAndDropColumn;
43

    
44
import java.util.ArrayList;
45
import java.util.Collections;
46
import java.util.Comparator;
47
import java.util.Iterator;
48
import java.util.List;
49

    
50
import com.google.gwt.cell.client.AbstractCell;
51
import com.google.gwt.cell.client.ImageResourceCell;
52
import com.google.gwt.cell.client.SafeHtmlCell;
53
import com.google.gwt.cell.client.TextCell;
54
import com.google.gwt.cell.client.ValueUpdater;
55
import com.google.gwt.core.client.GWT;
56
import com.google.gwt.core.client.Scheduler;
57
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
58
import com.google.gwt.dom.client.Style.Cursor;
59
import com.google.gwt.http.client.URL;
60
import com.google.gwt.i18n.client.DateTimeFormat;
61
import com.google.gwt.resources.client.ClientBundle;
62
import com.google.gwt.resources.client.ImageResource;
63
import com.google.gwt.safehtml.client.SafeHtmlTemplates;
64
import com.google.gwt.safehtml.shared.SafeHtml;
65
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
66
import com.google.gwt.user.cellview.client.CellTable;
67
import com.google.gwt.user.cellview.client.GssSimplePager;
68
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
69
import com.google.gwt.user.client.DOM;
70
import com.google.gwt.user.client.DeferredCommand;
71
import com.google.gwt.user.client.Event;
72
import com.google.gwt.user.client.Window;
73
import com.google.gwt.user.client.ui.AbstractImagePrototype;
74
import com.google.gwt.user.client.ui.Composite;
75
import com.google.gwt.user.client.ui.HTML;
76
import com.google.gwt.user.client.ui.VerticalPanel;
77
import com.google.gwt.view.client.AsyncDataProvider;
78
import com.google.gwt.view.client.HasData;
79
import com.google.gwt.view.client.MultiSelectionModel;
80
import com.google.gwt.view.client.ProvidesKey;
81
import com.google.gwt.view.client.SelectionChangeEvent;
82
import com.google.gwt.view.client.SelectionChangeEvent.Handler;
83

    
84
import javax.xml.transform.Templates;
85

    
86
/**
87
 * A composite that displays a list of search results for a particular query on
88
 * files.
89
 */
90
public class SearchResults extends Composite{
91
        private HTML searchResults = new HTML("Results for search:");
92
        private String lastQuery;
93
        SearchDataProvider provider = new SearchDataProvider();
94
        /**
95
         * Specifies that the images available for this composite will be the ones
96
         * available in FileContextMenu.
97
         */
98
        public interface Images extends ClientBundle,FileContextMenu.Images, CellTreeView.Images, FileList.Images {
99

    
100
                @Source("gr/ebs/gss/resources/blank.gif")
101
                ImageResource blank();
102

    
103
                @Source("gr/ebs/gss/resources/asc.png")
104
                ImageResource asc();
105

    
106
                @Source("gr/ebs/gss/resources/desc.png")
107
                ImageResource desc();
108
        }
109

    
110
        
111
        interface TableResources extends DragAndDropCellTable.Resources {
112
            @Source({CellTable.Style.DEFAULT_CSS, "GssCellTable.css"})
113
            TableStyle cellTableStyle();
114
          }
115
        
116
        /**
117
           * The styles applied to the table.
118
           */
119
          interface TableStyle extends CellTable.Style {
120
          }
121

    
122
        private String showingStats = "";
123

    
124
        private int startIndex = 0;
125

    
126
        /**
127
         * A constant that denotes the completion of an IncrementalCommand.
128
         */
129
        public static final boolean DONE = false;
130

    
131
        
132
        
133
        private final DateTimeFormat formatter = DateTimeFormat.getFormat("d/M/yyyy h:mm a");
134

    
135
        
136
        
137
        DragStopEventHandler dragStop = new DragStopEventHandler() {
138
                
139
                @Override
140
                public void onDragStop(DragStopEvent event) {
141
                        GWT.log("DRAG STOPPED");
142
                        
143
                }
144
        };
145
        
146
        private static class ContactCell extends AbstractCell<gr.ebs.gss.web.client.rest.resource.FileResource> {
147

    
148
            /**
149
             * The html of the image used for contacts.
150
             * 
151
             */
152
            private final String imageHtml;
153

    
154
            public ContactCell(ImageResource image) {
155
              this.imageHtml = AbstractImagePrototype.create(image).getHTML();
156
            }
157

    
158
            
159

    
160
                
161

    
162
            @Override
163
            public void render(Context context, FileResource value, SafeHtmlBuilder sb) {
164
              // Value can be null, so do a null check..
165
              if (value == null) {
166
                return;
167
              }
168

    
169
          sb.append(FileList.Templates.INSTANCE.rendelContactCell(imageHtml, value.getName(), value.getFileSizeAsString()));
170
            }
171

    
172

    
173
          }
174
        /**
175
         * Retrieve the celltable.
176
         *
177
         * @return the celltable
178
         */
179
        public DragAndDropCellTable<FileResource> getCelltable() {
180
                return celltable;
181
        }
182
        
183

    
184
        
185
        /**
186
         * The number of files in this folder.
187
         */
188
        int folderFileCount;
189

    
190
        /**
191
         * Total folder size
192
         */
193
        long folderTotalSize;
194

    
195
        /**
196
         * A cache of the files in the list.
197
         */
198
        private List<FileResource> files;
199

    
200
        /**
201
         * The widget's image bundle.
202
         */
203
        private final Images images;
204
        
205
        private FileContextMenu menuShowing;
206
        private DragAndDropCellTable<FileResource> celltable;
207
        private final MultiSelectionModel<FileResource> selectionModel;
208
        
209
        GssSimplePager pager;
210
        GssSimplePager pagerTop;
211
        /**
212
         * Construct the file list widget. This entails setting up the widget
213
         * layout, fetching the number of files in the current folder from the
214
         * server and filling the local file cache of displayed files with data from
215
         * the server, as well.
216
         *
217
         * @param _images
218
         */
219
        public SearchResults(Images _images) {
220
                images = _images;
221
                DragAndDropCellTable.Resources resources = GWT.create(TableResources.class);
222
                ProvidesKey<FileResource> keyProvider = new ProvidesKey<FileResource>(){
223

    
224
                        @Override
225
                        public Object getKey(FileResource item) {
226
                                return item.getUri();
227
                        }
228
                        
229
                };
230
                
231
                celltable = new DragAndDropCellTable<FileResource>(GSS.VISIBLE_FILE_COUNT,resources,keyProvider){
232
                        @Override
233
                        protected void onBrowserEvent2(Event event) {
234
                                /*if (DOM.eventGetType((Event) event) == Event.ONMOUSEDOWN && DOM.eventGetButton((Event) event) == NativeEvent.BUTTON_RIGHT){
235
                                        fireClickEvent((Element) event.getEventTarget().cast());                                        
236
                                }*/
237
                                super.onBrowserEvent2(event);
238
                        }
239
                };
240
                provider.addDataDisplay(celltable);
241
                celltable.addDragStopHandler(dragStop);
242
                celltable.addDragStartHandler(new DragStartEventHandler() {
243

    
244
                      public void onDragStart(DragStartEvent event) {
245
                        FileResource value = event.getDraggableData();
246
                        
247
                        com.google.gwt.dom.client.Element helper = event.getHelper();
248
                        SafeHtmlBuilder sb = new SafeHtmlBuilder();
249
                        sb.appendHtmlConstant("<b>");
250
                        DisplayHelper.log(value.getName());
251
                        if(getSelectedFiles().size()==1)
252
                                sb.appendEscaped(value.getName());
253
                        else
254
                                sb.appendEscaped(getSelectedFiles().size()+" files");
255
                        sb.appendHtmlConstant("</b>");
256
                        helper.setInnerHTML(sb.toSafeHtml().asString());
257

    
258
                      }
259
                    });
260
                DragAndDropColumn<FileResource, ImageResource> status = new DragAndDropColumn<FileResource, ImageResource>(new ImageResourceCell(){
261
                        @Override
262
                  public boolean handlesSelection() {
263
                            return false;
264
                          }
265
                }) {
266
                  @Override
267
                  public ImageResource getValue(FileResource entity) {
268
                    return getFileIcon(entity);
269
                  }
270
                  
271
               };
272
            celltable.addColumn(status,"");
273
            
274
            initDragOperation(status);
275
                final DragAndDropColumn<FileResource,SafeHtml> nameColumn = new DragAndDropColumn<FileResource,SafeHtml>(new SafeHtmlCell()) {
276

    
277

    
278
                        @Override
279
                        public SafeHtml getValue(FileResource object) {
280
                                SafeHtmlBuilder sb = new SafeHtmlBuilder();
281
                sb.append(FileList.Templates.INSTANCE.filenameSpan(object.getName()));
282
                                if (object.getContentType().endsWith("png") || object.getContentType().endsWith("gif") || object.getContentType().endsWith("jpeg") ){
283
                    sb.appendHtmlConstant("&nbsp;").append(FileList.Templates.INSTANCE.viewLink(GSS.get().getTopPanel().getFileMenu().getDownloadURL(object), object.getOwner() + " : " + object.getPath() + object.getName()));
284
                                }
285

    
286
                                return sb.toSafeHtml();
287
                        }
288
                        
289
                };
290
                initDragOperation(nameColumn);
291
                celltable.addColumn(nameColumn,"Name");
292
                
293
            DragAndDropColumn<FileResource,String> aColumn;
294
                celltable.addColumn(aColumn=new DragAndDropColumn<FileResource,String>(new TextCell()) {
295
                        @Override
296
                        public String getValue(FileResource object) {
297
                                return GSS.get().findUserFullName(object.getOwner());
298
                        }                        
299
                },"Owner");
300
                initDragOperation(aColumn);
301
                
302
                celltable.addColumn(aColumn=new DragAndDropColumn<FileResource,String>(new TextCell()) {
303
                        @Override
304
                        public String getValue(FileResource object) {
305
                                if(object.isDeleted())
306
                                        return object.getPath()+" (In Trash)";
307
                                return object.getPath();
308
                        }                        
309
                },"Path");
310
                initDragOperation(aColumn);
311
                
312
                
313
                        
314
                celltable.addColumn(aColumn=new DragAndDropColumn<FileResource,String>(new TextCell()) {
315
                        @Override
316
                        public String getValue(FileResource object) {
317
                                return object.getVersion().toString();
318
                        }                        
319
                },"Version");
320
                initDragOperation(aColumn);
321
                
322
                
323
                celltable.addColumn(aColumn=new DragAndDropColumn<FileResource,String>(new TextCell()) {
324
                        @Override
325
                        public String getValue(FileResource object) {
326
                                // TODO Auto-generated method stub
327
                                return object.getFileSizeAsString();
328
                        }                        
329
                },"Size");
330
                initDragOperation(aColumn);
331
                        
332
                celltable.addColumn(aColumn=new DragAndDropColumn<FileResource,String>(new TextCell()) {
333
                        @Override
334
                        public String getValue(FileResource object) {
335
                                return formatter.format(object.getModificationDate());
336
                        }                        
337
                },"Last Modified");
338
                
339
                
340
               
341

    
342
                VerticalPanel vp = new VerticalPanel();
343
                vp.setWidth("100%");
344
                celltable.setWidth("100%");
345
                vp.add(searchResults);
346
                searchResults.addStyleName("gss-searchLabel");
347
                pagerTop = new GssSimplePager(GssSimplePager.TextLocation.CENTER);
348
                pagerTop.setDisplay(celltable);
349
                vp.add(pagerTop);
350
                vp.add(celltable);
351
                pager = new GssSimplePager(GssSimplePager.TextLocation.CENTER);
352
                pager.setDisplay(celltable);
353
                //celltable.setPageSize(2);
354
                
355
                vp.add(pager);
356
                vp.setCellWidth(celltable, "100%");
357
                
358
                initWidget(vp);
359
                
360
                //initWidget(celltable);
361
                celltable.setStyleName("gss-List");
362
                selectionModel = new MultiSelectionModel<FileResource>();
363
                
364

    
365
                 Handler selectionHandler = new SelectionChangeEvent.Handler() { 
366
             @Override 
367
             public void onSelectionChange(com.google.gwt.view.client.SelectionChangeEvent event) {
368
                     if(getSelectedFiles().size()==1)
369
                             GSS.get().setCurrentSelection(getSelectedFiles().get(0));
370
                     else
371
                             GSS.get().setCurrentSelection(getSelectedFiles());
372
                                 //contextMenu.setFiles(getSelectedFiles());
373
             }
374
         };
375
         selectionModel.addSelectionChangeHandler(selectionHandler);
376
         
377
                celltable.setSelectionModel(selectionModel,GSSSelectionEventManager.<FileResource>createDefaultManager());
378
                celltable.setPageSize(GSS.VISIBLE_FILE_COUNT);
379
                celltable.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
380
                Scheduler.get().scheduleIncremental(new RepeatingCommand() {
381

    
382
                        @Override
383
                        public boolean execute() {
384
                                return fetchRootFolder();
385
                        }
386
                });
387
                sinkEvents(Event.ONCONTEXTMENU);
388
                sinkEvents(Event.ONMOUSEUP);
389
                sinkEvents(Event.ONMOUSEDOWN);
390
                sinkEvents(Event.ONCLICK);
391
                sinkEvents(Event.ONKEYDOWN);
392
                sinkEvents(Event.ONDBLCLICK);
393
                GSS.preventIESelection();
394
        }
395
        
396
        //public native void fireClickEvent(Element element) /*-{
397
          //  var evObj = $doc.createEvent('MouseEvents');
398
            //evObj.initEvent('click', true, true);
399
            //element.dispatchEvent(evObj);
400
          //}-*/;
401

    
402
         public List<FileResource> getSelectedFiles() {
403
         return new ArrayList<FileResource>(selectionModel.getSelectedSet());
404
         }
405
        
406
         private void initDragOperation(DragAndDropColumn<?, ?> column) {
407

    
408
                    // retrieve draggableOptions on the column
409
                    DraggableOptions draggableOptions = column.getDraggableOptions();
410
                    // use template to construct the helper. The content of the div will be set
411
                    // after
412
                    draggableOptions.setHelper($(FileList.Templates.INSTANCE.outerHelper().asString()));
413
                    //draggableOptions.setZIndex(100);
414
                    // opacity of the helper
415
                    draggableOptions.setAppendTo("body"); 
416
                    //draggableOptions.setOpacity((float) 0.8);
417
                    draggableOptions.setContainment("document");
418
                    // cursor to use during the drag operation
419
                    draggableOptions.setCursor(Cursor.MOVE);
420
                    // set the revert option
421
                    draggableOptions.setRevert(RevertOption.ON_INVALID_DROP);
422
                    // prevents dragging when user click on the category drop-down list
423
                    draggableOptions.setCancel("select");
424
                    
425
                    draggableOptions.setOnBeforeDragStart(new DragFunction() {
426
                                
427
                                @Override
428
                                public void f(DragContext context) {
429
                                         FileResource value = context.getDraggableData();
430
                                     if(!selectionModel.isSelected(value)){
431
                                               throw new StopDragException();
432
                                      }
433
                                        
434
                                }
435
                        });
436
                  }
437
        
438
         public void showContextMenu(Event event){
439
                 menuShowing = new FileContextMenu(images, false, true);
440
                        menuShowing=menuShowing.onEmptyEvent(event);
441
         }
442
        @Override
443
        public void onBrowserEvent(Event event) {
444
                
445
                if (files == null || files.size() == 0) {
446
                        if (DOM.eventGetType(event) == Event.ONCONTEXTMENU && getSelectedFiles().size() == 0) {
447
                                menuShowing = new FileContextMenu(images, false, true);
448
                                menuShowing=menuShowing.onEmptyEvent(event);
449
                                event.preventDefault();
450
                                event.cancelBubble(true);
451
                        }
452
                        return;
453
                }
454
                if (DOM.eventGetType(event) == Event.ONCONTEXTMENU && getSelectedFiles().size() != 0) {
455
                        GWT.log("*****GOING TO SHOW CONTEXT MENU ****", null);
456
                        menuShowing =  new FileContextMenu(images, false, false);
457
                        menuShowing=menuShowing.onEvent(event);
458
                        event.cancelBubble(true);
459
                        event.preventDefault();
460
                } else if (DOM.eventGetType(event) == Event.ONCONTEXTMENU && getSelectedFiles().size() == 0) {
461
                        menuShowing = new FileContextMenu(images, false, true);
462
                        menuShowing=menuShowing.onEmptyEvent(event);
463
                        event.cancelBubble(true);
464
                        event.preventDefault();
465
                } else if (DOM.eventGetType(event) == Event.ONDBLCLICK)
466
                        if (getSelectedFiles().size() == 1) {
467
                                GSS app = GSS.get();
468
                                FileResource file = getSelectedFiles().get(0);
469
                                String dateString = RestCommand.getDate();
470
                                String resource = file.getUri().substring(app.getApiPath().length() - 1, file.getUri().length());
471
                                String sig = app.getCurrentUserResource().getUsername() + " " +
472
                                                RestCommand.calculateSig("GET", dateString, resource,
473
                                                RestCommand.base64decode(app.getToken()));
474
                                if(!file.isDeleted()){
475
                                        Window.open(file.getUri() + "?Authorization=" + URL.encodeComponent(sig) + "&Date=" + URL.encodeComponent(dateString), "_blank", "");
476
                                }
477
                                event.preventDefault();
478
                                return;
479
                        }
480
                super.onBrowserEvent(event);
481
        }
482

    
483
        /**
484
         * Retrieve the root folder for the current user.
485
         *
486
         * @return true if the retrieval was successful
487
         */
488
        protected boolean fetchRootFolder() {
489
                UserResource user = GSS.get().getCurrentUserResource();
490
                if (user == null)
491
                        return !DONE;
492
                // Update cache and clear selection.
493
                updateFileCache(null);
494
                return DONE;
495
        }
496

    
497

    
498
        /**
499
         * Update the display of the file list.
500
         */
501
        void update(boolean sort) {
502
                int count = folderFileCount;
503
                int max = startIndex + GSS.VISIBLE_FILE_COUNT;
504
                if (max > count)
505
                        max = count;
506
                folderTotalSize = 0;
507
                
508
                copyListAndContinue(files);
509
                for(FileResource f : files){
510
                        folderTotalSize += f.getContentLength();
511
                }
512
                if (folderFileCount == 0) {
513
                        showingStats = "no files";
514
                } else if (folderFileCount < GSS.VISIBLE_FILE_COUNT) {
515
                        if (folderFileCount == 1)
516
                                showingStats = "1 file";
517
                        else
518
                                showingStats = folderFileCount + " files";
519
                        showingStats += " (" + FileResource.getFileSizeAsString(folderTotalSize) + ")";
520
                } else {
521
                        showingStats = "" + (startIndex + 1) + " - " + max + " of " + count + " files" + " (" + FileResource.getFileSizeAsString(folderTotalSize) + ")";
522
                }
523
                updateCurrentlyShowingStats();
524

    
525
        }
526

    
527
        /**
528
         * Return the proper icon based on the MIME type of the file.
529
         *
530
         * @param file
531
         * @return the icon
532
         */
533
        private ImageResource getFileIcon(FileResource file) {
534
                String mimetype = file.getContentType();
535
                boolean shared = file.isShared();
536
                if (mimetype == null)
537
                        return shared ? images.documentShared() : images.document();
538
                mimetype = mimetype.toLowerCase();
539
                if (mimetype.startsWith("application/pdf"))
540
                        return shared ? images.pdfShared() : images.pdf();
541
                else if (mimetype.endsWith("excel"))
542
                        return shared ? images.spreadsheetShared() : images.spreadsheet();
543
                else if (mimetype.endsWith("msword"))
544
                        return shared ? images.wordprocessorShared() : images.wordprocessor();
545
                else if (mimetype.endsWith("powerpoint"))
546
                        return shared ? images.presentationShared() : images.presentation();
547
                else if (mimetype.startsWith("application/zip") ||
548
                                        mimetype.startsWith("application/gzip") ||
549
                                        mimetype.startsWith("application/x-gzip") ||
550
                                        mimetype.startsWith("application/x-tar") ||
551
                                        mimetype.startsWith("application/x-gtar"))
552
                        return shared ? images.zipShared() : images.zip();
553
                else if (mimetype.startsWith("text/html"))
554
                        return shared ? images.htmlShared() : images.html();
555
                else if (mimetype.startsWith("text/plain"))
556
                        return shared ? images.txtShared() : images.txt();
557
                else if (mimetype.startsWith("image/"))
558
                        return shared ? images.imageShared() : images.image();
559
                else if (mimetype.startsWith("video/"))
560
                        return shared ? images.videoShared() : images.video();
561
                else if (mimetype.startsWith("audio/"))
562
                        return shared ? images.audioShared() : images.audio();
563
                return shared ? images.documentShared() : images.document();
564
        }
565

    
566
        /**
567
         * Update status panel with currently showing file stats.
568
         */
569
        public void updateCurrentlyShowingStats() {
570
                GSS.get().getStatusPanel().updateCurrentlyShowing(showingStats);
571
        }
572

    
573
        public void updateFileCache(String query) {
574
                final GSS app = GSS.get();
575
                setLastQuery(query);
576
                clearSelectedRows();
577
                //clearLabels();
578
                startIndex = 0;
579
                app.showLoadingIndicator();
580
                if (query == null || query.trim().equals("")) {
581
                        searchResults.setHTML("You must specify a query.");
582
                        setFiles(new ArrayList());
583
                        update(true);
584
                        app.hideLoadingIndicator();
585
                } else if (!GSS.isValidResourceName(query)) {
586
                        searchResults.setHTML("The query was invalid. Try to use words that appear in the file's name, contents or tags.");
587
                        setFiles(new ArrayList());
588
                        update(true);
589
                        app.hideLoadingIndicator();
590
                } else{
591
                        searchResults.setHTML("Search results for " + query);
592
                        showCellTable(true);
593
                        
594
                }
595
        }
596

    
597
        /**
598
         * Fill the file cache with data.
599
         */
600
        public void setFiles(final List<FileResource> _files) {
601
                if (_files.size() > 0 && ! (GSS.get().getTreeView().getSelection() instanceof TrashResource)) {
602
                        files = new ArrayList<FileResource>();
603
                        for (FileResource fres : _files)
604
                                files.add(fres);
605
                }
606
                else
607
                        files = _files;
608
                Collections.sort(files, new Comparator<FileResource>() {
609

    
610
                        @Override
611
                        public int compare(FileResource arg0, FileResource arg1) {
612
                                return arg0.getName().compareTo(arg1.getName());
613
                        }
614

    
615
                });
616
                folderFileCount = files.size();
617
        }
618

    
619
        
620

    
621
        
622
        /**
623
         * Does the list contains the requested filename
624
         *
625
         * @param fileName
626
         * @return true/false
627
         */
628
        public boolean contains(String fileName) {
629
                for (int i = 0; i < files.size(); i++)
630
                        if (files.get(i).getName().equals(fileName))
631
                                return true;
632
                return false;
633
        }
634

    
635
        public void clearSelectedRows() {
636
                Iterator<FileResource> it = selectionModel.getSelectedSet().iterator();
637
                while(it.hasNext()){
638
                        selectionModel.setSelected(it.next(),false);
639
                }
640
        }
641

    
642
        /**
643
         *
644
         */
645
        public void selectAllRows() {
646
                Iterator<FileResource> it = selectionModel.getSelectedSet().iterator();
647
                while(it.hasNext()){
648
                        selectionModel.setSelected(it.next(),true);
649
                }
650

    
651

    
652
        }
653

    
654
        
655
        private void sortFiles(final String sortingProperty, final boolean sortingType){
656
                Collections.sort(files, new Comparator<FileResource>() {
657

    
658
            @Override
659
            public int compare(FileResource arg0, FileResource arg1) {
660
                    AbstractImagePrototype descPrototype = AbstractImagePrototype.create(images.desc());
661
                    AbstractImagePrototype ascPrototype = AbstractImagePrototype.create(images.asc());
662
                    if (sortingType){
663
                            if (sortingProperty.equals("version")) {
664
                                    return arg0.getVersion().compareTo(arg1.getVersion());
665
                            } else if (sortingProperty.equals("owner")) {
666
                                    return arg0.getOwner().compareTo(arg1.getOwner());
667
                            } else if (sortingProperty.equals("date")) {
668
                                    return arg0.getModificationDate().compareTo(arg1.getModificationDate());
669
                            } else if (sortingProperty.equals("size")) {
670
                                    return arg0.getContentLength().compareTo(arg1.getContentLength());
671
                            } else if (sortingProperty.equals("name")) {
672
                                    return arg0.getName().compareTo(arg1.getName());
673
                            } else if (sortingProperty.equals("path")) {
674
                                    return arg0.getUri().compareTo(arg1.getUri());
675
                            } else {
676
                                    return arg0.getName().compareTo(arg1.getName());
677
                            }
678
                    }
679
                    else if (sortingProperty.equals("version")) {
680
                            
681
                            return arg1.getVersion().compareTo(arg0.getVersion());
682
                    } else if (sortingProperty.equals("owner")) {
683
                            
684
                            return arg1.getOwner().compareTo(arg0.getOwner());
685
                    } else if (sortingProperty.equals("date")) {
686
                            
687
                            return arg1.getModificationDate().compareTo(arg0.getModificationDate());
688
                    } else if (sortingProperty.equals("size")) {
689
                            
690
                            return arg1.getContentLength().compareTo(arg0.getContentLength());
691
                    } else if (sortingProperty.equals("name")) {
692
                            
693
                            return arg1.getName().compareTo(arg0.getName());
694
                    } else if (sortingProperty.equals("path")) {
695
                            
696
                            return arg1.getUri().compareTo(arg0.getUri());
697
                    } else {
698
                            
699
                            return arg1.getName().compareTo(arg0.getName());
700
                    }
701
            }
702

    
703
                });
704
        }
705
        
706
        
707
        /**
708
         * Creates a new ArrayList<FileResources> from the given files ArrayList 
709
         * in order that the input files remain untouched 
710
         * and continues to find user's full names of each FileResource element
711
         * in the new ArrayList
712
         *    
713
         * @param filesInput
714
         */
715
        private void copyListAndContinue(List<FileResource> filesInput){
716
                List<FileResource> copiedFiles = new ArrayList<FileResource>();                
717
                for(FileResource file : filesInput) {
718
                        copiedFiles.add(file);
719
                }
720
                handleFullNames(copiedFiles);
721
        }
722
        
723
        /**
724
         * Examines whether or not the user's full name exists in the 
725
         * userFullNameMap in the GSS.java for every element of the input list.
726
         * If the user's full name does not exist in the map then a command is being made.  
727
         * 
728
         * @param filesInput
729
         */
730
        private void handleFullNames(List<FileResource> filesInput){                
731
                if(filesInput.size() == 0){
732
                        showCellTable(false);
733
                        return;
734
                }                
735

    
736
                if(GSS.get().findUserFullName(filesInput.get(0).getOwner()) == null){
737
                        findFullNameAndUpdate(filesInput);                
738
                        return;
739
                }
740
                                
741
                if(filesInput.size() >= 1){
742
                        filesInput.remove(filesInput.get(0));
743
                        if(filesInput.isEmpty()){
744
                                showCellTable(false);                                
745
                        }else{
746
                                handleFullNames(filesInput);
747
                        }
748
                }                
749
        }
750
        
751
        /**
752
         * Makes a command to search for full name from a given username. 
753
         * Only after the completion of the command the celltable is shown
754
         * or the search for the next full name continues.
755
         *  
756
         * @param filesInput
757
         */
758
        private void findFullNameAndUpdate(final List<FileResource> filesInput){                
759
                String aUserName = filesInput.get(0).getOwner();
760
                String path = GSS.get().getApiPath() + "users/" + aUserName; 
761

    
762
                GetCommand<UserSearchResource> gg = new GetCommand<UserSearchResource>(UserSearchResource.class, path, false,null) {
763
                        @Override
764
                        public void onComplete() {
765
                                final UserSearchResource result = getResult();
766
                                for (UserResource user : result.getUsers()){
767
                                        String username = user.getUsername();
768
                                        String userFullName = user.getName();
769
                                        GSS.get().putUserToMap(username, userFullName);
770
                                        if(filesInput.size() >= 1){
771
                                                filesInput.remove(filesInput.get(0));
772
                                                if(filesInput.isEmpty()){
773
                                                        showCellTable(false);
774
                                                }else{
775
                                                        handleFullNames(filesInput);
776
                                                }                                                                                                
777
                                        }                                                                        
778
                                }
779
                        }
780
                        @Override
781
                        public void onError(Throwable t) {
782
                                GWT.log("", t);
783
                                GSS.get().displayError("Unable to fetch user's full name from the given username " + filesInput.get(0).getOwner());
784
                                if(filesInput.size() >= 1){
785
                                        filesInput.remove(filesInput.get(0));
786
                                        handleFullNames(filesInput);                                        
787
                                }
788
                        }
789
                };
790
                DeferredCommand.addCommand(gg);
791
        
792
        }
793
        /**
794
         * Shows the files in the cellTable 
795
         */
796

    
797
        private void showCellTable(boolean update){
798
                if(celltable.getRowCount()>GSS.VISIBLE_FILE_COUNT){
799
                        pager.setVisible(true);
800
                        pagerTop.setVisible(true);
801
                }
802
                else{
803
                        pager.setVisible(false);
804
                        pagerTop.setVisible(false);
805
                }
806
                if(update)
807
                        provider.onRangeChanged(celltable);
808
                celltable.redrawHeaders();                
809
        }
810
        
811
        
812
        /**
813
         * Retrieve the lastQuery.
814
         *
815
         * @return the lastQuery
816
         */
817
        public String getLastQuery() {
818
                return lastQuery;
819
        }
820
        
821
        
822
        /**
823
         * Modify the lastQuery.
824
         *
825
         * @param lastQuery the lastQuery to set
826
         */
827
        public void setLastQuery(String lastQuery) {
828
                this.lastQuery = lastQuery;
829
        }
830
        
831
        class SearchDataProvider extends AsyncDataProvider<FileResource>{
832

    
833
                @Override
834
                protected void onRangeChanged(final HasData<FileResource> display) {
835
                        final int start = display.getVisibleRange().getStart();
836
                        final GSS app = GSS.get();
837
                        if(getLastQuery()==null||getLastQuery().equals("")){
838
                                display.setRowCount(0,true);
839
                                return;
840
                                
841
                        }
842
                        GetCommand<SearchResource> eg = new GetCommand<SearchResource>(SearchResource.class,
843
                                                app.getApiPath() + "search/" +URL.encodeComponent(getLastQuery())+"?start="+start, null) {
844

    
845
                                @Override
846
                                public void onComplete() {
847
                                        SearchResource s = getResult();
848
                                        display.setRowCount(s.getSize(),true);
849
                                        display.setRowData(start, s.getFiles());
850
                                        setFiles(s.getFiles());
851
                                        update(true);
852
                                        
853
                                }
854

    
855
                                @Override
856
                                public void onError(Throwable t) {
857
                                        if(t instanceof RestException)
858
                                                app.displayError("Unable to perform search:"+((RestException)t).getHttpStatusText());
859
                                        else
860
                                                app.displayError("System error performing search:"+t.getMessage());
861
                                        GWT.log("",t);
862
                                        updateFileCache("");
863
                                }
864

    
865
                        };
866
                        DeferredCommand.addCommand(eg);
867
                        
868
                }
869
                
870
        }
871

    
872
}