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_importer.h"
16 
17 #include <core/io/intf_file_manager.h>
18 
19 #include <meta/api/util.h>
20 
21 #include "backend/json_input.h"
22 #include "backend/json_output.h"
23 #include "metav1_compat.h"
24 
25 META_BEGIN_NAMESPACE()
26 namespace Serialization {
27 
ImportAsTree(CORE_NS::IFile & input)28 ISerNode::Ptr JsonImporter::ImportAsTree(CORE_NS::IFile& input)
29 {
30     ISerNode::Ptr tree;
31     BASE_NS::string data;
32     data.resize(input.GetLength());
33     if (input.Read(data.data(), data.size()) == data.size()) {
34         JsonInput json;
35         tree = json.Process(data);
36         if (tree) {
37             if (json.GetJsonVersion() < Version(2, 0)) {
38                 tree = RewriteMetaV1NodeTree(tree);
39                 if (!tree) {
40                     CORE_LOG_E("Converting old meta v1 serialization data failed");
41                     return nullptr;
42                 }
43 #ifdef _DEBUG
44                 /// debug
45                 JsonOutput backend;
46                 auto json = backend.Process(tree);
47                 if (json.empty()) {
48                     CORE_LOG_E("Fail");
49                     return nullptr;
50                 }
51                 auto f = CORE_NS::GetPluginRegister().GetFileManager().CreateFile("file://./rewrite.json");
52                 f->Write(json.c_str(), json.size());
53                 ///
54 #endif
55             }
56         }
57     }
58     return tree;
59 }
60 
Import(CORE_NS::IFile & input)61 IObject::Ptr JsonImporter::Import(CORE_NS::IFile& input)
62 {
63     if (auto tree = ImportAsTree(input)) {
64         Importer imp;
65         return imp.Import(tree);
66     }
67     return nullptr;
68 }
69 
70 } // namespace Serialization
71 META_END_NAMESPACE()
72