Browse Source

Rewrote Synchronization between Devices:
- Split Record in MessageRecord, AttackRecord, NetworkRecord
(for UI access Record not deleted)
- Updated Database
- Added Tracing Synchronization Service + (empty) Activity
Missing: - Log Portscan correctly
- Kill Handler that are created during a portscan

Lars Pandikow 10 years ago
parent
commit
18daa77da8
30 changed files with 2784 additions and 2192 deletions
  1. 1 1
      .classpath
  2. 5 0
      AndroidManifest.xml
  3. 1 1
      res/layout/activity_nfc.xml
  4. 1 0
      res/values/strings_gui.xml
  5. 1 1
      src/de/tudarmstadt/informatik/hostage/ConnectionGuard.java
  6. 43 15
      src/de/tudarmstadt/informatik/hostage/Handler.java
  7. 331 401
      src/de/tudarmstadt/informatik/hostage/commons/HelperUtils.java
  8. 0 305
      src/de/tudarmstadt/informatik/hostage/deprecated/OldLogger.java
  9. 1 7
      src/de/tudarmstadt/informatik/hostage/deprecated/UglyDbHelper.java
  10. 163 0
      src/de/tudarmstadt/informatik/hostage/logging/AttackRecord.java
  11. 51 20
      src/de/tudarmstadt/informatik/hostage/logging/Logger.java
  12. 125 0
      src/de/tudarmstadt/informatik/hostage/logging/MessageRecord.java
  13. 136 0
      src/de/tudarmstadt/informatik/hostage/logging/NetworkRecord.java
  14. 47 133
      src/de/tudarmstadt/informatik/hostage/logging/Record.java
  15. 63 0
      src/de/tudarmstadt/informatik/hostage/logging/SyncInfoRecord.java
  16. 17 9
      src/de/tudarmstadt/informatik/hostage/persistence/HostageDBContract.java
  17. 427 266
      src/de/tudarmstadt/informatik/hostage/persistence/HostageDBOpenHelper.java
  18. 39 0
      src/de/tudarmstadt/informatik/hostage/sync/SyncMessage.java
  19. 34 191
      src/de/tudarmstadt/informatik/hostage/sync/bluetooth/BluetoothSync.java
  20. 29 0
      src/de/tudarmstadt/informatik/hostage/sync/bluetooth/BluetoothSyncService.java
  21. 48 0
      src/de/tudarmstadt/informatik/hostage/sync/bluetooth/ClientThread.java
  22. 145 0
      src/de/tudarmstadt/informatik/hostage/sync/bluetooth/CommunicationThread.java
  23. 57 0
      src/de/tudarmstadt/informatik/hostage/sync/bluetooth/ServerThread.java
  24. 5 6
      src/de/tudarmstadt/informatik/hostage/sync/nfc/NFCSync.java
  25. 5 0
      src/de/tudarmstadt/informatik/hostage/sync/tracing/TracingSyncActivity.java
  26. 162 0
      src/de/tudarmstadt/informatik/hostage/sync/tracing/TracingSyncService.java
  27. 1 1
      src/de/tudarmstadt/informatik/hostage/ui/MainActivity.java
  28. 31 21
      src/de/tudarmstadt/informatik/hostage/ui/PlayGroundActivity.java
  29. 2 1
      src/de/tudarmstadt/informatik/hostage/ui2/fragment/RecordDetailFragment.java
  30. 813 813
      src/de/tudarmstadt/informatik/hostage/ui2/fragment/RecordOverviewFragment.java

+ 1 - 1
.classpath

@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <classpath>
-	<classpathentry kind="src" path="src"/>
+	<classpathentry excluding="de/tudarmstadt/informatik/hostage/ui/ViewLog.java|de/tudarmstadt/informatik/hostage/ui/ViewLogTable.java" kind="src" path="src"/>
 	<classpathentry kind="src" path="gen"/>
 	<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
 	<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>

+ 5 - 0
AndroidManifest.xml

@@ -77,6 +77,11 @@
             android:name="de.tudarmstadt.informatik.hostage.ui.PlayGroundActivity"
             android:label="@string/gui_playground" >
         </activity>
+        <activity
+            android:name="de.tudarmstadt.informatik.hostage.sync.TracingSync"
+            android:label="@string/gui_tracing"
+            android:theme="@android:style/Theme.Dialog" >
+        </activity>
         <activity
             android:name="de.tudarmstadt.informatik.hostage.sync.BluetoothSync"
             android:label="@string/gui_bluetooth"

+ 1 - 1
res/layout/activity_nfc.xml

@@ -9,7 +9,7 @@
     android:paddingTop="@dimen/activity_vertical_margin" >
 
     <TextView
-        android:id="@+id/record_details_text_ssid"
+        android:id="@+id/nfc_text_view"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="NFC - SYNC" />

+ 1 - 0
res/values/strings_gui.xml

@@ -30,5 +30,6 @@
     <string name="gui_choose_device">Choose Device</string>
     <string name="gui_nfc">NFC</string>
     <string name="gui_bluetooth">Bluetooth</string>
+    <string name="gui_tracing">Tracing</string>
     
 </resources>

+ 1 - 1
src/de/tudarmstadt/informatik/hostage/ConnectionGuard.java

@@ -22,7 +22,7 @@ public class ConnectionGuard {
 		boolean sameIP = (lastIP == ip);
 		boolean sameProtocol = (lastProtocol == protocol);
 		if (!firstConnection && sameIP && belowThreshold && !sameProtocol) {
-			Logger.logPortscan(Hostage.getContext(), System.currentTimeMillis(), ip);
+//TODO LOG PORTSCAN			Logger.logPortscan(Hostage.getContext(), System.currentTimeMillis(), ip);
 		}
 		lastTimestamp = timestamp;
 		lastIP = ip;

+ 43 - 15
src/de/tudarmstadt/informatik/hostage/Handler.java

@@ -12,9 +12,11 @@ import android.content.SharedPreferences.Editor;
 import android.preference.PreferenceManager;
 import android.util.Log;
 import de.tudarmstadt.informatik.hostage.location.MyLocationManager;
+import de.tudarmstadt.informatik.hostage.logging.AttackRecord;
 import de.tudarmstadt.informatik.hostage.logging.Logger;
-import de.tudarmstadt.informatik.hostage.logging.Record;
-import de.tudarmstadt.informatik.hostage.logging.Record.TYPE;
+import de.tudarmstadt.informatik.hostage.logging.MessageRecord;
+import de.tudarmstadt.informatik.hostage.logging.MessageRecord.TYPE;
+import de.tudarmstadt.informatik.hostage.logging.NetworkRecord;
 import de.tudarmstadt.informatik.hostage.nio.Reader;
 import de.tudarmstadt.informatik.hostage.nio.Writer;
 import de.tudarmstadt.informatik.hostage.protocol.GHOST;
@@ -71,14 +73,16 @@ public class Handler implements Runnable {
 		this.thread = new Thread(this);
 		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(service);
 		TIMEOUT = pref.getInt("timeout", 30) * 1000;
-		// TODO ThreadSicher?
 		getAndIncrementAttackID(pref);
 		SharedPreferences connInfo = service.getSharedPreferences(service.getString(R.string.connection_info), Context.MODE_PRIVATE);
 		BSSID = connInfo.getString(service.getString(R.string.connection_info_bssid), null);
 		SSID = connInfo.getString(service.getString(R.string.connection_info_ssid), null);
 		externalIP = connInfo.getString(service.getString(R.string.connection_info_external_ip), null);
 		setSoTimeout(client);
+		Logger.log(Hostage.getContext(), createNetworkRecord());
+		Logger.log(Hostage.getContext(), createAttackRecord());
 		thread.start();
+		
 	}
 
 	/**
@@ -100,8 +104,10 @@ public class Handler implements Runnable {
 		try {
 			client.close();
 			Log.i("HoneyHandler", "Socket closed: " + client.isClosed());
-		} catch (IOException e) {
-		}
+		} catch (Exception e) {
+			
+		} 
+		
 		listener.refreshHandlers();
 	}
 
@@ -157,7 +163,7 @@ public class Handler implements Runnable {
 	}
 
 	/**
-	 * Creates a Record for a message exchanged with a client.
+	 * Creates a MessageRecord for a message exchanged with a client.
 	 * 
 	 * @param type
 	 *            The type of the message.
@@ -165,21 +171,43 @@ public class Handler implements Runnable {
 	 *            The content of the message.
 	 * @return The Record representing the communication message.
 	 */
-	protected Record createRecord(TYPE type, String packet) {
-		Record record = new Record();
+	protected MessageRecord createMessageRecord(TYPE type, String packet) {
+		MessageRecord record = new MessageRecord();
 		record.setId(message_id++);
-		record.setAttack_id(attack_id);
-		record.setProtocol(protocol.toString());
+		record.setAttack_id(attack_id);		
 		record.setType(type);
 		record.setTimestamp(System.currentTimeMillis());
+		record.setPacket(packet);
+		return record;
+	}
+	
+	/**
+	 * Creates a AttackRecord for a specific attack from a client.
+	 * 
+	 * @return The AttackRecord representing the attack.
+	 */
+	protected AttackRecord createAttackRecord() {
+		AttackRecord record = new AttackRecord();
+		record.setAttack_id(attack_id);			
+		record.setProtocol(protocol.toString());
 		record.setExternalIP(externalIP);
 		record.setLocalIP(client.getLocalAddress().getHostAddress());
 		record.setLocalPort(protocol.getPort());
 		record.setRemoteIP(client.getInetAddress().getHostAddress());
 		record.setRemotePort(client.getPort());
 		record.setBssid(BSSID);
-		record.setSsid(SSID);
-		record.setPacket(packet);
+		return record;
+	}
+	
+	/**
+	 * Creates a NetworkRecord containing information about the current network.
+	 * 
+	 * @return The NetworkRecord representing the current network.
+	 */
+	protected NetworkRecord createNetworkRecord() {
+		NetworkRecord record = new NetworkRecord();
+		record.setBssid(BSSID);		
+		record.setSsid(SSID);		
 		if (MyLocationManager.getNewestLocation() != null) {
 			record.setLatitude(MyLocationManager.getNewestLocation().getLatitude());
 			record.setLongitude(MyLocationManager.getNewestLocation().getLongitude());
@@ -213,16 +241,16 @@ public class Handler implements Runnable {
 			outputLine = protocol.processMessage(null);
 			writer.write(outputLine);
 			for (Packet o : outputLine) {
-				Logger.log(Hostage.getContext(), createRecord(TYPE.SEND, o.toString()));
+				Logger.log(Hostage.getContext(), createMessageRecord(TYPE.SEND, o.toString()));
 			}
 		}
 		while (!thread.isInterrupted() && (inputLine = reader.read()) != null) {
 			outputLine = protocol.processMessage(inputLine);
-			Logger.log(Hostage.getContext(), createRecord(TYPE.RECEIVE, inputLine.toString()));
+			Logger.log(Hostage.getContext(), createMessageRecord(TYPE.RECEIVE, inputLine.toString()));
 			if (outputLine != null) {
 				writer.write(outputLine);
 				for (Packet o : outputLine) {
-					Logger.log(Hostage.getContext(), createRecord(TYPE.SEND, o.toString()));
+					Logger.log(Hostage.getContext(), createMessageRecord(TYPE.SEND, o.toString()));
 				}
 			}
 			if (protocol.isClosed()) {

+ 331 - 401
src/de/tudarmstadt/informatik/hostage/commons/HelperUtils.java

@@ -1,401 +1,331 @@
-package de.tudarmstadt.informatik.hostage.commons;
-
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.security.KeyStore;
-import java.security.SecureRandom;
-
-import org.apache.http.HttpVersion;
-import org.apache.http.client.HttpClient;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.conn.ClientConnectionManager;
-import org.apache.http.conn.scheme.PlainSocketFactory;
-import org.apache.http.conn.scheme.Scheme;
-import org.apache.http.conn.scheme.SchemeRegistry;
-import org.apache.http.conn.ssl.SSLSocketFactory;
-import org.apache.http.entity.StringEntity;
-import org.apache.http.impl.client.DefaultHttpClient;
-import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
-import org.apache.http.params.BasicHttpParams;
-import org.apache.http.params.HttpParams;
-import org.apache.http.params.HttpProtocolParams;
-import org.apache.http.protocol.HTTP;
-
-import android.content.Context;
-import android.net.ConnectivityManager;
-import android.net.NetworkInfo;
-import android.net.wifi.WifiInfo;
-import android.net.wifi.WifiManager;
-import android.os.Environment;
-import android.preference.PreferenceManager;
-import android.text.TextUtils;
-import de.tudarmstadt.informatik.hostage.logging.Record;
-import de.tudarmstadt.informatik.hostage.logging.formatter.TraCINgFormatter;
-import de.tudarmstadt.informatik.hostage.net.MySSLSocketFactory;
-
-/**
- * Helper class with some static methods for general usage.
- * 
- * @author Lars Pandikow
- * @author Wulf Pfeiffer
- * 
- */
-public final class HelperUtils {
-
-	/**
-	 * Converts a byte array into a hexadecimal String, e.g. {0x00, 0x01} to
-	 * "00, 01".
-	 * 
-	 * @param bytes
-	 *            that will be converted.
-	 * @return converted String.
-	 */
-	public static String bytesToHexString(byte[] bytes) {
-		char[] hexArray = "0123456789ABCDEF".toCharArray();
-		int v;
-		StringBuffer buffer = new StringBuffer();
-		for (int j = 0; j < bytes.length; j++) {
-			v = bytes[j] & 0xFF;
-			buffer.append(hexArray[v >>> 4]);
-			buffer.append(hexArray[v & 0x0F]);
-			if (j < bytes.length - 1)
-				buffer.append(", ");
-		}
-		return buffer.toString();
-	}
-
-	/**
-	 * Converts a byte[] to a String, but only characters in ASCII between 32
-	 * and 127
-	 * 
-	 * @param bytes
-	 *            that are converted
-	 * @return converted String
-	 */
-	public static String byteToStr(byte[] bytes) {
-		int size = 0;
-		for(byte b : bytes) {
-			 if(isLetter((char) b)) {
-				 size++;
-			 }
-		}
-		char[] chars = new char[size];
-		for (int i = 0, j = 0; i < bytes.length && j < size; i++) {
-			if (isLetter((char) bytes[i])) {
-				chars[j] = (char) bytes[i];
-				j++;
-			}
-		}
-		return new String(chars);
-	}
-
-	/**
-	 * Concatenates several byte arrays.
-	 * 
-	 * @param bytes
-	 *            The byte arrays.
-	 * @return A single byte arrays containing all the bytes from the given
-	 *         arrays in the order they are given.
-	 */
-	public static byte[] concat(byte[]... bytes) {
-		int newSize = 0;
-		for (byte[] b : bytes)
-			if (b != null)
-				newSize += b.length;
-		byte[] dst = new byte[newSize];
-
-		int currentPos = 0;
-		int newPos;
-		for (byte[] b : bytes) {
-			if (b != null) {
-				newPos = b.length;
-				System.arraycopy(b, 0, dst, currentPos, newPos);
-				currentPos += newPos;
-			}
-		}
-		return dst;
-	}
-
-	/**
-	 * Creates a HttpClient with an own SSL Socket.
-	 * 
-	 * @return HttpsClient who accepts accepts all certificates.
-	 * @see MySSLSocketFactory
-	 */
-	public static HttpClient createHttpClient() {
-		try {
-			KeyStore trustStore = KeyStore.getInstance(KeyStore
-					.getDefaultType());
-			trustStore.load(null, null);
-
-			SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
-			sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
-
-			HttpParams params = new BasicHttpParams();
-			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
-			HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
-
-			SchemeRegistry registry = new SchemeRegistry();
-			registry.register(new Scheme("http", PlainSocketFactory
-					.getSocketFactory(), 80));
-			registry.register(new Scheme("https", sf, 443));
-
-			ClientConnectionManager ccm = new ThreadSafeClientConnManager(
-					params, registry);
-
-			return new DefaultHttpClient(ccm, params);
-		} catch (Exception e) {
-			e.printStackTrace();
-			return new DefaultHttpClient();
-		}
-	}
-
-	/**
-	 * Puts a 0x00 byte between each byte in a byte array.
-	 * 
-	 * @param bytes
-	 *            that need to be filled with 0x00.
-	 * @return filled byte array.
-	 */
-	public static byte[] fillWithZero(byte[] bytes) {
-		byte[] newBytes = new byte[(bytes.length * 2)];
-		for (int i = 0, j = 0; i < bytes.length && j < newBytes.length; i++, j = j + 2) {
-			newBytes[j] = bytes[i];
-			newBytes[j + 1] = 0x00;
-		}
-		return newBytes;
-	}
-
-	/**
-	 * Puts a 0x00 byte between each byte and another 2 0x00 bytes at the end of
-	 * a byte array.
-	 * 
-	 * @param bytes
-	 *            that need to be filled with 0x00.
-	 * @return filled byte array.
-	 */
-	public static byte[] fillWithZeroExtended(byte[] bytes) {
-		byte[] zeroBytes = fillWithZero(bytes);
-		byte[] newBytes = new byte[zeroBytes.length + 2];
-		newBytes = HelperUtils.concat(zeroBytes, new byte[] { 0x00, 0x00 });
-		return newBytes;
-	}
-
-	/**
-	 * Gets BSSID of the wireless network.
-	 * 
-	 * @param context
-	 *            Needs a context to get system recourses.
-	 * @return BSSID of wireless network if connected, else null.
-	 */
-	public static String getBSSID(Context context) {
-		String bssid = null;
-		ConnectivityManager connManager = (ConnectivityManager) context
-				.getSystemService(Context.CONNECTIVITY_SERVICE);
-		NetworkInfo networkInfo = connManager
-				.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
-		if (networkInfo != null && networkInfo.isConnected()) {
-			final WifiManager wifiManager = (WifiManager) context
-					.getSystemService(Context.WIFI_SERVICE);
-			final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
-			if (connectionInfo != null
-					&& !TextUtils.isEmpty(connectionInfo.getSSID())) {
-				bssid = connectionInfo.getBSSID();
-			}
-		}
-		return bssid;
-	}
-
-	/**
-	 * Gets internal IP address of the device in a wireless network.
-	 * 
-	 * @param context
-	 *            Needs a context to get system recourses.
-	 * @return internal IP of the device in a wireless network if connected,
-	 *         else null.
-	 */
-	public static String getInternalIP(Context context) {
-		String ipAddress = null;
-		ConnectivityManager connManager = (ConnectivityManager) context
-				.getSystemService(Context.CONNECTIVITY_SERVICE);
-		NetworkInfo networkInfo = connManager
-				.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
-		if (networkInfo != null && networkInfo.isConnected()) {
-			final WifiManager wifiManager = (WifiManager) context
-					.getSystemService(Context.WIFI_SERVICE);
-			final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
-			if (connectionInfo != null) {
-				try {
-					ipAddress = InetAddress.getByAddress(
-							unpackInetAddress(connectionInfo.getIpAddress()))
-							.getHostAddress();
-				} catch (UnknownHostException e) {
-					e.printStackTrace();
-				}
-			}
-		}
-		return ipAddress;
-	}
-
-	/**
-	 * Produces a random String. The String can be of random length (minimum 1)
-	 * with a maximum length, or it can be forced to have the length that was
-	 * given.
-	 * 
-	 * @param length
-	 *            maximal / forced length of String.
-	 * @param forceLength
-	 *            forces the String to be exact the given length instead of
-	 *            maximum
-	 * @return random String.
-	 */
-	public static String getRandomString(int length, boolean forceLength) {
-		SecureRandom rndm = new SecureRandom();
-		char[] c = new char[forceLength ? length : rndm.nextInt(length - 1) + 1];
-		for (int i = 0; i < c.length; i++) {
-			c[i] = (char) (rndm.nextInt(95) + 32);
-		}
-		return new String(c);
-	}
-
-	/**
-	 * Gets SSID of the wireless network.
-	 * 
-	 * @param context
-	 *            Needs a context to get system recourses
-	 * @return SSID of wireless network if connected, else null.
-	 */
-	public static String getSSID(Context context) {
-		String ssid = null;
-		ConnectivityManager connManager = (ConnectivityManager) context
-				.getSystemService(Context.CONNECTIVITY_SERVICE);
-		NetworkInfo networkInfo = connManager
-				.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
-		if (networkInfo != null && networkInfo.isConnected()) {
-			final WifiManager wifiManager = (WifiManager) context
-					.getSystemService(Context.WIFI_SERVICE);
-			final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
-			if (connectionInfo != null
-					&& !TextUtils.isEmpty(connectionInfo.getSSID())) {
-				ssid = connectionInfo.getSSID();
-			}
-		}
-		return ssid;
-	}
-
-	/**
-	 * Converts a String into a byte array, e.g. "00, 01" to {0x00, 0x01}.
-	 * 
-	 * @param string
-	 *            that will be converted.
-	 * @return converted byte array.
-	 */
-	public static byte[] hexStringToBytes(String string) {
-		String[] hexStrings = string.split(", ");
-		byte[] bytes = new byte[hexStrings.length];
-		for (int j = 0; j < hexStrings.length; j++) {
-			bytes[j] = (byte) ((Character.digit(hexStrings[j].charAt(0), 16) << 4) + Character
-					.digit(hexStrings[j].charAt(1), 16));
-		}
-		return bytes;
-	}
-
-	/**
-	 * Checks if external storage is available for read and write.
-	 * 
-	 * @return True if external storage is available for read and write, else
-	 *         false.
-	 */
-	public static boolean isExternalStorageWritable() {
-		String state = Environment.getExternalStorageState();
-		if (Environment.MEDIA_MOUNTED.equals(state)) {
-			return true;
-		}
-		return false;
-	}
-
-	/**
-	 * Generates a random byte[] of a specified size
-	 * 
-	 * @param size
-	 *            of the byte[]
-	 * @return random byte[]
-	 */
-	public static byte[] randomBytes(int size) {
-		byte[] bytes = new byte[size];
-		SecureRandom rdm = new SecureRandom();
-		rdm.nextBytes(bytes);
-		return bytes;
-	}
-
-	/**
-	 * Turns around the values of an byte[], e.g. {0x00, 0x01, 0x02} turns into
-	 * {0x02, 0x01, 0x00}.
-	 * 
-	 * @param bytes
-	 *            array that is turned.
-	 * @return turned array.
-	 */
-	public static byte[] turnByteArray(byte[] bytes) {
-		byte[] tmp = new byte[bytes.length];
-		for (int i = 0; i < bytes.length; i++) {
-			tmp[i] = bytes[bytes.length - 1 - i];
-		}
-		return tmp;
-	}
-
-	/**
-	 * Uploads a single Record to a server, specified in the settings.
-	 * 
-	 * @param record
-	 *            The Record to upload.
-	 * @return True if the upload was successful, else false.
-	 */
-	public static boolean uploadSingleRecord(Context context, Record record) {
-		// Create a https client. Uses MySSLSocketFactory to accept all
-		// certificates
-		HttpClient httpclient = HelperUtils.createHttpClient();
-		HttpPost httppost;
-		try {
-			// Create HttpPost
-			httppost = new HttpPost(PreferenceManager
-					.getDefaultSharedPreferences(context).getString(
-							"pref_upload", "https://ssi.cased.de"));
-			// Create JSON String of Record
-			StringEntity se = new StringEntity(record.toString(TraCINgFormatter
-					.getInstance()));
-			httppost.setEntity(se);
-			// Execute HttpPost
-			httpclient.execute(httppost);
-		} catch (Exception e) {
-			e.printStackTrace();
-			return false;
-		}
-		return true;
-	}
-
-	/**
-	 * Determines if a character is in ASCII between 32 and 126
-	 * 
-	 * @param character
-	 *            that is checked
-	 * @return true if the character is between 32 and 126, else false
-	 */
-	private static boolean isLetter(char character) {
-		return (character > 31 && character < 127);
-	}
-
-	private static byte[] unpackInetAddress(int bytes) {
-		return new byte[] { (byte) ((bytes) & 0xff),
-				(byte) ((bytes >>> 8) & 0xff), (byte) ((bytes >>> 16) & 0xff),
-				(byte) ((bytes >>> 24) & 0xff) };
-	}
-
-	public static boolean isWifiConnected(Context context){
-		if(context == null) return false;
-		ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
-		NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
-
-		return mWifi.isConnected();
-	}
-}
+package de.tudarmstadt.informatik.hostage.commons;
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.security.SecureRandom;
+
+import android.content.Context;
+import android.net.ConnectivityManager;
+import android.net.NetworkInfo;
+import android.net.wifi.WifiInfo;
+import android.net.wifi.WifiManager;
+import android.os.Environment;
+import android.text.TextUtils;
+
+/**
+ * Helper class with some static methods for general usage.
+ * 
+ * @author Lars Pandikow
+ * @author Wulf Pfeiffer
+ * 
+ */
+public final class HelperUtils {
+
+	/**
+	 * Converts a byte array into a hexadecimal String, e.g. {0x00, 0x01} to
+	 * "00, 01".
+	 * 
+	 * @param bytes
+	 *            that will be converted.
+	 * @return converted String.
+	 */
+	public static String bytesToHexString(byte[] bytes) {
+		char[] hexArray = "0123456789ABCDEF".toCharArray();
+		int v;
+		StringBuffer buffer = new StringBuffer();
+		for (int j = 0; j < bytes.length; j++) {
+			v = bytes[j] & 0xFF;
+			buffer.append(hexArray[v >>> 4]);
+			buffer.append(hexArray[v & 0x0F]);
+			if (j < bytes.length - 1)
+				buffer.append(", ");
+		}
+		return buffer.toString();
+	}
+
+	/**
+	 * Converts a byte[] to a String, but only characters in ASCII between 32
+	 * and 127
+	 * 
+	 * @param bytes
+	 *            that are converted
+	 * @return converted String
+	 */
+	public static String byteToStr(byte[] bytes) {
+		int size = 0;
+		for(byte b : bytes) {
+			 if(isLetter((char) b)) {
+				 size++;
+			 }
+		}
+		char[] chars = new char[size];
+		for (int i = 0, j = 0; i < bytes.length && j < size; i++) {
+			if (isLetter((char) bytes[i])) {
+				chars[j] = (char) bytes[i];
+				j++;
+			}
+		}
+		return new String(chars);
+	}
+
+	/**
+	 * Concatenates several byte arrays.
+	 * 
+	 * @param bytes
+	 *            The byte arrays.
+	 * @return A single byte arrays containing all the bytes from the given
+	 *         arrays in the order they are given.
+	 */
+	public static byte[] concat(byte[]... bytes) {
+		int newSize = 0;
+		for (byte[] b : bytes)
+			if (b != null)
+				newSize += b.length;
+		byte[] dst = new byte[newSize];
+
+		int currentPos = 0;
+		int newPos;
+		for (byte[] b : bytes) {
+			if (b != null) {
+				newPos = b.length;
+				System.arraycopy(b, 0, dst, currentPos, newPos);
+				currentPos += newPos;
+			}
+		}
+		return dst;
+	}
+
+	/**
+	 * Puts a 0x00 byte between each byte in a byte array.
+	 * 
+	 * @param bytes
+	 *            that need to be filled with 0x00.
+	 * @return filled byte array.
+	 */
+	public static byte[] fillWithZero(byte[] bytes) {
+		byte[] newBytes = new byte[(bytes.length * 2)];
+		for (int i = 0, j = 0; i < bytes.length && j < newBytes.length; i++, j = j + 2) {
+			newBytes[j] = bytes[i];
+			newBytes[j + 1] = 0x00;
+		}
+		return newBytes;
+	}
+
+	/**
+	 * Puts a 0x00 byte between each byte and another 2 0x00 bytes at the end of
+	 * a byte array.
+	 * 
+	 * @param bytes
+	 *            that need to be filled with 0x00.
+	 * @return filled byte array.
+	 */
+	public static byte[] fillWithZeroExtended(byte[] bytes) {
+		byte[] zeroBytes = fillWithZero(bytes);
+		byte[] newBytes = new byte[zeroBytes.length + 2];
+		newBytes = HelperUtils.concat(zeroBytes, new byte[] { 0x00, 0x00 });
+		return newBytes;
+	}
+
+	/**
+	 * Gets BSSID of the wireless network.
+	 * 
+	 * @param context
+	 *            Needs a context to get system recourses.
+	 * @return BSSID of wireless network if connected, else null.
+	 */
+	public static String getBSSID(Context context) {
+		String bssid = null;
+		ConnectivityManager connManager = (ConnectivityManager) context
+				.getSystemService(Context.CONNECTIVITY_SERVICE);
+		NetworkInfo networkInfo = connManager
+				.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
+		if (networkInfo != null && networkInfo.isConnected()) {
+			final WifiManager wifiManager = (WifiManager) context
+					.getSystemService(Context.WIFI_SERVICE);
+			final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
+			if (connectionInfo != null
+					&& !TextUtils.isEmpty(connectionInfo.getSSID())) {
+				bssid = connectionInfo.getBSSID();
+			}
+		}
+		return bssid;
+	}
+
+	/**
+	 * Gets internal IP address of the device in a wireless network.
+	 * 
+	 * @param context
+	 *            Needs a context to get system recourses.
+	 * @return internal IP of the device in a wireless network if connected,
+	 *         else null.
+	 */
+	public static String getInternalIP(Context context) {
+		String ipAddress = null;
+		ConnectivityManager connManager = (ConnectivityManager) context
+				.getSystemService(Context.CONNECTIVITY_SERVICE);
+		NetworkInfo networkInfo = connManager
+				.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
+		if (networkInfo != null && networkInfo.isConnected()) {
+			final WifiManager wifiManager = (WifiManager) context
+					.getSystemService(Context.WIFI_SERVICE);
+			final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
+			if (connectionInfo != null) {
+				try {
+					ipAddress = InetAddress.getByAddress(
+							unpackInetAddress(connectionInfo.getIpAddress()))
+							.getHostAddress();
+				} catch (UnknownHostException e) {
+					e.printStackTrace();
+				}
+			}
+		}
+		return ipAddress;
+	}
+
+	/**
+	 * Gets SSID of the wireless network.
+	 * 
+	 * @param context
+	 *            Needs a context to get system recourses
+	 * @return SSID of wireless network if connected, else null.
+	 */
+	public static String getSSID(Context context) {
+		String ssid = null;
+		ConnectivityManager connManager = (ConnectivityManager) context
+				.getSystemService(Context.CONNECTIVITY_SERVICE);
+		NetworkInfo networkInfo = connManager
+				.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
+		if (networkInfo != null && networkInfo.isConnected()) {
+			final WifiManager wifiManager = (WifiManager) context
+					.getSystemService(Context.WIFI_SERVICE);
+			final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
+			if (connectionInfo != null
+					&& !TextUtils.isEmpty(connectionInfo.getSSID())) {
+				ssid = connectionInfo.getSSID();
+			}
+		}
+		return ssid;
+	}
+	
+	/**
+	 * Gets the mac address of the devicek.
+	 * 
+	 * @param context
+	 *            Needs a context to get system recourses
+	 * @return MAC address of the device.
+	 */
+	public static String getMacAdress(Context context) {
+		String mac = null;
+		WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
+		WifiInfo connectionInfo = wifiManager.getConnectionInfo();		
+		mac = connectionInfo.getMacAddress();
+		return mac;
+	}
+	
+	/**
+	 * Produces a random String. The String can be of random length (minimum 1)
+	 * with a maximum length, or it can be forced to have the length that was
+	 * given.
+	 * 
+	 * @param length
+	 *            maximal / forced length of String.
+	 * @param forceLength
+	 *            forces the String to be exact the given length instead of
+	 *            maximum
+	 * @return random String.
+	 */
+	public static String getRandomString(int length, boolean forceLength) {
+		SecureRandom rndm = new SecureRandom();
+		char[] c = new char[forceLength ? length : rndm.nextInt(length - 1) + 1];
+		for (int i = 0; i < c.length; i++) {
+			c[i] = (char) (rndm.nextInt(95) + 32);
+		}
+		return new String(c);
+	}
+
+	/**
+	 * Converts a String into a byte array, e.g. "00, 01" to {0x00, 0x01}.
+	 * 
+	 * @param string
+	 *            that will be converted.
+	 * @return converted byte array.
+	 */
+	public static byte[] hexStringToBytes(String string) {
+		String[] hexStrings = string.split(", ");
+		byte[] bytes = new byte[hexStrings.length];
+		for (int j = 0; j < hexStrings.length; j++) {
+			bytes[j] = (byte) ((Character.digit(hexStrings[j].charAt(0), 16) << 4) + Character
+					.digit(hexStrings[j].charAt(1), 16));
+		}
+		return bytes;
+	}
+
+	/**
+	 * Checks if external storage is available for read and write.
+	 * 
+	 * @return True if external storage is available for read and write, else
+	 *         false.
+	 */
+	public static boolean isExternalStorageWritable() {
+		String state = Environment.getExternalStorageState();
+		if (Environment.MEDIA_MOUNTED.equals(state)) {
+			return true;
+		}
+		return false;
+	}
+
+	/**
+	 * Generates a random byte[] of a specified size
+	 * 
+	 * @param size
+	 *            of the byte[]
+	 * @return random byte[]
+	 */
+	public static byte[] randomBytes(int size) {
+		byte[] bytes = new byte[size];
+		SecureRandom rdm = new SecureRandom();
+		rdm.nextBytes(bytes);
+		return bytes;
+	}
+
+	/**
+	 * Turns around the values of an byte[], e.g. {0x00, 0x01, 0x02} turns into
+	 * {0x02, 0x01, 0x00}.
+	 * 
+	 * @param bytes
+	 *            array that is turned.
+	 * @return turned array.
+	 */
+	public static byte[] turnByteArray(byte[] bytes) {
+		byte[] tmp = new byte[bytes.length];
+		for (int i = 0; i < bytes.length; i++) {
+			tmp[i] = bytes[bytes.length - 1 - i];
+		}
+		return tmp;
+	}
+
+	/**
+	 * Determines if a character is in ASCII between 32 and 126
+	 * 
+	 * @param character
+	 *            that is checked
+	 * @return true if the character is between 32 and 126, else false
+	 */
+	private static boolean isLetter(char character) {
+		return (character > 31 && character < 127);
+	}
+
+	private static byte[] unpackInetAddress(int bytes) {
+		return new byte[] { (byte) ((bytes) & 0xff),
+				(byte) ((bytes >>> 8) & 0xff), (byte) ((bytes >>> 16) & 0xff),
+				(byte) ((bytes >>> 24) & 0xff) };
+	}
+	
+	public static boolean isWifiConnected(Context context){
+		if(context == null) return false;
+		ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
+		NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
+
+		return mWifi.isConnected();
+	}
+}

+ 0 - 305
src/de/tudarmstadt/informatik/hostage/deprecated/OldLogger.java

@@ -1,305 +0,0 @@
-package de.tudarmstadt.informatik.hostage.deprecated;
-
-import java.util.ArrayList;
-
-import android.app.IntentService;
-import android.content.Context;
-import android.content.Intent;
-import android.os.Bundle;
-import android.os.ResultReceiver;
-import de.tudarmstadt.informatik.hostage.logging.Record;
-
-/**
- * An {@link IntentService} subclass for handling asynchronous task requests in
- * a service on a separate handler thread.
- * 
- * @author Mihai Plasoianu
- */
-public class OldLogger extends IntentService {
-
-	private static final String ACTION_LOG = "de.tudarmstadt.informatik.hostage.action.LOG";
-	private static final String ACTION_GET_RECORD_ALL = "de.tudarmstadt.informatik.hostage.action.GET_RECORD_ALL";
-	private static final String ACTION_GET_RECORD_EACH = "de.tudarmstadt.informatik.hostage.action.GET_RECORD_EACH";
-	private static final String ACTION_GET_RECORD_ID = "de.tudarmstadt.informatik.hostage.action.GET_RECORD_ID";
-	private static final String ACTION_GET_COUNT_ALL = "de.tudarmstadt.informatik.hostage.action.GET_COUNT_ALL";
-	private static final String ACTION_GET_COUNT_PROTOCOL = "de.tudarmstadt.informatik.hostage.action.GET_COUNT_PROTOCOL";
-	private static final String ACTION_GET_ATTACK_MIN = "de.tudarmstadt.informatik.hostage.action.GET_ATTACK_MIN";
-	private static final String ACTION_GET_ATTACK_MAX = "de.tudarmstadt.informatik.hostage.action.GET_ATTACK_MAX";
-	private static final String ACTION_IS_BSSID_SEEN = "de.tudarmstadt.informatik.hostage.action.IS_BSSID_SEEN";
-	private static final String ACTION_GET_BSSID_ALL = "de.tudarmstadt.informatik.hostage.action.GET_BSSID_ALL";
-	private static final String ACTION_GET_SSID_BSSID = "de.tudarmstadt.informatik.hostage.action.GET_SSID_BSSID";
-	private static final String ACTION_CLEAR_DATE = "de.tudarmstadt.informatik.hostage.action.CLEAR_DATE";
-	private static final String ACTION_CLEAR_BSSID = "de.tudarmstadt.informatik.hostage.action.CLEAR_BSSID";
-	private static final String ACTION_CLEAR_ALL = "de.tudarmstadt.informatik.hostage.action.CLEAR_ALL";
-
-	private static final String EXTRA_RECORD = "de.tudarmstadt.informatik.hostage.extra.RECORD";
-	private static final String EXTRA_PROTOCOL = "de.tudarmstadt.informatik.hostage.extra.PROTOCOL";
-	private static final String EXTRA_BSSID = "de.tudarmstadt.informatik.hostage.extra.BSSID";
-	private static final String EXTRA_PRIMITIVE = "de.tudarmstadt.informatik.hostage.extra.PRIMITIVE";
-
-	private static final String RESULT_RECEIVER = "de.tudarmstadt.informatik.hostage.RESULT_RECEIVER";
-
-	public static void deleteAll(Context context) {
-		Intent intent = new Intent(context, OldLogger.class);
-		intent.setAction(ACTION_CLEAR_ALL);
-		context.startService(intent);
-	}
-
-	public static void deleteByBssid(Context context, String bssid) {
-		Intent intent = new Intent(context, OldLogger.class);
-		intent.setAction(ACTION_CLEAR_BSSID);
-		intent.putExtra(EXTRA_BSSID, bssid);
-		context.startService(intent);
-	}
-
-	public static void deleteByDate(Context context, long time) {
-		Intent intent = new Intent(context, OldLogger.class);
-		intent.setAction(ACTION_CLEAR_DATE);
-		intent.putExtra(EXTRA_PRIMITIVE, time);
-		context.startService(intent);
-	}
-
-	public static void getAllBssids(Context context, ResultReceiver receiver) {
-		Intent intent = new Intent(context, OldLogger.class);
-		intent.setAction(ACTION_GET_BSSID_ALL);
-		intent.putExtra(RESULT_RECEIVER, receiver);
-		context.startService(intent);
-	}
-
-	public static void getAllRecords(Context context, ResultReceiver receiver) {
-		Intent intent = new Intent(context, OldLogger.class);
-		intent.setAction(ACTION_GET_RECORD_ALL);
-		intent.putExtra(RESULT_RECEIVER, receiver);
-		context.startService(intent);
-	}
-
-	public static void getAttackCount(Context context, ResultReceiver receiver) {
-		Intent intent = new Intent(context, OldLogger.class);
-		intent.setAction(ACTION_GET_COUNT_ALL);
-		intent.putExtra(RESULT_RECEIVER, receiver);
-		context.startService(intent);
-	}
-
-	public static void getAttackPerProtocolCount(Context context, String protocol, ResultReceiver receiver) {
-		Intent intent = new Intent(context, OldLogger.class);
-		intent.setAction(ACTION_GET_COUNT_PROTOCOL);
-		intent.putExtra(EXTRA_PROTOCOL, protocol);
-		intent.putExtra(RESULT_RECEIVER, receiver);
-		context.startService(intent);
-	}
-
-	public static void getMaxAttackId(Context context, ResultReceiver receiver) {
-		Intent intent = new Intent(context, OldLogger.class);
-		intent.setAction(ACTION_GET_ATTACK_MAX);
-		intent.putExtra(RESULT_RECEIVER, receiver);
-		context.startService(intent);
-	}
-
-	public static void getMinAttackId(Context context, ResultReceiver receiver) {
-		Intent intent = new Intent(context, OldLogger.class);
-		intent.setAction(ACTION_GET_ATTACK_MIN);
-		intent.putExtra(RESULT_RECEIVER, receiver);
-		context.startService(intent);
-	}
-
-	public static void getRecordOfAttackId(Context context, long attack_id, ResultReceiver receiver) {
-		Intent intent = new Intent(context, OldLogger.class);
-		intent.setAction(ACTION_GET_RECORD_ID);
-		intent.putExtra(EXTRA_PRIMITIVE, attack_id);
-		intent.putExtra(RESULT_RECEIVER, receiver);
-		context.startService(intent);
-	}
-
-	public static void getRecordOfEachAttack(Context context, int lastUploadedAttackId, ResultReceiver receiver) {
-		Intent intent = new Intent(context, OldLogger.class);
-		intent.setAction(ACTION_GET_RECORD_EACH);
-		intent.putExtra(EXTRA_PRIMITIVE, lastUploadedAttackId);
-		intent.putExtra(RESULT_RECEIVER, receiver);
-		context.startService(intent);
-	}
-
-	public static void getSsid(Context context, String bssid, ResultReceiver receiver) {
-		Intent intent = new Intent(context, OldLogger.class);
-		intent.setAction(ACTION_GET_SSID_BSSID);
-		intent.putExtra(EXTRA_BSSID, bssid);
-		intent.putExtra(RESULT_RECEIVER, receiver);
-		context.startService(intent);
-	}
-
-	public static void isBssidSeen(Context context, String protocol, String bssid, ResultReceiver receiver) {
-		Intent intent = new Intent(context, OldLogger.class);
-		intent.setAction(ACTION_IS_BSSID_SEEN);
-		intent.putExtra(EXTRA_PROTOCOL, protocol);
-		intent.putExtra(EXTRA_BSSID, bssid);
-		intent.putExtra(RESULT_RECEIVER, receiver);
-		context.startService(intent);
-	}
-
-	public static void log(Context context, Record record) {
-		Intent intent = new Intent(context, OldLogger.class);
-		intent.setAction(ACTION_LOG);
-		intent.putExtra(EXTRA_RECORD, record);
-		context.startService(intent);
-	}
-
-	private UglyDbHelper mDbHelper;
-
-	public OldLogger() {
-		super("Logger");
-	}
-
-	@Override
-	public void onCreate() {
-		super.onCreate();
-		mDbHelper = new UglyDbHelper(getApplicationContext());
-	}
-
-	private boolean handleActionBssidSeen(String protocol, String bssid) {
-		return mDbHelper.bssidSeen(protocol, bssid);
-	}
-
-	/**
-	 * Delete all records.
-	 */
-	private void handleActionDeleteAll() {
-		mDbHelper.clearData();
-	}
-
-	private void handleActionDeleteByBssid(String bssid) {
-		mDbHelper.deleteByBSSID(bssid);
-	}
-
-	private void handleActionDeleteByDate(long time) {
-		mDbHelper.deleteByDate(time);
-	}
-
-	private String[] handleActionGetAllBssids() {
-		return mDbHelper.getAllBSSIDS();
-	}
-
-	private ArrayList<Record> handleActionGetAllRecords() {
-		return mDbHelper.getAllRecords();
-	}
-
-	private int handleActionGetAttackCount() {
-		return mDbHelper.getAttackCount();
-	}
-
-	private int handleActionGetAttackPerProtocolCount(String protocol) {
-		return mDbHelper.getAttackPerProtocolCount(protocol);
-	}
-
-	private long handleActionGetMaxAttackId() {
-		return mDbHelper.getHighestAttackId();
-	}
-
-	private long handleActionGetMinAttackId() {
-		return mDbHelper.getSmallestAttackId();
-	}
-
-	private Record handleActionGetRecordOfAttackId(long attack_id) {
-		return mDbHelper.getRecordOfAttackId(attack_id);
-	}
-
-	private ArrayList<Record> handleActionGetRecordOfEachAttack(int lastUploadedAttackId) {
-		return mDbHelper.getRecordOfEachAttack(lastUploadedAttackId);
-	}
-
-	private String handleActionGetSsid(String bssid) {
-		return mDbHelper.getSSID(bssid);
-	}
-
-	/**
-	 * Log a record.
-	 */
-	private void handleActionLog(Record record) {
-		mDbHelper.addRecord(record);
-	}
-
-	@Override
-	protected void onHandleIntent(Intent intent) {
-		if (intent != null) {
-			final String action = intent.getAction();
-			if (ACTION_LOG.equals(action)) {
-				final Record record = intent.getParcelableExtra(EXTRA_RECORD);
-				handleActionLog(record);
-			} else if (ACTION_GET_RECORD_ALL.equals(action)) {
-				ResultReceiver receiver = intent.getParcelableExtra(RESULT_RECEIVER);
-				ArrayList<Record> r = handleActionGetAllRecords();
-				Bundle result = new Bundle();
-				result.putParcelableArrayList("result", r);
-				receiver.send(0, result);
-			} else if (ACTION_GET_RECORD_EACH.equals(action)) {
-				final int lastUploadedAttackId = intent.getIntExtra(EXTRA_PRIMITIVE, -1);
-				ResultReceiver receiver = intent.getParcelableExtra(RESULT_RECEIVER);
-				ArrayList<Record> r = handleActionGetRecordOfEachAttack(lastUploadedAttackId);
-				Bundle result = new Bundle();
-				result.putParcelableArrayList("result", r);
-				receiver.send(0, result);
-			} else if (ACTION_GET_RECORD_ID.equals(action)) {
-				final int attack_id = intent.getIntExtra(EXTRA_PRIMITIVE, -1);
-				ResultReceiver receiver = intent.getParcelableExtra(RESULT_RECEIVER);
-				Record r = handleActionGetRecordOfAttackId(attack_id);
-				Bundle result = new Bundle();
-				result.putParcelable("result", r);
-				receiver.send(0, result);
-			} else if (ACTION_GET_COUNT_ALL.equals(action)) {
-				ResultReceiver receiver = intent.getParcelableExtra(RESULT_RECEIVER);
-				int r = handleActionGetAttackCount();
-				Bundle result = new Bundle();
-				result.putInt("result", r);
-				receiver.send(0, result);
-			} else if (ACTION_GET_COUNT_PROTOCOL.equals(action)) {
-				final String protocol = intent.getStringExtra(EXTRA_PROTOCOL);
-				ResultReceiver receiver = intent.getParcelableExtra(RESULT_RECEIVER);
-				int r = handleActionGetAttackPerProtocolCount(protocol);
-				Bundle result = new Bundle();
-				result.putInt("result", r);
-				receiver.send(0, result);
-			} else if (ACTION_GET_ATTACK_MIN.equals(action)) {
-				ResultReceiver receiver = intent.getParcelableExtra(RESULT_RECEIVER);
-				long r = handleActionGetMinAttackId();
-				Bundle result = new Bundle();
-				result.putLong("result", r);
-				receiver.send(0, result);
-				handleActionGetMinAttackId();
-			} else if (ACTION_GET_ATTACK_MAX.equals(action)) {
-				ResultReceiver receiver = intent.getParcelableExtra(RESULT_RECEIVER);
-				long r = handleActionGetMaxAttackId();
-				Bundle result = new Bundle();
-				result.putLong("result", r);
-				receiver.send(0, result);
-			} else if (ACTION_IS_BSSID_SEEN.equals(action)) {
-				final String protocol = intent.getStringExtra(EXTRA_PROTOCOL);
-				final String bssid = intent.getStringExtra(EXTRA_BSSID);
-				ResultReceiver receiver = intent.getParcelableExtra(RESULT_RECEIVER);
-				boolean r = handleActionBssidSeen(protocol, bssid);
-				Bundle result = new Bundle();
-				result.putBoolean("result", r);
-				receiver.send(0, result);
-			} else if (ACTION_GET_BSSID_ALL.equals(action)) {
-				ResultReceiver receiver = intent.getParcelableExtra(RESULT_RECEIVER);
-				String[] r = handleActionGetAllBssids();
-				Bundle result = new Bundle();
-				result.putStringArray("result", r);
-				receiver.send(0, result);
-			} else if (ACTION_GET_SSID_BSSID.equals(action)) {
-				final String bssid = intent.getStringExtra(EXTRA_BSSID);
-				ResultReceiver receiver = intent.getParcelableExtra(RESULT_RECEIVER);
-				String r = handleActionGetSsid(bssid);
-				Bundle result = new Bundle();
-				result.putString("result", r);
-				receiver.send(0, result);
-			} else if (ACTION_CLEAR_DATE.equals(action)) {
-				final long time = intent.getLongExtra(EXTRA_PRIMITIVE, -1L);
-				handleActionDeleteByDate(time);
-			} else if (ACTION_CLEAR_BSSID.equals(action)) {
-				final String bssid = intent.getStringExtra(EXTRA_BSSID);
-				handleActionDeleteByBssid(bssid);
-			} else if (ACTION_CLEAR_ALL.equals(action)) {
-				handleActionDeleteAll();
-			}
-		}
-	}
-
-}

+ 1 - 7
src/de/tudarmstadt/informatik/hostage/deprecated/UglyDbHelper.java

@@ -12,9 +12,8 @@ import android.database.sqlite.SQLiteDatabase;
 import android.database.sqlite.SQLiteOpenHelper;
 import android.util.Log;
 import de.tudarmstadt.informatik.hostage.logging.Record;
-import de.tudarmstadt.informatik.hostage.logging.Record.TYPE;
+import de.tudarmstadt.informatik.hostage.logging.MessageRecord.TYPE;
 import de.tudarmstadt.informatik.hostage.model.Profile;
-import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract.PortscanEntry;
 import de.tudarmstadt.informatik.hostage.ui.LogFilter;
 
 /**
@@ -88,10 +87,6 @@ public class UglyDbHelper extends SQLiteOpenHelper {
 	private static final String CREATE_BSSID_TABLE = "CREATE TABLE " + TABLE_BSSIDS + "(" + KEY_BSSID + " TEXT PRIMARY KEY," + KEY_SSID + " TEXT,"
 			+ KEY_LATITUDE + " INTEGER," + KEY_LONGITUDE + " INTEGER," + KEY_ACCURACY + " INTEGER," + KEY_GEO_TIMESTAMP + " INTEGER" + ")";
 
-	private static final String CREATE_PORTSCAN_TABLE = "CREATE TABLE " + PortscanEntry.TABLE_NAME + "(" + PortscanEntry.COLUMN_NAME_ID
-			+ " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + PortscanEntry.COLUMN_NAME_PORTSCAN_TIMESTAMP + " INTEGER," + PortscanEntry.COLUMN_NAME_FROM_IP
-			+ " TEXT" + ")";
-
 	public UglyDbHelper(Context context) {
 		super(context, DATABASE_NAME, null, DATABASE_VERSION);
 	}
@@ -796,7 +791,6 @@ public class UglyDbHelper extends SQLiteOpenHelper {
 		db.execSQL(CREATE_ATTACK_INFO_TABLE);
 		db.execSQL(CREATE_RECORD_TABLE);
 		db.execSQL(CREATE_PROFILE_TABLE);
-		db.execSQL(CREATE_PORTSCAN_TABLE);
 	}
 
 	// Upgrading database

+ 163 - 0
src/de/tudarmstadt/informatik/hostage/logging/AttackRecord.java

@@ -0,0 +1,163 @@
+package de.tudarmstadt.informatik.hostage.logging;
+
+import java.io.Serializable;
+
+import android.os.Parcel;
+import android.os.Parcelable;
+
+public class AttackRecord implements Parcelable, Serializable{
+	
+	private static final long serialVersionUID = 6111024905373724227L;
+	
+	private long attack_id;
+	private String bssid;
+	private String protocol;
+	private String localIP;
+	private int localPort;
+	private String remoteIP;
+	private int remotePort;
+	private String externalIP;
+	
+	
+    public static final Parcelable.Creator<AttackRecord> CREATOR = new Parcelable.Creator<AttackRecord>() {
+    	@Override
+        public AttackRecord createFromParcel(Parcel source) {
+                    return new AttackRecord(source);
+            }
+
+            @Override
+            public AttackRecord[] newArray(int size) {
+            	return new AttackRecord[size];
+            }
+    };
+
+    public AttackRecord() {
+
+    }
+
+    public AttackRecord(Parcel source) {
+            this.attack_id = source.readLong();
+            this.protocol = source.readString();
+            this.localIP = source.readString();
+            this.localPort = source.readInt();
+            this.remoteIP = source.readString();
+            this.remotePort = source.readInt();
+            this.externalIP = source.readString();
+            this.bssid = source.readString();
+    }
+	
+	@Override
+	public int describeContents() {
+		return 0;
+	}
+	
+	@Override
+	public void writeToParcel(Parcel dest, int flags) {
+        dest.writeLong(attack_id);
+        dest.writeString(protocol);
+        dest.writeString(localIP);
+        dest.writeInt(localPort);
+        dest.writeString(remoteIP);
+        dest.writeInt(remotePort);
+        dest.writeString(externalIP);
+        dest.writeString(bssid);
+	}
+	
+	/**
+	 * @return the attack_id
+	 */
+	public long getAttack_id() {
+		return attack_id;
+	}
+	/**
+	 * @param attack_id the attack_id to set
+	 */
+	public void setAttack_id(long attack_id) {
+		this.attack_id = attack_id;
+	}
+	/**
+	 * @return the bssid
+	 */
+	public String getBssid() {
+		return bssid;
+	}
+	/**
+	 * @param bssid the bssid to set
+	 */
+	public void setBssid(String bssid) {
+		this.bssid = bssid;
+	}
+	/**
+	 * @return the protocol
+	 */
+	public String getProtocol() {
+		return protocol;
+	}
+	/**
+	 * @param protocol the protocol to set
+	 */
+	public void setProtocol(String protocol) {
+		this.protocol = protocol;
+	}
+	/**
+	 * @return the localIP
+	 */
+	public String getLocalIP() {
+		return localIP;
+	}
+	/**
+	 * @param localIP the localIP to set
+	 */
+	public void setLocalIP(String localIP) {
+		this.localIP = localIP;
+	}
+	/**
+	 * @return the localPort
+	 */
+	public int getLocalPort() {
+		return localPort;
+	}
+	/**
+	 * @param localPort the localPort to set
+	 */
+	public void setLocalPort(int localPort) {
+		this.localPort = localPort;
+	}
+	/**
+	 * @return the remoteIP
+	 */
+	public String getRemoteIP() {
+		return remoteIP;
+	}
+	/**
+	 * @param remoteIP the remoteIP to set
+	 */
+	public void setRemoteIP(String remoteIP) {
+		this.remoteIP = remoteIP;
+	}
+	/**
+	 * @return the remotePort
+	 */
+	public int getRemotePort() {
+		return remotePort;
+	}
+	/**
+	 * @param remotePort the remotePort to set
+	 */
+	public void setRemotePort(int remotePort) {
+		this.remotePort = remotePort;
+	}
+	/**
+	 * @return the externalIP
+	 */
+	public String getExternalIP() {
+		return externalIP;
+	}
+	/**
+	 * @param externalIP the externalIP to set
+	 */
+	public void setExternalIP(String externalIP) {
+		this.externalIP = externalIP;
+	}
+
+}

+ 51 - 20
src/de/tudarmstadt/informatik/hostage/logging/Logger.java

@@ -3,29 +3,46 @@ package de.tudarmstadt.informatik.hostage.logging;
 import android.app.IntentService;
 import android.content.Context;
 import android.content.Intent;
+import android.os.Parcelable;
+import de.tudarmstadt.informatik.hostage.logging.MessageRecord.TYPE;
 import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
 
 public class Logger extends IntentService {
 
-	private static final String ACTION_LOG = "de.tudarmstadt.informatik.hostage.action.LOG";
+	private static final String ACTION_LOG_MESSAGE = "de.tudarmstadt.informatik.hostage.action.LOG_MESSAGE";
+	private static final String ACTION_LOG_ATTACK = "de.tudarmstadt.informatik.hostage.action.LOG_ATTACK";
+	private static final String ACTION_LOG_NETWORK = "de.tudarmstadt.informatik.hostage.action.LOG_NETWORK";
 	private static final String ACTION_LOG_PORTSCAN = "de.tudarmstadt.informatik.hostage.action.LOG_PORTSCAN";
 
 	private static final String EXTRA_RECORD = "de.tudarmstadt.informatik.hostage.extra.RECORD";
 	private static final String EXTRA_TIMESTAMP = "de.tudarmstadt.informatik.hostage.extra.TIMESTAMP";
-	private static final String EXTRA_IP = "de.tudarmstadt.informatik.hostage.extra.IP";
 
-	public static void log(Context context, Record record) {
+	public static void log(Context context, MessageRecord record) {
 		Intent intent = new Intent(context, Logger.class);
-		intent.setAction(ACTION_LOG);
-		intent.putExtra(EXTRA_RECORD, record);
+		intent.setAction(ACTION_LOG_MESSAGE);
+		intent.putExtra(EXTRA_RECORD, (Parcelable)record);
 		context.startService(intent);
 	}
-
-	public static void logPortscan(Context context, long timestamp, String ip) {
+	
+	public static void log(Context context, AttackRecord record) {
+		Intent intent = new Intent(context, Logger.class);
+		intent.setAction(ACTION_LOG_ATTACK);
+		intent.putExtra(EXTRA_RECORD, (Parcelable)record);
+		context.startService(intent);
+	}
+	
+	public static void log(Context context, NetworkRecord record) {
+		Intent intent = new Intent(context, Logger.class);
+		intent.setAction(ACTION_LOG_NETWORK);
+		intent.putExtra(EXTRA_RECORD, (Parcelable)record);
+		context.startService(intent);
+	}
+	
+	public static void logPortscan(Context context, AttackRecord record, long timestamp){
 		Intent intent = new Intent(context, Logger.class);
-		intent.setAction(ACTION_LOG);
+		intent.setAction(ACTION_LOG_PORTSCAN);
+		intent.putExtra(EXTRA_RECORD, (Parcelable)record);
 		intent.putExtra(EXTRA_TIMESTAMP, timestamp);
-		intent.putExtra(EXTRA_IP, ip);
 		context.startService(intent);
 	}
 
@@ -41,25 +58,39 @@ public class Logger extends IntentService {
 		mDbHelper = new HostageDBOpenHelper(getApplicationContext());
 	}
 
-	private void handleActionLog(Record record) {
-		mDbHelper.addRecord(record);
+	private void handleActionLog(MessageRecord record) {
+		mDbHelper.addMessageRecord(record);
 	}
-
-	private void handleActionLogPortscan(long timestamp, String ip) {
-		mDbHelper.insertPortscan(timestamp, ip);
+	private void handleActionLog(AttackRecord record) {
+		mDbHelper.addAttackRecord(record);
+		mDbHelper.updateSyncAttackCounter(record);
+	}
+	private void handleActionLog(NetworkRecord record) {
+		mDbHelper.updateNetworkInformation(record);
 	}
 
 	@Override
 	protected void onHandleIntent(Intent intent) {
 		if (intent != null) {
 			final String action = intent.getAction();
-			if (ACTION_LOG.equals(action)) {
-				final Record record = intent.getParcelableExtra(EXTRA_RECORD);
+			if (ACTION_LOG_MESSAGE.equals(action)) {
+				final MessageRecord record = intent.getParcelableExtra(EXTRA_RECORD);
+				handleActionLog(record);
+			}else if(ACTION_LOG_ATTACK.equals(action)){
+				final AttackRecord record = intent.getParcelableExtra(EXTRA_RECORD);
+				handleActionLog(record);
+			}else if(ACTION_LOG_NETWORK.equals(action)){
+				final NetworkRecord record = intent.getParcelableExtra(EXTRA_RECORD);
+				handleActionLog(record);
+			}else if(ACTION_LOG_PORTSCAN.equals(action)){
+				final AttackRecord record = intent.getParcelableExtra(EXTRA_RECORD);
 				handleActionLog(record);
-			} else if (ACTION_LOG_PORTSCAN.equals(action)) {
-				final long timestamp = intent.getParcelableExtra(EXTRA_TIMESTAMP);
-				final String ip = intent.getParcelableExtra(EXTRA_IP);
-				handleActionLogPortscan(timestamp, ip);
+				MessageRecord mRecord = new MessageRecord();
+				mRecord.setAttack_id(record.getAttack_id());
+				mRecord.setId(0);
+				mRecord.setPacket("");
+				mRecord.setTimestamp(intent.getLongExtra(EXTRA_TIMESTAMP, 0));
+				mRecord.setType(TYPE.RECEIVE);
 			}
 		}
 	}

+ 125 - 0
src/de/tudarmstadt/informatik/hostage/logging/MessageRecord.java

@@ -0,0 +1,125 @@
+package de.tudarmstadt.informatik.hostage.logging;
+
+import java.io.Serializable;
+
+import android.os.Parcel;
+import android.os.Parcelable;
+
+
+public class MessageRecord implements Parcelable, Serializable{
+	
+	private static final long serialVersionUID = -5936572995202342935L;
+	
+	public static enum TYPE {
+		SEND, RECEIVE
+	};
+	
+	// attack
+	private int id;
+	private long attack_id;
+	private long timestamp;
+	private TYPE type;
+	private String packet;
+	
+    public static final Parcelable.Creator<MessageRecord> CREATOR = new Parcelable.Creator<MessageRecord>() {
+    	@Override
+        public MessageRecord createFromParcel(Parcel source) {
+                    return new MessageRecord(source);
+            }
+
+            @Override
+            public MessageRecord[] newArray(int size) {
+            	return new MessageRecord[size];
+            }
+    };
+
+
+    public MessageRecord() {
+
+    }
+
+
+    public MessageRecord(Parcel source) {
+            this.id = source.readInt();
+            this.attack_id = source.readLong();
+            this.timestamp = source.readLong();
+            this.type = TYPE.valueOf(source.readString());
+            this.packet = source.readString(); 
+    }
+
+	
+	@Override
+	public int describeContents() {
+		return 0;
+	}
+	
+	@Override
+	public void writeToParcel(Parcel dest, int flags) {
+        dest.writeInt(id);
+        dest.writeLong(attack_id);
+        dest.writeLong(timestamp);
+        dest.writeString(type.name());
+        dest.writeString(packet);
+	}
+	
+	/**
+	 * @return the id
+	 */
+	public int getId() {
+		return id;
+	}
+	/**
+	 * @param id the id to set
+	 */
+	public void setId(int id) {
+		this.id = id;
+	}
+	/**
+	 * @return the attack_id
+	 */
+	public long getAttack_id() {
+		return attack_id;
+	}
+	/**
+	 * @param attack_id the attack_id to set
+	 */
+	public void setAttack_id(long attack_id) {
+		this.attack_id = attack_id;
+	}
+	/**
+	 * @return the timestamp
+	 */
+	public long getTimestamp() {
+		return timestamp;
+	}
+	/**
+	 * @param timestamp the timestamp to set
+	 */
+	public void setTimestamp(long timestamp) {
+		this.timestamp = timestamp;
+	}
+	/**
+	 * @return the type
+	 */
+	public TYPE getType() {
+		return type;
+	}
+	/**
+	 * @param type the type to set
+	 */
+	public void setType(TYPE type) {
+		this.type = type;
+	}
+	/**
+	 * @return the packet
+	 */
+	public String getPacket() {
+		return packet;
+	}
+	/**
+	 * @param packet the packet to set
+	 */
+	public void setPacket(String packet) {
+		this.packet = packet;
+	}
+}

+ 136 - 0
src/de/tudarmstadt/informatik/hostage/logging/NetworkRecord.java

@@ -0,0 +1,136 @@
+package de.tudarmstadt.informatik.hostage.logging;
+
+import java.io.Serializable;
+
+import android.os.Parcel;
+import android.os.Parcelable;
+
+public class NetworkRecord implements Parcelable, Serializable{	
+	
+	private static final long serialVersionUID = -1586629159904177836L;
+
+	private String bssid;
+	private String ssid;
+	private long timestampLocation;
+	private double latitude;
+	private double longitude;
+	private float accuracy;
+	
+    public static final Parcelable.Creator<NetworkRecord> CREATOR = new Parcelable.Creator<NetworkRecord>() {
+    	@Override
+        public NetworkRecord createFromParcel(Parcel source) {
+                    return new NetworkRecord(source);
+            }
+
+            @Override
+            public NetworkRecord[] newArray(int size) {
+            	return new NetworkRecord[size];
+            }
+    };
+
+
+    public NetworkRecord() {
+
+    }
+
+
+    public NetworkRecord(Parcel source) {
+            this.bssid = source.readString();
+            this.ssid = source.readString();  
+            this.timestampLocation = source.readLong();
+            this.latitude = source.readDouble();
+            this.longitude = source.readDouble();
+            this.accuracy = source.readFloat();
+    }
+
+	
+	@Override
+	public int describeContents() {
+		return 0;
+	}
+	
+	@Override
+	public void writeToParcel(Parcel dest, int flags) {
+        dest.writeString(bssid);
+        dest.writeString(ssid);
+        dest.writeLong(timestampLocation);
+        dest.writeDouble(latitude);
+        dest.writeDouble(longitude);
+        dest.writeFloat(accuracy);
+
+	}
+	
+	/**
+	 * @return the bssid
+	 */
+	public String getBssid() {
+		return bssid;
+	}
+	/**
+	 * @param bssid the bssid to set
+	 */
+	public void setBssid(String bssid) {
+		this.bssid = bssid;
+	}
+	/**
+	 * @return the ssid
+	 */
+	public String getSsid() {
+		return ssid;
+	}
+	/**
+	 * @param ssid the ssid to set
+	 */
+	public void setSsid(String ssid) {
+		this.ssid = ssid;
+	}
+	/**
+	 * @return the timestampLocation
+	 */
+	public long getTimestampLocation() {
+		return timestampLocation;
+	}
+	/**
+	 * @param timestampLocation the timestampLocation to set
+	 */
+	public void setTimestampLocation(long timestampLocation) {
+		this.timestampLocation = timestampLocation;
+	}
+	/**
+	 * @return the latitude
+	 */
+	public double getLatitude() {
+		return latitude;
+	}
+	/**
+	 * @param latitude the latitude to set
+	 */
+	public void setLatitude(double latitude) {
+		this.latitude = latitude;
+	}
+	/**
+	 * @return the longitude
+	 */
+	public double getLongitude() {
+		return longitude;
+	}
+	/**
+	 * @param longitude the longitude to set
+	 */
+	public void setLongitude(double longitude) {
+		this.longitude = longitude;
+	}
+	/**
+	 * @return the accuracy
+	 */
+	public float getAccuracy() {
+		return accuracy;
+	}
+	/**
+	 * @param accuracy the accuracy to set
+	 */
+	public void setAccuracy(float accuracy) {
+		this.accuracy = accuracy;
+	}
+
+}

+ 47 - 133
src/de/tudarmstadt/informatik/hostage/logging/Record.java

@@ -1,218 +1,159 @@
 package de.tudarmstadt.informatik.hostage.logging;
 
-import android.os.Parcel;
-import android.os.Parcelable;
+import de.tudarmstadt.informatik.hostage.logging.MessageRecord.TYPE;
 import de.tudarmstadt.informatik.hostage.logging.formatter.Formatter;
 
-public class Record implements Parcelable {
-
-	public static enum TYPE {
-		SEND, RECEIVE
-	};
+public class Record {
 
+	//
+	private MessageRecord message;
 	// attack
-	private int id;
-	private long attack_id;
-	private long timestamp;
-	private String protocol;
-	private TYPE type;
-	private String packet;
-
+	private AttackRecord attack;
 	// network
-	private String localIP;
-	private int localPort;
-	private String remoteIP;
-	private int remotePort;
-	private String externalIP;
-	private String bssid;
-	private String ssid;
-
-	// location
-	private long timestampLocation;
-	private double latitude;
-	private double longitude;
-	private float accuracy;
-
-	public static final Parcelable.Creator<Record> CREATOR = new Parcelable.Creator<Record>() {
-
-		@Override
-		public Record createFromParcel(Parcel source) {
-			return new Record(source);
-		}
-
-		@Override
-		public Record[] newArray(int size) {
-			return new Record[size];
-		}
-	};
-
-	public Record() {
-	}
-
-	public Record(Parcel source) {
-		// attack
-		this.id = source.readInt();
-		this.attack_id = source.readLong();
-		this.timestamp = source.readLong();
-		this.protocol = source.readString();
-		this.type = TYPE.valueOf(source.readString());
-		this.packet = source.readString();
-
-		// network
-		this.localIP = source.readString();
-		this.localPort = source.readInt();
-		this.remoteIP = source.readString();
-		this.remotePort = source.readInt();
-		this.externalIP = source.readString();
-		this.bssid = source.readString();
-		this.ssid = source.readString();
-
-		// location
-		this.timestampLocation = source.readLong();
-		this.latitude = source.readDouble();
-		this.longitude = source.readDouble();
-		this.accuracy = source.readFloat();
-	}
-
-	@Override
-	public int describeContents() {
-		return 0;
+	private NetworkRecord network;
+	
+	public Record(){
+		message = new MessageRecord();
+		attack = new AttackRecord();
+		network = new NetworkRecord();
 	}
 
 	public float getAccuracy() {
-		return accuracy;
+		return network.getAccuracy();
 	}
 
 	public long getAttack_id() {
-		return attack_id;
+		return attack.getAttack_id();
 	}
 
 	public String getBssid() {
-		return bssid;
+		return network.getBssid();
 	}
 
 	public String getExternalIP() {
-		return externalIP;
+		return attack.getExternalIP();
 	}
 
 	public int getId() {
-		return id;
+		return message.getId();
 	}
 
 	public double getLatitude() {
-		return latitude;
+		return network.getLatitude();
 	}
 
 	public String getLocalIP() {
-		return localIP;
+		return attack.getLocalIP();
 	}
 
 	public int getLocalPort() {
-		return localPort;
+		return attack.getLocalPort();
 	}
 
 	public double getLongitude() {
-		return longitude;
+		return network.getLongitude();
 	}
 
 	public String getPacket() {
-		return packet;
+		return message.getPacket();
 	}
 
 	public String getProtocol() {
-		return protocol;
+		return attack.getProtocol();
 	}
 
 	public String getRemoteIP() {
-		return remoteIP;
+		return attack.getRemoteIP();
 	}
 
 	public int getRemotePort() {
-		return remotePort;
+		return attack.getRemotePort();
 	}
 
 	public String getSsid() {
-		return ssid;
+		return network.getSsid();
 	}
 
 	public long getTimestamp() {
-		return timestamp;
+		return message.getTimestamp();
 	}
 
 	public long getTimestampLocation() {
-		return timestampLocation;
+		return network.getTimestampLocation();
 	}
 
 	public TYPE getType() {
-		return type;
+		return message.getType();
 	}
 
 	public void setAccuracy(float accuracy) {
-		this.accuracy = accuracy;
+		network.setAccuracy(accuracy);
 	}
 
 	public void setAttack_id(long attack_id) {
-		this.attack_id = attack_id;
+		message.setAttack_id(attack_id);
+		attack.setAttack_id(attack_id);
 	}
 
 	public void setBssid(String bssid) {
-		this.bssid = bssid;
+		attack.setBssid(bssid);
+		network.setBssid(bssid);
 	}
 
 	public void setExternalIP(String externalIP) {
-		this.externalIP = externalIP;
+		attack.setExternalIP(externalIP);
 	}
 
 	public void setId(int id) {
-		this.id = id;
+		message.setId(id);
 	}
 
 	public void setLatitude(double latitude) {
-		this.latitude = latitude;
+		network.setLatitude(latitude);
 	}
 
 	public void setLocalIP(String localIP) {
-		this.localIP = localIP;
+		attack.setLocalIP(localIP);
 	}
 
 	public void setLocalPort(int localPort) {
-		this.localPort = localPort;
+		attack.setLocalPort(localPort);
 	}
 
 	public void setLongitude(double longitude) {
-		this.longitude = longitude;
+		network.setLongitude(longitude);
 	}
 
 	public void setPacket(String packet) {
-		this.packet = packet;
+		message.setPacket(packet);
 	}
 
 	public void setProtocol(String protocol) {
-		this.protocol = protocol;
+		attack.setProtocol(protocol);
 	}
 
 	public void setRemoteIP(String remoteIP) {
-		this.remoteIP = remoteIP;
+		attack.setRemoteIP(remoteIP);
 	}
 
 	public void setRemotePort(int remotePort) {
-		this.remotePort = remotePort;
+		attack.setRemotePort(remotePort);
 	}
 
 	public void setSsid(String ssid) {
-		this.ssid = ssid;
+		network.setSsid(ssid);
 	}
 
 	public void setTimestamp(long timestamp) {
-		this.timestamp = timestamp;
+		message.setTimestamp(timestamp);
 	}
 
 	public void setTimestampLocation(long timestampLocation) {
-		this.timestampLocation = timestampLocation;
+		network.setTimestampLocation(timestampLocation);
 	}
 
 	public void setType(TYPE type) {
-		this.type = type;
+		message.setType(type);
 	}
 
 	@Override
@@ -226,31 +167,4 @@ public class Record implements Parcelable {
 		}
 		return formatter.format(this);
 	}
-
-	@Override
-	public void writeToParcel(Parcel dest, int flags) {
-		// attack
-		dest.writeInt(id);
-		dest.writeLong(attack_id);
-		dest.writeLong(timestamp);
-		dest.writeString(protocol);
-		dest.writeString(type.name());
-		dest.writeString(packet);
-
-		// network
-		dest.writeString(localIP);
-		dest.writeInt(localPort);
-		dest.writeString(remoteIP);
-		dest.writeInt(remotePort);
-		dest.writeString(externalIP);
-		dest.writeString(bssid);
-		dest.writeString(ssid);
-
-		// location
-		dest.writeLong(timestampLocation);
-		dest.writeDouble(latitude);
-		dest.writeDouble(longitude);
-		dest.writeFloat(accuracy);
-	}
-
 }

+ 63 - 0
src/de/tudarmstadt/informatik/hostage/logging/SyncInfoRecord.java

@@ -0,0 +1,63 @@
+package de.tudarmstadt.informatik.hostage.logging;
+
+import java.io.Serializable;
+
+public class SyncInfoRecord implements Serializable{	
+
+	private static final long serialVersionUID = 7156818788190434192L;
+	
+	private String deviceID;
+	private String BSSID;
+	private long number_of_attacks;
+	private long number_of_portscans;
+	
+	/**
+	 * @return the deviceID
+	 */
+	public String getDeviceID() {
+		return deviceID;
+	}
+	/**
+	 * @param deviceID the deviceID to set
+	 */
+	public void setDeviceID(String deviceID) {
+		this.deviceID = deviceID;
+	}
+	/**
+	 * @return the bSSID
+	 */
+	public String getBSSID() {
+		return BSSID;
+	}
+	/**
+	 * @param bSSID the bSSID to set
+	 */
+	public void setBSSID(String bSSID) {
+		BSSID = bSSID;
+	}
+	/**
+	 * @return the number_of_attacks
+	 */
+	public long getNumber_of_attacks() {
+		return number_of_attacks;
+	}
+	/**
+	 * @param number_of_attacks the number_of_attacks to set
+	 */
+	public void setNumber_of_attacks(long number_of_attacks) {
+		this.number_of_attacks = number_of_attacks;
+	}
+	/**
+	 * @return the number_of_portscans
+	 */
+	public long getNumber_of_portscans() {
+		return number_of_portscans;
+	}
+	/**
+	 * @param number_of_portscans the number_of_portscans to set
+	 */
+	public void setNumber_of_portscans(long number_of_portscans) {
+		this.number_of_portscans = number_of_portscans;
+	}
+
+}

+ 17 - 9
src/de/tudarmstadt/informatik/hostage/persistence/HostageDBContract.java

@@ -40,14 +40,22 @@ public final class HostageDBContract {
 
 		public static final String KEY_ID = COLUMN_NAME_ID;
 	}
-
-	public static abstract class PortscanEntry implements BaseColumns {
-		public static final String TABLE_NAME = "portscan";
-		public static final String COLUMN_NAME_ID = "_id";
-		public static final String COLUMN_NAME_PORTSCAN_TIMESTAMP = "portscan_timestamp";
-		public static final String COLUMN_NAME_FROM_IP = "from_ip";
-
-		public static final String KEY_ID = COLUMN_NAME_ID;
+	
+	public static abstract class SyncDeviceEntry implements BaseColumns {
+		public static final String TABLE_NAME = "sync_devices";
+		public static final String COLUMN_NAME_DEVICE_ID = "_device_id";	
+		public static final String COLUMN_NAME_DEVICE_TIMESTAMP = "last_sync_timestamp";
+		
+		public static final String KEY_ID = COLUMN_NAME_DEVICE_ID;
+	}
+	
+	public static abstract class SyncInfoEntry implements BaseColumns {
+		public static final String TABLE_NAME = "sync_info";
+		public static final String COLUMN_NAME_DEVICE_ID = "_device_id";	
+		public static final String COLUMN_NAME_BSSID = "_bssid";
+		public static final String COLUMN_NAME_NUMBER_ATTACKS = "number_of_attacks";
+		public static final String COLUMN_NAME_NUMBER_PORTSCANS = "number_of_portscans";		
+		
+		public static final String KEY_ID = COLUMN_NAME_DEVICE_ID;
 	}
-
 }

+ 427 - 266
src/de/tudarmstadt/informatik/hostage/persistence/HostageDBOpenHelper.java

@@ -9,17 +9,22 @@ import android.database.Cursor;
 import android.database.sqlite.SQLiteDatabase;
 import android.database.sqlite.SQLiteOpenHelper;
 import android.util.Log;
-import de.tudarmstadt.informatik.hostage.logging.Record;
-import de.tudarmstadt.informatik.hostage.logging.Record.TYPE;
+import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
+import de.tudarmstadt.informatik.hostage.logging.AttackRecord;
+import de.tudarmstadt.informatik.hostage.logging.MessageRecord;
+import de.tudarmstadt.informatik.hostage.logging.NetworkRecord;
+import de.tudarmstadt.informatik.hostage.logging.SyncInfoRecord;
 import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract.AttackEntry;
 import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract.NetworkEntry;
 import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract.PacketEntry;
-import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract.PortscanEntry;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract.SyncDeviceEntry;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract.SyncInfoEntry;
 
 public class HostageDBOpenHelper extends SQLiteOpenHelper {
 
 	private static final String DATABASE_NAME = "hostage.db";
 	private static final int DATABASE_VERSION = 1;
+	private Context context;
 
 	static {
 		StringBuilder networkSQLBuilder = new StringBuilder("CREATE TABLE ").append(NetworkEntry.TABLE_NAME).append("(");
@@ -57,105 +62,151 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 				AttackEntry.COLUMN_NAME_ATTACK_ID));
 		packetSQLBuilder.append(")");
 		SQL_CREATE_PACKET_ENTRIES = packetSQLBuilder.toString();
+		
+		StringBuilder syncDevicesSQLBuilder = new StringBuilder("CREATE TABLE ").append(SyncDeviceEntry.TABLE_NAME).append("(");
+		syncDevicesSQLBuilder.append(SyncDeviceEntry.COLUMN_NAME_DEVICE_ID).append(" TEXT PRIMARY KEY,");
+		syncDevicesSQLBuilder.append(SyncDeviceEntry.COLUMN_NAME_DEVICE_TIMESTAMP).append(" INTEGER");
+		syncDevicesSQLBuilder.append(")");
+		SQL_CREATE_SYNC_DEVICES_ENTRIES = syncDevicesSQLBuilder.toString();
+		
+		StringBuilder syncInfoSQLBuilder = new StringBuilder("CREATE TABLE ").append(SyncInfoEntry.TABLE_NAME).append("(");
+		syncInfoSQLBuilder.append(SyncInfoEntry.COLUMN_NAME_DEVICE_ID).append(" TEXT,");
+		syncInfoSQLBuilder.append(SyncInfoEntry.COLUMN_NAME_BSSID).append(" TEXT,");
+		syncInfoSQLBuilder.append(SyncInfoEntry.COLUMN_NAME_NUMBER_ATTACKS).append(" INTEGER,");
+		syncInfoSQLBuilder.append(SyncInfoEntry.COLUMN_NAME_NUMBER_PORTSCANS).append(" INTEGER,");
+		syncInfoSQLBuilder.append(String.format("PRIMARY KEY(%s,%s)", SyncInfoEntry.COLUMN_NAME_DEVICE_ID, SyncInfoEntry.COLUMN_NAME_BSSID));
+		syncInfoSQLBuilder.append(String.format("FOREIGN KEY(%s) REFERENCES %s(%s)", SyncInfoEntry.COLUMN_NAME_BSSID, NetworkEntry.TABLE_NAME,
+				NetworkEntry.COLUMN_NAME_BSSID));
+		syncInfoSQLBuilder.append(")");
+		SQL_CREATE_SYNC_INFO_ENTRIES = syncInfoSQLBuilder.toString();
+		
+
 	}
 
 	private static final String SQL_CREATE_NETWORK_ENTRIES;
 	private static final String SQL_CREATE_ATTACK_ENTRIES;
 	private static final String SQL_CREATE_PACKET_ENTRIES;
+	private static final String SQL_CREATE_SYNC_DEVICES_ENTRIES;
+	private static final String SQL_CREATE_SYNC_INFO_ENTRIES;
 
 	private static final String SQL_DELETE_PACKET_ENTRIES = "DROP TABLE IF EXISTS " + PacketEntry.TABLE_NAME;
 	private static final String SQL_DELETE_ATTACK_ENTRIES = "DROP TABLE IF EXISTS " + AttackEntry.TABLE_NAME;
 	private static final String SQL_DELETE_NETWORK_ENTRIES = "DROP TABLE IF EXISTS " + NetworkEntry.TABLE_NAME;
+	private static final String SQL_DELETE_SYNC_DEVICES_ENTRIES = "DROP TABLE IF EXISTS " + SyncDeviceEntry.TABLE_NAME;
+	private static final String SQL_DELETE_SYNC_INFO_ENTRIES = "DROP TABLE IF EXISTS " + SyncInfoEntry.TABLE_NAME;
 
 	public HostageDBOpenHelper(Context context) {
 		super(context, DATABASE_NAME, null, DATABASE_VERSION);
+		this.context = context;
 	}
 
 	@Override
 	public void onCreate(SQLiteDatabase db) {
-		db.execSQL(SQL_CREATE_PACKET_ENTRIES);
-		db.execSQL(SQL_CREATE_ATTACK_ENTRIES);
 		db.execSQL(SQL_CREATE_NETWORK_ENTRIES);
+		db.execSQL(SQL_CREATE_ATTACK_ENTRIES);
+		db.execSQL(SQL_CREATE_PACKET_ENTRIES);
+		db.execSQL(SQL_CREATE_SYNC_DEVICES_ENTRIES);
+		db.execSQL(SQL_CREATE_SYNC_INFO_ENTRIES);
 	}
 
 	@Override
 	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
+		db.execSQL(SQL_DELETE_SYNC_INFO_ENTRIES);
 		db.execSQL(SQL_DELETE_PACKET_ENTRIES);
 		db.execSQL(SQL_DELETE_ATTACK_ENTRIES);
 		db.execSQL(SQL_DELETE_NETWORK_ENTRIES);
+		db.execSQL(SQL_DELETE_SYNC_DEVICES_ENTRIES);
 		onCreate(db);
 	}
 
 	/**
-	 * Adds a given {@link Record} to the database.
+	 * Adds a given {@link MessageRecord} to the database.
 	 * 
 	 * @param record
-	 *            The added {@link Record} .
+	 *            The added {@link MessageRecord} .
 	 */
-	public void addRecord(Record record) {
+	public void addMessageRecord(MessageRecord record) {
 		SQLiteDatabase db = this.getWritableDatabase();
 
-		HashMap<String, Object> bssidValues = new HashMap<String, Object>();
-		bssidValues.put(NetworkEntry.COLUMN_NAME_BSSID, record.getBssid());
-		bssidValues.put(NetworkEntry.COLUMN_NAME_SSID, record.getSsid());
-		bssidValues.put(NetworkEntry.COLUMN_NAME_LATITUDE, record.getLatitude());
-		bssidValues.put(NetworkEntry.COLUMN_NAME_LONGITUDE, record.getLongitude());
-		bssidValues.put(NetworkEntry.COLUMN_NAME_ACCURACY, record.getAccuracy());
-		bssidValues.put(NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP, record.getTimestampLocation());
+		ContentValues recordValues = new ContentValues();
+		recordValues.put(PacketEntry.COLUMN_NAME_ID, record.getId()); // Log Message Number
+		recordValues.put(PacketEntry.COLUMN_NAME_ATTACK_ID, record.getAttack_id()); // Log Attack ID
+		recordValues.put(PacketEntry.COLUMN_NAME_TYPE, record.getType().name()); // Log Type
+		recordValues.put(PacketEntry.COLUMN_NAME_PACKET_TIMESTAMP, record.getTimestamp()); // Log Timestamp
+		recordValues.put(PacketEntry.COLUMN_NAME_PACKET, record.getPacket()); // Log Packet
+
+		// Inserting Rows
+		db.insert(PacketEntry.TABLE_NAME, null, recordValues);
+		db.close(); // Closing database connection
+	}
+	
+	/**
+	 * Adds a given {@link AttackRecord} to the database.
+	 * 
+	 * @param record
+	 *            The added {@link AttackRecord} .
+	 */
+	public void addAttackRecord(AttackRecord record) {
+		Log.i("DBHelper", "Add Attack Record with id: " + record.getAttack_id());
+		SQLiteDatabase db = this.getWritableDatabase();
 
 		ContentValues attackValues = new ContentValues();
-		attackValues.put(AttackEntry.COLUMN_NAME_ATTACK_ID, record.getAttack_id()); // Log
-																					// Attack
-																					// ID
+		attackValues.put(AttackEntry.COLUMN_NAME_ATTACK_ID, record.getAttack_id()); // Log Attack ID
 		attackValues.put(AttackEntry.COLUMN_NAME_PROTOCOL, record.getProtocol().toString());
 		attackValues.put(AttackEntry.COLUMN_NAME_EXTERNAL_IP, record.getExternalIP());
-		attackValues.put(AttackEntry.COLUMN_NAME_LOCAL_IP, record.getLocalIP()); // Log
-																					// Local
-																					// IP
+		attackValues.put(AttackEntry.COLUMN_NAME_LOCAL_IP, record.getLocalIP()); // Log Local IP
 		attackValues.put(AttackEntry.COLUMN_NAME_LOCAL_PORT, record.getLocalPort());
-		attackValues.put(AttackEntry.COLUMN_NAME_REMOTE_IP, record.getRemoteIP()); // Log
-																					// Remote
-																					// IP
-		attackValues.put(AttackEntry.COLUMN_NAME_REMOTE_PORT, record.getRemotePort()); // Log
-																						// Remote
-																						// Port
+		attackValues.put(AttackEntry.COLUMN_NAME_REMOTE_IP, record.getRemoteIP()); // Log Remote IP
+		attackValues.put(AttackEntry.COLUMN_NAME_REMOTE_PORT, record.getRemotePort()); // Log Remote Port
 		attackValues.put(AttackEntry.COLUMN_NAME_BSSID, record.getBssid());
-
-		ContentValues recordValues = new ContentValues();
-		recordValues.put(PacketEntry.COLUMN_NAME_ID, record.getId()); // Log
-																		// Message
-																		// Number
-		recordValues.put(PacketEntry.COLUMN_NAME_ATTACK_ID, record.getAttack_id()); // Log
-																					// Attack
-																					// ID
-		recordValues.put(PacketEntry.COLUMN_NAME_TYPE, record.getType().name()); // Log
-																					// Type
-		recordValues.put(PacketEntry.COLUMN_NAME_PACKET_TIMESTAMP, record.getTimestamp()); // Log
-																							// Timestamp
-		recordValues.put(PacketEntry.COLUMN_NAME_PACKET, record.getPacket()); // Log
-																				// Packet
+		
 
 		// Inserting Rows
 		db.insertWithOnConflict(AttackEntry.TABLE_NAME, null, attackValues, SQLiteDatabase.CONFLICT_REPLACE);
-		db.insert(PacketEntry.TABLE_NAME, null, recordValues);
 		db.close(); // Closing database connection
-		// Update Network Information
-		updateNetworkInformation(bssidValues);
 	}
-
-	public void insertPortscan(long timestamp, String ip) {
+	
+	public void updateSyncAttackCounter(AttackRecord record){
+		
 		SQLiteDatabase db = this.getWritableDatabase();
 
-		ContentValues portscanValues = new ContentValues();
-		portscanValues.put(PortscanEntry.COLUMN_NAME_PORTSCAN_TIMESTAMP, timestamp);
-		portscanValues.put(PortscanEntry.COLUMN_NAME_FROM_IP, ip);
+		String mac = HelperUtils.getMacAdress(context);
+		ContentValues syncDeviceValues = new ContentValues();
+		syncDeviceValues.put(SyncDeviceEntry.COLUMN_NAME_DEVICE_ID, mac);
+		syncDeviceValues.put(SyncDeviceEntry.COLUMN_NAME_DEVICE_TIMESTAMP, System.currentTimeMillis());
+		
+		String query = "SELECT  * FROM " + SyncInfoEntry.TABLE_NAME + 
+					  " WHERE " + SyncInfoEntry.COLUMN_NAME_DEVICE_ID + " = ? " +
+					   "AND " + SyncInfoEntry.COLUMN_NAME_BSSID + " = ?";
+		Cursor cursor = db.rawQuery(query, new String[] {mac, record.getBssid()});
+		long attackCount = 0;
+		long portscanCount = 0;
+		if (cursor.moveToFirst()){
+			attackCount = cursor.getLong(2);
+			portscanCount = cursor.getLong(3);
+		}			
+		
+		if("PORTSCAN".equals(record.getProtocol())){
+			portscanCount++;
+		}else { attackCount++; }
+			
+		Log.i("DBHelper", "Update number of attack: " + attackCount);
+		
+		ContentValues synInfoValues = new ContentValues();
+		synInfoValues.put(SyncInfoEntry.COLUMN_NAME_BSSID, record.getBssid());
+		synInfoValues.put(SyncInfoEntry.COLUMN_NAME_DEVICE_ID, mac);
+		synInfoValues.put(SyncInfoEntry.COLUMN_NAME_NUMBER_ATTACKS, attackCount);
+		synInfoValues.put(SyncInfoEntry.COLUMN_NAME_NUMBER_PORTSCANS, portscanCount);
 
-		db.insert(PortscanEntry.TABLE_NAME, null, portscanValues);
+		// Inserting Rows
+		db.insertWithOnConflict(SyncInfoEntry.TABLE_NAME, null, synInfoValues, SQLiteDatabase.CONFLICT_REPLACE);
+		db.insertWithOnConflict(SyncDeviceEntry.TABLE_NAME, null, syncDeviceValues, SQLiteDatabase.CONFLICT_REPLACE);
+		db.close(); // Closing database connection
 	}
+	
 
 	/**
-	 * Determines if a network with given BSSID has already been recorded as
-	 * malicious.
+	 * Determines if a network with given BSSID has already been recorded as malicious.
 	 * 
 	 * @param BSSID
 	 *            The BSSID of the network.
@@ -163,9 +214,9 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 	 *         BSSID, else false.
 	 */
 	public boolean bssidSeen(String BSSID) {
-		String countQuery = "SELECT  * FROM " + NetworkEntry.TABLE_NAME + " WHERE " + NetworkEntry.COLUMN_NAME_BSSID + " = " + "'" + BSSID + "'";
+		String countQuery = "SELECT  * FROM " + NetworkEntry.TABLE_NAME + " WHERE " + NetworkEntry.COLUMN_NAME_BSSID + " = ?";
 		SQLiteDatabase db = this.getReadableDatabase();
-		Cursor cursor = db.rawQuery(countQuery, null);
+		Cursor cursor = db.rawQuery(countQuery, new String[] {BSSID});
 		int result = cursor.getCount();
 		cursor.close();
 		db.close();
@@ -186,52 +237,19 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 	 *         network with the given BSSID, else false.
 	 */
 	public boolean bssidSeen(String protocol, String BSSID) {
+		if(BSSID == null || protocol == null){
+			return false;
+		}
 		String countQuery = "SELECT  * FROM " + AttackEntry.TABLE_NAME + " NATURAL JOIN " + NetworkEntry.TABLE_NAME + " WHERE "
-				+ AttackEntry.COLUMN_NAME_PROTOCOL + " = " + "'" + protocol + "'" + " AND " + NetworkEntry.COLUMN_NAME_BSSID + " = " + "'" + BSSID + "'";
+				+ AttackEntry.COLUMN_NAME_PROTOCOL + " = ? AND " + NetworkEntry.COLUMN_NAME_BSSID + " = ?";
 		SQLiteDatabase db = this.getReadableDatabase();
-		Cursor cursor = db.rawQuery(countQuery, null);
+		Cursor cursor = db.rawQuery(countQuery, new String[]{protocol, BSSID});
 		int result = cursor.getCount();
 		cursor.close();
 		db.close();
 		return result > 0;
 	}
 
-	/**
-	 * Deletes all records from {@link #PacketEntry.TABLE_NAME}.
-	 */
-	public void clearData() {
-		SQLiteDatabase db = this.getReadableDatabase();
-		db.delete(PacketEntry.TABLE_NAME, null, null);
-		db.delete(AttackEntry.TABLE_NAME, null, null);
-		db.close();
-	}
-
-	/**
-	 * Deletes all records from {@link #PacketEntry.TABLE_NAME} with a specific BSSID.
-	 * 
-	 * @param bssid
-	 *            The BSSID to match against.
-	 */
-	public void deleteByBSSID(String bssid) {
-		SQLiteDatabase db = this.getReadableDatabase();
-		db.delete(NetworkEntry.TABLE_NAME, NetworkEntry.COLUMN_NAME_BSSID + " = ?", new String[] { bssid });
-		db.delete(AttackEntry.TABLE_NAME, AttackEntry.COLUMN_NAME_BSSID + " = ?", new String[] { bssid });
-		db.close();
-	}
-
-	/**
-	 * Deletes all records from {@link #PacketEntry.TABLE_NAME} with a time stamp smaller
-	 * then the given
-	 * 
-	 * @param date
-	 *            A Date represented in milliseconds.
-	 */
-	public void deleteByDate(long date) {
-		SQLiteDatabase db = this.getReadableDatabase();
-		String deleteQuery = "DELETE  FROM " + PacketEntry.TABLE_NAME + " WHERE " + PacketEntry.COLUMN_NAME_PACKET_TIMESTAMP + " < " + date;
-		db.execSQL(deleteQuery);
-		db.close();
-	}
 
 	/**
 	 * Returns a String array with all BSSIDs stored in the database.
@@ -257,73 +275,38 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 	}
 
 	/**
-	 * Gets all received {@link Record Records} for every attack identified by
-	 * its attack id and ordered by date.
+	 * Determines the number of different attacks in the database.
 	 * 
-	 * @return A ArrayList with all received {@link Record Records} for each
-	 *         attack id in the Database.
+	 * @return The number of different attacks in the database.
 	 */
-	public ArrayList<Record> getAllReceivedRecordsOfEachAttack() {
-		ArrayList<Record> recordList = new ArrayList<Record>();
-		String selectQuery = "SELECT  * FROM " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " NATURAL JOIN "
-				+ NetworkEntry.TABLE_NAME + " WHERE " + PacketEntry.COLUMN_NAME_TYPE + "='RECEIVE'" + " ORDER BY " + PacketEntry.COLUMN_NAME_PACKET_TIMESTAMP;
+	public int getAttackCount() {
 		SQLiteDatabase db = this.getReadableDatabase();
-		Cursor cursor = db.rawQuery(selectQuery, null);
-
-		// looping through all rows and adding to list
-		if (cursor.moveToFirst()) {
-			do {
-				Record record = createRecord(cursor);
-				// Adding record to list
-				recordList.add(record);
-			} while (cursor.moveToNext());
-		}
+		String countQuery = "SELECT  * FROM " + AttackEntry.TABLE_NAME + 
+				           " WHERE " + AttackEntry.COLUMN_NAME_PROTOCOL + " <> ?";		
+		Cursor cursor = db.rawQuery(countQuery, new String[]{"PORTSCAN"});
+		int result = cursor.getCount();
 		cursor.close();
 
-		// return record list
-		db.close();
-		return recordList;
-	}
-
-	/**
-	 * Gets all {@link Record Records} saved in the database.
-	 * 
-	 * @return A ArrayList of all the {@link Record Records} in the Database.
-	 */
-	public ArrayList<Record> getAllRecords() {
-		ArrayList<Record> recordList = new ArrayList<Record>();
-		// Select All Query
-		String selectQuery = "SELECT  * FROM " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " JOIN " + NetworkEntry.TABLE_NAME
-				+ " USING (_bssid)";
-
-		SQLiteDatabase db = this.getWritableDatabase();
-		Cursor cursor = db.rawQuery(selectQuery, null);
-
-		Log.i("Database", "Start loop");
-		// looping through all rows and adding to list
-		if (cursor.moveToFirst()) {
-			do {
-				Log.i("Database", "Add Record");
-				Record record = createRecord(cursor);
-				// Adding record to list
-				recordList.add(record);
-			} while (cursor.moveToNext());
-		}
-		cursor.close();
+		// return count
 		db.close();
-		// return record list
-		return recordList;
+		return result;
 	}
-
+	
 	/**
-	 * Determines the number of different attack_ids in the database.
-	 * 
-	 * @return The number of different attack_ids in the database.
+	 * Determines the number of different recorded attacks in a specific access point since the given attack_id.
+	 * The given attack_id is not included.
+	 * @param attack_id  The attack id to match the query against.
+	 * @param bssid  The BSSID of the access point. 
+	 * @return The number of different attacks in the database since the given attack_id.
 	 */
-	public int getAttackCount() {
-		String countQuery = "SELECT  * FROM " + AttackEntry.TABLE_NAME;
+	public int getAttackCount(int attack_id, String bssid) {
 		SQLiteDatabase db = this.getReadableDatabase();
-		Cursor cursor = db.rawQuery(countQuery, null);
+		String countQuery = "SELECT * FROM " + AttackEntry.TABLE_NAME + 
+				           " WHERE "+ AttackEntry.COLUMN_NAME_PROTOCOL + " <> ? " +
+				           	"AND " + AttackEntry.COLUMN_NAME_ATTACK_ID + " > ? " +
+				           	"AND " + AttackEntry.COLUMN_NAME_BSSID + " = ?";			
+		String[] selectArgs = new String[]{"PORTSCAN", attack_id + "", bssid};
+		Cursor cursor = db.rawQuery(countQuery, selectArgs);
 		int result = cursor.getCount();
 		cursor.close();
 
@@ -331,21 +314,23 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 		db.close();
 		return result;
 	}
+	
 
 	/**
-	 * Determines the number of different attack_ids for a specific protocol in
+	 * Determines the number of different attacks for a specific protocol in
 	 * the database.
 	 * 
 	 * @param protocol
 	 *            The String representation of the
 	 *            {@link de.tudarmstadt.informatik.hostage.protocol.Protocol
 	 *            Protocol}
-	 * @return The number of different attack_ids in the database.
+	 * @return The number of different attacks in the database.
 	 */
 	public int getAttackPerProtocolCount(String protocol) {
-		String countQuery = "SELECT  * FROM " + AttackEntry.TABLE_NAME + " WHERE " + AttackEntry.COLUMN_NAME_PROTOCOL + " = " + "'" + protocol + "'";
 		SQLiteDatabase db = this.getReadableDatabase();
-		Cursor cursor = db.rawQuery(countQuery, null);
+		String countQuery = "SELECT * FROM " + AttackEntry.TABLE_NAME + 
+		                   " WHERE "+ AttackEntry.COLUMN_NAME_PROTOCOL + " = ? ";	
+		Cursor cursor = db.rawQuery(countQuery, new String[]{protocol});
 		int result = cursor.getCount();
 		cursor.close();
 
@@ -353,77 +338,86 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 		db.close();
 		return result;
 	}
-
+	
 	/**
-	 * Determines the highest attack id stored in the database.
+	 * Determines the number of  attacks for a specific protocol in
+	 * the database since the given attack_id.
 	 * 
-	 * @return The highest attack id stored in the database.
+	 * @param protocol
+	 *            The String representation of the
+	 *            {@link de.tudarmstadt.informatik.hostage.protocol.Protocol
+	 *            Protocol}
+	 * @param attack_id  The attack id to match the query against.
+	 * @return The number of different attacks in the database since the given attack_id.
 	 */
-	public long getHighestAttackId() {
-		String selectQuery = "SELECT MAX(" + AttackEntry.COLUMN_NAME_ATTACK_ID + ") FROM " + AttackEntry.TABLE_NAME;
+	public int getAttackPerProtocolCount(String protocol, int attack_id) {
 		SQLiteDatabase db = this.getReadableDatabase();
-		Cursor cursor = db.rawQuery(selectQuery, null);
-		int result;
-
-		if (cursor.moveToFirst()) {
-			result = cursor.getInt(0);
-		} else {
-			result = -1;
-		}
+		String countQuery = "SELECT * FROM " + AttackEntry.TABLE_NAME + 
+                		   " WHERE "+ AttackEntry.COLUMN_NAME_PROTOCOL + " = ? " +
+                		    "AND " + AttackEntry.COLUMN_NAME_ATTACK_ID + " > ? ";	
+		Cursor cursor = db.rawQuery(countQuery, new String[]{protocol, attack_id + ""});
+		int result = cursor.getCount();
 		cursor.close();
+
+		// return count
 		db.close();
 		return result;
 	}
-
-	public ArrayList<HashMap<String, Object>> getNetworkInformation() {
-		String selectQuery = "SELECT  * FROM " + NetworkEntry.TABLE_NAME;
+	
+	/**
+	 * Determines the number of recorded attacks for a specific protocol and accesss point since the given attack_id.
+	 * 
+	 * @param protocol
+	 *            The String representation of the
+	 *            {@link de.tudarmstadt.informatik.hostage.protocol.Protocol
+	 *            Protocol}
+	 * @param attack_id  The attack id to match the query against.
+	 * @param bssid The BSSID of the access point. 
+	 * @return The number of different attacks in the database since the given attack_id.
+	 */
+	public int getAttackPerProtocolCount(String protocol, int attack_id, String bssid) {
 		SQLiteDatabase db = this.getReadableDatabase();
-		Cursor cursor = db.rawQuery(selectQuery, null);
-
-		ArrayList<HashMap<String, Object>> networkInformation = new ArrayList<HashMap<String, Object>>();
-
-		// looping through all rows and adding to list
-		if (cursor.moveToFirst()) {
-			do {
-				HashMap<String, Object> values = new HashMap<String, Object>();
-				values.put(NetworkEntry.COLUMN_NAME_BSSID, cursor.getString(0));
-				values.put(NetworkEntry.COLUMN_NAME_SSID, cursor.getString(1));
-				values.put(NetworkEntry.COLUMN_NAME_LATITUDE, Double.parseDouble(cursor.getString(2)));
-				values.put(NetworkEntry.COLUMN_NAME_LONGITUDE, Double.parseDouble(cursor.getString(3)));
-				values.put(NetworkEntry.COLUMN_NAME_ACCURACY, Float.parseFloat(cursor.getString(4)));
-				values.put(NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP, cursor.getLong(5));
-				networkInformation.add(values);
-			} while (cursor.moveToNext());
-		}
-
+		String countQuery = "SELECT * FROM " + AttackEntry.TABLE_NAME + 
+     		   			   " WHERE "+ AttackEntry.COLUMN_NAME_PROTOCOL + " = ? " +
+     		   			    "AND " + AttackEntry.COLUMN_NAME_ATTACK_ID + " > ? " +	
+						 	"AND " + AttackEntry.COLUMN_NAME_BSSID + " = ?";
+		Cursor cursor = db.rawQuery(countQuery, new String[]{protocol, attack_id + "", bssid});
+		int result = cursor.getCount();
 		cursor.close();
+
+		// return count
 		db.close();
-		return networkInformation;
+		return result;
 	}
-
+	
 	/**
-	 * Gets a single {@link Record} with the given ID from the database.
+	 * Determines the number of portscans stored in the database.
 	 * 
-	 * @param id
-	 *            The ID of the {@link Record};
-	 * @return The {@link Record}.
+	 * @return The number of portscans stored in the database.
 	 */
-	public Record getRecord(int id) {
-		String selectQuery = "SELECT  * FROM " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " NATURAL JOIN "
-				+ NetworkEntry.TABLE_NAME + " WHERE " + PacketEntry.COLUMN_NAME_ID + " = " + id;
-		SQLiteDatabase db = this.getReadableDatabase();
-
-		Cursor cursor = db.rawQuery(selectQuery, null);
-		Record record = null;
-		if (cursor.moveToFirst()) {
-			record = createRecord(cursor);
-		}
+	public int getPortscanCount() {
+		return getAttackPerProtocolCount("PORTSCAN");
+	}	
+	
+	/**
+	 * Determines the number of recorded portscans since the given attack_id.
+	 * @param attack_id  The attack id to match the query against.
+	 * @return The number of portscans stored in the database since the given attack_id.
+	 */
+	public int getPortscanCount(int attack_id) {
+		return getAttackPerProtocolCount("PORTSCAN", attack_id);
+	}	
+	
+	/**
+	 * Determines the number of recorded portscans in a specific access point since the given attack_id.
+	 * @param attack_id  The attack id to match the query against.
+	 * @param bssid The BSSID of the access point. 
+	 * @return The number of portscans stored in the database since the given attack_id.
+	 */
+	public int getPortscanCount(int attack_id, String bssid) {
+		return getAttackPerProtocolCount("PORTSCAN", attack_id, bssid);
+	}	
 
-		cursor.close();
-		db.close();
-		// return contact
-		return record;
-	}
 
 	/**
 	 * Determines the number of {@link Record Records} in the database.
@@ -443,22 +437,20 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 	}
 
 	/**
-	 * Gets a single {@link Record} with the given attack id from the database.
+	 * Returns the {@link AttackRecord} with the given attack id from the database.
 	 * 
 	 * @param attack_id
 	 *            The attack id of the {@link Record};
 	 * @return The {@link Record}.
 	 */
-	public Record getRecordOfAttackId(long attack_id) {
-		String selectQuery = "SELECT  * FROM " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " NATURAL JOIN "
-				+ NetworkEntry.TABLE_NAME + " WHERE " + AttackEntry.COLUMN_NAME_ATTACK_ID + " = " + attack_id + " GROUP BY "
-				+ AttackEntry.COLUMN_NAME_ATTACK_ID;
+	public AttackRecord getRecordOfAttackId(long attack_id) {
+		String selectQuery = "SELECT  * FROM " + AttackEntry.TABLE_NAME + " WHERE " + AttackEntry.COLUMN_NAME_ATTACK_ID + " = " + attack_id;
 		SQLiteDatabase db = this.getReadableDatabase();
 		Cursor cursor = db.rawQuery(selectQuery, null);
-		Record record = null;
+		AttackRecord record = null;
 
 		if (cursor.moveToFirst()) {
-			record = createRecord(cursor);
+			record = createAttackRecord(cursor);
 		}
 		cursor.close();
 
@@ -468,23 +460,20 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 	}
 
 	/**
-	 * Gets a representative {@link Record} for every attack identified by its
-	 * attack id.
+	 * Gets a {@link AttackRecord} for every attack identified by its attack id.
 	 * 
-	 * @return A ArrayList with one {@link Record Records} for each attack id in
-	 *         the Database.
+	 * @return A ArrayList with a {@link AttackRecord} for each attack id in the Database.
 	 */
-	public ArrayList<Record> getRecordOfEachAttack() {
-		ArrayList<Record> recordList = new ArrayList<Record>();
-		String selectQuery = "SELECT  * FROM " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " NATURAL JOIN "
-				+ NetworkEntry.TABLE_NAME + " GROUP BY " + AttackEntry.COLUMN_NAME_ATTACK_ID;
+	public ArrayList<AttackRecord> getRecordOfEachAttack() {
+		ArrayList<AttackRecord> recordList = new ArrayList<AttackRecord>();
+		String selectQuery = "SELECT  * FROM " + AttackEntry.TABLE_NAME;
 		SQLiteDatabase db = this.getReadableDatabase();
 		Cursor cursor = db.rawQuery(selectQuery, null);
 
 		// looping through all rows and adding to list
 		if (cursor.moveToFirst()) {
 			do {
-				Record record = createRecord(cursor);
+				AttackRecord record = createAttackRecord(cursor);
 				// Adding record to list
 				recordList.add(record);
 			} while (cursor.moveToNext());
@@ -497,26 +486,23 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 	}
 
 	/**
-	 * Gets a representative {@link Record} for every attack with a higher
-	 * attack id than the specified.
+	 * Gets a AttackRecord for every attack with a higher attack id than the specified.
 	 * 
 	 * @param attack_id
 	 *            The attack id to match the query against.
-	 * @return A ArrayList with one {@link Record Records} for each attack id
+	 * @return A ArrayList with one {@link AttackRecord} for each attack id
 	 *         higher than the given.
 	 */
-	public ArrayList<Record> getRecordOfEachAttack(long attack_id) {
-		ArrayList<Record> recordList = new ArrayList<Record>();
-		String selectQuery = "SELECT  * FROM " + PacketEntry.TABLE_NAME + " NATURAL JOIN " + AttackEntry.TABLE_NAME + " NATURAL JOIN "
-				+ NetworkEntry.TABLE_NAME + " WHERE " + AttackEntry.COLUMN_NAME_ATTACK_ID + " > " + attack_id + " GROUP BY "
-				+ AttackEntry.COLUMN_NAME_ATTACK_ID;
+	public ArrayList<AttackRecord> getRecordOfEachAttack(long attack_id) {
+		ArrayList<AttackRecord> recordList = new ArrayList<AttackRecord>();
+		String selectQuery = "SELECT  * FROM " + AttackEntry.TABLE_NAME + " WHERE " + AttackEntry.COLUMN_NAME_ATTACK_ID + " > " + attack_id;
 		SQLiteDatabase db = this.getReadableDatabase();
 		Cursor cursor = db.rawQuery(selectQuery, null);
 
 		// looping through all rows and adding to list
 		if (cursor.moveToFirst()) {
 			do {
-				Record record = createRecord(cursor);
+				AttackRecord record = createAttackRecord(cursor);
 				// Adding record to list
 				recordList.add(record);
 			} while (cursor.moveToNext());
@@ -527,6 +513,27 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 		db.close();
 		return recordList;
 	}
+	
+	/**
+	 * Determines the highest attack id stored in the database.
+	 * 
+	 * @return The highest attack id stored in the database.
+	 */
+	public long getHighestAttackId() {
+		String selectQuery = "SELECT MAX(" + AttackEntry.COLUMN_NAME_ATTACK_ID + ") FROM " + AttackEntry.TABLE_NAME;
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(selectQuery, null);
+		int result;
+
+		if (cursor.moveToFirst()) {
+			result = cursor.getInt(0);
+		} else {
+			result = -1;
+		}
+		cursor.close();
+		db.close();
+		return result;
+	}
 
 	/**
 	 * Determines the smallest attack id stored in the database.
@@ -570,36 +577,184 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 		db.close();
 		return ssid;
 	}
+	
+	public ArrayList<NetworkRecord> getNetworkInformation() {
+		String selectQuery = "SELECT  * FROM " + NetworkEntry.TABLE_NAME;
+		SQLiteDatabase db = this.getReadableDatabase();
+		Cursor cursor = db.rawQuery(selectQuery, null);
+
+		ArrayList<NetworkRecord> networkInformation = new ArrayList<NetworkRecord>();
+
+		// looping through all rows and adding to list
+		if (cursor.moveToFirst()) {
+			do {
+				NetworkRecord record = new NetworkRecord();
+				record.setBssid(cursor.getString(0));
+				record.setSsid(cursor.getString(1));
+				record.setLatitude(Double.parseDouble(cursor.getString(2)));
+				record.setLongitude(Double.parseDouble(cursor.getString(3)));
+				record.setAccuracy(Float.parseFloat(cursor.getString(4)));
+				record.setTimestampLocation(cursor.getLong(5));
+				networkInformation.add(record);
+			} while (cursor.moveToNext());
+		}
+
+		cursor.close();
+		db.close();
+		return networkInformation;
+	}
 
-	public void updateNetworkInformation(ArrayList<HashMap<String, Object>> networkInformation) {
+	public void updateNetworkInformation(ArrayList<NetworkRecord> networkInformation) {
 		Log.i("DatabaseHandler", "Starte updating");
-		for (HashMap<String, Object> values : networkInformation) {
-			updateNetworkInformation(values);
+		for (NetworkRecord record : networkInformation) {
+			updateNetworkInformation(record);
 		}
 	}
 
-	public void updateNetworkInformation(HashMap<String, Object> networkInformation) {
+	public void updateNetworkInformation(NetworkRecord record) {
 		SQLiteDatabase db = this.getReadableDatabase();
-		String bssid = (String) networkInformation.get(NetworkEntry.COLUMN_NAME_BSSID);
-		String bssidQuery = "SELECT  * FROM " + NetworkEntry.TABLE_NAME + " WHERE " + NetworkEntry.COLUMN_NAME_BSSID + " = " + "'" + bssid + "'";
-		Cursor cursor = db.rawQuery(bssidQuery, null);
-		int result = cursor.getCount();
-		if (cursor != null && cursor.moveToFirst()
-				&& (result <= 0 || cursor.getLong(5) < (Long) networkInformation.get(NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP)))
-			;
-		{
+		String bssid = record.getBssid();
+		String bssidQuery = "SELECT  * FROM " +  NetworkEntry.TABLE_NAME + " WHERE " +  NetworkEntry.COLUMN_NAME_BSSID + " = ?";
+		Cursor cursor = db.rawQuery(bssidQuery, new String[] {bssid});
+		if (!cursor.moveToFirst() || cursor.getLong(5) < record.getTimestampLocation()){
 			ContentValues bssidValues = new ContentValues();
 			bssidValues.put(NetworkEntry.COLUMN_NAME_BSSID, bssid);
-			bssidValues.put(NetworkEntry.COLUMN_NAME_SSID, (String) networkInformation.get(NetworkEntry.COLUMN_NAME_SSID));
-			bssidValues.put(NetworkEntry.COLUMN_NAME_LATITUDE, (double) (Double) networkInformation.get(NetworkEntry.COLUMN_NAME_LATITUDE));
-			bssidValues.put(NetworkEntry.COLUMN_NAME_LONGITUDE, (double) (Double) networkInformation.get(NetworkEntry.COLUMN_NAME_LONGITUDE));
-			bssidValues.put(NetworkEntry.COLUMN_NAME_ACCURACY, (float) (Float) networkInformation.get(NetworkEntry.COLUMN_NAME_ACCURACY));
-			bssidValues.put(NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP, (Long) networkInformation.get(NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP));
+			bssidValues.put(NetworkEntry.COLUMN_NAME_SSID, record.getSsid());
+			bssidValues.put(NetworkEntry.COLUMN_NAME_LATITUDE, record.getLatitude());
+			bssidValues.put(NetworkEntry.COLUMN_NAME_LONGITUDE, record.getLongitude());
+			bssidValues.put(NetworkEntry.COLUMN_NAME_ACCURACY, record.getAccuracy());
+			bssidValues.put(NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP, record.getTimestampLocation());
 			db.insertWithOnConflict(NetworkEntry.TABLE_NAME, null, bssidValues, SQLiteDatabase.CONFLICT_REPLACE);
 		}
 		cursor.close();
 		db.close();
 	}
+	
+	
+	public void updateSyncDevices(HashMap<String, Long> devices){
+		SQLiteDatabase db = this.getReadableDatabase();		
+		for(String key : devices.keySet()){
+			ContentValues deviceValues = new ContentValues();
+			deviceValues.put(SyncDeviceEntry.COLUMN_NAME_DEVICE_ID, key);
+			deviceValues.put(SyncDeviceEntry.COLUMN_NAME_DEVICE_TIMESTAMP, devices.get(key));
+			db.insertWithOnConflict(SyncDeviceEntry.TABLE_NAME, null, deviceValues, SQLiteDatabase.CONFLICT_REPLACE);
+		}
+		db.close();
+	}
+	
+	/**
+	 * Returns a HashMap of all devices that were previously synchronized with.
+	 * @return HashMap containing device id's and the last synchronization timestamp.
+	 */
+	public HashMap<String, Long> getSyncDevices(){
+		SQLiteDatabase db = this.getReadableDatabase();
+		HashMap<String, Long> devices = new HashMap<String, Long>();
+		
+		String query = "SELECT  * FROM " + SyncDeviceEntry.TABLE_NAME;
+		Cursor cursor = db.rawQuery(query, null);
+		
+		if (cursor.moveToFirst()) {
+			do {
+				devices.put(cursor.getString(0), cursor.getLong(1));
+			} while (cursor.moveToNext());
+		}
+		cursor.close();
+		db.close();
+		return devices;
+	}
+	
+	/**
+	 * Returns a ArrayList containing all information stored in the SyncInfo table.
+	 * @return ArrayList<SyncInfo>
+	 */
+	public ArrayList<SyncInfoRecord> getSyncInfo(){
+		SQLiteDatabase db = this.getReadableDatabase();
+		ArrayList<SyncInfoRecord> syncInfo = new ArrayList<SyncInfoRecord>();
+		
+		String query = "SELECT  * FROM " + SyncInfoEntry.TABLE_NAME;
+		Cursor cursor = db.rawQuery(query, null);
+		
+		if (cursor.moveToFirst()) {
+			do {
+				SyncInfoRecord info = new SyncInfoRecord();
+				info.setDeviceID(cursor.getString(0));
+				info.setBSSID(cursor.getString(1));
+				info.setNumber_of_attacks(cursor.getLong(2));
+				info.setNumber_of_portscans(cursor.getLong(3));
+				syncInfo.add(info);
+			} while (cursor.moveToNext());
+		}
+		cursor.close();
+		db.close();
+		return syncInfo;
+	}	
+	
+	
+	public void updateSyncInfo(ArrayList<SyncInfoRecord> syncInfo){
+		for(SyncInfoRecord info : syncInfo){
+			updateSyncInfo(info);
+		}
+	}
+	
+	public void updateSyncInfo(SyncInfoRecord syncInfo){
+		SQLiteDatabase db = this.getReadableDatabase();
+		ContentValues syncValues = new ContentValues();
+		syncValues.put(SyncInfoEntry.COLUMN_NAME_BSSID, syncInfo.getBSSID());
+		syncValues.put(SyncInfoEntry.COLUMN_NAME_DEVICE_ID, syncInfo.getDeviceID());
+		syncValues.put(SyncInfoEntry.COLUMN_NAME_NUMBER_ATTACKS, syncInfo.getNumber_of_attacks());
+		syncValues.put(SyncInfoEntry.COLUMN_NAME_NUMBER_PORTSCANS, syncInfo.getNumber_of_portscans());
+		db.insertWithOnConflict(SyncInfoEntry.TABLE_NAME, null, syncValues, SQLiteDatabase.CONFLICT_REPLACE);
+		db.close();
+	}
+	
+	/**
+	 * Deletes a device with given id from the device {@link SyncDeviceEntry.TABLE_NAME} and also all data captured by this device in  {@link SyncInfoEntry.TABLE_NAME}
+	 * @param device_id The id of the device that is to be deleted.
+	 */
+	public void clearSyncInfos(){
+		SQLiteDatabase db = this.getReadableDatabase();
+		db.delete(SyncDeviceEntry.TABLE_NAME, null, null);
+		db.delete(SyncInfoEntry.TABLE_NAME, null, null);
+		db.close();
+	}
+	
+	
+	/**
+	 * Deletes all records from {@link #PacketEntry.TABLE_NAME}.
+	 */
+	public void clearData() {
+		SQLiteDatabase db = this.getReadableDatabase();
+		db.delete(PacketEntry.TABLE_NAME, null, null);
+		db.delete(AttackEntry.TABLE_NAME, null, null);
+		db.close();
+	}
+
+	/**
+	 * Deletes all records from {@link #PacketEntry.TABLE_NAME} with a specific BSSID.
+	 * 
+	 * @param bssid
+	 *            The BSSID to match against.
+	 */
+	public void deleteByBSSID(String bssid) {
+		SQLiteDatabase db = this.getReadableDatabase();
+		db.delete(NetworkEntry.TABLE_NAME, NetworkEntry.COLUMN_NAME_BSSID + " = ?", new String[] { bssid });
+		db.delete(AttackEntry.TABLE_NAME, AttackEntry.COLUMN_NAME_BSSID + " = ?", new String[] { bssid });
+		db.close();
+	}
+	
+	/**
+	 * Deletes all records from {@link #PacketEntry.TABLE_NAME} with a time stamp smaller
+	 * then the given
+	 * 
+	 * @param date
+	 *            A Date represented in milliseconds.
+	 */
+	public void deleteByDate(long date) {
+		SQLiteDatabase db = this.getReadableDatabase();
+		String deleteQuery = "DELETE  FROM " + PacketEntry.TABLE_NAME + " WHERE " + PacketEntry.COLUMN_NAME_PACKET_TIMESTAMP + " < " + date;
+		db.execSQL(deleteQuery);
+		db.close();
+	}
 
 	/**
 	 * Creates a {@link Record} from a Cursor. If the cursor does not show to a
@@ -608,28 +763,34 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 	 * @param cursor
 	 * @return Returns the created {@link Record} .
 	 */
-	private Record createRecord(Cursor cursor) {
-		Record record = new Record();
+	private MessageRecord createMessageRecord(Cursor cursor) {
+		MessageRecord record = new MessageRecord();
 		record.setId(Integer.parseInt(cursor.getString(0)));
 		record.setAttack_id(cursor.getLong(1));
-		record.setType(TYPE.valueOf(cursor.getString(2)));
+		record.setType(MessageRecord.TYPE.valueOf(cursor.getString(2)));
 		record.setTimestamp(cursor.getLong(3));
 		record.setPacket(cursor.getString(4));
-		record.setProtocol(cursor.getString(5));
-		record.setExternalIP(cursor.getString(6));
-
-		record.setLocalIP(cursor.getString(7));
-		record.setLocalPort(Integer.parseInt(cursor.getString(8)));
-
-		record.setRemoteIP(cursor.getString(9));
-		record.setRemotePort(Integer.parseInt(cursor.getString(10)));
 
+		return record;
+	}
+	
+	/**
+	 * Creates a {@link AttackRecord} from a Cursor. If the cursor does not show to a
+	 * valid data structure a runtime exception is thrown.
+	 * 
+	 * @param cursor
+	 * @return Returns the created {@link Record} .
+	 */
+	private AttackRecord createAttackRecord(Cursor cursor) {
+		AttackRecord record = new AttackRecord();
+		record.setAttack_id(cursor.getLong(0));
+		record.setProtocol(cursor.getString(1));
+		record.setExternalIP(cursor.getString(2));
+		record.setLocalIP(cursor.getString(3));
+		record.setLocalPort(Integer.parseInt(cursor.getString(4)));
+		record.setRemoteIP(cursor.getString(5));
+		record.setRemotePort(Integer.parseInt(cursor.getString(6)));
 		record.setBssid(cursor.getString(11));
-		record.setSsid(cursor.getString(12));
-		record.setLatitude(Double.parseDouble(cursor.getString(13)));
-		record.setLongitude(Double.parseDouble(cursor.getString(14)));
-		record.setAccuracy(Float.parseFloat(cursor.getString(15)));
-		record.setTimestampLocation(cursor.getLong(16));
 
 		return record;
 	}

+ 39 - 0
src/de/tudarmstadt/informatik/hostage/sync/SyncMessage.java

@@ -0,0 +1,39 @@
+package de.tudarmstadt.informatik.hostage.sync;
+
+import java.io.Serializable;
+
+public class SyncMessage implements Serializable{
+	
+
+	private static final long serialVersionUID = -7597101233186914926L;
+	
+	//REQUEST CODES
+	public static final int SYNC_REQUEST = 0x00;
+	public static final int SYNC_RESPONSE_NET_INFO = 0x01;
+	public static final int SYNC_RESPONSE_SYNC_INFO = 0x02;
+	
+	private int message_code;
+	private Object payload;
+	
+	public SyncMessage(int message_code, Object payload){
+		this.message_code = message_code;
+		this.payload = payload;
+	}
+
+	public int getMessage_code() {
+		return message_code;
+	}
+
+	public void setMessage_code(int message_code) {
+		this.message_code = message_code;
+	}
+
+	public Object getPayload() {
+		return payload;
+	}
+
+	public void setPayload(Object payload) {
+		this.payload = payload;
+	}
+
+}

+ 34 - 191
src/de/tudarmstadt/informatik/hostage/sync/BluetoothSync.java → src/de/tudarmstadt/informatik/hostage/sync/bluetooth/BluetoothSync.java

@@ -1,9 +1,5 @@
-package de.tudarmstadt.informatik.hostage.sync;
+package de.tudarmstadt.informatik.hostage.sync.bluetooth;
 
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.UUID;
 
@@ -11,7 +7,6 @@ import android.util.Log;
 import android.app.Activity;
 import android.bluetooth.BluetoothAdapter;
 import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothServerSocket;
 import android.bluetooth.BluetoothSocket;
 import android.content.BroadcastReceiver;
 import android.content.Context;
@@ -28,27 +23,30 @@ import android.widget.ListView;
 import android.widget.TextView;
 import android.widget.AdapterView.OnItemClickListener;
 import de.tudarmstadt.informatik.hostage.R;
+import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
 import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
+import de.tudarmstadt.informatik.hostage.sync.SyncMessage;
 
 public class BluetoothSync extends Activity{	
 	
-    private static final int CONNECTION_ESTABLISHED = 0x0;
-    private static final int CONNECTION_FAILED = 0x1;
-    private static final int MESSAGE_SENT = 0x2;
-    private static final int MESSAGE_RECIEVED = 0x3;
+    public static final int CONNECTION_ESTABLISHED = 0x0;
+    public static final int CONNECTION_FAILED = 0x1;
+    public static final int SYNC_SUCCESSFUL = 0x2;
+    public static final int SYNC_FAILED = 0x3;
     
-	private UUID serviceUUID;
+    public static UUID serviceUUID;
 	
 	private BluetoothAdapter mBluetoothAdapter;
 	private ArrayAdapter<String> arrayAdapter;
 
 	private ServerThread serverThread;	
 	private ClientThread clientThread;
-	CommunicationThread commThread;
+	private CommunicationThread commThread;
 	
-	TextView mInfoText;
-	ListView listView;
-	LinearLayout layout;
+	
+	private TextView mInfoText;
+	private ListView listView;
+	private LinearLayout layout;
 	
 	
 	@Override
@@ -108,7 +106,7 @@ public class BluetoothSync extends Activity{
 		discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
 		startActivity(discoverableIntent);
 
-		serverThread = new ServerThread();
+		serverThread = new ServerThread(mHandler, getResources().getString(R.string.app_name));
 		serverThread.start();
 	}
 		
@@ -116,163 +114,20 @@ public class BluetoothSync extends Activity{
 	private void manageConnectedSocket(BluetoothSocket socket) {
 		mBluetoothAdapter.cancelDiscovery();
 		unregisterBroadcastReceiver();
-		commThread = new CommunicationThread(socket);
-		commThread.start();
+		
+		layout.removeView(listView);
+		String deviceName = socket.getRemoteDevice().getName();
+		mInfoText.setText("Synchronizing with " + deviceName + "...");	
+		
 		HostageDBOpenHelper dbh = new HostageDBOpenHelper(this);
-		ArrayList<HashMap<String, Object>> localNetworkInformation = dbh.getNetworkInformation();
-		commThread.write(localNetworkInformation);
-	}
-
-	private class ClientThread extends Thread {
-		private final BluetoothSocket socket;
-
-		public ClientThread(BluetoothDevice device) {
-			BluetoothSocket tmp = null;
-			try {
-				tmp = device.createRfcommSocketToServiceRecord(serviceUUID);
-			} catch (IOException e) {
-			}
-			socket = tmp;
-		}
-
-		/** Will cancel an in-progress connection, and close the socket */
-		public void cancel() {
-			try {
-				socket.close();
-			} catch (IOException e) {
-			}
-		}
-
-		@Override
-		public void run() {
-
-			try {
-				socket.connect();
-			} catch (IOException connectException) {
-				mHandler.obtainMessage(CONNECTION_FAILED).sendToTarget();
-				// Unable to connect; close the socket and get out
-				try {
-					socket.close();
-				} catch (IOException closeException) {
-				}
-				return;
-			}
-			mHandler.obtainMessage(CONNECTION_ESTABLISHED, socket).sendToTarget();
-			manageConnectedSocket(socket);
-		}
-	}
-
-	private class ServerThread extends Thread {
-		private final BluetoothServerSocket serverSocket;
-
-		public ServerThread() {
-			BluetoothServerSocket tmp = null;
-			try {
-				tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(getResources().getString(R.string.app_name), serviceUUID);
-			} catch (IOException e) {
-			}
-			serverSocket = tmp;
-		}
-
-		/** Will cancel the listening socket, and cause the thread to finish */
-		public void cancel() {
-			try {
-				serverSocket.close();
-			} catch (IOException e) {
-			}
-		}
-
-		@Override
-		public void run() {
-			BluetoothSocket socket = null;
-			while (true) {
-				try {
-					socket = serverSocket.accept();
-				} catch (IOException e) {
-					e.printStackTrace();
-					mHandler.obtainMessage(CONNECTION_FAILED).sendToTarget();
-					break;
-				}
-
-				if (socket != null) {
-					// Do work to manage the connection (in a separate thread)
-					manageConnectedSocket(socket);
-					mHandler.obtainMessage(CONNECTION_ESTABLISHED, socket).sendToTarget();
-					try {
-						serverSocket.close();
-					} catch (IOException e) {
-						e.printStackTrace();
-					}
-					break;
-				}
-			}
-		}
-	}
-	
-	private class CommunicationThread extends Thread {
-		private final BluetoothSocket mmSocket;
-		private final ObjectInputStream objectInput;
-		private final ObjectOutputStream objectOuput;
-
-		public CommunicationThread(BluetoothSocket socket) {
-			mmSocket = socket;
-			ObjectInputStream tmpIn = null;
-			ObjectOutputStream tmpOut = null;
-
-			// Get the input and output streams, using temp objects because
-			// member streams are final
-			try {
-				tmpOut = new ObjectOutputStream(socket.getOutputStream());
-				tmpIn = new ObjectInputStream(socket.getInputStream());
-			} catch (IOException e) {
-				e.printStackTrace();
-			}
-
-			objectInput = tmpIn;
-			objectOuput = tmpOut;
-		}
-
-		/* Call this from the main activity to shutdown the connection */
-		public void cancel() {
-			try {
-				mmSocket.close();
-			} catch (IOException e) {
-			}
-		}
-
-		@Override
-		public void run() {
-			// Keep listening to the InputStream until an exception occurs
-			while (true) {
-			try {
-				// TODO Ersetze dbh mit Logger
-				HostageDBOpenHelper dbh = new HostageDBOpenHelper(getContext());
-				// Read from the InputStream
-				ArrayList<HashMap<String, Object>> remoteNetworkInformation = (ArrayList<HashMap<String, Object>>) objectInput.readObject();
-				// update database
-				dbh.updateNetworkInformation(remoteNetworkInformation);	
-				mHandler.obtainMessage(MESSAGE_RECIEVED).sendToTarget();
-			} catch (ClassNotFoundException e) {
-				e.printStackTrace();
-			} catch (IOException e) {
-				e.printStackTrace();
-				break;
-			}
-			}
-		}
-
-		/* Call this from the main activity to send data to the remote device */
-		public void write(ArrayList<HashMap<String, Object>> networkInformation) {
-			try {
-				objectOuput.writeObject(networkInformation);
-				mHandler.obtainMessage(MESSAGE_SENT).sendToTarget();
-			} catch (IOException e) {
-				e.printStackTrace();
-			}
-		}
+		commThread = new CommunicationThread(this, socket, mHandler);
+		commThread.start();
+		
+		//TODO auslagern
+		HashMap<String, Long> devices = dbh.getSyncDevices();
+		commThread.write(new SyncMessage(SyncMessage.SYNC_REQUEST, devices));
 	}
 
-
 	// Create a BroadcastReceiver for ACTION_FOUND
 	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
 		@Override
@@ -315,10 +170,6 @@ public class BluetoothSync extends Activity{
 		mRecieverRegistered = false;
 	}
 	
-	private Context getContext(){
-		return this;
-	}
-	
 	private void setLayoutElement(){
 		mInfoText = (TextView) findViewById(R.id.bluetoothInfoText);
 		layout = (LinearLayout) findViewById(R.id.bluetoothLayout);
@@ -329,40 +180,32 @@ public class BluetoothSync extends Activity{
 			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
 				String deviceInfo = arrayAdapter.getItem(position);
 				String mac = deviceInfo.substring(deviceInfo.indexOf("\n") + 1);
-				clientThread = new ClientThread(mBluetoothAdapter.getRemoteDevice(mac));
+				clientThread = new ClientThread(mBluetoothAdapter.getRemoteDevice(mac), mHandler);
 				clientThread.start();
 			}
 		});		
 	}	
 	
-	private boolean message_sent = false;
-	private boolean message_recieved = false;
-	
 	private Handler mHandler = new Handler() {
 
         @Override
         public void handleMessage(Message msg) {
         	switch(msg.what){
         		case CONNECTION_ESTABLISHED: 
-        			layout.removeView(listView);
-        			BluetoothSocket socket = (BluetoothSocket) msg.obj;
-        			String deviceName = socket.getRemoteDevice().getName();
-        			mInfoText.setText("Synchronizing with " + deviceName + "...");	
+        			manageConnectedSocket((BluetoothSocket) msg.obj);
         			break;
         		case CONNECTION_FAILED: 
         			mInfoText.setText("Synchronization failed!");
         			break;
-        		case MESSAGE_SENT: 
-        			message_sent = true;
-        			if(message_recieved)
-        				mInfoText.setText("Synchronization successfull!");
+        		case SYNC_SUCCESSFUL: 
+        			mInfoText.setText("Synchronization successfull!");
         			break;	
-        		case MESSAGE_RECIEVED: 
-        			message_recieved = true;
-        			if(message_sent)
-        				mInfoText.setText("Synchronization successfull!");
+        		case SYNC_FAILED: 
+        			mInfoText.setText("Synchronization failed!");
         			break;	
         	}        		
         }
-};
+	};
+	
+	
 }

+ 29 - 0
src/de/tudarmstadt/informatik/hostage/sync/bluetooth/BluetoothSyncService.java

@@ -0,0 +1,29 @@
+package de.tudarmstadt.informatik.hostage.sync.bluetooth;
+
+import android.app.IntentService;
+import android.bluetooth.BluetoothAdapter;
+import android.content.Intent;
+
+public class BluetoothSyncService extends IntentService {
+	
+	private ServerThread serverThread;	
+	private ClientThread clientThread;
+	private CommunicationThread commThread;
+	
+	private BluetoothAdapter mBluetoothAdapter;
+	
+	
+	public BluetoothSyncService() {
+		super("BluetoothSyncService");
+		
+	}
+
+	@Override
+	protected void onHandleIntent(Intent intent) {
+		// TODO Auto-generated method stub
+		
+	}
+
+
+	
+}

+ 48 - 0
src/de/tudarmstadt/informatik/hostage/sync/bluetooth/ClientThread.java

@@ -0,0 +1,48 @@
+package de.tudarmstadt.informatik.hostage.sync.bluetooth;
+
+import java.io.IOException;
+
+
+import android.bluetooth.BluetoothDevice;
+import android.bluetooth.BluetoothSocket;
+import android.os.Handler;
+
+public class ClientThread extends Thread {
+	private final BluetoothSocket socket;
+	private final Handler mHandler;
+
+	public ClientThread(BluetoothDevice device, Handler handler) {
+		mHandler = handler;
+		BluetoothSocket tmp = null;
+		try {
+			tmp = device.createRfcommSocketToServiceRecord(BluetoothSync.serviceUUID);
+		} catch (IOException e) {
+		}
+		socket = tmp;
+	}
+
+	/** Will cancel an in-progress connection, and close the socket */
+	public void cancel() {
+		try {
+			socket.close();
+		} catch (IOException e) {
+		}
+	}
+
+	@Override
+	public void run() {
+
+		try {
+			socket.connect();
+		} catch (IOException connectException) {
+			mHandler.obtainMessage(BluetoothSync.CONNECTION_FAILED).sendToTarget();
+			// Unable to connect; close the socket and get out
+			try {
+				socket.close();
+			} catch (IOException closeException) {
+			}
+			return;
+		}
+		mHandler.obtainMessage(BluetoothSync.CONNECTION_ESTABLISHED, socket).sendToTarget();
+	}
+}

+ 145 - 0
src/de/tudarmstadt/informatik/hostage/sync/bluetooth/CommunicationThread.java

@@ -0,0 +1,145 @@
+package de.tudarmstadt.informatik.hostage.sync.bluetooth;
+
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+
+import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
+import de.tudarmstadt.informatik.hostage.logging.NetworkRecord;
+import de.tudarmstadt.informatik.hostage.logging.SyncInfoRecord;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
+import de.tudarmstadt.informatik.hostage.sync.SyncMessage;
+
+
+import android.bluetooth.BluetoothSocket;
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.os.Handler;
+import android.preference.PreferenceManager;
+import android.util.Log;
+
+public class CommunicationThread extends Thread {
+	private final Context context;
+	private final BluetoothSocket mmSocket;
+	private final ObjectInputStream objectInput;
+	private final ObjectOutputStream objectOuput;
+	private final Handler mHandler;
+	private final HostageDBOpenHelper mdbh;
+	private final SharedPreferences pref;
+
+
+	public CommunicationThread(Context con, BluetoothSocket socket, Handler handler) {
+		mmSocket = socket;
+		mHandler = handler;
+		context = con;
+		mdbh = new HostageDBOpenHelper(context);		
+		pref = PreferenceManager.getDefaultSharedPreferences(context);
+		ObjectInputStream tmpIn = null;
+		ObjectOutputStream tmpOut = null;
+		
+
+		// Get the input and output streams, using temp objects because
+		// member streams are final
+		try {
+			tmpOut = new ObjectOutputStream(socket.getOutputStream());
+			tmpIn = new ObjectInputStream(socket.getInputStream());
+		} catch (IOException e) {
+			mHandler.obtainMessage(BluetoothSync.CONNECTION_FAILED).sendToTarget();
+			e.printStackTrace();
+		}
+
+		objectInput = tmpIn;
+		objectOuput = tmpOut;
+	}
+
+	/* Call this from the main activity to shutdown the connection */
+	public void cancel() {
+		try {
+			mmSocket.close();
+		} catch (IOException e) {
+		}
+	}
+
+	@Override
+	public void run() {	
+		// Keep listening to the InputStream until an exception occurs
+		while (true) {
+		try {
+			Object inputObject = objectInput.readObject();
+			if(inputObject instanceof SyncMessage){
+				handleMessage((SyncMessage) inputObject);				
+			}		
+		} catch (ClassNotFoundException e) {
+			e.printStackTrace();
+		} catch (IOException e) {
+			e.printStackTrace();
+			break;
+		}
+		}
+	}
+	
+	/**
+	 * Handles a received synchronization message.
+	 * @param message The received message.
+	 */
+	private void handleMessage(SyncMessage message){
+		Log.i("CommunicationThread", "Recieved: " + message.getMessage_code());
+		switch(message.getMessage_code()){
+			case SyncMessage.SYNC_REQUEST:
+				HashMap<String, Long> devices_remote = (HashMap<String, Long>) message.getPayload();
+				HashMap<String, Long> devices_local = mdbh.getSyncDevices();
+				ArrayList<SyncInfoRecord> syncInfo = mdbh.getSyncInfo();
+
+				long tracing_timestamp = 0;
+				//TODO "TRACING" zentral definieren
+				if(devices_local.containsKey("TRACING"))
+					tracing_timestamp = devices_local.get("TRACING");				
+					
+				for(String key : devices_remote.keySet()){
+					if((devices_local.containsKey(key) && devices_local.get(key) >= devices_remote.get(key)) 
+					    || (tracing_timestamp > devices_remote.get(key))){
+						Log.i("CommunicationThread", "Removed: " + key);
+						devices_remote.remove(key);
+					}
+				}
+				mdbh.updateSyncDevices(devices_remote);
+				
+				for ( Iterator<SyncInfoRecord> i = syncInfo.iterator(); i.hasNext(); ){
+					SyncInfoRecord info = i.next();
+					if(devices_remote.containsKey(info.getDeviceID())){
+						Log.i("CommunicationThread", "Removed from SyncInfo: " + info.getDeviceID());
+						i.remove();
+					}				    
+				}				
+								
+				write(new SyncMessage(SyncMessage.SYNC_RESPONSE_SYNC_INFO, syncInfo));
+				write(new SyncMessage(SyncMessage.SYNC_RESPONSE_NET_INFO, mdbh.getNetworkInformation()));
+				break;			
+			case SyncMessage.SYNC_RESPONSE_NET_INFO:
+				ArrayList<NetworkRecord> netInfo = (ArrayList<NetworkRecord>) message.getPayload();
+				mdbh.updateNetworkInformation(netInfo);	
+				mHandler.obtainMessage(BluetoothSync.SYNC_SUCCESSFUL).sendToTarget();	
+				break;			
+			case SyncMessage.SYNC_RESPONSE_SYNC_INFO:
+				ArrayList<SyncInfoRecord> syncInfo_new = (ArrayList<SyncInfoRecord>) message.getPayload();
+				mdbh.updateSyncInfo(syncInfo_new);
+				break;
+			default: 
+				//TODO DEFAULT WITH UNKNOWN MESSAGE CODE;
+		}		
+	}
+	
+	/* Call this from the main activity to send data to the remote device */
+	public void write(SyncMessage message) {
+		try {
+			objectOuput.writeObject(message);
+//TODO NACHRICHT SCHICKEN?			mHandler.obtainMessage(BluetoothSync.MESSAGE_SENT).sendToTarget();
+		} catch (IOException e) {
+			mHandler.obtainMessage(BluetoothSync.CONNECTION_FAILED).sendToTarget();
+			e.printStackTrace();
+		}
+	}
+}	

+ 57 - 0
src/de/tudarmstadt/informatik/hostage/sync/bluetooth/ServerThread.java

@@ -0,0 +1,57 @@
+package de.tudarmstadt.informatik.hostage.sync.bluetooth;
+
+import java.io.IOException;
+
+import android.bluetooth.BluetoothAdapter;
+import android.bluetooth.BluetoothServerSocket;
+import android.bluetooth.BluetoothSocket;
+import android.os.Handler;
+
+public class ServerThread extends Thread {
+	private final BluetoothServerSocket serverSocket;
+	private final Handler mHandler;
+
+	public ServerThread(Handler handler, String app_name) {
+		BluetoothServerSocket tmp = null;
+		mHandler = handler;
+		try {
+			tmp = BluetoothAdapter.getDefaultAdapter().listenUsingRfcommWithServiceRecord(app_name, BluetoothSync.serviceUUID);
+		} catch (IOException e) {
+			mHandler.obtainMessage(BluetoothSync.CONNECTION_FAILED).sendToTarget();
+		}
+		serverSocket = tmp;
+	}
+
+	/** Will cancel the listening socket, and cause the thread to finish */
+	public void cancel() {
+		try {
+			serverSocket.close();
+		} catch (IOException e) {
+		}
+	}
+
+	@Override
+	public void run() {
+		BluetoothSocket socket = null;
+		while (true) {
+			try {
+				socket = serverSocket.accept();
+			} catch (IOException e) {
+				e.printStackTrace();
+				mHandler.obtainMessage(BluetoothSync.CONNECTION_FAILED).sendToTarget();
+				break;
+			}
+
+			if (socket != null) {
+				// Do work to manage the connection (in a separate thread)
+				mHandler.obtainMessage(BluetoothSync.CONNECTION_ESTABLISHED, socket).sendToTarget();
+				try {
+					serverSocket.close();
+				} catch (IOException e) {
+					e.printStackTrace();
+				}
+				break;
+			}
+		}
+	}
+}

+ 5 - 6
src/de/tudarmstadt/informatik/hostage/sync/NFCSync.java → src/de/tudarmstadt/informatik/hostage/sync/nfc/NFCSync.java

@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package de.tudarmstadt.informatik.hostage.sync;
+package de.tudarmstadt.informatik.hostage.sync.nfc;
 
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
@@ -22,8 +22,6 @@ import java.io.IOException;
 import java.io.ObjectInputStream;
 import java.io.ObjectOutputStream;
 import java.util.ArrayList;
-import java.util.HashMap;
-
 import android.annotation.TargetApi;
 import android.app.Activity;
 import android.content.Intent;
@@ -42,6 +40,7 @@ import android.util.Log;
 import android.widget.TextView;
 import android.widget.Toast;
 import de.tudarmstadt.informatik.hostage.R;
+import de.tudarmstadt.informatik.hostage.logging.NetworkRecord;
 import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
 
 @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@@ -72,7 +71,7 @@ public class NFCSync extends Activity implements CreateNdefMessageCallback, OnNd
 	public NdefMessage createNdefMessage(NfcEvent event) {
 		// Get Networkdata
 		HostageDBOpenHelper dbh = new HostageDBOpenHelper(this);
-		ArrayList<HashMap<String, Object>> localNetworkInformation = dbh.getNetworkInformation();
+		ArrayList<NetworkRecord> localNetworkInformation = dbh.getNetworkInformation();
 		Log.i("NFC", "Creating Message");
 		NdefMessage msg = null;
 		try {
@@ -90,7 +89,7 @@ public class NFCSync extends Activity implements CreateNdefMessageCallback, OnNd
 		super.onCreate(savedInstanceState);
 		setContentView(R.layout.activity_nfc);
 
-		mInfoText = (TextView) findViewById(R.id.record_details_text_ssid);
+		mInfoText = (TextView) findViewById(R.id.nfc_text_view);
 		// Check for available NFC Adapter
 		mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
 		if (mNfcAdapter == null) {
@@ -143,7 +142,7 @@ public class NFCSync extends Activity implements CreateNdefMessageCallback, OnNd
 		Log.i("NFC", "Getting Message!");
 		try {
 			object = deserialize(msg.getRecords()[0].getPayload());
-			ArrayList<HashMap<String, Object>> remoteNetworkInformation = (ArrayList<HashMap<String, Object>>) object;
+			ArrayList<NetworkRecord> remoteNetworkInformation = (ArrayList<NetworkRecord>) object;
 			HostageDBOpenHelper dbh = new HostageDBOpenHelper(this);
 			dbh.updateNetworkInformation(remoteNetworkInformation);
 		} catch (ClassNotFoundException e) {

+ 5 - 0
src/de/tudarmstadt/informatik/hostage/sync/tracing/TracingSyncActivity.java

@@ -0,0 +1,5 @@
+package de.tudarmstadt.informatik.hostage.sync.tracing;
+
+public class TracingSyncActivity {
+	//TODO
+}

+ 162 - 0
src/de/tudarmstadt/informatik/hostage/sync/tracing/TracingSyncService.java

@@ -0,0 +1,162 @@
+package de.tudarmstadt.informatik.hostage.sync.tracing;
+
+import java.security.KeyStore;
+import java.util.ArrayList;
+
+import org.apache.http.HttpVersion;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.conn.ClientConnectionManager;
+import org.apache.http.conn.scheme.PlainSocketFactory;
+import org.apache.http.conn.scheme.Scheme;
+import org.apache.http.conn.scheme.SchemeRegistry;
+import org.apache.http.conn.ssl.SSLSocketFactory;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.DefaultHttpClient;
+import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
+import org.apache.http.params.BasicHttpParams;
+import org.apache.http.params.HttpParams;
+import org.apache.http.params.HttpProtocolParams;
+import org.apache.http.protocol.HTTP;
+
+import android.app.IntentService;
+import android.content.Intent;
+import android.content.SharedPreferences;
+import android.content.SharedPreferences.Editor;
+import android.os.Handler;
+import android.preference.PreferenceManager;
+import de.tudarmstadt.informatik.hostage.logging.AttackRecord;
+import de.tudarmstadt.informatik.hostage.logging.formatter.TraCINgFormatter;
+import de.tudarmstadt.informatik.hostage.net.MySSLSocketFactory;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
+
+public class TracingSyncService extends IntentService{
+	
+	public static final int RECORD_UPLOADED = 0x00;
+	public static final int SYNC_COMPLETE = 0x01;
+	
+	private HttpClient httpClient;
+	private Handler mHandler;
+	
+	HostageDBOpenHelper dbh;
+	
+	SharedPreferences pref;
+	Editor editor;
+
+	public TracingSyncService(Handler handler) {
+		super("TracingSyncService");
+		mHandler = handler;
+		httpClient = createHttpClient();
+		pref = PreferenceManager.getDefaultSharedPreferences(this);
+		editor = pref.edit();
+		dbh = new HostageDBOpenHelper(this);
+	}
+
+	/**
+	 * The IntentService calls this method from the default worker thread with
+	 * the intent that started the service. When this method returns, IntentService
+	 * stops the service, as appropriate.
+	 */
+	@Override
+	protected void onHandleIntent(Intent intent) {
+		//TODO Fallunterscheidung Intents		
+		uploadNewRecords();
+		getRemoteData();
+		dbh.clearSyncInfos();
+	}	
+	
+	
+	/**
+	 * Uploads all new Records to a server, specified in the settings.
+	 */
+	private void uploadNewRecords() {
+		int lastUploadedAttackId = pref.getInt("LAST_UPLOADED_ATTACK_ID", -1);
+		String serverAddress = pref.getString("pref_upload", "https://ssi.cased.de");	
+		ArrayList<AttackRecord> recordList = dbh.getRecordOfEachAttack(lastUploadedAttackId);
+		int size = recordList.size();
+		int offset = 1;
+		for(AttackRecord record: recordList){
+			editor.putInt("LAST_UPLOADED_ATTACK_ID", lastUploadedAttackId + offset);
+			uploadSingleRecord(record, serverAddress);
+			if(mHandler != null)
+				mHandler.obtainMessage(RECORD_UPLOADED, offset, size);
+			offset++;			
+		}
+	}	
+	
+	/**
+	 * Uploads a single Record to a server, specified in the settings.
+	 * 
+	 * @param record The Record to upload.
+	 * @serverAddress Address of the target server
+	 * @return True if the upload was successful, else false.
+	 */
+	private boolean uploadSingleRecord(AttackRecord record, String serverAddress) {
+		// Create a https client. Uses MySSLSocketFactory to accept all certificates
+		HttpPost httppost;
+		try {
+			// Create HttpPost
+			httppost = new HttpPost();
+			// Create JSON String of Record
+			//TODO FIX ME
+			StringEntity se = new StringEntity( null/*record.toString(TraCINgFormatter
+					.getInstance()) */);
+			httppost.setEntity(se);
+			// Execute HttpPost
+			httpClient.execute(httppost);
+		} catch (Exception e) {
+			e.printStackTrace();
+			return false;
+		}
+		return true;
+	}
+	
+	/**
+	 * Uploads a single Record to a server, specified in the settings.
+	 * 
+	 * @param record
+	 *            The Record to upload.
+	 * @return True if the upload was successful, else false.
+	 */
+	private void getRemoteData() {
+		//TODO GET DATA FROM SERVER
+		//TODO SAVE DATA IN DATABASE
+	}
+	
+	/**
+	 * Creates a HttpClient with an own SSL Socket.
+	 * 
+	 * @return HttpsClient who accepts accepts all certificates.
+	 * @see MySSLSocketFactory
+	 */
+	private HttpClient createHttpClient() {
+		try {
+			KeyStore trustStore = KeyStore.getInstance(KeyStore
+					.getDefaultType());
+			trustStore.load(null, null);
+
+			SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
+			sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
+
+			HttpParams params = new BasicHttpParams();
+			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
+			HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
+
+			SchemeRegistry registry = new SchemeRegistry();
+			registry.register(new Scheme("http", PlainSocketFactory
+					.getSocketFactory(), 80));
+			registry.register(new Scheme("https", sf, 443));
+
+			ClientConnectionManager ccm = new ThreadSafeClientConnManager(
+					params, registry);
+
+			return new DefaultHttpClient(ccm, params);
+		} catch (Exception e) {
+			e.printStackTrace();
+			return new DefaultHttpClient();
+		}
+	}
+
+
+
+}

+ 1 - 1
src/de/tudarmstadt/informatik/hostage/ui/MainActivity.java

@@ -205,7 +205,7 @@ public class MainActivity extends FragmentActivity {
 	 *            View elements which triggers the method call.
 	 */
 	public void showLog(View view) {
-		startActivity(new Intent(this, ViewLog.class));
+		//startActivity(new Intent(this, ViewLog.class));
 	}
 
 	public void startPlayGround(View view) {

+ 31 - 21
src/de/tudarmstadt/informatik/hostage/ui/PlayGroundActivity.java

@@ -8,30 +8,35 @@ import java.util.Random;
 import android.app.Activity;
 import android.content.Intent;
 import android.os.Bundle;
+import android.preference.PreferenceManager;
+import android.util.Log;
 import android.view.Menu;
 import android.view.View;
 import android.widget.TextView;
 import de.tudarmstadt.informatik.hostage.R;
+import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
+import de.tudarmstadt.informatik.hostage.logging.NetworkRecord;
+import de.tudarmstadt.informatik.hostage.logging.SyncInfoRecord;
 import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract;
 import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
-import de.tudarmstadt.informatik.hostage.sync.BluetoothSync;
-import de.tudarmstadt.informatik.hostage.sync.NFCSync;
+import de.tudarmstadt.informatik.hostage.sync.bluetooth.BluetoothSync;
+import de.tudarmstadt.informatik.hostage.sync.nfc.NFCSync;
 
 public class PlayGroundActivity extends Activity {
 
 
 	public void createNetworkData(View view) {
 		Random rnd = new Random();
-		ArrayList<HashMap<String, Object>> fakeNetInfo = new ArrayList<HashMap<String, Object>>();
+		ArrayList<NetworkRecord> fakeNetInfo = new ArrayList<NetworkRecord>();
 		for (int i = 0; i < 25; i++) {
-			HashMap<String, Object> network = new HashMap<String, Object>();
-			network.put(HostageDBContract.NetworkEntry.COLUMN_NAME_BSSID, createRandomBSSID());
-			network.put(HostageDBContract.NetworkEntry.COLUMN_NAME_SSID, new BigInteger(130, rnd).toString(32));
-			network.put(HostageDBContract.NetworkEntry.COLUMN_NAME_LATITUDE, rnd.nextDouble() * 360);
-			network.put(HostageDBContract.NetworkEntry.COLUMN_NAME_LONGITUDE, rnd.nextDouble() * 360);
-			network.put(HostageDBContract.NetworkEntry.COLUMN_NAME_ACCURACY, rnd.nextFloat());
-			network.put(HostageDBContract.NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP, System.currentTimeMillis());
-			fakeNetInfo.add(network);
+			NetworkRecord record = new NetworkRecord();
+			record.setBssid(createRandomBSSID());
+			record.setSsid(new BigInteger(130, rnd).toString(32));
+			record.setLatitude(rnd.nextDouble() * 360);
+			record.setLongitude(rnd.nextDouble() * 360);
+			record.setAccuracy(rnd.nextFloat());
+			record.setTimestampLocation(System.currentTimeMillis());
+			fakeNetInfo.add(record);
 		}
 
 		setNetworkInfoText();
@@ -73,18 +78,23 @@ public class PlayGroundActivity extends Activity {
 
 	private void setNetworkInfoText() {
 		HostageDBOpenHelper dbh = new HostageDBOpenHelper(this);
-		TextView bssids = (TextView) findViewById(R.id.textView1);
+		TextView text_view = (TextView) findViewById(R.id.textView1);
 		String text = "";
-		ArrayList<HashMap<String, Object>> netInfo = dbh.getNetworkInformation();
-		for (HashMap<String, Object> network : netInfo) {
-			text = text + (String) network.get(HostageDBContract.NetworkEntry.COLUMN_NAME_BSSID) + "\n"
-					+ (String) network.get(HostageDBContract.NetworkEntry.COLUMN_NAME_SSID) + "\n"
-					+ network.get(HostageDBContract.NetworkEntry.COLUMN_NAME_LATITUDE) + "\n"
-					+ network.get(HostageDBContract.NetworkEntry.COLUMN_NAME_LONGITUDE) + "\n"
-					+ network.get(HostageDBContract.NetworkEntry.COLUMN_NAME_ACCURACY) + "\n"
-					+ network.get(HostageDBContract.NetworkEntry.COLUMN_NAME_GEO_TIMESTAMP) + "\n\n";
+		ArrayList<SyncInfoRecord> syncInfo = dbh.getSyncInfo();
+		HashMap<String, Long> syncDevices = dbh.getSyncDevices();
+
+		for (SyncInfoRecord info: syncInfo) {
+			text = text + info.getBSSID() + "\n"
+					+ info.getDeviceID() + "\n" +
+					+ info.getNumber_of_attacks() + "\n"
+					+ info.getNumber_of_portscans() + "\n\n";
+		}
+		
+		for(String device: syncDevices.keySet()){
+			text = text + device + "\n"
+					+ syncDevices.get(device) + "\n\n";
 		}
-		bssids.setText(text);
+		text_view.setText(text);
 	}
 
 	@Override

+ 2 - 1
src/de/tudarmstadt/informatik/hostage/ui2/fragment/RecordDetailFragment.java

@@ -17,6 +17,7 @@ import android.widget.TextView;
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.deprecated.UglyDbHelper;
 import de.tudarmstadt.informatik.hostage.logging.Record;
+import de.tudarmstadt.informatik.hostage.logging.MessageRecord;
 
 /**
  * Created by Julien on 02.03.14.
@@ -138,7 +139,7 @@ public class RecordDetailFragment extends UpNavigatibleFragment {
 			String from = r.getLocalIP() == null ? "-" : r.getLocalIP() + ":" + r.getLocalPort();
 			String to = r.getRemoteIP() == null ? "-" : r.getRemoteIP() + ":" + r.getRemotePort();
 
-			if (r.getType() == Record.TYPE.SEND) {
+			if (r.getType() == MessageRecord.TYPE.SEND) {
 				row = mInflater.inflate(R.layout.fragment_record_conversation_sent, null);
 			} else {
 				row = mInflater.inflate(R.layout.fragment_record_conversation_received, null);

+ 813 - 813
src/de/tudarmstadt/informatik/hostage/ui2/fragment/RecordOverviewFragment.java

@@ -1,813 +1,813 @@
-package de.tudarmstadt.informatik.hostage.ui2.fragment;
-
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Random;
-
-import android.annotation.SuppressLint;
-import android.app.FragmentManager;
-import android.content.Context;
-import android.content.Intent;
-import android.os.Bundle;
-import android.util.Log;
-import android.view.LayoutInflater;
-import android.view.Menu;
-import android.view.MenuInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.ExpandableListView;
-import android.widget.ImageButton;
-
-import com.google.android.gms.maps.model.LatLng;
-
-import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.deprecated.UglyDbHelper;
-import de.tudarmstadt.informatik.hostage.logging.Record;
-import de.tudarmstadt.informatik.hostage.logging.Record.TYPE;
-import de.tudarmstadt.informatik.hostage.ui.LogFilter;
-import de.tudarmstadt.informatik.hostage.ui.LogFilter.SortType;
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
-import de.tudarmstadt.informatik.hostage.ui2.adapter.RecordListAdapter;
-import de.tudarmstadt.informatik.hostage.ui2.dialog.ChecklistDialog;
-import de.tudarmstadt.informatik.hostage.ui2.dialog.DateTimeDialogFragment;
-import de.tudarmstadt.informatik.hostage.ui2.model.ExpandableListItem;
-import de.tudarmstadt.informatik.hostage.ui2.popup.AbstractPopup;
-import de.tudarmstadt.informatik.hostage.ui2.popup.AbstractPopupItem;
-import de.tudarmstadt.informatik.hostage.ui2.popup.SimplePopupItem;
-import de.tudarmstadt.informatik.hostage.ui2.popup.SimplePopupTable;
-import de.tudarmstadt.informatik.hostage.ui2.popup.SplitPopupItem;
-
-public class RecordOverviewFragment extends UpNavigatibleFragment implements ChecklistDialog.ChecklistDialogListener,
-		DateTimeDialogFragment.DateTimeDialogFragmentListener {
-
-	static final String FILTER_MENU_TITLE_BSSID = "BSSID";
-	static final String FILTER_MENU_TITLE_ESSID = "ESSID";
-	static final String FILTER_MENU_TITLE_PROTOCOLS = MainActivity.getContext().getString(R.string.rec_protocol);
-	static final String FILTER_MENU_TITLE_TIMESTAMP_BELOW = MainActivity.getContext().getString(R.string.rec_latest);
-	static final String FILTER_MENU_TITLE_TIMESTAMP_ABOVE = MainActivity.getContext().getString(R.string.rec_earliest);
-	static final String FILTER_MENU_TITLE_SORTING = MainActivity.getContext().getString(R.string.rec_sortby);
-	static final String FILTER_MENU_TITLE_REMOVE = MainActivity.getContext().getString(R.string.rec_reset_filter);
-	static final String FILTER_MENU_TITLE_GROUP = MainActivity.getContext().getString(R.string.rec_group_by);
-	static final String FILTER_MENU_POPUP_TITLE = MainActivity.getContext().getString(R.string.rec_filter_by);
-
-	private boolean wasBelowTimePicker;
-
-	private LogFilter filter;
-	private boolean showFilterButton;
-
-	private int mListPosition = -1;
-	private int mItemPosition = -1;
-
-	public String groupingKey;
-
-	private ExpandableListView expListView;
-
-	UglyDbHelper dbh;
-
-	private String sectionToOpen = "";
-	private ArrayList<Integer> openSections;
-
-	public void setFilter(LogFilter filter) {
-		this.filter = filter;
-	}
-
-	public RecordOverviewFragment() {
-	}
-
-	public void setGroupKey(String key) {
-		this.groupingKey = key;
-	}
-
-	@Override
-	public void onCreate(Bundle savedInstanceState) {
-		super.onCreate(savedInstanceState);
-		setHasOptionsMenu(true);
-	}
-
-	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
-
-		getActivity().setTitle(getResources().getString(R.string.drawer_records));
-
-		dbh = new UglyDbHelper(this.getActivity().getBaseContext());
-
-		// Get the message from the intent
-
-		if (this.filter == null) {
-			Intent intent = this.getActivity().getIntent();
-			LogFilter filter = intent.getParcelableExtra(LogFilter.LOG_FILTER_INTENT_KEY);
-
-			if (filter == null) {
-				this.clearFilter();
-			} else {
-				this.filter = filter;
-			}
-		}
-
-		if (this.groupingKey == null)
-			this.groupingKey = this.groupingTitles().get(0);
-
-		this.setShowFilterButton(!this.filter.isNotEditable());
-		// this.addRecordToDB();
-
-		View rootView = inflater.inflate(this.getLayoutId(), container, false);
-		ExpandableListView mylist = (ExpandableListView) rootView.findViewById(R.id.loglistview);
-
-		this.expListView = mylist;
-		populateListViewFromDB(mylist);
-
-		if (this.openSections != null && this.openSections.size() != 0) {
-			for (int i = 0; i < this.openSections.size(); i++) {
-				int index = this.openSections.get(i);
-				this.expListView.expandGroup(index);
-			}
-		} else {
-			this.openSections = new ArrayList<Integer>();
-		}
-
-		if (mListPosition != -1 && mItemPosition != -1)
-			this.expListView.setSelectedChild(mListPosition, mItemPosition, true);
-
-		mListPosition = -1;
-		mItemPosition = -1;
-
-		registerListClickCallback(mylist);
-
-		ImageButton filterButton = (ImageButton) rootView.findViewById(R.id.FilterButton);
-		filterButton.setOnClickListener(new View.OnClickListener() {
-			public void onClick(View v) {
-				RecordOverviewFragment.this.openFilterPopupMenuOnView(v);
-			}
-		});
-		filterButton.setVisibility(this.showFilterButton ? View.VISIBLE : View.INVISIBLE);
-
-		ImageButton sortButton = (ImageButton) rootView.findViewById(R.id.SortButton);
-		sortButton.setOnClickListener(new View.OnClickListener() {
-			public void onClick(View v) {
-				// Open SortMenu
-				RecordOverviewFragment.this.openSortingDialog();
-			}
-		});
-
-		ImageButton groupButton = (ImageButton) rootView.findViewById(R.id.GroupButton);
-		groupButton.setOnClickListener(new View.OnClickListener() {
-			public void onClick(View v) {
-				// Open SortMenu
-				RecordOverviewFragment.this.openGroupingDialog();
-			}
-		});
-
-		return rootView;
-	}
-
-	public int getLayoutId() {
-		return R.layout.fragment_record_list;
-	}
-
-	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
-		super.onCreateOptionsMenu(menu, inflater);
-	}
-
-	public void onFilterMenuItemSelected(AbstractPopupItem item) {
-		String title = item.getTitle();
-
-		if (item instanceof SplitPopupItem) {
-			SplitPopupItem splitItem = (SplitPopupItem) item;
-			if (splitItem.wasRightTouch) {
-				this.openTimestampToFilterDialog();
-			} else {
-				this.openTimestampFromFilterDialog();
-			}
-			return;
-		}
-
-		if (title != null) {
-			if (title.equals(FILTER_MENU_TITLE_BSSID)) {
-				this.openBSSIDFilterDialog();
-			}
-			if (title.equals(FILTER_MENU_TITLE_ESSID)) {
-				this.openESSIDFilterDialog();
-			}
-			if (title.equals(FILTER_MENU_TITLE_PROTOCOLS)) {
-				this.openProtocolsFilterDialog();
-			}
-			if (title.equals(FILTER_MENU_TITLE_SORTING)) {
-				this.openSortingDialog();
-			}
-			if (title.equals(FILTER_MENU_TITLE_REMOVE)) {
-				this.clearFilter();
-				this.populateListViewFromDB(this.expListView);
-			}
-			if (title.equals(FILTER_MENU_TITLE_TIMESTAMP_BELOW)) {
-				this.openTimestampToFilterDialog();
-			}
-			if (title.equals(FILTER_MENU_TITLE_TIMESTAMP_ABOVE)) {
-				this.openTimestampFromFilterDialog();
-			}
-		}
-		// return super.onOptionsItemSelected(item);
-	}
-
-	public void onStart() {
-		super.onStart();
-		// this.populateListViewFromDB(this.expListView);
-		if (this.expListView.getExpandableListAdapter().getGroupCount() == 1) {
-			this.expListView.expandGroup(0);
-		} else {
-			this.setSectionToOpen(this.sectionToOpen);
-		}
-	}
-
-	/*****************************
-	 * 
-	 * Public API
-	 * 
-	 * ***************************/
-
-	/**
-	 * Group records by SSID and expand given SSID
-	 * 
-	 * @param SSID
-	 *            the SSID
-	 */
-	public void showDetailsForSSID(Context context, String SSID) {
-		Log.e("RecordOverviewFragment", "Implement showDetailsForSSID!!");
-		this.clearFilter();
-		int ESSID_INDEX = 2;
-		ArrayList<String> ssids = new ArrayList<String>();
-		this.sectionToOpen = SSID;
-		this.groupingKey = this.groupingTitles(context).get(ESSID_INDEX);
-	}
-
-	/*****************************
-	 * UglyDbHelper
-	 * 
-	 * ListView Stuff
-	 * 
-	 * ***************************/
-
-	private void populateListViewFromDB(ExpandableListView mylist) {
-
-		HashMap<String, ArrayList<ExpandableListItem>> sectionData = new HashMap<String, ArrayList<ExpandableListItem>>();
-
-		ArrayList<Record> data = dbh.getRecordsForFilter(this.filter);
-
-		// Adding Items to ListView
-		String keys[] = new String[] { this.getString(R.string.RecordBSSID), this.getString(R.string.RecordSSID), this.getString(R.string.RecordProtocol),
-				this.getString(R.string.RecordTimestamp) };
-		int ids[] = new int[] { R.id.RecordTextFieldBSSID, R.id.RecordTextFieldSSID, R.id.RecordTextFieldProtocol, R.id.RecordTextFieldTimestamp };
-
-		HashMap<String, Integer> mapping = new HashMap<String, Integer>();
-		int i = 0;
-		for (String key : keys) {
-			mapping.put(key, ids[i]);
-			i++;
-		}
-
-		ArrayList<String> groupTitle = new ArrayList<String>();
-
-		for (Record val : data) {
-			// DO GROUPING IN HERE
-			HashMap<String, String> map = new HashMap<String, String>();
-			map.put(this.getString(R.string.RecordBSSID), val.getBssid());
-			map.put(this.getString(R.string.RecordSSID), val.getSsid());
-			map.put(this.getString(R.string.RecordProtocol), val.getProtocol());
-			map.put(this.getString(R.string.RecordTimestamp), this.getDateAsString(val.getTimestamp()));
-
-			ExpandableListItem item = new ExpandableListItem();
-			item.setData(map);
-
-			item.setId_Mapping(mapping);
-
-			item.setTag(val.getAttack_id());
-
-			String groupID = this.getGroupValue(val);
-
-			ArrayList<ExpandableListItem> items = sectionData.get(groupID);
-			if (items == null) {
-				items = new ArrayList<ExpandableListItem>();
-				sectionData.put(groupID, items);
-				groupTitle.add(groupID);
-			}
-
-			items.add(item);
-		}
-
-		Collections.sort(groupTitle, new Comparator<String>() {
-			@Override
-			public int compare(String s1, String s2) {
-				return s1.compareToIgnoreCase(s2);
-			}
-		});
-
-		RecordListAdapter adapter = new RecordListAdapter(this.getApplicationContext(), groupTitle, sectionData);
-
-		mylist.setAdapter(adapter);
-	}
-
-	private void setSectionToOpen(String s) {
-		this.sectionToOpen = s;
-		if (this.sectionToOpen != null && this.sectionToOpen.length() != 0) {
-			if (this.getGroupTitle().contains(this.sectionToOpen)) {
-				int section = this.getGroupTitle().indexOf(this.sectionToOpen);
-				this.expListView.expandGroup(section);
-				this.sectionToOpen = "";
-			}
-		}
-	}
-
-	private Context getBaseContext() {
-		return this.getActivity().getBaseContext();
-	}
-
-	private Context getApplicationContext() {
-		return this.getActivity().getApplicationContext();
-	}
-
-	private void registerListClickCallback(ExpandableListView mylist) {
-		mylist.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
-			@Override
-			public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i2, long l) {
-				RecordListAdapter adapter = (RecordListAdapter) expandableListView.getExpandableListAdapter();
-
-				ExpandableListItem item = (ExpandableListItem) adapter.getChild(i, i2);
-
-				mListPosition = i;
-				mItemPosition = i2;
-				UglyDbHelper dbh = new UglyDbHelper(getBaseContext());
-				Record rec = dbh.getRecordOfAttackId((int) item.getTag());
-				RecordOverviewFragment.this.pushRecordDetailViewForRecord(rec);
-				return true;
-			}
-		});
-		mylist.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
-			@Override
-			public void onGroupExpand(int i) {
-				RecordOverviewFragment.this.openSections.add(new Integer(i));
-			}
-		});
-		mylist.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
-			@Override
-			public void onGroupCollapse(int i) {
-				RecordOverviewFragment.this.openSections.remove(new Integer(i));
-			}
-		});
-	}
-
-	/*****************************
-	 * 
-	 * Date Transform
-	 * 
-	 * ***************************/
-
-	@SuppressLint("SimpleDateFormat")
-	private String getDateAsString(long timeStamp) {
-
-		try {
-			DateFormat sdf = new SimpleDateFormat("H:mm d.M.yy");
-			Date netDate = (new Date(timeStamp));
-			return sdf.format(netDate);
-		} catch (Exception ex) {
-			return "xx";
-		}
-	}
-
-	/*****************************
-	 * 
-	 * Getter / Setter
-	 * 
-	 * ***************************/
-
-	public boolean isShowFilterButton() {
-		return showFilterButton;
-	}
-
-	public void setShowFilterButton(boolean showFilterButton) {
-		this.showFilterButton = showFilterButton;
-	}
-
-	/*****************************
-	 * 
-	 * Open Dialog Methods
-	 * 
-	 * ***************************/
-
-	private void openGroupingDialog() {
-		ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_TITLE_GROUP, this.groupingTitles(), this.selectedGroup(), false, this);
-		newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_GROUP);
-	}
-
-	private void openBSSIDFilterDialog() {
-		ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_TITLE_BSSID, this.bssids(), this.selectedBSSIDs(), true, this);
-		newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_BSSID);
-	}
-
-	private void openESSIDFilterDialog() {
-		ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_TITLE_ESSID, this.essids(), this.selectedESSIDs(), true, this);
-		newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_ESSID);
-	}
-
-	private void openProtocolsFilterDialog() {
-		ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_TITLE_PROTOCOLS, this.protocolTitles(), this.selectedProtocols(), true, this);
-		newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_PROTOCOLS);
-	}
-
-	private void openTimestampFromFilterDialog() {
-		this.wasBelowTimePicker = false;
-		DateTimeDialogFragment newFragment = new DateTimeDialogFragment(this.getActivity());
-		newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_SORTING);
-		if (this.filter.aboveTimestamp != Long.MIN_VALUE)
-			newFragment.setDate(this.filter.aboveTimestamp);
-	}
-
-	private void openTimestampToFilterDialog() {
-		this.wasBelowTimePicker = true;
-		DateTimeDialogFragment newFragment = new DateTimeDialogFragment(this.getActivity());
-		newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_SORTING);
-		if (this.filter.belowTimestamp != Long.MAX_VALUE)
-			newFragment.setDate(this.filter.belowTimestamp);
-	}
-
-	private void openSortingDialog() {
-		ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_TITLE_SORTING, this.sortTypeTiles(), this.selectedSorttype(), false, this);
-		newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_SORTING);
-	}
-
-	/*****************************
-	 * 
-	 * Grouping Stuff
-	 * 
-	 * ***************************/
-
-	public String getGroupValue(Record rec) {
-		int index = this.groupingTitles().indexOf(this.groupingKey);
-		switch (index) {
-		case 0:
-			return rec.getProtocol();
-		case 1:
-			return rec.getBssid();
-		case 2:
-			return rec.getSsid();
-		default:
-			return rec.getProtocol();
-		}
-	}
-
-	public ArrayList<String> getGroupTitle() {
-		int index = this.groupingTitles().indexOf(this.groupingKey);
-		switch (index) {
-		case 0:
-			return this.protocolTitles();
-		case 1:
-			return this.bssids();
-		case 2:
-			return this.essids();
-		default:
-			return this.protocolTitles();
-		}
-	}
-
-	/*****************************
-	 * 
-	 * Filter Stuff
-	 * 
-	 * ***************************/
-
-	private void openFilterPopupMenuOnView(View v) {
-
-		SimplePopupTable filterMenu = new SimplePopupTable(this.getActivity(), new AbstractPopup.OnPopupItemClickListener() {
-			public void onItemClick(Object ob) {
-				if (ob instanceof AbstractPopupItem) {
-					AbstractPopupItem item = (AbstractPopupItem) ob;
-					RecordOverviewFragment.this.onFilterMenuItemSelected(item);
-				}
-			}
-		});
-		filterMenu.setTitle(FILTER_MENU_POPUP_TITLE);
-		for (String title : RecordOverviewFragment.this.filterMenuTitles()) {
-			AbstractPopupItem item = null;
-			if (title.equals(FILTER_MENU_TITLE_TIMESTAMP_BELOW))
-				continue;
-			if (title.equals(FILTER_MENU_TITLE_TIMESTAMP_ABOVE)) {
-				item = new SplitPopupItem(this.getActivity());
-				item.setValue(SplitPopupItem.RIGHT_TITLE, FILTER_MENU_TITLE_TIMESTAMP_BELOW);
-				item.setValue(SplitPopupItem.LEFT_TITLE, FILTER_MENU_TITLE_TIMESTAMP_ABOVE);
-				if (this.filter.hasBelowTimestamp()) {
-					item.setValue(SplitPopupItem.RIGHT_SUBTITLE, this.getDateAsString(this.filter.belowTimestamp));
-				}
-				if (this.filter.hasAboveTimestamp()) {
-					item.setValue(SplitPopupItem.LEFT_SUBTITLE, this.getDateAsString(this.filter.aboveTimestamp));
-				}
-			} else {
-				item = new SimplePopupItem(this.getActivity());
-				item.setTitle(title);
-				((SimplePopupItem) item).setSelected(this.isFilterSetForTitle(title));
-			}
-
-			filterMenu.addItem(item);
-		}
-		filterMenu.showOnView(v);
-	}
-
-	private boolean isFilterSetForTitle(String title) {
-		if (title.equals(FILTER_MENU_TITLE_BSSID)) {
-			return this.filter.hasBSSIDs();
-		}
-		if (title.equals(FILTER_MENU_TITLE_ESSID)) {
-			return this.filter.hasESSIDs();
-		}
-		if (title.equals(FILTER_MENU_TITLE_PROTOCOLS)) {
-			return this.filter.hasProtocols();
-		}
-		if (title.equals(FILTER_MENU_TITLE_TIMESTAMP_BELOW)) {
-			return this.filter.hasBelowTimestamp();
-		}
-		if (title.equals(FILTER_MENU_TITLE_TIMESTAMP_ABOVE)) {
-			return this.filter.hasAboveTimestamp();
-		}
-		return false;
-	}
-
-	private void clearFilter() {
-		if (filter == null)
-			this.filter = new LogFilter();
-		this.filter.clear();
-	}
-
-	public ArrayList<String> groupingTitles(Context context) {
-		ArrayList<String> titles = new ArrayList<String>();
-		for (String groupTitle : context.getResources().getStringArray(R.array.Grouping)) {
-			titles.add(groupTitle);
-		}
-		return titles;
-	}
-
-	public ArrayList<String> groupingTitles() {
-		ArrayList<String> titles = new ArrayList<String>();
-		for (String groupTitle : this.getResources().getStringArray(R.array.Grouping)) {
-			titles.add(groupTitle);
-		}
-		return titles;
-	}
-
-	public boolean[] selectedGroup() {
-		ArrayList<String> groups = this.groupingTitles();
-		boolean[] selected = new boolean[groups.size()];
-		int i = 0;
-		for (String group : groups) {
-			selected[i] = (group.equals(this.groupingKey));
-			i++;
-		}
-		return selected;
-	}
-
-	public ArrayList<String> protocolTitles() {
-		ArrayList<String> titles = new ArrayList<String>();
-		for (String protocol : this.getResources().getStringArray(R.array.protocols)) {
-			titles.add(protocol);
-		}
-		return titles;
-	}
-
-	public boolean[] selectedProtocols() {
-		ArrayList<String> protocols = this.protocolTitles();
-		boolean[] selected = new boolean[protocols.size()];
-
-		int i = 0;
-		for (String protocol : protocols) {
-			selected[i] = (this.filter.protocols.contains(protocol));
-			i++;
-		}
-		return selected;
-	}
-
-	public ArrayList<String> sortTypeTiles() {
-		ArrayList<String> titles = new ArrayList<String>();
-		titles.add(MainActivity.getContext().getString(R.string.rec_time));
-		titles.add(MainActivity.getContext().getString(R.string.rec_protocol));
-		titles.add("BSSID");
-		titles.add("ESSID");
-		// titles.add("Remote Host Name");
-		// titles.add("Local Host Name");
-		// titles.add("Attack ID");
-		// titles.add("ID");
-		return titles;
-	}
-
-	public boolean[] selectedSorttype() {
-		ArrayList<String> types = this.sortTypeTiles();
-		boolean[] selected = new boolean[types.size()];
-		int i = 0;
-		for (String sorttype : types) {
-			selected[i] = (this.filter.sorttype.toString().equals(sorttype));
-			i++;
-		}
-		return selected;
-	}
-
-	public ArrayList<String> bssids() {
-		ArrayList<String> records = dbh.getUniqueBSSIDRecords();
-		return records;
-	}
-
-	public boolean[] selectedBSSIDs() {
-		ArrayList<String> bssids = this.bssids();
-		boolean[] selected = new boolean[bssids.size()];
-
-		int i = 0;
-		for (String bssid : bssids) {
-			selected[i] = (this.filter.BSSIDs.contains(bssid));
-			i++;
-		}
-		return selected;
-	}
-
-	public ArrayList<String> essids() {
-		ArrayList<String> records = dbh.getUniqueESSIDRecords();
-		return records;
-	}
-
-	public boolean[] selectedESSIDs() {
-		ArrayList<String> essids = this.essids();
-		boolean[] selected = new boolean[essids.size()];
-
-		int i = 0;
-		for (String essid : essids) {
-			selected[i] = (this.filter.ESSIDs.contains(essid));
-			i++;
-		}
-		return selected;
-	}
-
-	private ArrayList<String> filterMenuTitles() {
-		ArrayList<String> titles = new ArrayList<String>();
-		titles.add(FILTER_MENU_TITLE_BSSID);
-		titles.add(FILTER_MENU_TITLE_ESSID);
-		titles.add(FILTER_MENU_TITLE_PROTOCOLS);
-		titles.add(FILTER_MENU_TITLE_TIMESTAMP_ABOVE);
-		titles.add(FILTER_MENU_TITLE_TIMESTAMP_BELOW);
-		if (this.filter.isSet())
-			titles.add(FILTER_MENU_TITLE_REMOVE);
-		return titles;
-	}
-
-	/*****************************
-	 * 
-	 * Listener Actions
-	 * 
-	 * ***************************/
-
-	public void onDateTimePickerPositiveClick(DateTimeDialogFragment dialog) {
-		if (this.wasBelowTimePicker) {
-			this.filter.setBelowTimestamp(dialog.getDate());
-		} else {
-			this.filter.setAboveTimestamp(dialog.getDate());
-		}
-		this.populateListViewFromDB(this.expListView);
-	}
-
-	public void onDateTimePickerNegativeClick(DateTimeDialogFragment dialog) {
-		if (this.wasBelowTimePicker) {
-			this.filter.setBelowTimestamp(Long.MAX_VALUE);
-		} else {
-			this.filter.setAboveTimestamp(Long.MIN_VALUE);
-		}
-	}
-
-	public void onDialogPositiveClick(ChecklistDialog dialog) {
-		String title = dialog.getTitle();
-		if (title.equals(FILTER_MENU_TITLE_BSSID)) {
-			ArrayList<String> titles = dialog.getSelectedItemTitles();
-			if (titles.size() == this.bssids().size()) {
-				this.filter.setBSSIDs(new ArrayList<String>());
-			} else {
-				this.filter.setBSSIDs(titles);
-			}
-		}
-		if (title.equals(FILTER_MENU_TITLE_ESSID)) {
-			ArrayList<String> titles = dialog.getSelectedItemTitles();
-			if (titles.size() == this.essids().size()) {
-				this.filter.setESSIDs(new ArrayList<String>());
-			} else {
-				this.filter.setESSIDs(titles);
-			}
-		}
-		if (title.equals(FILTER_MENU_TITLE_PROTOCOLS)) {
-			ArrayList<String> protocols = dialog.getSelectedItemTitles();
-			if (protocols.size() == this.protocolTitles().size()) {
-				this.filter.setProtocols(new ArrayList<String>());
-			} else {
-				this.filter.setProtocols(dialog.getSelectedItemTitles());
-			}
-		}
-		if (title.equals(FILTER_MENU_TITLE_SORTING)) {
-			ArrayList<String> titles = dialog.getSelectedItemTitles();
-			if (titles.size() == 0)
-				return;
-			String t = titles.get(0);
-			int sortType = this.sortTypeTiles().indexOf(t);
-			this.filter.setSorttype(SortType.values()[sortType]);
-		}
-		if (title.equals(FILTER_MENU_TITLE_GROUP)) {
-			ArrayList<String> titles = dialog.getSelectedItemTitles();
-			if (titles.size() == 0)
-				return;
-			this.groupingKey = titles.get(0);
-		}
-		this.populateListViewFromDB(this.expListView);
-	}
-
-	public void onDialogNegativeClick(ChecklistDialog dialog) {
-
-	}
-
-	/*****************************
-	 * 
-	 * TEST
-	 * 
-	 * ***************************/
-
-	private void addRecordToDB() {
-		if ((dbh.getRecordCount() > 0))
-			return;
-
-		Calendar cal = Calendar.getInstance();
-
-		int maxProtocolsIndex = this.getResources().getStringArray(R.array.protocols).length;
-
-		Random random = new Random();
-
-		LatLng tudarmstadtLoc = new LatLng(49.86923, 8.6632768);
-
-		final int numSSIDs = 10;
-		final int numUniqueSSIDs = 6;
-		final double ssidRadius = 0.1;
-		final double bssidRadius = 0.004;
-		int id = 0; // global id
-		for (int ssid = 0; ssid < numSSIDs; ssid++) {
-			LatLng ssidLocation = new LatLng(tudarmstadtLoc.latitude - ssidRadius + 2.0 * ssidRadius * Math.random(), tudarmstadtLoc.longitude - ssidRadius
-					+ 2.0 * ssidRadius * Math.random());
-
-			String ssidName = "WiFi" + ((ssid % numUniqueSSIDs) + 1);
-
-			int numBSSIDs = (Math.abs(random.nextInt()) % 20) + 1;
-			for (int bssid = 0; bssid < numBSSIDs; bssid++) {
-				Record record = new Record();
-				record.setId(id);
-				record.setAttack_id(id);
-				record.setBssid("BSSID" + id);
-				id++;
-
-				record.setSsid(ssidName);
-				record.setTimestamp(cal.getTimeInMillis() + ((id * 60 * 60 * 60 * 24) * 1000));
-
-				int index = id % maxProtocolsIndex;
-				String protocolName = this.getResources().getStringArray(R.array.protocols)[index];
-
-				record.setProtocol(protocolName);
-
-				record.setLocalIP("127.0.0.1");
-				record.setType(TYPE.SEND);
-
-				record.setLatitude(ssidLocation.latitude - bssidRadius + 2.0 * bssidRadius * Math.random());
-				record.setLongitude(ssidLocation.longitude - bssidRadius + 2.0 * bssidRadius * Math.random());
-
-				dbh.addRecord(record);
-			}
-		}
-
-		int countAllLogs = dbh.getAllRecords().size();
-		int countRecords = dbh.getRecordCount();
-		int countAttacks = dbh.getAttackCount();
-
-		if ((countRecords == 0)) {
-			Record rec = dbh.getRecordOfAttackId(0);
-			Record rec2 = dbh.getRecord(0);
-
-			System.out.println("" + "Could not create logs!");
-		}
-
-	}
-
-	/* Navigation */
-	private void pushRecordDetailViewForRecord(Record record) {
-
-		FragmentManager fm = this.getActivity().getFragmentManager();
-
-		if (fm != null) {
-			RecordDetailFragment newFragment = new RecordDetailFragment();
-			newFragment.setRecord(record);
-
-			newFragment.setUpNavigatible(true);
-
-			MainActivity.getInstance().injectFragment(newFragment);
-
-		}
-
-	}
-}
+package de.tudarmstadt.informatik.hostage.ui2.fragment;
+
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Random;
+
+import android.annotation.SuppressLint;
+import android.app.FragmentManager;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.Menu;
+import android.view.MenuInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ExpandableListView;
+import android.widget.ImageButton;
+
+import com.google.android.gms.maps.model.LatLng;
+
+import de.tudarmstadt.informatik.hostage.R;
+import de.tudarmstadt.informatik.hostage.deprecated.UglyDbHelper;
+import de.tudarmstadt.informatik.hostage.logging.Record;
+import de.tudarmstadt.informatik.hostage.logging.MessageRecord;
+import de.tudarmstadt.informatik.hostage.ui.LogFilter;
+import de.tudarmstadt.informatik.hostage.ui.LogFilter.SortType;
+import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
+import de.tudarmstadt.informatik.hostage.ui2.adapter.RecordListAdapter;
+import de.tudarmstadt.informatik.hostage.ui2.dialog.ChecklistDialog;
+import de.tudarmstadt.informatik.hostage.ui2.dialog.DateTimeDialogFragment;
+import de.tudarmstadt.informatik.hostage.ui2.model.ExpandableListItem;
+import de.tudarmstadt.informatik.hostage.ui2.popup.AbstractPopup;
+import de.tudarmstadt.informatik.hostage.ui2.popup.AbstractPopupItem;
+import de.tudarmstadt.informatik.hostage.ui2.popup.SimplePopupItem;
+import de.tudarmstadt.informatik.hostage.ui2.popup.SimplePopupTable;
+import de.tudarmstadt.informatik.hostage.ui2.popup.SplitPopupItem;
+
+public class RecordOverviewFragment extends UpNavigatibleFragment implements ChecklistDialog.ChecklistDialogListener,
+		DateTimeDialogFragment.DateTimeDialogFragmentListener {
+
+	static final String FILTER_MENU_TITLE_BSSID = "BSSID";
+	static final String FILTER_MENU_TITLE_ESSID = "ESSID";
+	static final String FILTER_MENU_TITLE_PROTOCOLS = MainActivity.getContext().getString(R.string.rec_protocol);
+	static final String FILTER_MENU_TITLE_TIMESTAMP_BELOW = MainActivity.getContext().getString(R.string.rec_latest);
+	static final String FILTER_MENU_TITLE_TIMESTAMP_ABOVE = MainActivity.getContext().getString(R.string.rec_earliest);
+	static final String FILTER_MENU_TITLE_SORTING = MainActivity.getContext().getString(R.string.rec_sortby);
+	static final String FILTER_MENU_TITLE_REMOVE = MainActivity.getContext().getString(R.string.rec_reset_filter);
+	static final String FILTER_MENU_TITLE_GROUP = MainActivity.getContext().getString(R.string.rec_group_by);
+	static final String FILTER_MENU_POPUP_TITLE = MainActivity.getContext().getString(R.string.rec_filter_by);
+
+	private boolean wasBelowTimePicker;
+
+	private LogFilter filter;
+	private boolean showFilterButton;
+
+	private int mListPosition = -1;
+	private int mItemPosition = -1;
+
+	public String groupingKey;
+
+	private ExpandableListView expListView;
+
+	UglyDbHelper dbh;
+
+	private String sectionToOpen = "";
+	private ArrayList<Integer> openSections;
+
+	public void setFilter(LogFilter filter) {
+		this.filter = filter;
+	}
+
+	public RecordOverviewFragment() {
+	}
+
+	public void setGroupKey(String key) {
+		this.groupingKey = key;
+	}
+
+	@Override
+	public void onCreate(Bundle savedInstanceState) {
+		super.onCreate(savedInstanceState);
+		setHasOptionsMenu(true);
+	}
+
+	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+
+		getActivity().setTitle(getResources().getString(R.string.drawer_records));
+
+		dbh = new UglyDbHelper(this.getActivity().getBaseContext());
+
+		// Get the message from the intent
+
+		if (this.filter == null) {
+			Intent intent = this.getActivity().getIntent();
+			LogFilter filter = intent.getParcelableExtra(LogFilter.LOG_FILTER_INTENT_KEY);
+
+			if (filter == null) {
+				this.clearFilter();
+			} else {
+				this.filter = filter;
+			}
+		}
+
+		if (this.groupingKey == null)
+			this.groupingKey = this.groupingTitles().get(0);
+
+		this.setShowFilterButton(!this.filter.isNotEditable());
+		// this.addRecordToDB();
+
+		View rootView = inflater.inflate(this.getLayoutId(), container, false);
+		ExpandableListView mylist = (ExpandableListView) rootView.findViewById(R.id.loglistview);
+
+		this.expListView = mylist;
+		populateListViewFromDB(mylist);
+
+		if (this.openSections != null && this.openSections.size() != 0) {
+			for (int i = 0; i < this.openSections.size(); i++) {
+				int index = this.openSections.get(i);
+				this.expListView.expandGroup(index);
+			}
+		} else {
+			this.openSections = new ArrayList<Integer>();
+		}
+
+		if (mListPosition != -1 && mItemPosition != -1)
+			this.expListView.setSelectedChild(mListPosition, mItemPosition, true);
+
+		mListPosition = -1;
+		mItemPosition = -1;
+
+		registerListClickCallback(mylist);
+
+		ImageButton filterButton = (ImageButton) rootView.findViewById(R.id.FilterButton);
+		filterButton.setOnClickListener(new View.OnClickListener() {
+			public void onClick(View v) {
+				RecordOverviewFragment.this.openFilterPopupMenuOnView(v);
+			}
+		});
+		filterButton.setVisibility(this.showFilterButton ? View.VISIBLE : View.INVISIBLE);
+
+		ImageButton sortButton = (ImageButton) rootView.findViewById(R.id.SortButton);
+		sortButton.setOnClickListener(new View.OnClickListener() {
+			public void onClick(View v) {
+				// Open SortMenu
+				RecordOverviewFragment.this.openSortingDialog();
+			}
+		});
+
+		ImageButton groupButton = (ImageButton) rootView.findViewById(R.id.GroupButton);
+		groupButton.setOnClickListener(new View.OnClickListener() {
+			public void onClick(View v) {
+				// Open SortMenu
+				RecordOverviewFragment.this.openGroupingDialog();
+			}
+		});
+
+		return rootView;
+	}
+
+	public int getLayoutId() {
+		return R.layout.fragment_record_list;
+	}
+
+	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
+		super.onCreateOptionsMenu(menu, inflater);
+	}
+
+	public void onFilterMenuItemSelected(AbstractPopupItem item) {
+		String title = item.getTitle();
+
+		if (item instanceof SplitPopupItem) {
+			SplitPopupItem splitItem = (SplitPopupItem) item;
+			if (splitItem.wasRightTouch) {
+				this.openTimestampToFilterDialog();
+			} else {
+				this.openTimestampFromFilterDialog();
+			}
+			return;
+		}
+
+		if (title != null) {
+			if (title.equals(FILTER_MENU_TITLE_BSSID)) {
+				this.openBSSIDFilterDialog();
+			}
+			if (title.equals(FILTER_MENU_TITLE_ESSID)) {
+				this.openESSIDFilterDialog();
+			}
+			if (title.equals(FILTER_MENU_TITLE_PROTOCOLS)) {
+				this.openProtocolsFilterDialog();
+			}
+			if (title.equals(FILTER_MENU_TITLE_SORTING)) {
+				this.openSortingDialog();
+			}
+			if (title.equals(FILTER_MENU_TITLE_REMOVE)) {
+				this.clearFilter();
+				this.populateListViewFromDB(this.expListView);
+			}
+			if (title.equals(FILTER_MENU_TITLE_TIMESTAMP_BELOW)) {
+				this.openTimestampToFilterDialog();
+			}
+			if (title.equals(FILTER_MENU_TITLE_TIMESTAMP_ABOVE)) {
+				this.openTimestampFromFilterDialog();
+			}
+		}
+		// return super.onOptionsItemSelected(item);
+	}
+
+	public void onStart() {
+		super.onStart();
+		// this.populateListViewFromDB(this.expListView);
+		if (this.expListView.getExpandableListAdapter().getGroupCount() == 1) {
+			this.expListView.expandGroup(0);
+		} else {
+			this.setSectionToOpen(this.sectionToOpen);
+		}
+	}
+
+	/*****************************
+	 * 
+	 * Public API
+	 * 
+	 * ***************************/
+
+	/**
+	 * Group records by SSID and expand given SSID
+	 * 
+	 * @param SSID
+	 *            the SSID
+	 */
+	public void showDetailsForSSID(Context context, String SSID) {
+		Log.e("RecordOverviewFragment", "Implement showDetailsForSSID!!");
+		this.clearFilter();
+		int ESSID_INDEX = 2;
+		ArrayList<String> ssids = new ArrayList<String>();
+		this.sectionToOpen = SSID;
+		this.groupingKey = this.groupingTitles(context).get(ESSID_INDEX);
+	}
+
+	/*****************************
+	 * UglyDbHelper
+	 * 
+	 * ListView Stuff
+	 * 
+	 * ***************************/
+
+	private void populateListViewFromDB(ExpandableListView mylist) {
+
+		HashMap<String, ArrayList<ExpandableListItem>> sectionData = new HashMap<String, ArrayList<ExpandableListItem>>();
+
+		ArrayList<Record> data = dbh.getRecordsForFilter(this.filter);
+
+		// Adding Items to ListView
+		String keys[] = new String[] { this.getString(R.string.RecordBSSID), this.getString(R.string.RecordSSID), this.getString(R.string.RecordProtocol),
+				this.getString(R.string.RecordTimestamp) };
+		int ids[] = new int[] { R.id.RecordTextFieldBSSID, R.id.RecordTextFieldSSID, R.id.RecordTextFieldProtocol, R.id.RecordTextFieldTimestamp };
+
+		HashMap<String, Integer> mapping = new HashMap<String, Integer>();
+		int i = 0;
+		for (String key : keys) {
+			mapping.put(key, ids[i]);
+			i++;
+		}
+
+		ArrayList<String> groupTitle = new ArrayList<String>();
+
+		for (Record val : data) {
+			// DO GROUPING IN HERE
+			HashMap<String, String> map = new HashMap<String, String>();
+			map.put(this.getString(R.string.RecordBSSID), val.getBssid());
+			map.put(this.getString(R.string.RecordSSID), val.getSsid());
+			map.put(this.getString(R.string.RecordProtocol), val.getProtocol());
+			map.put(this.getString(R.string.RecordTimestamp), this.getDateAsString(val.getTimestamp()));
+
+			ExpandableListItem item = new ExpandableListItem();
+			item.setData(map);
+
+			item.setId_Mapping(mapping);
+
+			item.setTag(val.getAttack_id());
+
+			String groupID = this.getGroupValue(val);
+
+			ArrayList<ExpandableListItem> items = sectionData.get(groupID);
+			if (items == null) {
+				items = new ArrayList<ExpandableListItem>();
+				sectionData.put(groupID, items);
+				groupTitle.add(groupID);
+			}
+
+			items.add(item);
+		}
+
+		Collections.sort(groupTitle, new Comparator<String>() {
+			@Override
+			public int compare(String s1, String s2) {
+				return s1.compareToIgnoreCase(s2);
+			}
+		});
+
+		RecordListAdapter adapter = new RecordListAdapter(this.getApplicationContext(), groupTitle, sectionData);
+
+		mylist.setAdapter(adapter);
+	}
+
+	private void setSectionToOpen(String s) {
+		this.sectionToOpen = s;
+		if (this.sectionToOpen != null && this.sectionToOpen.length() != 0) {
+			if (this.getGroupTitle().contains(this.sectionToOpen)) {
+				int section = this.getGroupTitle().indexOf(this.sectionToOpen);
+				this.expListView.expandGroup(section);
+				this.sectionToOpen = "";
+			}
+		}
+	}
+
+	private Context getBaseContext() {
+		return this.getActivity().getBaseContext();
+	}
+
+	private Context getApplicationContext() {
+		return this.getActivity().getApplicationContext();
+	}
+
+	private void registerListClickCallback(ExpandableListView mylist) {
+		mylist.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
+			@Override
+			public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i2, long l) {
+				RecordListAdapter adapter = (RecordListAdapter) expandableListView.getExpandableListAdapter();
+
+				ExpandableListItem item = (ExpandableListItem) adapter.getChild(i, i2);
+
+				mListPosition = i;
+				mItemPosition = i2;
+				UglyDbHelper dbh = new UglyDbHelper(getBaseContext());
+				Record rec = dbh.getRecordOfAttackId((int) item.getTag());
+				RecordOverviewFragment.this.pushRecordDetailViewForRecord(rec);
+				return true;
+			}
+		});
+		mylist.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
+			@Override
+			public void onGroupExpand(int i) {
+				RecordOverviewFragment.this.openSections.add(new Integer(i));
+			}
+		});
+		mylist.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
+			@Override
+			public void onGroupCollapse(int i) {
+				RecordOverviewFragment.this.openSections.remove(new Integer(i));
+			}
+		});
+	}
+
+	/*****************************
+	 * 
+	 * Date Transform
+	 * 
+	 * ***************************/
+
+	@SuppressLint("SimpleDateFormat")
+	private String getDateAsString(long timeStamp) {
+
+		try {
+			DateFormat sdf = new SimpleDateFormat("H:mm d.M.yy");
+			Date netDate = (new Date(timeStamp));
+			return sdf.format(netDate);
+		} catch (Exception ex) {
+			return "xx";
+		}
+	}
+
+	/*****************************
+	 * 
+	 * Getter / Setter
+	 * 
+	 * ***************************/
+
+	public boolean isShowFilterButton() {
+		return showFilterButton;
+	}
+
+	public void setShowFilterButton(boolean showFilterButton) {
+		this.showFilterButton = showFilterButton;
+	}
+
+	/*****************************
+	 * 
+	 * Open Dialog Methods
+	 * 
+	 * ***************************/
+
+	private void openGroupingDialog() {
+		ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_TITLE_GROUP, this.groupingTitles(), this.selectedGroup(), false, this);
+		newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_GROUP);
+	}
+
+	private void openBSSIDFilterDialog() {
+		ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_TITLE_BSSID, this.bssids(), this.selectedBSSIDs(), true, this);
+		newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_BSSID);
+	}
+
+	private void openESSIDFilterDialog() {
+		ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_TITLE_ESSID, this.essids(), this.selectedESSIDs(), true, this);
+		newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_ESSID);
+	}
+
+	private void openProtocolsFilterDialog() {
+		ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_TITLE_PROTOCOLS, this.protocolTitles(), this.selectedProtocols(), true, this);
+		newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_PROTOCOLS);
+	}
+
+	private void openTimestampFromFilterDialog() {
+		this.wasBelowTimePicker = false;
+		DateTimeDialogFragment newFragment = new DateTimeDialogFragment(this.getActivity());
+		newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_SORTING);
+		if (this.filter.aboveTimestamp != Long.MIN_VALUE)
+			newFragment.setDate(this.filter.aboveTimestamp);
+	}
+
+	private void openTimestampToFilterDialog() {
+		this.wasBelowTimePicker = true;
+		DateTimeDialogFragment newFragment = new DateTimeDialogFragment(this.getActivity());
+		newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_SORTING);
+		if (this.filter.belowTimestamp != Long.MAX_VALUE)
+			newFragment.setDate(this.filter.belowTimestamp);
+	}
+
+	private void openSortingDialog() {
+		ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_TITLE_SORTING, this.sortTypeTiles(), this.selectedSorttype(), false, this);
+		newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_SORTING);
+	}
+
+	/*****************************
+	 * 
+	 * Grouping Stuff
+	 * 
+	 * ***************************/
+
+	public String getGroupValue(Record rec) {
+		int index = this.groupingTitles().indexOf(this.groupingKey);
+		switch (index) {
+		case 0:
+			return rec.getProtocol();
+		case 1:
+			return rec.getBssid();
+		case 2:
+			return rec.getSsid();
+		default:
+			return rec.getProtocol();
+		}
+	}
+
+	public ArrayList<String> getGroupTitle() {
+		int index = this.groupingTitles().indexOf(this.groupingKey);
+		switch (index) {
+		case 0:
+			return this.protocolTitles();
+		case 1:
+			return this.bssids();
+		case 2:
+			return this.essids();
+		default:
+			return this.protocolTitles();
+		}
+	}
+
+	/*****************************
+	 * 
+	 * Filter Stuff
+	 * 
+	 * ***************************/
+
+	private void openFilterPopupMenuOnView(View v) {
+
+		SimplePopupTable filterMenu = new SimplePopupTable(this.getActivity(), new AbstractPopup.OnPopupItemClickListener() {
+			public void onItemClick(Object ob) {
+				if (ob instanceof AbstractPopupItem) {
+					AbstractPopupItem item = (AbstractPopupItem) ob;
+					RecordOverviewFragment.this.onFilterMenuItemSelected(item);
+				}
+			}
+		});
+		filterMenu.setTitle(FILTER_MENU_POPUP_TITLE);
+		for (String title : RecordOverviewFragment.this.filterMenuTitles()) {
+			AbstractPopupItem item = null;
+			if (title.equals(FILTER_MENU_TITLE_TIMESTAMP_BELOW))
+				continue;
+			if (title.equals(FILTER_MENU_TITLE_TIMESTAMP_ABOVE)) {
+				item = new SplitPopupItem(this.getActivity());
+				item.setValue(SplitPopupItem.RIGHT_TITLE, FILTER_MENU_TITLE_TIMESTAMP_BELOW);
+				item.setValue(SplitPopupItem.LEFT_TITLE, FILTER_MENU_TITLE_TIMESTAMP_ABOVE);
+				if (this.filter.hasBelowTimestamp()) {
+					item.setValue(SplitPopupItem.RIGHT_SUBTITLE, this.getDateAsString(this.filter.belowTimestamp));
+				}
+				if (this.filter.hasAboveTimestamp()) {
+					item.setValue(SplitPopupItem.LEFT_SUBTITLE, this.getDateAsString(this.filter.aboveTimestamp));
+				}
+			} else {
+				item = new SimplePopupItem(this.getActivity());
+				item.setTitle(title);
+				((SimplePopupItem) item).setSelected(this.isFilterSetForTitle(title));
+			}
+
+			filterMenu.addItem(item);
+		}
+		filterMenu.showOnView(v);
+	}
+
+	private boolean isFilterSetForTitle(String title) {
+		if (title.equals(FILTER_MENU_TITLE_BSSID)) {
+			return this.filter.hasBSSIDs();
+		}
+		if (title.equals(FILTER_MENU_TITLE_ESSID)) {
+			return this.filter.hasESSIDs();
+		}
+		if (title.equals(FILTER_MENU_TITLE_PROTOCOLS)) {
+			return this.filter.hasProtocols();
+		}
+		if (title.equals(FILTER_MENU_TITLE_TIMESTAMP_BELOW)) {
+			return this.filter.hasBelowTimestamp();
+		}
+		if (title.equals(FILTER_MENU_TITLE_TIMESTAMP_ABOVE)) {
+			return this.filter.hasAboveTimestamp();
+		}
+		return false;
+	}
+
+	private void clearFilter() {
+		if (filter == null)
+			this.filter = new LogFilter();
+		this.filter.clear();
+	}
+
+	public ArrayList<String> groupingTitles(Context context) {
+		ArrayList<String> titles = new ArrayList<String>();
+		for (String groupTitle : context.getResources().getStringArray(R.array.Grouping)) {
+			titles.add(groupTitle);
+		}
+		return titles;
+	}
+
+	public ArrayList<String> groupingTitles() {
+		ArrayList<String> titles = new ArrayList<String>();
+		for (String groupTitle : this.getResources().getStringArray(R.array.Grouping)) {
+			titles.add(groupTitle);
+		}
+		return titles;
+	}
+
+	public boolean[] selectedGroup() {
+		ArrayList<String> groups = this.groupingTitles();
+		boolean[] selected = new boolean[groups.size()];
+		int i = 0;
+		for (String group : groups) {
+			selected[i] = (group.equals(this.groupingKey));
+			i++;
+		}
+		return selected;
+	}
+
+	public ArrayList<String> protocolTitles() {
+		ArrayList<String> titles = new ArrayList<String>();
+		for (String protocol : this.getResources().getStringArray(R.array.protocols)) {
+			titles.add(protocol);
+		}
+		return titles;
+	}
+
+	public boolean[] selectedProtocols() {
+		ArrayList<String> protocols = this.protocolTitles();
+		boolean[] selected = new boolean[protocols.size()];
+
+		int i = 0;
+		for (String protocol : protocols) {
+			selected[i] = (this.filter.protocols.contains(protocol));
+			i++;
+		}
+		return selected;
+	}
+
+	public ArrayList<String> sortTypeTiles() {
+		ArrayList<String> titles = new ArrayList<String>();
+		titles.add(MainActivity.getContext().getString(R.string.rec_time));
+		titles.add(MainActivity.getContext().getString(R.string.rec_protocol));
+		titles.add("BSSID");
+		titles.add("ESSID");
+		// titles.add("Remote Host Name");
+		// titles.add("Local Host Name");
+		// titles.add("Attack ID");
+		// titles.add("ID");
+		return titles;
+	}
+
+	public boolean[] selectedSorttype() {
+		ArrayList<String> types = this.sortTypeTiles();
+		boolean[] selected = new boolean[types.size()];
+		int i = 0;
+		for (String sorttype : types) {
+			selected[i] = (this.filter.sorttype.toString().equals(sorttype));
+			i++;
+		}
+		return selected;
+	}
+
+	public ArrayList<String> bssids() {
+		ArrayList<String> records = dbh.getUniqueBSSIDRecords();
+		return records;
+	}
+
+	public boolean[] selectedBSSIDs() {
+		ArrayList<String> bssids = this.bssids();
+		boolean[] selected = new boolean[bssids.size()];
+
+		int i = 0;
+		for (String bssid : bssids) {
+			selected[i] = (this.filter.BSSIDs.contains(bssid));
+			i++;
+		}
+		return selected;
+	}
+
+	public ArrayList<String> essids() {
+		ArrayList<String> records = dbh.getUniqueESSIDRecords();
+		return records;
+	}
+
+	public boolean[] selectedESSIDs() {
+		ArrayList<String> essids = this.essids();
+		boolean[] selected = new boolean[essids.size()];
+
+		int i = 0;
+		for (String essid : essids) {
+			selected[i] = (this.filter.ESSIDs.contains(essid));
+			i++;
+		}
+		return selected;
+	}
+
+	private ArrayList<String> filterMenuTitles() {
+		ArrayList<String> titles = new ArrayList<String>();
+		titles.add(FILTER_MENU_TITLE_BSSID);
+		titles.add(FILTER_MENU_TITLE_ESSID);
+		titles.add(FILTER_MENU_TITLE_PROTOCOLS);
+		titles.add(FILTER_MENU_TITLE_TIMESTAMP_ABOVE);
+		titles.add(FILTER_MENU_TITLE_TIMESTAMP_BELOW);
+		if (this.filter.isSet())
+			titles.add(FILTER_MENU_TITLE_REMOVE);
+		return titles;
+	}
+
+	/*****************************
+	 * 
+	 * Listener Actions
+	 * 
+	 * ***************************/
+
+	public void onDateTimePickerPositiveClick(DateTimeDialogFragment dialog) {
+		if (this.wasBelowTimePicker) {
+			this.filter.setBelowTimestamp(dialog.getDate());
+		} else {
+			this.filter.setAboveTimestamp(dialog.getDate());
+		}
+		this.populateListViewFromDB(this.expListView);
+	}
+
+	public void onDateTimePickerNegativeClick(DateTimeDialogFragment dialog) {
+		if (this.wasBelowTimePicker) {
+			this.filter.setBelowTimestamp(Long.MAX_VALUE);
+		} else {
+			this.filter.setAboveTimestamp(Long.MIN_VALUE);
+		}
+	}
+
+	public void onDialogPositiveClick(ChecklistDialog dialog) {
+		String title = dialog.getTitle();
+		if (title.equals(FILTER_MENU_TITLE_BSSID)) {
+			ArrayList<String> titles = dialog.getSelectedItemTitles();
+			if (titles.size() == this.bssids().size()) {
+				this.filter.setBSSIDs(new ArrayList<String>());
+			} else {
+				this.filter.setBSSIDs(titles);
+			}
+		}
+		if (title.equals(FILTER_MENU_TITLE_ESSID)) {
+			ArrayList<String> titles = dialog.getSelectedItemTitles();
+			if (titles.size() == this.essids().size()) {
+				this.filter.setESSIDs(new ArrayList<String>());
+			} else {
+				this.filter.setESSIDs(titles);
+			}
+		}
+		if (title.equals(FILTER_MENU_TITLE_PROTOCOLS)) {
+			ArrayList<String> protocols = dialog.getSelectedItemTitles();
+			if (protocols.size() == this.protocolTitles().size()) {
+				this.filter.setProtocols(new ArrayList<String>());
+			} else {
+				this.filter.setProtocols(dialog.getSelectedItemTitles());
+			}
+		}
+		if (title.equals(FILTER_MENU_TITLE_SORTING)) {
+			ArrayList<String> titles = dialog.getSelectedItemTitles();
+			if (titles.size() == 0)
+				return;
+			String t = titles.get(0);
+			int sortType = this.sortTypeTiles().indexOf(t);
+			this.filter.setSorttype(SortType.values()[sortType]);
+		}
+		if (title.equals(FILTER_MENU_TITLE_GROUP)) {
+			ArrayList<String> titles = dialog.getSelectedItemTitles();
+			if (titles.size() == 0)
+				return;
+			this.groupingKey = titles.get(0);
+		}
+		this.populateListViewFromDB(this.expListView);
+	}
+
+	public void onDialogNegativeClick(ChecklistDialog dialog) {
+
+	}
+
+	/*****************************
+	 * 
+	 * TEST
+	 * 
+	 * ***************************/
+
+	private void addRecordToDB() {
+		if ((dbh.getRecordCount() > 0))
+			return;
+
+		Calendar cal = Calendar.getInstance();
+
+		int maxProtocolsIndex = this.getResources().getStringArray(R.array.protocols).length;
+
+		Random random = new Random();
+
+		LatLng tudarmstadtLoc = new LatLng(49.86923, 8.6632768);
+
+		final int numSSIDs = 10;
+		final int numUniqueSSIDs = 6;
+		final double ssidRadius = 0.1;
+		final double bssidRadius = 0.004;
+		int id = 0; // global id
+		for (int ssid = 0; ssid < numSSIDs; ssid++) {
+			LatLng ssidLocation = new LatLng(tudarmstadtLoc.latitude - ssidRadius + 2.0 * ssidRadius * Math.random(), tudarmstadtLoc.longitude - ssidRadius
+					+ 2.0 * ssidRadius * Math.random());
+
+			String ssidName = "WiFi" + ((ssid % numUniqueSSIDs) + 1);
+
+			int numBSSIDs = (Math.abs(random.nextInt()) % 20) + 1;
+			for (int bssid = 0; bssid < numBSSIDs; bssid++) {
+				Record record = new Record();
+				record.setId(id);
+				record.setAttack_id(id);
+				record.setBssid("BSSID" + id);
+				id++;
+
+				record.setSsid(ssidName);
+				record.setTimestamp(cal.getTimeInMillis() + ((id * 60 * 60 * 60 * 24) * 1000));
+
+				int index = id % maxProtocolsIndex;
+				String protocolName = this.getResources().getStringArray(R.array.protocols)[index];
+
+				record.setProtocol(protocolName);
+
+				record.setLocalIP("127.0.0.1");
+				record.setType(MessageRecord.TYPE.SEND);
+
+				record.setLatitude(ssidLocation.latitude - bssidRadius + 2.0 * bssidRadius * Math.random());
+				record.setLongitude(ssidLocation.longitude - bssidRadius + 2.0 * bssidRadius * Math.random());
+
+				dbh.addRecord(record);
+			}
+		}
+
+		int countAllLogs = dbh.getAllRecords().size();
+		int countRecords = dbh.getRecordCount();
+		int countAttacks = dbh.getAttackCount();
+
+		if ((countRecords == 0)) {
+			Record rec = dbh.getRecordOfAttackId(0);
+			Record rec2 = dbh.getRecord(0);
+
+			System.out.println("" + "Could not create logs!");
+		}
+
+	}
+
+	/* Navigation */
+	private void pushRecordDetailViewForRecord(Record record) {
+
+		FragmentManager fm = this.getActivity().getFragmentManager();
+
+		if (fm != null) {
+			RecordDetailFragment newFragment = new RecordDetailFragment();
+			newFragment.setRecord(record);
+
+			newFragment.setUpNavigatible(true);
+
+			MainActivity.getInstance().injectFragment(newFragment);
+
+		}
+
+	}
+}