File: ControlThread.java

package info (click to toggle)
libjpf-java 1.5.1%2Bdfsg-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 2,280 kB
  • sloc: java: 13,449; xml: 337; makefile: 17
file content (343 lines) | stat: -rw-r--r-- 12,718 bytes parent folder | download | duplicates (4)
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/*****************************************************************************
 * Java Plug-in Framework (JPF)
 * Copyright (C) 2004-2007 Dmitry Olshansky
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *****************************************************************************/
package org.java.plugin.boot;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @version $Id$
 */
final class ControlThread extends Thread {
    static boolean isApplicationRunning(final InetAddress host,
            final int port) {
        try {
            Socket socket = new Socket(host, port);
            try {
                socket.setKeepAlive(true);
                String test = "" + System.currentTimeMillis(); //$NON-NLS-1$
                OutputStream out = socket.getOutputStream();
                InputStream in = null;
                try {
                    System.out.println("found running control service on " //$NON-NLS-1$
                            + host + ":" + port); //$NON-NLS-1$
                    out.write(("PING " + test).getBytes()); //$NON-NLS-1$
                    out.flush();
                    socket.shutdownOutput();
                    in = socket.getInputStream();
                    StringBuilder commandResult = new StringBuilder();
                    byte[] buf = new byte[16];
                    int len;
                    while ((len = in.read(buf)) != -1) {
                        commandResult.append(new String(buf, 0, len));
                    }
                    socket.shutdownInput();
                    if (commandResult.toString().startsWith("OK") //$NON-NLS-1$
                            && (commandResult.toString().indexOf(test) != -1)) {
                        System.out.println("PING command succeed"); //$NON-NLS-1$
                        return true;
                    }
                    System.out.println("PING command failed"); //$NON-NLS-1$
                } finally {
                    try {
                        out.close();
                    } catch (IOException ioe) {
                        // ignore
                    }
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException ioe) {
                            // ignore
                        }
                    }
                }
            } finally {
                socket.close();
            }
        } catch (IOException ioe) {
            System.out.println(
                    "seems that there is no control service running on " //$NON-NLS-1$
                    + host + ":" + port); //$NON-NLS-1$
            //ioe.printStackTrace();
        }
        return false;
    }
    
    static boolean stopRunningApplication(final InetAddress host,
            final int port) {
        boolean result = false;
        try {
            Socket socket = new Socket(host, port);
            try {
                socket.setKeepAlive(true);
                OutputStream out = socket.getOutputStream();
                InputStream in = null;
                try {
                    System.out.println("found running control service on " //$NON-NLS-1$
                            + host + ":" + port); //$NON-NLS-1$
                    out.write("STOP".getBytes()); //$NON-NLS-1$
                    out.flush();
                    socket.shutdownOutput();
                    in = socket.getInputStream();
                    StringBuilder commandResult = new StringBuilder();
                    byte[] buf = new byte[16];
                    int len;
                    while ((len = in.read(buf)) != -1) {
                        commandResult.append(new String(buf, 0, len));
                    }
                    socket.shutdownInput();
                    if (commandResult.toString().startsWith("OK")) { //$NON-NLS-1$
                        System.out.println("STOP command succeed"); //$NON-NLS-1$
                        result = true;
                    } else {
                        System.out.println("STOP command failed"); //$NON-NLS-1$
                    }
                } finally {
                    try {
                        out.close();
                    } catch (IOException ioe) {
                        // ignore
                    }
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException ioe) {
                            // ignore
                        }
                    }
                }
            } finally {
                socket.close();
            }
        } catch (IOException ioe) {
            System.out.println(
                    "seems that there is no control service running on " //$NON-NLS-1$
                    + host + ":" + port); //$NON-NLS-1$
            //ioe.printStackTrace();
        }
        if (result) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException ie) {
                // ignore
            }
        }
        return result;
    }

    private Log log;

    private ServerSocket serverSocket;
    private final ServiceApplication application;
    private boolean appRunning;
    
    ControlThread(final InetAddress host, final int port,
            final ServiceApplication server) throws Exception {
        log = LogFactory.getLog(this.getClass());
        application = server;
        serverSocket = new ServerSocket(port, 1, host);
        appRunning = true;
        setName("jpf-application-control-thread"); //$NON-NLS-1$
    }
    
    /**
     * @see java.lang.Runnable#run()
     */
    @Override
    public void run() {
        try {
            while (true) {
                try {
                    Socket clientSocket = serverSocket.accept();
                    try {
                        if (handleRequest(clientSocket)) {
                            break;
                        }
                    } finally {
                        try {
                            clientSocket.close();
                        } catch (IOException ioe) {
                            // ignore
                        }
                    }
                } catch (Exception e) {
                    warn("error on server socket", e); //$NON-NLS-1$
                    break;
                }
            }
        } catch (Exception e) {
            error(e);
        } finally {
            try {
                serverSocket.close();
            } catch (IOException ioe) {
                warn("error closing server socket", ioe); //$NON-NLS-1$
            }
            if (appRunning) {
                stopApplication();
            }
        }
    }
    
    private synchronized boolean handleRequest(final Socket clientSocket) {
        debug("handling control request"); //$NON-NLS-1$
        if (!isValidRemoteHost(clientSocket.getInetAddress())) {
            warn("incoming connection to control socket registered" //$NON-NLS-1$
                    + " from REMOTE address " + clientSocket.getInetAddress() //$NON-NLS-1$
                    + ", attempt to execute command was IGNORED"); //$NON-NLS-1$
            try {
                clientSocket.close();
            } catch (IOException e) {
                // ignore
            }
            return false;
        }
        debug("processing control request"); //$NON-NLS-1$
        boolean result = false;
        try {
            String commandResult;
            InputStream in = clientSocket.getInputStream();
            OutputStream out = null;
            try {
                StringBuilder command = new StringBuilder();
                byte[] buf = new byte[16];
                int len;
                while ((len = in.read(buf)) != -1) {
                    command.append(new String(buf, 0, len));
                }
                clientSocket.shutdownInput();
                debug("got command - " + command); //$NON-NLS-1$
                if ("STOP".equals(command.toString())) { //$NON-NLS-1$
                    stopApplication();
                    result = true;
                    commandResult = "OK: stop done"; //$NON-NLS-1$
                } else if (command.toString().startsWith("PING")) { //$NON-NLS-1$
                    commandResult = "OK: " //$NON-NLS-1$
                        + command.substring("PING".length()); //$NON-NLS-1$
                } else {
                    commandResult = "ERROR: unknown command"; //$NON-NLS-1$
                }
                //debug("command executed");
                //debug("sending command result - " + commandResult);
                out = clientSocket.getOutputStream();
                out.write(commandResult.getBytes());
                out.flush();
                clientSocket.shutdownOutput();
                //debug("command result sent");
            } finally {
                try {
                    in.close();
                } catch (IOException ioe) {
                    // ignore
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException ioe) {
                        // ignore
                    }
                }
            }
        } catch (IOException ioe) {
            error("error processing control request", ioe); //$NON-NLS-1$
        }
        return result;
    }
    
    private void stopApplication() {
        if (!appRunning) {
            debug("application not running"); //$NON-NLS-1$
            return;
        }
        appRunning = false;
        debug("stopping application"); //$NON-NLS-1$
        try {
            Boot.stopApplication(application);
            log = null;
        } catch (Exception e) {
            error("an error has occurred while stopping" //$NON-NLS-1$
                    + " application", e); //$NON-NLS-1$
        }
        debug("application stopped from control thread"); //$NON-NLS-1$
    }
    
    private boolean isValidRemoteHost(final InetAddress addr) {
        byte[] localAddr = serverSocket.getInetAddress().getAddress();
        byte[] remoteAddr = addr.getAddress();
        if (localAddr.length != remoteAddr.length) {
            return false;
        }
        for (int i = 0; i < remoteAddr.length; i++) {
            if (localAddr[i] != remoteAddr[i]) {
                return false;
            }
        }
        return true;
    }
    
    private void debug(final String msg) {
        if (log != null) {
            log.debug(msg);
        } else {
            System.out.println(msg);
        }
    }
    
    private void warn(final String msg) {
        if (log != null) {
            log.warn(msg);
        } else {
            System.out.println(msg);
        }
    }
    
    private void warn(final String msg, final Exception e) {
        if (log != null) {
            log.warn(msg, e);
        } else {
            System.out.println(msg);
            e.printStackTrace();
        }
    }
    
    private void error(final String msg, final Exception e) {
        if (log != null) {
            log.error(msg, e);
        } else {
            System.err.println(msg);
            e.printStackTrace();
        }
    }
    
    private void error(final Exception e) {
        if (log != null) {
            log.error(e);
        } else {
            e.printStackTrace();
        }
    }
}