Seed code for Routing Manager (ric-plt/rtmgr).
[ric-plt/rtmgr.git] / pkg / sdl / file.go
1 /*
2 ==================================================================================
3   Copyright (c) 2019 AT&T Intellectual Property.
4   Copyright (c) 2019 Nokia
5
6    Licensed under the Apache License, Version 2.0 (the "License");
7    you may not use this file except in compliance with the License.
8    You may obtain a copy of the License at
9
10        http://www.apache.org/licenses/LICENSE-2.0
11
12    Unless required by applicable law or agreed to in writing, software
13    distributed under the License is distributed on an "AS IS" BASIS,
14    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15    See the License for the specific language governing permissions and
16    limitations under the License.
17 ==================================================================================
18 */
19 /*
20   Mnemonic:     file.go
21   Abstract:     File SDL implementation. Only for testing purpose.
22   Date:         16 March 2019
23 */
24
25 package sdl
26
27 import (
28         "encoding/json"
29         "errors"
30         "io/ioutil"
31         "os"
32         "rtmgr"
33 )
34
35 /*
36 Reads the content of the rt.json file
37 Parses the JSON content and loads each xApp entry into an xApp object
38 Returns an array os xApp object
39 */
40 func fileReadAll(file string) (*[]rtmgr.XApp, error) {
41         rtmgr.Logger.Debug("Invoked file.fileReadAll")
42         rtmgr.Logger.Debug("file.fileReadAll opens file: " + file)
43         var xapps *[]rtmgr.XApp
44         jsonFile, err := os.Open(file)
45         if err != nil {
46                 return nil, errors.New("cannot open the file due to: " + err.Error())
47         }
48         defer jsonFile.Close()
49         byteValue, err := ioutil.ReadAll(jsonFile)
50         if err != nil {
51                 return nil, errors.New("cannot read the file due to: " + err.Error())
52         }
53         err = json.Unmarshal(byteValue, &xapps)
54         if err != nil {
55                 return nil, errors.New("cannot parse data due to: " + err.Error())
56         }
57         rtmgr.Logger.Debug("file.fileReadAll returns: %v", xapps)
58         return xapps, nil
59 }
60
61 func fileWriteAll(file string, xapps *[]rtmgr.XApp) error {
62         rtmgr.Logger.Debug("Invoked file.fileWriteAll")
63         rtmgr.Logger.Debug("file.fileWriteAll writes into file: " + file)
64         rtmgr.Logger.Debug("file.fileWriteAll writes data: %v", (*xapps))
65         byteValue, err := json.Marshal(xapps)
66         if err != nil {
67                 return errors.New("cannot convert data due to: " + err.Error())
68         }
69         err = ioutil.WriteFile(file, byteValue, 0644)
70         if err != nil {
71                 return errors.New("cannot write file due to: " + err.Error())
72         }
73         return nil
74 }