ViewLog.java 17 KB

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