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.facade; 18 19 import android.app.Service; 20 import android.content.Intent; 21 22 import com.googlecode.android_scripting.jsonrpc.RpcReceiver; 23 import com.googlecode.android_scripting.jsonrpc.RpcReceiverManager; 24 import com.googlecode.android_scripting.jsonrpc.RpcReceiverManagerFactory; 25 26 import java.util.Collection; 27 import java.util.HashMap; 28 import java.util.Map; 29 30 public class FacadeManagerFactory implements RpcReceiverManagerFactory { 31 32 private final int mSdkLevel; 33 private final Service mService; 34 private final Intent mIntent; 35 private final Collection<Class<? extends RpcReceiver>> mClassList; 36 private final Map<String, RpcReceiverManager> mFacadeManagers; 37 FacadeManagerFactory(int sdkLevel, Service service, Intent intent, Collection<Class<? extends RpcReceiver>> classList)38 public FacadeManagerFactory(int sdkLevel, Service service, Intent intent, 39 Collection<Class<? extends RpcReceiver>> classList) { 40 mSdkLevel = sdkLevel; 41 mService = service; 42 mIntent = intent; 43 mClassList = classList; 44 mFacadeManagers = new HashMap<>(); 45 } 46 47 @Override create(String sessionId)48 public FacadeManager create(String sessionId) throws IllegalArgumentException { 49 FacadeManager facadeManager = new FacadeManager(mSdkLevel, mService, mIntent, mClassList); 50 // TODO(markdr): This lock isn't entirely safe, since another object injects this reference 51 // into the RpcReceiverManagerFactory, and can therefore make mutations elsewhere. 52 // Refactor this to prevent that from potentially occurring. 53 synchronized (mFacadeManagers) { 54 if (mFacadeManagers.containsKey(sessionId)) { 55 throw new IllegalArgumentException("SessionID " + sessionId + " already exists."); 56 } 57 mFacadeManagers.put(sessionId, facadeManager); 58 } 59 return facadeManager; 60 } 61 62 @Override destroy(String sessionId)63 public boolean destroy(String sessionId) { 64 RpcReceiverManager removed = mFacadeManagers.remove(sessionId); 65 if (removed != null) { 66 removed.shutdown(); 67 } 68 return removed != null; 69 } 70 71 @Override getRpcReceiverManagers()72 public Map<String, RpcReceiverManager> getRpcReceiverManagers() { 73 return mFacadeManagers; 74 } 75 } 76