aboutsummaryrefslogtreecommitdiffstats
path: root/jdisc_http_service/src/test/java/com/yahoo/jdisc/http/server/jetty/SimpleHttpClient.java
blob: 79a2dc5a2fb788a6e2bab2e5688f15c38832d6c3 (plain) (blame)
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
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.http.server.jetty;

import com.yahoo.jdisc.http.HttpHeaders;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.FormBodyPart;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.hamcrest.Matcher;
import org.hamcrest.MatcherAssert;

import javax.net.ssl.SSLContext;
import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.regex.Pattern;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;

/**
 * A simple http client for testing
 *
 * @author Simon Thoresen Hult
 */
public class SimpleHttpClient {

    private final HttpClient delegate;
    private final String scheme;
    private final int listenPort;

    public SimpleHttpClient(final SSLContext sslContext, final int listenPort, final boolean useCompression) {
        HttpClientBuilder builder = HttpClientBuilder.create();
        if (!useCompression) {
            builder.disableContentCompression();
        }
        if (sslContext != null) {
            SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(
                    sslContext,
                    SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            builder.setSSLSocketFactory(sslConnectionFactory);

            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", sslConnectionFactory)
                    .build();
            builder.setConnectionManager(new BasicHttpClientConnectionManager(registry));
            scheme = "https";
        } else {
            scheme = "http";
        }
        this.delegate = builder.build();
        this.listenPort = listenPort;
    }

    public URI newUri(final String path) {
        return URI.create(scheme + "://localhost:" + listenPort + path);
    }

    public RequestExecutor newGet(final String path) {
        return newRequest(new HttpGet(newUri(path)));
    }

    public RequestExecutor newPost(final String path) {
        return newRequest(new HttpPost(newUri(path)));
    }

    public RequestExecutor newRequest(final HttpUriRequest request) {
        return new RequestExecutor().setRequest(request);
    }

    public ResponseValidator execute(final HttpUriRequest request) throws IOException {
        return newRequest(request).execute();
    }

    public ResponseValidator get(final String path) throws IOException {
        return newGet(path).execute();
    }

    public String raw(final String request) throws IOException {
        final Socket socket = new Socket("localhost", listenPort);
        final OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8);
        out.write(request);
        out.flush();

        final ByteArrayOutputStream buf = new ByteArrayOutputStream();
        final InputStream in = socket.getInputStream();
        final int[] TERMINATOR = { '\r', '\n', '\r', '\n' };
        for (int pos = 0; pos < TERMINATOR.length; ++pos) {
            final int b = in.read();
            if (b < 0) {
                throw new EOFException();
            }
            if (b != TERMINATOR[pos]) {
                pos = -1;
            }
            buf.write(b);
        }
        final String response = buf.toString(StandardCharsets.UTF_8.name());
        final java.util.regex.Matcher matcher = Pattern.compile(HttpHeaders.Names.CONTENT_LENGTH + ": (.+)\r\n").matcher(response);
        if (matcher.find()) {
            final int len = Integer.valueOf(matcher.group(1));
            for (int i = 0; i < len; ++i) {
                final int b = in.read();
                if (b < 0) {
                    throw new EOFException();
                }
                buf.write(b);
            }
        }

        socket.close();
        return buf.toString(StandardCharsets.UTF_8.name());
    }

    public class RequestExecutor {

        private HttpUriRequest request;
        private HttpEntity entity;

        public RequestExecutor setRequest(final HttpUriRequest request) {
            this.request = request;
            return this;
        }

        public RequestExecutor addHeader(final String name, final String value) {
            this.request.addHeader(name, value);
            return this;
        }

        public RequestExecutor setContent(final String content) {
            this.entity = new StringEntity(content, StandardCharsets.UTF_8);
            return this;
        }

        public RequestExecutor setBinaryContent(final byte[] content) {
            this.entity = new ByteArrayEntity(content);
            return this;
        }

        public RequestExecutor setMultipartContent(final FormBodyPart... parts) {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            Arrays.stream(parts).forEach(part -> builder.addPart(part.getName(), part.getBody()));
            this.entity = builder.build();
            return this;
        }

        public ResponseValidator execute() throws IOException {
            if (entity != null) {
                ((HttpPost)request).setEntity(entity);
            }
            return new ResponseValidator(delegate.execute(request));
        }
    }

    public static class ResponseValidator {

        private final HttpResponse response;
        private final String content;

        public ResponseValidator(final HttpResponse response) throws IOException {
            this.response = response;

            final HttpEntity entity = response.getEntity();
            this.content = entity == null ? null :
                           EntityUtils.toString(entity, StandardCharsets.UTF_8);
        }

        public ResponseValidator expectStatusCode(final Matcher<Integer> matcher) {
            MatcherAssert.assertThat(response.getStatusLine().getStatusCode(), matcher);
            return this;
        }

        public ResponseValidator expectHeader(final String headerName, final Matcher<String> matcher) {
            final Header firstHeader = response.getFirstHeader(headerName);
            final String headerValue = firstHeader != null ? firstHeader.getValue() : null;
            MatcherAssert.assertThat(headerValue, matcher);
            assertThat(firstHeader, is(not(nullValue())));
            return this;
        }

        public ResponseValidator expectNoHeader(final String headerName) {
            final Header firstHeader = response.getFirstHeader(headerName);
            assertThat(firstHeader, is(nullValue()));
            return this;
        }

        public ResponseValidator expectContent(final Matcher<String> matcher) throws IOException {
            MatcherAssert.assertThat(content, matcher);
            return this;
        }

        public ResponseValidator expectTrailer(final String trailerName, final Matcher<String> matcher) {
            // TODO: check trailer, not header
            return expectHeader(trailerName, matcher);
        }
    }
}