Fix make files so it builds in master
Fix build_all.sh so user does not need to modify path and jdk version any more
Adding a logging field in JsonRpcServer
Changing event id scheme in ScanFacade

Change-Id: Ib60b6230403d312278ead307692a4bbb0e79506e
diff --git a/Common/Android.mk b/Common/Android.mk
new file mode 100644
index 0000000..b823553
--- /dev/null
+++ b/Common/Android.mk
@@ -0,0 +1,19 @@
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+
+LOCAL_MODULE := sl4a.Common
+
+LOCAL_JAVA_LIBRARIES := libGoogleAnalytics
+LOCAL_STATIC_JAVA_LIBRARIES := guava android-common sl4a.Utils
+
+LOCAL_SRC_FILES := $(call all-java-files-under, src/com/googlecode/android_scripting)
+LOCAL_SRC_FILES += $(call all-java-files-under, src/org/apache/commons/codec)
+
+LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res
+
+include $(BUILD_STATIC_JAVA_LIBRARY)
+
+
diff --git a/Common/src/com/googlecode/android_scripting/jsonrpc/JsonRpcServer.java b/Common/src/com/googlecode/android_scripting/jsonrpc/JsonRpcServer.java
new file mode 100644
index 0000000..a984137
--- /dev/null
+++ b/Common/src/com/googlecode/android_scripting/jsonrpc/JsonRpcServer.java
@@ -0,0 +1,138 @@
+/*
+ * Copyright (C) 2009 Google Inc.
+ *
+ * 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.googlecode.android_scripting.jsonrpc;
+
+import com.googlecode.android_scripting.Log;
+import com.googlecode.android_scripting.SimpleServer;
+import com.googlecode.android_scripting.rpc.MethodDescriptor;
+import com.googlecode.android_scripting.rpc.RpcError;
+
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.net.Socket;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+/**
+ * A JSON RPC server that forwards RPC calls to a specified receiver object.
+ * 
+ * @author Damon Kohler (damonkohler@gmail.com)
+ */
+public class JsonRpcServer extends SimpleServer {
+
+  private final RpcReceiverManagerFactory mRpcReceiverManagerFactory;
+  private final String mHandshake;
+
+  /**
+   * Construct a {@link JsonRpcServer} connected to the provided {@link RpcReceiverManager}.
+   * 
+   * @param managerFactory
+   *          the {@link RpcReceiverManager} to register with the server
+   * @param handshake
+   *          the secret handshake required for authorization to use this server
+   */
+  public JsonRpcServer(RpcReceiverManagerFactory managerFactory, String handshake) {
+    mHandshake = handshake;
+    mRpcReceiverManagerFactory = managerFactory;
+  }
+
+  @Override
+  public void shutdown() {
+    super.shutdown();
+    // Notify all RPC receiving objects. They may have to clean up some of their state.
+    for (RpcReceiverManager manager : mRpcReceiverManagerFactory.getRpcReceiverManagers().values()) {
+      manager.shutdown();
+    }
+  }
+
+
+  @Override
+  protected void handleRPCConnection(Socket sock, Integer UID, BufferedReader reader, PrintWriter writer) throws Exception {
+    RpcReceiverManager receiverManager = null;
+    //Log.d("Sock state 3: "+sock.isClosed());
+    Log.d("UID "+UID);
+    Log.d("manager map size: "+mRpcReceiverManagerFactory.getRpcReceiverManagers().size());
+    Log.d("manager map keys: "+mRpcReceiverManagerFactory.getRpcReceiverManagers().keySet());
+    if(mRpcReceiverManagerFactory.getRpcReceiverManagers().containsKey(UID)) {
+      Log.d("Look up existing session");
+      receiverManager = mRpcReceiverManagerFactory.getRpcReceiverManagers().get(UID);
+    }else{
+      Log.d("Create a new session");
+      receiverManager = mRpcReceiverManagerFactory.create(UID);
+    }
+    //Log.d("Sock state 4: "+sock.isClosed());
+
+    /*RpcReceiverManager receiverManager = mRpcReceiverManagerFactory.create();
+    BufferedReader reader =
+        new BufferedReader(new InputStreamReader(socket.getInputStream()), 8192);
+    PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);*/
+    //boolean passedAuthentication = false;
+    String data;
+    while ((data = reader.readLine()) != null) {
+      Log.v("Session " + UID + " Received: " + data);
+      JSONObject request = new JSONObject(data);
+      int id = request.getInt("id");
+      String method = request.getString("method");
+      JSONArray params = request.getJSONArray("params");
+
+      // First RPC must be _authenticate if a handshake was specified.
+//      if (!passedAuthentication && mHandshake != null) {
+//        if (!checkHandshake(method, params)) {
+//          SecurityException exception = new SecurityException("Authentication failed!");
+//          send(writer, JsonRpcResult.error(id, exception));
+//          shutdown();
+//          throw exception;
+//        }
+//        passedAuthentication = true;
+//        send(writer, JsonRpcResult.result(id, true));
+//        continue;
+//      }
+
+      MethodDescriptor rpc = receiverManager.getMethodDescriptor(method);
+      if (rpc == null) {
+        send(writer, JsonRpcResult.error(id, new RpcError("Unknown RPC.")), UID);
+        continue;
+      }
+      try {
+        send(writer, JsonRpcResult.result(id, rpc.invoke(receiverManager, params)), UID);
+      } catch (Throwable t) {
+        Log.e("Invocation error.", t);
+        send(writer, JsonRpcResult.error(id, t), UID);
+      }
+    }
+  }
+
+  private boolean checkHandshake(String method, JSONArray params) throws JSONException {
+    if (!method.equals("_authenticate") || !mHandshake.equals(params.getString(0))) {
+      return false;
+    }
+    return true;
+  }
+
+  private void send(PrintWriter writer, JSONObject result, int UID) {
+    writer.write(result + "\n");
+    writer.flush();
+    Log.v("Session " + UID + " Sent: " + result);
+  }
+
+  @Override
+  protected void handleConnection(Socket socket) throws Exception {
+  }
+}
diff --git a/QuickAction/Android.mk b/QuickAction/Android.mk
new file mode 100644
index 0000000..3423915
--- /dev/null
+++ b/QuickAction/Android.mk
@@ -0,0 +1,14 @@
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+
+LOCAL_MODULE := sl4a.QuickAction
+LOCAL_STATIC_JAVA_LIBRARIES := guava android-common
+LOCAL_SRC_FILES := $(call all-java-files-under, src/net/londatiga/android)
+
+
+LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res
+
+include $(BUILD_STATIC_JAVA_LIBRARY)
diff --git a/Utils/Android.mk b/Utils/Android.mk
new file mode 100644
index 0000000..3ada573
--- /dev/null
+++ b/Utils/Android.mk
@@ -0,0 +1,15 @@
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+
+LOCAL_MODULE := sl4a.Utils
+LOCAL_STATIC_JAVA_LIBRARIES := guava android-common
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+EXCLUDES := src/com/googlecode/android_scripting/facade/ScanFacade.java
+
+
+LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res
+
+include $(BUILD_STATIC_JAVA_LIBRARY)
diff --git a/build_all.sh b/build_all.sh
new file mode 100755
index 0000000..bca0916
--- /dev/null
+++ b/build_all.sh
@@ -0,0 +1,95 @@
+#! /bin/bash
+#This script does a clean build of sl4a and install it to your device through adb
+#Requires envsetup.sh in the branch
+
+#function to change jdk version
+function setup_jdk() {
+  # Remove the current JDK from PATH
+  if [ -n "$JAVA_HOME" ] ; then
+    PATH=${PATH/$JAVA_HOME\/bin:/}
+  fi
+  export JAVA_HOME=$1
+  export PATH=$JAVA_HOME/bin:$PATH
+}
+
+#Color code for echo
+r='\e[0;31m'
+brn='\e[0;33m'
+y='\e[1;33m'
+g='\e[0;32m'
+cy='\e[0;36m'
+lb='\e[1;34m'
+p='\e[0;35m'
+lg='\e[0;37m'
+NC='\e[0m' # No Color
+
+echo -e "Welcome to ${r}U${brn}N${y}I${g}C${lb}O${cy}R${p}N${NC} build system for ${g}sl4a${NC}"
+
+#List of sl4a dependency libs to be built in order
+declare -a lib_list=("Utils" "Common" "BluetoothFacade" "SignalStrengthFacade" "TextToSpeechFacade" "WebCamFacade" "InterpreterForAndroid" "ScriptingLayer" "QuickAction")
+
+declare -a test_list=("Utils" "Common")
+
+APP_NAME=sl4a
+APP_PACKAGE_NAME=com.googlecode.android_scripting
+
+BRANCH_ROOT=$PWD/../../../../..
+SL4A_ROOT=$BRANCH_ROOT/vendor/google_testing/comms/Tools/sl4a
+SHARED_LIB_JAR_ROOT=$BRANCH_ROOT/out/target/common/obj/JAVA_LIBRARIES
+APP_JAR_ROOT=$BRANCH_ROOT/out/target/common/obj/APPS
+APK_ROOT=$BRANCH_ROOT/out/target/product/hammerhead/data/app
+SL4A_PROJ_DIR=$SL4A_ROOT/ScriptingLayerForAndroid
+
+echo -e "${y}Removing intermediates of all the dependency libs${NC}"
+for i in "${lib_list[@]}"
+do
+  rm -r $SHARED_LIB_JAR_ROOT/sl4a."$i"_intermediates
+done
+
+echo -e "${y}Removing intermeidates of the app${NC}"
+rm -r $APP_JAR_ROOT/"$APP_NAME"_intermediates
+#Remove the apk file
+rm $APK_ROOT/"$APP_NAME".apk
+
+#Build all the dependency libs
+. $BRANCH_ROOT/build/envsetup.sh
+
+exec () {
+  ${@:1:($#-1)}
+  if [ $? -ne 0 ]; then
+    echo -e "${r}Encountered error when ${@:$#}${NC}"
+    echo -e "${lg}UNICORN ${r}DIED${NC}!"
+    exit 1
+  fi
+}
+
+
+for i in "${lib_list[@]}"
+do
+  echo -e "${lb}+++++++ Building $i +++++++${NC}"
+  cd $SL4A_ROOT/"$i"
+  exec mm -B "building $i"
+  echo
+done
+
+echo -e "${lb}+++++++ Building $APP_NAME.apk +++++++${NC}"
+cd $SL4A_PROJ_DIR
+exec mm -B "building $APP_NAME.apk"
+echo
+
+echo -e "${y}Switching to root${NC}"
+adb root
+adb remount
+
+echo -e "${y}Uninstalling old apk from device${NC}"
+adb uninstall $APP_PACKAGE_NAME
+adb shell rm -r /system/priv-app/$APP_NAME.apk
+
+echo -e "${lb}Installing apk to device${NC}"
+cd $APK_ROOT
+#exec adb install $APP_NAME.apk "installing apk to device"
+exec adb push $APP_NAME.apk /system/priv-app "installing apk to previliged dir"
+
+echo "All clear!"
+echo -e " ${r}U${brn}N${y}I${g}C${cy}O${lb}R${p}N ${r}P${brn}O${y}W${g}E${cy}R${lb}!${p}!${NC}"
+