aboutsummaryrefslogtreecommitdiffstats
path: root/src/com/itmill/toolkit/ui/Upload.java
blob: a755b1413718dc8ccdc594dc2ae04db671912f1e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
/* *************************************************************************
 
 IT Mill Toolkit 

 Development of Browser User Interfaces Made Easy

 Copyright (C) 2000-2006 IT Mill Ltd
 
 *************************************************************************

 This product is distributed under commercial license that can be found
 from the product package on license.pdf. Use of this product might 
 require purchasing a commercial license from IT Mill Ltd. For guidelines 
 on usage, see licensing-guidelines.html

 *************************************************************************
 
 For more information, contact:
 
 IT Mill Ltd                           phone: +358 2 4802 7180
 Ruukinkatu 2-4                        fax:   +358 2 4802 7181
 20540, Turku                          email:  info@itmill.com
 Finland                               company www: www.itmill.com
 
 Primary source for information and releases: www.itmill.com

 ********************************************************************** */

package com.itmill.toolkit.ui;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.Map;

import com.itmill.toolkit.terminal.PaintException;
import com.itmill.toolkit.terminal.PaintTarget;
import com.itmill.toolkit.terminal.UploadStream;

/**
 * Component for client file uploading.
 * 
 * @author IT Mill Ltd.
 * @version
 * @VERSION@
 * @since 3.0
 */
public class Upload extends AbstractComponent implements Component.Focusable {

    /**
     * Upload buffer size.
     */
    private static final int BUFFER_SIZE = 64 * 1024; // 64k

    /**
     * Should the field be focused on next repaint?
     */
    private boolean focus = false;

    /**
     * The tab order number of this field.
     */
    private int tabIndex = 0;

    /**
     * The output of the upload is redirected to this receiver.
     */
    private Receiver receiver;

    private long focusableId = -1;

    private boolean isUploading;

    private long contentLength = -1;

    private int totalBytes;

    /**
     * ProgressListener to which information about progress is sent during
     * upload
     */
    private ProgressListener progressListener;

    /* TODO: Add a default constructor, receive to temp file. */

    /**
     * Creates a new instance of Upload that redirects the uploaded data to
     * given stream.
     * 
     * @param caption
     * @param uploadReceiver
     */
    public Upload(String caption, Receiver uploadReceiver) {
        focusableId = Window.getNewFocusableId(this);
        setCaption(caption);
        receiver = uploadReceiver;
    }

    /**
     * Gets the component type.
     * 
     * @return Component type as string.
     */
    public String getTag() {
        return "upload";
    }

    public void receiveUpload(UploadStream upload) {
        if (!isUploading) {
            throw new IllegalStateException("uploading not started");
        }

        // Gets file properties
        String filename = upload.getContentName();
        String type = upload.getContentType();

        fireStarted(filename, type);

        // Gets the output target stream
        OutputStream out = receiver.receiveUpload(filename, type);
        if (out == null) {
            throw new RuntimeException(
                    "Error getting outputstream from upload receiver");
        }

        InputStream in = upload.getStream();

        if (null == in) {
            // No file, for instance non-existent filename in html upload
            fireUploadInterrupted(filename, type, 0);
            endUpload();
            return;
        }

        byte buffer[] = new byte[BUFFER_SIZE];
        int bytesRead = 0;
        totalBytes = 0;
        try {
            while ((bytesRead = in.read(buffer)) > 0) {
                out.write(buffer, 0, bytesRead);
                totalBytes += bytesRead;
                if (progressListener != null && contentLength > 0) {
                    // update progress if listener set and contentLength
                    // received
                    progressListener.updateProgress(totalBytes, contentLength);
                }
            }

            // upload successful
            out.close();
            fireUploadSuccess(filename, type, totalBytes);
            endUpload();
            requestRepaint();

        } catch (IOException e) {

            // Download interrupted
            fireUploadInterrupted(filename, type, totalBytes);
            endUpload();
        }
    }

    /**
     * Invoked when the value of a variable has changed.
     * 
     * @see com.itmill.toolkit.ui.AbstractComponent#changeVariables(java.lang.Object,
     *      java.util.Map)
     */
    public void changeVariables(Object source, Map variables) {
        // NOP

    }

    /**
     * Paints the content of this component.
     * 
     * @param target
     *                Target to paint the content on.
     * @throws PaintException
     *                 if the paint operation failed.
     */
    public void paintContent(PaintTarget target) throws PaintException {
        // The field should be focused
        if (focus) {
            target.addAttribute("focus", true);
        }

        // The tab ordering number
        if (tabIndex >= 0) {
            target.addAttribute("tabindex", tabIndex);
        }

        target.addAttribute("state", isUploading);

        target.addVariable(this, "fake", true);

        target.addUploadStreamVariable(this, "stream");
    }

    /**
     * Interface that must be implemented by the upload receivers.
     * 
     * @author IT Mill Ltd.
     * @version
     * @VERSION@
     * @since 3.0
     */
    public interface Receiver {

        /**
         * Invoked when a new upload arrives.
         * 
         * @param filename
         *                the desired filename of the upload, usually as
         *                specified by the client.
         * @param MIMEType
         *                the MIME type of the uploaded file.
         * @return Stream to which the uploaded file should be written.
         */
        public OutputStream receiveUpload(String filename, String MIMEType);
    }

    /* Upload events ************************************************ */

    private static final Method UPLOAD_FINISHED_METHOD;

    private static final Method UPLOAD_FAILED_METHOD;

    private static final Method UPLOAD_SUCCEEDED_METHOD;

    private static final Method UPLOAD_STARTED_METHOD;

    static {
        try {
            UPLOAD_FINISHED_METHOD = FinishedListener.class.getDeclaredMethod(
                    "uploadFinished", new Class[] { FinishedEvent.class });
            UPLOAD_FAILED_METHOD = FailedListener.class.getDeclaredMethod(
                    "uploadFailed", new Class[] { FailedEvent.class });
            UPLOAD_STARTED_METHOD = StartedListener.class.getDeclaredMethod(
                    "uploadStarted", new Class[] { StartedEvent.class });
            UPLOAD_SUCCEEDED_METHOD = SucceededListener.class
                    .getDeclaredMethod("uploadSucceeded",
                            new Class[] { SucceededEvent.class });
        } catch (java.lang.NoSuchMethodException e) {
            // This should never happen
            throw new java.lang.RuntimeException("Internal error");
        }
    }

    /**
     * Upload.Received event is sent when the upload receives a file, regardless
     * if the receival was successfull.
     * 
     * @author IT Mill Ltd.
     * @version
     * @VERSION@
     * @since 3.0
     */
    public class FinishedEvent extends Component.Event {

        /**
         * Serial generated by eclipse.
         */
        private static final long serialVersionUID = 3257288015385670969L;

        /**
         * Length of the received file.
         */
        private long length;

        /**
         * MIME type of the received file.
         */
        private String type;

        /**
         * Received file name.
         */
        private String filename;

        /**
         * 
         * @param source
         *                the source of the file.
         * @param filename
         *                the received file name.
         * @param MIMEType
         *                the MIME type of the received file.
         * @param length
         *                the length of the received file.
         */
        public FinishedEvent(Upload source, String filename, String MIMEType,
                long length) {
            super(source);
            type = MIMEType;
            this.filename = filename;
            this.length = length;
        }

        /**
         * Uploads where the event occurred.
         * 
         * @return the Source of the event.
         */
        public Upload getUpload() {
            return (Upload) getSource();
        }

        /**
         * Gets the file name.
         * 
         * @return the filename.
         */
        public String getFilename() {
            return filename;
        }

        /**
         * Gets the MIME Type of the file.
         * 
         * @return the MIME type.
         */
        public String getMIMEType() {
            return type;
        }

        /**
         * Gets the length of the file.
         * 
         * @return the length.
         */
        public long getLength() {
            return length;
        }

    }

    /**
     * Upload.Interrupted event is sent when the upload is received, but the
     * reception is interrupted for some reason.
     * 
     * @author IT Mill Ltd.
     * @version
     * @VERSION@
     * @since 3.0
     */
    public class FailedEvent extends FinishedEvent {

        /**
         * Serial generated by eclipse.
         */
        private static final long serialVersionUID = 3833746590157386293L;

        /**
         * 
         * @param source
         * @param filename
         * @param MIMEType
         * @param length
         */
        public FailedEvent(Upload source, String filename, String MIMEType,
                long length) {
            super(source, filename, MIMEType, length);
        }

    }

    /**
     * Upload.Success event is sent when the upload is received successfully.
     * 
     * @author IT Mill Ltd.
     * @version
     * @VERSION@
     * @since 3.0
     */
    public class SucceededEvent extends FinishedEvent {

        /**
         * Serial generated by eclipse.
         */
        private static final long serialVersionUID = 3256445798169524023L;

        /**
         * 
         * @param source
         * @param filename
         * @param MIMEType
         * @param length
         */
        public SucceededEvent(Upload source, String filename, String MIMEType,
                long length) {
            super(source, filename, MIMEType, length);
        }

    }

    /**
     * Upload.Started event is sent when the upload is started to received.
     * 
     * @author IT Mill Ltd.
     * @version
     * @VERSION@
     * @since 5.0
     */
    public class StartedEvent extends Component.Event {

        /**
         * Serial generated by eclipse.
         */
        private static final long serialVersionUID = -3984393770487403525L;
        private String filename;
        private String type;

        /**
         * 
         * @param source
         * @param filename
         * @param MIMEType
         * @param length
         */
        public StartedEvent(Upload source, String filename, String MIMEType) {
            super(source);
            this.filename = filename;
            type = MIMEType;
        }

        /**
         * Uploads where the event occurred.
         * 
         * @return the Source of the event.
         */
        public Upload getUpload() {
            return (Upload) getSource();
        }

        /**
         * Gets the file name.
         * 
         * @return the filename.
         */
        public String getFilename() {
            return filename;
        }

        /**
         * Gets the MIME Type of the file.
         * 
         * @return the MIME type.
         */
        public String getMIMEType() {
            return type;
        }

    }

    /**
     * Receives the events when the upload starts.
     * 
     * @author IT Mill Ltd.
     * @version
     * @VERSION@
     * @since 5.0
     */
    public interface StartedListener {

        /**
         * Upload has started.
         * 
         * @param event
         *                the Upload started event.
         */
        public void uploadStarted(StartedEvent event);
    }

    /**
     * Receives the events when the uploads are ready.
     * 
     * @author IT Mill Ltd.
     * @version
     * @VERSION@
     * @since 3.0
     */
    public interface FinishedListener {

        /**
         * Upload has finished.
         * 
         * @param event
         *                the Upload finished event.
         */
        public void uploadFinished(FinishedEvent event);
    }

    /**
     * Receives events when the uploads are finished, but unsuccessful.
     * 
     * @author IT Mill Ltd.
     * @version
     * @VERSION@
     * @since 3.0
     */
    public interface FailedListener {

        /**
         * Upload has finished unsuccessfully.
         * 
         * @param event
         *                the Upload failed event.
         */
        public void uploadFailed(FailedEvent event);
    }

    /**
     * Receives events when the uploads are successfully finished.
     * 
     * @author IT Mill Ltd.
     * @version
     * @VERSION@
     * @since 3.0
     */
    public interface SucceededListener {

        /**
         * Upload successfull..
         * 
         * @param event
         *                the Upload successfull event.
         */
        public void uploadSucceeded(SucceededEvent event);
    }

    /**
     * Adds the upload started event listener.
     * 
     * @param listener
     *                the Listener to be added.
     */
    public void addListener(StartedListener listener) {
        addListener(StartedEvent.class, listener, UPLOAD_STARTED_METHOD);
    }

    /**
     * Removes the upload started event listener.
     * 
     * @param listener
     *                the Listener to be removed.
     */
    public void removeListener(StartedListener listener) {
        removeListener(FinishedEvent.class, listener, UPLOAD_STARTED_METHOD);
    }

    /**
     * Adds the upload received event listener.
     * 
     * @param listener
     *                the Listener to be added.
     */
    public void addListener(FinishedListener listener) {
        addListener(FinishedEvent.class, listener, UPLOAD_FINISHED_METHOD);
    }

    /**
     * Removes the upload received event listener.
     * 
     * @param listener
     *                the Listener to be removed.
     */
    public void removeListener(FinishedListener listener) {
        removeListener(FinishedEvent.class, listener, UPLOAD_FINISHED_METHOD);
    }

    /**
     * Adds the upload interrupted event listener.
     * 
     * @param listener
     *                the Listener to be added.
     */
    public void addListener(FailedListener listener) {
        addListener(FailedEvent.class, listener, UPLOAD_FAILED_METHOD);
    }

    /**
     * Removes the upload interrupted event listener.
     * 
     * @param listener
     *                the Listener to be removed.
     */
    public void removeListener(FailedListener listener) {
        removeListener(FinishedEvent.class, listener, UPLOAD_FAILED_METHOD);
    }

    /**
     * Adds the upload success event listener.
     * 
     * @param listener
     *                the Listener to be added.
     */
    public void addListener(SucceededListener listener) {
        addListener(SucceededEvent.class, listener, UPLOAD_SUCCEEDED_METHOD);
    }

    /**
     * Removes the upload success event listener.
     * 
     * @param listener
     *                the Listener to be removed.
     */
    public void removeListener(SucceededListener listener) {
        removeListener(SucceededEvent.class, listener, UPLOAD_SUCCEEDED_METHOD);
    }

    /**
     * Emit upload received event.
     * 
     * @param filename
     * @param MIMEType
     * @param length
     */
    protected void fireStarted(String filename, String MIMEType) {
        fireEvent(new Upload.StartedEvent(this, filename, MIMEType));
    }

    /**
     * Emit upload received event.
     * 
     * @param filename
     * @param MIMEType
     * @param length
     */
    protected void fireUploadReceived(String filename, String MIMEType,
            long length) {
        fireEvent(new Upload.FinishedEvent(this, filename, MIMEType, length));
    }

    /**
     * Emits the upload interrupted event.
     * 
     * @param filename
     * @param MIMEType
     * @param length
     */
    protected void fireUploadInterrupted(String filename, String MIMEType,
            long length) {
        fireEvent(new Upload.FailedEvent(this, filename, MIMEType, length));
    }

    /**
     * Emits the upload success event.
     * 
     * @param filename
     * @param MIMEType
     * @param length
     * 
     */
    protected void fireUploadSuccess(String filename, String MIMEType,
            long length) {
        fireEvent(new Upload.SucceededEvent(this, filename, MIMEType, length));
    }

    /**
     * Returns the current receiver.
     * 
     * @return the Receiver.
     */
    public Receiver getReceiver() {
        return receiver;
    }

    /**
     * Sets the receiver.
     * 
     * @param receiver
     *                the receiver to set.
     */
    public void setReceiver(Receiver receiver) {
        this.receiver = receiver;
    }

    /**
     * Sets the focus to this component.
     * 
     * @see com.itmill.toolkit.ui.Component.Focusable#focus()
     */
    public void focus() {
        Window w = getWindow();
        if (w != null) {
            w.setFocusedComponent(this);
        }
    }

    /**
     * Gets the Tabulator index of this Focusable component.
     * 
     * @see com.itmill.toolkit.ui.Component.Focusable#getTabIndex()
     */
    public int getTabIndex() {
        return tabIndex;
    }

    /**
     * Sets the Tabulator index of this Focusable component.
     * 
     * @see com.itmill.toolkit.ui.Component.Focusable#setTabIndex(int)
     */
    public void setTabIndex(int tabIndex) {
        this.tabIndex = tabIndex;
    }

    /**
     * Gets the unique ID of focusable.
     * 
     * @see com.itmill.toolkit.ui.Component.Focusable#getFocusableId()
     */
    public long getFocusableId() {
        return focusableId;
    }

    /**
     * Sets the size of the file currently being uploaded.
     * 
     * @param contentLength
     */
    public void setUploadSize(long contentLength) {
        this.contentLength = contentLength;
    }

    /**
     * Go into upload state. This is to prevent double uploading on same
     * component.
     */
    public void startUpload() {
        if (isUploading) {
            throw new IllegalStateException("uploading already started");
        }
        isUploading = true;
    }

    /**
     * Go into state where new uploading can begin.
     */
    public void endUpload() {
        isUploading = false;
        contentLength = -1;
    }

    public boolean isUploading() {
        return isUploading;
    }

    /**
     * Gets read bytes of the file currently being uploaded.
     * 
     * @return bytes
     */
    public long getBytesRead() {
        return totalBytes;
    }

    /**
     * Returns size of file currently being uploaded. Value sane only during
     * upload.
     * 
     * @return size in bytes
     */
    public long getUploadSize() {
        return contentLength;
    }

    /**
     * Sets listener to track progress of upload.
     * 
     * @param progressListener
     */
    public void setProgressListener(ProgressListener progressListener) {
        this.progressListener = progressListener;
    }

    /**
     * Gets listener that tracks progress of upload.
     * 
     * @return listener
     * 
     */
    public ProgressListener getProgressListener() {
        return progressListener;
    }

    /**
     * ProgressListener receives events to track progress of upload.
     */
    public interface ProgressListener {
        /**
         * Updates progress to listener
         * 
         * @param readBytes
         *                bytes transferred
         * @param contentLength
         *                total size of file currently being uploaded, -1 if
         *                unknown
         */
        public void updateProgress(long readBytes, long contentLength);
    }
}