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.http.localserver;
29
30 import java.io.IOException;
31 import java.util.Locale;
32
33 import org.apache.http.Consts;
34 import org.apache.http.HttpException;
35 import org.apache.http.HttpRequest;
36 import org.apache.http.HttpResponse;
37 import org.apache.http.HttpStatus;
38 import org.apache.http.MethodNotSupportedException;
39 import org.apache.http.entity.ContentType;
40 import org.apache.http.nio.entity.NByteArrayEntity;
41 import org.apache.http.protocol.HttpContext;
42 import org.apache.http.protocol.HttpRequestHandler;
43
44
45
46
47 public class RandomHandler implements HttpRequestHandler {
48
49 private final static byte[] RANGE;
50 static {
51 RANGE = ("abcdefghijklmnopqrstuvwxyz" +
52 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789"
53 ).getBytes(Consts.ASCII);
54 }
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71 @Override
72 public void handle(final HttpRequest request,
73 final HttpResponse response,
74 final HttpContext context)
75 throws HttpException, IOException {
76
77 final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ROOT);
78 if (!"GET".equals(method) && !"HEAD".equals(method)) {
79 throw new MethodNotSupportedException
80 (method + " not supported by " + getClass().getName());
81 }
82
83 final String uri = request.getRequestLine().getUri();
84 final int slash = uri.lastIndexOf('/');
85 int length = -1;
86 if (slash < uri.length()-1) {
87 try {
88
89 length = Integer.parseInt(uri.substring(slash+1));
90
91 if (length < 0) {
92 response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
93 response.setReasonPhrase("LENGTH " + length);
94 }
95 } catch (final NumberFormatException nfx) {
96 response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
97 response.setReasonPhrase(nfx.toString());
98 }
99 } else {
100
101 length = 1 + (int)(Math.random() * 79.0);
102 }
103
104 if (length >= 0) {
105 final byte[] data = new byte[length];
106 for (int i = 0; i < length; i++) {
107 double value = 0.0;
108
109 if (i%5 == 0) {
110 value = Math.random();
111 }
112 value = value * RANGE.length;
113 final int d = (int) value;
114 value = value - d;
115 data[i] = RANGE[d];
116 }
117 final NByteArrayEntity bae = new NByteArrayEntity(data, ContentType.DEFAULT_TEXT);
118 response.setEntity(bae);
119 }
120 }
121
122 }