Skip to content
Snippets Groups Projects
Commit 30bca1b0 authored by Maximilian Betz's avatar Maximilian Betz
Browse files

improved exception handling

parent cf82a484
No related branches found
No related tags found
No related merge requests found
......@@ -55,12 +55,11 @@ class _MyHomePageState extends State<Configuration> {
Future<void> updateConfiguration() async {
final EventStoreInstance event = EventStoreInstance();
String token = '';
List<Device> devices = [];
try{
token = await connector.getAuthToken(configuration.loginInformation.mail, configuration.loginInformation.password);
devices = await connector.fetchCollectionDevices(configuration.currentCollection.id);
configuration.devices = await futureDevices; //already fetched just use the data.
configuration.eventTypes = await futureEventTypes; //already fetched just use the data.
event.currentEvent.id = 0;
event.currentEvent.urnId = configuration.devices[0].id; //TODO: fix if devices are an empty list.
......@@ -69,6 +68,7 @@ class _MyHomePageState extends State<Configuration> {
event.currentEvent.label = '';
event.currentEvent.type = configuration.eventTypes[0].name;
var date = DateTime.now().toUtc();
var isoDate = date.toIso8601String();
event.currentEvent.startDate = isoDate;
......@@ -86,10 +86,6 @@ class _MyHomePageState extends State<Configuration> {
_status = 'Login success & configuration stored';
setState(() {});
} on SocketException catch (e) {
debugPrint('Exception: $e');
_status = 'No connection';
setState(() {});
} catch (e) {
debugPrint('Exception: $e');
_status = '$e';
......@@ -151,8 +147,8 @@ class _MyHomePageState extends State<Configuration> {
initialValue: configuration.loginInformation.mail,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Sensor E-Mail',
hintText: 'User for writing events',
labelText: 'E-Mail',
hintText: '',
),
onChanged: (value) {
configuration.loginInformation.mail = value;
......@@ -163,12 +159,13 @@ class _MyHomePageState extends State<Configuration> {
),
const SizedBox(height: 15.0),
TextFormField(
obscureText: true,
autofocus: false,
initialValue: configuration.loginInformation.password,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Sensor Password',
hintText: 'Password for writing events',
labelText: 'Password',
hintText: '',
),
onChanged: (value){
configuration.loginInformation.password = value;
......@@ -193,6 +190,7 @@ class _MyHomePageState extends State<Configuration> {
if(configuration.currentCollection.id == -1){
configuration.currentCollection = configuration.collections[0];
futureDevices = connector.fetchCollectionDevices(configuration.currentCollection.id);
//TODO: shall this be removed here and just done at confirmation.?
}
return DropdownButtonFormField(
......@@ -276,5 +274,5 @@ class _MyHomePageState extends State<Configuration> {
//TODO: write configuration on app dispose!
//TODO: display mission internet connection properly.
//TODO: add label prefix with appended upcounting number.
//TODO: grey out update button if nothing has changed. ?
\ No newline at end of file
import 'dart:convert';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;
import 'datamodel.dart';
......@@ -21,116 +22,143 @@ class SensorConnector {
};
String encodedBody = body.keys.map((key) => "$key=${body[key]}").join("&");
final response = await http.post(Uri.parse(url),
body: encodedBody,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
encoding: Encoding.getByName("utf-8")
);
if (response.statusCode == 200) {
token = response.headers['set-cookie']?.split(';')[0];
debugPrint('Login success. Token: ' + token!.toString());
} else {
debugPrint('Failed to login'
'Header: ' + response.headers.toString() +
' StatusCode: ' +response.statusCode.toString() +
' Body: ' +response.body.toString());
throw Exception('Failed to login');
try {
final response = await http.post(Uri.parse(url),
body: encodedBody,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
encoding: Encoding.getByName("utf-8")
);
if (response.statusCode == 200) {
token = response.headers['set-cookie']?.split(';')[0];
debugPrint('Login success. Token: ' + token!.toString());
return token;
}
else {
debugPrint('Failed to login'
'Header: ' + response.headers.toString() +
' StatusCode: ' + response.statusCode.toString() +
' Body: ' + response.body.toString());
throw Exception('Failed to login');
}
} on SocketException catch (e){
throw Exception('No connection');
}catch (e){
rethrow;
}
return token;
}
Future<List<Collection>> fetchCollections() async {
String url = baseUrl + collectionsUrl;
List<Collection> collectionList = [];
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
collectionList = (json.decode(response.body) as List)
.map((i) => Collection.fromJson(i))
.toList();
debugPrint("Fetching Collections Success: " + collectionList.toString());
} else {
throw Exception('Failed to fetch Collections. '
'Header: ' + response.headers.toString() +
' StatusCode: ' +response.statusCode.toString() +
' Body: ' +response.body.toString());
try{
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
collectionList = (json.decode(response.body) as List)
.map((i) => Collection.fromJson(i))
.toList();
debugPrint("Fetching Collections Success: " + collectionList.toString());
return collectionList;
} else {
throw Exception('Failed to fetch Collections. '
'Header: ' + response.headers.toString() +
' StatusCode: ' +response.statusCode.toString() +
' Body: ' +response.body.toString());
}
} on SocketException catch (e){
throw Exception('No connection');
}catch (e){
rethrow;
}
return collectionList;
}
Future<List<EventType>> fetchEventTypes() async {
String url = baseUrl + eventTypesUrl;
List<EventType> eventTypeList = [];
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
//eventTypeList = (json.decode(response.body) as List)
// .map((i) => EventType.fromSensorJson(i))
// .toList();
List<dynamic> data = json.decode(response.body);
for (var entry in data) {
eventTypeList.add(EventType.fromSensorJson(entry));
try{
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
List<dynamic> data = json.decode(response.body);
for (var entry in data) {
eventTypeList.add(EventType.fromSensorJson(entry));
}
debugPrint("Fetching Event Types Success: " + eventTypeList.toString());
return eventTypeList;
} else{
throw Exception('Failed to fetch event types. '
'Header: ' + response.headers.toString() +
' StatusCode: ' +response.statusCode.toString() +
' Body: ' +response.body.toString());
}
debugPrint("Fetching Event Types Success: " + eventTypeList.toString());
} else{
throw Exception('Failed to fetch event types. '
'Header: ' + response.headers.toString() +
' StatusCode: ' +response.statusCode.toString() +
' Body: ' +response.body.toString());
} on SocketException catch (e){
throw Exception('No connection');
}catch (e){
rethrow;
}
return eventTypeList;
}
Future<List<Device>> fetchCollectionDevices(int collectionId) async {
String url = baseUrl + collectionItemsUrl + collectionId.toString();
List<Device> collectionDevices = [];
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
List<dynamic> data = json.decode(response.body);
for (var entry in data) {
collectionDevices.add(Device.fromJson(entry));
try{
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
List<dynamic> data = json.decode(response.body);
for (var entry in data) {
collectionDevices.add(Device.fromJson(entry));
}
debugPrint("Fetching Collection Devices Success: " + collectionDevices.toString());
return collectionDevices;
} else {
throw Exception('Failed to load Collection Devices. '
'Header: ' + response.headers.toString() +
' StatusCode: ' +response.statusCode.toString() +
' Body: ' +response.body.toString());
}
debugPrint("Fetching Collection Devices Success: " + collectionDevices.toString());
} else {
throw Exception('Failed to load Collection Devices. '
'Header: ' + response.headers.toString() +
' StatusCode: ' +response.statusCode.toString() +
' Body: ' +response.body.toString());
} on SocketException catch (e){
throw Exception('No connection');
}catch (e){
rethrow;
}
return collectionDevices;
}
Future<bool> putEvent(Event event, String authToken) async {
// Create url with corresponding device id:
String url = baseUrl + putEventUrl + event.urnId.toString() + '?createVersion=false';
final response = await http.put(Uri.parse(url),
headers: {
"Content-Type": "application/json",
"Cookie": authToken
},
body: event.toSensorJson().toString(),
encoding: Encoding.getByName("utf-8"),
);
if (response.statusCode == 201) {
return true;
} else {
throw Exception('Failed to put event. '
'Header: ' + response.headers.toString() +
' StatusCode: ' +response.statusCode.toString() +
' Body: ' +response.body.toString());
return false;
try{
final response = await http.put(Uri.parse(url),
headers: {
"Content-Type": "application/json",
"Cookie": authToken
},
body: event.toSensorJson().toString(),
encoding: Encoding.getByName("utf-8"),
);
if (response.statusCode == 201) {
return true;
} else if (response.statusCode == 401) {
throw Exception('No editor for UrnId ' + event.urnId.toString());
}
else {
debugPrint(response.statusCode.toString());
throw Exception('Failed to put event. '
'Header: ' + response.headers.toString() +
' StatusCode: ' +response.statusCode.toString() +
' Body: ' +response.body.toString());
}
} on SocketException catch (e){
throw Exception('No connection');
}catch (e){
rethrow;
}
}
}
......
......@@ -69,10 +69,6 @@ class _ViewEvents extends State<ViewEvents> {
}
}
_syncStatus = 'export success';
} on SocketException catch (e) {
debugPrint('Exception: $e');
_syncStatus = 'No connection';
setState(() {});
} catch (e) {
debugPrint('Exception: $e');
_syncStatus = '$e';
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment