Commit 741f1928 authored by Manuel's avatar Manuel

traceRetrieval: implemented path resolving

parent 4d9ebc89
import json
from authentication.token_manager import TokenManager
import network_constants
import json
import logging
import requests
LOGGER = logging.getLogger(__name__)
class MessageHandler:
......@@ -44,9 +48,66 @@ class MessageHandler:
return result
def handle_blockchain_transaction(self, transaction):
jwt_token = TokenManager.getInstance().getToken()
transaction_data = json.loads(transaction)
use_case = transaction_data["content"]["ApplicationType"]
# query schema information
url = f'https://{network_constants.BUSINESS_LOGIC_HOSTNAME}:{network_constants.BUSINESS_LOGIC_REST_PORT}/api/use-cases/{use_case}/schema'
print(f"CALLING: {url}")
response = requests.get(
url,
verify = False,
proxies = { "http":None, "https":None },
headers = { "Authorization": f"Bearer {jwt_token}"}
)
print(f"RESPONSE: {response.text}")
data = json.loads(response.text)
mappings = data["mappings"]
flattened = {}
# iterate over schema mappings and resolve paths
for mapping in mappings.keys():
path_pieces = mappings[mapping].split("//")
value = transaction_data["content"]
# resolve all pieces of the path in order
for i in range(0,len(path_pieces)):
piece = path_pieces[i]
# is the current path piece in the form attribute[index]?
if piece[-1] == "]":
start = piece.index("[")
# stem ... attribute name
# index ... list index
stem = piece[:start]
index = int(piece[start+1:-1])
value = value[stem][index]
else:
value = value[piece]
flattened[mapping] = value
print("Flattened: "+str(flattened))
# TODO forward [flattened] to next MS
# TODO store the data
# TODO think if inserting makes sense (or just caching while processing if ms goes down)
# self._mongo_repo.insert_trace(transaction)
# TODO convert raw input to prepared data based on key 'ApplicationType'
# inform semantic linking microservice
......
import unittest
import manage_sys_paths
import json
from messaging.MessageHandler import MessageHandler
class DummyMongoRepo:
'''Dummy class to be used for testing the MessageHandler'''
last_trace = None
def insert_trace(self, trace):
self.last_trace = trace
from messaging.DummyMessageManager import DummyMessageManager as DummyMessageSender
class Test_MessageHandler(unittest.TestCase):
handler = None
repo = None
msg_sender = None
def setUp(self):
self.repo = DummyMongoRepo()
self.msg_sender = DummyMessageSender.get_instance()
self.handler = MessageHandler(self.repo, self.msg_sender)
def _get_valid_message(self) -> str:
message_values = \
{
'type': 'blockchain-transaction',
'content':
{
"ApplicationType": "smart-energy",
"Customer": 13,
"Postcode": 2261,
"Timestamp": "01.07.2012 00:30",
"Solar_Production_kWh": 0.0,
"Energy_Consumption_kWh": 0.23399999999999999,
"Heating_Consumption_kWh": 0.23399999999999999,
"Price_AUD/MWh": 57.04,
"Total_Demand_MWh": 8097.93,
"Latitude": -33.362679,
"Longitude": 151.447302,
}
}
return json.dumps(message_values)
def _get_pizza_message(self) -> str:
message_values = \
{
'type': 'blockchain-transaction',
'content':
{
"ApplicationType": "debug",
"name": "Margherita",
"dough": {
"type": "wheat",
"cheese": False,
},
"sauces": [
{
"name": "tomato"
},
{
"name": "caramel"
}
]
}
}
return json.dumps(message_values)
# def test_handleGeneric_correctTraceContent_NotificationSentCorrectly(self):
# msg = self._get_valid_message()
# _ = self.handler.handle_blockchain_transaction(msg)
def test_HandlePizzaMessage(self):
print("STARTING THE TEST...")
msg = self._get_pizza_message()
_ = self.handler.handle_blockchain_transaction(msg)
if __name__ == '__main__':
unittest.main()
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment