PageRenderTime 32ms CodeModel.GetById 17ms app.highlight 11ms RepoModel.GetById 1ms app.codeStats 0ms

/build/mobile/sutagent/android/RunCmdThread.java

http://github.com/zpao/v8monkey
Java | 318 lines | 236 code | 40 blank | 42 comment | 22 complexity | dc2707ac2ac615eae0b9dc8bbd6cffe0 MD5 | raw file
  1/* ***** BEGIN LICENSE BLOCK *****
  2 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  3 *
  4 * The contents of this file are subject to the Mozilla Public License Version
  5 * 1.1 (the "License"); you may not use this file except in compliance with
  6 * the License. You may obtain a copy of the License at
  7 * http://www.mozilla.org/MPL/
  8 *
  9 * Software distributed under the License is distributed on an "AS IS" basis,
 10 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 11 * for the specific language governing rights and limitations under the
 12 * License.
 13 *
 14 * The Original Code is Android SUTAgent code.
 15 *
 16 * The Initial Developer of the Original Code is
 17 * Bob Moss.
 18 * Portions created by the Initial Developer are Copyright (C) 2010
 19 * the Initial Developer. All Rights Reserved.
 20 *
 21 * Contributor(s):
 22 *  Bob Moss <bmoss@mozilla.com>
 23 *
 24 * Alternatively, the contents of this file may be used under the terms of
 25 * either the GNU General Public License Version 2 or later (the "GPL"), or
 26 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 27 * in which case the provisions of the GPL or the LGPL are applicable instead
 28 * of those above. If you wish to allow use of your version of this file only
 29 * under the terms of either the GPL or the LGPL, and not to allow others to
 30 * use your version of this file under the terms of the MPL, indicate your
 31 * decision by deleting the provisions above and replace them with the notice
 32 * and other provisions required by the GPL or the LGPL. If you do not delete
 33 * the provisions above, a recipient may use your version of this file under
 34 * the terms of any one of the MPL, the GPL or the LGPL.
 35 *
 36 * ***** END LICENSE BLOCK ***** */
 37
 38package com.mozilla.SUTAgentAndroid.service;
 39
 40import java.io.IOException;
 41import java.io.InputStream;
 42import java.net.ServerSocket;
 43import java.net.Socket;
 44import java.net.SocketTimeoutException;
 45import java.util.ArrayList;
 46import java.util.List;
 47
 48import com.mozilla.SUTAgentAndroid.R;
 49import com.mozilla.SUTAgentAndroid.SUTAgentAndroid;
 50
 51import android.app.Notification;
 52import android.app.NotificationManager;
 53import android.app.PendingIntent;
 54import android.content.Context;
 55import android.content.Intent;
 56import android.os.Handler;
 57
 58public class RunCmdThread extends Thread
 59    {
 60    private ServerSocket SvrSocket = null;
 61    private Socket socket    = null;
 62    private Handler handler = null;
 63    boolean bListening    = true;
 64    boolean bNetError = false;
 65    List<CmdWorkerThread> theWorkers = new ArrayList<CmdWorkerThread>();
 66    android.app.Service    svc = null;
 67
 68    public RunCmdThread(ServerSocket socket, android.app.Service service, Handler handler)
 69        {
 70        super("RunCmdThread");
 71        this.SvrSocket = socket;
 72        this.svc = service;
 73        this.handler = handler;
 74        }
 75
 76    public void StopListening()
 77        {
 78        bListening = false;
 79        }
 80
 81    public void run() {
 82        try {
 83            int    nIterations = 0;
 84
 85            SvrSocket.setSoTimeout(5000);
 86            while (bListening)
 87                {
 88                try
 89                    {
 90                    socket = SvrSocket.accept();
 91                    CmdWorkerThread theWorker = new CmdWorkerThread(this, socket);
 92                    theWorker.start();
 93                    theWorkers.add(theWorker);
 94                    }
 95                catch (SocketTimeoutException toe)
 96                    {
 97                    if (++nIterations > 60)
 98                        {
 99                        nIterations = 0;
100                        String sRet = SendPing("www.mozilla.org");
101                        if (sRet.contains("3 received"))
102                            handler.post(new doCancelNotification());
103                        else
104                            handler.post(new doSendNotification("SUTAgent - Network Connectivity Error", sRet));
105                        sRet = null;
106                        }
107                    continue;
108                    }
109                catch (IOException e)
110                    {
111                    e.printStackTrace();
112                    continue;
113                    }
114                }
115
116            int nNumWorkers = theWorkers.size();
117            for (int lcv = 0; lcv < nNumWorkers; lcv++)
118                {
119                if (theWorkers.get(lcv).isAlive())
120                    {
121                    theWorkers.get(lcv).StopListening();
122                    while(theWorkers.get(lcv).isAlive())
123                        ;
124                    }
125                }
126
127            theWorkers.clear();
128
129            SvrSocket.close();
130
131            svc.stopSelf();
132
133//            SUTAgentAndroid.me.finish();
134            }
135        catch (IOException e)
136            {
137            e.printStackTrace();
138            }
139        return;
140        }
141
142    private String SendPing(String sIPAddr)
143        {
144        Process    pProc;
145        String sRet = "";
146        String [] theArgs = new String [4];
147        boolean bStillRunning = true;
148        int    nBytesOut = 0;
149        int nBytesErr = 0;
150        int nBytesRead = 0;
151        byte[] buffer = new byte[1024];
152
153        theArgs[0] = "ping";
154        theArgs[1] = "-c";
155        theArgs[2] = "3";
156        theArgs[3] = sIPAddr;
157
158        try
159            {
160            pProc = Runtime.getRuntime().exec(theArgs);
161
162            InputStream sutOut = pProc.getInputStream();
163            InputStream sutErr = pProc.getErrorStream();
164
165            while (bStillRunning)
166                {
167                try
168                    {
169                    if ((nBytesOut = sutOut.available()) > 0)
170                        {
171                        if (nBytesOut > buffer.length)
172                            {
173                            buffer = null;
174                            System.gc();
175                            buffer = new byte[nBytesOut];
176                            }
177                        nBytesRead = sutOut.read(buffer, 0, nBytesOut);
178                        if (nBytesRead == -1)
179                            bStillRunning = false;
180                        else
181                            {
182                            String sRep = new String(buffer,0,nBytesRead).replace("\n", "\r\n");
183                            sRet += sRep;
184                            sRep = null;
185                            }
186                        }
187
188                    if ((nBytesErr = sutErr.available()) > 0)
189                        {
190                        if (nBytesErr > buffer.length)
191                            {
192                            buffer = null;
193                            System.gc();
194                            buffer = new byte[nBytesErr];
195                            }
196                        nBytesRead = sutErr.read(buffer, 0, nBytesErr);
197                        if (nBytesRead == -1)
198                            bStillRunning = false;
199                        else
200                            {
201                            String sRep = new String(buffer,0,nBytesRead).replace("\n", "\r\n");
202                            sRet += sRep;
203                            sRep = null;
204                            }
205                        }
206
207                    bStillRunning = (IsProcRunning(pProc) || (sutOut.available() > 0) || (sutErr.available() > 0));
208                    }
209                catch (IOException e)
210                    {
211                    e.printStackTrace();
212                    }
213
214                if ((bStillRunning == true) && (nBytesErr == 0) && (nBytesOut == 0))
215                    {
216                    try {
217                        sleep(2000);
218                        }
219                    catch (InterruptedException e) {
220                        e.printStackTrace();
221                        }
222                    }
223                }
224
225            pProc.destroy();
226            pProc = null;
227            }
228        catch (IOException e)
229            {
230            sRet = e.getMessage();
231            e.printStackTrace();
232            }
233
234        return (sRet);
235        }
236
237    private boolean IsProcRunning(Process pProc)
238        {
239        boolean bRet = false;
240        @SuppressWarnings("unused")
241        int nExitCode = 0;
242
243        try
244            {
245            nExitCode = pProc.exitValue();
246            }
247        catch (IllegalThreadStateException z)
248            {
249            bRet = true;
250            }
251        catch (Exception e)
252            {
253            e.printStackTrace();
254            }
255
256        return(bRet);
257        }
258
259    private void SendNotification(String tickerText, String expandedText)
260        {
261        NotificationManager notificationManager = (NotificationManager)svc.getSystemService(Context.NOTIFICATION_SERVICE);
262
263//        int icon = android.R.drawable.stat_notify_more;
264//        int icon = R.drawable.ic_stat_first;
265//        int icon = R.drawable.ic_stat_second;
266//        int icon = R.drawable.ic_stat_neterror;
267        int icon = R.drawable.ateamlogo;
268        long when = System.currentTimeMillis();
269
270        Notification notification = new Notification(icon, tickerText, when);
271
272        notification.flags |= (Notification.FLAG_INSISTENT | Notification.FLAG_AUTO_CANCEL);
273        notification.defaults |= Notification.DEFAULT_SOUND;
274        notification.defaults |= Notification.DEFAULT_VIBRATE;
275        notification.defaults |= Notification.DEFAULT_LIGHTS;
276
277        Context context = svc.getApplicationContext();
278
279        // Intent to launch an activity when the extended text is clicked
280        Intent intent2 = new Intent(svc, SUTAgentAndroid.class);
281        PendingIntent launchIntent = PendingIntent.getActivity(context, 0, intent2, 0);
282
283        notification.setLatestEventInfo(context, tickerText, expandedText, launchIntent);
284
285        notificationManager.notify(1959, notification);
286        }
287
288    private void CancelNotification()
289        {
290        NotificationManager notificationManager = (NotificationManager)svc.getSystemService(Context.NOTIFICATION_SERVICE);
291        notificationManager.cancel(1959);
292        }
293
294    class doCancelNotification implements Runnable
295        {
296        public void run()
297            {
298            CancelNotification();
299            }
300        };
301
302    class doSendNotification implements Runnable
303        {
304        private String sTitle = "";
305        private String sBText = "";
306
307        doSendNotification(String sTitle, String sBodyText)
308            {
309            this.sTitle = sTitle;
310            this.sBText = sBodyText;
311            }
312
313        public void run()
314            {
315            SendNotification(sTitle, sBText);
316            }
317        };
318}