Monkey源碼分析之事件來源,monkey源碼
上一篇文章《Monkey源碼分析之運行流程》給出了monkey啟動並執行整個流程,讓我們有一個概貌,那麼往後的文章我們會嘗試進一步的闡述相關的一些知識點。
這裡先把整個monkey類的結構圖給出來供大家參考,該圖源自網上(我自己的backbook pro上沒有安裝OmniGraffle工具,55美金,不捨得,所以直接貼網上的)
圖中有幾點需要注意下的:
- MonkeyEventScript應該是MonkeySourceScript
- MonkeyEventRandom應該是MonkeySourceRandom
- 這裡沒有列出其他源,比如我們今天描述的重點MonkeySourceNetwork,因為它不是由MonkeyEventQueque這個類維護的,但其維護的事件隊列和MonkeyEventQueque一樣都是繼承於LinkedList的,所以大同小異
本文我們重點是以處理來來自網路sokcet也就是monkeyrunner的命令為例子來闡述事件來源是怎麼處理的,其他的源大同小異。
1. 事件隊列維護者CommandQueque
在開始之前我們需要先去瞭解幾個基礎類,這樣子我們才方便分析。
我們在擷取了事件來源之後,會把這些事件排隊放入一個隊列,然後其他地方就可以去把隊列裡面的事件取出來進一步進行處理了。那麼這裡我們先看下維護這個事件隊列的相應代碼:
public static interface CommandQueue { /** * Enqueue an event to be returned later. This allows a * command to return multiple events. Commands using the * command queue still have to return a valid event from their * translateCommand method. The returned command will be * executed before anything put into the queue. * * @param e the event to be enqueued. */ public void enqueueEvent(MonkeyEvent e); }; // Queue of Events to be processed. This allows commands to push // multiple events into the queue to be processed. private static class CommandQueueImpl implements CommandQueue{ private final Queue<MonkeyEvent> queuedEvents = new LinkedList<MonkeyEvent>(); public void enqueueEvent(MonkeyEvent e) { queuedEvents.offer(e); } /** * Get the next queued event to excecute. * * @return the next event, or null if there aren't any more. */ public MonkeyEvent getNextQueuedEvent() { return queuedEvents.poll(); } };
介面CommandQueue只定義個了一個方法enqueueEvent,由實作類別CommandQueueImpl來實現,而實作類別維護了一個MonkeyEvent類型的由LinkedList實現的隊列quequeEvents,然後實現了兩個方法來分別往這個隊列裡面放和取事件。挺簡單的實現,這裡主要是要提醒大家queueEvents這個隊列的重要性。這裡要注意的是MonkeyEventScript和monkeyEventRandom這兩個事件來源維護隊列的類稍微有些不一樣,用的是MonkeyEventQueue這個類,但是其實這個類也是繼承自上面描述的LinkedList的,所以原理是一樣的。
最後建立和維護一個CommandQueueImple這個實作類別的一個執行個體commandQueque來轉被對裡面的quequeEvents進行管理。
private final CommandQueueImpl commandQueue = new CommandQueueImpl();
2. 事件翻譯員MonkeyCommand
下一個我們需要瞭解的基礎內部類就是MonkeCommand。從資料來源過來的命令都是一串字串,我們需要把它轉換成對應的monkey事件並存入到我們上面提到的由CommandQueque維護的事件隊列quequeEvents裡面。首先我們看下MonkeyCommand這個介面:
/** * Interface that MonkeyCommands must implement. */ public interface MonkeyCommand { /** * Translate the command line into a sequence of MonkeyEvents. * * @param command the command line. * @param queue the command queue. * @return MonkeyCommandReturn indicating what happened. */ MonkeyCommandReturn translateCommand(List<String> command, CommandQueue queue); }
它只定義了一個實作類別需要實現的方法translateCommand,從它的描述和接受的的參數可以知道,這個方法要做的事情就是把從事件來源接受到的字串命令轉換成上面說的CommandQueue類型維護的那個eventQueues。以monkeyrunner發過來的press這個命令為例子,傳過來給monkey的字串是"press KEY_COKDE"(請查看《MonkeyRunner源碼分析之與Android裝置通訊方式》)
針對每一個命令都會有一個對應的MonkeyCommand的實作類別來做真正的字串到事件的翻譯工作,以剛才提到的press這個命令為例子,我們看下它的實現代碼:
/** * Command to "press" a buttons (Sends an up and down key event.) */ private static class PressCommand implements MonkeyCommand { // press keycode public MonkeyCommandReturn translateCommand(List<String> command, CommandQueue queue) { if (command.size() == 2) { int keyCode = getKeyCode(command.get(1)); if (keyCode < 0) { // Ok, you gave us something bad. Log.e(TAG, "Can't find keyname: " + command.get(1)); return EARG; } queue.enqueueEvent(new MonkeyKeyEvent(KeyEvent.ACTION_DOWN, keyCode)); queue.enqueueEvent(new MonkeyKeyEvent(KeyEvent.ACTION_UP, keyCode)); return OK; } return EARG; } }以monkeyrunner過來的'press KEY_CODE'為例分析這段代碼:
- 從字串中得到第1個參數,也就是key_code
- 判斷key_code是否有效
- 建立按下按鍵的MonkeyKeyEvent事件並存入到CommandQueque維護的quequeEvents
- 建立彈起按鍵的MonkeyKeyEvent事件並存入到CommandQueque維護的quequeEvents(press這個動作會出發按下和彈起按鍵兩個動作)
命令字串和對應的MonkeyCommand實作類別的對應關係會由MonkeySourceNetwork類的COMMAND_MAP這個私人靜態成員來維護,這裡只是分析了"press"這個命令,其他的大家有興趣就自行分析,原理是一致的。
private static final Map<String, MonkeyCommand> COMMAND_MAP = new HashMap<String, MonkeyCommand>(); static { // Add in all the commands we support COMMAND_MAP.put("flip", new FlipCommand()); COMMAND_MAP.put("touch", new TouchCommand()); COMMAND_MAP.put("trackball", new TrackballCommand()); COMMAND_MAP.put("key", new KeyCommand()); COMMAND_MAP.put("sleep", new SleepCommand()); COMMAND_MAP.put("wake", new WakeCommand()); COMMAND_MAP.put("tap", new TapCommand()); COMMAND_MAP.put("press", new PressCommand()); COMMAND_MAP.put("type", new TypeCommand()); COMMAND_MAP.put("listvar", new MonkeySourceNetworkVars.ListVarCommand()); COMMAND_MAP.put("getvar", new MonkeySourceNetworkVars.GetVarCommand()); COMMAND_MAP.put("listviews", new MonkeySourceNetworkViews.ListViewsCommand()); COMMAND_MAP.put("queryview", new MonkeySourceNetworkViews.QueryViewCommand()); COMMAND_MAP.put("getrootview", new MonkeySourceNetworkViews.GetRootViewCommand()); COMMAND_MAP.put("getviewswithtext", new MonkeySourceNetworkViews.GetViewsWithTextCommand()); COMMAND_MAP.put("deferreturn", new DeferReturnCommand()); }
3. 事件來源擷取者之getNextEvent
終於到了如何擷取事件的分析了,我們繼續以MonkeySourceNetwork這個處理monkeyrunner過來的網路命令為例子,看下它是如何處理monkeyrunner過來的命令的。我們先看下它實現的介面類MonkeyEventSource
/** * event source interface */public interface MonkeyEventSource { /** * @return the next monkey event from the source */ public MonkeyEvent getNextEvent(); /** * set verbose to allow different level of log * * @param verbose output mode? 1= verbose, 2=very verbose */ public void setVerbose(int verbose); /** * check whether precondition is satisfied * * @return false if something fails, e.g. factor failure in random source or * file can not open from script source etc */ public boolean validate();}
這裡我最關心的就是getNextEvent這個介面,因為就是它來從socket獲得我們monkeyrunner過來的命令,然後通過上面描述的MonkeyCommand的實作類別來把命令翻譯成最上面的CommandQueque維護的quequeEvents隊列的。往下我們會看它是怎麼做到的,這裡我們先看下介面實作類別MonkeySourceNetwork的建構函式:
public MonkeySourceNetwork(int port) throws IOException { // Only bind this to local host. This means that you can only // talk to the monkey locally, or though adb port forwarding. serverSocket = new ServerSocket(port, 0, // default backlog InetAddress.getLocalHost()); }所做的事情就是通過指定的連接埠執行個體化一個ServerSocket,這裡要注意它綁定的只是本地主機地址,意思是說只有本地的socket串連或者通過連接埠轉寄連過來的adb連接埠(也就是我們這篇文章關注的monkeyrunner啟動的那個adb)才會被接受。
這裡只是執行個體化了一個socket,現在為止還沒有真正啟動起來的,也就是說還沒有開始真正的啟動對指定連接埠的監聽的。真正開始監聽是startServer這個方法觸發的:
/** * Start a network server listening on the specified port. The * network protocol is a line oriented protocol, where each line * is a different command that can be run. * * @param port the port to listen on */ private void startServer() throws IOException { clientSocket = serverSocket.accept(); // At this point, we have a client connected. // Attach the accessibility listeners so that we can start receiving // view events. Do this before wake so we can catch the wake event // if possible. MonkeySourceNetworkViews.setup(); // Wake the device up in preparation for doing some commands. wake(); input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); // auto-flush output = new PrintWriter(clientSocket.getOutputStream(), true); }這裡除了開始監聽連接埠之外,還如monkeyrunner對連接埠讀寫的情況一樣,維護和執行個體化了input和output這兩個成員變數來專門對連接埠資料進行操作。
那麼這個startServer開始監聽資料的方法又是由誰調用的呢?這裡終於就來到了我們這一章節,也是本文的核心getNextEvent了
public MonkeyEvent getNextEvent() { if (!started) { try { startServer(); } catch (IOException e) { Log.e(TAG, "Got IOException from server", e); return null; } started = true; } // Now, get the next command. This call may block, but that's OK try { while (true) { // Check to see if we have any events queued up. If // we do, use those until we have no more. Then get // more input from the user. MonkeyEvent queuedEvent = commandQueue.getNextQueuedEvent(); if (queuedEvent != null) { // dispatch the event return queuedEvent; } // Check to see if we have any returns that have been deferred. If so, now that // we've run the queued commands, wait for the given event to happen (or the timeout // to be reached), and handle the deferred MonkeyCommandReturn. if (deferredReturn != null) { Log.d(TAG, "Waiting for event"); MonkeyCommandReturn ret = deferredReturn.waitForEvent(); deferredReturn = null; handleReturn(ret); } String command = input.readLine(); if (command == null) { Log.d(TAG, "Connection dropped."); // Treat this exactly the same as if the user had // ended the session cleanly with a done commant. command = DONE; } if (DONE.equals(command)) { // stop the server so it can accept new connections try { stopServer(); } catch (IOException e) { Log.e(TAG, "Got IOException shutting down!", e); return null; } // return a noop event so we keep executing the main // loop return new MonkeyNoopEvent(); } // Do quit checking here if (QUIT.equals(command)) { // then we're done Log.d(TAG, "Quit requested"); // let the host know the command ran OK returnOk(); return null; } // Do comment checking here. Comments aren't a // command, so we don't echo anything back to the // user. if (command.startsWith("#")) { // keep going continue; } // Translate the command line. This will handle returning error/ok to the user translateCommand(command); } } catch (IOException e) { Log.e(TAG, "Exception: ", e); return null; } }有了以上介紹的那些背景知識,這段代碼的理解就不會太費力了,我這裡大概描述下:
- 啟動socket連接埠監聽monkeyrunner過來的串連和資料
- 進入無限迴圈
- 調用最上面描述的commandQueque這個事件隊列維護者執行個體來嘗試來從隊列獲得一個事件
- 如果隊列由事件的話就立刻返回給上一篇文章《MonkeyRunner源碼分析之啟動》描述的runMonkeyCles那個方法取調用執行
- 如果隊列沒有事件的話,調用上面描述的socket讀寫變數input來獲得socket中monkeyrunner發過來的一行資料(也就是一個命令字串)
- 調用translateCommand這個私人方法來針對不同的命令調用不同的MonkeyCommand實作類別介面的translateCommand把字串命令翻譯成對應的事件並放到命令隊列裡面(這個命令上面還沒有描述,往下我會分析下)
- 如果確實沒有命令了或者收到訊號要退出了等情況下就跳出迴圈,否則回到迴圈開始繼續以上步驟
好,我們還是看看剛才那個translateCommand的私人方法究竟是怎麼調用到不同命令的translateCommand介面的:
/** * Translate the given command line into a MonkeyEvent. * * @param commandLine the full command line given. */ private void translateCommand(String commandLine) { Log.d(TAG, "translateCommand: " + commandLine); List<String> parts = commandLineSplit(commandLine); if (parts.size() > 0) { MonkeyCommand command = COMMAND_MAP.get(parts.get(0)); if (command != null) { MonkeyCommandReturn ret = command.translateCommand(parts, commandQueue); handleReturn(ret); } } }很簡單,就是擷取monkeyunner進來的命令字串列表的的第一個值,然後通過上面的COMMAND_MAP把字串轉換成對應的MonkeyCommand實作類別,然後調用其tranlsateCommand把該字串命令翻譯成對應的MonkeyEvent並儲存到事件隊列。比如monkeyrunner過來的字串轉換成隊列是[‘press','KEY_CODE'],獲得第一個列表成員是press,那麼COMMAND_MAP對應於"press"字串這個key的MonkeyCommand就是:
COMMAND_MAP.put("press", new PressCommand());所以調用的就是PressCommand這個MonkeyCommand介面實作類別的translateCommand方法來把press這個命令轉換成對應的MonkeyKeyEvent了。
4.總結最後我們結合上一章《Monkey源碼分析之運行流程》把整個擷取事件來源然後執行該事件的過程整理下:
- Monkey啟動開始調用run方法
- ran方法根據輸入的參數執行個體化指定的事件來源,比如我們這裡的MonkeySourceNetwork
- Monkey類中的runMonkeyCyles這個方法開始迴圈取事件執行
- 調用Monkey類維護的mEventSource的getNextEvent方法來擷取一條事件,在本文執行個體中就是上面表述的MonkeySourceNetwork執行個體的getNextEvent方法
- getNextEvent方法從CommandQueueImpl執行個體commandQueque所維護的quequeEvents裡面讀取一條事件
- 如果事件存在則返回
- getNextEvent方法啟動事件來源讀取監聽,本文執行個體中就是上面的startServer方法來監聽monkeyrunner過來的socket串連和命令資料
- getNextEvent方法從事件來源讀取一個命令
- getNextEvent方法通過調用對應的的MonkeyCommand介面實作類別的translateCommand方法把字串命令翻譯成對應的monkey事件然後儲存到commandQueque維護的quequeEvents隊列
- 執行返回event的injectEvent方法
好,事件來源的分析就到此為止了,下一篇文章準備描述Monkey的Event,看它是如何執行這些事件的。
怎分析網站源碼
說詳細點,你說的分析是啥意思
VB 網頁原始碼分析
用Regex以的方法比較穩定.
但是如果內容變化,使用WebBrowser控制項進行DOM分析網頁比較方便.
具體要看實際情況.
如使用WebBrowser控制項:
1.把網頁代碼下載下來,建議使用inet下載(注意utf8編碼的問題)
2.把代碼進行處理,去除script,iframe,object等(不然用WebBrowser的時候彈出對話方塊就很麻煩)
3.把處理好的代碼給WebBrowser裡面,
4.從WebBrowser獲得document進行DOM處理.
程式碼範例:
'獲得webbrowser的 document對象
Public Function getDocumentByHtml(html As String) As HTMLDocument
WebBrowser1.Silent = True
WebBrowser1.Navigate "about:blank" '先清空
Do Until WebBrowser1.ReadyState = 4 '等待載入完畢
DoEvents
Loop
WebBrowser1.Document.write clearHtml(html)
Do Until WebBrowser1.ReadyState = 4 '等待載入完畢
DoEvents
Loop
Set getDocumentByHtml = WebBrowser1.Document
End Function
獲得document後,就可以使用
document.getElementByID("tr1855")獲得的tr對象
然後
document.getElementByID("tr1855").getElementsByTagName("td") 再獲得表格裡面的文本
如使用Regex
1.把網頁代碼下載下來,建議使用inet下載(注意utf8編碼的問題)
2.直接對代碼進行Regex處理
程式碼範例:
Dim reg As New RegExp
reg.IgnoreCase = True
reg.Global = True
reg.MultiLine = True
reg.Pattern = "<tr.*id=\x22tr1855\x22[^\x00]*?</tr>" 'Regex的代碼,這段擷取id為tr1855的表格代碼
然後用 reg.Execute("網頁的代碼") 返回的是matchcollection類型
最後再分別取出的td裡面所要的文本