Index: src/gnuboat/common/bin/gnuboat-log-uploader
===================================================================
--- src/gnuboat/common/bin/gnuboat-log-uploader	(revision ac05b5229e4ec2aa54fb04665291f847a30b106e)
+++ src/gnuboat/common/bin/gnuboat-log-uploader	(revision 48dcf7728b06c742b95055a29133f0782eefbcdc)
@@ -21,6 +21,14 @@
 import sys
 import json
-import requests
+import getpass
 import argparse
+from urllib3.exceptions import RequestError
+
+from gnuboat.mapservice_client.configuration import Configuration as MsConfiguration
+from gnuboat.mapservice_client.api_client import ApiClient as MsApiClient
+from gnuboat.mapservice_client.exceptions import ApiException as MsApiException
+from gnuboat.mapservice_client.api.logs_api import LogsApi as MsLogsApi
+from gnuboat.mapservice_client.models.log_creation import LogCreation as MsLogCreation
+from gnuboat.mapservice_client.api.devices_api import DevicesApi as MsDevicesApi
 
 
@@ -63,52 +71,167 @@
 
 
-def header(api_key):
-    return {
-        'X-API-KEY': api_key
-        #	'Content-type': 'multipart/form-data'
-    }
-
-
-def create_log(log, url, api_key):
-    response = requests.post(
-        url, json=log.log_creation(), headers=header(api_key)
-    )
-
-    if response.status_code != 200:
-        print(
-            'ERROR: Could not create LogMetaData for logfile {}'.format(
-                log.logfile
+def mapservice_configuration(username, password, api_key, base_url = None):
+    configuration = MsConfiguration()
+    if base_url is not None:
+        configuration.host = base_url
+    if api_key:
+        configuration.api_key['X-API-KEY'] = api_key
+    else:
+        configuration.username = username
+        configuration.password = password
+    return configuration
+
+
+def handle_mapservice_error(exception, error_message):
+    if isinstance(exception, MsApiException):
+        response_body = json.loads(exception.body)
+        print(error_message)
+        print('  Status code: {}'.format(response_body['status']))
+        print('  Details:     {}'.format(response_body['detail']))
+    elif isinstance(exception, RequestError):
+        print('Could not connect to server {}:{}/{}'.format(
+            exception.pool.host, exception.pool.port, exception.url
+        ))
+    else:
+        print('An unhandled error occured: {}'.format(repr(exception)))
+    sys.exit(5)
+
+
+def display_devices(configuration):
+    with MsApiClient(configuration) as api_client:
+        try:
+            devices = MsDevicesApi(api_client).devices_get()
+        except Exception as e:
+            handle_mapservice_error(e, 'ERROR: Could not get devices')
+
+    if len(devices) < 0:
+        print('You have no devices at {}').format(configuration.host)
+        return
+
+    print('Id     Name                          Sensor Depth Comment')
+    for device in devices:
+        print('{:6d} {:30s} {:11f} {}'.format(
+            device.device_id, device.name,
+            device.sensor_depth, device.comment
+        ))
+
+def create_log(log, configuration):
+    with MsApiClient(configuration) as api_client:
+        try:
+            log_metadata = MsLogsApi(api_client).logs_log_create(log_creation = log.log_creation())
+        except Exception as e:
+            error_message = ('ERROR: Could not create Log entry for '
+                             'logfile {}').format(log.logfile)
+            handle_mapservice_error(e, error_message)
+    return log_metadata.log_id
+
+
+def upload_log(log_id, log, configuration):
+    with open(log.logfile, 'rb') as logfilehandle:
+        file_content = logfilehandle.read()
+    with MsApiClient(configuration) as api_client:
+        try:
+            log_metadata = MsLogsApi(api_client).logs_log_upload(log_id = log_id, body = file_content)
+        except MsApiException as e:
+            handle_mapservice_error(e, log)
+
+
+def load_and_upload_logs(input_file_path, configuration):
+    logs_checked = []
+    print('Checking input from {}'.format(input_file_path))
+    with open(input_file_path, 'r') as input_file:
+        logs = json.load(input_file)
+        for log in logs:
+            if not 'water' in log:
+                print('ERROR: No water in log {}'.format(json.dumps(log)))
+                sys.exit(4)
+            water_id = to_int(log['water'])
+            if not water_id:
+                print(
+                    'ERROR: Could not convert water to int {}'.format(
+                        log['water']
+                    )
+                )
+                sys.exit(4)
+
+            if not 'gauge' in log:
+                print('ERROR: No gauge in log {}'.format(json.dumps(log)))
+                sys.exit(4)
+            gauge_id = to_int(log['gauge'])
+            if not gauge_id:
+                print(
+                    'ERROR: Could not convert gauge to int {}'.format(
+                        log['gauge']
+                    )
+                )
+                sys.exit(4)
+
+            if not 'device' in log:
+                print('ERROR: No device in log {}'.format(json.dumps(log)))
+                sys.exit(4)
+            device_id = to_int(log['device'])
+            if not device_id:
+                print(
+                    'ERROR: Could not convert device to int {}'.format(
+                        log['device']
+                    )
+                )
+                sys.exit(4)
+
+            if not 'gaugeHeight' in log:
+                print(
+                    'ERROR: No gaugeHeight in log {}'.format(json.dumps(log))
+                )
+                sys.exit(4)
+            gauge_height = to_float(log['gaugeHeight'])
+            if not gauge_height:
+                print(
+                    'ERROR: Could not convert gaugeHeight to float {}'.format(
+                        log['gaugeHeight']
+                    )
+                )
+                sys.exit(4)
+
+            if not 'file' in log:
+                print('ERROR: No file in log {}'.format(json.dumps(log)))
+                sys.exit(4)
+
+            comment = ''
+            if 'comment' in log:
+                comment = log['comment']
+
+            logfile = os.path.join(os.path.dirname(__file__), log['file'])
+            if not os.path.exists(logfile):
+                logfile_rel = os.path.join(
+                    os.path.dirname(input_file_path), log['file']
+                )
+                if not os.path.exists(logfile_rel):
+                    print(
+                        'ERROR: Logfile not found at {} or {}'.format(
+                            logfile, logfile_rel
+                        )
+                    )
+                    sys.exit(4)
+                else:
+                    logfile = logfile_rel
+            logs_checked.append(
+                Log(
+                    water_id, device_id, gauge_id, gauge_height, comment,
+                    logfile
+                )
             )
-        )
-        print('  Response status code: {}'.format(response.status_code))
-        print('  Response:             \n{}'.format(response.text))
-        print('  Request headers:      {}'.format(response.request.headers))
-        print('  Request body:         {}'.format(response.request.body))
-        sys.exit(5)
-
-    data = response.json()
-    if not 'logId' in data:
-        print('ERROR: No log id returned')
-        sys.exit(6)
-    return data["logId"]
-
-
-def upload_log(log_id, log, url, api_key):
-    fileContent = open(log.logfile, 'rb')
-    headers = header(api_key)
-    headers["Accept"] = "application/json"
-    response = requests.post(
-        "{}/{}".format(url, log_id), data=fileContent, headers=headers
-    )
-    if response.status_code != 200:
-        print('ERROR: Could not upload log for logfile {}'.format(log.logfile))
-        print("Response status code: {}".format(response.status_code))
-        print("Response:             \n{}".format(response.text))
-        sys.exit(7)
+
+    print('Uploading {} logs'.format(len(logs_checked)))
+    for log in logs_checked:
+        log_id = create_log(log, configuration)
+        upload_log(log_id, log, configuration)
+        print(' Finished {}'.format(log.logfile))
 
 
 def main(argv):
     input_file_path = None
-    url = None
+    base_url = None
+    username = None
+    password = None
     api_key = None
 
@@ -120,13 +243,15 @@
         metavar='input_file_path',
         type=str,
+        nargs='?',
         help=
         'JSON file with water, gauge, device, logfiles and correction data to be processed'
     )
     parser.add_argument(
-        '-s',
-        '--server',
-        dest='server',
+        '-b',
+        '--base',
+        dest='base_url',
         type=str,
-        help='Server host and port to upload the logsfiles to'
+        default=MsConfiguration().host,
+        help='Server base url to upload the logsfiles to'
     )
     parser.add_argument(
@@ -137,5 +262,37 @@
         help='API Key for authorisation'
     )
+    parser.add_argument(
+        '-d',
+        '--devices',
+        dest='devices',
+        action='store_true',
+        help='Display a list of your devices on the server'
+    )
     arguments = parser.parse_args(argv)
+
+
+    # handle base parameter
+    if arguments.base_url is not None:
+        if arguments.base_url.endswith('/'):
+            base_url = arguments.base_url[:-1]
+        else:
+            base_url = arguments.base_url
+
+    if arguments.api_key is None:
+        username = input('Username: ')
+        if not username:
+            print('ERROR: No username given')
+            sys.exit(2)
+        password = getpass.getpass()
+        if not password:
+            print('ERROR: No password given')
+            sys.exit(2)
+    else:
+        api_key = arguments.api_key
+    configuration = mapservice_configuration(username, password, api_key, base_url)
+
+    if arguments.devices:
+        display_devices(configuration)
+        sys.exit(0)
 
     if arguments.input_file is None:
@@ -152,105 +309,5 @@
         input_file_path = arguments.input_file
 
-    if arguments.server is None:
-        print('ERROR: No server specified')
-        sys.exit(2)
-    else:
-        url = 'http://{}/mapservice/v1/logs'.format(arguments.server)
-
-    if arguments.api_key is None:
-        print('ERROR: No API key specified')
-        sys.exit(2)
-    else:
-        api_key = arguments.api_key
-
-    logs_checked = []
-    print('Checking input from {}'.format(input_file_path))
-    with open(input_file_path, 'r') as input_file:
-        logs = json.load(input_file)
-        for log in logs:
-            if not 'water' in log:
-                print('ERROR: No water in log {}'.format(json.dumps(log)))
-                sys.exit(4)
-            water_id = to_int(log['water'])
-            if not water_id:
-                print(
-                    'ERROR: Could not convert water to int {}'.format(
-                        log['water']
-                    )
-                )
-                sys.exit(4)
-
-            if not 'gauge' in log:
-                print('ERROR: No gauge in log {}'.format(json.dumps(log)))
-                sys.exit(4)
-            gauge_id = to_int(log['gauge'])
-            if not gauge_id:
-                print(
-                    'ERROR: Could not convert gauge to int {}'.format(
-                        log['gauge']
-                    )
-                )
-                sys.exit(4)
-
-            if not 'device' in log:
-                print('ERROR: No device in log {}'.format(json.dumps(log)))
-                sys.exit(4)
-            device_id = to_int(log['device'])
-            if not device_id:
-                print(
-                    'ERROR: Could not convert device to int {}'.format(
-                        log['device']
-                    )
-                )
-                sys.exit(4)
-
-            if not 'gaugeHeight' in log:
-                print(
-                    'ERROR: No gaugeHeight in log {}'.format(json.dumps(log))
-                )
-                sys.exit(4)
-            gauge_height = to_float(log['gaugeHeight'])
-            if not gauge_height:
-                print(
-                    'ERROR: Could not convert gaugeHeight to float {}'.format(
-                        log['gaugeHeight']
-                    )
-                )
-                sys.exit(4)
-
-            if not 'file' in log:
-                print('ERROR: No file in log {}'.format(json.dumps(log)))
-                sys.exit(4)
-
-            comment = ''
-            if 'comment' in log:
-                comment = log['comment']
-
-            logfile = os.path.join(os.path.dirname(__file__), log['file'])
-            if not os.path.exists(logfile):
-                logfile_rel = os.path.join(
-                    os.path.dirname(input_file_path), log['file']
-                )
-                if not os.path.exists(logfile_rel):
-                    print(
-                        'ERROR: Logfile not found at {} or {}'.format(
-                            logfile, logfile_rel
-                        )
-                    )
-                    sys.exit(4)
-                else:
-                    logfile = logfile_rel
-            logs_checked.append(
-                Log(
-                    water_id, device_id, gauge_id, gauge_height, comment,
-                    logfile
-                )
-            )
-
-    print('Uploading {} logs'.format(len(logs_checked)))
-    for log in logs_checked:
-        log_id = create_log(log, url, api_key)
-        upload_log(log_id, log, url, api_key)
-        print(' Finished {}'.format(log.logfile))
+    load_and_upload_logs(input_file_path, configuration)
 
 
