1/*
2 * Copyright 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.conscrypt.testing;
18
19import java.io.IOException;
20import java.io.InputStream;
21import java.io.OutputStream;
22import javax.net.ssl.SSLSocket;
23
24/**
25 * Client-side endpoint. Provides basic services for sending/receiving messages from the client
26 * socket.
27 */
28public final class TestClient {
29    private final SSLSocket socket;
30    private InputStream input;
31    private OutputStream output;
32
33    public TestClient(SSLSocket socket) {
34        this.socket = socket;
35    }
36
37    public void start() {
38        try {
39            socket.startHandshake();
40            input = socket.getInputStream();
41            output = socket.getOutputStream();
42        } catch (IOException e) {
43            throw new RuntimeException(e);
44        }
45    }
46
47    public void stop() {
48        try {
49            socket.close();
50        } catch (IOException e) {
51            throw new RuntimeException(e);
52        }
53    }
54
55    public int readMessage(byte[] buffer) {
56        try {
57            int totalBytesRead = 0;
58            while (totalBytesRead < buffer.length) {
59                int remaining = buffer.length - totalBytesRead;
60                int bytesRead = input.read(buffer, totalBytesRead, remaining);
61                if (bytesRead == -1) {
62                    break;
63                }
64                totalBytesRead += bytesRead;
65            }
66            return totalBytesRead;
67        } catch (Throwable e) {
68            throw new RuntimeException(e);
69        }
70    }
71
72    public void sendMessage(byte[] data) {
73        try {
74            output.write(data);
75        } catch (IOException e) {
76            throw new RuntimeException(e);
77        }
78    }
79
80    public void flush() {
81        try {
82            output.flush();
83        } catch (IOException e) {
84            throw new RuntimeException(e);
85        }
86    }
87}
88