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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. /*
  2. * Copyright 2000-2016 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.server.StreamResource;
  29. import com.vaadin.shared.ui.ContentMode;
  30. import com.vaadin.ui.Button;
  31. import com.vaadin.ui.Button.ClickEvent;
  32. import com.vaadin.ui.CheckBox;
  33. import com.vaadin.ui.CustomComponent;
  34. import com.vaadin.ui.Label;
  35. import com.vaadin.ui.Layout;
  36. import com.vaadin.ui.LegacyWindow;
  37. import com.vaadin.ui.Link;
  38. import com.vaadin.ui.Panel;
  39. import com.vaadin.ui.Upload;
  40. import com.vaadin.ui.Upload.FinishedEvent;
  41. import com.vaadin.ui.Upload.StartedEvent;
  42. import com.vaadin.ui.Upload.StartedListener;
  43. import com.vaadin.ui.VerticalLayout;
  44. import com.vaadin.v7.data.Property.ValueChangeEvent;
  45. import com.vaadin.v7.ui.AbstractField;
  46. import com.vaadin.v7.ui.ProgressIndicator;
  47. import com.vaadin.v7.ui.Select;
  48. import com.vaadin.v7.ui.TextField;
  49. public class TestForUpload extends CustomComponent
  50. implements 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 TextField 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(
  71. new Label("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 TextField("Test field");
  82. textFieldValue = new Label();
  83. main.addComponent(textField);
  84. main.addComponent(textFieldValue);
  85. up = new Upload("Upload", buffer);
  86. up.setImmediateMode(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.addStartedListener(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.addFinishedListener(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(
  116. "Finished with failure ( " + reason + " ), 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(
  129. new Label("<b>Name:</b> " + event.getFilename(),
  130. ContentMode.HTML));
  131. statusLayout.addComponent(
  132. new Label("<b>Mimetype:</b> " + event.getMIMEType(),
  133. ContentMode.HTML));
  134. statusLayout.addComponent(new Label(
  135. "<b>Size:</b> " + event.getLength() + " bytes.",
  136. ContentMode.HTML));
  137. statusLayout.addComponent(new Link(
  138. "Download " + buffer.getFileName(),
  139. new StreamResource(buffer, buffer.getFileName())));
  140. statusLayout.setVisible(true);
  141. }
  142. setBuffer();
  143. }
  144. });
  145. up.addProgressListener(new Upload.ProgressListener() {
  146. @Override
  147. public void updateProgress(long readBytes, long contentLenght) {
  148. pi2.setValue(new Float(readBytes / (float) contentLenght));
  149. refreshMemUsage();
  150. }
  151. });
  152. final Button b = new Button("Reed state from upload",
  153. new Button.ClickListener() {
  154. @Override
  155. public void buttonClick(ClickEvent event) {
  156. readState();
  157. }
  158. });
  159. final Button c = new Button("Force GC", new Button.ClickListener() {
  160. @Override
  161. public void buttonClick(ClickEvent event) {
  162. gc();
  163. }
  164. });
  165. main.addComponent(b);
  166. main.addComponent(c);
  167. main.addComponent(beSluggish);
  168. main.addComponent(throwExecption);
  169. main.addComponent(interrupt);
  170. interrupt.addClickListener(new Button.ClickListener() {
  171. @Override
  172. public void buttonClick(ClickEvent event) {
  173. up.interruptUpload();
  174. }
  175. });
  176. uploadBufferSelector = new Select("StreamVariable type");
  177. uploadBufferSelector.setImmediate(true);
  178. uploadBufferSelector.addItem("memory");
  179. uploadBufferSelector.setValue("memory");
  180. uploadBufferSelector.addItem("tempfile");
  181. uploadBufferSelector
  182. .addListener(new AbstractField.ValueChangeListener() {
  183. @Override
  184. public void valueChange(ValueChangeEvent event) {
  185. setBuffer();
  186. }
  187. });
  188. main.addComponent(uploadBufferSelector);
  189. main.addComponent(up);
  190. l = new Label("Idle");
  191. main.addComponent(l);
  192. pi.setVisible(false);
  193. pi.setPollingInterval(1000);
  194. main.addComponent(pi);
  195. pi2.setVisible(false);
  196. pi2.setPollingInterval(1000);
  197. main.addComponent(pi2);
  198. memoryStatus = new Label();
  199. main.addComponent(memoryStatus);
  200. statusLayout.setMargin(true);
  201. status.setVisible(false);
  202. main.addComponent(status);
  203. final Button restart = new Button("R");
  204. restart.addClickListener(new Button.ClickListener() {
  205. @Override
  206. public void buttonClick(ClickEvent event) {
  207. LegacyWindow window = (LegacyWindow) event.getButton().getUI();
  208. window.getApplication().close();
  209. }
  210. });
  211. main.addComponent(restart);
  212. }
  213. private void setBuffer() {
  214. final String id = (String) uploadBufferSelector.getValue();
  215. if ("memory".equals(id)) {
  216. buffer = new MemoryBuffer();
  217. } else if ("tempfile".equals(id)) {
  218. buffer = new TmpFileBuffer();
  219. }
  220. up.setReceiver(buffer);
  221. }
  222. public void gc() {
  223. Runtime.getRuntime().gc();
  224. }
  225. public void readState() {
  226. final StringBuffer sb = new StringBuffer();
  227. if (up.isUploading()) {
  228. sb.append("Uploading...");
  229. sb.append(up.getBytesRead());
  230. sb.append("/");
  231. sb.append(up.getUploadSize());
  232. sb.append(" ");
  233. sb.append(Math.round(
  234. 100 * up.getBytesRead() / (double) up.getUploadSize()));
  235. sb.append("%");
  236. } else {
  237. sb.append("Idle");
  238. }
  239. l.setValue(sb.toString());
  240. refreshMemUsage();
  241. }
  242. public interface Buffer
  243. extends StreamResource.StreamSource, Upload.Receiver {
  244. String getFileName();
  245. }
  246. public class MemoryBuffer implements Buffer {
  247. ByteArrayOutputStream outputBuffer = null;
  248. String mimeType;
  249. String fileName;
  250. public MemoryBuffer() {
  251. }
  252. @Override
  253. public InputStream getStream() {
  254. if (outputBuffer == null) {
  255. return null;
  256. }
  257. return new ByteArrayInputStream(outputBuffer.toByteArray());
  258. }
  259. /**
  260. * @see com.vaadin.ui.Upload.Receiver#receiveUpload(String, String)
  261. */
  262. @Override
  263. public OutputStream receiveUpload(String filename, String MIMEType) {
  264. fileName = filename;
  265. mimeType = MIMEType;
  266. outputBuffer = new ByteArrayOutputStream() {
  267. @Override
  268. public synchronized void write(byte[] b, int off, int len) {
  269. beSluggish();
  270. throwExecption();
  271. super.write(b, off, len);
  272. }
  273. };
  274. return outputBuffer;
  275. }
  276. /**
  277. * Returns the fileName.
  278. *
  279. * @return String
  280. */
  281. @Override
  282. public String getFileName() {
  283. return fileName;
  284. }
  285. /**
  286. * Returns the mimeType.
  287. *
  288. * @return String
  289. */
  290. public String getMimeType() {
  291. return mimeType;
  292. }
  293. }
  294. public class TmpFileBuffer implements Buffer {
  295. String mimeType;
  296. String fileName;
  297. private File file;
  298. public TmpFileBuffer() {
  299. final String tempFileName = "upload_tmpfile_"
  300. + System.currentTimeMillis();
  301. try {
  302. file = File.createTempFile(tempFileName, null);
  303. } catch (final IOException e) {
  304. // TODO Auto-generated catch block
  305. e.printStackTrace();
  306. }
  307. }
  308. @Override
  309. public InputStream getStream() {
  310. if (file == null) {
  311. return null;
  312. }
  313. try {
  314. return new FileInputStream(file);
  315. } catch (final FileNotFoundException e) {
  316. // TODO Auto-generated catch block
  317. e.printStackTrace();
  318. }
  319. return null;
  320. }
  321. /**
  322. * @see com.vaadin.ui.Upload.Receiver#receiveUpload(String, String)
  323. */
  324. @Override
  325. public OutputStream receiveUpload(String filename, String MIMEType) {
  326. fileName = filename;
  327. mimeType = MIMEType;
  328. try {
  329. return new FileOutputStream(file) {
  330. @Override
  331. public void write(byte[] b, int off, int len)
  332. throws IOException {
  333. beSluggish();
  334. throwExecption();
  335. super.write(b, off, len);
  336. }
  337. };
  338. } catch (final FileNotFoundException e) {
  339. // TODO Auto-generated catch block
  340. e.printStackTrace();
  341. }
  342. return null;
  343. }
  344. /**
  345. * Returns the fileName.
  346. *
  347. * @return String
  348. */
  349. @Override
  350. public String getFileName() {
  351. return fileName;
  352. }
  353. /**
  354. * Returns the mimeType.
  355. *
  356. * @return String
  357. */
  358. public String getMimeType() {
  359. return mimeType;
  360. }
  361. }
  362. @Override
  363. public void updateProgress(long readBytes, long contentLenght) {
  364. pi.setValue(new Float(readBytes / (float) contentLenght));
  365. refreshMemUsage();
  366. }
  367. private void refreshMemUsage() {
  368. memoryStatus.setValue("Not available in Java 1.4");
  369. StringBuffer mem = new StringBuffer();
  370. MemoryMXBean mmBean = ManagementFactory.getMemoryMXBean();
  371. mem.append("Heap (M):");
  372. mem.append(mmBean.getHeapMemoryUsage().getUsed() / 1048576);
  373. mem.append(" | Non-Heap (M):");
  374. mem.append(mmBean.getNonHeapMemoryUsage().getUsed() / 1048576);
  375. memoryStatus.setValue(mem.toString());
  376. }
  377. private void beSluggish() {
  378. if (beSluggish.getValue()) {
  379. try {
  380. Thread.sleep(1000);
  381. } catch (InterruptedException e) {
  382. // TODO Auto-generated catch block
  383. e.printStackTrace();
  384. }
  385. }
  386. }
  387. private void throwExecption() {
  388. if (throwExecption.getValue()) {
  389. throwExecption.setValue(false);
  390. throw new RuntimeException("Test execption in receiver.");
  391. }
  392. }
  393. }