Statistics
| Branch: | Tag: | Revision:

root / src / org / gss_project / gss / web / client / SearchResults.java @ 1206:292dec4eae08

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

    
21

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

    
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.RestException;
27
import org.gss_project.gss.web.client.rest.resource.FileResource;
28
import org.gss_project.gss.web.client.rest.resource.SearchResource;
29
import org.gss_project.gss.web.client.rest.resource.TrashResource;
30
import org.gss_project.gss.web.client.rest.resource.UserResource;
31
import org.gss_project.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.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.shared.SafeHtml;
63
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
64
import com.google.gwt.user.cellview.client.CellTable;
65
import com.google.gwt.user.cellview.client.GssSimplePager;
66
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
67
import com.google.gwt.user.client.DOM;
68
import com.google.gwt.user.client.DeferredCommand;
69
import com.google.gwt.user.client.Event;
70
import com.google.gwt.user.client.Window;
71
import com.google.gwt.user.client.ui.AbstractImagePrototype;
72
import com.google.gwt.user.client.ui.Composite;
73
import com.google.gwt.user.client.ui.HTML;
74
import com.google.gwt.user.client.ui.VerticalPanel;
75
import com.google.gwt.view.client.AsyncDataProvider;
76
import com.google.gwt.view.client.HasData;
77
import com.google.gwt.view.client.MultiSelectionModel;
78
import com.google.gwt.view.client.ProvidesKey;
79
import com.google.gwt.view.client.SelectionChangeEvent;
80
import com.google.gwt.view.client.SelectionChangeEvent.Handler;
81

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

    
96
                @Source("org/gss_project/gss/resources/blank.gif")
97
                ImageResource blank();
98

    
99
                @Source("org/gss_project/gss/resources/asc.png")
100
                ImageResource asc();
101

    
102
                @Source("org/gss_project/gss/resources/desc.png")
103
                ImageResource desc();
104
        }
105

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

    
118
        private String showingStats = "";
119

    
120
        private int startIndex = 0;
121

    
122
        /**
123
         * A constant that denotes the completion of an IncrementalCommand.
124
         */
125
        public static final boolean DONE = false;
126

    
127
        
128
        
129
        private final DateTimeFormat formatter = DateTimeFormat.getFormat("d/M/yyyy h:mm a");
130

    
131
        
132
        
133
        DragStopEventHandler dragStop = new DragStopEventHandler() {
134
                
135
                @Override
136
                public void onDragStop(DragStopEvent event) {
137
                        GWT.log("DRAG STOPPED");
138
                        
139
                }
140
        };
141
        
142
        private static class ContactCell extends AbstractCell<org.gss_project.gss.web.client.rest.resource.FileResource> {
143

    
144
            /**
145
             * The html of the image used for contacts.
146
             * 
147
             */
148
            private final String imageHtml;
149

    
150
            public ContactCell(ImageResource image) {
151
              this.imageHtml = AbstractImagePrototype.create(image).getHTML();
152
            }
153

    
154
            
155

    
156
                
157

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

    
165
          sb.append(FileList.Templates.INSTANCE.rendelContactCell(imageHtml, value.getName(), value.getFileSizeAsString()));
166
            }
167

    
168

    
169
          }
170
        /**
171
         * Retrieve the celltable.
172
         *
173
         * @return the celltable
174
         */
175
        public DragAndDropCellTable<FileResource> getCelltable() {
176
                return celltable;
177
        }
178
        
179

    
180
        
181
        /**
182
         * The number of files in this folder.
183
         */
184
        int folderFileCount;
185

    
186
        /**
187
         * Total folder size
188
         */
189
        long folderTotalSize;
190

    
191
        /**
192
         * A cache of the files in the list.
193
         */
194
        private List<FileResource> files;
195

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

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

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

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

    
273

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

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

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

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

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

    
398
         public List<FileResource> getSelectedFiles() {
399
         return new ArrayList<FileResource>(selectionModel.getSelectedSet());
400
         }
401
        
402
         private void initDragOperation(DragAndDropColumn<?, ?> column) {
403

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

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

    
493

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

    
521
        }
522

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

    
562
        /**
563
         * Update status panel with currently showing file stats.
564
         */
565
        public void updateCurrentlyShowingStats() {
566
                GSS.get().getStatusPanel().updateCurrentlyShowing(showingStats);
567
        }
568

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

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

    
606
                        @Override
607
                        public int compare(FileResource arg0, FileResource arg1) {
608
                                return arg0.getName().compareTo(arg1.getName());
609
                        }
610

    
611
                });
612
                folderFileCount = files.size();
613
        }
614

    
615
        
616

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

    
631
        public void clearSelectedRows() {
632
                Iterator<FileResource> it = selectionModel.getSelectedSet().iterator();
633
                while(it.hasNext()){
634
                        selectionModel.setSelected(it.next(),false);
635
                }
636
        }
637

    
638
        /**
639
         *
640
         */
641
        public void selectAllRows() {
642
                Iterator<FileResource> it = selectionModel.getSelectedSet().iterator();
643
                while(it.hasNext()){
644
                        selectionModel.setSelected(it.next(),true);
645
                }
646

    
647

    
648
        }
649

    
650
        
651
        private void sortFiles(final String sortingProperty, final boolean sortingType){
652
                Collections.sort(files, new Comparator<FileResource>() {
653

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

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

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

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

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

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

    
841
                                @Override
842
                                public void onComplete() {
843
                                        SearchResource s = getResult();
844
                                        display.setRowCount(s.getSize(),true);
845
                                        display.setRowData(start, s.getFiles());
846
                                        setFiles(s.getFiles());
847
                                        update(true);
848
                                        
849
                                }
850

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

    
861
                        };
862
                        DeferredCommand.addCommand(eg);
863
                        
864
                }
865
                
866
        }
867

    
868
}