From 2ec0e10f0484c666b096bd7115910d90c5e8e537 Mon Sep 17 00:00:00 2001
From: Maximilian Betz <Maximilian.Betz@awi.de>
Date: Mon, 21 Mar 2022 13:43:52 +0100
Subject: [PATCH] improved exception handling

---
 lib/datamodel.dart       |   6 +
 lib/sensorconnector.dart |   6 +-
 lib/viewevents.dart      | 334 ++++++++++++++++++++-------------------
 3 files changed, 184 insertions(+), 162 deletions(-)

diff --git a/lib/datamodel.dart b/lib/datamodel.dart
index d81ac2e..422526a 100644
--- a/lib/datamodel.dart
+++ b/lib/datamodel.dart
@@ -1,4 +1,5 @@
 
+
 class Collection {
   int id;
   String description;
@@ -41,6 +42,7 @@ class Device{
   }
 }
 
+
 class Event{
   int id;  // Device URN id
   String urn;
@@ -138,6 +140,7 @@ class Event{
   }
 }
 
+
 class EventType{
   int id;
   String name;
@@ -152,6 +155,7 @@ class EventType{
   }
 }
 
+
 class SensorLogin{
   String mail;
   String password;
@@ -220,6 +224,7 @@ abstract class ConfigurationStoreBase {
   }
 }
 
+
 class ConfigurationStoreInstance extends ConfigurationStoreBase {
   static final ConfigurationStoreInstance _instance = ConfigurationStoreInstance
       ._internal();
@@ -251,6 +256,7 @@ abstract class EventStoreBase{
   }
 }
 
+
 class EventStoreInstance extends EventStoreBase {
   static final EventStoreInstance _instance = EventStoreInstance._internal();
 
diff --git a/lib/sensorconnector.dart b/lib/sensorconnector.dart
index 41fb7d7..f872dee 100644
--- a/lib/sensorconnector.dart
+++ b/lib/sensorconnector.dart
@@ -34,10 +34,12 @@ class SensorConnector {
       debugPrint('Login success. Token: ' + token!.toString());
 
     } else {
-      throw Exception('Failed to login. '
-          'Header: ' + response.headers.toString() +
+      debugPrint('Failed to login'
+      'Header: ' + response.headers.toString() +
           ' StatusCode: ' +response.statusCode.toString() +
           ' Body: ' +response.body.toString());
+
+      throw Exception('Failed to login');
     }
     return token;
   }
diff --git a/lib/viewevents.dart b/lib/viewevents.dart
index 10fec9e..57cf27e 100644
--- a/lib/viewevents.dart
+++ b/lib/viewevents.dart
@@ -23,40 +23,48 @@ class _ViewEvents extends State<ViewEvents> {
     super.initState();
   }
 
-  Future<bool> syncEvents() async {
-    //final EventStoreInstance events = EventStoreInstance();
+  Future<void> syncEvents() async {
     final ConfigurationStoreInstance configuration = ConfigurationStoreInstance();
     SensorConnector connection = SensorConnector();
-    int _synccounter = 0;  //For displaying progress during event upload
+    int syncCounter = _events.getPendingEventCount();; //For displaying progress during event upload
 
-    String? token = await connection.getAuthToken(configuration.loginInformation.mail,
-        configuration.loginInformation.password);
+    if(syncCounter > 0) {
+      try {
+        String? token = await connection.getAuthToken(
+            configuration.loginInformation.mail,
+            configuration.loginInformation.password);
 
-    if (token != null) {
-      _synccounter = _events.getPendingEventCount();
-      debugPrint('Number of Events: ' + _events.events.length.toString());
-      debugPrint('Number of Pending Events: ' + _synccounter.toString());
-      var index = 0;
-      for (var event in _events.events) {
-        if (event.status == 'PENDING') {
-          debugPrint('Idx: ' + index.toString() + ' ' +
-              event.toSensorJson().toString());
-          index++;
-          if (await connection.putEvent(event, token) == true){
-            //Event has been posted to Sensor.
-            _synccounter--;
-            debugPrint('put success, remaining events: ' + _synccounter.toString());
-            event.status = 'EXPORTED'; //Update event status so that it is only exported once.
-            setState(() {});
-          }else{
-            _sync_status = 'export failed: ' + event.urn;
+        if (token != null) {
+          debugPrint('Number of Events: ' + _events.events.length.toString());
+          debugPrint('Number of Pending Events: ' + syncCounter.toString());
+          var index = 0;
+          for (var event in _events.events) {
+            if (event.status == 'PENDING') {
+              debugPrint('Idx: ' + index.toString() + ' ' +
+                  event.toSensorJson().toString());
+              index++;
+              if (await connection.putEvent(event, token) == true) {
+                //Event has been posted to Sensor.
+                syncCounter--;
+                debugPrint(
+                    'put success, remaining events: ' + syncCounter.toString());
+                event.status = 'EXPORTED'; //Update event export only once
+                setState(() {});
+              } else {
+                throw Exception('Sync for ' + event.urn + 'failed');
+              }
+            }
           }
+          _sync_status = 'export success';
         }
+      } catch (e) {
+        debugPrint('Exception: $e');
+        _sync_status = '$e';
+        setState(() {});
       }
-      _sync_status = 'export success';
-      return true;
+    }else{
+      debugPrint('Nothing to export');
     }
-    return false;
   }
 
   @override
@@ -67,168 +75,174 @@ class _ViewEvents extends State<ViewEvents> {
         title: const Text("View Added Events"),
       ),
       body: Container(
-      margin: const EdgeInsets.symmetric(horizontal: 5.0),
-      child:
-      SingleChildScrollView(
-        scrollDirection: Axis.horizontal,
-        child: SingleChildScrollView(
-          scrollDirection: Axis.vertical,
-          child: DataTable(
+        margin: const EdgeInsets.symmetric(horizontal: 5.0),
+        child:
+        SingleChildScrollView(
+          scrollDirection: Axis.horizontal,
+          child: SingleChildScrollView(
+            scrollDirection: Axis.vertical,
+            child: DataTable(
 
-            columns: const <DataColumn>[
-              DataColumn(
-                label: Text(
-                  'Id',
-                  style: TextStyle(fontStyle: FontStyle.italic),
+              columns: const <DataColumn>[
+                DataColumn(
+                  label: Text(
+                    'Id',
+                    style: TextStyle(fontStyle: FontStyle.italic),
+                  ),
                 ),
-              ),
-              DataColumn(
-                label: Text(
-                  'URN',
-                  style: TextStyle(fontStyle: FontStyle.italic),
+                DataColumn(
+                  label: Text(
+                    'URN',
+                    style: TextStyle(fontStyle: FontStyle.italic),
+                  ),
                 ),
-              ),
-              DataColumn(
-                label: Text(
-                  'Label',
-                  style: TextStyle(fontStyle: FontStyle.italic),
+                DataColumn(
+                  label: Text(
+                    'Label',
+                    style: TextStyle(fontStyle: FontStyle.italic),
+                  ),
                 ),
-              ),
-              DataColumn(
-                label: Text(
-                  'Type',
-                  style: TextStyle(fontStyle: FontStyle.italic),
+                DataColumn(
+                  label: Text(
+                    'Type',
+                    style: TextStyle(fontStyle: FontStyle.italic),
+                  ),
                 ),
-              ),
-              DataColumn(
-                label: Text(
-                  'Description',
-                  style: TextStyle(fontStyle: FontStyle.italic),
+                DataColumn(
+                  label: Text(
+                    'Description',
+                    style: TextStyle(fontStyle: FontStyle.italic),
+                  ),
                 ),
-              ),
-              DataColumn(
-                label: Text(
-                  'StartDate',
-                  style: TextStyle(fontStyle: FontStyle.italic),
+                DataColumn(
+                  label: Text(
+                    'StartDate',
+                    style: TextStyle(fontStyle: FontStyle.italic),
+                  ),
                 ),
-              ),
-              DataColumn(
-                label: Text(
-                  'EndDate',
-                  style: TextStyle(fontStyle: FontStyle.italic),
+                DataColumn(
+                  label: Text(
+                    'EndDate',
+                    style: TextStyle(fontStyle: FontStyle.italic),
+                  ),
                 ),
-              ),
-              DataColumn(
-                label: Text(
-                  'Latitude',
-                  style: TextStyle(fontStyle: FontStyle.italic),
+                DataColumn(
+                  label: Text(
+                    'Latitude',
+                    style: TextStyle(fontStyle: FontStyle.italic),
+                  ),
                 ),
-              ),
-              DataColumn(
-                label: Text(
-                  'Longitude',
-                  style: TextStyle(fontStyle: FontStyle.italic),
+                DataColumn(
+                  label: Text(
+                    'Longitude',
+                    style: TextStyle(fontStyle: FontStyle.italic),
+                  ),
                 ),
-              ),
-              DataColumn(
-                label: Text(
-                  'Elevation',
-                  style: TextStyle(fontStyle: FontStyle.italic),
+                DataColumn(
+                  label: Text(
+                    'Elevation',
+                    style: TextStyle(fontStyle: FontStyle.italic),
+                  ),
                 ),
-              ),
-              DataColumn(
-                label: Text(
-                  'Status',
-                  style: TextStyle(fontStyle: FontStyle.italic),
+                DataColumn(
+                  label: Text(
+                    'Status',
+                    style: TextStyle(fontStyle: FontStyle.italic),
+                  ),
                 ),
-              ),
-            ],
-            rows: <DataRow>[
-              for (var event in _events.events)
-                DataRow(
-                  cells: <DataCell>[
-                    DataCell(Text(event.id.toString())),
-                    DataCell(Text(event.urn)),
-                    DataCell(
-                      TextFormField(
-                        readOnly: true,
-                        initialValue: event.label,
-                        onFieldSubmitted: (val) {
-                          event.label = val; //Update Database
-                        },
+              ],
+              rows: <DataRow>[
+                for (var event in _events.events)
+                  DataRow(
+                    cells: <DataCell>[
+                      DataCell(Text(event.id.toString())),
+                      DataCell(Text(event.urn)),
+                      DataCell(
+                        TextFormField(
+                          readOnly: true,
+                          initialValue: event.label,
+                          onFieldSubmitted: (val) {
+                            event.label = val; //Update Database
+                          },
+                        ),
                       ),
-                    ),
-                    DataCell(Text(event.type)),
-                    DataCell(
-                      TextFormField(
-                        readOnly: true,
-                        initialValue: event.description,
-                        onFieldSubmitted: (val) {
-                          event.description = val; //Update Database
-                        },
+                      DataCell(Text(event.type)),
+                      DataCell(
+                        TextFormField(
+                          readOnly: true,
+                          initialValue: event.description,
+                          onFieldSubmitted: (val) {
+                            event.description = val; //Update Database
+                          },
+                        ),
                       ),
-                    ),
-                    DataCell(Text(event.startDate)),
-                    DataCell(Text(event.endDate)),
-                    DataCell(
-                      TextFormField(
-                        readOnly: true,
-                        initialValue: event.latitude,
-                        onFieldSubmitted: (val) {
-                          event.latitude = val; //Update Database
-                        },
+                      DataCell(Text(event.startDate)),
+                      DataCell(Text(event.endDate)),
+                      DataCell(
+                        TextFormField(
+                          readOnly: true,
+                          initialValue: event.latitude,
+                          onFieldSubmitted: (val) {
+                            event.latitude = val; //Update Database
+                          },
+                        ),
                       ),
-                    ),
-                    DataCell(
-                      TextFormField(
-                        readOnly: true,
-                        initialValue: event.longitude,
-                        onFieldSubmitted: (val) {
-                          event.longitude = val; //Update Database
-                        },
+                      DataCell(
+                        TextFormField(
+                          readOnly: true,
+                          initialValue: event.longitude,
+                          onFieldSubmitted: (val) {
+                            event.longitude = val; //Update Database
+                          },
+                        ),
                       ),
-                    ),
-                    DataCell(
-                      TextFormField(
-                        readOnly: true,
-                        initialValue: event.elevation,
-                        onFieldSubmitted: (val) {
-                          event.elevation = val; //Update Database
-                        },
+                      DataCell(
+                        TextFormField(
+                          readOnly: true,
+                          initialValue: event.elevation,
+                          onFieldSubmitted: (val) {
+                            event.elevation = val; //Update Database
+                          },
+                        ),
                       ),
-                    ),
-                    DataCell(
-                      TextFormField(
-                        readOnly: true,
-                        controller: TextEditingController(  //Required to update field here
+                      DataCell(
+                        TextFormField(
+                          readOnly: true,
+                          controller: TextEditingController(  //Required to update field here
                             text: event.status,
+                          ),
+                          onFieldSubmitted: (val) {
+                            event.status = val; //Update Database
+                          },
                         ),
-                        onFieldSubmitted: (val) {
-                          event.status = val; //Update Database
-                        },
                       ),
-                    ),
-                  ],
-                ),
-            ],
+                    ],
+                  ),
+              ],
+            ),
           ),
         ),
       ),
-      ),
       bottomNavigationBar: Row(
-        mainAxisAlignment: MainAxisAlignment.spaceBetween,
+        mainAxisAlignment: MainAxisAlignment.end,
         children: [
           const SizedBox(width: 10),
           Text(_sync_status),
-          FloatingActionButton.extended(
-            heroTag: null,
-            tooltip: 'Upload Events',
-            icon: null,
-            label: const Text('Sync'),
-            onPressed: () {
-              syncEvents();
-            },
+          const SizedBox(width: 50),
+          Container(
+            margin: const EdgeInsets.symmetric(vertical: 10.0),
+            child:
+            FloatingActionButton.extended(
+              heroTag: null,
+              tooltip: 'Upload Events',
+              icon: null,
+              label: const Text('Sync'),
+              onPressed: () {
+                syncEvents();
+              },
+            ),
           ),
+          const SizedBox(width: 10.0),
         ],
       ),
     );
-- 
GitLab