ea0fc3d3ab3dde6c1bdd5c84d29dff1c8f2782e9
[pti/o2.git] / o2ims / domain / stx_object.py
1 # Copyright (C) 2021 Wind River Systems, Inc.
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 # from dataclasses import dataclass
16 import datetime
17 import json
18 from o2common.domain.base import AgRoot
19
20 from o2ims.domain.resource_type import ResourceTypeEnum, MismatchedModel
21 from o2common.helper import o2logging
22 logger = o2logging.get_logger(__name__)
23
24
25 class StxGenericModel(AgRoot):
26     def __init__(self, type: ResourceTypeEnum,
27                  api_response: dict = None, content_hash=None) -> None:
28         super().__init__()
29         if api_response:
30             self.id = str(api_response.uuid)
31             self.type = type
32             self.updatetime = datetime.datetime.strptime(
33                 api_response.updated_at.split('.')[0], "%Y-%m-%dT%H:%M:%S") \
34                 if api_response.updated_at else None
35             self.createtime = datetime.datetime.strptime(
36                 api_response.created_at.split('.')[0], "%Y-%m-%dT%H:%M:%S") \
37                 if api_response.created_at else None
38             self.name = api_response.name
39             self.hash = content_hash if content_hash \
40                 else str(hash((self.id, self.updatetime)))
41             self.content = json.dumps(api_response.to_dict())
42
43     def is_outdated(self, newmodel) -> bool:
44         # return self.updatetime < newmodel.updatetime
45         # logger.warning("hash1: " + self.hash + " vs hash2: " + newmodel.hash)
46         return self.hash != newmodel.hash
47
48     def update_by(self, newmodel) -> None:
49         if self.id != newmodel.id:
50             raise MismatchedModel("Mismatched model")
51         self.name = newmodel.name
52         self.createtime = newmodel.createtime
53         self.updatetime = newmodel.updatetime
54         self.content = newmodel.content