summaryrefslogtreecommitdiffstats
path: root/server/src/com/vaadin/ui/Upload.java
blob: a61bcf1bd91c802336c74e9ab76bc7242ad68dd4 (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
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
/*
 * Copyright 2000-2014 Vaadin Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.vaadin.ui;

import java.io.OutputStream;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;

import com.vaadin.server.NoInputStreamException;
import com.vaadin.server.NoOutputStreamException;
import com.vaadin.server.PaintException;
import com.vaadin.server.PaintTarget;
import com.vaadin.server.StreamVariable.StreamingProgressEvent;
import com.vaadin.shared.EventId;
import com.vaadin.shared.ui.upload.UploadClientRpc;
import com.vaadin.shared.ui.upload.UploadServerRpc;
import com.vaadin.shared.ui.upload.UploadState;
import com.vaadin.util.ReflectTools;

/**
 * Component for uploading files from client to server.
 *
 * <p>
 * The visible component consists of a file name input box and a browse button
 * and an upload submit button to start uploading.
 *
 * <p>
 * The Upload component needs a java.io.OutputStream to write the uploaded data.
 * You need to implement the Upload.Receiver interface and return the output
 * stream in the receiveUpload() method.
 *
 * <p>
 * You can get an event regarding starting (StartedEvent), progress
 * (ProgressEvent), and finishing (FinishedEvent) of upload by implementing
 * StartedListener, ProgressListener, and FinishedListener, respectively. The
 * FinishedListener is called for both failed and succeeded uploads. If you wish
 * to separate between these two cases, you can use SucceededListener
 * (SucceededEvenet) and FailedListener (FailedEvent).
 *
 * <p>
 * The upload component does not itself show upload progress, but you can use
 * the ProgressIndicator for providing progress feedback by implementing
 * ProgressListener and updating the indicator in updateProgress().
 *
 * <p>
 * Setting upload component immediate initiates the upload as soon as a file is
 * selected, instead of the common pattern of file selection field and upload
 * button.
 *
 * <p>
 * Note! Because of browser dependent implementations of <input type="file">
 * element, setting size for Upload component is not supported. For some
 * browsers setting size may work to some extend.
 *
 * @author Vaadin Ltd.
 * @since 3.0
 */
@SuppressWarnings("serial")
public class Upload extends AbstractComponent implements Component.Focusable,
        LegacyComponent {

    /**
     * Should the field be focused on next repaint?
     */
    private final 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 boolean isUploading;

    private long contentLength = -1;

    private int totalBytes;

    private String buttonCaption = "Upload";

    /**
     * ProgressListeners to which information about progress is sent during
     * upload
     */
    private LinkedHashSet<ProgressListener> progressListeners;

    private boolean interrupted = false;

    private boolean notStarted;

    private int nextid;

    /**
     * Creates a new instance of Upload.
     *
     * The receiver must be set before performing an upload.
     */
    public Upload() {
        registerRpc(new UploadServerRpc() {
            @Override
            public void change(String filename) {
                fireEvent(new ChangeEvent(Upload.this, filename));
            }

            @Override
            public void poll() {
                // Nothing to do, called only to visit the server
            }
        });
    }

    public Upload(String caption, Receiver uploadReceiver) {
        this();
        setCaption(caption);
        receiver = uploadReceiver;
    }

    /**
     * Invoked when the value of a variable has changed.
     *
     * @see com.vaadin.ui.AbstractComponent#changeVariables(java.lang.Object,
     *      java.util.Map)
     */
    @Override
    public void changeVariables(Object source, Map<String, Object> variables) {
        if (variables.containsKey("pollForStart")) {
            int id = (Integer) variables.get("pollForStart");
            if (!isUploading && id == nextid) {
                notStarted = true;
                markAsDirty();
            } else {
            }
        }
    }

    /**
     * Paints the content of this component.
     *
     * @param target
     *            Target to paint the content on.
     * @throws PaintException
     *             if the paint operation failed.
     */
    @Override
    public void paintContent(PaintTarget target) throws PaintException {
        if (notStarted) {
            target.addAttribute("notStarted", true);
            notStarted = false;
            return;
        }
        // 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);

        if (buttonCaption != null) {
            target.addAttribute("buttoncaption", buttonCaption);
        }

        target.addAttribute("nextid", nextid);

        // Post file to this strean variable
        target.addVariable(this, "action", getStreamVariable());

    }

    /**
     * Interface that must be implemented by the upload receivers to provide the
     * Upload component an output stream to write the uploaded data.
     *
     * @author Vaadin Ltd.
     * @since 3.0
     */
    public interface Receiver extends Serializable {

        /**
         * 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 (final java.lang.NoSuchMethodException e) {
            // This should never happen
            throw new java.lang.RuntimeException(
                    "Internal error finding methods in Upload");
        }
    }

    /**
     * Upload.FinishedEvent is sent when the upload receives a file, regardless
     * of whether the reception was successful or failed. If you wish to
     * distinguish between the two cases, use either SucceededEvent or
     * FailedEvent, which are both subclasses of the FinishedEvent.
     *
     * @author Vaadin Ltd.
     * @since 3.0
     */
    public static class FinishedEvent extends Component.Event {

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

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

        /**
         * Received file name.
         */
        private final 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.FailedEvent event is sent when the upload is received, but the
     * reception is interrupted for some reason.
     *
     * @author Vaadin Ltd.
     * @since 3.0
     */
    public static class FailedEvent extends FinishedEvent {

        private Exception reason = null;

        /**
         *
         * @param source
         * @param filename
         * @param MIMEType
         * @param length
         * @param exception
         */
        public FailedEvent(Upload source, String filename, String MIMEType,
                long length, Exception reason) {
            this(source, filename, MIMEType, length);
            this.reason = reason;
        }

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

        /**
         * Gets the exception that caused the failure.
         *
         * @return the exception that caused the failure, null if n/a
         */
        public Exception getReason() {
            return reason;
        }

    }

    /**
     * FailedEvent that indicates that an output stream could not be obtained.
     */
    public static class NoOutputStreamEvent extends FailedEvent {

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

    /**
     * FailedEvent that indicates that an input stream could not be obtained.
     */
    public static class NoInputStreamEvent extends FailedEvent {

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

    }

    /**
     * Upload.SucceededEvent event is sent when the upload is received
     * successfully.
     *
     * @author Vaadin Ltd.
     * @since 3.0
     */
    public static class SucceededEvent extends FinishedEvent {

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

    }

    /**
     * Upload.StartedEvent event is sent when the upload is started to received.
     *
     * @author Vaadin Ltd.
     * @since 5.0
     */
    public static class StartedEvent extends Component.Event {

        private final String filename;
        private final String type;
        /**
         * Length of the received file.
         */
        private final long length;

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

        /**
         * 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;
        }

        /**
         * @return the length of the file that is being uploaded
         */
        public long getContentLength() {
            return length;
        }

    }

    /**
     * Upload.ChangeEvent event is sent when the value (filename) of the upload
     * changes.
     *
     * @since 7.2
     */
    public static class ChangeEvent extends Component.Event {

        private final String filename;

        public ChangeEvent(Upload source, String filename) {
            super(source);
            this.filename = filename;
        }

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

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

    }

    /**
     * Receives the events when the upload starts.
     *
     * @author Vaadin Ltd.
     * @since 5.0
     */
    public interface StartedListener extends Serializable {

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

    /**
     * Receives the events when the uploads are ready.
     *
     * @author Vaadin Ltd.
     * @since 3.0
     */
    public interface FinishedListener extends Serializable {

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

    /**
     * Receives events when the uploads are finished, but unsuccessful.
     *
     * @author Vaadin Ltd.
     * @since 3.0
     */
    public interface FailedListener extends Serializable {

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

    /**
     * Receives events when the uploads are successfully finished.
     *
     * @author Vaadin Ltd.
     * @since 3.0
     */
    public interface SucceededListener extends Serializable {

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

    /**
     * Listener for {@link ChangeEvent}
     *
     * @since 7.2
     */
    public interface ChangeListener extends Serializable {

        Method FILENAME_CHANGED = ReflectTools.findMethod(ChangeListener.class,
                "filenameChanged", ChangeEvent.class);

        /**
         * A file has been selected but upload has not yet started.
         *
         * @param event
         *            the change event
         */
        public void filenameChanged(ChangeEvent event);
    }

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

    /**
     * @deprecated As of 7.0, replaced by
     *             {@link #addStartedListener(StartedListener)}
     **/
    @Deprecated
    public void addListener(StartedListener listener) {
        addStartedListener(listener);
    }

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

    /**
     * @deprecated As of 7.0, replaced by
     *             {@link #removeStartedListener(StartedListener)}
     **/
    @Deprecated
    public void removeListener(StartedListener listener) {
        removeStartedListener(listener);
    }

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

    /**
     * @deprecated As of 7.0, replaced by
     *             {@link #addFinishedListener(FinishedListener)}
     **/
    @Deprecated
    public void addListener(FinishedListener listener) {
        addFinishedListener(listener);
    }

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

    /**
     * @deprecated As of 7.0, replaced by
     *             {@link #removeFinishedListener(FinishedListener)}
     **/
    @Deprecated
    public void removeListener(FinishedListener listener) {
        removeFinishedListener(listener);
    }

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

    /**
     * @deprecated As of 7.0, replaced by
     *             {@link #addFailedListener(FailedListener)}
     **/
    @Deprecated
    public void addListener(FailedListener listener) {
        addFailedListener(listener);
    }

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

    /**
     * @deprecated As of 7.0, replaced by
     *             {@link #removeFailedListener(FailedListener)}
     **/
    @Deprecated
    public void removeListener(FailedListener listener) {
        removeFailedListener(listener);
    }

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

    /**
     * @deprecated As of 7.0, replaced by
     *             {@link #addSucceededListener(SucceededListener)}
     **/
    @Deprecated
    public void addListener(SucceededListener listener) {
        addSucceededListener(listener);
    }

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

    /**
     * @deprecated As of 7.0, replaced by
     *             {@link #removeSucceededListener(SucceededListener)}
     **/
    @Deprecated
    public void removeListener(SucceededListener listener) {
        removeSucceededListener(listener);
    }

    /**
     * Adds the upload progress event listener.
     *
     * @param listener
     *            the progress listener to be added
     */
    public void addProgressListener(ProgressListener listener) {
        if (progressListeners == null) {
            progressListeners = new LinkedHashSet<ProgressListener>();
        }
        progressListeners.add(listener);
    }

    /**
     * @deprecated As of 7.0, replaced by
     *             {@link #addProgressListener(ProgressListener)}
     **/
    @Deprecated
    public void addListener(ProgressListener listener) {
        addProgressListener(listener);
    }

    /**
     * Removes the upload progress event listener.
     *
     * @param listener
     *            the progress listener to be removed
     */
    public void removeProgressListener(ProgressListener listener) {
        if (progressListeners != null) {
            progressListeners.remove(listener);
        }
    }

    /**
     * Adds a filename change event listener
     *
     * @param listener
     *            the Listener to add
     */
    public void addChangeListener(ChangeListener listener) {
        super.addListener(EventId.CHANGE, ChangeEvent.class, listener,
                ChangeListener.FILENAME_CHANGED);
    }

    /**
     * Removes a filename change event listener
     *
     * @param listener
     *            the listener to be removed
     */
    public void removeChangeListener(ChangeListener listener) {
        super.removeListener(EventId.CHANGE, ChangeEvent.class, listener);
    }

    /**
     * @deprecated As of 7.0, replaced by
     *             {@link #removeProgressListener(ProgressListener)}
     **/
    @Deprecated
    public void removeListener(ProgressListener listener) {
        removeProgressListener(listener);
    }

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

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

    protected void fireNoInputStream(String filename, String MIMEType,
            long length) {
        fireEvent(new Upload.NoInputStreamEvent(this, filename, MIMEType,
                length));
    }

    protected void fireNoOutputStream(String filename, String MIMEType,
            long length) {
        fireEvent(new Upload.NoOutputStreamEvent(this, filename, MIMEType,
                length));
    }

    protected void fireUploadInterrupted(String filename, String MIMEType,
            long length, Exception e) {
        fireEvent(new Upload.FailedEvent(this, filename, MIMEType, length, e));
    }

    /**
     * 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));
    }

    /**
     * Emits the progress event.
     *
     * @param totalBytes
     *            bytes received so far
     * @param contentLength
     *            actual size of the file being uploaded, if known
     *
     */
    protected void fireUpdateProgress(long totalBytes, long contentLength) {
        // this is implemented differently than other listeners to maintain
        // backwards compatibility
        if (progressListeners != null) {
            for (Iterator<ProgressListener> it = progressListeners.iterator(); it
                    .hasNext();) {
                ProgressListener l = it.next();
                l.updateProgress(totalBytes, contentLength);
            }
        }
    }

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

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

    /**
     * {@inheritDoc}
     */
    @Override
    public void focus() {
        super.focus();
    }

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

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

    /**
     * Go into upload state. This is to prevent double uploading on same
     * component.
     *
     * Warning: this is an internal method used by the framework and should not
     * be used by user of the Upload component. Using it results in the Upload
     * component going in wrong state and not working. It is currently public
     * because it is used by another class.
     */
    public void startUpload() {
        if (isUploading) {
            throw new IllegalStateException("uploading already started");
        }
        isUploading = true;
        nextid++;
    }

    /**
     * Interrupts the upload currently being received. The interruption will be
     * done by the receiving thread so this method will return immediately and
     * the actual interrupt will happen a bit later.
     */
    public void interruptUpload() {
        if (isUploading) {
            interrupted = true;
        }
    }

    /**
     * Go into state where new uploading can begin.
     *
     * Warning: this is an internal method used by the framework and should not
     * be used by user of the Upload component.
     */
    private void endUpload() {
        isUploading = false;
        contentLength = -1;
        interrupted = false;
        markAsDirty();
    }

    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;
    }

    /**
     * ProgressListener receives events to track progress of upload.
     */
    public interface ProgressListener extends Serializable {
        /**
         * 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);
    }

    /**
     * @return String to be rendered into button that fires uploading
     */
    public String getButtonCaption() {
        return buttonCaption;
    }

    /**
     * In addition to the actual file chooser, upload components have button
     * that starts actual upload progress. This method is used to set text in
     * that button.
     * <p>
     * In case the button text is set to null, the button is hidden. In this
     * case developer must explicitly initiate the upload process with
     * {@link #submitUpload()}.
     * <p>
     * In case the Upload is used in immediate mode using
     * {@link #setImmediate(boolean)}, the file choose (html input with type
     * "file") is hidden and only the button with this text is shown.
     * <p>
     *
     * <p>
     * <strong>Note</strong> the string given is set as is to the button. HTML
     * formatting is not stripped. Be sure to properly validate your value
     * according to your needs.
     *
     * @param buttonCaption
     *            text for upload components button.
     */
    public void setButtonCaption(String buttonCaption) {
        this.buttonCaption = buttonCaption;
        markAsDirty();
    }

    /**
     * Forces the upload the send selected file to the server.
     * <p>
     * In case developer wants to use this feature, he/she will most probably
     * want to hide the uploads internal submit button by setting its caption to
     * null with {@link #setButtonCaption(String)} method.
     * <p>
     * Note, that the upload runs asynchronous. Developer should use normal
     * upload listeners to trac the process of upload. If the field is empty
     * uploaded the file name will be empty string and file length 0 in the
     * upload finished event.
     * <p>
     * Also note, that the developer should not remove or modify the upload in
     * the same user transaction where the upload submit is requested. The
     * upload may safely be hidden or removed once the upload started event is
     * fired.
     */
    public void submitUpload() {
        markAsDirty();
        getRpcProxy(UploadClientRpc.class).submitUpload();
    }

    @Override
    public void markAsDirty() {
        super.markAsDirty();
    }

    /*
     * Handle to terminal via Upload monitors and controls the upload during it
     * is being streamed.
     */
    private com.vaadin.server.StreamVariable streamVariable;

    protected com.vaadin.server.StreamVariable getStreamVariable() {
        if (streamVariable == null) {
            streamVariable = new com.vaadin.server.StreamVariable() {
                private StreamingStartEvent lastStartedEvent;

                @Override
                public boolean listenProgress() {
                    return (progressListeners != null && !progressListeners
                            .isEmpty());
                }

                @Override
                public void onProgress(StreamingProgressEvent event) {
                    fireUpdateProgress(event.getBytesReceived(),
                            event.getContentLength());
                }

                @Override
                public boolean isInterrupted() {
                    return interrupted;
                }

                @Override
                public OutputStream getOutputStream() {
                    if (getReceiver() == null) {
                        throw new IllegalStateException(
                                "Upload cannot be performed without a receiver set");
                    }
                    OutputStream receiveUpload = getReceiver().receiveUpload(
                            lastStartedEvent.getFileName(),
                            lastStartedEvent.getMimeType());
                    lastStartedEvent = null;
                    return receiveUpload;
                }

                @Override
                public void streamingStarted(StreamingStartEvent event) {
                    startUpload();
                    contentLength = event.getContentLength();
                    fireStarted(event.getFileName(), event.getMimeType());
                    lastStartedEvent = event;
                }

                @Override
                public void streamingFinished(StreamingEndEvent event) {
                    fireUploadSuccess(event.getFileName(), event.getMimeType(),
                            event.getContentLength());
                    endUpload();
                }

                @Override
                public void streamingFailed(StreamingErrorEvent event) {
                    try {
                        Exception exception = event.getException();
                        if (exception instanceof NoInputStreamException) {
                            fireNoInputStream(event.getFileName(),
                                    event.getMimeType(), 0);
                        } else if (exception instanceof NoOutputStreamException) {
                            fireNoOutputStream(event.getFileName(),
                                    event.getMimeType(), 0);
                        } else {
                            fireUploadInterrupted(event.getFileName(),
                                    event.getMimeType(), 0, exception);
                        }
                    } finally {
                        endUpload();
                    }
                }
            };
        }
        return streamVariable;
    }

    @Override
    public java.util.Collection<?> getListeners(java.lang.Class<?> eventType) {
        if (StreamingProgressEvent.class.isAssignableFrom(eventType)) {
            if (progressListeners == null) {
                return Collections.EMPTY_LIST;
            } else {
                return Collections.unmodifiableCollection(progressListeners);
            }

        }
        return super.getListeners(eventType);
    }

    @Override
    protected UploadState getState() {
        return (UploadState) super.getState();
    }
}