2 * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include "common/app_db.h"
19 #include <app_preference.h>
22 #include "common/string_utils.h"
27 const char* kSectionPrefix = "_SECT_";
28 const char* kSectionSuffix = "_SECT_";
32 class PreferenceAppDB : public AppDB {
35 virtual bool HasKey(const std::string& section,
36 const std::string& key) const;
37 virtual std::string Get(const std::string& section,
38 const std::string& key) const;
39 virtual void Set(const std::string& section,
40 const std::string& key,
41 const std::string& value);
42 virtual void GetKeys(const std::string& section,
43 std::list<std::string>* keys) const;
44 virtual void Remove(const std::string& section,
45 const std::string& key);
48 PreferenceAppDB::PreferenceAppDB() {
51 bool PreferenceAppDB::HasKey(const std::string& section,
52 const std::string& key) const {
54 std::string combined_key = kSectionPrefix + section + kSectionSuffix + key;
55 return preference_is_existing(combined_key.c_str(), &existed) == 0 && existed;
58 std::string PreferenceAppDB::Get(const std::string& section,
59 const std::string& key) const {
60 std::string combined_key = kSectionPrefix + section + kSectionSuffix + key;
62 if (preference_get_string(combined_key.c_str(), &value) == 0) {
63 std::unique_ptr<char, decltype(std::free)*> ptr {value, std::free};
64 return std::string(value);
69 void PreferenceAppDB::Set(const std::string& section,
70 const std::string& key,
71 const std::string& value) {
72 std::string combined_key = kSectionPrefix + section + kSectionSuffix + key;
73 preference_set_string(combined_key.c_str(), value.c_str());
76 void PreferenceAppDB::GetKeys(const std::string& section,
77 std::list<std::string>* keys) const {
78 auto callback = [](const char* key, void *user_data) {
79 auto list = static_cast<std::list<std::string>*>(user_data);
80 if (utils::StartsWith(key, list->front())) {
81 list->push_back(key+list->front().size());
85 std::string key_prefix = kSectionPrefix + section + kSectionSuffix;
86 keys->push_front(key_prefix);
87 preference_foreach_item(callback, keys);
91 void PreferenceAppDB::Remove(const std::string& section,
92 const std::string& key) {
93 std::string combined_key = kSectionPrefix + section + kSectionSuffix + key;
94 preference_remove(combined_key.c_str());
98 AppDB* AppDB::GetInstance() {
99 static PreferenceAppDB instance;