Merge "trex_learning: Add learning packet option to T-Rex testing"
[vswitchperf.git] / tools / pkt_gen / xena / json / json_utilities.py
1 # Copyright 2017 Red Hat Inc & Xena Networks.
2 #
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 # Contributors:
16 #   Dan Amzulescu, Xena Networks
17 #   Christian Trautman, Red Hat Inc.
18
19 """JSON utility module"""
20
21 import base64
22 import json
23 import locale
24 import logging
25 import uuid
26
27 _LOGGER = logging.getLogger(__name__)
28 _LOCALE = locale.getlocale()[1]
29
30 def create_segment(header_type, encode_64_string):
31     """
32     Create segment for JSON file
33     :param header_type: Type of header as string
34     :param encode_64_string: 64 byte encoded string value of the hex bytes
35     :return: segment as dictionary
36     """
37     return {
38         "SegmentType": header_type.upper(),
39         "SegmentValue": encode_64_string,
40         "ItemID": str(uuid.uuid4()),
41         "ParentID": "",
42         "Label": ""}
43
44
45 def decode_byte_array(enc_str):
46     """ Decodes the base64-encoded string to a byte array
47     :param enc_str: The base64-encoded string representing a byte array
48     :return: The decoded byte array
49     """
50     dec_string = base64.b64decode(enc_str)
51     barray = bytearray()
52     barray.extend(dec_string)
53     return barray
54
55
56 def encode_byte_array(byte_arr):
57     """ Encodes the byte array as a base64-encoded string
58     :param byte_arr: A bytearray containing the bytes to convert
59     :return: A base64 encoded string
60     """
61     enc_string = base64.b64encode(bytes(byte_arr))
62     return enc_string
63
64
65 def read_json_file(json_file):
66     """
67     Read the json file path and return a dictionary of the data
68     :param json_file: path to json file
69     :return: dictionary of json data
70     """
71     try:
72         with open(json_file, 'r', encoding=_LOCALE) as data_file:
73             file_data = json.loads(data_file.read())
74     except ValueError as exc:
75         # general json exception, Python 3.5 adds new exception type
76         _LOGGER.exception("Exception with json read: %s", exc)
77         raise
78     except IOError as exc:
79         _LOGGER.exception(
80             'Exception during file open: %s file=%s', exc, json_file)
81         raise
82     return file_data
83
84
85 def write_json_file(json_data, output_path):
86     """
87     Write out the dictionary of data to a json file
88     :param json_data: dictionary of json data
89     :param output_path: file path to write output
90     :return: Boolean if success
91     """
92     try:
93         with open(output_path, 'w', encoding=_LOCALE) as fileh:
94             json.dump(json_data, fileh, indent=2, sort_keys=True,
95                       ensure_ascii=True)
96         return True
97     except ValueError as exc:
98         # general json exception, Python 3.5 adds new exception type
99         _LOGGER.exception(
100             "Exception with json write: %s", exc)
101         return False
102     except IOError as exc:
103         _LOGGER.exception(
104             'Exception during file write: %s file=%s', exc, output_path)
105         return False