summaryrefslogtreecommitdiffstats
path: root/src/com/itmill/toolkit/ui/Upload.java
blob: e19f7c05980d1177461442c20c03cc980ea06161 (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
/* *************************************************************************
 
                               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.InputStream;
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;

import java.io.IOException;
import java.io.OutputStream;

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

    /* TODO: Add a default constructor, receive to temp file. */
    
	/** Creates a new instance of Upload that redirects the 
	 * uploaded data to given stream. 
	 * 
	 */
	public Upload(String caption, Receiver uploadReceiver) {
		this.focusableId = Window.getNewFocusableId(this);
		setCaption(caption);
		receiver = uploadReceiver;
	}

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

	/** Invoked when the value of a variable has changed.  */
	public void changeVariables(Object source, Map variables) {

		// Check the variable name
		if (!variables.containsKey("stream"))
			return;

		// Get the upload stream    
		UploadStream upload = (UploadStream) variables.get("stream");

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

		// Get 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);
			return;
		}
		byte buffer[] = new byte[BUFFER_SIZE];
		int bytesRead = 0;
		long totalBytes = 0;
		try {
			while ((bytesRead = in.read(buffer)) > 0) {
				out.write(buffer, 0, bytesRead);
				totalBytes += bytesRead;
			}

			// Download successfull
			out.close();
			fireUploadSuccess(filename, type, totalBytes);
			requestRepaint();
			
		} catch (IOException e) {

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

	/** Paint the content of this component.
	 * @param target Target to paint the content on.
	 * @throws PaintException 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 (this.tabIndex >= 0)
			target.addAttribute("tabindex", this.tabIndex);
		
		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;

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

		public FinishedEvent(
			Upload source,
			String filename,
			String MIMEType,
			long length) {
			super(source);
			this.type = MIMEType;
			this.filename = filename;
			this.length = length;
		}

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

		/**
		 * Returns the length.
		 */
		public long getLength() {
			return length;
		}

		/**
		 * Returns the type.
		 */
		public String getMIMEType() {
			return type;
		}

	}

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

        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;

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

	}

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

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

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

		/** Upload has finished unsuccessfully.
		 * @param event 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 Upload successfull event.
		 */
		public void uploadSucceeded(SucceededEvent event);
	}

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

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

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

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

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

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

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

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

	/** Emit upload success event. */
	protected void fireUploadSuccess(
		String filename,
		String MIMEType,
		long length) {
		fireEvent(new Upload.SucceededEvent(this, filename, MIMEType, length));
	}
	/** Returns the current receiver.
	 * @return Receiver
	 */
	public Receiver getReceiver() {
		return receiver;
	}

	/** Sets the receiver.
	 * @param receiver The receiver to set
	 */
	public void setReceiver(Receiver receiver) {
		this.receiver = receiver;
	}
	/**
	 * @see com.itmill.toolkit.ui.Component.Focusable#focus()
	 */
	public void focus() {
		Window w = getWindow();
		if (w != null) {
			w.setFocusedComponent(this);
		}
	}
	
	/**
	 * @see com.itmill.toolkit.ui.Component.Focusable#getTabIndex()
	 */
	public int getTabIndex() {
		return this.tabIndex;
	}
	
	/**
	 * @see com.itmill.toolkit.ui.Component.Focusable#setTabIndex(int)
	 */
	public void setTabIndex(int tabIndex) {
		this.tabIndex = tabIndex;
	}
	
	/**
	 * @see com.itmill.toolkit.ui.Component.Focusable#getFocusableId()
	 */
	public long getFocusableId() {
		return this.focusableId;
	}

}