mip-it 10 years ago
parent
commit
29f748ae26

+ 54 - 1
src/de/tudarmstadt/informatik/hostage/HoneyListener.java

@@ -20,11 +20,21 @@ import de.tudarmstadt.informatik.hostage.protocol.Protocol;
 import de.tudarmstadt.informatik.hostage.protocol.SSLProtocol;
 import de.tudarmstadt.informatik.hostage.ui.MainActivity;
 import de.tudarmstadt.informatik.hostage.wrapper.ByteArray;
-
+/**
+ * Protocol listener class:<br>
+ * Creates a Socket on the port of a given protocol and listens for incoming connections.<br>
+ * For each connection creates a Socket and instantiate an {@link AbstractHandler}.
+ * @author Mihai Plasoianu 
+ *
+ */
 public class HoneyListener implements Runnable {
 
 	private ArrayList<AbstractHandler> handlers = new ArrayList<AbstractHandler>();
 
+	/**
+	 * Determines the amount of active handlers.
+	 * @return The number of active handlers.
+	 */
 	public int getHandlerCount() {
 		return handlers.size();
 	}
@@ -42,10 +52,19 @@ public class HoneyListener implements Runnable {
 
 	private boolean running = false;
 
+	/**
+	 * Determines if the service is running.
+	 * @return True if the service is running, else false.
+	 */
 	public boolean isRunning() {
 		return running;
 	}
 
+	/**
+	 * Constructor for the class. Instantiate class variables.
+	 * @param service The Background service that started the listener. 
+	 * @param protocol The Protocol on which the listener is running.
+	 */
 	public HoneyListener(HoneyService service, Protocol protocol) {
 		this.service = service;
 		this.protocol = protocol;
@@ -64,6 +83,9 @@ public class HoneyListener implements Runnable {
 		}
 	}
 
+	/**
+	 * Starts the listener. Creates a server socket runs itself in a new Thread and notifies the background service.
+	 */
 	public void start() {
 		try {
 			server = new MyServerSocketFactory().createServerSocket(protocol
@@ -78,6 +100,9 @@ public class HoneyListener implements Runnable {
 		}
 	}
 
+	/**
+	 * Stops the listener. Closes the server socket, interrupts the Thread its running in and notifies the background service.
+	 */
 	public void stop() {
 		try {
 			server.close();
@@ -91,10 +116,17 @@ public class HoneyListener implements Runnable {
 		}
 	}
 
+	/**
+	 * Determine the name of the protocol the listener is running on.
+	 * @return Name of the protocol
+	 */
 	public String getProtocolName() {
 		return protocol.toString();
 	}
 
+	/**
+	 * Remove all terminated handlers from its internal ArrayList.
+	 */
 	public void refreshHandlers() {
 		for (Iterator<AbstractHandler> iterator = handlers.iterator(); iterator
 				.hasNext();) {
@@ -105,6 +137,9 @@ public class HoneyListener implements Runnable {
 		}
 	}
 
+	/**
+	 * Waits for an incoming connection, accepts it and starts a {@link AbstractHandler}
+	 */
 	private void addHandler() {
 		try {
 			Socket client = server.accept();
@@ -124,6 +159,11 @@ public class HoneyListener implements Runnable {
 		}
 	}
 
+	/**
+	 * Creates a SSLSocket out of the given socket and starts a {@link AbstractHandler}.
+	 * @param client The socket with the accepted connection.
+	 * @throws Exception
+	 */
 	private void startSecureHandler(Socket client) throws Exception {
 		SSLContext sslContext = ((SSLProtocol) protocol).getSSLContext();
 		SSLSocketFactory factory = sslContext.getSocketFactory();
@@ -134,11 +174,24 @@ public class HoneyListener implements Runnable {
 				.newInstance(), sslClient));
 	}
 
+	/**
+	 * Starts a {@link AbstractHandler} with the given socket.
+	 * @param client The socket with the accepted connection.
+	 * @throws Exception
+	 */
 	private void startHandler(Socket client) throws Exception {
 		handlers.add(newInstance(service, this, protocol.getClass()
 				.newInstance(), client));
 	}
 
+	/**
+	 * Creates a new instance of an {@link AbstractHandler}.
+	 * @param service The background service
+	 * @param listener The listener that created the handler
+	 * @param protocol The Protocol the handler will run on
+	 * @param client The Socket the handler uses
+	 * @return A Instance of a {@link AbstractHandler} with the specified parameter.
+	 */
 	private AbstractHandler newInstance(HoneyService service,
 			HoneyListener listener, Protocol protocol, Socket client) {
 		if (protocol.getType().equals(String.class)) {

+ 73 - 13
src/de/tudarmstadt/informatik/hostage/HoneyService.java

@@ -27,13 +27,20 @@ import de.tudarmstadt.informatik.hostage.logging.Logger;
 import de.tudarmstadt.informatik.hostage.logging.SQLLogger;
 import de.tudarmstadt.informatik.hostage.protocol.Protocol;
 import de.tudarmstadt.informatik.hostage.ui.MainActivity;
-
+/**
+ * Background service running as long as at least one protocol is active.
+ * Service controls start and stop of protocol listener.
+ * Notifies GUI about events happening in the background.
+ * Creates Notifications to inform the user what it happening.
+ * @author Mihai Plasoianu 
+ * @author Lars Pandikow
+ */
 public class HoneyService extends Service {
 
 	private ArrayList<HoneyListener> listeners = new ArrayList<HoneyListener>();
 	private NotificationCompat.Builder builder;
 	private SharedPreferences pref;
-	Editor editor;
+	private Editor editor;
 	private boolean stopped = false;
 
 	public List<HoneyListener> getListeners() {
@@ -56,8 +63,6 @@ public class HoneyService extends Service {
 
 	@Override
 	public IBinder onBind(Intent intent) {
-		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
-		mNotificationManager.cancel(2);
 		return mBinder;
 	}
 
@@ -88,12 +93,18 @@ public class HoneyService extends Service {
 		unregisterNetReceiver();
 	}
 	
-	// Delete session data
+	/**
+	 * Deletes all session related data.
+	 */
 	private void deleteSessionData(){
     	editor.clear();
     	editor.commit();
 	}
 	
+	/**
+	 * Register broadcast receiver for custom broadcast.
+	 * @see MainActivity#BROADCAST
+	 */
 	private void registerNetReceiver() {
 	    // register BroadcastReceiver on network state changes	    
 		IntentFilter intent = new IntentFilter();
@@ -101,15 +112,18 @@ public class HoneyService extends Service {
 	    registerReceiver(netReceiver, intent);
 	}
 
+	/**
+	 * Unregister broadcast receiver for custom broadcast.
+	 * @see MainActivity#BROADCAST
+	 */
 	private void unregisterNetReceiver() {
 		unregisterReceiver(netReceiver);
 	}
-	
-	private void mStopSelf(){
-		stopped = true;
-		stopSelf();	
-	}
 
+	/**
+	 * Receiver for custom broadcast.
+	 * @see MainActivity#BROADCAST
+	 */
 	private BroadcastReceiver netReceiver = new BroadcastReceiver() {
 		@Override
 		public void onReceive(Context context, Intent intent) {
@@ -124,7 +138,18 @@ public class HoneyService extends Service {
 				}
 		}
 	};	
+	
+	/**
+	 * Service stops himself.
+	 */
+	private void mStopSelf(){
+		stopped = true;
+		stopSelf();	
+	}
 
+	/**
+	 * Creates a Notification in the notification bar.
+	 */
 	private void createNotification() {
 		DatabaseHandler dbh = new DatabaseHandler(this);
 		boolean activeHandlers = false;
@@ -162,6 +187,9 @@ public class HoneyService extends Service {
 		mNotificationManager.notify(1, builder.build());
 	}
 	
+	/**
+	 * Updates the notification when a attack is registered.
+	 */
 	private void updateNotification() {
 		SharedPreferences defaultPref = PreferenceManager.getDefaultSharedPreferences(this);
 		String strRingtonePreference = defaultPref.getString("pref_notification_sound", "content://settings/system/notification_sound");  
@@ -170,6 +198,7 @@ public class HoneyService extends Service {
 				.setTicker("Honeypot under attack!")
 				.setContentText("Network is infected!")
 				.setSmallIcon(R.drawable.ic_service_red)
+				.setAutoCancel(true)
 				.setWhen(System.currentTimeMillis())
 				.setSound(Uri.parse(strRingtonePreference)); 
 		TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
@@ -186,6 +215,9 @@ public class HoneyService extends Service {
 		mNotificationManager.notify(1, builder.build());
 	}
 
+	/**
+	 * Cancels the Notification
+	 */
 	private void cancelNotification() {
 		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
 		mNotificationManager.cancel(1);
@@ -216,6 +248,10 @@ public class HoneyService extends Service {
 		mNotificationManager.notify(2, builder.build());
 	}
 
+	/**
+	 * Creates a instance of each protocol defined in /res/values/protocols.xml and puts it in a List
+	 * @return ArrayList of {@link de.tudarmstadt.informatik.hostage.protocol.Protocol}
+	 */
 	private ArrayList<Protocol> getProtocolArray() {
 		String[] protocols = getResources().getStringArray(R.array.protocols);
 		String packageName = Protocol.class.getPackage().getName();
@@ -233,6 +269,10 @@ public class HoneyService extends Service {
 		return protocolArray;
 	}
 	
+	/**
+	 * Determines if there are running listeners.
+	 * @return True if there is a running listener, else false.
+	 */
 	public boolean hasRunningListeners(){
 		for (HoneyListener listener : listeners) {
 				if (listener.isRunning())
@@ -241,8 +281,11 @@ public class HoneyService extends Service {
 		return false;
 	}
 
-	// IPC
-	
+	/**
+	 * Notifies the GUI about a event.
+	 * @param protocol The protocol where the event happend.
+	 * @param key The key for the event.
+	 */
 	public void notifyUI(String protocol, String key) {
 		// Send Notification
 		if (key.equals(MainActivity.HANDLER_COUNT)){
@@ -253,7 +296,9 @@ public class HoneyService extends Service {
 		LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
 	}	
 	
-
+	/**
+	 * Starts all listeners which are not already running
+	 */
 	public void startListeners() {
 		for (HoneyListener listener : listeners) {
 			if(!listener.isRunning()){
@@ -263,6 +308,9 @@ public class HoneyService extends Service {
 		Toast.makeText(getApplicationContext(), "SERVICES STARTED!", Toast.LENGTH_SHORT).show();
 	}
 
+	/**
+	 * Stops all running listeners.
+	 */
 	public void stopListeners() {
 		for (HoneyListener listener : listeners) {
 			if(listener.isRunning()){
@@ -272,6 +320,10 @@ public class HoneyService extends Service {
 		Toast.makeText(getApplicationContext(), "SERVICES STOPPED!", Toast.LENGTH_SHORT).show();
 	}
 
+	/**
+	 * Starts the listener for the specified protocol.
+	 * @param protocolName Name of the protocol that should be started.
+	 */ 
 	public void startListener(String protocolName) {
 		for (HoneyListener listener : listeners) {
 			if (listener.getProtocolName().equals(protocolName)) {
@@ -283,6 +335,10 @@ public class HoneyService extends Service {
 		Toast.makeText(getApplicationContext(), protocolName + " SERVICE STARTED!", Toast.LENGTH_SHORT).show();
 	}
 
+	/**
+	 * Stops the listener for the specified protocol.
+	 * @param protocolName Name of the protocol that should be stopped.
+	 */ 
 	public void stopListener(String protocolName) {
 		for (HoneyListener listener : listeners) {
 			if (listener.getProtocolName().equals(protocolName)) {
@@ -294,6 +350,10 @@ public class HoneyService extends Service {
 		Toast.makeText(getApplicationContext(), protocolName + " SERVICE STOPPED!", Toast.LENGTH_SHORT).show();
 	}
 
+	/**
+	 * Toggles a listener for specified protocol.
+	 * @param protocolName Name of the protocol that should be toggled.
+	 */
 	public void toggleListener(String protocolName) {
 		for (HoneyListener listener : listeners) {
 			if (listener.getProtocolName().equals(protocolName)) {

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

@@ -9,7 +9,12 @@ import org.apache.http.util.EntityUtils;
 import org.json.JSONObject;
 
 import android.os.AsyncTask;
-
+/**
+ * A {@link android.os.AsyncTask} that determines and returns the external IP address of the device.
+ * Therefore it uses a given URL to get a JSON Object containing the external IP address.
+ * @author Lars Pandikow
+ *
+ */
 public class GetExternalIPTask extends AsyncTask<String, Void, String> {
 	 @Override
     protected String doInBackground(String... url) {

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

@@ -30,8 +30,19 @@ import android.net.wifi.WifiManager;
 import android.os.Environment;
 import android.text.TextUtils;
 
+/**
+ * Helper class with some static methods for general usage.
+ * @author Lars Pandikow
+ * @author Wulf Pfeiffer
+ *
+ */
 public final class HelperUtils {
 
+	/**
+	 * Gets SSID of the wireless network.
+	 * @param context Needs a context to get system recourses
+	 * @return SSID of wireless network if connected, else null.
+	 */
 	public static String getSSID(Context context) {
 		String ssid = null;
 		ConnectivityManager connManager = (ConnectivityManager) context
@@ -50,6 +61,11 @@ public final class HelperUtils {
 		return ssid;
 	}
 
+	/**
+	 * Gets BSSID of the wireless network.
+	 * @param context Needs a context to get system recourses.
+	 * @return BSSID of wireless network if connected, else null.
+	 */
 	public static String getBSSID(Context context) {
 		String bssid = null;
 		ConnectivityManager connManager = (ConnectivityManager) context
@@ -68,6 +84,11 @@ public final class HelperUtils {
 		return bssid;
 	}
 
+	/**
+	 * Gets internal IP address of the device in a wireless network.
+	 * @param context Needs a context to get system recourses.
+	 * @return internal IP of the device in a wireless network if connected, else null.
+	 */
 	public static String getInternalIP(Context context) {
 		String ipAddress = null;
 		ConnectivityManager connManager = (ConnectivityManager) context
@@ -97,6 +118,12 @@ public final class HelperUtils {
 				(byte) ((bytes >>> 24) & 0xff) };
 	}
 
+	/**
+	 * Determines and returns the external IP address of the device.
+	 * @param context  Needs a context to get system recourses.
+	 * @return A String representation of the external IP of the device.
+	 * @see GetExternalIPTask
+	 */
 	public static String getExternalIP(Context context) {
 		String ipAddress = null;
 		GetExternalIPTask task = new GetExternalIPTask();
@@ -104,16 +131,18 @@ public final class HelperUtils {
 		try {
 			ipAddress =  task.get();
 		} catch (InterruptedException e) {
-			// TODO Auto-generated catch block
 			e.printStackTrace();
 		} catch (ExecutionException e) {
-			// TODO Auto-generated catch block
 			e.printStackTrace();
 		}
 		return ipAddress;
 	}
 	 
-	
+	/**
+	 * Updates the connextion info and saves them in the the SharedPreferences for session data.
+	 * @param context Needs a context to get system recourses.
+	 * @see MainActivity#SESSION_DATA
+	 */
 	public static void updateConnectionInfo(Context context) {	
 		SharedPreferences pref = context.getSharedPreferences(MainActivity.SESSION_DATA, Context.MODE_PRIVATE);
 		Editor editor = pref.edit();
@@ -124,7 +153,10 @@ public final class HelperUtils {
 		editor.commit();
 	}	
 
-	/* Checks if external storage is available for read and write */
+	/**
+	 * 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)) {
@@ -133,6 +165,11 @@ public final class HelperUtils {
 		return false;
 	}
 
+	/**
+	 * Creates a HttpClient with an own SSL Socket.
+	 * @return HttpsClient who accepts accepts all certificates.
+	 * @see MySSLSocketFactory
+	 */
 	public static HttpClient createHttpClient() {
 		try {
 			KeyStore trustStore = KeyStore.getInstance(KeyStore
@@ -161,7 +198,12 @@ public final class HelperUtils {
 		}
 	}
 	
-		public static byte[] concat(byte[]... bytes) {
+	/**
+	 * Concatenates several byte arrays.
+	 * @param bytes The byte arrays.
+	 * @return A single byte arrays containing all the bytes from the given arrays in the order they are given.
+	 */
+	public static byte[] concat(byte[]... bytes) {
 		int newSize = 0;
 		for (byte[] b : bytes)
 			newSize += b.length;

+ 64 - 64
src/de/tudarmstadt/informatik/hostage/logging/DatabaseHandler.java

@@ -166,6 +166,67 @@ public class DatabaseHandler extends SQLiteOpenHelper {
 		// return record list
 		return recordList;
 	}
+    
+	// Getting first Record for each AttackId greater than a given id
+    public Record getRecordOfAttackId(long attack_id) {
+        String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_BSSIDS + " WHERE " + KEY_ATTACK_ID + " = " + attack_id + " GROUP BY " + KEY_ATTACK_ID;
+        SQLiteDatabase db = this.getReadableDatabase();
+        Cursor cursor = db.rawQuery(selectQuery, null);
+        Record record = null;
+        
+		if (cursor.moveToFirst()) {
+				record = createRecord(cursor);
+		}
+        cursor.close();
+ 
+        // return count
+        db.close();
+        return record;
+    }
+    
+	// Getting first Record for each AttackId
+    public ArrayList<Record> getRecordOfEachAttack() {
+    	ArrayList<Record> recordList = new ArrayList<Record>();
+        String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_BSSIDS + " GROUP BY " + KEY_ATTACK_ID;
+        SQLiteDatabase db = this.getReadableDatabase();
+        Cursor cursor = db.rawQuery(selectQuery, null);
+		
+        // looping through all rows and adding to list
+		if (cursor.moveToFirst()) {
+			do {
+				Record record = createRecord(cursor);
+				// Adding record to list
+				recordList.add(record);
+			} while (cursor.moveToNext());
+		}       
+        cursor.close();
+ 
+        // return count
+        db.close();
+        return recordList;
+    }
+    
+	// Getting first Record for each AttackId greater than a given id
+    public ArrayList<Record> getRecordOfEachAttack(long attack_id) {
+    	ArrayList<Record> recordList = new ArrayList<Record>();
+        String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_BSSIDS + " WHERE " + KEY_ATTACK_ID + " > " + attack_id + " GROUP BY " + KEY_ATTACK_ID;
+        SQLiteDatabase db = this.getReadableDatabase();
+        Cursor cursor = db.rawQuery(selectQuery, null);
+		
+        // looping through all rows and adding to list
+		if (cursor.moveToFirst()) {
+			do {
+				Record record = createRecord(cursor);
+				// Adding record to list
+				recordList.add(record);
+			} while (cursor.moveToNext()); 
+		}       
+        cursor.close();
+ 
+        // return count
+        db.close();
+        return recordList;
+    }
 	
 	// Getting record Count
     public int getRecordCount() {
@@ -207,7 +268,7 @@ public class DatabaseHandler extends SQLiteOpenHelper {
     }
     
     //Get the smallest AttackId
-    public int getSmallestAttackId(){
+    public long getSmallestAttackId(){
     	String selectQuery = "SELECT MIN(" + KEY_ATTACK_ID +") FROM " + TABLE_RECORDS;
         SQLiteDatabase db = this.getReadableDatabase();
         Cursor cursor = db.rawQuery(selectQuery, null);        
@@ -224,7 +285,7 @@ public class DatabaseHandler extends SQLiteOpenHelper {
     }
     
     //Get the smallest AttackId
-    public int getHighestAttackId(){
+    public long getHighestAttackId(){
     	String selectQuery = "SELECT MAX(" + KEY_ATTACK_ID +") FROM " + TABLE_RECORDS;
         SQLiteDatabase db = this.getReadableDatabase();
         Cursor cursor = db.rawQuery(selectQuery, null);
@@ -239,68 +300,7 @@ public class DatabaseHandler extends SQLiteOpenHelper {
     	db.close();
     	return result;
     }
-    
-	// Getting first Record for each AttackId
-    public ArrayList<Record> getRecordOfEachAttack() {
-    	ArrayList<Record> recordList = new ArrayList<Record>();
-        String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_BSSIDS + " GROUP BY " + KEY_ATTACK_ID;
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(selectQuery, null);
-		
-        // looping through all rows and adding to list
-		if (cursor.moveToFirst()) {
-			do {
-				Record record = createRecord(cursor);
-				// Adding record to list
-				recordList.add(record);
-			} while (cursor.moveToNext());
-		}       
-        cursor.close();
- 
-        // return count
-        db.close();
-        return recordList;
-    }
-    
-	// Getting first Record for each AttackId greater than a given id
-    public ArrayList<Record> getRecordOfEachAttack(int attack_id) {
-    	ArrayList<Record> recordList = new ArrayList<Record>();
-        String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_BSSIDS + " WHERE " + KEY_ATTACK_ID + " > " + attack_id + " GROUP BY " + KEY_ATTACK_ID;
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(selectQuery, null);
-		
-        // looping through all rows and adding to list
-		if (cursor.moveToFirst()) {
-			do {
-				Record record = createRecord(cursor);
-				// Adding record to list
-				recordList.add(record);
-			} while (cursor.moveToNext()); 
-		}       
-        cursor.close();
- 
-        // return count
-        db.close();
-        return recordList;
-    }
-    
-	// Getting first Record for each AttackId greater than a given id
-    public Record getRecordOfAttackId(int attack_id) {
-        String selectQuery = "SELECT  * FROM " + TABLE_RECORDS + " NATURAL JOIN " + TABLE_BSSIDS + " WHERE " + KEY_ATTACK_ID + " = " + attack_id + " GROUP BY " + KEY_ATTACK_ID;
-        SQLiteDatabase db = this.getReadableDatabase();
-        Cursor cursor = db.rawQuery(selectQuery, null);
-        Record record = null;
-        
-		if (cursor.moveToFirst()) {
-				record = createRecord(cursor);
-		}
-        cursor.close();
- 
-        // return count
-        db.close();
-        return record;
-    }
-    
+   
     public boolean bssidSeen(String protocol, String BSSID){
         String countQuery = "SELECT  * FROM " + TABLE_RECORDS + " WHERE " + KEY_PROTOCOL + " = " + "'" + protocol + "'" + " AND " + KEY_BSSID + " = " + "'" + BSSID + "'";
         SQLiteDatabase db = this.getReadableDatabase();

+ 0 - 46
src/de/tudarmstadt/informatik/hostage/logging/FileLogger.java

@@ -1,46 +0,0 @@
-/*package de.tudarmstadt.informatik.hostage.logging;
-
-import java.io.File;
-import java.io.FileOutputStream;
-
-import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
-import android.content.Context;
-
-public class FileLogger implements Logger {
-
-	private FileOutputStream log = null;
-
-	public FileLogger(Context context) {
-		File path = HelperUtils.getSDStorageDir("logs");
-		File logFile = new File(path, "hostage.log");
-		try {
-//TODO log auf SD speichern			log = context.openFileOutput(logFile, Context.MODE_APPEND);
-		} catch (Exception e) {
-			e.printStackTrace();
-		}
-	}
-
-	@Override
-	public synchronized void write(Record record) {
-		if (log != null) {
-			try {
-				log.write((record.toString() + "\n").getBytes());
-			} catch (Exception e) {
-				e.printStackTrace();
-			}
-		}
-	}
-
-	@Override
-	public void close() {
-		if (log != null) {
-			try {
-				log.flush();
-				log.close();
-			} catch (Exception e) {
-				e.printStackTrace();
-			}
-		}
-	}
-
-}*/

+ 84 - 5
src/de/tudarmstadt/informatik/hostage/logging/Logger.java

@@ -1,11 +1,90 @@
 package de.tudarmstadt.informatik.hostage.logging;
 
+import java.util.ArrayList;
+/**
+ * Interface to define which functionality is needed for a Logger in this application.
+ * @author Mihai Plasoianu 
+ * @author Lars Pandikow
+ *
+ */
 public interface Logger {
-
+	/**
+	 * Write a single Record to the log.
+	 * @param record The Record that has to be added.
+	 */
 	void write(Record record);
 	
-	int getAttackCount();
-
-	void close();
-
+	/**
+	 * Returns all saved Records.
+	 * @return ArrayList which contains all Records from the log.
+	 */
+	ArrayList<Record> getAllRecords();
+	/**
+	 * Returns a single Record as representative for each attack with an attack id higher then the given.
+	 * @param lastUploadedAttackId The threshold value for attack id's
+	 * @return ArrayList which contains one Record for each attack.
+	 */
+	ArrayList<Record> getRecordOfEachAttack(int lastUploadedAttackId);
+	/**
+	 * 
+	 * @param attack_id Attack id of the record
+	 * @return A Record with a specific attack id, or null if there is no Record with such an attack id.
+	 */
+	Record getRecordOfAttackId(long attack_id);
+	
+	/**
+	 * Determines the number of recorded attacks.
+	 * @return he Number of Attacks.
+	 */
+	int getAttackCount();	
+	/**
+	 * Returns the number of recorded attack for a specific protocol.
+	 * @param protocol The considered protocol.
+	 * @return The Number of recorded attacks per protocol.
+	 */
+	int getAttackPerProtokolCount(String protocol);
+	/**
+	 * Finds the smallest saved attack id.
+	 * @return The smallest saved attack id.
+	 */
+	long getSmallestAttackId();
+	/**
+	 * Finds the highest saved attack id.
+	 * @return The highest saved attack id.
+	 */
+	long getHighestAttackId();
+	
+	/**
+	 * Determines if an attack on a given protocol has already been recorded in a network with a specific BSSID.
+	 * @param protocol The considered protocol.
+	 * @param bssid The considered BSSID.
+	 * @return True if there has been a attack on a protocol in a network with the given BSSID, else returns false.
+	 */
+	boolean bssidSeen(String protocol, String bssid);
+	/**
+	 * Returns all BSSIDs in which an attack has been recorded.
+	 * @return String arrays with all recorded BSSIDs
+	 */
+	String[] getAllBSSIDS();
+	/**
+	 * Returns the last known SSID of a network with a specific BSSID.
+	 * @param bssid The considered BSSID.
+	 * @return String representation of the searched SSID, or null if there is no entry with the given BSSID
+	 */
+	String getSSID(String bssid);
+	
+	/**
+	 * Deletes all Records with a smaller time stamp than the given.
+	 * @param time The time stamp to compare with.
+	 */
+	void deleteByDate(long time);
+	/**
+	 * Deletes all Record which contain the given BSSID.
+	 * @param bssid The BSSID to compare with.
+	 */
+	void deleteByBSSID(String bssid);
+	/**
+	 * Resets complete log file.
+	 */
+	void clearData();
 }

+ 17 - 5
src/de/tudarmstadt/informatik/hostage/logging/Record.java

@@ -2,7 +2,15 @@ package de.tudarmstadt.informatik.hostage.logging;
 
 import java.io.Serializable;
 import java.net.InetAddress;
-
+/**
+ * This class defines the attributes of a record.<br>
+ * A Record is a single message exchanged between the application and an attacker.<br>
+ * The class has no own functionality except for getter and setter methods.
+ * To change the logging mechanism you have to to change the logger in {@link de.tudarmstadt.informatik.hostage.HoneyService} and 
+ * {@link de.tudarmstadt.informatik.hostage.ui.ViewLog}
+ * @author Mihai Plasoianu 
+ * @author Lars Pandikow
+ */
 public class Record implements Serializable {
 
 	private static final long serialVersionUID = 1L;
@@ -22,9 +30,7 @@ public class Record implements Serializable {
 	private int remotePort;
 	private String BSSID;
 	private String SSID;
-	private String packet;
-	
-	
+	private String packet;	
 
 	/**
 	 * @return the id
@@ -162,9 +168,15 @@ public class Record implements Serializable {
 				remotePort, packet);
 	}
 	
+	/**
+	 * Returns a string representation after a chosen format. Formats should be defined in /res/values/export_formats.xml to use {@link de.tudarmstadt.informatik.hostage.ui.ViewLog#exportDatabase(android.view.View)}
+	 * The Intger representation of the format is equal to its position in the format array.
+	 * @param format Integer representation of the format.
+	 * @return A string representation after chosen format.
+	 */
 	public String toString(int format){
 		// Choose String Format
-		// Add additional case for your own Format. Also add format Name to /res/values/export_formats/
+		// Add additional case for your own Format. Also add format Name to 
 		switch (format){
 			case 1: 
 				return String.format("{ \"src\":{\"IP\": %s, \"Port\": %d} \"dst\": {\"IP\": %s, \"Port\": %d} \"type\": 0 \"name\": \"HOsTaGe\" }", localIP.getHostAddress(), localPort, remoteIP.getHostAddress(),

+ 55 - 138
src/de/tudarmstadt/informatik/hostage/logging/SQLLogger.java

@@ -1,168 +1,85 @@
 package de.tudarmstadt.informatik.hostage.logging;
 
-import java.io.File;
-import java.io.FileOutputStream;
 import java.util.ArrayList;
 
-import org.apache.http.HttpResponse;
-import org.apache.http.client.HttpClient;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.entity.StringEntity;
-
-import de.tudarmstadt.informatik.hostage.R;
-import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
-import de.tudarmstadt.informatik.hostage.ui.MainActivity;
-import android.app.NotificationManager;
-import android.app.PendingIntent;
 import android.content.Context;
-import android.content.Intent;
-import android.content.SharedPreferences;
-import android.content.SharedPreferences.Editor;
-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.widget.Toast;
 
 public class SQLLogger implements Logger{
 	Context context;
 	DatabaseHandler dbh;
-	public static final int JSON = 0x01;
-	private int progressMax;
-	private NotificationCompat.Builder builder;
-	private NotificationManager mNotifyManager;
-	SharedPreferences pref;
-	Editor editor;
 	
 	public SQLLogger(Context context){
 		this.context = context;
 		dbh = new DatabaseHandler(context);	
-		pref = PreferenceManager.getDefaultSharedPreferences(context);
-		editor = pref.edit();
 	}
 
 	@Override
 	public synchronized void write(Record record) {
 		dbh.addRecord(record);
 	}
-	
-	public 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(context, "Could not write to SD Card", Toast.LENGTH_SHORT).show();
-					return;
-				}
-
-			} else{
-				log = context.openFileOutput("hostage_" + format + "_" + System.currentTimeMillis() + ".log", Context.MODE_PRIVATE);
-			}
-			
-			ArrayList<Record> records = dbh.getAllRecords();
-			for(Record record : records){
-					log.write((record.toString(format) + "\n").getBytes());
-			}
-			log.flush();
-			log.close();
-			Toast.makeText(context, externalStorage ? filename + " saved on external memory! " + externalLocation : filename + " saved on internal memory!", Toast.LENGTH_LONG).show();
-		} catch (Exception e) {
-			Toast.makeText(context, "Could not write to SD Card", Toast.LENGTH_SHORT).show();
-			e.printStackTrace();
-		}	
-	}	
-	
-	public void uploadDatabase(){	
-		final int lastUploadedAttackId = pref.getInt("LAST_UPLOADED_ATTACK_ID", -1);
-		int currentAttackId = pref.getInt("ATTACK_ID_COUNTER", 0);
-		if(lastUploadedAttackId == currentAttackId -1){
-			Toast.makeText(context, "All data have already been uploaded.", Toast.LENGTH_SHORT).show();
-			return;
-		}
-		// Show Upload Notification
-		builder = new NotificationCompat.Builder(context)
-							.setContentTitle(context.getString(R.string.app_name))
-							.setContentText("Upload in progress...")
-							.setTicker("Uploading Data...")
-							.setSmallIcon(R.drawable.ic_launcher)	
-							.setWhen(System.currentTimeMillis());	
-		TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
-		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) context.getSystemService(Context.NOTIFICATION_SERVICE);
-		mNotifyManager.notify(2, builder.build());
-		new Thread(new Runnable() {
-
-			  @Override
-			public void run() {				  
-					HttpClient httpclient = HelperUtils.createHttpClient();
-					ArrayList<Record> recordList = dbh.getRecordOfEachAttack(lastUploadedAttackId);
-					progressMax = recordList.size();		
-					Log.i("SQLLogger", "Logs to upload: " + progressMax);	
-							HttpPost httppost;
-							int progressBarStatus = 0;
-							for(Record record: recordList){
-								Log.i("SQLLogger", "Uploading log: " + progressBarStatus);
-								try {
-								httppost = new HttpPost(pref.getString("pref_upload", "https://ssi.cased.de"));
-								StringEntity se = new StringEntity(record.toString(JSON));
-								httppost.setEntity(se);
-								HttpResponse response = httpclient.execute(httppost);
-								Log.i("SQLLogger", "Statuscode of log "  + progressBarStatus + ": " + " " + response.getStatusLine().getStatusCode());	
-								progressBarStatus++;								
-								builder.setProgress(progressMax, progressBarStatus, false);
-			                     // Update the progress bar
-								mNotifyManager.notify(2, builder.build());
-								} catch (Exception e) {
-									Log.i("SQLLogger", "Failed");
-									// TODO Auto-generated catch block
-									e.printStackTrace();
-								}
-							}
-
-					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();				
+
+	@Override
+	public ArrayList<Record> getAllRecords() {
+		return dbh.getAllRecords();
 	}
-	
+
+	@Override
+	public ArrayList<Record> getRecordOfEachAttack(int lastUploadedAttackId) {
+		return dbh.getRecordOfEachAttack(lastUploadedAttackId);
+	}
+
 	@Override
-	public int getAttackCount(){
+	public Record getRecordOfAttackId(long attack_id) {
+		return dbh.getRecordOfAttackId(attack_id);
+	}
+
+	@Override
+	public int getAttackCount() {
 		return dbh.getAttackCount();
 	}
-	
-	public int getAttackPerProtokollCount(String protocol){
+
+	@Override
+	public int getAttackPerProtokolCount(String protocol) {
 		return dbh.getAttackPerProtokolCount(protocol);
 	}
-	
-	public void clearLog(){
-		dbh.clearData();
+
+	@Override
+	public long getSmallestAttackId() {
+		return dbh.getSmallestAttackId();
 	}
 
 	@Override
-	public void close() {
-		// TODO Auto-generated method stub		
+	public long getHighestAttackId() {
+		return dbh.getHighestAttackId();
+	}
+
+	@Override
+	public boolean bssidSeen(String protocol, String bssid) {
+		return dbh.bssidSeen(protocol, bssid);
+	}
+
+	@Override
+	public String[] getAllBSSIDS() {
+		return dbh.getAllBSSIDS();
+	}
+
+	@Override
+	public String getSSID(String bssid) {
+		return dbh.getSSID(bssid);
+	}
+
+	@Override
+	public void deleteByDate(long time) {
+		dbh.deleteByDate(time);		
+	}
+
+	@Override
+	public void deleteByBSSID(String bssid) {
+		dbh.deleteByBSSID(bssid);
+	}
+
+	@Override
+	public void clearData() {
+		dbh.clearData();
 	}
 }

+ 15 - 15
src/de/tudarmstadt/informatik/hostage/protocol/Protocol.java

@@ -3,57 +3,57 @@ package de.tudarmstadt.informatik.hostage.protocol;
 import java.util.List;
 
 /**
- * Interface for protocols that are used by hostage
- * @param <T> Denotes if the protocol is using Strings or ByteArrays
+ * Interface for protocols that are used by the application.
+ * @param <T> Denotes if the protocol is using Strings or ByteArrays.
  */
 public interface Protocol<T> {
 
 	/**
-	 * Represents who starts the communication once the connection is established
+	 * Represents who starts the communication once the connection is established.
 	 */
 	public static enum TALK_FIRST {
 		SERVER, CLIENT
 	};
 
 	/**
-	 * Returns the port on which the protocol is running
+	 * Returns the port on which the protocol is running.
 	 * @return the port used by the protocol (range: 0-65535)
 	 */
 	int getPort();
 
 	/**
 	 * Returns who starts the communication (server or client)
-	 * @return TALK_FIRST.server if the server starts or TALK_FIRST.client if the client starts
+	 * @return TALK_FIRST.server if the server starts or TALK_FIRST.client if the client starts.
 	 */
 	TALK_FIRST whoTalksFirst();
 
 	/**
-	 * Determines the next message that is sent by the server
-	 * @param message last message that was sent by the client
-	 * @return next message that will be sent
+	 * Determines the next message that is sent by the server.
+	 * @param message last message that was sent by the client.
+	 * @return next message that will be sent.
 	 */
 	List<T> processMessage(T message);
 
 	/**
-	 * Returns whether the communication is ended and the connection should be closed or not
-	 * @return true if the connection should be closed, else false
+	 * Returns whether the communication is ended and the connection should be closed or not.
+	 * @return true if the connection should be closed, else false.
 	 */
 	boolean isClosed();
 
 	/**
-	 * Returns if the protocol uses SSL/TLS connection or not
-	 * @return true if SSL/TLS is used, else false
+	 * Returns if the protocol uses SSL/TLS connection or not.
+	 * @return true if SSL/TLS is used, else false.
 	 */
 	boolean isSecure();
 
 	/**
-	 * Returns what type the protocol is using, Strings or ByteArrays
-	 * @return the class that the protocol is using
+	 * Returns what type the protocol is using, Strings or ByteArrays.
+	 * @return the class that the protocol is using.
 	 */
 	Class<T> getType();
 	
 	/**
-	 * Returns the name of the protocol
+	 * Returns the name of the protocol.
 	 * @return name of the protocol
 	 */
 	@Override 

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

@@ -6,14 +6,18 @@ import android.content.pm.PackageInfo;
 import android.content.pm.PackageManager.NameNotFoundException;
 import android.os.Bundle;
 import android.widget.TextView;
-
+/**
+ * Shows a simple About View with application version, a small discription and authors of the project.
+ * @author Lars Pandikow
+ *
+ */
 public class AboutActivity extends Activity{
 
 	@Override
 	protected void onCreate(Bundle savedInstanceState) {
 		super.onCreate(savedInstanceState);
 		setContentView(R.layout.activity_about);
-
+		// Set Version Number
 		PackageInfo pInfo;
 		try {
 			pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);

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

@@ -10,7 +10,10 @@ import android.widget.BaseAdapter;
 import android.widget.ImageView;
 import android.widget.TextView;
 import de.tudarmstadt.informatik.hostage.R;
-
+/**
+ * Custom ListViewAdapter to dynamically create a list of protocols.
+ * @author Mihai Plasoianu
+ */
 public class ListViewAdapter extends BaseAdapter {
 
 	private LayoutInflater inflater;

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

@@ -41,12 +41,30 @@ import de.tudarmstadt.informatik.hostage.HoneyService.LocalBinder;
 import de.tudarmstadt.informatik.hostage.R;
 import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
 import de.tudarmstadt.informatik.hostage.logging.DatabaseHandler;
-
+import de.tudarmstadt.informatik.hostage.logging.Logger;
+import de.tudarmstadt.informatik.hostage.logging.SQLLogger;
+/**
+ * MainActivity is the central activity for the GUI of the application.
+ * MainActivity is launched when the application is first started.
+ * It shows the user: <br>
+ * - information about the network<br>
+ * - light indicators for recorded attacks on each protocol<br>
+ * - amount of attacks on each protocols<br>
+ * The user can start and stop services.
+ * @author Mihai Plasoianu
+ * @author Lars Pandikow
+ *
+ */
 public class MainActivity extends Activity {
-
+	// String constants for whole application
+	/**
+	 * Used for Broadcast between service and GUI. String: "de.tudarmstadt.informatik.hostage.BROADCAST"
+	 */
 	public static final String BROADCAST = "de.tudarmstadt.informatik.hostage.BROADCAST";
+	/**
+	 * Used to store session related data in a SharedPrefereces. String: "de.tudarmstadt.informatik.hostage.SESSION_DATA"
+	 */
 	public static final String SESSION_DATA = "de.tudarmstadt.informatik.hostage.SESSION_DATA";
-	public static final String PERSISTENT_DATA = "de.tudarmstadt.informatik.hostage.SESSION_DATA";
 	public static final String LISTENER = "_LISTENER";
 	public static final String HANDLER_COUNT = "_HANDLER_COUNT";
 	public static final String SSID = "SSID";
@@ -54,20 +72,32 @@ public class MainActivity extends Activity {
 	public static final String INTERNAL_IP = "INTERNAL_IP";
 	public static final String EXTERNAL_IP = "EXTERNAL_IP";
 
+	/**
+	 * Integer representing a grey light.
+	 */
 	public static final int LIGHT_GREY = 0x01;
+	/**
+	 * Integer representing a green light.
+	 */
 	public static final int LIGHT_GREEN = 0x02;
+	/**
+	 * Integer representing a red light.
+	 */
 	public static final int LIGHT_RED = 0x03;
+	/**
+	 * Integer representing a yellow light.
+	 */
 	public static final int LIGHT_YELLOW = 0x04;
 
 	private HoneyService mService;
 	private boolean serviceBound;
 	private SharedPreferences pref;
 	private Editor editor;
-	private DatabaseHandler dbh;
+	private Logger logger;
 
+	// variables for the swipe animation
 	private ViewAnimator viewAnimator;
 	private GestureDetector gestureDetector;
-
 	private Animation animFlipInLR;
 	private Animation animFlipOutLR;
 	private Animation animFlipInRL;
@@ -77,16 +107,18 @@ public class MainActivity extends Activity {
 	private ListViewAdapter adapter;
 	
 	private String protocolClicked;
-
+	
 	@Override
 	protected void onCreate(Bundle savedInstanceState) {
 		super.onCreate(savedInstanceState);
 		setContentView(R.layout.activity_main);
-
+		
+		// Create dynamic view elements
 		initViewAnimator();
 		initListView();
+		// Initialize Class variables
 		pref = getSharedPreferences(MainActivity.SESSION_DATA, Context.MODE_PRIVATE);
-		dbh = new DatabaseHandler(getApplicationContext());
+		logger = new SQLLogger(this);
 		editor = pref.edit();
 	}
 
@@ -114,8 +146,10 @@ public class MainActivity extends Activity {
 	@Override
 	protected void onStart() {
 		super.onStart();
+		//Register Broadcast Receiver
 		registerReceiver();
 		registerNetReceiver();
+		// Bind service if running, else check for connection change and delete sessionData
 		if (isServiceRunning()) {
 			bindService(getServiceIntent(), mConnection, BIND_AUTO_CREATE);
 		} else {
@@ -125,15 +159,18 @@ public class MainActivity extends Activity {
 				deleteSessionData();
 			}
 		}
+		// Update UI
 		updateUI();
 		updateConnectionInfo();
 	}
 
 	@Override
 	protected void onStop() {
+		//Unbind running service
 		if (isServiceRunning()) {
 			unbindService(mConnection);
 		}
+		// Unregister Broadcast Receiver
 		unregisterNetReceiver();
 		unregisterReceiver();
 		super.onStop();
@@ -142,11 +179,16 @@ public class MainActivity extends Activity {
 	@Override
 	protected void onDestroy(){
 		super.onDestroy();
+		// If service not running delete session data
 		if(!isServiceRunning()){
 			deleteSessionData();
 		}
 	}
 
+	/**
+	 * Called when User presses on/off button
+	 * @param view
+	 */
 	public void buttonOnOffClick(View view) {
 		if (((ToggleButton) view).isChecked()) {
 			if (isParanoid()) {
@@ -160,7 +202,20 @@ public class MainActivity extends Activity {
 			stopAndUnbind();
 		}
 	}
+	
+	/**
+	 * Starts the ViewLog activity, when the Button is pressed
+	 * @see ViewLog
+	 * @param view View elements which triggers the method call.
+	 */
+	public void showLog(View view){
+		startActivity(new Intent(this, ViewLog.class));
+	}
 
+	/**
+	 * If mobile phone is connected to a wireless network starts the background service ands binds itself to it.
+	 * Else notifies the user that service could not be started.
+	 */
 	private void startAndBind() {
 		if(HelperUtils.getBSSID(this) != null){
 			startService(getServiceIntent());
@@ -172,23 +227,42 @@ public class MainActivity extends Activity {
 		}
 	}
 	
+	/**
+	 * Binds service to Activity
+	 * @see HoneyService
+	 */
 	private void bindService(){
 		bindService(getServiceIntent(), mConnection, BIND_AUTO_CREATE);
 		serviceBound = true;
 	}
 
+	/**
+	 * Stops service and unbinds it.
+	 * @see HoneyService
+	 */
 	private void stopAndUnbind() {
 		unbindService();
 		stopService(getServiceIntent());
 	}
 	
+	/**
+	 * Unbinds service.
+	 * @see HoneyService
+	 */
 	private void unbindService(){
 		unbindService(mConnection);
 		serviceBound = false;
 	}
 	
+	/**
+	 * Connection to bind the background service
+	 * @see HoneyService
+	 */
 	private ServiceConnection mConnection = new ServiceConnection() {
-
+		/** 
+		 * After the service is bound, check which has been clicked and start it.
+		 * @see android.content.ServiceConnection#onServiceConnected(android.content.ComponentName)
+		 */
 		@Override
 		public void onServiceConnected(ComponentName name, IBinder service) {
 			mService = ((LocalBinder) service).getService();
@@ -199,7 +273,11 @@ public class MainActivity extends Activity {
 			}
 			protocolClicked = null;
 		}
-
+		
+		/**
+		 * After the service is unbound, delete reference.
+		 * @see android.content.ServiceConnection#onServiceDisconnected(android.content.ComponentName)
+		 */
 		@Override
 		public void onServiceDisconnected(ComponentName name) {
 			mService = null;			
@@ -207,14 +285,26 @@ public class MainActivity extends Activity {
 
 	};
 	
+	/**
+	 * Returns an intent to start HoneyService.
+	 * @return An Intent to start HoneyService
+	 */
 	private Intent getServiceIntent() {
 		return new Intent(this, HoneyService.class);
 	}
 
+	/**
+	 * Checks if user selected paranoid mode.
+	 * @return True when paranoid mode is selected, else returns false.
+	 */
 	private boolean isParanoid() {
 		return ((CheckBox) findViewById(R.id.checkBoxParanoid)).isChecked();
 	}
 
+	/**
+	 * Initializes the ListView. Creating its contents dynamic from protocol protocols.xml
+	 * @see /res/values/protocols.xml
+	 */
 	private void initListView() {
 		ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
 		for (String protocol : getResources().getStringArray(R.array.protocols)) {
@@ -255,6 +345,11 @@ public class MainActivity extends Activity {
 		});
 	}
 
+	/**
+	 * Checks if a HoneService instance is running.
+	 * @return True if HonerService is running, else false.
+	 * @see HonerService
+	 */
 	private boolean isServiceRunning() {
 		ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
 		for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
@@ -265,39 +360,63 @@ public class MainActivity extends Activity {
 		return false;
 	}
 	
-	// Delete session data
+	/**
+	 * Deletes all session related Data.
+	 */
 	private void deleteSessionData(){
     	editor.clear();
     	editor.commit();
 	}
 
+	/**
+	 * Register broadcast receiver for custom broadcast.
+	 * @see MainActivity#BROADCAST
+	 */
 	private void registerReceiver() {
 		LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,
 				new IntentFilter(BROADCAST));
 	}
 
+	/**
+	 * Unregisters broadcast receiver for custom broadcast.
+	 * @see MainActivity#BROADCAST
+	 */
 	private void unregisterReceiver() {
 		LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
 	}
 	
+	/**
+	 * Receiver for custom broadcast.
+	 * @see MainActivity#BROADCAST
+	 */
 	private BroadcastReceiver mReceiver = new BroadcastReceiver() {
 		@Override
 		public void onReceive(Context context, Intent intent) {
+			// Update user interface.
 			updateUI();
 		}
 	};
 
-	private void registerNetReceiver() {
-	    // register BroadcastReceiver on network state changes	    
+	/**
+	 * Register broadcast receiver for network state changes.
+	 * @see ConnectivityManager#CONNECTIVITY_ACTION
+	 */
+	private void registerNetReceiver() {   
 		IntentFilter intent = new IntentFilter();
 	    intent.addAction(ConnectivityManager.CONNECTIVITY_ACTION); //"android.net.conn.CONNECTIVITY_CHANGE"
 	    registerReceiver(netReceiver, intent);
 	}
 
+	/**
+	 * Unregister broadcast receiver for network state changes.
+	 */
 	private void unregisterNetReceiver() {
 		unregisterReceiver(netReceiver);
 	}
 
+	/**
+	 * Receiver for network state change events.
+	 */
 	private BroadcastReceiver netReceiver = new BroadcastReceiver() {
 		@Override
 		public void onReceive(Context context, Intent intent) {
@@ -311,21 +430,29 @@ public class MainActivity extends Activity {
 		}
 	};	
 
+	/**
+	 * Updates Information shown by the GUI.
+	 */
 	private void updateUI() {		
 		boolean activeListeners = false;
 		boolean activeHandlers = false;
 		boolean yellowLight = false;
 		
+		//Check for all protocols if listeners are active and attacks have been recorded
+		//Update protocol lights and connection information.
 		for(String protocol : getResources().getStringArray(R.array.protocols)){
+			//Check if protocol is active
 			if(pref.getBoolean(protocol + LISTENER, false)){
 				activeListeners = true;
 				int handlerCount = pref.getInt(protocol + HANDLER_COUNT, 0);
+				//Check if attacks have been recorded in this session.
 				if(handlerCount > 0){
 					activeHandlers = true;
 					updateProtocolLight(LIGHT_RED, protocol);
 					updateProtocolConnections(handlerCount, protocol);
 				} else{
-					if(dbh.bssidSeen(protocol, HelperUtils.getBSSID(getApplicationContext()))){
+					//Check if the bssid of the wireless network has already been recorded as infected.
+					if(logger.bssidSeen(protocol, HelperUtils.getBSSID(getApplicationContext()))){
 						updateProtocolLight(LIGHT_YELLOW, protocol);
 						yellowLight = true;
 					} else{
@@ -338,6 +465,7 @@ public class MainActivity extends Activity {
 			}
 		}
 
+		//Update the big attack indicator.
 		if (activeListeners) {
 			if (activeHandlers) {
 				updateStatusLight(LIGHT_RED);
@@ -359,6 +487,14 @@ public class MainActivity extends Activity {
 		}
 	}
 
+	/**
+	 * Sets the big light indicator.
+	 * @param light Integer code to set the light color.
+	 * @see MainActivity#LIGHT_GREY 
+	 * @see MainActivity#LIGHT_GREEN
+	 * @see MainActivity#LIGHT_RED
+	 * @see MainActivity#LIGHT_YELLOW
+	 */
 	private void updateStatusLight(int light) {
 		switch (light) {
 		case LIGHT_GREY:
@@ -380,6 +516,11 @@ public class MainActivity extends Activity {
 		}
 	}
 
+	/**
+	 * Sets the light indicator for a given protocol.
+	 * @param light Integer code to set the light color.
+	 * @param protocolName Name of the protocol which should be updated.
+	 */
 	private void updateProtocolLight(int light, String protocolName) {
 		for (int i = 0; i < adapter.getCount(); ++i) {
 			HashMap<String, String> d = (HashMap<String, String>) adapter
@@ -405,6 +546,11 @@ public class MainActivity extends Activity {
 		adapter.notifyDataSetChanged();
 	}
 
+	/**
+	 * Sets the connections count for a given protocol
+	 * @param connections New value for recorded connections.
+	 * @param protocolName Name of the protocol which should be updated.
+	 */
 	private void updateProtocolConnections(int connections, String protocolName) {
 		for (int i = 0; i < adapter.getCount(); ++i) {
 			HashMap<String, String> d = ((HashMap<String, String>) adapter
@@ -416,19 +562,26 @@ public class MainActivity extends Activity {
 		adapter.notifyDataSetChanged();
 	}
 
+	/**
+	 * Gets Information about connection state and updates the GUI.
+	 */
 	private void updateConnectionInfo() {
+		//Get text fields
 		TextView ssidView = (TextView) findViewById(R.id.textViewSSIDValue);
 		TextView bssidView = (TextView) findViewById(R.id.textViewBSSIDValue);
 		TextView internalIPView = (TextView) findViewById(R.id.textViewInternalIPValue);
 		TextView externalIPView = (TextView) findViewById(R.id.textViewExternalIPValue);
 		
+		//Update the connection information
 		HelperUtils.updateConnectionInfo(this);
 		
+		//Get connection information
 		String ssid = pref.getString(SSID, "-");
 		String bssid = pref.getString(BSSID, "-");
 		String internalIP = pref.getString(INTERNAL_IP, "-");
 		String externalIP = pref.getString(EXTERNAL_IP, "-");
 
+		//Set text fields
 		if (ssid != null)
 			ssidView.setText(ssid);
 		else
@@ -448,20 +601,19 @@ public class MainActivity extends Activity {
 			externalIPView.setText(externalIP);
 		else
 			externalIPView.setText("-");		
-
-		ssidView.invalidate();
-		bssidView.invalidate();
-		internalIPView.invalidate();
 	}
 
 
-	/*############# AB HIER KOMMEN HILFSFUNKTIONEN F�R GESTEN ##################*/
+	/*############# Help functions for animation ##################*/
 	
 	@Override
 	public boolean onTouchEvent(MotionEvent event) {
 		return gestureDetector.onTouchEvent(event);
 	}
 	
+	/**
+	 * Initializes variables for screen animation
+	 */
 	private void initViewAnimator() {
 		viewAnimator = (ViewAnimator) findViewById(R.id.viewAnimator);
 		gestureDetector = new GestureDetector(this, simpleOnGestureListener);
@@ -476,6 +628,9 @@ public class MainActivity extends Activity {
 				R.anim.out_right_to_left);
 	}
 	
+	/**
+	 * Called when a swipe to the Left is registered.
+	 */
 	private void swipeRightToLeft() {
 		if (viewAnimator.getDisplayedChild() == 0) {
 			viewAnimator.setInAnimation(animFlipInRL);
@@ -484,6 +639,9 @@ public class MainActivity extends Activity {
 		}
 	}
 
+	/**
+	 * Called when a swipe to the Right is registered.
+	 */
 	private void swipeLeftToRight() {
 		if (viewAnimator.getDisplayedChild() == 1) {
 			viewAnimator.setInAnimation(animFlipInLR);
@@ -506,10 +664,4 @@ public class MainActivity extends Activity {
 			return true;
 		}
 	};
-	
-	public void showLog(View view){
-		startActivity(new Intent(this, ViewLog.class));
-	}
-
-
 }

+ 13 - 8
src/de/tudarmstadt/informatik/hostage/ui/SettingsActivity.java

@@ -8,42 +8,47 @@ import android.preference.EditTextPreference;
 import android.preference.Preference;
 import android.preference.PreferenceActivity;
 import android.widget.Toast;
-
+/**
+ * SettingsActivity creates the settings defined in /xml/preferences.xml.
+ * @author Lars Pandikow.
+ */
 public class SettingsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
-        addPreferencesFromResource(R.xml.preferences);       
+        addPreferencesFromResource(R.xml.preferences);  
+        //Set the value of the preference as the summary for the preference
         Preference pref = findPreference("pref_external_location");
         EditTextPreference etp = (EditTextPreference) pref;
         pref.setSummary(etp.getText());
         
+      //Set the value of the preference as the summary for the preference
         pref = findPreference("pref_upload_server");
         etp = (EditTextPreference) pref;
         pref.setSummary(etp.getText());
     }    
 
-    @Override
-	protected void onResume() {
+    protected void onResume() {
+    	// register a listener to catch preference changes
         super.onResume();
         getPreferenceScreen().getSharedPreferences()
                 .registerOnSharedPreferenceChangeListener(this);
     }
 
-    @Override
-	protected void onPause() {
+    protected void onPause() {
         super.onPause();
         getPreferenceScreen().getSharedPreferences()
                 .unregisterOnSharedPreferenceChangeListener(this);
     }
 
-    @Override
-	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
+    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
             String key) {
+    	// Check which preference has been changed
     	if(key.equals("pref_external_location")){
             Preference pref = findPreference(key);
             EditTextPreference etp = (EditTextPreference) pref;
             String path = etp.getText();
+            //Check if the Path is valid
             if(!path.startsWith("/"))
             	path = new String("/").concat(path);
             if(!path.endsWith("/"))

+ 253 - 69
src/de/tudarmstadt/informatik/hostage/ui/ViewLog.java

@@ -1,16 +1,31 @@
 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 org.apache.http.HttpResponse;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.StringEntity;
+
+import de.tudarmstadt.informatik.hostage.R;
+import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
+import de.tudarmstadt.informatik.hostage.logging.Logger;
+import de.tudarmstadt.informatik.hostage.logging.Record;
+import de.tudarmstadt.informatik.hostage.logging.SQLLogger;
 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;
@@ -18,7 +33,11 @@ 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;
@@ -29,22 +48,33 @@ 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.logging.DatabaseHandler;
-import de.tudarmstadt.informatik.hostage.logging.Record;
-import de.tudarmstadt.informatik.hostage.logging.SQLLogger;
-
+/**
+ * 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 {
+	
+	public static final int JSON = 0x01;
+	
+	private final SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm", Locale.US);
 
-	DatabaseHandler dbh;
-	private final Context context = this;
-	private final SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");
+	private Logger logger;
+	private SharedPreferences pref;
+	private Editor editor;
 
 	@Override
 	protected void onCreate(Bundle savedInstanceState) {
 		super.onCreate(savedInstanceState);
 		setContentView(R.layout.activity_viewlog);
-		dbh = new DatabaseHandler(getApplicationContext());
+		logger = new SQLLogger(this);
+		pref = PreferenceManager.getDefaultSharedPreferences(this);
+		editor = pref.edit();
 		initStatistic();
 	}
 
@@ -69,37 +99,171 @@ public class ViewLog extends Activity {
         return super.onOptionsItemSelected(item);
 	}
 
+	/**
+	 * 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.export_dialog_title);
 		builder.setItems(R.array.format, new DialogInterface.OnClickListener() {
-			@Override
 			public void onClick(DialogInterface dialog, int position) {
-				SQLLogger logger = new SQLLogger(context);
-				logger.exportDatabase(position);
+				exportDatabase(position);
 			}
 		});
 		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;
+				}
 
-	public void uploadDatabase(View view) {
-		SQLLogger log = new SQLLogger(this);
-		log.uploadDatabase();
+			} else{
+				log = this.openFileOutput("hostage_" + format + "_" + System.currentTimeMillis() + ".log", Context.MODE_PRIVATE);
+			}
+			
+			ArrayList<Record> records = logger.getAllRecords();
+			for(Record record : records){
+					log.write((record.toString(format) + "\n").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();
+		}	
+	}
+	
+	/**
+	 * 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.
+	 * 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.
+	 * @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());
+		// Create a new Thread for upload
+		new Thread(new Runnable() {
+			  public void run() {	
+				  	// Create a https client. Uses MySSLSocketFactory to accept all certificates
+					HttpClient httpclient = HelperUtils.createHttpClient();
+					// get RecordList
+					ArrayList<Record> recordList = logger.getRecordOfEachAttack(lastUploadedAttackId);
+					final int progressMax = recordList.size();		
+					Log.i("SQLLogger", "Logs to upload: " + progressMax);	
+							HttpPost httppost;
+							int progressBarStatus = 0;
+							for(Record record: recordList){
+								Log.i("SQLLogger", "Uploading log: " + progressBarStatus);
+								try {
+								// Create HttpPost
+								httppost = new HttpPost(pref.getString("pref_upload", "https://ssi.cased.de"));
+								// Create JSON String of Record
+								StringEntity se = new StringEntity(record.toString(JSON));
+								httppost.setEntity(se);
+								// Execute HttpPost
+								HttpResponse response = httpclient.execute(httppost);
+								Log.i("SQLLogger", "Statuscode of log "  + progressBarStatus + ": " + " " + response.getStatusLine().getReasonPhrase());	
+								Log.i("SQLLogger", "Statuscode of log "  + progressBarStatus + ": " + " " + response.getStatusLine().getStatusCode());	
+								// Update Notification progress bar
+								progressBarStatus++;								
+								builder.setProgress(progressMax, progressBarStatus, false);
+			                     // Update the progress bar
+								mNotifyManager.notify(2, builder.build());
+								} catch (Exception e) {
+									Log.i("SQLLogger", "Failed");
+									e.printStackTrace();
+								}
+							}
+							
+					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();				
 	}
 
+	/**
+	 * 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));
 	}
 
-	@SuppressLint("NewApi")
+	/**
+	 * Creates a Dialog that lets the user decide which criteria he want to use to delete records.
+	 * Then calls the corresponding method.
+	 * @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.delete_dialog_title);
 		builder.setItems(R.array.delete_criteria,
 				new DialogInterface.OnClickListener() {
-					@Override
 					public void onClick(DialogInterface dialog, int position) {
 						switch (position) {
 						case 0:
@@ -116,19 +280,47 @@ public class ViewLog extends Activity {
 		builder.create();
 		builder.show();
 	}
+	
+	/**
+	 * Shows a List with all recorded BSSIDs.
+	 * If a BSSID is selected the method calls {@link Logger#deleteByBSSID(String)} to delete all records with the chosen BSSID
+	 * @see Logger#deleteByBSSID
+	 */
+	private void deleteByBSSID() {
+		AlertDialog.Builder builder = new AlertDialog.Builder(this);
+		final String[] bssidArray = logger.getAllBSSIDS();
+		for(int i = 0; i < bssidArray.length; i++){
+			bssidArray[i] = bssidArray[i] + " (" + logger.getSSID(bssidArray[i]) +")";
+		}
+		builder.setTitle(R.string.delete_dialog_title);
+		builder.setItems(bssidArray, new DialogInterface.OnClickListener() {
+			@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);
 	}
 
-	private DatePickerDialog.OnDateSetListener pDateSetListener = new DatePickerDialog.OnDateSetListener() {
-
-		@Override
-		public void onDateSet(DatePicker view, int year, int monthOfYear,
-				int dayOfMonth) {
-			deleteByDate(year, monthOfYear, dayOfMonth);
-		}
-	};
 
 	@Override
 	protected Dialog onCreateDialog(int id) {
@@ -138,14 +330,24 @@ public class ViewLog extends Activity {
 			int pYear = cal.get(Calendar.YEAR);
 			int pMonth = cal.get(Calendar.MONTH);
 			int pDay = cal.get(Calendar.DAY_OF_MONTH);
-			return new DatePickerDialog(this, pDateSetListener, pYear, pMonth,
-					pDay);
+			return new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
+				public void onDateSet(DatePicker view, int year, int monthOfYear,
+						int dayOfMonth) {deleteByDate(year, monthOfYear, dayOfMonth);}}
+			, pYear, pMonth, pDay);
 		}
 		return null;
 	}
 
+	/**
+	 * 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 Logger#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(context);
+		TimePicker timePicker = new TimePicker(this);
 		final Calendar calendar = Calendar.getInstance();
 		calendar.set(year, monthOfYear, dayOfMonth,
 				timePicker.getCurrentHour(), timePicker.getCurrentMinute(), 0);
@@ -154,12 +356,11 @@ public class ViewLog extends Activity {
 				.setMessage(sdf.format(calendar.getTime()))
 				.setPositiveButton(R.string.delete,
 						new DialogInterface.OnClickListener() {
-							@Override
 							@SuppressLint("NewApi")
 							public void onClick(DialogInterface dialog, int id) {
 								long time = calendar.getTimeInMillis();
 								// Delete Data
-								dbh.deleteByDate(time);
+								logger.deleteByDate(time);
 								Toast.makeText(getApplicationContext(),
 										"Data sets deleted!",
 										Toast.LENGTH_SHORT).show();
@@ -175,7 +376,6 @@ public class ViewLog extends Activity {
 						})
 				.setNegativeButton(R.string.cancel,
 						new DialogInterface.OnClickListener() {
-							@Override
 							public void onClick(DialogInterface dialog, int id) {
 								// User cancelled the dialog
 							}
@@ -185,47 +385,20 @@ public class ViewLog extends Activity {
 		builder.show();
 	}
 
-	private void deleteByBSSID() {
-		AlertDialog.Builder builder = new AlertDialog.Builder(this);
-		final String[] bssidArray = dbh.getAllBSSIDS();
-		for(int i = 0; i < bssidArray.length; i++){
-			bssidArray[i] = bssidArray[i] + " (" + dbh.getSSID(bssidArray[i]) +")";
-		}
-		builder.setTitle(R.string.delete_dialog_title);
-		builder.setItems(bssidArray, new DialogInterface.OnClickListener() {
-			@Override
-			@SuppressLint("NewApi")
-			public void onClick(DialogInterface dialog, int position) {
-				dbh.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();
-	}
-
+	/**
+	 * Shows a Dialog to confirm that the database should be cleared.
+	 * If confirmed {@link SQLLogger#clearData()} is called.
+	 * @see Logger#clearData()
+	 */
 	private void deleteAll() {
 		AlertDialog.Builder builder = new AlertDialog.Builder(this);
 		builder.setMessage(R.string.dialog_clear_database)
 				.setPositiveButton(R.string.clear,
 						new DialogInterface.OnClickListener() {
-							@Override
 							@SuppressLint("NewApi")
 							public void onClick(DialogInterface dialog, int id) {
 								// Clear all Data
-								dbh.clearData();
-								SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
-								Editor editor = pref.edit();
+								logger.clearData();
 								editor.putInt("ATTACK_ID_COUNTER", 0);
 								editor.putInt("LAST_UPLOADED_ATTACK_ID", -1);
 								editor.commit();
@@ -244,7 +417,6 @@ public class ViewLog extends Activity {
 						})
 				.setNegativeButton(R.string.cancel,
 						new DialogInterface.OnClickListener() {
-							@Override
 							public void onClick(DialogInterface dialog, int id) {
 								// User cancelled the dialog
 							}
@@ -254,6 +426,12 @@ public class ViewLog extends Activity {
 		builder.show();
 	}
 
+	/**
+	 * 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 Logger#getAttackCount()
+	 * @see Logger#getAttackPerProtokolCount(String)
+	 */
 	private void initStatistic() {
 		TableLayout table = (TableLayout) findViewById(R.id.layoutContainer);
 
@@ -278,18 +456,24 @@ public class ViewLog extends Activity {
 			value.setPadding(3, 0, 3, 0);
 			row.addView(value);
 			if (protocol.equals("Total")) {
-				value.setText("" + dbh.getAttackCount());
+				value.setText("" + logger.getAttackCount());
 			} else {
-				value.setText("" + dbh.getAttackPerProtokolCount(protocol));
+				value.setText("" + logger.getAttackPerProtokolCount(protocol));
 			}
 			table.addView(row);
 		}
 		setFirstAndLastAttack();
 	}
 
+	/**
+	 * Sets the TextViews for first and last attack.
+	 * @see Logger#getSmallestAttackId()
+	 * @see Logger#getHighestAttackId()
+	 * @see Logger#getRecordOfAttackId(long)
+	 */
 	private void setFirstAndLastAttack() {
-		Record firstAttack = dbh.getRecordOfAttackId(dbh.getSmallestAttackId());
-		Record lastAttack = dbh.getRecordOfAttackId(dbh.getHighestAttackId());
+		Record firstAttack = logger.getRecordOfAttackId(logger.getSmallestAttackId());
+		Record lastAttack = logger.getRecordOfAttackId(logger.getHighestAttackId());
 		if (firstAttack != null) {
 			Date resultdate = new Date(firstAttack.getTimestamp());
 			TextView text = (TextView) findViewById(R.id.textFirstAttackValue);

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

@@ -6,7 +6,11 @@ import android.app.Activity;
 import android.os.Bundle;
 import android.widget.ScrollView;
 import android.widget.TextView;
-
+/**
+ * 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
@@ -14,6 +18,7 @@ public class ViewLogTable extends Activity{
 		super.onCreate(savedInstanceState);
 		DatabaseHandler dbh = new DatabaseHandler(getBaseContext());
 		String log = "";
+		//Create a log entry for every attack in the Database
 		for(Record record: dbh.getRecordOfEachAttack())
 		{
 			log = log + record.toString(2) + "\n";
@@ -25,7 +30,6 @@ public class ViewLogTable extends Activity{
 		text.setTextAppearance(this, android.R.style.TextAppearance_Medium);
 		scroll.addView(text);
 		setContentView(scroll);
-
 	}
 
 }