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
17 #include "json_importer.h"
18
19 #include <core/io/intf_file_manager.h>
20
21 #include <meta/api/util.h>
22
23 #include "backend/json_input.h"
24 #include "backend/json_output.h"
25 #include "metav1_compat.h"
26
27 META_BEGIN_NAMESPACE()
28 namespace Serialization {
29
JsonImporter()30 JsonImporter::JsonImporter() : transformations_ { CreateShared<MetaMigrateV1>() } {}
ImportAsTree(CORE_NS::IFile & input)31 ISerNode::Ptr JsonImporter::ImportAsTree(CORE_NS::IFile& input)
32 {
33 ISerNode::Ptr tree;
34 BASE_NS::string data;
35 data.resize(input.GetLength());
36 if (input.Read(data.data(), data.size()) == data.size()) {
37 JsonInput json;
38 tree = json.Process(data);
39 if (tree) {
40 tree = Transform(tree, json.GetVersion());
41 /// debug
42 ///
43 }
44 }
45 return tree;
46 }
47
Import(CORE_NS::IFile & input)48 IObject::Ptr JsonImporter::Import(CORE_NS::IFile& input)
49 {
50 if (auto tree = ImportAsTree(input)) {
51 Importer imp;
52 return imp.Import(tree);
53 }
54 return nullptr;
55 }
56
Transform(ISerNode::Ptr tree,const Version & ver)57 ISerNode::Ptr JsonImporter::Transform(ISerNode::Ptr tree, const Version& ver)
58 {
59 bool transformed = false;
60 for (auto&& t : transformations_) {
61 if (ver < t->ApplyForLessThanVersion()) {
62 transformed = true;
63 tree = t->Process(tree);
64 if (!tree) {
65 CORE_LOG_E("Transforming serialisation tree failed (step: %s)", t->GetName().c_str());
66 return nullptr;
67 }
68 }
69 }
70 #ifdef _DEBUG
71 if (transformed) {
72 JsonOutput backend;
73 auto json = backend.Process(tree);
74 if (json.empty()) {
75 CORE_LOG_E("Fail");
76 return nullptr;
77 }
78 auto f = CORE_NS::GetPluginRegister().GetFileManager().CreateFile("file://./rewrite.json");
79 f->Write(json.c_str(), json.size());
80 }
81 #endif
82 return tree;
83 }
GetTransformations() const84 BASE_NS::vector<ISerTransformation::Ptr> JsonImporter::GetTransformations() const
85 {
86 return transformations_;
87 }
SetTransformations(BASE_NS::vector<ISerTransformation::Ptr> t)88 void JsonImporter::SetTransformations(BASE_NS::vector<ISerTransformation::Ptr> t)
89 {
90 transformations_ = BASE_NS::move(t);
91 }
92 } // namespace Serialization
93 META_END_NAMESPACE()
94