Skip to content
Snippets Groups Projects
Commit d641b1c3 authored by Philip's avatar Philip
Browse files

Umstellung auf CBOR

parent 9b27aebe
No related branches found
No related tags found
No related merge requests found
package boarderGateway;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.eclipse.californium.core.CoapResource;
......@@ -10,6 +13,18 @@ import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.cbor.CBORConstants;
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
import com.fasterxml.jackson.dataformat.cbor.CBORParser;
import co.nstant.in.cbor.*;
import co.nstant.in.cbor.decoder.UnicodeStringDecoder;
import co.nstant.in.cbor.model.*;
public class CoAPRessources {
......@@ -22,34 +37,86 @@ public class CoAPRessources {
getAttributes().setTitle("Client Registrierung");
}
@Override
public void handlePOST(CoapExchange exchange) {
try {
// Parse empfangenen String als JSON. Bei Fehler: BAD_REQUEST
JSONObject json = new JSONObject(exchange.getRequestText());
String name = json.getString("name");
int clientID = json.getInt("id");
// Parse JSONArray in Java List
JSONArray params = json.getJSONArray("parameter");
List<String> list = new ArrayList<String>();
for(int i = 0; i < params.length(); i++){
list.add(params.get(i).toString());
List<String> allowedTypes = Arrays.asList("string", "integer");
boolean errorOccurred = false;
// TODO Auto-generated method stub
CBORFactory f = new CBORFactory();
String source_address = exchange.getSourceAddress().getHostAddress();
System.out.println("GOT A PUT from "+source_address);
// Check, if source IP is allowed to
if (database.isClientAllowed(source_address)){
try {
// Lade erhaltenen Bytecode in CBOR Parser
byte payload[] = exchange.getRequestPayload();
CBORParser myCborParser = f.createParser(payload);
List<String> paras = new ArrayList<String>();
List<String> types = new ArrayList<String>();
myCborParser.nextToken();
String name = myCborParser.getText();
System.out.println("Name: "+name);
// Lese Arrays aus: [ "Parameter Name" , "Datentyp"]
String para = "";
String type = "";
// While Schleife, bis zum Ende der CBOR Nachricht
while (myCborParser.nextToken() != null){
// Array Beginn
if (myCborParser.getText().equals("[")){
para = myCborParser.nextTextValue();
type = myCborParser.nextTextValue();
// Prüfe ob Typ supported wird.
if (allowedTypes.contains(type)){
paras.add(para);
types.add(type);
}else{
errorOccurred = true;
}
// Nächstes Token muss Array schließen, ansonsten Fehler.
myCborParser.nextToken();
if (!myCborParser.getText().equals("]")){
errorOccurred = true;
}
}else{
// Kein (korrektes) Array in CBOR gefunden
errorOccurred = true;
}
}
if (!errorOccurred){
if (database.registerClient(name, source_address, paras, types)){
exchange.respond(ResponseCode.CREATED);
}else{
exchange.respond(ResponseCode.INTERNAL_SERVER_ERROR);
}
}else{
exchange.respond(ResponseCode.BAD_REQUEST);
}
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Füge Client in Datenbank hinzu. Bei Fehler: INTERNAL_SERVER_ERROR
if (database.registerClient(name, clientID, list)){
exchange.respond(ResponseCode.CREATED);
}else{
exchange.respond(ResponseCode.INTERNAL_SERVER_ERROR);
}
}catch(JSONException e){
exchange.respond(ResponseCode.BAD_REQUEST);
}
}
}else{
exchange.respond(ResponseCode.UNAUTHORIZED);
}
}
}
public static class DataRessource extends CoapResource{
......@@ -60,8 +127,74 @@ public class CoAPRessources {
getAttributes().setTitle("Datenuebertragung");
}
@Override
public void handlePOST(CoapExchange exchange) {
// TODO Auto-generated method stub
System.out.println("DATA POST!");
// Ermittle letzte registrierte ID zur Source Address
CBORFactory f = new CBORFactory();
String source_address = exchange.getSourceAddress().getHostAddress();
List<String> values = new ArrayList<String>();
if (database.doesClientAddressExist(source_address)){
try {
byte payload[] = exchange.getRequestPayload();
CBORParser myCborParser = f.createParser(payload);
// Erhalte Reihenfolge von String & Integer
List<String> types = database.getClientParamsTypeList(source_address);
System.out.println("#Types: "+types.size());
for (int i = 0; i < types.size();i++){
System.out.println(types.get(i));
}
for (String type : types) {
switch (type){
case "string":
String paraString = myCborParser.nextTextValue();
System.out.println("String! : "+paraString);
values.add(paraString);
break;
case "integer":
int paraInt = myCborParser.nextIntValue(0);
System.out.println("Int! : "+paraInt);
values.add(Integer.toString(paraInt));
break;
case "float":
myCborParser.nextToken();
float paraFloat = myCborParser.getFloatValue();
Float.toString(paraFloat);
values.add(Float.toString(paraFloat));
break;
default:
// Error
}
}
// Füge Daten in Datenbank hinzu. Bei Fehler: INTERNAL_SERVER_ERROR
if (database.addData(source_address, values)){
exchange.respond(ResponseCode.CHANGED);
}else{
exchange.respond(ResponseCode.INTERNAL_SERVER_ERROR);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
exchange.respond(ResponseCode.UNAUTHORIZED);
}
}
/*@Override
public void handlePUT(CoapExchange exchange) {
try {
......@@ -93,7 +226,7 @@ public class CoAPRessources {
}catch(JSONException e){
exchange.respond(ResponseCode.BAD_REQUEST);
}
}
}*/
}
}
......@@ -19,6 +19,7 @@ public class MySQL {
public static final String TBL_REGISTER = "tbl_register";
public static final String TBL_PARAMS = "tbl_parameter";
public static final String TBL_DATA = "tbl_data";
public static final String TBL_ADDRESSES = "tbl_addresses";
private Connection conn = null;
private Statement statement = null;
......@@ -73,17 +74,31 @@ public class MySQL {
}
}
public boolean registerClient(String name, int clientID, List<String> params){
public boolean isClientAllowed(String source_address){
String query = "";
query = "SELECT * FROM "+MySQL.TBL_ADDRESSES+" WHERE address = '"+source_address+"'";
ResultSet rs;
try {
rs = this.statement.executeQuery(query);
return rs.next();
} catch (SQLException e) {
// TODO Auto-generated catch block
return false;
}
}
public boolean registerClient(String name, String clientAddress, List<String> params, List<String> types){
// TODO: Prüfe ob Client bereits registriert?
String query = "";
try {
query = "INSERT INTO "+MySQL.TBL_REGISTER+"(clientID, name) VALUES("+clientID+", '"+name+"')";
query = "INSERT INTO "+MySQL.TBL_REGISTER+"(clientAddress, name) VALUES('"+clientAddress+"', '"+name+"')";
System.out.println(query);
this.statement.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
int lastID = this.getLastInsertedID(this.statement.getGeneratedKeys());
if (lastID > 0){
for ( String para : params){
query = "INSERT INTO "+MySQL.TBL_PARAMS+"(fid_register, param) VALUES("+lastID+", '"+para+"')";
for ( int i = 0; i<params.size(); i++){
query = "INSERT INTO "+MySQL.TBL_PARAMS+"(fid_register, param, type) VALUES("+lastID+", '"+params.get(i)+"', '"+types.get(i)+"')";
System.out.println(query);
this.statement.executeUpdate(query);
}
......@@ -101,13 +116,13 @@ public class MySQL {
}
}
public boolean addData(int clientID, List<String> values){
public boolean addData(String clientAddress, List<String> values){
String query = "";
try {
// Erhalte aktuellsten Primary Key der entsprechenden clientID
query = "SELECT * FROM "+MySQL.TBL_REGISTER+" WHERE clientID = "+clientID+" ORDER BY ID DESC LIMIT 1";
query = "SELECT * FROM "+MySQL.TBL_REGISTER+" WHERE clientAddress = '"+clientAddress+"' ORDER BY ID DESC LIMIT 1";
ResultSet rs = this.statement.executeQuery(query);
rs.next();
int id = rs.getInt(1);
......@@ -142,8 +157,8 @@ public class MySQL {
return true;
}
public boolean doesClientIDExist(int clientID){
String query = "SELECT * FROM "+MySQL.TBL_REGISTER+" WHERE clientID = "+clientID;
public boolean doesClientAddressExist(String clientAddress){
String query = "SELECT * FROM "+MySQL.TBL_REGISTER+" WHERE clientAddress = '"+clientAddress+"'";
try {
ResultSet rs = this.statement.executeQuery(query);
// True if not empty
......@@ -155,6 +170,30 @@ public class MySQL {
}
public List<String> getClientParamsTypeList(String clientAddress){
List<String> parameters = new ArrayList<String>();
String query = "SELECT * FROM "+MySQL.TBL_REGISTER+" WHERE clientAddress = '"+clientAddress+"' ORDER BY id DESC LIMIT 1";
ResultSet rs;
String clientID = "";
try {
rs = this.statement.executeQuery(query);
while (rs.next()){
clientID = Integer.toString(rs.getInt("id"));
}
query = "SELECT * FROM "+MySQL.TBL_PARAMS+" WHERE fid_register = "+clientID;
rs = this.statement.executeQuery(query);
while (rs.next()){
parameters.add(rs.getString("type"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return parameters;
}
private int getLastInsertedID(ResultSet keys){
try {
keys.next();
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment