aboutsummaryrefslogtreecommitdiffstats
path: root/uitest/src/main/java/com/vaadin/tests/TestForUpload.java
blob: f50f0ec33290cab460630cfef5a53486bba559c3 (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
package com.vaadin.tests;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;

import com.vaadin.server.StreamResource;
import com.vaadin.shared.ui.ContentMode;
import com.vaadin.ui.Button;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.Label;
import com.vaadin.ui.Layout;
import com.vaadin.ui.LegacyWindow;
import com.vaadin.ui.Link;
import com.vaadin.ui.Panel;
import com.vaadin.ui.Upload;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.v7.ui.ProgressIndicator;
import com.vaadin.v7.ui.Select;
import com.vaadin.v7.ui.TextField;

public class TestForUpload extends CustomComponent
        implements Upload.ProgressListener {

    private static final long serialVersionUID = -3400119871764256575L;

    Layout main = new VerticalLayout();

    Buffer buffer = new MemoryBuffer();

    VerticalLayout statusLayout = new VerticalLayout();
    Panel status = new Panel("Uploaded file:", statusLayout);

    private final Upload up;

    private final Label l;

    private final ProgressIndicator pi = new ProgressIndicator();
    private final ProgressIndicator pi2 = new ProgressIndicator();

    private final Label memoryStatus;

    private final Select uploadBufferSelector;

    private TextField textField;

    private Label textFieldValue;

    private CheckBox beSluggish = new CheckBox("Be sluggish");

    private CheckBox throwExecption = new CheckBox(
            "Throw exception in receiver");

    private Button interrupt = new Button("Interrupt upload");

    public TestForUpload() {
        setCompositionRoot(main);
        main.addComponent(
                new Label("This is a simple test for upload application. "
                        + "Upload should work with big files and concurrent "
                        + "requests should not be blocked. Button 'b' reads "
                        + "current state into label below it. Memory receiver "
                        + "streams upload contents into memory. You may track"
                        + "consumption."
                        + "tempfile receiver writes upload to file and "
                        + "should have low memory consumption."));

        main.addComponent(new Label(
                "Clicking on button b updates information about upload components status or same with garbage collector."));

        textField = new TextField("Test field");
        textFieldValue = new Label();
        main.addComponent(textField);
        main.addComponent(textFieldValue);

        up = new Upload("Upload", buffer);
        up.setImmediateMode(true);

        final Button b = new Button("Reed state from upload",
                event -> readState());

        final Button c = new Button("Force GC", event -> gc());

        main.addComponent(b);
        main.addComponent(c);
        main.addComponent(beSluggish);
        main.addComponent(throwExecption);
        main.addComponent(interrupt);
        interrupt.addClickListener(event -> up.interruptUpload());

        uploadBufferSelector = new Select("StreamVariable type");
        uploadBufferSelector.setImmediate(true);
        uploadBufferSelector.addItem("memory");
        uploadBufferSelector.setValue("memory");
        uploadBufferSelector.addItem("tempfile");
        uploadBufferSelector.addValueChangeListener(event -> setBuffer());
        main.addComponent(uploadBufferSelector);

        main.addComponent(up);
        l = new Label("Idle");
        main.addComponent(l);

        up.addListener((Listener) event -> {
            // print out all events fired by upload for debug purposes
            System.out.println("Upload fired event | " + event);
        });

        up.addStartedListener(event -> {
            pi.setVisible(true);
            pi2.setVisible(true);
            l.setValue("Started uploading file " + event.getFilename());
            textFieldValue.setValue(" TestFields value at the upload start is:"
                    + textField.getValue());
        });

        up.addFinishedListener(event -> {
            pi.setVisible(false);
            pi2.setVisible(false);
            if (event instanceof Upload.FailedEvent) {
                Exception reason = ((Upload.FailedEvent) event).getReason();
                l.setValue("Finished with failure ( " + reason + "  ), idle");
            } else if (event instanceof Upload.SucceededEvent) {
                l.setValue("Finished with succes, idle");
            } else {
                l.setValue("Finished with unknow event");
            }

            statusLayout.removeAllComponents();
            final InputStream stream = buffer.getStream();
            if (stream == null) {
                statusLayout.addComponent(new Label(
                        "Upload finished, but output buffer is null"));
            } else {
                statusLayout.addComponent(
                        new Label("<b>Name:</b> " + event.getFilename(),
                                ContentMode.HTML));
                statusLayout.addComponent(
                        new Label("<b>Mimetype:</b> " + event.getMIMEType(),
                                ContentMode.HTML));
                statusLayout.addComponent(new Label(
                        "<b>Size:</b> " + event.getLength() + " bytes.",
                        ContentMode.HTML));

                statusLayout.addComponent(new Link(
                        "Download " + buffer.getFileName(),
                        new StreamResource(buffer, buffer.getFileName())));

                statusLayout.setVisible(true);
            }

            setBuffer();
        });

        up.addProgressListener((readBytes, contentLength) -> {
            pi2.setValue(new Float(readBytes / (float) contentLength));

            refreshMemUsage();
        });

        pi.setVisible(false);
        pi.setPollingInterval(1000);
        main.addComponent(pi);

        pi2.setVisible(false);
        pi2.setPollingInterval(1000);
        main.addComponent(pi2);

        memoryStatus = new Label();
        main.addComponent(memoryStatus);

        statusLayout.setMargin(true);
        status.setVisible(false);
        main.addComponent(status);

        final Button restart = new Button("R");
        restart.addClickListener(event -> {
            LegacyWindow window = (LegacyWindow) event.getButton().getUI();
            window.getApplication().close();
        });
        main.addComponent(restart);

    }

    private void setBuffer() {
        final String id = (String) uploadBufferSelector.getValue();
        if ("memory".equals(id)) {
            buffer = new MemoryBuffer();
        } else if ("tempfile".equals(id)) {
            buffer = new TmpFileBuffer();
        }
        up.setReceiver(buffer);
    }

    public void gc() {
        Runtime.getRuntime().gc();
    }

    public void readState() {
        final StringBuilder sb = new StringBuilder();

        if (up.isUploading()) {
            sb.append("Uploading...");
            sb.append(up.getBytesRead());
            sb.append('/');
            sb.append(up.getUploadSize());
            sb.append(' ');
            sb.append(Math.round(
                    100 * up.getBytesRead() / (double) up.getUploadSize()));
            sb.append('%');
        } else {
            sb.append("Idle");
        }
        l.setValue(sb.toString());
        refreshMemUsage();
    }

    public interface Buffer
            extends StreamResource.StreamSource, Upload.Receiver {

        String getFileName();
    }

    public class MemoryBuffer implements Buffer {
        ByteArrayOutputStream outputBuffer = null;

        String mimeType;

        String fileName;

        public MemoryBuffer() {

        }

        @Override
        public InputStream getStream() {
            if (outputBuffer == null) {
                return null;
            }
            return new ByteArrayInputStream(outputBuffer.toByteArray());
        }

        /**
         * @see com.vaadin.ui.Upload.Receiver#receiveUpload(String, String)
         */
        @Override
        public OutputStream receiveUpload(String filename, String MIMEType) {
            fileName = filename;
            mimeType = MIMEType;
            outputBuffer = new ByteArrayOutputStream() {
                @Override
                public synchronized void write(byte[] b, int off, int len) {
                    beSluggish();
                    throwExecption();
                    super.write(b, off, len);
                }

            };
            return outputBuffer;
        }

        /**
         * Returns the fileName.
         *
         * @return String
         */
        @Override
        public String getFileName() {
            return fileName;
        }

        /**
         * Returns the mimeType.
         *
         * @return String
         */
        public String getMimeType() {
            return mimeType;
        }

    }

    public class TmpFileBuffer implements Buffer {
        String mimeType;

        String fileName;

        private File file;

        public TmpFileBuffer() {
            final String tempFileName = "upload_tmpfile_"
                    + System.currentTimeMillis();
            try {
                file = File.createTempFile(tempFileName, null);
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public InputStream getStream() {
            if (file == null) {
                return null;
            }
            try {
                return new FileInputStream(file);
            } catch (final FileNotFoundException e) {
                e.printStackTrace();
            }
            return null;
        }

        /**
         * @see com.vaadin.ui.Upload.Receiver#receiveUpload(String, String)
         */
        @Override
        public OutputStream receiveUpload(String filename, String MIMEType) {
            fileName = filename;
            mimeType = MIMEType;
            try {
                return new FileOutputStream(file) {

                    @Override
                    public void write(byte[] b, int off, int len)
                            throws IOException {
                        beSluggish();
                        throwExecption();
                        super.write(b, off, len);
                    }

                };
            } catch (final FileNotFoundException e) {
                e.printStackTrace();
            }
            return null;
        }

        /**
         * Returns the fileName.
         *
         * @return String
         */
        @Override
        public String getFileName() {
            return fileName;
        }

        /**
         * Returns the mimeType.
         *
         * @return String
         */
        public String getMimeType() {
            return mimeType;
        }

    }

    @Override
    public void updateProgress(long readBytes, long contentLenght) {
        pi.setValue(new Float(readBytes / (float) contentLenght));

        refreshMemUsage();
    }

    private void refreshMemUsage() {
        memoryStatus.setValue("Not available in Java 1.4");

        StringBuilder mem = new StringBuilder();
        MemoryMXBean mmBean = ManagementFactory.getMemoryMXBean();
        mem.append("Heap (M):");
        mem.append(mmBean.getHeapMemoryUsage().getUsed() / 1048576);
        mem.append(" | Non-Heap (M):");
        mem.append(mmBean.getNonHeapMemoryUsage().getUsed() / 1048576);
        memoryStatus.setValue(mem.toString());

    }

    private void beSluggish() {
        if (beSluggish.getValue()) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void throwExecption() {
        if (throwExecption.getValue()) {
            throwExecption.setValue(false);
            throw new RuntimeException("Test execption in receiver.");
        }
    }
}