1 /* 2 * Copyright (C) 2014 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.android.server.telecom; 18 19 import com.google.common.collect.HashBiMap; 20 21 /** Utility to map {@link Call} objects to unique IDs. IDs are generated when a call is added. */ 22 class CallIdMapper { 23 private final HashBiMap<String, Call> mCalls = HashBiMap.create(); 24 private final String mCallIdPrefix; 25 private static int sIdCount; 26 CallIdMapper(String callIdPrefix)27 CallIdMapper(String callIdPrefix) { 28 ThreadUtil.checkOnMainThread(); 29 mCallIdPrefix = callIdPrefix + "@"; 30 } 31 replaceCall(Call newCall, Call callToReplace)32 void replaceCall(Call newCall, Call callToReplace) { 33 ThreadUtil.checkOnMainThread(); 34 35 // Use the old call's ID for the new call. 36 String callId = getCallId(callToReplace); 37 mCalls.put(callId, newCall); 38 } 39 addCall(Call call, String id)40 void addCall(Call call, String id) { 41 if (call == null) { 42 return; 43 } 44 ThreadUtil.checkOnMainThread(); 45 mCalls.put(id, call); 46 } 47 addCall(Call call)48 void addCall(Call call) { 49 ThreadUtil.checkOnMainThread(); 50 addCall(call, getNewId()); 51 } 52 removeCall(Call call)53 void removeCall(Call call) { 54 if (call == null) { 55 return; 56 } 57 ThreadUtil.checkOnMainThread(); 58 mCalls.inverse().remove(call); 59 } 60 removeCall(String callId)61 void removeCall(String callId) { 62 ThreadUtil.checkOnMainThread(); 63 mCalls.remove(callId); 64 } 65 getCallId(Call call)66 String getCallId(Call call) { 67 if (call == null) { 68 return null; 69 } 70 ThreadUtil.checkOnMainThread(); 71 return mCalls.inverse().get(call); 72 } 73 getCall(Object objId)74 Call getCall(Object objId) { 75 ThreadUtil.checkOnMainThread(); 76 77 String callId = null; 78 if (objId instanceof String) { 79 callId = (String) objId; 80 } 81 if (!isValidCallId(callId) && !isValidConferenceId(callId)) { 82 return null; 83 } 84 85 return mCalls.get(callId); 86 } 87 clear()88 void clear() { 89 mCalls.clear(); 90 } 91 isValidCallId(String callId)92 boolean isValidCallId(String callId) { 93 // Note, no need for thread check, this method is thread safe. 94 return callId != null && callId.startsWith(mCallIdPrefix); 95 } 96 isValidConferenceId(String callId)97 boolean isValidConferenceId(String callId) { 98 return callId != null; 99 } 100 getNewId()101 String getNewId() { 102 sIdCount++; 103 return mCallIdPrefix + sIdCount; 104 } 105 } 106