summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMagnus Feuer <mfeuer@jaguarlandrover.com>2014-12-01 14:58:41 -0800
committerMagnus Feuer <mfeuer@jaguarlandrover.com>2014-12-01 14:58:41 -0800
commit8ec6c5127466b6e68333d03255910aca627ea65c (patch)
tree78dc2cfd6a7b29f04124e942415e5a0554144b5a
parent636f9bdaa7405d87591e53a6287107dd5a85a6ef (diff)
downloadrvi_core-8ec6c5127466b6e68333d03255910aca627ea65c.tar.gz
Added spec and manifest to build big_data demo Tizen RPM
-rw-r--r--big_data_demo/big_data.service18
-rw-r--r--big_data_demo/jsonrpclib/.gitignore3
-rw-r--r--big_data_demo/jsonrpclib/LICENSE.txt11
-rw-r--r--big_data_demo/jsonrpclib/MANIFEST.in1
-rw-r--r--big_data_demo/jsonrpclib/README.md219
-rwxr-xr-xbig_data_demo/jsonrpclib/setup.py29
-rw-r--r--big_data_demo/jsonrpclib/tests.py456
-rw-r--r--big_data_demo/mod/lib/python/gps/__init__.py13
-rw-r--r--big_data_demo/mod/lib/python/gps/__init__.pycbin0 -> 252 bytes
-rw-r--r--big_data_demo/mod/lib/python/gps/client.py206
-rw-r--r--big_data_demo/mod/lib/python/gps/client.pycbin0 -> 7909 bytes
-rw-r--r--big_data_demo/mod/lib/python/gps/fake.py594
-rwxr-xr-xbig_data_demo/mod/lib/python/gps/gps.py366
-rw-r--r--big_data_demo/mod/lib/python/gps/gps.pycbin0 -> 11887 bytes
-rw-r--r--big_data_demo/mod/lib/python/gps/misc.py102
-rw-r--r--big_data_demo/mod/lib/python/gps/misc.pycbin0 -> 3301 bytes
-rw-r--r--big_data_demo/mod/lib/python/jsonrpclib-0.1.3-py2.7.egg-info229
-rw-r--r--big_data_demo/mod/lib/python/jsonrpclib/SimpleJSONRPCServer.py (renamed from big_data_demo/jsonrpclib/jsonrpclib/SimpleJSONRPCServer.py)0
-rw-r--r--big_data_demo/mod/lib/python/jsonrpclib/SimpleJSONRPCServer.pycbin0 -> 7854 bytes
-rw-r--r--big_data_demo/mod/lib/python/jsonrpclib/__init__.py (renamed from big_data_demo/jsonrpclib/jsonrpclib/__init__.py)0
-rw-r--r--big_data_demo/mod/lib/python/jsonrpclib/__init__.pycbin0 -> 514 bytes
-rw-r--r--big_data_demo/mod/lib/python/jsonrpclib/config.py (renamed from big_data_demo/jsonrpclib/jsonrpclib/config.py)0
-rw-r--r--big_data_demo/mod/lib/python/jsonrpclib/config.pycbin0 -> 1539 bytes
-rw-r--r--big_data_demo/mod/lib/python/jsonrpclib/history.py (renamed from big_data_demo/jsonrpclib/jsonrpclib/history.py)0
-rw-r--r--big_data_demo/mod/lib/python/jsonrpclib/history.pycbin0 -> 1798 bytes
-rw-r--r--big_data_demo/mod/lib/python/jsonrpclib/jsonclass.py (renamed from big_data_demo/jsonrpclib/jsonrpclib/jsonclass.py)0
-rw-r--r--big_data_demo/mod/lib/python/jsonrpclib/jsonclass.pycbin0 -> 3747 bytes
-rw-r--r--big_data_demo/mod/lib/python/jsonrpclib/jsonrpc.py (renamed from big_data_demo/jsonrpclib/jsonrpclib/jsonrpc.py)0
-rw-r--r--big_data_demo/mod/lib/python/jsonrpclib/jsonrpc.pycbin0 -> 21139 bytes
-rw-r--r--packaging/big_data_demo.manifest5
-rwxr-xr-xpackaging/big_data_demo.spec56
-rw-r--r--sota_demo/jsonrpclib/.gitignore3
-rw-r--r--sota_demo/jsonrpclib/LICENSE.txt11
-rw-r--r--sota_demo/jsonrpclib/MANIFEST.in1
-rw-r--r--sota_demo/jsonrpclib/README.md219
-rw-r--r--sota_demo/jsonrpclib/jsonrpclib/SimpleJSONRPCServer.py232
-rw-r--r--sota_demo/jsonrpclib/jsonrpclib/__init__.py6
-rw-r--r--sota_demo/jsonrpclib/jsonrpclib/config.py38
-rw-r--r--sota_demo/jsonrpclib/jsonrpclib/history.py40
-rw-r--r--sota_demo/jsonrpclib/jsonrpclib/jsonclass.py152
-rw-r--r--sota_demo/jsonrpclib/jsonrpclib/jsonrpc.py556
-rwxr-xr-xsota_demo/jsonrpclib/setup.py29
-rw-r--r--sota_demo/jsonrpclib/tests.py456
43 files changed, 1589 insertions, 2462 deletions
diff --git a/big_data_demo/big_data.service b/big_data_demo/big_data.service
new file mode 100644
index 0000000..3e85b3a
--- /dev/null
+++ b/big_data_demo/big_data.service
@@ -0,0 +1,18 @@
+# systemd(8) setup usde by Tizen and others.
+[Unit]
+Description=Software Over The Air Service
+Wants=network-online.target rvi.service
+
+[Service]
+Environment="HOME=/opt/big_data_demo-0.3.0"
+Environment="PYTHONPATH=/opt/big_data_demo-0.3.0/mod/lib/python"
+Environment="HOME=/opt/big_data_demo-0.3.0 PYTHONPATH=/opt/big_data_demo-0.3.0/mod/lib/python "
+WorkingDirectory=/opt/big_data_demo-0.3.0
+Type=simple
+StandardOutput=journal
+StandardError=journal
+ExecStart=/bin/sh -c "sleep 10;/usr/bin/python big_data_device.py http://localhost:8811"
+GuessMainPID=yes
+
+[Install]
+WantedBy=graphical.target multi-user.target
diff --git a/big_data_demo/jsonrpclib/.gitignore b/big_data_demo/jsonrpclib/.gitignore
deleted file mode 100644
index f7d6c1a..0000000
--- a/big_data_demo/jsonrpclib/.gitignore
+++ /dev/null
@@ -1,3 +0,0 @@
-*.pyc
-build/*
-dist/*
diff --git a/big_data_demo/jsonrpclib/LICENSE.txt b/big_data_demo/jsonrpclib/LICENSE.txt
deleted file mode 100644
index 51fca54..0000000
--- a/big_data_demo/jsonrpclib/LICENSE.txt
+++ /dev/null
@@ -1,11 +0,0 @@
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
diff --git a/big_data_demo/jsonrpclib/MANIFEST.in b/big_data_demo/jsonrpclib/MANIFEST.in
deleted file mode 100644
index ab30e9a..0000000
--- a/big_data_demo/jsonrpclib/MANIFEST.in
+++ /dev/null
@@ -1 +0,0 @@
-include *.txt
diff --git a/big_data_demo/jsonrpclib/README.md b/big_data_demo/jsonrpclib/README.md
deleted file mode 100644
index 85a157e..0000000
--- a/big_data_demo/jsonrpclib/README.md
+++ /dev/null
@@ -1,219 +0,0 @@
-JSONRPClib
-==========
-This library is an implementation of the JSON-RPC specification.
-It supports both the original 1.0 specification, as well as the
-new (proposed) 2.0 spec, which includes batch submission, keyword
-arguments, etc.
-
-It is licensed under the Apache License, Version 2.0
-(http://www.apache.org/licenses/LICENSE-2.0.html).
-
-Communication
--------------
-Feel free to send any questions, comments, or patches to our Google Group
-mailing list (you'll need to join to send a message):
-http://groups.google.com/group/jsonrpclib
-
-Summary
--------
-This library implements the JSON-RPC 2.0 proposed specification in pure Python.
-It is designed to be as compatible with the syntax of xmlrpclib as possible
-(it extends where possible), so that projects using xmlrpclib could easily be
-modified to use JSON and experiment with the differences.
-
-It is backwards-compatible with the 1.0 specification, and supports all of the
-new proposed features of 2.0, including:
-
-* Batch submission (via MultiCall)
-* Keyword arguments
-* Notifications (both in a batch and 'normal')
-* Class translation using the 'jsonclass' key.
-
-I've added a "SimpleJSONRPCServer", which is intended to emulate the
-"SimpleXMLRPCServer" from the default Python distribution.
-
-Requirements
-------------
-It supports cjson and simplejson, and looks for the parsers in that order
-(searching first for cjson, then for the "built-in" simplejson as json in 2.6+,
-and then the simplejson external library). One of these must be installed to
-use this library, although if you have a standard distribution of 2.6+, you
-should already have one. Keep in mind that cjson is supposed to be the
-quickest, I believe, so if you are going for full-on optimization you may
-want to pick it up.
-
-Installation
-------------
-You can install this from PyPI with one of the following commands (sudo
-may be required):
-
- easy_install jsonrpclib
- pip install jsonrpclib
-
-Alternatively, you can download the source from the github repository
-at http://github.com/joshmarshall/jsonrpclib and manually install it
-with the following commands:
-
- git clone git://github.com/joshmarshall/jsonrpclib.git
- cd jsonrpclib
- python setup.py install
-
-Client Usage
-------------
-
-This is (obviously) taken from a console session.
-
- >>> import jsonrpclib
- >>> server = jsonrpclib.Server('http://localhost:8080')
- >>> server.add(5,6)
- 11
- >>> print jsonrpclib.history.request
- {"jsonrpc": "2.0", "params": [5, 6], "id": "gb3c9g37", "method": "add"}
- >>> print jsonrpclib.history.response
- {'jsonrpc': '2.0', 'result': 11, 'id': 'gb3c9g37'}
- >>> server.add(x=5, y=10)
- 15
- >>> server._notify.add(5,6)
- # No result returned...
- >>> batch = jsonrpclib.MultiCall(server)
- >>> batch.add(5, 6)
- >>> batch.ping({'key':'value'})
- >>> batch._notify.add(4, 30)
- >>> results = batch()
- >>> for result in results:
- >>> ... print result
- 11
- {'key': 'value'}
- # Note that there are only two responses -- this is according to spec.
-
-If you need 1.0 functionality, there are a bunch of places you can pass that
-in, although the best is just to change the value on
-jsonrpclib.config.version:
-
- >>> import jsonrpclib
- >>> jsonrpclib.config.version
- 2.0
- >>> jsonrpclib.config.version = 1.0
- >>> server = jsonrpclib.Server('http://localhost:8080')
- >>> server.add(7, 10)
- 17
- >>> print jsonrpclib..history.request
- {"params": [7, 10], "id": "thes7tl2", "method": "add"}
- >>> print jsonrpclib.history.response
- {'id': 'thes7tl2', 'result': 17, 'error': None}
- >>>
-
-The equivalent loads and dumps functions also exist, although with minor
-modifications. The dumps arguments are almost identical, but it adds three
-arguments: rpcid for the 'id' key, version to specify the JSON-RPC
-compatibility, and notify if it's a request that you want to be a
-notification.
-
-Additionally, the loads method does not return the params and method like
-xmlrpclib, but instead a.) parses for errors, raising ProtocolErrors, and
-b.) returns the entire structure of the request / response for manual parsing.
-
-SimpleJSONRPCServer
--------------------
-This is identical in usage (or should be) to the SimpleXMLRPCServer in the default Python install. Some of the differences in features are that it obviously supports notification, batch calls, class translation (if left on), etc. Note: The import line is slightly different from the regular SimpleXMLRPCServer, since the SimpleJSONRPCServer is distributed within the jsonrpclib library.
-
- from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
-
- server = SimpleJSONRPCServer(('localhost', 8080))
- server.register_function(pow)
- server.register_function(lambda x,y: x+y, 'add')
- server.register_function(lambda x: x, 'ping')
- server.serve_forever()
-
-Class Translation
------------------
-I've recently added "automatic" class translation support, although it is
-turned off by default. This can be devastatingly slow if improperly used, so
-the following is just a short list of things to keep in mind when using it.
-
-* Keep It (the object) Simple Stupid. (for exceptions, keep reading.)
-* Do not require init params (for exceptions, keep reading)
-* Getter properties without setters could be dangerous (read: not tested)
-
-If any of the above are issues, use the _serialize method. (see usage below)
-The server and client must BOTH have use_jsonclass configuration item on and
-they must both have access to the same libraries used by the objects for
-this to work.
-
-If you have excessively nested arguments, it would be better to turn off the
-translation and manually invoke it on specific objects using
-jsonrpclib.jsonclass.dump / jsonrpclib.jsonclass.load (since the default
-behavior recursively goes through attributes and lists / dicts / tuples).
-
-[test_obj.py]
-
- # This object is /very/ simple, and the system will look through the
- # attributes and serialize what it can.
- class TestObj(object):
- foo = 'bar'
-
- # This object requires __init__ params, so it uses the _serialize method
- # and returns a tuple of init params and attribute values (the init params
- # can be a dict or a list, but the attribute values must be a dict.)
- class TestSerial(object):
- foo = 'bar'
- def __init__(self, *args):
- self.args = args
- def _serialize(self):
- return (self.args, {'foo':self.foo,})
-
-[usage]
-
- import jsonrpclib
- import test_obj
-
- jsonrpclib.config.use_jsonclass = True
-
- testobj1 = test_obj.TestObj()
- testobj2 = test_obj.TestSerial()
- server = jsonrpclib.Server('http://localhost:8080')
- # The 'ping' just returns whatever is sent
- ping1 = server.ping(testobj1)
- ping2 = server.ping(testobj2)
- print jsonrpclib.history.request
- # {"jsonrpc": "2.0", "params": [{"__jsonclass__": ["test_obj.TestSerial", ["foo"]]}], "id": "a0l976iv", "method": "ping"}
- print jsonrpclib.history.result
- # {'jsonrpc': '2.0', 'result': <test_obj.TestSerial object at 0x2744590>, 'id': 'a0l976iv'}
-
-To turn on this behaviour, just set jsonrpclib.config.use_jsonclass to True.
-If you want to use a different method for serialization, just set
-jsonrpclib.config.serialize_method to the method name. Finally, if you are
-using classes that you have defined in the implementation (as in, not a
-separate library), you'll need to add those (on BOTH the server and the
-client) using the jsonrpclib.config.classes.add() method.
-(Examples forthcoming.)
-
-Feedback on this "feature" is very, VERY much appreciated.
-
-Why JSON-RPC?
--------------
-In my opinion, there are several reasons to choose JSON over XML for RPC:
-
-* Much simpler to read (I suppose this is opinion, but I know I'm right. :)
-* Size / Bandwidth - Main reason, a JSON object representation is just much smaller.
-* Parsing - JSON should be much quicker to parse than XML.
-* Easy class passing with jsonclass (when enabled)
-
-In the interest of being fair, there are also a few reasons to choose XML
-over JSON:
-
-* Your server doesn't do JSON (rather obvious)
-* Wider XML-RPC support across APIs (can we change this? :))
-* Libraries are more established, i.e. more stable (Let's change this too.)
-
-TESTS
------
-I've dropped almost-verbatim tests from the JSON-RPC spec 2.0 page.
-You can run it with:
-
- python tests.py
-
-TODO
-----
-* Use HTTP error codes on SimpleJSONRPCServer
-* Test, test, test and optimize
diff --git a/big_data_demo/jsonrpclib/setup.py b/big_data_demo/jsonrpclib/setup.py
deleted file mode 100755
index 72f8b35..0000000
--- a/big_data_demo/jsonrpclib/setup.py
+++ /dev/null
@@ -1,29 +0,0 @@
-#!/usr/bin/env python
-"""
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-"""
-
-import distutils.core
-
-distutils.core.setup(
- name = "jsonrpclib",
- version = "0.1.3",
- packages = ["jsonrpclib"],
- author = "Josh Marshall",
- author_email = "catchjosh@gmail.com",
- url = "http://github.com/joshmarshall/jsonrpclib/",
- license = "http://www.apache.org/licenses/LICENSE-2.0",
- description = "This project is an implementation of the JSON-RPC v2.0 " +
- "specification (backwards-compatible) as a client library.",
- long_description = open("README.md").read()
-)
diff --git a/big_data_demo/jsonrpclib/tests.py b/big_data_demo/jsonrpclib/tests.py
deleted file mode 100644
index 3ce1009..0000000
--- a/big_data_demo/jsonrpclib/tests.py
+++ /dev/null
@@ -1,456 +0,0 @@
-"""
-The tests in this file compare the request and response objects
-to the JSON-RPC 2.0 specification document, as well as testing
-several internal components of the jsonrpclib library. Run this
-module without any parameters to run the tests.
-
-Currently, this is not easily tested with a framework like
-nosetests because we spin up a daemon thread running the
-the Server, and nosetests (at least in my tests) does not
-ever "kill" the thread.
-
-If you are testing jsonrpclib and the module doesn't return to
-the command prompt after running the tests, you can hit
-"Ctrl-C" (or "Ctrl-Break" on Windows) and that should kill it.
-
-TODO:
-* Finish implementing JSON-RPC 2.0 Spec tests
-* Implement JSON-RPC 1.0 tests
-* Implement JSONClass, History, Config tests
-"""
-
-from jsonrpclib import Server, MultiCall, history, config, ProtocolError
-from jsonrpclib import jsonrpc
-from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
-from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCRequestHandler
-import socket
-import tempfile
-import unittest
-import os
-import time
-try:
- import json
-except ImportError:
- import simplejson as json
-from threading import Thread
-
-PORTS = range(8000, 8999)
-
-class TestCompatibility(unittest.TestCase):
-
- client = None
- port = None
- server = None
-
- def setUp(self):
- self.port = PORTS.pop()
- self.server = server_set_up(addr=('', self.port))
- self.client = Server('http://localhost:%d' % self.port)
-
- # v1 tests forthcoming
-
- # Version 2.0 Tests
- def test_positional(self):
- """ Positional arguments in a single call """
- result = self.client.subtract(23, 42)
- self.assertTrue(result == -19)
- result = self.client.subtract(42, 23)
- self.assertTrue(result == 19)
- request = json.loads(history.request)
- response = json.loads(history.response)
- verify_request = {
- "jsonrpc": "2.0", "method": "subtract",
- "params": [42, 23], "id": request['id']
- }
- verify_response = {
- "jsonrpc": "2.0", "result": 19, "id": request['id']
- }
- self.assertTrue(request == verify_request)
- self.assertTrue(response == verify_response)
-
- def test_named(self):
- """ Named arguments in a single call """
- result = self.client.subtract(subtrahend=23, minuend=42)
- self.assertTrue(result == 19)
- result = self.client.subtract(minuend=42, subtrahend=23)
- self.assertTrue(result == 19)
- request = json.loads(history.request)
- response = json.loads(history.response)
- verify_request = {
- "jsonrpc": "2.0", "method": "subtract",
- "params": {"subtrahend": 23, "minuend": 42},
- "id": request['id']
- }
- verify_response = {
- "jsonrpc": "2.0", "result": 19, "id": request['id']
- }
- self.assertTrue(request == verify_request)
- self.assertTrue(response == verify_response)
-
- def test_notification(self):
- """ Testing a notification (response should be null) """
- result = self.client._notify.update(1, 2, 3, 4, 5)
- self.assertTrue(result == None)
- request = json.loads(history.request)
- response = history.response
- verify_request = {
- "jsonrpc": "2.0", "method": "update", "params": [1,2,3,4,5]
- }
- verify_response = ''
- self.assertTrue(request == verify_request)
- self.assertTrue(response == verify_response)
-
- def test_non_existent_method(self):
- self.assertRaises(ProtocolError, self.client.foobar)
- request = json.loads(history.request)
- response = json.loads(history.response)
- verify_request = {
- "jsonrpc": "2.0", "method": "foobar", "id": request['id']
- }
- verify_response = {
- "jsonrpc": "2.0",
- "error":
- {"code": -32601, "message": response['error']['message']},
- "id": request['id']
- }
- self.assertTrue(request == verify_request)
- self.assertTrue(response == verify_response)
-
- def test_invalid_json(self):
- invalid_json = '{"jsonrpc": "2.0", "method": "foobar, '+ \
- '"params": "bar", "baz]'
- response = self.client._run_request(invalid_json)
- response = json.loads(history.response)
- verify_response = json.loads(
- '{"jsonrpc": "2.0", "error": {"code": -32700,'+
- ' "message": "Parse error."}, "id": null}'
- )
- verify_response['error']['message'] = response['error']['message']
- self.assertTrue(response == verify_response)
-
- def test_invalid_request(self):
- invalid_request = '{"jsonrpc": "2.0", "method": 1, "params": "bar"}'
- response = self.client._run_request(invalid_request)
- response = json.loads(history.response)
- verify_response = json.loads(
- '{"jsonrpc": "2.0", "error": {"code": -32600, '+
- '"message": "Invalid Request."}, "id": null}'
- )
- verify_response['error']['message'] = response['error']['message']
- self.assertTrue(response == verify_response)
-
- def test_batch_invalid_json(self):
- invalid_request = '[ {"jsonrpc": "2.0", "method": "sum", '+ \
- '"params": [1,2,4], "id": "1"},{"jsonrpc": "2.0", "method" ]'
- response = self.client._run_request(invalid_request)
- response = json.loads(history.response)
- verify_response = json.loads(
- '{"jsonrpc": "2.0", "error": {"code": -32700,'+
- '"message": "Parse error."}, "id": null}'
- )
- verify_response['error']['message'] = response['error']['message']
- self.assertTrue(response == verify_response)
-
- def test_empty_array(self):
- invalid_request = '[]'
- response = self.client._run_request(invalid_request)
- response = json.loads(history.response)
- verify_response = json.loads(
- '{"jsonrpc": "2.0", "error": {"code": -32600, '+
- '"message": "Invalid Request."}, "id": null}'
- )
- verify_response['error']['message'] = response['error']['message']
- self.assertTrue(response == verify_response)
-
- def test_nonempty_array(self):
- invalid_request = '[1,2]'
- request_obj = json.loads(invalid_request)
- response = self.client._run_request(invalid_request)
- response = json.loads(history.response)
- self.assertTrue(len(response) == len(request_obj))
- for resp in response:
- verify_resp = json.loads(
- '{"jsonrpc": "2.0", "error": {"code": -32600, '+
- '"message": "Invalid Request."}, "id": null}'
- )
- verify_resp['error']['message'] = resp['error']['message']
- self.assertTrue(resp == verify_resp)
-
- def test_batch(self):
- multicall = MultiCall(self.client)
- multicall.sum(1,2,4)
- multicall._notify.notify_hello(7)
- multicall.subtract(42,23)
- multicall.foo.get(name='myself')
- multicall.get_data()
- job_requests = [j.request() for j in multicall._job_list]
- job_requests.insert(3, '{"foo": "boo"}')
- json_requests = '[%s]' % ','.join(job_requests)
- requests = json.loads(json_requests)
- responses = self.client._run_request(json_requests)
-
- verify_requests = json.loads("""[
- {"jsonrpc": "2.0", "method": "sum", "params": [1,2,4], "id": "1"},
- {"jsonrpc": "2.0", "method": "notify_hello", "params": [7]},
- {"jsonrpc": "2.0", "method": "subtract", "params": [42,23], "id": "2"},
- {"foo": "boo"},
- {"jsonrpc": "2.0", "method": "foo.get", "params": {"name": "myself"}, "id": "5"},
- {"jsonrpc": "2.0", "method": "get_data", "id": "9"}
- ]""")
-
- # Thankfully, these are in order so testing is pretty simple.
- verify_responses = json.loads("""[
- {"jsonrpc": "2.0", "result": 7, "id": "1"},
- {"jsonrpc": "2.0", "result": 19, "id": "2"},
- {"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request."}, "id": null},
- {"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found."}, "id": "5"},
- {"jsonrpc": "2.0", "result": ["hello", 5], "id": "9"}
- ]""")
-
- self.assertTrue(len(requests) == len(verify_requests))
- self.assertTrue(len(responses) == len(verify_responses))
-
- responses_by_id = {}
- response_i = 0
-
- for i in range(len(requests)):
- verify_request = verify_requests[i]
- request = requests[i]
- response = None
- if request.get('method') != 'notify_hello':
- req_id = request.get('id')
- if verify_request.has_key('id'):
- verify_request['id'] = req_id
- verify_response = verify_responses[response_i]
- verify_response['id'] = req_id
- responses_by_id[req_id] = verify_response
- response_i += 1
- response = verify_response
- self.assertTrue(request == verify_request)
-
- for response in responses:
- verify_response = responses_by_id.get(response.get('id'))
- if verify_response.has_key('error'):
- verify_response['error']['message'] = \
- response['error']['message']
- self.assertTrue(response == verify_response)
-
- def test_batch_notifications(self):
- multicall = MultiCall(self.client)
- multicall._notify.notify_sum(1, 2, 4)
- multicall._notify.notify_hello(7)
- result = multicall()
- self.assertTrue(len(result) == 0)
- valid_request = json.loads(
- '[{"jsonrpc": "2.0", "method": "notify_sum", '+
- '"params": [1,2,4]},{"jsonrpc": "2.0", '+
- '"method": "notify_hello", "params": [7]}]'
- )
- request = json.loads(history.request)
- self.assertTrue(len(request) == len(valid_request))
- for i in range(len(request)):
- req = request[i]
- valid_req = valid_request[i]
- self.assertTrue(req == valid_req)
- self.assertTrue(history.response == '')
-
-class InternalTests(unittest.TestCase):
- """
- These tests verify that the client and server portions of
- jsonrpclib talk to each other properly.
- """
- client = None
- server = None
- port = None
-
- def setUp(self):
- self.port = PORTS.pop()
- self.server = server_set_up(addr=('', self.port))
-
- def get_client(self):
- return Server('http://localhost:%d' % self.port)
-
- def get_multicall_client(self):
- server = self.get_client()
- return MultiCall(server)
-
- def test_connect(self):
- client = self.get_client()
- result = client.ping()
- self.assertTrue(result)
-
- def test_single_args(self):
- client = self.get_client()
- result = client.add(5, 10)
- self.assertTrue(result == 15)
-
- def test_single_kwargs(self):
- client = self.get_client()
- result = client.add(x=5, y=10)
- self.assertTrue(result == 15)
-
- def test_single_kwargs_and_args(self):
- client = self.get_client()
- self.assertRaises(ProtocolError, client.add, (5,), {'y':10})
-
- def test_single_notify(self):
- client = self.get_client()
- result = client._notify.add(5, 10)
- self.assertTrue(result == None)
-
- def test_single_namespace(self):
- client = self.get_client()
- response = client.namespace.sum(1,2,4)
- request = json.loads(history.request)
- response = json.loads(history.response)
- verify_request = {
- "jsonrpc": "2.0", "params": [1, 2, 4],
- "id": "5", "method": "namespace.sum"
- }
- verify_response = {
- "jsonrpc": "2.0", "result": 7, "id": "5"
- }
- verify_request['id'] = request['id']
- verify_response['id'] = request['id']
- self.assertTrue(verify_request == request)
- self.assertTrue(verify_response == response)
-
- def test_multicall_success(self):
- multicall = self.get_multicall_client()
- multicall.ping()
- multicall.add(5, 10)
- multicall.namespace.sum([5, 10, 15])
- correct = [True, 15, 30]
- i = 0
- for result in multicall():
- self.assertTrue(result == correct[i])
- i += 1
-
- def test_multicall_success(self):
- multicall = self.get_multicall_client()
- for i in range(3):
- multicall.add(5, i)
- result = multicall()
- self.assertTrue(result[2] == 7)
-
- def test_multicall_failure(self):
- multicall = self.get_multicall_client()
- multicall.ping()
- multicall.add(x=5, y=10, z=10)
- raises = [None, ProtocolError]
- result = multicall()
- for i in range(2):
- if not raises[i]:
- result[i]
- else:
- def func():
- return result[i]
- self.assertRaises(raises[i], func)
-
-
-if jsonrpc.USE_UNIX_SOCKETS:
- # We won't do these tests unless Unix Sockets are supported
-
- class UnixSocketInternalTests(InternalTests):
- """
- These tests run the same internal communication tests,
- but over a Unix socket instead of a TCP socket.
- """
- def setUp(self):
- suffix = "%d.sock" % PORTS.pop()
-
- # Open to safer, alternative processes
- # for getting a temp file name...
- temp = tempfile.NamedTemporaryFile(
- suffix=suffix
- )
- self.port = temp.name
- temp.close()
-
- self.server = server_set_up(
- addr=self.port,
- address_family=socket.AF_UNIX
- )
-
- def get_client(self):
- return Server('unix:/%s' % self.port)
-
- def tearDown(self):
- """ Removes the tempory socket file """
- os.unlink(self.port)
-
-class UnixSocketErrorTests(unittest.TestCase):
- """
- Simply tests that the proper exceptions fire if
- Unix sockets are attempted to be used on a platform
- that doesn't support them.
- """
-
- def setUp(self):
- self.original_value = jsonrpc.USE_UNIX_SOCKETS
- if (jsonrpc.USE_UNIX_SOCKETS):
- jsonrpc.USE_UNIX_SOCKETS = False
-
- def test_client(self):
- address = "unix://shouldnt/work.sock"
- self.assertRaises(
- jsonrpc.UnixSocketMissing,
- Server,
- address
- )
-
- def tearDown(self):
- jsonrpc.USE_UNIX_SOCKETS = self.original_value
-
-
-""" Test Methods """
-def subtract(minuend, subtrahend):
- """ Using the keywords from the JSON-RPC v2 doc """
- return minuend-subtrahend
-
-def add(x, y):
- return x + y
-
-def update(*args):
- return args
-
-def summation(*args):
- return sum(args)
-
-def notify_hello(*args):
- return args
-
-def get_data():
- return ['hello', 5]
-
-def ping():
- return True
-
-def server_set_up(addr, address_family=socket.AF_INET):
- # Not sure this is a good idea to spin up a new server thread
- # for each test... but it seems to work fine.
- def log_request(self, *args, **kwargs):
- """ Making the server output 'quiet' """
- pass
- SimpleJSONRPCRequestHandler.log_request = log_request
- server = SimpleJSONRPCServer(addr, address_family=address_family)
- server.register_function(summation, 'sum')
- server.register_function(summation, 'notify_sum')
- server.register_function(notify_hello)
- server.register_function(subtract)
- server.register_function(update)
- server.register_function(get_data)
- server.register_function(add)
- server.register_function(ping)
- server.register_function(summation, 'namespace.sum')
- server_proc = Thread(target=server.serve_forever)
- server_proc.daemon = True
- server_proc.start()
- return server_proc
-
-if __name__ == '__main__':
- print "==============================================================="
- print " NOTE: There may be threading exceptions after tests finish. "
- print "==============================================================="
- time.sleep(2)
- unittest.main()
diff --git a/big_data_demo/mod/lib/python/gps/__init__.py b/big_data_demo/mod/lib/python/gps/__init__.py
new file mode 100644
index 0000000..cb73669
--- /dev/null
+++ b/big_data_demo/mod/lib/python/gps/__init__.py
@@ -0,0 +1,13 @@
+# Make core client functions available without prefix.
+#
+# This file is Copyright (c) 2010 by the GPSD project
+# BSD terms apply: see the file COPYING in the distribution root for details.
+
+api_major_version = 5 # bumped on incompatible changes
+api_minor_version = 0 # bumped on compatible changes
+
+from gps import *
+from misc import *
+
+# The 'client' module exposes some C utility functions for Python clients.
+# The 'packet' module exposes the packet getter via a Python interface.
diff --git a/big_data_demo/mod/lib/python/gps/__init__.pyc b/big_data_demo/mod/lib/python/gps/__init__.pyc
new file mode 100644
index 0000000..ca397fe
--- /dev/null
+++ b/big_data_demo/mod/lib/python/gps/__init__.pyc
Binary files differ
diff --git a/big_data_demo/mod/lib/python/gps/client.py b/big_data_demo/mod/lib/python/gps/client.py
new file mode 100644
index 0000000..43a8be4
--- /dev/null
+++ b/big_data_demo/mod/lib/python/gps/client.py
@@ -0,0 +1,206 @@
+# This file is Copyright (c) 2010 by the GPSD project
+# BSD terms apply: see the file COPYING in the distribution root for details.
+#
+import time, socket, sys, select
+
+if sys.hexversion >= 0x2060000:
+ import json # For Python 2.6
+else:
+ import simplejson as json # For Python 2.4 and 2.5
+
+GPSD_PORT="2947"
+
+class json_error:
+ def __init__(self, data, explanation):
+ self.data = data
+ self.explanation = explanation
+
+class gpscommon:
+ "Isolate socket handling and buffering from the protcol interpretation."
+ def __init__(self, host="127.0.0.1", port=GPSD_PORT, verbose=0):
+ self.sock = None # in case we blow up in connect
+ self.linebuffer = ""
+ self.verbose = verbose
+ if host != None:
+ self.connect(host, port)
+
+ def connect(self, host, port):
+ """Connect to a host on a given port.
+
+ If the hostname ends with a colon (`:') followed by a number, and
+ there is no port specified, that suffix will be stripped off and the
+ number interpreted as the port number to use.
+ """
+ if not port and (host.find(':') == host.rfind(':')):
+ i = host.rfind(':')
+ if i >= 0:
+ host, port = host[:i], host[i+1:]
+ try: port = int(port)
+ except ValueError:
+ raise socket.error, "nonnumeric port"
+ #if self.verbose > 0:
+ # print 'connect:', (host, port)
+ msg = "getaddrinfo returns an empty list"
+ self.sock = None
+ for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
+ af, socktype, proto, canonname, sa = res
+ try:
+ self.sock = socket.socket(af, socktype, proto)
+ #if self.debuglevel > 0: print 'connect:', (host, port)
+ self.sock.connect(sa)
+ except socket.error, msg:
+ #if self.debuglevel > 0: print 'connect fail:', (host, port)
+ self.close()
+ continue
+ break
+ if not self.sock:
+ raise socket.error, msg
+
+ def close(self):
+ if self.sock:
+ self.sock.close()
+ self.sock = None
+
+ def __del__(self):
+ self.close()
+
+ def waiting(self, timeout=0):
+ "Return True if data is ready for the client."
+ if self.linebuffer:
+ return True
+ (winput, woutput, wexceptions) = select.select((self.sock,), (), (), timeout)
+ return winput != []
+
+ def read(self):
+ "Wait for and read data being streamed from the daemon."
+ if self.verbose > 1:
+ sys.stderr.write("poll: reading from daemon...\n")
+ eol = self.linebuffer.find('\n')
+ if eol == -1:
+ frag = self.sock.recv(4096)
+ self.linebuffer += frag
+ if self.verbose > 1:
+ sys.stderr.write("poll: read complete.\n")
+ if not self.linebuffer:
+ if self.verbose > 1:
+ sys.stderr.write("poll: returning -1.\n")
+ # Read failed
+ return -1
+ eol = self.linebuffer.find('\n')
+ if eol == -1:
+ if self.verbose > 1:
+ sys.stderr.write("poll: returning 0.\n")
+ # Read succeeded, but only got a fragment
+ return 0
+ else:
+ if self.verbose > 1:
+ sys.stderr.write("poll: fetching from buffer.\n")
+
+ # We got a line
+ eol += 1
+ self.response = self.linebuffer[:eol]
+ self.linebuffer = self.linebuffer[eol:]
+
+ # Can happen if daemon terminates while we're reading.
+ if not self.response:
+ return -1
+ if self.verbose:
+ sys.stderr.write("poll: data is %s\n" % repr(self.response))
+ self.received = time.time()
+ # We got a \n-terminated line
+ return len(self.response)
+
+ def data(self):
+ "Return the client data buffer."
+ return self.response
+
+ def send(self, commands):
+ "Ship commands to the daemon."
+ if not commands.endswith("\n"):
+ commands += "\n"
+ self.sock.send(commands)
+
+WATCH_ENABLE = 0x000001 # enable streaming
+WATCH_DISABLE = 0x000002 # disable watching
+WATCH_JSON = 0x000010 # JSON output
+WATCH_NMEA = 0x000020 # output in NMEA
+WATCH_RARE = 0x000040 # output of packets in hex
+WATCH_RAW = 0x000080 # output of raw packets
+WATCH_SCALED = 0x000100 # scale output to floats
+WATCH_TIMING = 0x000200 # timing information
+WATCH_DEVICE = 0x000800 # watch specific device
+
+class gpsjson(gpscommon):
+ "Basic JSON decoding."
+ def __iter__(self):
+ return self
+
+ def unpack(self, buf):
+ try:
+ self.data = dictwrapper(json.loads(buf.strip(), encoding="ascii"))
+ except ValueError, e:
+ raise json_error(buf, e.args[0])
+ # Should be done for any other array-valued subobjects, too.
+ # This particular logic can fire on SKY or RTCM2 objects.
+ if hasattr(self.data, "satellites"):
+ self.data.satellites = map(dictwrapper, self.data.satellites)
+
+ def stream(self, flags=0, devpath=None):
+ "Control streaming reports from the daemon,"
+ if flags & WATCH_DISABLE:
+ arg = '?WATCH={"enable":false'
+ if flags & WATCH_JSON:
+ arg += ',"json":false'
+ if flags & WATCH_NMEA:
+ arg += ',"nmea":false'
+ if flags & WATCH_RARE:
+ arg += ',"raw":1'
+ if flags & WATCH_RAW:
+ arg += ',"raw":2'
+ if flags & WATCH_SCALED:
+ arg += ',"scaled":false'
+ if flags & WATCH_TIMING:
+ arg += ',"timing":false'
+ else: # flags & WATCH_ENABLE:
+ arg = '?WATCH={"enable":true'
+ if flags & WATCH_JSON:
+ arg += ',"json":true'
+ if flags & WATCH_NMEA:
+ arg += ',"nmea":true'
+ if flags & WATCH_RAW:
+ arg += ',"raw":1'
+ if flags & WATCH_RARE:
+ arg += ',"raw":0'
+ if flags & WATCH_SCALED:
+ arg += ',"scaled":true'
+ if flags & WATCH_TIMING:
+ arg += ',"timing":true'
+ if flags & WATCH_DEVICE:
+ arg += ',"device":"%s"' % devpath
+ return self.send(arg + "}")
+
+class dictwrapper:
+ "Wrapper that yields both class and dictionary behavior,"
+ def __init__(self, ddict):
+ self.__dict__ = ddict
+ def get(self, k, d=None):
+ return self.__dict__.get(k, d)
+ def keys(self):
+ return self.__dict__.keys()
+ def __getitem__(self, key):
+ "Emulate dictionary, for new-style interface."
+ return self.__dict__[key]
+ def __setitem__(self, key, val):
+ "Emulate dictionary, for new-style interface."
+ self.__dict__[key] = val
+ def __contains__(self, key):
+ return key in self.__dict__
+ def __str__(self):
+ return "<dictwrapper: " + str(self.__dict__) + ">"
+ __repr__ = __str__
+
+#
+# Someday a cleaner Python iterface using this machinery will live here
+#
+
+# End
diff --git a/big_data_demo/mod/lib/python/gps/client.pyc b/big_data_demo/mod/lib/python/gps/client.pyc
new file mode 100644
index 0000000..0671ed7
--- /dev/null
+++ b/big_data_demo/mod/lib/python/gps/client.pyc
Binary files differ
diff --git a/big_data_demo/mod/lib/python/gps/fake.py b/big_data_demo/mod/lib/python/gps/fake.py
new file mode 100644
index 0000000..1fe71d3
--- /dev/null
+++ b/big_data_demo/mod/lib/python/gps/fake.py
@@ -0,0 +1,594 @@
+# This file is Copyright (c) 2010 by the GPSD project
+# BSD terms apply: see the file COPYING in the distribution root for details.
+"""
+gpsfake.py -- classes for creating a controlled test environment around gpsd.
+
+The gpsfake(1) regression tester shipped with gpsd is a trivial wrapper
+around this code. For a more interesting usage example, see the
+valgrind-audit script shipped with the gpsd code.
+
+To use this code, start by instantiating a TestSession class. Use the
+prefix argument if you want to run the daemon under some kind of run-time
+monitor like valgrind or gdb. Here are some particularly useful possibilities:
+
+valgrind --tool=memcheck --gen-suppressions=yes --leak-check=yes
+ Run under Valgrind, checking for malloc errors and memory leaks.
+
+xterm -e gdb -tui --args
+ Run under gdb, controlled from a new xterm.
+
+You can use the options argument to pass in daemon options; normally you will
+use this to set the debug-logging level.
+
+On initialization, the test object spawns an instance of gpsd with no
+devices or clients attached, connected to a control socket.
+
+TestSession has methods to attach and detch fake GPSes. The
+TestSession class simulates GPS devices for you with objects composed
+from a pty and a class instance that cycles sentences into the master side
+from some specified logfile; gpsd reads the slave side. A fake GPS is
+identified by the string naming its slave device.
+
+TestSession also has methods to start and end client sessions. Daemon
+responses to a client are fed to a hook function which, by default,
+discards them. You can change the hook to sys.stdout.write() to dump
+responses to standard output (this is what the gpsfake executable
+does) or do something more exotic. A client session is identified by a
+small integer that counts the number of client session starts.
+
+There are a couple of convenience methods. TestSession.wait() does nothing,
+allowing a specified number of seconds to elapse. TestSession.send()
+ships commands to an open client session.
+
+TestSession does not currently capture the daemon's log output. It is
+run with -N, so the output will go to stderr (along with, for example,
+Valgrind notifications).
+
+Each FakeGPS instance tries to packetize the data from the logfile it
+is initialized with. It uses the same packet-getter as the daeomon.
+
+The TestSession code maintains a run queue of FakeGPS and gps.gs (client-
+session) objects. It repeatedly cycles through the run queue. For each
+client session object in the queue, it tries to read data from gpsd. For
+each fake GPS, it sends one line of stored data. When a fake-GPS's
+go predicate becomes false, the fake GPS is removed from the run queue.
+
+There are two ways to use this code. The more deterministic is
+non-threaded mode: set up your client sessions and fake GPS devices,
+then call the run() method. The run() method will terminate when
+there are no more objects in the run queue. Note, you must have
+created at least one fake client or fake GPS before calling run(),
+otherwise it will terminate immediately.
+
+To allow for adding and removing clients while the test is running,
+run in threaded mode by calling the start() method. This simply calls
+the run method in a subthread, with locking of critical regions.
+"""
+import os, time, signal, pty, termios # fcntl, array, struct
+import exceptions, threading, socket
+import gps
+import packet as sniffer
+
+# The two magic numbers below have to be derived from observation. If
+# they're too high you'll slow the tests down a lot. If they're too low
+# you'll get random spurious regression failures that usually look
+# like lines missing from the end of the test output relative to the
+# check file. These numbers might have to be adjusted upward on faster
+# machines. The need for them may be symptomatic of race conditions
+# in the pty layer or elsewhere.
+
+# Define a per-line delay on writes so we won't spam the buffers in
+# the pty layer or gpsd itself. Removing this entirely was tried but
+# caused failures under NetBSD. Values smaller than the system timer
+# tick don't make any difference here.
+WRITE_PAD = 0.001
+
+# We delay briefly after a GPS source is exhausted before removing it.
+# This should give its subscribers time to get gpsd's response before
+# we call the cleanup code. Note that using fractional seconds in
+# CLOSE_DELAY may have no effect; Python time.time() returns a float
+# value, but it is not guaranteed by Python that the C implementation
+# underneath will return with precision finer than 1 second. (Linux
+# and *BSD return full precision.) Dropping this to 0.1 has been
+# tried but caused failures.
+CLOSE_DELAY = 0.2
+
+class TestLoadError(exceptions.Exception):
+ def __init__(self, msg):
+ self.msg = msg
+
+class TestLoad:
+ "Digest a logfile into a list of sentences we can cycle through."
+ def __init__(self, logfp, predump=False):
+ self.sentences = [] # This is the interesting part
+ if type(logfp) == type(""):
+ logfp = open(logfp, "r")
+ self.name = logfp.name
+ self.logfp = logfp
+ self.predump = predump
+ self.logfile = logfp.name
+ self.type = None
+ self.sourcetype = "pty"
+ self.serial = None
+ # Grab the packets
+ getter = sniffer.new()
+ #gps.packet.register_report(reporter)
+ type_latch = None
+ while True:
+ (plen, ptype, packet, counter) = getter.get(logfp.fileno())
+ if plen <= 0:
+ break
+ elif ptype == sniffer.COMMENT_PACKET:
+ # Some comments are magic
+ if "Serial:" in packet:
+ # Change serial parameters
+ packet = packet[1:].strip()
+ try:
+ (xx, baud, params) = packet.split()
+ baud = int(baud)
+ if params[0] in ('7', '8'):
+ databits = int(params[0])
+ else:
+ raise ValueError
+ if params[1] in ('N', 'O', 'E'):
+ parity = params[1]
+ else:
+ raise ValueError
+ if params[2] in ('1', '2'):
+ stopbits = int(params[2])
+ else:
+ raise ValueError
+ except (ValueError, IndexError):
+ raise TestLoadError("bad serial-parameter spec in %s"%\
+ logfp.name)
+ self.serial = (baud, databits, parity, stopbits)
+ elif "UDP" in packet:
+ self.sourcetype = "UDP"
+ else:
+ if type_latch is None:
+ type_latch = ptype
+ if self.predump:
+ print repr(packet)
+ if not packet:
+ raise TestLoadError("zero-length packet from %s"%\
+ logfp.name)
+ self.sentences.append(packet)
+ # Look at the first packet to grok the GPS type
+ self.textual = (type_latch == sniffer.NMEA_PACKET)
+ if self.textual:
+ self.legend = "gpsfake: line %d: "
+ else:
+ self.legend = "gpsfake: packet %d"
+
+class PacketError(exceptions.Exception):
+ def __init__(self, msg):
+ self.msg = msg
+
+class FakeGPS:
+ def __init__(self, testload, progress=None):
+ self.testload = testload
+ self.progress = progress
+ self.go_predicate = lambda: True
+ self.readers = 0
+ self.index = 0
+ self.progress("gpsfake: %s provides %d sentences\n" % (self.testload.name, len(self.testload.sentences)))
+
+ def write(self, line):
+ "Throw an error if this superclass is ever instantiated."
+ raise ValueError, line
+
+ def feed(self):
+ "Feed a line from the contents of the GPS log to the daemon."
+ line = self.testload.sentences[self.index % len(self.testload.sentences)]
+ if "%Delay:" in line:
+ # Delay specified number of seconds
+ delay = line.split()[1]
+ time.sleep(int(delay))
+ # self.write has to be set by the derived class
+ self.write(line)
+ if self.progress:
+ self.progress("gpsfake: %s feeds %d=%s\n" % (self.testload.name, len(line), repr(line)))
+ time.sleep(WRITE_PAD)
+ self.index += 1
+
+class FakePTY(FakeGPS):
+ "A FakePTY is a pty with a test log ready to be cycled to it."
+ def __init__(self, testload,
+ speed=4800, databits=8, parity='N', stopbits=1,
+ progress=None):
+ FakeGPS.__init__(self, testload, progress)
+ # Allow Serial: header to be overridden by explicit spped.
+ if self.testload.serial:
+ (speed, databits, parity, stopbits) = self.testload.serial
+ self.speed = speed
+ baudrates = {
+ 0: termios.B0,
+ 50: termios.B50,
+ 75: termios.B75,
+ 110: termios.B110,
+ 134: termios.B134,
+ 150: termios.B150,
+ 200: termios.B200,
+ 300: termios.B300,
+ 600: termios.B600,
+ 1200: termios.B1200,
+ 1800: termios.B1800,
+ 2400: termios.B2400,
+ 4800: termios.B4800,
+ 9600: termios.B9600,
+ 19200: termios.B19200,
+ 38400: termios.B38400,
+ 57600: termios.B57600,
+ 115200: termios.B115200,
+ 230400: termios.B230400,
+ }
+ speed = baudrates[speed] # Throw an error if the speed isn't legal
+ (self.fd, self.slave_fd) = pty.openpty()
+ self.byname = os.ttyname(self.slave_fd)
+ (iflag, oflag, cflag, lflag, ispeed, ospeed, cc) = termios.tcgetattr(self.slave_fd)
+ cc[termios.VMIN] = 1
+ cflag &= ~(termios.PARENB | termios.PARODD | termios.CRTSCTS)
+ cflag |= termios.CREAD | termios.CLOCAL
+ iflag = oflag = lflag = 0
+ iflag &=~ (termios.PARMRK | termios.INPCK)
+ cflag &=~ (termios.CSIZE | termios.CSTOPB | termios.PARENB | termios.PARODD)
+ if databits == 7:
+ cflag |= termios.CS7
+ else:
+ cflag |= termios.CS8
+ if stopbits == 2:
+ cflag |= termios.CSTOPB
+ if parity == 'E':
+ iflag |= termios.INPCK
+ cflag |= termios.PARENB
+ elif parity == 'O':
+ iflag |= termios.INPCK
+ cflag |= termios.PARENB | termios.PARODD
+ ispeed = ospeed = speed
+ termios.tcsetattr(self.slave_fd, termios.TCSANOW,
+ [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
+ def read(self):
+ "Discard control strings written by gpsd."
+ # A tcflush implementation works on Linux but fails on OpenBSD 4.
+ termios.tcflush(self.fd, termios.TCIFLUSH)
+ # Alas, the FIONREAD version also works on Linux and fails on OpenBSD.
+ #try:
+ # buf = array.array('i', [0])
+ # fcntl.ioctl(self.master_fd, termios.FIONREAD, buf, True)
+ # n = struct.unpack('i', buf)[0]
+ # os.read(self.master_fd, n)
+ #except IOError:
+ # pass
+
+ def write(self, line):
+ os.write(self.fd, line)
+
+ def drain(self):
+ "Wait for the associated device to drain (e.g. before closing)."
+ termios.tcdrain(self.fd)
+
+class FakeUDP(FakeGPS):
+ "A UDP broadcaster with a test log ready to be cycled to it."
+ def __init__(self, testload,
+ ipaddr, port,
+ progress=None):
+ FakeGPS.__init__(self, testload, progress)
+ self.ipaddr = ipaddr
+ self.port = port
+ self.byname = "udp://" + ipaddr + ":" + port
+ self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+
+ def read(self):
+ "Discard control strings written by gpsd."
+ pass
+
+ def write(self, line):
+ self.sock.sendto(line, (self.ipaddr, int(self.port)))
+
+ def drain(self):
+ "Wait for the associated device to drain (e.g. before closing)."
+ pass # shutdown() fails on UDP
+
+class DaemonError(exceptions.Exception):
+ def __init__(self, msg):
+ self.msg = msg
+ def __str__(self):
+ return repr(self.msg)
+
+class DaemonInstance:
+ "Control a gpsd instance."
+ def __init__(self, control_socket=None):
+ self.sockfile = None
+ self.pid = None
+ self.tmpdir = os.environ.get('TMPDIR', '/tmp')
+ if control_socket:
+ self.control_socket = control_socket
+ else:
+ self.control_socket = "%s/gpsfake-%d.sock" % (self.tmpdir, os.getpid())
+ self.pidfile = "%s/gpsfake-%d.pid" % (self.tmpdir, os.getpid())
+ def spawn(self, options, port, background=False, prefix=""):
+ "Spawn a daemon instance."
+ self.spawncmd = None
+
+ # Look for gpsd in GPSD_HOME env variable
+ if os.environ.get('GPSD_HOME'):
+ for path in os.environ['GPSD_HOME'].split(':'):
+ _spawncmd = "%s/gpsd" % path
+ if os.path.isfile(_spawncmd) and os.access(_spawncmd, os.X_OK):
+ self.spawncmd = _spawncmd
+ break
+
+ # if we could not find it yet try PATH env variable for it
+ if not self.spawncmd:
+ if not '/usr/sbin' in os.environ['PATH']:
+ os.environ['PATH']=os.environ['PATH'] + ":/usr/sbin"
+ for path in os.environ['PATH'].split(':'):
+ _spawncmd = "%s/gpsd" % path
+ if os.path.isfile(_spawncmd) and os.access(_spawncmd, os.X_OK):
+ self.spawncmd = _spawncmd
+ break
+
+ if not self.spawncmd:
+ raise DaemonError("Cannot execute gpsd: executable not found. Set GPSD_HOME env variable")
+ # The -b option to suppress hanging on probe returns is needed to cope
+ # with OpenBSD (and possibly other non-Linux systems) that don't support
+ # anything we can use to implement the FakeGPS.read() method
+ self.spawncmd += " -b -N -S %s -F %s -P %s %s" % (port, self.control_socket, self.pidfile, options)
+ if prefix:
+ self.spawncmd = prefix + " " + self.spawncmd.strip()
+ if background:
+ self.spawncmd += " &"
+ status = os.system(self.spawncmd)
+ if os.WIFSIGNALED(status) or os.WEXITSTATUS(status):
+ raise DaemonError("daemon exited with status %d" % status)
+ def wait_pid(self):
+ "Wait for the daemon, get its PID and a control-socket connection."
+ while True:
+ try:
+ fp = open(self.pidfile)
+ except IOError:
+ time.sleep(0.1)
+ continue
+ try:
+ fp.seek(0)
+ pidstr = fp.read()
+ self.pid = int(pidstr)
+ except ValueError:
+ time.sleep(0.5)
+ continue # Avoid race condition -- PID not yet written
+ fp.close()
+ break
+ def __get_control_socket(self):
+ # Now we know it's running, get a connection to the control socket.
+ if not os.path.exists(self.control_socket):
+ return None
+ try:
+ self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0)
+ self.sock.connect(self.control_socket)
+ except socket.error:
+ if self.sock:
+ self.sock.close()
+ self.sock = None
+ return self.sock
+ def is_alive(self):
+ "Is the daemon still alive?"
+ try:
+ os.kill(self.pid, 0)
+ return True
+ except OSError:
+ return False
+ def add_device(self, path):
+ "Add a device to the daemon's internal search list."
+ if self.__get_control_socket():
+ self.sock.sendall("+%s\r\n\x00" % path)
+ self.sock.recv(12)
+ self.sock.close()
+ def remove_device(self, path):
+ "Remove a device from the daemon's internal search list."
+ if self.__get_control_socket():
+ self.sock.sendall("-%s\r\n\x00" % path)
+ self.sock.recv(12)
+ self.sock.close()
+ def kill(self):
+ "Kill the daemon instance."
+ if self.pid:
+ try:
+ os.kill(self.pid, signal.SIGTERM)
+ # Raises an OSError for ESRCH when we've killed it.
+ while True:
+ os.kill(self.pid, signal.SIGTERM)
+ time.sleep(0.01)
+ except OSError:
+ pass
+ self.pid = None
+
+class TestSessionError(exceptions.Exception):
+ def __init__(self, msg):
+ self.msg = msg
+
+class TestSession:
+ "Manage a session including a daemon with fake GPSes and clients."
+ def __init__(self, prefix=None, port=None, options=None, verbose=0, predump=False, udp=False):
+ "Initialize the test session by launching the daemon."
+ self.prefix = prefix
+ self.port = port
+ self.options = options
+ self.verbose = verbose
+ self.predump = predump
+ self.udp = udp
+ self.daemon = DaemonInstance()
+ self.fakegpslist = {}
+ self.client_id = 0
+ self.readers = 0
+ self.writers = 0
+ self.runqueue = []
+ self.index = 0
+ if port:
+ self.port = port
+ else:
+ self.port = gps.GPSD_PORT
+ self.progress = lambda x: None
+ self.reporter = lambda x: None
+ self.default_predicate = None
+ self.fd_set = []
+ self.threadlock = None
+ def spawn(self):
+ for sig in (signal.SIGQUIT, signal.SIGINT, signal.SIGTERM):
+ signal.signal(sig, lambda unused, dummy: self.cleanup())
+ self.daemon.spawn(background=True, prefix=self.prefix, port=self.port, options=self.options)
+ self.daemon.wait_pid()
+ def set_predicate(self, pred):
+ "Set a default go predicate for the session."
+ self.default_predicate = pred
+ def gps_add(self, logfile, speed=19200, pred=None):
+ "Add a simulated GPS being fed by the specified logfile."
+ self.progress("gpsfake: gps_add(%s, %d)\n" % (logfile, speed))
+ if logfile not in self.fakegpslist:
+ testload = TestLoad(logfile, predump=self.predump)
+ if testload.sourcetype == "UDP" or self.udp:
+ newgps = FakeUDP(testload, ipaddr="127.0.0.1", port="5000",
+ progress=self.progress)
+ else:
+ newgps = FakePTY(testload, speed=speed,
+ progress=self.progress)
+ if pred:
+ newgps.go_predicate = pred
+ elif self.default_predicate:
+ newgps.go_predicate = self.default_predicate
+ self.fakegpslist[newgps.byname] = newgps
+ self.append(newgps)
+ newgps.exhausted = 0
+ self.daemon.add_device(newgps.byname)
+ return newgps.byname
+ def gps_remove(self, name):
+ "Remove a simulated GPS from the daemon's search list."
+ self.progress("gpsfake: gps_remove(%s)\n" % name)
+ self.fakegpslist[name].drain()
+ self.remove(self.fakegpslist[name])
+ self.daemon.remove_device(name)
+ del self.fakegpslist[name]
+ def client_add(self, commands):
+ "Initiate a client session and force connection to a fake GPS."
+ self.progress("gpsfake: client_add()\n")
+ newclient = gps.gps(port=self.port, verbose=self.verbose)
+ self.append(newclient)
+ newclient.id = self.client_id + 1
+ self.client_id += 1
+ self.progress("gpsfake: client %d has %s\n" % (self.client_id,newclient.device))
+ if commands:
+ self.initialize(newclient, commands)
+ return self.client_id
+ def client_remove(self, cid):
+ "Terminate a client session."
+ self.progress("gpsfake: client_remove(%d)\n" % cid)
+ for obj in self.runqueue:
+ if isinstance(obj, gps.gps) and obj.id == cid:
+ self.remove(obj)
+ return True
+ else:
+ return False
+ def wait(self, seconds):
+ "Wait, doing nothing."
+ self.progress("gpsfake: wait(%d)\n" % seconds)
+ time.sleep(seconds)
+ def gather(self, seconds):
+ "Wait, doing nothing but watching for sentences."
+ self.progress("gpsfake: gather(%d)\n" % seconds)
+ #mark = time.time()
+ time.sleep(seconds)
+ def cleanup(self):
+ "We're done, kill the daemon."
+ self.progress("gpsfake: cleanup()\n")
+ if self.daemon:
+ self.daemon.kill()
+ self.daemon = None
+ def run(self):
+ "Run the tests."
+ try:
+ self.progress("gpsfake: test loop begins\n")
+ while self.daemon:
+ # We have to read anything that gpsd might have tried
+ # to send to the GPS here -- under OpenBSD the
+ # TIOCDRAIN will hang, otherwise.
+ for device in self.runqueue:
+ if isinstance(device, FakeGPS):
+ device.read()
+ had_output = False
+ chosen = self.choose()
+ if isinstance(chosen, FakeGPS):
+ if chosen.exhausted and (time.time() - chosen.exhausted > CLOSE_DELAY):
+ self.gps_remove(chosen.byname)
+ self.progress("gpsfake: GPS %s removed\n" % chosen.byname)
+ elif not chosen.go_predicate(chosen.index, chosen):
+ if chosen.exhausted == 0:
+ chosen.exhausted = time.time()
+ self.progress("gpsfake: GPS %s ran out of input\n" % chosen.byname)
+ else:
+ chosen.feed()
+ elif isinstance(chosen, gps.gps):
+ if chosen.enqueued:
+ chosen.send(chosen.enqueued)
+ chosen.enqueued = ""
+ while chosen.waiting():
+ chosen.read()
+ if chosen.valid & gps.PACKET_SET:
+ self.reporter(chosen.response)
+ had_output = True
+ else:
+ raise TestSessionError("test object of unknown type")
+ if not self.writers and not had_output:
+ self.progress("gpsfake: no writers and no output\n")
+ break
+ self.progress("gpsfake: test loop ends\n")
+ finally:
+ self.cleanup()
+
+ # All knowledge about locks and threading is below this line,
+ # except for the bare fact that self.threadlock is set to None
+ # in the class init method.
+
+ def append(self, obj):
+ "Add a producer or consumer to the object list."
+ if self.threadlock:
+ self.threadlock.acquire()
+ self.runqueue.append(obj)
+ if isinstance(obj, FakeGPS):
+ self.writers += 1
+ elif isinstance(obj, gps.gps):
+ self.readers += 1
+ if self.threadlock:
+ self.threadlock.release()
+ def remove(self, obj):
+ "Remove a producer or consumer from the object list."
+ if self.threadlock:
+ self.threadlock.acquire()
+ self.runqueue.remove(obj)
+ if isinstance(obj, FakeGPS):
+ self.writers -= 1
+ elif isinstance(obj, gps.gps):
+ self.readers -= 1
+ self.index = min(len(self.runqueue)-1, self.index)
+ if self.threadlock:
+ self.threadlock.release()
+ def choose(self):
+ "Atomically get the next object scheduled to do something."
+ if self.threadlock:
+ self.threadlock.acquire()
+ chosen = self.index
+ self.index += 1
+ self.index %= len(self.runqueue)
+ if self.threadlock:
+ self.threadlock.release()
+ return self.runqueue[chosen]
+ def initialize(self, client, commands):
+ "Arrange for client to ship specified commands when it goes active."
+ client.enqueued = ""
+ if not self.threadlock:
+ client.send(commands)
+ else:
+ client.enqueued = commands
+ def start(self):
+ self.threadlock = threading.Lock()
+ threading.Thread(target=self.run)
+
+# End
diff --git a/big_data_demo/mod/lib/python/gps/gps.py b/big_data_demo/mod/lib/python/gps/gps.py
new file mode 100755
index 0000000..73199a4
--- /dev/null
+++ b/big_data_demo/mod/lib/python/gps/gps.py
@@ -0,0 +1,366 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+# This file is Copyright (c) 2010 by the GPSD project
+# BSD terms apply: see the file COPYING in the distribution root for details.
+#
+# gps.py -- Python interface to GPSD.
+#
+# This interface has a lot of historical cruft in it related to old
+# protocol, and was modeled on the C interface. It won't be thrown
+# away, but it's likely to be deprecated in favor of something more
+# Pythonic.
+#
+# The JSON parts of this (which will be reused by any new interface)
+# now live in a different module.
+#
+from client import *
+from misc import isotime
+
+NaN = float('nan')
+def isnan(x): return str(x) == 'nan'
+
+# Don't hand-hack this list, it's generated.
+ONLINE_SET = (1<<1)
+TIME_SET = (1<<2)
+TIMERR_SET = (1<<3)
+LATLON_SET = (1<<4)
+ALTITUDE_SET = (1<<5)
+SPEED_SET = (1<<6)
+TRACK_SET = (1<<7)
+CLIMB_SET = (1<<8)
+STATUS_SET = (1<<9)
+MODE_SET = (1<<10)
+DOP_SET = (1<<11)
+HERR_SET = (1<<12)
+VERR_SET = (1<<13)
+ATTITUDE_SET = (1<<14)
+SATELLITE_SET = (1<<15)
+SPEEDERR_SET = (1<<16)
+TRACKERR_SET = (1<<17)
+CLIMBERR_SET = (1<<18)
+DEVICE_SET = (1<<19)
+DEVICELIST_SET = (1<<20)
+DEVICEID_SET = (1<<21)
+RTCM2_SET = (1<<22)
+RTCM3_SET = (1<<23)
+AIS_SET = (1<<24)
+PACKET_SET = (1<<25)
+SUBFRAME_SET = (1<<26)
+GST_SET = (1<<27)
+VERSION_SET = (1<<28)
+POLICY_SET = (1<<29)
+ERROR_SET = (1<<30)
+UNION_SET = (RTCM2_SET|RTCM3_SET|SUBFRAME_SET|AIS_SET|VERSION_SET|DEVICELIST_SET|ERROR_SET|GST_SET)
+STATUS_NO_FIX = 0
+STATUS_FIX = 1
+STATUS_DGPS_FIX = 2
+MODE_NO_FIX = 1
+MODE_2D = 2
+MODE_3D = 3
+MAXCHANNELS = 20
+SIGNAL_STRENGTH_UNKNOWN = NaN
+
+WATCH_NEWSTYLE = 0x010000 # force JSON streaming
+WATCH_OLDSTYLE = 0x020000 # force old-style streaming
+
+class gpsfix:
+ def __init__(self):
+ self.mode = MODE_NO_FIX
+ self.time = NaN
+ self.ept = NaN
+ self.latitude = self.longitude = 0.0
+ self.epx = NaN
+ self.epy = NaN
+ self.altitude = NaN # Meters
+ self.epv = NaN
+ self.track = NaN # Degrees from true north
+ self.speed = NaN # Knots
+ self.climb = NaN # Meters per second
+ self.epd = NaN
+ self.eps = NaN
+ self.epc = NaN
+
+class gpsdata:
+ "Position, track, velocity and status information returned by a GPS."
+
+ class satellite:
+ def __init__(self, PRN, elevation, azimuth, ss, used=None):
+ self.PRN = PRN
+ self.elevation = elevation
+ self.azimuth = azimuth
+ self.ss = ss
+ self.used = used
+ def __repr__(self):
+ return "PRN: %3d E: %3d Az: %3d Ss: %3d Used: %s" % (
+ self.PRN, self.elevation, self.azimuth, self.ss, "ny"[self.used]
+ )
+
+ def __init__(self):
+ # Initialize all data members
+ self.online = 0 # NZ if GPS on, zero if not
+
+ self.valid = 0
+ self.fix = gpsfix()
+
+ self.status = STATUS_NO_FIX
+ self.utc = ""
+
+ self.satellites_used = 0 # Satellites used in last fix
+ self.xdop = self.ydop = self.vdop = self.tdop = 0
+ self.pdop = self.hdop = self.gdop = 0.0
+
+ self.epe = 0.0
+
+ self.satellites = [] # satellite objects in view
+
+ self.gps_id = None
+ self.driver_mode = 0
+ self.baudrate = 0
+ self.stopbits = 0
+ self.cycle = 0
+ self.mincycle = 0
+ self.device = None
+ self.devices = []
+
+ self.version = None
+
+ def __repr__(self):
+ st = "Time: %s (%s)\n" % (self.utc, self.fix.time)
+ st += "Lat/Lon: %f %f\n" % (self.fix.latitude, self.fix.longitude)
+ if isnan(self.fix.altitude):
+ st += "Altitude: ?\n"
+ else:
+ st += "Altitude: %f\n" % (self.fix.altitude)
+ if isnan(self.fix.speed):
+ st += "Speed: ?\n"
+ else:
+ st += "Speed: %f\n" % (self.fix.speed)
+ if isnan(self.fix.track):
+ st += "Track: ?\n"
+ else:
+ st += "Track: %f\n" % (self.fix.track)
+ st += "Status: STATUS_%s\n" % ("NO_FIX", "FIX", "DGPS_FIX")[self.status]
+ st += "Mode: MODE_%s\n" % ("ZERO", "NO_FIX", "2D", "3D")[self.fix.mode]
+ st += "Quality: %d p=%2.2f h=%2.2f v=%2.2f t=%2.2f g=%2.2f\n" % \
+ (self.satellites_used, self.pdop, self.hdop, self.vdop, self.tdop, self.gdop)
+ st += "Y: %s satellites in view:\n" % len(self.satellites)
+ for sat in self.satellites:
+ st += " %r\n" % sat
+ return st
+
+class gps(gpsdata, gpsjson):
+ "Client interface to a running gpsd instance."
+ def __init__(self, host="127.0.0.1", port=GPSD_PORT, verbose=0, mode=0):
+ gpscommon.__init__(self, host, port, verbose)
+ gpsdata.__init__(self)
+ self.newstyle = False
+ if mode:
+ self.stream(mode)
+
+ def __oldstyle_unpack(self, buf):
+ # unpack a daemon response into the gps instance members
+ self.fix.time = 0.0
+ fields = buf.strip().split(",")
+ if fields[0] == "GPSD":
+ for field in fields[1:]:
+ if not field or field[1] != '=':
+ continue
+ cmd = field[0].upper()
+ data = field[2:]
+ if data[0] == "?":
+ continue
+ if cmd == 'F':
+ self.device = data
+ elif cmd == 'I':
+ self.gps_id = data
+ elif cmd == 'O':
+ fields = data.split()
+ if fields[0] == '?':
+ self.fix.mode = MODE_NO_FIX
+ else:
+ def default(i, vbit=0, cnv=float):
+ if fields[i] == '?':
+ return NaN
+ else:
+ try:
+ value = cnv(fields[i])
+ except ValueError:
+ return NaN
+ self.valid |= vbit
+ return value
+ # clear all valid bits that might be set again below
+ self.valid &= ~(
+ TIME_SET | TIMERR_SET | LATLON_SET | ALTITUDE_SET |
+ HERR_SET | VERR_SET | TRACK_SET | SPEED_SET |
+ CLIMB_SET | SPEEDERR_SET | CLIMBERR_SET | MODE_SET
+ )
+ self.utc = fields[1]
+ self.fix.time = default(1, TIME_SET)
+ if not isnan(self.fix.time):
+ self.utc = isotime(self.fix.time)
+ self.fix.ept = default(2, TIMERR_SET)
+ self.fix.latitude = default(3, LATLON_SET)
+ self.fix.longitude = default(4)
+ self.fix.altitude = default(5, ALTITUDE_SET)
+ self.fix.epx = self.epy = default(6, HERR_SET)
+ self.fix.epv = default(7, VERR_SET)
+ self.fix.track = default(8, TRACK_SET)
+ self.fix.speed = default(9, SPEED_SET)
+ self.fix.climb = default(10, CLIMB_SET)
+ self.fix.epd = default(11)
+ self.fix.eps = default(12, SPEEDERR_SET)
+ self.fix.epc = default(13, CLIMBERR_SET)
+ if len(fields) > 14:
+ self.fix.mode = default(14, MODE_SET, int)
+ else:
+ if self.valid & ALTITUDE_SET:
+ self.fix.mode = MODE_2D
+ else:
+ self.fix.mode = MODE_3D
+ self.valid |= MODE_SET
+ elif cmd == 'X':
+ self.online = float(data)
+ self.valid |= ONLINE_SET
+ elif cmd == 'Y':
+ satellites = data.split(":")
+ prefix = satellites.pop(0).split()
+ d1 = int(prefix.pop())
+ newsats = []
+ for i in range(d1):
+ newsats.append(gps.satellite(*map(int, satellites[i].split())))
+ self.satellites = newsats
+ self.valid |= SATELLITE_SET
+
+ def __oldstyle_shim(self):
+ # The rest is backwards compatibility for the old interface
+ def default(k, dflt, vbit=0):
+ if k not in self.data.keys():
+ return dflt
+ else:
+ self.valid |= vbit
+ return self.data[k]
+ if self.data.get("class") == "VERSION":
+ self.version = self.data
+ elif self.data.get("class") == "DEVICE":
+ self.valid = ONLINE_SET | DEVICE_SET
+ self.path = self.data["path"]
+ self.activated = default("activated", None)
+ driver = default("driver", None, DEVICEID_SET)
+ subtype = default("subtype", None, DEVICEID_SET)
+ self.gps_id = driver
+ if subtype:
+ self.gps_id += " " + subtype
+ self.driver_mode = default("native", 0)
+ self.baudrate = default("bps", 0)
+ self.serialmode = default("serialmode", "8N1")
+ self.cycle = default("cycle", NaN)
+ self.mincycle = default("mincycle", NaN)
+ elif self.data.get("class") == "TPV":
+ self.valid = ONLINE_SET
+ self.utc = default("time", None, TIME_SET)
+ if self.utc is not None:
+ # Time can be either Unix time as a float or an ISO8601 string
+ if type(self.fix.time) == type(0.0):
+ self.fix.time = self.utc
+ else:
+ self.fix.time = isotime(self.utc.encode("ascii"))
+ self.fix.ept = default("ept", NaN, TIMERR_SET)
+ self.fix.latitude = default("lat", NaN, LATLON_SET)
+ self.fix.longitude = default("lon", NaN)
+ self.fix.altitude = default("alt", NaN, ALTITUDE_SET)
+ self.fix.epx = default("epx", NaN, HERR_SET)
+ self.fix.epy = default("epy", NaN, HERR_SET)
+ self.fix.epv = default("epv", NaN, VERR_SET)
+ self.fix.track = default("track", NaN, TRACK_SET)
+ self.fix.speed = default("speed", NaN, SPEED_SET)
+ self.fix.climb = default("climb", NaN, CLIMB_SET)
+ self.fix.epd = default("epd", NaN)
+ self.fix.eps = default("eps", NaN, SPEEDERR_SET)
+ self.fix.epc = default("epc", NaN, CLIMBERR_SET)
+ self.fix.mode = default("mode", 0, MODE_SET)
+ elif self.data.get("class") == "SKY":
+ for attrp in ("x", "y", "v", "h", "p", "g"):
+ setattr(self, attrp+"dop", default(attrp+"dop", NaN, DOP_SET))
+ if "satellites" in self.data.keys():
+ self.satellites = []
+ for sat in self.data['satellites']:
+ self.satellites.append(gps.satellite(PRN=sat['PRN'], elevation=sat['el'], azimuth=sat['az'], ss=sat['ss'], used=sat['used']))
+ self.satellites_used = 0
+ for sat in self.satellites:
+ if sat.used:
+ self.satellites_used += 1
+ self.valid = ONLINE_SET | SATELLITE_SET
+
+ def read(self):
+ "Read and interpret data from the daemon."
+ status = gpscommon.read(self)
+ if status <= 0:
+ return status
+ if self.response.startswith("{") and self.response.endswith("}\r\n"):
+ self.unpack(self.response)
+ self.__oldstyle_shim()
+ self.newstyle = True
+ self.valid |= PACKET_SET
+ elif self.response.startswith("GPSD"):
+ self.__oldstyle_unpack(self.response)
+ self.valid |= PACKET_SET
+ return 0
+
+ def next(self):
+ if self.read() == -1:
+ raise StopIteration
+ if hasattr(self, "data"):
+ return self.data
+ else:
+ return self.response
+
+ def stream(self, flags=0, devpath=None):
+ "Ask gpsd to stream reports at your client."
+ if (flags & (WATCH_JSON|WATCH_OLDSTYLE|WATCH_NMEA|WATCH_RAW)) == 0:
+ flags |= WATCH_JSON
+ if flags & WATCH_DISABLE:
+ if flags & WATCH_OLDSTYLE:
+ arg = "w-"
+ if flags & WATCH_NMEA:
+ arg += 'r-'
+ return self.send(arg)
+ else:
+ gpsjson.stream(self, ~flags, devpath)
+ else: # flags & WATCH_ENABLE:
+ if flags & WATCH_OLDSTYLE:
+ arg = 'w+'
+ if (flags & WATCH_NMEA):
+ arg += 'r+'
+ return self.send(arg)
+ else:
+ gpsjson.stream(self, flags, devpath)
+
+if __name__ == '__main__':
+ import getopt, sys
+ (options, arguments) = getopt.getopt(sys.argv[1:], "v")
+ streaming = False
+ verbose = False
+ for (switch, val) in options:
+ if switch == '-v':
+ verbose = True
+ if len(arguments) > 2:
+ print 'Usage: gps.py [-v] [host [port]]'
+ sys.exit(1)
+
+ opts = { "verbose" : verbose }
+ if len(arguments) > 0:
+ opts["host"] = arguments[0]
+ if len(arguments) > 1:
+ opts["port"] = arguments[1]
+
+ session = gps(**opts)
+ session.stream(WATCH_ENABLE)
+ try:
+ for report in session:
+ print report
+ except KeyboardInterrupt:
+ # Avoid garble on ^C
+ print ""
+
+# gps.py ends here
diff --git a/big_data_demo/mod/lib/python/gps/gps.pyc b/big_data_demo/mod/lib/python/gps/gps.pyc
new file mode 100644
index 0000000..f47aef9
--- /dev/null
+++ b/big_data_demo/mod/lib/python/gps/gps.pyc
Binary files differ
diff --git a/big_data_demo/mod/lib/python/gps/misc.py b/big_data_demo/mod/lib/python/gps/misc.py
new file mode 100644
index 0000000..42ef840
--- /dev/null
+++ b/big_data_demo/mod/lib/python/gps/misc.py
@@ -0,0 +1,102 @@
+# misc.py - miscellaneous geodesy and time functions
+#
+# This file is Copyright (c) 2010 by the GPSD project
+# BSD terms apply: see the file COPYING in the distribution root for details.
+
+import time, calendar, math
+
+# some multipliers for interpreting GPS output
+METERS_TO_FEET = 3.2808399 # Meters to U.S./British feet
+METERS_TO_MILES = 0.00062137119 # Meters to miles
+METERS_TO_FATHOMS = 0.54680665 # Meters to fathoms
+KNOTS_TO_MPH = 1.1507794 # Knots to miles per hour
+KNOTS_TO_KPH = 1.852 # Knots to kilometers per hour
+KNOTS_TO_MPS = 0.51444444 # Knots to meters per second
+MPS_TO_KPH = 3.6 # Meters per second to klicks/hr
+MPS_TO_MPH = 2.2369363 # Meters/second to miles per hour
+MPS_TO_KNOTS = 1.9438445 # Meters per second to knots
+
+# EarthDistance code swiped from Kismet and corrected
+
+def Deg2Rad(x):
+ "Degrees to radians."
+ return x * (math.pi/180)
+
+def Rad2Deg(x):
+ "Radians to degress."
+ return x * (180/math.pi)
+
+def CalcRad(lat):
+ "Radius of curvature in meters at specified latitude."
+ a = 6378.137
+ e2 = 0.081082 * 0.081082
+ # the radius of curvature of an ellipsoidal Earth in the plane of a
+ # meridian of latitude is given by
+ #
+ # R' = a * (1 - e^2) / (1 - e^2 * (sin(lat))^2)^(3/2)
+ #
+ # where a is the equatorial radius,
+ # b is the polar radius, and
+ # e is the eccentricity of the ellipsoid = sqrt(1 - b^2/a^2)
+ #
+ # a = 6378 km (3963 mi) Equatorial radius (surface to center distance)
+ # b = 6356.752 km (3950 mi) Polar radius (surface to center distance)
+ # e = 0.081082 Eccentricity
+ sc = math.sin(Deg2Rad(lat))
+ x = a * (1.0 - e2)
+ z = 1.0 - e2 * sc * sc
+ y = pow(z, 1.5)
+ r = x / y
+
+ r = r * 1000.0 # Convert to meters
+ return r
+
+def EarthDistance((lat1, lon1), (lat2, lon2)):
+ "Distance in meters between two points specified in degrees."
+ x1 = CalcRad(lat1) * math.cos(Deg2Rad(lon1)) * math.sin(Deg2Rad(90-lat1))
+ x2 = CalcRad(lat2) * math.cos(Deg2Rad(lon2)) * math.sin(Deg2Rad(90-lat2))
+ y1 = CalcRad(lat1) * math.sin(Deg2Rad(lon1)) * math.sin(Deg2Rad(90-lat1))
+ y2 = CalcRad(lat2) * math.sin(Deg2Rad(lon2)) * math.sin(Deg2Rad(90-lat2))
+ z1 = CalcRad(lat1) * math.cos(Deg2Rad(90-lat1))
+ z2 = CalcRad(lat2) * math.cos(Deg2Rad(90-lat2))
+ a = (x1*x2 + y1*y2 + z1*z2)/pow(CalcRad((lat1+lat2)/2), 2)
+ # a should be in [1, -1] but can sometimes fall outside it by
+ # a very small amount due to rounding errors in the preceding
+ # calculations (this is prone to happen when the argument points
+ # are very close together). Thus we constrain it here.
+ if abs(a) > 1: a = 1
+ elif a < -1: a = -1
+ return CalcRad((lat1+lat2) / 2) * math.acos(a)
+
+def MeterOffset((lat1, lon1), (lat2, lon2)):
+ "Return offset in meters of second arg from first."
+ dx = EarthDistance((lat1, lon1), (lat1, lon2))
+ dy = EarthDistance((lat1, lon1), (lat2, lon1))
+ if lat1 < lat2: dy *= -1
+ if lon1 < lon2: dx *= -1
+ return (dx, dy)
+
+def isotime(s):
+ "Convert timestamps in ISO8661 format to and from Unix time."
+ if type(s) == type(1):
+ return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(s))
+ elif type(s) == type(1.0):
+ date = int(s)
+ msec = s - date
+ date = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(s))
+ return date + "." + repr(msec)[3:]
+ elif type(s) == type("") or type(s) == type(u""):
+ if s[-1] == "Z":
+ s = s[:-1]
+ if "." in s:
+ (date, msec) = s.split(".")
+ else:
+ date = s
+ msec = "0"
+ # Note: no leap-second correction!
+ return calendar.timegm(time.strptime(date, "%Y-%m-%dT%H:%M:%S")) + float("0." + msec)
+ else:
+ raise TypeError
+
+# End
+
diff --git a/big_data_demo/mod/lib/python/gps/misc.pyc b/big_data_demo/mod/lib/python/gps/misc.pyc
new file mode 100644
index 0000000..708a385
--- /dev/null
+++ b/big_data_demo/mod/lib/python/gps/misc.pyc
Binary files differ
diff --git a/big_data_demo/mod/lib/python/jsonrpclib-0.1.3-py2.7.egg-info b/big_data_demo/mod/lib/python/jsonrpclib-0.1.3-py2.7.egg-info
new file mode 100644
index 0000000..edbd221
--- /dev/null
+++ b/big_data_demo/mod/lib/python/jsonrpclib-0.1.3-py2.7.egg-info
@@ -0,0 +1,229 @@
+Metadata-Version: 1.0
+Name: jsonrpclib
+Version: 0.1.3
+Summary: This project is an implementation of the JSON-RPC v2.0 specification (backwards-compatible) as a client library.
+Home-page: http://github.com/joshmarshall/jsonrpclib/
+Author: Josh Marshall
+Author-email: catchjosh@gmail.com
+License: http://www.apache.org/licenses/LICENSE-2.0
+Description: JSONRPClib
+ ==========
+ This library is an implementation of the JSON-RPC specification.
+ It supports both the original 1.0 specification, as well as the
+ new (proposed) 2.0 spec, which includes batch submission, keyword
+ arguments, etc.
+
+ It is licensed under the Apache License, Version 2.0
+ (http://www.apache.org/licenses/LICENSE-2.0.html).
+
+ Communication
+ -------------
+ Feel free to send any questions, comments, or patches to our Google Group
+ mailing list (you'll need to join to send a message):
+ http://groups.google.com/group/jsonrpclib
+
+ Summary
+ -------
+ This library implements the JSON-RPC 2.0 proposed specification in pure Python.
+ It is designed to be as compatible with the syntax of xmlrpclib as possible
+ (it extends where possible), so that projects using xmlrpclib could easily be
+ modified to use JSON and experiment with the differences.
+
+ It is backwards-compatible with the 1.0 specification, and supports all of the
+ new proposed features of 2.0, including:
+
+ * Batch submission (via MultiCall)
+ * Keyword arguments
+ * Notifications (both in a batch and 'normal')
+ * Class translation using the 'jsonclass' key.
+
+ I've added a "SimpleJSONRPCServer", which is intended to emulate the
+ "SimpleXMLRPCServer" from the default Python distribution.
+
+ Requirements
+ ------------
+ It supports cjson and simplejson, and looks for the parsers in that order
+ (searching first for cjson, then for the "built-in" simplejson as json in 2.6+,
+ and then the simplejson external library). One of these must be installed to
+ use this library, although if you have a standard distribution of 2.6+, you
+ should already have one. Keep in mind that cjson is supposed to be the
+ quickest, I believe, so if you are going for full-on optimization you may
+ want to pick it up.
+
+ Installation
+ ------------
+ You can install this from PyPI with one of the following commands (sudo
+ may be required):
+
+ easy_install jsonrpclib
+ pip install jsonrpclib
+
+ Alternatively, you can download the source from the github repository
+ at http://github.com/joshmarshall/jsonrpclib and manually install it
+ with the following commands:
+
+ git clone git://github.com/joshmarshall/jsonrpclib.git
+ cd jsonrpclib
+ python setup.py install
+
+ Client Usage
+ ------------
+
+ This is (obviously) taken from a console session.
+
+ >>> import jsonrpclib
+ >>> server = jsonrpclib.Server('http://localhost:8080')
+ >>> server.add(5,6)
+ 11
+ >>> print jsonrpclib.history.request
+ {"jsonrpc": "2.0", "params": [5, 6], "id": "gb3c9g37", "method": "add"}
+ >>> print jsonrpclib.history.response
+ {'jsonrpc': '2.0', 'result': 11, 'id': 'gb3c9g37'}
+ >>> server.add(x=5, y=10)
+ 15
+ >>> server._notify.add(5,6)
+ # No result returned...
+ >>> batch = jsonrpclib.MultiCall(server)
+ >>> batch.add(5, 6)
+ >>> batch.ping({'key':'value'})
+ >>> batch._notify.add(4, 30)
+ >>> results = batch()
+ >>> for result in results:
+ >>> ... print result
+ 11
+ {'key': 'value'}
+ # Note that there are only two responses -- this is according to spec.
+
+ If you need 1.0 functionality, there are a bunch of places you can pass that
+ in, although the best is just to change the value on
+ jsonrpclib.config.version:
+
+ >>> import jsonrpclib
+ >>> jsonrpclib.config.version
+ 2.0
+ >>> jsonrpclib.config.version = 1.0
+ >>> server = jsonrpclib.Server('http://localhost:8080')
+ >>> server.add(7, 10)
+ 17
+ >>> print jsonrpclib..history.request
+ {"params": [7, 10], "id": "thes7tl2", "method": "add"}
+ >>> print jsonrpclib.history.response
+ {'id': 'thes7tl2', 'result': 17, 'error': None}
+ >>>
+
+ The equivalent loads and dumps functions also exist, although with minor
+ modifications. The dumps arguments are almost identical, but it adds three
+ arguments: rpcid for the 'id' key, version to specify the JSON-RPC
+ compatibility, and notify if it's a request that you want to be a
+ notification.
+
+ Additionally, the loads method does not return the params and method like
+ xmlrpclib, but instead a.) parses for errors, raising ProtocolErrors, and
+ b.) returns the entire structure of the request / response for manual parsing.
+
+ SimpleJSONRPCServer
+ -------------------
+ This is identical in usage (or should be) to the SimpleXMLRPCServer in the default Python install. Some of the differences in features are that it obviously supports notification, batch calls, class translation (if left on), etc. Note: The import line is slightly different from the regular SimpleXMLRPCServer, since the SimpleJSONRPCServer is distributed within the jsonrpclib library.
+
+ from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
+
+ server = SimpleJSONRPCServer(('localhost', 8080))
+ server.register_function(pow)
+ server.register_function(lambda x,y: x+y, 'add')
+ server.register_function(lambda x: x, 'ping')
+ server.serve_forever()
+
+ Class Translation
+ -----------------
+ I've recently added "automatic" class translation support, although it is
+ turned off by default. This can be devastatingly slow if improperly used, so
+ the following is just a short list of things to keep in mind when using it.
+
+ * Keep It (the object) Simple Stupid. (for exceptions, keep reading.)
+ * Do not require init params (for exceptions, keep reading)
+ * Getter properties without setters could be dangerous (read: not tested)
+
+ If any of the above are issues, use the _serialize method. (see usage below)
+ The server and client must BOTH have use_jsonclass configuration item on and
+ they must both have access to the same libraries used by the objects for
+ this to work.
+
+ If you have excessively nested arguments, it would be better to turn off the
+ translation and manually invoke it on specific objects using
+ jsonrpclib.jsonclass.dump / jsonrpclib.jsonclass.load (since the default
+ behavior recursively goes through attributes and lists / dicts / tuples).
+
+ [test_obj.py]
+
+ # This object is /very/ simple, and the system will look through the
+ # attributes and serialize what it can.
+ class TestObj(object):
+ foo = 'bar'
+
+ # This object requires __init__ params, so it uses the _serialize method
+ # and returns a tuple of init params and attribute values (the init params
+ # can be a dict or a list, but the attribute values must be a dict.)
+ class TestSerial(object):
+ foo = 'bar'
+ def __init__(self, *args):
+ self.args = args
+ def _serialize(self):
+ return (self.args, {'foo':self.foo,})
+
+ [usage]
+
+ import jsonrpclib
+ import test_obj
+
+ jsonrpclib.config.use_jsonclass = True
+
+ testobj1 = test_obj.TestObj()
+ testobj2 = test_obj.TestSerial()
+ server = jsonrpclib.Server('http://localhost:8080')
+ # The 'ping' just returns whatever is sent
+ ping1 = server.ping(testobj1)
+ ping2 = server.ping(testobj2)
+ print jsonrpclib.history.request
+ # {"jsonrpc": "2.0", "params": [{"__jsonclass__": ["test_obj.TestSerial", ["foo"]]}], "id": "a0l976iv", "method": "ping"}
+ print jsonrpclib.history.result
+ # {'jsonrpc': '2.0', 'result': <test_obj.TestSerial object at 0x2744590>, 'id': 'a0l976iv'}
+
+ To turn on this behaviour, just set jsonrpclib.config.use_jsonclass to True.
+ If you want to use a different method for serialization, just set
+ jsonrpclib.config.serialize_method to the method name. Finally, if you are
+ using classes that you have defined in the implementation (as in, not a
+ separate library), you'll need to add those (on BOTH the server and the
+ client) using the jsonrpclib.config.classes.add() method.
+ (Examples forthcoming.)
+
+ Feedback on this "feature" is very, VERY much appreciated.
+
+ Why JSON-RPC?
+ -------------
+ In my opinion, there are several reasons to choose JSON over XML for RPC:
+
+ * Much simpler to read (I suppose this is opinion, but I know I'm right. :)
+ * Size / Bandwidth - Main reason, a JSON object representation is just much smaller.
+ * Parsing - JSON should be much quicker to parse than XML.
+ * Easy class passing with jsonclass (when enabled)
+
+ In the interest of being fair, there are also a few reasons to choose XML
+ over JSON:
+
+ * Your server doesn't do JSON (rather obvious)
+ * Wider XML-RPC support across APIs (can we change this? :))
+ * Libraries are more established, i.e. more stable (Let's change this too.)
+
+ TESTS
+ -----
+ I've dropped almost-verbatim tests from the JSON-RPC spec 2.0 page.
+ You can run it with:
+
+ python tests.py
+
+ TODO
+ ----
+ * Use HTTP error codes on SimpleJSONRPCServer
+ * Test, test, test and optimize
+
+Platform: UNKNOWN
diff --git a/big_data_demo/jsonrpclib/jsonrpclib/SimpleJSONRPCServer.py b/big_data_demo/mod/lib/python/jsonrpclib/SimpleJSONRPCServer.py
index c746f0c..c746f0c 100644
--- a/big_data_demo/jsonrpclib/jsonrpclib/SimpleJSONRPCServer.py
+++ b/big_data_demo/mod/lib/python/jsonrpclib/SimpleJSONRPCServer.py
diff --git a/big_data_demo/mod/lib/python/jsonrpclib/SimpleJSONRPCServer.pyc b/big_data_demo/mod/lib/python/jsonrpclib/SimpleJSONRPCServer.pyc
new file mode 100644
index 0000000..60ea0a7
--- /dev/null
+++ b/big_data_demo/mod/lib/python/jsonrpclib/SimpleJSONRPCServer.pyc
Binary files differ
diff --git a/big_data_demo/jsonrpclib/jsonrpclib/__init__.py b/big_data_demo/mod/lib/python/jsonrpclib/__init__.py
index 6e884b8..6e884b8 100644
--- a/big_data_demo/jsonrpclib/jsonrpclib/__init__.py
+++ b/big_data_demo/mod/lib/python/jsonrpclib/__init__.py
diff --git a/big_data_demo/mod/lib/python/jsonrpclib/__init__.pyc b/big_data_demo/mod/lib/python/jsonrpclib/__init__.pyc
new file mode 100644
index 0000000..37e793b
--- /dev/null
+++ b/big_data_demo/mod/lib/python/jsonrpclib/__init__.pyc
Binary files differ
diff --git a/big_data_demo/jsonrpclib/jsonrpclib/config.py b/big_data_demo/mod/lib/python/jsonrpclib/config.py
index 4d28f1b..4d28f1b 100644
--- a/big_data_demo/jsonrpclib/jsonrpclib/config.py
+++ b/big_data_demo/mod/lib/python/jsonrpclib/config.py
diff --git a/big_data_demo/mod/lib/python/jsonrpclib/config.pyc b/big_data_demo/mod/lib/python/jsonrpclib/config.pyc
new file mode 100644
index 0000000..779d5dc
--- /dev/null
+++ b/big_data_demo/mod/lib/python/jsonrpclib/config.pyc
Binary files differ
diff --git a/big_data_demo/jsonrpclib/jsonrpclib/history.py b/big_data_demo/mod/lib/python/jsonrpclib/history.py
index d11863d..d11863d 100644
--- a/big_data_demo/jsonrpclib/jsonrpclib/history.py
+++ b/big_data_demo/mod/lib/python/jsonrpclib/history.py
diff --git a/big_data_demo/mod/lib/python/jsonrpclib/history.pyc b/big_data_demo/mod/lib/python/jsonrpclib/history.pyc
new file mode 100644
index 0000000..55ce9f8
--- /dev/null
+++ b/big_data_demo/mod/lib/python/jsonrpclib/history.pyc
Binary files differ
diff --git a/big_data_demo/jsonrpclib/jsonrpclib/jsonclass.py b/big_data_demo/mod/lib/python/jsonrpclib/jsonclass.py
index 1d86d5f..1d86d5f 100644
--- a/big_data_demo/jsonrpclib/jsonrpclib/jsonclass.py
+++ b/big_data_demo/mod/lib/python/jsonrpclib/jsonclass.py
diff --git a/big_data_demo/mod/lib/python/jsonrpclib/jsonclass.pyc b/big_data_demo/mod/lib/python/jsonrpclib/jsonclass.pyc
new file mode 100644
index 0000000..28baf5d
--- /dev/null
+++ b/big_data_demo/mod/lib/python/jsonrpclib/jsonclass.pyc
Binary files differ
diff --git a/big_data_demo/jsonrpclib/jsonrpclib/jsonrpc.py b/big_data_demo/mod/lib/python/jsonrpclib/jsonrpc.py
index e11939a..e11939a 100644
--- a/big_data_demo/jsonrpclib/jsonrpclib/jsonrpc.py
+++ b/big_data_demo/mod/lib/python/jsonrpclib/jsonrpc.py
diff --git a/big_data_demo/mod/lib/python/jsonrpclib/jsonrpc.pyc b/big_data_demo/mod/lib/python/jsonrpclib/jsonrpc.pyc
new file mode 100644
index 0000000..3fc31da
--- /dev/null
+++ b/big_data_demo/mod/lib/python/jsonrpclib/jsonrpc.pyc
Binary files differ
diff --git a/packaging/big_data_demo.manifest b/packaging/big_data_demo.manifest
new file mode 100644
index 0000000..97e8c31
--- /dev/null
+++ b/packaging/big_data_demo.manifest
@@ -0,0 +1,5 @@
+<manifest>
+ <request>
+ <domain name="_"/>
+ </request>
+</manifest>
diff --git a/packaging/big_data_demo.spec b/packaging/big_data_demo.spec
new file mode 100755
index 0000000..feecbcc
--- /dev/null
+++ b/packaging/big_data_demo.spec
@@ -0,0 +1,56 @@
+Summary: Remote Vehicle Interaction - Big Data Demo packaging
+Name: big_data_demo
+Version: 0.3.0
+Release: 1
+Group: App Framework/Application Communication
+License: Mozilla Public License 2.0
+Source: http://content.linuxfoundation.org/auto/downloads/big_data_demo/big_data_demo-0.3.0.tgz
+
+BuildRequires: make
+BuildRequires: python
+BuildRequires: rpm
+# BuildRequires: git
+
+%description
+Big Data Demo running on top of RVI
+
+
+%prep
+%setup -c big_data_demo-$RPM_PACKAGE_VERSION
+
+%build
+
+%install
+# Install the code.
+
+rm -fr $RPM_BUILD_ROOT/opt/big_data_demo-$RPM_PACKAGE_VERSION
+mkdir -p $RPM_BUILD_ROOT/opt/big_data_demo-$RPM_PACKAGE_VERSION
+
+cp ./big_data_demo/rvi_json_rpc_server.py $RPM_BUILD_ROOT/opt/big_data_demo-$RPM_PACKAGE_VERSION
+cp ./big_data_demo/amb_dbus.py $RPM_BUILD_ROOT/opt/big_data_demo-$RPM_PACKAGE_VERSION
+cp ./big_data_demo/data_logger.py $RPM_BUILD_ROOT/opt/big_data_demo-$RPM_PACKAGE_VERSION
+cp ./big_data_demo/gps_collector.py $RPM_BUILD_ROOT/opt/big_data_demo-$RPM_PACKAGE_VERSION
+cp ./big_data_demo/big_data_device.py $RPM_BUILD_ROOT/opt/big_data_demo-$RPM_PACKAGE_VERSION
+cp -r ./big_data_demo/mod $RPM_BUILD_ROOT/opt/big_data_demo-$RPM_PACKAGE_VERSION
+
+# Setup systemd
+mkdir -p $RPM_BUILD_ROOT/usr/lib/systemd/system/
+mkdir -p $RPM_BUILD_ROOT/etc/systemd/system/multi-user.target.wants/
+install ./big_data_demo/big_data.service $RPM_BUILD_ROOT/usr/lib/systemd/system/big_data.service
+ln -fsr $RPM_BUILD_ROOT/usr/lib/systemd/system/big_data.service $RPM_BUILD_ROOT/etc/systemd/system/multi-user.target.wants/big_data.service
+###################
+
+%post
+/usr/bin/systemctl daemon-reload
+
+%postun
+
+%clean
+rm -rf $RPM_BUILD_ROOT
+
+%files
+%manifest packaging/big_data_demo.manifest
+%defattr(-,root,root)
+/usr/lib/systemd/system/big_data.service
+/etc/systemd/system/multi-user.target.wants/big_data.service
+/opt/big_data_demo-0.3.0
diff --git a/sota_demo/jsonrpclib/.gitignore b/sota_demo/jsonrpclib/.gitignore
deleted file mode 100644
index f7d6c1a..0000000
--- a/sota_demo/jsonrpclib/.gitignore
+++ /dev/null
@@ -1,3 +0,0 @@
-*.pyc
-build/*
-dist/*
diff --git a/sota_demo/jsonrpclib/LICENSE.txt b/sota_demo/jsonrpclib/LICENSE.txt
deleted file mode 100644
index 51fca54..0000000
--- a/sota_demo/jsonrpclib/LICENSE.txt
+++ /dev/null
@@ -1,11 +0,0 @@
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
diff --git a/sota_demo/jsonrpclib/MANIFEST.in b/sota_demo/jsonrpclib/MANIFEST.in
deleted file mode 100644
index ab30e9a..0000000
--- a/sota_demo/jsonrpclib/MANIFEST.in
+++ /dev/null
@@ -1 +0,0 @@
-include *.txt
diff --git a/sota_demo/jsonrpclib/README.md b/sota_demo/jsonrpclib/README.md
deleted file mode 100644
index 85a157e..0000000
--- a/sota_demo/jsonrpclib/README.md
+++ /dev/null
@@ -1,219 +0,0 @@
-JSONRPClib
-==========
-This library is an implementation of the JSON-RPC specification.
-It supports both the original 1.0 specification, as well as the
-new (proposed) 2.0 spec, which includes batch submission, keyword
-arguments, etc.
-
-It is licensed under the Apache License, Version 2.0
-(http://www.apache.org/licenses/LICENSE-2.0.html).
-
-Communication
--------------
-Feel free to send any questions, comments, or patches to our Google Group
-mailing list (you'll need to join to send a message):
-http://groups.google.com/group/jsonrpclib
-
-Summary
--------
-This library implements the JSON-RPC 2.0 proposed specification in pure Python.
-It is designed to be as compatible with the syntax of xmlrpclib as possible
-(it extends where possible), so that projects using xmlrpclib could easily be
-modified to use JSON and experiment with the differences.
-
-It is backwards-compatible with the 1.0 specification, and supports all of the
-new proposed features of 2.0, including:
-
-* Batch submission (via MultiCall)
-* Keyword arguments
-* Notifications (both in a batch and 'normal')
-* Class translation using the 'jsonclass' key.
-
-I've added a "SimpleJSONRPCServer", which is intended to emulate the
-"SimpleXMLRPCServer" from the default Python distribution.
-
-Requirements
-------------
-It supports cjson and simplejson, and looks for the parsers in that order
-(searching first for cjson, then for the "built-in" simplejson as json in 2.6+,
-and then the simplejson external library). One of these must be installed to
-use this library, although if you have a standard distribution of 2.6+, you
-should already have one. Keep in mind that cjson is supposed to be the
-quickest, I believe, so if you are going for full-on optimization you may
-want to pick it up.
-
-Installation
-------------
-You can install this from PyPI with one of the following commands (sudo
-may be required):
-
- easy_install jsonrpclib
- pip install jsonrpclib
-
-Alternatively, you can download the source from the github repository
-at http://github.com/joshmarshall/jsonrpclib and manually install it
-with the following commands:
-
- git clone git://github.com/joshmarshall/jsonrpclib.git
- cd jsonrpclib
- python setup.py install
-
-Client Usage
-------------
-
-This is (obviously) taken from a console session.
-
- >>> import jsonrpclib
- >>> server = jsonrpclib.Server('http://localhost:8080')
- >>> server.add(5,6)
- 11
- >>> print jsonrpclib.history.request
- {"jsonrpc": "2.0", "params": [5, 6], "id": "gb3c9g37", "method": "add"}
- >>> print jsonrpclib.history.response
- {'jsonrpc': '2.0', 'result': 11, 'id': 'gb3c9g37'}
- >>> server.add(x=5, y=10)
- 15
- >>> server._notify.add(5,6)
- # No result returned...
- >>> batch = jsonrpclib.MultiCall(server)
- >>> batch.add(5, 6)
- >>> batch.ping({'key':'value'})
- >>> batch._notify.add(4, 30)
- >>> results = batch()
- >>> for result in results:
- >>> ... print result
- 11
- {'key': 'value'}
- # Note that there are only two responses -- this is according to spec.
-
-If you need 1.0 functionality, there are a bunch of places you can pass that
-in, although the best is just to change the value on
-jsonrpclib.config.version:
-
- >>> import jsonrpclib
- >>> jsonrpclib.config.version
- 2.0
- >>> jsonrpclib.config.version = 1.0
- >>> server = jsonrpclib.Server('http://localhost:8080')
- >>> server.add(7, 10)
- 17
- >>> print jsonrpclib..history.request
- {"params": [7, 10], "id": "thes7tl2", "method": "add"}
- >>> print jsonrpclib.history.response
- {'id': 'thes7tl2', 'result': 17, 'error': None}
- >>>
-
-The equivalent loads and dumps functions also exist, although with minor
-modifications. The dumps arguments are almost identical, but it adds three
-arguments: rpcid for the 'id' key, version to specify the JSON-RPC
-compatibility, and notify if it's a request that you want to be a
-notification.
-
-Additionally, the loads method does not return the params and method like
-xmlrpclib, but instead a.) parses for errors, raising ProtocolErrors, and
-b.) returns the entire structure of the request / response for manual parsing.
-
-SimpleJSONRPCServer
--------------------
-This is identical in usage (or should be) to the SimpleXMLRPCServer in the default Python install. Some of the differences in features are that it obviously supports notification, batch calls, class translation (if left on), etc. Note: The import line is slightly different from the regular SimpleXMLRPCServer, since the SimpleJSONRPCServer is distributed within the jsonrpclib library.
-
- from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
-
- server = SimpleJSONRPCServer(('localhost', 8080))
- server.register_function(pow)
- server.register_function(lambda x,y: x+y, 'add')
- server.register_function(lambda x: x, 'ping')
- server.serve_forever()
-
-Class Translation
------------------
-I've recently added "automatic" class translation support, although it is
-turned off by default. This can be devastatingly slow if improperly used, so
-the following is just a short list of things to keep in mind when using it.
-
-* Keep It (the object) Simple Stupid. (for exceptions, keep reading.)
-* Do not require init params (for exceptions, keep reading)
-* Getter properties without setters could be dangerous (read: not tested)
-
-If any of the above are issues, use the _serialize method. (see usage below)
-The server and client must BOTH have use_jsonclass configuration item on and
-they must both have access to the same libraries used by the objects for
-this to work.
-
-If you have excessively nested arguments, it would be better to turn off the
-translation and manually invoke it on specific objects using
-jsonrpclib.jsonclass.dump / jsonrpclib.jsonclass.load (since the default
-behavior recursively goes through attributes and lists / dicts / tuples).
-
-[test_obj.py]
-
- # This object is /very/ simple, and the system will look through the
- # attributes and serialize what it can.
- class TestObj(object):
- foo = 'bar'
-
- # This object requires __init__ params, so it uses the _serialize method
- # and returns a tuple of init params and attribute values (the init params
- # can be a dict or a list, but the attribute values must be a dict.)
- class TestSerial(object):
- foo = 'bar'
- def __init__(self, *args):
- self.args = args
- def _serialize(self):
- return (self.args, {'foo':self.foo,})
-
-[usage]
-
- import jsonrpclib
- import test_obj
-
- jsonrpclib.config.use_jsonclass = True
-
- testobj1 = test_obj.TestObj()
- testobj2 = test_obj.TestSerial()
- server = jsonrpclib.Server('http://localhost:8080')
- # The 'ping' just returns whatever is sent
- ping1 = server.ping(testobj1)
- ping2 = server.ping(testobj2)
- print jsonrpclib.history.request
- # {"jsonrpc": "2.0", "params": [{"__jsonclass__": ["test_obj.TestSerial", ["foo"]]}], "id": "a0l976iv", "method": "ping"}
- print jsonrpclib.history.result
- # {'jsonrpc': '2.0', 'result': <test_obj.TestSerial object at 0x2744590>, 'id': 'a0l976iv'}
-
-To turn on this behaviour, just set jsonrpclib.config.use_jsonclass to True.
-If you want to use a different method for serialization, just set
-jsonrpclib.config.serialize_method to the method name. Finally, if you are
-using classes that you have defined in the implementation (as in, not a
-separate library), you'll need to add those (on BOTH the server and the
-client) using the jsonrpclib.config.classes.add() method.
-(Examples forthcoming.)
-
-Feedback on this "feature" is very, VERY much appreciated.
-
-Why JSON-RPC?
--------------
-In my opinion, there are several reasons to choose JSON over XML for RPC:
-
-* Much simpler to read (I suppose this is opinion, but I know I'm right. :)
-* Size / Bandwidth - Main reason, a JSON object representation is just much smaller.
-* Parsing - JSON should be much quicker to parse than XML.
-* Easy class passing with jsonclass (when enabled)
-
-In the interest of being fair, there are also a few reasons to choose XML
-over JSON:
-
-* Your server doesn't do JSON (rather obvious)
-* Wider XML-RPC support across APIs (can we change this? :))
-* Libraries are more established, i.e. more stable (Let's change this too.)
-
-TESTS
------
-I've dropped almost-verbatim tests from the JSON-RPC spec 2.0 page.
-You can run it with:
-
- python tests.py
-
-TODO
-----
-* Use HTTP error codes on SimpleJSONRPCServer
-* Test, test, test and optimize
diff --git a/sota_demo/jsonrpclib/jsonrpclib/SimpleJSONRPCServer.py b/sota_demo/jsonrpclib/jsonrpclib/SimpleJSONRPCServer.py
deleted file mode 100644
index c746f0c..0000000
--- a/sota_demo/jsonrpclib/jsonrpclib/SimpleJSONRPCServer.py
+++ /dev/null
@@ -1,232 +0,0 @@
-import jsonrpclib
-from jsonrpclib import Fault
-from jsonrpclib.jsonrpc import USE_UNIX_SOCKETS
-import SimpleXMLRPCServer
-import SocketServer
-import socket
-import logging
-import os
-import types
-import traceback
-import sys
-try:
- import fcntl
-except ImportError:
- # For Windows
- fcntl = None
-
-def get_version(request):
- # must be a dict
- if 'jsonrpc' in request.keys():
- return 2.0
- if 'id' in request.keys():
- return 1.0
- return None
-
-def validate_request(request):
- if type(request) is not types.DictType:
- fault = Fault(
- -32600, 'Request must be {}, not %s.' % type(request)
- )
- return fault
- rpcid = request.get('id', None)
- version = get_version(request)
- if not version:
- fault = Fault(-32600, 'Request %s invalid.' % request, rpcid=rpcid)
- return fault
- request.setdefault('params', [])
- method = request.get('method', None)
- params = request.get('params')
- param_types = (types.ListType, types.DictType, types.TupleType)
- if not method or type(method) not in types.StringTypes or \
- type(params) not in param_types:
- fault = Fault(
- -32600, 'Invalid request parameters or method.', rpcid=rpcid
- )
- return fault
- return True
-
-class SimpleJSONRPCDispatcher(SimpleXMLRPCServer.SimpleXMLRPCDispatcher):
-
- def __init__(self, encoding=None):
- SimpleXMLRPCServer.SimpleXMLRPCDispatcher.__init__(self,
- allow_none=True,
- encoding=encoding)
-
- def _marshaled_dispatch(self, data, dispatch_method = None):
- response = None
- try:
- request = jsonrpclib.loads(data)
- except Exception, e:
- fault = Fault(-32700, 'Request %s invalid. (%s)' % (data, e))
- response = fault.response()
- return response
- if not request:
- fault = Fault(-32600, 'Request invalid -- no request data.')
- return fault.response()
- if type(request) is types.ListType:
- # This SHOULD be a batch, by spec
- responses = []
- for req_entry in request:
- result = validate_request(req_entry)
- if type(result) is Fault:
- responses.append(result.response())
- continue
- resp_entry = self._marshaled_single_dispatch(req_entry)
- if resp_entry is not None:
- responses.append(resp_entry)
- if len(responses) > 0:
- response = '[%s]' % ','.join(responses)
- else:
- response = ''
- else:
- result = validate_request(request)
- if type(result) is Fault:
- return result.response()
- response = self._marshaled_single_dispatch(request)
- return response
-
- def _marshaled_single_dispatch(self, request):
- # TODO - Use the multiprocessing and skip the response if
- # it is a notification
- # Put in support for custom dispatcher here
- # (See SimpleXMLRPCServer._marshaled_dispatch)
- method = request.get('method')
- params = request.get('params')
- try:
- response = self._dispatch(method, params)
- except:
- exc_type, exc_value, exc_tb = sys.exc_info()
- fault = Fault(-32603, '%s:%s' % (exc_type, exc_value))
- return fault.response()
- if 'id' not in request.keys() or request['id'] == None:
- # It's a notification
- return None
- try:
- response = jsonrpclib.dumps(response,
- methodresponse=True,
- rpcid=request['id']
- )
- return response
- except:
- exc_type, exc_value, exc_tb = sys.exc_info()
- fault = Fault(-32603, '%s:%s' % (exc_type, exc_value))
- return fault.response()
-
- def _dispatch(self, method, params):
- func = None
- try:
- func = self.funcs[method]
- except KeyError:
- if self.instance is not None:
- if hasattr(self.instance, '_dispatch'):
- return self.instance._dispatch(method, params)
- else:
- try:
- func = SimpleXMLRPCServer.resolve_dotted_attribute(
- self.instance,
- method,
- True
- )
- except AttributeError:
- pass
- if func is not None:
- try:
- if type(params) is types.ListType:
- response = func(*params)
- else:
- response = func(**params)
- return response
- except TypeError:
- return Fault(-32602, 'Invalid parameters.')
- except:
- err_lines = traceback.format_exc().splitlines()
- trace_string = '%s | %s' % (err_lines[-3], err_lines[-1])
- fault = jsonrpclib.Fault(-32603, 'Server error: %s' %
- trace_string)
- return fault
- else:
- return Fault(-32601, 'Method %s not supported.' % method)
-
-class SimpleJSONRPCRequestHandler(
- SimpleXMLRPCServer.SimpleXMLRPCRequestHandler):
-
- def do_POST(self):
- if not self.is_rpc_path_valid():
- self.report_404()
- return
- try:
- max_chunk_size = 10*1024*1024
- size_remaining = int(self.headers["content-length"])
- L = []
- while size_remaining:
- chunk_size = min(size_remaining, max_chunk_size)
- L.append(self.rfile.read(chunk_size))
- size_remaining -= len(L[-1])
- data = ''.join(L)
- response = self.server._marshaled_dispatch(data)
- self.send_response(200)
- except Exception, e:
- self.send_response(500)
- err_lines = traceback.format_exc().splitlines()
- trace_string = '%s | %s' % (err_lines[-3], err_lines[-1])
- fault = jsonrpclib.Fault(-32603, 'Server error: %s' % trace_string)
- response = fault.response()
- if response == None:
- response = ''
- self.send_header("Content-type", "application/json-rpc")
- self.send_header("Content-length", str(len(response)))
- self.end_headers()
- self.wfile.write(response)
- self.wfile.flush()
- try:
- self.connection.shutdown(1)
- except:
- return
-
-class SimpleJSONRPCServer(SocketServer.TCPServer, SimpleJSONRPCDispatcher):
-
- allow_reuse_address = True
-
- def __init__(self, addr, requestHandler=SimpleJSONRPCRequestHandler,
- logRequests=True, encoding=None, bind_and_activate=True,
- address_family=socket.AF_INET):
- self.logRequests = logRequests
- SimpleJSONRPCDispatcher.__init__(self, encoding)
- # TCPServer.__init__ has an extra parameter on 2.6+, so
- # check Python version and decide on how to call it
- vi = sys.version_info
- self.address_family = address_family
- if USE_UNIX_SOCKETS and address_family == socket.AF_UNIX:
- # Unix sockets can't be bound if they already exist in the
- # filesystem. The convention of e.g. X11 is to unlink
- # before binding again.
- if os.path.exists(addr):
- try:
- os.unlink(addr)
- except OSError:
- logging.warning("Could not unlink socket %s", addr)
- # if python 2.5 and lower
- if vi[0] < 3 and vi[1] < 6:
- SocketServer.TCPServer.__init__(self, addr, requestHandler)
- else:
- SocketServer.TCPServer.__init__(self, addr, requestHandler,
- bind_and_activate)
- if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'):
- flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD)
- flags |= fcntl.FD_CLOEXEC
- fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags)
-
-class CGIJSONRPCRequestHandler(SimpleJSONRPCDispatcher):
-
- def __init__(self, encoding=None):
- SimpleJSONRPCDispatcher.__init__(self, encoding)
-
- def handle_jsonrpc(self, request_text):
- response = self._marshaled_dispatch(request_text)
- print 'Content-Type: application/json-rpc'
- print 'Content-Length: %d' % len(response)
- print
- sys.stdout.write(response)
-
- handle_xmlrpc = handle_jsonrpc
diff --git a/sota_demo/jsonrpclib/jsonrpclib/__init__.py b/sota_demo/jsonrpclib/jsonrpclib/__init__.py
deleted file mode 100644
index 6e884b8..0000000
--- a/sota_demo/jsonrpclib/jsonrpclib/__init__.py
+++ /dev/null
@@ -1,6 +0,0 @@
-from jsonrpclib.config import Config
-config = Config.instance()
-from jsonrpclib.history import History
-history = History.instance()
-from jsonrpclib.jsonrpc import Server, MultiCall, Fault
-from jsonrpclib.jsonrpc import ProtocolError, loads, dumps
diff --git a/sota_demo/jsonrpclib/jsonrpclib/config.py b/sota_demo/jsonrpclib/jsonrpclib/config.py
deleted file mode 100644
index 4d28f1b..0000000
--- a/sota_demo/jsonrpclib/jsonrpclib/config.py
+++ /dev/null
@@ -1,38 +0,0 @@
-import sys
-
-class LocalClasses(dict):
- def add(self, cls):
- self[cls.__name__] = cls
-
-class Config(object):
- """
- This is pretty much used exclusively for the 'jsonclass'
- functionality... set use_jsonclass to False to turn it off.
- You can change serialize_method and ignore_attribute, or use
- the local_classes.add(class) to include "local" classes.
- """
- use_jsonclass = True
- # Change to False to keep __jsonclass__ entries raw.
- serialize_method = '_serialize'
- # The serialize_method should be a string that references the
- # method on a custom class object which is responsible for
- # returning a tuple of the constructor arguments and a dict of
- # attributes.
- ignore_attribute = '_ignore'
- # The ignore attribute should be a string that references the
- # attribute on a custom class object which holds strings and / or
- # references of the attributes the class translator should ignore.
- classes = LocalClasses()
- # The list of classes to use for jsonclass translation.
- version = 2.0
- # Version of the JSON-RPC spec to support
- user_agent = 'jsonrpclib/0.1 (Python %s)' % \
- '.'.join([str(ver) for ver in sys.version_info[0:3]])
- # User agent to use for calls.
- _instance = None
-
- @classmethod
- def instance(cls):
- if not cls._instance:
- cls._instance = cls()
- return cls._instance
diff --git a/sota_demo/jsonrpclib/jsonrpclib/history.py b/sota_demo/jsonrpclib/jsonrpclib/history.py
deleted file mode 100644
index d11863d..0000000
--- a/sota_demo/jsonrpclib/jsonrpclib/history.py
+++ /dev/null
@@ -1,40 +0,0 @@
-class History(object):
- """
- This holds all the response and request objects for a
- session. A server using this should call "clear" after
- each request cycle in order to keep it from clogging
- memory.
- """
- requests = []
- responses = []
- _instance = None
-
- @classmethod
- def instance(cls):
- if not cls._instance:
- cls._instance = cls()
- return cls._instance
-
- def add_response(self, response_obj):
- self.responses.append(response_obj)
-
- def add_request(self, request_obj):
- self.requests.append(request_obj)
-
- @property
- def request(self):
- if len(self.requests) == 0:
- return None
- else:
- return self.requests[-1]
-
- @property
- def response(self):
- if len(self.responses) == 0:
- return None
- else:
- return self.responses[-1]
-
- def clear(self):
- del self.requests[:]
- del self.responses[:]
diff --git a/sota_demo/jsonrpclib/jsonrpclib/jsonclass.py b/sota_demo/jsonrpclib/jsonrpclib/jsonclass.py
deleted file mode 100644
index 1d86d5f..0000000
--- a/sota_demo/jsonrpclib/jsonrpclib/jsonclass.py
+++ /dev/null
@@ -1,152 +0,0 @@
-import types
-import inspect
-import re
-import traceback
-
-from jsonrpclib import config
-
-iter_types = [
- types.DictType,
- types.ListType,
- types.TupleType
-]
-
-string_types = [
- types.StringType,
- types.UnicodeType
-]
-
-numeric_types = [
- types.IntType,
- types.LongType,
- types.FloatType
-]
-
-value_types = [
- types.BooleanType,
- types.NoneType
-]
-
-supported_types = iter_types+string_types+numeric_types+value_types
-invalid_module_chars = r'[^a-zA-Z0-9\_\.]'
-
-class TranslationError(Exception):
- pass
-
-def dump(obj, serialize_method=None, ignore_attribute=None, ignore=[]):
- if not serialize_method:
- serialize_method = config.serialize_method
- if not ignore_attribute:
- ignore_attribute = config.ignore_attribute
- obj_type = type(obj)
- # Parse / return default "types"...
- if obj_type in numeric_types+string_types+value_types:
- return obj
- if obj_type in iter_types:
- if obj_type in (types.ListType, types.TupleType):
- new_obj = []
- for item in obj:
- new_obj.append(dump(item, serialize_method,
- ignore_attribute, ignore))
- if obj_type is types.TupleType:
- new_obj = tuple(new_obj)
- return new_obj
- # It's a dict...
- else:
- new_obj = {}
- for key, value in obj.iteritems():
- new_obj[key] = dump(value, serialize_method,
- ignore_attribute, ignore)
- return new_obj
- # It's not a standard type, so it needs __jsonclass__
- module_name = inspect.getmodule(obj).__name__
- class_name = obj.__class__.__name__
- json_class = class_name
- if module_name not in ['', '__main__']:
- json_class = '%s.%s' % (module_name, json_class)
- return_obj = {"__jsonclass__":[json_class,]}
- # If a serialization method is defined..
- if serialize_method in dir(obj):
- # Params can be a dict (keyword) or list (positional)
- # Attrs MUST be a dict.
- serialize = getattr(obj, serialize_method)
- params, attrs = serialize()
- return_obj['__jsonclass__'].append(params)
- return_obj.update(attrs)
- return return_obj
- # Otherwise, try to figure it out
- # Obviously, we can't assume to know anything about the
- # parameters passed to __init__
- return_obj['__jsonclass__'].append([])
- attrs = {}
- ignore_list = getattr(obj, ignore_attribute, [])+ignore
- for attr_name, attr_value in obj.__dict__.iteritems():
- if type(attr_value) in supported_types and \
- attr_name not in ignore_list and \
- attr_value not in ignore_list:
- attrs[attr_name] = dump(attr_value, serialize_method,
- ignore_attribute, ignore)
- return_obj.update(attrs)
- return return_obj
-
-def load(obj):
- if type(obj) in string_types+numeric_types+value_types:
- return obj
- if type(obj) is types.ListType:
- return_list = []
- for entry in obj:
- return_list.append(load(entry))
- return return_list
- # Othewise, it's a dict type
- if '__jsonclass__' not in obj.keys():
- return_dict = {}
- for key, value in obj.iteritems():
- new_value = load(value)
- return_dict[key] = new_value
- return return_dict
- # It's a dict, and it's a __jsonclass__
- orig_module_name = obj['__jsonclass__'][0]
- params = obj['__jsonclass__'][1]
- if orig_module_name == '':
- raise TranslationError('Module name empty.')
- json_module_clean = re.sub(invalid_module_chars, '', orig_module_name)
- if json_module_clean != orig_module_name:
- raise TranslationError('Module name %s has invalid characters.' %
- orig_module_name)
- json_module_parts = json_module_clean.split('.')
- json_class = None
- if len(json_module_parts) == 1:
- # Local class name -- probably means it won't work
- if json_module_parts[0] not in config.classes.keys():
- raise TranslationError('Unknown class or module %s.' %
- json_module_parts[0])
- json_class = config.classes[json_module_parts[0]]
- else:
- json_class_name = json_module_parts.pop()
- json_module_tree = '.'.join(json_module_parts)
- try:
- temp_module = __import__(json_module_tree)
- except ImportError:
- raise TranslationError('Could not import %s from module %s.' %
- (json_class_name, json_module_tree))
-
- # The returned class is the top-level module, not the one we really
- # want. (E.g., if we import a.b.c, we now have a.) Walk through other
- # path components to get to b and c.
- for i in json_module_parts[1:]:
- temp_module = getattr(temp_module, i)
-
- json_class = getattr(temp_module, json_class_name)
- # Creating the object...
- new_obj = None
- if type(params) is types.ListType:
- new_obj = json_class(*params)
- elif type(params) is types.DictType:
- new_obj = json_class(**params)
- else:
- raise TranslationError('Constructor args must be a dict or list.')
- for key, value in obj.iteritems():
- if key == '__jsonclass__':
- continue
- setattr(new_obj, key, value)
- return new_obj
diff --git a/sota_demo/jsonrpclib/jsonrpclib/jsonrpc.py b/sota_demo/jsonrpclib/jsonrpclib/jsonrpc.py
deleted file mode 100644
index e11939a..0000000
--- a/sota_demo/jsonrpclib/jsonrpclib/jsonrpc.py
+++ /dev/null
@@ -1,556 +0,0 @@
-"""
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-
-============================
-JSONRPC Library (jsonrpclib)
-============================
-
-This library is a JSON-RPC v.2 (proposed) implementation which
-follows the xmlrpclib API for portability between clients. It
-uses the same Server / ServerProxy, loads, dumps, etc. syntax,
-while providing features not present in XML-RPC like:
-
-* Keyword arguments
-* Notifications
-* Versioning
-* Batches and batch notifications
-
-Eventually, I'll add a SimpleXMLRPCServer compatible library,
-and other things to tie the thing off nicely. :)
-
-For a quick-start, just open a console and type the following,
-replacing the server address, method, and parameters
-appropriately.
->>> import jsonrpclib
->>> server = jsonrpclib.Server('http://localhost:8181')
->>> server.add(5, 6)
-11
->>> server._notify.add(5, 6)
->>> batch = jsonrpclib.MultiCall(server)
->>> batch.add(3, 50)
->>> batch.add(2, 3)
->>> batch._notify.add(3, 5)
->>> batch()
-[53, 5]
-
-See http://code.google.com/p/jsonrpclib/ for more info.
-"""
-
-import types
-import sys
-from xmlrpclib import Transport as XMLTransport
-from xmlrpclib import SafeTransport as XMLSafeTransport
-from xmlrpclib import ServerProxy as XMLServerProxy
-from xmlrpclib import _Method as XML_Method
-import time
-import string
-import random
-
-# Library includes
-import jsonrpclib
-from jsonrpclib import config
-from jsonrpclib import history
-
-# JSON library importing
-cjson = None
-json = None
-try:
- import cjson
-except ImportError:
- try:
- import json
- except ImportError:
- try:
- import simplejson as json
- except ImportError:
- raise ImportError(
- 'You must have the cjson, json, or simplejson ' +
- 'module(s) available.'
- )
-
-IDCHARS = string.ascii_lowercase+string.digits
-
-class UnixSocketMissing(Exception):
- """
- Just a properly named Exception if Unix Sockets usage is
- attempted on a platform that doesn't support them (Windows)
- """
- pass
-
-#JSON Abstractions
-
-def jdumps(obj, encoding='utf-8'):
- # Do 'serialize' test at some point for other classes
- global cjson
- if cjson:
- return cjson.encode(obj)
- else:
- return json.dumps(obj, encoding=encoding)
-
-def jloads(json_string):
- global cjson
- if cjson:
- return cjson.decode(json_string)
- else:
- return json.loads(json_string)
-
-
-# XMLRPClib re-implementations
-
-class ProtocolError(Exception):
- pass
-
-class TransportMixIn(object):
- """ Just extends the XMLRPC transport where necessary. """
- user_agent = config.user_agent
- # for Python 2.7 support
- _connection = None
-
- def send_content(self, connection, request_body):
- connection.putheader("Content-Type", "application/json-rpc")
- connection.putheader("Content-Length", str(len(request_body)))
- connection.endheaders()
- if request_body:
- connection.send(request_body)
-
- def getparser(self):
- target = JSONTarget()
- return JSONParser(target), target
-
-class JSONParser(object):
- def __init__(self, target):
- self.target = target
-
- def feed(self, data):
- self.target.feed(data)
-
- def close(self):
- pass
-
-class JSONTarget(object):
- def __init__(self):
- self.data = []
-
- def feed(self, data):
- self.data.append(data)
-
- def close(self):
- return ''.join(self.data)
-
-class Transport(TransportMixIn, XMLTransport):
- pass
-
-class SafeTransport(TransportMixIn, XMLSafeTransport):
- pass
-from httplib import HTTP, HTTPConnection
-from socket import socket
-
-USE_UNIX_SOCKETS = False
-
-try:
- from socket import AF_UNIX, SOCK_STREAM
- USE_UNIX_SOCKETS = True
-except ImportError:
- pass
-
-if (USE_UNIX_SOCKETS):
-
- class UnixHTTPConnection(HTTPConnection):
- def connect(self):
- self.sock = socket(AF_UNIX, SOCK_STREAM)
- self.sock.connect(self.host)
-
- class UnixHTTP(HTTP):
- _connection_class = UnixHTTPConnection
-
- class UnixTransport(TransportMixIn, XMLTransport):
- def make_connection(self, host):
- import httplib
- host, extra_headers, x509 = self.get_host_info(host)
- return UnixHTTP(host)
-
-
-class ServerProxy(XMLServerProxy):
- """
- Unfortunately, much more of this class has to be copied since
- so much of it does the serialization.
- """
-
- def __init__(self, uri, transport=None, encoding=None,
- verbose=0, version=None):
- import urllib
- if not version:
- version = config.version
- self.__version = version
- schema, uri = urllib.splittype(uri)
- if schema not in ('http', 'https', 'unix'):
- raise IOError('Unsupported JSON-RPC protocol.')
- if schema == 'unix':
- if not USE_UNIX_SOCKETS:
- # Don't like the "generic" Exception...
- raise UnixSocketMissing("Unix sockets not available.")
- self.__host = uri
- self.__handler = '/'
- else:
- self.__host, self.__handler = urllib.splithost(uri)
- if not self.__handler:
- # Not sure if this is in the JSON spec?
- #self.__handler = '/'
- self.__handler == '/'
- if transport is None:
- if schema == 'unix':
- transport = UnixTransport()
- elif schema == 'https':
- transport = SafeTransport()
- else:
- transport = Transport()
- self.__transport = transport
- self.__encoding = encoding
- self.__verbose = verbose
-
- def _request(self, methodname, params, rpcid=None):
- request = dumps(params, methodname, encoding=self.__encoding,
- rpcid=rpcid, version=self.__version)
- response = self._run_request(request)
- check_for_errors(response)
- return response['result']
-
- def _request_notify(self, methodname, params, rpcid=None):
- request = dumps(params, methodname, encoding=self.__encoding,
- rpcid=rpcid, version=self.__version, notify=True)
- response = self._run_request(request, notify=True)
- check_for_errors(response)
- return
-
- def _run_request(self, request, notify=None):
- history.add_request(request)
-
- response = self.__transport.request(
- self.__host,
- self.__handler,
- request,
- verbose=self.__verbose
- )
-
- # Here, the XMLRPC library translates a single list
- # response to the single value -- should we do the
- # same, and require a tuple / list to be passed to
- # the response object, or expect the Server to be
- # outputting the response appropriately?
-
- history.add_response(response)
- if not response:
- return None
- return_obj = loads(response)
- return return_obj
-
- def __getattr__(self, name):
- # Same as original, just with new _Method reference
- return _Method(self._request, name)
-
- @property
- def _notify(self):
- # Just like __getattr__, but with notify namespace.
- return _Notify(self._request_notify)
-
-
-class _Method(XML_Method):
-
- def __call__(self, *args, **kwargs):
- if len(args) > 0 and len(kwargs) > 0:
- raise ProtocolError('Cannot use both positional ' +
- 'and keyword arguments (according to JSON-RPC spec.)')
- if len(args) > 0:
- return self.__send(self.__name, args)
- else:
- return self.__send(self.__name, kwargs)
-
- def __getattr__(self, name):
- self.__name = '%s.%s' % (self.__name, name)
- return self
- # The old method returned a new instance, but this seemed wasteful.
- # The only thing that changes is the name.
- #return _Method(self.__send, "%s.%s" % (self.__name, name))
-
-class _Notify(object):
- def __init__(self, request):
- self._request = request
-
- def __getattr__(self, name):
- return _Method(self._request, name)
-
-# Batch implementation
-
-class MultiCallMethod(object):
-
- def __init__(self, method, notify=False):
- self.method = method
- self.params = []
- self.notify = notify
-
- def __call__(self, *args, **kwargs):
- if len(kwargs) > 0 and len(args) > 0:
- raise ProtocolError('JSON-RPC does not support both ' +
- 'positional and keyword arguments.')
- if len(kwargs) > 0:
- self.params = kwargs
- else:
- self.params = args
-
- def request(self, encoding=None, rpcid=None):
- return dumps(self.params, self.method, version=2.0,
- encoding=encoding, rpcid=rpcid, notify=self.notify)
-
- def __repr__(self):
- return '%s' % self.request()
-
- def __getattr__(self, method):
- new_method = '%s.%s' % (self.method, method)
- self.method = new_method
- return self
-
-class MultiCallNotify(object):
-
- def __init__(self, multicall):
- self.multicall = multicall
-
- def __getattr__(self, name):
- new_job = MultiCallMethod(name, notify=True)
- self.multicall._job_list.append(new_job)
- return new_job
-
-class MultiCallIterator(object):
-
- def __init__(self, results):
- self.results = results
-
- def __iter__(self):
- for i in range(0, len(self.results)):
- yield self[i]
- raise StopIteration
-
- def __getitem__(self, i):
- item = self.results[i]
- check_for_errors(item)
- return item['result']
-
- def __len__(self):
- return len(self.results)
-
-class MultiCall(object):
-
- def __init__(self, server):
- self._server = server
- self._job_list = []
-
- def _request(self):
- if len(self._job_list) < 1:
- # Should we alert? This /is/ pretty obvious.
- return
- request_body = '[ %s ]' % ','.join([job.request() for
- job in self._job_list])
- responses = self._server._run_request(request_body)
- del self._job_list[:]
- if not responses:
- responses = []
- return MultiCallIterator(responses)
-
- @property
- def _notify(self):
- return MultiCallNotify(self)
-
- def __getattr__(self, name):
- new_job = MultiCallMethod(name)
- self._job_list.append(new_job)
- return new_job
-
- __call__ = _request
-
-# These lines conform to xmlrpclib's "compatibility" line.
-# Not really sure if we should include these, but oh well.
-Server = ServerProxy
-
-class Fault(object):
- # JSON-RPC error class
- def __init__(self, code=-32000, message='Server error', rpcid=None):
- self.faultCode = code
- self.faultString = message
- self.rpcid = rpcid
-
- def error(self):
- return {'code':self.faultCode, 'message':self.faultString}
-
- def response(self, rpcid=None, version=None):
- if not version:
- version = config.version
- if rpcid:
- self.rpcid = rpcid
- return dumps(
- self, methodresponse=True, rpcid=self.rpcid, version=version
- )
-
- def __repr__(self):
- return '<Fault %s: %s>' % (self.faultCode, self.faultString)
-
-def random_id(length=8):
- return_id = ''
- for i in range(length):
- return_id += random.choice(IDCHARS)
- return return_id
-
-class Payload(dict):
- def __init__(self, rpcid=None, version=None):
- if not version:
- version = config.version
- self.id = rpcid
- self.version = float(version)
-
- def request(self, method, params=[]):
- if type(method) not in types.StringTypes:
- raise ValueError('Method name must be a string.')
- if not self.id:
- self.id = random_id()
- request = { 'id':self.id, 'method':method }
- if params:
- request['params'] = params
- if self.version >= 2:
- request['jsonrpc'] = str(self.version)
- return request
-
- def notify(self, method, params=[]):
- request = self.request(method, params)
- if self.version >= 2:
- del request['id']
- else:
- request['id'] = None
- return request
-
- def response(self, result=None):
- response = {'result':result, 'id':self.id}
- if self.version >= 2:
- response['jsonrpc'] = str(self.version)
- else:
- response['error'] = None
- return response
-
- def error(self, code=-32000, message='Server error.'):
- error = self.response()
- if self.version >= 2:
- del error['result']
- else:
- error['result'] = None
- error['error'] = {'code':code, 'message':message}
- return error
-
-def dumps(params=[], methodname=None, methodresponse=None,
- encoding=None, rpcid=None, version=None, notify=None):
- """
- This differs from the Python implementation in that it implements
- the rpcid argument since the 2.0 spec requires it for responses.
- """
- if not version:
- version = config.version
- valid_params = (types.TupleType, types.ListType, types.DictType)
- if methodname in types.StringTypes and \
- type(params) not in valid_params and \
- not isinstance(params, Fault):
- """
- If a method, and params are not in a listish or a Fault,
- error out.
- """
- raise TypeError('Params must be a dict, list, tuple or Fault ' +
- 'instance.')
- # Begin parsing object
- payload = Payload(rpcid=rpcid, version=version)
- if not encoding:
- encoding = 'utf-8'
- if type(params) is Fault:
- response = payload.error(params.faultCode, params.faultString)
- return jdumps(response, encoding=encoding)
- if type(methodname) not in types.StringTypes and methodresponse != True:
- raise ValueError('Method name must be a string, or methodresponse '+
- 'must be set to True.')
- if config.use_jsonclass == True:
- from jsonrpclib import jsonclass
- params = jsonclass.dump(params)
- if methodresponse is True:
- if rpcid is None:
- raise ValueError('A method response must have an rpcid.')
- response = payload.response(params)
- return jdumps(response, encoding=encoding)
- request = None
- if notify == True:
- request = payload.notify(methodname, params)
- else:
- request = payload.request(methodname, params)
- return jdumps(request, encoding=encoding)
-
-def loads(data):
- """
- This differs from the Python implementation, in that it returns
- the request structure in Dict format instead of the method, params.
- It will return a list in the case of a batch request / response.
- """
- if data == '':
- # notification
- return None
- result = jloads(data)
- # if the above raises an error, the implementing server code
- # should return something like the following:
- # { 'jsonrpc':'2.0', 'error': fault.error(), id: None }
- if config.use_jsonclass == True:
- from jsonrpclib import jsonclass
- result = jsonclass.load(result)
- return result
-
-def check_for_errors(result):
- if not result:
- # Notification
- return result
- if type(result) is not types.DictType:
- raise TypeError('Response is not a dict.')
- if 'jsonrpc' in result.keys() and float(result['jsonrpc']) > 2.0:
- raise NotImplementedError('JSON-RPC version not yet supported.')
- if 'result' not in result.keys() and 'error' not in result.keys():
- raise ValueError('Response does not have a result or error key.')
- if 'error' in result.keys() and result['error'] != None:
- code = result['error']['code']
- message = result['error']['message']
- raise ProtocolError((code, message))
- return result
-
-def isbatch(result):
- if type(result) not in (types.ListType, types.TupleType):
- return False
- if len(result) < 1:
- return False
- if type(result[0]) is not types.DictType:
- return False
- if 'jsonrpc' not in result[0].keys():
- return False
- try:
- version = float(result[0]['jsonrpc'])
- except ValueError:
- raise ProtocolError('"jsonrpc" key must be a float(able) value.')
- if version < 2:
- return False
- return True
-
-def isnotification(request):
- if 'id' not in request.keys():
- # 2.0 notification
- return True
- if request['id'] == None:
- # 1.0 notification
- return True
- return False
diff --git a/sota_demo/jsonrpclib/setup.py b/sota_demo/jsonrpclib/setup.py
deleted file mode 100755
index 72f8b35..0000000
--- a/sota_demo/jsonrpclib/setup.py
+++ /dev/null
@@ -1,29 +0,0 @@
-#!/usr/bin/env python
-"""
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-"""
-
-import distutils.core
-
-distutils.core.setup(
- name = "jsonrpclib",
- version = "0.1.3",
- packages = ["jsonrpclib"],
- author = "Josh Marshall",
- author_email = "catchjosh@gmail.com",
- url = "http://github.com/joshmarshall/jsonrpclib/",
- license = "http://www.apache.org/licenses/LICENSE-2.0",
- description = "This project is an implementation of the JSON-RPC v2.0 " +
- "specification (backwards-compatible) as a client library.",
- long_description = open("README.md").read()
-)
diff --git a/sota_demo/jsonrpclib/tests.py b/sota_demo/jsonrpclib/tests.py
deleted file mode 100644
index 3ce1009..0000000
--- a/sota_demo/jsonrpclib/tests.py
+++ /dev/null
@@ -1,456 +0,0 @@
-"""
-The tests in this file compare the request and response objects
-to the JSON-RPC 2.0 specification document, as well as testing
-several internal components of the jsonrpclib library. Run this
-module without any parameters to run the tests.
-
-Currently, this is not easily tested with a framework like
-nosetests because we spin up a daemon thread running the
-the Server, and nosetests (at least in my tests) does not
-ever "kill" the thread.
-
-If you are testing jsonrpclib and the module doesn't return to
-the command prompt after running the tests, you can hit
-"Ctrl-C" (or "Ctrl-Break" on Windows) and that should kill it.
-
-TODO:
-* Finish implementing JSON-RPC 2.0 Spec tests
-* Implement JSON-RPC 1.0 tests
-* Implement JSONClass, History, Config tests
-"""
-
-from jsonrpclib import Server, MultiCall, history, config, ProtocolError
-from jsonrpclib import jsonrpc
-from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
-from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCRequestHandler
-import socket
-import tempfile
-import unittest
-import os
-import time
-try:
- import json
-except ImportError:
- import simplejson as json
-from threading import Thread
-
-PORTS = range(8000, 8999)
-
-class TestCompatibility(unittest.TestCase):
-
- client = None
- port = None
- server = None
-
- def setUp(self):
- self.port = PORTS.pop()
- self.server = server_set_up(addr=('', self.port))
- self.client = Server('http://localhost:%d' % self.port)
-
- # v1 tests forthcoming
-
- # Version 2.0 Tests
- def test_positional(self):
- """ Positional arguments in a single call """
- result = self.client.subtract(23, 42)
- self.assertTrue(result == -19)
- result = self.client.subtract(42, 23)
- self.assertTrue(result == 19)
- request = json.loads(history.request)
- response = json.loads(history.response)
- verify_request = {
- "jsonrpc": "2.0", "method": "subtract",
- "params": [42, 23], "id": request['id']
- }
- verify_response = {
- "jsonrpc": "2.0", "result": 19, "id": request['id']
- }
- self.assertTrue(request == verify_request)
- self.assertTrue(response == verify_response)
-
- def test_named(self):
- """ Named arguments in a single call """
- result = self.client.subtract(subtrahend=23, minuend=42)
- self.assertTrue(result == 19)
- result = self.client.subtract(minuend=42, subtrahend=23)
- self.assertTrue(result == 19)
- request = json.loads(history.request)
- response = json.loads(history.response)
- verify_request = {
- "jsonrpc": "2.0", "method": "subtract",
- "params": {"subtrahend": 23, "minuend": 42},
- "id": request['id']
- }
- verify_response = {
- "jsonrpc": "2.0", "result": 19, "id": request['id']
- }
- self.assertTrue(request == verify_request)
- self.assertTrue(response == verify_response)
-
- def test_notification(self):
- """ Testing a notification (response should be null) """
- result = self.client._notify.update(1, 2, 3, 4, 5)
- self.assertTrue(result == None)
- request = json.loads(history.request)
- response = history.response
- verify_request = {
- "jsonrpc": "2.0", "method": "update", "params": [1,2,3,4,5]
- }
- verify_response = ''
- self.assertTrue(request == verify_request)
- self.assertTrue(response == verify_response)
-
- def test_non_existent_method(self):
- self.assertRaises(ProtocolError, self.client.foobar)
- request = json.loads(history.request)
- response = json.loads(history.response)
- verify_request = {
- "jsonrpc": "2.0", "method": "foobar", "id": request['id']
- }
- verify_response = {
- "jsonrpc": "2.0",
- "error":
- {"code": -32601, "message": response['error']['message']},
- "id": request['id']
- }
- self.assertTrue(request == verify_request)
- self.assertTrue(response == verify_response)
-
- def test_invalid_json(self):
- invalid_json = '{"jsonrpc": "2.0", "method": "foobar, '+ \
- '"params": "bar", "baz]'
- response = self.client._run_request(invalid_json)
- response = json.loads(history.response)
- verify_response = json.loads(
- '{"jsonrpc": "2.0", "error": {"code": -32700,'+
- ' "message": "Parse error."}, "id": null}'
- )
- verify_response['error']['message'] = response['error']['message']
- self.assertTrue(response == verify_response)
-
- def test_invalid_request(self):
- invalid_request = '{"jsonrpc": "2.0", "method": 1, "params": "bar"}'
- response = self.client._run_request(invalid_request)
- response = json.loads(history.response)
- verify_response = json.loads(
- '{"jsonrpc": "2.0", "error": {"code": -32600, '+
- '"message": "Invalid Request."}, "id": null}'
- )
- verify_response['error']['message'] = response['error']['message']
- self.assertTrue(response == verify_response)
-
- def test_batch_invalid_json(self):
- invalid_request = '[ {"jsonrpc": "2.0", "method": "sum", '+ \
- '"params": [1,2,4], "id": "1"},{"jsonrpc": "2.0", "method" ]'
- response = self.client._run_request(invalid_request)
- response = json.loads(history.response)
- verify_response = json.loads(
- '{"jsonrpc": "2.0", "error": {"code": -32700,'+
- '"message": "Parse error."}, "id": null}'
- )
- verify_response['error']['message'] = response['error']['message']
- self.assertTrue(response == verify_response)
-
- def test_empty_array(self):
- invalid_request = '[]'
- response = self.client._run_request(invalid_request)
- response = json.loads(history.response)
- verify_response = json.loads(
- '{"jsonrpc": "2.0", "error": {"code": -32600, '+
- '"message": "Invalid Request."}, "id": null}'
- )
- verify_response['error']['message'] = response['error']['message']
- self.assertTrue(response == verify_response)
-
- def test_nonempty_array(self):
- invalid_request = '[1,2]'
- request_obj = json.loads(invalid_request)
- response = self.client._run_request(invalid_request)
- response = json.loads(history.response)
- self.assertTrue(len(response) == len(request_obj))
- for resp in response:
- verify_resp = json.loads(
- '{"jsonrpc": "2.0", "error": {"code": -32600, '+
- '"message": "Invalid Request."}, "id": null}'
- )
- verify_resp['error']['message'] = resp['error']['message']
- self.assertTrue(resp == verify_resp)
-
- def test_batch(self):
- multicall = MultiCall(self.client)
- multicall.sum(1,2,4)
- multicall._notify.notify_hello(7)
- multicall.subtract(42,23)
- multicall.foo.get(name='myself')
- multicall.get_data()
- job_requests = [j.request() for j in multicall._job_list]
- job_requests.insert(3, '{"foo": "boo"}')
- json_requests = '[%s]' % ','.join(job_requests)
- requests = json.loads(json_requests)
- responses = self.client._run_request(json_requests)
-
- verify_requests = json.loads("""[
- {"jsonrpc": "2.0", "method": "sum", "params": [1,2,4], "id": "1"},
- {"jsonrpc": "2.0", "method": "notify_hello", "params": [7]},
- {"jsonrpc": "2.0", "method": "subtract", "params": [42,23], "id": "2"},
- {"foo": "boo"},
- {"jsonrpc": "2.0", "method": "foo.get", "params": {"name": "myself"}, "id": "5"},
- {"jsonrpc": "2.0", "method": "get_data", "id": "9"}
- ]""")
-
- # Thankfully, these are in order so testing is pretty simple.
- verify_responses = json.loads("""[
- {"jsonrpc": "2.0", "result": 7, "id": "1"},
- {"jsonrpc": "2.0", "result": 19, "id": "2"},
- {"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request."}, "id": null},
- {"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found."}, "id": "5"},
- {"jsonrpc": "2.0", "result": ["hello", 5], "id": "9"}
- ]""")
-
- self.assertTrue(len(requests) == len(verify_requests))
- self.assertTrue(len(responses) == len(verify_responses))
-
- responses_by_id = {}
- response_i = 0
-
- for i in range(len(requests)):
- verify_request = verify_requests[i]
- request = requests[i]
- response = None
- if request.get('method') != 'notify_hello':
- req_id = request.get('id')
- if verify_request.has_key('id'):
- verify_request['id'] = req_id
- verify_response = verify_responses[response_i]
- verify_response['id'] = req_id
- responses_by_id[req_id] = verify_response
- response_i += 1
- response = verify_response
- self.assertTrue(request == verify_request)
-
- for response in responses:
- verify_response = responses_by_id.get(response.get('id'))
- if verify_response.has_key('error'):
- verify_response['error']['message'] = \
- response['error']['message']
- self.assertTrue(response == verify_response)
-
- def test_batch_notifications(self):
- multicall = MultiCall(self.client)
- multicall._notify.notify_sum(1, 2, 4)
- multicall._notify.notify_hello(7)
- result = multicall()
- self.assertTrue(len(result) == 0)
- valid_request = json.loads(
- '[{"jsonrpc": "2.0", "method": "notify_sum", '+
- '"params": [1,2,4]},{"jsonrpc": "2.0", '+
- '"method": "notify_hello", "params": [7]}]'
- )
- request = json.loads(history.request)
- self.assertTrue(len(request) == len(valid_request))
- for i in range(len(request)):
- req = request[i]
- valid_req = valid_request[i]
- self.assertTrue(req == valid_req)
- self.assertTrue(history.response == '')
-
-class InternalTests(unittest.TestCase):
- """
- These tests verify that the client and server portions of
- jsonrpclib talk to each other properly.
- """
- client = None
- server = None
- port = None
-
- def setUp(self):
- self.port = PORTS.pop()
- self.server = server_set_up(addr=('', self.port))
-
- def get_client(self):
- return Server('http://localhost:%d' % self.port)
-
- def get_multicall_client(self):
- server = self.get_client()
- return MultiCall(server)
-
- def test_connect(self):
- client = self.get_client()
- result = client.ping()
- self.assertTrue(result)
-
- def test_single_args(self):
- client = self.get_client()
- result = client.add(5, 10)
- self.assertTrue(result == 15)
-
- def test_single_kwargs(self):
- client = self.get_client()
- result = client.add(x=5, y=10)
- self.assertTrue(result == 15)
-
- def test_single_kwargs_and_args(self):
- client = self.get_client()
- self.assertRaises(ProtocolError, client.add, (5,), {'y':10})
-
- def test_single_notify(self):
- client = self.get_client()
- result = client._notify.add(5, 10)
- self.assertTrue(result == None)
-
- def test_single_namespace(self):
- client = self.get_client()
- response = client.namespace.sum(1,2,4)
- request = json.loads(history.request)
- response = json.loads(history.response)
- verify_request = {
- "jsonrpc": "2.0", "params": [1, 2, 4],
- "id": "5", "method": "namespace.sum"
- }
- verify_response = {
- "jsonrpc": "2.0", "result": 7, "id": "5"
- }
- verify_request['id'] = request['id']
- verify_response['id'] = request['id']
- self.assertTrue(verify_request == request)
- self.assertTrue(verify_response == response)
-
- def test_multicall_success(self):
- multicall = self.get_multicall_client()
- multicall.ping()
- multicall.add(5, 10)
- multicall.namespace.sum([5, 10, 15])
- correct = [True, 15, 30]
- i = 0
- for result in multicall():
- self.assertTrue(result == correct[i])
- i += 1
-
- def test_multicall_success(self):
- multicall = self.get_multicall_client()
- for i in range(3):
- multicall.add(5, i)
- result = multicall()
- self.assertTrue(result[2] == 7)
-
- def test_multicall_failure(self):
- multicall = self.get_multicall_client()
- multicall.ping()
- multicall.add(x=5, y=10, z=10)
- raises = [None, ProtocolError]
- result = multicall()
- for i in range(2):
- if not raises[i]:
- result[i]
- else:
- def func():
- return result[i]
- self.assertRaises(raises[i], func)
-
-
-if jsonrpc.USE_UNIX_SOCKETS:
- # We won't do these tests unless Unix Sockets are supported
-
- class UnixSocketInternalTests(InternalTests):
- """
- These tests run the same internal communication tests,
- but over a Unix socket instead of a TCP socket.
- """
- def setUp(self):
- suffix = "%d.sock" % PORTS.pop()
-
- # Open to safer, alternative processes
- # for getting a temp file name...
- temp = tempfile.NamedTemporaryFile(
- suffix=suffix
- )
- self.port = temp.name
- temp.close()
-
- self.server = server_set_up(
- addr=self.port,
- address_family=socket.AF_UNIX
- )
-
- def get_client(self):
- return Server('unix:/%s' % self.port)
-
- def tearDown(self):
- """ Removes the tempory socket file """
- os.unlink(self.port)
-
-class UnixSocketErrorTests(unittest.TestCase):
- """
- Simply tests that the proper exceptions fire if
- Unix sockets are attempted to be used on a platform
- that doesn't support them.
- """
-
- def setUp(self):
- self.original_value = jsonrpc.USE_UNIX_SOCKETS
- if (jsonrpc.USE_UNIX_SOCKETS):
- jsonrpc.USE_UNIX_SOCKETS = False
-
- def test_client(self):
- address = "unix://shouldnt/work.sock"
- self.assertRaises(
- jsonrpc.UnixSocketMissing,
- Server,
- address
- )
-
- def tearDown(self):
- jsonrpc.USE_UNIX_SOCKETS = self.original_value
-
-
-""" Test Methods """
-def subtract(minuend, subtrahend):
- """ Using the keywords from the JSON-RPC v2 doc """
- return minuend-subtrahend
-
-def add(x, y):
- return x + y
-
-def update(*args):
- return args
-
-def summation(*args):
- return sum(args)
-
-def notify_hello(*args):
- return args
-
-def get_data():
- return ['hello', 5]
-
-def ping():
- return True
-
-def server_set_up(addr, address_family=socket.AF_INET):
- # Not sure this is a good idea to spin up a new server thread
- # for each test... but it seems to work fine.
- def log_request(self, *args, **kwargs):
- """ Making the server output 'quiet' """
- pass
- SimpleJSONRPCRequestHandler.log_request = log_request
- server = SimpleJSONRPCServer(addr, address_family=address_family)
- server.register_function(summation, 'sum')
- server.register_function(summation, 'notify_sum')
- server.register_function(notify_hello)
- server.register_function(subtract)
- server.register_function(update)
- server.register_function(get_data)
- server.register_function(add)
- server.register_function(ping)
- server.register_function(summation, 'namespace.sum')
- server_proc = Thread(target=server.serve_forever)
- server_proc.daemon = True
- server_proc.start()
- return server_proc
-
-if __name__ == '__main__':
- print "==============================================================="
- print " NOTE: There may be threading exceptions after tests finish. "
- print "==============================================================="
- time.sleep(2)
- unittest.main()