aboutsummaryrefslogtreecommitdiff
path: root/apps/SdkController/src/com/android/tools/sdkcontroller/lib/Socket.java
blob: 08e6b2813ed71042f259bc2b08105b6c77c92ff0 (plain)
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
/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.android.tools.sdkcontroller.lib;

import android.net.LocalSocket;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteOrder;
import java.nio.channels.ClosedChannelException;

/**
 * Encapsulates a connection with the emulator over a UNIX-domain socket.
 */
public class Socket {
    /** UNIX-domain socket connected with the emulator. */
    private LocalSocket mSocket = null;
    /** Channel name for the connection established via this socket. */
    private String mChannelName;
    /** Endianness of data transferred in this connection. */
    private ByteOrder mEndian;

    /** Tag for message logging. */
    private static final String TAG = "SdkControllerSocket";
    /** Controls debug log. */
    private static boolean DEBUG = false;

    /**
     * Constructs Socket instance.
     *
     * @param socket Socket connection with the emulator.
     * @param name Channel port name for this connection.
     * @param endian Endianness of data transferred in this connection.
     */
    public Socket(LocalSocket socket, String name, ByteOrder endian) {
        mSocket = socket;
        mChannelName = name;
        mEndian = endian;
        if (DEBUG) Log.d(TAG, "Socket is constructed for " + mChannelName);
    }

    /**
     * Gets connection status of this socket.
     *
     * @return true if socket is connected, or false if socket is not connected.
     */
    public boolean isConnected() {
        return mSocket != null;
    }

    /**
     * Gets channel name for this socket.
     *
     * @return Channel name for this socket.
     */
    public String getChannelName() {
        return mChannelName;
    }

    /**
     * Gets endianness of data transferred via this socket.
     *
     * @return Endianness of data transferred via this socket.
     */
    public ByteOrder getEndian() {
        return mEndian;
    }

    /**
     * Sends data to the socket.
     *
     * @param data Data to send. Data size is defined by the length of the
     *            array.
     * @throws IOException
     */
    public void send(byte[] data) throws IOException {
        // Use local copy of the socket, ensuring it's not going to NULL while
        // we're working with it. If it gets closed, while we're in the middle
        // of data transfer - it's OK, since it will produce an exception, and
        // the caller will gracefully handle it.
        //
        // Same technique is used everywhere in this class where mSocket member
        // is touched.
        LocalSocket socket = mSocket;
        if (socket == null) {
            Logw("'send' request on closed Socket " + mChannelName);
            throw new ClosedChannelException();
        }
        socket.getOutputStream().write(data);
    }

    /**
     * Sends data to the socket.
     *
     * @param data Data to send.
     * @param offset The start position in data from where to get bytes.
     * @param len The number of bytes from data to write to this socket.
     * @throws IOException
     */
    public void send(byte[] data, int offset, int len) throws IOException {
        LocalSocket socket = mSocket;
        if (socket == null) {
            Logw("'send' request on closed Socket " + mChannelName);
            throw new ClosedChannelException();
        }
        socket.getOutputStream().write(data, offset, len);
    }

    /**
     * Receives data from the socket.
     *
     * @param socket Socket from where to receive data.
     * @param data Array where to save received data.
     * @param len Number of bytes to receive.
     * @throws IOException
     */
    public static void receive(LocalSocket socket, byte[] data, int len) throws IOException {
        final InputStream is = socket.getInputStream();
        int received = 0;
        while (received != len) {
            final int chunk = is.read(data, received, len - received);
            if (chunk < 0) {
                throw new IOException(
                        "I/O failure while receiving SDK controller data from socket.");
            }
            received += chunk;
        }
    }

    /**
     * Receives data from the socket.
     *
     * @param data Array where to save received data.
     * @param len Number of bytes to receive.
     * @throws IOException
     */
    public void receive(byte[] data, int len) throws IOException {
        LocalSocket socket = mSocket;
        if (socket == null) {
            Logw("'receive' request on closed Socket " + mChannelName);
            throw new ClosedChannelException();
        }
        receive(socket, data, len);
    }

    /**
     * Receives data from the socket.
     *
     * @param data Array where to save received data. Data size is defined by
     *            the size of the array.
     * @throws IOException
     */
    public void receive(byte[] data) throws IOException {
        receive(data, data.length);
    }

    /**
     * Closes the socket.
     *
     * @return true if socket has been closed in this call, or false if it had
     *         been already closed when this method has been called.
     */
    public boolean close() {
        // This is the only place in this class where we will null the socket
        // object. Since this method can be called concurrently from different
        // threads, lets do this under the lock.
        LocalSocket socket;
        synchronized (this) {
            socket = mSocket;
            mSocket = null;
        }
        if (socket != null) {
            try {
                // Force all I/O to stop before closing the socket.
                socket.shutdownInput();
                socket.shutdownOutput();
                socket.close();
                if (DEBUG) Log.d(TAG, "Socket is closed for " + mChannelName);
                return true;
            } catch (IOException e) {
                Loge("Exception " + e + " while closing Socket for " + mChannelName);
            }
        }
        return false;
    }

    /***************************************************************************
     * Logging wrappers
     **************************************************************************/

    private void Loge(String log) {
        Log.e(TAG, log);
    }

    private void Logw(String log) {
        Log.w(TAG, log);
    }
}