1 /* 2 * Copyright (c) 2024 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #include "json_content_loader.h" 17 18 #include "../serialization/importer.h" 19 #include "../serialization/json_importer.h" 20 META_BEGIN_NAMESPACE()21META_BEGIN_NAMESPACE() 22 23 bool JsonContentLoader::Build(const IMetadata::Ptr& data) 24 { 25 cachedChangedHandler_.Subscribe( 26 META_ACCESS_PROPERTY(Cached), MakeCallback<IOnChanged>(this, &JsonContentLoader::Reload)); 27 return true; 28 } 29 Reload()30void JsonContentLoader::Reload() 31 { 32 tree_.reset(); 33 Invoke<IOnChanged>(META_ACCESS_EVENT(ContentChanged)); 34 } 35 Create(const IObject::Ptr &)36IObject::Ptr JsonContentLoader::Create(const IObject::Ptr&) 37 { 38 if (META_ACCESS_PROPERTY(Cached)->GetValue()) { 39 // Try to use a cached file 40 return LoadCached(); 41 } 42 if (file_) { 43 file_->Seek(0); 44 Serialization::JsonImporter importer; 45 if (auto result = importer.Import(*file_)) { 46 return result; 47 } 48 CORE_LOG_E("Importing object hierarchy failed."); 49 } 50 return nullptr; 51 } 52 LoadCached()53IObject::Ptr JsonContentLoader::LoadCached() 54 { 55 if (!UpdateTree()) { 56 CORE_LOG_E("Instantiating object failed"); 57 // No object 58 return {}; 59 } 60 61 Serialization::Importer imp; 62 return imp.Import(tree_); 63 } 64 UpdateTree()65bool JsonContentLoader::UpdateTree() 66 { 67 if (tree_) { 68 return true; 69 } 70 if (!file_) { 71 return false; 72 } 73 74 file_->Seek(0); 75 76 Serialization::JsonImporter importer; 77 tree_ = importer.ImportAsTree(*file_); 78 79 return tree_ != nullptr; 80 } 81 SetFile(CORE_NS::IFile::Ptr file)82bool JsonContentLoader::SetFile(CORE_NS::IFile::Ptr file) 83 { 84 file_ = BASE_NS::move(file); 85 Reload(); 86 return true; 87 } 88 89 META_END_NAMESPACE() 90