Home | History | Annotate | Download | only in service
      1 /*
      2  * Copyright (C) 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 
     17 package com.googlecode.android_scripting.service;
     18 
     19 import android.annotation.TargetApi;
     20 import android.os.Bundle;
     21 import android.os.Handler;
     22 import android.os.HandlerThread;
     23 import android.os.Message;
     24 import android.os.RemoteException;
     25 
     26 import com.googlecode.android_scripting.Log;
     27 import com.googlecode.android_scripting.jsonrpc.JsonRpcResult;
     28 import com.googlecode.android_scripting.jsonrpc.RpcReceiverManager;
     29 import com.googlecode.android_scripting.jsonrpc.RpcReceiverManagerFactory;
     30 import com.googlecode.android_scripting.rpc.MethodDescriptor;
     31 
     32 import org.json.JSONException;
     33 import org.json.JSONObject;
     34 
     35 /**
     36  * Class responsible for Handling messages that came through the FacadeService
     37  * interface.
     38  * <br>
     39  * Please refer to {@link FacadeService} for details on how to use.
     40  */
     41 @TargetApi(3)
     42 public class MessageHandler extends Handler {
     43 
     44     private static final int SL4A_ACTION = 0;
     45     private static final int DEFAULT_SENDING_ID = 0;
     46 
     47     // Android sets this to -1 when the message is not sent by a Messenger.
     48     // see http://developer.android.com/reference/android/os/Message.html#sendingUid
     49     private static final int DEFAULT_UNSET_SENDING_ID = 1;
     50 
     51     // Keys for the Bundles.
     52     private static final String SL4A_METHOD = "sl4aMethod";
     53     private static final String SL4A_RESULT = "sl4aResult";
     54 
     55     private final RpcReceiverManagerFactory mRpcReceiverManagerFactory;
     56 
     57     public MessageHandler(HandlerThread handlerThread,
     58                           RpcReceiverManagerFactory rpcReceiverManagerFactory) {
     59         super(handlerThread.getLooper());
     60         this.mRpcReceiverManagerFactory = rpcReceiverManagerFactory;
     61     }
     62 
     63     /**
     64      * Handles messages for the service. It does this via the same mechanism used
     65      * for RPCs through RpcManagers.
     66      *
     67      * @param message The message that contains the method and parameters to
     68      *     execute.
     69      */
     70     @Override
     71     public void handleMessage(Message message) {
     72         Log.d("Handling Remote request");
     73         int senderId = message.sendingUid == DEFAULT_UNSET_SENDING_ID ?
     74                 DEFAULT_SENDING_ID : message.sendingUid;
     75         if (message.what == SL4A_ACTION) {
     76             RpcReceiverManager receiverManager;
     77             if (mRpcReceiverManagerFactory.getRpcReceiverManagers().containsKey(senderId)) {
     78                 receiverManager = mRpcReceiverManagerFactory.getRpcReceiverManagers().get(senderId);
     79             } else {
     80                 receiverManager = mRpcReceiverManagerFactory.create(senderId);
     81             }
     82             Bundle sl4aRequest = message.getData();
     83             String method = sl4aRequest.getString(SL4A_METHOD);
     84             if (method == null || "".equals(method)) {
     85                 Log.e("No SL4A method specified on the Bundle. Specify one with "
     86                         + SL4A_METHOD);
     87                 return;
     88             }
     89             MethodDescriptor rpc = receiverManager.getMethodDescriptor(method);
     90             if (rpc == null) {
     91                 Log.e("Unknown RPC: \"" + method + "\"");
     92                 return;
     93             }
     94             try {
     95                 Log.d("Invoking method " + rpc.getName());
     96                 Object result = rpc.invoke(receiverManager, sl4aRequest);
     97                 // Only return a result if we were passed a Messenger. Otherwise assume
     98                 // client did not care for the response.
     99                 if (message.replyTo != null) {
    100                     Message reply = Message.obtain();
    101                     Bundle sl4aResponse = new Bundle();
    102                     putResult(senderId, result, sl4aResponse);
    103                     reply.setData(sl4aResponse);
    104                     message.replyTo.send(reply);
    105                 }
    106             } catch (RemoteException e) {
    107                 Log.e("Could not send reply back to client", e);
    108             } catch (Throwable t) {
    109                 Log.e("Exception while executing sl4a method", t);
    110             }
    111         }
    112     }
    113 
    114     private void putResult(int id, Object result, Bundle reply) {
    115         JSONObject json;
    116         try {
    117             if (result instanceof Throwable) {
    118                 json = JsonRpcResult.error(id, (Throwable) result);
    119             } else {
    120                 json = JsonRpcResult.result(id, result);
    121             }
    122         } catch (JSONException e) {
    123             // There was an error converting the result to JSON. This shouldn't
    124             // happen normally.
    125             Log.e("Caught exception when filling JSON result.", e);
    126             reply.putString(SL4A_RESULT, e.toString());
    127             return;
    128         }
    129         Log.d("Returning result: " + json.toString());
    130         reply.putString(SL4A_RESULT, json.toString());
    131     }
    132 }
    133