Refactor DMaaP simulator and add tests.
[integration/csit.git] / tests / dcaegen2 / testcases / resources / robot_library / dmaap_simulator / DMaaPHandler.py
1 '''
2 Created on Aug 15, 2017
3
4 @author: sw6830
5 '''
6 import os
7 import posixpath
8 import BaseHTTPServer
9 import urllib
10 import urlparse
11 import cgi
12 import sys
13 import shutil
14 import mimetypes
15 from robot_library import DcaeVariables
16
17 try:
18     from cStringIO import StringIO
19 except ImportError:
20     from StringIO import StringIO
21
22
23 class DMaaPHandler(BaseHTTPServer.BaseHTTPRequestHandler):
24
25     def __init__(self, dmaap_simulator, *args):
26         self.dmaap_simulator = dmaap_simulator
27         BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, *args)
28
29     def do_POST(self):
30         if 'POST' not in self.requestline:
31             resp_code = 405
32         else:
33             resp_code = self.parse_the_posted_data()
34
35         if resp_code == 0:
36             self.send_successful_response()
37         else:
38             self.send_response(resp_code)
39
40     def parse_the_posted_data(self):
41         topic = self.extract_topic_from_path()
42         content_len = self.get_content_length()
43         post_body = self.rfile.read(content_len)
44         post_body = self.get_json_part_of_post_body(post_body)
45         event = "{\"" + topic + "\":" + post_body + "}"
46         if self.dmaap_simulator.enque_event(event):
47             resp_code = 0
48         else:
49             print "enque event fails"
50             resp_code = 500
51         return resp_code
52
53     def get_json_part_of_post_body(self, post_body):
54         indx = post_body.index("{")
55         if indx != 0:
56             post_body = post_body[indx:]
57         return post_body
58
59     def extract_topic_from_path(self):
60         return self.path["/events/".__len__():]
61
62     def get_content_length(self):
63         return int(self.headers.getheader('content-length', 0))
64
65     def send_successful_response(self):
66         if 'clientThrottlingState' in self.requestline:
67             self.send_response(204)
68         else:
69             self.send_response(200)
70             self.send_header('Content-Type', 'application/json')
71             self.end_headers()
72             self.wfile.write("{'count': 1, 'serverTimeMs': 3}")
73             self.wfile.close()