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 #include "json_content_loader.h"
16 
17 #include "../serialization/importer.h"
18 #include "../serialization/json_importer.h"
19 
META_BEGIN_NAMESPACE()20 META_BEGIN_NAMESPACE()
21 
22 bool JsonContentLoader::Build(const IMetadata::Ptr& data)
23 {
24     cachedChangedHandler_.Subscribe(
25         META_ACCESS_PROPERTY(Cached), MakeCallback<IOnChanged>(this, &JsonContentLoader::Reload));
26     return true;
27 }
28 
Reload()29 void JsonContentLoader::Reload()
30 {
31     tree_.reset();
32     META_ACCESS_EVENT(ContentChanged)->Invoke();
33 }
34 
Create(const IObject::Ptr &)35 IObject::Ptr JsonContentLoader::Create(const IObject::Ptr&)
36 {
37     if (META_ACCESS_PROPERTY(Cached)->GetValue()) {
38         // Try to use a cached file
39         return LoadCached();
40     }
41     if (file_) {
42         file_->Seek(0);
43         Serialization::JsonImporter importer;
44         if (auto result = importer.Import(*file_)) {
45             return result;
46         }
47         CORE_LOG_E("Importing object hierarchy failed.");
48     }
49     return nullptr;
50 }
51 
LoadCached()52 IObject::Ptr JsonContentLoader::LoadCached()
53 {
54     if (!UpdateTree()) {
55         CORE_LOG_E("Instantiating object failed");
56         // No object
57         return {};
58     }
59 
60     Serialization::Importer imp;
61     return imp.Import(tree_);
62 }
63 
UpdateTree()64 bool JsonContentLoader::UpdateTree()
65 {
66     if (tree_) {
67         return true;
68     }
69     if (!file_) {
70         return false;
71     }
72 
73     file_->Seek(0);
74 
75     Serialization::JsonImporter importer;
76     tree_ = importer.ImportAsTree(*file_);
77 
78     return tree_ != nullptr;
79 }
80 
SetFile(CORE_NS::IFile::Ptr file)81 bool JsonContentLoader::SetFile(CORE_NS::IFile::Ptr file)
82 {
83     file_ = BASE_NS::move(file);
84     Reload();
85     return true;
86 }
87 
88 META_END_NAMESPACE()
89