1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.springframework.mock.web.test;
18
19 import java.io.ByteArrayInputStream;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.util.Collection;
23 import java.util.Collections;
24 import javax.servlet.http.Part;
25
26 import org.springframework.util.Assert;
27 import org.springframework.util.FileCopyUtils;
28
29
30
31
32
33
34
35
36 public class MockPart implements Part {
37
38 private static final String CONTENT_TYPE = "Content-Type";
39
40 private final String name;
41
42 private String contentType;
43
44 private final byte[] content;
45
46
47
48
49
50
51 public MockPart(String name, byte[] content) {
52 this(name, "", content);
53 }
54
55
56
57
58
59
60
61 public MockPart(String name, InputStream contentStream) throws IOException {
62 this(name, "", FileCopyUtils.copyToByteArray(contentStream));
63 }
64
65
66
67
68
69
70
71 public MockPart(String name, String contentType, byte[] content) {
72 Assert.hasLength(name, "Name must not be null");
73 this.name = name;
74 this.contentType = contentType;
75 this.content = (content != null ? content : new byte[0]);
76 }
77
78
79
80
81
82
83
84
85 public MockPart(String name, String contentType, InputStream contentStream)
86 throws IOException {
87
88 this(name, contentType, FileCopyUtils.copyToByteArray(contentStream));
89 }
90
91
92 @Override
93 public String getName() {
94 return this.name;
95 }
96
97 @Override
98 public String getContentType() {
99 return this.contentType;
100 }
101
102 @Override
103 public long getSize() {
104 return this.content.length;
105 }
106
107 @Override
108 public InputStream getInputStream() throws IOException {
109 return new ByteArrayInputStream(this.content);
110 }
111
112 @Override
113 public String getHeader(String name) {
114 if (CONTENT_TYPE.equalsIgnoreCase(name)) {
115 return this.contentType;
116 }
117 else {
118 return null;
119 }
120 }
121
122 @Override
123 public Collection<String> getHeaders(String name) {
124 if (CONTENT_TYPE.equalsIgnoreCase(name)) {
125 return Collections.singleton(this.contentType);
126 }
127 else {
128 return null;
129 }
130 }
131
132 @Override
133 public Collection<String> getHeaderNames() {
134 return Collections.singleton(CONTENT_TYPE);
135 }
136
137 @Override
138 public void write(String fileName) throws IOException {
139 throw new UnsupportedOperationException();
140 }
141
142 @Override
143 public void delete() throws IOException {
144 throw new UnsupportedOperationException();
145 }
146
147 }