您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

TestForUpload.java 12KB

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