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 package org.apache.hc.core5.http.nio.entity;
29
30 import java.io.File;
31 import java.io.FileOutputStream;
32 import java.io.OutputStreamWriter;
33 import java.io.Writer;
34 import java.nio.charset.StandardCharsets;
35
36 import org.apache.hc.core5.http.ContentType;
37 import org.apache.hc.core5.http.WritableByteChannelMock;
38 import org.apache.hc.core5.http.nio.AsyncEntityProducer;
39 import org.apache.hc.core5.http.nio.BasicDataStreamChannel;
40 import org.apache.hc.core5.http.nio.DataStreamChannel;
41 import org.junit.After;
42 import org.junit.Assert;
43 import org.junit.Before;
44 import org.junit.Test;
45
46 public class TestFileAsyncEntityProducer {
47
48 private File tempFile;
49
50 @Before
51 public void setup() throws Exception {
52 tempFile = File.createTempFile("testing", ".txt");
53 try (final Writer writer = new OutputStreamWriter(new FileOutputStream(tempFile), StandardCharsets.US_ASCII)) {
54 writer.append("abcdef");
55 writer.flush();
56 }
57 }
58
59 @After
60 public void cleanup() {
61 if (tempFile != null) {
62 tempFile.delete();
63 tempFile = null;
64 }
65 }
66 @Test
67 public void testTextContent() throws Exception {
68
69 final AsyncEntityProducer producer = new FileEntityProducer(tempFile, ContentType.TEXT_PLAIN);
70
71 Assert.assertEquals(6, producer.getContentLength());
72 Assert.assertEquals(ContentType.TEXT_PLAIN.toString(), producer.getContentType());
73 Assert.assertEquals(null, producer.getContentEncoding());
74
75 final WritableByteChannelMocknelMock.html#WritableByteChannelMock">WritableByteChannelMock byteChannel = new WritableByteChannelMock(1024);
76 final DataStreamChannel streamChannel = new BasicDataStreamChannel(byteChannel);
77
78 producer.produce(streamChannel);
79 producer.produce(streamChannel);
80
81 Assert.assertFalse(byteChannel.isOpen());
82 Assert.assertEquals("abcdef", byteChannel.dump(StandardCharsets.US_ASCII));
83 }
84
85 @Test
86 public void testTextContentRepeatable() throws Exception {
87 final AsyncEntityProducer producer = new FileEntityProducer(tempFile, ContentType.TEXT_PLAIN);
88
89 Assert.assertEquals(6, producer.getContentLength());
90 Assert.assertEquals(ContentType.TEXT_PLAIN.toString(), producer.getContentType());
91 Assert.assertEquals(null, producer.getContentEncoding());
92
93 for (int i = 0; i < 3; i++) {
94 final WritableByteChannelMocknelMock.html#WritableByteChannelMock">WritableByteChannelMock byteChannel = new WritableByteChannelMock(1024);
95 final DataStreamChannel streamChannel = new BasicDataStreamChannel(byteChannel);
96
97 producer.produce(streamChannel);
98 producer.produce(streamChannel);
99
100 Assert.assertFalse(byteChannel.isOpen());
101 Assert.assertEquals("abcdef", byteChannel.dump(StandardCharsets.US_ASCII));
102
103 producer.releaseResources();
104 }
105 }
106
107 }