You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TestForUpload.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. /*
  2. * Copyright 2000-2014 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.tests;
  17. import java.io.ByteArrayInputStream;
  18. import java.io.ByteArrayOutputStream;
  19. import java.io.File;
  20. import java.io.FileInputStream;
  21. import java.io.FileNotFoundException;
  22. import java.io.FileOutputStream;
  23. import java.io.IOException;
  24. import java.io.InputStream;
  25. import java.io.OutputStream;
  26. import java.lang.management.ManagementFactory;
  27. import java.lang.management.MemoryMXBean;
  28. import com.vaadin.data.Property.ValueChangeEvent;
  29. import com.vaadin.legacy.ui.LegacyAbstractField;
  30. import com.vaadin.legacy.ui.LegacyTextField;
  31. import com.vaadin.server.StreamResource;
  32. import com.vaadin.shared.ui.label.ContentMode;
  33. import com.vaadin.ui.Button;
  34. import com.vaadin.ui.Button.ClickEvent;
  35. import com.vaadin.ui.CheckBox;
  36. import com.vaadin.ui.CustomComponent;
  37. import com.vaadin.ui.Label;
  38. import com.vaadin.ui.Layout;
  39. import com.vaadin.ui.LegacyWindow;
  40. import com.vaadin.ui.Link;
  41. import com.vaadin.ui.Panel;
  42. import com.vaadin.ui.ProgressIndicator;
  43. import com.vaadin.ui.Select;
  44. import com.vaadin.ui.Upload;
  45. import com.vaadin.ui.Upload.FinishedEvent;
  46. import com.vaadin.ui.Upload.StartedEvent;
  47. import com.vaadin.ui.Upload.StartedListener;
  48. import com.vaadin.ui.VerticalLayout;
  49. public class TestForUpload extends CustomComponent implements
  50. Upload.ProgressListener {
  51. private static final long serialVersionUID = -3400119871764256575L;
  52. Layout main = new VerticalLayout();
  53. Buffer buffer = new MemoryBuffer();
  54. VerticalLayout statusLayout = new VerticalLayout();
  55. Panel status = new Panel("Uploaded file:", statusLayout);
  56. private final Upload up;
  57. private final Label l;
  58. private final ProgressIndicator pi = new ProgressIndicator();
  59. private final ProgressIndicator pi2 = new ProgressIndicator();
  60. private final Label memoryStatus;
  61. private final Select uploadBufferSelector;
  62. private LegacyTextField textField;
  63. private Label textFieldValue;
  64. private CheckBox beSluggish = new CheckBox("Be sluggish");
  65. private CheckBox throwExecption = new CheckBox(
  66. "Throw exception in receiver");
  67. private Button interrupt = new Button("Interrupt upload");
  68. public TestForUpload() {
  69. setCompositionRoot(main);
  70. main.addComponent(new Label(
  71. "This is a simple test for upload application. "
  72. + "Upload should work with big files and concurrent "
  73. + "requests should not be blocked. Button 'b' reads "
  74. + "current state into label below it. Memory receiver "
  75. + "streams upload contents into memory. You may track"
  76. + "consumption."
  77. + "tempfile receiver writes upload to file and "
  78. + "should have low memory consumption."));
  79. main.addComponent(new Label(
  80. "Clicking on button b updates information about upload components status or same with garbage collector."));
  81. textField = new LegacyTextField("Test field");
  82. textFieldValue = new Label();
  83. main.addComponent(textField);
  84. main.addComponent(textFieldValue);
  85. up = new Upload("Upload", buffer);
  86. up.setImmediate(true);
  87. up.addListener(new Listener() {
  88. private static final long serialVersionUID = -8319074730512324303L;
  89. @Override
  90. public void componentEvent(Event event) {
  91. // print out all events fired by upload for debug purposes
  92. System.out.println("Upload fired event | " + event);
  93. }
  94. });
  95. up.addListener(new StartedListener() {
  96. private static final long serialVersionUID = 5508883803861085154L;
  97. @Override
  98. public void uploadStarted(StartedEvent event) {
  99. pi.setVisible(true);
  100. pi2.setVisible(true);
  101. l.setValue("Started uploading file " + event.getFilename());
  102. textFieldValue
  103. .setValue(" TestFields value at the upload start is:"
  104. + textField.getValue());
  105. }
  106. });
  107. up.addListener(new Upload.FinishedListener() {
  108. private static final long serialVersionUID = -3773034195991947371L;
  109. @Override
  110. public void uploadFinished(FinishedEvent event) {
  111. pi.setVisible(false);
  112. pi2.setVisible(false);
  113. if (event instanceof Upload.FailedEvent) {
  114. Exception reason = ((Upload.FailedEvent) event).getReason();
  115. l.setValue("Finished with failure ( " + reason
  116. + " ), idle");
  117. } else if (event instanceof Upload.SucceededEvent) {
  118. l.setValue("Finished with succes, idle");
  119. } else {
  120. l.setValue("Finished with unknow event");
  121. }
  122. statusLayout.removeAllComponents();
  123. final InputStream stream = buffer.getStream();
  124. if (stream == null) {
  125. statusLayout.addComponent(new Label(
  126. "Upload finished, but output buffer is null"));
  127. } else {
  128. statusLayout.addComponent(new Label("<b>Name:</b> "
  129. + event.getFilename(), ContentMode.HTML));
  130. statusLayout.addComponent(new Label("<b>Mimetype:</b> "
  131. + event.getMIMEType(), ContentMode.HTML));
  132. statusLayout.addComponent(new Label("<b>Size:</b> "
  133. + event.getLength() + " bytes.", ContentMode.HTML));
  134. statusLayout.addComponent(new Link("Download "
  135. + buffer.getFileName(), new StreamResource(buffer,
  136. buffer.getFileName())));
  137. statusLayout.setVisible(true);
  138. }
  139. setBuffer();
  140. }
  141. });
  142. up.addListener(new Upload.ProgressListener() {
  143. @Override
  144. public void updateProgress(long readBytes, long contentLenght) {
  145. pi2.setValue(new Float(readBytes / (float) contentLenght));
  146. refreshMemUsage();
  147. }
  148. });
  149. final Button b = new Button("Reed state from upload",
  150. new Button.ClickListener() {
  151. @Override
  152. public void buttonClick(ClickEvent event) {
  153. readState();
  154. }
  155. });
  156. final Button c = new Button("Force GC", new Button.ClickListener() {
  157. @Override
  158. public void buttonClick(ClickEvent event) {
  159. gc();
  160. }
  161. });
  162. main.addComponent(b);
  163. main.addComponent(c);
  164. main.addComponent(beSluggish);
  165. main.addComponent(throwExecption);
  166. main.addComponent(interrupt);
  167. interrupt.addListener(new Button.ClickListener() {
  168. @Override
  169. public void buttonClick(ClickEvent event) {
  170. up.interruptUpload();
  171. }
  172. });
  173. uploadBufferSelector = new Select("StreamVariable type");
  174. uploadBufferSelector.setImmediate(true);
  175. uploadBufferSelector.addItem("memory");
  176. uploadBufferSelector.setValue("memory");
  177. uploadBufferSelector.addItem("tempfile");
  178. uploadBufferSelector
  179. .addListener(new LegacyAbstractField.ValueChangeListener() {
  180. @Override
  181. public void valueChange(ValueChangeEvent event) {
  182. setBuffer();
  183. }
  184. });
  185. main.addComponent(uploadBufferSelector);
  186. main.addComponent(up);
  187. l = new Label("Idle");
  188. main.addComponent(l);
  189. pi.setVisible(false);
  190. pi.setPollingInterval(1000);
  191. main.addComponent(pi);
  192. pi2.setVisible(false);
  193. pi2.setPollingInterval(1000);
  194. main.addComponent(pi2);
  195. memoryStatus = new Label();
  196. main.addComponent(memoryStatus);
  197. statusLayout.setMargin(true);
  198. status.setVisible(false);
  199. main.addComponent(status);
  200. final Button restart = new Button("R");
  201. restart.addListener(new Button.ClickListener() {
  202. @Override
  203. public void buttonClick(ClickEvent event) {
  204. LegacyWindow window = (LegacyWindow) event.getButton().getUI();
  205. window.getApplication().close();
  206. }
  207. });
  208. main.addComponent(restart);
  209. }
  210. private void setBuffer() {
  211. final String id = (String) uploadBufferSelector.getValue();
  212. if ("memory".equals(id)) {
  213. buffer = new MemoryBuffer();
  214. } else if ("tempfile".equals(id)) {
  215. buffer = new TmpFileBuffer();
  216. }
  217. up.setReceiver(buffer);
  218. }
  219. public void gc() {
  220. Runtime.getRuntime().gc();
  221. }
  222. public void readState() {
  223. final StringBuffer sb = new StringBuffer();
  224. if (up.isUploading()) {
  225. sb.append("Uploading...");
  226. sb.append(up.getBytesRead());
  227. sb.append("/");
  228. sb.append(up.getUploadSize());
  229. sb.append(" ");
  230. sb.append(Math.round(100 * up.getBytesRead()
  231. / (double) up.getUploadSize()));
  232. sb.append("%");
  233. } else {
  234. sb.append("Idle");
  235. }
  236. l.setValue(sb.toString());
  237. refreshMemUsage();
  238. }
  239. public interface Buffer extends StreamResource.StreamSource,
  240. Upload.Receiver {
  241. String getFileName();
  242. }
  243. public class MemoryBuffer implements Buffer {
  244. ByteArrayOutputStream outputBuffer = null;
  245. String mimeType;
  246. String fileName;
  247. public MemoryBuffer() {
  248. }
  249. @Override
  250. public InputStream getStream() {
  251. if (outputBuffer == null) {
  252. return null;
  253. }
  254. return new ByteArrayInputStream(outputBuffer.toByteArray());
  255. }
  256. /**
  257. * @see com.vaadin.ui.Upload.Receiver#receiveUpload(String, String)
  258. */
  259. @Override
  260. public OutputStream receiveUpload(String filename, String MIMEType) {
  261. fileName = filename;
  262. mimeType = MIMEType;
  263. outputBuffer = new ByteArrayOutputStream() {
  264. @Override
  265. public synchronized void write(byte[] b, int off, int len) {
  266. beSluggish();
  267. throwExecption();
  268. super.write(b, off, len);
  269. }
  270. };
  271. return outputBuffer;
  272. }
  273. /**
  274. * Returns the fileName.
  275. *
  276. * @return String
  277. */
  278. @Override
  279. public String getFileName() {
  280. return fileName;
  281. }
  282. /**
  283. * Returns the mimeType.
  284. *
  285. * @return String
  286. */
  287. public String getMimeType() {
  288. return mimeType;
  289. }
  290. }
  291. public class TmpFileBuffer implements Buffer {
  292. String mimeType;
  293. String fileName;
  294. private File file;
  295. public TmpFileBuffer() {
  296. final String tempFileName = "upload_tmpfile_"
  297. + System.currentTimeMillis();
  298. try {
  299. file = File.createTempFile(tempFileName, null);
  300. } catch (final IOException e) {
  301. // TODO Auto-generated catch block
  302. e.printStackTrace();
  303. }
  304. }
  305. @Override
  306. public InputStream getStream() {
  307. if (file == null) {
  308. return null;
  309. }
  310. try {
  311. return new FileInputStream(file);
  312. } catch (final FileNotFoundException e) {
  313. // TODO Auto-generated catch block
  314. e.printStackTrace();
  315. }
  316. return null;
  317. }
  318. /**
  319. * @see com.vaadin.ui.Upload.Receiver#receiveUpload(String, String)
  320. */
  321. @Override
  322. public OutputStream receiveUpload(String filename, String MIMEType) {
  323. fileName = filename;
  324. mimeType = MIMEType;
  325. try {
  326. return new FileOutputStream(file) {
  327. @Override
  328. public void write(byte[] b, int off, int len)
  329. throws IOException {
  330. beSluggish();
  331. throwExecption();
  332. super.write(b, off, len);
  333. }
  334. };
  335. } catch (final FileNotFoundException e) {
  336. // TODO Auto-generated catch block
  337. e.printStackTrace();
  338. }
  339. return null;
  340. }
  341. /**
  342. * Returns the fileName.
  343. *
  344. * @return String
  345. */
  346. @Override
  347. public String getFileName() {
  348. return fileName;
  349. }
  350. /**
  351. * Returns the mimeType.
  352. *
  353. * @return String
  354. */
  355. public String getMimeType() {
  356. return mimeType;
  357. }
  358. }
  359. @Override
  360. public void updateProgress(long readBytes, long contentLenght) {
  361. pi.setValue(new Float(readBytes / (float) contentLenght));
  362. refreshMemUsage();
  363. }
  364. private void refreshMemUsage() {
  365. memoryStatus.setValue("Not available in Java 1.4");
  366. StringBuffer mem = new StringBuffer();
  367. MemoryMXBean mmBean = ManagementFactory.getMemoryMXBean();
  368. mem.append("Heap (M):");
  369. mem.append(mmBean.getHeapMemoryUsage().getUsed() / 1048576);
  370. mem.append(" | Non-Heap (M):");
  371. mem.append(mmBean.getNonHeapMemoryUsage().getUsed() / 1048576);
  372. memoryStatus.setValue(mem.toString());
  373. }
  374. private void beSluggish() {
  375. if (beSluggish.getValue()) {
  376. try {
  377. Thread.sleep(1000);
  378. } catch (InterruptedException e) {
  379. // TODO Auto-generated catch block
  380. e.printStackTrace();
  381. }
  382. }
  383. }
  384. private void throwExecption() {
  385. if (throwExecption.getValue()) {
  386. throwExecption.setValue(false);
  387. throw new RuntimeException("Test execption in receiver.");
  388. }
  389. }
  390. }