ViewLog.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. package de.tudarmstadt.informatik.hostage.ui;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.text.SimpleDateFormat;
  5. import java.util.ArrayList;
  6. import java.util.Arrays;
  7. import java.util.Calendar;
  8. import java.util.Date;
  9. import java.util.Locale;
  10. import org.apache.http.HttpResponse;
  11. import org.apache.http.client.HttpClient;
  12. import org.apache.http.client.methods.HttpPost;
  13. import org.apache.http.entity.StringEntity;
  14. import de.tudarmstadt.informatik.hostage.R;
  15. import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
  16. import de.tudarmstadt.informatik.hostage.logging.Logger;
  17. import de.tudarmstadt.informatik.hostage.logging.Record;
  18. import de.tudarmstadt.informatik.hostage.logging.SQLLogger;
  19. import android.annotation.SuppressLint;
  20. import android.app.Activity;
  21. import android.app.AlertDialog;
  22. import android.app.DatePickerDialog;
  23. import android.app.Dialog;
  24. import android.app.NotificationManager;
  25. import android.app.PendingIntent;
  26. import android.content.Context;
  27. import android.content.DialogInterface;
  28. import android.content.Intent;
  29. import android.content.SharedPreferences;
  30. import android.content.SharedPreferences.Editor;
  31. import android.os.Build;
  32. import android.os.Bundle;
  33. import android.os.Environment;
  34. import android.preference.PreferenceManager;
  35. import android.support.v4.app.NotificationCompat;
  36. import android.support.v4.app.TaskStackBuilder;
  37. import android.util.Log;
  38. import android.view.Gravity;
  39. import android.view.Menu;
  40. import android.view.MenuItem;
  41. import android.view.View;
  42. import android.widget.DatePicker;
  43. import android.widget.TableLayout;
  44. import android.widget.TableRow;
  45. import android.widget.TextView;
  46. import android.widget.TimePicker;
  47. import android.widget.Toast;
  48. /**
  49. * ViewLog shows Statistics about the recorded Attacks.
  50. * It also offers the user several options to perform actions with the database.
  51. * This includes:<br>
  52. * - show records,<br>
  53. * - export records,<br>
  54. * - upload records,<br>
  55. * - and delete records.
  56. * @author Lars Pandikow
  57. */
  58. public class ViewLog extends Activity {
  59. public static final int JSON = 0x01;
  60. private final SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm", Locale.US);
  61. private Logger logger;
  62. private SharedPreferences pref;
  63. private Editor editor;
  64. @Override
  65. protected void onCreate(Bundle savedInstanceState) {
  66. super.onCreate(savedInstanceState);
  67. setContentView(R.layout.activity_viewlog);
  68. logger = new SQLLogger(this);
  69. pref = PreferenceManager.getDefaultSharedPreferences(this);
  70. editor = pref.edit();
  71. initStatistic();
  72. }
  73. @Override
  74. public boolean onCreateOptionsMenu(Menu menu) {
  75. getMenuInflater().inflate(R.menu.main, menu);
  76. return true;
  77. }
  78. @Override
  79. public boolean onOptionsItemSelected(MenuItem item) {
  80. // Handle item selection
  81. switch (item.getItemId()) {
  82. case R.id.action_settings:
  83. startActivity(new Intent(this, SettingsActivity.class));
  84. break;
  85. case R.id.action_about:
  86. startActivity(new Intent(this, AboutActivity.class));
  87. break;
  88. default:
  89. }
  90. return super.onOptionsItemSelected(item);
  91. }
  92. /**
  93. * Creates a Dialog to choose export format.
  94. * Then calls {@link ViewLog#exportDatabase(int)}
  95. * @param view View elements which triggers the method call.
  96. */
  97. public void exportDatabase(View view) {
  98. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  99. builder.setTitle(R.string.export_dialog_title);
  100. builder.setItems(R.array.format, new DialogInterface.OnClickListener() {
  101. public void onClick(DialogInterface dialog, int position) {
  102. exportDatabase(position);
  103. }
  104. });
  105. builder.create();
  106. builder.show();
  107. }
  108. /**
  109. * Exports all records in a given format. Before exporting checks export location from preferences.
  110. * @param format Integer coded export format
  111. * @see Record#toString(int)
  112. */
  113. private void exportDatabase(int format){
  114. try {
  115. FileOutputStream log;
  116. String filename = "hostage_" + format + "_" + System.currentTimeMillis() + ".log";
  117. boolean externalStorage = pref.getBoolean("pref_external_storage", false);
  118. String externalLocation = pref.getString("pref_external_location", "");
  119. if(externalStorage){
  120. String root = Environment.getExternalStorageDirectory().toString();
  121. if(root != null && HelperUtils.isExternalStorageWritable()){
  122. File dir = new File(root + externalLocation);
  123. dir.mkdirs();
  124. File file = new File(dir, filename);
  125. log = new FileOutputStream(file);
  126. }else {
  127. Toast.makeText(this, "Could not write to SD Card", Toast.LENGTH_SHORT).show();
  128. return;
  129. }
  130. } else{
  131. log = this.openFileOutput("hostage_" + format + "_" + System.currentTimeMillis() + ".log", Context.MODE_PRIVATE);
  132. }
  133. ArrayList<Record> records = logger.getAllRecords();
  134. for(Record record : records){
  135. log.write((record.toString(format) + "\n").getBytes());
  136. }
  137. log.flush();
  138. log.close();
  139. Toast.makeText(this, externalStorage ? filename + " saved on external memory! " + externalLocation : filename + " saved on internal memory!", Toast.LENGTH_LONG).show();
  140. } catch (Exception e) {
  141. Toast.makeText(this, "Could not write to SD Card", Toast.LENGTH_SHORT).show();
  142. e.printStackTrace();
  143. }
  144. }
  145. /**
  146. * Uploads a JSON Representation of each attack to a server, specified in the preferences.<br>
  147. * The method only uploads information about attacks that have net been uploaded yet.
  148. * For the Upload it uses a HttpPost with a HttpsClient, which does not validate any certificates.<br>
  149. * The Upload runs in its own Thread.<br>
  150. * While uploading the method also creates a notification to inform the user about the status of the upload.
  151. * @param view View elements which triggers the method call.
  152. * @see de.tudarmstadt.informatik.hostage.net.MySSLSocketFactory
  153. */
  154. public void uploadDatabase(View view){
  155. //Create a Notification
  156. final NotificationCompat.Builder builder;
  157. final NotificationManager mNotifyManager;
  158. final int lastUploadedAttackId = pref.getInt("LAST_UPLOADED_ATTACK_ID", -1);
  159. int currentAttackId = pref.getInt("ATTACK_ID_COUNTER", 0);
  160. // Check if there are new records to upload
  161. if(lastUploadedAttackId == currentAttackId -1){
  162. // Inform user that no upload is necessary
  163. Toast.makeText(this, "All data have already been uploaded.", Toast.LENGTH_SHORT).show();
  164. return;
  165. }
  166. // Build and show Upload Notification in notification bar
  167. builder = new NotificationCompat.Builder(this)
  168. .setContentTitle(this.getString(R.string.app_name))
  169. .setContentText("Upload in progress...")
  170. .setTicker("Uploading Data...")
  171. .setSmallIcon(R.drawable.ic_launcher)
  172. .setWhen(System.currentTimeMillis());
  173. TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
  174. stackBuilder.addParentStack(MainActivity.class);
  175. stackBuilder.addNextIntent(new Intent());
  176. PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
  177. PendingIntent.FLAG_UPDATE_CURRENT);
  178. builder.setContentIntent(resultPendingIntent);
  179. builder.setAutoCancel(true);
  180. builder.setOnlyAlertOnce(false);
  181. mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  182. mNotifyManager.notify(2, builder.build());
  183. // Create a new Thread for upload
  184. new Thread(new Runnable() {
  185. public void run() {
  186. // Create a https client. Uses MySSLSocketFactory to accept all certificates
  187. HttpClient httpclient = HelperUtils.createHttpClient();
  188. // get RecordList
  189. ArrayList<Record> recordList = logger.getRecordOfEachAttack(lastUploadedAttackId);
  190. final int progressMax = recordList.size();
  191. Log.i("SQLLogger", "Logs to upload: " + progressMax);
  192. HttpPost httppost;
  193. int progressBarStatus = 0;
  194. for(Record record: recordList){
  195. Log.i("SQLLogger", "Uploading log: " + progressBarStatus);
  196. try {
  197. // Create HttpPost
  198. httppost = new HttpPost(pref.getString("pref_upload", "https://ssi.cased.de"));
  199. // Create JSON String of Record
  200. StringEntity se = new StringEntity(record.toString(JSON));
  201. httppost.setEntity(se);
  202. // Execute HttpPost
  203. HttpResponse response = httpclient.execute(httppost);
  204. Log.i("SQLLogger", "Statuscode of log " + progressBarStatus + ": " + " " + response.getStatusLine().getReasonPhrase());
  205. Log.i("SQLLogger", "Statuscode of log " + progressBarStatus + ": " + " " + response.getStatusLine().getStatusCode());
  206. // Update Notification progress bar
  207. progressBarStatus++;
  208. builder.setProgress(progressMax, progressBarStatus, false);
  209. // Update the progress bar
  210. mNotifyManager.notify(2, builder.build());
  211. } catch (Exception e) {
  212. Log.i("SQLLogger", "Failed");
  213. e.printStackTrace();
  214. }
  215. }
  216. if(progressBarStatus == progressMax){
  217. // When the loop is finished, updates the notification
  218. builder.setContentText("Upload complete")
  219. .setTicker("Upload complete")
  220. // Removes the progress bar
  221. .setProgress(0,0,false);
  222. mNotifyManager.notify(2, builder.build());
  223. }
  224. }}).start();
  225. editor.putInt("LAST_UPLOADED_ATTACK_ID",currentAttackId - 1);
  226. editor.commit();
  227. }
  228. /**
  229. * Starts a ViewLogTable Activity.
  230. * @param view View elements which triggers the method call.
  231. * @see ViewLogTable
  232. */
  233. public void showLog(View view) {
  234. startActivity(new Intent(this, ViewLogTable.class));
  235. }
  236. /**
  237. * Creates a Dialog that lets the user decide which criteria he want to use to delete records.
  238. * Then calls the corresponding method.<br>
  239. * The possible criteria are coded in /res/values/arrays.xml
  240. * To add a criteria add a String to the array and extend the switch statement.
  241. * @param view View elements which triggers the method call.
  242. * @see ViewLog#deleteByBSSID()
  243. * @see ViewLog#deleteByDate()
  244. * @see ViewLog#deleteAll()
  245. */
  246. public void deleteLog(View view) {
  247. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  248. builder.setTitle(R.string.delete_dialog_title);
  249. builder.setItems(R.array.delete_criteria,
  250. new DialogInterface.OnClickListener() {
  251. public void onClick(DialogInterface dialog, int position) {
  252. switch (position) {
  253. case 0:
  254. deleteByBSSID();
  255. break;
  256. case 1:
  257. deleteByDate();
  258. break;
  259. case 2:
  260. deleteAll();
  261. }
  262. }
  263. });
  264. builder.create();
  265. builder.show();
  266. }
  267. /**
  268. * Shows a List with all recorded BSSIDs.
  269. * If a BSSID is selected the method calls {@link Logger#deleteByBSSID(String)} to delete all records with the chosen BSSID
  270. * @see Logger#deleteByBSSID
  271. */
  272. private void deleteByBSSID() {
  273. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  274. final String[] bssidArray = logger.getAllBSSIDS();
  275. final String[] strings = new String[bssidArray.length];
  276. for(int i = 0; i < bssidArray.length; i++){
  277. strings[i] = bssidArray[i] + " (" + logger.getSSID(bssidArray[i]) +")";
  278. }
  279. builder.setTitle(R.string.delete_dialog_title);
  280. builder.setItems(strings, new DialogInterface.OnClickListener() {
  281. @SuppressLint("NewApi")
  282. public void onClick(DialogInterface dialog, int position) {
  283. logger.deleteByBSSID(bssidArray[position]);
  284. Toast.makeText(
  285. getApplicationContext(),
  286. "All entries with bssid '" + bssidArray[position]
  287. + "' deleted.", Toast.LENGTH_SHORT).show();
  288. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
  289. recreate();
  290. } else {
  291. Intent intent = getIntent();
  292. finish();
  293. startActivity(intent);
  294. }
  295. }
  296. });
  297. builder.create();
  298. builder.show();
  299. }
  300. /**
  301. * Creates a DatePicking Dialog where the user can choose a date. Afterwards {@link ViewLog#deleteByDate(int, int, int)} is called.
  302. */
  303. private void deleteByDate() {
  304. showDialog(0);
  305. }
  306. @Override
  307. protected Dialog onCreateDialog(int id) {
  308. switch (id) {
  309. case 0:
  310. final Calendar cal = Calendar.getInstance();
  311. int pYear = cal.get(Calendar.YEAR);
  312. int pMonth = cal.get(Calendar.MONTH);
  313. int pDay = cal.get(Calendar.DAY_OF_MONTH);
  314. return new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
  315. public void onDateSet(DatePicker view, int year, int monthOfYear,
  316. int dayOfMonth) {deleteByDate(year, monthOfYear, dayOfMonth);}}
  317. , pYear, pMonth, pDay);
  318. }
  319. return null;
  320. }
  321. /**
  322. * Shows a Dialog with the given date and ask him to confirm deleting records that are older than the shown date.
  323. * When the user confirms {@link Logger#deleteByDate(long)} is called with a long representation of the Date.
  324. * If the user cancels the Dialog nothing happens and the dialog disappears.
  325. * @param year
  326. * @param monthOfYear
  327. * @param dayOfMonth
  328. */
  329. private void deleteByDate(int year, int monthOfYear, int dayOfMonth) {
  330. TimePicker timePicker = new TimePicker(this);
  331. final Calendar calendar = Calendar.getInstance();
  332. calendar.set(year, monthOfYear, dayOfMonth,
  333. timePicker.getCurrentHour(), timePicker.getCurrentMinute(), 0);
  334. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  335. builder.setTitle(R.string.dialog_clear_database_date)
  336. .setMessage(sdf.format(calendar.getTime()))
  337. .setPositiveButton(R.string.delete,
  338. new DialogInterface.OnClickListener() {
  339. @SuppressLint("NewApi")
  340. public void onClick(DialogInterface dialog, int id) {
  341. long time = calendar.getTimeInMillis();
  342. // Delete Data
  343. logger.deleteByDate(time);
  344. Toast.makeText(getApplicationContext(),
  345. "Data sets deleted!",
  346. Toast.LENGTH_SHORT).show();
  347. // Recreate the activity
  348. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
  349. recreate();
  350. } else {
  351. Intent intent = getIntent();
  352. finish();
  353. startActivity(intent);
  354. }
  355. }
  356. })
  357. .setNegativeButton(R.string.cancel,
  358. new DialogInterface.OnClickListener() {
  359. public void onClick(DialogInterface dialog, int id) {
  360. // User cancelled the dialog
  361. }
  362. });
  363. // Create the AlertDialog object
  364. builder.create();
  365. builder.show();
  366. }
  367. /**
  368. * Shows a Dialog to confirm that the database should be cleared.
  369. * If confirmed {@link SQLLogger#clearData()} is called.
  370. * @see Logger#clearData()
  371. */
  372. private void deleteAll() {
  373. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  374. builder.setMessage(R.string.dialog_clear_database)
  375. .setPositiveButton(R.string.clear,
  376. new DialogInterface.OnClickListener() {
  377. @SuppressLint("NewApi")
  378. public void onClick(DialogInterface dialog, int id) {
  379. // Clear all Data
  380. logger.clearData();
  381. editor.putInt("ATTACK_ID_COUNTER", 0);
  382. editor.putInt("LAST_UPLOADED_ATTACK_ID", -1);
  383. editor.commit();
  384. Toast.makeText(getApplicationContext(),
  385. "Database cleared!", Toast.LENGTH_SHORT)
  386. .show();
  387. // Recreate the activity
  388. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
  389. recreate();
  390. } else {
  391. Intent intent = getIntent();
  392. finish();
  393. startActivity(intent);
  394. }
  395. }
  396. })
  397. .setNegativeButton(R.string.cancel,
  398. new DialogInterface.OnClickListener() {
  399. public void onClick(DialogInterface dialog, int id) {
  400. // User cancelled the dialog
  401. }
  402. });
  403. // Create the AlertDialog object
  404. builder.create();
  405. builder.show();
  406. }
  407. /**
  408. * Initializes the Statistics. Creates a table row for every protocol and checks the dabase for the attack count.
  409. * Calls {@link ViewLog#setFirstAndLastAttack()} to set the TextViews.
  410. * @see Logger#getAttackCount()
  411. * @see Logger#getAttackPerProtokolCount(String)
  412. */
  413. private void initStatistic() {
  414. TableLayout table = (TableLayout) findViewById(R.id.layoutContainer);
  415. ArrayList<String> protocols = new ArrayList<String>();
  416. protocols.add("Total");
  417. protocols.addAll(Arrays.asList(getResources().getStringArray(
  418. R.array.protocols)));
  419. for (String protocol : protocols) {
  420. TableRow row = new TableRow(this);
  421. TextView protocolName = new TextView(this);
  422. protocolName.setBackgroundResource(R.color.dark_grey);
  423. protocolName.setText(protocol);
  424. protocolName.setTextAppearance(this,
  425. android.R.style.TextAppearance_Medium);
  426. protocolName.setPadding(6, 0, 0, 0);
  427. row.addView(protocolName);
  428. TextView value = new TextView(this);
  429. value.setBackgroundResource(R.color.light_grey);
  430. value.setTextAppearance(this, android.R.style.TextAppearance_Medium);
  431. value.setGravity(Gravity.RIGHT);
  432. value.setPadding(3, 0, 3, 0);
  433. row.addView(value);
  434. if (protocol.equals("Total")) {
  435. value.setText("" + logger.getAttackCount());
  436. } else {
  437. value.setText("" + logger.getAttackPerProtokolCount(protocol));
  438. }
  439. table.addView(row);
  440. }
  441. setFirstAndLastAttack();
  442. }
  443. /**
  444. * Sets the TextViews for first and last attack.
  445. * @see Logger#getSmallestAttackId()
  446. * @see Logger#getHighestAttackId()
  447. * @see Logger#getRecordOfAttackId(long)
  448. */
  449. private void setFirstAndLastAttack() {
  450. Record firstAttack = logger.getRecordOfAttackId(logger.getSmallestAttackId());
  451. Record lastAttack = logger.getRecordOfAttackId(logger.getHighestAttackId());
  452. if (firstAttack != null) {
  453. Date resultdate = new Date(firstAttack.getTimestamp());
  454. TextView text = (TextView) findViewById(R.id.textFirstAttackValue);
  455. text.setText(sdf.format(resultdate));
  456. text = (TextView) findViewById(R.id.textLastAttackValue);
  457. resultdate = new Date(lastAttack.getTimestamp());
  458. text.setText(sdf.format(resultdate));
  459. } else {
  460. TextView text = (TextView) findViewById(R.id.textFirstAttackValue);
  461. text.setText("-");
  462. text = (TextView) findViewById(R.id.textLastAttackValue);
  463. text.setText("-");
  464. }
  465. }
  466. }