Repository navigation
Expand file tree
/
Copy pathExchange.java
More file actions
225 lines (207 loc) · 7.19 KB
/
Copy pathExchange.java
File metadata and controls
225 lines (207 loc) · 7.19 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
package org.javawebstack.httpserver;
import com.google.gson.JsonElement;
import org.javawebstack.abstractdata.AbstractElement;
import org.javawebstack.abstractdata.AbstractNull;
import org.javawebstack.httpserver.helper.HttpMethod;
import org.javawebstack.httpserver.helper.MimeType;
import org.javawebstack.validator.ValidationException;
import org.javawebstack.validator.ValidationResult;
import org.javawebstack.validator.Validator;
import javax.servlet.MultipartConfigElement;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class Exchange {
private final HTTPServer server;
private final HttpMethod method;
private final String path;
private byte[] body = null;
public Map<String, Object> pathVariables;
public final Map<String, String> parameters = new HashMap<>();
private final HttpServletRequest request;
private final HttpServletResponse response;
private final Map<String, Object> attributes = new HashMap<>();
public Exchange(HTTPServer server, HttpServletRequest request, HttpServletResponse response){
this.server = server;
this.request = request;
this.response = response;
this.path = request.getPathInfo();
method = "websocket".equalsIgnoreCase(request.getHeader("Upgrade")) ? HttpMethod.WEBSOCKET : HttpMethod.valueOf(request.getMethod());
}
public <T> T body(Class<T> clazz){
if(body == null)
body = read();
if(clazz == byte[].class)
return (T) body;
String body = new String(this.body, StandardCharsets.UTF_8);
if(clazz == String.class)
return (T) body;
MimeType type = MimeType.byMimeType(getContentType());
if(type == null)
type = MimeType.JSON;
AbstractElement request = AbstractNull.INSTANCE;
switch (type){
case JSON:
request = AbstractElement.fromJson(body);
break;
case YAML:
request = AbstractElement.fromYaml(body, !(clazz.isArray() || Collection.class.isAssignableFrom(clazz)));
break;
case X_WWW_FORM_URLENCODED:
request = AbstractElement.fromFormData(body);
break;
}
ValidationResult result = Validator.getValidator(clazz).validate(request);
if(!result.isValid())
throw new ValidationException(result);
return server.getAbstractMapper().fromAbstract(request, clazz);
}
public HTTPServer getServer() {
return server;
}
public HttpMethod getMethod() {
return method;
}
public String getPath() {
return path;
}
public String getContentType(){
return request.getContentType();
}
public byte[] read(){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
InputStream is = request.getInputStream();
byte [] data = new byte[1024];
int r;
while (is.available() > 0){
r = is.read(data);
baos.write(data, 0, r);
}
}catch(IOException ex){
throw new RuntimeException(ex);
}
return baos.toByteArray();
}
public Exchange write(String data){
write(data.getBytes(StandardCharsets.UTF_8));
return this;
}
public Exchange write(byte[] bytes){
try {
response.getOutputStream().write(bytes);
}catch (IOException ignored){}
return this;
}
public Exchange write(byte[] bytes, int offset, int length){
try {
response.getOutputStream().write(bytes, offset, length);
} catch (IOException ignored){}
return this;
}
public Exchange close() {
try {
response.getOutputStream().close();
} catch (IOException ignored){}
return this;
}
public Exchange header(String header, String value){
if(header.equalsIgnoreCase("content-type")){
response.setContentType(value);
return this;
}
response.setHeader(header, value);
return this;
}
public Exchange status(int code){
response.setStatus(code);
return this;
}
public String header(String header){
return request.getHeader(header);
}
public Exchange redirect(String url){
response.setStatus(302);
try {
response.sendRedirect(url);
}catch (IOException ex){
throw new RuntimeException(ex);
}
return this;
}
public List<Locale> locales(){
return Collections.list(request.getLocales());
}
public Locale locale(Locale... possible){
if(possible.length == 0)
return request.getLocale();
List<Locale> possibleList = Arrays.asList(possible);
for(Locale l : locales()){
if(possibleList.contains(l))
return l;
}
return possible[0];
}
public Exchange contentType(MimeType type){
return contentType(type.getMimeTypes().get(0));
}
public Exchange contentType(String contentType){
return header("Content-Type", contentType);
}
public HttpServletRequest rawRequest(){
return request;
}
public HttpServletResponse rawResponse(){
return response;
}
public <T> T attrib(String key){
if(attributes.get(key) == null)
return null;
return (T) attributes.get(key);
}
public Exchange attrib(String key, Object value){
attributes.put(key, value);
return this;
}
public String bearerAuth(){
String auth = header("Authorization");
if(auth == null)
return null;
if(!auth.startsWith("Bearer "))
return null;
return auth.substring(7);
}
public <T> T getBodyPath(String path, Class<T> clazz){
return server.getAbstractMapper().fromAbstract(getBodyPathElement(path), clazz);
}
public AbstractElement getBodyPathElement(String path){
return getPathElement(body(AbstractElement.class), path);
}
protected static AbstractElement getPathElement(AbstractElement source, String path){
if(source == null || path == null || path.length() == 0)
return source;
if(!path.contains(".")){
if(source.isObject()){
return source.object().get(path);
}else if(source.isArray()){
return source.array().get(Integer.parseInt(path));
}else{
return null;
}
}
String[] spl = path.split("\\.");
return getPathElement(getPathElement(source, spl[0]), path.substring(spl[0].length()+1));
}
public Exchange enableMultipart(String location){
enableMultipart(location, -1L);
return this;
}
public Exchange enableMultipart(String location, long maxFileSize){
request.setAttribute("org.eclipse.jetty.multipartConfig", new MultipartConfigElement(location, maxFileSize, -1L, 0));
return this;
}
}