Statistics
| Branch: | Tag: | Revision:

root / src / gr / ebs / gss / client / SearchResults.java @ 76f91765

History | View | Annotate | Download (30.4 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.client;
20

    
21

    
22
import static com.google.gwt.query.client.GQuery.$;
23
import gr.ebs.gss.client.FileList.FileValueUpdater;
24
import gr.ebs.gss.client.FileList.Images;
25
import gr.ebs.gss.client.FileList.TableResources;
26
import gr.ebs.gss.client.FileList.TableStyle;
27
import gr.ebs.gss.client.FileList.Templates;
28
import gr.ebs.gss.client.rest.GetCommand;
29
import gr.ebs.gss.client.rest.RestCommand;
30
import gr.ebs.gss.client.rest.RestException;
31
import gr.ebs.gss.client.rest.resource.FileResource;
32
import gr.ebs.gss.client.rest.resource.RestResource;
33
import gr.ebs.gss.client.rest.resource.RestResourceWrapper;
34
import gr.ebs.gss.client.rest.resource.SearchResource;
35
import gr.ebs.gss.client.rest.resource.SharedResource;
36
import gr.ebs.gss.client.rest.resource.TrashResource;
37
import gr.ebs.gss.client.rest.resource.UserResource;
38
import gr.ebs.gss.client.rest.resource.UserSearchResource;
39
import gwtquery.plugins.draggable.client.DraggableOptions;
40
import gwtquery.plugins.draggable.client.StopDragException;
41
import gwtquery.plugins.draggable.client.DraggableOptions.DragFunction;
42
import gwtquery.plugins.draggable.client.DraggableOptions.RevertOption;
43
import gwtquery.plugins.draggable.client.events.DragContext;
44
import gwtquery.plugins.draggable.client.events.DragStartEvent;
45
import gwtquery.plugins.draggable.client.events.DragStopEvent;
46
import gwtquery.plugins.draggable.client.events.DragStartEvent.DragStartEventHandler;
47
import gwtquery.plugins.draggable.client.events.DragStopEvent.DragStopEventHandler;
48
import gwtquery.plugins.droppable.client.gwt.DragAndDropCellTable;
49
import gwtquery.plugins.droppable.client.gwt.DragAndDropColumn;
50

    
51
import java.util.ArrayList;
52
import java.util.Collections;
53
import java.util.Comparator;
54
import java.util.Iterator;
55
import java.util.List;
56

    
57
import org.hibernate.mapping.Array;
58

    
59
import com.google.gwt.cell.client.AbstractCell;
60
import com.google.gwt.cell.client.ImageResourceCell;
61
import com.google.gwt.cell.client.SafeHtmlCell;
62
import com.google.gwt.cell.client.TextCell;
63
import com.google.gwt.cell.client.ValueUpdater;
64
import com.google.gwt.cell.client.Cell.Context;
65
import com.google.gwt.core.client.GWT;
66
import com.google.gwt.core.client.Scheduler;
67
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
68
import com.google.gwt.dom.client.NativeEvent;
69
import com.google.gwt.dom.client.Style.Cursor;
70
import com.google.gwt.event.dom.client.ClickEvent;
71
import com.google.gwt.event.dom.client.ClickHandler;
72
import com.google.gwt.http.client.URL;
73
import com.google.gwt.i18n.client.DateTimeFormat;
74
import com.google.gwt.resources.client.ClientBundle;
75
import com.google.gwt.resources.client.ImageResource;
76
import com.google.gwt.resources.client.ClientBundle.Source;
77
import com.google.gwt.safehtml.client.SafeHtmlTemplates;
78
import com.google.gwt.safehtml.client.SafeHtmlTemplates.Template;
79
import com.google.gwt.safehtml.shared.SafeHtml;
80
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
81
import com.google.gwt.user.cellview.client.CellTable;
82
import com.google.gwt.user.cellview.client.Column;
83
import com.google.gwt.user.cellview.client.GssSimplePager;
84
import com.google.gwt.user.cellview.client.TextColumn;
85
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
86
import com.google.gwt.user.client.DOM;
87
import com.google.gwt.user.client.DeferredCommand;
88
import com.google.gwt.user.client.Event;
89
import com.google.gwt.user.client.IncrementalCommand;
90
import com.google.gwt.user.client.Window;
91
import com.google.gwt.user.client.ui.AbstractImagePrototype;
92
import com.google.gwt.user.client.ui.Composite;
93
import com.google.gwt.user.client.ui.Grid;
94
import com.google.gwt.user.client.ui.HTML;
95
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
96
import com.google.gwt.user.client.ui.HorizontalPanel;
97
import com.google.gwt.user.client.ui.VerticalPanel;
98
import com.google.gwt.user.client.ui.HTMLTable.Cell;
99
import com.google.gwt.view.client.AsyncDataProvider;
100
import com.google.gwt.view.client.HasData;
101
import com.google.gwt.view.client.ListDataProvider;
102
import com.google.gwt.view.client.MultiSelectionModel;
103
import com.google.gwt.view.client.ProvidesKey;
104
import com.google.gwt.view.client.SelectionChangeEvent;
105
import com.google.gwt.view.client.SelectionChangeEvent.Handler;
106

    
107
/**
108
 * A composite that displays a list of search results for a particular query on
109
 * files.
110
 */
111
public class SearchResults extends Composite{
112
        private HTML searchResults = new HTML("Results for search:");
113
        private String lastQuery;
114
        SearchDataProvider provider = new SearchDataProvider();
115
        /**
116
         * Specifies that the images available for this composite will be the ones
117
         * available in FileContextMenu.
118
         */
119
        public interface Images extends ClientBundle,FileContextMenu.Images, CellTreeView.Images, FileList.Images {
120

    
121
                @Source("gr/ebs/gss/resources/blank.gif")
122
                ImageResource blank();
123

    
124
                @Source("gr/ebs/gss/resources/asc.png")
125
                ImageResource asc();
126

    
127
                @Source("gr/ebs/gss/resources/desc.png")
128
                ImageResource desc();
129
        }
130

    
131
        
132
        interface TableResources extends DragAndDropCellTable.Resources {
133
            @Source({CellTable.Style.DEFAULT_CSS, "GssCellTable.css"})
134
            TableStyle cellTableStyle();
135
          }
136
        
137
        static interface Templates extends SafeHtmlTemplates {
138
            Templates INSTANCE = GWT.create(Templates.class);
139

    
140
            @Template("<div id='dragHelper' style='border:1px solid black; background-color:#ffffff; color:black; width:150px;z-index:100'></div>")
141
            SafeHtml outerHelper();
142
          }
143
        
144
        
145
        /**
146
           * The styles applied to the table.
147
           */
148
          interface TableStyle extends CellTable.Style {
149
          }
150

    
151
        private String showingStats = "";
152

    
153
        private int startIndex = 0;
154

    
155
        /**
156
         * A constant that denotes the completion of an IncrementalCommand.
157
         */
158
        public static final boolean DONE = false;
159

    
160
        
161
        
162
        private final DateTimeFormat formatter = DateTimeFormat.getFormat("d/M/yyyy h:mm a");
163

    
164
        
165
        
166
        DragStopEventHandler dragStop = new DragStopEventHandler() {
167
                
168
                @Override
169
                public void onDragStop(DragStopEvent event) {
170
                        GWT.log("DRAG STOPPED");
171
                        
172
                }
173
        };
174
        
175
        private static class ContactCell extends AbstractCell<gr.ebs.gss.client.rest.resource.FileResource> {
176

    
177
            /**
178
             * The html of the image used for contacts.
179
             * 
180
             */
181
            private final String imageHtml;
182

    
183
            public ContactCell(ImageResource image) {
184
              this.imageHtml = AbstractImagePrototype.create(image).getHTML();
185
            }
186

    
187
            
188

    
189
                
190

    
191
            @Override
192
            public void render(Context context, FileResource value, SafeHtmlBuilder sb) {
193
              // Value can be null, so do a null check..
194
              if (value == null) {
195
                return;
196
              }
197

    
198
              sb.appendHtmlConstant("<table>");
199

    
200
              // Add the contact image.
201
              sb.appendHtmlConstant("<tr><td rowspan='3'>");
202
              sb.appendHtmlConstant(imageHtml);
203
              sb.appendHtmlConstant("</td>");
204

    
205
              // Add the name and address.
206
              DisplayHelper.log("value.getName()");
207
              sb.appendHtmlConstant("<td style='font-size:95%;' id='"+value.getName()+"'>");
208
              sb.appendEscaped(value.getName());
209
              sb.appendHtmlConstant("</td></tr><tr><td>");
210
              sb.appendEscaped(value.getFileSizeAsString());
211
              sb.appendHtmlConstant("</td></tr></table>");
212
            }
213

    
214

    
215
          }
216
        /**
217
         * Retrieve the celltable.
218
         *
219
         * @return the celltable
220
         */
221
        public DragAndDropCellTable<FileResource> getCelltable() {
222
                return celltable;
223
        }
224
        
225

    
226
        
227
        /**
228
         * The number of files in this folder.
229
         */
230
        int folderFileCount;
231

    
232
        /**
233
         * Total folder size
234
         */
235
        long folderTotalSize;
236

    
237
        /**
238
         * A cache of the files in the list.
239
         */
240
        private List<FileResource> files;
241

    
242
        /**
243
         * The widget's image bundle.
244
         */
245
        private final Images images;
246
        
247
        private FileContextMenu menuShowing;
248
        private DragAndDropCellTable<FileResource> celltable;
249
        private final MultiSelectionModel<FileResource> selectionModel;
250
        
251
        GssSimplePager pager;
252
        GssSimplePager pagerTop;
253
        /**
254
         * Construct the file list widget. This entails setting up the widget
255
         * layout, fetching the number of files in the current folder from the
256
         * server and filling the local file cache of displayed files with data from
257
         * the server, as well.
258
         *
259
         * @param _images
260
         */
261
        public SearchResults(Images _images) {
262
                images = _images;
263
                DragAndDropCellTable.Resources resources = GWT.create(TableResources.class);
264
                ProvidesKey<FileResource> keyProvider = new ProvidesKey<FileResource>(){
265

    
266
                        @Override
267
                        public Object getKey(FileResource item) {
268
                                return item.getUri();
269
                        }
270
                        
271
                };
272
                
273
                celltable = new DragAndDropCellTable<FileResource>(GSS.VISIBLE_FILE_COUNT,resources,keyProvider){
274
                        @Override
275
                        protected void onBrowserEvent2(Event event) {
276
                                /*if (DOM.eventGetType((Event) event) == Event.ONMOUSEDOWN && DOM.eventGetButton((Event) event) == NativeEvent.BUTTON_RIGHT){
277
                                        fireClickEvent((Element) event.getEventTarget().cast());                                        
278
                                }*/
279
                                super.onBrowserEvent2(event);
280
                        }
281
                };
282
                provider.addDataDisplay(celltable);
283
                celltable.addDragStopHandler(dragStop);
284
                celltable.addDragStartHandler(new DragStartEventHandler() {
285

    
286
                      public void onDragStart(DragStartEvent event) {
287
                        FileResource value = event.getDraggableData();
288
                        
289
                        com.google.gwt.dom.client.Element helper = event.getHelper();
290
                        SafeHtmlBuilder sb = new SafeHtmlBuilder();
291
                        sb.appendHtmlConstant("<b>");
292
                        DisplayHelper.log(value.getName());
293
                        if(getSelectedFiles().size()==1)
294
                                sb.appendEscaped(value.getName());
295
                        else
296
                                sb.appendEscaped(getSelectedFiles().size()+" files");
297
                        sb.appendHtmlConstant("</b>");
298
                        helper.setInnerHTML(sb.toSafeHtml().asString());
299

    
300
                      }
301
                    });
302
                DragAndDropColumn<FileResource, ImageResource> status = new DragAndDropColumn<FileResource, ImageResource>(new ImageResourceCell(){
303
                        @Override
304
                  public boolean handlesSelection() {
305
                            return false;
306
                          }
307
                }) {
308
                  @Override
309
                  public ImageResource getValue(FileResource entity) {
310
                    return getFileIcon(entity);
311
                  }
312
                  
313
               };
314
            celltable.addColumn(status,"");
315
            
316
            initDragOperation(status);
317
                final DragAndDropColumn<FileResource,SafeHtml> nameColumn = new DragAndDropColumn<FileResource,SafeHtml>(new SafeHtmlCell()) {
318

    
319

    
320
                        @Override
321
                        public SafeHtml getValue(FileResource object) {
322
                                SafeHtmlBuilder sb = new SafeHtmlBuilder();
323
                                if (object.getContentType().endsWith("png") || object.getContentType().endsWith("gif") || object.getContentType().endsWith("jpeg") ){                                        
324
                                        sb.appendHtmlConstant("<span id='fileList."+ object.getName() +"'>");
325
                                        sb.appendEscaped(object.getName());
326
                                        sb.appendHtmlConstant("</span>");
327
                                        sb.appendHtmlConstant(" <a href='" +
328
                                GSS.get().getTopPanel().getFileMenu().getDownloadURL(object) +
329
                                "' title='" + object.getOwner() + " : " + object.getPath() + object.getName() +
330
                                "' rel='lytebox[mnf]' " +
331
                                "onclick='myLytebox.start(this, false, false); return false;'>" +
332
                                "(view)" + "</a>");
333
                                        
334
                                        
335
                                }
336
                                else{                                        
337
                                        sb.appendHtmlConstant("<span id='fileList."+ object.getName() +"'>");
338
                                        sb.appendEscaped(object.getName());
339
                                        sb.appendHtmlConstant("</span>");
340
                                }
341
                                
342
                                return sb.toSafeHtml();
343
                        }
344
                        
345
                };
346
                initDragOperation(nameColumn);
347
                celltable.addColumn(nameColumn,"Name");
348
                
349
            DragAndDropColumn<FileResource,String> aColumn;
350
                celltable.addColumn(aColumn=new DragAndDropColumn<FileResource,String>(new TextCell()) {
351
                        @Override
352
                        public String getValue(FileResource object) {
353
                                return GSS.get().findUserFullName(object.getOwner());
354
                        }                        
355
                },"Owner");
356
                initDragOperation(aColumn);
357
                
358
                celltable.addColumn(aColumn=new DragAndDropColumn<FileResource,String>(new TextCell()) {
359
                        @Override
360
                        public String getValue(FileResource object) {
361
                                if(object.isDeleted())
362
                                        return object.getPath()+" (In Trash)";
363
                                return object.getPath();
364
                        }                        
365
                },"Path");
366
                initDragOperation(aColumn);
367
                
368
                
369
                        
370
                celltable.addColumn(aColumn=new DragAndDropColumn<FileResource,String>(new TextCell()) {
371
                        @Override
372
                        public String getValue(FileResource object) {
373
                                return object.getVersion().toString();
374
                        }                        
375
                },"Version");
376
                initDragOperation(aColumn);
377
                
378
                
379
                celltable.addColumn(aColumn=new DragAndDropColumn<FileResource,String>(new TextCell()) {
380
                        @Override
381
                        public String getValue(FileResource object) {
382
                                // TODO Auto-generated method stub
383
                                return object.getFileSizeAsString();
384
                        }                        
385
                },"Size");
386
                initDragOperation(aColumn);
387
                        
388
                celltable.addColumn(aColumn=new DragAndDropColumn<FileResource,String>(new TextCell()) {
389
                        @Override
390
                        public String getValue(FileResource object) {
391
                                return formatter.format(object.getModificationDate());
392
                        }                        
393
                },"Last Modified");
394
                
395
                
396
               
397

    
398
                VerticalPanel vp = new VerticalPanel();
399
                vp.setWidth("100%");
400
                celltable.setWidth("100%");
401
                vp.add(searchResults);
402
                searchResults.addStyleName("gss-searchLabel");
403
                pagerTop = new GssSimplePager(GssSimplePager.TextLocation.CENTER);
404
                pagerTop.setDisplay(celltable);
405
                vp.add(pagerTop);
406
                vp.add(celltable);
407
                pager = new GssSimplePager(GssSimplePager.TextLocation.CENTER);
408
                pager.setDisplay(celltable);
409
                //celltable.setPageSize(2);
410
                
411
                vp.add(pager);
412
                vp.setCellWidth(celltable, "100%");
413
                
414
                initWidget(vp);
415
                
416
                //initWidget(celltable);
417
                celltable.setStyleName("gss-List");
418
                selectionModel = new MultiSelectionModel<FileResource>();
419
                
420

    
421
                 Handler selectionHandler = new SelectionChangeEvent.Handler() { 
422
             @Override 
423
             public void onSelectionChange(com.google.gwt.view.client.SelectionChangeEvent event) {
424
                     if(getSelectedFiles().size()==1)
425
                             GSS.get().setCurrentSelection(getSelectedFiles().get(0));
426
                     else
427
                             GSS.get().setCurrentSelection(getSelectedFiles());
428
                                 //contextMenu.setFiles(getSelectedFiles());
429
             }
430
         };
431
         selectionModel.addSelectionChangeHandler(selectionHandler);
432
         
433
                celltable.setSelectionModel(selectionModel,GSSSelectionEventManager.<FileResource>createDefaultManager());
434
                celltable.setPageSize(GSS.VISIBLE_FILE_COUNT);
435
                celltable.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
436
                Scheduler.get().scheduleIncremental(new RepeatingCommand() {
437

    
438
                        @Override
439
                        public boolean execute() {
440
                                return fetchRootFolder();
441
                        }
442
                });
443
                sinkEvents(Event.ONCONTEXTMENU);
444
                sinkEvents(Event.ONMOUSEUP);
445
                sinkEvents(Event.ONMOUSEDOWN);
446
                sinkEvents(Event.ONCLICK);
447
                sinkEvents(Event.ONKEYDOWN);
448
                sinkEvents(Event.ONDBLCLICK);
449
                GSS.preventIESelection();
450
        }
451
        
452
        //public native void fireClickEvent(Element element) /*-{
453
          //  var evObj = $doc.createEvent('MouseEvents');
454
            //evObj.initEvent('click', true, true);
455
            //element.dispatchEvent(evObj);
456
          //}-*/;
457

    
458
         public List<FileResource> getSelectedFiles() {
459
         return new ArrayList<FileResource>(selectionModel.getSelectedSet());
460
         }
461
        
462
         private void initDragOperation(DragAndDropColumn<?, ?> column) {
463

    
464
                    // retrieve draggableOptions on the column
465
                    DraggableOptions draggableOptions = column.getDraggableOptions();
466
                    // use template to construct the helper. The content of the div will be set
467
                    // after
468
                    draggableOptions.setHelper($(Templates.INSTANCE.outerHelper().asString()));
469
                    //draggableOptions.setZIndex(100);
470
                    // opacity of the helper
471
                    draggableOptions.setAppendTo("body"); 
472
                    //draggableOptions.setOpacity((float) 0.8);
473
                    draggableOptions.setContainment("document");
474
                    // cursor to use during the drag operation
475
                    draggableOptions.setCursor(Cursor.MOVE);
476
                    // set the revert option
477
                    draggableOptions.setRevert(RevertOption.ON_INVALID_DROP);
478
                    // prevents dragging when user click on the category drop-down list
479
                    draggableOptions.setCancel("select");
480
                    
481
                    draggableOptions.setOnBeforeDragStart(new DragFunction() {
482
                                
483
                                @Override
484
                                public void f(DragContext context) {
485
                                         FileResource value = context.getDraggableData();
486
                                     if(!selectionModel.isSelected(value)){
487
                                               throw new StopDragException();
488
                                      }
489
                                        
490
                                }
491
                        });
492
                  }
493
        
494
         public void showContextMenu(Event event){
495
                 menuShowing = new FileContextMenu(images, false, true);
496
                        menuShowing=menuShowing.onEmptyEvent(event);
497
         }
498
        @Override
499
        public void onBrowserEvent(Event event) {
500
                
501
                if (files == null || files.size() == 0) {
502
                        if (DOM.eventGetType(event) == Event.ONCONTEXTMENU && getSelectedFiles().size() == 0) {
503
                                menuShowing = new FileContextMenu(images, false, true);
504
                                menuShowing=menuShowing.onEmptyEvent(event);
505
                                event.preventDefault();
506
                                event.cancelBubble(true);
507
                        }
508
                        return;
509
                }
510
                if (DOM.eventGetType(event) == Event.ONCONTEXTMENU && getSelectedFiles().size() != 0) {
511
                        GWT.log("*****GOING TO SHOW CONTEXT MENU ****", null);
512
                        menuShowing =  new FileContextMenu(images, false, false);
513
                        menuShowing=menuShowing.onEvent(event);
514
                        event.cancelBubble(true);
515
                        event.preventDefault();
516
                } else if (DOM.eventGetType(event) == Event.ONCONTEXTMENU && getSelectedFiles().size() == 0) {
517
                        menuShowing = new FileContextMenu(images, false, true);
518
                        menuShowing=menuShowing.onEmptyEvent(event);
519
                        event.cancelBubble(true);
520
                        event.preventDefault();
521
                } else if (DOM.eventGetType(event) == Event.ONDBLCLICK)
522
                        if (getSelectedFiles().size() == 1) {
523
                                GSS app = GSS.get();
524
                                FileResource file = getSelectedFiles().get(0);
525
                                String dateString = RestCommand.getDate();
526
                                String resource = file.getUri().substring(app.getApiPath().length() - 1, file.getUri().length());
527
                                String sig = app.getCurrentUserResource().getUsername() + " " +
528
                                                RestCommand.calculateSig("GET", dateString, resource,
529
                                                RestCommand.base64decode(app.getToken()));
530
                                if(!file.isDeleted()){
531
                                        Window.open(file.getUri() + "?Authorization=" + URL.encodeComponent(sig) + "&Date=" + URL.encodeComponent(dateString), "_blank", "");
532
                                }
533
                                event.preventDefault();
534
                                return;
535
                        }
536
                super.onBrowserEvent(event);
537
        }
538

    
539
        /**
540
         * Retrieve the root folder for the current user.
541
         *
542
         * @return true if the retrieval was successful
543
         */
544
        protected boolean fetchRootFolder() {
545
                UserResource user = GSS.get().getCurrentUserResource();
546
                if (user == null)
547
                        return !DONE;
548
                // Update cache and clear selection.
549
                updateFileCache(null);
550
                return DONE;
551
        }
552

    
553

    
554
        /**
555
         * Update the display of the file list.
556
         */
557
        void update(boolean sort) {
558
                int count = folderFileCount;
559
                int max = startIndex + GSS.VISIBLE_FILE_COUNT;
560
                if (max > count)
561
                        max = count;
562
                folderTotalSize = 0;
563
                
564
                copyListAndContinue(files);
565
                for(FileResource f : files){
566
                        folderTotalSize += f.getContentLength();
567
                }
568
                if (folderFileCount == 0) {
569
                        showingStats = "no files";
570
                } else if (folderFileCount < GSS.VISIBLE_FILE_COUNT) {
571
                        if (folderFileCount == 1)
572
                                showingStats = "1 file";
573
                        else
574
                                showingStats = folderFileCount + " files";
575
                        showingStats += " (" + FileResource.getFileSizeAsString(folderTotalSize) + ")";
576
                } else {
577
                        showingStats = "" + (startIndex + 1) + " - " + max + " of " + count + " files" + " (" + FileResource.getFileSizeAsString(folderTotalSize) + ")";
578
                }
579
                updateCurrentlyShowingStats();
580

    
581
        }
582

    
583
        /**
584
         * Return the proper icon based on the MIME type of the file.
585
         *
586
         * @param file
587
         * @return the icon
588
         */
589
        private ImageResource getFileIcon(FileResource file) {
590
                String mimetype = file.getContentType();
591
                boolean shared = file.isShared();
592
                if (mimetype == null)
593
                        return shared ? images.documentShared() : images.document();
594
                mimetype = mimetype.toLowerCase();
595
                if (mimetype.startsWith("application/pdf"))
596
                        return shared ? images.pdfShared() : images.pdf();
597
                else if (mimetype.endsWith("excel"))
598
                        return shared ? images.spreadsheetShared() : images.spreadsheet();
599
                else if (mimetype.endsWith("msword"))
600
                        return shared ? images.wordprocessorShared() : images.wordprocessor();
601
                else if (mimetype.endsWith("powerpoint"))
602
                        return shared ? images.presentationShared() : images.presentation();
603
                else if (mimetype.startsWith("application/zip") ||
604
                                        mimetype.startsWith("application/gzip") ||
605
                                        mimetype.startsWith("application/x-gzip") ||
606
                                        mimetype.startsWith("application/x-tar") ||
607
                                        mimetype.startsWith("application/x-gtar"))
608
                        return shared ? images.zipShared() : images.zip();
609
                else if (mimetype.startsWith("text/html"))
610
                        return shared ? images.htmlShared() : images.html();
611
                else if (mimetype.startsWith("text/plain"))
612
                        return shared ? images.txtShared() : images.txt();
613
                else if (mimetype.startsWith("image/"))
614
                        return shared ? images.imageShared() : images.image();
615
                else if (mimetype.startsWith("video/"))
616
                        return shared ? images.videoShared() : images.video();
617
                else if (mimetype.startsWith("audio/"))
618
                        return shared ? images.audioShared() : images.audio();
619
                return shared ? images.documentShared() : images.document();
620
        }
621

    
622
        /**
623
         * Update status panel with currently showing file stats.
624
         */
625
        public void updateCurrentlyShowingStats() {
626
                GSS.get().getStatusPanel().updateCurrentlyShowing(showingStats);
627
        }
628

    
629
        public void updateFileCache(String query) {
630
                final GSS app = GSS.get();
631
                setLastQuery(query);
632
                clearSelectedRows();
633
                //clearLabels();
634
                startIndex = 0;
635
                app.showLoadingIndicator();
636
                if (query == null || query.trim().equals("")) {
637
                        searchResults.setHTML("You must specify a query.");
638
                        setFiles(new ArrayList());
639
                        update(true);
640
                        app.hideLoadingIndicator();
641
                } else if (!GSS.isValidResourceName(query)) {
642
                        searchResults.setHTML("The query was invalid. Try to use words that appear in the file's name, contents or tags.");
643
                        setFiles(new ArrayList());
644
                        update(true);
645
                        app.hideLoadingIndicator();
646
                } else{
647
                        searchResults.setHTML("Search results for " + query);
648
                        showCellTable(true);
649
                        
650
                }
651
        }
652

    
653
        /**
654
         * Fill the file cache with data.
655
         */
656
        public void setFiles(final List<FileResource> _files) {
657
                if (_files.size() > 0 && ! (GSS.get().getTreeView().getSelection() instanceof TrashResource)) {
658
                        files = new ArrayList<FileResource>();
659
                        for (FileResource fres : _files)
660
                                files.add(fres);
661
                }
662
                else
663
                        files = _files;
664
                Collections.sort(files, new Comparator<FileResource>() {
665

    
666
                        @Override
667
                        public int compare(FileResource arg0, FileResource arg1) {
668
                                return arg0.getName().compareTo(arg1.getName());
669
                        }
670

    
671
                });
672
                folderFileCount = files.size();
673
        }
674

    
675
        
676

    
677
        
678
        /**
679
         * Does the list contains the requested filename
680
         *
681
         * @param fileName
682
         * @return true/false
683
         */
684
        public boolean contains(String fileName) {
685
                for (int i = 0; i < files.size(); i++)
686
                        if (files.get(i).getName().equals(fileName))
687
                                return true;
688
                return false;
689
        }
690

    
691
        public void clearSelectedRows() {
692
                Iterator<FileResource> it = selectionModel.getSelectedSet().iterator();
693
                while(it.hasNext()){
694
                        selectionModel.setSelected(it.next(),false);
695
                }
696
        }
697

    
698
        /**
699
         *
700
         */
701
        public void selectAllRows() {
702
                Iterator<FileResource> it = selectionModel.getSelectedSet().iterator();
703
                while(it.hasNext()){
704
                        selectionModel.setSelected(it.next(),true);
705
                }
706

    
707

    
708
        }
709

    
710
        
711
        private void sortFiles(final String sortingProperty, final boolean sortingType){
712
                Collections.sort(files, new Comparator<FileResource>() {
713

    
714
            @Override
715
            public int compare(FileResource arg0, FileResource arg1) {
716
                    AbstractImagePrototype descPrototype = AbstractImagePrototype.create(images.desc());
717
                    AbstractImagePrototype ascPrototype = AbstractImagePrototype.create(images.asc());
718
                    if (sortingType){
719
                            if (sortingProperty.equals("version")) {
720
                                    return arg0.getVersion().compareTo(arg1.getVersion());
721
                            } else if (sortingProperty.equals("owner")) {
722
                                    return arg0.getOwner().compareTo(arg1.getOwner());
723
                            } else if (sortingProperty.equals("date")) {
724
                                    return arg0.getModificationDate().compareTo(arg1.getModificationDate());
725
                            } else if (sortingProperty.equals("size")) {
726
                                    return arg0.getContentLength().compareTo(arg1.getContentLength());
727
                            } else if (sortingProperty.equals("name")) {
728
                                    return arg0.getName().compareTo(arg1.getName());
729
                            } else if (sortingProperty.equals("path")) {
730
                                    return arg0.getUri().compareTo(arg1.getUri());
731
                            } else {
732
                                    return arg0.getName().compareTo(arg1.getName());
733
                            }
734
                    }
735
                    else if (sortingProperty.equals("version")) {
736
                            
737
                            return arg1.getVersion().compareTo(arg0.getVersion());
738
                    } else if (sortingProperty.equals("owner")) {
739
                            
740
                            return arg1.getOwner().compareTo(arg0.getOwner());
741
                    } else if (sortingProperty.equals("date")) {
742
                            
743
                            return arg1.getModificationDate().compareTo(arg0.getModificationDate());
744
                    } else if (sortingProperty.equals("size")) {
745
                            
746
                            return arg1.getContentLength().compareTo(arg0.getContentLength());
747
                    } else if (sortingProperty.equals("name")) {
748
                            
749
                            return arg1.getName().compareTo(arg0.getName());
750
                    } else if (sortingProperty.equals("path")) {
751
                            
752
                            return arg1.getUri().compareTo(arg0.getUri());
753
                    } else {
754
                            
755
                            return arg1.getName().compareTo(arg0.getName());
756
                    }
757
            }
758

    
759
                });
760
        }
761
        
762
        
763
        /**
764
         * Creates a new ArrayList<FileResources> from the given files ArrayList 
765
         * in order that the input files remain untouched 
766
         * and continues to find user's full names of each FileResource element
767
         * in the new ArrayList
768
         *    
769
         * @param filesInput
770
         */
771
        private void copyListAndContinue(List<FileResource> filesInput){
772
                List<FileResource> copiedFiles = new ArrayList<FileResource>();                
773
                for(FileResource file : filesInput) {
774
                        copiedFiles.add(file);
775
                }
776
                handleFullNames(copiedFiles);
777
        }
778
        
779
        /**
780
         * Examines whether or not the user's full name exists in the 
781
         * userFullNameMap in the GSS.java for every element of the input list.
782
         * If the user's full name does not exist in the map then a command is being made.  
783
         * 
784
         * @param filesInput
785
         */
786
        private void handleFullNames(List<FileResource> filesInput){                
787
                if(filesInput.size() == 0){
788
                        showCellTable(false);
789
                        return;
790
                }                
791

    
792
                if(GSS.get().findUserFullName(filesInput.get(0).getOwner()) == null){
793
                        findFullNameAndUpdate(filesInput);                
794
                        return;
795
                }
796
                                
797
                if(filesInput.size() >= 1){
798
                        filesInput.remove(filesInput.get(0));
799
                        if(filesInput.isEmpty()){
800
                                showCellTable(false);                                
801
                        }else{
802
                                handleFullNames(filesInput);
803
                        }
804
                }                
805
        }
806
        
807
        /**
808
         * Makes a command to search for full name from a given username. 
809
         * Only after the completion of the command the celltable is shown
810
         * or the search for the next full name continues.
811
         *  
812
         * @param filesInput
813
         */
814
        private void findFullNameAndUpdate(final List<FileResource> filesInput){                
815
                String aUserName = filesInput.get(0).getOwner();
816
                String path = GSS.get().getApiPath() + "users/" + aUserName; 
817

    
818
                GetCommand<UserSearchResource> gg = new GetCommand<UserSearchResource>(UserSearchResource.class, path, false,null) {
819
                        @Override
820
                        public void onComplete() {
821
                                final UserSearchResource result = getResult();
822
                                for (UserResource user : result.getUsers()){
823
                                        String username = user.getUsername();
824
                                        String userFullName = user.getName();
825
                                        GSS.get().putUserToMap(username, userFullName);
826
                                        if(filesInput.size() >= 1){
827
                                                filesInput.remove(filesInput.get(0));
828
                                                if(filesInput.isEmpty()){
829
                                                        showCellTable(false);
830
                                                }else{
831
                                                        handleFullNames(filesInput);
832
                                                }                                                                                                
833
                                        }                                                                        
834
                                }
835
                        }
836
                        @Override
837
                        public void onError(Throwable t) {
838
                                GWT.log("", t);
839
                                GSS.get().displayError("Unable to fetch user's full name from the given username " + filesInput.get(0).getOwner());
840
                                if(filesInput.size() >= 1){
841
                                        filesInput.remove(filesInput.get(0));
842
                                        handleFullNames(filesInput);                                        
843
                                }
844
                        }
845
                };
846
                DeferredCommand.addCommand(gg);
847
        
848
        }
849
        /**
850
         * Shows the files in the cellTable 
851
         */
852

    
853
        private void showCellTable(boolean update){
854
                if(celltable.getRowCount()>GSS.VISIBLE_FILE_COUNT){
855
                        pager.setVisible(true);
856
                        pagerTop.setVisible(true);
857
                }
858
                else{
859
                        pager.setVisible(false);
860
                        pagerTop.setVisible(false);
861
                }
862
                if(update)
863
                        provider.onRangeChanged(celltable);
864
                celltable.redrawHeaders();                
865
        }
866
        
867
        
868
        /**
869
         * Retrieve the lastQuery.
870
         *
871
         * @return the lastQuery
872
         */
873
        public String getLastQuery() {
874
                return lastQuery;
875
        }
876
        
877
        
878
        /**
879
         * Modify the lastQuery.
880
         *
881
         * @param lastQuery the lastQuery to set
882
         */
883
        public void setLastQuery(String lastQuery) {
884
                this.lastQuery = lastQuery;
885
        }
886
        
887
        class SearchDataProvider extends AsyncDataProvider<FileResource>{
888

    
889
                @Override
890
                protected void onRangeChanged(final HasData<FileResource> display) {
891
                        final int start = display.getVisibleRange().getStart();
892
                        final GSS app = GSS.get();
893
                        if(getLastQuery()==null||getLastQuery().equals("")){
894
                                display.setRowCount(0,true);
895
                                return;
896
                                
897
                        }
898
                        GetCommand<SearchResource> eg = new GetCommand<SearchResource>(SearchResource.class,
899
                                                app.getApiPath() + "search/" +URL.encodeComponent(getLastQuery())+"?start="+start, null) {
900

    
901
                                @Override
902
                                public void onComplete() {
903
                                        SearchResource s = getResult();
904
                                        display.setRowCount(s.getSize(),true);
905
                                        display.setRowData(start, s.getFiles());
906
                                        setFiles(s.getFiles());
907
                                        update(true);
908
                                        
909
                                }
910

    
911
                                @Override
912
                                public void onError(Throwable t) {
913
                                        if(t instanceof RestException)
914
                                                app.displayError("Unable to perform search:"+((RestException)t).getHttpStatusText());
915
                                        else
916
                                                app.displayError("System error performing search:"+t.getMessage());
917
                                        GWT.log("",t);
918
                                        updateFileCache("");
919
                                }
920

    
921
                        };
922
                        DeferredCommand.addCommand(eg);
923
                        
924
                }
925
                
926
        }
927

    
928
}