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//#define LOG_NDEBUG 0
18#define LOG_TAG "MockSessionLibrary"
19
20#include <utils/Log.h>
21#include <utils/String8.h>
22#include "MockSessionLibrary.h"
23
24namespace android {
25
26Mutex MockSessionLibrary::sSingletonLock;
27MockSessionLibrary* MockSessionLibrary::sSingleton = NULL;
28
29MockSessionLibrary* MockSessionLibrary::get() {
30    Mutex::Autolock lock(sSingletonLock);
31
32    if (sSingleton == NULL) {
33        ALOGD("Instantiating Session Library Singleton.");
34        sSingleton = new MockSessionLibrary();
35    }
36
37    return sSingleton;
38}
39
40MockSessionLibrary::MockSessionLibrary() : mNextSessionId(1) {}
41
42status_t MockSessionLibrary::addSession(
43        CasPlugin *plugin, CasSessionId *sessionId) {
44    Mutex::Autolock lock(mSessionsLock);
45
46    sp<MockCasSession> session = new MockCasSession(plugin);
47
48    uint8_t *byteArray = (uint8_t *) &mNextSessionId;
49    sessionId->push_back(byteArray[3]);
50    sessionId->push_back(byteArray[2]);
51    sessionId->push_back(byteArray[1]);
52    sessionId->push_back(byteArray[0]);
53    mNextSessionId++;
54
55    mIDToSessionMap.add(*sessionId, session);
56    return OK;
57}
58
59sp<MockCasSession> MockSessionLibrary::findSession(
60        const CasSessionId& sessionId) {
61    Mutex::Autolock lock(mSessionsLock);
62
63    ssize_t index = mIDToSessionMap.indexOfKey(sessionId);
64    if (index < 0) {
65        return NULL;
66    }
67    return mIDToSessionMap.valueFor(sessionId);
68}
69
70void MockSessionLibrary::destroySession(const CasSessionId& sessionId) {
71    Mutex::Autolock lock(mSessionsLock);
72
73    ssize_t index = mIDToSessionMap.indexOfKey(sessionId);
74    if (index < 0) {
75        return;
76    }
77
78    sp<MockCasSession> session = mIDToSessionMap.valueAt(index);
79    mIDToSessionMap.removeItemsAt(index);
80}
81
82void MockSessionLibrary::destroyPlugin(CasPlugin *plugin) {
83    Mutex::Autolock lock(mSessionsLock);
84
85    for (ssize_t index = mIDToSessionMap.size() - 1; index >= 0; index--) {
86        sp<MockCasSession> session = mIDToSessionMap.valueAt(index);
87        if (session->getPlugin() == plugin) {
88            mIDToSessionMap.removeItemsAt(index);
89        }
90    }
91}
92
93} // namespace android
94