Browse Source

Portscan is logged corretly.
Handler only log an attack on the first message
Added LogExport service
Added JavaDoc

Lars Pandikow 10 years ago
parent
commit
5e63295acd
28 changed files with 280 additions and 706 deletions
  1. 6 4
      AndroidManifest.xml
  2. 39 10
      src/de/tudarmstadt/informatik/hostage/ConnectionGuard.java
  3. 1 0
      src/de/tudarmstadt/informatik/hostage/ConnectionRegister.java
  4. 15 4
      src/de/tudarmstadt/informatik/hostage/Handler.java
  5. 0 5
      src/de/tudarmstadt/informatik/hostage/Hostage.java
  6. 15 19
      src/de/tudarmstadt/informatik/hostage/Listener.java
  7. 0 14
      src/de/tudarmstadt/informatik/hostage/commons/HelperUtils.java
  8. 11 2
      src/de/tudarmstadt/informatik/hostage/location/MyLocationManager.java
  9. 3 0
      src/de/tudarmstadt/informatik/hostage/logging/AttackRecord.java
  10. 45 10
      src/de/tudarmstadt/informatik/hostage/logging/Logger.java
  11. 3 1
      src/de/tudarmstadt/informatik/hostage/logging/MessageRecord.java
  12. 3 0
      src/de/tudarmstadt/informatik/hostage/logging/NetworkRecord.java
  13. 4 0
      src/de/tudarmstadt/informatik/hostage/logging/Record.java
  14. 4 0
      src/de/tudarmstadt/informatik/hostage/logging/SyncInfoRecord.java
  15. 5 0
      src/de/tudarmstadt/informatik/hostage/persistence/HostageDBContract.java
  16. 32 2
      src/de/tudarmstadt/informatik/hostage/persistence/HostageDBOpenHelper.java
  17. 18 0
      src/de/tudarmstadt/informatik/hostage/sync/SyncMessage.java
  18. 35 4
      src/de/tudarmstadt/informatik/hostage/sync/bluetooth/BluetoothSyncActivity.java
  19. 0 29
      src/de/tudarmstadt/informatik/hostage/sync/bluetooth/BluetoothSyncService.java
  20. 7 3
      src/de/tudarmstadt/informatik/hostage/sync/bluetooth/ClientThread.java
  21. 11 7
      src/de/tudarmstadt/informatik/hostage/sync/bluetooth/CommunicationThread.java
  22. 8 4
      src/de/tudarmstadt/informatik/hostage/sync/bluetooth/ServerThread.java
  23. 4 0
      src/de/tudarmstadt/informatik/hostage/sync/tracing/TracingSyncActivity.java
  24. 4 0
      src/de/tudarmstadt/informatik/hostage/sync/tracing/TracingSyncResultReciever.java
  25. 5 5
      src/de/tudarmstadt/informatik/hostage/sync/tracing/TracingSyncService.java
  26. 2 2
      src/de/tudarmstadt/informatik/hostage/ui/PlayGroundActivity.java
  27. 0 544
      src/de/tudarmstadt/informatik/hostage/ui/ViewLog.java
  28. 0 37
      src/de/tudarmstadt/informatik/hostage/ui/ViewLogTable.java

+ 6 - 4
AndroidManifest.xml

@@ -44,16 +44,18 @@
             android:name="de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity"
             android:configChanges="keyboardHidden|orientation|screenSize"
             android:label="@string/app_name"
-            android:screenOrientation="portrait" >
-            <intent-filter>
+            android:screenOrientation="portrait" > 
+           	<intent-filter>
                 <action android:name="android.intent.action.MAIN" />
                 <category android:name="android.intent.category.LAUNCHER" />
-            </intent-filter>     
+            </intent-filter>  
+  
         </activity>
         <activity
             android:name="de.tudarmstadt.informatik.hostage.ui.MainActivity"
             android:configChanges="keyboardHidden|orientation|screenSize"
             android:label="@string/app_name" >
+ 
        
         </activity>
         <activity
@@ -86,7 +88,7 @@
             android:theme="@android:style/Theme.Dialog" >
         </activity>
         <activity
-            android:name="de.tudarmstadt.informatik.hostage.sync.bluetooth.BluetoothSync"
+            android:name="de.tudarmstadt.informatik.hostage.sync.bluetooth.BluetoothSyncActivity"
             android:label="@string/gui_bluetooth"
             android:theme="@android:style/Theme.Dialog" >
         </activity>

+ 39 - 10
src/de/tudarmstadt/informatik/hostage/ConnectionGuard.java

@@ -2,7 +2,11 @@ package de.tudarmstadt.informatik.hostage;
 
 import android.util.Log;
 
-
+/**
+ * Class used to detect port scans. 
+ * We assume a port scan if at least 2 different ports get a connection in a small amount of time.
+ *
+ */
 public class ConnectionGuard {
 
 	private final static ConnectionGuard INSTANCE = new ConnectionGuard();
@@ -10,32 +14,57 @@ public class ConnectionGuard {
 	private ConnectionGuard() {
 	}
 
+	/**
+	 * Intervall between 2 connection in wich we assume a port scan
+	 */
 	public final static long ONE_SECOND_IN_NANOSECONDS = 1000000000;
 
 	private static long lastTimestamp = 0;
 	private static String lastIP = "";
-	private static String lastProtocol = "";
+	private static int lastPort = 0;
 
-	public synchronized static boolean registerConnection(String protocol, String ip) {
+	/**
+	 * Register a connection for port scan detection. Stores information about the last connection.
+	 * @param port The local port used for communication.
+	 * @param ip The IP address of the remote device.
+	 * @return True if a port scan has been detected.
+	 */
+	public synchronized static boolean registerConnection(int port, String ip) {
 		long timestamp = System.nanoTime();		
-		boolean result = detectedPortscan(protocol, ip, timestamp);
+		boolean result = detectedPortscan(port, ip, timestamp);
+		
 		lastTimestamp = timestamp;
 		lastIP = ip;
-		lastProtocol = protocol;
+		lastPort = port;
 		return result;
 	}
 	
-	public synchronized static boolean detectedPortscan(String protocol, String ip){
-		return detectedPortscan(protocol, ip, System.nanoTime());
+	/**
+	 * Check if the new connection is part of a port scan attack.
+	 * @param port The local port used for communication.
+	 * @param ip The IP address of the remote device.
+	 * @return True if a port scan has been detected.
+	 */
+	public synchronized static boolean detectedPortscan(int port, String ip){
+		return detectedPortscan(port, ip, System.nanoTime());
 	}
 	
-	public synchronized static boolean detectedPortscan(String protocol, String ip, long timestamp) {
+	/**
+	 * Check if the new connection is part of a port scan attack.
+	 * @param port The local port used for communication.
+	 * @param ip The IP address of the remote device.
+	 * @param timestamp Time stamp of connection
+	 * @return True if a port scan has been detected.
+	 */
+	private synchronized static boolean detectedPortscan(int port, String ip, long timestamp) {
+		Log.i("Alte Werte:", "LastTime: " + lastTimestamp + " ,LastIP: " + lastIP + ", lastPort:" + port);
+		Log.i("Alte Werte:", "Time: " + timestamp + " ,IP: " + ip + ", Port:" + port);
 		boolean result = false;
 		boolean firstConnection = (lastTimestamp == 0);
 		boolean belowThreshold = ((timestamp - lastTimestamp) < ONE_SECOND_IN_NANOSECONDS);
 		boolean sameIP = (lastIP.equals(ip));
-		boolean sameProtocol = (lastProtocol.equals(protocol));
-		if (!firstConnection && sameIP && belowThreshold && !sameProtocol) {
+		boolean samePort = (lastPort == port);
+		if (!firstConnection && sameIP && belowThreshold && !samePort) {
 			result = true;
 		}
 		

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

@@ -8,6 +8,7 @@ import android.preference.PreferenceManager;
  * Saves the amount of active connections and limits them to a specific number.
  * 
  * @author Wulf Pfeiffer
+ * @author Lars Pandikow
  */
 public class ConnectionRegister {
 

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

@@ -28,6 +28,7 @@ import de.tudarmstadt.informatik.hostage.wrapper.Packet;
  * 
  * @author Mihai Plasoianu
  * @author Wulf Pfeiffer
+ * @author Lars Pandikow
  */
 public class Handler implements Runnable {
 
@@ -44,6 +45,8 @@ public class Handler implements Runnable {
 	private String externalIP;
 	private String BSSID;
 	private String SSID;
+	
+	private boolean logged;
 
 	private Listener listener;
 
@@ -78,8 +81,7 @@ public class Handler implements Runnable {
 		SSID = connInfo.getString(service.getString(R.string.connection_info_ssid), null);
 		externalIP = connInfo.getString(service.getString(R.string.connection_info_external_ip), null);
 		setSoTimeout(client);
-		Logger.log(Hostage.getContext(), createNetworkRecord());
-		Logger.log(Hostage.getContext(), createAttackRecord());
+		logged = false;
 		thread.start();
 		
 	}
@@ -219,6 +221,15 @@ public class Handler implements Runnable {
 		}
 		return record;
 	}
+	
+	private void log(TYPE type, String packet){
+		if(!logged){
+			Logger.log(Hostage.getContext(), createNetworkRecord());
+			Logger.log(Hostage.getContext(), createAttackRecord());
+			logged = true;
+		}
+		Logger.log(Hostage.getContext(), createMessageRecord(type, packet));
+	}
 
 	/**
 	 * Communicates with a client using the corresponding protocol
@@ -239,7 +250,7 @@ public class Handler implements Runnable {
 			outputLine = protocol.processMessage(null);
 			writer.write(outputLine);
 			for (Packet o : outputLine) {
-				Logger.log(Hostage.getContext(), createMessageRecord(TYPE.SEND, o.toString()));
+				log(TYPE.SEND, o.toString());
 			}
 		}
 		while (!thread.isInterrupted() && (inputLine = reader.read()) != null) {
@@ -248,7 +259,7 @@ public class Handler implements Runnable {
 			if (outputLine != null) {
 				writer.write(outputLine);
 				for (Packet o : outputLine) {
-					Logger.log(Hostage.getContext(), createMessageRecord(TYPE.SEND, o.toString()));
+					log(TYPE.SEND, o.toString());
 				}
 			}
 			if (protocol.isClosed()) {

+ 0 - 5
src/de/tudarmstadt/informatik/hostage/Hostage.java

@@ -1,9 +1,5 @@
 package de.tudarmstadt.informatik.hostage;
 
-import java.io.BufferedReader;
-import java.io.InputStreamReader;
-import java.net.Socket;
-import java.security.SecureRandom;
 import java.util.ArrayList;
 import java.util.LinkedList;
 import java.util.List;
@@ -39,7 +35,6 @@ import android.widget.Toast;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
 import de.tudarmstadt.informatik.hostage.location.MyLocationManager;
 import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
-import de.tudarmstadt.informatik.hostage.protocol.HTTP;
 import de.tudarmstadt.informatik.hostage.protocol.Protocol;
 import de.tudarmstadt.informatik.hostage.ui2.activity.MainActivity;
 

+ 15 - 19
src/de/tudarmstadt/informatik/hostage/Listener.java

@@ -1,11 +1,8 @@
 package de.tudarmstadt.informatik.hostage;
 
-import java.io.BufferedReader;
 import java.io.IOException;
-import java.io.InputStreamReader;
 import java.net.ServerSocket;
 import java.net.Socket;
-import java.security.SecureRandom;
 import java.util.ArrayList;
 import java.util.Iterator;
 
@@ -16,16 +13,13 @@ import javax.net.ssl.SSLSocketFactory;
 import android.content.Context;
 import android.content.SharedPreferences;
 import android.content.SharedPreferences.Editor;
-import android.os.AsyncTask;
 import android.preference.PreferenceManager;
 import android.util.Log;
-
 import de.tudarmstadt.informatik.hostage.location.MyLocationManager;
 import de.tudarmstadt.informatik.hostage.logging.AttackRecord;
 import de.tudarmstadt.informatik.hostage.logging.Logger;
 import de.tudarmstadt.informatik.hostage.logging.NetworkRecord;
 import de.tudarmstadt.informatik.hostage.net.MyServerSocketFactory;
-import de.tudarmstadt.informatik.hostage.protocol.HTTP;
 import de.tudarmstadt.informatik.hostage.protocol.Protocol;
 import de.tudarmstadt.informatik.hostage.protocol.SMB;
 import de.tudarmstadt.informatik.hostage.protocol.SSLProtocol;
@@ -38,6 +32,7 @@ import de.tudarmstadt.informatik.hostage.protocol.SSLProtocol;
  * 
  * @author Mihai Plasoianu
  * @author Wulf Pfeiffer
+ * @author Lars Pandikow
  */
 public class Listener implements Runnable {
 
@@ -181,22 +176,22 @@ public class Listener implements Runnable {
 		if (conReg.isConnectionFree()) {
 			try {
 				final Socket client = server.accept();
-				final String protocolName = this.getProtocolName();
 				new Thread( new Runnable() {
 				    @Override
 				    public void run() {
 				    	try {
 				    		String ip = client.getInetAddress().getHostAddress();
-				    		if (ConnectionGuard.registerConnection(protocolName, ip)){
-				    			Log.i("Listener", "Portscan detected.");
+				    		if (ConnectionGuard.registerConnection(port, ip)){
+				    			Log.i("sda", "PORTSCAN ICH MACH NIX");
 				    			return;
 				    		}
-				    		
-				    		Thread.sleep(ConnectionGuard.ONE_SECOND_IN_NANOSECONDS / 1000);
-				    		if(ConnectionGuard.detectedPortscan(protocolName, ip)){
-				    			Log.i("Listener", "Portscan detected.");
-				    			logPortscan(client);
+				    		Log.i("sda", "pause");
+				    		Thread.sleep(999);
+				    		if(ConnectionGuard.detectedPortscan(port, ip)){
+				    			Log.i("sda", "ICH LOGGE JETZT PORTSANCS");
+				    			logPortscan(client, System.currentTimeMillis());
 				    		}else{
+				    			Log.i("sda", "ICH LOGGE JETZT NIX =(");
 								if (protocol.isSecure()) {
 									startSecureHandler(client);
 								} else {
@@ -260,9 +255,11 @@ public class Listener implements Runnable {
 	}	
 	
 	/**
-	 * Starts a Handler with Portscan as Protocol. Afterwards kills it. For Logging purpose only!
+	 * Logs a port scan attack
+	 * @param client The socket on which a port scan has been detected.
+	 * @param timestamp Timestamp when the portscan has been detected.
 	 */
-	private void logPortscan(Socket client){
+	private void logPortscan(Socket client, long timestamp){
 		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(service);
 		SharedPreferences connInfo = service.getSharedPreferences(service.getString(R.string.connection_info), Context.MODE_PRIVATE);
 
@@ -295,8 +292,7 @@ public class Listener implements Runnable {
 			networkRecord.setAccuracy(Float.MAX_VALUE);
 			networkRecord.setTimestampLocation(0);
 		}
-		
-		Logger.log(Hostage.getContext(), attackRecord);
-		Logger.log(Hostage.getContext(), networkRecord);
+		Log.i("sda", "YEAAAAH");
+		Logger.logPortscan(Hostage.getContext(), attackRecord, networkRecord, timestamp);
 	}
 }

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

@@ -260,20 +260,6 @@ public final class HelperUtils {
 		return bytes;
 	}
 
-	/**
-	 * Checks if external storage is available for read and write.
-	 * 
-	 * @return True if external storage is available for read and write, else
-	 *         false.
-	 */
-	public static boolean isExternalStorageWritable() {
-		String state = Environment.getExternalStorageState();
-		if (Environment.MEDIA_MOUNTED.equals(state)) {
-			return true;
-		}
-		return false;
-	}
-
 	/**
 	 * Generates a random byte[] of a specified size
 	 * 

+ 11 - 2
src/de/tudarmstadt/informatik/hostage/location/MyLocationManager.java

@@ -9,8 +9,15 @@ import android.location.LocationListener;
 import android.location.LocationManager;
 import android.os.Bundle;
 
+/**
+ * This Class is used to get Location data. You can get the last found Location or start searching for new location data.
+ * @author Lars Pandikow
+ */
 public class MyLocationManager {
 
+	/**
+	 * TimerTask to stop updates after a given time.
+	 */
 	class StopTask extends TimerTask {
 		@Override
 		public void run() {
@@ -105,8 +112,7 @@ public class MyLocationManager {
 		if (!gpsEnabled && !networkEnabled)
 			return;
 
-		// Register the listener with the Location Manager to receive location
-		// updates
+		// Register the listener with the Location Manager to receive location updates
 		if (gpsEnabled)
 			locationManager.requestLocationUpdates(
 					LocationManager.GPS_PROVIDER, 0, 0, locationListener);
@@ -115,6 +121,9 @@ public class MyLocationManager {
 					LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
 	}
 
+	/**
+	 * Stop updating the location.
+	 */
 	public void stopUpdates() {
 		locationManager.removeUpdates(locationListener);
 	}

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

@@ -5,6 +5,9 @@ import java.io.Serializable;
 import android.os.Parcel;
 import android.os.Parcelable;
 
+/**
+ * Holds all necessary information about a single attack.
+ */
 public class AttackRecord implements Parcelable, Serializable{
 	
 	private static final long serialVersionUID = 6111024905373724227L;

+ 45 - 10
src/de/tudarmstadt/informatik/hostage/logging/Logger.java

@@ -7,6 +7,11 @@ import android.os.Parcelable;
 import de.tudarmstadt.informatik.hostage.logging.MessageRecord.TYPE;
 import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
 
+/**
+ * The Logger is used to write the database in dedicated worker threads and implements a message queue.
+ * @author Mihai Plasoianu
+ * @author Lars Pandikow
+ */
 public class Logger extends IntentService {
 
 	private static final String ACTION_LOG_MESSAGE = "de.tudarmstadt.informatik.hostage.action.LOG_MESSAGE";
@@ -15,8 +20,14 @@ public class Logger extends IntentService {
 	private static final String ACTION_LOG_PORTSCAN = "de.tudarmstadt.informatik.hostage.action.LOG_PORTSCAN";
 
 	private static final String EXTRA_RECORD = "de.tudarmstadt.informatik.hostage.extra.RECORD";
+	private static final String EXTRA_RECORD2 = "de.tudarmstadt.informatik.hostage.extra.RECORD2";
 	private static final String EXTRA_TIMESTAMP = "de.tudarmstadt.informatik.hostage.extra.TIMESTAMP";
 
+	/**
+	 * Adds a single MessageRecord to the Database.
+	 * @param context Context needed to access database
+	 * @param record The MessageRecord to be added
+	 */
 	public static void log(Context context, MessageRecord record) {
 		Intent intent = new Intent(context, Logger.class);
 		intent.setAction(ACTION_LOG_MESSAGE);
@@ -24,6 +35,11 @@ public class Logger extends IntentService {
 		context.startService(intent);
 	}
 	
+	/**
+	 * Adds a single AttackRecord to the Database.
+	 * @param context Context needed to access database
+	 * @param record The AttackRecord to be added
+	 */
 	public static void log(Context context, AttackRecord record) {
 		Intent intent = new Intent(context, Logger.class);
 		intent.setAction(ACTION_LOG_ATTACK);
@@ -31,6 +47,11 @@ public class Logger extends IntentService {
 		context.startService(intent);
 	}
 	
+	/**
+	 * Adds a single NetworkRecord to the Database.
+	 * @param context Context needed to access database
+	 * @param record The NetworkRecord to be added
+	 */
 	public static void log(Context context, NetworkRecord record) {
 		Intent intent = new Intent(context, Logger.class);
 		intent.setAction(ACTION_LOG_NETWORK);
@@ -38,10 +59,18 @@ public class Logger extends IntentService {
 		context.startService(intent);
 	}
 	
-	public static void logPortscan(Context context, AttackRecord record, long timestamp){
+	/**
+	 * Adds a port scan entry to the database
+	 * @param context Context needed to access database
+	 * @param attackRecord AttackRecord containing the attack information of the port scan
+	 * @param netRecord NetworkRecord containing the network information of the port scan
+	 * @param timestamp Timestamp of the port scan
+	 */
+	public static void logPortscan(Context context, AttackRecord attackRecord, NetworkRecord netRecord, long timestamp){
 		Intent intent = new Intent(context, Logger.class);
 		intent.setAction(ACTION_LOG_PORTSCAN);
-		intent.putExtra(EXTRA_RECORD, (Parcelable)record);
+		intent.putExtra(EXTRA_RECORD, (Parcelable)attackRecord);
+		intent.putExtra(EXTRA_RECORD2, (Parcelable)netRecord);
 		intent.putExtra(EXTRA_TIMESTAMP, timestamp);
 		context.startService(intent);
 	}
@@ -69,6 +98,9 @@ public class Logger extends IntentService {
 		mDbHelper.updateNetworkInformation(record);
 	}
 
+	/**
+	 * Method to handle the Intent createt by the public interface.
+	 */
 	@Override
 	protected void onHandleIntent(Intent intent) {
 		if (intent != null) {
@@ -83,14 +115,17 @@ public class Logger extends IntentService {
 				final NetworkRecord record = intent.getParcelableExtra(EXTRA_RECORD);
 				handleActionLog(record);
 			}else if(ACTION_LOG_PORTSCAN.equals(action)){
-				final AttackRecord record = intent.getParcelableExtra(EXTRA_RECORD);
-				handleActionLog(record);
-				MessageRecord mRecord = new MessageRecord();
-				mRecord.setAttack_id(record.getAttack_id());
-				mRecord.setId(0);
-				mRecord.setPacket("");
-				mRecord.setTimestamp(intent.getLongExtra(EXTRA_TIMESTAMP, 0));
-				mRecord.setType(TYPE.RECEIVE);
+				final AttackRecord attackRecord = intent.getParcelableExtra(EXTRA_RECORD);
+				final NetworkRecord networkRecord = intent.getParcelableExtra(EXTRA_RECORD2);
+				MessageRecord messageRecord = new MessageRecord();
+				messageRecord.setAttack_id(attackRecord.getAttack_id());
+				messageRecord.setId(0);
+				messageRecord.setPacket("");
+				messageRecord.setTimestamp(intent.getLongExtra(EXTRA_TIMESTAMP, 0));
+				messageRecord.setType(TYPE.RECEIVE);
+				handleActionLog(attackRecord);
+				handleActionLog(networkRecord);
+				handleActionLog(messageRecord);
 			}
 		}
 	}

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

@@ -5,7 +5,9 @@ import java.io.Serializable;
 import android.os.Parcel;
 import android.os.Parcelable;
 
-
+/**
+ * Holds all necessary information about a single message exchanged during an attack.
+ */
 public class MessageRecord implements Parcelable, Serializable{
 	
 	private static final long serialVersionUID = -5936572995202342935L;

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

@@ -5,6 +5,9 @@ import java.io.Serializable;
 import android.os.Parcel;
 import android.os.Parcelable;
 
+/**
+ * Holds all necessary information about a single network.
+ */
 public class NetworkRecord implements Parcelable, Serializable{	
 	
 	private static final long serialVersionUID = -1586629159904177836L;

+ 4 - 0
src/de/tudarmstadt/informatik/hostage/logging/Record.java

@@ -3,6 +3,10 @@ package de.tudarmstadt.informatik.hostage.logging;
 import de.tudarmstadt.informatik.hostage.logging.MessageRecord.TYPE;
 import de.tudarmstadt.informatik.hostage.logging.formatter.Formatter;
 
+/**
+ * Record that holds all information of a message including full attack and network information.
+ * This class should be avoided but is necessary due to inter group complications.
+ */
 public class Record {
 
 	//

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

@@ -2,6 +2,10 @@ package de.tudarmstadt.informatik.hostage.logging;
 
 import java.io.Serializable;
 
+/**
+ * Holds the Information a specific device gathered about a network identified by its BSSID.
+ * @author Lars Pandikow
+ */
 public class SyncInfoRecord implements Serializable{	
 
 	private static final long serialVersionUID = 7156818788190434192L;

+ 5 - 0
src/de/tudarmstadt/informatik/hostage/persistence/HostageDBContract.java

@@ -2,6 +2,11 @@ package de.tudarmstadt.informatik.hostage.persistence;
 
 import android.provider.BaseColumns;
 
+/**
+ * Contract class defines names for the {@link HostageDBOpenHelper}.
+ * @author Mihai Plasoianu
+ * @author Lars Pandikow
+ */
 public final class HostageDBContract {
 
 	public static abstract class NetworkEntry implements BaseColumns {

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

@@ -26,6 +26,12 @@ import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract.SyncDevic
 import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract.SyncInfoEntry;
 import de.tudarmstadt.informatik.hostage.ui.LogFilter;
 
+/**
+ * Database Helper class to create, read and write the database.
+ * @author Mihai Plasoianu
+ * @author Lars Pandikow
+ *
+ */
 public class HostageDBOpenHelper extends SQLiteOpenHelper {
 
 	private static final String DATABASE_NAME = "hostage.db";
@@ -622,6 +628,10 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 		return ssid;
 	}
 	
+	/**
+	 * Gets all network related data stored in the database
+	 * @return An ArrayList with an Network for all Entry in the network table.
+	 */
 	public ArrayList<NetworkRecord> getNetworkInformation() {
 		String selectQuery = "SELECT  * FROM " + NetworkEntry.TABLE_NAME;
 		SQLiteDatabase db = this.getReadableDatabase();
@@ -629,7 +639,6 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 
 		ArrayList<NetworkRecord> networkInformation = new ArrayList<NetworkRecord>();
 
-		// looping through all rows and adding to list
 		if (cursor.moveToFirst()) {
 			do {
 				NetworkRecord record = new NetworkRecord();
@@ -648,12 +657,24 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 		return networkInformation;
 	}
 
+	/**
+	 * Updates the network table with the information contained in the parameter.
+	 * @param networkInformation ArrayList of {@link NetworkRecord NetworkRecords}
+	 * @see  {@link HostageDBOpenHelper#updateNetworkInformation(NetworkRecord record)}
+	 */
 	public void updateNetworkInformation(ArrayList<NetworkRecord> networkInformation) {;
 		for (NetworkRecord record : networkInformation) {
 			updateNetworkInformation(record);
 		}
 	}
 
+	/**
+	 * Updated the network table with a new {@link NetworkRecord}.
+	 * If information about this BSSID are already in the database, 
+	 * the table will only be updated if the new {@link NetworkRecord } 
+	 * has a newer location time stamp.
+	 * @param record The new {@link NetworkRecord}.
+	 */
 	public void updateNetworkInformation(NetworkRecord record) {
 		SQLiteDatabase db = this.getReadableDatabase();
 		String bssid = record.getBssid();
@@ -750,13 +771,22 @@ public class HostageDBOpenHelper extends SQLiteOpenHelper {
 		return syncInfo;
 	}	
 	
-	
+	/**
+	 * Updates the sync_info table with the information contained in the parameter.
+	 * @param networkInformation ArrayList of {@link SyncInfoRecord SyncInfoRecords}
+	 * @see  {@link HostageDBOpenHelper#updateSyncInfo(SyncInfoRecord syncInfo)}
+	 */
 	public void updateSyncInfo(ArrayList<SyncInfoRecord> syncInfo){
 		for(SyncInfoRecord info : syncInfo){
 			updateSyncInfo(info);
 		}
 	}
 	
+	/**
+	 * Updated the network table with a new {@link SyncInfoRecord}.
+	 * Conflicting rows will be replaced.
+	 * @param syncInfo The new {@link NetworkRecord}.
+	 */
 	public void updateSyncInfo(SyncInfoRecord syncInfo){
 		SQLiteDatabase db = this.getReadableDatabase();
 		ContentValues syncValues = new ContentValues();

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

@@ -2,6 +2,10 @@ package de.tudarmstadt.informatik.hostage.sync;
 
 import java.io.Serializable;
 
+/**
+ * Message class for synchronization between devices.
+ * @author Lars Pandikow
+ */
 public class SyncMessage implements Serializable{
 	
 
@@ -20,20 +24,34 @@ public class SyncMessage implements Serializable{
 		this.payload = payload;
 	}
 
+	/**
+	 * @return the message_code
+	 */
 	public int getMessage_code() {
 		return message_code;
 	}
 
+	/**
+	 * @param message_code the message_code to set
+	 */
 	public void setMessage_code(int message_code) {
 		this.message_code = message_code;
 	}
 
+	/**
+	 * @return the payload
+	 */
 	public Object getPayload() {
 		return payload;
 	}
 
+	/**
+	 * @param payload the payload to set
+	 */
 	public void setPayload(Object payload) {
 		this.payload = payload;
 	}
 
+
+
 }

+ 35 - 4
src/de/tudarmstadt/informatik/hostage/sync/bluetooth/BluetoothSync.java → src/de/tudarmstadt/informatik/hostage/sync/bluetooth/BluetoothSyncActivity.java

@@ -23,7 +23,13 @@ import android.widget.TextView;
 import android.widget.AdapterView.OnItemClickListener;
 import de.tudarmstadt.informatik.hostage.R;
 
-public class BluetoothSync extends Activity{	
+/**
+ * Activity that allows the user to choose a bluetooth device to 
+ * synchronize with and informs about the status of the synchronization.
+ *
+ * @author Lars Pandikow
+ */
+public class BluetoothSyncActivity extends Activity{	
 	
 	public static final int CONNECTING = 0x0;
     public static final int CONNECTION_ESTABLISHED = 0x1;
@@ -89,6 +95,9 @@ public class BluetoothSync extends Activity{
 		}
 	}
 	
+	/**
+	 * Starts discorvry of bluetooth devices.
+	 */
 	private void chooseDevice(){
 		arrayAdapter.clear();
 		if (!mBluetoothAdapter.startDiscovery())
@@ -98,6 +107,10 @@ public class BluetoothSync extends Activity{
 		setContentView(layout);
 	}
 
+	/**
+	 * Start a ServerThread to listen for incomming connections
+	 * @see ServerThread
+	 */
 	private void startConnectionListener() {
 		Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
 		discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
@@ -107,7 +120,11 @@ public class BluetoothSync extends Activity{
 		serverThread.start();
 	}
 		
-
+	/**
+	 * Called when a connection has been established.
+	 * Starts a {@link CommunicationThread} for communication.
+	 * @param socket The socket of the connection.
+	 */
 	protected void manageConnectedSocket(BluetoothSocket socket) {
 		mBluetoothAdapter.cancelDiscovery();
 		unregisterBroadcastReceiver();
@@ -120,7 +137,9 @@ public class BluetoothSync extends Activity{
 		commThread.start();
 	}
 
-	// Create a BroadcastReceiver for ACTION_FOUND
+	/**
+	 * BroadcastReciever listens for state changes of bluetooth and discovery of new devices.
+	 */
 	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
 		@Override
 		public void onReceive(Context context, Intent intent) {
@@ -149,7 +168,9 @@ public class BluetoothSync extends Activity{
 	private boolean mRecieverRegistered = false;
 
 
-	// Register the BroadcastReceiver
+	/**
+	 *  Register the BroadcastReceiver
+	 */
 	private void registerBroadcastReceiver() {
 		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
 		filter.addAction(BluetoothAdapter. ACTION_STATE_CHANGED);
@@ -157,11 +178,18 @@ public class BluetoothSync extends Activity{
 		mRecieverRegistered = true;
 	}
 	
+	/**
+	 *  Unregister the BroadcastReceiver
+	 */
 	private void unregisterBroadcastReceiver(){
 		unregisterReceiver(mReceiver);
 		mRecieverRegistered = false;
 	}
 	
+	/**
+	 * Creates the list of bluetooth devices. 
+	 * Starts a {@link ClientThread} to establish connection when a device is clicked.
+	 */
 	private void setLayoutElement(){
 		mInfoText = (TextView) findViewById(R.id.bluetoothInfoText);
 		layout = (LinearLayout) findViewById(R.id.bluetoothLayout);
@@ -180,6 +208,9 @@ public class BluetoothSync extends Activity{
 		});		
 	}	
 	
+	/**
+	 * Handles message sent from the background threads and updates UI.
+	 */
 	private Handler mHandler = new Handler() {
 
         @Override

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

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

+ 7 - 3
src/de/tudarmstadt/informatik/hostage/sync/bluetooth/ClientThread.java

@@ -7,6 +7,10 @@ import android.bluetooth.BluetoothDevice;
 import android.bluetooth.BluetoothSocket;
 import android.os.Handler;
 
+/**
+ * Thread used to connect to a remote bluetooth device.
+ * @author Lars Pandikow
+ */
 public class ClientThread extends Thread {
 	private final BluetoothSocket socket;
 	private final Handler mHandler;
@@ -15,7 +19,7 @@ public class ClientThread extends Thread {
 		mHandler = handler;
 		BluetoothSocket tmp = null;
 		try {
-			tmp = device.createRfcommSocketToServiceRecord(BluetoothSync.serviceUUID);
+			tmp = device.createRfcommSocketToServiceRecord(BluetoothSyncActivity.serviceUUID);
 		} catch (IOException e) {
 		}
 		socket = tmp;
@@ -34,9 +38,9 @@ public class ClientThread extends Thread {
 
 		try {
 			socket.connect();
-			mHandler.obtainMessage(BluetoothSync.CONNECTION_ESTABLISHED, socket).sendToTarget();
+			mHandler.obtainMessage(BluetoothSyncActivity.CONNECTION_ESTABLISHED, socket).sendToTarget();
 		} catch (IOException connectException) {
-			mHandler.obtainMessage(BluetoothSync.CONNECTION_FAILED).sendToTarget();
+			mHandler.obtainMessage(BluetoothSyncActivity.CONNECTION_FAILED).sendToTarget();
 			// Unable to connect; close the socket and get out
 			try {
 				socket.close();

+ 11 - 7
src/de/tudarmstadt/informatik/hostage/sync/bluetooth/CommunicationThread.java

@@ -19,6 +19,10 @@ import android.content.Context;
 import android.os.Handler;
 import android.util.Log;
 
+/**
+ * CommunicationThread is responsible for the exchange of synchronization messages between devices.
+ * @author Lars Pandikow
+ */
 public class CommunicationThread extends Thread {
 	private final Context context;
 	private final BluetoothSocket mmSocket;
@@ -43,7 +47,7 @@ public class CommunicationThread extends Thread {
 			tmpOut = new ObjectOutputStream(socket.getOutputStream());
 			tmpIn = new ObjectInputStream(socket.getInputStream());
 		} catch (IOException e) {
-			mHandler.obtainMessage(BluetoothSync.CONNECTION_FAILED).sendToTarget();
+			mHandler.obtainMessage(BluetoothSyncActivity.CONNECTION_FAILED).sendToTarget();
 			e.printStackTrace();
 		}
 
@@ -117,24 +121,24 @@ public class CommunicationThread extends Thread {
 			case SyncMessage.SYNC_RESPONSE_NET_INFO:
 				ArrayList<NetworkRecord> netInfo = (ArrayList<NetworkRecord>) message.getPayload();
 				mdbh.updateNetworkInformation(netInfo);	
-				mHandler.obtainMessage(BluetoothSync.SYNC_SUCCESSFUL).sendToTarget();	
+				mHandler.obtainMessage(BluetoothSyncActivity.SYNC_SUCCESSFUL).sendToTarget();	
 				break;			
 			case SyncMessage.SYNC_RESPONSE_SYNC_INFO:
 				ArrayList<SyncInfoRecord> syncInfo_new = (ArrayList<SyncInfoRecord>) message.getPayload();
 				mdbh.updateSyncInfo(syncInfo_new);
 				break;
-			default: 
-				//TODO DEFAULT WITH UNKNOWN MESSAGE CODE;
 		}		
 	}
 	
-	/* Call this from the main activity to send data to the remote device */
+	/**
+	 * Send a message to the remote device.
+	 * @param message The message to send.
+	 */
 	public void write(SyncMessage message) {
 		try {
 			objectOuput.writeObject(message);
-//TODO NACHRICHT SCHICKEN?			mHandler.obtainMessage(BluetoothSync.MESSAGE_SENT).sendToTarget();
 		} catch (IOException e) {
-			mHandler.obtainMessage(BluetoothSync.CONNECTION_FAILED).sendToTarget();
+			mHandler.obtainMessage(BluetoothSyncActivity.CONNECTION_FAILED).sendToTarget();
 			e.printStackTrace();
 		}
 	}

+ 8 - 4
src/de/tudarmstadt/informatik/hostage/sync/bluetooth/ServerThread.java

@@ -7,6 +7,10 @@ import android.bluetooth.BluetoothServerSocket;
 import android.bluetooth.BluetoothSocket;
 import android.os.Handler;
 
+/**
+ * Thread listens for incomming connections.
+ * @author Lars Pandikow
+ */
 public class ServerThread extends Thread {
 	private final BluetoothServerSocket serverSocket;
 	private final Handler mHandler;
@@ -15,9 +19,9 @@ public class ServerThread extends Thread {
 		BluetoothServerSocket tmp = null;
 		mHandler = handler;
 		try {
-			tmp = BluetoothAdapter.getDefaultAdapter().listenUsingRfcommWithServiceRecord(app_name, BluetoothSync.serviceUUID);
+			tmp = BluetoothAdapter.getDefaultAdapter().listenUsingRfcommWithServiceRecord(app_name, BluetoothSyncActivity.serviceUUID);
 		} catch (IOException e) {
-			mHandler.obtainMessage(BluetoothSync.CONNECTION_FAILED).sendToTarget();
+			mHandler.obtainMessage(BluetoothSyncActivity.CONNECTION_FAILED).sendToTarget();
 		}
 		serverSocket = tmp;
 	}
@@ -38,13 +42,13 @@ public class ServerThread extends Thread {
 				socket = serverSocket.accept();
 			} catch (IOException e) {
 				e.printStackTrace();
-				mHandler.obtainMessage(BluetoothSync.CONNECTION_FAILED).sendToTarget();
+				mHandler.obtainMessage(BluetoothSyncActivity.CONNECTION_FAILED).sendToTarget();
 				break;
 			}
 
 			if (socket != null) {
 				// Do work to manage the connection (in a separate thread)
-				mHandler.obtainMessage(BluetoothSync.CONNECTION_ESTABLISHED, socket).sendToTarget();
+				mHandler.obtainMessage(BluetoothSyncActivity.CONNECTION_ESTABLISHED, socket).sendToTarget();
 				try {
 					serverSocket.close();
 				} catch (IOException e) {

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

@@ -7,6 +7,10 @@ import android.os.Bundle;
 import android.os.Handler;
 import android.widget.TextView;
 
+/**
+ * Starts a synchronization service and shows the progress of the synchronization.
+ * @author Lars Pandikow
+ */
 public class TracingSyncActivity extends Activity implements TracingSyncResultReciever.Receiver{
 	
 	TextView mInfoText;

+ 4 - 0
src/de/tudarmstadt/informatik/hostage/sync/tracing/TracingSyncResultReciever.java

@@ -4,6 +4,10 @@ import android.os.Bundle;
 import android.os.Handler;
 import android.os.ResultReceiver;
  
+/**
+ * Helper Class to send messages from {@link TracingSyncService} to {@link TracingSyncActivity}.
+ * @author Lars Pandikow
+ */
 public class TracingSyncResultReciever extends ResultReceiver {
     private Receiver mReceiver;
  

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

@@ -32,6 +32,10 @@ import de.tudarmstadt.informatik.hostage.logging.AttackRecord;
 import de.tudarmstadt.informatik.hostage.net.MySSLSocketFactory;
 import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
 
+/**
+ * Service that synchronizes with a specified remote server.
+ * @author Lars Pandikow
+ */
 public class TracingSyncService extends IntentService{
 	
 	public static final String REMOTE_DEVICE = "de.tudarmstadt.informatik.hostage.REMOTE_DEVICE";
@@ -146,11 +150,7 @@ public class TracingSyncService extends IntentService{
 	}
 	
 	/**
-	 * Uploads a single Record to a server, specified in the settings.
-	 * 
-	 * @param record
-	 *            The Record to upload.
-	 * @return True if the upload was successful, else false.
+	 * Gets the data from the server and updates the database.
 	 */
 	private void getRemoteData() {
 		//TODO GET DATA FROM SERVER

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

@@ -19,7 +19,7 @@ import de.tudarmstadt.informatik.hostage.logging.NetworkRecord;
 import de.tudarmstadt.informatik.hostage.logging.SyncInfoRecord;
 import de.tudarmstadt.informatik.hostage.persistence.HostageDBContract;
 import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
-import de.tudarmstadt.informatik.hostage.sync.bluetooth.BluetoothSync;
+import de.tudarmstadt.informatik.hostage.sync.bluetooth.BluetoothSyncActivity;
 import de.tudarmstadt.informatik.hostage.sync.nfc.NFCSync;
 import de.tudarmstadt.informatik.hostage.sync.tracing.TracingSyncActivity;
 
@@ -55,7 +55,7 @@ public class PlayGroundActivity extends Activity {
 	}
 
 	public void syncData(View view) {
-		startActivity(new Intent(this, BluetoothSync.class));
+		startActivity(new Intent(this, BluetoothSyncActivity.class));
 	}
 
 	private String createRandomBSSID() {

+ 0 - 544
src/de/tudarmstadt/informatik/hostage/ui/ViewLog.java

@@ -1,544 +0,0 @@
-package de.tudarmstadt.informatik.hostage.ui;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.Locale;
-
-import android.annotation.SuppressLint;
-import android.app.Activity;
-import android.app.AlertDialog;
-import android.app.DatePickerDialog;
-import android.app.Dialog;
-import android.app.NotificationManager;
-import android.app.PendingIntent;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.content.Intent;
-import android.content.SharedPreferences;
-import android.content.SharedPreferences.Editor;
-import android.os.Build;
-import android.os.Bundle;
-import android.os.Environment;
-import android.preference.PreferenceManager;
-import android.support.v4.app.NotificationCompat;
-import android.support.v4.app.TaskStackBuilder;
-import android.util.Log;
-import android.view.Gravity;
-import android.view.Menu;
-import android.view.MenuItem;
-import android.view.View;
-import android.widget.DatePicker;
-import android.widget.TableLayout;
-import android.widget.TableRow;
-import android.widget.TextView;
-import android.widget.TimePicker;
-import android.widget.Toast;
-import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
-import de.tudarmstadt.informatik.hostage.logging.Record;
-import de.tudarmstadt.informatik.hostage.logging.formatter.TraCINgFormatter;
-
-/**
- * ViewLog shows Statistics about the recorded Attacks. It also offers the user
- * several options to perform actions with the database. This includes:<br>
- * - show records,<br>
- * - export records,<br>
- * - upload records,<br>
- * - and delete records.
- * 
- * @author Lars Pandikow
- */
-public class ViewLog extends Activity {
-
-	private final SimpleDateFormat sdf = new SimpleDateFormat(
-			"MMM dd,yyyy HH:mm", Locale.US);
-
-	private SharedPreferences pref;
-	private Editor editor;
-
-	/**
-	 * Creates a Dialog that lets the user decide which criteria he want to use
-	 * to delete records. Then calls the corresponding method.<br>
-	 * The possible criteria are coded in /res/values/arrays.xml To add a
-	 * criteria add a String to the array and extend the switch statement.
-	 * 
-	 * @param view
-	 *            View elements which triggers the method call.
-	 * @see ViewLog#deleteByBSSID()
-	 * @see ViewLog#deleteByDate()
-	 * @see ViewLog#deleteAll()
-	 */
-	public void deleteLog(View view) {
-		AlertDialog.Builder builder = new AlertDialog.Builder(this);
-		builder.setTitle(R.string.gui_delete_dialog_title);
-		builder.setItems(R.array.delete_criteria,
-				new DialogInterface.OnClickListener() {
-					@Override
-					public void onClick(DialogInterface dialog, int position) {
-						switch (position) {
-						case 0:
-							deleteByBSSID();
-							break;
-						case 1:
-							deleteByDate();
-							break;
-						case 2:
-							deleteAll();
-						}
-					}
-				});
-		builder.create();
-		builder.show();
-	}
-
-	/**
-	 * Creates a Dialog to choose export format. Then calls
-	 * {@link ViewLog#exportDatabase(int)}
-	 * 
-	 * @param view
-	 *            View elements which triggers the method call.
-	 */
-	public void exportDatabase(View view) {
-		AlertDialog.Builder builder = new AlertDialog.Builder(this);
-		builder.setTitle(R.string.gui_export_dialog_title);
-		builder.setItems(R.array.format, new DialogInterface.OnClickListener() {
-			@Override
-			public void onClick(DialogInterface dialog, int position) {
-				exportDatabase(position);
-			}
-		});
-		builder.create();
-		builder.show();
-	}
-
-	@Override
-	public boolean onCreateOptionsMenu(Menu menu) {
-		getMenuInflater().inflate(R.menu.main, menu);
-		return true;
-	}
-
-	@Override
-	public boolean onOptionsItemSelected(MenuItem item) {
-		// Handle item selection
-		switch (item.getItemId()) {
-		case R.id.action_settings:
-			startActivity(new Intent(this, SettingsActivity.class));
-			break;
-		case R.id.action_about:
-			startActivity(new Intent(this, AboutActivity.class));
-			break;
-		default:
-		}
-		return super.onOptionsItemSelected(item);
-	}
-
-	/**
-	 * Starts a ViewLogTable Activity.
-	 * 
-	 * @param view
-	 *            View elements which triggers the method call.
-	 * @see ViewLogTable
-	 */
-	public void showLog(View view) {
-		startActivity(new Intent(this, ViewLogTable.class));
-		// TODO Delete
-
-	}
-
-	/**
-	 * Uploads a JSON Representation of each attack to a server, specified in
-	 * the preferences.<br>
-	 * The method only uploads information about attacks that have net been
-	 * uploaded yet.<br>
-	 * The local and remote IP of each record will be replaced with the external
-	 * IP of then device at the time of the upload. For the Upload it uses a
-	 * HttpPost with a HttpsClient, which does not validate any certificates.<br>
-	 * The Upload runs in its own Thread.<br>
-	 * While uploading the method also creates a notification to inform the user
-	 * about the status of the upload.<br>
-	 * <b>Only uploads Records with a external IP that is not null!
-	 * 
-	 * @param view
-	 *            View elements which triggers the method call.
-	 * @see de.tudarmstadt.informatik.hostage.net.MySSLSocketFactory
-	 */
-	public void uploadDatabase(View view) {
-		// Create a Notification
-		final NotificationCompat.Builder builder;
-		final NotificationManager mNotifyManager;
-		final int lastUploadedAttackId = pref.getInt("LAST_UPLOADED_ATTACK_ID",
-				-1);
-		int currentAttackId = pref.getInt("ATTACK_ID_COUNTER", 0);
-		// Check if there are new records to upload
-		if (lastUploadedAttackId == currentAttackId - 1) {
-			// Inform user that no upload is necessary
-			Toast.makeText(this, "All data have already been uploaded.",
-					Toast.LENGTH_SHORT).show();
-			return;
-		}
-		// Build and show Upload Notification in notification bar
-		builder = new NotificationCompat.Builder(this)
-				.setContentTitle(this.getString(R.string.app_name))
-				.setContentText("Upload in progress...")
-				.setTicker("Uploading Data...")
-				.setSmallIcon(R.drawable.ic_launcher)
-				.setWhen(System.currentTimeMillis());
-		TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
-		stackBuilder.addParentStack(MainActivity.class);
-		stackBuilder.addNextIntent(new Intent());
-		PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
-				PendingIntent.FLAG_UPDATE_CURRENT);
-		builder.setContentIntent(resultPendingIntent);
-		builder.setAutoCancel(true);
-		builder.setOnlyAlertOnce(false);
-		mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
-		mNotifyManager.notify(2, builder.build());
-		final Context context = this;
-		// Create a new Thread for upload
-		new Thread(new Runnable() {
-			@Override
-			public void run() {
-				// get RecordList
-				ArrayList<Record> recordList = null;// logger.getRecordOfEachAttack(lastUploadedAttackId);
-				final int progressMax = recordList.size();
-				Log.i("SQLLogger", "Logs to upload: " + progressMax);
-
-				int progressBarStatus = 0;
-				int retry_counter = 0;
-				while (progressBarStatus < progressMax) {
-					Record record = recordList.get(progressBarStatus);
-					// Only upload records with a saved external ip
-					if (record.getExternalIP() != null) {
-						retry_counter = 0;
-						if (HelperUtils.uploadSingleRecord(context, record)) {
-							// Update Notification progress bar
-							progressBarStatus++;
-							builder.setProgress(progressMax, progressBarStatus,
-									false);
-							// Update the progress bar
-							mNotifyManager.notify(2, builder.build());
-						} else {
-							retry_counter++;
-							if (retry_counter == 3) {
-								retry_counter = 0;
-								progressBarStatus++;
-							}
-						}
-					}
-				}
-
-				if (progressBarStatus == progressMax) {
-					// When the loop is finished, updates the notification
-					builder.setContentText("Upload complete")
-							.setTicker("Upload complete")
-							// Removes the progress bar
-							.setProgress(0, 0, false);
-					mNotifyManager.notify(2, builder.build());
-				}
-			}
-		}).start();
-		editor.putInt("LAST_UPLOADED_ATTACK_ID", currentAttackId - 1);
-		editor.commit();
-	}
-
-	/**
-	 * Shows a Dialog to confirm that the database should be cleared. If
-	 * confirmed {@link SQLLogger#clearData()} is called.
-	 * 
-	 * @see ILogger#clearData()
-	 */
-	private void deleteAll() {
-		AlertDialog.Builder builder = new AlertDialog.Builder(this);
-		builder.setMessage(R.string.gui_dialog_clear_database)
-				.setPositiveButton(R.string.gui_clear,
-						new DialogInterface.OnClickListener() {
-							@Override
-							@SuppressLint("NewApi")
-							public void onClick(DialogInterface dialog, int id) {
-								// Clear all Data
-								// logger.clearData();
-								editor.putInt("ATTACK_ID_COUNTER", 0);
-								editor.putInt("LAST_UPLOADED_ATTACK_ID", -1);
-								editor.commit();
-								Toast.makeText(getApplicationContext(),
-										"Database cleared!", Toast.LENGTH_SHORT)
-										.show();
-								// Recreate the activity
-								if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
-									recreate();
-								} else {
-									Intent intent = getIntent();
-									finish();
-									startActivity(intent);
-								}
-							}
-						})
-				.setNegativeButton(R.string.gui_cancel,
-						new DialogInterface.OnClickListener() {
-							@Override
-							public void onClick(DialogInterface dialog, int id) {
-								// User cancelled the dialog
-							}
-						});
-		// Create the AlertDialog object
-		builder.create();
-		builder.show();
-	}
-
-	/**
-	 * Shows a List with all recorded BSSIDs. If a BSSID is selected the method
-	 * calls {@link ILogger#deleteByBSSID(String)} to delete all records with
-	 * the chosen BSSID
-	 * 
-	 * @see ILogger#deleteByBSSID
-	 */
-	private void deleteByBSSID() {
-		AlertDialog.Builder builder = new AlertDialog.Builder(this);
-		final String[] bssidArray = null;// logger.getAllBSSIDS();
-		final String[] strings = new String[bssidArray.length];
-		for (int i = 0; i < bssidArray.length; i++) {
-			strings[i] = bssidArray[i] + " (" // + logger.getSSID(bssidArray[i])
-					+ ")";
-		}
-		builder.setTitle(R.string.gui_delete_dialog_title);
-		builder.setItems(strings, new DialogInterface.OnClickListener() {
-			@Override
-			@SuppressLint("NewApi")
-			public void onClick(DialogInterface dialog, int position) {
-
-				// logger.deleteByBSSID(bssidArray[position]);
-				Toast.makeText(
-						getApplicationContext(),
-						"All entries with bssid '" + bssidArray[position]
-								+ "' deleted.", Toast.LENGTH_SHORT).show();
-				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
-					recreate();
-				} else {
-					Intent intent = getIntent();
-					finish();
-					startActivity(intent);
-				}
-			}
-		});
-		builder.create();
-		builder.show();
-	}
-
-	/**
-	 * Creates a DatePicking Dialog where the user can choose a date. Afterwards
-	 * {@link ViewLog#deleteByDate(int, int, int)} is called.
-	 */
-	private void deleteByDate() {
-		showDialog(0);
-	}
-
-	/**
-	 * Shows a Dialog with the given date and ask him to confirm deleting
-	 * records that are older than the shown date. When the user confirms
-	 * {@link ILogger#deleteByDate(long)} is called with a long representation
-	 * of the Date. If the user cancels the Dialog nothing happens and the
-	 * dialog disappears.
-	 * 
-	 * @param year
-	 * @param monthOfYear
-	 * @param dayOfMonth
-	 */
-	private void deleteByDate(int year, int monthOfYear, int dayOfMonth) {
-		TimePicker timePicker = new TimePicker(this);
-		final Calendar calendar = Calendar.getInstance();
-		calendar.set(year, monthOfYear, dayOfMonth,
-				timePicker.getCurrentHour(), timePicker.getCurrentMinute(), 0);
-		AlertDialog.Builder builder = new AlertDialog.Builder(this);
-		builder.setTitle(R.string.gui_dialog_clear_database_date)
-				.setMessage(sdf.format(calendar.getTime()))
-				.setPositiveButton(R.string.gui_delete,
-						new DialogInterface.OnClickListener() {
-							@Override
-							@SuppressLint("NewApi")
-							public void onClick(DialogInterface dialog, int id) {
-								long time = calendar.getTimeInMillis();
-								// Delete Data
-								// logger.deleteByDate(time);
-								Toast.makeText(getApplicationContext(),
-										"Data sets deleted!",
-										Toast.LENGTH_SHORT).show();
-								// Recreate the activity
-								if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
-									recreate();
-								} else {
-									Intent intent = getIntent();
-									finish();
-									startActivity(intent);
-								}
-							}
-						})
-				.setNegativeButton(R.string.gui_cancel,
-						new DialogInterface.OnClickListener() {
-							@Override
-							public void onClick(DialogInterface dialog, int id) {
-								// User cancelled the dialog
-							}
-						});
-		// Create the AlertDialog object
-		builder.create();
-		builder.show();
-	}
-
-	/**
-	 * Exports all records in a given format. Before exporting checks export
-	 * location from preferences.
-	 * 
-	 * @param format
-	 *            Integer coded export format
-	 * @see Record#toString(int)
-	 */
-	private void exportDatabase(int format) {
-		try {
-			FileOutputStream log;
-			String filename = "hostage_" + format + "_"
-					+ System.currentTimeMillis() + ".log";
-			boolean externalStorage = pref.getBoolean("pref_external_storage",
-					false);
-			String externalLocation = pref.getString("pref_external_location",
-					"");
-			if (externalStorage) {
-				String root = Environment.getExternalStorageDirectory()
-						.toString();
-				if (root != null && HelperUtils.isExternalStorageWritable()) {
-					File dir = new File(root + externalLocation);
-					dir.mkdirs();
-					File file = new File(dir, filename);
-					log = new FileOutputStream(file);
-				} else {
-					Toast.makeText(this, "Could not write to SD Card",
-							Toast.LENGTH_SHORT).show();
-					return;
-				}
-
-			} else {
-				log = this.openFileOutput(
-						"hostage_" + format + "_" + System.currentTimeMillis()
-								+ ".log", Context.MODE_PRIVATE);
-			}
-
-			ArrayList<Record> records = null;// logger.getAllRecords();
-			for (Record record : records) {
-				log.write((record.toString((format == 1) ? TraCINgFormatter
-						.getInstance() : null)).getBytes());
-			}
-			log.flush();
-			log.close();
-			Toast.makeText(
-					this,
-					externalStorage ? filename + " saved on external memory! "
-							+ externalLocation : filename
-							+ " saved on internal memory!", Toast.LENGTH_LONG)
-					.show();
-		} catch (Exception e) {
-			Toast.makeText(this, "Could not write to SD Card",
-					Toast.LENGTH_SHORT).show();
-			e.printStackTrace();
-		}
-	}
-
-	/**
-	 * Initializes the Statistics. Creates a table row for every protocol and
-	 * checks the dabase for the attack count. Calls
-	 * {@link ViewLog#setFirstAndLastAttack()} to set the TextViews.
-	 * 
-	 * @see ILogger#getAttackCount()
-	 * @see ILogger#getAttackPerProtocolCount(String)
-	 */
-	private void initStatistic() {
-		TableLayout table = (TableLayout) findViewById(R.id.layoutContainer);
-
-		ArrayList<String> protocols = new ArrayList<String>();
-		protocols.add("Total");
-		protocols.addAll(Arrays.asList(getResources().getStringArray(
-				R.array.protocols)));
-
-		for (String protocol : protocols) {
-			TableRow row = new TableRow(this);
-			TextView protocolName = new TextView(this);
-			protocolName.setBackgroundResource(R.color.dark_grey);
-			protocolName.setText(protocol);
-			protocolName.setTextAppearance(this,
-					android.R.style.TextAppearance_Medium);
-			protocolName.setPadding(6, 0, 0, 0);
-			row.addView(protocolName);
-			TextView value = new TextView(this);
-			value.setBackgroundResource(R.color.light_grey);
-			value.setTextAppearance(this, android.R.style.TextAppearance_Medium);
-			value.setGravity(Gravity.RIGHT);
-			value.setPadding(3, 0, 3, 0);
-			row.addView(value);
-			if (protocol.equals("Total")) {
-				value.setText(""); // + logger.getAttackCount());
-			} else {
-				value.setText("");// +
-									// logger.getAttackPerProtocolCount(protocol));
-			}
-			table.addView(row);
-		}
-		setFirstAndLastAttack();
-	}
-
-	/**
-	 * Sets the TextViews for first and last attack.
-	 * 
-	 * @see ILogger#getSmallestAttackId()
-	 * @see ILogger#getHighestAttackId()
-	 * @see ILogger#getRecordOfAttackId(long)
-	 */
-	private void setFirstAndLastAttack() {
-		Record firstAttack = null;// logger.getRecordOfAttackId(logger.getSmallestAttackId());
-		Record lastAttack = null;// logger.getRecordOfAttackId(logger.getHighestAttackId());
-		if (firstAttack != null) {
-			Date resultdate = new Date(firstAttack.getTimestamp());
-			TextView text = (TextView) findViewById(R.id.textFirstAttackValue);
-			text.setText(sdf.format(resultdate));
-			text = (TextView) findViewById(R.id.textLastAttackValue);
-			resultdate = new Date(lastAttack.getTimestamp());
-			text.setText(sdf.format(resultdate));
-		} else {
-			TextView text = (TextView) findViewById(R.id.textFirstAttackValue);
-			text.setText("-");
-			text = (TextView) findViewById(R.id.textLastAttackValue);
-			text.setText("-");
-		}
-	}
-
-	@Override
-	protected void onCreate(Bundle savedInstanceState) {
-		super.onCreate(savedInstanceState);
-		setContentView(R.layout.activity_viewlog);
-		pref = PreferenceManager.getDefaultSharedPreferences(this);
-		editor = pref.edit();
-		initStatistic();
-	}
-
-	@Override
-	protected Dialog onCreateDialog(int id) {
-		switch (id) {
-		case 0:
-			final Calendar cal = Calendar.getInstance();
-			int pYear = cal.get(Calendar.YEAR);
-			int pMonth = cal.get(Calendar.MONTH);
-			int pDay = cal.get(Calendar.DAY_OF_MONTH);
-			return new DatePickerDialog(this,
-					new DatePickerDialog.OnDateSetListener() {
-						@Override
-						public void onDateSet(DatePicker view, int year,
-								int monthOfYear, int dayOfMonth) {
-							deleteByDate(year, monthOfYear, dayOfMonth);
-						}
-					}, pYear, pMonth, pDay);
-		}
-		return null;
-	}
-}

+ 0 - 37
src/de/tudarmstadt/informatik/hostage/ui/ViewLogTable.java

@@ -1,37 +0,0 @@
-package de.tudarmstadt.informatik.hostage.ui;
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.widget.ScrollView;
-import android.widget.TextView;
-import de.tudarmstadt.informatik.hostage.logging.Record;
-import de.tudarmstadt.informatik.hostage.persistence.HostageDBOpenHelper;
-
-/**
- * Creates a simple log view. Shows the Information for every attack. The format
- * ist defined in {@link Record#toString(int)}.
- * 
- * @author Lars Pandikow
- * 
- */
-public class ViewLogTable extends Activity {
-
-	@Override
-	protected void onCreate(Bundle savedInstanceState) {
-		super.onCreate(savedInstanceState);
-		HostageDBOpenHelper dbh = new HostageDBOpenHelper(getBaseContext());
-		StringBuffer log = new StringBuffer();
-		// Create a log entry for every attack in the Database
-		for (Record record : dbh.getAllRecords()) {
-			log.append(record.toString());
-		}
-
-		ScrollView scroll = new ScrollView(this);
-		TextView text = new TextView(getApplicationContext());
-		text.setText(log);
-		text.setTextAppearance(this, android.R.style.TextAppearance_Medium);
-		scroll.addView(text);
-		setContentView(scroll);
-	}
-
-}