Browse Source

merged conflicts

Alexander Brakowski 9 years ago
parent
commit
cb543bc5ca
69 changed files with 2916 additions and 3095 deletions
  1. 2 2
      .gitignore
  2. 1 1
      AndroidManifest.xml
  3. 3 2
      phpsync/pull.php
  4. 1 1
      phpsync/push.php
  5. 7 0
      res/layout/activity_bluetooth.xml
  6. 21 21
      res/layout/date_time_dialog.xml
  7. 1 1
      res/layout/fragment_home.xml
  8. 1 1
      res/layout/fragment_profile_manager.xml
  9. 78 78
      res/layout/fragment_record_list.xml
  10. 47 47
      res/layout/record_list_item.xml
  11. 2 0
      res/values-de/strings.xml
  12. 1 1
      src/com/echo/holographlibrary/PieGraph.java
  13. 2 2
      src/de/tudarmstadt/informatik/hostage/Handler.java
  14. 29 3
      src/de/tudarmstadt/informatik/hostage/Hostage.java
  15. 1 1
      src/de/tudarmstadt/informatik/hostage/commons/HelperUtils.java
  16. 1 15
      src/de/tudarmstadt/informatik/hostage/logging/AttackRecord.java
  17. 2 3
      src/de/tudarmstadt/informatik/hostage/logging/LogExport.java
  18. 58 39
      src/de/tudarmstadt/informatik/hostage/logging/NetworkRecord.java
  19. 1 1
      src/de/tudarmstadt/informatik/hostage/model/Profile.java
  20. 1 1
      src/de/tudarmstadt/informatik/hostage/net/MyServerSocketFactory.java
  21. 17 2
      src/de/tudarmstadt/informatik/hostage/persistence/HostageDBOpenHelper.java
  22. 2 2
      src/de/tudarmstadt/informatik/hostage/persistence/ProfileManager.java
  23. 25 0
      src/de/tudarmstadt/informatik/hostage/protocol/SMB.java
  24. 279 288
      src/de/tudarmstadt/informatik/hostage/protocol/SSH.java
  25. 60 29
      src/de/tudarmstadt/informatik/hostage/sync/bluetooth/BluetoothSyncActivity.java
  26. 3 0
      src/de/tudarmstadt/informatik/hostage/sync/bluetooth/CommunicationThread.java
  27. 52 25
      src/de/tudarmstadt/informatik/hostage/sync/nfc/NFCSyncActivity.java
  28. 27 10
      src/de/tudarmstadt/informatik/hostage/sync/tracing/TracingSyncService.java
  29. 13 13
      src/de/tudarmstadt/informatik/hostage/ui/activity/MainActivity.java
  30. 2 2
      src/de/tudarmstadt/informatik/hostage/ui/activity/ProfileEditActivity.java
  31. 2 2
      src/de/tudarmstadt/informatik/hostage/ui/adapter/DrawerListAdapter.java
  32. 2 2
      src/de/tudarmstadt/informatik/hostage/ui/adapter/ExpandableListAdapter.java
  33. 4 4
      src/de/tudarmstadt/informatik/hostage/ui/adapter/ProfileManagerListAdapter.java
  34. 64 64
      src/de/tudarmstadt/informatik/hostage/ui/adapter/RecordListAdapter.java
  35. 3 3
      src/de/tudarmstadt/informatik/hostage/ui/adapter/ServicesListAdapter.java
  36. 2 2
      src/de/tudarmstadt/informatik/hostage/ui/adapter/StatisticListAdapter.java
  37. 199 199
      src/de/tudarmstadt/informatik/hostage/ui/dialog/ChecklistDialog.java
  38. 302 302
      src/de/tudarmstadt/informatik/hostage/ui/dialog/DateTimeDialogFragment.java
  39. 1 1
      src/de/tudarmstadt/informatik/hostage/ui/fragment/AboutFragment.java
  40. 3 3
      src/de/tudarmstadt/informatik/hostage/ui/fragment/ConnectionInfoDialogFragment.java
  41. 22 163
      src/de/tudarmstadt/informatik/hostage/ui/fragment/HomeFragment.java
  42. 1 1
      src/de/tudarmstadt/informatik/hostage/ui/fragment/PreferenceHostageFrament.java
  43. 4 1
      src/de/tudarmstadt/informatik/hostage/ui/fragment/ProfileEditFragment.java
  44. 5 5
      src/de/tudarmstadt/informatik/hostage/ui/fragment/ProfileManagerFragment.java
  45. 3 2
      src/de/tudarmstadt/informatik/hostage/ui/fragment/RecordDetailFragment.java
  46. 1438 1438
      src/de/tudarmstadt/informatik/hostage/ui/fragment/RecordOverviewFragment.java
  47. 4 4
      src/de/tudarmstadt/informatik/hostage/ui/fragment/ServicesFragment.java
  48. 5 238
      src/de/tudarmstadt/informatik/hostage/ui/fragment/SettingsFragment.java
  49. 13 13
      src/de/tudarmstadt/informatik/hostage/ui/fragment/StatisticsFragment.java
  50. 4 4
      src/de/tudarmstadt/informatik/hostage/ui/fragment/ThreatMapFragment.java
  51. 2 30
      src/de/tudarmstadt/informatik/hostage/ui/fragment/UpNavigatibleFragment.java
  52. 1 1
      src/de/tudarmstadt/informatik/hostage/ui/fragment/opengl/AnimatedMesh.java
  53. 1 1
      src/de/tudarmstadt/informatik/hostage/ui/fragment/opengl/HomeGLSurfaceView.java
  54. 1 1
      src/de/tudarmstadt/informatik/hostage/ui/fragment/opengl/Quaternion.java
  55. 1 1
      src/de/tudarmstadt/informatik/hostage/ui/fragment/opengl/ThreatIndicatorGLRenderer.java
  56. 1 1
      src/de/tudarmstadt/informatik/hostage/ui/helper/ColorSequenceGenerator.java
  57. 1 1
      src/de/tudarmstadt/informatik/hostage/ui/layouts/FlowLayout.java
  58. 1 1
      src/de/tudarmstadt/informatik/hostage/ui/model/DrawerListItem.java
  59. 1 1
      src/de/tudarmstadt/informatik/hostage/ui/model/ExpandableListItem.java
  60. 1 1
      src/de/tudarmstadt/informatik/hostage/ui/model/PlotComparisonItem.java
  61. 31 0
      src/de/tudarmstadt/informatik/hostage/ui/model/ProfileListItem.java
  62. 6 6
      src/de/tudarmstadt/informatik/hostage/ui/popup/AbstractPopup.java
  63. 2 2
      src/de/tudarmstadt/informatik/hostage/ui/popup/AbstractPopupItem.java
  64. 1 1
      src/de/tudarmstadt/informatik/hostage/ui/popup/SimplePopupItem.java
  65. 1 1
      src/de/tudarmstadt/informatik/hostage/ui/popup/SimplePopupTable.java
  66. 2 2
      src/de/tudarmstadt/informatik/hostage/ui/popup/SplitPopupItem.java
  67. 1 1
      src/de/tudarmstadt/informatik/hostage/ui/swipelist/SwipeListView.java
  68. 38 0
      src/de/tudarmstadt/informatik/hostage/ui/task/LoaderTask.java
  69. 2 1
      src/de/tudarmstadt/informatik/hostage/wrapper/Packet.java

+ 2 - 2
.gitignore

@@ -31,5 +31,5 @@ build/
 gen-external-apklibs/
 native/build
 native/build.o
-native/bind.o
-native/bind
+/javadoc.xml
+/doc

+ 1 - 1
AndroidManifest.xml

@@ -108,4 +108,4 @@
         </provider>
     </application>
 
-</manifest>
+</manifest>

+ 3 - 2
phpsync/pull.php

@@ -1,6 +1,5 @@
 <?php
 $bssid = $_POST ["bssid"];
-$timestamp = $_POST ["timestamp"];
 
 $username = "hostage";
 $password = "hostageDB";
@@ -8,7 +7,9 @@ $hostname = "localhost";
 
 $dbhandle = mysql_connect ( $hostname, $username, $password ) or die ( "Unable to connect to MySQL" );
 
-$result = mysql_query ( "SELECT * FROM `hostage`.`sync` WHERE `bssid` = " . $bssid . " AND `timestamp` > " . $timestamp );
+$query = "SELECT * FROM `hostage`.`sync` WHERE `bssid` = '" . $bssid . "'";
+
+$result = mysql_query ( $query );
 
 if (! $result) {
 	die ( 'Could not select record: ' . mysql_error () );

+ 1 - 1
phpsync/push.php

@@ -19,7 +19,7 @@ $hostname = "localhost";
 
 $dbhandle = mysql_connect ( $hostname, $username, $password ) or die ( "Unable to connect to MySQL" );
 
-$result = mysql_query ( "INSERT INTO `hostage`.`sync` (`bssid`, `ssid`, `longitude`, `latitude`, `timestamp`, `attacks`, `portscans`) VALUES " . $values );
+$result = mysql_query ( "INSERT INTO `hostage`.`sync` (`bssid`, `ssid`, `latitude`, `longitude`, `timestamp`, `attacks`, `portscans`) VALUES " . $values );
 
 if (! $result) {
 	die ( 'Could not insert record: ' . mysql_error () );

+ 7 - 0
res/layout/activity_bluetooth.xml

@@ -14,5 +14,12 @@
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         />
+    
+    <ListView
+        android:id="@+id/bluetoothListView"
+        android:visibility="gone"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        />
 
 </LinearLayout>

+ 21 - 21
res/layout/date_time_dialog.xml

@@ -1,22 +1,22 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    android:id="@+id/DateTimePicker"
-    android:layout_width="wrap_content"
-    android:layout_height="fill_parent"
-    android:gravity="center"
-    android:orientation="vertical"
-    android:padding="5dip" >
-
-    <DatePicker
-        android:id="@+id/DatePicker"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-         />
-
-    <TimePicker
-        android:id="@+id/TimePicker"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-         />
-
+<?xml version="1.0" encoding="utf-8"?>
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@+id/DateTimePicker"
+    android:layout_width="wrap_content"
+    android:layout_height="fill_parent"
+    android:gravity="center"
+    android:orientation="vertical"
+    android:padding="5dip" >
+
+    <DatePicker
+        android:id="@+id/DatePicker"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+         />
+
+    <TimePicker
+        android:id="@+id/TimePicker"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+         />
+
 </LinearLayout>

+ 1 - 1
res/layout/fragment_home.xml

@@ -11,7 +11,7 @@
         android:layout_height="match_parent"
         android:layout_weight="1" >
 
-        <de.tudarmstadt.informatik.hostage.ui2.fragment.opengl.HomeGLSurfaceView
+        <de.tudarmstadt.informatik.hostage.ui.fragment.opengl.HomeGLSurfaceView
             android:id="@+id/surfaceview"
             android:layout_width="match_parent"
             android:layout_height="match_parent" />

+ 1 - 1
res/layout/fragment_profile_manager.xml

@@ -7,7 +7,7 @@
     android:layout_height="fill_parent"
     android:id="@+id/profile_manager_root_view">
 
-    <de.tudarmstadt.informatik.hostage.ui2.swipelist.SwipeListView
+    <de.tudarmstadt.informatik.hostage.ui.swipelist.SwipeListView
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         xmlns:swipe="http://schemas.android.com/apk/res-auto"

+ 78 - 78
res/layout/fragment_record_list.xml

@@ -1,78 +1,78 @@
-<?xml version="1.0" encoding="utf-8"?>
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    android:layout_width="match_parent"
-    android:layout_height="match_parent"
-    android:background="@android:color/transparent"
-    >
-
-    <ProgressBar
-        android:id="@+id/progressBar1"
-        style="?android:attr/progressBarStyleLarge"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:layout_centerHorizontal="true"
-        android:layout_centerVertical="true"
-        android:visibility="gone"/>
-
-            <ExpandableListView
-                xmlns:android="http://schemas.android.com/apk/res/android"
-                android:id="@+id/loglistview"
-                android:layout_width="match_parent"
-                android:layout_height="match_parent"
-                android:layout_above="@+id/linearLayout"
-                android:layout_alignParentLeft="true"
-                android:layout_alignParentTop="true"
-                android:layout_marginLeft="0dp"
-                android:layout_marginTop="0dp"
-                android:background="@android:color/transparent"
-                android:choiceMode="singleChoice"
-                android:divider="@android:color/transparent"
-                android:dividerHeight="5dp"
-                android:padding="5dp"
-                android:headerDividersEnabled="false"
-                android:childDivider="@android:color/transparent">
-
-    </ExpandableListView>
-
-    <RelativeLayout
-        style="@android:style/Widget.Holo.Light.ActionBar.Solid.Inverse"
-        android:orientation="horizontal"
-        android:layout_width="fill_parent"
-        android:layout_height="wrap_content"
-        android:alpha="0.8"
-        android:id="@+id/linearLayout"
-        android:layout_alignParentBottom="true" android:layout_alignParentLeft="true"
-        android:layout_alignParentStart="true">
-
-        <ImageButton
-            style="@android:style/Widget.DeviceDefault.ActionButton.Overflow"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:id="@+id/SortButton"
-            android:src="@drawable/ic_sort_by_size"
-            android:layout_gravity="right"
-            android:layout_alignParentTop="true"
-            android:layout_alignParentRight="true"
-            android:layout_alignParentEnd="true"/>
-
-        <ImageButton
-            style="@android:style/Widget.DeviceDefault.ActionButton.Overflow"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:id="@+id/FilterButton"
-            android:src="@drawable/ic_filter"
-            android:layout_alignParentTop="true"
-            android:layout_toLeftOf="@+id/GroupButton"/>
-
-        <ImageButton
-            style="@android:style/Widget.DeviceDefault.ActionButton.Overflow"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:id="@+id/GroupButton"
-            android:src="@drawable/ic_device_access_storage"
-            android:layout_alignParentTop="true"
-            android:layout_toLeftOf="@+id/SortButton"/>
-    </RelativeLayout>
-
-
-</RelativeLayout>
+<?xml version="1.0" encoding="utf-8"?>
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:background="@android:color/transparent"
+    >
+
+    <ProgressBar
+        android:id="@+id/progressBar1"
+        style="?android:attr/progressBarStyleLarge"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_centerHorizontal="true"
+        android:layout_centerVertical="true"
+        android:visibility="gone"/>
+
+            <ExpandableListView
+                xmlns:android="http://schemas.android.com/apk/res/android"
+                android:id="@+id/loglistview"
+                android:layout_width="match_parent"
+                android:layout_height="match_parent"
+                android:layout_above="@+id/linearLayout"
+                android:layout_alignParentLeft="true"
+                android:layout_alignParentTop="true"
+                android:layout_marginLeft="0dp"
+                android:layout_marginTop="0dp"
+                android:background="@android:color/transparent"
+                android:choiceMode="singleChoice"
+                android:divider="@android:color/transparent"
+                android:dividerHeight="5dp"
+                android:padding="5dp"
+                android:headerDividersEnabled="false"
+                android:childDivider="@android:color/transparent">
+
+    </ExpandableListView>
+
+    <RelativeLayout
+        style="@android:style/Widget.Holo.Light.ActionBar.Solid.Inverse"
+        android:orientation="horizontal"
+        android:layout_width="fill_parent"
+        android:layout_height="wrap_content"
+        android:alpha="0.8"
+        android:id="@+id/linearLayout"
+        android:layout_alignParentBottom="true" android:layout_alignParentLeft="true"
+        android:layout_alignParentStart="true">
+
+        <ImageButton
+            style="@android:style/Widget.DeviceDefault.ActionButton.Overflow"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:id="@+id/SortButton"
+            android:src="@drawable/ic_sort_by_size"
+            android:layout_gravity="right"
+            android:layout_alignParentTop="true"
+            android:layout_alignParentRight="true"
+            android:layout_alignParentEnd="true"/>
+
+        <ImageButton
+            style="@android:style/Widget.DeviceDefault.ActionButton.Overflow"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:id="@+id/FilterButton"
+            android:src="@drawable/ic_filter"
+            android:layout_alignParentTop="true"
+            android:layout_toLeftOf="@+id/GroupButton"/>
+
+        <ImageButton
+            style="@android:style/Widget.DeviceDefault.ActionButton.Overflow"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:id="@+id/GroupButton"
+            android:src="@drawable/ic_device_access_storage"
+            android:layout_alignParentTop="true"
+            android:layout_toLeftOf="@+id/SortButton"/>
+    </RelativeLayout>
+
+
+</RelativeLayout>

+ 47 - 47
res/layout/record_list_item.xml

@@ -1,48 +1,48 @@
-<?xml version="1.0" encoding="utf-8"?>
-
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    android:layout_width="match_parent"
-    android:layout_height="match_parent"
-    android:padding="5dp"
-    android:baselineAligned="false"
-    android:background="@drawable/panel_bg">
-
-    <TextView
-        android:id="@+id/RecordTextFieldBSSID"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:layout_alignParentLeft="true"
-        android:layout_alignParentTop="true"
-        android:textAppearance="?android:attr/textAppearanceLarge"
-        android:textColor="#000000" />
-
-    <TextView
-        android:id="@+id/RecordTextFieldSSID"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:layout_alignLeft="@+id/RecordTextFieldBSSID"
-        android:layout_below="@+id/RecordTextFieldBSSID"
-        android:layout_marginTop="24dp"
-        android:textAppearance="?android:attr/textAppearanceSmall" />
-
-    <TextView
-        android:id="@+id/RecordTextFieldTimestamp"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:layout_alignBaseline="@+id/RecordTextFieldSSID"
-        android:layout_alignBottom="@+id/RecordTextFieldSSID"
-        android:layout_alignParentRight="true"
-        android:layout_marginRight="5dp"
-        android:textAppearance="?android:attr/textAppearanceSmall" />
-
-    <TextView
-        android:id="@+id/RecordTextFieldProtocol"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:layout_alignBaseline="@+id/RecordTextFieldBSSID"
-        android:layout_alignBottom="@+id/RecordTextFieldBSSID"
-        android:layout_alignRight="@+id/RecordTextFieldTimestamp"
-        android:textAppearance="?android:attr/textAppearanceMedium"
-        android:textColor="#000000" />
-
+<?xml version="1.0" encoding="utf-8"?>
+
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:padding="5dp"
+    android:baselineAligned="false"
+    android:background="@drawable/panel_bg">
+
+    <TextView
+        android:id="@+id/RecordTextFieldBSSID"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_alignParentLeft="true"
+        android:layout_alignParentTop="true"
+        android:textAppearance="?android:attr/textAppearanceLarge"
+        android:textColor="#000000" />
+
+    <TextView
+        android:id="@+id/RecordTextFieldSSID"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_alignLeft="@+id/RecordTextFieldBSSID"
+        android:layout_below="@+id/RecordTextFieldBSSID"
+        android:layout_marginTop="24dp"
+        android:textAppearance="?android:attr/textAppearanceSmall" />
+
+    <TextView
+        android:id="@+id/RecordTextFieldTimestamp"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_alignBaseline="@+id/RecordTextFieldSSID"
+        android:layout_alignBottom="@+id/RecordTextFieldSSID"
+        android:layout_alignParentRight="true"
+        android:layout_marginRight="5dp"
+        android:textAppearance="?android:attr/textAppearanceSmall" />
+
+    <TextView
+        android:id="@+id/RecordTextFieldProtocol"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_alignBaseline="@+id/RecordTextFieldBSSID"
+        android:layout_alignBottom="@+id/RecordTextFieldBSSID"
+        android:layout_alignRight="@+id/RecordTextFieldTimestamp"
+        android:textAppearance="?android:attr/textAppearanceMedium"
+        android:textColor="#000000" />
+
 </RelativeLayout>

+ 2 - 0
res/values-de/strings.xml

@@ -13,6 +13,8 @@
     <string name="not_connected">Nicht verbunden</string>
     <string name="attack">&#160;Angriff</string>
     <string name="attacks">&#160;Angriffe</string>
+	<string name="portscan">&#160;Portscan</string>
+    <string name="portscans">&#160;Portscans</string>
     <string name="secure">Sicher</string>
     <string name="insecure">Unsicher</string>
     <string name="logged">&#160;gelogged</string>

+ 1 - 1
src/com/echo/holographlibrary/PieGraph.java

@@ -41,7 +41,7 @@ import java.util.ArrayList;
 import java.util.Iterator;
 
 import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
+import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
 
 public class PieGraph extends View {
 

+ 2 - 2
src/de/tudarmstadt/informatik/hostage/Handler.java

@@ -202,7 +202,7 @@ public class Handler implements Runnable {
 		record.setProtocol(protocol.toString());
 		record.setExternalIP(externalIP);
 		record.setLocalIP(client.getLocalAddress().getHostAddress());
-		record.setLocalPort(protocol.getPort());
+		record.setLocalPort(client.getLocalPort());
 		record.setRemoteIP(client.getInetAddress().getHostAddress());
 		record.setRemotePort(client.getPort());
 		record.setBssid(BSSID);
@@ -265,7 +265,7 @@ public class Handler implements Runnable {
 		}
 		while (!thread.isInterrupted() && (inputLine = reader.read()) != null) {
 			outputLine = protocol.processMessage(inputLine);
-			Logger.log(Hostage.getContext(), createMessageRecord(TYPE.RECEIVE, inputLine.toString()));
+			log(TYPE.RECEIVE, inputLine.toString());
 			if (outputLine != null) {
 				writer.write(outputLine);
 				for (Packet o : outputLine) {

+ 29 - 3
src/de/tudarmstadt/informatik/hostage/Hostage.java

@@ -1,5 +1,18 @@
 package de.tudarmstadt.informatik.hostage;
 
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.impl.client.DefaultHttpClient;
+import org.apache.http.util.EntityUtils;
+import org.json.JSONObject;
+
 import android.app.NotificationManager;
 import android.app.PendingIntent;
 import android.app.Service;
@@ -38,7 +51,7 @@ import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
 import de.tudarmstadt.informatik.hostage.location.MyLocationManager;
 import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
 import de.tudarmstadt.informatik.hostage.protocol.Protocol;
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
+import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
 
 /**
  * Background service running as long as at least one protocol is active.
@@ -225,6 +238,16 @@ public class Hostage extends Service {
 		}
 		return false;
 	}
+	
+	public boolean isRunningAnyPort(String protocolName){
+		for(Listener listener: listeners){
+			if(listener.getProtocolName().equals(protocolName)){
+				if(listener.isRunning()) return true;
+			}
+		}
+
+		return false;
+	}
 
 	/**
 	 * Notifies the GUI about a event.
@@ -261,7 +284,7 @@ public class Hostage extends Service {
 		implementedProtocols = getImplementedProtocols();
 		connectionInfo = getSharedPreferences(getString(R.string.connection_info), Context.MODE_PRIVATE);
 		connectionInfoEditor = connectionInfo.edit();
-
+		
 		mProtocolActiveAttacks = new HashMap<String, Boolean>();
 
 		createNotification();
@@ -374,6 +397,7 @@ public class Hostage extends Service {
 		// Toast.makeText(getApplicationContext(), protocolName +
 		// " SERVICE STOPPED!", Toast.LENGTH_SHORT).show();
 	}
+	
 
 	public void stopListenerAllPorts(String protocolName){
 		for(Listener listener: listeners){
@@ -578,6 +602,7 @@ public class Hostage extends Service {
 	private void unregisterNetReceiver() {
 		unregisterReceiver(netReceiver);
 	}
+	
 
 	public boolean hasProtocolActiveAttacks(String protocol){
 		if(!mProtocolActiveAttacks.containsKey(protocol)) return false;
@@ -591,6 +616,7 @@ public class Hostage extends Service {
 
 		return false;
 	}
+
 	/**
 	 * Updates the connection info and saves them in the the SharedPreferences
 	 * for session data.
@@ -609,7 +635,7 @@ public class Hostage extends Service {
 		SetExternalIPTask async = new SetExternalIPTask();
 		async.execute(new String[] { "http://ip2country.sourceforge.net/ip2c.php?format=JSON" });
 
-		this.mProtocolActiveAttacks.clear();
+		this.mProtocolActiveAttacks.clear();		
 	}
 
 }

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

@@ -396,8 +396,8 @@ public final class HelperUtils {
 	}
 	
 	public static boolean isNetworkAvailable(Context context) {
+		if(context == null) return false;
 
-        if(context == null) return false;
 		ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
 		NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
 		return activeNetworkInfo != null && activeNetworkInfo.isConnected();

+ 1 - 15
src/de/tudarmstadt/informatik/hostage/logging/AttackRecord.java

@@ -183,19 +183,5 @@ public class AttackRecord implements Parcelable, Serializable {
 	 */
 	public void setExternalIP(String externalIP) {
 		this.externalIP = externalIP;
-	}
-
-	// TEMP ZU TEST
-	@Override
-	public String toString() {
-		return String
-				.format("{ \"sensor\":{\"type\": \"Honeypot\", \"name\": \"HosTaGe\"}, \"type\": \"%s server access\", \"src\":{\"ip\": \"%s\", \"port\": %d}, \"dst\":{\"ip\": \"%s\", \"port\": %d} }",
-						getProtocol(), getRemoteIP(), getRemotePort(), getExternalIP(), getLocalPort());
-	}
-
-	public String toJSON() {
-		return String.format("{\"bssid\":\"%s\",\"ssid\":\"%s\",\"latitude\":%d,\"longitude\":%d,\"timestamp\":%d,\"attacks\":%d,\"portscans\":%d}", "bssid",
-				"ssid", 23, 32, 123456, 22, 2);
-	}
-
+	}	
 }

+ 2 - 3
src/de/tudarmstadt/informatik/hostage/logging/LogExport.java

@@ -33,7 +33,6 @@ public class LogExport extends IntentService{
 	
 	public LogExport() {
 		super(LogExport.class.getName());
-		mMainThreadHandler = new Handler();
 	}
 	
 	@Override
@@ -41,6 +40,7 @@ public class LogExport extends IntentService{
 		super.onCreate();
 		pref = PreferenceManager.getDefaultSharedPreferences(this);
 		dbh = new HostageDBOpenHelper(this);
+		mMainThreadHandler = new Handler();
 	}
 	
 	/**
@@ -58,8 +58,7 @@ public class LogExport extends IntentService{
 				Formatter formatter = (format == 1 ? TraCINgFormatter.getInstance() : null);
 				exportDatabase(formatter);
 			}
-
-		}	
+		}
 	}
 	
 	/**

+ 58 - 39
src/de/tudarmstadt/informatik/hostage/logging/NetworkRecord.java

@@ -8,8 +8,8 @@ import android.os.Parcelable;
 /**
  * Holds all necessary information about a single network.
  */
-public class NetworkRecord implements Parcelable, Serializable{	
-	
+public class NetworkRecord implements Parcelable, Serializable {
+
 	private static final long serialVersionUID = -1586629159904177836L;
 
 	private String bssid;
@@ -18,122 +18,141 @@ public class NetworkRecord implements Parcelable, Serializable{
 	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 static final Parcelable.Creator<NetworkRecord> CREATOR = new Parcelable.Creator<NetworkRecord>() {
+		@Override
+		public NetworkRecord createFromParcel(Parcel source) {
+			return new NetworkRecord(source);
+		}
 
-    public NetworkRecord() {
+		@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();
-    }
+	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);
+		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
+	 * @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
+	 * @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
+	 * @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
+	 * @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
+	 * @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
+	 * @param accuracy
+	 *            the accuracy to set
 	 */
 	public void setAccuracy(float accuracy) {
 		this.accuracy = accuracy;
 	}
 
+	public String toJSON() {
+		return String.format("{\"bssid\":\"%s\",\"ssid\":%s,\"latitude\":%s,\"longitude\":%s,\"timestamp\":%s,\"attacks\":%d,\"portscans\":%d}", bssid, ssid,
+				latitude, longitude, timestampLocation, -1, -1);
+	}
+
 }

+ 1 - 1
src/de/tudarmstadt/informatik/hostage/model/Profile.java

@@ -20,7 +20,7 @@ import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
 
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
+import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
 
 /**
  * @author Alexander Brakowski

+ 1 - 1
src/de/tudarmstadt/informatik/hostage/net/MyServerSocketFactory.java

@@ -13,7 +13,7 @@ import javax.net.ServerSocketFactory;
 import de.tudarmstadt.informatik.hostage.system.Device;
 import de.tudarmstadt.informatik.hostage.system.PrivilegedPort;
 import de.tudarmstadt.informatik.hostage.system.PrivilegedPort.TYPE;
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
+import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
 
 public class MyServerSocketFactory extends ServerSocketFactory {
 

+ 17 - 2
src/de/tudarmstadt/informatik/hostage/persistence/HostageDBOpenHelper.java

@@ -666,7 +666,7 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 	 * @param networkInformation ArrayList of {@link NetworkRecord NetworkRecords}
 	 * @see  {@link HostageDBOpenHelper#updateNetworkInformation(NetworkRecord record)}
 	 */
-	public void updateNetworkInformation(ArrayList<NetworkRecord> networkInformation) {;
+	public void updateNetworkInformation(ArrayList<NetworkRecord> networkInformation) {
 		for (NetworkRecord record : networkInformation) {
 			updateNetworkInformation(record);
 		}
@@ -775,6 +775,8 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 		return syncInfo;
 	}	
 	
+	
+	
 	/**
 	 * Updates the sync_info table with the information contained in the parameter.
 	 * @param networkInformation ArrayList of {@link SyncInfoRecord SyncInfoRecords}
@@ -850,7 +852,20 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 		db.execSQL(deleteQuery);
 		db.close();
 	}
-
+	
+	/**
+	 * Deletes all records from {@link #TABLE_RECORDS} with a specific Attack ID.
+	 *
+	 * @param attackID
+	 *            The Attack ID to match against.
+	 */
+	public synchronized void deleteByAttackID(long attackID) {
+		SQLiteDatabase db = this.getReadableDatabase();
+		db.delete(AttackEntry.TABLE_NAME, AttackEntry.COLUMN_NAME_ATTACK_ID + " = ?", new String[] { String.valueOf(attackID) });
+		db.delete(PacketEntry.TABLE_NAME, PacketEntry.COLUMN_NAME_ATTACK_ID + " = ?", new String[] { String.valueOf(attackID) });
+		db.close();
+	}
+	
 	/**
 	 * Deletes all records from {@link #TABLE_RECORDS} with a specific Attack ID.
 	 *

+ 2 - 2
src/de/tudarmstadt/informatik/hostage/persistence/ProfileManager.java

@@ -32,8 +32,8 @@ import de.tudarmstadt.informatik.hostage.Hostage;
 import de.tudarmstadt.informatik.hostage.Listener;
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.model.Profile;
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
-import de.tudarmstadt.informatik.hostage.ui2.adapter.ProfileManagerListAdapter;
+import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
+import de.tudarmstadt.informatik.hostage.ui.adapter.ProfileManagerListAdapter;
 
 /**
  * The profile manager is responsible for persisting and deleting profiles

+ 25 - 0
src/de/tudarmstadt/informatik/hostage/protocol/SMB.java

@@ -4,6 +4,9 @@ import java.security.SecureRandom;
 import java.util.ArrayList;
 import java.util.List;
 
+import android.content.SharedPreferences;
+import android.preference.PreferenceManager;
+
 import de.tudarmstadt.informatik.hostage.Hostage;
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
@@ -98,6 +101,15 @@ public class SMB implements Protocol {
 			.getRandomString(16, true).getBytes());
 	private static String workgroup;
 	private SMBPacket smbPacket = new SMBPacket(serverVersion, new String(serverName), workgroup);
+	private int maxEchoPackets = initMaxPackets();
+	private int receivedEchoPackets = 0;
+	
+	private int initMaxPackets() {
+		int maxPackets;
+		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Hostage.getContext());
+		maxPackets = prefs.getInt("timeout", 30) / 5;
+		return maxPackets;
+	}
 
 	@Override
 	public int getPort() {
@@ -123,6 +135,19 @@ public class SMB implements Protocol {
 		byte[] response;
 		List<Packet> responsePackets = new ArrayList<Packet>();
 
+		if (smbCommand == SMB_COM_ECHO) {
+			receivedEchoPackets++;
+		} else {
+			receivedEchoPackets = 0;
+		}
+		
+		if (receivedEchoPackets == maxEchoPackets) {
+			state = STATE.CLOSED;
+			response = smbPacket.getTreeDisc();
+			responsePackets.add(new Packet(response, toString()));
+			return responsePackets;
+		}
+		
 		switch (state) {
 			case NONE:
 				if (smbCommand == SMB_COM_NEGOTIATE) {

+ 279 - 288
src/de/tudarmstadt/informatik/hostage/protocol/SSH.java

@@ -37,36 +37,10 @@ public class SSH implements Protocol {
 		NONE, SERVER_VERSION, CLIENT_VERSION, KEX_INIT, NEW_KEYS, USERAUTH, CONNECTION, CHANNEL, TERMINAL_CMD, TERMINAL_ENTER, CLOSED
 	}
 
-	/**
-	 * Converts a byte[] to int
-	 * 
-	 * @param bytes
-	 *            that are converted
-	 * @return converted byte[] as int
-	 */
-	private int byteToInt(byte[] bytes) {
-		int convertedInteger = 0;
-		for (int i = 0; i < bytes.length; i++) {
-			convertedInteger <<= 8;
-			convertedInteger |= bytes[i] & 0xFF;
-		}
-		return convertedInteger;
-	}
-
-	private String initSshType() {
-		SecureRandom rnd = new SecureRandom();
-		int majorVersion = rnd.nextInt(possibleSshTypes.length);
-		return "OpenSSH_"
-				+ possibleSshTypes[majorVersion][0][0]
-				+ possibleSshTypes[majorVersion][1][rnd
-						.nextInt(possibleSshTypes[majorVersion][1].length)];
-	}
-
 	/**
 	 * Denotes in which state the protocol is right now.
 	 */
 	private STATE state = STATE.NONE;
-
 	private boolean useEncryption = false;
 
 	// version stuff
@@ -76,70 +50,60 @@ public class SSH implements Protocol {
 			{ { "5." }, { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" } },
 			{ { "6." }, { "0", "1", "2", "3", "4" } } };
 
-	// server infos
-	private String serverVersion = "SSH-2.0-";
+	private String initSshType() {
+		SecureRandom rnd = new SecureRandom();
+		int majorVersion = rnd.nextInt(possibleSshTypes.length);
+		return "OpenSSH_"
+				+ possibleSshTypes[majorVersion][0][0]
+				+ possibleSshTypes[majorVersion][1][rnd
+						.nextInt(possibleSshTypes[majorVersion][1].length)];
+	}
 
+	// server infos
+	private static final String serverVersion = "SSH-2.0-";
 	private String serverType = initSshType();
-
 	private String serverName = HelperUtils.getRandomString(16, false);
-
 	private int packetNumber = 0;
-
 	private int recipientChannel;
-
 	private String userName;
-
 	private String terminalPrefix;
-
 	private StringBuffer command = new StringBuffer();
-
 	private SecureRandom random = new SecureRandom();
 
 	// SSH Parameters for Kex etc.
 	private byte[] V_S = (serverVersion + serverType).getBytes();
-
 	private byte[] V_C;
-
 	private byte[] I_S;
-
 	private byte[] I_C;
-
 	private byte[] e;
-
 	private BigInteger f;
-
 	private byte[] h;
-
 	private BigInteger k;
-
 	private byte[] K_S;
-
 	private byte[] signature;
 
 	// allowed algorithms for kexinit
 	private static final String KEX_ALG = "diffie-hellman-group1-sha1";
-
 	private static final String SERVER_ALG = "ssh-dss";
-
 	private static final String ENCRYPT_ALG_C = "3des-cbc";
-
 	private static final String ENCRYPT_ALG_S = "3des-cbc";
-
 	private static final String MAC_ALG_C = "hmac-sha1";
 	private static final String MAC_ALG_S = "hmac-sha1";
 	private static final String COMP_ALG_C = "none";
 	private static final String COMP_ALG_S = "none";
+
 	private int cipherBlockSize = 16;
+
 	// for en- and decryption
 	private DESede desEncryption;
 	private DESede desDecryption;
 	private CBCMode cbcEncryption;
 	private CBCMode cbcDecryption;
-
 	private MAC macEncryption;
 	// private MAC macDec;
+
 	// dsa private key
-	private final char[] dsaPem = ("-----BEGIN DSA PRIVATE KEY-----\n"
+	private static final char[] dsaPem = ("-----BEGIN DSA PRIVATE KEY-----\n"
 			+ "MIIBugIBAAKBgQCDZ9R2vfCPwjv5vKF1igIv9drrZ7G0dhMkGT9AZTjgI34Qm4w0\n"
 			+ "0iWeCqO7SmqiaMIjbRIm91MeDed4ObAq4sAkqRE/2P4mTbzFx5KhEczRRiDoqQBX\n"
 			+ "xYa0yWKJpeZ94SGM6DEPuBTxKo0T4uMjbq2FzHL2FXT1/WoNCmRU6gFSiwIVAMK4\n"
@@ -158,13 +122,8 @@ public class SSH implements Protocol {
 	}
 
 	@Override
-	public boolean isClosed() {
-		return (state == STATE.CLOSED);
-	}
-
-	@Override
-	public boolean isSecure() {
-		return false;
+	public TALK_FIRST whoTalksFirst() {
+		return TALK_FIRST.CLIENT;
 	}
 
 	@Override
@@ -179,12 +138,12 @@ public class SSH implements Protocol {
 		}
 		switch (state) {
 		case NONE:
-			responsePackets
-					.add(new Packet(serverVersion + serverType + "\r\n", toString()));
+			extractType(request);
+			responsePackets.add(new Packet(serverVersion + serverType + "\r\n",
+					toString()));
 			state = STATE.SERVER_VERSION;
 			break;
 		case SERVER_VERSION:
-			extractType(request);
 			extractPayload(request);
 			responsePackets.add(kexInit());
 			state = STATE.CLIENT_VERSION;
@@ -230,87 +189,84 @@ public class SSH implements Protocol {
 	}
 
 	@Override
-	public String toString() {
-		return "SSH";
+	public boolean isClosed() {
+		return (state == STATE.CLOSED);
 	}
 
 	@Override
-	public TALK_FIRST whoTalksFirst() {
-		return TALK_FIRST.SERVER;
+	public boolean isSecure() {
+		return false;
+	}
+
+	@Override
+	public String toString() {
+		return "SSH";
 	}
 
 	/**
-	 * Channel Open Reply.
+	 * Wraps the packets with packet length and padding.
 	 * 
-	 * @param request
-	 *            from client.
-	 * @return Channel Open Reply.
+	 * @param response
+	 *            content that is wrapped.
+	 * @return wrapped packet.
 	 */
-	private Packet channelOpenReply(byte[] request) {
-		if (!(HelperUtils.byteToStr(request).contains("session"))) {
-			return disconnectReply(2); // if contains "session" ok else disc
-		}
-		TypesReader tr = new TypesReader(request, 6);
-		TypesWriter tw = new TypesWriter();
-		try {
-			tr.readString();
-			recipientChannel = tr.readUINT32();
-			int senderChannel = recipientChannel;
-			int initialWindowSize = tr.readUINT32();
-			int maximumPacketSize = tr.readUINT32();
+	private Packet wrapPacket(byte[] response) {
+		// 4 byte packet length, 1 byte padding length, payload length
+		int packetLength = 5 + response.length;
+		int paddingLengthCBS = cipherBlockSize
+				- (packetLength % cipherBlockSize);
+		int paddingLength8 = 8 - (packetLength % 8);
+		int paddingLength = paddingLengthCBS > paddingLength8 ? paddingLengthCBS
+				: paddingLength8;
+		if (paddingLength < 4)
+			paddingLength += cipherBlockSize;
+		// add padding string length to packet length
+		packetLength = packetLength + paddingLength - 4;
 
-			tw.writeByte(0x5b); // msgcode
-			tw.writeUINT32(recipientChannel);
-			tw.writeUINT32(senderChannel);
-			tw.writeUINT32(initialWindowSize);
-			tw.writeUINT32(maximumPacketSize);
-		} catch (IOException e) {
-			e.printStackTrace();
+		byte[] packetLen = ByteBuffer.allocate(4).putInt(packetLength).array();
+		byte[] paddingLen = { (byte) paddingLength };
+		byte[] paddingString = HelperUtils.randomBytes(paddingLength);
+		byte[] wrappedResponse = HelperUtils.concat(packetLen, paddingLen,
+				response, paddingString);
+		if (useEncryption) {
+			byte[] mac = createMac(wrappedResponse);
+			byte[] responseEnc = encryptBytes(wrappedResponse);
+			wrappedResponse = HelperUtils.concat(responseEnc, mac);
 		}
+		packetNumber++;
 
-		return wrapPacket(tw.getBytes());
+		return new Packet(wrappedResponse, toString());
 	}
 
 	/**
-	 * Channel Success Reply.
+	 * Encrypts a request with triple DES.
 	 * 
 	 * @param request
-	 *            from client.
-	 * @return Channel Success Reply.
+	 *            that is encrypted.
+	 * @return encrypted request.
 	 */
-	private Packet channelSuccessReply(byte[] request) {
-		if (!(HelperUtils.byteToStr(request)).contains("pty-req")) {
-			return disconnectReply(2);
+	private byte[] encryptBytes(byte[] bytes) {
+		byte[] responseEncrypted = new byte[bytes.length];
+		for (int i = 0; i < bytes.length; i += 8) {
+			cbcEncryption.transformBlock(bytes, i, responseEncrypted, i);
 		}
-		TypesWriter tw = new TypesWriter();
-		tw.writeByte(0x63); // msgcode
-		tw.writeUINT32(recipientChannel);
-
-		return wrapPacket(tw.getBytes());
+		return responseEncrypted;
 	}
 
 	/**
-	 * Userauth ssh-connection reply.
+	 * Decrypts a request with triple DES.
 	 * 
 	 * @param request
-	 *            from the client.
-	 * @return ssh-connection reply.
+	 *            that is decrypted.
+	 * @return decrypted request.
 	 */
-	private Packet connectionReply(byte[] request) {
-		if (request[5] != 0x32
-				&& !(HelperUtils.byteToStr(request).contains("ssh-connection"))) {
-			return disconnectReply(14);// disconnect because its not
-										// servicerequest ssh-connect
-		}
-		try {
-			TypesReader tr = new TypesReader(request, 6);
-			userName = tr.readString();
-			terminalPrefix = "[" + userName + "@" + serverName + " ~]$ ";
-		} catch (IOException e) {
-			e.printStackTrace();
+	private byte[] decryptBytes(byte[] request) {
+		byte[] decryptedRequest = new byte[request.length
+				- ((request.length % 8 == 0) ? 0 : 20)];
+		for (int i = 0; i < decryptedRequest.length; i += 8) {
+			cbcDecryption.transformBlock(request, i, decryptedRequest, i);
 		}
-		byte[] msgcode = { 0x34 };
-		return wrapPacket(msgcode);
+		return decryptedRequest;
 	}
 
 	/**
@@ -329,19 +285,36 @@ public class SSH implements Protocol {
 	}
 
 	/**
-	 * Decrypts a request with triple DES.
+	 * Builds the Kex Init packet that contains all the allowed algorithms by
+	 * the server.
 	 * 
-	 * @param request
-	 *            that is decrypted.
-	 * @return decrypted request.
+	 * @return Kex Init packet.
 	 */
-	private byte[] decryptBytes(byte[] request) {
-		byte[] decryptedRequest = new byte[request.length
-				- ((request.length % 8 == 0) ? 0 : 20)];
-		for (int i = 0; i < decryptedRequest.length; i += 8) { // -12 wegen MAC
-			cbcDecryption.transformBlock(request, i, decryptedRequest, i);
-		}
-		return decryptedRequest;
+	private Packet kexInit() {
+		TypesWriter tw = new TypesWriter();
+		tw.writeByte(0x14);
+		// cookie
+		tw.writeBytes(HelperUtils.randomBytes(16));
+		tw.writeString(KEX_ALG);
+		tw.writeString(SERVER_ALG);
+		tw.writeString(ENCRYPT_ALG_C);
+		tw.writeString(ENCRYPT_ALG_S);
+		tw.writeString(MAC_ALG_C);
+		tw.writeString(MAC_ALG_S);
+		tw.writeString(COMP_ALG_C);
+		tw.writeString(COMP_ALG_S);
+		// language client to server
+		tw.writeBytes(new byte[] { 0x00, 0x00, 0x00, 0x00 });
+		// language server to client
+		tw.writeBytes(new byte[] { 0x00, 0x00, 0x00, 0x00 });
+		// no guess from server
+		tw.writeByte(0x00);
+		// reserved
+		tw.writeBytes(new byte[] { 0x00, 0x00, 0x00, 0x00 });
+		byte[] response = tw.getBytes();
+		I_S = response;
+
+		return wrapPacket(response);
 	}
 
 	/**
@@ -371,9 +344,10 @@ public class SSH implements Protocol {
 			response = tw.getBytes();
 
 			// init for decryption and encryption
+			// KeyMaterial: alg, h, k, keylength, blocklength, maclength,
+			// keylength, blocklength, maclength
 			KeyMaterial km = KeyMaterial.create("SHA1", h, k, h, 24, 8, 20, 24,
-					8, 20); // alg, h, k, keylength, blocklength, maclength,
-							// keylength, blocklength, maclength
+					8, 20);
 			desEncryption = new DESede();
 			desDecryption = new DESede();
 			desEncryption.init(true, km.enc_key_server_to_client);
@@ -392,171 +366,116 @@ public class SSH implements Protocol {
 	}
 
 	/**
-	 * Disconnect Reply using the given number as reason code.
-	 * 
-	 * @param reasonCode
-	 *            for disconnect reply. Must be between 1 and 15, default is 2.
-	 * @return Disconnect Reply.
-	 */
-	private Packet disconnectReply(int reasonCode) {
-		TypesWriter tw = new TypesWriter();
-		tw.writeByte(0x01);
-		switch (reasonCode) {
-		case 1:
-			tw.writeUINT32(1);
-			tw.writeString("SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT");
-			break;
-		case 7:
-			tw.writeUINT32(7);
-			tw.writeString("SSH_DISCONNECT_SERVICE_NOT_AVAILABLE");
-			break;
-		case 14:
-			tw.writeUINT32(14);
-			tw.writeString("SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE");
-			break;
-		default:
-			tw.writeUINT32(2);
-			tw.writeString("SSH_DISCONNECT_PROTOCOL_ERROR");
-			break;
-		}
-		return wrapPacket(tw.getBytes());
-	}
-
-	/**
-	 * Encrypts a request with triple DES.
+	 * New Keys response.
 	 * 
-	 * @param request
-	 *            that is encrypted.
-	 * @return encrypted request.
+	 * @return New Keys response.
 	 */
-	private byte[] encryptBytes(byte[] bytes) {
-		byte[] responseEncrypted = new byte[bytes.length];
-		for (int i = 0; i < bytes.length; i += 8) {
-			cbcEncryption.transformBlock(bytes, i, responseEncrypted, i);
-		}
-		return responseEncrypted;
+	private Packet newKeys() {
+		byte[] msgCode = { 0x15 };
+		return wrapPacket(msgCode);
 	}
 
 	/**
-	 * Extracts the payload of a packet and writes it in I_C.
+	 * Service ssh-userauth reply.
 	 * 
 	 * @param request
-	 *            packet of which the payload is extracted.
+	 *            from the client.
+	 * @return Service reply.
 	 */
-	private void extractPayload(byte[] request) {
-		int position = 0;
-		if (request[5] != 0x14) {
-			position = 1;
-			for (int i = 0; i < request.length; i++, position++) {
-				if (request[i] == 0x0a)
-					break;
-			}
+	private Packet serviceReply(byte[] request) {
+		byte[] message;
+		// if newkeys request is included in the same packet remove it
+		if (request[5] == 0x15) {
+			message = new byte[request.length - 16];
+			System.arraycopy(request, 16, message, 0, request.length - 16);
+		} else {
+			message = request;
 		}
-		int packetLength = byteToInt(new byte[] { request[position],
-				request[1 + position], request[2 + position],
-				request[3 + position] });
-		int paddingLength = byteToInt(new byte[] { request[4 + position] });
-		byte[] payload = new byte[packetLength - paddingLength - 1];
-		for (int i = 5; i < packetLength - paddingLength - 1; i++) {
-			payload[i - 5] = request[i + position];
+		if (message[5] != 0x05
+				&& !(HelperUtils.byteToStr(message).contains("ssh-userauth"))) {
+			// disconnect because its not servicerequest ssh-userauth
+			return disconnectReply(7);
 		}
-		I_C = payload;
+		TypesWriter tw = new TypesWriter();
+		tw.writeByte(0x06);
+		tw.writeString("ssh-userauth");
+		return wrapPacket(tw.getBytes());
 	}
 
 	/**
-	 * Extracts the public key from the DH Kex Request
+	 * Userauth ssh-connection reply.
 	 * 
 	 * @param request
-	 *            containing the clients public key
+	 *            from the client.
+	 * @return ssh-connection reply.
 	 */
-	private void extractPubKey(byte[] request) {
-		e = new byte[byteToInt(new byte[] { request[6], request[7], request[8],
-				request[9] })];
-		for (int i = 0; i < e.length; i++) {
-			e[i] = request[i + 10];
+	private Packet connectionReply(byte[] request) {
+		if (request[5] != 0x32
+				&& !(HelperUtils.byteToStr(request).contains("ssh-connection"))) {
+			// disconnect because its not servicerequest ssh-connect
+			return disconnectReply(14);
+		}
+		try {
+			TypesReader tr = new TypesReader(request, 6);
+			userName = tr.readString();
+			terminalPrefix = "[" + userName + "@" + serverName + " ~]$ ";
+		} catch (IOException e) {
+			e.printStackTrace();
 		}
+		byte[] msgcode = { 0x34 };
+		return wrapPacket(msgcode);
 	}
 
 	/**
-	 * Extracts the type of the client
+	 * Channel Open Reply.
 	 * 
 	 * @param request
-	 *            containing the clients type
+	 *            from client.
+	 * @return Channel Open Reply.
 	 */
-	private void extractType(byte[] request) {
-		int length = 0;
-		for (int i = 0; i < request.length; i++, length++) {
-			if (request[i] == 0x0d)
-				break; // find the end of the type: '\r'
+	private Packet channelOpenReply(byte[] request) {
+		if (!(HelperUtils.byteToStr(request).contains("session"))) {
+			// if contains "session" ok else disc
+			return disconnectReply(2);
 		}
-		V_C = new byte[length];
-		System.arraycopy(request, 0, V_C, 0, length);
-	}
-
-	/**
-	 * Builds the Kex Init packet that contains all the allowed algorithms by
-	 * the server.
-	 * 
-	 * @return Kex Init packet.
-	 */
-	private Packet kexInit() {
+		TypesReader tr = new TypesReader(request, 6);
 		TypesWriter tw = new TypesWriter();
-		tw.writeByte(0x14);
-		tw.writeBytes(HelperUtils.randomBytes(16)); // cookie
-		tw.writeString(KEX_ALG);
-		tw.writeString(SERVER_ALG);
-		tw.writeString(ENCRYPT_ALG_C);
-		tw.writeString(ENCRYPT_ALG_S);
-		tw.writeString(MAC_ALG_C);
-		tw.writeString(MAC_ALG_S);
-		tw.writeString(COMP_ALG_C);
-		tw.writeString(COMP_ALG_S);
-		tw.writeBytes(new byte[] { 0x00, 0x00, 0x00, 0x00 }); // language client
-																// to server
-		tw.writeBytes(new byte[] { 0x00, 0x00, 0x00, 0x00 }); // language server
-																// to client
-		tw.writeByte(0x00); // no guess from server
-		tw.writeBytes(new byte[] { 0x00, 0x00, 0x00, 0x00 }); // reserved
-		byte[] response = tw.getBytes();
-		I_S = response;
+		try {
+			tr.readString();
+			recipientChannel = tr.readUINT32();
+			int senderChannel = recipientChannel;
+			int initialWindowSize = tr.readUINT32();
+			int maximumPacketSize = tr.readUINT32();
 
-		return wrapPacket(response);
-	}
+			// msgcode
+			tw.writeByte(0x5b);
+			tw.writeUINT32(recipientChannel);
+			tw.writeUINT32(senderChannel);
+			tw.writeUINT32(initialWindowSize);
+			tw.writeUINT32(maximumPacketSize);
+		} catch (IOException e) {
+			e.printStackTrace();
+		}
 
-	/**
-	 * New Keys response.
-	 * 
-	 * @return New Keys response.
-	 */
-	private Packet newKeys() {
-		byte[] msgCode = { 0x15 };
-		return wrapPacket(msgCode);
+		return wrapPacket(tw.getBytes());
 	}
 
 	/**
-	 * Service ssh-userauth reply.
+	 * Channel Success Reply.
 	 * 
 	 * @param request
-	 *            from the client.
-	 * @return Service reply.
+	 *            from client.
+	 * @return Channel Success Reply.
 	 */
-	private Packet serviceReply(byte[] request) {
-		byte[] message;
-		if (request[5] == 0x15) { // if newkeys request is included in the same
-									// packet
-			message = new byte[request.length - 16]; // remove it
-			System.arraycopy(request, 16, message, 0, request.length - 16);
-		} else {
-			message = request;
-		}
-		if (message[5] != 0x05
-				&& !(HelperUtils.byteToStr(message).contains("ssh-userauth"))) {
-			return disconnectReply(7); // disconnect because its not
-										// servicerequest ssh-userauth
+	private Packet channelSuccessReply(byte[] request) {
+		if (!(HelperUtils.byteToStr(request)).contains("pty-req")) {
+			return disconnectReply(2);
 		}
 		TypesWriter tw = new TypesWriter();
-		tw.writeByte(0x06);
-		tw.writeString("ssh-userauth");
+		// msgcode
+		tw.writeByte(0x63);
+		tw.writeUINT32(recipientChannel);
+
 		return wrapPacket(tw.getBytes());
 	}
 
@@ -589,7 +508,7 @@ public class SSH implements Protocol {
 			message = tr.readString();
 			if (message.contains("\r")) {
 				if (command.toString().contains("exit")) {
-					state = STATE.CLOSED; // ugly style
+					state = STATE.CLOSED;
 					return disconnectReply(2);
 				}
 				message = "\r\nbash: " + command + " :command not found\r\n"
@@ -606,43 +525,115 @@ public class SSH implements Protocol {
 			e.printStackTrace();
 		}
 		TypesWriter tw = new TypesWriter();
-		tw.writeByte(0x5e); // msgcode
+		// msgcode
+		tw.writeByte(0x5e);
 		tw.writeUINT32(recipientChannel);
 		tw.writeString(message);
 		return wrapPacket(tw.getBytes());
 	}
 
 	/**
-	 * Wraps the packets with packet length and padding.
+	 * Disconnect Reply using the given number as reason code.
 	 * 
-	 * @param response
-	 *            content that is wrapped.
-	 * @return wrapped packet.
+	 * @param reasonCode
+	 *            for disconnect reply. Must be between 1 and 15, default is 2.
+	 * @return Disconnect Reply.
 	 */
-	private Packet wrapPacket(byte[] response) {
-		// 4 byte packet length, 1 byte padding length, payload length
-		int packetLength = 5 + response.length;
-		int paddingLengthCBS = cipherBlockSize
-				- (packetLength % cipherBlockSize);
-		int paddingLength8 = 8 - (packetLength % 8);
-		int paddingLength = paddingLengthCBS > paddingLength8 ? paddingLengthCBS
-				: paddingLength8;
-		if (paddingLength < 4)
-			paddingLength += cipherBlockSize;
-		// add padding string length to packet length
-		packetLength = packetLength + paddingLength - 4; 
-		byte[] packetLen = ByteBuffer.allocate(4).putInt(packetLength).array();
-		byte[] paddingLen = { (byte) paddingLength };
-		byte[] paddingString = HelperUtils.randomBytes(paddingLength);
-		byte[] wrappedResponse = HelperUtils.concat(packetLen, paddingLen,
-				response, paddingString);
-		if (useEncryption) {
-			byte[] mac = createMac(wrappedResponse);
-			byte[] responseEnc = encryptBytes(wrappedResponse);
-			wrappedResponse = HelperUtils.concat(responseEnc, mac);
+	private Packet disconnectReply(int reasonCode) {
+		TypesWriter tw = new TypesWriter();
+		tw.writeByte(0x01);
+		switch (reasonCode) {
+		case 1:
+			tw.writeUINT32(1);
+			tw.writeString("SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT");
+			break;
+		case 7:
+			tw.writeUINT32(7);
+			tw.writeString("SSH_DISCONNECT_SERVICE_NOT_AVAILABLE");
+			break;
+		case 14:
+			tw.writeUINT32(14);
+			tw.writeString("SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE");
+			break;
+		default:
+			tw.writeUINT32(2);
+			tw.writeString("SSH_DISCONNECT_PROTOCOL_ERROR");
+			break;
 		}
-		packetNumber++;
+		return wrapPacket(tw.getBytes());
+	}
 
-		return new Packet(wrappedResponse, toString());
+	/**
+	 * Extracts the type of the client
+	 * 
+	 * @param request
+	 *            containing the clients type
+	 */
+	private void extractType(byte[] request) {
+		int length = 0;
+		for (int i = 0; i < request.length; i++, length++) {
+			// find the end of the type: '\r'
+			if (request[i] == 0x0d)
+				break;
+		}
+		V_C = new byte[length];
+		System.arraycopy(request, 0, V_C, 0, length);
+	}
+
+	/**
+	 * Extracts the payload of a packet and writes it in I_C.
+	 * 
+	 * @param request
+	 *            packet of which the payload is extracted.
+	 */
+	private void extractPayload(byte[] request) {
+		int position = 0;
+		if (request[5] != 0x14) {
+			position = 1;
+			for (int i = 0; i < request.length; i++, position++) {
+				if (request[i] == 0x0a)
+					break;
+			}
+		}
+		int packetLength = byteToInt(new byte[] { request[position],
+				request[1 + position], request[2 + position],
+				request[3 + position] });
+		int paddingLength = byteToInt(new byte[] { request[4 + position] });
+		byte[] payload = new byte[packetLength - paddingLength - 1];
+		for (int i = 5; i < packetLength - paddingLength - 1; i++) {
+			payload[i - 5] = request[i + position];
+		}
+		I_C = payload;
+	}
+
+	/**
+	 * Extracts the public key from the DH Kex Request
+	 * 
+	 * @param request
+	 *            containing the clients public key
+	 */
+	private void extractPubKey(byte[] request) {
+		e = new byte[byteToInt(new byte[] { request[6], request[7], request[8],
+				request[9] })];
+		for (int i = 0; i < e.length; i++) {
+			e[i] = request[i + 10];
+		}
 	}
+
+	/**
+	 * Converts a byte[] to int
+	 * 
+	 * @param bytes
+	 *            that are converted
+	 * @return converted byte[] as int
+	 */
+	private static int byteToInt(byte[] bytes) {
+		int convertedInteger = 0;
+		for (int i = 0; i < bytes.length; i++) {
+			convertedInteger <<= 8;
+			convertedInteger |= bytes[i] & 0xFF;
+		}
+		return convertedInteger;
+	}
+
 }

+ 60 - 29
src/de/tudarmstadt/informatik/hostage/sync/bluetooth/BluetoothSyncActivity.java

@@ -2,7 +2,6 @@ package de.tudarmstadt.informatik.hostage.sync.bluetooth;
 
 import java.util.UUID;
 
-import android.util.Log;
 import android.app.Activity;
 import android.bluetooth.BluetoothAdapter;
 import android.bluetooth.BluetoothDevice;
@@ -17,7 +16,6 @@ import android.os.Message;
 import android.view.View;
 import android.widget.AdapterView;
 import android.widget.ArrayAdapter;
-import android.widget.LinearLayout;
 import android.widget.ListView;
 import android.widget.TextView;
 import android.widget.AdapterView.OnItemClickListener;
@@ -49,7 +47,6 @@ public class BluetoothSyncActivity extends Activity{
 	
 	private TextView mInfoText;
 	private ListView listView;
-	private LinearLayout layout;
 	
 	
 	@Override
@@ -58,11 +55,29 @@ public class BluetoothSyncActivity extends Activity{
 		setContentView(R.layout.activity_bluetooth);		
 		
 		serviceUUID = UUID.fromString(getResources().getString(R.string.UUID));
-		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();					
+		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();	
 		arrayAdapter = new ArrayAdapter<String>(this, R.layout.list_view_bluetooth_devices);	
-		setLayoutElement();
+		
+		setLayoutElement();		
 		registerBroadcastReceiver();
-				
+		
+		if(savedInstanceState != null){
+			CharSequence text = savedInstanceState.getCharSequence("mInfoText");
+			mInfoText.setText(text); 		
+		    String[] data = savedInstanceState.getStringArray("adapter");
+		    if(data != null){
+			    for(int i = 0; i < data.length; i++){
+					arrayAdapter.add(data[i]);
+				    arrayAdapter.notifyDataSetChanged();
+			    }
+		    }	
+		    if(savedInstanceState.getBoolean("listView")){
+		    	listView.setVisibility(View.VISIBLE);
+		    }else{
+		    	listView.setVisibility(View.GONE);
+		    }
+		}
+							
 		if (mBluetoothAdapter == null) {
 			// Device does not support Bluetooth
 			mInfoText.setText("Bluetooth is not available on this device.");
@@ -71,7 +86,7 @@ public class BluetoothSyncActivity extends Activity{
 			mInfoText.setText("Enable Bluetooth before synchronizing.");
 			Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
 			startActivity(enableBtIntent);
-		} else {
+		} else if(savedInstanceState == null){
 			startConnectionListener();
 			chooseDevice();
 		}
@@ -84,37 +99,42 @@ public class BluetoothSyncActivity extends Activity{
 		if(mRecieverRegistered){
 			unregisterBroadcastReceiver();
 		}
-		if(commThread != null) {
-			commThread.cancel();
-		}
-		if(clientThread != null){
-			clientThread.cancel();
-		}
-		if(serverThread != null){
-			serverThread.cancel();
+		cancelThreads();
+	}
+	
+	@Override
+	protected void onSaveInstanceState(Bundle outState){
+		String[] data = new String[arrayAdapter.getCount()];
+		for(int i = 0; i < arrayAdapter.getCount(); i++){
+			data[i] = arrayAdapter.getItem(i);
 		}
+		outState.putStringArray("adapter", data);
+		outState.putCharSequence("mInfoText", mInfoText.getText());
+		outState.putBoolean("listView", listView.isShown());
+		super.onSaveInstanceState(outState);
 	}
 	
+	
 	/**
-	 * Starts discorvry of bluetooth devices.
+	 * Starts discovery of bluetooth devices.
 	 */
 	private void chooseDevice(){
-		arrayAdapter.clear();
 		if (!mBluetoothAdapter.startDiscovery())
 			return;
 		mInfoText.setText("Choose Device for synchronizing:\n");
-		layout.addView(listView);
-		setContentView(layout);
+		listView.setVisibility(View.VISIBLE);
 	}
 
 	/**
-	 * Start a ServerThread to listen for incomming connections
+	 * Start a ServerThread to listen for incoming connections
 	 * @see ServerThread
 	 */
 	private void startConnectionListener() {
-		Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
-		discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
-		startActivity(discoverableIntent);
+		if(mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE){
+			Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
+			discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
+			startActivity(discoverableIntent);
+		}
 
 		serverThread = new ServerThread(mHandler, getResources().getString(R.string.app_name));
 		serverThread.start();
@@ -129,7 +149,7 @@ public class BluetoothSyncActivity extends Activity{
 		mBluetoothAdapter.cancelDiscovery();
 		unregisterBroadcastReceiver();
 		
-		layout.removeView(listView);
+		listView.setVisibility(View.GONE);
 		String deviceName = socket.getRemoteDevice().getName();
 		mInfoText.setText("Synchronizing with " + deviceName + "...");	
 		
@@ -153,13 +173,12 @@ public class BluetoothSyncActivity extends Activity{
 				arrayAdapter.notifyDataSetChanged();
 			}else if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
 				int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
-				Log.i("BluetoothSync", state + "");
 				if(state == BluetoothAdapter.STATE_ON){
 					startConnectionListener();
 					chooseDevice();
 				}else if(state == BluetoothAdapter.STATE_OFF ||  state == BluetoothAdapter.STATE_TURNING_OFF){
 					mInfoText.setText("Enable Bluetooth before synchronizing.");
-					layout.removeView(listView);
+					listView.setVisibility(View.GONE);
 				}
 			}
 		}
@@ -192,8 +211,7 @@ public class BluetoothSyncActivity extends Activity{
 	 */
 	private void setLayoutElement(){
 		mInfoText = (TextView) findViewById(R.id.bluetoothInfoText);
-		layout = (LinearLayout) findViewById(R.id.bluetoothLayout);
-		listView = new ListView(this);
+		listView = (ListView) findViewById(R.id.bluetoothListView);
 		listView.setAdapter(arrayAdapter);
 		listView.setOnItemClickListener(new OnItemClickListener() {
 			@Override
@@ -208,6 +226,18 @@ public class BluetoothSyncActivity extends Activity{
 		});		
 	}	
 	
+	private void cancelThreads(){
+		if(commThread != null) {
+			commThread.cancel();
+		}
+		if(clientThread != null){
+			clientThread.cancel();
+		}
+		if(serverThread != null){
+			serverThread.cancel();
+		}
+	}
+	
 	/**
 	 * Handles message sent from the background threads and updates UI.
 	 */
@@ -217,7 +247,7 @@ public class BluetoothSyncActivity extends Activity{
         public void handleMessage(Message msg) {
         	switch(msg.what){
         		case CONNECTING:       
-        			layout.removeView(listView);
+        			listView.setVisibility(View.GONE);
         			mInfoText.setText("Connecting to " + (String)msg.obj + "!");
         			break;
         		case CONNECTION_ESTABLISHED: 
@@ -231,6 +261,7 @@ public class BluetoothSyncActivity extends Activity{
         			mInfoText.setText("Synchronization successfull!");
         			break;	
         		case SYNC_FAILED: 
+        			commThread.cancel();
         			mInfoText.setText("Synchronization failed!");
         			break;	
         	}        		

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

@@ -58,6 +58,8 @@ public class CommunicationThread extends Thread {
 	/* Call this from the main activity to shutdown the connection */
 	public void cancel() {
 		try {
+			objectInput.close();
+			objectOuput.close();
 			mmSocket.close();
 		} catch (IOException e) {
 		}
@@ -77,6 +79,7 @@ public class CommunicationThread extends Thread {
 		} catch (ClassNotFoundException e) {
 			e.printStackTrace();
 		} catch (IOException e) {
+			cancel();
 			e.printStackTrace();
 			break;
 		}

+ 52 - 25
src/de/tudarmstadt/informatik/hostage/sync/nfc/NFCSync.java → src/de/tudarmstadt/informatik/hostage/sync/nfc/NFCSyncActivity.java

@@ -27,13 +27,16 @@ import java.util.Iterator;
 
 import android.annotation.TargetApi;
 import android.app.Activity;
+import android.app.PendingIntent;
 import android.content.Intent;
+import android.content.IntentFilter;
 import android.nfc.NdefMessage;
 import android.nfc.NdefRecord;
 import android.nfc.NfcAdapter;
 import android.nfc.NfcAdapter.CreateNdefMessageCallback;
 import android.nfc.NfcAdapter.OnNdefPushCompleteCallback;
 import android.nfc.NfcEvent;
+import android.nfc.tech.NfcF;
 import android.os.Build;
 import android.os.Bundle;
 import android.os.Handler;
@@ -49,23 +52,30 @@ import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
 import de.tudarmstadt.informatik.hostage.sync.tracing.TracingSyncService;
 
 @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
-public class NFCSync extends Activity implements CreateNdefMessageCallback, OnNdefPushCompleteCallback {
+public class NFCSyncActivity extends Activity implements CreateNdefMessageCallback, OnNdefPushCompleteCallback {
 	NfcAdapter mNfcAdapter;
 	TextView mInfoText;
 	private static final int MESSAGE_SENT = 0x1;
-	private static final int SYNC_SUCCESSFUL = 0x2;
+	private static final int MESSAGE_RECEIVED = 0x3;
+	
 
 	private final Handler mHandler = new Handler() {
 		@Override
 		public void handleMessage(Message msg) {
 			switch (msg.what) {
-			case MESSAGE_SENT:
-				mInfoText.setText("Synchronization data sent, wait for data.");
-				Log.i("NFC", "Message sent!");
+			case MESSAGE_SENT:				
+				runOnUiThread(new Runnable() {
+					public void run() {
+		            	Toast.makeText(NFCSyncActivity.this, "Data sent!", Toast.LENGTH_LONG).show();
+					}
+		        });
 				break;
-			case SYNC_SUCCESSFUL:
-				mInfoText.setText("Synchronization successfull!");
-				Log.i("NFC", "Message sent!");
+			case MESSAGE_RECEIVED:
+				runOnUiThread(new Runnable() {
+					public void run() {
+		            	Toast.makeText(NFCSyncActivity.this, "Data recieved!", Toast.LENGTH_LONG).show();
+					}
+		        });				
 				break;
 			}
 		}
@@ -84,7 +94,7 @@ public class NFCSync extends Activity implements CreateNdefMessageCallback, OnNd
 		} else if(!mNfcAdapter.isEnabled()){
 			mInfoText.setText("Enable Android Beam before synchronizing.");
 		} else {
-			mInfoText.setText("Hold phones together to synchronize.");
+			mInfoText.setText("Hold phones together to send or recieve data.");
 			// Register callback to set NDEF message
 			mNfcAdapter.setNdefPushMessageCallback(this, this);
 			// Register callback to listen for message-sent success
@@ -103,7 +113,6 @@ public class NFCSync extends Activity implements CreateNdefMessageCallback, OnNd
 		HashMap<String, Long> devices_local = dbh.getSyncDevices();
 		ArrayList<SyncInfoRecord> syncInfo = dbh.getSyncInfo();
 		
-		Log.i("NFC", "Creating Message");
 		NdefMessage msg = null;
 		try {
 			NdefRecord netData = NdefRecord.createMime("application/de.tudarmstadt.informatik.hostage", serialize(localNetworkInformation));
@@ -138,10 +147,36 @@ public class NFCSync extends Activity implements CreateNdefMessageCallback, OnNd
 	@Override
 	public void onResume() {
 		super.onResume();
+		IntentFilter[] mIntentFilters = null;
+			
+	    PendingIntent mPendingIntent = PendingIntent.getActivity(this, 0, 
+	    		new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
+ 
+        // set an intent filter for all MIME data
+        IntentFilter ndefIntent = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
+        try {
+            ndefIntent.addDataType("*/*");
+            mIntentFilters = new IntentFilter[] { ndefIntent };
+        } catch (Exception e) {
+            Log.e("TagDispatch", e.toString());
+        }
+ 
+        String[][] mNFCTechLists = new String[][] { new String[] { NfcF.class.getName() } };
+        
+        if (mNfcAdapter != null)
+            mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, mIntentFilters, mNFCTechLists);
+	
 		// Check to see that the Activity started due to an Android Beam
 		if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
 			processIntent(getIntent());
-		}
+		}		
+	}
+	
+	@Override
+	public void onPause() {
+		super.onPause();
+		if (mNfcAdapter != null)
+			mNfcAdapter.disableForegroundDispatch(this);
 	}
 
 	/**
@@ -151,20 +186,13 @@ public class NFCSync extends Activity implements CreateNdefMessageCallback, OnNd
 		Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
 		// only one message sent during the beam
 		NdefMessage msg = (NdefMessage) rawMsgs[0];
-		// record 0 contains the MIME type, record 1 is the AAR, if present
-		Object netData;
-		Object deviceData;
-		Object syncData;
-		Log.i("NFC", "Getting Message!");
 		try {
 			HostageDBOpenHelper dbh = new HostageDBOpenHelper(this);
-			netData = deserialize(msg.getRecords()[0].getPayload());
-			deviceData = deserialize(msg.getRecords()[1].getPayload());
-			syncData = deserialize(msg.getRecords()[2].getPayload());
-			ArrayList<NetworkRecord> remoteNetworkInformation = (ArrayList<NetworkRecord>) netData;
-			HashMap<String, Long> devices_remote = (HashMap<String, Long>) deviceData;
+
+			ArrayList<NetworkRecord> remoteNetworkInformation = (ArrayList<NetworkRecord>) deserialize(msg.getRecords()[0].getPayload());
+			HashMap<String, Long> devices_remote = (HashMap<String, Long>) deserialize(msg.getRecords()[1].getPayload());
 			HashMap<String, Long> devices_local = dbh.getSyncDevices();
-			ArrayList<SyncInfoRecord> syncInfo = (ArrayList<SyncInfoRecord>) syncData;
+			ArrayList<SyncInfoRecord> syncInfo = (ArrayList<SyncInfoRecord>) deserialize(msg.getRecords()[2].getPayload());
 			
 			long tracing_timestamp = 0;
 			if(devices_local.containsKey(TracingSyncService.REMOTE_DEVICE))
@@ -177,11 +205,10 @@ public class NFCSync extends Activity implements CreateNdefMessageCallback, OnNd
 					i.remove();
 				}
 			}
-
 			
 			for ( Iterator<SyncInfoRecord> i = syncInfo.iterator(); i.hasNext(); ){
 				SyncInfoRecord info = i.next();
-				if(devices_remote.containsKey(info.getDeviceID())){
+				if(!devices_remote.containsKey(info.getDeviceID())){
 					i.remove();
 				}				    
 			}	
@@ -189,7 +216,7 @@ public class NFCSync extends Activity implements CreateNdefMessageCallback, OnNd
 			dbh.updateSyncDevices(devices_remote);
 			dbh.updateSyncInfo(syncInfo);
 			dbh.updateNetworkInformation(remoteNetworkInformation);
-			mHandler.obtainMessage(SYNC_SUCCESSFUL).sendToTarget();
+			mHandler.obtainMessage(MESSAGE_RECEIVED).sendToTarget();
 		} catch (ClassNotFoundException e) {
 			e.printStackTrace();
 		} catch (IOException e) {

+ 27 - 10
src/de/tudarmstadt/informatik/hostage/sync/tracing/TracingSyncService.java

@@ -25,6 +25,8 @@ 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 org.json.JSONException;
+import org.json.JSONObject;
 
 import android.app.IntentService;
 import android.content.Intent;
@@ -34,7 +36,8 @@ import android.os.Bundle;
 import android.os.ResultReceiver;
 import android.preference.PreferenceManager;
 import android.util.Log;
-import de.tudarmstadt.informatik.hostage.logging.AttackRecord;
+import de.tudarmstadt.informatik.hostage.logging.NetworkRecord;
+import de.tudarmstadt.informatik.hostage.logging.SyncInfoRecord;
 import de.tudarmstadt.informatik.hostage.net.MySSLSocketFactory;
 import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
 
@@ -106,13 +109,11 @@ public class TracingSyncService extends IntentService {
 		// String serverAddress = pref.getString("pref_upload",
 		// "https://ssi.cased.de");
 		String serverAddress = "http://87.230.23.240/hostage/push.php";
-		ArrayList<AttackRecord> recordList = dbh.getRecordOfEachAttack(lastUploadedAttackId);
+		ArrayList<NetworkRecord> recordList = dbh.getNetworkInformation();
+
 		int size = recordList.size();
 		int offset = 1;
-		for (AttackRecord record : recordList) {
-			editor.putInt("LAST_UPLOADED_ATTACK_ID", lastUploadedAttackId + offset);
-			editor.commit();
-
+		for (NetworkRecord record : recordList) {
 			boolean success = uploadSingleRecord(record, serverAddress);
 			Log.i("Tracing upload", "Upload of record: " + offset + "/" + size + ((success) ? " successful." : " failed."));
 			if (receiver != null) {
@@ -136,7 +137,7 @@ public class TracingSyncService extends IntentService {
 	 * @serverAddress Address of the target server
 	 * @return True if the upload was successful, else false.
 	 */
-	private boolean uploadSingleRecord(AttackRecord record, String serverAddress) {
+	private boolean uploadSingleRecord(NetworkRecord record, String serverAddress) {
 		// Create a https client. Uses MySSLSocketFactory to accept all
 		// certificates
 		HttpPost httppost;
@@ -147,11 +148,13 @@ public class TracingSyncService extends IntentService {
 			// Create JSON String of Record
 			// TODO StringEntity se = new
 			// StringEntity(record.toString(TraCINgFormatter.getInstance()));
-			StringEntity se = new StringEntity("record=" + record.toJSON()); // FIXME
+			String s = record.toJSON();
+			StringEntity se = new StringEntity("record=" + record.toJSON());
 			httppost.addHeader("content-type", "application/x-www-form-urlencoded");
 			httppost.setEntity(se);
 			// Execute HttpPost
 			HttpResponse response = httpClient.execute(httppost);
+			getRemoteData(record.getBssid(), record.getTimestampLocation());
 			Log.i("TracingSyncService", "Status Code: " + response.getStatusLine().getStatusCode());
 		} catch (Exception e) {
 			e.printStackTrace();
@@ -168,7 +171,7 @@ public class TracingSyncService extends IntentService {
 		OutputStreamWriter request = null;
 		URL url = null;
 		String response = null;
-		String parameters = "bssid=" + bssid + "timestamp=" + timestamp;
+		String parameters = "bssid=" + bssid;
 		try {
 			url = new URL("http://87.230.23.240/hostage/pull.php");
 			connection = (HttpURLConnection) url.openConnection();
@@ -189,11 +192,25 @@ public class TracingSyncService extends IntentService {
 				sb.append(line);
 			}
 			response = sb.toString();
+			JSONObject jsonObj = new JSONObject(response);
+				NetworkRecord net = new NetworkRecord();
+				net.setBssid(jsonObj.getString("bssid"));
+				net.setSsid(jsonObj.getString("ssid"));
+				net.setLatitude(jsonObj.getDouble("latitude"));
+				net.setLongitude(jsonObj.getDouble("longitude"));
+				net.setTimestampLocation(jsonObj.getLong("timestamp"));
+				SyncInfoRecord sync = new SyncInfoRecord();
+				sync.setBSSID(jsonObj.getString("bssid"));
+				sync.setDeviceID("-1");
+				sync.setNumber_of_attacks(jsonObj.getLong("attacks"));
+				sync.setNumber_of_portscans(jsonObj.getLong("portscans"));
+				dbh.updateNetworkInformation(net);
 			isr.close();
 			reader.close();
-			Log.d("TEST", response);
 		} catch (IOException e) {
 			Log.i("NetworkTest", "Network Error: " + e);
+		} catch (JSONException e) {
+			e.printStackTrace();
 		}
 	}
 

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

@@ -38,19 +38,19 @@ import de.tudarmstadt.informatik.hostage.Hostage;
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.model.Profile;
 import de.tudarmstadt.informatik.hostage.persistence.ProfileManager;
-import de.tudarmstadt.informatik.hostage.ui2.model.LogFilter;
-import de.tudarmstadt.informatik.hostage.ui2.adapter.DrawerListAdapter;
-import de.tudarmstadt.informatik.hostage.ui2.fragment.AboutFragment;
-import de.tudarmstadt.informatik.hostage.ui2.fragment.HomeFragment;
-import de.tudarmstadt.informatik.hostage.ui2.fragment.ProfileManagerFragment;
-import de.tudarmstadt.informatik.hostage.ui2.fragment.RecordOverviewFragment;
-import de.tudarmstadt.informatik.hostage.ui2.fragment.ServicesFragment;
-import de.tudarmstadt.informatik.hostage.ui2.fragment.SettingsFragment;
-import de.tudarmstadt.informatik.hostage.ui2.fragment.StatisticsFragment;
-import de.tudarmstadt.informatik.hostage.ui2.fragment.ThreatMapFragment;
-import de.tudarmstadt.informatik.hostage.ui2.fragment.UpNavigatibleFragment;
-import de.tudarmstadt.informatik.hostage.ui2.fragment.opengl.ThreatIndicatorGLRenderer;
-import de.tudarmstadt.informatik.hostage.ui2.model.DrawerListItem;
+import de.tudarmstadt.informatik.hostage.ui.model.LogFilter;
+import de.tudarmstadt.informatik.hostage.ui.adapter.DrawerListAdapter;
+import de.tudarmstadt.informatik.hostage.ui.fragment.AboutFragment;
+import de.tudarmstadt.informatik.hostage.ui.fragment.HomeFragment;
+import de.tudarmstadt.informatik.hostage.ui.fragment.ProfileManagerFragment;
+import de.tudarmstadt.informatik.hostage.ui.fragment.RecordOverviewFragment;
+import de.tudarmstadt.informatik.hostage.ui.fragment.ServicesFragment;
+import de.tudarmstadt.informatik.hostage.ui.fragment.SettingsFragment;
+import de.tudarmstadt.informatik.hostage.ui.fragment.StatisticsFragment;
+import de.tudarmstadt.informatik.hostage.ui.fragment.ThreatMapFragment;
+import de.tudarmstadt.informatik.hostage.ui.fragment.UpNavigatibleFragment;
+import de.tudarmstadt.informatik.hostage.ui.fragment.opengl.ThreatIndicatorGLRenderer;
+import de.tudarmstadt.informatik.hostage.ui.model.DrawerListItem;
 
 /**
  * Manages the whole application, and should act like an singleton.

+ 2 - 2
src/de/tudarmstadt/informatik/hostage/ui/activity/ProfileEditActivity.java

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.ui2.activity;
+package de.tudarmstadt.informatik.hostage.ui.activity;
 
 import android.content.Intent;
 import android.database.Cursor;
@@ -11,7 +11,7 @@ import android.preference.Preference;
 import android.preference.PreferenceActivity;
 import android.provider.MediaStore;
 
-import de.tudarmstadt.informatik.hostage.ui2.fragment.ProfileEditFragment;
+import de.tudarmstadt.informatik.hostage.ui.fragment.ProfileEditFragment;
 
 /**
  * This activity manages an fragment for editing and creating a profile

+ 2 - 2
src/de/tudarmstadt/informatik/hostage/ui/adapter/DrawerListAdapter.java

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.ui2.adapter;
+package de.tudarmstadt.informatik.hostage.ui.adapter;
 
 import android.content.Context;
 import android.view.LayoutInflater;
@@ -11,7 +11,7 @@ import android.widget.TextView;
 import java.util.List;
 
 import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.ui2.model.DrawerListItem;
+import de.tudarmstadt.informatik.hostage.ui.model.DrawerListItem;
 
 /**
  * Creates the item view for the navigation drawer listview

+ 2 - 2
src/de/tudarmstadt/informatik/hostage/ui/adapter/ExpandableListAdapter.java

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.ui2.adapter;
+package de.tudarmstadt.informatik.hostage.ui.adapter;
 
 import android.content.Context;
 import android.view.LayoutInflater;
@@ -10,7 +10,7 @@ import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 
-import de.tudarmstadt.informatik.hostage.ui2.model.ExpandableListItem;
+import de.tudarmstadt.informatik.hostage.ui.model.ExpandableListItem;
 
 /**
  * Created by Julien on 06.02.14.

+ 4 - 4
src/de/tudarmstadt/informatik/hostage/ui/adapter/ProfileManagerListAdapter.java

@@ -22,10 +22,10 @@ import de.tudarmstadt.informatik.hostage.Hostage;
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.persistence.ProfileManager;
 import de.tudarmstadt.informatik.hostage.model.Profile;
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
-import de.tudarmstadt.informatik.hostage.ui2.activity.ProfileEditActivity;
-import de.tudarmstadt.informatik.hostage.ui2.layouts.FlowLayout;
-import de.tudarmstadt.informatik.hostage.ui2.swipelist.SwipeListView;
+import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
+import de.tudarmstadt.informatik.hostage.ui.activity.ProfileEditActivity;
+import de.tudarmstadt.informatik.hostage.ui.layouts.FlowLayout;
+import de.tudarmstadt.informatik.hostage.ui.swipelist.SwipeListView;
 
 /**
  * This adapter creates the item views for the profile manager by making use the viewholder pattern

+ 64 - 64
src/de/tudarmstadt/informatik/hostage/ui/adapter/RecordListAdapter.java

@@ -1,64 +1,64 @@
-package de.tudarmstadt.informatik.hostage.ui2.adapter;
-
-import android.content.Context;
-import android.view.View;
-import android.widget.TextView;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-
-import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.ui2.model.ExpandableListItem;
-
-public class RecordListAdapter extends ExpandableListAdapter {
-
-    /**
-     * Constructor
-     * @param context the context
-     * @param listSectionHeaders the section titles
-     * @param dataMapping HashMap<String, ArrayList<{@link ExpandableListItem ExpandableListItem}>> the data to visualise
-     */
-    public RecordListAdapter(Context context, List<String> listSectionHeaders, HashMap<String, ArrayList<ExpandableListItem>> dataMapping) {
-        super(context, listSectionHeaders, dataMapping);
-    }
-
-
-    /*****************************
-     *
-     *          Required Methods
-     *
-     * ***************************/
-
-    @Override
-    public void configureCellView(View cell, int section, int row) {
-        ExpandableListItem object = this.getDataForRow(section, row);
-        for (String key : object.getId_Mapping().keySet()){
-            int viewID = object.getId_Mapping().get(key);
-            String textualInfo = object.getData().get(key);
-            TextView tView = (TextView) cell.findViewById(viewID);
-            tView.setText(textualInfo);
-        }
-    }
-
-    @Override
-    public void configureSectionHeaderView(View sectionHeader, int section) {
-        int headerLabelID = R.id.sectionHeaderTitle;
-        int valueLabelID = R.id.sectionHeaderValue;
-        TextView tView = (TextView) sectionHeader.findViewById(headerLabelID);
-        TextView vView = (TextView) sectionHeader.findViewById(valueLabelID);
-        int value = this.getChildrenCount(section);
-        tView.setText(this._sectionHeader.get(section));
-        vView.setText("" + value);
-    }
-
-    @Override
-    public int getSectionLayoutID() {
-        return R.layout.expandable_section_header;
-    }
-
-    @Override
-    public int getCellLayoutID() {
-        return R.layout.record_list_item;
-    }
-}
+package de.tudarmstadt.informatik.hostage.ui.adapter;
+
+import android.content.Context;
+import android.view.View;
+import android.widget.TextView;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+import de.tudarmstadt.informatik.hostage.R;
+import de.tudarmstadt.informatik.hostage.ui.model.ExpandableListItem;
+
+public class RecordListAdapter extends ExpandableListAdapter {
+
+    /**
+     * Constructor
+     * @param context the context
+     * @param listSectionHeaders the section titles
+     * @param dataMapping HashMap<String, ArrayList<{@link ExpandableListItem ExpandableListItem}>> the data to visualise
+     */
+    public RecordListAdapter(Context context, List<String> listSectionHeaders, HashMap<String, ArrayList<ExpandableListItem>> dataMapping) {
+        super(context, listSectionHeaders, dataMapping);
+    }
+
+
+    /*****************************
+     *
+     *          Required Methods
+     *
+     * ***************************/
+
+    @Override
+    public void configureCellView(View cell, int section, int row) {
+        ExpandableListItem object = this.getDataForRow(section, row);
+        for (String key : object.getId_Mapping().keySet()){
+            int viewID = object.getId_Mapping().get(key);
+            String textualInfo = object.getData().get(key);
+            TextView tView = (TextView) cell.findViewById(viewID);
+            tView.setText(textualInfo);
+        }
+    }
+
+    @Override
+    public void configureSectionHeaderView(View sectionHeader, int section) {
+        int headerLabelID = R.id.sectionHeaderTitle;
+        int valueLabelID = R.id.sectionHeaderValue;
+        TextView tView = (TextView) sectionHeader.findViewById(headerLabelID);
+        TextView vView = (TextView) sectionHeader.findViewById(valueLabelID);
+        int value = this.getChildrenCount(section);
+        tView.setText(this._sectionHeader.get(section));
+        vView.setText("" + value);
+    }
+
+    @Override
+    public int getSectionLayoutID() {
+        return R.layout.expandable_section_header;
+    }
+
+    @Override
+    public int getCellLayoutID() {
+        return R.layout.record_list_item;
+    }
+}

+ 3 - 3
src/de/tudarmstadt/informatik/hostage/ui/adapter/ServicesListAdapter.java

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.ui2.adapter;
+package de.tudarmstadt.informatik.hostage.ui.adapter;
 
 import java.util.List;
 
@@ -19,8 +19,8 @@ import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
 import de.tudarmstadt.informatik.hostage.model.Profile;
 import de.tudarmstadt.informatik.hostage.persistence.ProfileManager;
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
-import de.tudarmstadt.informatik.hostage.ui2.model.ServicesListItem;
+import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
+import de.tudarmstadt.informatik.hostage.ui.model.ServicesListItem;
 
 /**
  * @author Daniel Lazar

+ 2 - 2
src/de/tudarmstadt/informatik/hostage/ui/adapter/StatisticListAdapter.java

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.ui2.adapter;
+package de.tudarmstadt.informatik.hostage.ui.adapter;
 
 import android.content.Context;
 import android.view.LayoutInflater;
@@ -11,7 +11,7 @@ import java.util.ArrayList;
 import java.util.List;
 
 import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.ui2.model.PlotComparisonItem;
+import de.tudarmstadt.informatik.hostage.ui.model.PlotComparisonItem;
 
 /**
  * Created by Julien on 22.02.14.

+ 199 - 199
src/de/tudarmstadt/informatik/hostage/ui/dialog/ChecklistDialog.java

@@ -1,199 +1,199 @@
-package de.tudarmstadt.informatik.hostage.ui2.dialog;
-
-import android.annotation.SuppressLint;
-import android.app.Activity;
-import android.app.AlertDialog;
-import android.app.Dialog;
-import android.app.DialogFragment;
-import android.content.DialogInterface;
-import android.os.Bundle;
-
-import java.util.ArrayList;
-
-import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
-
-//import android.content.Intent;
-/**
- * Created by Julien on 16.02.14.
- */
-@SuppressLint("ValidFragment")
-public class ChecklistDialog extends DialogFragment {
-	
-	private ArrayList<Integer> mSelectedItems;
-	private ArrayList<String> itemTitles;
-    private ChecklistDialogListener mListener;
-    
-    private int selectedIndex;
-    private boolean isMultipleChoice;
-    
-    public String title;
-	
-	/**
-     * The ChecklistDialogListener will be called if the user clicked a "cancel" or "ok" button.
-     * */
-    @SuppressLint("ValidFragment")
-	public interface ChecklistDialogListener {
-        /**
-         * Called if the user tapped "ok"
-         * @param dialog {@link ChecklistDialog ChecklistDialog}
-         */
-        public void onDialogPositiveClick(ChecklistDialog dialog);
-
-        /**
-         * Called if the user tapped "cancel".
-         * @param dialog {@link ChecklistDialog ChecklistDialog}
-         */
-        public void onDialogNegativeClick(ChecklistDialog dialog);
-    }
-
-    /**
-     * Returns the dialog title
-     * @return title String
-     */
-    public String getTitle(){
-    	return this.title;
-    }
-
-    /**
-     * Returns true if the checklist dialog is a multiple choice dialog.
-     * @return boolean isMultipleChoice
-     * */
-    public boolean isMultipleChoice(){
-    	return this.isMultipleChoice;
-    }
-
-    /*CONSTRUCTOR*/
-    /**
-     * The Constructor Method
-     * @param  title String
-     * @param itemTitles ArrayList<String> item titles list
-     * @param selected boolean[] an array of bools descriping the position of all the selected titles.
-     * @param isMultipleChoice boolean isMultipleChoice
-     * @param listener ChecklistDialogListener an user "event" listener
-     *
-     * */
-    public ChecklistDialog(String title, ArrayList<String> itemTitles, boolean[] selected, boolean isMultipleChoice , ChecklistDialogListener listener){
-    	mListener = listener;
-    	this.mSelectedItems = new ArrayList<Integer>();
-	    
-    	this.isMultipleChoice = isMultipleChoice;
-	    this.title = title;
-	    this.itemTitles = itemTitles;
-
-	    
-	    
-	    boolean[] selectedArray = new boolean[this.itemTitles.size()];
-
-	    if(this.isMultipleChoice){
-		    for(int i = 0; i < this.itemTitles.size(); i++){
-		    	boolean isSelected = selected[i];
-		    	selectedArray[i] = isSelected;
-		    	if(isSelected) this.mSelectedItems.add(i);
-		    }
-	    } else {
-		    for(int i = 0; i < this.itemTitles.size(); i++){
-		    	boolean isSelected = selected[i];
-		    	selectedArray[i] = isSelected;
-		    	if(isSelected) this.selectedIndex = i;
-		    }
-	    }
-    }
-    
-    @Override
-    public void onAttach(Activity activity) {
-        super.onAttach(activity);
-        
-        if(this.mListener == null)
-        try {
-            
-            if (activity.getClass().equals(MainActivity.class)){
-            	mListener = (ChecklistDialogListener) (((MainActivity)activity).getDisplayedFragment());
-            } else {
-            	mListener = (ChecklistDialogListener) activity;
-            }
-        } catch (ClassCastException e) {
-            throw new ClassCastException(activity.toString()
-                    + " must implement ChecklistDialogListener");
-        }
-    }
-
-    /**
-     * Return the selected titles.
-     * @return ArrayList<String>
-     */
-    public ArrayList<String> getSelectedItemTitles(){
-    	ArrayList<String> list = new ArrayList<String>();
-        if (this.mSelectedItems == null){
-            return  list;
-        }
-    	for(Integer i : this.mSelectedItems){
-    		list.add(this.itemTitles.get(i.intValue()));
-    	}
-        if (this.mSelectedItems.size() == 0 && !this.isMultipleChoice){
-            list.add(this.itemTitles.get(this.selectedIndex));
-       }
-    	return list;
-    }
-
-
-	
-	@Override
-	public Dialog onCreateDialog(Bundle savedInstanceState) {
-	    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
-	    
-	    CharSequence[] titles = this.itemTitles.toArray(new CharSequence[this.itemTitles.size()]);
-	    
-	    boolean[] selectedArray = new boolean[this.itemTitles.size()];
-	    for(Integer selection : this.mSelectedItems){
-	    	selectedArray[selection.intValue()] = true;
-	    }
-
-	    if(this.isMultipleChoice){
-	        builder.setTitle(title).setMultiChoiceItems(titles, selectedArray,
-                    new DialogInterface.OnMultiChoiceClickListener() {
-             public void onClick(DialogInterface dialog, int which,
-                     boolean isChecked) {
-          		   if (isChecked) {
-                     	mSelectedItems.add(which);
-                 	} else if (mSelectedItems.contains(which)) {
-                     	mSelectedItems.remove(Integer.valueOf(which));
-                 	}
-             }
-         }).setPositiveButton(R.string.button_title_apply, new DialogInterface.OnClickListener() {
-             public void onClick(DialogInterface dialog, int id) {
-                 mListener.onDialogPositiveClick(ChecklistDialog.this);
-             }
-         })
-         .setNegativeButton(R.string.button_title_cancel, new DialogInterface.OnClickListener() {
-             public void onClick(DialogInterface dialog, int id) {
-                 mListener.onDialogNegativeClick(ChecklistDialog.this);
-             }
-         });
-	        
-	    } else {
-	    	
-	    	 builder.setTitle(title).setSingleChoiceItems(titles, this.selectedIndex, 
-	    			 new DialogInterface.OnClickListener() {
-	             public void onClick(DialogInterface dialog, int id) {
-	                 mSelectedItems.clear();
-	            	 mSelectedItems.add(id);
-	             }
-	         })
-	         .setPositiveButton(R.string.button_title_apply, new DialogInterface.OnClickListener() {
-             public void onClick(DialogInterface dialog, int id) {
-                 mListener.onDialogPositiveClick(ChecklistDialog.this);
-             }
-	         })
-	         .setNegativeButton(R.string.button_title_cancel, new DialogInterface.OnClickListener() {
-	             public void onClick(DialogInterface dialog, int id) {
-	                 mListener.onDialogNegativeClick(ChecklistDialog.this);
-	             }
-	         });
-	    }
-	    
-	    return builder.create();
-	}
-}
-
-
+package de.tudarmstadt.informatik.hostage.ui.dialog;
+
+import android.annotation.SuppressLint;
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.app.Dialog;
+import android.app.DialogFragment;
+import android.content.DialogInterface;
+import android.os.Bundle;
+
+import java.util.ArrayList;
+
+import de.tudarmstadt.informatik.hostage.R;
+import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
+
+//import android.content.Intent;
+/**
+ * Created by Julien on 16.02.14.
+ */
+@SuppressLint("ValidFragment")
+public class ChecklistDialog extends DialogFragment {
+	
+	private ArrayList<Integer> mSelectedItems;
+	private ArrayList<String> itemTitles;
+    private ChecklistDialogListener mListener;
+    
+    private int selectedIndex;
+    private boolean isMultipleChoice;
+    
+    public String title;
+	
+	/**
+     * The ChecklistDialogListener will be called if the user clicked a "cancel" or "ok" button.
+     * */
+    @SuppressLint("ValidFragment")
+	public interface ChecklistDialogListener {
+        /**
+         * Called if the user tapped "ok"
+         * @param dialog {@link ChecklistDialog ChecklistDialog}
+         */
+        public void onDialogPositiveClick(ChecklistDialog dialog);
+
+        /**
+         * Called if the user tapped "cancel".
+         * @param dialog {@link ChecklistDialog ChecklistDialog}
+         */
+        public void onDialogNegativeClick(ChecklistDialog dialog);
+    }
+
+    /**
+     * Returns the dialog title
+     * @return title String
+     */
+    public String getTitle(){
+    	return this.title;
+    }
+
+    /**
+     * Returns true if the checklist dialog is a multiple choice dialog.
+     * @return boolean isMultipleChoice
+     * */
+    public boolean isMultipleChoice(){
+    	return this.isMultipleChoice;
+    }
+
+    /*CONSTRUCTOR*/
+    /**
+     * The Constructor Method
+     * @param  title String
+     * @param itemTitles ArrayList<String> item titles list
+     * @param selected boolean[] an array of bools descriping the position of all the selected titles.
+     * @param isMultipleChoice boolean isMultipleChoice
+     * @param listener ChecklistDialogListener an user "event" listener
+     *
+     * */
+    public ChecklistDialog(String title, ArrayList<String> itemTitles, boolean[] selected, boolean isMultipleChoice , ChecklistDialogListener listener){
+    	mListener = listener;
+    	this.mSelectedItems = new ArrayList<Integer>();
+	    
+    	this.isMultipleChoice = isMultipleChoice;
+	    this.title = title;
+	    this.itemTitles = itemTitles;
+
+	    
+	    
+	    boolean[] selectedArray = new boolean[this.itemTitles.size()];
+
+	    if(this.isMultipleChoice){
+		    for(int i = 0; i < this.itemTitles.size(); i++){
+		    	boolean isSelected = selected[i];
+		    	selectedArray[i] = isSelected;
+		    	if(isSelected) this.mSelectedItems.add(i);
+		    }
+	    } else {
+		    for(int i = 0; i < this.itemTitles.size(); i++){
+		    	boolean isSelected = selected[i];
+		    	selectedArray[i] = isSelected;
+		    	if(isSelected) this.selectedIndex = i;
+		    }
+	    }
+    }
+    
+    @Override
+    public void onAttach(Activity activity) {
+        super.onAttach(activity);
+        
+        if(this.mListener == null)
+        try {
+            
+            if (activity.getClass().equals(MainActivity.class)){
+            	mListener = (ChecklistDialogListener) (((MainActivity)activity).getDisplayedFragment());
+            } else {
+            	mListener = (ChecklistDialogListener) activity;
+            }
+        } catch (ClassCastException e) {
+            throw new ClassCastException(activity.toString()
+                    + " must implement ChecklistDialogListener");
+        }
+    }
+
+    /**
+     * Return the selected titles.
+     * @return ArrayList<String>
+     */
+    public ArrayList<String> getSelectedItemTitles(){
+    	ArrayList<String> list = new ArrayList<String>();
+        if (this.mSelectedItems == null){
+            return  list;
+        }
+    	for(Integer i : this.mSelectedItems){
+    		list.add(this.itemTitles.get(i.intValue()));
+    	}
+        if (this.mSelectedItems.size() == 0 && !this.isMultipleChoice){
+            list.add(this.itemTitles.get(this.selectedIndex));
+       }
+    	return list;
+    }
+
+
+	
+	@Override
+	public Dialog onCreateDialog(Bundle savedInstanceState) {
+	    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
+	    
+	    CharSequence[] titles = this.itemTitles.toArray(new CharSequence[this.itemTitles.size()]);
+	    
+	    boolean[] selectedArray = new boolean[this.itemTitles.size()];
+	    for(Integer selection : this.mSelectedItems){
+	    	selectedArray[selection.intValue()] = true;
+	    }
+
+	    if(this.isMultipleChoice){
+	        builder.setTitle(title).setMultiChoiceItems(titles, selectedArray,
+                    new DialogInterface.OnMultiChoiceClickListener() {
+             public void onClick(DialogInterface dialog, int which,
+                     boolean isChecked) {
+          		   if (isChecked) {
+                     	mSelectedItems.add(which);
+                 	} else if (mSelectedItems.contains(which)) {
+                     	mSelectedItems.remove(Integer.valueOf(which));
+                 	}
+             }
+         }).setPositiveButton(R.string.button_title_apply, new DialogInterface.OnClickListener() {
+             public void onClick(DialogInterface dialog, int id) {
+                 mListener.onDialogPositiveClick(ChecklistDialog.this);
+             }
+         })
+         .setNegativeButton(R.string.button_title_cancel, new DialogInterface.OnClickListener() {
+             public void onClick(DialogInterface dialog, int id) {
+                 mListener.onDialogNegativeClick(ChecklistDialog.this);
+             }
+         });
+	        
+	    } else {
+	    	
+	    	 builder.setTitle(title).setSingleChoiceItems(titles, this.selectedIndex, 
+	    			 new DialogInterface.OnClickListener() {
+	             public void onClick(DialogInterface dialog, int id) {
+	                 mSelectedItems.clear();
+	            	 mSelectedItems.add(id);
+	             }
+	         })
+	         .setPositiveButton(R.string.button_title_apply, new DialogInterface.OnClickListener() {
+             public void onClick(DialogInterface dialog, int id) {
+                 mListener.onDialogPositiveClick(ChecklistDialog.this);
+             }
+	         })
+	         .setNegativeButton(R.string.button_title_cancel, new DialogInterface.OnClickListener() {
+	             public void onClick(DialogInterface dialog, int id) {
+	                 mListener.onDialogNegativeClick(ChecklistDialog.this);
+	             }
+	         });
+	    }
+	    
+	    return builder.create();
+	}
+}
+
+

+ 302 - 302
src/de/tudarmstadt/informatik/hostage/ui/dialog/DateTimeDialogFragment.java

@@ -1,303 +1,303 @@
-package de.tudarmstadt.informatik.hostage.ui2.dialog;
-
-import android.annotation.SuppressLint;
-import android.app.Activity;
-import android.app.AlertDialog;
-import android.app.AlertDialog.Builder;
-import android.app.Dialog;
-import android.app.DialogFragment;
-import android.content.DialogInterface;
-import android.content.res.Configuration;
-import android.os.Bundle;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.DatePicker;
-import android.widget.DatePicker.OnDateChangedListener;
-import android.widget.TimePicker;
-import android.widget.TimePicker.OnTimeChangedListener;
-
-import java.util.Calendar;
-
-import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
-/**
- * Created by Julien on 16.02.14.
- */
-@SuppressLint("ValidFragment")
-public class DateTimeDialogFragment extends DialogFragment implements OnDateChangedListener, OnTimeChangedListener {
-    // Define constants for date-time picker.
-    public final static int DATE_PICKER = 1;
-    public final static int TIME_PICKER = 2;
-    public final static int DATE_TIME_PICKER = 3;
-
-    // DatePicker reference
-    public DatePicker datePicker;
-
-    // TimePicker reference
-    public TimePicker timePicker;
-
-    // Calendar reference
-    private Calendar mCalendar;
-
-    // Define activity
-    private Activity activity;
-
-    // Define Dialog type
-    private int DialogType;
-
-    // Define Dialog view
-    private View mView;
-
-    // Constructor start
-    public DateTimeDialogFragment(Activity activity) {
-        this(activity, DATE_TIME_PICKER);
-    }
-
-    /**
-     * Constructor
-     * @param activity the activity
-     * @param DialogType, what kind of dialog it is (TIME_PICKER, DATE_PICKER, DATE_TIME_PICKER)
-     */
-    public DateTimeDialogFragment(Activity activity, int DialogType) {
-
-        this.activity = activity;
-        this.DialogType = DialogType;
-
-        LayoutInflater inflater = activity.getLayoutInflater();
-        mView = inflater.inflate(R.layout.date_time_dialog, null);
-
-        this.setupRootView(mView);
-
-    }
-
-
-    @Override
-    public void onConfigurationChanged(Configuration newConfig){
-        super.onConfigurationChanged(newConfig);
-        LayoutInflater inflater = LayoutInflater.from(this.activity);
-
-        ViewGroup container = (ViewGroup) this.mView.getParent();
-
-        container.removeView(this.mView);
-
-        mView = inflater.inflate(R.layout.date_time_dialog, null);
-        container.addView(mView);
-        this.setupRootView(mView);
-    }
-
-    /**
-     * Configure the root view in here.
-     * @param mView, root view
-     */
-    private void setupRootView(View mView){
-
-        mCalendar = Calendar.getInstance();
-
-        datePicker = (DatePicker) mView.findViewById(R.id.DatePicker);
-        datePicker.init(mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH), this);
-
-
-        timePicker = (TimePicker) mView.findViewById(R.id.TimePicker);
-
-        setIs24HourView(true);
-        setCalendarViewShown(false);
-
-        switch (DialogType) {
-            case DATE_PICKER:
-                timePicker.setVisibility(View.GONE);
-                break;
-            case TIME_PICKER:
-                datePicker.setVisibility(View.GONE);
-                break;
-        }
-    }
-
-    /**
-     * Set the current date.
-     * @param timeInMillis, date in milliseconds
-     */
-    public void setDate(long timeInMillis){
-        Calendar calendar = Calendar.getInstance();
-        calendar.setTimeInMillis (timeInMillis);
-
-        int year    = calendar.get(Calendar.YEAR) ;
-        int month   = calendar.get(Calendar.MONTH);
-        int day     = calendar.get(Calendar.DATE);
-        int hour    = calendar.get(Calendar.HOUR);
-        int min     = calendar.get(Calendar.MINUTE);
-
-        datePicker.updateDate(year, month, day);
-        timePicker.setCurrentHour(hour);
-        timePicker.setCurrentMinute(min);
-    }
-
-    /**
-     * Returns the current selected date.
-     * @return long, date in milliseconds
-     */
-   public long getDate(){
-	   
-       int day = datePicker.getDayOfMonth();
-       int month = datePicker.getMonth();
-       int year =  datePicker.getYear();
-       
-       int hourOfDay = timePicker.getCurrentHour();
-       int minute = timePicker.getCurrentMinute();
-
-       Calendar calendar = Calendar.getInstance();
-
-       calendar.set(year, month, day, hourOfDay, minute);
-
-       return calendar.getTime().getTime();
-   }
-
-    /**
-     * The listener which will be called if the user tapped "cancel" or "ok"
-     */
-    public interface DateTimeDialogFragmentListener {
-        /**
-         * Called if the user tapped "ok"
-         * @param dialog {@link DateTimeDialogFragment DateTimeDialogFragment}
-         */
-        public void onDateTimePickerPositiveClick(DateTimeDialogFragment dialog);
-
-        /**
-         * Called if the user tapped "cancel"
-         * @param dialog {@link DateTimeDialogFragment DateTimeDialogFragment}
-         */
-        public void onDateTimePickerNegativeClick(DateTimeDialogFragment dialog);
-    }
-    private DateTimeDialogFragmentListener mListener;
-
-    /**
-     * Set the user interaction listener.
-     * @param listener DateTimeDialogFragmentListener
-     */
-    public void setDateChangeListener(DateTimeDialogFragmentListener listener){
-        this.mListener = listener;
-    }
-
-    @Override
-    public void onAttach(Activity activity) {
-        super.onAttach(activity);
-        try {
-            if (this.mListener == null){
-                if (activity.getClass().equals(MainActivity.class)){
-                    mListener = (DateTimeDialogFragmentListener) (((MainActivity)activity).getDisplayedFragment());
-                } else {
-                    mListener = (DateTimeDialogFragmentListener) activity;
-                }
-            }
-        } catch (ClassCastException e) {
-            throw new ClassCastException(activity.toString()
-                    + " must implement DateTimeDialogListener");
-        }
-    }
-
-    @Override
-    public Dialog onCreateDialog(Bundle savedInstanceState) {
-
-        Builder builder = new AlertDialog.Builder(activity);
-
-        builder.setView(mView);
-
-        builder.setMessage(activity.getString(R.string.rec_set_date))
-                .setPositiveButton(activity.getString(R.string.rec_set),
-						new DialogInterface.OnClickListener() {
-							public void onClick(DialogInterface dialog, int id) {
-								mListener
-										.onDateTimePickerPositiveClick(DateTimeDialogFragment.this);
-							}
-						})
-                .setNegativeButton(activity.getString(R.string.rec_cancel),
-						new DialogInterface.OnClickListener() {
-							public void onClick(DialogInterface dialog, int id) {
-								mListener
-										.onDateTimePickerNegativeClick(DateTimeDialogFragment.this);
-								DateTimeDialogFragment.this.getDialog().cancel();
-							}
-						}); 
-
-        return builder.create();
-    }
-
-    @Override
-    public void onActivityCreated(Bundle savedInstanceState) {
-        super.onActivityCreated(savedInstanceState);
-        timePicker.setOnTimeChangedListener(this);
-    }
-
-    /**
-     * Returns the value of the given field after computing the field values by calling complete() first.
-     * @param field int
-     * @return int
-     */
-    public int get(final int field) {
-        return mCalendar.get(field);
-    }
-
-    /**
-     * Set the time picker style.
-     * @param is24HourView
-     */
-    public void setIs24HourView(boolean is24HourView) {
-        timePicker.setIs24HourView(is24HourView);
-    }
-
-    /**
-     * Show / hide the calendar view of the DatePicker.
-     * @param calendarView boolean
-     */
-    public void setCalendarViewShown(boolean calendarView) {
-        datePicker.setCalendarViewShown(calendarView);
-    }
-
-
-
-    /**
-     * Handles date change event.
-     * @param view DatePicker
-     * @param year changed year
-     * @param monthOfYear changed month of Year
-     * @param dayOfMonth changed day of Month
-     */
-    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
-        mCalendar.set(year, monthOfYear, dayOfMonth, mCalendar.get(Calendar.HOUR_OF_DAY), mCalendar.get(Calendar.MINUTE));
-    }
-
-    /**
-     * Handles on time changed events.
-     * @param view TimePicker
-     * @param hourOfDay changed hour
-     * @param minute changed minute
-     */
-    public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
-        mCalendar.set(mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH), hourOfDay, minute);
-    }
-
-    // MAYBE NEED IN FUTURE DEVELOPMENT
-    // UNUSED
-//    public long getDateTimeMillis() {
-//        return mCalendar.getTimeInMillis();
-//    }
-//    public boolean CalendarViewShown() {
-//        return datePicker.getCalendarViewShown();
-//    }
-//    public boolean is24HourView() {
-//        return timePicker.is24HourView();
-//    }
-//    public void updateDate(int year, int monthOfYear, int dayOfMonth) {
-//        datePicker.updateDate(year, monthOfYear, dayOfMonth);
-//    }
-//
-//    public void updateTime(int currentHour, int currentMinute) {
-//        timePicker.setCurrentHour(currentHour);
-//        timePicker.setCurrentMinute(currentMinute);
-//    }
-//
-//    public String getDateTime() {
-//        DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(activity);
-//        return dateFormat.format(mCalendar.getTime());
-//    }
+package de.tudarmstadt.informatik.hostage.ui.dialog;
+
+import android.annotation.SuppressLint;
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.app.AlertDialog.Builder;
+import android.app.Dialog;
+import android.app.DialogFragment;
+import android.content.DialogInterface;
+import android.content.res.Configuration;
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.DatePicker;
+import android.widget.DatePicker.OnDateChangedListener;
+import android.widget.TimePicker;
+import android.widget.TimePicker.OnTimeChangedListener;
+
+import java.util.Calendar;
+
+import de.tudarmstadt.informatik.hostage.R;
+import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
+/**
+ * Created by Julien on 16.02.14.
+ */
+@SuppressLint("ValidFragment")
+public class DateTimeDialogFragment extends DialogFragment implements OnDateChangedListener, OnTimeChangedListener {
+    // Define constants for date-time picker.
+    public final static int DATE_PICKER = 1;
+    public final static int TIME_PICKER = 2;
+    public final static int DATE_TIME_PICKER = 3;
+
+    // DatePicker reference
+    public DatePicker datePicker;
+
+    // TimePicker reference
+    public TimePicker timePicker;
+
+    // Calendar reference
+    private Calendar mCalendar;
+
+    // Define activity
+    private Activity activity;
+
+    // Define Dialog type
+    private int DialogType;
+
+    // Define Dialog view
+    private View mView;
+
+    // Constructor start
+    public DateTimeDialogFragment(Activity activity) {
+        this(activity, DATE_TIME_PICKER);
+    }
+
+    /**
+     * Constructor
+     * @param activity the activity
+     * @param DialogType, what kind of dialog it is (TIME_PICKER, DATE_PICKER, DATE_TIME_PICKER)
+     */
+    public DateTimeDialogFragment(Activity activity, int DialogType) {
+
+        this.activity = activity;
+        this.DialogType = DialogType;
+
+        LayoutInflater inflater = activity.getLayoutInflater();
+        mView = inflater.inflate(R.layout.date_time_dialog, null);
+
+        this.setupRootView(mView);
+
+    }
+
+
+    @Override
+    public void onConfigurationChanged(Configuration newConfig){
+        super.onConfigurationChanged(newConfig);
+        LayoutInflater inflater = LayoutInflater.from(this.activity);
+
+        ViewGroup container = (ViewGroup) this.mView.getParent();
+
+        container.removeView(this.mView);
+
+        mView = inflater.inflate(R.layout.date_time_dialog, null);
+        container.addView(mView);
+        this.setupRootView(mView);
+    }
+
+    /**
+     * Configure the root view in here.
+     * @param mView, root view
+     */
+    private void setupRootView(View mView){
+
+        mCalendar = Calendar.getInstance();
+
+        datePicker = (DatePicker) mView.findViewById(R.id.DatePicker);
+        datePicker.init(mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH), this);
+
+
+        timePicker = (TimePicker) mView.findViewById(R.id.TimePicker);
+
+        setIs24HourView(true);
+        setCalendarViewShown(false);
+
+        switch (DialogType) {
+            case DATE_PICKER:
+                timePicker.setVisibility(View.GONE);
+                break;
+            case TIME_PICKER:
+                datePicker.setVisibility(View.GONE);
+                break;
+        }
+    }
+
+    /**
+     * Set the current date.
+     * @param timeInMillis, date in milliseconds
+     */
+    public void setDate(long timeInMillis){
+        Calendar calendar = Calendar.getInstance();
+        calendar.setTimeInMillis (timeInMillis);
+
+        int year    = calendar.get(Calendar.YEAR) ;
+        int month   = calendar.get(Calendar.MONTH);
+        int day     = calendar.get(Calendar.DATE);
+        int hour    = calendar.get(Calendar.HOUR);
+        int min     = calendar.get(Calendar.MINUTE);
+
+        datePicker.updateDate(year, month, day);
+        timePicker.setCurrentHour(hour);
+        timePicker.setCurrentMinute(min);
+    }
+
+    /**
+     * Returns the current selected date.
+     * @return long, date in milliseconds
+     */
+   public long getDate(){
+	   
+       int day = datePicker.getDayOfMonth();
+       int month = datePicker.getMonth();
+       int year =  datePicker.getYear();
+       
+       int hourOfDay = timePicker.getCurrentHour();
+       int minute = timePicker.getCurrentMinute();
+
+       Calendar calendar = Calendar.getInstance();
+
+       calendar.set(year, month, day, hourOfDay, minute);
+
+       return calendar.getTime().getTime();
+   }
+
+    /**
+     * The listener which will be called if the user tapped "cancel" or "ok"
+     */
+    public interface DateTimeDialogFragmentListener {
+        /**
+         * Called if the user tapped "ok"
+         * @param dialog {@link DateTimeDialogFragment DateTimeDialogFragment}
+         */
+        public void onDateTimePickerPositiveClick(DateTimeDialogFragment dialog);
+
+        /**
+         * Called if the user tapped "cancel"
+         * @param dialog {@link DateTimeDialogFragment DateTimeDialogFragment}
+         */
+        public void onDateTimePickerNegativeClick(DateTimeDialogFragment dialog);
+    }
+    private DateTimeDialogFragmentListener mListener;
+
+    /**
+     * Set the user interaction listener.
+     * @param listener DateTimeDialogFragmentListener
+     */
+    public void setDateChangeListener(DateTimeDialogFragmentListener listener){
+        this.mListener = listener;
+    }
+
+    @Override
+    public void onAttach(Activity activity) {
+        super.onAttach(activity);
+        try {
+            if (this.mListener == null){
+                if (activity.getClass().equals(MainActivity.class)){
+                    mListener = (DateTimeDialogFragmentListener) (((MainActivity)activity).getDisplayedFragment());
+                } else {
+                    mListener = (DateTimeDialogFragmentListener) activity;
+                }
+            }
+        } catch (ClassCastException e) {
+            throw new ClassCastException(activity.toString()
+                    + " must implement DateTimeDialogListener");
+        }
+    }
+
+    @Override
+    public Dialog onCreateDialog(Bundle savedInstanceState) {
+
+        Builder builder = new AlertDialog.Builder(activity);
+
+        builder.setView(mView);
+
+        builder.setMessage(activity.getString(R.string.rec_set_date))
+                .setPositiveButton(activity.getString(R.string.rec_set),
+						new DialogInterface.OnClickListener() {
+							public void onClick(DialogInterface dialog, int id) {
+								mListener
+										.onDateTimePickerPositiveClick(DateTimeDialogFragment.this);
+							}
+						})
+                .setNegativeButton(activity.getString(R.string.rec_cancel),
+						new DialogInterface.OnClickListener() {
+							public void onClick(DialogInterface dialog, int id) {
+								mListener
+										.onDateTimePickerNegativeClick(DateTimeDialogFragment.this);
+								DateTimeDialogFragment.this.getDialog().cancel();
+							}
+						}); 
+
+        return builder.create();
+    }
+
+    @Override
+    public void onActivityCreated(Bundle savedInstanceState) {
+        super.onActivityCreated(savedInstanceState);
+        timePicker.setOnTimeChangedListener(this);
+    }
+
+    /**
+     * Returns the value of the given field after computing the field values by calling complete() first.
+     * @param field int
+     * @return int
+     */
+    public int get(final int field) {
+        return mCalendar.get(field);
+    }
+
+    /**
+     * Set the time picker style.
+     * @param is24HourView
+     */
+    public void setIs24HourView(boolean is24HourView) {
+        timePicker.setIs24HourView(is24HourView);
+    }
+
+    /**
+     * Show / hide the calendar view of the DatePicker.
+     * @param calendarView boolean
+     */
+    public void setCalendarViewShown(boolean calendarView) {
+        datePicker.setCalendarViewShown(calendarView);
+    }
+
+
+
+    /**
+     * Handles date change event.
+     * @param view DatePicker
+     * @param year changed year
+     * @param monthOfYear changed month of Year
+     * @param dayOfMonth changed day of Month
+     */
+    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
+        mCalendar.set(year, monthOfYear, dayOfMonth, mCalendar.get(Calendar.HOUR_OF_DAY), mCalendar.get(Calendar.MINUTE));
+    }
+
+    /**
+     * Handles on time changed events.
+     * @param view TimePicker
+     * @param hourOfDay changed hour
+     * @param minute changed minute
+     */
+    public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
+        mCalendar.set(mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH), hourOfDay, minute);
+    }
+
+    // MAYBE NEED IN FUTURE DEVELOPMENT
+    // UNUSED
+//    public long getDateTimeMillis() {
+//        return mCalendar.getTimeInMillis();
+//    }
+//    public boolean CalendarViewShown() {
+//        return datePicker.getCalendarViewShown();
+//    }
+//    public boolean is24HourView() {
+//        return timePicker.is24HourView();
+//    }
+//    public void updateDate(int year, int monthOfYear, int dayOfMonth) {
+//        datePicker.updateDate(year, monthOfYear, dayOfMonth);
+//    }
+//
+//    public void updateTime(int currentHour, int currentMinute) {
+//        timePicker.setCurrentHour(currentHour);
+//        timePicker.setCurrentMinute(currentMinute);
+//    }
+//
+//    public String getDateTime() {
+//        DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(activity);
+//        return dateFormat.format(mCalendar.getTime());
+//    }
 }

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

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.ui2.fragment;
+package de.tudarmstadt.informatik.hostage.ui.fragment;
 
 import android.app.Activity;
 import android.app.Fragment;

+ 3 - 3
src/de/tudarmstadt/informatik/hostage/ui/fragment/ConnectionInfoDialogFragment.java

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.ui2.fragment;
+package de.tudarmstadt.informatik.hostage.ui.fragment;
 
 import android.app.Activity;
 import android.app.AlertDialog;
@@ -16,8 +16,8 @@ import android.widget.TextView;
 import java.util.ArrayList;
 
 import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.ui2.model.LogFilter;
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
+import de.tudarmstadt.informatik.hostage.ui.model.LogFilter;
+import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
 
 /**
  * Created by Fabio Arnold on 03.03.14.

+ 22 - 163
src/de/tudarmstadt/informatik/hostage/ui/fragment/HomeFragment.java

@@ -1,7 +1,4 @@
-package de.tudarmstadt.informatik.hostage.ui2.fragment;
-
-import com.google.android.gms.analytics.HitBuilders;
-import com.google.android.gms.analytics.Tracker;
+package de.tudarmstadt.informatik.hostage.ui.fragment;
 
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -18,7 +15,6 @@ import android.content.DialogInterface;
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.content.SharedPreferences;
-import android.net.Uri;
 import android.os.Bundle;
 import android.support.v4.content.LocalBroadcastManager;
 import android.view.LayoutInflater;
@@ -29,94 +25,59 @@ import android.widget.ImageView;
 import android.widget.Switch;
 import android.widget.TextView;
 
-import de.tudarmstadt.informatik.hostage.Hostage;
-import de.tudarmstadt.informatik.hostage.HostageApplication;
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
 import de.tudarmstadt.informatik.hostage.persistence.ProfileManager;
 import de.tudarmstadt.informatik.hostage.model.Profile;
 import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
-import de.tudarmstadt.informatik.hostage.ui2.model.LogFilter;
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
-import de.tudarmstadt.informatik.hostage.ui2.fragment.opengl.ThreatIndicatorGLRenderer;
-import de.tudarmstadt.informatik.hostage.system.Device;
+import de.tudarmstadt.informatik.hostage.ui.LogFilter;
+import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
+import de.tudarmstadt.informatik.hostage.ui.fragment.opengl.ThreatIndicatorGLRenderer;
 
 /**
- * This fragments displays the current hostage state and attacks on the device in form of an animation and simple view components
- *
  * @author Alexander Brakowski
  * @created 13.01.14 19:06
  */
 
-public class HomeFragment extends TrackerFragment {
+public class HomeFragment extends Fragment {
 
-	/**
-	 * View objects from the layout
-	 */
 	private Switch mHomeSwitchConnection;
+
 	private TextView mHomeTextName;
+
 	private TextView mHomeTextSecurity;
+
 	private TextView mHomeTextAttacks;
+
 	private TextView mHomeTextProfile;
+
 	private TextView mHomeTextProfileHeader;
+
 	private ImageView mHomeProfileImage;
+
 	private ImageView mHomeConnectionInfoButton;
+
 	private View mRootView;
 
-	/**
-	 * This handles all the broadcasts from the Hostage service
-	 */
 	private BroadcastReceiver mReceiver;
 
-	/**
-	 * A change listener for the monitor switch
-	 */
 	private CompoundButton.OnCheckedChangeListener mSwitchChangeListener = null;
 
-
 	private int mDefaultTextColor;
 
-	/**
-	 * A reference to the profile manager
-	 */
 	private ProfileManager mProfileManager;
 
-	/**
-	 * A shared preference that holds all the connection info of the current network connection
-	 */
 	private SharedPreferences mConnectionInfo;
 
-    /**
-     * Hold the shared preferences for the app
-     */
-    private SharedPreferences mSharedPreferences;
-
-	/**
-	 * An Helper to access the sqllite database with all the records
-	 */
 	private HostageDBOpenHelper mDbHelper;
 
-	/**
-	 * Holds a state if the broadcast receiver is registered to the hostage service
- 	 */
 	private boolean mReceiverRegistered;
 
-	/**
-	 * Holds a state if the hostage service is active
-	 */
-	private boolean isActive = false;
+	private boolean mRestoredFromSaved = false;
 
-	/**
-	 * Holds a state if the device is currently connected to a network
-	 */
+	private boolean isActive = false;
 	private boolean isConnected = false;
 
-	public HomeFragment() {
-	}
-
-	/**
-	 * Looks up all the neccessary views in the layout
-	 */
 	private void assignViews() {
 		mHomeSwitchConnection = (Switch) mRootView.findViewById(R.id.home_switch_connection);
 		mHomeTextName = (TextView) mRootView.findViewById(R.id.home_text_name);
@@ -128,9 +89,6 @@ public class HomeFragment extends TrackerFragment {
 		mHomeConnectionInfoButton = (ImageView) mRootView.findViewById(R.id.home_button_connection_info);
 	}
 
-	/**
-	 * Registers the broadcast receiver with the hostage service
-	 */
 	private void registerBroadcastReceiver() {
 		if (!mReceiverRegistered) {
 			LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mReceiver, new IntentFilter(getString(R.string.broadcast)));
@@ -138,9 +96,6 @@ public class HomeFragment extends TrackerFragment {
 		}
 	}
 
-	/**
-	 * Unregisters the broadcast receiver
-	 */
 	private void unregisterBroadcastReceiver() {
 		if (mReceiverRegistered) {
 			LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
@@ -148,12 +103,9 @@ public class HomeFragment extends TrackerFragment {
 		}
 	}
 
-	/**
-	 * Sets the view state to not active.
-	 * This means hiding and graying out all the informations in the view, that are not important, if the service is not active.
-	 *
-	 * @param initial indicates that the method was called on creation of view
-	 */
+	public HomeFragment() {
+	}
+
 	public void setStateNotActive(boolean initial) {
 		mHomeTextName.setTextColor(getResources().getColor(R.color.light_grey));
 		mHomeTextSecurity.setTextColor(getResources().getColor(R.color.light_grey));
@@ -169,26 +121,14 @@ public class HomeFragment extends TrackerFragment {
 		isActive = false;
 	}
 
-	/**
-	 * Alias for calling setStateNotActive with the initial value being false
-	 */
 	public void setStateNotActive() {
 		setStateNotActive(false);
 	}
 
-	/**
-	 * Alias for calling setStateActive with the initial value being false
-	 */
 	public void setStateActive() {
 		setStateActive(false);
 	}
 
-	/**
-	 * Sets the state of the view to active.
-	 * That means that all the information showing the active state of the hostage service is being displayed.
-	 *
-	 * @param initial indicates that the method was called on creation of view
-	 */
 	public void setStateActive(boolean initial) {
 		mHomeTextAttacks.setVisibility(View.VISIBLE);
 		mHomeTextSecurity.setVisibility(View.VISIBLE);
@@ -205,9 +145,6 @@ public class HomeFragment extends TrackerFragment {
 		isActive = true;
 	}
 
-	/**
-	 * Sets the state of the view to not connected by hiding information about the attacks.
-	 */
 	public void setStateNotConnected() {
 		mHomeTextSecurity.setVisibility(View.INVISIBLE);
 		mHomeTextAttacks.setVisibility(View.INVISIBLE);
@@ -220,9 +157,6 @@ public class HomeFragment extends TrackerFragment {
 		isConnected = false;
 	}
 
-	/**
-	 * Sets the state of the view to connected by showing informations about attacks
-	 */
 	public void setStateConnected() {
 		mHomeTextProfile.setVisibility(View.VISIBLE);
 		mHomeTextProfileHeader.setVisibility(View.VISIBLE);
@@ -231,14 +165,6 @@ public class HomeFragment extends TrackerFragment {
 		isConnected = true;
 	}
 
-	/**
-	 * Updates the view.
-	 *
-	 * That means: updating the number of attacks on the view,
-	 *             updating the threat level,
-	 *             updating the connection state,
-	 *             updating the monitoring state
-	 */
 	public void updateUI() {
 		Profile profile = mProfileManager.getCurrentActivatedProfile();
 		if (profile != null) {
@@ -246,10 +172,7 @@ public class HomeFragment extends TrackerFragment {
 			mHomeProfileImage.setImageBitmap(profile.getIconBitmap());
 		}
 
-		// if the device is connected to an network display the network name
-        //SK: Temporary Bugfix
-		//if (HelperUtils.isNetworkAvailable(getActivity())) {
-        if (HelperUtils.isWifiConnected(getActivity())) {
+		if (HelperUtils.isNetworkAvailable(getActivity())) {
 			setStateConnected();
 			String ssid = mConnectionInfo.getString(getString(R.string.connection_info_ssid), "\"\"");
 			mHomeTextName.setText(ssid.substring(1,ssid.length() - 1));
@@ -261,7 +184,6 @@ public class HomeFragment extends TrackerFragment {
 		int totalAttacks = mDbHelper.numBssidSeen(mConnectionInfo.getString(getString(R.string.connection_info_bssid), null));
 		ThreatIndicatorGLRenderer.ThreatLevel threatLevel = ThreatIndicatorGLRenderer.ThreatLevel.NOT_MONITORING;
 
-		// decides which threat level to display
 		if (MainActivity.getInstance().getHostageService() != null) {
 			if (MainActivity.getInstance().getHostageService().hasRunningListeners()) {
 				hasActiveListeners = true;
@@ -276,7 +198,6 @@ public class HomeFragment extends TrackerFragment {
 			}
 		}
 
-		// if the monitoring is running show the information
 		if (hasActiveListeners) {
 			setStateActive(true);
 
@@ -317,9 +238,6 @@ public class HomeFragment extends TrackerFragment {
 		}
 	}
 
-	/**
-	 * {@inheritDoc}
-	 */
 	@Override
 	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 		super.onCreateView(inflater, container, savedInstanceState);
@@ -351,11 +269,9 @@ public class HomeFragment extends TrackerFragment {
 
 		mDefaultTextColor = mHomeTextName.getCurrentTextColor();
 
-		// sets state and connection initially to off
 		setStateNotActive(true);
 		setStateNotConnected();
 
-		// register the broadcast receiver
 		mReceiver = new BroadcastReceiver() {
 			@SuppressLint("NewApi")
 			@Override
@@ -368,21 +284,14 @@ public class HomeFragment extends TrackerFragment {
 
 		updateUI();
 
-		// connects the switch listener to the switch button
 		mHomeSwitchConnection = (Switch) mRootView.findViewById(R.id.home_switch_connection);
 		mHomeSwitchConnection.setSaveEnabled(false);
 
 		if (mSwitchChangeListener == null) {
 			mSwitchChangeListener = new CompoundButton.OnCheckedChangeListener() {
 				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
-					// displays a alert dialog if no network is available
-
-                    //SK: Temporary bugfix to limit to wifi
-					//if (!HelperUtils.isNetworkAvailable(getActivity())) {
-                    if (!HelperUtils.isWifiConnected(getActivity())) {
-
-						//new AlertDialog.Builder(getActivity()).setTitle(R.string.information).setMessage(R.string.network_not_connected_msg)
-                        new AlertDialog.Builder(getActivity()).setTitle(R.string.information).setMessage(R.string.wifi_not_connected_msg)
+					if (!HelperUtils.isNetworkAvailable(getActivity())) {
+						new AlertDialog.Builder(getActivity()).setTitle(R.string.information).setMessage(R.string.network_not_connected_msg)
 								.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
 									public void onClick(DialogInterface dialog, int which) {
 
@@ -393,47 +302,10 @@ public class HomeFragment extends TrackerFragment {
 						setStateNotConnected();
 					} else {
 						if (isChecked) {
-
 							boolean protocolActivated = false;
-
-                            mSharedPreferences = getActivity().getSharedPreferences(getString(R.string.shared_preference_path), Hostage.MODE_PRIVATE);
-
-
-                            if(mSharedPreferences.getBoolean( "isFirstEmulation", true)) {
-                                //Notify Porthack is not installed to user
-                                if(!Device.isPorthackInstalled()) {
-                                    new AlertDialog.Builder(getActivity())
-                                            .setTitle(R.string.information)
-                                            .setMessage(R.string.no_portbinder_msg2)
-                                            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
-                                                public void onClick(DialogInterface dialog, int which) {
-
-                                                }
-                                            })
-                                            .setNegativeButton(R.string.help, new DialogInterface.OnClickListener() {
-                                                public void onClick(DialogInterface dialog, int which) {
-                                                    MainActivity.getInstance().displayView(MainActivity.MainMenuItem.SETTINGS.getValue());
-
-
-                                                }
-                                            })
-
-                                            .setIcon(android.R.drawable.ic_dialog_info).show();
-
-                                }
-
-                                // Disable hint for 'first' time emulation notification
-                                SharedPreferences.Editor editor = mSharedPreferences.edit();
-                                editor.putBoolean("isFirstEmulation", false);
-                                editor.commit();
-
-                            }
-
 							if (ProfileManager.getInstance().getCurrentActivatedProfile() == null) {
-								// starts all services
 								MainActivity.getInstance().startMonitorServices(Arrays.asList(getResources().getStringArray(R.array.protocols)));
 							} else {
-								// starts the services that are actived in the current profile
 								ProfileManager profileManager = ProfileManager.getInstance();
 
 								if (profileManager.isRandomActive()) {
@@ -453,7 +325,6 @@ public class HomeFragment extends TrackerFragment {
 							if (protocolActivated) {
 								setStateActive();
 							} else {
-								// no protocol was started, so show alert dialog
 								new AlertDialog.Builder(getActivity()).setTitle(R.string.information).setMessage(R.string.profile_no_services_msg)
 										.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
 											public void onClick(DialogInterface dialog, int which) {
@@ -464,7 +335,6 @@ public class HomeFragment extends TrackerFragment {
 								setStateNotActive();
 							}
 						} else {
-							// stop hostage service and all listeners
 							if (MainActivity.getInstance().getHostageService() != null) {
 								MainActivity.getInstance().getHostageService().stopListeners();
 								MainActivity.getInstance().stopAndUnbind();
@@ -477,16 +347,14 @@ public class HomeFragment extends TrackerFragment {
 		}
 		mHomeSwitchConnection.setOnCheckedChangeListener(mSwitchChangeListener);
 
-		// connects the profile text an click listener
 		mRootView.findViewById(R.id.home_profile_details).setOnClickListener(new View.OnClickListener() {
 			@Override
 			public void onClick(View v) {
 				Fragment fragment = new ProfileManagerFragment();
-				MainActivity.getInstance().injectFragment(fragment);
+				MainActivity.getInstance().injectFragment(fragment, false);
 			}
 		});
 
-		// connect the attacks text to an click listener
 		View.OnClickListener attackClickListener = new View.OnClickListener() {
 			@Override
 			public void onClick(View v) {
@@ -513,18 +381,12 @@ public class HomeFragment extends TrackerFragment {
 		return mRootView;
 	}
 
-	/**
-	 * {@inheritDoc}
-	 */
 	@Override
 	public void onStop() {
 		super.onStop();
 		unregisterBroadcastReceiver();
 	}
 
-	/**
-	 * {@inheritDoc}
-	 */
 	@Override
 	public void onStart() {
 		super.onStart();
@@ -532,9 +394,6 @@ public class HomeFragment extends TrackerFragment {
 		updateUI();
 	}
 
-	/**
-	 * {@inheritDoc}
-	 */
 	@Override
 	public void onDestroy() {
 		super.onDestroy();

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

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.ui2.fragment;
+package de.tudarmstadt.informatik.hostage.ui.fragment;
 
 import android.content.SharedPreferences;
 import android.os.Bundle;

+ 4 - 1
src/de/tudarmstadt/informatik/hostage/ui/fragment/ProfileEditFragment.java

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.ui2.fragment;
+package de.tudarmstadt.informatik.hostage.ui.fragment;
 
 import android.app.ActionBar;
 import android.app.Activity;
@@ -288,6 +288,9 @@ public class ProfileEditFragment extends PreferenceFragment implements
 		super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
 
 		if(resultCode == Activity.RESULT_OK){
+
+			assert selectedImage != null;
+
 			Cursor cursor = getActivity().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
 					new String[]{
 							MediaStore.Images.Media.DATA,

+ 5 - 5
src/de/tudarmstadt/informatik/hostage/ui/fragment/ProfileManagerFragment.java

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.ui2.fragment;
+package de.tudarmstadt.informatik.hostage.ui.fragment;
 
 import android.app.Fragment;
 import android.content.Intent;
@@ -20,10 +20,10 @@ import de.tudarmstadt.informatik.hostage.Hostage;
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.persistence.ProfileManager;
 import de.tudarmstadt.informatik.hostage.model.Profile;
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
-import de.tudarmstadt.informatik.hostage.ui2.activity.ProfileEditActivity;
-import de.tudarmstadt.informatik.hostage.ui2.adapter.ProfileManagerListAdapter;
-import de.tudarmstadt.informatik.hostage.ui2.swipelist.SwipeListView;
+import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
+import de.tudarmstadt.informatik.hostage.ui.activity.ProfileEditActivity;
+import de.tudarmstadt.informatik.hostage.ui.adapter.ProfileManagerListAdapter;
+import de.tudarmstadt.informatik.hostage.ui.swipelist.SwipeListView;
 
 /**
  * Displays a list of all available profiles and allows invocation of the edit activity for an profile

+ 3 - 2
src/de/tudarmstadt/informatik/hostage/ui/fragment/RecordDetailFragment.java

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.ui2.fragment;
+package de.tudarmstadt.informatik.hostage.ui.fragment;
 
 import java.util.ArrayList;
 import java.util.Date;
@@ -20,7 +20,8 @@ import android.widget.ScrollView;
 import android.widget.TextView;
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.logging.Record;
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
+import de.tudarmstadt.informatik.hostage.ui.LogFilter;
+import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
 import de.tudarmstadt.informatik.hostage.logging.MessageRecord;
 import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
 

+ 1438 - 1438
src/de/tudarmstadt/informatik/hostage/ui/fragment/RecordOverviewFragment.java

@@ -1,1438 +1,1438 @@
-package de.tudarmstadt.informatik.hostage.ui2.fragment;
-
-import android.annotation.SuppressLint;
-import android.app.Activity;
-import android.app.AlertDialog;
-import android.app.FragmentManager;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.content.Intent;
-import android.content.SharedPreferences;
-import android.os.Bundle;
-import android.preference.PreferenceManager;
-import android.util.Log;
-import android.view.LayoutInflater;
-import android.view.Menu;
-import android.view.MenuInflater;
-import android.view.MenuItem;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.ExpandableListView;
-import android.widget.ImageButton;
-import android.widget.ProgressBar;
-import android.widget.Toast;
-
-import com.google.android.gms.maps.model.LatLng;
-
-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.List;
-import java.util.Locale;
-import java.util.Random;
-
-import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.logging.AttackRecord;
-import de.tudarmstadt.informatik.hostage.logging.LogExport;
-import de.tudarmstadt.informatik.hostage.logging.MessageRecord;
-import de.tudarmstadt.informatik.hostage.logging.NetworkRecord;
-import de.tudarmstadt.informatik.hostage.logging.Record;
-import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
-import de.tudarmstadt.informatik.hostage.sync.bluetooth.BluetoothSyncActivity;
-import de.tudarmstadt.informatik.hostage.sync.nfc.NFCSync;
-import de.tudarmstadt.informatik.hostage.sync.tracing.TracingSyncActivity;
-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.model.LogFilter;
-import de.tudarmstadt.informatik.hostage.ui2.model.LogFilter.SortType;
-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 = MainActivity.getContext().getString(R.string.BSSID);
-	static final String FILTER_MENU_TITLE_ESSID = MainActivity.getContext().getString(R.string.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);
-
-    static final int DEFAULT_GROUPING_KEY_INDEX = 0;
-
-    private boolean wasBelowTimePicker;
-
-    private LogFilter filter;
-    private boolean showFilterButton;
-    private View rootView;
-
-    private int mListPosition = -1;
-    private int mItemPosition = -1;
-
-    public String groupingKey;
-
-    private ExpandableListView expListView;
-    private ProgressBar spinner;
-
-    private Toast noDataNotificationToast;
-
-    HostageDBOpenHelper dbh;
-
-    private String sectionToOpen = "";
-    private ArrayList<Integer> openSections;
-
-	private SharedPreferences pref;
-
-    Thread loader;
-
-
-    /* DATE CONVERSION STUFF*/
-    static final DateFormat localisedDateFormatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
-    // DATE WHICH PATTERN
-    static final String localDatePattern  = ((SimpleDateFormat)localisedDateFormatter).toLocalizedPattern();
-    static final String groupingDatePattern  = "MMMM yyyy";
-
-    // INSERT HERE YOUR DATE PATERN
-    static final SimpleDateFormat groupingDateFormatter = new SimpleDateFormat(groupingDatePattern);
-    static final Calendar calendar = Calendar.getInstance();
-
-    // DATE STRINGS
-    static final String TODAY = MainActivity.getInstance().getResources().getString( R.string.TODAY);
-    static final String YESTERDAY = MainActivity.getInstance().getResources().getString( R.string.YESTERDAY);
-
-
-
-
-    /**
-     * Constructor
-     */
-    public RecordOverviewFragment(){}
-
-
-    @Override
-    public void onCreate(Bundle savedInstanceState) {
-        super.onCreate(savedInstanceState);
-        setHasOptionsMenu(true);
-    }
-
-    @Override
-	public View onCreateView(LayoutInflater inflater, ViewGroup container,
-             Bundle savedInstanceState) {
-
-		setHasOptionsMenu(true);
-		getActivity().setTitle(getResources().getString(R.string.drawer_records));
-
-		dbh = new HostageDBOpenHelper(this.getActivity().getBaseContext());
-	    pref = PreferenceManager.getDefaultSharedPreferences(getActivity());
-
-	    // 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(DEFAULT_GROUPING_KEY_INDEX);
-
-	    this.setShowFilterButton(!this.filter.isNotEditable());
-
-		View rootView = inflater.inflate(this.getLayoutId(), container, false);
-        this.rootView = rootView;
-		ExpandableListView mylist = (ExpandableListView) rootView.findViewById(R.id.loglistview);
-
-        this.spinner =(ProgressBar) rootView.findViewById(R.id.progressBar1);
-        this.spinner.setVisibility(View.GONE);
-
-		this.expListView = mylist;
-
-        this.initialiseListView();
-
-        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;
-	 }
-
-
-    /**Initialises the expandable list view in a backgorund thread*/
-    private void initialiseListView(){
-        if (loader != null) loader.interrupt();
-
-        this.spinner.setVisibility(View.VISIBLE);
-
-        loader = new Thread(new Runnable(){
-
-            private void updateUI(final RecordListAdapter currentAdapter)
-            {
-                if(loader.isInterrupted()){
-                    return;
-                }
-                Activity activity = RecordOverviewFragment.this.getActivity();
-
-                if (activity != null){
-                    activity.runOnUiThread(new Runnable() {
-                        @Override
-                        public void run() {
-                            RecordOverviewFragment.this.expListView.setAdapter(currentAdapter);
-                            // Update view and remove loading spinner etc...
-                            RecordListAdapter adapter = (RecordListAdapter) RecordOverviewFragment.this.expListView.getExpandableListAdapter();
-
-                            if (adapter != null){
-                                adapter.notifyDataSetChanged();
-
-                                if (adapter.getGroupCount() >= 1){
-                                    RecordOverviewFragment.this.expListView.expandGroup(DEFAULT_GROUPING_KEY_INDEX);
-                                } else {
-                                    RecordOverviewFragment.this.setSectionToOpen(RecordOverviewFragment.this.sectionToOpen);
-                                }
-                            }
-
-                            if (RecordOverviewFragment.this.openSections != null && RecordOverviewFragment.this.openSections.size() != 0){
-                                for (int i = 0; i < RecordOverviewFragment.this.openSections.size(); i++){
-                                    int index = RecordOverviewFragment.this.openSections.get(i);
-                                    RecordOverviewFragment.this.expListView.expandGroup(index);
-                                }
-                            } else {
-                                RecordOverviewFragment.this.openSections = new ArrayList<Integer>();
-                            }
-
-                            if (mListPosition != -1 && mItemPosition != -1)
-                                RecordOverviewFragment.this.expListView.setSelectedChild(mListPosition, mItemPosition, true);
-
-                            mListPosition = -1;
-                            mItemPosition = -1;
-                            registerListClickCallback(RecordOverviewFragment.this.expListView);
-                            RecordOverviewFragment.this.spinner.setVisibility(View.GONE);
-                            RecordOverviewFragment.this.actualiseFilterButton();
-                            RecordOverviewFragment.this.showEmptyDataNotification();
-                        }
-                    });
-                }
-            }
-
-            private RecordListAdapter doInBackground()
-            {
-                return populateListViewFromDB(RecordOverviewFragment.this.expListView);
-            }
-
-            @Override
-            public void run()
-            {
-                //RecordOverviewFragment.this.addRecordToDB(40, 10, 4);
-                updateUI(doInBackground());
-            }
-
-        });
-
-        loader.start();
-
-        this.actualiseFilterButton();
-    }
-
-
-    /**
-    *  Returns the Fragment layout ID
-    *  @return int The fragment layout ID
-    * */
-    public int getLayoutId(){
-        return R.layout.fragment_record_list;
-    }
-
-    /**
-    * Gets called if the user clicks on item in the filter menu.
-    *
-    * @param  item {@link AbstractPopupItem AbstractPopupItem }
-    * */
-	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.actualiseListViewInBackground();
-            }
-            if(title.equals(FILTER_MENU_TITLE_TIMESTAMP_BELOW)){
-                this.openTimestampToFilterDialog();
-            }
-            if(title.equals(FILTER_MENU_TITLE_TIMESTAMP_ABOVE)){
-                this.openTimestampFromFilterDialog();
-            }
-        }
-		//return super.onOptionsItemSelected(item);
-	}
-
-
-
-    @Override
-    public void onStart() {
-        super.onStart();
-        if (this.expListView.getExpandableListAdapter() != null){
-            if (this.expListView.getExpandableListAdapter().getGroupCount() == 1){
-                this.expListView.expandGroup(0);
-            } else {
-                this.setSectionToOpen(this.sectionToOpen);
-            }
-        }
-
-    }
-
-	@Override
-	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
-		// Inflate the menu items for use in the action bar
-		inflater.inflate(R.menu.records_overview_actions, menu);
-	}
-
-	@Override
-	public boolean onOptionsItemSelected(MenuItem item) {
-		switch (item.getItemId()) {
-			case R.id.records_action_synchronize:
-
-				AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
-				builder.setTitle(MainActivity.getInstance().getString(R.string.rec_sync_rec));
-				builder.setItems(new String[]{
-						MainActivity.getInstance().getString(R.string.rec_via_bt),
-						MainActivity.getInstance().getString(R.string.rec_via_nfc),
-						MainActivity.getInstance().getString(R.string.rec_via_online)
-				}, new DialogInterface.OnClickListener() {
-					@Override
-					public void onClick(DialogInterface dialog, int position) {
-						switch(position){
-							case 0:
-								getActivity().startActivity(new Intent(getActivity(), BluetoothSyncActivity.class));
-								break;
-							case 1:
-								getActivity().startActivity(new Intent(getActivity(), NFCSync.class));
-								break;
-
-							case 2:
-								getActivity().startActivity(new Intent(getActivity(), TracingSyncActivity.class));
-								break;
-						}
-					}
-				});
-				builder.create();
-				builder.show();
-
-
-				return true;
-			case R.id.records_action_export:
-				AlertDialog.Builder builderExport = new AlertDialog.Builder(getActivity());
-				builderExport.setTitle(MainActivity.getInstance().getString(R.string.rec_choose_export_format));
-				builderExport.setItems(R.array.format, new DialogInterface.OnClickListener() {
-					@Override
-					public void onClick(DialogInterface dialog, int position) {
-						//RecordOverviewFragment.this.exportDatabase(position);
-						Intent intent = new Intent(getActivity(), LogExport.class);
-						intent.setAction(LogExport.ACTION_EXPORT_DATABASE);
-						intent.putExtra(LogExport.FORMAT_EXPORT_DATABASE, position);
-
-						RecordOverviewFragment.this.getActivity().startService(intent);
-					}
-				});
-				builderExport.create();
-				builderExport.show();
-
-				return true;
-		}
-
-		return false;
-	}
-
-	/*****************************
-	 *
-	 * 			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().get(ESSID_INDEX);
-  	}
-
-
-	/*****************************
-	 *
-	 *          ListView Stuff
-	 *
-	 * ***************************/
-
-    /**
-    *  Reloads the data in the ExpandableListView for the given filter object.
-    *  @param  mylist {@link ExpandableListView ExpandableListView}
-    * */
-	private RecordListAdapter populateListViewFromDB(ExpandableListView mylist) {
-        ArrayList<String> groupTitle = new ArrayList<String>();
-
-        HashMap<String, ArrayList<ExpandableListItem>> sectionData = this.fetchDataForFilter(this.filter, groupTitle);
-
-        RecordListAdapter adapter = null;
-        if (mylist.getAdapter() != null && mylist.getAdapter() instanceof RecordListAdapter){
-            adapter = (RecordListAdapter) mylist.getAdapter();
-            adapter.setData(sectionData);
-            adapter.setSectionHeader(groupTitle);
-        } else {
-            adapter = new RecordListAdapter( RecordOverviewFragment.this.getApplicationContext(), groupTitle, sectionData);
-        }
-
-        return adapter;
-	}
-
-    private HashMap<String, ArrayList<ExpandableListItem>> fetchDataForFilter(LogFilter filter, ArrayList<String> groupTitle){
-        HashMap<String, ArrayList<ExpandableListItem>> sectionData = new HashMap<String, ArrayList<ExpandableListItem>>();
-
-        ArrayList<Record> data = dbh.getRecordsForFilter(filter == null ? this.filter : filter);
-
-        // Adding Items to ListView
-        String keys[] = new String[] { RecordOverviewFragment.this.getString(R.string.RecordBSSID), RecordOverviewFragment.this.getString(R.string.RecordSSID), RecordOverviewFragment.this.getString(R.string.RecordProtocol), RecordOverviewFragment.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++;
-        }
-
-        if (groupTitle == null){
-            groupTitle = new ArrayList<String>();
-        } else {
-            groupTitle.clear();
-        }
-
-
-        for (Record val : data) {
-            // DO GROUPING IN HERE
-            HashMap<String, String> map = new HashMap<String, String>();
-            map.put(RecordOverviewFragment.this.getString(R.string.RecordBSSID), val.getBssid());
-            map.put(RecordOverviewFragment.this.getString(R.string.RecordSSID), val.getSsid());
-            map.put(RecordOverviewFragment.this.getString(R.string.RecordProtocol), val.getProtocol());
-            map.put(RecordOverviewFragment.this.getString(R.string.RecordTimestamp),
-                    RecordOverviewFragment.this.getDateAsString(val.getTimestamp()));
-
-            ExpandableListItem item = new ExpandableListItem();
-            item.setData(map);
-
-            item.setId_Mapping(mapping);
-
-            item.setTag(val.getAttack_id());
-
-            String groupID = RecordOverviewFragment.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);
-        }
-
-        if (this.groupingKey.equals(this.groupingTitles().get(DEFAULT_GROUPING_KEY_INDEX))){
-            Collections.sort(groupTitle,new DateStringComparator());
-        } else {
-            Collections.sort(groupTitle, new Comparator<String>() {
-                @Override
-                public int compare(String s1, String s2) {
-                    return s1.compareToIgnoreCase(s2);
-                }
-            });
-        }
-
-        return sectionData;
-    }
-
-    /**
-     * The DateStringComparator compares formatted date strings by converting the into date.
-     * This class  is mainly used for grouping the records by their timestamp.
-     */
-    class DateStringComparator implements Comparator<String>
-    {
-        public int compare(String lhs, String rhs)
-        {
-            Date date1 = RecordOverviewFragment.this.convertStringToDate(lhs);
-            Date date2 = RecordOverviewFragment.this.convertStringToDate(rhs);
-
-            return date2.compareTo(date1);
-        }
-    }
-
-    /**
-     * Actualises the list in a background thread
-     */
-    private void actualiseListViewInBackground(){
-        if (loader != null && loader.isAlive()) loader.interrupt();
-
-        loader = null;
-
-        this.spinner.setVisibility(View.VISIBLE);
-        this.actualiseFilterButton();
-
-        loader = new Thread(new Runnable() {
-            @Override
-            public void run() {
-                this.runOnUiThread(this.doInBackground());
-            }
-
-            private RecordListAdapter doInBackground(){
-                return RecordOverviewFragment.this.populateListViewFromDB(RecordOverviewFragment.this.expListView);
-            }
-
-            private void runOnUiThread(final RecordListAdapter adapter){
-                Activity actv = RecordOverviewFragment.this.getActivity();
-                if (actv != null){
-                    actv.runOnUiThread(new Runnable() {
-                        @Override
-                        public void run() {
-                            this.actualiseUI();
-                        }
-                        private void actualiseUI(){
-                            if (adapter != null){
-                                RecordOverviewFragment.this.expListView.setAdapter(adapter);
-                                adapter.notifyDataSetChanged();
-                                RecordOverviewFragment.this.spinner.setVisibility(View.GONE);
-                            }
-                            RecordOverviewFragment.this.showEmptyDataNotification();
-                        }
-                    });
-                }
-            }
-        });
-        loader.start();
-    }
-
-    /**
-     * Shows a small toast if the data to show is empty (no records).
-     */
-    private void showEmptyDataNotification(){
-        if (RecordOverviewFragment.this.noDataNotificationToast == null){
-            RecordOverviewFragment.this.noDataNotificationToast =  Toast.makeText(getApplicationContext(), R.string.no_data_notification, Toast.LENGTH_SHORT);
-        }
-        RecordListAdapter adapter = (RecordListAdapter) RecordOverviewFragment.this.expListView.getExpandableListAdapter();
-
-        if (this.getFilterButton().getVisibility() == View.VISIBLE && this.filter.isSet()){
-            this.noDataNotificationToast.setText(R.string.no_data_notification);
-        } else {
-            this.noDataNotificationToast.setText(R.string.no_data_notification_no_filter);
-        }
-        if (adapter == null || adapter.getData().isEmpty())
-            RecordOverviewFragment.this.noDataNotificationToast.show();
-
-    }
-
-    /**This will open a section in the ExpandableListView with the same title as the parameter s.
-    *
-    * @param s String (the section title to open)
-    *
-    * */
-    private void setSectionToOpen(String s){
-        this.sectionToOpen = s;
-        if (this.sectionToOpen != null && this.sectionToOpen.length() != 0){
-            if (this.getGroupTitles().contains(this.sectionToOpen)){
-                int section = this.getGroupTitles().indexOf(this.sectionToOpen);
-                this.expListView.expandGroup(section);
-                this.sectionToOpen = "";
-            }
-        }
-    }
-
-    /**
-    * Returns the base context.
-    * @return Context baseContext
-    * */
-	private Context getBaseContext(){
-		return this.getActivity().getBaseContext();
-	}
-
-    /**Returns the application context.
-    * @return Context application context
-    * */
-	private Context getApplicationContext(){
-		return this.getActivity().getApplicationContext();
-	}
-
-    /**Sets the list view listener on the given ExpandableListView.
-    *
-    * @param mylist  {@link ExpandableListView ExpandableListView }
-    * */
-	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;
-	            HostageDBOpenHelper dbh = new HostageDBOpenHelper(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 Transformation / Conversion
-	 *
-	 * ***************************/
-
-
-    /**Returns the localised date format for the given timestamp
-    * @param timeStamp long */
-	@SuppressLint("SimpleDateFormat")
-	private String getDateAsString(long timeStamp) {
-        Date date = (new Date(timeStamp));
-        try {
-            DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.getDefault());
-			return formatter.format(date);
-		} catch (Exception ex) {
-			return "---";
-		}
-	}
-
-    /**
-     * Returns the timestamp in a own format.
-     * Depending on the returned format the grouping by timestamp will change.
-     *
-     * e.g.
-     * If you return a DateAsMonth formatted Date the records will be mapped by their month and year.
-     * If you return the a DateAsDay formatted Date the records will be mapped by their day, month and year.
-     * and so on...
-     *
-     * @param timestamp long
-     * @return formatted date String
-     */
-    public String getFormattedDateForGrouping(long timestamp) {
-
-        // DECIDE WHICH KIND OF FORMAT SHOULD BE USED
-        // MONTH FORMAT
-        String date = this.getDateAsMonthString(timestamp);
-        // DAY FORMAT
-        //String date = this.getDateAsDayString(timestamp);
-
-        return date;
-    }
-
-    /**Returns a date as a formated string
-     * @param timestamp date
-     * @return String date format is localised*/
-    @SuppressLint("SimpleDateFormat")
-    private String getDateAsDayString(long timestamp) {
-        try {
-            Date netDate = (new Date(timestamp));
-            String dateString;
-
-            long date = this.dayMilliseconds(timestamp);
-
-            if(this.todayMilliseconds() == date ){
-                dateString = TODAY;
-            }else if(this.yesterdayMilliseconds() == date ){
-                dateString = YESTERDAY;
-            } else {
-                dateString = localisedDateFormatter.format(netDate);
-            }
-            return dateString;
-
-        } catch (Exception ex) {
-            return "---";
-        }
-    }
-
-    /**
-     * Converts a formatted DateString into a date.
-     * @param dateString String
-     * @return Date
-     */
-    private Date convertStringToDate(String dateString){
-        if (dateString != null && dateString.length() != 0){
-            SimpleDateFormat dateFormat = groupingDateFormatter; //new SimpleDateFormat(localDatePattern);
-            Date date;
-            try {
-                if (dateString.equals(TODAY)){
-                    long millisec = RecordOverviewFragment.this.todayMilliseconds();
-                    date = new Date(millisec);
-                } else if (dateString.equals(YESTERDAY)){
-                    long millisec = RecordOverviewFragment.this.yesterdayMilliseconds();
-                    date = new Date(millisec);
-                } else {
-                    date = dateFormat.parse(dateString);
-                }
-                return date;
-
-            } catch (java.text.ParseException e ) {
-                date = new Date(0);
-                return date;
-            }
-        } else {
-            return new Date(0);
-        }
-    }
-
-    /**
-     * Returns the milliseconds for the day today (not the time).
-     * @return long
-     */
-    private long todayMilliseconds(){
-        Date current = new Date();
-        calendar.setTimeInMillis(current.getTime());
-        int day = calendar.get(Calendar.DATE);
-        int month = calendar.get(Calendar.MONTH);
-        int year = calendar.get(Calendar.YEAR);
-
-        calendar.set(year, month, day, 0,0,0);
-
-        long milli = calendar.getTimeInMillis();
-
-        Date today = new Date(milli);
-
-        return (milli / (long) 1000) * (long) 1000;
-    }
-
-    /**
-     * Returns the milliseconds for the day yesterday (not the time).
-     * @return long
-     */
-    private long yesterdayMilliseconds(){
-        Date current = new Date();
-        calendar.setTimeInMillis(current.getTime());
-        int day = calendar.get(Calendar.DATE);
-        int month = calendar.get(Calendar.MONTH);
-        int year = calendar.get(Calendar.YEAR);
-
-        calendar.set(year, month, day, 0,0,0);
-
-        calendar.add(Calendar.DATE, -1);
-
-        long milli = calendar.getTimeInMillis();
-
-        Date today = new Date(milli);
-
-        return (milli / (long) 1000) * (long) 1000;
-    }
-
-    /**
-     * returns just the date not the time of a date.
-     * @param date Date
-     * @return long
-     */
-    private long dayMilliseconds(long date){
-        //Date current = new Date();
-        calendar.setTimeInMillis(date);
-        int day = calendar.get(Calendar.DATE);
-        int month = calendar.get(Calendar.MONTH);
-        int year = calendar.get(Calendar.YEAR);
-
-        calendar.set(year, month, day, 0,0,0);
-
-        long milli = calendar.getTimeInMillis();
-
-        Date test = new Date(milli);
-
-        return (milli / (long) 1000) * (long) 1000;
-    }
-
-    /**Returns a date as a formated string
-     * @param timeStamp date
-     * @return String date format is localised*/
-    @SuppressLint("SimpleDateFormat")
-    private String getDateAsMonthString(long timeStamp) {
-        try {
-            Date netDate = (new Date(timeStamp));
-            return groupingDateFormatter.format(netDate);
-        } catch (Exception ex) {
-            return "xx";
-        }
-    }
-
-
-	/*****************************
-	 *
-	 *          Getter / Setter
-	 *
-	 * ***************************/
-
-	public boolean isShowFilterButton() {
-		return showFilterButton;
-	}
-
-	public void setShowFilterButton(boolean showFilterButton) {
-		this.showFilterButton = showFilterButton;
-	}
-
-    /**
-     * Set the group key for grouping the records.
-     * All possible grouping keys are:
-     * R.string.date,
-     * R.string.rec_protocol,
-     * R.string.ESSID,
-     * R.string.BSSID
-     * @param key String
-     */
-    public void setGroupKey(String key){
-        this.groupingKey = key;
-    }
-
-    public void setFilter(LogFilter filter){
-        this.filter = filter;
-    }
-
-
-	/*****************************
-	 *
-	 *          Open Dialog Methods
-	 *
-	 * ***************************/
-
-    /**Opens the grouping dialog*/
-    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);
-    }
-
-    /**opens the bssid filter dialog*/
-	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);
-	}
-
-    /**opens the essid filter dialog*/
-	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);
-	}
-
-    /**opens the protocol filter dialog*/
-	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);
-	}
-
-    /**opens the timestamp filter dialog (minimal timestamp required)*/
-	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);
-	}
-
-    /**opens time timestamp filter dialog (maximal timestamp required)*/
-	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);
-    }
-
-    /**opens the sorting dialog*/
-	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
-     *
-     * ***************************/
-
-    /**returns the group title for the given record. Uses the groupingKey to decied which value of the record should be used.
-    * @param  rec {@link Record Record }
-    * @return String grouptitle*/
-    public String getGroupValue(Record rec){
-        int index = this.groupingTitles().indexOf(this.groupingKey);
-        switch (index){
-            case 1:
-                return rec.getProtocol();
-            case 2:
-                return rec.getSsid();
-            case 3:
-                return rec.getBssid();
-            case 0:
-                return this.getFormattedDateForGrouping(rec.getTimestamp());
-            default:
-                return this.getFormattedDateForGrouping(rec.getTimestamp());
-        }
-    }
-
-    /**Returns the Group titles for the specified grouping key. e.g. groupingKey is "ESSID" it returns all available essids.
-    * @return ArrayList<String> grouptitles*/
-    public List<String> getGroupTitles(){
-        int index = this.groupingTitles().indexOf(this.groupingKey);
-        switch (index){
-            case 1:
-                return this.protocolTitles();
-            case 2:
-                return this.essids();
-            case 3:
-                return this.bssids();
-            case 0:
-            default:
-                RecordListAdapter adapter = (RecordListAdapter) this.expListView.getExpandableListAdapter();
-                if (adapter != null){
-                    return adapter.getSectionHeaders();
-                }
-                return new ArrayList<String>();
-            }
-    }
-
-
-	/*****************************
-	 *
-	 *          Filter Stuff
-	 *
-	 * ***************************/
-
-    /**Returns the FilterButton.
-     * @return ImageButton filterButton*/
-    private ImageButton getFilterButton(){
-        return (ImageButton) this.rootView.findViewById(R.id.FilterButton);
-    }
-
-    /**Opens the filter menu on a anchor view. The filter menu will always be on top of the anchor.
-    * @param  v View the anchorView*/
-	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);
-	}
-
-    /**Returns true  if the filter object is set for the given title otherwise false. e.g. the filter object has protocols,
-    * so the method will return for the title FILTER_MENU_TITLE_PROTOCOLS TRUE.
-    * @param  title String
-    * @return boolean value
-    * */
-    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;
-    }
-
-    /**clears the filter. Does not invoke populatelistview!*/
-	private void clearFilter(){
-    	if(filter == null) this.filter = new LogFilter();
-    	this.filter.clear();
-	}
-
-    /**Returns all grouping titles.
-    * @return ArrayList<String> tiles*/
-    public ArrayList<String> groupingTitles(){
-        ArrayList<String> titles = new ArrayList<String>();
-        titles.add(MainActivity.getContext().getString(R.string.date));
-        titles.add(MainActivity.getContext().getString(R.string.rec_protocol));
-        titles.add(MainActivity.getContext().getString(R.string.ESSID));
-        titles.add(MainActivity.getContext().getString(R.string.BSSID));
-        return titles;
-    }
-    /**
-     * Returns a bool array. This array is true at the index of the groupingKey in groupingTitles(), otherwise false.
-    * @return boolean[] selection
-    * */
-    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;
-    }
-
-    /**Returns all protocol titles / names.
-    * @return ArrayList<String> protocolTitles
-    * */
-	public ArrayList<String> protocolTitles(){
-		ArrayList<String> titles = new ArrayList<String>();
-		for (String protocol : this.getResources().getStringArray(
-				R.array.protocols)) {
-			titles.add(protocol);
-		}
-
-		titles.add("PORTSCAN");
-		return titles;
-	}
-    /**Return a boolean array of the selected / filtered protocols. If the filter object has
-    * an protocol from the protocolTitles() array, the index of it will be true, otherwise false.
-    * @return boolean[] protocol selection
-    * */
-	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;
-	}
-
-    /**
-    * Returns the Sorttype Titles
-    * @return ArayList<String> Sort type titles
-    * */
-	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(MainActivity.getContext().getString(R.string.ESSID));
-        titles.add(MainActivity.getContext().getString(R.string.BSSID));
-		return titles;
-	}
-    /**
-    * Returns an boolean array. The array is true at the index of the selected sort type..
-    * The index of the selected sort type is the same index in the sortTypeTiles array.
-    * @return boolean array, length == sortTypeTiles().length
-    * */
-	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;
-	}
-
-    /**
-    * Returns all unique bssids.
-    * @return ArrayList<String>
-    * */
-	public ArrayList<String> bssids(){
-		ArrayList<String> records = dbh.getUniqueBSSIDRecords();
-		return records;
-	}
-    /**
-    * Returns an boolean array. The array is true at the indices of the selected bssids.
-    * The index of the selected bssid is the same index in the bssids() array.
-    * @return boolean array, length == bssids().length
-    * */
-	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;
-	}
-
-    /**
-    * Returns all unique essids.
-    * @return ArrayList<String>
-    * */
-	public ArrayList<String> essids(){
-		ArrayList<String> records = dbh.getUniqueESSIDRecords();
-		return records;
-	}
-    /**
-    * Returns an boolean array. The array is true at the indices of the selected essids.
-    * The index of the selected essid is the same index in the essids() array.
-    * @return boolean array, length == essids().length
-    * */
-	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;
-	}
-
-    /**
-     * Returns all filter menu titles.
-     * @return ArrayList<String>
-     * */
-	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
-	 *
-	 * ***************************/
-
-    /**
-     * Will be called if the users selects a timestamp.
-     * @param  dialog {@link DateTimeDialogFragment DateTimeDialogFragment }
-     * */
-	public void onDateTimePickerPositiveClick(DateTimeDialogFragment dialog) {
-		if(this.wasBelowTimePicker){
-			this.filter.setBelowTimestamp(dialog.getDate());
-		} else {
-			this.filter.setAboveTimestamp(dialog.getDate());
-		}
-        this.actualiseListViewInBackground();
-        this.actualiseFilterButton();
-    }
-    /**
-     * Will be called if the users cancels a timestamp selection.
-     * @param dialog  {@link DateTimeDialogFragment DateTimeDialogFragment }
-     * */
-	public void onDateTimePickerNegativeClick(DateTimeDialogFragment dialog) {
-		if(this.wasBelowTimePicker){
-			this.filter.setBelowTimestamp(Long.MAX_VALUE);
-		} else {
-			this.filter.setAboveTimestamp(Long.MIN_VALUE);
-		}
-        this.actualiseListViewInBackground();
-        this.actualiseFilterButton();
-    }
-
-    /**
-     * Will be called if the users clicks the positiv button on a ChechlistDialog.
-     * @param  dialog  {@link ChecklistDialog ChecklistDialog }
-     */
-	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;
-            // ALWAYS GET THE FIRST ELEMENT (SHOULD BE ALWAYS ONE)
-            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;
-            // ALWAYS GET THE FIRST ELEMENT (SHOULD BE ALWAYS ONE)
-            this.groupingKey =  titles.get(0);
-        }
-        this.actualiseListViewInBackground();
-
-        this.actualiseFilterButton();
-	}
-
-    /**Paints the filter button if the current filter object is set.*/
-    private void actualiseFilterButton(){
-        if (this.filter.isSet() ){
-            ImageButton filterButton = this.getFilterButton();
-            if (filterButton != null){
-                filterButton.setImageResource(R.drawable.ic_filter_pressed);
-                filterButton.invalidate();
-            }
-        } else {
-            ImageButton filterButton = this.getFilterButton();
-            if (filterButton != null){
-                filterButton.setImageResource(R.drawable.ic_filter);
-                filterButton.invalidate();
-            }
-        }
-    }
-
-    /**
-     * Will be called if the users clicks the negativ button on a ChechlistDialog.
-     * @param  dialog  {@link ChecklistDialog ChecklistDialog }
-     */
-	public void onDialogNegativeClick(ChecklistDialog dialog) {}
-
-
-	/*****************************
-	 *
-	 *          TEST
-	 *
-	 * ***************************/
-
-    /**
-    * This will clear the database at first and than add new attacks.
-    * @param createNetworks number of networks to create
-    * @param attacksPerNetwork maximal number of attack per network
-    * @param maxMessagePerAttack maximal number of messages per attack
-    * */
-	private void addRecordToDB( int createNetworks, int attacksPerNetwork, int maxMessagePerAttack) {
-        if ((dbh.getRecordCount() > 0)) dbh.clearData();
-
-		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 double ssidRadius = 0.1;
-		final double bssidRadius = 0.004;
-
-        int attackId = 0;
-
-        for (int numOfNetworks = 0; numOfNetworks < createNetworks; numOfNetworks++){
-            String ssidName = "WiFi" + ((numOfNetworks) + 1);
-            String bssidName = "127.0.0." + ((numOfNetworks) + 1);
-
-            int protocolIndex = numOfNetworks % maxProtocolsIndex;
-            String protocolName = this.getResources().getStringArray(
-                    R.array.protocols)[protocolIndex];
-
-            int numOfAttackPerNetwork = (Math.abs(random.nextInt()) % Math.max(1, attacksPerNetwork + 1));
-
-            NetworkRecord network = new NetworkRecord();
-            network.setBssid(bssidName);
-            network.setSsid(ssidName);
-
-            LatLng ssidLocation = new LatLng(tudarmstadtLoc.latitude - ssidRadius + 2.0 * ssidRadius * Math.random(), tudarmstadtLoc.longitude - ssidRadius + 2.0 * ssidRadius * Math.random());
-            double latitude = ssidLocation.latitude - bssidRadius + 2.0 * bssidRadius * Math.random();
-            double longitude = ssidLocation.longitude - bssidRadius + 2.0 * bssidRadius * Math.random();
-
-            long timestamp = cal.getTimeInMillis();
-            network.setTimestampLocation(timestamp);
-            network.setLongitude(longitude);
-            network.setLatitude(latitude);
-            network.setAccuracy(0.f);
-
-            dbh.updateNetworkInformation(network);
-
-            // ATTACKS PER NETWORK
-            for (int attackNumber = 0; attackNumber < numOfAttackPerNetwork; attackNumber++) {
-
-                int numRecordsPerAttack = (Math.abs(random.nextInt()) % (Math.max( maxMessagePerAttack, 1))) + 1;
-
-                if (maxMessagePerAttack <= 0) numRecordsPerAttack = 0;
-
-                /* ADD A ATTACK*/
-                AttackRecord attack = new AttackRecord();
-                attack.setAttack_id(attackId);
-
-                attack.setBssid(bssidName);
-
-                attack.setProtocol(protocolName);
-                attack.setLocalIP(bssidName);
-
-
-                dbh.addAttackRecord(attack);
-
-                // MESSAGE PER ATTACK
-                for (int messageID = attackId; messageID < attackId + numRecordsPerAttack; messageID++) {
-                    MessageRecord message = new MessageRecord();
-                    message.setId(messageID);
-                    message.setAttack_id(attackId);
-
-                    // GO BACK IN TIME
-                    message.setTimestamp(cal.getTimeInMillis()
-                            - ((messageID * 60 * 60 * 24) * 1000) + (1000 * ((messageID - attackId) + 1)));
-
-                    if ((messageID - attackId) % 2 == 0){
-                        message.setType(MessageRecord.TYPE.RECEIVE);
-                    } else {
-                        message.setType(MessageRecord.TYPE.SEND);
-                    }
-                    message.setPacket("");
-
-                    dbh.addMessageRecord(message);
-                }
-
-                attackId+=numRecordsPerAttack;
-            }
-
-        }
-
-//        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. Shows the record detail view for the given record
-    * @param  record  {@link Record Record } to show
-    * */
-    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.ui.fragment;
+
+import android.annotation.SuppressLint;
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.app.FragmentManager;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.Intent;
+import android.content.SharedPreferences;
+import android.os.Bundle;
+import android.preference.PreferenceManager;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.Menu;
+import android.view.MenuInflater;
+import android.view.MenuItem;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ExpandableListView;
+import android.widget.ImageButton;
+import android.widget.ProgressBar;
+import android.widget.Toast;
+
+import com.google.android.gms.maps.model.LatLng;
+
+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.List;
+import java.util.Locale;
+import java.util.Random;
+
+import de.tudarmstadt.informatik.hostage.R;
+import de.tudarmstadt.informatik.hostage.logging.AttackRecord;
+import de.tudarmstadt.informatik.hostage.logging.LogExport;
+import de.tudarmstadt.informatik.hostage.logging.MessageRecord;
+import de.tudarmstadt.informatik.hostage.logging.NetworkRecord;
+import de.tudarmstadt.informatik.hostage.logging.Record;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
+import de.tudarmstadt.informatik.hostage.sync.bluetooth.BluetoothSyncActivity;
+import de.tudarmstadt.informatik.hostage.sync.nfc.NFCSync;
+import de.tudarmstadt.informatik.hostage.sync.tracing.TracingSyncActivity;
+import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
+import de.tudarmstadt.informatik.hostage.ui.adapter.RecordListAdapter;
+import de.tudarmstadt.informatik.hostage.ui.dialog.ChecklistDialog;
+import de.tudarmstadt.informatik.hostage.ui.dialog.DateTimeDialogFragment;
+import de.tudarmstadt.informatik.hostage.ui.model.ExpandableListItem;
+import de.tudarmstadt.informatik.hostage.ui.model.LogFilter;
+import de.tudarmstadt.informatik.hostage.ui.model.LogFilter.SortType;
+import de.tudarmstadt.informatik.hostage.ui.popup.AbstractPopup;
+import de.tudarmstadt.informatik.hostage.ui.popup.AbstractPopupItem;
+import de.tudarmstadt.informatik.hostage.ui.popup.SimplePopupItem;
+import de.tudarmstadt.informatik.hostage.ui.popup.SimplePopupTable;
+import de.tudarmstadt.informatik.hostage.ui.popup.SplitPopupItem;
+
+public class RecordOverviewFragment extends UpNavigatibleFragment implements ChecklistDialog.ChecklistDialogListener, DateTimeDialogFragment.DateTimeDialogFragmentListener {
+
+	static final String FILTER_MENU_TITLE_BSSID = MainActivity.getContext().getString(R.string.BSSID);
+	static final String FILTER_MENU_TITLE_ESSID = MainActivity.getContext().getString(R.string.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);
+
+    static final int DEFAULT_GROUPING_KEY_INDEX = 0;
+
+    private boolean wasBelowTimePicker;
+
+    private LogFilter filter;
+    private boolean showFilterButton;
+    private View rootView;
+
+    private int mListPosition = -1;
+    private int mItemPosition = -1;
+
+    public String groupingKey;
+
+    private ExpandableListView expListView;
+    private ProgressBar spinner;
+
+    private Toast noDataNotificationToast;
+
+    HostageDBOpenHelper dbh;
+
+    private String sectionToOpen = "";
+    private ArrayList<Integer> openSections;
+
+	private SharedPreferences pref;
+
+    Thread loader;
+
+
+    /* DATE CONVERSION STUFF*/
+    static final DateFormat localisedDateFormatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
+    // DATE WHICH PATTERN
+    static final String localDatePattern  = ((SimpleDateFormat)localisedDateFormatter).toLocalizedPattern();
+    static final String groupingDatePattern  = "MMMM yyyy";
+
+    // INSERT HERE YOUR DATE PATERN
+    static final SimpleDateFormat groupingDateFormatter = new SimpleDateFormat(groupingDatePattern);
+    static final Calendar calendar = Calendar.getInstance();
+
+    // DATE STRINGS
+    static final String TODAY = MainActivity.getInstance().getResources().getString( R.string.TODAY);
+    static final String YESTERDAY = MainActivity.getInstance().getResources().getString( R.string.YESTERDAY);
+
+
+
+
+    /**
+     * Constructor
+     */
+    public RecordOverviewFragment(){}
+
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setHasOptionsMenu(true);
+    }
+
+    @Override
+	public View onCreateView(LayoutInflater inflater, ViewGroup container,
+             Bundle savedInstanceState) {
+
+		setHasOptionsMenu(true);
+		getActivity().setTitle(getResources().getString(R.string.drawer_records));
+
+		dbh = new HostageDBOpenHelper(this.getActivity().getBaseContext());
+	    pref = PreferenceManager.getDefaultSharedPreferences(getActivity());
+
+	    // 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(DEFAULT_GROUPING_KEY_INDEX);
+
+	    this.setShowFilterButton(!this.filter.isNotEditable());
+
+		View rootView = inflater.inflate(this.getLayoutId(), container, false);
+        this.rootView = rootView;
+		ExpandableListView mylist = (ExpandableListView) rootView.findViewById(R.id.loglistview);
+
+        this.spinner =(ProgressBar) rootView.findViewById(R.id.progressBar1);
+        this.spinner.setVisibility(View.GONE);
+
+		this.expListView = mylist;
+
+        this.initialiseListView();
+
+        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;
+	 }
+
+
+    /**Initialises the expandable list view in a backgorund thread*/
+    private void initialiseListView(){
+        if (loader != null) loader.interrupt();
+
+        this.spinner.setVisibility(View.VISIBLE);
+
+        loader = new Thread(new Runnable(){
+
+            private void updateUI(final RecordListAdapter currentAdapter)
+            {
+                if(loader.isInterrupted()){
+                    return;
+                }
+                Activity activity = RecordOverviewFragment.this.getActivity();
+
+                if (activity != null){
+                    activity.runOnUiThread(new Runnable() {
+                        @Override
+                        public void run() {
+                            RecordOverviewFragment.this.expListView.setAdapter(currentAdapter);
+                            // Update view and remove loading spinner etc...
+                            RecordListAdapter adapter = (RecordListAdapter) RecordOverviewFragment.this.expListView.getExpandableListAdapter();
+
+                            if (adapter != null){
+                                adapter.notifyDataSetChanged();
+
+                                if (adapter.getGroupCount() >= 1){
+                                    RecordOverviewFragment.this.expListView.expandGroup(DEFAULT_GROUPING_KEY_INDEX);
+                                } else {
+                                    RecordOverviewFragment.this.setSectionToOpen(RecordOverviewFragment.this.sectionToOpen);
+                                }
+                            }
+
+                            if (RecordOverviewFragment.this.openSections != null && RecordOverviewFragment.this.openSections.size() != 0){
+                                for (int i = 0; i < RecordOverviewFragment.this.openSections.size(); i++){
+                                    int index = RecordOverviewFragment.this.openSections.get(i);
+                                    RecordOverviewFragment.this.expListView.expandGroup(index);
+                                }
+                            } else {
+                                RecordOverviewFragment.this.openSections = new ArrayList<Integer>();
+                            }
+
+                            if (mListPosition != -1 && mItemPosition != -1)
+                                RecordOverviewFragment.this.expListView.setSelectedChild(mListPosition, mItemPosition, true);
+
+                            mListPosition = -1;
+                            mItemPosition = -1;
+                            registerListClickCallback(RecordOverviewFragment.this.expListView);
+                            RecordOverviewFragment.this.spinner.setVisibility(View.GONE);
+                            RecordOverviewFragment.this.actualiseFilterButton();
+                            RecordOverviewFragment.this.showEmptyDataNotification();
+                        }
+                    });
+                }
+            }
+
+            private RecordListAdapter doInBackground()
+            {
+                return populateListViewFromDB(RecordOverviewFragment.this.expListView);
+            }
+
+            @Override
+            public void run()
+            {
+                //RecordOverviewFragment.this.addRecordToDB(40, 10, 4);
+                updateUI(doInBackground());
+            }
+
+        });
+
+        loader.start();
+
+        this.actualiseFilterButton();
+    }
+
+
+    /**
+    *  Returns the Fragment layout ID
+    *  @return int The fragment layout ID
+    * */
+    public int getLayoutId(){
+        return R.layout.fragment_record_list;
+    }
+
+    /**
+    * Gets called if the user clicks on item in the filter menu.
+    *
+    * @param  item {@link AbstractPopupItem AbstractPopupItem }
+    * */
+	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.actualiseListViewInBackground();
+            }
+            if(title.equals(FILTER_MENU_TITLE_TIMESTAMP_BELOW)){
+                this.openTimestampToFilterDialog();
+            }
+            if(title.equals(FILTER_MENU_TITLE_TIMESTAMP_ABOVE)){
+                this.openTimestampFromFilterDialog();
+            }
+        }
+		//return super.onOptionsItemSelected(item);
+	}
+
+
+
+    @Override
+    public void onStart() {
+        super.onStart();
+        if (this.expListView.getExpandableListAdapter() != null){
+            if (this.expListView.getExpandableListAdapter().getGroupCount() == 1){
+                this.expListView.expandGroup(0);
+            } else {
+                this.setSectionToOpen(this.sectionToOpen);
+            }
+        }
+
+    }
+
+	@Override
+	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
+		// Inflate the menu items for use in the action bar
+		inflater.inflate(R.menu.records_overview_actions, menu);
+	}
+
+	@Override
+	public boolean onOptionsItemSelected(MenuItem item) {
+		switch (item.getItemId()) {
+			case R.id.records_action_synchronize:
+
+				AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
+				builder.setTitle(MainActivity.getInstance().getString(R.string.rec_sync_rec));
+				builder.setItems(new String[]{
+						MainActivity.getInstance().getString(R.string.rec_via_bt),
+						MainActivity.getInstance().getString(R.string.rec_via_nfc),
+						MainActivity.getInstance().getString(R.string.rec_via_online)
+				}, new DialogInterface.OnClickListener() {
+					@Override
+					public void onClick(DialogInterface dialog, int position) {
+						switch(position){
+							case 0:
+								getActivity().startActivity(new Intent(getActivity(), BluetoothSyncActivity.class));
+								break;
+							case 1:
+								getActivity().startActivity(new Intent(getActivity(), NFCSync.class));
+								break;
+
+							case 2:
+								getActivity().startActivity(new Intent(getActivity(), TracingSyncActivity.class));
+								break;
+						}
+					}
+				});
+				builder.create();
+				builder.show();
+
+
+				return true;
+			case R.id.records_action_export:
+				AlertDialog.Builder builderExport = new AlertDialog.Builder(getActivity());
+				builderExport.setTitle(MainActivity.getInstance().getString(R.string.rec_choose_export_format));
+				builderExport.setItems(R.array.format, new DialogInterface.OnClickListener() {
+					@Override
+					public void onClick(DialogInterface dialog, int position) {
+						//RecordOverviewFragment.this.exportDatabase(position);
+						Intent intent = new Intent(getActivity(), LogExport.class);
+						intent.setAction(LogExport.ACTION_EXPORT_DATABASE);
+						intent.putExtra(LogExport.FORMAT_EXPORT_DATABASE, position);
+
+						RecordOverviewFragment.this.getActivity().startService(intent);
+					}
+				});
+				builderExport.create();
+				builderExport.show();
+
+				return true;
+		}
+
+		return false;
+	}
+
+	/*****************************
+	 *
+	 * 			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().get(ESSID_INDEX);
+  	}
+
+
+	/*****************************
+	 *
+	 *          ListView Stuff
+	 *
+	 * ***************************/
+
+    /**
+    *  Reloads the data in the ExpandableListView for the given filter object.
+    *  @param  mylist {@link ExpandableListView ExpandableListView}
+    * */
+	private RecordListAdapter populateListViewFromDB(ExpandableListView mylist) {
+        ArrayList<String> groupTitle = new ArrayList<String>();
+
+        HashMap<String, ArrayList<ExpandableListItem>> sectionData = this.fetchDataForFilter(this.filter, groupTitle);
+
+        RecordListAdapter adapter = null;
+        if (mylist.getAdapter() != null && mylist.getAdapter() instanceof RecordListAdapter){
+            adapter = (RecordListAdapter) mylist.getAdapter();
+            adapter.setData(sectionData);
+            adapter.setSectionHeader(groupTitle);
+        } else {
+            adapter = new RecordListAdapter( RecordOverviewFragment.this.getApplicationContext(), groupTitle, sectionData);
+        }
+
+        return adapter;
+	}
+
+    private HashMap<String, ArrayList<ExpandableListItem>> fetchDataForFilter(LogFilter filter, ArrayList<String> groupTitle){
+        HashMap<String, ArrayList<ExpandableListItem>> sectionData = new HashMap<String, ArrayList<ExpandableListItem>>();
+
+        ArrayList<Record> data = dbh.getRecordsForFilter(filter == null ? this.filter : filter);
+
+        // Adding Items to ListView
+        String keys[] = new String[] { RecordOverviewFragment.this.getString(R.string.RecordBSSID), RecordOverviewFragment.this.getString(R.string.RecordSSID), RecordOverviewFragment.this.getString(R.string.RecordProtocol), RecordOverviewFragment.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++;
+        }
+
+        if (groupTitle == null){
+            groupTitle = new ArrayList<String>();
+        } else {
+            groupTitle.clear();
+        }
+
+
+        for (Record val : data) {
+            // DO GROUPING IN HERE
+            HashMap<String, String> map = new HashMap<String, String>();
+            map.put(RecordOverviewFragment.this.getString(R.string.RecordBSSID), val.getBssid());
+            map.put(RecordOverviewFragment.this.getString(R.string.RecordSSID), val.getSsid());
+            map.put(RecordOverviewFragment.this.getString(R.string.RecordProtocol), val.getProtocol());
+            map.put(RecordOverviewFragment.this.getString(R.string.RecordTimestamp),
+                    RecordOverviewFragment.this.getDateAsString(val.getTimestamp()));
+
+            ExpandableListItem item = new ExpandableListItem();
+            item.setData(map);
+
+            item.setId_Mapping(mapping);
+
+            item.setTag(val.getAttack_id());
+
+            String groupID = RecordOverviewFragment.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);
+        }
+
+        if (this.groupingKey.equals(this.groupingTitles().get(DEFAULT_GROUPING_KEY_INDEX))){
+            Collections.sort(groupTitle,new DateStringComparator());
+        } else {
+            Collections.sort(groupTitle, new Comparator<String>() {
+                @Override
+                public int compare(String s1, String s2) {
+                    return s1.compareToIgnoreCase(s2);
+                }
+            });
+        }
+
+        return sectionData;
+    }
+
+    /**
+     * The DateStringComparator compares formatted date strings by converting the into date.
+     * This class  is mainly used for grouping the records by their timestamp.
+     */
+    class DateStringComparator implements Comparator<String>
+    {
+        public int compare(String lhs, String rhs)
+        {
+            Date date1 = RecordOverviewFragment.this.convertStringToDate(lhs);
+            Date date2 = RecordOverviewFragment.this.convertStringToDate(rhs);
+
+            return date2.compareTo(date1);
+        }
+    }
+
+    /**
+     * Actualises the list in a background thread
+     */
+    private void actualiseListViewInBackground(){
+        if (loader != null && loader.isAlive()) loader.interrupt();
+
+        loader = null;
+
+        this.spinner.setVisibility(View.VISIBLE);
+        this.actualiseFilterButton();
+
+        loader = new Thread(new Runnable() {
+            @Override
+            public void run() {
+                this.runOnUiThread(this.doInBackground());
+            }
+
+            private RecordListAdapter doInBackground(){
+                return RecordOverviewFragment.this.populateListViewFromDB(RecordOverviewFragment.this.expListView);
+            }
+
+            private void runOnUiThread(final RecordListAdapter adapter){
+                Activity actv = RecordOverviewFragment.this.getActivity();
+                if (actv != null){
+                    actv.runOnUiThread(new Runnable() {
+                        @Override
+                        public void run() {
+                            this.actualiseUI();
+                        }
+                        private void actualiseUI(){
+                            if (adapter != null){
+                                RecordOverviewFragment.this.expListView.setAdapter(adapter);
+                                adapter.notifyDataSetChanged();
+                                RecordOverviewFragment.this.spinner.setVisibility(View.GONE);
+                            }
+                            RecordOverviewFragment.this.showEmptyDataNotification();
+                        }
+                    });
+                }
+            }
+        });
+        loader.start();
+    }
+
+    /**
+     * Shows a small toast if the data to show is empty (no records).
+     */
+    private void showEmptyDataNotification(){
+        if (RecordOverviewFragment.this.noDataNotificationToast == null){
+            RecordOverviewFragment.this.noDataNotificationToast =  Toast.makeText(getApplicationContext(), R.string.no_data_notification, Toast.LENGTH_SHORT);
+        }
+        RecordListAdapter adapter = (RecordListAdapter) RecordOverviewFragment.this.expListView.getExpandableListAdapter();
+
+        if (this.getFilterButton().getVisibility() == View.VISIBLE && this.filter.isSet()){
+            this.noDataNotificationToast.setText(R.string.no_data_notification);
+        } else {
+            this.noDataNotificationToast.setText(R.string.no_data_notification_no_filter);
+        }
+        if (adapter == null || adapter.getData().isEmpty())
+            RecordOverviewFragment.this.noDataNotificationToast.show();
+
+    }
+
+    /**This will open a section in the ExpandableListView with the same title as the parameter s.
+    *
+    * @param s String (the section title to open)
+    *
+    * */
+    private void setSectionToOpen(String s){
+        this.sectionToOpen = s;
+        if (this.sectionToOpen != null && this.sectionToOpen.length() != 0){
+            if (this.getGroupTitles().contains(this.sectionToOpen)){
+                int section = this.getGroupTitles().indexOf(this.sectionToOpen);
+                this.expListView.expandGroup(section);
+                this.sectionToOpen = "";
+            }
+        }
+    }
+
+    /**
+    * Returns the base context.
+    * @return Context baseContext
+    * */
+	private Context getBaseContext(){
+		return this.getActivity().getBaseContext();
+	}
+
+    /**Returns the application context.
+    * @return Context application context
+    * */
+	private Context getApplicationContext(){
+		return this.getActivity().getApplicationContext();
+	}
+
+    /**Sets the list view listener on the given ExpandableListView.
+    *
+    * @param mylist  {@link ExpandableListView ExpandableListView }
+    * */
+	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;
+	            HostageDBOpenHelper dbh = new HostageDBOpenHelper(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 Transformation / Conversion
+	 *
+	 * ***************************/
+
+
+    /**Returns the localised date format for the given timestamp
+    * @param timeStamp long */
+	@SuppressLint("SimpleDateFormat")
+	private String getDateAsString(long timeStamp) {
+        Date date = (new Date(timeStamp));
+        try {
+            DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.getDefault());
+			return formatter.format(date);
+		} catch (Exception ex) {
+			return "---";
+		}
+	}
+
+    /**
+     * Returns the timestamp in a own format.
+     * Depending on the returned format the grouping by timestamp will change.
+     *
+     * e.g.
+     * If you return a DateAsMonth formatted Date the records will be mapped by their month and year.
+     * If you return the a DateAsDay formatted Date the records will be mapped by their day, month and year.
+     * and so on...
+     *
+     * @param timestamp long
+     * @return formatted date String
+     */
+    public String getFormattedDateForGrouping(long timestamp) {
+
+        // DECIDE WHICH KIND OF FORMAT SHOULD BE USED
+        // MONTH FORMAT
+        String date = this.getDateAsMonthString(timestamp);
+        // DAY FORMAT
+        //String date = this.getDateAsDayString(timestamp);
+
+        return date;
+    }
+
+    /**Returns a date as a formated string
+     * @param timestamp date
+     * @return String date format is localised*/
+    @SuppressLint("SimpleDateFormat")
+    private String getDateAsDayString(long timestamp) {
+        try {
+            Date netDate = (new Date(timestamp));
+            String dateString;
+
+            long date = this.dayMilliseconds(timestamp);
+
+            if(this.todayMilliseconds() == date ){
+                dateString = TODAY;
+            }else if(this.yesterdayMilliseconds() == date ){
+                dateString = YESTERDAY;
+            } else {
+                dateString = localisedDateFormatter.format(netDate);
+            }
+            return dateString;
+
+        } catch (Exception ex) {
+            return "---";
+        }
+    }
+
+    /**
+     * Converts a formatted DateString into a date.
+     * @param dateString String
+     * @return Date
+     */
+    private Date convertStringToDate(String dateString){
+        if (dateString != null && dateString.length() != 0){
+            SimpleDateFormat dateFormat = groupingDateFormatter; //new SimpleDateFormat(localDatePattern);
+            Date date;
+            try {
+                if (dateString.equals(TODAY)){
+                    long millisec = RecordOverviewFragment.this.todayMilliseconds();
+                    date = new Date(millisec);
+                } else if (dateString.equals(YESTERDAY)){
+                    long millisec = RecordOverviewFragment.this.yesterdayMilliseconds();
+                    date = new Date(millisec);
+                } else {
+                    date = dateFormat.parse(dateString);
+                }
+                return date;
+
+            } catch (java.text.ParseException e ) {
+                date = new Date(0);
+                return date;
+            }
+        } else {
+            return new Date(0);
+        }
+    }
+
+    /**
+     * Returns the milliseconds for the day today (not the time).
+     * @return long
+     */
+    private long todayMilliseconds(){
+        Date current = new Date();
+        calendar.setTimeInMillis(current.getTime());
+        int day = calendar.get(Calendar.DATE);
+        int month = calendar.get(Calendar.MONTH);
+        int year = calendar.get(Calendar.YEAR);
+
+        calendar.set(year, month, day, 0,0,0);
+
+        long milli = calendar.getTimeInMillis();
+
+        Date today = new Date(milli);
+
+        return (milli / (long) 1000) * (long) 1000;
+    }
+
+    /**
+     * Returns the milliseconds for the day yesterday (not the time).
+     * @return long
+     */
+    private long yesterdayMilliseconds(){
+        Date current = new Date();
+        calendar.setTimeInMillis(current.getTime());
+        int day = calendar.get(Calendar.DATE);
+        int month = calendar.get(Calendar.MONTH);
+        int year = calendar.get(Calendar.YEAR);
+
+        calendar.set(year, month, day, 0,0,0);
+
+        calendar.add(Calendar.DATE, -1);
+
+        long milli = calendar.getTimeInMillis();
+
+        Date today = new Date(milli);
+
+        return (milli / (long) 1000) * (long) 1000;
+    }
+
+    /**
+     * returns just the date not the time of a date.
+     * @param date Date
+     * @return long
+     */
+    private long dayMilliseconds(long date){
+        //Date current = new Date();
+        calendar.setTimeInMillis(date);
+        int day = calendar.get(Calendar.DATE);
+        int month = calendar.get(Calendar.MONTH);
+        int year = calendar.get(Calendar.YEAR);
+
+        calendar.set(year, month, day, 0,0,0);
+
+        long milli = calendar.getTimeInMillis();
+
+        Date test = new Date(milli);
+
+        return (milli / (long) 1000) * (long) 1000;
+    }
+
+    /**Returns a date as a formated string
+     * @param timeStamp date
+     * @return String date format is localised*/
+    @SuppressLint("SimpleDateFormat")
+    private String getDateAsMonthString(long timeStamp) {
+        try {
+            Date netDate = (new Date(timeStamp));
+            return groupingDateFormatter.format(netDate);
+        } catch (Exception ex) {
+            return "xx";
+        }
+    }
+
+
+	/*****************************
+	 *
+	 *          Getter / Setter
+	 *
+	 * ***************************/
+
+	public boolean isShowFilterButton() {
+		return showFilterButton;
+	}
+
+	public void setShowFilterButton(boolean showFilterButton) {
+		this.showFilterButton = showFilterButton;
+	}
+
+    /**
+     * Set the group key for grouping the records.
+     * All possible grouping keys are:
+     * R.string.date,
+     * R.string.rec_protocol,
+     * R.string.ESSID,
+     * R.string.BSSID
+     * @param key String
+     */
+    public void setGroupKey(String key){
+        this.groupingKey = key;
+    }
+
+    public void setFilter(LogFilter filter){
+        this.filter = filter;
+    }
+
+
+	/*****************************
+	 *
+	 *          Open Dialog Methods
+	 *
+	 * ***************************/
+
+    /**Opens the grouping dialog*/
+    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);
+    }
+
+    /**opens the bssid filter dialog*/
+	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);
+	}
+
+    /**opens the essid filter dialog*/
+	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);
+	}
+
+    /**opens the protocol filter dialog*/
+	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);
+	}
+
+    /**opens the timestamp filter dialog (minimal timestamp required)*/
+	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);
+	}
+
+    /**opens time timestamp filter dialog (maximal timestamp required)*/
+	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);
+    }
+
+    /**opens the sorting dialog*/
+	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
+     *
+     * ***************************/
+
+    /**returns the group title for the given record. Uses the groupingKey to decied which value of the record should be used.
+    * @param  rec {@link Record Record }
+    * @return String grouptitle*/
+    public String getGroupValue(Record rec){
+        int index = this.groupingTitles().indexOf(this.groupingKey);
+        switch (index){
+            case 1:
+                return rec.getProtocol();
+            case 2:
+                return rec.getSsid();
+            case 3:
+                return rec.getBssid();
+            case 0:
+                return this.getFormattedDateForGrouping(rec.getTimestamp());
+            default:
+                return this.getFormattedDateForGrouping(rec.getTimestamp());
+        }
+    }
+
+    /**Returns the Group titles for the specified grouping key. e.g. groupingKey is "ESSID" it returns all available essids.
+    * @return ArrayList<String> grouptitles*/
+    public List<String> getGroupTitles(){
+        int index = this.groupingTitles().indexOf(this.groupingKey);
+        switch (index){
+            case 1:
+                return this.protocolTitles();
+            case 2:
+                return this.essids();
+            case 3:
+                return this.bssids();
+            case 0:
+            default:
+                RecordListAdapter adapter = (RecordListAdapter) this.expListView.getExpandableListAdapter();
+                if (adapter != null){
+                    return adapter.getSectionHeaders();
+                }
+                return new ArrayList<String>();
+            }
+    }
+
+
+	/*****************************
+	 *
+	 *          Filter Stuff
+	 *
+	 * ***************************/
+
+    /**Returns the FilterButton.
+     * @return ImageButton filterButton*/
+    private ImageButton getFilterButton(){
+        return (ImageButton) this.rootView.findViewById(R.id.FilterButton);
+    }
+
+    /**Opens the filter menu on a anchor view. The filter menu will always be on top of the anchor.
+    * @param  v View the anchorView*/
+	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);
+	}
+
+    /**Returns true  if the filter object is set for the given title otherwise false. e.g. the filter object has protocols,
+    * so the method will return for the title FILTER_MENU_TITLE_PROTOCOLS TRUE.
+    * @param  title String
+    * @return boolean value
+    * */
+    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;
+    }
+
+    /**clears the filter. Does not invoke populatelistview!*/
+	private void clearFilter(){
+    	if(filter == null) this.filter = new LogFilter();
+    	this.filter.clear();
+	}
+
+    /**Returns all grouping titles.
+    * @return ArrayList<String> tiles*/
+    public ArrayList<String> groupingTitles(){
+        ArrayList<String> titles = new ArrayList<String>();
+        titles.add(MainActivity.getContext().getString(R.string.date));
+        titles.add(MainActivity.getContext().getString(R.string.rec_protocol));
+        titles.add(MainActivity.getContext().getString(R.string.ESSID));
+        titles.add(MainActivity.getContext().getString(R.string.BSSID));
+        return titles;
+    }
+    /**
+     * Returns a bool array. This array is true at the index of the groupingKey in groupingTitles(), otherwise false.
+    * @return boolean[] selection
+    * */
+    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;
+    }
+
+    /**Returns all protocol titles / names.
+    * @return ArrayList<String> protocolTitles
+    * */
+	public ArrayList<String> protocolTitles(){
+		ArrayList<String> titles = new ArrayList<String>();
+		for (String protocol : this.getResources().getStringArray(
+				R.array.protocols)) {
+			titles.add(protocol);
+		}
+
+		titles.add("PORTSCAN");
+		return titles;
+	}
+    /**Return a boolean array of the selected / filtered protocols. If the filter object has
+    * an protocol from the protocolTitles() array, the index of it will be true, otherwise false.
+    * @return boolean[] protocol selection
+    * */
+	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;
+	}
+
+    /**
+    * Returns the Sorttype Titles
+    * @return ArayList<String> Sort type titles
+    * */
+	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(MainActivity.getContext().getString(R.string.ESSID));
+        titles.add(MainActivity.getContext().getString(R.string.BSSID));
+		return titles;
+	}
+    /**
+    * Returns an boolean array. The array is true at the index of the selected sort type..
+    * The index of the selected sort type is the same index in the sortTypeTiles array.
+    * @return boolean array, length == sortTypeTiles().length
+    * */
+	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;
+	}
+
+    /**
+    * Returns all unique bssids.
+    * @return ArrayList<String>
+    * */
+	public ArrayList<String> bssids(){
+		ArrayList<String> records = dbh.getUniqueBSSIDRecords();
+		return records;
+	}
+    /**
+    * Returns an boolean array. The array is true at the indices of the selected bssids.
+    * The index of the selected bssid is the same index in the bssids() array.
+    * @return boolean array, length == bssids().length
+    * */
+	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;
+	}
+
+    /**
+    * Returns all unique essids.
+    * @return ArrayList<String>
+    * */
+	public ArrayList<String> essids(){
+		ArrayList<String> records = dbh.getUniqueESSIDRecords();
+		return records;
+	}
+    /**
+    * Returns an boolean array. The array is true at the indices of the selected essids.
+    * The index of the selected essid is the same index in the essids() array.
+    * @return boolean array, length == essids().length
+    * */
+	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;
+	}
+
+    /**
+     * Returns all filter menu titles.
+     * @return ArrayList<String>
+     * */
+	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
+	 *
+	 * ***************************/
+
+    /**
+     * Will be called if the users selects a timestamp.
+     * @param  dialog {@link DateTimeDialogFragment DateTimeDialogFragment }
+     * */
+	public void onDateTimePickerPositiveClick(DateTimeDialogFragment dialog) {
+		if(this.wasBelowTimePicker){
+			this.filter.setBelowTimestamp(dialog.getDate());
+		} else {
+			this.filter.setAboveTimestamp(dialog.getDate());
+		}
+        this.actualiseListViewInBackground();
+        this.actualiseFilterButton();
+    }
+    /**
+     * Will be called if the users cancels a timestamp selection.
+     * @param dialog  {@link DateTimeDialogFragment DateTimeDialogFragment }
+     * */
+	public void onDateTimePickerNegativeClick(DateTimeDialogFragment dialog) {
+		if(this.wasBelowTimePicker){
+			this.filter.setBelowTimestamp(Long.MAX_VALUE);
+		} else {
+			this.filter.setAboveTimestamp(Long.MIN_VALUE);
+		}
+        this.actualiseListViewInBackground();
+        this.actualiseFilterButton();
+    }
+
+    /**
+     * Will be called if the users clicks the positiv button on a ChechlistDialog.
+     * @param  dialog  {@link ChecklistDialog ChecklistDialog }
+     */
+	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;
+            // ALWAYS GET THE FIRST ELEMENT (SHOULD BE ALWAYS ONE)
+            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;
+            // ALWAYS GET THE FIRST ELEMENT (SHOULD BE ALWAYS ONE)
+            this.groupingKey =  titles.get(0);
+        }
+        this.actualiseListViewInBackground();
+
+        this.actualiseFilterButton();
+	}
+
+    /**Paints the filter button if the current filter object is set.*/
+    private void actualiseFilterButton(){
+        if (this.filter.isSet() ){
+            ImageButton filterButton = this.getFilterButton();
+            if (filterButton != null){
+                filterButton.setImageResource(R.drawable.ic_filter_pressed);
+                filterButton.invalidate();
+            }
+        } else {
+            ImageButton filterButton = this.getFilterButton();
+            if (filterButton != null){
+                filterButton.setImageResource(R.drawable.ic_filter);
+                filterButton.invalidate();
+            }
+        }
+    }
+
+    /**
+     * Will be called if the users clicks the negativ button on a ChechlistDialog.
+     * @param  dialog  {@link ChecklistDialog ChecklistDialog }
+     */
+	public void onDialogNegativeClick(ChecklistDialog dialog) {}
+
+
+	/*****************************
+	 *
+	 *          TEST
+	 *
+	 * ***************************/
+
+    /**
+    * This will clear the database at first and than add new attacks.
+    * @param createNetworks number of networks to create
+    * @param attacksPerNetwork maximal number of attack per network
+    * @param maxMessagePerAttack maximal number of messages per attack
+    * */
+	private void addRecordToDB( int createNetworks, int attacksPerNetwork, int maxMessagePerAttack) {
+        if ((dbh.getRecordCount() > 0)) dbh.clearData();
+
+		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 double ssidRadius = 0.1;
+		final double bssidRadius = 0.004;
+
+        int attackId = 0;
+
+        for (int numOfNetworks = 0; numOfNetworks < createNetworks; numOfNetworks++){
+            String ssidName = "WiFi" + ((numOfNetworks) + 1);
+            String bssidName = "127.0.0." + ((numOfNetworks) + 1);
+
+            int protocolIndex = numOfNetworks % maxProtocolsIndex;
+            String protocolName = this.getResources().getStringArray(
+                    R.array.protocols)[protocolIndex];
+
+            int numOfAttackPerNetwork = (Math.abs(random.nextInt()) % Math.max(1, attacksPerNetwork + 1));
+
+            NetworkRecord network = new NetworkRecord();
+            network.setBssid(bssidName);
+            network.setSsid(ssidName);
+
+            LatLng ssidLocation = new LatLng(tudarmstadtLoc.latitude - ssidRadius + 2.0 * ssidRadius * Math.random(), tudarmstadtLoc.longitude - ssidRadius + 2.0 * ssidRadius * Math.random());
+            double latitude = ssidLocation.latitude - bssidRadius + 2.0 * bssidRadius * Math.random();
+            double longitude = ssidLocation.longitude - bssidRadius + 2.0 * bssidRadius * Math.random();
+
+            long timestamp = cal.getTimeInMillis();
+            network.setTimestampLocation(timestamp);
+            network.setLongitude(longitude);
+            network.setLatitude(latitude);
+            network.setAccuracy(0.f);
+
+            dbh.updateNetworkInformation(network);
+
+            // ATTACKS PER NETWORK
+            for (int attackNumber = 0; attackNumber < numOfAttackPerNetwork; attackNumber++) {
+
+                int numRecordsPerAttack = (Math.abs(random.nextInt()) % (Math.max( maxMessagePerAttack, 1))) + 1;
+
+                if (maxMessagePerAttack <= 0) numRecordsPerAttack = 0;
+
+                /* ADD A ATTACK*/
+                AttackRecord attack = new AttackRecord();
+                attack.setAttack_id(attackId);
+
+                attack.setBssid(bssidName);
+
+                attack.setProtocol(protocolName);
+                attack.setLocalIP(bssidName);
+
+
+                dbh.addAttackRecord(attack);
+
+                // MESSAGE PER ATTACK
+                for (int messageID = attackId; messageID < attackId + numRecordsPerAttack; messageID++) {
+                    MessageRecord message = new MessageRecord();
+                    message.setId(messageID);
+                    message.setAttack_id(attackId);
+
+                    // GO BACK IN TIME
+                    message.setTimestamp(cal.getTimeInMillis()
+                            - ((messageID * 60 * 60 * 24) * 1000) + (1000 * ((messageID - attackId) + 1)));
+
+                    if ((messageID - attackId) % 2 == 0){
+                        message.setType(MessageRecord.TYPE.RECEIVE);
+                    } else {
+                        message.setType(MessageRecord.TYPE.SEND);
+                    }
+                    message.setPacket("");
+
+                    dbh.addMessageRecord(message);
+                }
+
+                attackId+=numRecordsPerAttack;
+            }
+
+        }
+
+//        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. Shows the record detail view for the given record
+    * @param  record  {@link Record Record } to show
+    * */
+    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);
+
+        }
+
+    }
+}

+ 4 - 4
src/de/tudarmstadt/informatik/hostage/ui/fragment/ServicesFragment.java

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.ui2.fragment;
+package de.tudarmstadt.informatik.hostage.ui.fragment;
 
 import java.util.ArrayList;
 
@@ -25,9 +25,9 @@ import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
 import de.tudarmstadt.informatik.hostage.model.Profile;
 import de.tudarmstadt.informatik.hostage.persistence.ProfileManager;
 import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
-import de.tudarmstadt.informatik.hostage.ui2.adapter.ServicesListAdapter;
-import de.tudarmstadt.informatik.hostage.ui2.model.ServicesListItem;
+import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
+import de.tudarmstadt.informatik.hostage.ui.adapter.ServicesListAdapter;
+import de.tudarmstadt.informatik.hostage.ui.model.ServicesListItem;
 
 /**
  * @author Daniel Lazar

+ 5 - 238
src/de/tudarmstadt/informatik/hostage/ui/fragment/SettingsFragment.java

@@ -1,175 +1,26 @@
-package de.tudarmstadt.informatik.hostage.ui2.fragment;
+package de.tudarmstadt.informatik.hostage.ui.fragment;
 
-import android.app.AlertDialog;
-import android.app.DownloadManager;
-import android.app.DownloadManager.Query;
-import android.app.DownloadManager.Request;
-import android.app.Fragment;
 import android.app.FragmentManager;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.content.SharedPreferences;
-import android.database.Cursor;
-import android.net.Uri;
 import android.os.Bundle;
-import android.os.Environment;
-import android.util.Log;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
-import android.widget.ImageView;
 import android.widget.TextView;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.nio.channels.FileChannel;
-import java.util.zip.ZipInputStream;
-
-import de.tudarmstadt.informatik.hostage.Hostage;
 import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.system.Decompress;
 import de.tudarmstadt.informatik.hostage.system.Device;
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
 
 /**
- * Creates the view to edit the preferences of the app and shows the porthack and rooted state of the device
- *
  * @author Alexander Brakowski
  * @created 24.02.14 23:37
  */
 public class SettingsFragment extends UpNavigatibleFragment {
-
-	/**
-	 * {@inheritDoc}
-	 */
-
-    private long enqueue;
-    private DownloadManager dm;
-    private BroadcastReceiver receiver;
-    /**
-     * Hold the shared preferences for the app
-     */
-    private SharedPreferences mSharedPreferences;
-
-    public void portbinderAlert(final SharedPreferences.Editor editor){
-        new AlertDialog.Builder(getActivity())
-                .setTitle(R.string.information)
-                .setMessage(R.string.no_portbinder_msg)
-                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
-                    public void onClick(DialogInterface dialog, int which) {
-
-                    }
-                })
-                .setNegativeButton(R.string.no_thanks, new DialogInterface.OnClickListener() {
-                            public void onClick(DialogInterface dialog, int which) {
-                                //never show this to users again
-                                if (editor != null) {
-                                    editor.putBoolean("donotshowagain", true);
-                                    editor.commit(); //commit if any changes on the preferences
-                                }
-                            }
-                        }
-                )
-                .setNeutralButton(R.string.how, new DialogInterface.OnClickListener() {
-
-                    public void onClick(DialogInterface dialog, int which) {
-                        dialog.dismiss();
-                        final AlertDialog alert;
-
-                        new AlertDialog.Builder(getActivity())
-                                .setTitle(R.string.portbinder)
-                                .setMessage(R.string.helpPortbinder)
-                                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
-                                    public void onClick(DialogInterface dialog, int which) {
-
-                                    }
-                                })
-                                .setNegativeButton(R.string.portbinder_website, new DialogInterface.OnClickListener() {
-                                    public void onClick(DialogInterface dialog, int which) {
-
-                                        Uri uri = Uri.parse("https://www.tk.informatik.tu-darmstadt.de/de/research/secure-smart-infrastructures/hostage/");
-                                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
-                                        startActivity(intent);
-
-                                    }
-                                })
-                                        //Testing automated installation of portbinder
-                                .setNeutralButton(R.string.help_me, new DialogInterface.OnClickListener() {
-                                    public void onClick(DialogInterface dialog, int which) {
-                                        dialog.dismiss();
-
-                                        new AlertDialog.Builder(getActivity())
-                                                .setTitle(R.string.portbinder)
-                                                .setMessage(R.string.confirm_msg)
-                                                .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
-                                                    public void onClick(DialogInterface dialog, int which) {
-                                                        //Download Portbinder
-                                                        dm = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
-
-                                                        //Identify architecture
-                                                        String arch = System.getProperty("os.arch"); //get the device architecture
-                                                        String fileName = "";
-
-                                                        //selecting necessary PortBinder architecture
-                                                        if (arch.matches("arm.*"))      //arm
-                                                            fileName = "bind-arm.zip";
-                                                        else if (arch.matches("x86"))   //x86
-                                                            fileName = "bind-x86.zip";
-                                                        else if (arch.matches("mips"))  //mips
-                                                            fileName = "bind-mips.zip";
-
-                                                        Uri uri = Uri.parse("https://www.tk.informatik.tu-darmstadt.de/fileadmin/user_upload/Group_TK/"+fileName);
-
-                                                        if (!fileName.isEmpty()) //As long we have a valid string (non-empty)
-                                                        {
-                                                            Request request = new Request(uri)
-                                                                    .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
-                                                            enqueue = dm.enqueue(request);
-                                                        }
-                                                        else {
-                                                            //report to user of an unknown architecture
-                                                        }
-
-                                                    }
-                                                })
-                                                .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
-                                                    public void onClick(DialogInterface dialog, int which) {
-
-
-
-                                                    }
-                                                })
-                                                .setIcon(android.R.drawable.ic_dialog_alert).show();
-                                                ;
-
-                                    }
-                                })
-                                .setIcon(android.R.drawable.ic_dialog_info).show();
-
-                    }
-                })
-                .setIcon(android.R.drawable.ic_dialog_info).show();
-    }
-
-    @Override
-    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 		super.onCreateView(inflater, container, savedInstanceState);
 		getActivity().setTitle(getResources().getString(R.string.drawer_settings));
 		View v = inflater.inflate(R.layout.fragment_settings, container, false);
 
-        mSharedPreferences = getActivity().getSharedPreferences(getString(R.string.shared_preference_path), Hostage.MODE_PRIVATE);
-        final SharedPreferences.Editor editor = mSharedPreferences.edit();
-
-		final TextView rootedText = (TextView) v.findViewById(R.id.settings_device_rooted);
-		final TextView porthackText = (TextView) v.findViewById(R.id.settings_porthack_installed);
+		TextView rootedText = (TextView) v.findViewById(R.id.settings_device_rooted);
+		TextView porthackText = (TextView) v.findViewById(R.id.settings_porthack_installed);
 
 		if (Device.isRooted()) {
 			rootedText.setText(R.string.yes);
@@ -183,101 +34,17 @@ public class SettingsFragment extends UpNavigatibleFragment {
 			porthackText.setText(R.string.yes);
 			porthackText.setTextColor(getResources().getColor(R.color.holo_dark_green));
 		} else {
-
-            if (!mSharedPreferences.getBoolean("donotshowagain", false))
-                portbinderAlert(editor);
-
 			porthackText.setText(R.string.no);
 			porthackText.setTextColor(getResources().getColor(R.color.holo_red));
 		}
 
-        //Handle if a download 'may' be needed
-        receiver = new BroadcastReceiver() {
-            @Override
-            public void onReceive(Context context, Intent intent) {
-                String action = intent.getAction();
-                if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
-                    long downloadId = intent.getLongExtra(
-                            DownloadManager.EXTRA_DOWNLOAD_ID, 0);
-                    Query query = new Query();
-                    query.setFilterById(enqueue);
-                    Cursor c = dm.query(query);
-                    if (c.moveToFirst()) {
-                        int columnIndex = c
-                                .getColumnIndex(DownloadManager.COLUMN_STATUS);
-                        if (DownloadManager.STATUS_SUCCESSFUL == c
-                                .getInt(columnIndex)) {
-
-                            String downloadFile = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
-                            String makeWritable[]= {"su","-c","chmod","777","/data/local"}; //change permission to allow rw access from x only
-                            String allowExec[]= {"su","-c","chmod","711","/data/local/bind"}; //change permission to allow x access
-                            String revert[]= {"su","-c","chmod","751","/data/local"}; //change permission back to x only
-
-                            try {
-                                //Chmod the local directory for write access
-                                Process process = Runtime.getRuntime().exec(makeWritable);
-                                process.waitFor();
-
-                                Log.d("portbinder:","Changing permission on /data/local to allow write access");
-
-                                //Decompressing downloaded zip to local directory
-                                Decompress dwnld = new Decompress(downloadFile,"/data/local/" );
-                                dwnld.unzip();
-                                Log.v("portbinder:","Decompressing downloaded file");
-
-                                //Chmod the Portbinder to allow it to be executable
-                                process = Runtime.getRuntime().exec(allowExec);
-                                process.waitFor();
-                                Log.v("portbinder:","Changing permission on /data/local/bind to allow the binary to be executed");
-
-                                //Chmod the local directory to back to non-read/write access
-                                process = Runtime.getRuntime().exec(revert);
-                                process.waitFor();
-                                Log.v("portbinder:","Changing permission on /data/local back to no-write access");
-
-
-                            } catch (IOException e) {
-                                e.printStackTrace();
-                            } catch (InterruptedException e) {
-                                e.printStackTrace();
-                            }
-
-                            if(Device.updatePorthack()) //if successful
-                            {
-                                porthackText.setText(R.string.yes);
-                                porthackText.setTextColor(getResources().getColor(R.color.holo_dark_green));
-                            }
-
-                        }
-                    }
-                }
-            }
-        };
-
-        getActivity().registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
-
-            return v;
+		return v;
 	}
 
-	/**
-	 * {@inheritDoc}
-	 */
-	@Override
 	public void onViewCreated(View view, Bundle savedInstanceState) {
 		super.onViewCreated(view, savedInstanceState);
 
 		FragmentManager manager = this.getFragmentManager();
 		manager.beginTransaction().replace(R.id.settings_fragment_container, new PreferenceHostageFrament()).commit();
 	}
-
-    /**
-     * {@inheritDoc}
-     */
-    @Override
-    public void onDestroy() {
-        super.onDestroy();
-        getActivity().unregisterReceiver(receiver);
-
-    }
-
 }

+ 13 - 13
src/de/tudarmstadt/informatik/hostage/ui/fragment/StatisticsFragment.java

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.ui2.fragment;
+package de.tudarmstadt.informatik.hostage.ui.fragment;
 
 import android.annotation.SuppressLint;
 import android.app.Activity;
@@ -41,18 +41,18 @@ import java.util.HashMap;
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.logging.Record;
 import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
-import de.tudarmstadt.informatik.hostage.ui2.model.LogFilter;
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
-import de.tudarmstadt.informatik.hostage.ui2.adapter.StatisticListAdapter;
-import de.tudarmstadt.informatik.hostage.ui2.dialog.ChecklistDialog;
-import de.tudarmstadt.informatik.hostage.ui2.dialog.DateTimeDialogFragment;
-import de.tudarmstadt.informatik.hostage.ui2.helper.ColorSequenceGenerator;
-import de.tudarmstadt.informatik.hostage.ui2.model.PlotComparisonItem;
-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;
+import de.tudarmstadt.informatik.hostage.ui.model.LogFilter;
+import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
+import de.tudarmstadt.informatik.hostage.ui.adapter.StatisticListAdapter;
+import de.tudarmstadt.informatik.hostage.ui.dialog.ChecklistDialog;
+import de.tudarmstadt.informatik.hostage.ui.dialog.DateTimeDialogFragment;
+import de.tudarmstadt.informatik.hostage.ui.helper.ColorSequenceGenerator;
+import de.tudarmstadt.informatik.hostage.ui.model.PlotComparisonItem;
+import de.tudarmstadt.informatik.hostage.ui.popup.AbstractPopup;
+import de.tudarmstadt.informatik.hostage.ui.popup.AbstractPopupItem;
+import de.tudarmstadt.informatik.hostage.ui.popup.SimplePopupItem;
+import de.tudarmstadt.informatik.hostage.ui.popup.SimplePopupTable;
+import de.tudarmstadt.informatik.hostage.ui.popup.SplitPopupItem;
 
 /**
  * Created by Julien on 16.02.14.

+ 4 - 4
src/de/tudarmstadt/informatik/hostage/ui/fragment/ThreatMapFragment.java

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.ui2.fragment;
+package de.tudarmstadt.informatik.hostage.ui.fragment;
 
 import static com.google.android.gms.common.GooglePlayServicesUtil.getErrorDialog;
 import static com.google.android.gms.common.GooglePlayServicesUtil.isGooglePlayServicesAvailable;
@@ -40,8 +40,8 @@ import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
 import de.tudarmstadt.informatik.hostage.logging.Record;
 import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
-import de.tudarmstadt.informatik.hostage.ui2.model.LogFilter;
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
+import de.tudarmstadt.informatik.hostage.ui.model.LogFilter;
+import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
 
 /**
  * ThreatMapFragment
@@ -107,7 +107,7 @@ public class ThreatMapFragment extends TrackerFragment implements GoogleMap.OnIn
 		recordOverviewFragment.setGroupKey("ESSID");
 		recordOverviewFragment.setAllowBack(true);
 
-		MainActivity.getInstance().injectFragment(recordOverviewFragment);
+		MainActivity.getInstance().injectFragment(recordOverviewFragment, false);
 		//recordOverviewFragment.showDetailsForSSID(getActivity(), ssid);
 		//}
 	}

+ 2 - 30
src/de/tudarmstadt/informatik/hostage/ui/fragment/UpNavigatibleFragment.java

@@ -1,57 +1,29 @@
-package de.tudarmstadt.informatik.hostage.ui2.fragment;
+package de.tudarmstadt.informatik.hostage.ui.fragment;
 
 import android.app.Fragment;
 
 /**
- * This abstract fragments allows the definition of an child - parent relation of fragments. It is necessary for the app to allow Up navigation of fragments.
- *
  * @author Alexander Brakowski
  * @created 12.03.14 16:20
  */
-public abstract class UpNavigatibleFragment extends TrackerFragment {
-	/**
-	 * Holds a reference to the parent fragment
-	 */
+public abstract class UpNavigatibleFragment extends Fragment {
 	private Class<?> mUpFragment;
-
-	/**
-	 * Indicates whether the fragment is up navigatible
-	 */
 	private boolean mIsUpNavigatible = false;
 
 	private boolean mAllowBack = false;
 
-	/**
-	 * Retrieves the parent fragment to be used for up navigation
-	 * @return the parent fragment
-	 */
 	public Class<?> getUpFragment(){
 		return mUpFragment;
 	}
 
-	/**
-	 * Sets the parent fragment of this fragment.
-	 * @param upFragment the fragment to set as parent
-	 */
 	public void setUpFragment(Class<?> upFragment){
 		this.mUpFragment = upFragment;
 	}
 
-	/**
-	 * Checks whether this fragment can be navigated up
-	 *
-	 * @return true if this fragment can be up navigated,
-	 *         false otherwise
-	 */
 	public boolean isUpNavigatible(){
 		return mIsUpNavigatible;
 	}
 
-	/**
-	 * Sets the state of up navigation for this fragment
-	 * @param isUpNavigatible true to allow up navigation
-	 *                        false no up navigation
-	 */
 	public void setUpNavigatible(boolean isUpNavigatible){
 		this.mIsUpNavigatible = isUpNavigatible;
 	}

+ 1 - 1
src/de/tudarmstadt/informatik/hostage/ui/fragment/opengl/AnimatedMesh.java

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.ui2.fragment.opengl;
+package de.tudarmstadt.informatik.hostage.ui.fragment.opengl;
 
 import java.io.ByteArrayOutputStream;
 import java.io.InputStream;

+ 1 - 1
src/de/tudarmstadt/informatik/hostage/ui/fragment/opengl/HomeGLSurfaceView.java

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.ui2.fragment.opengl;
+package de.tudarmstadt.informatik.hostage.ui.fragment.opengl;
 
 import android.content.Context;
 import android.opengl.GLSurfaceView;

+ 1 - 1
src/de/tudarmstadt/informatik/hostage/ui/fragment/opengl/Quaternion.java

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.ui2.fragment.opengl;
+package de.tudarmstadt.informatik.hostage.ui.fragment.opengl;
 
 /**
  * some basic quaternion class because android doesn't provide any

+ 1 - 1
src/de/tudarmstadt/informatik/hostage/ui/fragment/opengl/ThreatIndicatorGLRenderer.java

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.ui2.fragment.opengl;
+package de.tudarmstadt.informatik.hostage.ui.fragment.opengl;
 
 import java.io.IOException;
 import java.io.InputStream;

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

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.ui2.helper;
+package de.tudarmstadt.informatik.hostage.ui.helper;
 
 import android.graphics.Color;
 

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

@@ -4,7 +4,7 @@
  *
  * Modified by Alexander Brakowski for the purpose of this project
  */
-package de.tudarmstadt.informatik.hostage.ui2.layouts;
+package de.tudarmstadt.informatik.hostage.ui.layouts;
 
 
 import android.content.Context;

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

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.ui2.model;
+package de.tudarmstadt.informatik.hostage.ui.model;
 
 import android.widget.ImageView;
 import android.widget.TextView;

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

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.ui2.model;
+package de.tudarmstadt.informatik.hostage.ui.model;
 
 import java.util.HashMap;
 

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

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.ui2.model;
+package de.tudarmstadt.informatik.hostage.ui.model;
 
 import java.util.ArrayList;
 

+ 31 - 0
src/de/tudarmstadt/informatik/hostage/ui/model/ProfileListItem.java

@@ -0,0 +1,31 @@
+package de.tudarmstadt.informatik.hostage.ui.model;
+
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+
+import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
+
+/**
+ * @author Alexander Brakowski
+ * @created 14.01.14 18:04
+ */
+public class ProfileListItem {
+    public String label;
+    public String text;
+
+    public boolean activated;
+    public Bitmap icon;
+
+	public boolean isBackVisible = false;
+
+    public ProfileListItem(String text, String label, Bitmap icon){
+        this.text = text;
+        this.label = label;
+        this.activated = false;
+        this.icon = icon;
+    }
+
+    public ProfileListItem(String text, String label, int icon){
+        this(text, label, BitmapFactory.decodeResource(MainActivity.context.getResources(), icon));
+    }
+}

+ 6 - 6
src/de/tudarmstadt/informatik/hostage/ui/popup/AbstractPopup.java

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.ui2.popup;
+package de.tudarmstadt.informatik.hostage.ui.popup;
 
 import android.app.Activity;
 import android.content.Context;
@@ -48,14 +48,14 @@ public abstract class AbstractPopup {
 
     /**
      * Override to make additional stuff with the rootview.
-     * @param view rootview
+     * @param View rootview
      */
     abstract void configureView(View view);
 
     /**
      * Constructor
-     * @param context Context
-     * @param  listener OnPopupItemClickListener
+     * @param Context context
+     * @param OnPopupItemClickListener listener
      */
     public AbstractPopup(Context context, OnPopupItemClickListener listener) {
         super();
@@ -84,7 +84,7 @@ public abstract class AbstractPopup {
 
     /**
      * Adds a table row item.
-     * @param item {@link de.tudarmstadt.informatik.hostage.ui2.popup.AbstractPopupItem AbstractPopupItem}
+     * @param AbstractPopupItem item
      */
     public void addItem(final AbstractPopupItem item)	{
         View view = item.getRootView();
@@ -131,7 +131,7 @@ public abstract class AbstractPopup {
 
     /**
      * Opens the Popup View on top of the given anchor.
-     * @param anchorView View
+     * @param View anchorView
      */
     public void showOnView(final View anchorView)	{
         if (this.rootView == null){

+ 2 - 2
src/de/tudarmstadt/informatik/hostage/ui/popup/AbstractPopupItem.java

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.ui2.popup;
+package de.tudarmstadt.informatik.hostage.ui.popup;
 
 import android.content.Context;
 import android.view.LayoutInflater;
@@ -130,4 +130,4 @@ public abstract class AbstractPopupItem {
 	public void onItemDeselect(MotionEvent event){
 
 	}
-}
+}

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

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.ui2.popup;
+package de.tudarmstadt.informatik.hostage.ui.popup;
 
 import android.content.Context;
 import android.view.MotionEvent;

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

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.ui2.popup;
+package de.tudarmstadt.informatik.hostage.ui.popup;
 
 import android.content.Context;
 import android.view.View;

+ 2 - 2
src/de/tudarmstadt/informatik/hostage/ui/popup/SplitPopupItem.java

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.ui2.popup;
+package de.tudarmstadt.informatik.hostage.ui.popup;
 
 import android.content.Context;
 import android.view.MotionEvent;
@@ -26,7 +26,7 @@ public class SplitPopupItem extends AbstractPopupItem {
     /**
      * Constructor
      *
-     * @param  context Context
+     * @param Context context
      */
     public SplitPopupItem(Context context){
         super(context);

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

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.ui2.swipelist;
+package de.tudarmstadt.informatik.hostage.ui.swipelist;
 
 import android.content.Context;
 import android.util.AttributeSet;

+ 38 - 0
src/de/tudarmstadt/informatik/hostage/ui/task/LoaderTask.java

@@ -0,0 +1,38 @@
+package de.tudarmstadt.informatik.hostage.ui.task;
+
+import android.annotation.SuppressLint;
+import android.os.AsyncTask;
+
+/**
+ * Created by Julien on 23.03.14.
+ */
+public class LoaderTask extends AsyncTask<Void, Void, Void> {
+
+    private TaskListener listener;
+
+    @SuppressLint("ValidFragment")
+    public interface TaskListener {
+        public void doInBackgorund();
+        public void onFinish();
+    }
+
+    public LoaderTask(TaskListener listener){
+        super();
+        this.listener = listener;
+    }
+
+    @Override
+    protected Void doInBackground(Void... unused) {
+        if (this.listener != null){
+            this.listener.doInBackgorund();
+        }
+        return(null);
+    }
+
+    @Override
+    protected void onPostExecute(Void unused) {
+        if (this.listener != null){
+            this.listener.onFinish();
+        }
+    }
+}

+ 2 - 1
src/de/tudarmstadt/informatik/hostage/wrapper/Packet.java

@@ -58,7 +58,8 @@ public class Packet {
 	public String toString() {
 		if (protocol.equals("FTP") 
 				|| protocol.equals("HTTP") 
-				|| protocol.equals("HTTPS")) {
+				|| protocol.equals("HTTPS")
+				|| protocol.equals("SIP")) {
 			return new String(payload);
 		} else {
 			return HelperUtils.bytesToHexString(payload);