Browse Source

Merged rc - branch and small clean up

Lars Pandikow 10 years ago
parent
commit
66b19427a8
80 changed files with 5038 additions and 5204 deletions
  1. 6 27
      AndroidManifest.xml
  2. 0 189
      res/layout/activity_main.xml
  3. 0 62
      res/layout/activity_playground.xml
  4. 0 127
      res/layout/activity_viewlog.xml
  5. 1 1
      res/layout/fragment_home.xml
  6. 1 1
      res/layout/fragment_profile_manager.xml
  7. 1 2
      res/layout/fragment_record_list.xml
  8. 2 4
      res/layout/fragment_record_overview.xml
  9. 3 3
      res/layout/profile_manager_list_item.xml
  10. 1 1
      src/com/echo/holographlibrary/BarGraph.java
  11. 42 35
      src/com/echo/holographlibrary/LineGraph.java
  12. 18 9
      src/com/echo/holographlibrary/PieGraph.java
  13. 56 14
      src/de/tudarmstadt/informatik/hostage/Hostage.java
  14. 8 0
      src/de/tudarmstadt/informatik/hostage/commons/HelperUtils.java
  15. 0 393
      src/de/tudarmstadt/informatik/hostage/dao/ProfileManager.java
  16. 1 10
      src/de/tudarmstadt/informatik/hostage/logging/AttackRecord.java
  17. 2 3
      src/de/tudarmstadt/informatik/hostage/logging/LogExport.java
  18. 12 0
      src/de/tudarmstadt/informatik/hostage/model/JSONSerializable.java
  19. 62 8
      src/de/tudarmstadt/informatik/hostage/model/Profile.java
  20. 0 13
      src/de/tudarmstadt/informatik/hostage/model/ProfilesHolder.java
  21. 1 1
      src/de/tudarmstadt/informatik/hostage/net/MyServerSocketFactory.java
  22. 14 1
      src/de/tudarmstadt/informatik/hostage/persistence/HostageDBOpenHelper.java
  23. 665 0
      src/de/tudarmstadt/informatik/hostage/persistence/ProfileManager.java
  24. 2 1
      src/de/tudarmstadt/informatik/hostage/sync/nfc/NFCSyncActivity.java
  25. 0 35
      src/de/tudarmstadt/informatik/hostage/ui/AboutActivity.java
  26. 0 66
      src/de/tudarmstadt/informatik/hostage/ui/ListViewAdapter.java
  27. 245 245
      src/de/tudarmstadt/informatik/hostage/ui/LogFilter.java
  28. 0 610
      src/de/tudarmstadt/informatik/hostage/ui/MainActivity.java
  29. 0 107
      src/de/tudarmstadt/informatik/hostage/ui/PlayGroundActivity.java
  30. 0 194
      src/de/tudarmstadt/informatik/hostage/ui/SettingsActivity.java
  31. 108 65
      src/de/tudarmstadt/informatik/hostage/ui/activity/MainActivity.java
  32. 2 2
      src/de/tudarmstadt/informatik/hostage/ui/activity/ProfileEditActivity.java
  33. 2 2
      src/de/tudarmstadt/informatik/hostage/ui/adapter/DrawerListAdapter.java
  34. 2 2
      src/de/tudarmstadt/informatik/hostage/ui/adapter/ExpandableListAdapter.java
  35. 205 0
      src/de/tudarmstadt/informatik/hostage/ui/adapter/ProfileManagerListAdapter.java
  36. 2 2
      src/de/tudarmstadt/informatik/hostage/ui/adapter/RecordListAdapter.java
  37. 309 0
      src/de/tudarmstadt/informatik/hostage/ui/adapter/ServicesListAdapter.java
  38. 2 2
      src/de/tudarmstadt/informatik/hostage/ui/adapter/StatisticListAdapter.java
  39. 182 164
      src/de/tudarmstadt/informatik/hostage/ui/dialog/ChecklistDialog.java
  40. 244 244
      src/de/tudarmstadt/informatik/hostage/ui/dialog/DateTimeDialogFragment.java
  41. 31 30
      src/de/tudarmstadt/informatik/hostage/ui/dialog/TimePickerFragment.java
  42. 1 1
      src/de/tudarmstadt/informatik/hostage/ui/fragment/AboutFragment.java
  43. 2 2
      src/de/tudarmstadt/informatik/hostage/ui/fragment/ConnectionInfoDialogFragment.java
  44. 98 93
      src/de/tudarmstadt/informatik/hostage/ui/fragment/HomeFragment.java
  45. 1 1
      src/de/tudarmstadt/informatik/hostage/ui/fragment/PreferenceHostageFrament.java
  46. 17 10
      src/de/tudarmstadt/informatik/hostage/ui/fragment/ProfileEditFragment.java
  47. 36 6
      src/de/tudarmstadt/informatik/hostage/ui/fragment/ProfileManagerFragment.java
  48. 39 1
      src/de/tudarmstadt/informatik/hostage/ui/fragment/RecordDetailFragment.java
  49. 12 17
      src/de/tudarmstadt/informatik/hostage/ui/fragment/RecordOverviewFragment.java
  50. 318 0
      src/de/tudarmstadt/informatik/hostage/ui/fragment/ServicesFragment.java
  51. 1 1
      src/de/tudarmstadt/informatik/hostage/ui/fragment/SettingsFragment.java
  52. 1830 0
      src/de/tudarmstadt/informatik/hostage/ui/fragment/StatisticsFragment.java
  53. 154 104
      src/de/tudarmstadt/informatik/hostage/ui/fragment/ThreatMapFragment.java
  54. 11 1
      src/de/tudarmstadt/informatik/hostage/ui/fragment/UpNavigatibleFragment.java
  55. 4 1
      src/de/tudarmstadt/informatik/hostage/ui/fragment/opengl/AnimatedMesh.java
  56. 1 1
      src/de/tudarmstadt/informatik/hostage/ui/fragment/opengl/HomeGLSurfaceView.java
  57. 1 1
      src/de/tudarmstadt/informatik/hostage/ui/fragment/opengl/Quaternion.java
  58. 1 1
      src/de/tudarmstadt/informatik/hostage/ui/fragment/opengl/ThreatIndicatorGLRenderer.java
  59. 1 1
      src/de/tudarmstadt/informatik/hostage/ui/helper/ColorSequenceGenerator.java
  60. 7 1
      src/de/tudarmstadt/informatik/hostage/ui/layouts/FlowLayout.java
  61. 1 1
      src/de/tudarmstadt/informatik/hostage/ui/model/DrawerListItem.java
  62. 1 1
      src/de/tudarmstadt/informatik/hostage/ui/model/ExpandableListItem.java
  63. 7 6
      src/de/tudarmstadt/informatik/hostage/ui/model/PlotComparisonItem.java
  64. 2 2
      src/de/tudarmstadt/informatik/hostage/ui/model/ProfileListItem.java
  65. 24 0
      src/de/tudarmstadt/informatik/hostage/ui/model/ServicesListItem.java
  66. 43 4
      src/de/tudarmstadt/informatik/hostage/ui/popup/AbstractPopup.java
  67. 129 0
      src/de/tudarmstadt/informatik/hostage/ui/popup/AbstractPopupItem.java
  68. 3 3
      src/de/tudarmstadt/informatik/hostage/ui/popup/SimplePopupItem.java
  69. 1 1
      src/de/tudarmstadt/informatik/hostage/ui/popup/SimplePopupTable.java
  70. 21 5
      src/de/tudarmstadt/informatik/hostage/ui/popup/SplitPopupItem.java
  71. 1 1
      src/de/tudarmstadt/informatik/hostage/ui/swipelist/SwipeListView.java
  72. 38 0
      src/de/tudarmstadt/informatik/hostage/ui/task/LoaderTask.java
  73. 0 188
      src/de/tudarmstadt/informatik/hostage/ui2/adapter/ProfileManagerListAdapter.java
  74. 0 165
      src/de/tudarmstadt/informatik/hostage/ui2/adapter/ServicesListAdapter.java
  75. 0 229
      src/de/tudarmstadt/informatik/hostage/ui2/fragment/ServicesFragment.java
  76. 0 1479
      src/de/tudarmstadt/informatik/hostage/ui2/fragment/StatisticsFragment.java
  77. 0 60
      src/de/tudarmstadt/informatik/hostage/ui2/listeners/OnSwipeTouchListener.java
  78. 0 16
      src/de/tudarmstadt/informatik/hostage/ui2/model/ServicesListItem.java
  79. 0 84
      src/de/tudarmstadt/informatik/hostage/ui2/popup/AbstractPopupItem.java
  80. 0 41
      src/de/tudarmstadt/informatik/hostage/ui2/preference/ImageSelectPreference.java

+ 6 - 27
AndroidManifest.xml

@@ -44,7 +44,7 @@
          	android:value="true" />
 
         <activity
-            android:name="de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity"
+            android:name="de.tudarmstadt.informatik.hostage.ui.activity.MainActivity"
             android:configChanges="keyboardHidden|orientation|screenSize"
             android:label="@string/app_name"
             android:screenOrientation="portrait" >  
@@ -54,34 +54,9 @@
             </intent-filter>                   
         </activity>
         <activity
-            android:name="de.tudarmstadt.informatik.hostage.ui.MainActivity"
-            android:configChanges="keyboardHidden|orientation|screenSize"
-            android:label="@string/app_name" >         
-        </activity>
-        <activity
-            android:name="de.tudarmstadt.informatik.hostage.ui.ViewLog"
-            android:label="@string/statistics" >
-        </activity>
-        <activity
-            android:name="de.tudarmstadt.informatik.hostage.ui.ViewLogTable"
-            android:label="@string/database" >
-        </activity>
-        <activity
-            android:name=".ui2.activity.ProfileEditActivity"
+            android:name="de.tudarmstadt.informatik.hostage.ui.activity.ProfileEditActivity"
             android:label="Edit Profile" >
         </activity>
-        <activity
-            android:name="de.tudarmstadt.informatik.hostage.ui.SettingsActivity"
-            android:label="@string/settings" >
-        </activity>
-        <activity
-            android:name="de.tudarmstadt.informatik.hostage.ui.AboutActivity"
-            android:label="@string/gui_action_about" >
-        </activity>
-        <activity
-            android:name="de.tudarmstadt.informatik.hostage.ui.PlayGroundActivity"
-            android:label="@string/gui_playground" >
-        </activity>
         <activity
             android:name="de.tudarmstadt.informatik.hostage.sync.tracing.TracingSyncActivity"
             android:label="@string/gui_tracing"
@@ -113,6 +88,10 @@
             android:name="de.tudarmstadt.informatik.hostage.logging.Logger"
             android:exported="false" >
         </service>
+	    <service
+		    android:name="de.tudarmstadt.informatik.hostage.logging.LogExport"
+	        android:exported="false">
+	    </service>        
         <service
             android:name="de.tudarmstadt.informatik.hostage.sync.tracing.TracingSyncService"
             android:exported="false" >

+ 0 - 189
res/layout/activity_main.xml

@@ -1,189 +0,0 @@
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:tools="http://schemas.android.com/tools"
-    android:layout_width="match_parent"
-    android:layout_height="match_parent"
-    android:paddingBottom="@dimen/activity_vertical_margin"
-    android:paddingLeft="@dimen/activity_horizontal_margin"
-    android:paddingRight="@dimen/activity_horizontal_margin"
-    android:paddingTop="@dimen/activity_vertical_margin"
-    tools:context=".MainActivity" >
-
-    <ViewAnimator
-        android:id="@+id/viewAnimator"
-        android:layout_width="match_parent"
-        android:layout_height="match_parent" >
-
-        <RelativeLayout
-            android:layout_width="match_parent"
-            android:layout_height="match_parent" >
-
-            <TextView
-                android:id="@+id/textViewStatus"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:layout_above="@+id/imageViewLight"
-                android:layout_centerHorizontal="true"
-                android:text="@string/gui_status"
-                android:textAppearance="?android:attr/textAppearanceLarge" />
-
-            <ImageView
-                android:id="@+id/imageViewLight"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:layout_centerHorizontal="true"
-                android:layout_centerVertical="true"
-                android:src="@drawable/light_grey_large" />
-
-            <CheckBox
-                android:id="@+id/checkBoxParanoid"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:layout_alignParentBottom="true"
-                android:layout_alignParentLeft="true"
-                android:text="@string/gui_paranoid" />
-
-            <ToggleButton
-                android:id="@+id/toggleButtonOnOff"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:layout_alignParentBottom="true"
-                android:layout_alignParentRight="true"
-                android:onClick="buttonOnOffClick"
-                android:textOff="@string/gui_capital_off"
-                android:textOn="@string/gui_capital_on" />
-
-            <Button
-                android:id="@+id/buttonShowLog"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:layout_alignParentLeft="true"
-                android:layout_alignParentTop="true"
-                android:onClick="showLog"
-                android:text="Show Log" />
-
-            <Button
-                android:id="@+id/buttonPlayGround"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:layout_alignParentTop="true"
-                android:layout_toRightOf="@+id/buttonShowLog"
-                android:onClick="startPlayGround"
-                android:text="PlayGround" />
-
-        </RelativeLayout>
-
-        <LinearLayout
-            android:layout_width="match_parent"
-            android:layout_height="match_parent"
-            android:orientation="vertical" >
-
-            <TextView
-                android:id="@+id/textViewDetails"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:text="@string/gui_details"
-                android:textAppearance="?android:attr/textAppearanceLarge" />
-
-            <LinearLayout
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content" >
-
-                <TextView
-                    android:id="@+id/textViewSSID"
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:paddingLeft="20dp"
-                    android:text="@string/gui_ssid"
-                    android:textAppearance="?android:attr/textAppearanceMedium" />
-
-                <TextView
-                    android:id="@+id/textViewSSIDValue"
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:paddingLeft="5dp"
-                    android:text="-"
-                    android:textAppearance="?android:attr/textAppearanceMedium" />
-            </LinearLayout>
-
-            <LinearLayout
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content" >
-
-                <TextView
-                    android:id="@+id/textViewBSSID"
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:paddingLeft="20dp"
-                    android:text="@string/gui_bssid"
-                    android:textAppearance="?android:attr/textAppearanceMedium" />
-
-                <TextView
-                    android:id="@+id/textViewBSSIDValue"
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:paddingLeft="5dp"
-                    android:text="-"
-                    android:textAppearance="?android:attr/textAppearanceMedium" />
-            </LinearLayout>
-
-            <LinearLayout
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content" >
-
-                <TextView
-                    android:id="@+id/textViewInternalIP"
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:paddingLeft="20dp"
-                    android:text="@string/gui_internal_ip"
-                    android:textAppearance="?android:attr/textAppearanceMedium" />
-
-                <TextView
-                    android:id="@+id/textViewInternalIPValue"
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:paddingLeft="5dp"
-                    android:text="-"
-                    android:textAppearance="?android:attr/textAppearanceMedium" />
-            </LinearLayout>
-            
-            <LinearLayout
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content" >
-
-                <TextView
-                    android:id="@+id/textViewExternalIP"
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:paddingLeft="20dp"
-                    android:text="@string/gui_external_ip"
-                    android:textAppearance="?android:attr/textAppearanceMedium" />
-
-                <TextView
-                    android:id="@+id/textViewExternalIPValue"
-                    android:layout_width="wrap_content"
-                    android:layout_height="wrap_content"
-                    android:paddingLeft="5dp"
-                    android:text="-"
-                    android:textAppearance="?android:attr/textAppearanceMedium" />
-            </LinearLayout>
-
-            <TextView
-                android:id="@+id/TextViewServices"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:text="@string/gui_services"
-                android:textAppearance="?android:attr/textAppearanceLarge" />
-
-            <ListView
-                android:id="@+id/listViewProtocols"
-                android:layout_width="match_parent"
-                android:layout_height="wrap_content"
-                android:divider="#b5b5b5"
-                android:dividerHeight="1dp"
-                android:entries="@array/protocols" >
-            </ListView>
-        </LinearLayout>
-    </ViewAnimator>
-
-</RelativeLayout>

+ 0 - 62
res/layout/activity_playground.xml

@@ -1,62 +0,0 @@
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:tools="http://schemas.android.com/tools"
-    android:layout_width="match_parent"
-    android:layout_height="wrap_content"
-    android:orientation="vertical"
-    android:paddingBottom="@dimen/activity_vertical_margin"
-    android:paddingLeft="@dimen/activity_horizontal_margin"
-    android:paddingRight="@dimen/activity_horizontal_margin"
-    android:paddingTop="@dimen/activity_vertical_margin" >
-
-    <LinearLayout
-        android:layout_width="match_parent"
-        android:layout_height="wrap_content"
-        android:orientation="horizontal" >
-
-        <Button
-            android:id="@+id/buttonBluetooth"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:onClick="startBluetooth"
-            android:text="Bluetooth" />
-        
-        <Button
-            android:id="@+id/buttonNFC"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:onClick="startNFC"
-            android:text="NFC" />
-        
-        <Button
-            android:id="@+id/buttonServer"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:onClick="startServer"
-            android:text="Server" />
-        
-
-        
-
-    </LinearLayout>
-
-    <Button
-        android:id="@+id/buttonCreateNetwork"
-        android:layout_width="wrap_content"
-        android:layout_height="wrap_content"
-        android:onClick="createNetworkData"
-        android:text="Create Network Data" />
-
-    <ScrollView
-        android:layout_width="match_parent"
-        android:layout_height="wrap_content"
-        >
-
-        <TextView
-            android:id="@+id/textView1"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:text="TextView" />
-         
-    </ScrollView>
-
-</LinearLayout>

+ 0 - 127
res/layout/activity_viewlog.xml

@@ -1,127 +0,0 @@
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:tools="http://schemas.android.com/tools"
-    android:layout_width="fill_parent"
-    android:layout_height="fill_parent"
-	android:scrollbars="none">
-
-   <LinearLayout
-        android:layout_width="match_parent"
-        android:layout_height="wrap_content"
-        android:orientation="vertical"
-        android:paddingBottom="@dimen/activity_vertical_margin"
-    	android:paddingLeft="@dimen/activity_horizontal_margin"
-    	android:paddingRight="@dimen/activity_horizontal_margin"
-    	android:paddingTop="@dimen/activity_vertical_margin" >
-
-        <TextView
-            android:id="@+id/textStatistics"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:text="@string/gui_statistics"
-            android:textAppearance="?android:attr/textAppearanceLarge" />
-
-        <TableLayout
-            android:id="@+id/layoutContainer"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:orientation="vertical" >
-        </TableLayout>
-
-        <LinearLayout
-            android:layout_width="match_parent"
-            android:layout_height="wrap_content"
-            android:orientation="horizontal" >
-
-            <TextView
-                android:id="@+id/textFirstAttack"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:text="@string/gui_firstAttack"
-                android:textAppearance="?android:attr/textAppearanceMedium" />
-
-            <TextView
-                android:id="@+id/textFirstAttackValue"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:paddingLeft="2dp"
-                android:text=""
-                android:textAppearance="?android:attr/textAppearanceMedium" />
-        </LinearLayout>
-
-        <LinearLayout
-            android:layout_width="match_parent"
-            android:layout_height="wrap_content"
-            android:orientation="horizontal" >
-
-            <TextView
-                android:id="@+id/textLastAttack"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:text="@string/gui_lastAttack"
-                android:textAppearance="?android:attr/textAppearanceMedium" />
-
-            <TextView
-                android:id="@+id/textLastAttackValue"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:paddingLeft="2dp"
-                android:text=""
-                android:textAppearance="?android:attr/textAppearanceMedium" />
-        </LinearLayout>
-
-        <TextView
-            android:id="@+id/textLogFile"
-            android:layout_width="wrap_content"
-            android:layout_height="wrap_content"
-            android:text="@string/gui_log_actions"
-            android:textAppearance="?android:attr/textAppearanceLarge" />
-
-        <LinearLayout
-            android:layout_width="match_parent"
-            android:layout_height="wrap_content"
-            android:orientation="horizontal" >
-
-            <Button
-                android:id="@+id/buttonShowLog"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:onClick="showLog"
-                android:text="Show Log" />
-
-            <Button
-                android:id="@+id/buttonExportDatabase"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:onClick="exportDatabase"
-                android:text="Export Database" />
-        </LinearLayout>
-
-        <LinearLayout
-            android:layout_width="match_parent"
-            android:layout_height="wrap_content"
-            android:orientation="horizontal" >
-
-            <Button
-                android:id="@+id/buttonUploadLog"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:onClick="uploadDatabase"
-                android:text="Upload Log" />
-
-            <Button
-                android:id="@+id/buttonDeleteLog"
-                android:layout_width="wrap_content"
-                android:layout_height="wrap_content"
-                android:onClick="deleteLog"
-                android:text="Delete Log" />
-        </LinearLayout>
-    </LinearLayout>
-
-        <TableLayout
-            android:id="@+id/attack_info"
-            android:layout_width="fill_parent"
-            android:layout_height="fill_parent"
-            android:orientation="vertical" >
-        </TableLayout>
-
-</RelativeLayout>

+ 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"

+ 1 - 2
res/layout/fragment_record_list.xml

@@ -5,7 +5,7 @@
     android:background="@android:color/transparent"
     >
 
-    <ProgressBar
+    <ProgressBar 
         android:id="@+id/progressBar1"
         style="?android:attr/progressBarStyleLarge"
         android:layout_width="wrap_content"
@@ -15,7 +15,6 @@
         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"

+ 2 - 4
res/layout/fragment_record_overview.xml

@@ -6,16 +6,14 @@
             android:id="@+id/scrollView"
             android:fillViewport="true">
 
-	<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-				  android:orientation="vertical"
+	<LinearLayout android:orientation="vertical"
 				  android:layout_width="match_parent"
 				  android:layout_height="wrap_content"
 				  android:measureWithLargestChild="false"
 				  android:baselineAligned="true"
 				  android:id="@+id/linearLayout3">
 
-		<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-					  android:orientation="vertical"
+		<LinearLayout  android:orientation="vertical"
 					  android:layout_width="match_parent"
 					  android:layout_height="wrap_content"
 					  android:measureWithLargestChild="false"

+ 3 - 3
res/layout/profile_manager_list_item.xml

@@ -58,7 +58,7 @@
         </LinearLayout>
 
     </RelativeLayout>
-	<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+	<RelativeLayout 
 	                android:id="@+id/swipelist_frontview"
 	                android:layout_width="match_parent"
 	                android:layout_height="match_parent"
@@ -118,7 +118,7 @@
 	        android:layout_alignParentLeft="true"
 	        android:layout_alignParentStart="true" android:scaleType="centerInside"/>
 
-		<de.tudarmstadt.informatik.hostage.ui2.layouts.FlowLayout
+		<de.tudarmstadt.informatik.hostage.ui.layouts.FlowLayout
 				xmlns:f="http://schemas.android.com/apk/res/de.tudarmstadt.informatik.hostage"
 				android:orientation="horizontal"
 				android:layout_width="fill_parent"
@@ -167,7 +167,7 @@
 			<TextView style="@style/ProfileManagerListBadge" android:layout_width="wrap_content" android:layout_height="wrap_content"
 			          android:textAppearance="?android:attr/textAppearanceSmall" android:text="HTTP" android:id="@+id/textView7" android:layout_gravity="center_vertical"
 			          android:layout_marginLeft="10dp"/>
-		</de.tudarmstadt.informatik.hostage.ui2.layouts.FlowLayout>
+		</de.tudarmstadt.informatik.hostage.ui.layouts.FlowLayout>
 
 	</RelativeLayout>
 

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

@@ -82,7 +82,7 @@ public class BarGraph extends View {
     public void setBars(ArrayList<Bar> points){
         this.mBars = points;
         mShouldUpdate = true;
-        postInvalidate();
+        //postInvalidate();
     }
     
     public ArrayList<Bar> getBars(){

+ 42 - 35
src/com/echo/holographlibrary/LineGraph.java

@@ -48,7 +48,7 @@ public class LineGraph extends View {
         public String convertDataForY_Position(double y);
     }
 
-    private final static int AXIS_LABEL_FONT_SIZE = 10;
+    private final static int AXIS_LABEL_FONT_SIZE = 8;
 
     private ArrayList<Line> lines = new ArrayList<Line>();
 	Paint paint = new Paint();
@@ -64,9 +64,8 @@ public class LineGraph extends View {
 	private Bitmap fullImage;
 	private boolean shouldUpdate = false;
 
-    static final float bottomPadding = 40, topPadding = 10;
-    static final float rightPadding = 10;
-    static final float leftPadding = 50;
+    static final float bottomPadding = 40, topPadding = 16;
+    static final float leftPadding = 50, rightPadding = 16;
     static final float sidePadding = rightPadding + leftPadding;
 
     private float xAxisStep = 4;
@@ -109,13 +108,13 @@ public class LineGraph extends View {
 			lines.remove(0);
 		}
 		shouldUpdate = true;
-		postInvalidate();
+		//postInvalidate();
 	}
 	
 	public void addLine(Line line) {
 		lines.add(line);
 		shouldUpdate = true;
-		postInvalidate();
+		//postInvalidate();
 	}
 	public void addPointToLine(int lineIndex, double x, double y){
 		addPointToLine(lineIndex, (float) x, (float) y);
@@ -146,7 +145,7 @@ public class LineGraph extends View {
 		lines.set(lineIndex, line);
 		resetLimits();
 		shouldUpdate = true;
-		postInvalidate();
+		//postInvalidate();
 	}
 	
 	public void addPointsToLine(int lineIndex, LinePoint[] points){
@@ -157,7 +156,7 @@ public class LineGraph extends View {
 		lines.set(lineIndex, line);
 		resetLimits();
 		shouldUpdate = true;
-		postInvalidate();
+		//postInvalidate();
 	}
 	
 	public void removeAllPointsAfter(int lineIndex, double x){
@@ -178,7 +177,7 @@ public class LineGraph extends View {
 		lines.set(lineIndex, line);
 		resetLimits();
 		shouldUpdate = true;
-		postInvalidate();
+		//postInvalidate();
 	}
 	public void removePointsFromLine(int lineIndex, LinePoint[] points){
 		Line line = getLine(lineIndex);
@@ -188,7 +187,7 @@ public class LineGraph extends View {
 		lines.set(lineIndex, line);
 		resetLimits();
 		shouldUpdate = true;
-		postInvalidate();
+		//postInvalidate();
 	}
 	public void removePointFromLine(int lineIndex, float x, float y){
 		LinePoint p = null;
@@ -202,7 +201,7 @@ public class LineGraph extends View {
 		lines.set(lineIndex, line);
 		resetLimits();
 		shouldUpdate = true;
-		postInvalidate();
+		//postInvalidate();
 	}
 	
 	public void resetYLimits(){
@@ -225,7 +224,7 @@ public class LineGraph extends View {
 	public void setLineToFill(int indexOfLine) {
 		this.lineToFill = indexOfLine;
 		shouldUpdate = true;
-		postInvalidate();
+		//postInvalidate();
 	}
 	public int getLineToFill(){
 		return lineToFill;
@@ -362,13 +361,12 @@ public class LineGraph extends View {
 	        // DRAW THE BACKGROUND
             //this.drawBackground(canvas);
 
+            paint.setAntiAlias(true);
+
             // DRAW THE AXIS
             this.drawAxis(canvas);
 
 
-            paint.reset();
-	        paint.setAntiAlias(true);
-
             // DRAW LINES
 			for (Line line : lines){
 				int count = 0;
@@ -446,20 +444,16 @@ public class LineGraph extends View {
 		}
 		
 		ca.drawBitmap(fullImage, 0, 0, null);
-		
-		
+
 	}
 
     private void drawAxis(Canvas canvas){
-        paint.reset();
-
-        double maxX = getMaxLimX();
-        double minX = getMinLimX();
+        //double maxX = getMaxLimX();
+        //double minX = getMinLimX();
+        //float usableWidth = getWidth() - 2*sidePadding;
+        //float usableHeight = getHeight() - bottomPadding - topPadding;
 
-        float usableWidth = getWidth() - 2*sidePadding;
-        float usableHeight = getHeight() - bottomPadding - topPadding;
-
-        float yPixels = getHeight() - (bottomPadding*3/5);
+        float yPixels = getHeight() - (bottomPadding - (10));
 
         // DRAW SEPERATOR
         paint.setColor(Color.BLACK);
@@ -471,27 +465,40 @@ public class LineGraph extends View {
         canvas.drawLine(leftPadding ,topPadding, leftPadding, yPixels, paint);
 
         paint.setAlpha(255);
+
+        this.drawAxisLabel(canvas);
+    }
+
+
+    private void drawAxisLabel(Canvas canvas){
         this.paint.setTextSize(AXIS_LABEL_FONT_SIZE * mContext.getResources().getDisplayMetrics().scaledDensity);
 
+        double maxX = getMaxLimX();
+        double minX = getMinLimX();
+
+        float usableWidth = getWidth() - 2*sidePadding;
+        float usableHeight = getHeight() - bottomPadding - topPadding;
+        float yPixels = getHeight() - (bottomPadding - (10));
+
+
         // Draw y-axis label text
-        //double skippedValue = (maxY - minY ) / (Math.max(1., yAxisStep));
         double step = Math.max(1., (maxY - minY) / (Math.max(1., yAxisStep)));
-
+        double v = 0;
         for (double y = minY; y <= maxY; y+=step){
             double yPercent = (y-minY)/(maxY - minY);
 
             double newYPixels = topPadding + (yPercent*usableHeight);
             canvas.drawLine((float)leftPadding,(float)newYPixels,(float)leftPadding-5.f,(float)newYPixels, paint);
-            String title = this.getY_AxisTitle(maxY - y);
+            String title = this.getY_AxisTitle(maxY - v);
             float textwidth = (this.paint.measureText(title));
             canvas.drawText(title, 5.f ,(float)newYPixels + (textwidth/2), this.paint);
 
-            //value+=skippedValue;
+            v+=step;
         }
 
+        this.paint.setTextSize(AXIS_LABEL_FONT_SIZE * mContext.getResources().getDisplayMetrics().scaledDensity);
+
         // Draw x-axis label text
-        //value = minX;
-        //skippedValue = (maxX - minX ) / (Math.max(1,xAxisStep));
         step = Math.max(1, (maxX - minX) / (Math.max(1, xAxisStep)));
 
         for (double x = minX; x <= maxX; x+=step){
@@ -501,12 +508,12 @@ public class LineGraph extends View {
             canvas.drawLine((float)newXPixels,(float) yPixels + 5,(float) newXPixels,(float) yPixels, paint);
             String title = this.getX_AxisTitle(x);
             float textwidth = (this.paint.measureText(title));
-            //this.paint.setTextSize(AXIS_LABEL_FONT_SIZE * mContext.getResources().getDisplayMetrics().scaledDensity);
-            canvas.drawText(title,(float) newXPixels - (textwidth/2),(float) yPixels + (bottomPadding / 2), this.paint);
 
-            //value+=skippedValue;
+            float x_Coord = Math.max(0.f, (float) (newXPixels - (textwidth / 2)));
+            x_Coord = Math.min(x_Coord, getWidth() - rightPadding);
+            float y_Coord =  (float) (yPixels + ((bottomPadding - 10) / 1));
+            canvas.drawText(title, x_Coord , y_Coord, this.paint);
         }
-        paint.reset();
     }
 
     private void drawBackground(Canvas canvas){

+ 18 - 9
src/com/echo/holographlibrary/PieGraph.java

@@ -39,9 +39,10 @@ import android.view.View;
 import android.widget.TextView;
 
 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 {
 
@@ -253,7 +254,7 @@ public class PieGraph extends View {
 	}
 	public void setSlices(ArrayList<PieSlice> slices) {
 		this.slices = slices;
-		postInvalidate();
+		//postInvalidate();
 	}
 	public PieSlice getSlice(int index) {
 		return slices.get(index);
@@ -263,12 +264,17 @@ public class PieGraph extends View {
 		    this.slices.add(slice);
 
         long countedValue = 0;
-        for (PieSlice s : this.slices){
-            countedValue+=s.getValue();
+
+        Iterator<PieSlice> iter = this.slices.iterator();
+
+        while (iter.hasNext()){
+            PieSlice s = iter.next();
+            countedValue+= s.getValue();
         }
+
         this.title = ALL_TITLE;
         this.subtitle = "" + countedValue;
-		postInvalidate();
+		//postInvalidate();
 	}
 	public void setOnSliceClickedListener(OnSliceClickedListener listener) {
 		this.listener = listener;
@@ -279,17 +285,20 @@ public class PieGraph extends View {
 	}
 	public void setThickness(int thickness) {
 		this.thickness = thickness;
-		postInvalidate();
+		//postInvalidate();
 	}
 	
 	public void removeSlices(){
-		for (int i = slices.size()-1; i >= 0; i--){
-			slices.remove(i);
+        Iterator<PieSlice> iter = slices.iterator();
+
+        while (iter.hasNext()) {
+            iter.next();
+            iter.remove();
 		}
         this.title = "";
         this.subtitle = "";
 
-		postInvalidate();
+		//postInvalidate();
 	}
 
 	public static interface OnSliceClickedListener {

+ 56 - 14
src/de/tudarmstadt/informatik/hostage/Hostage.java

@@ -1,6 +1,7 @@
 package de.tudarmstadt.informatik.hostage;
 
 import java.util.ArrayList;
+import java.util.HashMap;
 import java.util.LinkedList;
 import java.util.List;
 
@@ -36,7 +37,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.
@@ -50,6 +51,8 @@ import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
  */
 public class Hostage extends Service {
 
+	private HashMap<String, Boolean> mProtocolActiveAttacks;
+
 	public class LocalBinder extends Binder {
 		public Hostage getService() {
 			return Hostage.this;
@@ -167,15 +170,6 @@ public class Hostage extends Service {
 		return 0;
 	}
 
-	public boolean hasActiveAttacks() {
-		for (Listener listener : listeners) {
-			if (listener.getHandlerCount() > 0) {
-				return true;
-			}
-		}
-		return false;
-	}
-
 	/**
 	 * Determines if there any listener is currently running.
 	 * 
@@ -220,6 +214,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.
@@ -233,6 +237,7 @@ public class Hostage extends Service {
 		createNotification();
 		// Send Notification
 		if (sender.equals(Handler.class.getName()) && values[0].equals(R.string.broadcast_started)) {
+			this.mProtocolActiveAttacks.put(values[1], true);
 			attackNotification();
 		}
 		// Inform UI of Preference Change
@@ -255,6 +260,9 @@ 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();
 		registerNetReceiver();
 		updateConnectionInfo();
@@ -358,12 +366,24 @@ public class Hostage extends Service {
 			if (listener.getProtocolName().equals(protocolName) && listener.getPort() == port) {
 				if (listener.isRunning()) {
 					listener.stop();
+					mProtocolActiveAttacks.remove(protocolName);
 				}
 			}
 		}
 		// Toast.makeText(getApplicationContext(), protocolName +
 		// " SERVICE STOPPED!", Toast.LENGTH_SHORT).show();
 	}
+	
+	public void stopListenerAllPorts(String protocolName){
+		for(Listener listener: listeners){
+			if(listener.getProtocolName().equals(protocolName)){
+				if(listener.isRunning()){
+					listener.stop();
+					mProtocolActiveAttacks.remove(protocolName);
+				}
+			}
+		}
+	}
 
 	/**
 	 * Stops all running listeners.
@@ -372,6 +392,7 @@ public class Hostage extends Service {
 		for (Listener listener : listeners) {
 			if (listener.isRunning()) {
 				listener.stop();
+				mProtocolActiveAttacks.remove(listener.getProtocolName());
 			}
 		}
 		// Toast.makeText(getApplicationContext(), "SERVICES STOPPED!",
@@ -390,8 +411,11 @@ public class Hostage extends Service {
 		Intent launchIntent = new Intent(getApplicationContext(), MainActivity.class);
 		TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
 		stackBuilder.addParentStack(MainActivity.class);
-		stackBuilder.addNextIntent(launchIntent);
-		PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
+		Intent intent = MainActivity.getInstance().getIntent();
+		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
+		intent.setAction("SHOW_HOME");
+		stackBuilder.addNextIntent(intent);
+		PendingIntent resultPendingIntent = PendingIntent.getActivity(MainActivity.context, 0, intent, 0);
 		builder.setContentIntent(resultPendingIntent);
 		if (defaultPref.getBoolean("pref_vibration", false)) {
 			builder.setVibrate(new long[] { 100, 200, 100, 200 });
@@ -468,8 +492,11 @@ public class Hostage extends Service {
 		Intent launchIntent = new Intent(getApplicationContext(), MainActivity.class);
 		TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
 		stackBuilder.addParentStack(MainActivity.class);
-		stackBuilder.addNextIntent(launchIntent);
-		PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
+		Intent intent = MainActivity.getInstance().getIntent();
+		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
+		intent.setAction("SHOW_HOME");
+		stackBuilder.addNextIntent(intent);
+		PendingIntent resultPendingIntent = PendingIntent.getActivity(MainActivity.context, 0, intent, 0); //stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
 		builder.setContentIntent(resultPendingIntent);
 		builder.setOngoing(true);
 		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
@@ -551,6 +578,19 @@ public class Hostage extends Service {
 	private void unregisterNetReceiver() {
 		unregisterReceiver(netReceiver);
 	}
+	
+	public boolean hasProtocolActiveAttacks(String protocol){
+		if(!mProtocolActiveAttacks.containsKey(protocol)) return false;
+		return mProtocolActiveAttacks.get(protocol);
+	}
+
+	public boolean hasActiveAttacks(){
+		for(boolean b: mProtocolActiveAttacks.values()){
+			if(b) return true;
+		}
+
+		return false;
+	}
 
 	/**
 	 * Updates the connection info and saves them in the the SharedPreferences
@@ -569,6 +609,8 @@ public class Hostage extends Service {
 		editor.commit();
 		SetExternalIPTask async = new SetExternalIPTask();
 		async.execute(new String[] { "http://ip2country.sourceforge.net/ip2c.php?format=JSON" });
+
+		this.mProtocolActiveAttacks.clear();		
 	}
 
 }

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

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

+ 0 - 393
src/de/tudarmstadt/informatik/hostage/dao/ProfileManager.java

@@ -1,393 +0,0 @@
-package de.tudarmstadt.informatik.hostage.dao;
-
-import android.content.Context;
-
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.StreamCorruptedException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Random;
-
-import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.model.Profile;
-import de.tudarmstadt.informatik.hostage.model.ProfilesHolder;
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
-import de.tudarmstadt.informatik.hostage.ui2.adapter.ProfileManagerListAdapter;
-
-/**
- * @author Alexander Brakowski
- * @created 10.02.14 20:24
- */
-public class ProfileManager {
-	private static ProfileManager INSTANCE = null;
-
-	private ProfileManagerListAdapter mProfileListAdapter = null;
-	private Profile mCurrentActivatedProfile = null;
-	private Profile mRandomProfile = null;
-
-	private static final String PERSIST_FILENAME = "hostage_profiles.dat";
-
-	private ProfilesHolder holder;
-
-	public static ProfileManager getInstance(){
-		if(INSTANCE == null){
-			INSTANCE = new ProfileManager();
-		}
-
-		if(INSTANCE.getNumberOfProfiles() == 0){
-			INSTANCE.loadData();
-		}
-
-		return INSTANCE;
-	}
-
-	private ProfileManager(){
-		holder = new ProfilesHolder();
-		holder.mProfiles = new HashMap<Integer, Profile>();
-	}
-
-	public void loadData(){
-		try {
-			FileInputStream fin = MainActivity.getContext().openFileInput(PERSIST_FILENAME);
-			ObjectInputStream ois = new ObjectInputStream(fin);
-
-			Object obj = ois.readObject();
-			ois.close();
-			fin.close();
-
-			if(obj != null && obj instanceof ProfilesHolder){
-				this.holder = (ProfilesHolder) obj;
-
-				for(Map.Entry<Integer, Profile> entry: holder.mProfiles.entrySet()){
-					if(entry.getValue().mActivated){
-						this.mCurrentActivatedProfile = entry.getValue();
-					}
-
-					if(entry.getValue().mIsRandom){
-						this.mRandomProfile = entry.getValue();
-					}
-				}
-			}
-		} catch (FileNotFoundException e) {
-			e.printStackTrace();
-		} catch (StreamCorruptedException e) {
-			e.printStackTrace();
-		} catch (IOException e) {
-			e.printStackTrace();
-		} catch (ClassNotFoundException e) {
-			e.printStackTrace();
-		} finally {
-			if(holder.mProfiles.size() == 0){
-				this.fillWithDefaultData();
-				loadData();
-			}
-
-			if(this.mRandomProfile != null){
-				randomizeProtocols(mRandomProfile);
-			}
-		}
-	}
-
-	public void persistData(){
-		try {
-			FileOutputStream fout = MainActivity.getContext().openFileOutput(PERSIST_FILENAME, Context.MODE_PRIVATE);
-			ObjectOutputStream oos = new ObjectOutputStream(fout);
-
-			oos.writeObject(holder);
-			oos.close();
-			fout.close();
-		} catch (FileNotFoundException e) {
-			e.printStackTrace();
-		} catch (IOException e) {
-			e.printStackTrace();
-		}
-
-	}
-
-	public List<Profile> getProfilesList(){
-		return new ArrayList<Profile>(getProfilesCollection());
-	}
-
-	public Collection<Profile> getProfilesCollection(){
-		if(holder.mProfiles.size() == 0 || holder.mProfiles == null){
-			this.loadData();
-		}
-
-		return holder.mProfiles.values();
-	}
-
-	public Map<Integer, Profile> getMapProfiles(){
-		return holder.mProfiles;
-	}
-
-	public void randomizeProtocols(Profile profile){
-		LinkedList<String> protocols = new LinkedList<String>(Arrays.asList(MainActivity.getContext().getResources().getStringArray(R.array.protocols)));
-		protocols.remove("GHOST");
-
-		profile.mActiveProtocols.clear();
-
-		Random rand = new Random();
-		int numberOfProtocolsToActivate = rand.nextInt(protocols.size()) + 1;
-
-		while(numberOfProtocolsToActivate-- > 0){
-			int randomIndex = rand.nextInt(protocols.size());
-			String protocol = protocols.get(randomIndex);
-
-			profile.mActiveProtocols.put(protocol, true);
-			protocols.remove(protocol);
-		}
-
-		persistData();
-	}
-
-	public long persistProfile(Profile profile){
-		if(profile.mId == -1){
-			profile.mId = ++holder.mIncrementValue;
-		}
-
-		holder.mProfiles.put(profile.mId, profile);
-
-		this.persistData();
-
-		if(this.mProfileListAdapter != null){
-			this.mProfileListAdapter.notifyDataSetChanged();
-		}
-
-		return profile.mId;
-	}
-
-	public Profile getProfile(int id){
-		if(holder.mProfiles.size() == 0){
-			loadData();
-		}
-
-		if(this.holder.mProfiles.containsKey(id)){
-			return this.holder.mProfiles.get(id);
-		}
-
-		return null;
-	}
-
-	public void addProfile(Profile profile){
-		this.addProfile(profile, true);
-	}
-
-	public void addProfile(Profile profile, boolean persist){
-
-		if(profile.mId == -1){
-			profile.mId = ++holder.mIncrementValue;
-		}
-
-		holder.mProfiles.put(profile.mId, profile);
-
-		if(persist){
-			persistData();
-		}
-
-		if(this.mProfileListAdapter != null){
-			this.mProfileListAdapter.add(profile);
-			this.mProfileListAdapter.notifyDataSetChanged();
-		}
-	}
-
-	public void deleteProfile(Profile profile){
-		if(this.holder.mProfiles.containsKey(profile.mId)){
-			Profile p = getProfile(profile.mId);
-			this.holder.mProfiles.remove(profile.mId);
-
-			if(p.mActivated || this.mCurrentActivatedProfile.mId == p.mId){
-				mCurrentActivatedProfile = mRandomProfile;
-				mRandomProfile.mActivated = true;
-			}
-
-			this.persistData();
-			//this.dbh.deleteProfile(profile.mId);
-
-			if(this.mProfileListAdapter != null){
-				this.mProfileListAdapter.remove(profile);
-				this.mProfileListAdapter.notifyDataSetChanged();
-			}
-		}
-	}
-
-	public void clearProfiles(){
-		holder.mProfiles.clear();
-		persistData();
-	}
-
-	public void activateProfile(Profile profile){
-		if(profile.equals(this.mCurrentActivatedProfile)) return;
-
-		if(this.mCurrentActivatedProfile != null){
-			this.mCurrentActivatedProfile.mActivated = false;
-			this.persistProfile(this.mCurrentActivatedProfile);
-		}
-
-		profile.mActivated = true;
-		this.mCurrentActivatedProfile = profile;
-		this.holder.mProfiles.put(profile.mId, profile);
-		persistData();
-	}
-
-	public boolean isRandomActive(){
-		return this.mCurrentActivatedProfile.equals(this.mRandomProfile);
-	}
-
-	public Profile getRandomProfile(){
-		return this.mRandomProfile;
-	}
-
-	public Profile getCurrentActivatedProfile(){
-		return mCurrentActivatedProfile;
-	}
-
-	public void setProfileListAdapter(ProfileManagerListAdapter profileListAdapter){
-		this.mProfileListAdapter = profileListAdapter;
-	}
-
-
-	public ProfileManagerListAdapter getProfileListAdapter(){
-		return this.mProfileListAdapter;
-	}
-
-	public int getNumberOfProfiles(){
-		return holder.mProfiles.size();
-	}
-
-	public void fillWithDefaultData(){
-		Profile windowsVista = new Profile(
-				0,
-				"Windows Vista",
-				"This profile will imitate a Windows Vista machine",
-				R.drawable.ic_profile_vista,
-				false
-		);
-
-		windowsVista.mActiveProtocols.put("ECHO", true);
-		windowsVista.mActiveProtocols.put("TELNET", true);
-
-		this.addProfile(windowsVista, false);
-
-		Profile windowsXP = new Profile(
-				1,
-				"Windows XP",
-				"This profile will activate Windows XP typical services",
-				R.drawable.ic_profile_xp,
-				false
-		);
-
-		windowsXP.mActiveProtocols.put("ECHO", true);
-		windowsXP.mActiveProtocols.put("TELNET", true);
-		windowsXP.mActiveProtocols.put("MySQL", true);
-
-		this.addProfile(windowsXP, false);
-
-		Profile serverHTTP = new Profile(
-				2,
-				"Webserver HTTP",
-				"This profile will imitate a simple webserver, which just supports the HTTP protocol",
-				R.drawable.ic_profile_apache,
-				false
-		);
-
-		serverHTTP.mActiveProtocols.put("HTTP", true);
-
-		this.addProfile(serverHTTP, false);
-
-		Profile serverWeb = new Profile(
-				3,
-				"Webserver",
-				"This profile will imitate a simple webserver, which supports both the HTTP and HTTPS protocol",
-				R.drawable.ic_profile_apache,
-				false
-		);
-
-		serverWeb.mActiveProtocols.put("HTTP", true);
-		serverWeb.mActiveProtocols.put("HTTPS", true);
-
-		this.addProfile(serverWeb, false);
-
-		Profile unixMachine = new Profile(
-				4,
-				"Unix",
-				"This profile monitors unix typical services",
-				R.drawable.ic_profile_unix,
-				false
-		);
-
-		unixMachine.mActiveProtocols.put("SSH", true);
-		unixMachine.mActiveProtocols.put("ECHO", true);
-
-		this.addProfile(unixMachine, false);
-
-		Profile linuxMachine = new Profile(
-				5,
-				"Linux",
-				"This profile will imitate a linux machine by monitoring linux typical services",
-				R.drawable.ic_profile_linux,
-				false
-		);
-
-		linuxMachine.mActiveProtocols.put("SSH", true);
-		linuxMachine.mActiveProtocols.put("TELNET", true);
-		linuxMachine.mActiveProtocols.put("ECHO", true);
-		linuxMachine.mActiveProtocols.put("SMB", true);
-
-		this.addProfile(linuxMachine, false);
-
-		Profile voipServer = new Profile(
-				6,
-				"VOIP Server",
-				"This profile imitates a VOIP Server by monitoring the SIP service",
-				R.drawable.ic_profile_asterisks,
-				false
-		);
-
-		voipServer.mActiveProtocols.put("SIP", true);
-
-		this.addProfile(voipServer, false);
-
-		Profile randomProfile = new Profile(
-				7,
-				"Random",
-				"This profile monitors services randomly",
-				R.drawable.ic_launcher,
-				false
-		);
-
-		randomProfile.mIsRandom = true;
-
-		this.addProfile(randomProfile, false);
-
-		Profile paranoidProfile = new Profile(
-				8,
-				"Paranoid",
-				"This profile monitors all available services",
-				R.drawable.ic_profile_paranoid,
-				false
-		);
-
-		for(String protocol: MainActivity.context.getResources().getStringArray(R.array.protocols)){
-			if(protocol.equals("GHOST")) continue;
-			paranoidProfile.mActiveProtocols.put(protocol, true);
-		}
-
-		paranoidProfile.mActivated = true;
-		this.addProfile(paranoidProfile, false);
-
-		holder.mIncrementValue = 8;
-		this.mCurrentActivatedProfile = paranoidProfile;
-
-		persistData();
-	}
-}

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

@@ -183,14 +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());
-	}
-
+	}	
 }

+ 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);
 			}
-
-		}	
+		}
 	}
 	
 	/**

+ 12 - 0
src/de/tudarmstadt/informatik/hostage/model/JSONSerializable.java

@@ -0,0 +1,12 @@
+package de.tudarmstadt.informatik.hostage.model;
+
+import org.json.JSONObject;
+
+/**
+ * @author Alexander Brakowski
+ * @created 23.03.14 11:45
+ */
+public interface JSONSerializable<T> {
+	public T fromJSON(JSONObject json);
+	public JSONObject toJSON();
+}

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

@@ -1,5 +1,8 @@
 package de.tudarmstadt.informatik.hostage.model;
 
+import org.json.JSONException;
+import org.json.JSONObject;
+
 import android.content.Context;
 import android.content.SharedPreferences;
 import android.graphics.Bitmap;
@@ -12,19 +15,18 @@ import android.os.Parcelable;
 
 import java.io.Serializable;
 import java.util.HashMap;
+import java.util.Iterator;
 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
  * @created 14.01.14 18:04
  */
-public class Profile implements Serializable {
-	private static final long serialVersionUID = 8L;
-
+public class Profile implements JSONSerializable<Profile> {
 	public String mText;
 	public String mLabel;
 	public int mId;
@@ -32,16 +34,15 @@ public class Profile implements Serializable {
 	transient public Bitmap mIcon;
 	transient public int mIconId;
 	public String mIconName;
-
 	public String mIconPath;
 
-	public boolean mIsBackVisible = false;
 	public boolean mEditable = false;
 	public boolean mIsRandom = false;
 
 	public HashMap<String, Boolean> mActiveProtocols = new HashMap<String, Boolean>();
 	public String mGhostPorts = "";
 	public boolean mGhostActive = false;
+	public boolean mShowTooltip = false;
 
 	public Profile(){
 		this.mEditable = true;
@@ -101,7 +102,7 @@ public class Profile implements Serializable {
 			return this.mIcon;
 		}
 
-		if(!this.mIconName.isEmpty()){
+		if(this.mIconName != null && !this.mIconName.isEmpty()){
 			this.mIconId = MainActivity.context.getResources().getIdentifier(this.mIconName,
 					"drawable", "de.tudarmstadt.informatik.hostage");
 			this.mIcon = BitmapFactory.decodeResource(MainActivity.context.getResources(), this.mIconId);
@@ -153,9 +154,62 @@ public class Profile implements Serializable {
 		Integer[] ports = new Integer[splits.length];
 
 		for(int i=0; i<splits.length; i++){
-			ports[i] = Integer.valueOf(splits[i]);
+            if(!splits[i].equals("")) {
+                ports[i] = Integer.valueOf(splits[i]);
+            }
 		}
 
 		return ports;
 	}
+
+	public JSONObject toJSON(){
+		JSONObject jsonObj = new JSONObject();
+
+		try {
+			jsonObj.put("text", mText);
+			jsonObj.put("label", mLabel);
+			jsonObj.put("id", mId);
+			jsonObj.put("activated", mActivated);
+			jsonObj.put("icon_name", mIconName);
+			jsonObj.put("icon_path", mIconPath);
+			jsonObj.put("editable", mEditable);
+			jsonObj.put("random", mIsRandom);
+			jsonObj.put("ghost_active", mGhostActive);
+			jsonObj.put("ghost_ports", mGhostPorts);
+			jsonObj.put("active_protocols", new JSONObject(mActiveProtocols));
+		} catch (JSONException e) {
+			e.printStackTrace();
+		}
+
+		return jsonObj;
+	}
+
+	public Profile fromJSON(JSONObject json){
+		mText = json.optString("text", "");
+		mLabel = json.optString("label", "");
+		mId = json.optInt("id", -1);
+		mActivated = json.optBoolean("activated", false);
+		mIconName = json.optString("icon_name", null);
+		mIconPath = json.optString("icon_path", null);
+		mEditable = json.optBoolean("editable", true);
+		mIsRandom = json.optBoolean("random", false);
+		mGhostActive = json.optBoolean("ghost_active", false);
+		mGhostPorts = json.optString("ghost_ports", "");
+
+		JSONObject activeProtocols = json.optJSONObject("active_protocols");
+		if(activeProtocols != null){
+			Iterator keys = activeProtocols.keys();
+
+			while(keys.hasNext()){
+				String protocol = (String) keys.next();
+				try {
+					mActiveProtocols.put(protocol, activeProtocols.getBoolean(protocol));
+				} catch (JSONException e) {
+					e.printStackTrace();
+				}
+			}
+		}
+
+		return this;
+	}
 }

+ 0 - 13
src/de/tudarmstadt/informatik/hostage/model/ProfilesHolder.java

@@ -1,13 +0,0 @@
-package de.tudarmstadt.informatik.hostage.model;
-
-import java.io.Serializable;
-import java.util.HashMap;
-
-/**
- * @author Alexander Brakowski
- * @created 07.03.14 00:23
- */
-public class ProfilesHolder implements Serializable {
-	public int mIncrementValue = 1;
-	public HashMap<Integer, Profile> mProfiles;
-}

+ 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 {
 

+ 14 - 1
src/de/tudarmstadt/informatik/hostage/persistence/HostageDBOpenHelper.java

@@ -848,7 +848,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();
+	}
+	
 	/**
 	 * Creates a {@link Record} from a Cursor. If the cursor does not show to a
 	 * valid data structure a runtime exception is thrown.

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

@@ -0,0 +1,665 @@
+package de.tudarmstadt.informatik.hostage.persistence;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.io.StreamCorruptedException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import java.util.Set;
+
+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.ui.activity.MainActivity;
+import de.tudarmstadt.informatik.hostage.ui.adapter.ProfileManagerListAdapter;
+
+/**
+ * The profile manager is responsible for persisting and deleting profiles
+ *
+ * @author Alexander Brakowski
+ * @created 10.02.14 20:24
+ */
+public class ProfileManager {
+
+	/**
+	 * The singleton instance holder
+	 */
+	private static ProfileManager INSTANCE = null;
+
+	/**
+	 * An list adapter, which the profile manager informs about data changes
+	 */
+	private ProfileManagerListAdapter mProfileListAdapter = null;
+
+	/**
+	 * Holds a reference to the currently active profile
+	 */
+	private Profile mCurrentActivatedProfile = null;
+
+	/**
+	 * Holds a reference to the random profile
+	 */
+	private Profile mRandomProfile = null;
+
+	/**
+	 * The profiles are being serialized and persisted into this file
+	 */
+	private static final String PERSIST_FILENAME = "hostage_profiles.json";
+
+	/**
+	 * Hold the current profile id, it will be incremented each time a new profile is added.
+	 * The new profile will get the newly incremented value as an id.
+	 */
+	public int mIncrementValue = 1;
+
+	/**
+	 * Holds all the available profiles. The key in the map is the ID of the profile.
+	 */
+	public HashMap<Integer, Profile> mProfiles;
+
+	private SharedPreferences mSharedPreferences;
+	private SharedPreferences.Editor mSharedEditor;
+
+	/**
+	 * Since the profile manager should only have one instance in the whole app, we are using the singleton pattern.
+	 * This method creates a new instance of the profile manager, if no instance already exists, and returns it.
+	 *
+	 * @return the singleton instance
+	 */
+	public static ProfileManager getInstance(){
+		if(INSTANCE == null){
+			INSTANCE = new ProfileManager();
+		}
+
+		if(INSTANCE.getNumberOfProfiles() == 0){
+			INSTANCE.loadData();
+		}
+
+		return INSTANCE;
+	}
+
+	/**
+	 * A private constructor, that can/should only be called by getInstance, since we want to enforce the usage of the singleton.
+	 */
+	private ProfileManager(){
+		mProfiles = new HashMap<Integer, Profile>();
+
+		String sharedPreferencePath = MainActivity.getContext().getString(R.string.shared_preference_path);
+		mSharedPreferences = MainActivity.getContext().getSharedPreferences(sharedPreferencePath, Hostage.MODE_PRIVATE);
+		mSharedEditor = mSharedPreferences.edit();
+	}
+
+	/**
+	 * Reads all data from an inputstream and appends it to a string
+	 *
+	 * @param is The input stream to read the data from
+	 * @return the whole data from the input stream as an string
+	 */
+	public String readAll( final InputStream is ) {
+		if( null == is ) {
+			return "";
+		}
+
+		StringBuilder sb = new StringBuilder();
+		int rc;
+		try {
+			while( (rc = is.read()) >= 0 ){
+				sb.append( (char) rc );
+			}
+		} catch (IOException e) {
+			e.printStackTrace();
+		}
+
+		return sb.toString();
+	}
+
+
+	/**
+	 * Reads all the data of the the profiles, that were persisted and unserializes them.
+	 *
+	 * The profiles were serialized into JSON and persisted into the android private file.
+	 * See {@see ProfileManager#persistData}.
+	 */
+	public void loadData(){
+		try {
+            String UTF8 = "utf8";
+            int BUFFER_SIZE = 8192;
+            BufferedReader fbr = new BufferedReader(new InputStreamReader(MainActivity.getContext().openFileInput(PERSIST_FILENAME), UTF8), BUFFER_SIZE);
+
+            StringBuilder sb = new StringBuilder();
+            String line;
+            while((line = fbr.readLine()) != null) {
+                sb.append(line);
+            }
+
+            JSONArray arr = new JSONArray(sb.toString());
+			fbr.close();
+
+			for(int i=0; i<arr.length(); i++){
+				JSONObject obj = arr.getJSONObject(i);
+
+				Profile p = new Profile();
+				p.fromJSON(obj);
+
+				mProfiles.put(p.mId, p);
+
+				if(p.mId > mIncrementValue){
+					mIncrementValue = p.mId;
+				}
+
+				if(p.mActivated){
+					activateProfile(p, false);
+				}
+
+				if(p.mIsRandom){
+					this.mRandomProfile = p;
+				}
+			}
+
+		} catch (FileNotFoundException e) {
+			e.printStackTrace();
+		} catch (StreamCorruptedException e) {
+			e.printStackTrace();
+		} catch (IOException e) {
+			e.printStackTrace();
+		} catch (JSONException e) {
+			e.printStackTrace();
+		} finally {
+			if(mProfiles.size() == 0){
+				this.fillWithDefaultData();
+			}
+
+			if(this.mRandomProfile != null){
+				randomizeProtocols(mRandomProfile);
+			}
+		}
+	}
+
+	/**
+	 * All the profiles that are hold by the profile manager are being serialized into JSON and then written into an private android file.
+	 */
+	public void persistData(){
+		try {
+			int BUFFER_SIZE = 8192;
+			String UTF8 = "utf8";
+
+			FileOutputStream fout = MainActivity.getContext().openFileOutput(PERSIST_FILENAME, Context.MODE_PRIVATE);
+			BufferedWriter fnw = new BufferedWriter(new OutputStreamWriter(fout, UTF8), BUFFER_SIZE);
+
+			JSONArray arr = new JSONArray();
+			for(Profile p: mProfiles.values()){
+				arr.put(p.toJSON());
+			}
+
+			fnw.write(arr.toString());
+
+			fnw.close();
+			fout.close();
+		} catch (FileNotFoundException e) {
+			e.printStackTrace();
+		} catch (IOException e) {
+			e.printStackTrace();
+		}
+
+	}
+
+	/**
+	 * Retrieves all the profiles as an List
+	 * @return a list that holds all the profiles
+	 */
+	public List<Profile> getProfilesList(){
+		return new ArrayList<Profile>(getProfilesCollection());
+	}
+
+	/**
+	 * Retrieves all the profiles as an collection
+	 * @return a collection of all the profiles
+	 */
+	public Collection<Profile> getProfilesCollection(){
+		if(mProfiles.size() == 0 || mProfiles == null){
+			this.loadData();
+		}
+
+		return mProfiles.values();
+	}
+
+	/**
+	 * Retrieves an map of all the profiles. The key in the map is the ID of an profile.
+	 * @return a map of profiles
+	 */
+	public Map<Integer, Profile> getMapProfiles(){
+		return mProfiles;
+	}
+
+	/**
+	 * Activates and deactivates protocols randomly in the given profile
+	 *
+	 * @param profile the profile to randomize the protocols for
+	 */
+	public void randomizeProtocols(Profile profile){
+		LinkedList<String> protocols = new LinkedList<String>(Arrays.asList(MainActivity.getContext().getResources().getStringArray(R.array.protocols)));
+		protocols.remove("GHOST");
+
+		profile.mActiveProtocols.clear();
+
+		Random rand = new Random();
+		int numberOfProtocolsToActivate = rand.nextInt(protocols.size()) + 1;
+
+		while(numberOfProtocolsToActivate-- > 0){
+			int randomIndex = rand.nextInt(protocols.size());
+			String protocol = protocols.get(randomIndex);
+
+			profile.mActiveProtocols.put(protocol, true);
+			protocols.remove(protocol);
+		}
+
+		persistData();
+	}
+
+	/**
+	 * Adds or updates a given profile.
+	 *
+	 * @param profile the profile to persist
+	 * @return the id the profile was assigned to
+	 */
+	public int persistProfile(Profile profile){
+		if(profile.mId == -1){
+			profile.mId = ++mIncrementValue;
+		}
+
+		mProfiles.put(profile.mId, profile);
+
+		this.persistData();
+
+		if(this.mProfileListAdapter != null){
+			this.mProfileListAdapter.notifyDataSetChanged();
+		}
+
+		return profile.mId;
+	}
+
+	/**
+	 * Retrieves the profile with the given id
+	 *
+	 * @param id the id of the profile
+	 * @return the profile
+	 */
+	public Profile getProfile(int id){
+		if(mProfiles.size() == 0){
+			loadData();
+		}
+
+		if(this.mProfiles.containsKey(id)){
+			return this.mProfiles.get(id);
+		}
+
+		return null;
+	}
+
+	/**
+	 * Adds a profile
+	 *
+	 * @param profile the profile to add
+	 */
+	public void addProfile(Profile profile){
+		this.addProfile(profile, true);
+	}
+
+	/**
+	 * Adds a given profile to the profile manager.
+	 *
+	 * @param profile the profile to add
+	 * @param persist true,  if the profile should also be persisted immediatly,
+	 *                false, if the profile should just be added internally without being persisted
+	 *                       (Note: you can still call persistData later to persist all the profiles)
+	 */
+	public void addProfile(Profile profile, boolean persist){
+
+		if(profile.mId == -1){
+			profile.mId = ++mIncrementValue;
+		}
+
+		mProfiles.put(profile.mId, profile);
+
+		if(persist){
+			persistData();
+		}
+
+		if(this.mProfileListAdapter != null){
+			this.mProfileListAdapter.add(profile);
+			this.mProfileListAdapter.notifyDataSetChanged();
+		}
+	}
+
+	/**
+	 * Deletes a given profile. These changes will be persisted immediatly.
+	 *
+	 * @param profile the profile to delete
+	 */
+	public void deleteProfile(Profile profile){
+		if(this.mProfiles.containsKey(profile.mId)){
+			Profile p = getProfile(profile.mId);
+			this.mProfiles.remove(profile.mId);
+
+			if(p.mActivated || this.mCurrentActivatedProfile.mId == p.mId){
+				mCurrentActivatedProfile = mRandomProfile;
+				mRandomProfile.mActivated = true;
+			}
+
+			this.persistData();
+			//this.dbh.deleteProfile(profile.mId);
+
+			if(this.mProfileListAdapter != null){
+				this.mProfileListAdapter.remove(profile);
+				this.mProfileListAdapter.notifyDataSetChanged();
+			}
+		}
+	}
+
+	/**
+	 * Removes all profiles.
+	 */
+	public void clearProfiles(){
+		mProfiles.clear();
+		persistData();
+	}
+
+	/**
+	 * Same as {@see activateProfile(Profile profile, boolean persist)} but with persist arg being always true
+	 * @param profile the profile to active
+	 */
+	public void activateProfile(Profile profile){
+		this.activateProfile(profile, true);
+	}
+
+	/**
+	 * Makes a given profile active.
+	 *
+	 * @param profile the profile to activate
+	 * @param persist indicates if the profile should be persisted after activating
+	 */
+	public void activateProfile(Profile profile, boolean persist){
+		if(profile.equals(this.mCurrentActivatedProfile)) return;
+
+		if(this.mCurrentActivatedProfile != null){
+			this.mCurrentActivatedProfile.mActivated = false;
+			this.persistProfile(this.mCurrentActivatedProfile);
+		}
+
+		profile.mActivated = true;
+		this.mCurrentActivatedProfile = profile;
+		this.mProfiles.put(profile.mId, profile);
+
+		mSharedEditor.putString("os", profile.mLabel);
+		mSharedEditor.commit();
+
+		if(persist) persistData();
+
+		if(this.mProfileListAdapter != null){
+			this.mProfileListAdapter.notifyDataSetChanged();
+		}
+
+		if(MainActivity.getInstance().getHostageService() != null){
+			if(MainActivity.getInstance().getHostageService().hasRunningListeners()){
+				List<String> protocolsToStart = profile.getActiveProtocols();
+				if(profile.mGhostActive){
+					protocolsToStart.add("GHOST");
+				}
+
+				for(Listener listener: MainActivity.getInstance().getHostageService().getListeners()){
+					if(listener.isRunning()){
+						if(protocolsToStart.contains(listener.getProtocolName()) && !listener.getProtocolName().equals("GHOST")){
+							protocolsToStart.remove(listener.getProtocolName());
+						} else {
+							MainActivity.getInstance().getHostageService().stopListenerAllPorts(listener.getProtocolName());
+						}
+					}
+				}
+
+				MainActivity.getInstance().startMonitorServices(protocolsToStart);
+			}
+		}
+	}
+
+	/**
+	 * Checks if the "random" profile is currently active
+	 *
+	 * @return true,  if active
+	 *         false, otherwise
+	 */
+	public boolean isRandomActive(){
+		return this.mCurrentActivatedProfile.equals(this.mRandomProfile);
+	}
+
+	/**
+	 * Retrieves the "random" profile
+	 *
+	 * @return the "random" profile
+	 */
+	public Profile getRandomProfile(){
+		return this.mRandomProfile;
+	}
+
+	/**
+	 * Retrieves the currently active profile
+	 *
+	 * @return the active profile
+	 */
+	public Profile getCurrentActivatedProfile(){
+		return mCurrentActivatedProfile;
+	}
+
+	/**
+	 * Sets the list adapter that should also be managed by the profile manager
+	 *
+	 * @param profileListAdapter the list adapter to manage
+	 */
+	public void setProfileListAdapter(ProfileManagerListAdapter profileListAdapter){
+		this.mProfileListAdapter = profileListAdapter;
+	}
+
+
+	/**
+	 * Retrieves the list adapter, that is being managed by the profile manager
+	 * @return the list adapter
+	 */
+	public ProfileManagerListAdapter getProfileListAdapter(){
+		return this.mProfileListAdapter;
+	}
+
+	/**
+	 * Retrieves the number of profiles
+	 *
+	 * @return the number of profiles
+	 */
+	public int getNumberOfProfiles(){
+		return mProfiles.size();
+	}
+
+
+
+	/**
+	 * Pick n numbers between 0 (inclusive) and k (inclusive)
+	 * While there are very deterministic ways to do this,
+	 * for large k and small n, this could be easier than creating
+	 * an large array and sorting, i.e. k = 10,000
+	 */
+	public Set<Integer> pickRandom(int n, int s, int k) {
+		Random random = new Random(); // if this method is used often, perhaps define random at class level
+		Set<Integer> picked = new HashSet<Integer>();
+		while(picked.size() < n) {
+			picked.add(random.nextInt(k-s) + s);
+		}
+		return picked;
+	}
+
+	/**
+	 * Fills the profiles manager with default profiles
+	 */
+	public void fillWithDefaultData(){
+		Profile windowsSeven = new Profile(
+				0,
+				"Windows 7",
+				MainActivity.getInstance().getString(R.string.profile_seven_desc),
+				R.drawable.ic_profile_vista,
+				false
+		);
+
+		windowsSeven.mActiveProtocols.put("SMB", true);
+		windowsSeven.mGhostActive = true;
+		windowsSeven.mGhostPorts = "135,5357";
+
+		for(int i: pickRandom(3, 49152, 70000)){
+			windowsSeven.mGhostPorts += "," + i;
+		}
+
+		windowsSeven.mActiveProtocols.put("ECHO", true);
+
+		this.addProfile(windowsSeven, false);
+
+		Profile windowsXP = new Profile(
+				1,
+				"Windows XP",
+                MainActivity.getInstance().getString(R.string.profile_xp_desc),
+				R.drawable.ic_profile_xp,
+				false
+		);
+
+		windowsXP.mActiveProtocols.put("SMB", true);
+		windowsXP.mGhostActive = true;
+		windowsXP.mGhostPorts = "135";
+
+		for(int i: pickRandom(3, 49152, 60000)){
+			windowsXP.mGhostPorts += "," + i;
+		}
+
+		windowsXP.mActiveProtocols.put("ECHO", true);
+
+		this.addProfile(windowsXP, false);
+
+		Profile serverHTTP = new Profile(
+				2,
+				"Web Server Apache",
+                MainActivity.getInstance().getString(R.string.profile_webserv_apache_desc),
+				R.drawable.ic_profile_apache,
+				false
+		);
+
+		serverHTTP.mActiveProtocols.put("HTTP", true);
+		serverHTTP.mActiveProtocols.put("HTTPS", true);
+		serverHTTP.mActiveProtocols.put("MYSQL", true);
+
+		this.addProfile(serverHTTP, false);
+
+		Profile serverWeb = new Profile(
+				3,
+				"Web Server IIS",
+                MainActivity.getInstance().getString(R.string.profile_webserv_iis_desc),
+				R.drawable.ic_profile_apache,
+				false
+		);
+
+		serverWeb.mActiveProtocols.put("HTTP", true);
+		serverWeb.mActiveProtocols.put("HTTPS", true);
+		serverWeb.mActiveProtocols.put("FTP", true);
+
+		this.addProfile(serverWeb, false);
+
+		Profile unixMachine = new Profile(
+				4,
+				"\"Hardened\" Linux system ",
+                MainActivity.getInstance().getString(R.string.profile_linux_hard_desc),
+				R.drawable.ic_profile_unix,
+				false
+		);
+
+		unixMachine.mActiveProtocols.put("SSH", true);
+
+		this.addProfile(unixMachine, false);
+
+		Profile linuxMachine = new Profile(
+				5,
+				"Linux system",
+                MainActivity.getInstance().getString(R.string.profile_linux_desc),
+				R.drawable.ic_profile_linux,
+				false
+		);
+
+		linuxMachine.mActiveProtocols.put("FTP", true);
+		linuxMachine.mActiveProtocols.put("TELNET", true);
+		linuxMachine.mActiveProtocols.put("HTTP", true);
+		linuxMachine.mActiveProtocols.put("HTTPS", true);
+		linuxMachine.mActiveProtocols.put("MYSQL", true);
+
+		this.addProfile(linuxMachine, false);
+
+		Profile voipServer = new Profile(
+				6,
+				"VOIP Server",
+                MainActivity.getInstance().getString(R.string.profile_voip_desc),
+				R.drawable.ic_profile_asterisks,
+				false
+		);
+
+		voipServer.mActiveProtocols.put("SIP", true);
+
+		this.addProfile(voipServer, false);
+
+		Profile randomProfile = new Profile(
+				7,
+				"Random",
+                MainActivity.getInstance().getString(R.string.profile_random_desc),
+				R.drawable.ic_launcher,
+				false
+		);
+
+		randomProfile.mIsRandom = true;
+
+		this.addProfile(randomProfile, false);
+
+		Profile paranoidProfile = new Profile(
+				8,
+				"Paranoid",
+                MainActivity.getInstance().getString(R.string.profile_paranoid_desc),
+				R.drawable.ic_profile_paranoid,
+				false
+		);
+
+		for(String protocol: MainActivity.context.getResources().getStringArray(R.array.protocols)){
+			if(protocol.equals("GHOST")) continue;
+			paranoidProfile.mActiveProtocols.put(protocol, true);
+		}
+
+		paranoidProfile.mActivated = true;
+		this.addProfile(paranoidProfile, false);
+
+		mIncrementValue = 8;
+
+		this.activateProfile(paranoidProfile, false);
+
+		persistData();
+	}
+
+}

+ 2 - 1
src/de/tudarmstadt/informatik/hostage/sync/nfc/NFCSyncActivity.java

@@ -175,7 +175,8 @@ public class NFCSyncActivity extends Activity implements CreateNdefMessageCallba
 	@Override
 	public void onPause() {
 		super.onPause();
-		mNfcAdapter.disableForegroundDispatch(this);
+		if (mNfcAdapter != null)
+			mNfcAdapter.disableForegroundDispatch(this);
 	}
 
 	/**

+ 0 - 35
src/de/tudarmstadt/informatik/hostage/ui/AboutActivity.java

@@ -1,35 +0,0 @@
-package de.tudarmstadt.informatik.hostage.ui;
-
-import android.app.Activity;
-import android.content.pm.PackageInfo;
-import android.content.pm.PackageManager.NameNotFoundException;
-import android.os.Bundle;
-import android.widget.TextView;
-import de.tudarmstadt.informatik.hostage.R;
-
-/**
- * Shows a simple About View with application version, a small discription and
- * authors of the project.
- * 
- * @author Lars Pandikow
- * 
- */
-public class AboutActivity extends Activity {
-
-	@Override
-	protected void onCreate(Bundle savedInstanceState) {
-		super.onCreate(savedInstanceState);
-		setContentView(R.layout.activity_about);
-		// Set Version Number
-		PackageInfo pInfo;
-		try {
-			pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
-			String version = pInfo.versionName;
-			TextView versionTextView = (TextView) findViewById(R.id.version);
-			versionTextView.setText(version);
-		} catch (NameNotFoundException e) {
-			e.printStackTrace();
-		}
-
-	}
-}

+ 0 - 66
src/de/tudarmstadt/informatik/hostage/ui/ListViewAdapter.java

@@ -1,66 +0,0 @@
-package de.tudarmstadt.informatik.hostage.ui;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.BaseAdapter;
-import android.widget.ImageView;
-import android.widget.TextView;
-import de.tudarmstadt.informatik.hostage.R;
-
-/**
- * Custom ListViewAdapter to dynamically create a list of protocols.
- * 
- * @author Mihai Plasoianu
- */
-public class ListViewAdapter extends BaseAdapter {
-
-	private LayoutInflater inflater;
-	private ArrayList<HashMap<String, String>> data;
-
-	public ListViewAdapter(LayoutInflater inflater,
-			ArrayList<HashMap<String, String>> data) {
-		this.inflater = inflater;
-		this.data = data;
-	}
-
-	@Override
-	public int getCount() {
-		return data.size();
-	}
-
-	@Override
-	public Object getItem(int position) {
-		return data.get(position);
-	}
-
-	@Override
-	public long getItemId(int position) {
-		return position;
-	}
-
-	@Override
-	public View getView(int position, View convertView, ViewGroup parent) {
-		View v = convertView;
-		if (v == null) {
-			v = inflater.inflate(R.layout.list_view_protocols_row, null);
-		}
-
-		ImageView light = (ImageView) v.findViewById(R.id.imageViewLight);
-		TextView protocol = (TextView) v.findViewById(R.id.textViewProtocol);
-		TextView connections = (TextView) v
-				.findViewById(R.id.textViewConnectionsValue);
-
-		HashMap<String, String> d = new HashMap<String, String>();
-		d = data.get(position);
-
-		light.setImageResource(Integer.valueOf(d.get("light")).intValue());
-		protocol.setText(d.get("protocol"));
-		connections.setText(d.get("connections"));
-
-		return v;
-	}
-}

+ 245 - 245
src/de/tudarmstadt/informatik/hostage/ui/LogFilter.java

@@ -1,245 +1,245 @@
-package de.tudarmstadt.informatik.hostage.ui;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import android.os.Parcel;
-import android.os.Parcelable;
-
-public class LogFilter implements Parcelable {
-
-	public final static String LOG_FILTER_INTENT_KEY = "de.tudarmstadt.informatik.hostage.logfilter";
-
-	private static final String TIMESTAMP_BELOW_KEY = "de.tudarmstadt.informatik.hostage.logfilter.timestampbelow";
-	private static final String TIMESTAMP_ABOVE_KEY = "de.tudarmstadt.informatik.hostage.logfilter.timestampabove";
-	private static final String PROTOCOLS_KEY = "de.tudarmstadt.informatik.hostage.logfilter.protocols";
-	private static final String ESSID_KEY = "de.tudarmstadt.informatik.hostage.logfilter.essid";
-	private static final String BSSID_KEY = "de.tudarmstadt.informatik.hostage.logfilter.bssid";
-	private static final String SORTTYPE_KEY = "de.tudarmstadt.informatik.hostage.logfilter.sorttype";
-
-	public enum SortType {
-		packet_timestamp(0), protocol(1), _bssid(1), ssid(3), _attack_id(7), _id(8);
-		private final int id;
-
-		SortType(int id) {
-			this.id = id;
-		}
-
-		public int getValue() {
-			return id;
-		}
-	}
-
-	public ArrayList<String> BSSIDs;
-	public ArrayList<String> ESSIDs;
-	public ArrayList<String> protocols;
-
-	public boolean isNotEditable;
-
-	public SortType sorttype;
-
-	public long belowTimestamp;
-	public long aboveTimestamp;
-
-	public LogFilter() {
-		this.clear();
-
-	}
-
-	public void clear() {
-		this.belowTimestamp = Long.MAX_VALUE;
-		this.aboveTimestamp = Long.MIN_VALUE;
-		this.sorttype = SortType.packet_timestamp;
-		this.BSSIDs = new ArrayList<String>();
-		this.ESSIDs = new ArrayList<String>();
-		this.protocols = new ArrayList<String>();
-	}
-
-	public int describeContents() {
-		return 0;
-	}
-
-	// write your object's data to the passed-in Parcel
-	public void writeToParcel(Parcel out, int flags) {
-		HashMap<String, ArrayList<String>> values = new HashMap<String, ArrayList<String>>();
-		if (this.BSSIDs != null && this.BSSIDs.size() > 0) {
-			values.put(BSSID_KEY, this.getBSSIDs());
-		}
-		if (this.ESSIDs != null && this.ESSIDs.size() > 0) {
-			values.put(ESSID_KEY, this.getESSIDs());
-		}
-		if (this.protocols != null && this.protocols.size() > 0) {
-			values.put(PROTOCOLS_KEY, this.getProtocols());
-		}
-		long timeArray[] = new long[] { this.aboveTimestamp, this.belowTimestamp };
-
-		out.writeMap(values);
-		out.writeInt(this.sorttype.getValue());
-		out.writeDouble(timeArray.length);
-		out.writeLongArray(timeArray);
-		out.writeString(this.isNotEditable ? "true" : "false");
-	}
-
-	public static final Parcelable.Creator<LogFilter> CREATOR = new Parcelable.Creator<LogFilter>() {
-		public LogFilter createFromParcel(Parcel in) {
-			return new LogFilter(in);
-		}
-
-		public LogFilter[] newArray(int size) {
-			return new LogFilter[size];
-		}
-	};
-
-	// example constructor that takes a Parcel and gives you an object populated
-	// with it's values
-	private LogFilter(Parcel in) {
-		// mData = in.readInt();
-		HashMap<String, ArrayList<String>> values = new HashMap<String, ArrayList<String>>();
-		in.readMap(values, ArrayList.class.getClassLoader());
-
-		this.BSSIDs = values.get(BSSID_KEY);
-		this.ESSIDs = values.get(ESSID_KEY);
-		this.protocols = values.get(protocols);
-
-		if (this.BSSIDs == null)
-			this.BSSIDs = new ArrayList<String>();
-		if (this.ESSIDs == null)
-			this.ESSIDs = new ArrayList<String>();
-		if (this.protocols == null)
-			this.protocols = new ArrayList<String>();
-
-		this.sorttype = SortType.values()[Math.min(in.readInt(), SortType.values().length)];
-
-		int size = (int) in.readDouble();
-		long timeArray[] = new long[size];
-		in.readLongArray(timeArray);
-
-		this.belowTimestamp = timeArray[1];
-		this.aboveTimestamp = timeArray[0];
-
-		String bool = in.readString();
-		if (bool.equals("true"))
-			this.isNotEditable = true;
-	}
-
-	public boolean isNotEditable() {
-		return this.isNotEditable;
-	}
-
-	public SortType getSorttype() {
-		return this.sorttype;
-	}
-
-	public ArrayList<String> getBSSIDs() {
-		return this.BSSIDs;
-	}
-
-	public ArrayList<String> getESSIDs() {
-		return this.ESSIDs;
-	}
-
-	public ArrayList<String> getProtocols() {
-		return this.protocols;
-	}
-
-	public void setIsNotEditable(boolean b) {
-		this.isNotEditable = b;
-	}
-
-	public long getBelowTimestamp() {
-		return this.belowTimestamp;
-	}
-
-	public long getAboveTimestamp() {
-		return this.aboveTimestamp;
-	}
-
-	public void setProtocols(ArrayList<String> protocols) {
-		this.protocols = protocols;
-	}
-
-	public void setBSSIDs(ArrayList<String> bssids) {
-		this.BSSIDs = bssids;
-	}
-
-	public void setESSIDs(ArrayList<String> essids) {
-		this.ESSIDs = essids;
-	}
-
-	public void setAboveTimestamp(long timestamp) {
-		this.aboveTimestamp = timestamp;
-	}
-
-	public void setBelowTimestamp(long timestamp) {
-		this.belowTimestamp = timestamp;
-	}
-
-	public void setSorttype(SortType type) {
-		this.sorttype = type;
-	}
-
-	public String getBSSIDQueryStatement(String tablename, String key) {
-		return this.convertArrayListToQueryString(this.BSSIDs, tablename, key);
-	}
-
-	public String getESSIDQueryStatement(String tablename, String key) {
-		return this.convertArrayListToQueryString(this.ESSIDs, tablename, key);
-	}
-
-	public String getProtocolsQueryStatement(String tablename, String key) {
-		return this.convertArrayListToQueryString(this.protocols, tablename, key);
-	}
-
-	public boolean isSet() {
-		boolean hasTime = this.hasATimestamp();
-		boolean hasBSSIDs = this.hasBSSIDs();
-		boolean hasESSIDs = this.hasESSIDs();
-		boolean hasProtocols = this.hasProtocols();
-
-		return hasBSSIDs || hasESSIDs || hasProtocols | hasTime;
-	}
-
-	public boolean hasBSSIDs() {
-		return this.getBSSIDs().size() > 0;
-	}
-
-	public boolean hasESSIDs() {
-		return this.getESSIDs().size() > 0;
-	}
-
-	public boolean hasProtocols() {
-		return this.getProtocols().size() > 0;
-	}
-
-	public boolean hasAboveTimestamp() {
-		return this.aboveTimestamp != Long.MIN_VALUE;
-	}
-
-	public boolean hasBelowTimestamp() {
-		return this.belowTimestamp != Long.MAX_VALUE;
-	}
-
-	public boolean hasATimestamp() {
-		return this.hasBelowTimestamp() || this.hasAboveTimestamp();
-	}
-
-	public String convertArrayListToQueryString(ArrayList<String> list, String table, String key) {
-		String statement = "";
-		if (list == null)
-			return statement;
-		statement = " ( ";
-
-		int i = 0, max = list.size();
-		for (String element : list) {
-			i++;
-			statement = statement + table + "." + key + " = " + "'" + element + "'";
-			if (i == max)
-				continue;
-			statement = statement + " OR ";
-		}
-		statement = statement + " ) ";
-
-		return statement;
-	}
-
-}
+package de.tudarmstadt.informatik.hostage.ui;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+
+import android.os.Parcel;
+import android.os.Parcelable;
+
+public class LogFilter implements Parcelable {
+
+	public final static String LOG_FILTER_INTENT_KEY = "de.tudarmstadt.informatik.hostage.logfilter";
+
+	private static final String TIMESTAMP_BELOW_KEY = "de.tudarmstadt.informatik.hostage.logfilter.timestampbelow";
+	private static final String TIMESTAMP_ABOVE_KEY = "de.tudarmstadt.informatik.hostage.logfilter.timestampabove";
+	private static final String PROTOCOLS_KEY = "de.tudarmstadt.informatik.hostage.logfilter.protocols";
+	private static final String ESSID_KEY = "de.tudarmstadt.informatik.hostage.logfilter.essid";
+	private static final String BSSID_KEY = "de.tudarmstadt.informatik.hostage.logfilter.bssid";
+	private static final String SORTTYPE_KEY = "de.tudarmstadt.informatik.hostage.logfilter.sorttype";
+
+	public enum SortType {
+		packet_timestamp(0), protocol(1), _bssid(1), ssid(3), _attack_id(7), _id(8);
+		private final int id;
+
+		SortType(int id) {
+			this.id = id;
+		}
+
+		public int getValue() {
+			return id;
+		}
+	}
+
+	public ArrayList<String> BSSIDs;
+	public ArrayList<String> ESSIDs;
+	public ArrayList<String> protocols;
+
+	public boolean isNotEditable;
+
+	public SortType sorttype;
+
+	public long belowTimestamp;
+	public long aboveTimestamp;
+
+	public LogFilter() {
+		this.clear();
+
+	}
+
+	public void clear() {
+		this.belowTimestamp = Long.MAX_VALUE;
+		this.aboveTimestamp = Long.MIN_VALUE;
+		this.sorttype = SortType.packet_timestamp;
+		this.BSSIDs = new ArrayList<String>();
+		this.ESSIDs = new ArrayList<String>();
+		this.protocols = new ArrayList<String>();
+	}
+
+	public int describeContents() {
+		return 0;
+	}
+
+	// write your object's data to the passed-in Parcel
+	public void writeToParcel(Parcel out, int flags) {
+		HashMap<String, ArrayList<String>> values = new HashMap<String, ArrayList<String>>();
+		if (this.BSSIDs != null && this.BSSIDs.size() > 0) {
+			values.put(BSSID_KEY, this.getBSSIDs());
+		}
+		if (this.ESSIDs != null && this.ESSIDs.size() > 0) {
+			values.put(ESSID_KEY, this.getESSIDs());
+		}
+		if (this.protocols != null && this.protocols.size() > 0) {
+			values.put(PROTOCOLS_KEY, this.getProtocols());
+		}
+		long timeArray[] = new long[] { this.aboveTimestamp, this.belowTimestamp };
+
+		out.writeMap(values);
+		out.writeInt(this.sorttype.getValue());
+		out.writeDouble(timeArray.length);
+		out.writeLongArray(timeArray);
+		out.writeString(this.isNotEditable ? "true" : "false");
+	}
+
+	public static final Parcelable.Creator<LogFilter> CREATOR = new Parcelable.Creator<LogFilter>() {
+		public LogFilter createFromParcel(Parcel in) {
+			return new LogFilter(in);
+		}
+
+		public LogFilter[] newArray(int size) {
+			return new LogFilter[size];
+		}
+	};
+
+	// example constructor that takes a Parcel and gives you an object populated
+	// with it's values
+	private LogFilter(Parcel in) {
+		// mData = in.readInt();
+		HashMap<String, ArrayList<String>> values = new HashMap<String, ArrayList<String>>();
+		in.readMap(values, ArrayList.class.getClassLoader());
+
+		this.BSSIDs = values.get(BSSID_KEY);
+		this.ESSIDs = values.get(ESSID_KEY);
+		this.protocols = values.get(protocols);
+
+		if (this.BSSIDs == null)
+			this.BSSIDs = new ArrayList<String>();
+		if (this.ESSIDs == null)
+			this.ESSIDs = new ArrayList<String>();
+		if (this.protocols == null)
+			this.protocols = new ArrayList<String>();
+
+		this.sorttype = SortType.values()[Math.min(in.readInt(), SortType.values().length)];
+
+		int size = (int) in.readDouble();
+		long timeArray[] = new long[size];
+		in.readLongArray(timeArray);
+
+		this.belowTimestamp = timeArray[1];
+		this.aboveTimestamp = timeArray[0];
+
+		String bool = in.readString();
+		if (bool.equals("true"))
+			this.isNotEditable = true;
+	}
+
+	public boolean isNotEditable() {
+		return this.isNotEditable;
+	}
+
+	public SortType getSorttype() {
+		return this.sorttype;
+	}
+
+	public ArrayList<String> getBSSIDs() {
+		return this.BSSIDs;
+	}
+
+	public ArrayList<String> getESSIDs() {
+		return this.ESSIDs;
+	}
+
+	public ArrayList<String> getProtocols() {
+		return this.protocols;
+	}
+
+	public void setIsNotEditable(boolean b) {
+		this.isNotEditable = b;
+	}
+
+	public long getBelowTimestamp() {
+		return this.belowTimestamp;
+	}
+
+	public long getAboveTimestamp() {
+		return this.aboveTimestamp;
+	}
+
+	public void setProtocols(ArrayList<String> protocols) {
+		this.protocols = protocols;
+	}
+
+	public void setBSSIDs(ArrayList<String> bssids) {
+		this.BSSIDs = bssids;
+	}
+
+	public void setESSIDs(ArrayList<String> essids) {
+		this.ESSIDs = essids;
+	}
+
+	public void setAboveTimestamp(long timestamp) {
+		this.aboveTimestamp = timestamp;
+	}
+
+	public void setBelowTimestamp(long timestamp) {
+		this.belowTimestamp = timestamp;
+	}
+
+	public void setSorttype(SortType type) {
+		this.sorttype = type;
+	}
+
+	public String getBSSIDQueryStatement(String tablename, String key) {
+		return this.convertArrayListToQueryString(this.BSSIDs, tablename, key);
+	}
+
+	public String getESSIDQueryStatement(String tablename, String key) {
+		return this.convertArrayListToQueryString(this.ESSIDs, tablename, key);
+	}
+
+	public String getProtocolsQueryStatement(String tablename, String key) {
+		return this.convertArrayListToQueryString(this.protocols, tablename, key);
+	}
+
+	public boolean isSet() {
+		boolean hasTime = this.hasATimestamp();
+		boolean hasBSSIDs = this.hasBSSIDs();
+		boolean hasESSIDs = this.hasESSIDs();
+		boolean hasProtocols = this.hasProtocols();
+
+		return hasBSSIDs || hasESSIDs || hasProtocols | hasTime;
+	}
+
+	public boolean hasBSSIDs() {
+		return this.getBSSIDs().size() > 0;
+	}
+
+	public boolean hasESSIDs() {
+		return this.getESSIDs().size() > 0;
+	}
+
+	public boolean hasProtocols() {
+		return this.getProtocols().size() > 0;
+	}
+
+	public boolean hasAboveTimestamp() {
+		return this.aboveTimestamp != Long.MIN_VALUE;
+	}
+
+	public boolean hasBelowTimestamp() {
+		return this.belowTimestamp != Long.MAX_VALUE;
+	}
+
+	public boolean hasATimestamp() {
+		return this.hasBelowTimestamp() || this.hasAboveTimestamp();
+	}
+
+	public String convertArrayListToQueryString(ArrayList<String> list, String table, String key) {
+		String statement = "";
+		if (list == null)
+			return statement;
+		statement = " ( ";
+
+		int i = 0, max = list.size();
+		for (String element : list) {
+			i++;
+			statement = statement + table + "." + key + " = " + "'" + element + "'";
+			if (i == max)
+				continue;
+			statement = statement + " OR ";
+		}
+		statement = statement + " ) ";
+
+		return statement;
+	}
+
+}

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

@@ -1,610 +0,0 @@
-package de.tudarmstadt.informatik.hostage.ui;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import android.app.ActivityManager;
-import android.app.ActivityManager.RunningServiceInfo;
-import android.content.BroadcastReceiver;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.content.ServiceConnection;
-import android.content.SharedPreferences;
-import android.os.Bundle;
-import android.os.IBinder;
-import android.support.v4.app.FragmentActivity;
-import android.support.v4.content.LocalBroadcastManager;
-import android.view.GestureDetector;
-import android.view.GestureDetector.SimpleOnGestureListener;
-import android.view.Menu;
-import android.view.MenuItem;
-import android.view.MotionEvent;
-import android.view.View;
-import android.view.View.OnTouchListener;
-import android.view.animation.Animation;
-import android.view.animation.AnimationUtils;
-import android.widget.AdapterView;
-import android.widget.AdapterView.OnItemClickListener;
-import android.widget.CheckBox;
-import android.widget.ImageView;
-import android.widget.ListView;
-import android.widget.TextView;
-import android.widget.ToggleButton;
-import android.widget.ViewAnimator;
-import de.tudarmstadt.informatik.hostage.Hostage;
-import de.tudarmstadt.informatik.hostage.Hostage.LocalBinder;
-import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
-
-/**
- * MainActivity is the central activity for the GUI of the application.
- * MainActivity is launched when the application is first started. It shows the
- * user: <br>
- * - information about the network<br>
- * - light indicators for recorded attacks on each protocol<br>
- * - amount of attacks on each protocols<br>
- * The user can start and stop services.
- * 
- * @author Mihai Plasoianu
- * @author Lars Pandikow
- * @author Wulf Pfeiffer
- */
-public class MainActivity extends FragmentActivity {
-
-	/**
-	 * Integer representing a grey light.
-	 */
-	public static final int LIGHT_GREY = 0x01;
-	/**
-	 * Integer representing a green light.
-	 */
-	public static final int LIGHT_GREEN = 0x02;
-	/**
-	 * Integer representing a red light.
-	 */
-	public static final int LIGHT_RED = 0x03;
-	/**
-	 * Integer representing a yellow light.
-	 */
-	public static final int LIGHT_YELLOW = 0x04;
-
-	private SharedPreferences connectionInfo;
-
-	private Hostage mService;
-	private boolean serviceBound;
-
-	// variables for the swipe animation
-	private ViewAnimator viewAnimator;
-	private GestureDetector gestureDetector;
-	private Animation animFlipInLR;
-	private Animation animFlipOutLR;
-	private Animation animFlipInRL;
-	private Animation animFlipOutRL;
-
-	private ListView listView;
-	private ListViewAdapter adapter;
-
-	/**
-	 * Connection to bind the background service
-	 * 
-	 * @see Hostage
-	 */
-	private ServiceConnection mConnection = new ServiceConnection() {
-		/**
-		 * After the service is bound, check which has been clicked and start
-		 * it.
-		 * 
-		 * @see android.content.ServiceConnection#onServiceConnected(android.content.ComponentName)
-		 */
-		@Override
-		public void onServiceConnected(ComponentName name, IBinder service) {
-			mService = ((LocalBinder) service).getService();
-			serviceBound = true;
-			updateUI();
-		}
-
-		/**
-		 * After the service is unbound, delete reference.
-		 * 
-		 * @see android.content.ServiceConnection#onServiceDisconnected(android.content.ComponentName)
-		 */
-		@Override
-		public void onServiceDisconnected(ComponentName name) {
-			mService = null;
-			serviceBound = false;
-		}
-
-	};
-
-	/**
-	 * Receiver for custom broadcast.
-	 * 
-	 * @see #BROADCAST
-	 */
-	private BroadcastReceiver mReceiver = new BroadcastReceiver() {
-		@Override
-		public void onReceive(Context context, Intent intent) {
-			// Update user interface.
-			updateUI();
-			updateConnectionInfText();
-		}
-	};
-
-	SimpleOnGestureListener simpleOnGestureListener = new SimpleOnGestureListener() {
-		@Override
-		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
-			float sensitvity = 50;
-			if ((e1.getX() - e2.getX()) > sensitvity) {
-				swipeRightToLeft();
-			} else if ((e2.getX() - e1.getX()) > sensitvity) {
-				swipeLeftToRight();
-			}
-
-			return true;
-		}
-	};
-
-	/**
-	 * Called when User presses on/off button.
-	 * 
-	 * @param view
-	 */
-	public void buttonOnOffClick(View view) {
-		if (((ToggleButton) view).isChecked()) {
-			if (isParanoid()) {
-				String[] protocols = getResources().getStringArray(R.array.protocols);
-				for (String protocol : protocols) {
-					mService.startListener(protocol);
-				}
-			} else {
-				if (mService.isRunning("SMB")) {
-					mService.stopListener("SMB");
-				} else {
-					mService.startListener("SMB");
-				}
-			}
-		} else {
-			mService.stopListeners();
-			stopAndUnbind();
-		}
-	}
-
-	@Override
-	public boolean onCreateOptionsMenu(Menu menu) {
-		getMenuInflater().inflate(R.menu.main, menu);
-		return true;
-	}
-
-	@Override
-	public boolean onOptionsItemSelected(MenuItem item) {
-		// Handle item selection
-		switch (item.getItemId()) {
-		case R.id.action_settings:
-			startActivity(new Intent(this, SettingsActivity.class));
-			break;
-		case R.id.action_about:
-			startActivity(new Intent(this, AboutActivity.class));
-			break;
-		default:
-		}
-		return super.onOptionsItemSelected(item);
-	}
-
-	@Override
-	public boolean onTouchEvent(MotionEvent event) {
-		return gestureDetector.onTouchEvent(event);
-	}
-
-	/**
-	 * Starts the ViewLog activity, when the Button is pressed.
-	 * 
-	 * @see ViewLog
-	 * @param view
-	 *            View elements which triggers the method call.
-	 */
-	public void showLog(View view) {
-		// startActivity(new Intent(this, ViewLog.class));
-	}
-
-	public void startPlayGround(View view) {
-		startActivity(new Intent(this, PlayGroundActivity.class));
-	}
-
-	/**
-	 * Binds service to Activity
-	 * 
-	 * @see Hostage
-	 */
-	private void bindService() {
-		bindService(getServiceIntent(), mConnection, BIND_AUTO_CREATE);
-	}
-
-	/**
-	 * Returns an intent to start HoneyService.
-	 * 
-	 * @return An Intent to start HoneyService
-	 */
-	private Intent getServiceIntent() {
-		return new Intent(this, Hostage.class);
-	}
-
-	/**
-	 * Initializes the ListView. Creating its contents dynamic from protocol
-	 * res/values/protocols.xml
-	 */
-	private void initListView() {
-		ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
-		for (String protocol : getResources().getStringArray(R.array.protocols)) {
-			HashMap<String, String> d = new HashMap<String, String>();
-			d.put("light", String.valueOf(R.drawable.light_grey));
-			d.put("protocol", protocol);
-			d.put("connections", "-");
-			data.add(d);
-		}
-		listView = (ListView) findViewById(R.id.listViewProtocols);
-		adapter = new ListViewAdapter(getLayoutInflater(), data);
-		listView.setAdapter(adapter);
-		listView.setOnTouchListener(new OnTouchListener() {
-
-			@Override
-			public boolean onTouch(View v, MotionEvent event) {
-				return gestureDetector.onTouchEvent(event);
-			}
-
-		});
-		listView.setOnItemClickListener(new OnItemClickListener() {
-
-			@Override
-			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
-				String protocolName = (String) ((HashMap<?, ?>) adapter.getItem(position)).get("protocol");
-				if (mService.isRunning(protocolName)) {
-					mService.stopListener(protocolName);
-				} else {
-					mService.startListener(protocolName);
-				}
-			}
-		});
-	}
-
-	/**
-	 * Initializes variables for screen animation
-	 */
-	private void initViewAnimator() {
-		viewAnimator = (ViewAnimator) findViewById(R.id.viewAnimator);
-		gestureDetector = new GestureDetector(this, simpleOnGestureListener);
-
-		animFlipInLR = AnimationUtils.loadAnimation(this, R.anim.in_left_to_right);
-		animFlipOutLR = AnimationUtils.loadAnimation(this, R.anim.out_left_to_right);
-		animFlipInRL = AnimationUtils.loadAnimation(this, R.anim.in_right_to_left);
-		animFlipOutRL = AnimationUtils.loadAnimation(this, R.anim.out_right_to_left);
-	}
-
-	/**
-	 * Checks if user selected paranoid mode.
-	 * 
-	 * @return True when paranoid mode is selected, else returns false.
-	 */
-	private boolean isParanoid() {
-		return ((CheckBox) findViewById(R.id.checkBoxParanoid)).isChecked();
-	}
-
-	/**
-	 * Checks if a {@link Hostage} instance is running.
-	 * 
-	 * @return True if {@link Hostage} is running, else false.
-	 */
-	private boolean isServiceBound() {
-		return serviceBound;
-	}
-
-	/**
-	 * Checks if a {@link Hostage} instance is running.
-	 * 
-	 * @return True if {@link Hostage} is running, else false.
-	 */
-	private boolean isServiceRunning() {
-		ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
-		for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
-			if (service.service.getClassName().equals(Hostage.class.getName())) {
-				return true;
-			}
-		}
-		return false;
-	}
-
-	/**
-	 * Register broadcast receiver for custom broadcast.
-	 * 
-	 * @see #BROADCAST
-	 */
-	private void registerReceiver() {
-		LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, new IntentFilter(getString(R.string.broadcast)));
-	}
-
-	/**
-	 * If mobile phone is connected to a wireless network starts the background
-	 * service ands binds itself to it. Else notifies the user that service
-	 * could not be started.
-	 */
-	private void startAndBind() {
-		startService(getServiceIntent());
-		bindService();
-	}
-
-	/**
-	 * Stops service and unbinds it.
-	 * 
-	 * @see Hostage
-	 */
-	private void stopAndUnbind() {
-		unbindService();
-		stopService(getServiceIntent());
-	}
-
-	/**
-	 * Called when a swipe to the Right is registered.
-	 */
-	private void swipeLeftToRight() {
-		if (viewAnimator.getDisplayedChild() == 1) {
-			viewAnimator.setInAnimation(animFlipInLR);
-			viewAnimator.setOutAnimation(animFlipOutLR);
-			viewAnimator.setDisplayedChild(0);
-		}
-	}
-
-	/**
-	 * Called when a swipe to the Left is registered.
-	 */
-	private void swipeRightToLeft() {
-		if (viewAnimator.getDisplayedChild() == 0) {
-			viewAnimator.setInAnimation(animFlipInRL);
-			viewAnimator.setOutAnimation(animFlipOutRL);
-			viewAnimator.setDisplayedChild(1);
-		}
-	}
-
-	/**
-	 * Unbinds service.
-	 * 
-	 * @see Hostage
-	 */
-	private void unbindService() {
-		unbindService(mConnection);
-	}
-
-	/**
-	 * Unregisters broadcast receiver for custom broadcast.
-	 * 
-	 * @see #BROADCAST
-	 */
-	private void unregisterReceiver() {
-		LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
-	}
-
-	/**
-	 * Gets Information about connection state and updates the GUI.
-	 */
-	private void updateConnectionInfText() {
-		TextView ssidView = (TextView) findViewById(R.id.textViewSSIDValue);
-		TextView bssidView = (TextView) findViewById(R.id.textViewBSSIDValue);
-		TextView internalIPView = (TextView) findViewById(R.id.textViewInternalIPValue);
-		TextView externalIPView = (TextView) findViewById(R.id.textViewExternalIPValue);
-
-		// externalIPView.setText("Loading...");
-
-		// Get connection information
-		String ssid = connectionInfo.getString(getString(R.string.connection_info_ssid), null);
-		String bssid = connectionInfo.getString(getString(R.string.connection_info_bssid), null);
-		String internalIP = connectionInfo.getString(getString(R.string.connection_info_internal_ip), null);
-		String externalIP = connectionInfo.getString(getString(R.string.connection_info_external_ip), null);
-
-		// Set text fields
-		if (ssid != null)
-			ssidView.setText(ssid);
-		else
-			ssidView.setText("-");
-
-		if (bssid != null)
-			bssidView.setText(bssid);
-		else
-			bssidView.setText("-");
-
-		if (internalIP != null)
-			internalIPView.setText(internalIP);
-		else
-			internalIPView.setText("-");
-
-		if (externalIP != null)
-			externalIPView.setText(externalIP);
-		else
-			externalIPView.setText("-");
-	}
-
-	/**
-	 * Sets the connections count for a given protocol.
-	 * 
-	 * @param connections
-	 *            New value for recorded connections.
-	 * @param protocolName
-	 *            Name of the protocol which should be updated.
-	 */
-	private void updateProtocolConnections(int connections, String protocolName) {
-		for (int i = 0; i < adapter.getCount(); ++i) {
-			HashMap<String, String> d = (HashMap<String, String>) adapter.getItem(i);
-			if (d.get("protocol").equals(protocolName)) {
-				d.put("connections", String.valueOf(connections));
-			}
-		}
-		adapter.notifyDataSetChanged();
-	}
-
-	/**
-	 * Sets the light indicator for a given protocol.
-	 * 
-	 * @param light
-	 *            Integer code to set the light color.
-	 * @param protocolName
-	 *            Name of the protocol which should be updated.
-	 */
-	private void updateProtocolLight(int light, String protocolName) {
-		for (int i = 0; i < adapter.getCount(); ++i) {
-			HashMap<String, String> d = (HashMap<String, String>) adapter.getItem(i);
-			if (d.get("protocol").equals(protocolName)) {
-				switch (light) {
-				case LIGHT_GREY:
-					d.put("light", String.valueOf(R.drawable.light_grey));
-					d.put("connections", "-");
-					break;
-				case LIGHT_GREEN:
-					d.put("light", String.valueOf(R.drawable.light_green));
-					break;
-				case LIGHT_RED:
-					d.put("light", String.valueOf(R.drawable.light_red));
-					break;
-				case LIGHT_YELLOW:
-					d.put("light", String.valueOf(R.drawable.light_yellow));
-					break;
-				}
-			}
-		}
-		adapter.notifyDataSetChanged();
-	}
-
-	/**
-	 * Sets the big light indicator.
-	 * 
-	 * @param light
-	 *            Integer code to set the light color.
-	 * @see #LIGHT_GREY
-	 * @see #LIGHT_GREEN
-	 * @see #LIGHT_RED
-	 * @see #LIGHT_YELLOW
-	 */
-	private void updateStatusLight(int light) {
-		switch (light) {
-		case LIGHT_GREY:
-			((ImageView) findViewById(R.id.imageViewLight)).setImageResource(R.drawable.light_grey_large);
-			break;
-		case LIGHT_GREEN:
-			((ImageView) findViewById(R.id.imageViewLight)).setImageResource(R.drawable.light_green_large);
-			break;
-		case LIGHT_RED:
-			((ImageView) findViewById(R.id.imageViewLight)).setImageResource(R.drawable.light_red_large);
-			break;
-		case LIGHT_YELLOW:
-			((ImageView) findViewById(R.id.imageViewLight)).setImageResource(R.drawable.light_yellow_large);
-			break;
-		}
-	}
-
-	/* ############# Help functions for animation ################## */
-
-	/**
-	 * Updates Information shown by the GUI.
-	 */
-	private void updateUI() {
-		boolean activeListeners = false;
-		boolean activeHandlers = false;
-		boolean yellowLight = false;
-
-		// Check for all protocols if listeners are active and attacks have been
-		// recorded
-		// Update protocol lights and connection information.
-		for (String protocol : getResources().getStringArray(R.array.protocols)) {
-			if (isServiceBound()) {
-				// Check if protocol is active
-				if (mService.isRunning(protocol)) {
-					activeListeners = true;
-					int handlerCount = mService.getNumberOfActiveConnections(protocol);
-					// Check if attacks have been recorded in this session.
-					if (handlerCount > 0) {
-						activeHandlers = true;
-						updateProtocolLight(LIGHT_RED, protocol);
-						updateProtocolConnections(handlerCount, protocol);
-					} else {
-						// Check if the bssid of the wireless network has
-						// already
-						// been recorded as infected.
-						HostageDBOpenHelper dbh = new HostageDBOpenHelper(this);
-						if (dbh.bssidSeen(protocol, connectionInfo.getString(getString(R.string.connection_info_bssid), null))) {
-							updateProtocolLight(LIGHT_YELLOW, protocol);
-							yellowLight = true;
-						} else {
-							updateProtocolLight(LIGHT_GREEN, protocol);
-						}
-						updateProtocolConnections(0, protocol);
-					}
-				} else {
-					updateProtocolLight(LIGHT_GREY, protocol);
-				}
-			} else {
-				updateProtocolLight(LIGHT_GREY, protocol);
-			}
-		}
-
-		// Update the big attack indicator.
-		if (activeListeners) {
-			if (activeHandlers) {
-				updateStatusLight(LIGHT_RED);
-			} else {
-				if (yellowLight) {
-					updateStatusLight(LIGHT_YELLOW);
-				} else {
-					updateStatusLight(LIGHT_GREEN);
-				}
-			}
-			((ToggleButton) findViewById(R.id.toggleButtonOnOff)).setChecked(true);
-			findViewById(R.id.checkBoxParanoid).setEnabled(false);
-		} else {
-			updateStatusLight(LIGHT_GREY);
-			((ToggleButton) findViewById(R.id.toggleButtonOnOff)).setChecked(false);
-			findViewById(R.id.checkBoxParanoid).setEnabled(true);
-		}
-	}
-
-	@Override
-	protected void onCreate(Bundle savedInstanceState) {
-		super.onCreate(savedInstanceState);
-		setContentView(R.layout.activity_main);
-		connectionInfo = getSharedPreferences(getString(R.string.connection_info), Context.MODE_PRIVATE);
-
-		// Create dynamic view elements
-		initViewAnimator();
-		initListView();
-		// Initialize Class variables
-		startAndBind();
-	}
-
-	@Override
-	protected void onDestroy() {
-		// Unbind running service
-		if (!mService.hasRunningListeners()) {
-			stopAndUnbind();
-		}
-		super.onDestroy();
-	}
-
-	@Override
-	protected void onStart() {
-		super.onStart();
-		// Register Broadcast Receiver
-		registerReceiver();
-		// Bind service if running, else check for connection change and delete
-		// sessionData
-		if (isServiceRunning()) {
-			bindService(getServiceIntent(), mConnection, BIND_AUTO_CREATE);
-		}
-		// Update UI
-		updateConnectionInfText();
-	}
-
-	@Override
-	protected void onStop() {
-		// Unregister Broadcast Receiver
-		unregisterReceiver();
-		super.onStop();
-	}
-
-}

+ 0 - 107
src/de/tudarmstadt/informatik/hostage/ui/PlayGroundActivity.java

@@ -1,107 +0,0 @@
-package de.tudarmstadt.informatik.hostage.ui;
-
-import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Random;
-
-import android.app.Activity;
-import android.content.Intent;
-import android.os.Bundle;
-import android.view.Menu;
-import android.view.View;
-import android.widget.TextView;
-import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.logging.NetworkRecord;
-import de.tudarmstadt.informatik.hostage.logging.SyncInfoRecord;
-import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
-import de.tudarmstadt.informatik.hostage.sync.bluetooth.BluetoothSyncActivity;
-import de.tudarmstadt.informatik.hostage.sync.nfc.NFCSyncActivity;
-import de.tudarmstadt.informatik.hostage.sync.tracing.TracingSyncActivity;
-
-public class PlayGroundActivity extends Activity {
-
-
-	public void createNetworkData(View view) {
-		Random rnd = new Random();
-		ArrayList<NetworkRecord> fakeNetInfo = new ArrayList<NetworkRecord>();
-		for (int i = 0; i < 25; i++) {
-			NetworkRecord record = new NetworkRecord();
-			record.setBssid(createRandomBSSID());
-			record.setSsid(new BigInteger(130, rnd).toString(32));
-			record.setLatitude(rnd.nextDouble() * 360);
-			record.setLongitude(rnd.nextDouble() * 360);
-			record.setAccuracy(rnd.nextFloat());
-			record.setTimestampLocation(System.currentTimeMillis());
-			fakeNetInfo.add(record);
-		}
-
-		setNetworkInfoText();
-		new HostageDBOpenHelper(this).updateNetworkInformation(fakeNetInfo);
-	}
-
-	@Override
-	public boolean onCreateOptionsMenu(Menu menu) {
-		getMenuInflater().inflate(R.menu.main, menu);
-		return true;
-	}
-
-	public void startNFC(View view) {
-		startActivity(new Intent(this, NFCSyncActivity.class));
-	}
-
-	public void startBluetooth(View view) {
-		startActivity(new Intent(this, BluetoothSyncActivity.class));
-	}
-	
-	public void startServer(View view) {
-		startActivity(new Intent(this, TracingSyncActivity.class));
-	}
-
-	private String createRandomBSSID() {
-		Random rnd = new Random();
-		char[] symbols = new char[16];
-		for (int idx = 0; idx < 10; ++idx)
-			symbols[idx] = (char) ('0' + idx);
-		for (int idx = 10; idx < 16; ++idx)
-			symbols[idx] = (char) ('a' + idx - 10);
-
-		char[] buf = new char[17];
-		for (int i = 0; i < 18; i += 3) {
-			buf[i] = symbols[rnd.nextInt(symbols.length)];
-			buf[i + 1] = symbols[rnd.nextInt(symbols.length)];
-			if (i < 15) {
-				buf[i + 2] = ':';
-			}
-		}
-		return new String(buf);
-	}
-
-	private void setNetworkInfoText() {
-		HostageDBOpenHelper dbh = new HostageDBOpenHelper(this);
-		TextView text_view = (TextView) findViewById(R.id.textView1);
-		String text = "";
-		ArrayList<SyncInfoRecord> syncInfo = dbh.getSyncInfo();
-		HashMap<String, Long> syncDevices = dbh.getSyncDevices();
-
-		for (SyncInfoRecord info: syncInfo) {
-			text = text + info.getBSSID() + "\n"
-					+ info.getDeviceID() + "\n" +
-					+ info.getNumber_of_attacks() + "\n"
-					+ info.getNumber_of_portscans() + "\n\n";
-		}
-		
-		for(String device: syncDevices.keySet()){
-			text = text + device + "\n"
-					+ syncDevices.get(device) + "\n\n";
-		}
-		text_view.setText(text);
-	}
-
-	@Override
-	protected void onCreate(Bundle savedInstanceState) {
-		super.onCreate(savedInstanceState);
-		setContentView(R.layout.activity_playground);
-		setNetworkInfoText();
-	}
-}

+ 0 - 194
src/de/tudarmstadt/informatik/hostage/ui/SettingsActivity.java

@@ -1,194 +0,0 @@
-package de.tudarmstadt.informatik.hostage.ui;
-
-import android.content.SharedPreferences;
-import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
-import android.os.Bundle;
-import android.preference.EditTextPreference;
-import android.preference.Preference;
-import android.preference.PreferenceActivity;
-import android.preference.PreferenceManager;
-import android.widget.Toast;
-import de.tudarmstadt.informatik.hostage.R;
-
-/**
- * SettingsActivity creates the settings defined in /res/xml/preferences.xml.
- * 
- * @author Lars Pandikow.
- */
-public class SettingsActivity extends PreferenceActivity implements
-		OnSharedPreferenceChangeListener {
-	@Override
-	public void onCreate(Bundle savedInstanceState) {
-		super.onCreate(savedInstanceState);
-		addPreferencesFromResource(R.xml.preferences);
-		// Set the value of the preference as the summary for the preference
-		Preference pref = findPreference("pref_external_location");
-		EditTextPreference etp = (EditTextPreference) pref;
-		pref.setSummary(etp.getText());
-
-		// Set the value of the preference as the summary for the preference
-		pref = findPreference("pref_upload_server");
-		etp = (EditTextPreference) pref;
-		pref.setSummary(etp.getText());
-
-		SharedPreferences defaultPref = PreferenceManager
-				.getDefaultSharedPreferences(this);
-		// Set the value of the preference as the summary for the preference
-		pref = findPreference("pref_max_connections");
-		etp = (EditTextPreference) pref;
-		defaultPref
-				.edit()
-				.putInt("max_connections",
-						Integer.valueOf(etp.getText()).intValue()).commit();
-		pref.setSummary(etp.getText());
-
-		// Set the value of the preference as the summary for the preference
-		pref = findPreference("pref_timeout");
-		etp = (EditTextPreference) pref;
-		defaultPref.edit()
-				.putInt("timeout", Integer.valueOf(etp.getText()).intValue())
-				.commit();
-		pref.setSummary(etp.getText());
-
-		// Set the value of the preference as the summary for the preference
-		pref = findPreference("pref_sleeptime");
-		etp = (EditTextPreference) pref;
-		defaultPref.edit()
-				.putInt("sleeptime", Integer.valueOf(etp.getText()).intValue())
-				.commit();
-		pref.setSummary(etp.getText());
-
-		// Set the value of the preference as the summary for the preference
-		pref = findPreference("pref_location_time");
-		etp = (EditTextPreference) pref;
-		defaultPref
-				.edit()
-				.putInt("location_time",
-						Integer.valueOf(etp.getText()).intValue()).commit();
-		pref.setSummary(etp.getText());
-
-		// Set the value of the preference as the summary for the preference
-		pref = findPreference("pref_location_retries");
-		etp = (EditTextPreference) pref;
-		defaultPref
-				.edit()
-				.putInt("location_retries",
-						Integer.valueOf(etp.getText()).intValue()).commit();
-		pref.setSummary(etp.getText());
-	}
-
-	@Override
-	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
-			String key) {
-		// Check which preference has been changed
-		if (key.equals("pref_external_location")) {
-			Preference pref = findPreference(key);
-			EditTextPreference etp = (EditTextPreference) pref;
-			String path = etp.getText();
-			// Check if the Path is valid
-			if (!path.startsWith("/"))
-				path = new String("/").concat(path);
-			if (!path.endsWith("/"))
-				path = path.concat(new String("/"));
-			if (!path.matches("/(([a-zA-Z_0-9])+/)*")) {
-				Toast.makeText(this,
-						"Path not valid. Must only contain a-zA-Z_0-9",
-						Toast.LENGTH_SHORT).show();
-				path = "/";
-				sharedPreferences.edit().putString(key, path).commit();
-			}
-			pref.setSummary(path);
-		} else if (key.equals("pref_upload_server")) {
-			Preference pref = findPreference(key);
-			EditTextPreference etp = (EditTextPreference) pref;
-			pref.setSummary(etp.getText());
-		} else if (key.equals("pref_max_connections")) {
-			Preference pref = findPreference(key);
-			EditTextPreference etp = (EditTextPreference) pref;
-			String value = etp.getText();
-			if (!value.matches("([0-9])+")) {
-				Toast.makeText(getApplicationContext(),
-						"Enter a valid number.", Toast.LENGTH_SHORT).show();
-				value = getResources().getString(
-						R.string.pref_max_connections_default);
-			}
-			sharedPreferences
-					.edit()
-					.putInt("max_connections",
-							Integer.valueOf(value).intValue()).commit();
-			pref.setSummary(value);
-		} else if (key.equals("pref_timeout")) {
-			Preference pref = findPreference(key);
-			EditTextPreference etp = (EditTextPreference) pref;
-			String value = etp.getText();
-			if (!value.matches("([0-9])+")) {
-				Toast.makeText(getApplicationContext(),
-						"Enter a valid number.", Toast.LENGTH_SHORT).show();
-				value = getResources().getString(R.string.pref_timeout_default);
-			}
-			sharedPreferences.edit()
-					.putInt("timeout", Integer.valueOf(value).intValue())
-					.commit();
-			pref.setSummary(value);
-		} else if (key.equals("pref_sleeptime")) {
-			Preference pref = findPreference(key);
-			EditTextPreference etp = (EditTextPreference) pref;
-			String value = etp.getText();
-			if (!value.matches("([0-9])+")) {
-				Toast.makeText(getApplicationContext(),
-						"Enter a valid number.", Toast.LENGTH_SHORT).show();
-				value = getResources().getString(
-						R.string.pref_sleeptime_default);
-			}
-			sharedPreferences.edit()
-					.putInt("sleeptime", Integer.valueOf(value).intValue())
-					.commit();
-			pref.setSummary(value);
-		} else if (key.equals("pref_location_time")) {
-			Preference pref = findPreference(key);
-			EditTextPreference etp = (EditTextPreference) pref;
-			String value = etp.getText();
-			if (!value.matches("([0-9])+")) {
-				Toast.makeText(getApplicationContext(),
-						"Enter a valid number.", Toast.LENGTH_SHORT).show();
-				value = getResources().getString(
-						R.string.pref_location_time_default);
-			}
-			sharedPreferences.edit()
-					.putInt("location_time", Integer.valueOf(value).intValue())
-					.commit();
-			pref.setSummary(value);
-		} else if (key.equals("pref_location_retries")) {
-			Preference pref = findPreference(key);
-			EditTextPreference etp = (EditTextPreference) pref;
-			String value = etp.getText();
-			if (!value.matches("([0-9])+")) {
-				Toast.makeText(getApplicationContext(),
-						"Enter a valid number.", Toast.LENGTH_SHORT).show();
-				value = getResources().getString(
-						R.string.pref_location_retries_default);
-			}
-			sharedPreferences
-					.edit()
-					.putInt("location_retries",
-							Integer.valueOf(value).intValue()).commit();
-			pref.setSummary(value);
-		}
-
-	}
-
-	@Override
-	protected void onPause() {
-		super.onPause();
-		getPreferenceScreen().getSharedPreferences()
-				.unregisterOnSharedPreferenceChangeListener(this);
-	}
-
-	@Override
-	protected void onResume() {
-		// register a listener to catch preference changes
-		super.onResume();
-		getPreferenceScreen().getSharedPreferences()
-				.registerOnSharedPreferenceChangeListener(this);
-	}
-}

+ 108 - 65
src/de/tudarmstadt/informatik/hostage/ui2/activity/MainActivity.java → src/de/tudarmstadt/informatik/hostage/ui/activity/MainActivity.java

@@ -1,7 +1,8 @@
-package de.tudarmstadt.informatik.hostage.ui2.activity;
+package de.tudarmstadt.informatik.hostage.ui.activity;
 
 import java.util.ArrayList;
 import java.util.HashMap;
+import java.util.List;
 
 import android.app.ActionBar;
 import android.app.Activity;
@@ -30,21 +31,25 @@ import android.view.MenuItem;
 import android.view.View;
 import android.widget.AdapterView;
 import android.widget.ListView;
+import android.widget.Toast;
+
 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.ui.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.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;
 
 /**
  * @author Alexander Brakowski
@@ -76,10 +81,14 @@ public class MainActivity extends Activity {
 
 	private boolean mServiceBound = false;
 
+	private ProfileManager mProfileManager;
+
+	private Fragment rootFragment;
+
 	/**
 	 * Connection to bind the background service
 	 * 
-	 * @see HoneyService
+	 * @see de.tudarmstadt.informatik.hostage.Hostage
 	 */
 	private ServiceConnection mConnection = new ServiceConnection() {
 		/**
@@ -108,10 +117,10 @@ public class MainActivity extends Activity {
 
 	};
 
-	private boolean mInvalidMenuItem = false;
-
 	private HashMap<String, Boolean> mAttacksOnProtocol = new HashMap<String, Boolean>();
 
+	private boolean mCloseWarning = false;
+
 	/**
 	 * Retrieve the singleton latest instance of the activity
 	 * 
@@ -148,11 +157,12 @@ public class MainActivity extends Activity {
 		super.onCreate(savedInstanceState);
 
 		sInstance = this;
-
 		MainActivity.context = getApplicationContext();
 
 		setContentView(R.layout.activity_drawer_main);
 
+		mProfileManager = ProfileManager.getInstance();
+
 		ThreatIndicatorGLRenderer.assets = getAssets();
 		ThreatIndicatorGLRenderer.setThreatLevel(ThreatIndicatorGLRenderer.ThreatLevel.NOT_MONITORING);
 		// set background color
@@ -295,12 +305,12 @@ public class MainActivity extends Activity {
 		String action = getIntent().getAction();
 
 		if (action != null && action.equals("SHOW_HOME")) {
-			if (this.mDisplayedFragment != null && !this.mDisplayedFragment.getClass().equals(HomeFragment.class)) {
+			/*if (this.mDisplayedFragment != null && !this.mDisplayedFragment.getClass().equals(HomeFragment.class)) {
 				getFragmentManager().popBackStackImmediate(HomeFragment.class.getName(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
 				displayView(MainMenuItem.HOME.getValue());
 
 				getIntent().setAction(null);
-			}
+			}*/
 		}
 	}
 
@@ -313,41 +323,32 @@ public class MainActivity extends Activity {
 
 		if (item.getItemId() == android.R.id.home) {
 			if (!mDrawerToggle.isDrawerIndicatorEnabled()) {
-				if (!(this.mDisplayedFragment instanceof UpNavigatibleFragment)) {
-					mDrawerToggle.setDrawerIndicatorEnabled(true);
-					return true;
-				}
-
-				UpNavigatibleFragment upNav = (UpNavigatibleFragment) this.mDisplayedFragment;
-
-				getFragmentManager().popBackStackImmediate(upNav.getUpFragment().getName(), 0);
-				this.mDisplayedFragment = getFragmentManager().findFragmentById(R.id.content_frame);
-				configureFragment();
-				/*
-				 * Fragment frag = null;
-				 * 
-				 * try{ frag = (Fragment) upNav.getUpFragment().newInstance(); }
-				 * catch (InstantiationException e) { Log.i(null,
-				 * "Could not create new instance of fragment"); } catch
-				 * (IllegalAccessException e) { Log.i(null,
-				 * "Could not create new instance of fragment"); }
-				 * 
-				 * if(frag != null) this.injectFragment(frag);
-				 */
-
-				if (!(this.mDisplayedFragment instanceof UpNavigatibleFragment) || !((UpNavigatibleFragment) this.mDisplayedFragment).isUpNavigatible()) {
-					mDrawerToggle.setDrawerIndicatorEnabled(true);
-				} else {
-					mDrawerToggle.setDrawerIndicatorEnabled(false);
-				}
-
-				return true;
+				navigateBack();
 			}
 		}
 
 		return super.onOptionsItemSelected(item);
 	}
 
+	public void navigateBack(){
+		if (!(this.mDisplayedFragment instanceof UpNavigatibleFragment)) {
+			mDrawerToggle.setDrawerIndicatorEnabled(true);
+			return;
+		}
+
+		UpNavigatibleFragment upNav = (UpNavigatibleFragment) this.mDisplayedFragment;
+
+		getFragmentManager().popBackStackImmediate(upNav.getUpFragment().getName(), 0);
+		this.mDisplayedFragment = getFragmentManager().findFragmentById(R.id.content_frame);
+		configureFragment();
+
+		if (!(this.mDisplayedFragment instanceof UpNavigatibleFragment) || !((UpNavigatibleFragment) this.mDisplayedFragment).isUpNavigatible()) {
+			mDrawerToggle.setDrawerIndicatorEnabled(true);
+		} else {
+			mDrawerToggle.setDrawerIndicatorEnabled(false);
+		}
+	}
+
 	@Override
 	public void setTitle(CharSequence title) {
 		mTitle = title;
@@ -400,8 +401,19 @@ public class MainActivity extends Activity {
 		}
 
 		if (fragment != null) {
+			if(position == 0 && rootFragment == null){
+				rootFragment = fragment;
+			}
+
+			boolean isFirst = getFragmentManager().getBackStackEntryCount() == 0;
+
+			//getFragmentManager().popBackStackImmediate(HomeFragment.class.getName(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
 			// update selected item and title, then close the drawer if needed
-			injectFragment(fragment);// , false, menuItemPosition);
+			//if(!(fragment instanceof HomeFragment) || isFirst) {
+				injectFragment(fragment);// , false, menuItemPosition);
+			//} else {
+			//	injectFragment(rootFragment);
+			//}
 
 			mDrawerList.setItemChecked(position, true);
 			mDrawerList.setSelection(position);
@@ -416,6 +428,8 @@ public class MainActivity extends Activity {
 	}
 
 	public void injectFragment(Fragment fragment) {
+		this.mCloseWarning = false;
+
 		// set orientation fixed to portrait in home fragment
 		if (fragment instanceof UpNavigatibleFragment) {
 			UpNavigatibleFragment upFrag = (UpNavigatibleFragment) fragment;
@@ -432,7 +446,6 @@ public class MainActivity extends Activity {
 		FragmentManager fragmentManager = getFragmentManager();
 		FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
 		fragmentTransaction.replace(R.id.content_frame, fragment, fragment.getClass().getName());
-
 		fragmentTransaction.addToBackStack(fragment.getClass().getName());
 
 		fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
@@ -464,8 +477,18 @@ public class MainActivity extends Activity {
 
 	@Override
 	public void onBackPressed() {
-		if (getFragmentManager().getBackStackEntryCount() == 1) {
-			finish();
+		if (mDisplayedFragment instanceof HomeFragment) {
+
+			if (this.mCloseWarning) {
+				MainActivity.getInstance().getHostageService().stopListeners();
+				MainActivity.getInstance().stopAndUnbind();
+				this.mCloseWarning = false;
+				finish();
+			} else {
+				Toast.makeText(this, "Press the back button again to close HosTaGe", Toast.LENGTH_SHORT).show();
+				this.mCloseWarning = true;
+			}
+			//}
 		} else {
 			super.onBackPressed();
 			this.mDisplayedFragment = getFragmentManager().findFragmentById(R.id.content_frame);
@@ -496,16 +519,6 @@ public class MainActivity extends Activity {
 		return super.onKeyDown(keycode, e);
 	}
 
-	public static void displayBackStack(FragmentManager fm) {
-		int count = fm.getBackStackEntryCount();
-		Log.d("Backstack log", "There are " + count + " entries");
-		for (int i = 0; i < count; i++) {
-			// Display Backstack-entry data like
-			String name = fm.getBackStackEntryAt(i).getName();
-			Log.d("Backstack log", "entry " + i + ": " + name);
-		}
-	}
-
 	public Intent getServiceIntent() {
 		return new Intent(this, Hostage.class);
 	}
@@ -532,10 +545,32 @@ public class MainActivity extends Activity {
 		return false;
 	}
 
+	public void startMonitorServices(List<String> protocols){
+		for(String protocol: protocols){
+			if(protocol.equals("GHOST")){
+				if(mProfileManager.getCurrentActivatedProfile() != null){
+					Profile profile = mProfileManager.getCurrentActivatedProfile();
+					if(profile.mGhostActive){
+						for(int port: profile.getGhostPorts()){
+							if(!getHostageService().isRunning(protocol, port)) getHostageService().startListener(protocol, port);
+						}
+					}
+				}
+			} else {
+				if(!getHostageService().isRunning(protocol)) getHostageService().startListener(protocol);
+			}
+		}
+	}
+
 	public enum MainMenuItem {
-		HOME(0, HomeFragment.class), THREAT_MAP(1, ThreatMapFragment.class), RECORDS(2, RecordOverviewFragment.class), STATISTICS(3, StatisticsFragment.class), SERVICES(
-				4, ServicesFragment.class), PROFILE_MANAGER(5, ProfileManagerFragment.class), SETTINGS(6, SettingsFragment.class), APPLICATION_INFO(7,
-				AboutFragment.class);
+		HOME(0, HomeFragment.class),
+		THREAT_MAP(1, ThreatMapFragment.class),
+		RECORDS(2, RecordOverviewFragment.class),
+		STATISTICS(3, StatisticsFragment.class),
+		SERVICES(4, ServicesFragment.class),
+		PROFILE_MANAGER(5, ProfileManagerFragment.class),
+		SETTINGS(6, SettingsFragment.class),
+		APPLICATION_INFO(7, AboutFragment.class);
 
 		private int value;
 		private Class<?> klass;
@@ -551,6 +586,14 @@ public class MainActivity extends Activity {
 			return MainMenuItem.values()[value];
 		}
 
+		public static boolean hasClass(Class<?> klass){
+			for(MainMenuItem m: MainMenuItem.values()){
+				if(m.getKlass().equals(klass)) return true;
+			}
+
+			return false;
+		}
+
 		public int getValue() {
 			return value;
 		}

+ 2 - 2
src/de/tudarmstadt/informatik/hostage/ui2/activity/ProfileEditActivity.java → 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;
 
 /**
  * @author Alexander Brakowski

+ 2 - 2
src/de/tudarmstadt/informatik/hostage/ui2/adapter/DrawerListAdapter.java → 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;
 
 /**
  * @author Alexander Brakowski

+ 2 - 2
src/de/tudarmstadt/informatik/hostage/ui2/adapter/ExpandableListAdapter.java → 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.

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

@@ -0,0 +1,205 @@
+package de.tudarmstadt.informatik.hostage.ui.adapter;
+
+import android.app.AlertDialog;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.Intent;
+import android.graphics.BitmapFactory;
+import android.view.ContextThemeWrapper;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ArrayAdapter;
+import android.widget.ImageButton;
+import android.widget.ImageView;
+import android.widget.RelativeLayout;
+import android.widget.TextView;
+
+import java.util.LinkedList;
+import java.util.List;
+
+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.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;
+
+/**
+ * @author Alexander Brakowski
+ * @created 14.01.14 18:00
+ */
+public class ProfileManagerListAdapter extends ArrayAdapter<Profile> {
+	private class ViewHolder {
+		public TextView labelView;
+		public TextView textView;
+		public ImageView imageSelected;
+		public ImageView itemIcon;
+		public ImageButton buttonEdit;
+		public ImageButton buttonDelete;
+		public View seperator;
+		public FlowLayout badgesContainer;
+	}
+
+    private final Context context;
+    private final List<Profile> values;
+	private SwipeListView list;
+
+    public ProfileManagerListAdapter(Context context, List<Profile> objects, SwipeListView list) {
+        super(context, R.layout.profile_manager_list_item, objects);
+        this.context = context;
+        this.values  = objects;
+	    this.list    = list;
+    }
+
+
+    @Override
+    public View getView(final int position, View convertView, ViewGroup parent) {
+	    LayoutInflater inflater = (LayoutInflater) context
+			    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+
+        View rowView = convertView;
+	    ViewHolder holder = null;
+
+	    final Profile item = values.get(position);
+
+	    if(item.mShowTooltip){
+		    rowView = inflater.inflate(R.layout.profile_manager_list_item_help, parent, false);
+		    rowView.findViewById(R.id.profile_manager_help_dismiss).setOnClickListener(new View.OnClickListener() {
+			    @Override
+			    public void onClick(View v) {
+				    ProfileManagerListAdapter.this.remove(item);
+				    ProfileManagerListAdapter.this.notifyDataSetChanged();
+				    list.dismiss(position);
+
+				    MainActivity.getContext().getSharedPreferences(
+						    MainActivity.getContext().getString(R.string.shared_preference_path), Hostage.MODE_PRIVATE
+				    ).edit().putBoolean("dismissedProfileSwipeHelp", true).commit();
+			    }
+		    });
+	    } else {
+		    if (rowView == null || rowView.getTag() == null) {
+			    rowView = inflater.inflate(R.layout.profile_manager_list_item, parent, false);
+
+			    holder = new ViewHolder();
+			    holder.labelView = (TextView) rowView.findViewById(R.id.profile_manager_item_label);
+			    holder.textView = (TextView) rowView.findViewById(R.id.profile_manager_item_text);
+			    holder.imageSelected = (ImageView) rowView.findViewById(R.id.profile_manager_item_activated);
+			    holder.itemIcon = (ImageView) rowView.findViewById(R.id.profile_manager_item_image);
+			    holder.buttonEdit = (ImageButton) rowView.findViewById(R.id.profile_manager_item_button_edit);
+			    holder.buttonDelete = (ImageButton) rowView.findViewById(R.id.profile_manager_item_button_delete);
+			    holder.seperator = rowView.findViewById(R.id.profile_manager_item_seperator);
+			    holder.badgesContainer = (FlowLayout) rowView.findViewById(R.id.badges_container);
+
+			    rowView.setTag(holder);
+		    } else {
+			    holder = (ViewHolder) rowView.getTag();
+		    }
+
+		    ((SwipeListView) parent).recycle(rowView, position);
+
+		    holder.textView.setText(item.mText);
+		    holder.labelView.setText(item.mLabel);
+
+		    if (item.getIconBitmap() != null) {
+			    //Bitmap bitmap = Bitmap.createScaledBitmap(item.getIconBitmap(), 32, 32, true);
+			    holder.itemIcon.setImageBitmap(item.getIconBitmap());
+		    } else {
+			    holder.itemIcon.setImageBitmap(BitmapFactory.decodeResource(MainActivity.context.getResources(), R.drawable.ic_launcher));
+		    }
+
+		    holder.buttonEdit.setOnClickListener(new View.OnClickListener() {
+			    @Override
+			    public void onClick(View v) {
+				    Intent intent = new Intent(context, ProfileEditActivity.class);
+				    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+				    intent.putExtra("profile_id", item.mId);
+				    //intent.putExtra("profile", item);
+				    context.startActivity(intent);
+			    }
+		    });
+
+		    holder.buttonDelete.setOnClickListener(new View.OnClickListener() {
+			    @Override
+			    public void onClick(View v) {
+				    new AlertDialog.Builder(context)
+						    .setTitle(R.string.delete_profile)
+						    .setMessage(R.string.really_want_delete_profiel)
+						    .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
+							    @Override
+							    public void onClick(DialogInterface dialog, int which) {
+
+							    }
+						    })
+						    .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
+							    public void onClick(DialogInterface dialog, int which) {
+								    ProfileManager profileManager = ProfileManager.getInstance();
+
+								    profileManager.deleteProfile(item);
+								    profileManager.getProfileListAdapter().notifyDataSetChanged();
+								    list.closeOpenedItems();
+							    }
+						    })
+						    .setIcon(android.R.drawable.ic_dialog_alert)
+						    .show();
+			    }
+		    });
+
+		    holder.badgesContainer.removeAllViews();
+		    boolean hasProtocols = false;
+
+		    List<String> profiles = new LinkedList<String>(item.getActiveProtocols());
+
+		    if (item.mGhostActive) {
+			    profiles.add("GHOST");
+		    }
+
+		    for (String protocol : profiles) {
+			    hasProtocols = true;
+			    TextView textView = new TextView(new ContextThemeWrapper(context, R.style.ProfileManagerListBadge));
+			    textView.setText(protocol);
+			    holder.badgesContainer.addView(textView);
+		    }
+
+		    if (!hasProtocols) {
+			    holder.badgesContainer.setVisibility(View.INVISIBLE);
+		    } else {
+			    holder.badgesContainer.setVisibility(View.VISIBLE);
+		    }
+
+		    RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) holder.textView.getLayoutParams();
+
+		    if (!item.mActivated) {
+			    lp.setMargins(0, 0, 0, 0);
+
+			    holder.textView.setLayoutParams(lp);
+
+			    holder.imageSelected.setVisibility(View.GONE);
+		    } else {
+				/*float d = context.getResources().getDisplayMetrics().density;
+				int dm = (int)(20 * d);
+
+				lp.setMargins(0,0,dm,0);
+
+				holder.textView.setLayoutParams(lp);*/
+
+			    holder.imageSelected.setVisibility(View.VISIBLE);
+		    }
+
+		    if (!item.isEditable()) {
+			    holder.buttonDelete.setVisibility(View.GONE);
+			    holder.seperator.setVisibility(View.GONE);
+		    } else {
+			    holder.buttonDelete.setVisibility(View.VISIBLE);
+			    holder.seperator.setVisibility(View.VISIBLE);
+		    }
+
+	    }
+
+        return rowView;
+    }
+
+
+}

+ 2 - 2
src/de/tudarmstadt/informatik/hostage/ui2/adapter/RecordListAdapter.java → src/de/tudarmstadt/informatik/hostage/ui/adapter/RecordListAdapter.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.View;
@@ -9,7 +9,7 @@ import java.util.HashMap;
 import java.util.List;
 
 import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.ui2.model.ExpandableListItem;
+import de.tudarmstadt.informatik.hostage.ui.model.ExpandableListItem;
 
 public class RecordListAdapter extends ExpandableListAdapter {
 

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

@@ -0,0 +1,309 @@
+package de.tudarmstadt.informatik.hostage.ui.adapter;
+
+import java.util.List;
+
+import android.app.AlertDialog;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.os.Build;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ArrayAdapter;
+import android.widget.CompoundButton;
+import android.widget.Switch;
+import android.widget.TextView;
+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.ui.activity.MainActivity;
+import de.tudarmstadt.informatik.hostage.ui.model.ServicesListItem;
+
+/**
+ * @author Daniel Lazar
+ * @created 06.02.14.
+ * a list adapter for loading switches and service information asynchronously
+ */
+public class ServicesListAdapter extends ArrayAdapter<ServicesListItem> {
+    private final Context context;
+    private final List<ServicesListItem> values;
+    int sdk = Build.VERSION.SDK_INT;
+    private Context mActivity;
+    private Switch mServicesSwitch;
+    private CompoundButton.OnCheckedChangeListener mListener;
+    private Profile mProfile;
+    private Integer[] mGhostPorts;
+
+    /**
+     * constructor
+     *
+     * @param context Context of the current activity
+     * @param objects List of ServicesListItem which contains all the protocols
+     */
+    public ServicesListAdapter(Context context, List<ServicesListItem> objects) {
+        super(context, R.layout.services_list_item, objects);
+
+        this.context = context;
+        this.values = objects;
+    }
+
+    /**
+     * method to save important information from parent fragment
+     *
+     * @param activity       activicty from parent fragment
+     * @param servicesSwitch the switch from parent fragment
+     * @param mainListener   Listener from parent fragment
+     */
+    public void setActivity(Context activity, Switch servicesSwitch, CompoundButton.OnCheckedChangeListener mainListener) {
+        mActivity = activity;
+        mServicesSwitch = servicesSwitch;
+        mListener = mainListener;
+    }
+
+    /**
+     * main method of ServicesListAdapter which initializes the holder if null
+     * Also activates protocols and switches
+     *
+     * @param position    current position in list
+     * @param convertView convert view
+     * @param parent the parent view group
+     * @return
+     */
+    @Override
+    public View getView(final int position, View convertView, ViewGroup parent) {
+        LayoutInflater inflater = (LayoutInflater) context
+                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+        View rowView = convertView;
+
+        ViewHolder holder;
+
+        final ServicesListItem item = values.get(position);
+
+        if (rowView == null) {
+            rowView = inflater.inflate(R.layout.services_list_item, parent, false);
+
+            holder = new ViewHolder();
+            assert rowView != null;
+            holder.protocolName = (TextView) rowView.findViewById(R.id.services_item_name);
+            holder.recordedAttacks = (TextView) rowView.findViewById(R.id.services_item_rec_attacks);
+            holder.activated = (Switch) rowView.findViewById(R.id.services_item_switch);
+            holder.circle = rowView.findViewById(R.id.services_circle);
+            rowView.setTag(holder);
+        } else {
+            holder = (ViewHolder) rowView.getTag();
+        }
+
+        holder.protocolName.setText(item.protocol);
+        holder.activated.setTag(item);
+
+        this.updateStatus(item, holder);
+
+        holder.activated.setOnCheckedChangeListener(
+                new CompoundButton.OnCheckedChangeListener() {
+                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+                        ServicesListItem item = (ServicesListItem) buttonView.getTag();
+                        mProfile = ProfileManager.getInstance().getCurrentActivatedProfile();
+                        if (!HelperUtils.isNetworkAvailable(mActivity)) {
+                            if(!MainActivity.getInstance().getHostageService().hasRunningListeners()) {
+                                new AlertDialog.Builder(mActivity)
+                                        .setTitle(R.string.information)
+                                        .setMessage(R.string.wifi_not_connected_msg)
+                                        .setPositiveButton(android.R.string.ok,
+                                                new DialogInterface.OnClickListener() {
+                                                    public void onClick(DialogInterface dialog,
+                                                                        int which) {
+                                                    }
+                                                }
+                                        )
+                                        .setIcon(android.R.drawable.ic_dialog_info).show();
+                                if (buttonView.isChecked()) {
+                                    buttonView.setChecked(false);
+                                }
+                            }
+                        } else {
+                            //check if switch is set to ON and start the concrete listener for the protocol
+                            if (isChecked) {
+                                if(item.protocol.equals("GHOST")){
+                                    if(mProfile.mGhostActive){
+                                        mGhostPorts = mProfile.getGhostPorts();
+
+                                        if(mGhostPorts.length != 0) {
+                                            for(Integer port: mGhostPorts){
+                                                if(!MainActivity.getInstance().getHostageService().isRunning(item.protocol, port)) {
+                                                    MainActivity.getInstance().getHostageService().startListener(item.protocol, port);
+                                                }
+                                            }
+                                            //set the main switch to null, so that he won't react and starts all protocols
+                                            mServicesSwitch.setOnCheckedChangeListener(null);
+                                            mServicesSwitch.setChecked(true);
+                                            mServicesSwitch.setOnCheckedChangeListener(mListener);
+
+                                            if(!buttonView.isChecked()) {
+                                                buttonView.setChecked(true);
+                                            }
+                                        }
+                                    }
+                                    else {
+                                        if(buttonView.isChecked()) {
+                                            buttonView.setChecked(false);
+                                        }
+                                    }
+                                }
+                                else if (!MainActivity.getInstance().getHostageService().isRunning(item.protocol)) {
+                                    MainActivity.getInstance().getHostageService().startListener(item.protocol);
+
+                                    //set the main switch to null, so that he won't react and starts all protocols
+                                    mServicesSwitch.setOnCheckedChangeListener(null);
+                                    mServicesSwitch.setChecked(true);
+                                    mServicesSwitch.setOnCheckedChangeListener(mListener);
+                                    if(!buttonView.isChecked()) {
+                                        buttonView.setChecked(true);
+                                    }
+                                } else {
+                                    if(!buttonView.isChecked()) {
+                                        buttonView.setChecked(true);
+                                    }
+                                }
+                            } else {
+                                   if(item.protocol.equals("GHOST")) {
+                                       mGhostPorts = mProfile.getGhostPorts();
+                                       for(Integer port: mGhostPorts){
+                                           if(port != null) {
+                                               if(MainActivity.getInstance().getHostageService().isRunning("GHOST",port)){
+                                                   MainActivity.getInstance().getHostageService().stopListener("GHOST", port);
+                                               }
+                                           }
+                                       }
+                                       if(buttonView.isChecked()) {
+                                           buttonView.setChecked(false);
+                                       }
+                                   }
+                                   else if (MainActivity.getInstance().getHostageService().isRunning(item.protocol)) {
+                                        MainActivity.getInstance().getHostageService().stopListener(item.protocol);
+                                    }
+                                    if(buttonView.isChecked()) {
+                                        buttonView.setChecked(false);
+                                    }
+                            }
+                        }
+                    }
+                }
+        );
+        return rowView;
+    }
+
+    /**
+     * method to update the current status, which includes changing the attack indication circle and the number of attacks
+     *
+     * @param item   ServiceListItem which has information about current item, e.g. protocol, activated, attacks
+     * @param holder ViewHolder which represents the item in the View
+     */
+    private void updateStatus(ServicesListItem item, ViewHolder holder) {
+        if(item.protocol.equals("GHOST")){
+            mProfile = ProfileManager.getInstance().getCurrentActivatedProfile();
+            mGhostPorts = mProfile.getGhostPorts();
+
+            boolean ghostActive = false;
+            if(mGhostPorts.length != 0) {
+                for (Integer port : mGhostPorts) {
+                    if(port != null){
+                        if (MainActivity.getInstance().getHostageService().isRunning("GHOST", port)) {
+                            ghostActive = true;
+                        }
+                    }
+                }
+            }
+            if(ghostActive){
+                if(!holder.activated.isChecked()) {
+                    holder.activated.setChecked(true);
+                }
+
+                if (!MainActivity.getInstance().getHostageService().hasProtocolActiveAttacks(item.protocol)) {
+                    if (item.attacks > 0) {
+                        setBackground(holder, R.drawable.services_circle_yellow);
+                    } else {
+                        setBackground(holder, R.drawable.services_circle_green);
+                    }
+
+                } else {
+                    if (MainActivity.getInstance().getHostageService().hasProtocolActiveAttacks(item.protocol)) {
+                        setBackground(holder, R.drawable.services_circle_red);
+                    }
+                }
+
+            } else if (item.attacks > 0) {
+                if(holder.activated.isChecked()) {
+                    holder.activated.setChecked(false);
+                }
+                setBackground(holder, R.drawable.services_circle_yellow);
+            } else {
+                if(holder.activated.isChecked()) {
+                    holder.activated.setChecked(false);
+                }
+                setBackground(holder, R.drawable.services_circle);
+            }
+
+
+
+
+        }
+        else if (MainActivity.getInstance().getHostageService().isRunning(item.protocol)) {
+            if(!holder.activated.isChecked()) {
+                holder.activated.setChecked(true);
+            }
+            if (!MainActivity.getInstance().getHostageService().hasProtocolActiveAttacks(item.protocol)) {
+                if (item.attacks > 0) {
+                    setBackground(holder, R.drawable.services_circle_yellow);
+                } else {
+                    setBackground(holder, R.drawable.services_circle_green);
+                }
+
+            } else {
+                if (MainActivity.getInstance().getHostageService().hasProtocolActiveAttacks(item.protocol)) {
+                    setBackground(holder, R.drawable.services_circle_red);
+                }
+            }
+        } else if (item.attacks > 0) {
+            if(holder.activated.isChecked()) {
+                holder.activated.setChecked(false);
+            }
+            setBackground(holder, R.drawable.services_circle_yellow);
+        } else {
+            if(holder.activated.isChecked()) {
+                holder.activated.setChecked(false);
+            }
+            setBackground(holder, R.drawable.services_circle);
+        }
+        holder.recordedAttacks
+                .setText(String.format(MainActivity.getContext().getResources().getString(R.string.recorded_attacks) + "  %d", Integer.valueOf(item.attacks)));
+    }
+
+    /**
+     * changes the indicator circle of a service
+     *
+     * @param holder   ViewHolder which represents the item in the View
+     * @param drawable int which represents the ID of the drawable we want to display, e.g. on a present attack it should be R.drawable.services_circle_red
+     */
+    private void setBackground(ViewHolder holder, int drawable) {
+        if (sdk < Build.VERSION_CODES.JELLY_BEAN) {
+            holder.circle.setBackgroundDrawable(MainActivity.getInstance().getResources().getDrawable(drawable));
+        } else {
+            holder.circle.setBackground(MainActivity.getInstance().getResources().getDrawable(drawable));
+        }
+    }
+
+    /**
+     * ViewHolder stands for a row in the view
+     */
+    private class ViewHolder {
+
+        public TextView protocolName;
+
+        public TextView recordedAttacks;
+
+        public Switch activated;
+
+        public View circle;
+    }
+}

+ 2 - 2
src/de/tudarmstadt/informatik/hostage/ui2/adapter/StatisticListAdapter.java → 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.

+ 182 - 164
src/de/tudarmstadt/informatik/hostage/ui2/dialog/ChecklistDialog.java → src/de/tudarmstadt/informatik/hostage/ui/dialog/ChecklistDialog.java

@@ -1,164 +1,182 @@
-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;
-
-@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;
-	
-	
-    @SuppressLint("ValidFragment")
-	public interface ChecklistDialogListener {
-        public void onDialogPositiveClick(ChecklistDialog dialog);
-        public void onDialogNegativeClick(ChecklistDialog dialog);
-    }
-    
-    public String getTitle(){
-    	return this.title;
-    }
-    
-    public boolean isMultipleChoice(){
-    	return this.isMultipleChoice;
-    }
-    
-    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");
-        }
-    }
-    
-    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 {
+        public void onDialogPositiveClick(ChecklistDialog dialog);
+        public void onDialogNegativeClick(ChecklistDialog dialog);
+    }
+    
+    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 String title
+     * @param ArrayList<String> item titles list
+     * @param boolean[] an array of bools descriping the position of all the selected titles.
+     * @param boolean isMultipleChoice
+     * @param 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");
+        }
+    }
+    
+    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();
+	}
+}
+
+

+ 244 - 244
src/de/tudarmstadt/informatik/hostage/ui2/dialog/DateTimeDialogFragment.java → src/de/tudarmstadt/informatik/hostage/ui/dialog/DateTimeDialogFragment.java

@@ -1,245 +1,245 @@
-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.text.SimpleDateFormat;
-import java.util.Calendar;
-import java.util.Locale;
-
-import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
-
-@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);
-    }
-
-    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);
-    }
-
-    private void setupRootView(View mView){
-        // Grab a Calendar instance
-        mCalendar = Calendar.getInstance();
-
-        // Init date picker
-        datePicker = (DatePicker) mView.findViewById(R.id.DatePicker);
-        datePicker.init(mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH), this);
-
-        // Init time picker
-        timePicker = (TimePicker) mView.findViewById(R.id.TimePicker);
-
-        // Set default Calendar and Time Style
-        setIs24HourView(true);
-        setCalendarViewShown(false);
-
-        switch (DialogType) {
-            case DATE_PICKER:
-                timePicker.setVisibility(View.GONE);
-                break;
-            case TIME_PICKER:
-                datePicker.setVisibility(View.GONE);
-                break;
-        }
-    }
-
-    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);
-    }
-
-   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();
-   }
-    
-    public interface DateTimeDialogFragmentListener {
-        public void onDateTimePickerPositiveClick(DateTimeDialogFragment dialog);
-        public void onDateTimePickerNegativeClick(DateTimeDialogFragment dialog);
-    }
-    private DateTimeDialogFragmentListener mListener;
-
-    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);
-    }
-
-    public int get(final int field) {
-        return mCalendar.get(field);
-    }
-
-    public long getDateTimeMillis() {
-        return mCalendar.getTimeInMillis();
-    }
-
-    public void setIs24HourView(boolean is24HourView) {
-        timePicker.setIs24HourView(is24HourView);
-    }
-
-    public boolean is24HourView() {
-        return timePicker.is24HourView();
-    }
-
-    public void setCalendarViewShown(boolean calendarView) {
-        datePicker.setCalendarViewShown(calendarView);
-    }
-
-    public boolean CalendarViewShown() {
-        return datePicker.getCalendarViewShown();
-    }
-
-    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() {
-        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
-        return sdf.format(mCalendar.getTime());
-    }
-
-    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));
-    }
-
-    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);
-    }
+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.text.DateFormat;
+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);
+    }
+
+    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);
+    }
+
+    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;
+        }
+    }
+
+    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);
+    }
+
+   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();
+   }
+    
+    public interface DateTimeDialogFragmentListener {
+        public void onDateTimePickerPositiveClick(DateTimeDialogFragment dialog);
+        public void onDateTimePickerNegativeClick(DateTimeDialogFragment dialog);
+    }
+    private DateTimeDialogFragmentListener mListener;
+
+    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);
+    }
+
+    public int get(final int field) {
+        return mCalendar.get(field);
+    }
+
+    public long getDateTimeMillis() {
+        return mCalendar.getTimeInMillis();
+    }
+
+    public void setIs24HourView(boolean is24HourView) {
+        timePicker.setIs24HourView(is24HourView);
+    }
+
+    public boolean is24HourView() {
+        return timePicker.is24HourView();
+    }
+
+    public void setCalendarViewShown(boolean calendarView) {
+        datePicker.setCalendarViewShown(calendarView);
+    }
+
+    public boolean CalendarViewShown() {
+        return datePicker.getCalendarViewShown();
+    }
+
+    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() {
+        //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
+        DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(activity);
+        return dateFormat.format(mCalendar.getTime());
+    }
+
+    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));
+    }
+
+    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);
+    }
 }

+ 31 - 30
src/de/tudarmstadt/informatik/hostage/ui2/dialog/TimePickerFragment.java → src/de/tudarmstadt/informatik/hostage/ui/dialog/TimePickerFragment.java

@@ -1,31 +1,32 @@
-package de.tudarmstadt.informatik.hostage.ui2.dialog;
-
-import java.util.Calendar;
-
-import android.app.Dialog;
-import android.app.DialogFragment;
-import android.app.TimePickerDialog;
-import android.os.Bundle;
-import android.text.format.DateFormat;
-import android.widget.TimePicker;
-
-
-public class TimePickerFragment extends DialogFragment implements
-		TimePickerDialog.OnTimeSetListener {
-
-	@Override
-	public Dialog onCreateDialog(Bundle savedInstanceState) {
-		// Use the current time as the default values for the picker
-		final Calendar c = Calendar.getInstance();
-		int hour = c.get(Calendar.HOUR_OF_DAY);
-		int minute = c.get(Calendar.MINUTE);
-
-		// Create a new instance of TimePickerDialog and return it
-		return new TimePickerDialog(getActivity(), this, hour, minute,
-				DateFormat.is24HourFormat(getActivity()));
-	}
-
-	public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
-		// Do something with the time chosen by the user
-	}
+package de.tudarmstadt.informatik.hostage.ui.dialog;
+
+import android.app.Dialog;
+import android.app.DialogFragment;
+import android.app.TimePickerDialog;
+import android.os.Bundle;
+import android.text.format.DateFormat;
+import android.widget.TimePicker;
+
+import java.util.Calendar;
+
+/**
+ * Created by Julien on 16.02.14.
+ */
+public class TimePickerFragment extends DialogFragment implements
+		TimePickerDialog.OnTimeSetListener {
+
+	@Override
+	public Dialog onCreateDialog(Bundle savedInstanceState) {
+		// Use the current time as the default values for the picker
+		final Calendar c = Calendar.getInstance();
+		int hour = c.get(Calendar.HOUR_OF_DAY);
+		int minute = c.get(Calendar.MINUTE);
+
+		return new TimePickerDialog(getActivity(), this, hour, minute,
+				DateFormat.is24HourFormat(getActivity()));
+	}
+
+	public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
+		// Do something with the time chosen by the user
+	}
 }

+ 1 - 1
src/de/tudarmstadt/informatik/hostage/ui2/fragment/AboutFragment.java → 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;

+ 2 - 2
src/de/tudarmstadt/informatik/hostage/ui2/fragment/ConnectionInfoDialogFragment.java → 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;
@@ -17,7 +17,7 @@ import java.util.ArrayList;
 
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.ui.LogFilter;
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
+import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
 
 /**
  * Created by Fabio Arnold on 03.03.14.

+ 98 - 93
src/de/tudarmstadt/informatik/hostage/ui2/fragment/HomeFragment.java → src/de/tudarmstadt/informatik/hostage/ui/fragment/HomeFragment.java

@@ -1,6 +1,8 @@
-package de.tudarmstadt.informatik.hostage.ui2.fragment;
+package de.tudarmstadt.informatik.hostage.ui.fragment;
 
 import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
 
 import android.annotation.SuppressLint;
 import android.app.Activity;
@@ -22,14 +24,15 @@ import android.widget.CompoundButton;
 import android.widget.ImageView;
 import android.widget.Switch;
 import android.widget.TextView;
+
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
-import de.tudarmstadt.informatik.hostage.dao.ProfileManager;
+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.ui.LogFilter;
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
-import de.tudarmstadt.informatik.hostage.ui2.fragment.opengl.ThreatIndicatorGLRenderer;
+import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
+import de.tudarmstadt.informatik.hostage.ui.fragment.opengl.ThreatIndicatorGLRenderer;
 
 /**
  * @author Alexander Brakowski
@@ -37,38 +40,53 @@ import de.tudarmstadt.informatik.hostage.ui2.fragment.opengl.ThreatIndicatorGLRe
  */
 
 public class HomeFragment extends Fragment {
+
 	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 rootView;
+	private View mRootView;
+
 	private BroadcastReceiver mReceiver;
 
-	private CompoundButton.OnCheckedChangeListener switchChangeListener = null;
+	private CompoundButton.OnCheckedChangeListener mSwitchChangeListener = null;
+
+	private int mDefaultTextColor;
 
-	private int defaultTextColor;
 	private ProfileManager mProfileManager;
 
 	private SharedPreferences mConnectionInfo;
-	private HostageDBOpenHelper dbh;
 
-	private static ThreatIndicatorGLRenderer.ThreatLevel THREAT_LEVEL = ThreatIndicatorGLRenderer.ThreatLevel.NO_THREAT;
+	private HostageDBOpenHelper mDbHelper;
+
 	private boolean mReceiverRegistered;
 
+	private boolean mRestoredFromSaved = false;
+
+	private boolean isActive = false;
+	private boolean isConnected = false;
+
 	private void assignViews() {
-		mHomeSwitchConnection = (Switch) rootView.findViewById(R.id.home_switch_connection);
-		mHomeTextName = (TextView) rootView.findViewById(R.id.home_text_name);
-		mHomeTextSecurity = (TextView) rootView.findViewById(R.id.home_text_security);
-		mHomeTextAttacks = (TextView) rootView.findViewById(R.id.home_text_attacks);
-		mHomeTextProfile = (TextView) rootView.findViewById(R.id.home_text_profile);
-		mHomeTextProfileHeader = (TextView) rootView.findViewById(R.id.home_text_profile_header);
-		mHomeProfileImage = (ImageView) rootView.findViewById(R.id.home_image_profile);
-		mHomeConnectionInfoButton = (ImageView) rootView.findViewById(R.id.home_button_connection_info);
+		mHomeSwitchConnection = (Switch) mRootView.findViewById(R.id.home_switch_connection);
+		mHomeTextName = (TextView) mRootView.findViewById(R.id.home_text_name);
+		mHomeTextSecurity = (TextView) mRootView.findViewById(R.id.home_text_security);
+		mHomeTextAttacks = (TextView) mRootView.findViewById(R.id.home_text_attacks);
+		mHomeTextProfile = (TextView) mRootView.findViewById(R.id.home_text_profile);
+		mHomeTextProfileHeader = (TextView) mRootView.findViewById(R.id.home_text_profile_header);
+		mHomeProfileImage = (ImageView) mRootView.findViewById(R.id.home_image_profile);
+		mHomeConnectionInfoButton = (ImageView) mRootView.findViewById(R.id.home_button_connection_info);
 	}
 
 	private void registerBroadcastReceiver() {
@@ -100,6 +118,7 @@ public class HomeFragment extends Fragment {
 		}
 
 		mHomeSwitchConnection.setChecked(false);
+		isActive = false;
 	}
 
 	public void setStateNotActive() {
@@ -114,15 +133,16 @@ public class HomeFragment extends Fragment {
 		mHomeTextAttacks.setVisibility(View.VISIBLE);
 		mHomeTextSecurity.setVisibility(View.VISIBLE);
 
-		mHomeTextName.setTextColor(defaultTextColor);
-		mHomeTextProfile.setTextColor(defaultTextColor);
-		mHomeTextProfileHeader.setTextColor(defaultTextColor);
+		mHomeTextName.setTextColor(mDefaultTextColor);
+		mHomeTextProfile.setTextColor(mDefaultTextColor);
+		mHomeTextProfileHeader.setTextColor(mDefaultTextColor);
 
 		if (!initial) {
 			ThreatIndicatorGLRenderer.setThreatLevel(ThreatIndicatorGLRenderer.ThreatLevel.NO_THREAT);
 		}
 
 		mHomeSwitchConnection.setChecked(true);
+		isActive = true;
 	}
 
 	public void setStateNotConnected() {
@@ -134,6 +154,7 @@ public class HomeFragment extends Fragment {
 		mHomeConnectionInfoButton.setVisibility(View.INVISIBLE);
 
 		mHomeTextName.setText(R.string.not_connected);
+		isConnected = false;
 	}
 
 	public void setStateConnected() {
@@ -141,6 +162,7 @@ public class HomeFragment extends Fragment {
 		mHomeTextProfileHeader.setVisibility(View.VISIBLE);
 		mHomeProfileImage.setVisibility(View.VISIBLE);
 		mHomeConnectionInfoButton.setVisibility(View.VISIBLE);
+		isConnected = true;
 	}
 
 	public void updateUI() {
@@ -150,13 +172,16 @@ public class HomeFragment extends Fragment {
 			mHomeProfileImage.setImageBitmap(profile.getIconBitmap());
 		}
 
-		if (HelperUtils.isWifiConnected(getActivity())) {
+		if (HelperUtils.isNetworkAvailable(getActivity())) {
 			setStateConnected();
-			mHomeTextName.setText(mConnectionInfo.getString(getString(R.string.connection_info_ssid), ""));
+			String ssid = mConnectionInfo.getString(getString(R.string.connection_info_ssid), "\"\"");
+			mHomeTextName.setText(ssid.substring(1,ssid.length() - 1));
+		} else {
+			setStateNotConnected();
 		}
 
 		boolean hasActiveListeners = false;
-		int totalAttacks = dbh.numBssidSeen(mConnectionInfo.getString(getString(R.string.connection_info_bssid), null));
+		int totalAttacks = mDbHelper.numBssidSeen(mConnectionInfo.getString(getString(R.string.connection_info_bssid), null));
 		ThreatIndicatorGLRenderer.ThreatLevel threatLevel = ThreatIndicatorGLRenderer.ThreatLevel.NOT_MONITORING;
 
 		if (MainActivity.getInstance().getHostageService() != null) {
@@ -176,44 +201,45 @@ public class HomeFragment extends Fragment {
 		if (hasActiveListeners) {
 			setStateActive(true);
 
-			switch (threatLevel) {
-			case NO_THREAT:
-				mHomeTextAttacks.setText(R.string.zero_attacks);
-				mHomeTextSecurity.setText(R.string.secure);
-				mHomeTextAttacks.setTextColor(getResources().getColor(R.color.holo_dark_green));
-				mHomeTextSecurity.setTextColor(getResources().getColor(R.color.holo_dark_green));
-				break;
-			case PAST_THREAT:
-				mHomeTextAttacks.setText(totalAttacks
-						+ (totalAttacks == 1 ? getResources().getString(R.string.attack) : getResources().getString(R.string.attacks))
-						+ getResources().getString(R.string.recorded));
-				mHomeTextSecurity.setText(R.string.insecure);
-				mHomeTextAttacks.setTextColor(getResources().getColor(R.color.holo_yellow));
-				mHomeTextSecurity.setTextColor(getResources().getColor(R.color.holo_yellow));
-				break;
-			case LIVE_THREAT:
-				mHomeTextAttacks.setText(totalAttacks
-						+ (totalAttacks == 1 ? getResources().getString(R.string.attack) : getResources().getString(R.string.attacks))
-						+ getResources().getString(R.string.recorded));
-				mHomeTextSecurity.setText(R.string.insecure);
-				mHomeTextAttacks.setTextColor(getResources().getColor(R.color.holo_red));
-				mHomeTextSecurity.setTextColor(getResources().getColor(R.color.holo_red));
-				break;
-			}
+			if(!isConnected){
+				ThreatIndicatorGLRenderer.setThreatLevel(ThreatIndicatorGLRenderer.ThreatLevel.NO_THREAT);
+				mHomeTextAttacks.setText("");
+				mHomeTextSecurity.setText("");
+			} else {
+				switch (threatLevel) {
+					case NO_THREAT:
+						mHomeTextAttacks.setText(R.string.zero_attacks);
+						mHomeTextSecurity.setText(R.string.secure);
+						mHomeTextAttacks.setTextColor(getResources().getColor(R.color.holo_dark_green));
+						mHomeTextSecurity.setTextColor(getResources().getColor(R.color.holo_dark_green));
+						break;
+					case PAST_THREAT:
+						mHomeTextAttacks.setText(totalAttacks
+								+ (totalAttacks == 1 ? getResources().getString(R.string.attack) : getResources().getString(R.string.attacks))
+								+ getResources().getString(R.string.recorded));
+						mHomeTextSecurity.setText(R.string.insecure);
+						mHomeTextAttacks.setTextColor(getResources().getColor(R.color.holo_yellow));
+						mHomeTextSecurity.setTextColor(getResources().getColor(R.color.holo_yellow));
+						break;
+					case LIVE_THREAT:
+						mHomeTextAttacks.setText(totalAttacks
+								+ (totalAttacks == 1 ? getResources().getString(R.string.attack) : getResources().getString(R.string.attacks))
+								+ getResources().getString(R.string.recorded));
+						mHomeTextSecurity.setText(R.string.insecure);
+						mHomeTextAttacks.setTextColor(getResources().getColor(R.color.holo_red));
+						mHomeTextSecurity.setTextColor(getResources().getColor(R.color.holo_red));
+						break;
+				}
 
-			ThreatIndicatorGLRenderer.setThreatLevel(threatLevel);
+				ThreatIndicatorGLRenderer.setThreatLevel(threatLevel);
+			}
 		} else {
 			setStateNotActive();
-
-			if (!HelperUtils.isWifiConnected(getActivity())) {
-				setStateNotConnected();
-			}
 		}
 	}
 
 	@Override
 	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
-
 		super.onCreateView(inflater, container, savedInstanceState);
 
 		final Activity activity = getActivity();
@@ -221,12 +247,12 @@ public class HomeFragment extends Fragment {
 			activity.setTitle(getResources().getString(R.string.drawer_overview));
 		}
 
-		dbh = new HostageDBOpenHelper(getActivity());
+		mDbHelper = new HostageDBOpenHelper(getActivity());
 
 		mProfileManager = ProfileManager.getInstance();
 		mConnectionInfo = getActivity().getSharedPreferences(getString(R.string.connection_info), Context.MODE_PRIVATE);
 
-		rootView = inflater.inflate(R.layout.fragment_home, container, false);
+		mRootView = inflater.inflate(R.layout.fragment_home, container, false);
 		assignViews();
 
 		// hook up the connection info button
@@ -241,7 +267,7 @@ public class HomeFragment extends Fragment {
 			}
 		});
 
-		defaultTextColor = mHomeTextName.getCurrentTextColor();
+		mDefaultTextColor = mHomeTextName.getCurrentTextColor();
 
 		setStateNotActive(true);
 		setStateNotConnected();
@@ -258,18 +284,14 @@ public class HomeFragment extends Fragment {
 
 		updateUI();
 
-		mHomeSwitchConnection = (Switch) rootView.findViewById(R.id.home_switch_connection);
+		mHomeSwitchConnection = (Switch) mRootView.findViewById(R.id.home_switch_connection);
+		mHomeSwitchConnection.setSaveEnabled(false);
 
-		if (switchChangeListener == null) {
-			switchChangeListener = new CompoundButton.OnCheckedChangeListener() {
+		if (mSwitchChangeListener == null) {
+			mSwitchChangeListener = new CompoundButton.OnCheckedChangeListener() {
 				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
-
-					// SYNC TEST
-					// startActivity(new Intent(getActivity(),
-					// TracingSyncActivity.class));
-
-					if (!HelperUtils.isWifiConnected(getActivity())) {
-						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) {
 
@@ -282,12 +304,7 @@ public class HomeFragment extends Fragment {
 						if (isChecked) {
 							boolean protocolActivated = false;
 							if (ProfileManager.getInstance().getCurrentActivatedProfile() == null) {
-								for (String protocol : getResources().getStringArray(R.array.protocols)) {
-									if (!MainActivity.getInstance().getHostageService().isRunning(protocol)) {
-										MainActivity.getInstance().getHostageService().startListener(protocol);
-										protocolActivated = true;
-									}
-								}
+								MainActivity.getInstance().startMonitorServices(Arrays.asList(getResources().getStringArray(R.array.protocols)));
 							} else {
 								ProfileManager profileManager = ProfileManager.getInstance();
 
@@ -295,23 +312,13 @@ public class HomeFragment extends Fragment {
 									profileManager.randomizeProtocols(profileManager.getRandomProfile());
 								}
 
-								for (String protocol : profileManager.getCurrentActivatedProfile().getActiveProtocols()) {
-									if (protocol.equals("GHOST"))
-										continue;
-
-									if (!MainActivity.getInstance().getHostageService().isRunning(protocol)) {
-										MainActivity.getInstance().getHostageService().startListener(protocol);
-										protocolActivated = true;
-									}
-								}
-
 								Profile currentProfile = profileManager.getCurrentActivatedProfile();
+								List<String> protocols = currentProfile.getActiveProtocols();
 
-								if (currentProfile.mGhostActive) {
-									for (int port : currentProfile.getGhostPorts()) {
-										MainActivity.getInstance().getHostageService().startListener("GHOST", port);
-										protocolActivated = true;
-									}
+								if(protocols.size() > 0 || currentProfile.mGhostActive){
+									protocols.add("GHOST");
+									MainActivity.getInstance().startMonitorServices(protocols);
+									protocolActivated = true;
 								}
 							}
 
@@ -338,9 +345,9 @@ public class HomeFragment extends Fragment {
 				}
 			};
 		}
-		mHomeSwitchConnection.setOnCheckedChangeListener(switchChangeListener);
+		mHomeSwitchConnection.setOnCheckedChangeListener(mSwitchChangeListener);
 
-		rootView.findViewById(R.id.home_profile_details).setOnClickListener(new View.OnClickListener() {
+		mRootView.findViewById(R.id.home_profile_details).setOnClickListener(new View.OnClickListener() {
 			@Override
 			public void onClick(View v) {
 				Fragment fragment = new ProfileManagerFragment();
@@ -371,14 +378,13 @@ public class HomeFragment extends Fragment {
 		mHomeTextAttacks.setOnClickListener(attackClickListener);
 		mHomeTextSecurity.setOnClickListener(attackClickListener);
 
-		return rootView;
+		return mRootView;
 	}
 
 	@Override
 	public void onStop() {
-		unregisterBroadcastReceiver();
-		// mHomeSwitchConnection.setOnCheckedChangeListener(null);
 		super.onStop();
+		unregisterBroadcastReceiver();
 	}
 
 	@Override
@@ -386,7 +392,6 @@ public class HomeFragment extends Fragment {
 		super.onStart();
 		registerBroadcastReceiver();
 		updateUI();
-		// mHomeSwitchConnection.setOnCheckedChangeListener(switchChangeListener);
 	}
 
 	@Override

+ 1 - 1
src/de/tudarmstadt/informatik/hostage/ui2/fragment/PreferenceHostageFrament.java → 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;

+ 17 - 10
src/de/tudarmstadt/informatik/hostage/ui2/fragment/ProfileEditFragment.java → 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;
@@ -13,12 +13,10 @@ import android.net.Uri;
 import android.os.Bundle;
 import android.preference.CheckBoxPreference;
 import android.preference.EditTextPreference;
-import android.preference.MultiSelectListPreference;
 import android.preference.Preference;
 import android.preference.PreferenceCategory;
 import android.preference.PreferenceFragment;
 import android.preference.PreferenceManager;
-import android.preference.PreferenceScreen;
 import android.provider.MediaStore;
 import android.view.LayoutInflater;
 import android.view.View;
@@ -27,7 +25,7 @@ import android.widget.LinearLayout;
 import java.util.HashMap;
 
 import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.dao.ProfileManager;
+import de.tudarmstadt.informatik.hostage.persistence.ProfileManager;
 import de.tudarmstadt.informatik.hostage.model.Profile;
 
 /**
@@ -253,14 +251,23 @@ public class ProfileEditFragment extends PreferenceFragment implements
 
 			assert selectedImage != null;
 
-			Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
+			Cursor cursor = getActivity().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
+					new String[]{
+							MediaStore.Images.Media.DATA,
+							MediaStore.Images.Media.DATE_ADDED,
+							MediaStore.Images.ImageColumns.ORIENTATION
+					},
+			MediaStore.Images.Media.DATE_ADDED, null, "date_added ASC");
 
 			assert cursor != null;
-			cursor.moveToFirst();
-
-			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
-			String filePath = cursor.getString(columnIndex);
-			cursor.close();
+			String filePath = "";
+			if(cursor != null && cursor.moveToFirst())
+			{
+				do {
+					filePath = Uri.parse(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA))).toString();
+				} while(cursor.moveToNext());
+				cursor.close();
+			}
 
 			Preference pref = findPreference("pref_profile_general_image");
 

+ 36 - 6
src/de/tudarmstadt/informatik/hostage/ui2/fragment/ProfileManagerFragment.java → src/de/tudarmstadt/informatik/hostage/ui/fragment/ProfileManagerFragment.java

@@ -1,7 +1,8 @@
-package de.tudarmstadt.informatik.hostage.ui2.fragment;
+package de.tudarmstadt.informatik.hostage.ui.fragment;
 
 import android.app.Fragment;
 import android.content.Intent;
+import android.content.SharedPreferences;
 import android.os.Bundle;
 import android.view.LayoutInflater;
 import android.view.Menu;
@@ -12,14 +13,17 @@ import android.view.ViewGroup;
 
 import com.fortysevendeg.android.swipelistview.BaseSwipeListViewListener;
 
+import java.util.LinkedList;
 import java.util.List;
 
+import de.tudarmstadt.informatik.hostage.Hostage;
 import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.dao.ProfileManager;
+import de.tudarmstadt.informatik.hostage.persistence.ProfileManager;
 import de.tudarmstadt.informatik.hostage.model.Profile;
-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;
 
 /**
  * @author Alexander Brakowski
@@ -28,6 +32,8 @@ import de.tudarmstadt.informatik.hostage.ui2.swipelist.SwipeListView;
 public class ProfileManagerFragment extends Fragment {
 	private ProfileManagerListAdapter mAdapter;
 
+	private SharedPreferences mSharedPreferences;
+
 	public ProfileManagerFragment(){}
 
 	private SwipeListView list;
@@ -45,7 +51,17 @@ public class ProfileManagerFragment extends Fragment {
 		final ProfileManager pmanager = ProfileManager.getInstance();
 		pmanager.loadData();
 
-        List<Profile> strList = pmanager.getProfilesList();
+	    String sharedPreferencePath = MainActivity.getContext().getString(R.string.shared_preference_path);
+	    mSharedPreferences = MainActivity.getContext().getSharedPreferences(sharedPreferencePath, Hostage.MODE_PRIVATE);
+
+        final List<Profile> strList = new LinkedList<Profile>(pmanager.getProfilesList());
+
+	    if(strList.size() > 0 && !mSharedPreferences.getBoolean("dismissedProfileSwipeHelp", false)){
+		    Profile tProfile = new Profile();
+		    tProfile.mShowTooltip = true;
+
+			strList.add(1, tProfile);
+	    }
 
 		mAdapter = new ProfileManagerListAdapter(getActivity(), strList, list);
 		pmanager.setProfileListAdapter(mAdapter);
@@ -53,9 +69,23 @@ public class ProfileManagerFragment extends Fragment {
         list.setAdapter(mAdapter);
 
 		list.setSwipeListViewListener(new BaseSwipeListViewListener() {
+			@Override
+			public void onOpened(int position, boolean toRight){
+				Profile profile = mAdapter.getItem(position);
+				if(profile.mShowTooltip){
+					mAdapter.remove(profile);
+					strList.remove(profile);
+					list.dismiss(position);
+
+					mSharedPreferences.edit().putBoolean("dismissedProfileSwipeHelp", true).commit();
+				}
+			}
+
 			@Override
 			public void onClickFrontView(int position) {
 				Profile profile = mAdapter.getItem(position);
+				if(profile.mShowTooltip) return;
+
 				pmanager.activateProfile(profile);
 
 				mAdapter.notifyDataSetChanged();

+ 39 - 1
src/de/tudarmstadt/informatik/hostage/ui2/fragment/RecordDetailFragment.java → src/de/tudarmstadt/informatik/hostage/ui/fragment/RecordDetailFragment.java

@@ -1,8 +1,11 @@
-package de.tudarmstadt.informatik.hostage.ui2.fragment;
+package de.tudarmstadt.informatik.hostage.ui.fragment;
 
 import java.util.ArrayList;
 import java.util.Date;
 
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.content.DialogInterface;
 import android.os.Bundle;
 import android.text.format.DateFormat;
 import android.view.LayoutInflater;
@@ -11,11 +14,14 @@ import android.view.MenuInflater;
 import android.view.MotionEvent;
 import android.view.View;
 import android.view.ViewGroup;
+import android.widget.Button;
 import android.widget.LinearLayout;
 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.ui.LogFilter;
+import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
 import de.tudarmstadt.informatik.hostage.logging.MessageRecord;
 import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
 
@@ -75,6 +81,7 @@ public class RecordDetailFragment extends UpNavigatibleFragment {
 	private TextView mRecordDetailsTextBssid;
 	private TextView mRecordDetailsTextRemoteip;
 	private TextView mRecordDetailsTextProtocol;
+	private Button mRecordDeleteButton;
 
 	public void setRecord(Record rec) {
 		this.record = rec;
@@ -121,6 +128,7 @@ public class RecordDetailFragment extends UpNavigatibleFragment {
 		mRecordDetailsTextBssid = (TextView) view.findViewById(R.id.record_details_text_bssid);
 		mRecordDetailsTextRemoteip = (TextView) view.findViewById(R.id.record_details_text_remoteip);
 		mRecordDetailsTextProtocol = (TextView) view.findViewById(R.id.record_details_text_protocol);
+		mRecordDeleteButton = (Button) view.findViewById(R.id.record_delete_button);
 	}
 
 	private void configurateRootView(View rootView) {
@@ -173,6 +181,36 @@ public class RecordDetailFragment extends UpNavigatibleFragment {
 
 			mRecordOverviewConversation.addView(row);
 		}
+
+		mRecordDeleteButton.setOnClickListener(new View.OnClickListener() {
+			@Override
+			public void onClick(View v) {
+				Activity activity = getActivity();
+				if (activity == null) {
+					return;
+				}
+				new AlertDialog.Builder(getActivity())
+						.setTitle(android.R.string.dialog_alert_title)
+						.setMessage(R.string.record_details_confirm_delete)
+						.setPositiveButton(R.string.yes,
+								new DialogInterface.OnClickListener() {
+									public void onClick(DialogInterface dialog,
+											int which) {
+										dbh.deleteByAttackID(record.getAttack_id());
+
+										// TODO: just navigate back...
+										/*RecordOverviewFragment recordOverviewFragment = new RecordOverviewFragment();
+										recordOverviewFragment.setFilter(new LogFilter());
+										recordOverviewFragment.setGroupKey("Protocol");
+
+										MainActivity.getInstance().injectFragment(recordOverviewFragment, false);*/
+										MainActivity.getInstance().navigateBack();
+									}
+								}
+						).setNegativeButton(R.string.no, null)
+						.setIcon(android.R.drawable.ic_dialog_alert).show();
+			}
+		});
 	}
 
 	/*****************************

+ 12 - 17
src/de/tudarmstadt/informatik/hostage/ui2/fragment/RecordOverviewFragment.java → src/de/tudarmstadt/informatik/hostage/ui/fragment/RecordOverviewFragment.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;
@@ -9,7 +9,6 @@ import android.content.DialogInterface;
 import android.content.Intent;
 import android.content.SharedPreferences;
 import android.os.Bundle;
-import android.os.Environment;
 import android.preference.PreferenceManager;
 import android.util.Log;
 import android.view.LayoutInflater;
@@ -25,8 +24,6 @@ import android.widget.Toast;
 
 import com.google.android.gms.maps.model.LatLng;
 
-import java.io.File;
-import java.io.FileOutputStream;
 import java.text.DateFormat;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
@@ -38,29 +35,27 @@ import java.util.HashMap;
 import java.util.Random;
 
 import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
 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.logging.formatter.TraCINgFormatter;
 import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
 import de.tudarmstadt.informatik.hostage.sync.bluetooth.BluetoothSyncActivity;
 import de.tudarmstadt.informatik.hostage.sync.nfc.NFCSyncActivity;
 import de.tudarmstadt.informatik.hostage.sync.tracing.TracingSyncActivity;
 import de.tudarmstadt.informatik.hostage.ui.LogFilter;
 import de.tudarmstadt.informatik.hostage.ui.LogFilter.SortType;
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
-import de.tudarmstadt.informatik.hostage.ui2.adapter.RecordListAdapter;
-import de.tudarmstadt.informatik.hostage.ui2.dialog.ChecklistDialog;
-import de.tudarmstadt.informatik.hostage.ui2.dialog.DateTimeDialogFragment;
-import de.tudarmstadt.informatik.hostage.ui2.model.ExpandableListItem;
-import de.tudarmstadt.informatik.hostage.ui2.popup.AbstractPopup;
-import de.tudarmstadt.informatik.hostage.ui2.popup.AbstractPopupItem;
-import de.tudarmstadt.informatik.hostage.ui2.popup.SimplePopupItem;
-import de.tudarmstadt.informatik.hostage.ui2.popup.SimplePopupTable;
-import de.tudarmstadt.informatik.hostage.ui2.popup.SplitPopupItem;
+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.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 {
 
@@ -382,7 +377,7 @@ public class RecordOverviewFragment extends UpNavigatibleFragment implements Che
 						Intent intent = new Intent(getActivity(), LogExport.class);
 						intent.setAction(LogExport.ACTION_EXPORT_DATABASE);
 						intent.putExtra(LogExport.FORMAT_EXPORT_DATABASE, position);
-
+						Log.i("Test", "Export Service started with position: " + position);
 						RecordOverviewFragment.this.getActivity().startService(intent);
 					}
 				});

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

@@ -0,0 +1,318 @@
+package de.tudarmstadt.informatik.hostage.ui.fragment;
+
+import java.util.ArrayList;
+
+import android.app.AlertDialog;
+import android.app.Fragment;
+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.os.Bundle;
+import android.support.v4.content.LocalBroadcastManager;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.CompoundButton;
+import android.widget.ListView;
+import android.widget.Switch;
+import android.widget.TextView;
+import de.tudarmstadt.informatik.hostage.Handler;
+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.persistence.HostageDBOpenHelper;
+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
+ * @created 05.02.14
+ * Fragment that displays a switch for every protocol.
+ * Also it can de-/activate every protocol by using this switch.
+ */
+public class ServicesFragment extends Fragment {
+    private Switch mServicesSwitchService;
+    private TextView mServicesTextName;
+
+    private View rootView;
+
+    private CompoundButton.OnCheckedChangeListener switchChangeListener = null;
+
+    private BroadcastReceiver mReceiver;
+
+    private ServicesListAdapter adapter;
+
+    private ArrayList<ServicesListItem> protocolList;
+
+    private HostageDBOpenHelper dbh = new HostageDBOpenHelper(MainActivity.getContext());
+
+    private String[] protocols;
+
+    private SharedPreferences mConnectionInfo;
+
+    private boolean mReceiverRegistered = false;
+
+    private Profile mProfile;
+    private Integer[] mGhostPorts;
+
+    public ServicesFragment() {
+    }
+
+    /**
+     * assign views which are not asynchronously loaded
+     */
+    private void assignViews() {
+        mServicesSwitchService = (Switch) rootView.findViewById(R.id.service_switch_connection);
+        mServicesTextName = (TextView) rootView.findViewById(R.id.services_text_name);
+
+        rootView.findViewById(R.id.services_button_connection_info).setOnClickListener(new View.OnClickListener() {
+            @Override
+            public void onClick(View v) {
+                ConnectionInfoDialogFragment connectionInfoDialogFragment = new ConnectionInfoDialogFragment();
+                connectionInfoDialogFragment.show(getFragmentManager().beginTransaction(), connectionInfoDialogFragment.getTag());
+            }
+        });
+
+    }
+
+    /**
+     * updates the user interface
+     * in detail: the main switch and the textField mServicesTextName
+     */
+    public void updateUI() {
+        if (!HelperUtils.isNetworkAvailable(getActivity())) {
+            if(!MainActivity.getInstance().getHostageService().hasRunningListeners()) {
+                mServicesSwitchService.setOnCheckedChangeListener(null);
+                setStateNotConnected();
+                setStateNotActive();
+                mServicesSwitchService.setOnCheckedChangeListener(switchChangeListener);
+            }
+            else{
+                mServicesSwitchService.setOnCheckedChangeListener(null);
+                setStateNotConnected();
+                mServicesSwitchService.setChecked(true);
+                mServicesSwitchService.setOnCheckedChangeListener(switchChangeListener);
+            }
+        } else {
+            if (MainActivity.getInstance().getHostageService().hasRunningListeners()) {
+                setStateActive();
+            }
+            String ssid = mConnectionInfo.getString(getString(R.string.connection_info_ssid), "");
+
+            mServicesTextName.setText(ssid.substring(1,ssid.length()-1));
+        }
+
+    }
+
+    /**
+     * register a broadcast receiver if not already registered
+     * and also update the number of attacks per protocol
+     */
+    private void registerBroadcastReceiver() {
+        if (!mReceiverRegistered) {
+            mReceiver = new BroadcastReceiver() {
+                @Override
+                public void onReceive(Context context, Intent intent) {
+                    String sender = intent.getStringExtra("SENDER");
+                    String[] values = intent.getStringArrayExtra("VALUES");
+
+                    if (sender.equals(Handler.class.getName()) && values[0].equals(getString(R.string.broadcast_started))) {
+                        for (ServicesListItem item : protocolList) {
+                            if (item.protocol.equals(values[1])) {
+                                item.attacks = dbh.numBssidSeen(item.protocol, mConnectionInfo.getString(getString(R.string.connection_info_bssid), null));
+                            }
+                        }
+                    }
+
+                    if (!MainActivity.getInstance().getHostageService().hasRunningListeners()) {
+                        setStateNotActive();
+                    } else {
+                        setStateActive();
+                    }
+                    updateUI();
+                    adapter.notifyDataSetChanged();
+                }
+            };
+
+            LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mReceiver, new IntentFilter(getString(R.string.broadcast)));
+            this.mReceiverRegistered = true;
+        }
+    }
+
+
+    /**
+     * most important method of this class
+     *
+     * @param inflater the inflater
+     * @param container the container
+     * @param savedInstanceState the saved instance state
+     * @return rootView
+     */
+    @Override
+    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+
+        super.onCreateView(inflater, container, savedInstanceState);
+
+        rootView = inflater.inflate(R.layout.fragment_services, container, false);
+        assignViews();
+
+        protocols = getResources().getStringArray(R.array.protocols);
+        mConnectionInfo = getActivity().getSharedPreferences(getString(R.string.connection_info), Context.MODE_PRIVATE);
+
+        updateUI();
+
+        ListView list = (ListView) rootView.findViewById(R.id.services_list_view);
+
+        protocolList = new ArrayList<ServicesListItem>();
+        int i = 0;
+        for (String protocol : protocols) {
+            protocolList.add(new ServicesListItem(protocol));
+            protocolList.get(i).attacks = dbh.numBssidSeen(protocolList.get(i).protocol, mConnectionInfo.getString(getString(R.string.connection_info_bssid), null));
+            i++;
+        }
+
+        mServicesSwitchService = (Switch) rootView.findViewById(R.id.service_switch_connection);
+
+        if (switchChangeListener == null) {
+            switchChangeListener = new CompoundButton.OnCheckedChangeListener() {
+                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+                    mProfile = ProfileManager.getInstance().getCurrentActivatedProfile();
+                        if (!HelperUtils.isNetworkAvailable(getActivity())) {
+                            if(!MainActivity.getInstance().getHostageService().hasRunningListeners()) {
+                                new AlertDialog.Builder(getActivity())
+                                        .setTitle(R.string.information)
+                                        .setMessage(R.string.wifi_not_connected_msg)
+                                        .setPositiveButton(android.R.string.ok,
+                                                new DialogInterface.OnClickListener() {
+                                                    public void onClick(DialogInterface dialog, int which) {
+
+                                                    }
+                                                }
+                                        )
+                                        .setIcon(android.R.drawable.ic_dialog_info)
+                                        .show();
+                                if(mServicesSwitchService.isChecked()) {
+                                    setStateNotActive();
+                                }
+                                setStateNotConnected();
+                            }
+                            else{
+                                setStateActive();
+                            }
+                    } else {
+                        if (MainActivity.getInstance().isServiceBound()) {
+                            if (isChecked) {
+                                for (String protocol : protocols) {
+                                    if (!protocol.equals("GHOST")) {
+                                        if (!MainActivity.getInstance().getHostageService().isRunning(protocol)) {
+                                            MainActivity.getInstance().getHostageService().startListener(protocol);
+                                        }
+                                    } else {
+                                        if (mProfile.mGhostActive) {
+
+                                            mGhostPorts = mProfile.getGhostPorts();
+                                            if (mGhostPorts.length != 0) {
+                                                for (Integer port : mGhostPorts) {
+                                                    if (!MainActivity.getInstance().getHostageService().isRunning("GHOST", port)) {
+                                                        MainActivity.getInstance().getHostageService().startListener("GHOST", port);
+                                                    }
+                                                }
+                                            }
+
+
+                                        }
+                                    }
+                                }
+                                setStateActive();
+                            } else{
+                                MainActivity.getInstance().getHostageService().stopListeners();
+                                MainActivity.getInstance().stopAndUnbind();
+                                setStateNotActive();
+                            }
+                        }
+                    }
+                }
+
+            };
+        }
+        mServicesSwitchService.setOnCheckedChangeListener(switchChangeListener);
+
+        adapter = new ServicesListAdapter(getActivity().getBaseContext(), protocolList);
+        adapter.setActivity(this.getActivity(), this.mServicesSwitchService, this.switchChangeListener);
+        list.setAdapter(adapter);
+
+        registerBroadcastReceiver();
+
+        return rootView;
+
+    }
+
+    /**
+     * called on start of this fragment.
+     * registers broadcast receiver and binds change listener to main switch
+     */
+    @Override
+    public void onStart() {
+        super.onStart();
+        registerBroadcastReceiver();
+        mServicesSwitchService.setOnCheckedChangeListener(switchChangeListener);
+    }
+
+    /**
+     * unregister the broadcast receiver if a receiver is already registered
+     */
+    private void unregisterBroadcastReceiver() {
+        if (mReceiverRegistered) {
+            LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
+            this.mReceiverRegistered = false;
+        }
+    }
+
+    /**
+     * sets main switch to true
+     */
+    private void setStateActive() {
+            mServicesSwitchService.setChecked(true);
+    }
+
+    /**
+     * sets text of text field to not connected, if the device is not connected to a network
+     */
+    private void setStateNotConnected() {
+        mServicesTextName.setText(R.string.not_connected);
+    }
+
+    /**
+     * sets main switch to false
+     */
+    private void setStateNotActive() {
+        if (mServicesSwitchService.isChecked()) {
+            mServicesSwitchService.setChecked(false);
+        }
+    }
+
+    /**
+     * overrides onStop
+     * unloads the ChangeListener
+     */
+    @Override
+    public void onStop() {
+        super.onStop();
+        mServicesSwitchService.setOnCheckedChangeListener(null);
+    }
+
+    /**
+     * overrides onDestroy
+     * unregisters broadcast receiver, when destroyed
+     */
+    @Override
+    public void onDestroy() {
+        super.onDestroy();
+        unregisterBroadcastReceiver();
+    }
+}

+ 1 - 1
src/de/tudarmstadt/informatik/hostage/ui2/fragment/SettingsFragment.java → src/de/tudarmstadt/informatik/hostage/ui/fragment/SettingsFragment.java

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

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

@@ -0,0 +1,1830 @@
+package de.tudarmstadt.informatik.hostage.ui.fragment;
+
+import android.annotation.SuppressLint;
+import android.app.Activity;
+import android.app.Fragment;
+import android.app.FragmentManager;
+import android.content.Context;
+import android.content.Intent;
+import android.content.res.Configuration;
+import android.graphics.Color;
+import android.os.Bundle;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ImageButton;
+import android.widget.LinearLayout;
+import android.widget.ListView;
+import android.widget.ProgressBar;
+import android.widget.RelativeLayout;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.echo.holographlibrary.Bar;
+import com.echo.holographlibrary.BarGraph;
+import com.echo.holographlibrary.Line;
+import com.echo.holographlibrary.LineGraph;
+import com.echo.holographlibrary.LinePoint;
+import com.echo.holographlibrary.PieGraph;
+import com.echo.holographlibrary.PieSlice;
+
+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 de.tudarmstadt.informatik.hostage.R;
+import de.tudarmstadt.informatik.hostage.logging.Record;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
+import de.tudarmstadt.informatik.hostage.ui.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.
+ */
+public class StatisticsFragment extends Fragment implements ChecklistDialog.ChecklistDialogListener, DateTimeDialogFragment.DateTimeDialogFragmentListener {
+
+    static final String FILTER_MENU_TITLE_BSSID = "BSSID";
+    static final String FILTER_MENU_TITLE_ESSID = "ESSID";
+    static final String FILTER_MENU_TITLE_PROTOCOLS = MainActivity.getContext().getString(R.string.stats_protocols);
+    static final String FILTER_MENU_TITLE_PROTOCOL = 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_REMOVE = MainActivity.getContext().getString(R.string.rec_reset_filter);
+    static final String FILTER_MENU_POPUP_TITLE = MainActivity.getContext().getString(R.string.rec_filter_by);
+
+
+    static final String MENU_TITLE_PROTOCOLS = MainActivity.getContext().getString(
+			R.string.stats_protocols);
+    static final String MENU_TITLE_NETWORK = MainActivity.getContext().getString(
+			R.string.stats_networks);
+    static final String MENU_TITLE_ATTACKS = MainActivity.getContext().getString(
+			R.string.stats_attacks);
+
+    static final String MENU_POPUP_TITLE = MainActivity.getContext().getString(
+			R.string.stats_visualize);
+
+    static final String CHART_TYPE_TITLE_BAR = MainActivity.getContext().getString(
+			R.string.stats_bar_plot);
+    static final String CHART_TYPE_TITLE_PIE = MainActivity.getContext().getString(R.string.stats_pie_plot);
+    static final String CHART_TYPE_TITLE_LINE = MainActivity.getContext().getString(R.string.stats_line_plot);
+
+    //static final String DIALOG_PROTOCOLS_TITLE = MainActivity.getContext().getString(R.string.stats_select_protocol_data);
+    static final String DIALOG_NETWORK_TITLE = MainActivity.getContext().getString(R.string.stats_select_network_data);
+    static final String DIALOG_ATTACK_TITLE = MainActivity.getContext().getString(R.string.stats_select_attack_data);
+
+    static  final String COMPARE_TITLE_AttacksPerProtocol   = MainActivity.getContext().getString(R.string.stats_attacks_protocol);
+    //static  final String COMPARE_TITLE_UsesPerProtocol      = MainActivity.getContext().getString(R.string.stats_uses_protocol);
+    static  final String COMPARE_TITLE_AttacksPerDate       = MainActivity.getContext().getString(R.string.stats_attacks_date);
+    static  final String COMPARE_TITLE_AttacksPerTime       = MainActivity.getContext().getString(R.string.stats_attacks_time);
+    static  final String COMPARE_TITLE_AttacksPerBSSID      = MainActivity.getContext().getString(R.string.stats_attacks_bssid);
+    static  final String COMPARE_TITLE_AttacksPerESSID      = MainActivity.getContext().getString(R.string.stats_attacks_essid);
+    static final String FILTER_MENU_PROTOCOL_SINGLE_CHOICE_TITLE = MainActivity.getContext().getString(R.string.stats_select_protocol);
+
+    static final String TABLE_HEADER_VALUE_TITLE_ATTACKS_COUNT = MainActivity.getContext().getString(R.string.stats_attacks_count);
+    static final String TABLE_HEADER_VALUE_TITLE_ATTACKS_PERCENTAGE = MainActivity.getContext().getString(R.string.stats_per_cent_all);
+
+
+    static final String OTHER_CHART_TITLE = MainActivity.getContext().getString(R.string.stats_other);
+
+    // MINIMAL 2
+    static int MAX_NUMBER_OF_CHART_OBJECTS = 6;
+
+    private boolean wasBelowTimePicker;
+
+    private LogFilter filter;
+
+    /*Maybe used in the future if the users doesn't need a filterbutton in every situation*/
+    private boolean showFilterButton;
+
+    private PieGraph pieGraph;
+    private LineGraph lineGraph;
+    private BarGraph barGraph;
+
+    private View rootView;
+    private View currentPlotView;
+
+    private Thread loader;
+    private ProgressBar spinner;
+
+    private ArrayList<PlotComparisonItem> currentData;
+
+    private HostageDBOpenHelper dbh;
+
+    private ListView legendListView;
+
+    private Toast noDataNotificationToast;
+
+
+    private String selectedCompareData = COMPARE_TITLE_AttacksPerProtocol;
+
+
+    /**The Charttype.
+     * PIE_CHART = 0
+     * BAR_CHART = 1
+     * LINE_CHART = 2
+     */
+    public enum ChartType {
+        PIE_CHART(0),
+        BAR_CHART(1),
+        LINE_CHART(2);
+
+        private int value;
+
+        private ChartType(int value) {
+            this.value = value;
+        }
+        static public ChartType create(int value){
+            if (value < 0 || value  >= ChartType.values().length) return ChartType.PIE_CHART;
+            return  ChartType.values()[value];
+        }
+
+        public String toString(){
+            if (this.equals(ChartType.create(0))){
+                return CHART_TYPE_TITLE_PIE;
+            }
+            if (this.equals(ChartType.create(1))){
+                return CHART_TYPE_TITLE_BAR;
+            }
+            return CHART_TYPE_TITLE_LINE;
+        }
+
+    }
+
+    /**Returns the FilterButton.
+    * @return ImageButton filterButton*/
+    private ImageButton getFilterButton(){
+        return (ImageButton) this.rootView.findViewById(R.id.FilterButton);
+    }
+
+    /**
+    * Returns the layout ID
+    * @Return int layoutID
+    * */
+    public int getLayoutID(){
+        return R.layout.fragment_statistics;
+    }
+
+    @Override
+    public View onCreateView(LayoutInflater inflater, ViewGroup container,
+                             Bundle savedInstanceState) {
+
+	    super.onCreateView(inflater, container, savedInstanceState);
+
+	    getActivity().setTitle(getResources().getString(R.string.drawer_statistics));
+
+        dbh = new HostageDBOpenHelper(this.getBaseContext());
+
+        // Get the message from the intent
+
+        if (this.filter == null){
+            Intent intent = this.getActivity().getIntent();
+            LogFilter filter = intent.getParcelableExtra(LogFilter.LOG_FILTER_INTENT_KEY);
+            if(filter == null){
+                this.clearFilter();
+            } else {
+                this.filter = filter;
+            }
+        }
+
+        this.rootView = inflater.inflate(this.getLayoutID(), container, false);
+
+        this.configureRootView(this.rootView);
+
+        return this.rootView;
+    }
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setHasOptionsMenu(true);
+        setRetainInstance(true);
+    }
+
+    @Override
+    public void onConfigurationChanged(Configuration newConfig){
+        super.onConfigurationChanged(newConfig);
+        LayoutInflater inflater = LayoutInflater.from(getActivity());
+
+        ViewGroup container = (ViewGroup) this.getView();
+        container.removeAllViewsInLayout();
+        this.rootView = inflater.inflate(this.getLayoutID(), container, false);
+        container.addView(this.rootView);
+
+        this.configureRootView(this.rootView);
+
+    }
+
+    /**Returns the base context.
+    * @return Context the base context
+    * */
+    private Context getBaseContext(){
+        return this.getActivity().getBaseContext();
+    }
+
+    /**Returns the application context.
+    * @return Context the application context*/
+    private Context getApplicationContext(){
+        return this.getActivity().getApplicationContext();
+    }
+
+    /**Configures the given rootview.
+    * Sets the Spinner, the list and all requiered buttons.
+    * It also actualises the current plot type.
+    * @param  rootView View
+    * */
+    public void configureRootView(View rootView){
+        LinearLayout plotLayout = (LinearLayout) rootView.findViewById(R.id.plot_layout);
+        plotLayout.removeAllViews();
+        plotLayout.setWillNotDraw(false);
+
+        ProgressBar spinner = (ProgressBar) rootView.findViewById(R.id.progressBar1);
+        if(spinner != null){
+            this.spinner = spinner;
+            this.spinner.setVisibility(View.GONE);
+        } else {
+            RelativeLayout parent = (RelativeLayout) this.spinner.getParent();
+            parent.removeView(this.spinner);
+            RelativeLayout newParent = (RelativeLayout) rootView.findViewById(R.id.plot_parent_layout);
+            if (newParent != null){
+                newParent.addView(this.spinner);
+            }
+        }
+
+        this.legendListView = (ListView) rootView.findViewById(R.id.legend_list_view);
+        this.legendListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
+            @Override
+            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
+                StatisticsFragment.this.userTappedOnLegendItem(i);
+            }
+        });
+        rootView.setWillNotDraw(false);
+
+        ImageButton visualButton = (ImageButton) rootView.findViewById(R.id.plot_data_button);
+        visualButton.setOnClickListener(new View.OnClickListener() {
+            public void onClick(View v) {
+                StatisticsFragment.this.openBarSelectionMenuOnView(v);
+            }
+        });
+
+
+        ImageButton filterButton = this.getFilterButton();
+        filterButton.setOnClickListener(new View.OnClickListener() {
+            public void onClick(View v) {
+                StatisticsFragment.this.openFilterMenuOnView(v);
+            }
+        });
+
+        this.actualiseCurrentPlot();
+
+        if (this.currentPlotView instanceof BarGraph){
+            this.setTitle("" + this.getCurrentSelectedProtocol() + ": " +this.selectedCompareData);
+        } else {
+            this.setTitle(this.selectedCompareData);
+        }
+    }
+
+    /**Sets the title over the plot view.
+    * @param  title String
+    * */
+    public void setTitle(String title){
+        TextView titleView = (TextView) this.rootView.findViewById(R.id.title_text_view);
+        if (title != null && titleView != null){
+            titleView.setText(title);
+            titleView.invalidate();
+        }
+    }
+
+    /**Returns the title over the plot view.
+    * @return String title
+    * */
+    public String getTitle(){
+        TextView titleView = (TextView) this.rootView.findViewById(R.id.title_text_view);
+        if (titleView != null){
+            return "" + titleView.getText();
+        }
+        return "";
+    }
+
+    @Override
+    public void onStart() {
+        super.onStart();
+        this.actualiseCurrentPlot();
+        this.currentPlotView.invalidate();
+
+        if (this.currentPlotView instanceof BarGraph){
+            this.setTitle("" + this.getCurrentSelectedProtocol() + ": " +this.selectedCompareData);
+        } else {
+            this.setTitle(this.selectedCompareData);
+        }
+    }
+
+    /**Sets the current chart to the given type and acualises it.
+    * @param  type  {@link de.tudarmstadt.informatik.hostage.ui.fragment.StatisticsFragment.ChartType ChartType}
+    * */
+    public void setChartType(ChartType type){
+        boolean shouldChange = true;
+        this.clearFilter();
+        if (this.currentPlotView != null){
+            if (type == ChartType.PIE_CHART){
+                shouldChange = ! (this.currentPlotView instanceof PieGraph);
+                // SET FILTER BUTTON HIDDEN
+                ImageButton filterButton = this.getFilterButton();
+                if (filterButton != null) filterButton.setVisibility(View.GONE);
+            } else {
+                if (this.pieGraph != null)
+                     this.pieGraph.setVisibility(View.GONE);
+                // SHOW FILTER BUTTON
+                ImageButton filterButton = this.getFilterButton();
+                if (filterButton != null) filterButton.setVisibility(View.VISIBLE);
+            }
+            if (type == ChartType.LINE_CHART){
+                shouldChange = ! (this.currentPlotView instanceof LineGraph);
+            } else {
+                if (this.lineGraph != null)
+                     this.lineGraph.setVisibility(View.GONE);
+            }
+            if (type == ChartType.BAR_CHART){
+                shouldChange = ! (this.currentPlotView instanceof BarGraph);
+
+            } else {
+                if (this.barGraph != null)
+                    this.barGraph.setVisibility(View.GONE);
+
+            }
+        }
+        if (shouldChange){
+            this.currentPlotView = this.getPlotViewForType(type);
+            this.currentPlotView.setVisibility(View.VISIBLE);
+
+        }
+        this.actualiseCurrentPlot();
+
+    }
+
+    /**Returns the plot view for a given type.
+    * @param type  {@link de.tudarmstadt.informatik.hostage.ui.fragment.StatisticsFragment.ChartType ChartType}
+    * */
+    public View getPlotViewForType(ChartType type){
+        switch (type){
+            case PIE_CHART:
+                return this.getPieGraphView();
+            case LINE_CHART:
+                return this.getLineGraphView();
+            default:
+                return this.getBarGraphView();
+        }
+    }
+
+    /**Actualises the list view. Therefore it requiers the "currentData".*/
+    public void actualiseLegendList(){
+        StatisticListAdapter adapter = new StatisticListAdapter(this.getApplicationContext(), this.currentData);
+        if (this.currentPlotView instanceof LineGraph){
+            adapter.setValueFormatter(new StatisticListAdapter.ValueFormatter() {
+                @Override
+                public String convertValueForItemToString(PlotComparisonItem item) {
+                    return String.format("%.02f", item.getValue2()) + " %" + " " + "("+ (item.getValue1().intValue())  +")";
+                }
+            });
+        } else {
+
+            adapter.setValueFormatter(new StatisticListAdapter.ValueFormatter() {
+                @Override
+                public String convertValueForItemToString(PlotComparisonItem item)  {
+                    int v = (int) item.getValue2().intValue();
+                    return "" + v;
+                }
+            });
+
+        }
+        this.legendListView.setAdapter(adapter);
+
+        TextView tableHeaderTitleView = (TextView) this.rootView.findViewById(R.id.table_header_title_textview);
+        TextView tableHeaderValueView = (TextView) this.rootView.findViewById(R.id.table_header_value_textview);
+        if (this.currentPlotView instanceof LineGraph){
+            tableHeaderTitleView.setText(FILTER_MENU_TITLE_ESSID);
+            tableHeaderValueView.setText(TABLE_HEADER_VALUE_TITLE_ATTACKS_PERCENTAGE);
+        }
+        if (this.currentPlotView instanceof PieGraph){
+            tableHeaderTitleView.setText(FILTER_MENU_TITLE_PROTOCOL);
+            tableHeaderValueView.setText(TABLE_HEADER_VALUE_TITLE_ATTACKS_COUNT);
+        }
+        if (this.currentPlotView instanceof BarGraph){
+            tableHeaderValueView.setText(TABLE_HEADER_VALUE_TITLE_ATTACKS_COUNT);
+            if (this.selectedCompareData.equals(COMPARE_TITLE_AttacksPerBSSID)){
+                tableHeaderTitleView.setText(FILTER_MENU_TITLE_BSSID);
+            } else {
+                tableHeaderTitleView.setText(FILTER_MENU_TITLE_ESSID);
+            }
+        }
+        if (this.currentData == null || this.currentData.isEmpty()){
+            tableHeaderTitleView.setText("");
+            tableHeaderValueView.setText("");
+        }
+    }
+
+    /*
+    * MENU
+    * */
+    /**Opens the Bar Option Menu above the given anchor view.
+    * @param anchorView View*/
+     private void openBarSelectionMenuOnView(View anchorView){
+        SimplePopupTable visualiseMenu = new SimplePopupTable(this.getActivity(), new AbstractPopup.OnPopupItemClickListener() {
+            public void onItemClick(Object ob) {
+                if (ob instanceof AbstractPopupItem){
+                    AbstractPopupItem item = (AbstractPopupItem) ob;
+                    StatisticsFragment.this.userSelectMenuItem(item);
+                }
+            }
+        });
+        visualiseMenu.setTitle(MENU_POPUP_TITLE);
+        int id = 0;
+        for(String title : StatisticsFragment.this.getMenuTitles()){
+            SimplePopupItem item = new SimplePopupItem(this.getActivity());
+            item.setTitle(title);
+            item.setItemId(id);
+            item.setSelected(false);
+            visualiseMenu.addItem(item);
+            id++;
+        }
+        visualiseMenu.showOnView(anchorView);
+    }
+
+    /**Will be called when the users selected an menu item (visualise menu / plot menu).
+    * If the user selected "Protocols" this method sets the current plot type to piegraph.
+    * Otherwise it will open a new dialog to select the comparison type.
+    * */
+    private void userSelectMenuItem(AbstractPopupItem item){
+        // OPEN A DIALOG TO SPECIFY THE VISUALISE DATA
+        if (item.getTitle().equals(MENU_TITLE_PROTOCOLS)){
+            ChartType chartType = ChartType.PIE_CHART;
+            this.selectedCompareData = COMPARE_TITLE_AttacksPerProtocol;
+            this.setChartType(chartType);
+            this.setTitle(COMPARE_TITLE_AttacksPerProtocol);
+        }
+        if (item.getTitle().equals(MENU_TITLE_NETWORK)){
+            this.openNetworkDataDialog();
+        }
+        if (item.getTitle().equals(MENU_TITLE_ATTACKS)){
+            this.openAttackDataDialog();
+        }
+    }
+
+    /**Returns the menu titles (visualise menu / plot menu)*/
+    private ArrayList<String> getMenuTitles(){
+        ArrayList<String> titles = new ArrayList<String>();
+        titles.add(MENU_TITLE_PROTOCOLS);
+        titles.add(MENU_TITLE_NETWORK);
+        titles.add(MENU_TITLE_ATTACKS);
+        return titles;
+    }
+
+    /*
+    * PLOT DATA DIALOGS
+    * */
+//     private void openProtocolDataDialog(){
+//        ArrayList<String> titles = this.getDialogProtocolDataTitle();
+//        ChecklistDialog newFragment = new ChecklistDialog(DIALOG_PROTOCOLS_TITLE, titles, this.selectedData(titles), false , this);
+//        newFragment.show(this.getActivity().getFragmentManager(), DIALOG_PROTOCOLS_TITLE);
+//    }
+    /**Opens the network comparison dialog*/
+    private void openNetworkDataDialog(){
+        ArrayList<String> titles = this.getDialogNetworkDataTitle();
+        ChecklistDialog newFragment = new ChecklistDialog(DIALOG_NETWORK_TITLE, titles, this.selectedData(titles), false , this);
+        newFragment.show(this.getActivity().getFragmentManager(), DIALOG_NETWORK_TITLE);
+    }
+    /**Opens the attack comparison dialog*/
+    private void openAttackDataDialog(){
+        ArrayList<String> titles = this.getDialogAttackDataTitle();
+        ChecklistDialog newFragment = new ChecklistDialog(DIALOG_ATTACK_TITLE, titles, this.selectedData(titles), false , this);
+        newFragment.show(this.getActivity().getFragmentManager(), DIALOG_ATTACK_TITLE);
+    }
+
+    /*
+    *
+    * DIALOG ACTION METHODS
+    *
+    * */
+    /**
+     * Will be called if the user selects the positiv button on an checklist dialog.
+     * @param dialog  {@link ChecklistDialog ChecklistDialog}
+     * */
+     public void onDialogPositiveClick(ChecklistDialog dialog) {
+        String title = dialog.getTitle();
+        ArrayList<String> titles =dialog.getSelectedItemTitles();
+
+        if (title.equals(FILTER_MENU_TITLE_PROTOCOLS)){
+            //titles = titles.size() == 0 ? this.protocolTitles() : titles;
+            this.filter.setProtocols(titles);
+            this.actualiseCurrentPlot();
+            return;
+        }
+        if (title.equals(FILTER_MENU_PROTOCOL_SINGLE_CHOICE_TITLE)){
+            if (titles.size() == 0){
+                titles = new ArrayList<String>();
+                titles.add(this.protocolTitles().get(0));
+            }
+            this.filter.setProtocols(titles);
+
+            this.actualiseCurrentPlot();
+            String fragTitle = "" + this.getCurrentSelectedProtocol() + ": " + this.selectedCompareData;
+            this.setTitle(fragTitle);
+
+            return;
+        }
+        if (title.equals(FILTER_MENU_TITLE_ESSID)){
+            this.filter.setESSIDs(titles);
+            this.actualiseCurrentPlot();
+
+            return;
+        }
+        if (title.equals(FILTER_MENU_TITLE_BSSID)){
+            this.filter.setBSSIDs(titles);
+            this.actualiseCurrentPlot();
+
+            return;
+        }
+
+        if (titles.size() != 0){
+            String data = titles.get(0);
+            this.setTitle(data);
+
+            this.actualiseFilterButton();
+
+            if (data.equals(COMPARE_TITLE_AttacksPerTime) || data.equals(COMPARE_TITLE_AttacksPerDate)){
+                ChartType chartType = ChartType.LINE_CHART;
+                this.selectedCompareData = data;
+                this.setChartType(chartType);
+                return;
+            }
+            if (data.equals(COMPARE_TITLE_AttacksPerBSSID) || data.equals(COMPARE_TITLE_AttacksPerESSID)){
+                ChartType chartType = ChartType.BAR_CHART;
+                this.selectedCompareData = data;
+                this.setChartType(chartType);
+
+                String fragTitle = "" + this.getCurrentSelectedProtocol() + ": " + this.selectedCompareData;
+                this.setTitle(fragTitle);
+                return;
+            }
+        }
+
+    }
+
+    /**
+     * Will be called if the user selects the negativ button on an checklist dialog.
+     * @param dialog  {@link ChecklistDialog ChecklistDialog}
+     * */
+    public void onDialogNegativeClick(ChecklistDialog dialog) {
+
+    }
+    /*
+    *
+    * DIALOG DATA
+    *
+    * */
+
+
+//     private ArrayList<String> getDialogProtocolDataTitle(){
+//        ArrayList<String> data = new ArrayList<String>();
+//        data.add(COMPARE_TITLE_AttacksPerProtocol);
+//        data.add(COMPARE_TITLE_UsesPerProtocol);
+//        return data;
+//    }
+    /**
+     *  Returns the Attacks comparison titles.
+     * @return  ArrayList<String> the titles
+     */
+    private ArrayList<String> getDialogAttackDataTitle(){
+        ArrayList<String> data = new ArrayList<String>();
+        data.add(COMPARE_TITLE_AttacksPerDate);
+        data.add(COMPARE_TITLE_AttacksPerTime);
+        return data;
+    }
+    /**
+     *  Returns the network comparison titles.
+     * @return  ArrayList<String> the titles
+     */
+    private ArrayList<String> getDialogNetworkDataTitle(){
+        ArrayList<String> data = new ArrayList<String>();
+        data.add(COMPARE_TITLE_AttacksPerESSID);
+        data.add(COMPARE_TITLE_AttacksPerBSSID);
+        return data;
+    }
+    /**
+     * DEFAULT
+     *  Returns an boolean array with a default selection. Just the first object is true.
+     * @return  boolean[] selected array
+     */
+    private boolean[] selectedData(ArrayList<String> data){
+        boolean[] selected = new boolean[data.size()];
+         // SET DEFAULT
+        selected[0] = true;
+        return selected;
+    }
+
+    /*
+    *
+    *  FILTER BUTTON
+    *
+    * */
+
+    /**Paints the filter button if the current filter object is set.*/
+    private void actualiseFilterButton(){
+        if ((this.filter.isSet() && (!(this.currentPlotView instanceof BarGraph))|| (this.filter.hasATimestamp() || this.filter.hasBSSIDs() || this.filter.hasESSIDs()))){
+            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();
+            }
+        }
+    }
+
+    /**
+     * Opens the filter menu above an given anchor view.
+     * @param  anchor View
+     */
+     private void openFilterMenuOnView(View anchor){
+        SimplePopupTable filterMenu = new SimplePopupTable(this.getActivity(), new AbstractPopup.OnPopupItemClickListener() {
+            public void onItemClick(Object ob) {
+                if (ob instanceof  AbstractPopupItem){
+                    AbstractPopupItem item = (AbstractPopupItem) ob;
+                    StatisticsFragment.this.onFilterMenuItemSelected(item);
+                }
+            }
+        });
+
+        filterMenu.setTitle(FILTER_MENU_POPUP_TITLE);
+        for(String title : StatisticsFragment.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(anchor);
+    }
+
+    /**
+     * Will be called if the user selected an filter item.
+     * @param  item  {@link AbstractPopupItem AbstractPopupItem}
+     */
+    private void onFilterMenuItemSelected(AbstractPopupItem item){
+        if (item instanceof SplitPopupItem){
+            SplitPopupItem sItem = (SplitPopupItem) item;
+            this.wasBelowTimePicker = sItem.wasRightTouch;
+            if (this.wasBelowTimePicker){
+                this.openTimestampToFilterDialog();
+            } else {
+                this.openTimestampFromFilterDialog();
+            }
+            return;
+        }
+        String title = item.getTitle();
+        if (title.equals(FILTER_MENU_TITLE_ESSID)){
+            this.openESSIDFilterDialog();
+        }
+        if (title.equals(FILTER_MENU_TITLE_BSSID)){
+            this.openBSSIDFilterDialog();
+        }
+        if (title.equals(FILTER_MENU_TITLE_PROTOCOL)){
+            this.openFilterDialogSelectProtocol();
+        }
+        if (title.equals(FILTER_MENU_TITLE_PROTOCOLS)){
+            this.openProtocolsFilterDialog();
+        }
+        if (title.equals(FILTER_MENU_TITLE_REMOVE)){
+            this.clearFilter();
+            this.actualiseCurrentPlot();
+        }
+    }
+
+    /**
+     * Return the menu titles of the filter menu.
+     * @return ArrayList<String> filter menu title
+     * */
+    private ArrayList<String> filterMenuTitles(){
+        ArrayList<String> titles = new ArrayList<String>();
+        if (this.currentPlotView instanceof LineGraph){
+            titles.add(FILTER_MENU_TITLE_ESSID);
+            titles.add(FILTER_MENU_TITLE_PROTOCOLS);
+            titles.add(FILTER_MENU_TITLE_TIMESTAMP_ABOVE);
+            if (this.filter.hasESSIDs() || this.filter.hasATimestamp() || (this.filter.getProtocols() != null  && this.filter.hasProtocols() && this.filter.getProtocols().size() != this.protocolTitles().size())){
+                titles.add(FILTER_MENU_TITLE_REMOVE);
+            }
+        } else {
+            titles.add(FILTER_MENU_TITLE_PROTOCOL);
+            String protocol = this.getCurrentSelectedProtocol();
+            if (protocol.length() > 0){
+                if (this.selectedCompareData.equals(COMPARE_TITLE_AttacksPerBSSID)){
+                    titles.add(FILTER_MENU_TITLE_BSSID);
+                } else {
+                    // DEFAULT
+                    titles.add(FILTER_MENU_TITLE_ESSID);
+                }
+            }
+            titles.add(FILTER_MENU_TITLE_TIMESTAMP_ABOVE);
+            if (this.filter.hasATimestamp() || this.filter.hasESSIDs() || this.filter.hasBSSIDs()
+                    || (this.currentPlotView instanceof LineGraph && this.filter.hasProtocols())){
+                titles.add(FILTER_MENU_TITLE_REMOVE);
+            }
+        }
+        return titles;
+    }
+
+    /**
+     * Opens a multiple protocol checklist 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 a single protocol checklist dialog
+     */
+    private void openFilterDialogSelectProtocol(){
+        ArrayList<String> titles = this.protocolTitles();
+        boolean[] selected = new boolean[titles.size()];
+        int i = 0;
+        for (String title : titles){
+            selected[i] = title.equals(this.getCurrentSelectedProtocol());
+            i++;
+        }
+        ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_PROTOCOL_SINGLE_CHOICE_TITLE, titles, selected, false , this);
+        newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_PROTOCOL_SINGLE_CHOICE_TITLE);
+    }
+
+    /**
+     * Opens a multiple essid checklist 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 a multiple bssid checlist 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 a minimal timestamp dialog.**/
+    private void openTimestampFromFilterDialog(){
+        this.wasBelowTimePicker = false;
+        DateTimeDialogFragment newFragment = new DateTimeDialogFragment(this.getActivity());
+        newFragment.setDateChangeListener(this);
+        newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_TIMESTAMP_ABOVE);
+
+        if (this.filter.aboveTimestamp != Long.MIN_VALUE)newFragment.setDate(this.filter.aboveTimestamp);
+    }
+
+    /** Opens the maximal timestamp dialog.*/
+    private void openTimestampToFilterDialog(){
+        this.wasBelowTimePicker = true;
+        DateTimeDialogFragment newFragment = new DateTimeDialogFragment(this.getActivity());
+        newFragment.setDateChangeListener(this);
+        newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_TIMESTAMP_BELOW);
+        if (this.filter.belowTimestamp != Long.MAX_VALUE) newFragment.setDate(this.filter.belowTimestamp);
+    }
+
+    /** Returns all essids
+     * If the current plot is a bar graph, it just return all possible essids for the selected protocol
+     * @return ArrayList<String> essids
+     * */
+    public ArrayList<String> essids(){
+        ArrayList<String> records;
+        if (this.currentPlotView instanceof BarGraph){
+            records = dbh.getUniqueESSIDRecordsForProtocol(this.getCurrentSelectedProtocol());
+        } else {
+            records = dbh.getUniqueESSIDRecords();
+        }
+        return records;
+    }
+    /** Returns a boolean array. The position in the array will be true, if the essid is selected in the filter.
+     * @return boolean[] selected essids*/
+    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.getESSIDs().contains(essid));
+            i++;
+        }
+        return selected;
+    }
+
+    /** Returns all bssids
+     * If the current plot is a bar graph, it just return all possible bssids for the selected protocol
+     * @return ArrayList<String> bssids
+     * */
+    public ArrayList<String> bssids(){
+        ArrayList<String> records ;
+        if (this.currentPlotView instanceof BarGraph){
+            records = dbh.getUniqueBSSIDRecordsForProtocol(this.getCurrentSelectedProtocol());
+        } else {
+            records = dbh.getUniqueBSSIDRecords();
+        }
+        return records;
+    }
+    /** Returns a boolean array. The position in the array will be true, if the bssid is selected in the filter.
+     * @return boolean[] selected bssids*/
+    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.getBSSIDs().contains(bssid));
+            i++;
+        }
+        return selected;
+    }
+
+    /**Will be called if the user selects an date on the timestamp dialog*/
+    public void onDateTimePickerPositiveClick(DateTimeDialogFragment dialog) {
+        if(this.wasBelowTimePicker){
+            this.filter.setBelowTimestamp(dialog.getDate());
+        } else {
+            this.filter.setAboveTimestamp(dialog.getDate());
+        }
+        this.actualiseCurrentPlot();
+    }
+
+    /**Will be called if the user cancels an date selection on the timestamp dialog*/
+    public void onDateTimePickerNegativeClick(DateTimeDialogFragment dialog) {
+        if(this.wasBelowTimePicker){
+            this.filter.setBelowTimestamp(Long.MAX_VALUE);
+        } else {
+            this.filter.setAboveTimestamp(Long.MIN_VALUE);
+        }
+        this.actualiseCurrentPlot();
+    }
+
+
+    /*
+    *
+    *  PLOT TYPES
+    *
+    * **/
+    /**Returns the current pie graph.
+     * @return PieGraph current piegraph*/
+     public PieGraph getPieGraphView(){
+        if (this.pieGraph == null) {
+            this.pieGraph = new PieGraph(this.getApplicationContext());
+            LinearLayout plotLayout = (LinearLayout) this.rootView.findViewById(R.id.plot_layout);
+            plotLayout.addView(this.pieGraph);
+            this.pieGraph.setOnSliceClickedListener(new PieGraph.OnSliceClickedListener() {
+                @Override
+                public void onClick(int index) {
+                    StatisticsFragment.this.onSliceClick(index);
+                }
+            });
+        }
+         return this.pieGraph;
+    }
+
+    /**
+     * Returns the current  {@link com.echo.holographlibrary.LineGraph Linegraph} .
+     * @return LineGraph current line graph
+     */
+    public LineGraph getLineGraphView(){
+        if (this.lineGraph == null) {
+            this.lineGraph = new LineGraph(this.getActivity());
+            LinearLayout plotLayout = (LinearLayout) this.rootView.findViewById(R.id.plot_layout);
+            plotLayout.addView(this.lineGraph);
+            this.lineGraph.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
+        }
+        return this.lineGraph;
+    }
+
+    /**
+     * Returns the current  {@link com.echo.holographlibrary.BarGraph BarGraph} .
+     * @return BarGraph the current bar graph
+     */
+    public BarGraph getBarGraphView(){
+        if (this.barGraph == null) {
+            this.barGraph = new BarGraph(this.getActivity());
+            LinearLayout plotLayout = (LinearLayout) this.rootView.findViewById(R.id.plot_layout);
+            this.barGraph.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT ));
+            plotLayout.addView(this.barGraph);
+            this.barGraph.setShowBarText(false);
+            this.barGraph.setPopupImageID(R.drawable.popup_black);
+            this.barGraph.setOnBarClickedListener(new BarGraph.OnBarClickedListener() {
+                @Override
+                public void onClick(int i) {
+                    StatisticsFragment.this.onBarClick(i);
+                }
+            });
+        }
+        return this.barGraph;
+    }
+
+    /*
+    *  FEED PLOTS WITH DATA
+    * */
+
+    /**
+     * Sets the data for the given PieGraph
+     * @param piegraph  {@link com.echo.holographlibrary.PieGraph PieGraph}
+     */
+     public void setPieGraphData(PieGraph piegraph){
+        this.currentData = this.getPieData();
+        if (this.currentData == null){
+            this.currentData = new ArrayList<PlotComparisonItem>();
+        }
+
+        piegraph.removeSlices();
+
+        for (PlotComparisonItem item : this.currentData){
+            PieSlice slice = new PieSlice();
+            slice.setColor(item.getColor());
+            Double value2 = (Double) item.getValue2();
+            float v = value2.floatValue();
+            slice.setValue(v);
+            slice.setTitle(item.getTitle());
+            piegraph.addSlice(slice);
+        }
+        //piegraph.invalidate();
+    }
+
+
+    /**
+     * Sets the data for the given LineGraph
+     * @param linegraph {@link LineGraph Linegraph}
+     */
+    public void setLineGraphData(LineGraph linegraph){
+        this.currentData = this.getLineData();
+        if (this.currentData == null){
+            this.currentData = new ArrayList<PlotComparisonItem>();
+        }
+
+        linegraph.removeAllLines();
+        double rangeMax_Y = 0;
+        double rangeMin_Y = 0;
+
+        double rangeMax_X = 0;
+        double rangeMin_X = 0;
+
+        int count = 0;
+        for (PlotComparisonItem lineItem : this.currentData){
+            ArrayList<PlotComparisonItem> data = lineItem.getChildItems();
+            //int index = 0;
+            Line l = new Line();
+            int lineColor = lineItem.getColor();
+            l.setColor(lineColor);
+
+            for (PlotComparisonItem pointItem : data){
+                LinePoint p = new LinePoint();
+                p.setX(pointItem.getValue1());
+                Double value2 = pointItem.getValue2();
+                p.setY(value2);
+                p.setColor(lineColor);
+                l.addPoint(p);
+                rangeMax_Y = Math.max(pointItem.getValue2(), rangeMax_Y);
+                rangeMax_X = Math.max(pointItem.getValue1(), rangeMax_X);
+
+                if (count != 0){
+                    rangeMin_Y = Math.min(pointItem.getValue2(), rangeMin_Y);
+                    rangeMin_X = Math.min(pointItem.getValue1(), rangeMin_X);
+                } else {
+                    rangeMin_Y = pointItem.getValue2();
+                    rangeMin_X = pointItem.getValue1();
+                }
+                //index++;
+                count++;
+            }
+            linegraph.addLine(l);
+        }
+        // add a bit more space
+        rangeMax_Y++;
+        rangeMin_Y--;
+
+        boolean shouldUseDate = this.selectedCompareData.equals(COMPARE_TITLE_AttacksPerDate);
+        if (shouldUseDate){
+            linegraph.resetXLimits();
+
+            if (this.filter.hasBelowTimestamp()){
+                rangeMax_X = Math.max(this.filter.belowTimestamp, rangeMax_X);
+            }
+            if (this.filter.hasAboveTimestamp()){
+                rangeMin_X = Math.min(this.filter.aboveTimestamp, rangeMin_X);
+            }
+
+            if (rangeMax_X == rangeMin_X){
+                double aDay = 60*60*24*1000;
+                rangeMax_X+= aDay;
+                rangeMin_X-= aDay;
+            }
+
+            double stepRange = (rangeMax_X - rangeMin_X)/(60*60*24*1000);
+            linegraph.setxAxisStep(Math.max(1, (float) Math.min(stepRange, 4)));
+
+            linegraph.setRangeX(rangeMin_X  , rangeMax_X);
+
+            linegraph.setConverter(new LineGraph.AxisDataConverter() {
+                @Override
+                public String convertDataForX_Position(double x) {
+                    return StatisticsFragment.this.getDateAsDayString((long)x);
+                }
+                @Override
+                public  String convertDataForY_Position(double y){
+                    return "" + (long)y;
+                }
+            });
+        } else {
+            linegraph.setxAxisStep(12.f);
+            linegraph.setRangeX(0, 24);
+            linegraph.setConverter(null);
+        }
+
+        int maxY = (int)(rangeMax_Y - rangeMin_Y);
+        linegraph.setYAxisStep(Math.min(maxY, 5));
+        int yStep = (int)linegraph.getyAxisStep();
+        if ((maxY % yStep) != 0) {
+            maxY = maxY + (yStep - (maxY % yStep));
+        }
+        rangeMax_Y = rangeMin_Y + maxY;
+        linegraph.setRangeY(rangeMin_Y, rangeMax_Y);
+        linegraph.setLineToFill(0);
+    }
+
+    /**
+    * Set the graph data to the given graph
+    * @param bargraph {@link BarGraph BarGraph}
+    * */
+    public void setBarGraphData(BarGraph bargraph){
+        this.currentData = this.getBarData();
+        if (this.currentData == null){
+            this.currentData = new ArrayList<PlotComparisonItem>();
+        }
+
+        ArrayList<Bar> bars = new ArrayList<Bar>();
+
+        for (PlotComparisonItem item : this.currentData){
+            Bar d = new Bar();
+            d.setColor(item.getColor());
+            Long value2 =  item.getValue2().longValue();
+            d.setName("");
+            d.setValue(value2.floatValue());
+            bars.add(d);
+        }
+
+        barGraph.setBars(bars);
+    }
+
+    /*
+    *
+    *  FETCH & ACTUALISE RECORD DATA
+    *
+    * */
+    /**
+     * Returns the DataBaseHandler result for the current filter.
+     * @return records {@link java.util.ArrayList}, {@link Record Record}
+     */
+     public ArrayList<Record> getFetchedRecords(){
+        if (this.filter == null) this.clearFilter();
+        return this.dbh.getRecordsForFilter(this.filter);
+    }
+
+    /**Actualises the current plot in a background thread.*/
+     public void actualiseCurrentPlot(){
+         this.spinner.setVisibility(View.VISIBLE);
+
+         this.actualiseFilterButton();
+
+         LinearLayout plotLayout = (LinearLayout) this.rootView.findViewById(R.id.plot_layout);
+
+         if (this.barGraph != null)
+            this.barGraph.setVisibility(View.GONE);
+         if (this.lineGraph != null)
+            this.lineGraph.setVisibility(View.GONE);
+         if (this.pieGraph != null)
+            this.pieGraph.setVisibility(View.GONE);
+
+        View plot = this.currentPlotView;
+         if (plot == null){
+             this.currentPlotView = this.getPieGraphView();
+             plot = this.currentPlotView;
+         }
+         if (plot.getParent() != null && !plot.getParent().equals(plotLayout)){
+             LinearLayout linLayout = (LinearLayout)plot.getParent();
+             linLayout.removeView(plot);
+             plot.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT ));
+             plotLayout.addView(plot);
+         }
+
+         this.currentPlotView = plot;
+
+         final LinearLayout thePlotlayout = plotLayout;
+
+         if (this.loader != null && this.loader.isAlive()) this.loader.interrupt();
+
+         this.loader = null;
+
+         this.loader = new Thread(new Runnable() {
+             @Override
+             public void run() {
+                 this.loadDataInBackground();
+                 this.actualiseUI();
+             }
+
+             private void loadDataInBackground(){
+                 View plot = StatisticsFragment.this.currentPlotView;
+                 if (plot instanceof PieGraph){
+                     PieGraph pie = (PieGraph) plot;
+                     StatisticsFragment.this.setPieGraphData(pie);
+                 }
+                 if (plot instanceof BarGraph){
+                     BarGraph bar = (BarGraph) plot;
+                     StatisticsFragment.this.setBarGraphData(bar);
+                 }
+                 if (plot instanceof LineGraph){
+                     LineGraph line = (LineGraph)plot;
+                     StatisticsFragment.this.setLineGraphData(line);
+                 }
+             }
+
+             private void actualiseUI(){
+
+                 Activity actv = StatisticsFragment.this.getActivity();
+
+                 if (actv != null){
+                     actv.runOnUiThread(new Runnable() {
+                         @Override
+                         public void run() {
+                             // SET VISIBILITY
+                             View plot = StatisticsFragment.this.currentPlotView;
+
+                             if (plot instanceof PieGraph){
+                                 // HIDE FILTER BUTTON
+                                 ImageButton filterButton = StatisticsFragment.this.getFilterButton();
+                                 if (filterButton != null) filterButton.setVisibility(View.GONE);
+                             } else {
+                                 if (StatisticsFragment.this.pieGraph != null){
+                                     StatisticsFragment.this.pieGraph.setVisibility(View.GONE);
+                                     if (StatisticsFragment.this.pieGraph.getParent() != null){
+                                         thePlotlayout.removeView(StatisticsFragment.this.pieGraph);
+                                     }
+                                 }
+                                 // SHOW FILTER BUTTON
+                                 ImageButton filterButton = StatisticsFragment.this.getFilterButton();
+                                 if (filterButton != null) filterButton.setVisibility(View.VISIBLE);
+                             }
+                             if (! (plot instanceof BarGraph)){
+                                 if (StatisticsFragment.this.barGraph != null){
+                                     StatisticsFragment.this.barGraph.setVisibility(View.GONE);
+                                     if (StatisticsFragment.this.barGraph.getParent() != null){
+                                         thePlotlayout.removeView(StatisticsFragment.this.barGraph);
+                                     }
+                                 }
+                             }
+                             if (!(plot instanceof LineGraph)){
+                                 if (StatisticsFragment.this.lineGraph != null){
+                                     StatisticsFragment.this.lineGraph.setVisibility(View.GONE);
+                                     if (StatisticsFragment.this.lineGraph.getParent() != null){
+                                         thePlotlayout.removeView(StatisticsFragment.this.lineGraph);
+                                     }
+                                 }
+                             }
+
+                             plot.setVisibility(View.VISIBLE);
+
+                             if (plot.getParent() == null){
+                                 thePlotlayout.addView(plot);
+                             }
+                             StatisticsFragment.this.actualiseLegendList();
+                             StatisticsFragment.this.currentPlotView.bringToFront();
+                             StatisticsFragment.this.currentPlotView.invalidate();
+
+                             StatisticsFragment.this.spinner.setVisibility(View.GONE);
+
+                             StatisticsFragment.this.showEmptyDataNotification();
+                         }
+                     });
+                 }
+             }
+         });
+
+        this.loader.start();
+     }
+
+    /**
+     * Shows a small toast if the data to show is empty (no records).
+     */
+    private void showEmptyDataNotification(){
+        if (this.noDataNotificationToast == null){
+            this.noDataNotificationToast =  Toast.makeText(getApplicationContext(), R.string.no_data_notification, Toast.LENGTH_SHORT);
+        }
+        if (this.getFilterButton().getVisibility() == View.VISIBLE){
+            this.noDataNotificationToast.setText(R.string.no_data_notification);
+        } else {
+            this.noDataNotificationToast.setText(R.string.no_data_notification_no_filter);
+        }
+        if (this.currentData == null || this.currentData.isEmpty()){
+            this.noDataNotificationToast.show();
+        }
+    }
+
+
+    /** Calculates and returns the data for the piegraph
+     * @return ArrayList<PlotComparisonItem> data */
+    public ArrayList<PlotComparisonItem> getPieData(){
+        // DEFAULT
+        return this.attacksPerProtocols();
+    }
+    /** Calculates and returns the data for the bargraph.
+     * @return ArrayList<PlotComparisonItem> data */
+    public ArrayList<PlotComparisonItem> getBarData(){
+        String protocol = this.getCurrentSelectedProtocol();
+
+        if (protocol.length() > 0){
+            if (this.selectedCompareData.equals(COMPARE_TITLE_AttacksPerESSID)){
+                return this.attacksPerESSID(protocol);
+            }
+            // DEFAULT
+            return this.attacksPerBSSID(protocol);
+        }
+        // Nothing available
+        return new ArrayList<PlotComparisonItem>();
+    }
+    /** Calculates and returns the data for the linegraph
+     * @return ArrayList<PlotComparisonItem> data */
+    public ArrayList<PlotComparisonItem> getLineData(){
+        return this.attacksPerTime();
+    }
+
+    /*
+    *  DATA SOURCE
+    * */
+
+    /*PROTOCOLS OVERVIEW*/
+
+    /**
+     * Returns the attacks per protocols comparison result.
+     * The returned data is resized to the specified limit.
+     * @return ArrayList<PlotComparisonItem>
+     */
+     public synchronized ArrayList<PlotComparisonItem> attacksPerProtocols(){
+        ArrayList<PlotComparisonItem> plotItems = new ArrayList<PlotComparisonItem>();
+         int index = 0;
+        for (String title : this.getSelectedProtocolTitles()){
+            int attacksCount = this.dbh.getAttackPerProtocolCount(title);
+            if (attacksCount == 0) continue;
+            PlotComparisonItem item = new PlotComparisonItem(title,this.getColor(index), 0., (double) attacksCount);
+            plotItems.add(item);
+            index++;
+        }
+         Collections.sort(plotItems, new Comparator<PlotComparisonItem>() {
+             @Override
+             public int compare(PlotComparisonItem s1, PlotComparisonItem s2) {
+                 return s2.getValue2().compareTo(s1.getValue2());
+             }
+         });
+         return this.resizeData(plotItems);
+    }
+
+
+    /*
+    *  LINE PLOT DATA
+    */
+
+    /**
+     * Returns the line graph data responding to the selectedCompareData key.
+     * The returned data is resized to the specified limit.
+     * @return plotItems {@link PlotComparisonItem PlotComparisonItems}
+     */
+    public ArrayList<PlotComparisonItem> attacksPerTime(){
+        HashMap<String,HashMap<Long, ArrayList<Record> > > lineMap = new HashMap<String, HashMap<Long, ArrayList<Record>>>();
+
+        boolean shouldUseDate = this.selectedCompareData.equals(COMPARE_TITLE_AttacksPerDate);
+
+        ArrayList<Record> records = this.getFetchedRecords();
+        for (Record record : records){
+            long timestamp = record.getTimestamp();
+            long time = 0;
+            if (shouldUseDate){
+                time = this.getDateFromMilliseconds(timestamp);
+            } else {
+                time = this.getDayHourFromDate(timestamp);
+            }
+
+            // GET CORRECT MAP
+            HashMap<Long, ArrayList<Record> > recordMap;
+            String groupKey = record.getSsid();
+            if (lineMap.containsKey(groupKey)){
+                recordMap = lineMap.get(record.getSsid());
+            } else {
+                recordMap = new HashMap<Long, ArrayList<Record> >();
+                lineMap.put(groupKey, recordMap);
+            }
+
+            // GET LIST OF RECORDS
+            ArrayList<Record> list;
+            if (recordMap.containsKey(time)){
+                list = recordMap.get(time);
+            } else {
+                list = new ArrayList<Record>();
+                recordMap.put(time, list);
+            }
+            list.add(record);
+        }
+
+        ArrayList<PlotComparisonItem> plotItems = new ArrayList<PlotComparisonItem>();
+
+        int index = 0;
+        for (String groupKey : lineMap.keySet()){
+            HashMap<Long, ArrayList<Record> > recordMap = lineMap.get(groupKey);
+            ArrayList<PlotComparisonItem> singleLineItems = new ArrayList<PlotComparisonItem>();
+
+            int numbOfAttacks = 0;
+            for (long time : recordMap.keySet()){
+                ArrayList<Record>list = recordMap.get(time);
+                if (list.size() == 0) continue;
+                PlotComparisonItem item = new PlotComparisonItem(this.getHourAsTimeString(time), 0 , (double)time, (double) list.size());
+                singleLineItems.add(item);
+                numbOfAttacks +=list.size();
+            }
+
+            Collections.sort(singleLineItems, new Comparator<PlotComparisonItem>() {
+                @Override
+                public int compare(PlotComparisonItem s1, PlotComparisonItem s2) {
+                    return s1.getValue1().compareTo(s2.getValue1());
+                }
+            });
+
+            double itemValue = (((double)numbOfAttacks / (double)records.size())*100.);
+            PlotComparisonItem item = new PlotComparisonItem(groupKey, this.getColor(index), (double) numbOfAttacks, itemValue);
+            item.setChildItems(singleLineItems);
+            plotItems.add(item);
+            index++;
+        }
+        Collections.sort(plotItems, new Comparator<PlotComparisonItem>() {
+            @Override
+            public int compare(PlotComparisonItem s1, PlotComparisonItem s2) {
+                return s2.getValue2().compareTo(s1.getValue2());
+            }
+        });
+        return plotItems;
+    }
+
+    /*
+    *  BAR PLOT DATA
+    */
+    /**Returns plotitems for the comparison "attacks per bssid"
+     * The returned data is resized to the specified limit.
+     * @return ArrayList of  {@link PlotComparisonItem PlotComparisonItems}
+    */
+    public ArrayList<PlotComparisonItem> attacksPerBSSID(String protocol){
+        LogFilter filter = new LogFilter();
+        ArrayList<String> protocollist = new ArrayList<String>();
+        filter.setAboveTimestamp(this.filter.getAboveTimestamp());
+        filter.setBelowTimestamp(this.filter.getBelowTimestamp());
+        filter.setBSSIDs(this.filter.getBSSIDs());
+        protocollist.add(protocol);
+        filter.setProtocols(protocollist);
+
+        ArrayList<PlotComparisonItem> plotItems = new ArrayList<PlotComparisonItem>();
+
+        HashMap<String, Integer> recordMap = new HashMap<String, Integer>();
+        ArrayList<Record> records = this.dbh.getRecordsForFilter(filter);
+        for (Record record : records){
+            int count = 0;
+            if (recordMap.containsKey(record.getBssid())){
+                count = recordMap.get(record.getBssid());
+            }
+            count++;
+            recordMap.put(record.getBssid(), count);
+        }
+        int index = 0;
+        for (String key : recordMap.keySet()){
+            double value = (double)recordMap.get(key);
+            if (value == 0.) continue;
+            PlotComparisonItem item = new PlotComparisonItem(key, this.getColor(index), 0., value);
+            plotItems.add(item);
+            index++;
+        }
+        Collections.sort(plotItems, new Comparator<PlotComparisonItem>() {
+            @Override
+            public int compare(PlotComparisonItem s1, PlotComparisonItem s2) {
+                return s2.getValue2().compareTo(s1.getValue2());
+            }
+        });
+        return this.resizeData(plotItems);
+    }
+    /**Returns plotitems for the comparison "attacks per essid"
+    * @return ArrayList of  {@link PlotComparisonItem PlotComparisonItems}
+    */
+    public ArrayList<PlotComparisonItem> attacksPerESSID(String protocol){
+        LogFilter filter = new LogFilter();
+        filter.setAboveTimestamp(this.filter.getAboveTimestamp());
+        filter.setBelowTimestamp(this.filter.getBelowTimestamp());
+        filter.setESSIDs(this.filter.getESSIDs());
+        ArrayList<String> protocollist = new ArrayList<String>();
+        protocollist.add(protocol);
+        filter.setProtocols(protocollist);
+
+        ArrayList<PlotComparisonItem> plotItems = new ArrayList<PlotComparisonItem>();
+
+        HashMap<String, Integer> recordMap = new HashMap<String, Integer>();
+        ArrayList<Record> records = this.dbh.getRecordsForFilter(filter);
+        for (Record record : records){
+            int count = 0;
+            if (recordMap.containsKey(record.getSsid())){
+                count = recordMap.get(record.getSsid());
+            }
+            count++;
+            recordMap.put(record.getSsid(), count);
+        }
+        int index = 0;
+        for (String key : recordMap.keySet()){
+            double value =  (double)recordMap.get(key);
+            if (value == 0.) continue;
+            PlotComparisonItem item = new PlotComparisonItem(key,this.getColor(index), 0. ,value);
+            plotItems.add(item);
+            index++;
+        }
+        Collections.sort(plotItems, new Comparator<PlotComparisonItem>() {
+            @Override
+            public int compare(PlotComparisonItem s1, PlotComparisonItem s2) {
+                return s2.getValue2().compareTo(s1.getValue2());
+            }
+        });
+
+        return this.resizeData(plotItems);
+    }
+
+    /**
+    * This will normalize the given list of plot items to the specified length of MAX_NUMBER_OF_CHART_OBJECTS.
+    * Creates an "others" group, containing all objects after the (MAX_NUMBER_OF_CHART_OBJECTS - 1)th object from the given list.
+    * If the given list does contain MAX_NUMBER_OF_CHART_OBJECTS+1 or more objects, nothing will change.
+    *
+    * @param plotItems to normalize  {@link PlotComparisonItem PlotComparisonItems}
+    * @return the normalized ArrayList of  {@link PlotComparisonItem PlotComparisonItems}
+    */
+    private ArrayList<PlotComparisonItem> resizeData(ArrayList<PlotComparisonItem> plotItems){
+        if (plotItems != null){
+            if (plotItems.size() > MAX_NUMBER_OF_CHART_OBJECTS && MAX_NUMBER_OF_CHART_OBJECTS > 1){
+                ArrayList<PlotComparisonItem> copy = new ArrayList<PlotComparisonItem>();
+                ArrayList<PlotComparisonItem> others = new ArrayList<PlotComparisonItem>();
+                double valueOfOthers = 0;
+
+                for (int i = 0; i < plotItems.size(); i++){
+                    if (i < MAX_NUMBER_OF_CHART_OBJECTS - 1){
+                        PlotComparisonItem item = plotItems.get(i);
+                        item.setColor(this.getColor(i));
+                        copy.add(plotItems.get(i));
+                    } else {
+                        PlotComparisonItem item = plotItems.get(i);
+                        others.add(item);
+                        valueOfOthers+=item.getValue2();
+                    }
+                }
+                PlotComparisonItem otherItem = new PlotComparisonItem(OTHER_CHART_TITLE, this.getOtherColor(), 0., valueOfOthers);
+                otherItem.setChildItems(others);
+                copy.add(otherItem);
+
+                Collections.sort(copy, new Comparator<PlotComparisonItem>() {
+                    @Override
+                    public int compare(PlotComparisonItem s1, PlotComparisonItem s2) {
+                        return s2.getValue2().compareTo(s1.getValue2());
+                    }
+                });
+
+                return copy;
+            }
+        }
+        return plotItems;
+    }
+
+    /*
+    * FILTER STUFF
+    * */
+
+    /**
+    * Returns the first selected protocol from all selected protocols.
+    * If no protocol is selected, it return the first protocol in the protocolTitles() list.
+    * @return String protocolName
+    * */
+    private String getCurrentSelectedProtocol(){
+         ArrayList<String> protocolTitles = this.getSelectedProtocolTitles();
+         if (protocolTitles != null && protocolTitles.size() != 0){
+             return  protocolTitles.get(0);
+         }
+         return this.protocolTitles().get(0);
+     }
+
+    /**
+     * Return all Protocols
+    *
+    * @return ArrayList<String> protocolNames
+    * */
+     public ArrayList<String> protocolTitles(){
+        ArrayList<String> titles = new ArrayList<String>();
+        for (String protocol : this.getResources().getStringArray(
+                R.array.protocols)) {
+            titles.add(protocol);
+        }
+        return titles;
+    }
+    /**
+    * Returns a boolean array containing a bool value for each protocol. If the value is true, the filter object contains the protocol.
+    * The array sequence equates to the protocolTitles() list.
+    * @return boolean[] selection array
+    * */
+    public boolean[] selectedProtocols(){
+        ArrayList<String> protocols = this.protocolTitles();
+        boolean[] selected = new boolean[protocols.size()];
+
+        int i = 0;
+        for(String protocol : protocols){
+            selected[i] =(this.filter.protocols.contains(protocol));
+            i++;
+        }
+        return selected;
+    }
+    public ArrayList<String> getSelectedProtocolTitles(){
+        ArrayList<String> knownProtocols = this.protocolTitles();
+        if (this.filter.hasProtocols()){
+            ArrayList<String> titles = new ArrayList<String>();
+            int i =0;
+            for (boolean b : this.selectedProtocols()){
+                if (b){
+                    String title = knownProtocols.get(i);
+                    titles.add(title);
+                }
+                i++;
+            }
+            return titles;
+        }
+        return this.protocolTitles();
+    }
+    /*
+    *
+    * COLOR STUFF
+    *
+    * */
+
+    /** Returns the color for the other group
+     * @return int color*/
+    public int getOtherColor(){
+        return Color.argb(255, 80, 80, 80); // grey
+	}
+    /** Returns the color for the given index
+     * @return int color*/
+    public Integer getColor(int index) {
+		return ColorSequenceGenerator.getColorForIndex(index);
+    }
+
+    /** Returns the Plot layout.
+     *
+     * @return LinearLayout plot layout
+     */
+    public LinearLayout getPlotLayout(){
+        if (this.rootView != null){
+            return (LinearLayout) this.rootView.findViewById(R.id.plot_layout);
+        } else {
+            return null;
+        }
+    }
+
+    /*
+     *
+     *  FILTER STUFF
+     *
+     * */
+    /**
+     * Returns true if the current filter is set for a given filter menu title.
+     * @param  title of the filter menu item {@link String String}
+     * @return boolean b
+     */
+     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.getProtocols() != null  && this.filter.hasProtocols() && this.filter.getProtocols().size() != this.protocolTitles().size());
+        }
+        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 current filter.
+     */
+    private void clearFilter(){
+        if(filter == null) this.filter = new LogFilter();
+        this.filter.clear();
+    }
+
+    /*
+    *
+    *  DATE TRANSFORMATION
+    *
+    */
+
+    /**
+     * Returns the current hour from a date.
+     * @param timeInMillis long
+     * @return milliseconds in long
+     */
+    public long getDayHourFromDate(long timeInMillis){
+
+        Calendar calendar = Calendar.getInstance();
+
+        calendar.setTimeInMillis (timeInMillis);
+        int hour    = calendar.get(Calendar.HOUR_OF_DAY);
+        //int min     = calendar.get(Calendar.MINUTE);
+
+        return hour;
+
+    }
+    /**
+     * Returns the current date without the seconds, minutes, hours.
+     * @param timeInMillis long
+     * @return long date with time 00:00:00
+     * */
+    public long getDateFromMilliseconds(long timeInMillis){
+        long millisInDay = 60 * 60 * 24 * 1000;
+        return (timeInMillis / millisInDay) * millisInDay;
+
+    }
+
+    /**
+    *  Returns the given hour as a formated string.
+     * Format: "HH:00"
+    * */
+    private String getHourAsTimeString(long hour) {
+        return "" + hour + ":00";
+    }
+
+    static final DateFormat dateFormat = new SimpleDateFormat("d.M.yy");
+
+    /**Returns a date as a formated string
+     * @param timeStamp date
+     * @return String date format (d.M.yy)*/
+    @SuppressLint("SimpleDateFormat")
+    private String getDateAsDayString(long timeStamp) {
+        try {
+            Date netDate = (new Date(timeStamp));
+            DateFormat dateFormat = android.text.format.DateFormat.getMediumDateFormat(this.getActivity());
+            return dateFormat.format(netDate);
+            //return dateFormat.format(netDate);
+        } catch (Exception ex) {
+            return "xx";
+        }
+    }
+
+    @SuppressLint("SimpleDateFormat")
+    /**Returns a date as a formated string
+     * @param long date
+     * @return String date format (H:mm  dd/MM/yyyy)*/
+    private String getDateAsString(long timeStamp) {
+        try {
+            DateFormat sdf = new SimpleDateFormat("H:mm  dd/MM/yyyy");
+            Date netDate = (new Date(timeStamp));
+            return sdf.format(netDate);
+        } catch (Exception ex) {
+            return "xx";
+        }
+    }
+
+
+    /**
+     * USERINTERACTION
+     */
+    /**
+     * Will be called if the users taps on a list row.
+     * @param index int
+     */
+    private void userTappedOnLegendItem(int index){
+        if (index < this.currentData.size()){
+            PlotComparisonItem item = this.currentData.get(index);
+            ArrayList<String> selectedData;
+            String sortKey = null;
+            selectedData = new ArrayList<String>();
+
+            if (item.getChildItems() == null){
+                selectedData.add(item.getTitle());
+            } else {
+                for (PlotComparisonItem other : item.getChildItems()){
+                    selectedData.add(other.getTitle());
+                }
+            }
+            LogFilter filter = new LogFilter();
+            if (this.currentPlotView instanceof PieGraph){
+                filter.setProtocols(selectedData);
+            }
+            if (this.currentPlotView instanceof BarGraph){
+
+                if (this.selectedCompareData.equals(COMPARE_TITLE_AttacksPerESSID)){
+                    filter.setESSIDs(selectedData);
+                    sortKey = "ESSID";
+                } else {
+                    filter.setBSSIDs(selectedData);
+                    sortKey = "BSSID";
+                }
+                ArrayList<String> currentSelectedProtocol = new ArrayList<String>();
+                currentSelectedProtocol.add(this.getCurrentSelectedProtocol());
+                filter.setProtocols(currentSelectedProtocol);
+            }
+            if (this.currentPlotView instanceof  LineGraph){
+                selectedData = new ArrayList<String>();
+                selectedData.add(item.getTitle());
+                filter.setESSIDs(selectedData);
+                filter.setProtocols(this.filter.getProtocols());
+                sortKey = "ESSID";
+            }
+
+            if (this.filter.hasATimestamp()){
+                filter.setAboveTimestamp(this.filter.getAboveTimestamp());
+                filter.setBelowTimestamp(this.filter.getBelowTimestamp());
+            }
+
+            this.pushRecordOverviewForFilter(filter, sortKey);
+        }
+    }
+
+    /**Will be called if the user clicked on a slice
+     * @param index of the slice (int)*/
+    public void onSliceClick(int index){
+    }
+    /**Will be called if the user clicked on a bar
+     * @param index of the bar (int)*/
+    public void onBarClick(int index){
+        this.userTappedOnLegendItem(index);
+    }
+
+    /**
+     * Displays a record over view fragment.
+     * @param filter  {@link de.tudarmstadt.informatik.hostage.ui.LogFilter LogFilter}
+     * @param sortKey String
+     */
+    private void pushRecordOverviewForFilter(LogFilter filter, String sortKey){
+
+        FragmentManager fm = this.getActivity().getFragmentManager();
+
+        if (fm != null){
+            RecordOverviewFragment newFragment = new RecordOverviewFragment();
+	        newFragment.setUpNavigatible(true);
+            newFragment.setFilter(filter);
+
+            if (sortKey != null && sortKey.length() != 0) newFragment.setGroupKey(sortKey);
+
+            MainActivity.getInstance().injectFragment(newFragment);
+
+        }
+
+    }
+
+
+}

+ 154 - 104
src/de/tudarmstadt/informatik/hostage/ui2/fragment/ThreatMapFragment.java → src/de/tudarmstadt/informatik/hostage/ui/fragment/ThreatMapFragment.java

@@ -1,11 +1,10 @@
-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;
 
 import java.util.ArrayList;
 import java.util.HashMap;
-import java.util.Iterator;
 import java.util.Map;
 
 import android.app.Activity;
@@ -39,12 +38,10 @@ import com.google.android.gms.maps.model.MarkerOptions;
 
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
-import de.tudarmstadt.informatik.hostage.logging.NetworkRecord;
 import de.tudarmstadt.informatik.hostage.logging.Record;
-import de.tudarmstadt.informatik.hostage.logging.SyncInfoRecord;
 import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
 import de.tudarmstadt.informatik.hostage.ui.LogFilter;
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
+import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
 
 /**
  * ThreatMapFragment
@@ -55,12 +52,17 @@ public class ThreatMapFragment extends Fragment implements GoogleMap.OnInfoWindo
 		GooglePlayServicesClient.ConnectionCallbacks,
 		GooglePlayServicesClient.OnConnectionFailedListener,
 		LocationListener {
+
 	private static GoogleMap sMap = null;
+
 	private static View sView = null;
 
+	private static Thread mLoader = null;
+
 	private static HashMap<String, String> sMarkerIDToSSID = new HashMap<String, String>();
 
 	private LocationClient mLocationClient;
+
 	private static final LocationRequest REQUEST = LocationRequest.create()
 			.setExpirationDuration(5000) // 5 seconds
 			.setInterval(5000)           // 5 seconds
@@ -103,9 +105,10 @@ public class ThreatMapFragment extends Fragment implements GoogleMap.OnInfoWindo
 		RecordOverviewFragment recordOverviewFragment = new RecordOverviewFragment();
 		recordOverviewFragment.setFilter(filter);
 		recordOverviewFragment.setGroupKey("ESSID");
+		recordOverviewFragment.setAllowBack(true);
 
 		MainActivity.getInstance().injectFragment(recordOverviewFragment, false);
-			//recordOverviewFragment.showDetailsForSSID(getActivity(), ssid);
+		//recordOverviewFragment.showDetailsForSSID(getActivity(), ssid);
 		//}
 	}
 
@@ -138,7 +141,9 @@ public class ThreatMapFragment extends Fragment implements GoogleMap.OnInfoWindo
 	 * easier to use than LatLng
 	 */
 	private class Point {
+
 		public double x, y;
+
 		public Point(double sx, double sy) {
 			x = sx;
 			y = sy;
@@ -151,42 +156,51 @@ public class ThreatMapFragment extends Fragment implements GoogleMap.OnInfoWindo
 	 * see MAX_DISTANCE
 	 */
 	private class SSIDArea {
-		public long numAttacks;
-		public long numPortscans;
-		Point mMinimum;
-		Point mMaximum;
+
+		private Point mMinimum, mMaximum;
+
+		public int numPoints;
 
 		public static final int MAX_NUM_ATTACKS = 20;
+
 		public static final float MAX_DISTANCE = 1000.0f; // 1km
 
-		
-		public SSIDArea(LatLng initLocation, long attacks, long portscans) {
-			mMinimum = new Point(initLocation.latitude, initLocation.longitude);
-			mMaximum = new Point(initLocation.latitude, initLocation.longitude);
-			numAttacks = attacks;
-			numPortscans = portscans;
+		public SSIDArea(LatLng initialLocation) {
+			//mMinimum = new Point(360.0, 360.0);
+			//mMaximum = new Point(-360.0, -360.0);
+			mMinimum = new Point(initialLocation.latitude, initialLocation.longitude);
+			mMaximum = new Point(initialLocation.latitude, initialLocation.longitude);
+			numPoints = 1;
 		}
-		
+
 		public boolean doesLocationBelongToArea(LatLng location) {
 			LatLng center = calculateCenterLocation();
 			float[] result = new float[1];
-			Location.distanceBetween(center.latitude, center.longitude, location.latitude, location.longitude, result);
+			Location.distanceBetween(center.latitude, center.longitude, location.latitude,
+					location.longitude, result);
 			return result[0] < MAX_DISTANCE;
 		}
-		
+
+		public void addLocation(LatLng location) {
+			Point point = new Point(location.latitude, location.longitude);
+			if (point.x < mMinimum.x) {
+				mMinimum.x = point.x;
+			}
+			if (point.x > mMaximum.x) {
+				mMaximum.x = point.x;
+			}
+			if (point.y < mMinimum.y) {
+				mMinimum.y = point.y;
+			}
+			if (point.y > mMaximum.y) {
+				mMaximum.y = point.y;
+			}
+			numPoints++;
+		}
+
 		public LatLng calculateCenterLocation() {
 			return new LatLng(0.5 * (mMinimum.x + mMaximum.x), 0.5 * (mMinimum.y + mMaximum.y));
 		}
-		
-		public void addLocation(LatLng location, long attacks, long portscans) {
-			Point point = new Point(location.latitude, location.longitude);
-			if (point.x < mMinimum.x) mMinimum.x = point.x;
-			if (point.x > mMaximum.x) mMaximum.x = point.x;
-			if (point.y < mMinimum.y) mMinimum.y = point.y;
-			if (point.y > mMaximum.y) mMaximum.y = point.y;
-			numAttacks += attacks;
-			numPortscans += portscans;
-		}
 
 		public float calculateRadius() {
 			float[] result = new float[1];
@@ -195,84 +209,109 @@ public class ThreatMapFragment extends Fragment implements GoogleMap.OnInfoWindo
 		}
 
 		public int calculateColor() {
-			long threatLevel = numAttacks;
-			if (threatLevel > MAX_NUM_ATTACKS) threatLevel = MAX_NUM_ATTACKS;
-			float alpha = 1.0f - (float)(threatLevel-1) / (float)(MAX_NUM_ATTACKS-1);
+			int threatLevel = numPoints;
+			if (threatLevel > MAX_NUM_ATTACKS) {
+				threatLevel = MAX_NUM_ATTACKS;
+			}
+			float alpha = 1.0f - (float) (threatLevel - 1) / (float) (MAX_NUM_ATTACKS - 1);
 			return Color.argb(127, (int) (240.0 + 15.0 * alpha), (int) (80.0 + 175.0 * alpha), 60);
 		}
 	}
 
 	/**
 	 * fills the map with markers and circle representing SSIDs
+	 * does it asynchronously in background thread
 	 */
 	private void populateMap() {
-		HostageDBOpenHelper dbh = new HostageDBOpenHelper(getActivity());
-		ArrayList<NetworkRecord> netRecords = dbh.getNetworkInformation();
-		ArrayList<SyncInfoRecord> syncRecords = dbh.getSyncInfo();
-		
-		HashMap<String, ArrayList<SSIDArea>> threadAreas = new HashMap<String, ArrayList<SSIDArea>>();
-
-		for (NetworkRecord netRecord : netRecords) {
-			LatLng location = new LatLng(netRecord.getLatitude(), netRecord.getLongitude());
-			long number_of_attack = 0;
-			long number_of_portscans = 0;
-			for ( Iterator<SyncInfoRecord> i = syncRecords.iterator(); i.hasNext(); ){
-				SyncInfoRecord info = i.next();
-				if(info.getBSSID().equals(netRecord.getBssid())){
-					number_of_attack += info.getNumber_of_attacks();
-					number_of_portscans += info.getNumber_of_portscans();
-					i.remove();
-				}				    
-			}	
-			
-			ArrayList<SSIDArea> areas;
-			if (threadAreas.containsKey(netRecord.getSsid())) {
-				areas = threadAreas.get(netRecord.getSsid());
-				boolean foundArea = false;
-				for (SSIDArea area : areas) {
-					if (area.doesLocationBelongToArea(location)) {
-						area.addLocation(location, number_of_attack, number_of_portscans);
-						foundArea = true;
-						break;
-					}
+		if (mLoader != null) {
+			mLoader.interrupt();
+		}
+		mLoader = new Thread(new Runnable() {
+			private void updateUI(final HashMap<String, ArrayList<SSIDArea>> threatAreas) {
+				if (mLoader.isInterrupted()) {
+					return;
 				}
-				if (!foundArea) {
-					areas.add(new SSIDArea(location, number_of_attack, number_of_portscans));
+
+				Activity activity = getActivity();
+				if (activity != null) {
+					activity.runOnUiThread(new Runnable() {
+						@Override
+						public void run() {
+							sMap.clear();
+
+							CircleOptions circleOptions = new CircleOptions().radius(200.0)
+									.fillColor(Color.argb(127, 240, 80, 60)).strokeWidth(0.0f);
+							BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory
+									.fromResource(R.drawable.wifi_marker);
+							for (Map.Entry<String, ArrayList<SSIDArea>> entry : threatAreas.entrySet()) {
+								String ssid = entry.getKey();
+								ArrayList<SSIDArea> areas = entry.getValue();
+
+								for (SSIDArea area : areas) {
+									int color = area.calculateColor();
+									LatLng center = area.calculateCenterLocation();
+									float radius = area.calculateRadius();
+
+									sMap.addCircle(circleOptions.center(center).radius(100.0 + radius)
+											.fillColor(color));
+									Marker marker = sMap.addMarker(new MarkerOptions()
+											.title(ssid + ": " + area.numPoints + (area.numPoints == 1
+													? getResources()
+													.getString(R.string.attack)
+													: getResources().getString(R.string.attacks))).position(
+													center));
+									marker.setIcon(bitmapDescriptor);
+
+									sMarkerIDToSSID.put(marker.getId(), ssid);
+								}
+							}
+
+						}
+					});
 				}
-			} else {
-				areas = new ArrayList<SSIDArea>();
-				areas.add(new SSIDArea(location, number_of_attack, number_of_portscans));
-				threadAreas.put(netRecord.getSsid(), areas);
-			}	
-		}
+			}
 
-		CircleOptions circleOptions = new CircleOptions().radius(200.0).fillColor(Color.argb(127, 240, 80, 60)).strokeWidth(0.0f);
-		BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.wifi_marker);
-		
-		for (Map.Entry<String, ArrayList<SSIDArea>> entry : threadAreas.entrySet()) {
-			String ssid = entry.getKey();
-			ArrayList<SSIDArea> areas = entry.getValue();
-			
-			for (SSIDArea area : areas)  {
-				int color = area.calculateColor();
-				LatLng center = area.calculateCenterLocation();
-				float radius = area.calculateRadius();
-
-				sMap.addCircle(circleOptions.center(center).radius(100.0 + radius).fillColor(color));
-				Marker marker = sMap.addMarker(new MarkerOptions()
-						.title(ssid  + ": " + (area.numAttacks + area.numPortscans) + ((area.numAttacks+area.numPortscans)  == 1 ? getResources()
-								.getString(R.string.attack) : getResources().getString(R.string.attacks)))
-								.position(center));
-				marker.setIcon(bitmapDescriptor);
-
-				sMarkerIDToSSID.put(marker.getId(), ssid);
+			private HashMap<String, ArrayList<SSIDArea>> doInBackground() {
+				HostageDBOpenHelper dbh = new HostageDBOpenHelper(getActivity());
+				ArrayList<Record> records = dbh.getRecordsForFilter(new LogFilter());
+
+				HashMap<String, ArrayList<SSIDArea>> threatAreas
+						= new HashMap<String, ArrayList<SSIDArea>>();
+
+				for (Record record : records) {
+					LatLng location = new LatLng(record.getLatitude(), record.getLongitude());
+					//Log.i("location", "lat: " + location.latitude + " long: " + location.longitude);
+					ArrayList<SSIDArea> areas;
+					if (threatAreas.containsKey(record.getSsid())) {
+						areas = threatAreas.get(record.getSsid());
+						boolean foundArea = false;
+						for (SSIDArea area : areas) {
+							if (area.doesLocationBelongToArea(location)) {
+								area.addLocation(location);
+								foundArea = true;
+								break;
+							}
+						}
+						if (!foundArea) {
+							areas.add(new SSIDArea(location));
+						}
+					} else {
+						areas = new ArrayList<SSIDArea>();
+						areas.add(new SSIDArea(location));
+						threatAreas.put(record.getSsid(), areas);
+					}
+				}
+
+				return threatAreas;
 			}
-		}
 
-		sMap.setMyLocationEnabled(true);
+			@Override
+			public void run() {
+				updateUI(doInBackground());
+			}
+		});
 
-		LatLng tudarmstadt = new LatLng(49.86923, 8.6632768); // default location
-		sMap.moveCamera(CameraUpdateFactory.newLatLngZoom(tudarmstadt, 13));
+		mLoader.start(); // run!
 	}
 
 	/**
@@ -281,14 +320,14 @@ public class ThreatMapFragment extends Fragment implements GoogleMap.OnInfoWindo
 	 * view must be removed if this object has been created once before
 	 * that is why view is static
 	 *
-	 * @param inflater the inflater
-	 * @param container the container
+	 * @param inflater           the inflater
+	 * @param container          the container
 	 * @param savedInstanceState the savedInstanceState
 	 * @return the view
 	 */
 	@Override
 	public View onCreateView(final LayoutInflater inflater, ViewGroup container,
-	                         Bundle savedInstanceState) {
+			Bundle savedInstanceState) {
 		super.onCreateView(inflater, container, savedInstanceState);
 
 		final Activity activity = getActivity();
@@ -298,10 +337,11 @@ public class ThreatMapFragment extends Fragment implements GoogleMap.OnInfoWindo
 
 		if (sView != null) {
 			ViewGroup parent = (ViewGroup) sView.getParent();
-			if (parent != null)
+			if (parent != null) {
 				parent.removeView(sView);
+			}
 		}
-		
+
 		try {
 			sView = inflater.inflate(R.layout.fragment_threatmap, container, false);
 			if (isGooglePlay()) {
@@ -311,14 +351,14 @@ public class ThreatMapFragment extends Fragment implements GoogleMap.OnInfoWindo
 							.findFragmentById(R.id.threatmapfragment);
 					if (mapFragment != null) {
 						sMap = mapFragment.getMap();
-						populateMap();
 					}
 				}
 			}
 		} catch (InflateException e) {
-        	// map already exists
+			// map already exists
 			//e.printStackTrace();
 		}
+
 		if (sMap != null) {
 			sMap.setOnInfoWindowClickListener(this);
 			// custom info window layout
@@ -332,7 +372,8 @@ public class ThreatMapFragment extends Fragment implements GoogleMap.OnInfoWindo
 				public View getInfoContents(Marker marker) {
 					View view = inflater.inflate(R.layout.fragment_threatmap_infowindow, null);
 					if (view != null) {
-						TextView titleTextView = (TextView)view.findViewById(R.id.threatmap_infowindow_title);
+						TextView titleTextView = (TextView) view
+								.findViewById(R.id.threatmap_infowindow_title);
 						if (titleTextView != null) {
 							titleTextView.setText(marker.getTitle());
 						}
@@ -340,10 +381,17 @@ public class ThreatMapFragment extends Fragment implements GoogleMap.OnInfoWindo
 					return view;
 				}
 			});
+
+			sMap.setMyLocationEnabled(true);
+
+			LatLng tudarmstadt = new LatLng(49.86923, 8.6632768); // default location
+			sMap.moveCamera(CameraUpdateFactory.newLatLngZoom(tudarmstadt, 13));
+
+			populateMap();
 		}
 
 		// tell the user to enable wifi so map data can be streamed
-		if (activity != null && !HelperUtils.isWifiConnected(activity)) {
+		if (activity != null && !HelperUtils.isNetworkAvailable(activity)) {
 			new AlertDialog.Builder(activity)
 					.setTitle(R.string.information)
 					.setMessage(R.string.no_network_connection_threatmap_msg)
@@ -352,7 +400,8 @@ public class ThreatMapFragment extends Fragment implements GoogleMap.OnInfoWindo
 								public void onClick(DialogInterface dialog,
 										int which) {
 								}
-							})
+							}
+					)
 					.setIcon(android.R.drawable.ic_dialog_info).show();
 		}
 
@@ -363,7 +412,8 @@ public class ThreatMapFragment extends Fragment implements GoogleMap.OnInfoWindo
 	public void onResume() {
 		super.onResume();
 		if (mLocationClient == null) {
-			mLocationClient = new LocationClient(MainActivity.getInstance().getApplicationContext(), this, this);
+			mLocationClient = new LocationClient(MainActivity.getInstance().getApplicationContext(),
+					this, this);
 		}
 		mLocationClient.connect();
 	}

+ 11 - 1
src/de/tudarmstadt/informatik/hostage/ui2/fragment/UpNavigatibleFragment.java → src/de/tudarmstadt/informatik/hostage/ui/fragment/UpNavigatibleFragment.java

@@ -1,4 +1,4 @@
-package de.tudarmstadt.informatik.hostage.ui2.fragment;
+package de.tudarmstadt.informatik.hostage.ui.fragment;
 
 import android.app.Fragment;
 
@@ -10,6 +10,8 @@ public abstract class UpNavigatibleFragment extends Fragment {
 	private Class<?> mUpFragment;
 	private boolean mIsUpNavigatible = false;
 
+	private boolean mAllowBack = false;
+
 	public Class<?> getUpFragment(){
 		return mUpFragment;
 	}
@@ -25,4 +27,12 @@ public abstract class UpNavigatibleFragment extends Fragment {
 	public void setUpNavigatible(boolean isUpNavigatible){
 		this.mIsUpNavigatible = isUpNavigatible;
 	}
+
+	public boolean getAllowBack(){
+		return mAllowBack;
+	}
+
+	public void setAllowBack(boolean allowBack){
+		this.mAllowBack = allowBack;
+	}
 }

+ 4 - 1
src/de/tudarmstadt/informatik/hostage/ui2/fragment/opengl/AnimatedMesh.java → 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;
@@ -62,10 +62,13 @@ public class AnimatedMesh {
 	public boolean isActionDone() {
 		if (currentAction == null)
 			return true;
+		return currentFrame <= 1 || currentFrame >= currentAction.numFrames - 1;
+		/*
 		if (reverseAction)
 			return currentFrame <= 0;
 		else
 			return currentFrame >= currentAction.numFrames - 1;
+			*/
 	}
 	
 	private class Bone {

+ 1 - 1
src/de/tudarmstadt/informatik/hostage/ui2/fragment/opengl/HomeGLSurfaceView.java → 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/ui2/fragment/opengl/Quaternion.java → 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;
 
 public class Quaternion {
 	public float w, x, y, z;

+ 1 - 1
src/de/tudarmstadt/informatik/hostage/ui2/fragment/opengl/ThreatIndicatorGLRenderer.java → 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/ui2/helper/ColorSequenceGenerator.java → 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;
 

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

@@ -1,4 +1,10 @@
-package de.tudarmstadt.informatik.hostage.ui2.layouts;
+/**
+ * Copyright (c) 2011, Artem Votincev (apmem.org)
+ * http://www.apache.org/licenses/LICENSE-2.0.txt
+ *
+ * Modified by Alexander Brakowski for the purpose of this project
+ */
+package de.tudarmstadt.informatik.hostage.ui.layouts;
 
 
 import android.content.Context;

+ 1 - 1
src/de/tudarmstadt/informatik/hostage/ui2/model/DrawerListItem.java → 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/ui2/model/ExpandableListItem.java → 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;
 

+ 7 - 6
src/de/tudarmstadt/informatik/hostage/ui2/model/PlotComparisonItem.java → 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;
 
@@ -14,8 +14,9 @@ public class PlotComparisonItem{
 
     private Integer color = 0;
 
-    private ArrayList<PlotComparisonItem> otherData;
+    private ArrayList<PlotComparisonItem> childItems;
 
+    /*CONSTRUCTOR*/
     public PlotComparisonItem(String title, Integer color , Double value1, Double value2){
         super();
         this.color = color;
@@ -24,11 +25,11 @@ public class PlotComparisonItem{
         this.value2 = value2;
     }
 
-    public ArrayList<PlotComparisonItem> getOtherData(){
-        return this.otherData;
+    public ArrayList<PlotComparisonItem> getChildItems(){
+        return this.childItems;
     }
-    public void setOtherData(ArrayList<PlotComparisonItem> other){
-        this.otherData = other;
+    public void setChildItems(ArrayList<PlotComparisonItem> other){
+        this.childItems = other;
     }
     public String getTitle(){
         return this.title;

+ 2 - 2
src/de/tudarmstadt/informatik/hostage/ui2/model/ProfileListItem.java → src/de/tudarmstadt/informatik/hostage/ui/model/ProfileListItem.java

@@ -1,9 +1,9 @@
-package de.tudarmstadt.informatik.hostage.ui2.model;
+package de.tudarmstadt.informatik.hostage.ui.model;
 
 import android.graphics.Bitmap;
 import android.graphics.BitmapFactory;
 
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
+import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
 
 /**
  * @author Alexander Brakowski

+ 24 - 0
src/de/tudarmstadt/informatik/hostage/ui/model/ServicesListItem.java

@@ -0,0 +1,24 @@
+package de.tudarmstadt.informatik.hostage.ui.model;
+
+/**
+ * @author Daniel Lazar
+ * @created 06.02.14
+ *
+ * defines a service list item
+ */
+public class ServicesListItem {
+	public String protocol;
+	public int attacks;
+
+	public boolean activated;
+
+    /**
+     * constructor of a service list item
+     *
+     * @param protocol protocol of this item, e.g. ftp
+     */
+	public ServicesListItem(String protocol){
+		this.protocol = protocol;
+		this.activated = false;
+	}
+}

+ 43 - 4
src/de/tudarmstadt/informatik/hostage/ui2/popup/AbstractPopup.java → 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;
@@ -19,8 +19,12 @@ import de.tudarmstadt.informatik.hostage.R;
  */
 public abstract class AbstractPopup {
 
-    static final int ORIENTATION_LANDSCAPE = 2;
+    //static final int ORIENTATION_LANDSCAPE = 2;
 
+    /**
+     * OnPopupItemClickListener
+     * The listener will be called if the user selects a table row
+     */
     public interface OnPopupItemClickListener {
         public void onItemClick(Object data);
     }
@@ -32,9 +36,23 @@ public abstract class AbstractPopup {
     private LayoutInflater lInf;
 	private View lastItemView;
 
+    /**
+     * Override to return the layout id.
+     * @return int layoutID
+     */
     abstract public int getLayoutId();
+
+    /**
+     * Override to make additional stuff with the rootview.
+     * @param View rootview
+     */
     abstract void configureView(View view);
 
+    /**
+     * Constructor
+     * @param Context context
+     * @param OnPopupItemClickListener listener
+     */
     public AbstractPopup(Context context, OnPopupItemClickListener listener) {
         super();
         this.context = (Activity) context;
@@ -46,14 +64,26 @@ public abstract class AbstractPopup {
 
     }
 
+    /**
+     * Override to return a linear layout to add a scrollview.
+     * @return LinearLayout
+     */
     public abstract LinearLayout getScrollableItemLayout();
 
+    /**
+     * Returns the root view
+     * @return View the rootview
+     */
     public View getRootView(){
         return this.rootView;
     }
 
+    /**
+     * Adds a table row item.
+     * @param AbstractPopupItem item
+     */
     public void addItem(final AbstractPopupItem item)	{
-        View view = item.getItemView();
+        View view = item.getRootView();
 
         if (this.rootView == null){
             this.rootView = (LinearLayout) this.lInf.inflate(this.getLayoutId(), null);
@@ -83,6 +113,11 @@ public abstract class AbstractPopup {
 
     }
 
+    /**
+     * Returns the rootview.
+     * If the root view is null, it initialises it with the layout id.
+     * @return View the root view
+     */
     public View getPopupView(){
         if (this.rootView == null){
             this.rootView = (LinearLayout) this.lInf.inflate(this.getLayoutId(), null);
@@ -90,6 +125,10 @@ public abstract class AbstractPopup {
         return this.rootView;
     }
 
+    /**
+     * Opens the Popup View on top of the given anchor.
+     * @param View anchorView
+     */
     public void showOnView(final View anchorView)	{
         if (this.rootView == null){
             this.rootView = (LinearLayout) this.lInf.inflate(this.getLayoutId(), null);
@@ -103,7 +142,7 @@ public abstract class AbstractPopup {
 
             Window window = this.context.getWindow();
             window.getDecorView().getWindowVisibleDisplayFrame(windowFrame);
-            int orientation = this.context.getResources().getConfiguration().orientation;
+            //int orientation = this.context.getResources().getConfiguration().orientation;
             int windowWidth = windowFrame.width();
             int windowHeight = windowFrame.height();
 

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

@@ -0,0 +1,129 @@
+package de.tudarmstadt.informatik.hostage.ui.popup;
+
+import android.content.Context;
+import android.view.LayoutInflater;
+import android.view.MotionEvent;
+import android.view.View;
+
+import java.util.HashMap;
+
+/**
+ * Created by Julien on 13.02.14.
+ */
+public abstract class AbstractPopupItem {
+    private int itemId;
+    private String title;
+
+    private View rootView;
+
+    private LayoutInflater lInf;
+
+    public HashMap<Object, Object> data;
+
+    /**
+     * Override to return the layout id.
+     * @return int layoutID
+     */
+    abstract public int getLayoutId();
+
+    /**
+     * Override to do additional stuff with the rootview.
+     *
+     * @param View rootview
+     */
+    abstract public void configureItemView(View view);
+
+
+    public void setValue(String key, Object value){
+        if (key != null && value != null){
+            this.data.put(key, value);
+            if (this.rootView != null) this.configureItemView(this.rootView);
+        }
+    }
+
+    /**
+     * Add other data to the item.
+     * @param HashMap<Object, Object> data
+     */
+    public void setMultipleData(HashMap<Object, Object> map){
+        if (map != null){
+            for(Object key : map.keySet()){
+                this.data.put(key, map.get(key));
+            }
+            if (this.rootView != null) this.configureItemView(this.rootView);
+        }
+    }
+
+    public void setTitle(String title){
+        this.title = title;
+        if (this.rootView != null) this.configureItemView(this.rootView);
+    }
+    public String getTitle(){
+        return this.title;
+    }
+
+    /**
+     * Set a specific item ID to identify it.
+     * @param int id
+     */
+    public void setItemId(int id){
+        this.itemId = id;
+        if (this.rootView != null) this.configureItemView(this.rootView);
+    }
+
+    /**
+     * Returns the item ID.
+     * @return int ID
+     */
+    public int getItemId() {
+        return this.itemId;
+    }
+
+    /**
+     * Constructor
+     * @param Context context
+     */
+    public AbstractPopupItem(Context context) {
+        super();
+        this.lInf = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+        this.data = new HashMap<Object, Object>();
+    }
+
+    /**
+     * Returns the rootview.
+     * This method calls everytime the ConfigureItemView methode.
+     * @return View rootview
+     */
+    public View getRootView(){
+        if (this.rootView == null){
+            this.rootView = this.lInf.inflate(this.getLayoutId(), null);
+        }
+        this.configureItemView(this.rootView);
+
+        return this.rootView;
+    }
+
+    /**
+     * The method is called if the user clicks the rootview.
+     * @param  MotionEvent event
+     * @return Object object
+     */
+    public Object onClickedResult(MotionEvent event){
+        return this;
+    }
+
+    /**
+     * Will be called if the user selected the view.
+     * @param MotionEvent event
+     */
+	public void onItemSelect(MotionEvent event){
+	}
+
+    /**
+     * Will be called if the user deselects the view.
+     * @param MotionEvent event
+     */
+	public void onItemDeselect(MotionEvent event){
+
+	}
+}

+ 3 - 3
src/de/tudarmstadt/informatik/hostage/ui2/popup/SimplePopupItem.java → 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;
@@ -41,12 +41,12 @@ public class SimplePopupItem extends AbstractPopupItem {
 
     public void setSelected(boolean selected){
         this.selected = selected;
-        if (this.getItemView() != null) this.configureItemView(this.getItemView());
+        if (this.getRootView() != null) this.configureItemView(this.getRootView());
     }
 
 	private View getContainer(){
 		if(container == null){
-			container = this.getItemView().findViewById(R.id.popup_item_container);
+			container = this.getRootView().findViewById(R.id.popup_item_container);
 		}
 
 		return container;

+ 1 - 1
src/de/tudarmstadt/informatik/hostage/ui2/popup/SimplePopupTable.java → 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;

+ 21 - 5
src/de/tudarmstadt/informatik/hostage/ui2/popup/SplitPopupItem.java → 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;
@@ -23,6 +23,11 @@ public class SplitPopupItem extends AbstractPopupItem {
 	private View left_container;
 	private View right_container;
 
+    /**
+     * Constructor
+     *
+     * @param Context context
+     */
     public SplitPopupItem(Context context){
         super(context);
 
@@ -64,22 +69,33 @@ public class SplitPopupItem extends AbstractPopupItem {
         return this;
     }
 
+    /**
+     * Returns true if the user touched the right side of the view.
+     * @return boolean isRightTouch
+     */
 	private boolean isRightTouch(MotionEvent event){
-		return event.getX() > this.getItemView().getX() + (this.getItemView().getWidth() / 2);
+		return event.getX() > this.getRootView().getX() + (this.getRootView().getWidth() / 2);
 	}
 
+    /**
+     * Returns the left view.
+     * @return View the left view
+     */
 	private View getLeftContainer(){
 		if(left_container == null){
-			left_container = this.getItemView().findViewById(R.id.popup_left_container);
+			left_container = this.getRootView().findViewById(R.id.popup_left_container);
 		}
 
 		return left_container;
 	}
 
-
+    /**
+     * Returns the right view.
+     * @return View the right view
+     */
 	private View getRightContainer(){
 		if(right_container == null){
-			right_container = this.getItemView().findViewById(R.id.popup_right_container);
+			right_container = this.getRootView().findViewById(R.id.popup_right_container);
 		}
 
 		return right_container;

+ 1 - 1
src/de/tudarmstadt/informatik/hostage/ui2/swipelist/SwipeListView.java → 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();
+        }
+    }
+}

+ 0 - 188
src/de/tudarmstadt/informatik/hostage/ui2/adapter/ProfileManagerListAdapter.java

@@ -1,188 +0,0 @@
-package de.tudarmstadt.informatik.hostage.ui2.adapter;
-
-import android.app.AlertDialog;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.content.Intent;
-import android.graphics.BitmapFactory;
-import android.view.ContextThemeWrapper;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.ArrayAdapter;
-import android.widget.ImageButton;
-import android.widget.ImageView;
-import android.widget.RelativeLayout;
-import android.widget.TextView;
-
-import java.util.LinkedList;
-import java.util.List;
-
-import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.dao.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;
-
-/**
- * @author Alexander Brakowski
- * @created 14.01.14 18:00
- */
-public class ProfileManagerListAdapter extends ArrayAdapter<Profile> {
-	private class ViewHolder {
-		public TextView labelView;
-		public TextView textView;
-		public ImageView imageSelected;
-		public ImageView itemIcon;
-		public ImageButton buttonEdit;
-		public ImageButton buttonDelete;
-		public View seperator;
-		public FlowLayout badgesContainer;
-	}
-
-    private final Context context;
-    private final List<Profile> values;
-	private SwipeListView list;
-
-    public ProfileManagerListAdapter(Context context, List<Profile> objects, SwipeListView list) {
-        super(context, R.layout.profile_manager_list_item, objects);
-        this.context = context;
-        this.values  = objects;
-	    this.list    = list;
-    }
-
-
-    @Override
-    public View getView(final int position, View convertView, ViewGroup parent) {
-	    LayoutInflater inflater = (LayoutInflater) context
-			    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
-
-        View rowView = convertView;
-	    ViewHolder holder = null;
-
-	    final Profile item = values.get(position);
-
-	    if(rowView == null){
-		    rowView = inflater.inflate(R.layout.profile_manager_list_item, parent, false);
-
-		    holder = new ViewHolder();
-		    holder.labelView = (TextView) rowView.findViewById(R.id.profile_manager_item_label);
-		    holder.textView = (TextView) rowView.findViewById(R.id.profile_manager_item_text);
-		    holder.imageSelected = (ImageView) rowView.findViewById(R.id.profile_manager_item_activated);
-		    holder.itemIcon = (ImageView) rowView.findViewById(R.id.profile_manager_item_image);
-		    holder.buttonEdit = (ImageButton) rowView.findViewById(R.id.profile_manager_item_button_edit);
-		    holder.buttonDelete = (ImageButton) rowView.findViewById(R.id.profile_manager_item_button_delete);
-			holder.seperator = rowView.findViewById(R.id.profile_manager_item_seperator);
-			holder.badgesContainer = (FlowLayout) rowView.findViewById(R.id.badges_container);
-
-		    rowView.setTag(holder);
-	    } else {
-		    holder = (ViewHolder) rowView.getTag();
-	    }
-
-	    ((SwipeListView)parent).recycle(rowView, position);
-
-	    holder.textView.setText(item.mText);
-	    holder.labelView.setText(item.mLabel);
-
-	    if(item.getIconBitmap() != null){
-	        //Bitmap bitmap = Bitmap.createScaledBitmap(item.getIconBitmap(), 32, 32, true);
-	        holder.itemIcon.setImageBitmap(item.getIconBitmap());
-	    } else {
-		    holder.itemIcon.setImageBitmap(BitmapFactory.decodeResource(MainActivity.context.getResources(), R.drawable.ic_launcher));
-	    }
-
-		holder.buttonEdit.setOnClickListener(new View.OnClickListener() {
-			@Override
-			public void onClick(View v) {
-				Intent intent = new Intent(context, ProfileEditActivity.class);
-				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
-				intent.putExtra("profile_id", item.mId);
-				//intent.putExtra("profile", item);
-				context.startActivity(intent);
-			}
-		});
-
-		holder.buttonDelete.setOnClickListener(new View.OnClickListener() {
-			@Override
-			public void onClick(View v) {
-				new AlertDialog.Builder(context)
-						.setTitle(R.string.delete_profile)
-						.setMessage(R.string.really_want_delete_profiel)
-						.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
-							@Override
-							public void onClick(DialogInterface dialog, int which) {
-
-							}
-						})
-						.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
-							public void onClick(DialogInterface dialog, int which) {
-								ProfileManager profileManager = ProfileManager.getInstance();
-
-								profileManager.deleteProfile(item);
-								profileManager.getProfileListAdapter().notifyDataSetChanged();
-								list.closeOpenedItems();
-							}
-						})
-						.setIcon(android.R.drawable.ic_dialog_alert)
-						.show();
-			}
-		});
-
-	    holder.badgesContainer.removeAllViews();
-	    boolean hasProtocols = false;
-
-	    List<String> profiles = new LinkedList<String>(item.getActiveProtocols());
-
-	    if(item.mGhostActive){
-		    profiles.add("GHOST");
-	    }
-
-	    for(String protocol: profiles){
-		    hasProtocols = true;
-			TextView textView = new TextView(new ContextThemeWrapper(context, R.style.ProfileManagerListBadge));
-		    textView.setText(protocol);
-		    holder.badgesContainer.addView(textView);
-	    }
-
-	    if(!hasProtocols){
-		    holder.badgesContainer.setVisibility(View.INVISIBLE);
-	    } else {
-		    holder.badgesContainer.setVisibility(View.VISIBLE);
-	    }
-
-		RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) holder.textView.getLayoutParams();
-
-        if(!item.mActivated){
-            lp.setMargins(0, 0, 0, 0);
-
-	        holder.textView.setLayoutParams(lp);
-
-	        holder.imageSelected.setVisibility(View.GONE);
-        } else {
-			/*float d = context.getResources().getDisplayMetrics().density;
-			int dm = (int)(20 * d);
-
-			lp.setMargins(0,0,dm,0);
-
-			holder.textView.setLayoutParams(lp);*/
-
-			holder.imageSelected.setVisibility(View.VISIBLE);
-		}
-
-
-		if(!item.isEditable()){
-			holder.buttonDelete.setVisibility(View.GONE);
-			holder.seperator.setVisibility(View.GONE);
-		} else {
-			holder.buttonDelete.setVisibility(View.VISIBLE);
-			holder.seperator.setVisibility(View.VISIBLE);
-		}
-
-        return rowView;
-    }
-
-
-}

+ 0 - 165
src/de/tudarmstadt/informatik/hostage/ui2/adapter/ServicesListAdapter.java

@@ -1,165 +0,0 @@
-package de.tudarmstadt.informatik.hostage.ui2.adapter;
-
-import java.util.List;
-
-import android.annotation.TargetApi;
-import android.app.AlertDialog;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.os.Build;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.ArrayAdapter;
-import android.widget.CompoundButton;
-import android.widget.Switch;
-import android.widget.TextView;
-import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
-import de.tudarmstadt.informatik.hostage.ui2.model.ServicesListItem;
-
-/**
- * Created by Daniel Lazar on 06.02.14.
- */
-public class ServicesListAdapter extends ArrayAdapter<ServicesListItem> {
-
-	private class ViewHolder {
-
-		public TextView protocolName;
-
-		public TextView recordedAttacks;
-
-		public Switch activated;
-
-		public View circle;
-	}
-
-	private Context mActivity;
-
-	private Switch mServicesSwitch;
-
-	private CompoundButton.OnCheckedChangeListener mListener;
-
-	private final Context context;
-
-	private final List<ServicesListItem> values;
-
-	int sdk = Build.VERSION.SDK_INT;
-
-	public ServicesListAdapter(Context context, List<ServicesListItem> objects) {
-		super(context, R.layout.services_list_item, objects);
-
-		this.context = context;
-		this.values = objects;
-	}
-
-	public void setActivity(Context activity, Switch servicesSwitch, CompoundButton.OnCheckedChangeListener mainListener) {
-		mActivity = activity;
-		mServicesSwitch = servicesSwitch;
-		mListener = mainListener;
-	}
-
-	@Override
-	public View getView(final int position, View convertView, ViewGroup parent) {
-		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
-		View rowView = convertView;
-
-		ViewHolder holder;
-
-		final ServicesListItem item = values.get(position);
-
-		if (rowView == null) {
-			rowView = inflater.inflate(R.layout.services_list_item, parent, false);
-
-			holder = new ViewHolder();
-			assert rowView != null;
-			holder.protocolName = (TextView) rowView.findViewById(R.id.services_item_name);
-			holder.recordedAttacks = (TextView) rowView.findViewById(R.id.services_item_rec_attacks);
-			holder.activated = (Switch) rowView.findViewById(R.id.services_item_switch);
-			holder.circle = rowView.findViewById(R.id.services_circle);
-			rowView.setTag(holder);
-		} else {
-			holder = (ViewHolder) rowView.getTag();
-		}
-
-		holder.protocolName.setText(item.protocol);
-		holder.activated.setTag(item);
-
-		this.updateStatus(item, holder);
-
-		holder.activated.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
-			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
-				ServicesListItem item = (ServicesListItem) buttonView.getTag();
-
-				if (!HelperUtils.isWifiConnected(mActivity)) {
-					new AlertDialog.Builder(mActivity).setTitle(R.string.information).setMessage(R.string.wifi_not_connected_msg)
-							.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
-								public void onClick(DialogInterface dialog, int which) {
-								}
-							}).setIcon(android.R.drawable.ic_dialog_info).show();
-
-					buttonView.setChecked(false);
-				} else {
-					// check if switch is set to ON and start the concrete
-					// listener for the protocol
-					if (isChecked) {
-						if (!MainActivity.getInstance().getHostageService().isRunning(item.protocol)) {
-							MainActivity.getInstance().getHostageService().startListener(item.protocol);
-
-							// set the main switch to null, so that he won't
-							// react and starts all protocols
-							mServicesSwitch.setOnCheckedChangeListener(null);
-							mServicesSwitch.setChecked(true);
-							mServicesSwitch.setOnCheckedChangeListener(mListener);
-							buttonView.setChecked(true);
-						} else if (MainActivity.getInstance().getHostageService().isRunning(item.protocol)) {
-							buttonView.setChecked(true);
-						}
-					} else {
-						if (MainActivity.getInstance().getHostageService().isRunning(item.protocol)) {
-							MainActivity.getInstance().getHostageService().stopListener(item.protocol);
-						}
-						buttonView.setChecked(false);
-					}
-				}
-			}
-		});
-		return rowView;
-	}
-
-	private void updateStatus(ServicesListItem item, ViewHolder holder) {
-		if (MainActivity.getInstance().getHostageService().isRunning(item.protocol)) {
-			holder.activated.setChecked(true);
-			if (!(MainActivity.getInstance().getHostageService().getNumberOfActiveConnections(item.protocol) > 0)) {
-				if (item.attacks > 0) {
-					setBackground(holder, R.drawable.services_circle_yellow);
-				} else {
-					setBackground(holder, R.drawable.services_circle_green);
-				}
-
-			} else {
-				if (MainActivity.getInstance().getHostageService().getNumberOfActiveConnections(item.protocol) > 0) {
-					setBackground(holder, R.drawable.services_circle_red);
-				}
-			}
-		} else if (item.attacks > 0) {
-			holder.activated.setChecked(false);
-			setBackground(holder, R.drawable.services_circle_yellow);
-		} else {
-			holder.activated.setChecked(false);
-			setBackground(holder, R.drawable.services_circle);
-		}
-		holder.recordedAttacks.setText(String.format(MainActivity.getContext().getResources().getString(R.string.recorded_attacks) + "  %d",
-				Integer.valueOf(item.attacks)));
-	}
-
-	@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
-	private void setBackground(ViewHolder holder, int drawable) {
-		if (sdk < Build.VERSION_CODES.JELLY_BEAN) {
-			holder.circle.setBackgroundDrawable(MainActivity.getInstance().getResources().getDrawable(drawable));
-		} else {
-			holder.circle.setBackground(MainActivity.getInstance().getResources().getDrawable(drawable));
-		}
-	}
-}

+ 0 - 229
src/de/tudarmstadt/informatik/hostage/ui2/fragment/ServicesFragment.java

@@ -1,229 +0,0 @@
-package de.tudarmstadt.informatik.hostage.ui2.fragment;
-
-import java.util.ArrayList;
-
-import android.app.AlertDialog;
-import android.app.Fragment;
-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.os.Bundle;
-import android.support.v4.content.LocalBroadcastManager;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.CompoundButton;
-import android.widget.ListView;
-import android.widget.Switch;
-import android.widget.TextView;
-import de.tudarmstadt.informatik.hostage.Handler;
-import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
-import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
-import de.tudarmstadt.informatik.hostage.ui2.adapter.ServicesListAdapter;
-import de.tudarmstadt.informatik.hostage.ui2.model.ServicesListItem;
-
-/**
- * Created by Daniel Lazar on 05.02.14.
- */
-public class ServicesFragment extends Fragment {
-
-	private Switch mServicesSwitchService;
-	private TextView mServicesTextName;
-
-	private View rootView;
-
-	private CompoundButton.OnCheckedChangeListener switchChangeListener = null;
-
-	private BroadcastReceiver mReceiver;
-
-	private ServicesListAdapter adapter;
-
-	private ArrayList<ServicesListItem> protocolList;
-
-	private HostageDBOpenHelper dbh = new HostageDBOpenHelper(MainActivity.getContext());
-
-	private String[] protocols;
-
-	private SharedPreferences mConnectionInfo;
-
-	private boolean mReceiverRegistered = false;
-
-	private void assignViews() {
-		mServicesSwitchService = (Switch) rootView.findViewById(R.id.service_switch_connection);
-		mServicesTextName = (TextView) rootView.findViewById(R.id.services_text_name);
-
-		rootView.findViewById(R.id.services_button_connection_info).setOnClickListener(new View.OnClickListener() {
-			@Override
-			public void onClick(View v) {
-				ConnectionInfoDialogFragment connectionInfoDialogFragment = new ConnectionInfoDialogFragment();
-				connectionInfoDialogFragment.show(getFragmentManager().beginTransaction(), connectionInfoDialogFragment.getTag());
-			}
-		});
-
-	}
-
-	public void updateUI() {
-		if (!HelperUtils.isWifiConnected(getActivity())) {
-			mServicesSwitchService.setOnCheckedChangeListener(null);
-			setStateNotConnected();
-			setStateNotActive();
-			mServicesSwitchService.setOnCheckedChangeListener(switchChangeListener);
-		} else {
-			if (MainActivity.getInstance().getHostageService().hasRunningListeners()) {
-				setStateActive();
-			}
-
-			mServicesTextName.setText(HelperUtils.getSSID(getActivity()));
-		}
-
-	}
-
-	public ServicesFragment() {
-	}
-
-	private void registerBroadcastReceiver() {
-		if (!mReceiverRegistered) {
-			mReceiver = new BroadcastReceiver() {
-				@Override
-				public void onReceive(Context context, Intent intent) {
-					String sender = intent.getStringExtra("SENDER");
-					String[] values = intent.getStringArrayExtra("VALUES");
-
-					if (sender.equals(Handler.class.getName()) && values[0].equals(getString(R.string.broadcast_started))) {
-						for (ServicesListItem item : protocolList) {
-							if (item.protocol.equals(values[1])) {
-								item.attacks = dbh.numBssidSeen(item.protocol, mConnectionInfo.getString(getString(R.string.connection_info_bssid), null));
-							}
-						}
-					}
-
-					if (!MainActivity.getInstance().getHostageService().hasRunningListeners()) {
-						setStateNotActive();
-					} else {
-						setStateActive();
-					}
-
-					adapter.notifyDataSetChanged();
-				}
-			};
-
-			LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mReceiver, new IntentFilter(getString(R.string.broadcast)));
-			this.mReceiverRegistered = true;
-		}
-	}
-
-	@Override
-	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
-
-		super.onCreateView(inflater, container, savedInstanceState);
-
-		rootView = inflater.inflate(R.layout.fragment_services, container, false);
-		assignViews();
-
-		protocols = getResources().getStringArray(R.array.protocols);
-		mConnectionInfo = getActivity().getSharedPreferences(getString(R.string.connection_info), Context.MODE_PRIVATE);
-
-		updateUI();
-
-		ListView list = (ListView) rootView.findViewById(R.id.services_list_view);
-
-		protocolList = new ArrayList<ServicesListItem>();
-		int i = 0;
-		for (String protocol : protocols) {
-			protocolList.add(new ServicesListItem(protocol));
-			protocolList.get(i).attacks = dbh.numBssidSeen(protocolList.get(i).protocol,
-					mConnectionInfo.getString(getString(R.string.connection_info_bssid), null));
-			i++;
-		}
-
-		mServicesSwitchService = (Switch) rootView.findViewById(R.id.service_switch_connection);
-
-		if (switchChangeListener == null) {
-			switchChangeListener = new CompoundButton.OnCheckedChangeListener() {
-				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
-					if (!HelperUtils.isWifiConnected(getActivity())) {
-						new AlertDialog.Builder(getActivity()).setTitle(R.string.information).setMessage(R.string.wifi_not_connected_msg)
-								.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
-									public void onClick(DialogInterface dialog, int which) {
-
-									}
-								}).setIcon(android.R.drawable.ic_dialog_info).show();
-
-						setStateNotActive();
-						setStateNotConnected();
-					} else {
-						if (MainActivity.getInstance().isServiceBound()) {
-							if (isChecked) {
-								for (String protocol : protocols) {
-									if (!MainActivity.getInstance().getHostageService().isRunning(protocol)) {
-										MainActivity.getInstance().getHostageService().startListener(protocol);
-									}
-								}
-								setStateActive();
-							} else {
-								MainActivity.getInstance().getHostageService().stopListeners();
-								MainActivity.getInstance().stopAndUnbind();
-								setStateNotActive();
-							}
-						}
-					}
-				}
-
-			};
-		}
-		mServicesSwitchService.setOnCheckedChangeListener(switchChangeListener);
-
-		adapter = new ServicesListAdapter(getActivity().getBaseContext(), protocolList);
-		adapter.setActivity(this.getActivity(), this.mServicesSwitchService, this.switchChangeListener);
-		list.setAdapter(adapter);
-
-		registerBroadcastReceiver();
-
-		return rootView;
-
-	};
-
-	@Override
-	public void onStart() {
-		super.onStart();
-		registerBroadcastReceiver();
-		mServicesSwitchService.setOnCheckedChangeListener(switchChangeListener);
-	}
-
-	private void unregisterBroadcastReceiver() {
-		if (mReceiverRegistered) {
-			LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
-			this.mReceiverRegistered = false;
-		}
-	}
-
-	private void setStateActive() {
-		mServicesSwitchService.setChecked(true);
-	}
-
-	private void setStateNotConnected() {
-		mServicesTextName.setText(R.string.not_connected);
-	}
-
-	private void setStateNotActive() {
-		mServicesSwitchService.setChecked(false);
-	}
-
-	@Override
-	public void onStop() {
-		super.onStop();
-		mServicesSwitchService.setOnCheckedChangeListener(null);
-	}
-
-	@Override
-	public void onDestroy() {
-		super.onDestroy();
-		unregisterBroadcastReceiver();
-	}
-
-}

+ 0 - 1479
src/de/tudarmstadt/informatik/hostage/ui2/fragment/StatisticsFragment.java

@@ -1,1479 +0,0 @@
-package de.tudarmstadt.informatik.hostage.ui2.fragment;
-
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.Date;
-import java.util.HashMap;
-
-import android.annotation.SuppressLint;
-import android.app.Fragment;
-import android.app.FragmentManager;
-import android.content.Context;
-import android.content.Intent;
-import android.content.res.Configuration;
-import android.graphics.Color;
-import android.os.Bundle;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.AdapterView;
-import android.widget.ImageButton;
-import android.widget.LinearLayout;
-import android.widget.ListView;
-import android.widget.TextView;
-
-import com.echo.holographlibrary.Bar;
-import com.echo.holographlibrary.BarGraph;
-import com.echo.holographlibrary.Line;
-import com.echo.holographlibrary.LineGraph;
-import com.echo.holographlibrary.LinePoint;
-import com.echo.holographlibrary.PieGraph;
-import com.echo.holographlibrary.PieSlice;
-
-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.ui.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;
-
-/**
- * Created by Julien on 16.02.14.
- */
-public class StatisticsFragment extends Fragment implements ChecklistDialog.ChecklistDialogListener, DateTimeDialogFragment.DateTimeDialogFragmentListener {
-
-	static final String FILTER_MENU_TITLE_BSSID = "BSSID";
-	static final String FILTER_MENU_TITLE_ESSID = "ESSID";
-	static final String FILTER_MENU_TITLE_PROTOCOLS = MainActivity.getContext().getString(R.string.stats_protocols);
-	static final String FILTER_MENU_TITLE_PROTOCOL = 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_REMOVE = MainActivity.getContext().getString(R.string.rec_reset_filter);
-	static final String FILTER_MENU_POPUP_TITLE = MainActivity.getContext().getString(R.string.rec_filter_by);
-
-	static final String MENU_TITLE_PROTOCOLS = MainActivity.getContext().getString(R.string.stats_protocols);
-	static final String MENU_TITLE_NETWORK = MainActivity.getContext().getString(R.string.stats_networks);
-	static final String MENU_TITLE_ATTACKS = MainActivity.getContext().getString(R.string.stats_attacks);
-
-	static final String MENU_POPUP_TITLE = MainActivity.getContext().getString(R.string.stats_visualize);
-
-	static final String CHART_TYPE_TITLE_BAR = MainActivity.getContext().getString(R.string.stats_bar_plot);
-	static final String CHART_TYPE_TITLE_PIE = MainActivity.getContext().getString(R.string.stats_pie_plot);
-	static final String CHART_TYPE_TITLE_LINE = MainActivity.getContext().getString(R.string.stats_line_plot);
-
-	static final String DIALOG_PROTOCOLS_TITLE = MainActivity.getContext().getString(R.string.stats_select_protocol_data);
-	static final String DIALOG_NETWORK_TITLE = MainActivity.getContext().getString(R.string.stats_select_network_data);
-	static final String DIALOG_ATTACK_TITLE = MainActivity.getContext().getString(R.string.stats_select_attack_data);
-
-	static final String COMPARE_TITLE_AttacksPerProtocol = MainActivity.getContext().getString(R.string.stats_attacks_protocol);
-	static final String COMPARE_TITLE_UsesPerProtocol = MainActivity.getContext().getString(R.string.stats_uses_protocol);
-	static final String COMPARE_TITLE_AttacksPerDate = MainActivity.getContext().getString(R.string.stats_attacks_date);
-	static final String COMPARE_TITLE_AttacksPerTime = MainActivity.getContext().getString(R.string.stats_attacks_time);
-	static final String COMPARE_TITLE_AttacksPerBSSID = MainActivity.getContext().getString(R.string.stats_attacks_bssid);
-	static final String COMPARE_TITLE_AttacksPerESSID = MainActivity.getContext().getString(R.string.stats_attacks_essid);
-	static final String FILTER_MENU_PROTOCOL_SINGLE_CHOICE_TITLE = MainActivity.getContext().getString(R.string.stats_select_protocol);
-
-	static final String TABLE_HEADER_VALUE_TITLE_ATTACKS_COUNT = MainActivity.getContext().getString(R.string.stats_attacks_count);
-	static final String TABLE_HEADER_VALUE_TITLE_ATTACKS_PERCENTAGE = MainActivity.getContext().getString(R.string.stats_per_cent_all);
-
-	static final String OTHER_CHART_TITLE = MainActivity.getContext().getString(R.string.stats_other);
-
-	// MINIMAL 2
-	static int MAX_NUMBER_OF_CHART_OBJECTS = 6;
-
-	private boolean wasBelowTimePicker;
-
-	private LogFilter filter;
-	private boolean showFilterButton;
-
-	private PieGraph pieGraph;
-	private LineGraph lineGraph;
-	private BarGraph barGraph;
-
-	private View rootView;
-	private View currentPlotView;
-
-	private ArrayList<Integer> colorList;
-	private ArrayList<PlotComparisonItem> currentData;
-
-	private HostageDBOpenHelper dbh;
-
-	private ListView legendListView;
-
-	private String selectedCompareData = COMPARE_TITLE_AttacksPerProtocol;
-
-	public enum ChartType {
-		PIE_CHART(0), BAR_CHART(1), LINE_CHART(2);
-
-		private int value;
-
-		private ChartType(int value) {
-			this.value = value;
-		}
-
-		static public ChartType create(int value) {
-			if (value < 0 || value >= ChartType.values().length)
-				return ChartType.PIE_CHART;
-			return ChartType.values()[value];
-		}
-
-		public String toString() {
-			if (this.equals(ChartType.create(0))) {
-				return CHART_TYPE_TITLE_PIE;
-			}
-			if (this.equals(ChartType.create(1))) {
-				return CHART_TYPE_TITLE_BAR;
-			}
-			return CHART_TYPE_TITLE_LINE;
-		}
-
-	}
-
-	private ImageButton getFilterButton() {
-		return (ImageButton) this.rootView.findViewById(R.id.FilterButton);
-	}
-
-	public int getLayoutID() {
-		return R.layout.fragment_statistics;
-	}
-
-	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
-
-		super.onCreateView(inflater, container, savedInstanceState);
-
-		getActivity().setTitle(getResources().getString(R.string.drawer_statistics));
-
-		dbh = new HostageDBOpenHelper(this.getBaseContext());
-
-		// Get the message from the intent
-
-		if (this.filter == null) {
-			Intent intent = this.getActivity().getIntent();
-			LogFilter filter = intent.getParcelableExtra(LogFilter.LOG_FILTER_INTENT_KEY);
-			if (filter == null) {
-				this.clearFilter();
-			} else {
-				this.filter = filter;
-			}
-		}
-
-		this.rootView = inflater.inflate(this.getLayoutID(), container, false);
-
-		this.configureRootView(this.rootView);
-
-		return this.rootView;
-	}
-
-	@Override
-	public void onCreate(Bundle savedInstanceState) {
-		super.onCreate(savedInstanceState);
-		setHasOptionsMenu(true);
-		setRetainInstance(true);
-	}
-
-	@Override
-	public void onConfigurationChanged(Configuration newConfig) {
-		super.onConfigurationChanged(newConfig);
-		LayoutInflater inflater = LayoutInflater.from(getActivity());
-
-		ViewGroup container = (ViewGroup) this.getView();
-		container.removeAllViewsInLayout();
-		this.rootView = inflater.inflate(this.getLayoutID(), container, false);
-		container.addView(this.rootView);
-
-		this.configureRootView(this.rootView);
-	}
-
-	private Context getBaseContext() {
-		return this.getActivity().getBaseContext();
-	}
-
-	private Context getApplicationContext() {
-		return this.getActivity().getApplicationContext();
-	}
-
-	public void configureRootView(View rootView) {
-		LinearLayout plotLayout = (LinearLayout) rootView.findViewById(R.id.plot_layout);
-		plotLayout.setWillNotDraw(false);
-		plotLayout.removeAllViews();
-
-		plotLayout.setWillNotDraw(false);
-
-		this.legendListView = (ListView) rootView.findViewById(R.id.legend_list_view);
-		this.legendListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
-			@Override
-			public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
-				StatisticsFragment.this.userTappedOnLegendItem(i);
-			}
-		});
-		rootView.setWillNotDraw(false);
-
-		this.actualiseCurrentPlot();
-
-		ImageButton visualButton = (ImageButton) rootView.findViewById(R.id.plot_data_button);
-		visualButton.setOnClickListener(new View.OnClickListener() {
-			public void onClick(View v) {
-				StatisticsFragment.this.openBarSelectionMenuOnView(v);
-			}
-		});
-
-		ImageButton filterButton = this.getFilterButton();
-		filterButton.setOnClickListener(new View.OnClickListener() {
-			public void onClick(View v) {
-				StatisticsFragment.this.openFilterMenuOnView(v);
-			}
-		});
-
-		if (this.currentPlotView instanceof BarGraph) {
-			this.setTitle("" + this.getCurrentSelectedProtocol() + ": " + this.selectedCompareData);
-		} else {
-			this.setTitle(this.selectedCompareData);
-		}
-	}
-
-	public void setTitle(String title) {
-		TextView titleView = (TextView) this.rootView.findViewById(R.id.title_text_view);
-		if (title != null && titleView != null) {
-			titleView.setText(title);
-			titleView.invalidate();
-		}
-	}
-
-	public String getTitle() {
-		TextView titleView = (TextView) this.rootView.findViewById(R.id.title_text_view);
-		if (titleView != null) {
-			return "" + titleView.getText();
-		}
-		return "";
-	}
-
-	public void onStart() {
-		super.onStart();
-		this.actualiseCurrentPlot();
-		this.currentPlotView.invalidate();
-
-		if (this.currentPlotView instanceof BarGraph) {
-			this.setTitle("" + this.getCurrentSelectedProtocol() + ": " + this.selectedCompareData);
-		} else {
-			this.setTitle(this.selectedCompareData);
-		}
-	}
-
-	public void setChartType(ChartType type) {
-		boolean shouldChange = true;
-		this.clearFilter();
-		if (this.currentPlotView != null) {
-			if (type == ChartType.PIE_CHART) {
-				shouldChange = !(this.currentPlotView instanceof PieGraph);
-				// SET FILTER BUTTON HIDDEN
-				ImageButton filterButton = this.getFilterButton();
-				if (filterButton != null)
-					filterButton.setVisibility(View.GONE);
-			} else {
-				if (this.pieGraph != null)
-					this.pieGraph.setVisibility(View.GONE);
-				// SHOW FILTER BUTTON
-				ImageButton filterButton = this.getFilterButton();
-				if (filterButton != null)
-					filterButton.setVisibility(View.VISIBLE);
-			}
-			if (type == ChartType.LINE_CHART) {
-				shouldChange = !(this.currentPlotView instanceof LineGraph);
-			} else {
-				if (this.lineGraph != null)
-					this.lineGraph.setVisibility(View.GONE);
-			}
-			if (type == ChartType.BAR_CHART) {
-				shouldChange = !(this.currentPlotView instanceof BarGraph);
-
-			} else {
-				if (this.barGraph != null)
-					this.barGraph.setVisibility(View.GONE);
-
-			}
-		}
-		if (shouldChange) {
-			this.currentPlotView = this.getPlotViewForType(type);
-			this.currentPlotView.setVisibility(View.VISIBLE);
-
-		}
-		this.actualiseCurrentPlot();
-
-	}
-
-	public View getPlotViewForType(ChartType type) {
-		switch (type) {
-		case PIE_CHART:
-			return this.getPieGraphView();
-		case LINE_CHART:
-			return this.getLineGraphView();
-		default:
-			return this.getBarGraphView();
-		}
-	}
-
-	public void actualiseLegendList() {
-		StatisticListAdapter adapter = new StatisticListAdapter(this.getApplicationContext(), this.currentData);
-		if (this.currentPlotView instanceof LineGraph) {
-			adapter.setValueFormatter(new StatisticListAdapter.ValueFormatter() {
-				@Override
-				public String convertValueForItemToString(PlotComparisonItem item) {
-					return String.format("%.02f", item.getValue2()) + " %" + " " + "(" + (item.getValue1().intValue()) + ")";
-				}
-			});
-		} else {
-
-			adapter.setValueFormatter(new StatisticListAdapter.ValueFormatter() {
-				@Override
-				public String convertValueForItemToString(PlotComparisonItem item) {
-					int v = (int) item.getValue2().intValue();
-					return "" + v;
-				}
-			});
-
-		}
-		this.legendListView.setAdapter(adapter);
-
-		TextView tableHeaderTitleView = (TextView) this.rootView.findViewById(R.id.table_header_title_textview);
-		TextView tableHeaderValueView = (TextView) this.rootView.findViewById(R.id.table_header_value_textview);
-		if (this.currentPlotView instanceof LineGraph) {
-			tableHeaderTitleView.setText(FILTER_MENU_TITLE_ESSID);
-			tableHeaderValueView.setText(TABLE_HEADER_VALUE_TITLE_ATTACKS_PERCENTAGE);
-		}
-		if (this.currentPlotView instanceof PieGraph) {
-			tableHeaderTitleView.setText(FILTER_MENU_TITLE_PROTOCOL);
-			tableHeaderValueView.setText(TABLE_HEADER_VALUE_TITLE_ATTACKS_COUNT);
-		}
-		if (this.currentPlotView instanceof BarGraph) {
-			tableHeaderValueView.setText(TABLE_HEADER_VALUE_TITLE_ATTACKS_COUNT);
-			if (this.selectedCompareData.equals(COMPARE_TITLE_AttacksPerBSSID)) {
-				tableHeaderTitleView.setText(FILTER_MENU_TITLE_BSSID);
-			} else {
-				tableHeaderTitleView.setText(FILTER_MENU_TITLE_ESSID);
-			}
-		}
-	}
-
-	/*
-	 * MENU
-	 */
-	private void openBarSelectionMenuOnView(View anchorView) {
-		SimplePopupTable visualiseMenu = new SimplePopupTable(this.getActivity(), new AbstractPopup.OnPopupItemClickListener() {
-			public void onItemClick(Object ob) {
-				if (ob instanceof AbstractPopupItem) {
-					AbstractPopupItem item = (AbstractPopupItem) ob;
-					StatisticsFragment.this.userSelectMenuItem(item);
-				}
-			}
-		});
-		visualiseMenu.setTitle(MENU_POPUP_TITLE);
-		int id = 0;
-		for (String title : StatisticsFragment.this.getMenuTitles()) {
-			SimplePopupItem item = new SimplePopupItem(this.getActivity());
-			item.setTitle(title);
-			item.setItemId(id);
-			item.setSelected(false);
-			visualiseMenu.addItem(item);
-			id++;
-		}
-		visualiseMenu.showOnView(anchorView);
-	}
-
-	private void userSelectMenuItem(AbstractPopupItem item) {
-		// OPEN A DIALOG TO SPECIFY THE VISUALISE DATA
-		if (item.getTitle().equals(MENU_TITLE_PROTOCOLS)) {
-			ChartType chartType = ChartType.PIE_CHART;
-			this.selectedCompareData = COMPARE_TITLE_AttacksPerProtocol;
-			this.setChartType(chartType);
-			this.setTitle(COMPARE_TITLE_AttacksPerProtocol);
-		}
-		if (item.getTitle().equals(MENU_TITLE_NETWORK)) {
-			this.openNetworkDataDialog();
-		}
-		if (item.getTitle().equals(MENU_TITLE_ATTACKS)) {
-			this.openAttackDataDialog();
-		}
-	}
-
-	private ArrayList<String> getMenuTitles() {
-		ArrayList<String> titles = new ArrayList<String>();
-		titles.add(MENU_TITLE_PROTOCOLS);
-		titles.add(MENU_TITLE_NETWORK);
-		titles.add(MENU_TITLE_ATTACKS);
-		return titles;
-	}
-
-	/*
-	 * PLOT DATA DIALOGS
-	 */
-	private void openProtocolDataDialog() {
-		ArrayList<String> titles = this.getDialogProtocolDataTitle();
-		ChecklistDialog newFragment = new ChecklistDialog(DIALOG_PROTOCOLS_TITLE, titles, this.selectedData(titles), false, this);
-		newFragment.show(this.getActivity().getFragmentManager(), DIALOG_PROTOCOLS_TITLE);
-	}
-
-	private void openNetworkDataDialog() {
-		ArrayList<String> titles = this.getDialogNetworkDataTitle();
-		ChecklistDialog newFragment = new ChecklistDialog(DIALOG_NETWORK_TITLE, titles, this.selectedData(titles), false, this);
-		newFragment.show(this.getActivity().getFragmentManager(), DIALOG_NETWORK_TITLE);
-	}
-
-	private void openAttackDataDialog() {
-		ArrayList<String> titles = this.getDialogAttackDataTitle();
-		ChecklistDialog newFragment = new ChecklistDialog(DIALOG_ATTACK_TITLE, titles, this.selectedData(titles), false, this);
-		newFragment.show(this.getActivity().getFragmentManager(), DIALOG_ATTACK_TITLE);
-	}
-
-	/*
-	 * 
-	 * DIALOG ACTION METHODS
-	 */
-	public void onDialogPositiveClick(ChecklistDialog dialog) {
-		String title = dialog.getTitle();
-		ArrayList<String> titles = dialog.getSelectedItemTitles();
-
-		if (title.equals(FILTER_MENU_TITLE_PROTOCOLS)) {
-			// titles = titles.size() == 0 ? this.protocolTitles() : titles;
-			this.filter.setProtocols(titles);
-			this.actualiseCurrentPlot();
-			return;
-		}
-		if (title.equals(FILTER_MENU_PROTOCOL_SINGLE_CHOICE_TITLE)) {
-			if (titles.size() == 0) {
-				titles = new ArrayList<String>();
-				titles.add(this.protocolTitles().get(0));
-			}
-			this.filter.setProtocols(titles);
-
-			this.actualiseCurrentPlot();
-			String fragTitle = "" + this.getCurrentSelectedProtocol() + ": " + this.selectedCompareData;
-			this.setTitle(fragTitle);
-			return;
-		}
-		if (title.equals(FILTER_MENU_TITLE_ESSID)) {
-			this.filter.setESSIDs(titles);
-			this.actualiseCurrentPlot();
-			return;
-		}
-		if (title.equals(FILTER_MENU_TITLE_BSSID)) {
-			this.filter.setBSSIDs(titles);
-			this.actualiseCurrentPlot();
-			return;
-		}
-
-		if (titles.size() != 0) {
-			String data = titles.get(0);
-			this.setTitle(data);
-			if (title.equals(DIALOG_PROTOCOLS_TITLE)) {
-				ChartType chartType = ChartType.PIE_CHART;
-				this.selectedCompareData = data;
-				this.setChartType(chartType);
-			}
-			if (title.equals(DIALOG_ATTACK_TITLE)) {
-				ChartType chartType = ChartType.LINE_CHART;
-				this.selectedCompareData = data;
-				this.setChartType(chartType);
-			}
-			if (title.equals(DIALOG_NETWORK_TITLE)) {
-				ChartType chartType = ChartType.BAR_CHART;
-				this.selectedCompareData = data;
-				this.setChartType(chartType);
-
-				String fragTitle = "" + this.getCurrentSelectedProtocol() + ": " + this.selectedCompareData;
-				this.setTitle(fragTitle);
-			}
-		}
-
-	}
-
-	public void onDialogNegativeClick(ChecklistDialog dialog) {
-
-	}
-
-	/*
-	 * 
-	 * DIALOG DATA
-	 */
-	private ArrayList<String> getDialogProtocolDataTitle() {
-		ArrayList<String> data = new ArrayList<String>();
-		data.add(COMPARE_TITLE_AttacksPerProtocol);
-		data.add(COMPARE_TITLE_UsesPerProtocol);
-		return data;
-	}
-
-	private ArrayList<String> getDialogAttackDataTitle() {
-		ArrayList<String> data = new ArrayList<String>();
-		data.add(COMPARE_TITLE_AttacksPerDate);
-		data.add(COMPARE_TITLE_AttacksPerTime);
-		return data;
-	}
-
-	private ArrayList<String> getDialogNetworkDataTitle() {
-		ArrayList<String> data = new ArrayList<String>();
-		data.add(COMPARE_TITLE_AttacksPerESSID);
-		data.add(COMPARE_TITLE_AttacksPerBSSID);
-		return data;
-	}
-
-	private boolean[] selectedData(ArrayList<String> data) {
-		boolean[] selected = new boolean[data.size()];
-		// SET DEFAULT
-		selected[0] = true;
-		return selected;
-	}
-
-	/*
-	 * 
-	 * FILTER BUTTON
-	 */
-	private void openFilterMenuOnView(View anchor) {
-		SimplePopupTable filterMenu = new SimplePopupTable(this.getActivity(), new AbstractPopup.OnPopupItemClickListener() {
-			public void onItemClick(Object ob) {
-				if (ob instanceof AbstractPopupItem) {
-					AbstractPopupItem item = (AbstractPopupItem) ob;
-					StatisticsFragment.this.onFilterMenuItemSelected(item);
-				}
-			}
-		});
-
-		filterMenu.setTitle(FILTER_MENU_POPUP_TITLE);
-		for (String title : StatisticsFragment.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(anchor);
-	}
-
-	private void onFilterMenuItemSelected(AbstractPopupItem item) {
-		if (item instanceof SplitPopupItem) {
-			SplitPopupItem sItem = (SplitPopupItem) item;
-			this.wasBelowTimePicker = sItem.wasRightTouch;
-			if (this.wasBelowTimePicker) {
-				this.openTimestampToFilterDialog();
-			} else {
-				this.openTimestampFromFilterDialog();
-			}
-			return;
-		}
-		String title = item.getTitle();
-		if (title.equals(FILTER_MENU_TITLE_ESSID)) {
-			this.openESSIDFilterDialog();
-		}
-		if (title.equals(FILTER_MENU_TITLE_BSSID)) {
-			this.openBSSIDFilterDialog();
-		}
-		if (title.equals(FILTER_MENU_TITLE_PROTOCOL)) {
-			this.openFilterDialogSelectProtocol();
-		}
-		if (title.equals(FILTER_MENU_TITLE_PROTOCOLS)) {
-			this.openProtocolsFilterDialog();
-		}
-		if (title.equals(FILTER_MENU_TITLE_REMOVE)) {
-			this.clearFilter();
-			this.actualiseCurrentPlot();
-		}
-	}
-
-	private ArrayList<String> filterMenuTitles() {
-		ArrayList<String> titles = new ArrayList<String>();
-		if (this.currentPlotView instanceof LineGraph) {
-			titles.add(FILTER_MENU_TITLE_ESSID);
-			titles.add(FILTER_MENU_TITLE_PROTOCOLS);
-			titles.add(FILTER_MENU_TITLE_TIMESTAMP_ABOVE);
-			if (this.filter.hasESSIDs() || this.filter.hasATimestamp()
-					|| (this.filter.getProtocols() != null && this.filter.hasProtocols() && this.filter.getProtocols().size() != this.protocolTitles().size())) {
-				titles.add(FILTER_MENU_TITLE_REMOVE);
-			}
-		} else {
-			titles.add(FILTER_MENU_TITLE_PROTOCOL);
-			String protocol = this.getCurrentSelectedProtocol();
-			if (protocol.length() > 0) {
-				if (this.selectedCompareData.equals(COMPARE_TITLE_AttacksPerBSSID)) {
-					titles.add(FILTER_MENU_TITLE_BSSID);
-				} else {
-					// DEFAULT
-					titles.add(FILTER_MENU_TITLE_ESSID);
-				}
-			}
-			titles.add(FILTER_MENU_TITLE_TIMESTAMP_ABOVE);
-			if (this.filter.hasATimestamp() || this.filter.hasESSIDs() || this.filter.hasBSSIDs()
-					|| (this.currentPlotView instanceof LineGraph && this.filter.hasProtocols())) {
-				titles.add(FILTER_MENU_TITLE_REMOVE);
-			}
-		}
-		return titles;
-	}
-
-	private void openProtocolsFilterDialog() {
-		ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_TITLE_PROTOCOLS, this.protocolTitles(), this.selectedProtocols(), true, this);
-		newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_PROTOCOLS);
-	}
-
-	private void openFilterDialogSelectProtocol() {
-		ArrayList<String> titles = this.protocolTitles();
-		boolean[] selected = new boolean[titles.size()];
-		int i = 0;
-		for (String title : titles) {
-			selected[i] = title.equals(this.getCurrentSelectedProtocol());
-			i++;
-		}
-		ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_PROTOCOL_SINGLE_CHOICE_TITLE, titles, selected, false, this);
-		newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_PROTOCOL_SINGLE_CHOICE_TITLE);
-	}
-
-	private void openESSIDFilterDialog() {
-		ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_TITLE_ESSID, this.essids(), this.selectedESSIDs(), true, this);
-		newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_ESSID);
-	}
-
-	private void openBSSIDFilterDialog() {
-		ChecklistDialog newFragment = new ChecklistDialog(FILTER_MENU_TITLE_BSSID, this.bssids(), this.selectedBSSIDs(), true, this);
-		newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_BSSID);
-	}
-
-	private void openTimestampFromFilterDialog() {
-		this.wasBelowTimePicker = false;
-		DateTimeDialogFragment newFragment = new DateTimeDialogFragment(this.getActivity());
-		newFragment.setDateChangeListener(this);
-		newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_TIMESTAMP_ABOVE);
-
-		if (this.filter.aboveTimestamp != Long.MIN_VALUE)
-			newFragment.setDate(this.filter.aboveTimestamp);
-	}
-
-	private void openTimestampToFilterDialog() {
-		this.wasBelowTimePicker = true;
-		DateTimeDialogFragment newFragment = new DateTimeDialogFragment(this.getActivity());
-		newFragment.setDateChangeListener(this);
-		newFragment.show(this.getActivity().getFragmentManager(), FILTER_MENU_TITLE_TIMESTAMP_BELOW);
-		if (this.filter.belowTimestamp != Long.MAX_VALUE)
-			newFragment.setDate(this.filter.belowTimestamp);
-	}
-
-	public ArrayList<String> essids() {
-		ArrayList<String> records;
-		if (this.currentPlotView instanceof BarGraph) {
-			records = dbh.getUniqueESSIDRecordsForProtocol(this.getCurrentSelectedProtocol());
-		} else {
-			records = dbh.getUniqueESSIDRecords();
-		}
-		return records;
-	}
-
-	public boolean[] selectedESSIDs() {
-		ArrayList<String> essids = this.essids();
-		boolean[] selected = new boolean[essids.size()];
-
-		int i = 0;
-		for (String essid : essids) {
-			selected[i] = (this.filter.getESSIDs().contains(essid));
-			i++;
-		}
-		return selected;
-	}
-
-	public ArrayList<String> bssids() {
-		ArrayList<String> records;
-		if (this.currentPlotView instanceof BarGraph) {
-			records = dbh.getUniqueBSSIDRecordsForProtocol(this.getCurrentSelectedProtocol());
-		} else {
-			records = dbh.getUniqueBSSIDRecords();
-		}
-		return records;
-	}
-
-	public boolean[] selectedBSSIDs() {
-		ArrayList<String> bssids = this.bssids();
-
-		boolean[] selected = new boolean[bssids.size()];
-
-		int i = 0;
-		for (String bssid : bssids) {
-			selected[i] = (this.filter.getBSSIDs().contains(bssid));
-			i++;
-		}
-		return selected;
-	}
-
-	public void onDateTimePickerPositiveClick(DateTimeDialogFragment dialog) {
-		if (this.wasBelowTimePicker) {
-			this.filter.setBelowTimestamp(dialog.getDate());
-		} else {
-			this.filter.setAboveTimestamp(dialog.getDate());
-		}
-		this.actualiseCurrentPlot();
-	}
-
-	public void onDateTimePickerNegativeClick(DateTimeDialogFragment dialog) {
-		if (this.wasBelowTimePicker) {
-			this.filter.setBelowTimestamp(Long.MAX_VALUE);
-		} else {
-			this.filter.setAboveTimestamp(Long.MIN_VALUE);
-		}
-		this.actualiseCurrentPlot();
-	}
-
-	/*
-	 * 
-	 * PLOT TYPES
-	 * 
-	 * *
-	 */
-	public PieGraph getPieGraphView() {
-		if (this.pieGraph == null) {
-			this.pieGraph = new PieGraph(this.getApplicationContext());
-			LinearLayout plotLayout = (LinearLayout) this.rootView.findViewById(R.id.plot_layout);
-			plotLayout.addView(this.pieGraph);
-			this.pieGraph.setOnSliceClickedListener(new PieGraph.OnSliceClickedListener() {
-				@Override
-				public void onClick(int index) {
-					StatisticsFragment.this.onSliceClick(index);
-				}
-			});
-		}
-		return this.pieGraph;
-	}
-
-	public LineGraph getLineGraphView() {
-		if (this.lineGraph == null) {
-			this.lineGraph = new LineGraph(this.getActivity());
-			LinearLayout plotLayout = (LinearLayout) this.rootView.findViewById(R.id.plot_layout);
-			plotLayout.addView(this.lineGraph);
-			this.lineGraph.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
-		}
-		return this.lineGraph;
-	}
-
-	public BarGraph getBarGraphView() {
-		if (this.barGraph == null) {
-			this.barGraph = new BarGraph(this.getActivity());
-			LinearLayout plotLayout = (LinearLayout) this.rootView.findViewById(R.id.plot_layout);
-			this.barGraph.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
-			plotLayout.addView(this.barGraph);
-			this.barGraph.setShowBarText(false);
-			this.barGraph.setPopupImageID(R.drawable.popup_black);
-			this.barGraph.setOnBarClickedListener(new BarGraph.OnBarClickedListener() {
-				@Override
-				public void onClick(int i) {
-					StatisticsFragment.this.onBarClick(i);
-				}
-			});
-		}
-		return this.barGraph;
-	}
-
-	/*
-	 * FEED PLOTS WITH DATA
-	 */
-	public void setPieGraphData(PieGraph piegraph) {
-		this.currentData = this.getPieData();
-		if (this.currentData == null) {
-			this.currentData = new ArrayList<PlotComparisonItem>();
-		}
-
-		this.pieGraph.removeSlices();
-
-		for (PlotComparisonItem item : this.currentData) {
-			PieSlice slice = new PieSlice();
-			slice.setColor(item.getColor());
-			Double value2 = (Double) item.getValue2();
-			float v = value2.floatValue();
-			slice.setValue(v);
-			slice.setTitle(item.getTitle());
-			this.pieGraph.addSlice(slice);
-		}
-		this.pieGraph.invalidate();
-
-	}
-
-	public void setLineGraphData(LineGraph linegraph) {
-		this.currentData = this.getLineData();
-		if (this.currentData == null) {
-			this.currentData = new ArrayList<PlotComparisonItem>();
-		}
-
-		this.lineGraph.removeAllLines();
-		double rangeMax_Y = 0;
-		double rangeMin_Y = 0;
-
-		double rangeMax_X = 0;
-		double rangeMin_X = 0;
-
-		int count = 0;
-		for (PlotComparisonItem lineItem : this.currentData) {
-			ArrayList<PlotComparisonItem> data = lineItem.getOtherData();
-			int index = 0;
-			Line l = new Line();
-			int lineColor = lineItem.getColor();
-			l.setColor(lineColor);
-
-			for (PlotComparisonItem pointItem : data) {
-				LinePoint p = new LinePoint();
-				p.setX(pointItem.getValue1());
-				Double value2 = pointItem.getValue2();
-				p.setY(value2);
-				p.setColor(lineColor);
-				l.addPoint(p);
-				rangeMax_Y = Math.max(pointItem.getValue2(), rangeMax_Y);
-				rangeMax_X = Math.max(pointItem.getValue1(), rangeMax_X);
-
-				if (count != 0) {
-					rangeMin_Y = Math.min(pointItem.getValue2(), rangeMin_Y);
-					rangeMin_X = Math.min(pointItem.getValue1(), rangeMin_X);
-				} else {
-					rangeMin_Y = pointItem.getValue2();
-					rangeMin_X = pointItem.getValue1();
-				}
-				index++;
-				count++;
-			}
-			this.lineGraph.addLine(l);
-		}
-		// add a bit more space
-		rangeMax_Y++;
-		rangeMin_Y--;
-
-		boolean shouldUseDate = this.selectedCompareData.equals(COMPARE_TITLE_AttacksPerDate);
-		if (shouldUseDate) {
-			this.lineGraph.resetXLimits();
-
-			if (this.filter.hasBelowTimestamp()) {
-				rangeMax_X = Math.max(this.filter.belowTimestamp, rangeMax_X);
-			}
-			if (this.filter.hasAboveTimestamp()) {
-				rangeMin_X = Math.min(this.filter.aboveTimestamp, rangeMin_X);
-			}
-
-			double stepRange = (rangeMax_X - rangeMin_X) / (60 * 60 * 24 * 1000);
-			this.lineGraph.setxAxisStep(Math.max(1, (float) Math.min(stepRange, 4)));
-
-			this.lineGraph.setRangeX(rangeMin_X, rangeMax_X);
-
-			this.lineGraph.setConverter(new LineGraph.AxisDataConverter() {
-				@Override
-				public String convertDataForX_Position(double x) {
-					return StatisticsFragment.this.getDateAsDayString((long) x);
-				}
-
-				@Override
-				public String convertDataForY_Position(double y) {
-					return "" + (long) y;
-				}
-			});
-		} else {
-			this.lineGraph.setxAxisStep(12.f);
-			this.lineGraph.setRangeX(0, 24);
-			this.lineGraph.setConverter(null);
-		}
-
-		int maxY = (int) (rangeMax_Y - rangeMin_Y);
-		this.lineGraph.setYAxisStep(Math.min(maxY, 5));
-		int yStep = (int) this.lineGraph.getyAxisStep();
-		if ((maxY % yStep) != 0) {
-			maxY = maxY + (yStep - (maxY % yStep));
-		}
-		this.lineGraph.setRangeY(rangeMin_Y, rangeMin_Y + maxY);
-		this.lineGraph.setLineToFill(0);
-		this.lineGraph.invalidate();
-	}
-
-	public void setBarGraphData(BarGraph bargraph) {
-		this.currentData = this.getBarData();
-		if (this.currentData == null) {
-			this.currentData = new ArrayList<PlotComparisonItem>();
-		}
-
-		ArrayList<Bar> bars = new ArrayList<Bar>();
-
-		for (PlotComparisonItem item : this.currentData) {
-			Bar d = new Bar();
-			d.setColor(item.getColor());
-			Long value2 = item.getValue2().longValue();
-			d.setName("" + value2);
-			d.setValue(value2.floatValue());
-			bars.add(d);
-		}
-
-		this.barGraph.setBars(bars);
-		this.barGraph.invalidate();
-	}
-
-	/*
-	 * 
-	 * FETCH & ACTUALISE RECORD DATA
-	 */
-	public ArrayList<Record> getFetchedRecords() {
-		if (this.filter == null)
-			this.clearFilter();
-		return this.dbh.getRecordsForFilter(this.filter);
-	}
-
-	public void actualiseCurrentPlot() {
-		LinearLayout plotLayout = (LinearLayout) this.rootView.findViewById(R.id.plot_layout);
-		View plot = this.currentPlotView;
-		if (plot == null) {
-			this.currentPlotView = this.getPieGraphView();
-			plot = this.currentPlotView;
-		}
-		if (plot.getParent() != null && !plot.getParent().equals(plotLayout)) {
-			LinearLayout linLayout = (LinearLayout) plot.getParent();
-			linLayout.removeView(plot);
-			plot.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
-			plotLayout.addView(plot);
-		}
-
-		if (plot.getVisibility() == View.GONE)
-			plot.setVisibility(View.VISIBLE);
-
-		if (plot instanceof PieGraph) {
-			PieGraph pie = (PieGraph) plot;
-			this.setPieGraphData(pie);
-			// HIDE FILTER BUTTON
-			ImageButton filterButton = this.getFilterButton();
-			if (filterButton != null)
-				filterButton.setVisibility(View.GONE);
-		} else {
-			if (this.pieGraph != null) {
-				this.pieGraph.setVisibility(View.GONE);
-				if (this.pieGraph.getParent() != null) {
-					plotLayout.removeView(this.pieGraph);
-				}
-			}
-			// SHOW FILTER BUTTON
-			ImageButton filterButton = this.getFilterButton();
-			if (filterButton != null)
-				filterButton.setVisibility(View.VISIBLE);
-		}
-		if (plot instanceof BarGraph) {
-			BarGraph bar = (BarGraph) plot;
-			this.setBarGraphData(bar);
-		} else {
-			if (this.barGraph != null) {
-				this.barGraph.setVisibility(View.GONE);
-				if (this.barGraph.getParent() != null) {
-					plotLayout.removeView(this.barGraph);
-				}
-			}
-		}
-		if (plot instanceof LineGraph) {
-			LineGraph line = (LineGraph) plot;
-			this.setLineGraphData(line);
-		} else {
-			if (this.lineGraph != null) {
-				this.lineGraph.setVisibility(View.GONE);
-				if (this.lineGraph.getParent() != null) {
-					plotLayout.removeView(this.lineGraph);
-				}
-			}
-		}
-		plot.setVisibility(View.VISIBLE);
-		if (plot.getParent() == null) {
-			plotLayout.addView(plot);
-		}
-		this.actualiseLegendList();
-		this.currentPlotView.bringToFront();
-		this.currentPlotView.invalidate();
-	}
-
-	public ArrayList<PlotComparisonItem> getPieData() {
-		// DEFAULT
-		return this.attacksPerProtocols();
-	}
-
-	public ArrayList<PlotComparisonItem> getBarData() {
-		String protocol = this.getCurrentSelectedProtocol();
-
-		if (protocol.length() > 0) {
-			if (this.selectedCompareData.equals(COMPARE_TITLE_AttacksPerESSID)) {
-				return this.attacksPerESSID(protocol);
-			}
-			// DEFAULT
-			return this.attacksPerBSSID(protocol);
-		}
-		// Nothing available
-		return new ArrayList<PlotComparisonItem>();
-	}
-
-	public ArrayList<PlotComparisonItem> getLineData() {
-		return this.attacksPerTime();
-	}
-
-	/*
-	 * DATA SOURCE
-	 */
-
-	/* PROTOCOLS OVERVIEW */
-	public ArrayList<PlotComparisonItem> attacksPerProtocols() {
-		ArrayList<PlotComparisonItem> plotItems = new ArrayList<PlotComparisonItem>();
-		int index = 0;
-		for (String title : this.getSelectedProtocolTitles()) {
-			int attacksCount = this.dbh.getAttackPerProtocolCount(title);
-			if (attacksCount == 0)
-				continue;
-			PlotComparisonItem item = new PlotComparisonItem(title, this.getColor(index), 0., (double) attacksCount);
-			plotItems.add(item);
-			index++;
-		}
-		Collections.sort(plotItems, new Comparator<PlotComparisonItem>() {
-			@Override
-			public int compare(PlotComparisonItem s1, PlotComparisonItem s2) {
-				return s2.getValue2().compareTo(s1.getValue2());
-			}
-		});
-		return this.resizeData(plotItems);
-	}
-
-	/* LINE PLOT DATA */
-
-	public ArrayList<PlotComparisonItem> attacksPerTime() {
-		HashMap<String, HashMap<Long, ArrayList<Record>>> lineMap = new HashMap<String, HashMap<Long, ArrayList<Record>>>();
-
-		boolean shouldUseDate = this.selectedCompareData.equals(COMPARE_TITLE_AttacksPerDate);
-
-		ArrayList<Record> records = this.getFetchedRecords();
-		for (Record record : records) {
-			long timestamp = record.getTimestamp();
-			long time = 0;
-			if (shouldUseDate) {
-				time = this.getDateFromMilliseconds(timestamp);
-			} else {
-				time = this.getDayHourFromDate(timestamp);
-			}
-
-			// GET CORRECT MAP
-			HashMap<Long, ArrayList<Record>> recordMap;
-			String groupKey = record.getSsid();
-			if (lineMap.containsKey(groupKey)) {
-				recordMap = lineMap.get(record.getSsid());
-			} else {
-				recordMap = new HashMap<Long, ArrayList<Record>>();
-				lineMap.put(groupKey, recordMap);
-			}
-
-			// GET LIST OF RECORDS
-			ArrayList<Record> list;
-			if (recordMap.containsKey(time)) {
-				list = recordMap.get(time);
-			} else {
-				list = new ArrayList<Record>();
-				recordMap.put(time, list);
-			}
-			list.add(record);
-		}
-
-		ArrayList<PlotComparisonItem> plotItems = new ArrayList<PlotComparisonItem>();
-
-		int index = 0;
-		for (String groupKey : lineMap.keySet()) {
-			HashMap<Long, ArrayList<Record>> recordMap = lineMap.get(groupKey);
-			ArrayList<PlotComparisonItem> singleLineItems = new ArrayList<PlotComparisonItem>();
-
-			int numbOfAttacks = 0;
-			for (long time : recordMap.keySet()) {
-				ArrayList<Record> list = recordMap.get(time);
-				if (list.size() == 0)
-					continue;
-				PlotComparisonItem item = new PlotComparisonItem(this.getHourAsTimeString(time), 0, (double) time, (double) list.size());
-				singleLineItems.add(item);
-				numbOfAttacks += list.size();
-			}
-
-			Collections.sort(singleLineItems, new Comparator<PlotComparisonItem>() {
-				@Override
-				public int compare(PlotComparisonItem s1, PlotComparisonItem s2) {
-					return s1.getValue1().compareTo(s2.getValue1());
-				}
-			});
-
-			double itemValue = (((double) numbOfAttacks / (double) records.size()) * 100.);
-			PlotComparisonItem item = new PlotComparisonItem(groupKey, this.getColor(index), (double) numbOfAttacks, itemValue);
-			item.setOtherData(singleLineItems);
-			plotItems.add(item);
-			index++;
-		}
-		Collections.sort(plotItems, new Comparator<PlotComparisonItem>() {
-			@Override
-			public int compare(PlotComparisonItem s1, PlotComparisonItem s2) {
-				return s2.getValue2().compareTo(s1.getValue2());
-			}
-		});
-		return plotItems;
-	}
-
-	// BAR PLOT DATA
-	public ArrayList<PlotComparisonItem> attacksPerBSSID(String protocol) {
-		LogFilter filter = new LogFilter();
-		ArrayList<String> protocollist = new ArrayList<String>();
-		filter.setAboveTimestamp(this.filter.getAboveTimestamp());
-		filter.setBelowTimestamp(this.filter.getBelowTimestamp());
-		filter.setBSSIDs(this.filter.getBSSIDs());
-		protocollist.add(protocol);
-		filter.setProtocols(protocollist);
-
-		ArrayList<PlotComparisonItem> plotItems = new ArrayList<PlotComparisonItem>();
-
-		HashMap<String, Integer> recordMap = new HashMap<String, Integer>();
-		ArrayList<Record> records = this.dbh.getRecordsForFilter(filter);
-		for (Record record : records) {
-			int count = 0;
-			if (recordMap.containsKey(record.getBssid())) {
-				count = recordMap.get(record.getBssid());
-			}
-			count++;
-			recordMap.put(record.getBssid(), count);
-		}
-		int index = 0;
-		for (String key : recordMap.keySet()) {
-			double value = (double) recordMap.get(key);
-			if (value == 0.)
-				continue;
-			PlotComparisonItem item = new PlotComparisonItem(key, this.getColor(index), 0., value);
-			plotItems.add(item);
-			index++;
-		}
-		Collections.sort(plotItems, new Comparator<PlotComparisonItem>() {
-			@Override
-			public int compare(PlotComparisonItem s1, PlotComparisonItem s2) {
-				return s2.getValue2().compareTo(s1.getValue2());
-			}
-		});
-		return this.resizeData(plotItems);
-	}
-
-	public ArrayList<PlotComparisonItem> attacksPerESSID(String protocol) {
-		LogFilter filter = new LogFilter();
-		filter.setAboveTimestamp(this.filter.getAboveTimestamp());
-		filter.setBelowTimestamp(this.filter.getBelowTimestamp());
-		filter.setESSIDs(this.filter.getESSIDs());
-		ArrayList<String> protocollist = new ArrayList<String>();
-		protocollist.add(protocol);
-		filter.setProtocols(protocollist);
-
-		ArrayList<PlotComparisonItem> plotItems = new ArrayList<PlotComparisonItem>();
-
-		HashMap<String, Integer> recordMap = new HashMap<String, Integer>();
-		ArrayList<Record> records = this.dbh.getRecordsForFilter(filter);
-		for (Record record : records) {
-			int count = 0;
-			if (recordMap.containsKey(record.getSsid())) {
-				count = recordMap.get(record.getSsid());
-			}
-			count++;
-			recordMap.put(record.getSsid(), count);
-		}
-		int index = 0;
-		for (String key : recordMap.keySet()) {
-			double value = (double) recordMap.get(key);
-			if (value == 0.)
-				continue;
-			PlotComparisonItem item = new PlotComparisonItem(key, this.getColor(index), 0., value);
-			plotItems.add(item);
-			index++;
-		}
-		Collections.sort(plotItems, new Comparator<PlotComparisonItem>() {
-			@Override
-			public int compare(PlotComparisonItem s1, PlotComparisonItem s2) {
-				return s2.getValue2().compareTo(s1.getValue2());
-			}
-		});
-
-		return this.resizeData(plotItems);
-	}
-
-	private ArrayList<PlotComparisonItem> resizeData(ArrayList<PlotComparisonItem> plotItems) {
-		if (plotItems != null) {
-			if (plotItems.size() > MAX_NUMBER_OF_CHART_OBJECTS && MAX_NUMBER_OF_CHART_OBJECTS > 1) {
-				ArrayList<PlotComparisonItem> copy = new ArrayList<PlotComparisonItem>();
-				ArrayList<PlotComparisonItem> others = new ArrayList<PlotComparisonItem>();
-				double valueOfOthers = 0;
-
-				for (int i = 0; i < plotItems.size(); i++) {
-					if (i < MAX_NUMBER_OF_CHART_OBJECTS - 1) {
-						PlotComparisonItem item = plotItems.get(i);
-						item.setColor(this.getColor(i));
-						copy.add(plotItems.get(i));
-					} else {
-						PlotComparisonItem item = plotItems.get(i);
-						others.add(item);
-						valueOfOthers += item.getValue2();
-					}
-				}
-				PlotComparisonItem otherItem = new PlotComparisonItem(OTHER_CHART_TITLE, this.getOtherColor(), 0., valueOfOthers);
-				otherItem.setOtherData(others);
-				copy.add(otherItem);
-
-				Collections.sort(copy, new Comparator<PlotComparisonItem>() {
-					@Override
-					public int compare(PlotComparisonItem s1, PlotComparisonItem s2) {
-						return s2.getValue2().compareTo(s1.getValue2());
-					}
-				});
-
-				return copy;
-			}
-		}
-		return plotItems;
-	}
-
-	/*
-	 * FILTER STUFF
-	 */
-	private String getCurrentSelectedProtocol() {
-		ArrayList<String> protocolTitles = this.getSelectedProtocolTitles();
-		if (protocolTitles != null && protocolTitles.size() != 0) {
-			return protocolTitles.get(0);
-		}
-		return this.protocolTitles().get(0);
-	}
-
-	public ArrayList<String> protocolTitles() {
-		ArrayList<String> titles = new ArrayList<String>();
-		for (String protocol : this.getResources().getStringArray(R.array.protocols)) {
-			titles.add(protocol);
-		}
-		return titles;
-	}
-
-	public boolean[] selectedProtocols() {
-		ArrayList<String> protocols = this.protocolTitles();
-		boolean[] selected = new boolean[protocols.size()];
-
-		int i = 0;
-		for (String protocol : protocols) {
-			selected[i] = (this.filter.protocols.contains(protocol));
-			i++;
-		}
-		return selected;
-	}
-
-	public ArrayList<String> getSelectedProtocolTitles() {
-		ArrayList<String> knownProtocols = this.protocolTitles();
-		if (this.filter.hasProtocols()) {
-			ArrayList<String> titles = new ArrayList<String>();
-			int i = 0;
-			for (boolean b : this.selectedProtocols()) {
-				if (b) {
-					String title = knownProtocols.get(i);
-					titles.add(title);
-				}
-				i++;
-			}
-			return titles;
-		}
-		return this.protocolTitles();
-	}
-
-	/*
-	 * 
-	 * COLOR STUFF
-	 */
-
-	public int getOtherColor() {
-		return Color.argb(255, 80, 80, 80); // grey
-	}
-
-	public Integer getColor(int index) {
-		return ColorSequenceGenerator.getColorForIndex(index);
-	}
-
-	public LinearLayout getPlotLayout() {
-		if (this.rootView != null) {
-			return (LinearLayout) this.rootView.findViewById(R.id.plot_layout);
-		} else {
-			return null;
-		}
-	}
-
-	/**
-	 * 
-	 * FILTER STUFF
-	 * 
-	 * */
-	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.getProtocols() != null && this.filter.hasProtocols() && this.filter.getProtocols().size() != this.protocolTitles().size());
-		}
-		if (title.equals(FILTER_MENU_TITLE_TIMESTAMP_BELOW)) {
-			return this.filter.hasBelowTimestamp();
-		}
-		if (title.equals(FILTER_MENU_TITLE_TIMESTAMP_ABOVE)) {
-			return this.filter.hasAboveTimestamp();
-		}
-		return false;
-	}
-
-	private void clearFilter() {
-		if (filter == null)
-			this.filter = new LogFilter();
-		this.filter.clear();
-	}
-
-	/*
-	 * 
-	 * DATE TRANSFORMATION
-	 */
-	public long getDayHourFromDate(long timeInMillis) {
-
-		Calendar calendar = Calendar.getInstance();
-
-		calendar.setTimeInMillis(timeInMillis);
-		int hour = calendar.get(Calendar.HOUR_OF_DAY);
-		int min = calendar.get(Calendar.MINUTE);
-
-		return hour;
-
-	}
-
-	public long getDateFromMilliseconds(long timeInMillis) {
-		long millisInDay = 60 * 60 * 24 * 1000;
-		return (timeInMillis / millisInDay) * millisInDay;
-
-	}
-
-	/*
-    *
-    * */
-	private String getHourAsTimeString(long hour) {
-		return "" + hour + ":00";
-	}
-
-	static final DateFormat dateFormat = new SimpleDateFormat("d.M.yyyy");
-
-	@SuppressLint("SimpleDateFormat")
-	private String getDateAsDayString(long timeStamp) {
-		try {
-			Date netDate = (new Date(timeStamp));
-			return dateFormat.format(netDate);
-		} catch (Exception ex) {
-			return "xx";
-		}
-	}
-
-	@SuppressLint("SimpleDateFormat")
-	private String getDateAsString(long timeStamp) {
-
-		try {
-			DateFormat sdf = new SimpleDateFormat("H:mm  dd/MM/yyyy");
-			Date netDate = (new Date(timeStamp));
-			return sdf.format(netDate);
-		} catch (Exception ex) {
-			return "xx";
-		}
-	}
-
-	/**
-	 * USERINTERACTION
-	 */
-	private void userTappedOnLegendItem(int index) {
-		if (index < this.currentData.size()) {
-			PlotComparisonItem item = this.currentData.get(index);
-			ArrayList<String> selectedData;
-			String sortKey = null;
-			selectedData = new ArrayList<String>();
-
-			if (item.getOtherData() == null) {
-				selectedData.add(item.getTitle());
-			} else {
-				for (PlotComparisonItem other : item.getOtherData()) {
-					selectedData.add(other.getTitle());
-				}
-			}
-			LogFilter filter = new LogFilter();
-			if (this.currentPlotView instanceof PieGraph) {
-				filter.setProtocols(selectedData);
-			}
-			if (this.currentPlotView instanceof BarGraph) {
-
-				if (this.selectedCompareData.equals(COMPARE_TITLE_AttacksPerESSID)) {
-					filter.setESSIDs(selectedData);
-					sortKey = "ESSID";
-				} else {
-					filter.setBSSIDs(selectedData);
-					sortKey = "BSSID";
-				}
-				ArrayList<String> currentSelectedProtocol = new ArrayList<String>();
-				currentSelectedProtocol.add(this.getCurrentSelectedProtocol());
-				filter.setProtocols(currentSelectedProtocol);
-			}
-			if (this.currentPlotView instanceof LineGraph) {
-				selectedData = new ArrayList<String>();
-				selectedData.add(item.getTitle());
-				filter.setESSIDs(selectedData);
-				filter.setProtocols(this.filter.getProtocols());
-				sortKey = "ESSID";
-			}
-
-			if (this.filter.hasATimestamp()) {
-				filter.setAboveTimestamp(this.filter.getAboveTimestamp());
-				filter.setBelowTimestamp(this.filter.getBelowTimestamp());
-			}
-
-			this.pushRecordOverviewForFilter(filter, sortKey);
-		}
-	}
-
-	public void onSliceClick(int index) {
-
-	}
-
-	public void onBarClick(int index) {
-		this.userTappedOnLegendItem(index);
-	}
-
-	private void pushRecordOverviewForFilter(LogFilter filter, String sortKey) {
-
-		FragmentManager fm = this.getActivity().getFragmentManager();
-
-		if (fm != null) {
-			RecordOverviewFragment newFragment = new RecordOverviewFragment();
-			newFragment.setUpNavigatible(true);
-			newFragment.setFilter(filter);
-
-			if (sortKey != null && sortKey.length() != 0)
-				newFragment.setGroupKey(sortKey);
-
-			MainActivity.getInstance().injectFragment(newFragment);
-
-		}
-
-	}
-
-}

+ 0 - 60
src/de/tudarmstadt/informatik/hostage/ui2/listeners/OnSwipeTouchListener.java

@@ -1,60 +0,0 @@
-package de.tudarmstadt.informatik.hostage.ui2.listeners;
-
-import android.view.GestureDetector;
-import android.view.GestureDetector.SimpleOnGestureListener;
-import android.view.MotionEvent;
-import android.view.View;
-import android.view.View.OnTouchListener;
-
-import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
-
-/**
- * @author Alexander Brakowski
- * @created 27.01.14 23:47
- */
-public class OnSwipeTouchListener implements OnTouchListener {
-
-	private final GestureDetector gestureDetector = new GestureDetector(MainActivity.getContext(), new GestureListener());
-
-	public boolean onTouch(final View view, final MotionEvent motionEvent) {
-		return gestureDetector.onTouchEvent(motionEvent);
-	}
-
-	private final class GestureListener extends SimpleOnGestureListener {
-
-		private static final int SWIPE_THRESHOLD = 50;
-		private static final int SWIPE_VELOCITY_THRESHOLD = 150;
-
-		@Override
-		public boolean onDown(MotionEvent e) {
-			return true;
-		}
-
-		@Override
-		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
-
-			try {
-				float diffX = e2.getX() - e1.getX();
-
-				if (Math.abs(diffX) > SWIPE_THRESHOLD) {
-					if (diffX > 0) {
-						onSwipeRight();
-					} else {
-						onSwipeLeft();
-					}
-				}
-			} catch (Exception exception) {
-				exception.printStackTrace();
-				return false;
-			}
-
-			return true;
-		}
-	}
-
-	public void onSwipeRight() {
-	}
-
-	public void onSwipeLeft() {
-	}
-}

+ 0 - 16
src/de/tudarmstadt/informatik/hostage/ui2/model/ServicesListItem.java

@@ -1,16 +0,0 @@
-package de.tudarmstadt.informatik.hostage.ui2.model;
-
-/**
- * Created by Daniel Lazar on 06.02.14.
- */
-public class ServicesListItem {
-	public String protocol;
-	public int attacks;
-
-	public boolean activated;
-
-	public ServicesListItem(String protocol){
-		this.protocol = protocol;
-		this.activated = false;
-	}
-}

+ 0 - 84
src/de/tudarmstadt/informatik/hostage/ui2/popup/AbstractPopupItem.java

@@ -1,84 +0,0 @@
-package de.tudarmstadt.informatik.hostage.ui2.popup;
-
-import android.content.Context;
-import android.view.LayoutInflater;
-import android.view.MotionEvent;
-import android.view.View;
-
-import java.util.HashMap;
-
-/**
- * Created by Julien on 13.02.14.
- */
-public abstract class AbstractPopupItem {
-    private int itemId;
-    private String title;
-
-    private View itemView;
-
-    private LayoutInflater lInf;
-
-    public HashMap<Object, Object> data;
-
-
-    abstract public int getLayoutId();
-
-    abstract public void configureItemView(View view);
-
-
-    public void setValue(String key, Object value){
-        if (key != null && value != null){
-            this.data.put(key, value);
-            if (this.itemView != null) this.configureItemView(this.itemView);
-        }
-    }
-    public void setMultipleData(HashMap<Object, Object> map){
-        if (map != null){
-            for(Object key : map.keySet()){
-                this.data.put(key, map.get(key));
-            }
-            if (this.itemView != null) this.configureItemView(this.itemView);
-        }
-    }
-
-    public void setTitle(String title){
-        this.title = title;
-        if (this.itemView != null) this.configureItemView(this.itemView);
-    }
-    public String getTitle(){
-        return this.title;
-    }
-    public void setItemId(int id){
-        this.itemId = id;
-        if (this.itemView != null) this.configureItemView(this.itemView);
-    }
-    public int getItemId() {
-        return this.itemId;
-    }
-
-    public AbstractPopupItem(Context context) {
-        super();
-        this.lInf = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
-        this.data = new HashMap<Object, Object>();
-    }
-
-    public View getItemView(){
-        if (this.itemView == null){
-            this.itemView = this.lInf.inflate(this.getLayoutId(), null);
-        }
-        this.configureItemView(this.itemView);
-
-        return this.itemView;
-    }
-
-    public Object onClickedResult(MotionEvent event){
-        return this;
-    }
-
-	public void onItemSelect(MotionEvent event){
-	}
-
-	public void onItemDeselect(MotionEvent event){
-
-	}
-}

+ 0 - 41
src/de/tudarmstadt/informatik/hostage/ui2/preference/ImageSelectPreference.java

@@ -1,41 +0,0 @@
-package de.tudarmstadt.informatik.hostage.ui2.preference;
-
-import android.content.Context;
-import android.preference.Preference;
-import android.util.AttributeSet;
-import android.view.View;
-import android.view.ViewGroup;
-
-import de.tudarmstadt.informatik.hostage.R;
-
-/**
- * @author Alexander Brakowski
- * @created 08.02.14 18:38
- */
-public class ImageSelectPreference extends Preference {
-
-	private Context context;
-
-	public ImageSelectPreference(Context context, AttributeSet attrs,
-			int defStyle) {
-		super(context, attrs, defStyle);
-
-		this.context = context;
-	}
-
-	public void init(){
-		this.setWidgetLayoutResource(R.layout.preferences_image_widget);
-	}
-
-	@Override
-	protected void onClick() {
-		//context.start
-	}
-
-	/*protected View onCreateView(ViewGroup parent) {
-		View p = super.onCreateView(parent);
-
-
-		return p;
-	}*/
-}