Fabio Arnold 10 年之前
父节点
当前提交
af9826961b
共有 25 个文件被更改,包括 1726 次插入249 次删除
  1. 13 4
      AndroidManifest.xml
  2. 26 7
      res/layout/activity_bluetooth.xml
  3. 18 11
      res/layout/activity_p2_psync.xml
  4. 1 1
      res/values/protocols.xml
  5. 1 0
      src/de/tudarmstadt/informatik/hostage/logging/AttackRecord.java
  6. 13 1
      src/de/tudarmstadt/informatik/hostage/logging/MessageRecord.java
  7. 11 0
      src/de/tudarmstadt/informatik/hostage/logging/NetworkRecord.java
  8. 93 96
      src/de/tudarmstadt/informatik/hostage/logging/SyncRecord.java
  9. 2 2
      src/de/tudarmstadt/informatik/hostage/nio/Reader.java
  10. 93 50
      src/de/tudarmstadt/informatik/hostage/persistence/HostageDBOpenHelper.java
  11. 1 1
      src/de/tudarmstadt/informatik/hostage/sync/Synchronizer.java
  12. 37 7
      src/de/tudarmstadt/informatik/hostage/sync/bluetooth/BluetoothSyncActivity.java
  13. 1 8
      src/de/tudarmstadt/informatik/hostage/sync/bluetooth/CommunicationThread.java
  14. 2 2
      src/de/tudarmstadt/informatik/hostage/sync/p2p/P2PSyncActivity.java
  15. 100 52
      src/de/tudarmstadt/informatik/hostage/sync/tracing/TracingSyncService.java
  16. 77 0
      src/de/tudarmstadt/informatik/hostage/sync/wifi_direct/BackgroundTask.java
  17. 275 0
      src/de/tudarmstadt/informatik/hostage/sync/wifi_direct/WiFiP2pBroadcastReceiver.java
  18. 145 0
      src/de/tudarmstadt/informatik/hostage/sync/wifi_direct/WiFiP2pClientTask.java
  19. 86 0
      src/de/tudarmstadt/informatik/hostage/sync/wifi_direct/WiFiP2pEventHandler.java
  20. 29 0
      src/de/tudarmstadt/informatik/hostage/sync/wifi_direct/WiFiP2pSerializableObject.java
  21. 104 0
      src/de/tudarmstadt/informatik/hostage/sync/wifi_direct/WiFiP2pServerTask.java
  22. 74 0
      src/de/tudarmstadt/informatik/hostage/sync/wifi_direct/sync_tasks/SyncClientTask.java
  23. 81 0
      src/de/tudarmstadt/informatik/hostage/sync/wifi_direct/sync_tasks/SyncHostTask.java
  24. 426 0
      src/de/tudarmstadt/informatik/hostage/sync/wifi_direct/ui/WiFiP2pSyncActivity.java
  25. 17 7
      src/de/tudarmstadt/informatik/hostage/ui/fragment/RecordOverviewFragment.java

+ 13 - 4
AndroidManifest.xml

@@ -66,12 +66,12 @@
         <activity
             android:name=".sync.tracing.TracingSyncActivity"
             android:label="@string/gui_tracing"
-            android:theme="@android:style/Theme.Dialog" >
+            android:theme="@android:style/Theme.Holo.Dialog" >
         </activity>
         <activity
             android:name=".sync.bluetooth.BluetoothSyncActivity"
             android:label="@string/gui_bluetooth"
-            android:theme="@android:style/Theme.Dialog" >
+            android:theme="@android:style/Theme.Holo.Dialog" >
         </activity>
         <activity
             android:name=".sync.nfc.NFCSyncActivity"
@@ -109,13 +109,22 @@
             android:exported="false" >
         </provider>
 
-        <activity
+        <!--<activity
             android:name=".sync.p2p.P2PSyncActivity"
             android:label="@string/title_activity_p2_psync"
             android:parentActivityName=".ui.activity.MainActivity" >
             <meta-data
                 android:name="android.support.PARENT_ACTIVITY"
-                android:value="de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity" />
+                android:value="de.tudarmstadt.informatik.hostage.ui.activity.MainActivity" />
+        </activity>-->
+
+        <activity
+            android:name=".sync.wifi_direct.ui.WiFiP2pSyncActivity"
+            android:label="@string/title_activity_p2_psync"
+            android:parentActivityName=".ui.activity.MainActivity" >
+            <meta-data
+                android:name="android.support.PARENT_ACTIVITY"
+                android:value="de.tudarmstadt.informatik.hostage.ui.activity.MainActivity" />
         </activity>
     </application>
 

+ 26 - 7
res/layout/activity_bluetooth.xml

@@ -1,4 +1,4 @@
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+<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="wrap_content"
@@ -9,17 +9,36 @@
     android:paddingTop="@dimen/activity_vertical_margin"
     android:id="@+id/bluetoothLayout" >
 
-    <TextView
-        android:id="@+id/bluetoothInfoText"
+    <ProgressBar
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
-        />
-    
+        android:id="@+id/bluetoothProgressBar"
+        android:layout_gravity="center_horizontal"
+        android:layout_centerVertical="true"
+        android:layout_centerHorizontal="true"
+        android:indeterminate="true"
+        android:indeterminateOnly="true"
+        android:textAlignment="center"
+        android:visibility="gone"
+        android:layout_marginBottom="10dp" />
+
     <ListView
         android:id="@+id/bluetoothListView"
         android:visibility="gone"
+        android:layout_width="fill_parent"
+        android:layout_height="wrap_content"
+        android:layout_below="@+id/bluetoothInfoText"
+        android:layout_centerHorizontal="true"
+        android:paddingTop="2dp" />
+
+    <TextView
+        android:id="@+id/bluetoothInfoText"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
-        />
+        android:gravity="center|top"
+        android:layout_below="@+id/bluetoothProgressBar"
+        android:layout_centerHorizontal="true"
+        android:layout_marginTop="10dp"
+        android:visibility="visible" />
 
-</LinearLayout>
+</RelativeLayout>

+ 18 - 11
res/layout/activity_p2_psync.xml

@@ -90,16 +90,13 @@
             android:layout_marginTop="6dp" />
     </RelativeLayout>
 
-    <ViewAnimator
+
+
+    <RelativeLayout
+        android:id="@+id/list_container"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
-        android:id="@+id/viewAnimator"
-        android:layout_below="@+id/device_info_panel"
-        android:layout_alignParentBottom="true"
-        android:layout_alignParentRight="true"
-        android:layout_alignParentEnd="true"
-        android:layout_alignParentLeft="true"
-        android:layout_alignParentStart="true">
+        android:layout_below="@+id/device_info_panel">
 
         <RelativeLayout
             android:layout_width="fill_parent"
@@ -124,9 +121,7 @@
         <RelativeLayout
             android:layout_width="fill_parent"
             android:layout_height="fill_parent"
-            android:layout_alignParentBottom="true"
-            android:layout_alignParentRight="true"
-            android:layout_alignParentEnd="true"
+
             android:id="@+id/devicesContainer">
 
             <TextView
@@ -159,6 +154,18 @@
 
         </RelativeLayout>
 
+    </RelativeLayout>
+
+    <ViewAnimator
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:id="@+id/viewAnimator"
+        android:layout_below="@+id/device_info_panel"
+        android:layout_alignParentBottom="true"
+        android:layout_alignParentRight="true"
+        android:layout_alignParentEnd="true"
+        android:layout_alignParentLeft="true"
+        android:layout_alignParentStart="true">
     </ViewAnimator>
 
 </RelativeLayout>

+ 1 - 1
res/values/protocols.xml

@@ -14,7 +14,7 @@
         <item>TELNET</item>
     </string-array>
 
-	<string-array name="protocols_description">
+    <string-array name="protocols_description">
 		<item>A service for testing and measurement of round-trip times in IP networks</item>
 		<item>A protocol used to transfer files from one host to another host</item>
 		<item>A protocol mirrors an incoming connection back to the attacker on the same port, that it is running on</item>

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

@@ -71,6 +71,7 @@ public class AttackRecord implements Parcelable, Serializable {
             this.sync_id = attack_id;
 
             SyncDevice currentDevice = SyncDevice.currentDevice();
+            currentDevice.setHighest_attack_id(attack_id);
             this.setDevice(currentDevice.getDeviceID());
         }
 

+ 13 - 1
src/de/tudarmstadt/informatik/hostage/logging/MessageRecord.java

@@ -133,7 +133,19 @@ public class MessageRecord implements Parcelable, Serializable{
 	public String getPacket() {
 		return packet;
 	}
-	/**
+
+    @Override
+    public String toString() {
+        return "MessageRecord{" +
+                "id=" + id +
+                ", attack_id=" + attack_id +
+                ", timestamp=" + timestamp +
+                ", type=" + type +
+                ", packet='" + packet + '\'' +
+                '}';
+    }
+
+    /**
 	 * @param packet the packet to set
 	 */
 	public void setPacket(String packet) {

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

@@ -156,4 +156,15 @@ public class NetworkRecord implements Parcelable, Serializable {
 				latitude, longitude, timestampLocation, -1, -1);
 	}
 
+    @Override
+    public String toString() {
+        return "NetworkRecord{" +
+                "bssid='" + bssid + '\'' +
+                ", ssid='" + ssid + '\'' +
+                ", timestampLocation=" + timestampLocation +
+                ", latitude=" + latitude +
+                ", longitude=" + longitude +
+                ", accuracy=" + accuracy +
+                '}';
+    }
 }

+ 93 - 96
src/de/tudarmstadt/informatik/hostage/logging/SyncRecord.java

@@ -4,6 +4,7 @@ package de.tudarmstadt.informatik.hostage.logging;
  * Created by Julien on 08.12.2014.
  */
 
+import android.os.Message;
 import android.os.Parcel;
 import android.os.Parcelable;
 
@@ -13,8 +14,12 @@ import android.os.Parcel;
 import android.os.Parcelable;
 
 import java.io.Serializable;
+import java.lang.reflect.Array;
+import java.util.ArrayList;
 import java.util.zip.Deflater;
 
+import de.tudarmstadt.informatik.hostage.wrapper.Packet;
+
 public class SyncRecord implements Parcelable, Serializable {
 
     private static final long serialVersionUID = 7106818788090434192L;
@@ -32,11 +37,15 @@ public class SyncRecord implements Parcelable, Serializable {
     private String externalIP;
     private int wasInternalAttack; // 1 if attacker ip and local ip were in same subnet, else 0
 
+    transient private AttackRecord attackRecord;
+
     // attack
-    private int id;
-    private long timestamp;
-    private MessageRecord.TYPE type;
-    private String packet;
+    //private int id;
+    //private long timestamp;
+    //private MessageRecord.TYPE type;
+    //private String packet;
+
+    private ArrayList<MessageRecord> messageRecords;
 
     public static final Parcelable.Creator<SyncRecord> CREATOR = new Parcelable.Creator<SyncRecord>() {
         @Override
@@ -54,6 +63,20 @@ public class SyncRecord implements Parcelable, Serializable {
 
     }
 
+    public SyncRecord(AttackRecord attackRecord){
+        this.attackRecord = attackRecord;
+        this.setAttack_id(attackRecord.getAttack_id());
+        this.setProtocol(attackRecord.getProtocol());
+        this.setExternalIP(attackRecord.getExternalIP());
+        this.setLocalPort(attackRecord.getLocalPort());
+        this.setRemoteIP(attackRecord.getRemoteIP());
+        this.setRemotePort(attackRecord.getRemotePort());
+        this.setWasInternalAttack(attackRecord.getWasInternalAttack());
+        this.setBssid(attackRecord.getBssid());
+        this.setSync_id(attackRecord.getSync_id());
+        this.setDevice(attackRecord.getDevice());
+    }
+
     public SyncRecord(Parcel source) {
         super();
         this.attack_id = source.readLong();
@@ -68,10 +91,17 @@ public class SyncRecord implements Parcelable, Serializable {
         this.device = source.readString();
         this.sync_id = source.readLong();
 
-        this.id = source.readInt();
-        this.timestamp = source.readLong();
-        this.type = MessageRecord.TYPE.valueOf(source.readString());
-        this.packet = source.readString();
+        this.messageRecords = source.readArrayList(MessageRecord.class.getClassLoader());
+
+
+        this.attackRecord = null;
+        AttackRecord attack= this.getAttackRecord();
+
+
+        //this.id = source.readInt();
+        //this.timestamp = source.readLong();
+        //this.type = MessageRecord.TYPE.valueOf(source.readString());
+        //this.packet = source.readString();
     }
 
     @Override
@@ -93,42 +123,47 @@ public class SyncRecord implements Parcelable, Serializable {
         dest.writeString(device);
         dest.writeLong(sync_id);
 
-        dest.writeInt(id);
-        dest.writeLong(timestamp);
-        dest.writeString(type.name());
-        dest.writeString(packet);
+        dest.writeList(this.messageRecords);
+        //dest.writeInt(id);
+        //dest.writeLong(timestamp);
+        //dest.writeString(type.name());
+        //dest.writeString(packet);
     }
 
 
     public AttackRecord getAttackRecord(){
-        boolean autoincrement = !this.device.equals(SyncDevice.currentDevice().getDeviceID());
-        AttackRecord record = new AttackRecord(autoincrement);
-
-        if (!autoincrement)
-            record.setAttack_id(this.attack_id);
-
-        this.attack_id = record.getAttack_id();
-        record.setProtocol(this.protocol);
-        record.setSync_id(this.sync_id);
-        record.setLocalIP(this.localIP);
-        record.setLocalPort(this.localPort);
-        record.setBssid(this.bssid);
-        record.setDevice(this.device);
-        record.setExternalIP(this.externalIP);
-        record.setWasInternalAttack(this.getWasInternalAttack());
-        record.setRemoteIP(this.remoteIP);
-        record.setRemotePort(this.remotePort);
-
-        return record;
+        if (this.attackRecord == null){
+            AttackRecord record = new AttackRecord(true);
+
+            this.attack_id = record.getAttack_id();
+            record.setProtocol(this.protocol);
+            record.setSync_id(this.sync_id);
+            record.setLocalIP(this.localIP);
+            record.setLocalPort(this.localPort);
+            record.setBssid(this.bssid);
+            record.setDevice(this.device);
+            record.setExternalIP(this.externalIP);
+            record.setWasInternalAttack(this.getWasInternalAttack());
+            record.setRemoteIP(this.remoteIP);
+            record.setRemotePort(this.remotePort);
+            this.attackRecord = record;
+
+            if (messageRecords != null){
+                for (MessageRecord messageRecord : this.messageRecords){
+                    messageRecord.setAttack_id(record.getAttack_id());
+                }
+            }
+        }
+
+        return this.attackRecord;
     }
 
-    public MessageRecord getMessageRecord(){
-        MessageRecord record = new MessageRecord(true);
-        record.setAttack_id(this.attack_id);
-        record.setPacket(this.packet);
-        record.setTimestamp(this.timestamp);
-        record.setType(this.type);
-        return record;
+    public ArrayList<MessageRecord> getMessageRecords(){
+        return this.messageRecords;
+    }
+
+    public void setMessageRecords(ArrayList<MessageRecord> mr){
+        this.messageRecords = mr;
     }
 
     /**
@@ -259,64 +294,6 @@ public class SyncRecord implements Parcelable, Serializable {
     public void setWasInternalAttack(boolean b) {wasInternalAttack = b ? 1 : 0;}
 
 
-
-    /*
-    *
-    *
-    *  MESSAGE RECORD
-    *
-    *
-    */
-    /**
-     * @return the id
-     */
-    public int getId() {
-        return id;
-    }
-    /**
-     * @param id the id to set
-     */
-    public void setId(int id) {
-        this.id = id;
-    }
-
-    /**
-     * @return the timestamp
-     */
-    public long getTimestamp() {
-        return timestamp;
-    }
-    /**
-     * @param timestamp the timestamp to set
-     */
-    public void setTimestamp(long timestamp) {
-        this.timestamp = timestamp;
-    }
-    /**
-     * @return the type
-     */
-    public MessageRecord.TYPE getType() {
-        return type;
-    }
-    /**
-     * @param type the type to set
-     */
-    public void setType(MessageRecord.TYPE type) {
-        this.type = type;
-    }
-    /**
-     * @return the packet
-     */
-    public String getPacket() {
-        return packet;
-    }
-    /**
-     * @param packet the packet to set
-     */
-    public void setPacket(String packet) {
-        this.packet = packet;
-    }
-
     /**
      * @return the number_of_attacks
      */
@@ -349,5 +326,25 @@ public class SyncRecord implements Parcelable, Serializable {
     private long number_of_attacks;
     private long number_of_portscans;
 
+    @Override
+    public String toString() {
+        return "SyncRecord{" +
+                "attack_id=" + attack_id +
+                ", sync_id=" + sync_id +
+                ", bssid='" + bssid + '\'' +
+                ", device='" + device + '\'' +
+                ", protocol='" + protocol + '\'' +
+                ", localIP='" + localIP + '\'' +
+                ", localPort=" + localPort +
+                ", remoteIP='" + remoteIP + '\'' +
+                ", remotePort=" + remotePort +
+                ", externalIP='" + externalIP + '\'' +
+                ", wasInternalAttack=" + wasInternalAttack +
+                ", attackRecord=" + attackRecord +
+                ", messageRecords=" + messageRecords +
+                ", number_of_attacks=" + number_of_attacks +
+                ", number_of_portscans=" + number_of_portscans +
+                '}';
+    }
 }
 

+ 2 - 2
src/de/tudarmstadt/informatik/hostage/nio/Reader.java

@@ -19,9 +19,9 @@ public class Reader {
 
 	public Packet read() throws IOException {
 		ByteArrayOutputStream payload = new ByteArrayOutputStream();
-		do {
+        while(in.available() > 0){
 			payload.write(in.read());
-		} while (in.available() > 0);
+		}
 		return new Packet(payload.toByteArray(), protocol);
 	}
 

+ 93 - 50
src/de/tudarmstadt/informatik/hostage/persistence/HostageDBOpenHelper.java

@@ -1,5 +1,7 @@
 package de.tudarmstadt.informatik.hostage.persistence;
 
+import java.lang.reflect.Array;
+import java.sql.SQLInput;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.LinkedList;
@@ -170,6 +172,11 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 
     private static  SyncDevice thisDevice = null;
     public static SyncDevice currentDevice(){
+        if (thisDevice != null){
+            SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(MainActivity.getContext());
+            int attack_id = pref.getInt("ATTACK_ID_COUNTER", 0);
+            thisDevice.setHighest_attack_id(attack_id);
+        }
         return thisDevice;
     }
     /**
@@ -199,6 +206,7 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
                 record.setLast_sync_timestamp(cursor.getLong(1));
                 record.setHighest_attack_id(cursor.getLong(2));
                 thisDevice = record;
+                thisDevice.setHighest_attack_id(attack_id-1);
                 cursor.close();
                 db.close();
                 // return record list
@@ -215,7 +223,7 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
                 editor.putString("CURRENT_DEVICE_IDENTIFIER", thisDevice.getDeviceID());
                 editor.commit();
                 thisDevice.setLast_sync_timestamp(0);
-                thisDevice.setHighest_attack_id(-1);
+                thisDevice.setHighest_attack_id(attack_id-1);
                 ArrayList<SyncDevice> devices = new ArrayList<SyncDevice>();
                 devices.add(thisDevice);
                 this.insertSyncDevices(devices);
@@ -235,7 +243,7 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 	 * @param record
 	 *            The added {@link MessageRecord} .
 	 */
-	public void addMessageRecord(MessageRecord record) {
+	synchronized public void addMessageRecord(MessageRecord record) {
 		SQLiteDatabase db = this.getWritableDatabase();
 
 		this.insertMessageRecordWithOnConflict(record, db);
@@ -248,7 +256,7 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
      * @param records {@link List}<MessageRecord>
      *            The added {@link de.tudarmstadt.informatik.hostage.logging.MessageRecord}s .
      */
-    public void insertMessageRecords(List<MessageRecord> records){
+    synchronized public void insertMessageRecords(List<MessageRecord> records){
         SQLiteDatabase db = this.getWritableDatabase();
         db.beginTransaction();
 
@@ -262,8 +270,13 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
         }
         db.close();
     }
+    public void insertMessageRecords(List<MessageRecord> records, SQLiteDatabase db){
+        for (MessageRecord record : records){
+            this.insertMessageRecordWithOnConflict(record,db);
+        }
+    }
 
-    private void insertMessageRecordWithOnConflict(MessageRecord record, SQLiteDatabase db){
+    synchronized private void insertMessageRecordWithOnConflict(MessageRecord record, SQLiteDatabase db){
         ContentValues recordValues = new ContentValues();
         recordValues.put(PacketEntry.COLUMN_NAME_ID, record.getId()); // Log Message Number
         recordValues.put(PacketEntry.COLUMN_NAME_ATTACK_ID, record.getAttack_id()); // Log Attack ID
@@ -281,7 +294,7 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 	 * @param record
 	 *            The added {@link AttackRecord} .
 	 */
-	public void addAttackRecord(AttackRecord record) {
+    synchronized public void addAttackRecord(AttackRecord record) {
 		//Log.i("DBHelper", "Add Attack Record with id: " + record.getAttack_id());
 		SQLiteDatabase db = this.getWritableDatabase();
 		this.insertAttackRecordWithOnConflict(record,db);
@@ -297,7 +310,7 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
      * @param records {@link List}<AttackRecord>
      *            The added {@link AttackRecord}s .
      */
-    public void insertAttackRecords(List<AttackRecord> records) {
+    synchronized public void insertAttackRecords(List<AttackRecord> records) {
 
 
         //Log.i("DBHelper", "Add Attack Record with id: " + record.getAttack_id());
@@ -318,7 +331,7 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
         this.updateSyncDevices(devices);
     }
 
-    private void insertAttackRecordWithOnConflict(AttackRecord record, SQLiteDatabase db){
+    synchronized private void insertAttackRecordWithOnConflict(AttackRecord record, SQLiteDatabase db){
         ContentValues attackValues = new ContentValues();
         attackValues.put(AttackEntry.COLUMN_NAME_ATTACK_ID, record.getAttack_id()); // Log Attack ID
         attackValues.put(AttackEntry.COLUMN_NAME_PROTOCOL, record.getProtocol().toString());
@@ -342,7 +355,7 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
      * @param records {@link List}<AttackRecord>
      *            The added {@link SyncRecord}s .
      */
-    public void insertSyncRecords(List<SyncRecord> records) {
+    synchronized public void insertSyncRecords(List<SyncRecord> records) {
         //Log.i("DBHelper", "Add Attack Record with id: " + record.getAttack_id());
         SQLiteDatabase db = this.getWritableDatabase();
         db.beginTransaction();
@@ -350,7 +363,7 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
         try {
             for (SyncRecord record : records){
                 this.insertAttackRecordWithOnConflict(record.getAttackRecord(), db);
-                this.insertMessageRecordWithOnConflict(record.getMessageRecord(), db);
+                this.insertMessageRecords(record.getMessageRecords(), db);
             }
             db.setTransactionSuccessful();
         } finally {
@@ -366,10 +379,10 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
     /**
      * Updates the sync devices max sync id.
      */
-    public void updateSyncDevicesMaxID(SQLiteDatabase db){
+    synchronized public void updateSyncDevicesMaxID(SQLiteDatabase db){
         HashMap<String, Long> deviceIDmap = new HashMap<String, Long>();
 
-        String selectQuery = "SELECT "+AttackEntry.COLUMN_NAME_DEVICE+ ","+ AttackEntry.COLUMN_NAME_SYNC_ID+" FROM " + AttackEntry.TABLE_NAME + " A "  + " GROUP BY " + AttackEntry.COLUMN_NAME_DEVICE + " HAVING " + AttackEntry.COLUMN_NAME_SYNC_ID + " = MAX( " + AttackEntry.COLUMN_NAME_SYNC_ID + " )";
+        String selectQuery = "SELECT "+AttackEntry.COLUMN_NAME_DEVICE+ ","+ AttackEntry.COLUMN_NAME_SYNC_ID+" FROM " + AttackEntry.TABLE_NAME + " A " + " WHERE " + AttackEntry.COLUMN_NAME_SYNC_ID + " NOT NULL "  + " GROUP BY " + AttackEntry.COLUMN_NAME_DEVICE + " HAVING " + AttackEntry.COLUMN_NAME_SYNC_ID + " = MAX( " + AttackEntry.COLUMN_NAME_SYNC_ID + " )";
 
         {
             Cursor cursor = db.rawQuery(selectQuery, null);
@@ -388,15 +401,17 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
         {
             ArrayList<SyncDevice> allDevices = this.getSyncDevices(db);
             for (SyncDevice device : allDevices){
-                long sync_id = deviceIDmap.get(device.getDeviceID());
-                device.setHighest_attack_id(sync_id);
+                Long sync_id = deviceIDmap.get(device.getDeviceID());
+                long highestID = device.getHighest_attack_id();
+                if (sync_id != null) highestID = sync_id.longValue();
+                device.setHighest_attack_id(highestID);
             }
             this.updateSyncDevices(allDevices, db);
         }
 
     }
-	
-	public void updateSyncAttackCounter(AttackRecord record){
+
+    synchronized public void updateSyncAttackCounter(AttackRecord record){
 		
 		SQLiteDatabase db = this.getWritableDatabase();
 
@@ -493,7 +508,7 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 		return result;
 	}
 
-	public int numBssidSeen(String protocol, String BSSID) {
+    synchronized public int numBssidSeen(String protocol, String BSSID) {
 		String countQuery = "SELECT  COUNT(*) FROM " + AttackEntry.TABLE_NAME 
 						+  " WHERE " + AttackEntry.TABLE_NAME + "." + AttackEntry.COLUMN_NAME_PROTOCOL + " = " + "'" + protocol + "'" 
 						+  " AND " + AttackEntry.TABLE_NAME + "." + AttackEntry.COLUMN_NAME_BSSID + " = " + "'" + BSSID + "'";
@@ -1012,12 +1027,21 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 		db.close();
 	}
 
+    /**
+     * Updates sync devices
+     * @param devices array list of sync devices
+     */
     public synchronized void updateSyncDevices(ArrayList<SyncDevice> devices){
         SQLiteDatabase db = this.getWritableDatabase();
         this.updateSyncDevices(devices, db);
         db.close();
     }
 
+    /**
+     * Updates sync devices.
+     * @param devices array list of sync devices
+     * @param db sqlite database
+     */
     public synchronized void updateSyncDevices(ArrayList<SyncDevice> devices, SQLiteDatabase db){
         db.beginTransaction();
 
@@ -1046,6 +1070,7 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
         for (SyncDevice device : devices){
             deviceMap.put(device.getDeviceID(), device.getHighest_attack_id());
         }
+        deviceMap.put(SyncDevice.currentDevice().getDeviceID(), SyncDevice.currentDevice().getHighest_attack_id());
         SyncInfo syncInfo = new SyncInfo();
         syncInfo.deviceMap  = deviceMap;
         syncInfo.bssids = this.getAllBSSIDS();
@@ -1201,7 +1226,7 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 	public synchronized void deleteByBSSID(String bssid) {
 		SQLiteDatabase db = this.getWritableDatabase();
 		db.delete(NetworkEntry.TABLE_NAME, NetworkEntry.COLUMN_NAME_BSSID + " = ?", new String[] { bssid });
-		db.delete(AttackEntry.TABLE_NAME, AttackEntry.COLUMN_NAME_BSSID + " = ?", new String[] { bssid });
+		db.delete(AttackEntry.TABLE_NAME, AttackEntry.COLUMN_NAME_BSSID + " = ?", new String[]{bssid});
 		db.close();
 	}
 	
@@ -1227,11 +1252,36 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 	 */
 	public synchronized void deleteByAttackID(long attackID) {
 		SQLiteDatabase db = this.getWritableDatabase();
-		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.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();
 	}
 
+    public ArrayList<MessageRecord> getMessageRecords(AttackRecord attackRecord , SQLiteDatabase db){
+        ArrayList<MessageRecord> mr = new ArrayList<MessageRecord>();
+
+        String selectQuery = "SELECT  * FROM " + PacketEntry.TABLE_NAME + " WHERE " + PacketEntry.COLUMN_NAME_ATTACK_ID + " = " + attackRecord.getAttack_id();
+
+        boolean createdDB = false;
+        if (db == null){
+            db = this.getReadableDatabase();
+            createdDB = true;
+        }
+
+        Cursor cursor = db.rawQuery(selectQuery, null);
+
+        if (cursor.moveToFirst()) {
+            do {
+                MessageRecord record = createMessageRecord(cursor);
+                mr.add(record);
+            } while (cursor.moveToNext());
+        }
+        cursor.close();
+
+        if (createdDB) db.close();
+        return mr;
+    }
+
 	/**
 	 * Creates a {@link MessageRecord} from a Cursor. If the cursor does not show to a
 	 * valid data structure a runtime exception is thrown.
@@ -1280,31 +1330,12 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
      * @param cursor
      * @return Returns the created {@link SyncRecord} .
      */
-    private synchronized SyncRecord createSyncRecord(Cursor cursor){
-        SyncRecord record = new SyncRecord();
-        record.setAttack_id(cursor.getLong(0));
-        record.setProtocol(cursor.getString(1));
-        record.setExternalIP(cursor.getString(2));
-        record.setLocalIP(cursor.getString(3));
-        record.setLocalPort(Integer.parseInt(cursor.getString(4)));
-        record.setRemoteIP(cursor.getString(5));
-        record.setRemotePort(Integer.parseInt(cursor.getString(6)));
-        record.setWasInternalAttack(cursor.getInt(7) == 1);
-        record.setBssid(cursor.getString(8));
-        record.setSync_id(cursor.getLong(9));
-        record.setDevice(cursor.getString(10));
+    private synchronized SyncRecord createSyncRecord(Cursor cursor, SQLiteDatabase db){
+        AttackRecord attackRecord = this.createAttackRecord(cursor);
+        SyncRecord record = new SyncRecord(attackRecord);
 
-        record.setId(Integer.parseInt(cursor.getString(11)));
-        //record.setAttack_id(cursor.getLong(12));
-        String v = cursor.getString(13);
-        if (v != null && !v.equals("RECEIVE")) {
-            record.setType(TYPE.SEND);
-            //record.setType(MessageRecord.TYPE.valueOf(v));
-        } else {
-            record.setType(TYPE.RECEIVE);
-        }
-        record.setTimestamp(cursor.getLong(14));
-        record.setPacket(cursor.getString(15));
+        ArrayList<MessageRecord> mr = this.getMessageRecords(attackRecord,db);
+        record.setMessageRecords(mr);
 
         return record;
     }
@@ -1825,6 +1856,7 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
      * @param includeMissing boolean
      * @return array of {@link de.tudarmstadt.informatik.hostage.logging.SyncDevice}s
      */
+    /*
     public ArrayList<SyncDevice> getUpdatedDevicesFor(List<SyncDevice> oldDevices, boolean includeMissing){
 
         HashMap<String, Long> oldDeviceMap = new HashMap<String, Long>();
@@ -1859,7 +1891,7 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
         // return record list
         db.close();
         return recordList;
-    }
+    }*/
 
 
     /**
@@ -1875,11 +1907,20 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
         SQLiteDatabase db = this.getReadableDatabase();
         Cursor cursor = db.rawQuery(selectQuery, null);
 
+        boolean actualiseOwnDevice = false;
+        if (oldDeviceMap.keySet().contains(currentDevice().getDeviceID()) || includeMissing){
+            actualiseOwnDevice = true;
+        }
+
         // looping through all rows and adding to list
         if (cursor.moveToFirst()) {
             do {
                 SyncDevice record = createSyncDevice(cursor);
                 // Adding record to list
+
+                if (currentDevice().getDeviceID().equals(record.getDeviceID()) && actualiseOwnDevice)
+                    record.setHighest_attack_id(currentDevice().getHighest_attack_id());
+
                 if (oldDeviceMap.containsKey(record.getDeviceID())){
                     Long oldSyncId = oldDeviceMap.get(record.getDeviceID());
                     if (oldSyncId < record.getHighest_attack_id()){
@@ -1889,6 +1930,7 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
                     if (includeMissing)
                         recordList.add(record);
                 }
+
             } while (cursor.moveToNext());
         }
         cursor.close();
@@ -1965,12 +2007,13 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
         for (SyncDevice sDevice : updatedDevices){
             String deviceID = sDevice.getDeviceID();
             Long maxID = deviceMap.get(deviceID);
-            String selectQuery = "SELECT * FROM " + AttackEntry.TABLE_NAME + " A " + " , " + PacketEntry.TABLE_NAME + " P "
+            long checkId = -1;
+            if (maxID != null) checkId = maxID.longValue();
+            String selectQuery = "SELECT * FROM " + AttackEntry.TABLE_NAME + " A "
                     + " WHERE "
                     +" ( "
-                    + "A." + AttackEntry.COLUMN_NAME_ATTACK_ID + " = " + " P."+ PacketEntry.COLUMN_NAME_ATTACK_ID
-                    + " AND " + " A." + AttackEntry.COLUMN_NAME_DEVICE + " = " + "'" + deviceID + "'"
-                    + " AND " + " A." + AttackEntry.COLUMN_NAME_SYNC_ID + " > " + maxID
+                    + " A." + AttackEntry.COLUMN_NAME_DEVICE + " = " + "'" + deviceID + "'"
+                    + " AND " + " A." + AttackEntry.COLUMN_NAME_SYNC_ID + " > " + checkId
                     + " ) "
                     //+ " GROUP BY " + AttackEntry.TABLE_NAME + "." + AttackEntry.COLUMN_NAME_DEVICE
                     + " ORDER BY " + " A" + "." + AttackEntry.COLUMN_NAME_SYNC_ID + " DESC ";
@@ -1980,7 +2023,7 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
             if (cursor != null){
                 if (cursor.moveToFirst()) {
                     do {
-                        SyncRecord record = createSyncRecord(cursor);
+                        SyncRecord record = createSyncRecord(cursor , db);
                         recordList.add(record);
                     } while (cursor.moveToNext());
                 }
@@ -2002,7 +2045,7 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 
         String filterQuery = this.selectionQueryFromFilter(filter, AttackEntry.COLUMN_NAME_ATTACK_ID);
 
-        String attackPerBSSID_Query = "SELECT " + NetworkEntry.COLUMN_NAME_BSSID + " , " + "COUNT( " + AttackEntry.COLUMN_NAME_ATTACK_ID + "  ) " + " "
+        String attackPerBSSID_Query = "SELECT " + NetworkEntry.TABLE_NAME + "." + NetworkEntry.COLUMN_NAME_BSSID + " , " + "COUNT( " + AttackEntry.COLUMN_NAME_ATTACK_ID + "  ) " + " "
                 + " FROM " + AttackEntry.TABLE_NAME + " a " + " , " + NetworkEntry.TABLE_NAME
                 + " WHERE " + " a." + AttackEntry.COLUMN_NAME_ATTACK_ID + " IN " + " ( " + filterQuery + " ) "
                 + " GROUP BY " + NetworkEntry.TABLE_NAME + "." + NetworkEntry.COLUMN_NAME_BSSID;

+ 1 - 1
src/de/tudarmstadt/informatik/hostage/sync/Synchronizer.java

@@ -175,7 +175,7 @@ public class Synchronizer {
     private ArrayList<SyncRecord> getUnsyncedRecords(SyncInfo si){
 
         if (si.deviceMap != null){
-            return this.dbh.getUnsyncedAttacksFor(si.deviceMap, false);
+            return this.dbh.getUnsyncedAttacksFor(si.deviceMap, true);
         }
         return new ArrayList<SyncRecord>();
     }

+ 37 - 7
src/de/tudarmstadt/informatik/hostage/sync/bluetooth/BluetoothSyncActivity.java

@@ -17,6 +17,7 @@ import android.view.View;
 import android.widget.AdapterView;
 import android.widget.ArrayAdapter;
 import android.widget.ListView;
+import android.widget.ProgressBar;
 import android.widget.TextView;
 import android.widget.AdapterView.OnItemClickListener;
 import de.tudarmstadt.informatik.hostage.R;
@@ -34,8 +35,9 @@ public class BluetoothSyncActivity extends Activity{
 	public static final int CONNECTING = 0x0;
     public static final int CONNECTION_ESTABLISHED = 0x1;
     public static final int CONNECTION_FAILED = 0x2;
-    public static final int SYNC_SUCCESSFUL = 0x3;
-    public static final int SYNC_FAILED = 0x4;
+    public static final int SYNC_START = 0x3;
+    public static final int SYNC_SUCCESSFUL = 0x4;
+    public static final int SYNC_FAILED = 0x5;
     
     public static UUID serviceUUID;
 	
@@ -49,6 +51,7 @@ public class BluetoothSyncActivity extends Activity{
 	
 	private TextView mInfoText;
 	private ListView listView;
+    private ProgressBar progressBar;
 
 
 	@Override
@@ -213,6 +216,8 @@ public class BluetoothSyncActivity extends Activity{
 	 */
 	private void setLayoutElement(){
 		mInfoText = (TextView) findViewById(R.id.bluetoothInfoText);
+        progressBar = (ProgressBar) findViewById(R.id.bluetoothProgressBar);
+
 		listView = (ListView) findViewById(R.id.bluetoothListView);
 		listView.setAdapter(arrayAdapter);
 		listView.setOnItemClickListener(new OnItemClickListener() {
@@ -239,7 +244,16 @@ public class BluetoothSyncActivity extends Activity{
 			serverThread.cancel();
 		}
 	}
-	
+
+    protected void setResultIntent(int result, boolean doFinish){
+        Intent intent = new Intent();
+        intent.putExtra("result", result);
+
+        setResult(result, intent);
+
+        if(doFinish) finish();
+    }
+
 	/**
 	 * Handles message sent from the background threads and updates UI.
 	 */
@@ -250,22 +264,38 @@ public class BluetoothSyncActivity extends Activity{
         	switch(msg.what){
         		case CONNECTING:       
         			listView.setVisibility(View.GONE);
-        			mInfoText.setText("Connecting to " + (String)msg.obj + "!");
+                    progressBar.setVisibility(View.VISIBLE);
+        			mInfoText.setText("Connecting to " + (String)msg.obj + "...");
         			break;
         		case CONNECTION_ESTABLISHED: 
         			BluetoothSocket socket = (BluetoothSocket) msg.obj;
         			manageConnectedSocket(socket);
         			break;
+                case SYNC_START:
+                    progressBar.setVisibility(View.VISIBLE);
+                    mInfoText.setText("Synchronizing data...");
+                    break;
         		case CONNECTION_FAILED: 
         			mInfoText.setText("Failed to connect to device!");
+                    progressBar.setVisibility(View.GONE);
+
+                    BluetoothSyncActivity.this.setResultIntent(SYNC_SUCCESSFUL, false);
+
         			break;
         		case SYNC_SUCCESSFUL: 
-        			mInfoText.setText("Synchronization successfull!");
-        			break;	
+        			mInfoText.setText("Synchronization successful!");
+                    progressBar.setVisibility(View.GONE);
+
+                    BluetoothSyncActivity.this.setResultIntent(SYNC_SUCCESSFUL, true);
+
+                    break;
         		case SYNC_FAILED: 
         			commThread.cancel();
         			mInfoText.setText("Synchronization failed!");
-        			break;	
+                    progressBar.setVisibility(View.GONE);
+
+                    BluetoothSyncActivity.this.setResultIntent(SYNC_FAILED, false);
+                    break;
         	}        		
         }
 	};

+ 1 - 8
src/de/tudarmstadt/informatik/hostage/sync/bluetooth/CommunicationThread.java

@@ -99,27 +99,20 @@ public class CommunicationThread extends Thread {
 		Log.i("CommunicationThread", "Recieved: " + message.getMessage_code());
 		switch(message.getMessage_code()){
 			case SyncMessage.SYNC_REQUEST:
+                mHandler.obtainMessage(BluetoothSyncActivity.SYNC_START).sendToTarget();
                 SyncInfo thisSyncInfo = synchronizer.getSyncInfo();
 
-                System.out.println("----------------------- Sent: " + Arrays.toString(thisSyncInfo.bssids.toArray()));
                 write(new SyncMessage(SyncMessage.SYNC_RESPONSE_INFO, thisSyncInfo));
 				break;			
 			case SyncMessage.SYNC_RESPONSE_INFO:
                 SyncInfo otherSyncInfo = (SyncInfo) message.getPayload();
 
-                System.out.println("----------------------- Received: " + Arrays.toString(otherSyncInfo.bssids.toArray()));
-                System.out.println("----------------------- Received: " + otherSyncInfo.deviceMap.toString());
-
                 SyncData thisSyncData = synchronizer.getSyncData(otherSyncInfo);
                 write(new SyncMessage(SyncMessage.SYNC_RESPONSE_DATA, thisSyncData));
 
 				break;
             case SyncMessage.SYNC_RESPONSE_DATA:
                 SyncData otherData = (SyncData) message.getPayload();
-
-                System.out.println("----------------------- Received: " + otherData.syncRecords.toString());
-                System.out.println("----------------------- Received: " + otherData.networkRecords.toString());
-
                 synchronizer.updateFromSyncData(otherData);
 
                 mHandler.obtainMessage(BluetoothSyncActivity.SYNC_SUCCESSFUL).sendToTarget();

+ 2 - 2
src/de/tudarmstadt/informatik/hostage/sync/p2p/P2PSyncActivity.java

@@ -88,9 +88,9 @@ public class P2PSyncActivity extends Activity implements WifiP2pManager.GroupInf
         //mTxtP2PHeader = (TextView) findViewById(R.id.txtP2PHeader);
         //mTxtP2PSubHeader = (TextView) findViewById(R.id.txtP2PSubheader);
         //mTxtP2PHelpBack = (TextView) findViewById(R.id.txtP2PHelpBack);
-        mViewAnimator = (ViewAnimator) findViewById(R.id.viewAnimator);
+        //mViewAnimator = (ViewAnimator) findViewById(R.id.viewAnimator);
         mDevicesContainer = (RelativeLayout) findViewById(R.id.devicesContainer);
-        mWelcomeContainer = (RelativeLayout) findViewById(R.id.welcomeContainer);
+        //mWelcomeContainer = (RelativeLayout) findViewById(R.id.welcomeContainer);
         mTxtP2PSearchProgress = (TextView) findViewById(R.id.txtP2PSearchProgress);
         mLstP2PDevices = (ListView) findViewById(R.id.lstP2PDevices);
         //mBtnP2PSearch = (Button) findViewById(R.id.btnP2PSearch);

+ 100 - 52
src/de/tudarmstadt/informatik/hostage/sync/tracing/TracingSyncService.java

@@ -3,11 +3,16 @@ package de.tudarmstadt.informatik.hostage.sync.tracing;
 import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStreamReader;
+import java.io.OutputStream;
 import java.io.OutputStreamWriter;
+import java.io.StringWriter;
+import java.io.Writer;
 import java.net.HttpURLConnection;
 import java.net.URL;
 import java.security.KeyStore;
 import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
 
 import org.apache.http.HttpResponse;
 import org.apache.http.HttpVersion;
@@ -37,9 +42,11 @@ import android.os.ResultReceiver;
 import android.preference.PreferenceManager;
 import android.util.Log;
 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.net.MySSLSocketFactory;
 import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
+import de.tudarmstadt.informatik.hostage.ui.model.LogFilter;
 
 /**
  * Service that synchronizes with a specified remote server.
@@ -59,6 +66,8 @@ public class TracingSyncService extends IntentService {
 	public static final int RECORD_UPLOADED = 0x00;
 	public static final int SYNC_COMPLETE = 0x01;
 
+    public static Map<String, Integer> protocolsTypeMap;
+
 	private HttpClient httpClient;
 	private ResultReceiver receiver;
 
@@ -67,6 +76,19 @@ public class TracingSyncService extends IntentService {
 	SharedPreferences pref;
 	Editor editor;
 
+    static {
+        protocolsTypeMap = new HashMap<String, Integer>();
+        protocolsTypeMap.put("ECHO", 10);
+        protocolsTypeMap.put("FTP", 0);
+        protocolsTypeMap.put("GHOST", 0);
+        protocolsTypeMap.put("HTTP", 0);
+        protocolsTypeMap.put("HTTPS", 0);
+        protocolsTypeMap.put("MySQL", 31);
+        protocolsTypeMap.put("SIP", 50);
+        protocolsTypeMap.put("SMB", 40);
+        protocolsTypeMap.put("TELNET", 0);
+    }
+
 	public TracingSyncService() {
 		super(TracingSyncService.class.getName());
 
@@ -105,65 +127,91 @@ public class TracingSyncService extends IntentService {
 	 * Uploads all new Records to a server, specified in the settings.
 	 */
 	private void syncNewRecords() {
-		int lastUploadedAttackId = pref.getInt("LAST_UPLOADED_ATTACK_ID", -1);
-		// String serverAddress = pref.getString("pref_upload",
-		// "https://ssi.cased.de");
-		String serverAddress = "http://87.230.23.240/hostage/push.php";
-		ArrayList<NetworkRecord> recordList = dbh.getNetworkInformation();
+        long lastSyncTime = pref.getLong("LAST_SYNC_TIME", 0);
+
+		String serverAddress = pref.getString("pref_upload", "https://ssi.cased.de"); //"https://192.168.1.118:9999"
+
+        LogFilter filter = new LogFilter();
+        filter.setAboveTimestamp(lastSyncTime);
+
+        ArrayList<Record> records = dbh.getRecordsForFilter(filter);
+        StringWriter writer = new StringWriter();
 
-		int size = recordList.size();
+		int size = records.size();
 		int offset = 1;
-		for (NetworkRecord record : recordList) {
-			boolean success = uploadSingleRecord(record, serverAddress);
-			Log.i("Tracing upload", "Upload of record: " + offset + "/" + size + ((success) ? " successful." : " failed."));
-			if (receiver != null) {
-				Bundle data = new Bundle();
-				data.putInt(UPLOAD_SIZE, size);
-				data.putInt(UPLOAD_PROGRESS, offset);
-				receiver.send(RECORD_UPLOADED, data);
-			}
-			offset++;
+        int currOffset = 1;
+		for (Record record : records) {
+            appendRecordToStringWriter(record, writer);
 
-			// TODO pull
-			// getRemoteData(record.getBssid(), record.getTimestamp());
-		}
-	}
+            if(currOffset == 5 || offset == size){
+                boolean success = uploadRecordsToServer(writer.toString(), serverAddress);
+                Log.i("Tracing upload", "Upload of record: " + offset + "/" + size + ((success) ? " successful." : " failed."));
+                if (receiver != null) {
+                    Bundle data = new Bundle();
+                    data.putInt(UPLOAD_SIZE, size);
+                    data.putInt(UPLOAD_PROGRESS, offset);
+                    receiver.send(RECORD_UPLOADED, data);
+                }
 
-	/**
-	 * Uploads a single Record to a server, specified in the settings.
-	 * 
-	 * @param record
-	 *            The Record to upload.
-	 * @serverAddress Address of the target server
-	 * @return True if the upload was successful, else false.
-	 */
-	private boolean uploadSingleRecord(NetworkRecord record, String serverAddress) {
-		// Create a https client. Uses MySSLSocketFactory to accept all
-		// certificates
-		HttpPost httppost;
-		try {
-			httpClient = createHttpClient();
-			// Create HttpPost
-			httppost = new HttpPost(serverAddress);
-			// Create JSON String of Record
-			// TODO StringEntity se = new
-			// StringEntity(record.toString(TraCINgFormatter.getInstance()));
-			String s = record.toJSON();
-			StringEntity se = new StringEntity("record=" + record.toJSON());
-			httppost.addHeader("content-type", "application/x-www-form-urlencoded");
-			httppost.setEntity(se);
-			// Execute HttpPost
-			HttpResponse response = httpClient.execute(httppost);
-            // TODO Does it make sense to update the network record after a commit?
-			getRemoteData(record.getBssid(), record.getTimestampLocation());
-			Log.i("TracingSyncService", "Status Code: " + response.getStatusLine().getStatusCode());
-		} catch (Exception e) {
-			e.printStackTrace();
-			return false;
+                writer.getBuffer().setLength(0);
+                currOffset = 0;
+            }
+
+            offset++;
+            currOffset++;
 		}
-		return true;
+
+        pref.edit().putLong("LAST_SYNC_TIME", System.currentTimeMillis()).apply();
 	}
 
+    private void appendRecordToStringWriter(Record record, Writer stream){
+        try {
+            stream.append(
+                "{" +
+                    "\"sensor\":{" +
+                        "\"name\":\"HosTaGe\"," +
+                        "\"type\":\"Honeypot\"" +
+                    "}," +
+                    "\"src\":{" +
+                        "\"ip\":\"" + record.getRemoteIP() + "\"," +
+                        "\"port\":" + record.getRemotePort() +
+                    "}," +
+                    "\"dst\":{" +
+                        "\"ip\":\"" + record.getExternalIP() /*record.getLocalIP()*/ + "\"," +
+                        "\"port\":" + record.getLocalPort() +
+                    "}," +
+                    "\"type\":" + (protocolsTypeMap.containsKey(record.getProtocol()) ? protocolsTypeMap.get(record.getProtocol()) : 0) + "," +
+                    "\"log\":\"" + record.getProtocol() + "\"," +
+                    "\"md5sum\":\"\"," +
+                    "\"date\":" + (int)(record.getTimestamp() / 1000) +
+                "}\n"
+            );
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+    }
+
+    private boolean uploadRecordsToServer(String entity, String serverAddress){
+        HttpPost httppost;
+        try {
+            httpClient = createHttpClient();
+            // Create HttpPost
+            httppost = new HttpPost(serverAddress);
+
+            StringEntity se = new StringEntity(entity);
+            httppost.addHeader("content-type", "application/json+newline");
+            httppost.setEntity(se);
+
+            // Execute HttpPost
+            HttpResponse response = httpClient.execute(httppost);
+            Log.i("TracingSyncService", "Status Code: " + response.getStatusLine().getStatusCode());
+        } catch (Exception e) {
+            e.printStackTrace();
+            return false;
+        }
+        return true;
+    }
+
 	/**
 	 * Gets the data from the server and updates the database.
 	 */

+ 77 - 0
src/de/tudarmstadt/informatik/hostage/sync/wifi_direct/BackgroundTask.java

@@ -0,0 +1,77 @@
+package de.tudarmstadt.informatik.hostage.sync.wifi_direct;
+
+import android.os.AsyncTask;
+
+
+/**
+ * Created by Julien on 07.01.2015.
+ */
+public class BackgroundTask extends AsyncTask<Void, Void, String> {
+
+    public interface BackgroundTaskCompletionListener {
+        public void didSucceed();
+        public void didFail();
+    }
+
+    private boolean isInterrupted;
+
+    public void interrupt(boolean b){
+        this.isInterrupted = b;
+    }
+
+    public boolean isInterrupted() {
+        return isInterrupted;
+    }
+
+    private BackgroundTaskCompletionListener completion_listener;
+
+    public BackgroundTask(BackgroundTaskCompletionListener l){
+        super();
+        this.completion_listener = l;
+    }
+
+    public void setInterrupted(boolean isInterrupted) {
+        this.isInterrupted = isInterrupted;
+    }
+
+
+
+    public boolean performInBackground(){
+        return true;
+    }
+
+    @Override
+    protected String doInBackground(Void... params) {
+        boolean success = this.performInBackground();
+
+        if (this.completion_listener != null) {
+            if (success){
+                this.completion_listener.didSucceed();
+            }else {
+                this.completion_listener.didFail();
+            }
+        }
+
+        return null;
+    }
+
+    /*
+     * (non-Javadoc)
+     * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
+     */
+    @Override
+    protected void onPostExecute(String result) {
+
+    }
+
+    /*
+     * (non-Javadoc)
+     * @see android.os.AsyncTask#onPreExecute()
+     */
+    @Override
+    protected void onPreExecute() {
+
+
+    }
+
+}

+ 275 - 0
src/de/tudarmstadt/informatik/hostage/sync/wifi_direct/WiFiP2pBroadcastReceiver.java

@@ -0,0 +1,275 @@
+package de.tudarmstadt.informatik.hostage.sync.wifi_direct;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.net.NetworkInfo;
+import android.net.wifi.WpsInfo;
+import android.net.wifi.p2p.WifiP2pConfig;
+import android.net.wifi.p2p.WifiP2pDevice;
+import android.net.wifi.p2p.WifiP2pDeviceList;
+import android.net.wifi.p2p.WifiP2pInfo;
+import android.net.wifi.p2p.WifiP2pManager;
+import android.util.Log;
+
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Created by Julien on 07.01.2015.
+ */
+public class WiFiP2pBroadcastReceiver extends BroadcastReceiver implements WifiP2pManager.PeerListListener, WifiP2pManager.ConnectionInfoListener {
+
+    public interface WiFiP2pBroadcastListener {
+        public void discoveredDevices(List<WifiP2pDevice> peers);
+        public void wifiP2pIsEnabled(boolean enabled);
+        public void didConnect(boolean isHost, WifiP2pInfo connectionInfo);
+        public void failedToConnect();
+        public void didDisconnect();
+        public void failedToDisconnect();
+        public void deviceIsUpdated(WifiP2pDevice device);
+    }
+
+    private WifiP2pManager manager;
+    private WifiP2pManager.Channel channel;
+
+    private android.net.NetworkInfo.DetailedState networkState = null;
+    //private WifiP2pManager.PeerListListener peerListListener;
+    //private WifiP2pManager.ConnectionInfoListener connectionInfoListener;
+
+    static boolean setIsWifiP2pEnabled;
+
+    static boolean isConnected = false;
+
+    private WiFiP2pBroadcastListener eventListener;
+
+    /**
+     * @param manager WifiP2pManager system service
+     * @param channel Wifi p2p channel
+     * @param listener WiFiP2pBroadcastListener
+     */
+    public WiFiP2pBroadcastReceiver(WifiP2pManager manager,
+                                    WifiP2pManager.Channel channel,
+                                    WiFiP2pBroadcastListener listener) {
+        super();
+        this.manager = manager;
+        this.channel = channel;
+        this.eventListener = listener;
+    }
+
+    /*
+     * (non-Javadoc)
+     * @see android.content.BroadcastReceiver#onReceive(android.content.Context,
+     * android.content.Intent)
+     */
+    @Override
+    public void onReceive(Context context, Intent intent) {
+        String action = intent.getAction();
+        if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
+
+            // UI update to indicate wifi p2p status.
+            int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
+            if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
+                // Wifi Direct mode is enabled
+                setIsWifiP2pEnabled = (true);
+            } else {
+                setIsWifiP2pEnabled =(false);
+            }
+            this.eventListener.wifiP2pIsEnabled(setIsWifiP2pEnabled);
+
+        } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
+            // THE DEVICE LIST CHANGED
+            // REQUEST THE LIST OF DEVICES
+            Log.d("WiFiP2pBroadcastReceiver", "P2P peers changed.");
+            if (manager != null) {
+                manager.requestPeers(channel, this);
+            }
+        } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
+
+            if (manager == null) {
+                return;
+            }
+
+            NetworkInfo networkInfo = (NetworkInfo) intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
+
+            if (networkInfo.isConnected()) {
+                isConnected = true;
+                // we are connected with the other device, request connection
+                // info to find group owner IP
+                manager.requestConnectionInfo(channel, this);
+            } else {
+                if (networkInfo.getDetailedState() == android.net.NetworkInfo.DetailedState.DISCONNECTED){
+                    isConnected = false;
+                }
+                if (this.networkState != null && !this.networkState.equals(networkInfo.getDetailedState()) && networkInfo.getDetailedState() == android.net.NetworkInfo.DetailedState.DISCONNECTED){
+                    // It's a disconnect
+                    this.eventListener.didDisconnect();
+                }
+            }
+            if (this.networkState != networkInfo.getDetailedState()){
+                Log.d("WiFiP2pBroadcastReceiver", "P2P device network state changed to " + this.getDeviceNetworkStatus(networkInfo.getDetailedState()) + ".");
+            }
+            this.networkState = networkInfo.getDetailedState();
+        } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
+            WifiP2pDevice device = intent.getParcelableExtra( WifiP2pManager.EXTRA_WIFI_P2P_DEVICE);
+            this.eventListener.deviceIsUpdated(device);
+        }
+    }
+
+
+    // CONNECTION TO A DEVICE
+    // ConnectionInfoListener
+    @Override
+    public void onConnectionInfoAvailable(final WifiP2pInfo info) {
+
+        //
+        // The owner IP is now known.
+        //boolean thisDeviceIsHost = info.isGroupOwner;
+        // InetAddress from WifiP2pInfo struct.
+        //String ownerIP = info.groupOwnerAddress.getHostAddress();
+
+        // After the group negotiation, we assign the group owner as the file
+        // server. The file server is single threaded, single connection server
+        // socket.
+
+        if (info.groupFormed){
+            if (info.isGroupOwner) {
+                //new FileServerAsyncTask(getActivity(), mContentView.findViewById(R.id.status_text)).execute();
+            } else  {
+                // The other device acts as the client. In this case, we enable the
+                // get file button.
+            }
+            this.eventListener.didConnect(info.isGroupOwner, info);
+        }
+    }
+
+    // AVAILABLE DEVICES
+    // PEERLISTLISTENER
+    @Override
+    public void onPeersAvailable(WifiP2pDeviceList peerList) {
+
+        List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
+        peers.addAll(peerList.getDeviceList());
+
+        if (peers.size() == 0) {
+            Log.d("WiFiP2pBroadcastReceiver", "No devices found");
+        }
+
+        this.eventListener.discoveredDevices(peers);
+        // DISMISS PROGRESS IF NEEDED
+    }
+
+
+    public void connect(WifiP2pDevice device){
+        WifiP2pConfig config = new WifiP2pConfig();
+        config.deviceAddress = device.deviceAddress;
+        config.wps.setup = WpsInfo.PBC;
+        manager.connect(channel, config, new WifiP2pManager.ActionListener() {
+            private WiFiP2pBroadcastListener eventListener;
+            @Override
+            public void onSuccess() {
+                isConnected = true;
+                // WiFiDirectBroadcastReceiver will notify us. Ignore for now.
+            }
+
+            @Override
+            public void onFailure(int reason) {
+                this.eventListener.failedToConnect();
+            }
+
+            public WifiP2pManager.ActionListener init(WiFiP2pBroadcastListener eventListener){
+                this.eventListener = eventListener;
+                return this;
+            }
+        }.init(this.eventListener));
+    }
+
+    public void disconnect() {
+        if (isConnected){
+            manager.removeGroup(channel, new WifiP2pManager.ActionListener() {
+                private WiFiP2pBroadcastListener eventListener;
+
+                @Override
+                public void onFailure(int reasonCode) {
+                    this.eventListener.failedToDisconnect();
+                }
+
+                @Override
+                public void onSuccess() {
+                    isConnected = false;
+                    this.eventListener.didDisconnect();
+                }
+
+                public WifiP2pManager.ActionListener init(WiFiP2pBroadcastListener eventListener){
+                    this.eventListener = eventListener;
+                    return this;
+                }
+            }.init(this.eventListener));
+        }
+    }
+
+    public void discoverDevices(){
+        manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {
+            @Override
+            public void onSuccess() {
+                Log.d("WiFiP2pBroadcastReceiver", " Discovering Peers initiated.");
+            }
+            @Override
+            public void onFailure(int reasonCode) {
+                Log.d("WiFiP2pBroadcastReceiver", " Discovering Peers failed. c="+reasonCode);
+            }
+        });
+    }
+
+
+    private String getDeviceNetworkStatus(android.net.NetworkInfo.DetailedState deviceStatus) {
+        switch (deviceStatus) {
+            case DISCONNECTED: {
+                return "Disconnected";
+            }
+            case AUTHENTICATING:
+            {
+                return "Authenticating";
+            }
+            case BLOCKED:
+            {
+                return "Blocked";
+            }
+            case CONNECTED: {
+                return "CONNECTED";
+            }
+            case CONNECTING:
+            {
+                return "Connecting";
+            }
+            case DISCONNECTING:
+            {
+                return "Disconnecting";
+            }
+            case FAILED:
+            {
+                return "Failed";
+            }
+            case IDLE:
+            {
+                return "IDLE";
+            }
+            case OBTAINING_IPADDR:
+            {
+                return "Obtaining IPADDR";
+            }
+            case SCANNING:
+            {
+                return "Scanning";
+            }
+            case SUSPENDED:
+            {
+                return "Suspended";
+            }
+            default: {
+                return "Unknown";
+            }
+        }
+    }
+}

+ 145 - 0
src/de/tudarmstadt/informatik/hostage/sync/wifi_direct/WiFiP2pClientTask.java

@@ -0,0 +1,145 @@
+package de.tudarmstadt.informatik.hostage.sync.wifi_direct;
+
+import android.util.Log;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+
+/**
+ * Created by Julien on 07.01.2015.
+ */
+public class WiFiP2pClientTask extends BackgroundTask {
+
+
+
+    private String hostIP;
+    private Socket socket;
+
+    public String getHostIP() {
+        return hostIP;
+    }
+
+    public void setHostIP(String hostIP) {
+        this.hostIP = hostIP;
+    }
+
+
+    public int port(){
+        return 8988;
+    }
+    public int time_out(){
+        return 1000;
+    }
+
+
+    public WiFiP2pClientTask(String hostIP, BackgroundTaskCompletionListener l){
+        super(l);
+        this.hostIP = hostIP;
+    }
+
+
+    @Override
+    public void interrupt(boolean b){
+        super.interrupt(b);
+        if (b && this.socket != null) {
+            try {
+                this.socket.close();
+            } catch (IOException e) {
+                Log.e("WiFiP2pClientTask", e.getMessage());
+            }
+        }
+    }
+
+    @Override
+    public boolean performInBackground(){
+        int tryNum = 1;
+        while (!this.isInterrupted()){
+            this.socket = new Socket();
+
+            try {
+                Log.d("WiFiP2pClientTask", "Opening client socket - ");
+                socket.bind(null);
+                socket.connect((new InetSocketAddress(hostIP, this.port())), this.time_out());
+
+                Log.d("WiFiP2pClientTask", "Client socket - " + socket.isConnected());
+                this.handleConnection(socket);
+
+                Log.d("WiFiP2pClientTask", "Client: Data written");
+            } catch (ClassNotFoundException e){
+                Log.e("WiFiP2pClientTask", e.getMessage());
+                return false;
+            } catch (IOException e) {
+                Log.e("WiFiP2pClientTask", e.getMessage());
+
+                if(this.isInterrupted()) {
+                    this.interrupt(true);
+                    break;
+                }
+
+                long seconds_to_wait = (long) Math.min(60, Math.pow(2, tryNum));
+                Log.i("WiFiP2pClientTask", "could not connect to server. Will try again in " + seconds_to_wait + "s");
+                try {
+                    Thread.sleep(seconds_to_wait * 1000);
+                } catch (InterruptedException ie){
+                    ie.printStackTrace();
+                }
+            } finally {
+                if (socket != null) {
+                    if (socket.isConnected()) {
+                        try {
+                            socket.close();
+                        } catch (IOException e) {
+                            // Give up
+                            e.printStackTrace();
+                            Log.d("WiFiP2p_Error"," Failed to close socket - "+ e.getLocalizedMessage());
+                            return false;
+                        }
+                    }
+                }
+            }
+        }
+        return true;
+    }
+
+
+
+    private void handleConnection(Socket client) throws IOException, ClassNotFoundException {
+
+        InputStream is = client.getInputStream();
+        ObjectInputStream ois = new ObjectInputStream(is);
+        OutputStream os = client.getOutputStream();
+        ObjectOutputStream oos = new ObjectOutputStream(os);
+
+        Object obj = null;
+
+        do {
+            WiFiP2pSerializableObject receivedObj = (  WiFiP2pSerializableObject) obj;
+            obj = null;
+            WiFiP2pSerializableObject toSend = this.handleReceivedObject(receivedObj);
+            if (toSend != null) {
+                oos.writeObject(toSend);
+                oos.flush();
+                oos.reset();
+                obj = ois.readObject();
+            }
+        } while (obj != null && obj instanceof WiFiP2pSerializableObject);
+
+        oos.close();
+        os.close();
+        ois.close();
+        is.close();
+
+        this.interrupt(true);
+    }
+
+    public WiFiP2pSerializableObject handleReceivedObject(WiFiP2pSerializableObject receivedObj){
+
+        return null;
+    }
+
+}

+ 86 - 0
src/de/tudarmstadt/informatik/hostage/sync/wifi_direct/WiFiP2pEventHandler.java

@@ -0,0 +1,86 @@
+package de.tudarmstadt.informatik.hostage.sync.wifi_direct;
+
+import android.app.Activity;
+import android.content.Context;
+import android.content.IntentFilter;
+import android.net.wifi.p2p.WifiP2pDevice;
+import android.net.wifi.p2p.WifiP2pManager;
+
+/**
+ * Created by Julien on 07.01.2015.
+ */
+public class WiFiP2pEventHandler implements WifiP2pManager.ChannelListener {
+
+    public interface WiFiP2pEventListener extends WiFiP2pBroadcastReceiver.WiFiP2pBroadcastListener{
+
+    }
+
+    private WifiP2pManager manager;
+
+    private boolean retryChannel = false;
+
+    private final IntentFilter intentFilter = new IntentFilter();
+    private WifiP2pManager.Channel channel;
+    private WiFiP2pBroadcastReceiver receiver = null;
+
+    private WiFiP2pEventListener eventListener;
+
+    private Activity activity;
+
+
+    public WiFiP2pEventHandler(Activity activity, WiFiP2pEventListener listener){
+        this.eventListener = listener;
+        this.activity = activity;
+        intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
+        intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
+        intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
+        intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
+
+        manager = (WifiP2pManager) activity.getSystemService(Context.WIFI_P2P_SERVICE);
+        channel = manager.initialize(activity, activity.getMainLooper(), this);
+
+        //receiver = new WiFiP2pBroadcastReceiver(manager, channel, this.eventListener);
+        //activity.registerReceiver(receiver, intentFilter);
+    }
+
+    public void onResume() {
+        if (receiver == null){
+            receiver = new WiFiP2pBroadcastReceiver(manager, channel, this.eventListener);
+            activity.registerReceiver(receiver, intentFilter);
+        }
+    }
+
+    public void onPause() {
+        if (receiver != null) {
+            activity.unregisterReceiver(receiver);
+            receiver = null;
+        }
+
+    }
+
+    @Override
+    public void onChannelDisconnected() {
+        // we will try once more
+        if (manager != null && !retryChannel) {
+            retryChannel = true;
+            manager.initialize(this.activity, this.activity.getMainLooper(), this);
+        } else {
+
+        }
+    }
+
+    public void connect(WifiP2pDevice device){
+        if (this.receiver != null)
+            this.receiver.connect(device);
+    }
+
+    public void disconnect() {
+        if (this.receiver != null)
+            this.receiver.disconnect();
+    }
+
+    public void discoverDevices(){
+        if (this.receiver != null)
+            this.receiver.discoverDevices();
+    }
+}

+ 29 - 0
src/de/tudarmstadt/informatik/hostage/sync/wifi_direct/WiFiP2pSerializableObject.java

@@ -0,0 +1,29 @@
+package de.tudarmstadt.informatik.hostage.sync.wifi_direct;
+
+import java.io.Serializable;
+
+/**
+ * Created by Julien on 07.01.2015.
+ */
+public class WiFiP2pSerializableObject implements Serializable {
+
+    private String methodName;
+
+    public Serializable getObjectToSend() {
+        return objectToSend;
+    }
+
+    public void setObjectToSend(Serializable objectToSend) {
+        this.objectToSend = objectToSend;
+    }
+
+    private Serializable objectToSend;
+
+    public void setMethodName(String m){
+        this.methodName = m;
+    }
+    public String getMethodName(){
+        return this.methodName;
+    }
+
+}

+ 104 - 0
src/de/tudarmstadt/informatik/hostage/sync/wifi_direct/WiFiP2pServerTask.java

@@ -0,0 +1,104 @@
+package de.tudarmstadt.informatik.hostage.sync.wifi_direct;
+
+import android.util.Log;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.OutputStream;
+import java.net.ServerSocket;
+import java.net.Socket;
+
+/**
+ * Created by Julien on 07.01.2015.
+ */
+public class WiFiP2pServerTask extends BackgroundTask {
+
+    private ServerSocket serverSocket;
+
+    @Override
+    public void interrupt(boolean b){
+        super.interrupt(b);
+        if (b && this.serverSocket != null) {
+            try {
+                this.serverSocket.close();
+            } catch (IOException e) {
+                Log.e("WiFiP2pServerTask", e.getMessage());
+            }
+        }
+    }
+
+    public WiFiP2pServerTask(BackgroundTaskCompletionListener l){
+        super(l);
+    }
+
+    @Override
+    public boolean performInBackground(){
+        while (!this.isInterrupted()){
+            try {
+                this.serverSocket = new ServerSocket(8988);
+                Log.d("WiFiP2pServerTask", "Server: Socket opened");
+                Socket client = this.serverSocket.accept();
+                Log.d("WiFiP2pServerTask", "Server: connection done");
+
+                this.handleConnection(client, this.serverSocket);
+
+                client.close();
+                serverSocket.close();
+
+                return true;
+            } catch (ClassNotFoundException e){
+                e.printStackTrace();
+                Log.e("WiFiP2pServerTask", e.getMessage());
+                return false;
+            } catch (IOException  e) {
+                e.printStackTrace();
+                Log.e("WiFiP2pServerTask", e.getMessage());
+                return false;
+            }
+        }
+        return true;
+    }
+
+
+
+    private void handleConnection(Socket client, ServerSocket server) throws IOException, ClassNotFoundException {
+        OutputStream os = client.getOutputStream();
+        ObjectOutputStream oos = new ObjectOutputStream(os);
+        oos.flush();
+
+        InputStream is = client.getInputStream();
+        ObjectInputStream ois = new ObjectInputStream(is);
+
+
+        Object obj = ois.readObject();
+
+        while (obj != null && obj instanceof WiFiP2pSerializableObject) {
+            WiFiP2pSerializableObject receivedObj = (  WiFiP2pSerializableObject) obj;
+            obj = null;
+            WiFiP2pSerializableObject toSend = this.handleReceivedObject(receivedObj);
+            if (toSend != null) {
+                oos.writeObject(toSend);
+                oos.flush();
+                oos.reset();
+            }
+            try {
+                obj = ois.readObject();
+            }catch (IOException e){
+                // IF NULL WAS TRANSMITTED
+                obj = null;
+            }
+        }
+
+        oos.close();
+        os.close();
+        ois.close();
+        is.close();
+    }
+
+    public WiFiP2pSerializableObject handleReceivedObject(WiFiP2pSerializableObject receivedObj){
+
+        return null;
+    }
+}

+ 74 - 0
src/de/tudarmstadt/informatik/hostage/sync/wifi_direct/sync_tasks/SyncClientTask.java

@@ -0,0 +1,74 @@
+package de.tudarmstadt.informatik.hostage.sync.wifi_direct.sync_tasks;
+
+import android.content.Context;
+import android.util.Log;
+
+import de.tudarmstadt.informatik.hostage.logging.SyncData;
+import de.tudarmstadt.informatik.hostage.logging.SyncInfo;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
+import de.tudarmstadt.informatik.hostage.sync.Synchronizer;
+import de.tudarmstadt.informatik.hostage.sync.wifi_direct.WiFiP2pClientTask;
+import de.tudarmstadt.informatik.hostage.sync.wifi_direct.WiFiP2pSerializableObject;
+
+
+
+/**
+ * Created by Julien on 14.01.2015.
+ */
+public class SyncClientTask extends WiFiP2pClientTask {
+
+    private HostageDBOpenHelper mdbh;
+    private Synchronizer synchronizer;
+
+    public SyncClientTask(String hostIP, BackgroundTaskCompletionListener l, Context context) {
+        super(hostIP, l);
+
+        mdbh = new HostageDBOpenHelper(context);
+        synchronizer = new Synchronizer(mdbh);
+    }
+
+    @Override
+    public WiFiP2pSerializableObject handleReceivedObject(WiFiP2pSerializableObject receivedObj) {
+
+        if (receivedObj == null) {
+            Log.i("WiFiP2p_Client", "Starting sync process: " + SyncHostTask.SYNC_INFO_REQUEST);
+            SyncInfo thisSyncInfo = synchronizer.getSyncInfo();
+            WiFiP2pSerializableObject syncObj = new WiFiP2pSerializableObject();
+
+            syncObj.setObjectToSend(thisSyncInfo);
+            syncObj.setMethodName(SyncHostTask.SYNC_INFO_REQUEST);
+
+            return syncObj;
+
+        } else {
+            Log.i("WiFiP2p_Client", "Received: " + receivedObj.getMethodName());
+            if (receivedObj.getMethodName().equals(SyncHostTask.SYNC_INFO_RESPONSE)) {
+                SyncInfo sinfo = (SyncInfo) receivedObj.getObjectToSend();
+
+                if (sinfo != null && (sinfo instanceof SyncInfo)) {
+                    Log.i("WiFiP2p_Client", "Sending Data: " + SyncHostTask.SYNC_DATA_REQUEST);
+                    SyncData syncData = synchronizer.getSyncData(sinfo);
+                    WiFiP2pSerializableObject syncObj = new WiFiP2pSerializableObject();
+
+                    syncObj.setObjectToSend(syncData);
+                    syncObj.setMethodName(SyncHostTask.SYNC_DATA_REQUEST);
+
+                    return syncObj;
+                }
+
+            } else if (receivedObj.getMethodName().equals(SyncHostTask.SYNC_DATA_RESPONSE)) {
+                Log.i("WiFiP2p_Client", "Received Sync Data - ending sync process successfully." );
+                SyncData sdata = (SyncData) receivedObj.getObjectToSend();
+
+                if (sdata != null && (sdata instanceof SyncData)) {
+                    synchronizer.updateFromSyncData(sdata);
+                }
+            }
+        }
+
+        // DISCONNECT
+        this.interrupt(true);
+
+        return null;
+    }
+}

+ 81 - 0
src/de/tudarmstadt/informatik/hostage/sync/wifi_direct/sync_tasks/SyncHostTask.java

@@ -0,0 +1,81 @@
+package de.tudarmstadt.informatik.hostage.sync.wifi_direct.sync_tasks;
+
+import android.content.Context;
+import android.util.Log;
+
+import de.tudarmstadt.informatik.hostage.logging.SyncData;
+import de.tudarmstadt.informatik.hostage.logging.SyncInfo;
+import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
+import de.tudarmstadt.informatik.hostage.sync.Synchronizer;
+import de.tudarmstadt.informatik.hostage.sync.wifi_direct.WiFiP2pSerializableObject;
+import de.tudarmstadt.informatik.hostage.sync.wifi_direct.WiFiP2pServerTask;
+
+/**
+ * Created by Julien on 14.01.2015.
+ */
+public class SyncHostTask extends WiFiP2pServerTask {
+
+
+    public static final String SYNC_INFO_REQUEST = "sync_info_request";
+    public static final String SYNC_INFO_RESPONSE = "sync_info_response";
+
+    public static final String SYNC_DATA_REQUEST = "sync_data_request";
+    public static final String SYNC_DATA_RESPONSE = "sync_data_response";
+
+    private HostageDBOpenHelper mdbh;
+    private Synchronizer synchronizer;
+
+    private SyncInfo receivedInfo;
+
+    public SyncHostTask(BackgroundTaskCompletionListener l , Context context) {
+        super(l);
+        mdbh = new HostageDBOpenHelper(context);
+        synchronizer = new Synchronizer(mdbh);
+    }
+
+    @Override
+    public WiFiP2pSerializableObject handleReceivedObject(WiFiP2pSerializableObject receivedObj){
+        if (receivedObj != null) {
+            Log.i("WiFiP2p_Host", "Received: " + receivedObj.getMethodName());
+
+            if (receivedObj.getMethodName().equals(SYNC_INFO_REQUEST)){
+                Log.i("WiFiP2p_Host", "Sending Sync Info: " + SYNC_INFO_RESPONSE);
+
+                this.receivedInfo = (SyncInfo) receivedObj.getObjectToSend();
+
+                SyncInfo response = synchronizer.getSyncInfo();
+                WiFiP2pSerializableObject syncObj = new WiFiP2pSerializableObject();
+
+                syncObj.setObjectToSend(response);
+                syncObj.setMethodName(SYNC_INFO_RESPONSE);
+
+                return syncObj;
+            }
+
+            if (receivedObj.getMethodName().equals(SYNC_DATA_REQUEST)){
+                Log.i("WiFiP2p_Host", "Sending Sync Data: " + SYNC_DATA_RESPONSE);
+
+                SyncData sdata = (SyncData) receivedObj.getObjectToSend();
+
+                if (sdata != null && sdata instanceof SyncData){
+                    synchronizer.updateFromSyncData(sdata);
+                }
+
+                if (this.receivedInfo != null){
+                    SyncData response = synchronizer.getSyncData(this.receivedInfo);
+
+                    WiFiP2pSerializableObject syncObj = new WiFiP2pSerializableObject();
+                    syncObj.setObjectToSend(response);
+                    syncObj.setMethodName(SYNC_DATA_RESPONSE);
+
+                    return syncObj;
+                }
+            }
+        }
+
+        Log.i("WiFiP2p_Host", "Stop Sync Process - Performing a disconnect.");
+        // DISCONNECT
+        this.interrupt(true);
+        return null;
+    }
+}

+ 426 - 0
src/de/tudarmstadt/informatik/hostage/sync/wifi_direct/ui/WiFiP2pSyncActivity.java

@@ -0,0 +1,426 @@
+package de.tudarmstadt.informatik.hostage.sync.wifi_direct.ui;
+
+import android.app.Activity;
+import android.content.Context;
+import android.net.wifi.p2p.WifiP2pDevice;
+import android.net.wifi.p2p.WifiP2pInfo;
+import android.os.Bundle;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.ArrayAdapter;
+import android.widget.ListView;
+import android.widget.RelativeLayout;
+import android.widget.TextView;
+import android.widget.Toast;
+import android.widget.ViewAnimator;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import de.tudarmstadt.informatik.hostage.R;
+import de.tudarmstadt.informatik.hostage.sync.wifi_direct.BackgroundTask;
+import de.tudarmstadt.informatik.hostage.sync.wifi_direct.WiFiP2pEventHandler;
+import de.tudarmstadt.informatik.hostage.sync.wifi_direct.sync_tasks.SyncClientTask;
+import de.tudarmstadt.informatik.hostage.sync.wifi_direct.sync_tasks.SyncHostTask;
+
+/**
+ * Created by Julien on 14.01.2015.
+ */
+public class WiFiP2pSyncActivity extends Activity implements AdapterView.OnItemClickListener {
+
+    private SyncClientTask clientTask;
+    private SyncHostTask  hostTask;
+    private boolean isHost;
+
+    private WiFiP2pEventHandler _wifiEventHandler = null;
+
+    private WiFiP2pEventHandler.WiFiP2pEventListener _p2pEventListener = null;
+    private BackgroundTask.BackgroundTaskCompletionListener _syncCompletionListener = null;
+
+
+    private TextView mTxtP2PDeviceName;
+    private TextView mTxtP2PDeviceStatus;
+    private ViewAnimator mViewAnimator;
+    private RelativeLayout mDevicesContainer;
+    private TextView mTxtP2PSearchProgress;
+    private ListView mLstP2PDevices;
+    private RelativeLayout mWelcomeContainer;
+    private TextView mTxtP2PNotAvailable;
+    private TextView mTxtP2PChangeDeviceName;
+
+    private WifiP2pDevice mDevice;
+    private WifiP2pDevice mOtherDevice;
+
+    private ArrayList<WifiP2pDevice> discoveredDevices = new ArrayList<WifiP2pDevice>();
+
+
+
+    public boolean isHost() {
+        return isHost;
+    }
+
+    public void setHost(boolean isHost) {
+        this.isHost = isHost;
+    }
+
+
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+
+        this.wifiEventHandler();
+
+        setContentView(R.layout.activity_p2_psync);
+
+        assert getActionBar() != null;
+        getActionBar().setTitle("WifiDirect Synchronization");
+
+        this.extractFromView();
+        this.registerListeners();
+
+    }
+
+    @Override
+    public void onResume() {
+        super.onResume();
+        this.wifiEventHandler().onResume();
+    }
+
+    @Override
+    public void onPause() {
+        this.wifiEventHandler().onPause();
+        super.onPause();
+    }
+
+    @Override
+    protected void onStart()
+    {
+        super.onStart();
+        this.wifiEventHandler().onResume();
+    }
+
+    @Override
+    protected void onStop()
+    {
+        this.wifiEventHandler().disconnect();
+        this.wifiEventHandler().onPause();
+        super.onStop();
+    }
+
+    @Override
+    protected void onDestroy(){
+        this.wifiEventHandler().onPause();
+        super.onDestroy();
+    }
+
+    private WiFiP2pEventHandler.WiFiP2pEventListener eventListener(){
+        if (_p2pEventListener == null){
+            _p2pEventListener = new WiFiP2pEventHandler.WiFiP2pEventListener() {
+                WiFiP2pSyncActivity activity = null;
+                public WiFiP2pEventHandler.WiFiP2pEventListener init(WiFiP2pSyncActivity act){
+                    this.activity = act;
+                    return this;
+                }
+
+                @Override
+                public void discoveredDevices(List<WifiP2pDevice> peers) {
+                    Log.d("WiFiP2pSyncActivity", "Actualise devices list" + ".");
+                    this.activity.updateDeviceListView(peers);
+                }
+
+                @Override
+                public void wifiP2pIsEnabled(boolean enabled) {
+                    String tmp = enabled? "enabled" : "disabled";
+                    Log.d("WiFiP2pSyncActivity", "Peer to peer is " + tmp + ".");
+                    this.activity.setWifiDirectAvailable(enabled);
+                }
+
+                @Override
+                public void didConnect(boolean isHost, WifiP2pInfo connectionInfo) {
+                    Log.d("WiFiP2pSyncActivity", "Did connect" + ".");
+                    this.activity.setHost(isHost);
+                    if (isHost){
+                        Log.d("WiFiP2pSyncActivity", "Connected as HOST" + ".");
+                        this.activity.startHost();
+                    } else {
+                        Log.d("WiFiP2pSyncActivity", "Connected as Client" + ".");
+                        this.activity.startClient(connectionInfo);
+                    }
+                }
+
+                @Override
+                public void failedToConnect() {
+                    Log.d("WiFiP2pSyncActivity", "Failed to connect" + ".");
+                    Toast.makeText(this.activity, "Could not connect to device. Retry.", Toast.LENGTH_LONG).show();
+                }
+
+                @Override
+                public void didDisconnect() {
+                    Log.d("WiFiP2pSyncActivity", "Did disconnect" + ".");
+
+                }
+
+                @Override
+                public void failedToDisconnect() {
+                    Log.d("WiFiP2pSyncActivity", "Failed to disconnect" + ".");
+                    Toast.makeText(this.activity, "Could not disconnect with device. Retry.", Toast.LENGTH_LONG).show();
+                }
+
+                @Override
+                public void deviceIsUpdated(WifiP2pDevice device) {
+                    Log.d("WiFiP2pSyncActivity", "Updated device " + device.deviceName + " " + device.deviceAddress + ".");
+                    this.activity.updateDevice(device);
+                    this.activity.searchForDevices();
+
+                }
+            }.init(this);
+        }
+
+        return _p2pEventListener;
+    }
+
+    private WiFiP2pEventHandler wifiEventHandler(){
+        if (this._wifiEventHandler == null){
+            this._wifiEventHandler = new WiFiP2pEventHandler(this, this.eventListener());
+        }
+        return this._wifiEventHandler;
+    }
+
+
+
+    private BackgroundTask.BackgroundTaskCompletionListener syncCompletionListener(){
+        if (_syncCompletionListener == null){
+            _syncCompletionListener = new BackgroundTask.BackgroundTaskCompletionListener() {
+                WiFiP2pSyncActivity activity = null;
+                public BackgroundTask.BackgroundTaskCompletionListener init(WiFiP2pSyncActivity act){
+                    this.activity = act;
+                    return this;
+                }
+                @Override
+                public void didSucceed() {
+                    this.activity.runOnUiThread(new Runnable() {
+                        private WiFiP2pSyncActivity activity;
+                        @Override
+                        public void run() {
+                            Toast.makeText(this.activity, "Synchronization complete.", Toast.LENGTH_SHORT).show();
+                            this.activity.wifiEventHandler().disconnect();
+                        }
+                        public Runnable init(WiFiP2pSyncActivity activity){
+                            this.activity = activity;
+                            return this;
+                        }
+                    }.init(this.activity));
+                }
+
+                @Override
+                public void didFail() {
+                    this.activity.runOnUiThread(new Runnable() {
+                        private WiFiP2pSyncActivity activity;
+                        @Override
+                        public void run() {
+                            Toast.makeText(this.activity, "Could not synchronize with device. Retry.", Toast.LENGTH_LONG).show();
+                            this.activity.wifiEventHandler().disconnect();
+                        }
+                        public Runnable init(WiFiP2pSyncActivity activity){
+                            this.activity = activity;
+                            return this;
+                        }
+                    }.init(this.activity));
+                }
+            }.init(this);
+        }
+        return _syncCompletionListener;
+    }
+
+
+    private void updateDeviceListView(List<WifiP2pDevice> peers){
+        mTxtP2PSearchProgress.setVisibility(View.GONE);
+
+        this.discoveredDevices = new ArrayList<WifiP2pDevice>();
+        this.discoveredDevices.addAll(peers);
+        WiFiPeerListAdapter listAdapter = (WiFiPeerListAdapter) this.mLstP2PDevices.getAdapter();
+        listAdapter.addItems(peers);
+        this.runOnUiThread(new Runnable() {
+            private ListView listView;
+
+            @Override
+            public void run() {
+                WiFiPeerListAdapter adapter = (WiFiPeerListAdapter) this.listView.getAdapter();
+                this.listView.setAdapter(null);
+                adapter.notifyDataSetChanged();
+                this.listView.setAdapter(adapter);
+            }
+
+            public Runnable init(ListView listview) {
+                this.listView = listview;
+                return this;
+            }
+        }.init(this.mLstP2PDevices));
+        Log.d("WiFiP2pSyncActivity", " Discovered "+peers.size()+" devices.");
+    }
+
+    private void startHost(){
+        Log.d("WiFiP2pSyncActivity", "Starting HOST Task" + ".");
+        Toast.makeText(this, "Acting as Host.", Toast.LENGTH_SHORT).show();
+        this.hostTask = new SyncHostTask(this.syncCompletionListener(), getApplicationContext());
+        this.hostTask.execute();
+    }
+
+    private void startClient(WifiP2pInfo info){
+        Log.d("WiFiP2pSyncActivity", "Starting CLIENT Task" + ".");
+        Toast.makeText(this, "Acting as Client.", Toast.LENGTH_SHORT).show();
+        this.clientTask = new SyncClientTask(info.groupOwnerAddress.getHostAddress(), this.syncCompletionListener(), getApplicationContext() );
+        this.clientTask.execute();
+    }
+
+
+    private static String getDeviceStatus(int deviceStatus) {
+        switch (deviceStatus) {
+            case WifiP2pDevice.AVAILABLE:
+                return "Available";
+            case WifiP2pDevice.INVITED:
+                return "Invited";
+            case WifiP2pDevice.CONNECTED:
+                return "Connected";
+            case WifiP2pDevice.FAILED:
+                return "Failed";
+            case WifiP2pDevice.UNAVAILABLE:
+                return "Unavailable";
+            default:
+                return "Unknown";
+        }
+    }
+
+
+    private void updateDevice(WifiP2pDevice device){
+        mTxtP2PDeviceName.setText(device.deviceName);
+        mTxtP2PDeviceStatus.setText(getDeviceStatus(device.status));
+        mDevice = device;
+    }
+
+    private void searchForDevices(){
+        mTxtP2PSearchProgress.setVisibility(View.VISIBLE);
+        this.wifiEventHandler().discoverDevices();
+    }
+
+    /********************** UI ************************/
+
+
+    public void setWifiDirectAvailable(boolean enabled){
+        if (enabled){
+            mTxtP2PNotAvailable.setVisibility(View.GONE);
+        } else {
+            mTxtP2PNotAvailable.setVisibility(View.VISIBLE);
+            ((WiFiPeerListAdapter) mLstP2PDevices.getAdapter()).notifyDataSetChanged();
+            mDevice = null;
+            this.updateDeviceListView(new ArrayList<WifiP2pDevice>());
+
+            Toast.makeText(this, "WiFi Direct P2P is disabled.", Toast.LENGTH_LONG).show();
+        }
+    }
+
+
+
+    private void extractFromView(){
+        this.mTxtP2PDeviceName = (TextView) findViewById(R.id.txt_p2p_device_name);
+        this.mTxtP2PDeviceStatus = (TextView) findViewById(R.id.txt_p2p_device_status);
+        this.mTxtP2PChangeDeviceName = (TextView) findViewById(R.id.txtP2PChangeDeviceName);
+
+        this.mViewAnimator = (ViewAnimator) findViewById(R.id.viewAnimator);
+        this.mDevicesContainer = (RelativeLayout) findViewById(R.id.devicesContainer);
+        this.mWelcomeContainer = (RelativeLayout) findViewById(R.id.welcomeContainer);
+        this.mTxtP2PSearchProgress = (TextView) findViewById(R.id.txtP2PSearchProgress);
+        this.mLstP2PDevices = (ListView) findViewById(R.id.lstP2PDevices);
+        this.mTxtP2PNotAvailable = (TextView) findViewById(R.id.txtP2PNotAvailable);
+    }
+
+    public void registerListeners(){
+        /*
+        mTxtP2PChangeDeviceName.setOnClickListener(new View.OnClickListener() {
+            @Override
+            public void onClick(View v) {
+                Method method1 = null;
+                try {
+                    method1 = mManager.getClass().getDeclaredMethod("setDeviceName", WifiP2pManager.Channel.class);
+                    method1.invoke(mManager, mChannel, "Android_fc546");
+                } catch (NoSuchMethodException e) {
+                    e.printStackTrace();
+                } catch (InvocationTargetException e) {
+                    e.printStackTrace();
+                } catch (IllegalAccessException e) {
+                    e.printStackTrace();
+                }
+            }
+        });*/
+
+        if (this.mLstP2PDevices.getOnItemClickListener() != this)
+            this.mLstP2PDevices.setOnItemClickListener(this);
+
+        if (this.mLstP2PDevices.getAdapter() == null){
+            this.discoveredDevices = new ArrayList();
+            WiFiPeerListAdapter listAdapter = new WiFiPeerListAdapter(this, R.layout.row_devices, this.discoveredDevices);
+            this.mLstP2PDevices.setAdapter(listAdapter);
+        }
+    }
+
+
+    @Override
+    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
+        final WifiP2pDevice device = (WifiP2pDevice) this.mLstP2PDevices.getAdapter().getItem(position);
+        this.wifiEventHandler().connect(device);
+        mOtherDevice = device;
+    }
+
+
+    /**
+     * Array adapter for ListFragment that maintains WifiP2pDevice list.
+     */
+    private class WiFiPeerListAdapter extends ArrayAdapter<WifiP2pDevice> {
+        private List<WifiP2pDevice> items;
+        /**
+         * @param context
+         * @param textViewResourceId
+         * @param objects
+         */
+        public WiFiPeerListAdapter(Context context, int textViewResourceId,
+                                   List<WifiP2pDevice> objects) {
+            super(context, textViewResourceId, objects);
+            items = objects;
+        }
+
+        @Override
+        public int getCount() {
+            return items.size();
+        }
+
+
+        public void addItems(List<WifiP2pDevice> devicesToAdd){
+            items.clear();
+            items.addAll(devicesToAdd);
+        }
+
+        @Override
+        public View getView(int position, View convertView, ViewGroup parent) {
+            View v = convertView;
+            if (v == null) {
+                LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+                v = vi.inflate(R.layout.row_devices, null);
+            }
+            WifiP2pDevice device = items.get(position);
+            if (device != null) {
+                TextView top = (TextView) v.findViewById(R.id.device_name);
+                TextView bottom = (TextView) v.findViewById(R.id.device_details);
+                if (top != null) {
+                    top.setText(device.deviceName);
+                }
+                if (bottom != null) {
+                    bottom.setText(getDeviceStatus(device.status));
+                }
+            }
+            return v;
+        }
+    }
+}

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

@@ -44,14 +44,12 @@ 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.SyncData;
-import de.tudarmstadt.informatik.hostage.logging.SyncDevice;
 import de.tudarmstadt.informatik.hostage.logging.SyncInfo;
 import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
-import de.tudarmstadt.informatik.hostage.sync.Synchronizer;
 import de.tudarmstadt.informatik.hostage.sync.bluetooth.BluetoothSyncActivity;
 import de.tudarmstadt.informatik.hostage.sync.nfc.NFCSyncActivity;
-import de.tudarmstadt.informatik.hostage.sync.p2p.P2PSyncActivity;
 import de.tudarmstadt.informatik.hostage.sync.tracing.TracingSyncActivity;
+import de.tudarmstadt.informatik.hostage.sync.wifi_direct.ui.WiFiP2pSyncActivity;
 import de.tudarmstadt.informatik.hostage.ui.activity.MainActivity;
 import de.tudarmstadt.informatik.hostage.ui.adapter.RecordListAdapter;
 import de.tudarmstadt.informatik.hostage.ui.dialog.ChecklistDialog;
@@ -152,7 +150,7 @@ public class RecordOverviewFragment extends UpNavigatibleFragment implements Che
 	    pref = PreferenceManager.getDefaultSharedPreferences(getActivity());
 
 	    // Get the message from the intent
-        // this.addRecordToDB(4,4,4);
+        //this.addRecordToDB(4,4,4);
         /*
          Synchronizer s = new Synchronizer(this.dbh);
          si = s.getSyncInfo();
@@ -384,7 +382,8 @@ public class RecordOverviewFragment extends UpNavigatibleFragment implements Che
 					public void onClick(DialogInterface dialog, int position) {
 						switch(position){
 							case 0:
-								getActivity().startActivity(new Intent(getActivity(), BluetoothSyncActivity.class));
+
+								startActivityForResult(new Intent(getBaseContext(), BluetoothSyncActivity.class), 0);
 								break;
 							case 1:
 								getActivity().startActivity(new Intent(getActivity(), NFCSyncActivity.class));
@@ -394,7 +393,7 @@ public class RecordOverviewFragment extends UpNavigatibleFragment implements Che
 								getActivity().startActivity(new Intent(getActivity(), TracingSyncActivity.class));
 								break;
                             case 3:
-                                getActivity().startActivity(new Intent(getActivity(), P2PSyncActivity.class));
+                                getActivity().startActivity(new Intent(getActivity(), WiFiP2pSyncActivity.class));
                                 break;
 						}
 					}
@@ -427,7 +426,18 @@ public class RecordOverviewFragment extends UpNavigatibleFragment implements Che
 		return false;
 	}
 
-	/*****************************
+    @Override
+    public void onActivityResult(int requestCode, int resultCode, Intent data) {
+        super.onActivityResult(requestCode, resultCode, data);
+
+        if(requestCode == 0){
+            if(resultCode == BluetoothSyncActivity.SYNC_SUCCESSFUL){
+                actualiseListViewInBackground();
+            }
+        }
+    }
+
+    /*****************************
 	 *
 	 * 			Public API
 	 *