3
""" A dummy network location provider that is used for testing reverse
4
geocoding. For fix requests it does not return a position. For reverse geocode
5
requests, it returns a fixed address.
8
class FixRequest(object):
9
""" Represents a fix request. """
11
def __init__(self, request_body):
12
""" Initialize FixRequest with a JSON string.
15
request_body: Request body as JSON string.
17
# simplejson module is imported by the server, see
18
# /test/runner/testwebserver.py
19
json_decoder = simplejson.JSONDecoder()
20
self.request = json_decoder.decode(request_body)
22
def IsValidRequest(self):
23
return self.request.has_key("version") and self.request.has_key("host")
25
def IsReverseGeocodeRequest(self):
26
if self.request.has_key("location"):
27
location = self.request["location"]
28
if location.has_key("latitude") and location.has_key("longitude"):
33
# A successful reverse-geocode response. We must include a valid latitude and
34
# longitude, but Gears will return to JavaScript the values from the reverse
35
# geocode request, not these values.
36
REVERSE_GEOCODE_REQUEST_RESPONSE = """{
41
"street_number": "76",
42
"street": "Buckingham Palace Road",
43
"postal_code": "SW1W 9TQ",
47
"country": "United Kingdom",
53
# An empty position response, indicates no location fixes were found.
54
FIX_REQUEST_RESPONSE = """{}"""
57
def send_response(request_handler, code, response):
58
""" Helper function to construct a HTTP response.
61
request_handler: The request handler instance to issue the response
62
code: The integer HTTP status code for the response
63
response: The string body of the response.
66
request_handler.send_response(code)
68
request_handler.send_header('Content-type', 'application/json')
69
request_handler.end_headers()
70
request_handler.outgoing.append(response)
73
# We accept only POST requests with Content-Type application/json.
74
if self.command == 'POST':
75
if self.headers.get('Content-Type') == 'application/json':
77
fix_request = FixRequest(self.body)
79
# Hard-coded rules to return desired responses
80
if not fix_request.IsValidRequest():
81
send_response(self, 400, "Invalid request")
82
elif fix_request.IsReverseGeocodeRequest():
83
send_response(self, 200, REVERSE_GEOCODE_REQUEST_RESPONSE)
85
send_response(self, 200, FIX_REQUEST_RESPONSE)
87
send_response(self, 400, "Empty request")
89
send_response(self, 400, "Content-Type should be application/json")
91
send_response(self, 405, "Request must be HTTP POST.")