ViewLog.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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.
  239. * @param view View elements which triggers the method call.
  240. * @see ViewLog#deleteByBSSID()
  241. * @see ViewLog#deleteByDate()
  242. * @see ViewLog#deleteAll()
  243. */
  244. public void deleteLog(View view) {
  245. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  246. builder.setTitle(R.string.delete_dialog_title);
  247. builder.setItems(R.array.delete_criteria,
  248. new DialogInterface.OnClickListener() {
  249. public void onClick(DialogInterface dialog, int position) {
  250. switch (position) {
  251. case 0:
  252. deleteByBSSID();
  253. break;
  254. case 1:
  255. deleteByDate();
  256. break;
  257. case 2:
  258. deleteAll();
  259. }
  260. }
  261. });
  262. builder.create();
  263. builder.show();
  264. }
  265. /**
  266. * Shows a List with all recorded BSSIDs.
  267. * If a BSSID is selected the method calls {@link Logger#deleteByBSSID(String)} to delete all records with the chosen BSSID
  268. * @see Logger#deleteByBSSID
  269. */
  270. private void deleteByBSSID() {
  271. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  272. final String[] bssidArray = logger.getAllBSSIDS();
  273. final String[] strings = new String[bssidArray.length];
  274. for(int i = 0; i < bssidArray.length; i++){
  275. strings[i] = bssidArray[i] + " (" + logger.getSSID(bssidArray[i]) +")";
  276. }
  277. builder.setTitle(R.string.delete_dialog_title);
  278. builder.setItems(strings, new DialogInterface.OnClickListener() {
  279. @SuppressLint("NewApi")
  280. public void onClick(DialogInterface dialog, int position) {
  281. logger.deleteByBSSID(bssidArray[position]);
  282. Toast.makeText(
  283. getApplicationContext(),
  284. "All entries with bssid '" + bssidArray[position]
  285. + "' deleted.", Toast.LENGTH_SHORT).show();
  286. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
  287. recreate();
  288. } else {
  289. Intent intent = getIntent();
  290. finish();
  291. startActivity(intent);
  292. }
  293. }
  294. });
  295. builder.create();
  296. builder.show();
  297. }
  298. /**
  299. * Creates a DatePicking Dialog where the user can choose a date. Afterwards {@link ViewLog#deleteByDate(int, int, int)} is called.
  300. */
  301. private void deleteByDate() {
  302. showDialog(0);
  303. }
  304. @Override
  305. protected Dialog onCreateDialog(int id) {
  306. switch (id) {
  307. case 0:
  308. final Calendar cal = Calendar.getInstance();
  309. int pYear = cal.get(Calendar.YEAR);
  310. int pMonth = cal.get(Calendar.MONTH);
  311. int pDay = cal.get(Calendar.DAY_OF_MONTH);
  312. return new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
  313. public void onDateSet(DatePicker view, int year, int monthOfYear,
  314. int dayOfMonth) {deleteByDate(year, monthOfYear, dayOfMonth);}}
  315. , pYear, pMonth, pDay);
  316. }
  317. return null;
  318. }
  319. /**
  320. * Shows a Dialog with the given date and ask him to confirm deleting records that are older than the shown date.
  321. * When the user confirms {@link Logger#deleteByDate(long)} is called with a long representation of the Date.
  322. * If the user cancels the Dialog nothing happens and the dialog disappears.
  323. * @param year
  324. * @param monthOfYear
  325. * @param dayOfMonth
  326. */
  327. private void deleteByDate(int year, int monthOfYear, int dayOfMonth) {
  328. TimePicker timePicker = new TimePicker(this);
  329. final Calendar calendar = Calendar.getInstance();
  330. calendar.set(year, monthOfYear, dayOfMonth,
  331. timePicker.getCurrentHour(), timePicker.getCurrentMinute(), 0);
  332. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  333. builder.setTitle(R.string.dialog_clear_database_date)
  334. .setMessage(sdf.format(calendar.getTime()))
  335. .setPositiveButton(R.string.delete,
  336. new DialogInterface.OnClickListener() {
  337. @SuppressLint("NewApi")
  338. public void onClick(DialogInterface dialog, int id) {
  339. long time = calendar.getTimeInMillis();
  340. // Delete Data
  341. logger.deleteByDate(time);
  342. Toast.makeText(getApplicationContext(),
  343. "Data sets deleted!",
  344. Toast.LENGTH_SHORT).show();
  345. // Recreate the activity
  346. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
  347. recreate();
  348. } else {
  349. Intent intent = getIntent();
  350. finish();
  351. startActivity(intent);
  352. }
  353. }
  354. })
  355. .setNegativeButton(R.string.cancel,
  356. new DialogInterface.OnClickListener() {
  357. public void onClick(DialogInterface dialog, int id) {
  358. // User cancelled the dialog
  359. }
  360. });
  361. // Create the AlertDialog object
  362. builder.create();
  363. builder.show();
  364. }
  365. /**
  366. * Shows a Dialog to confirm that the database should be cleared.
  367. * If confirmed {@link SQLLogger#clearData()} is called.
  368. * @see Logger#clearData()
  369. */
  370. private void deleteAll() {
  371. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  372. builder.setMessage(R.string.dialog_clear_database)
  373. .setPositiveButton(R.string.clear,
  374. new DialogInterface.OnClickListener() {
  375. @SuppressLint("NewApi")
  376. public void onClick(DialogInterface dialog, int id) {
  377. // Clear all Data
  378. logger.clearData();
  379. editor.putInt("ATTACK_ID_COUNTER", 0);
  380. editor.putInt("LAST_UPLOADED_ATTACK_ID", -1);
  381. editor.commit();
  382. Toast.makeText(getApplicationContext(),
  383. "Database cleared!", Toast.LENGTH_SHORT)
  384. .show();
  385. // Recreate the activity
  386. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
  387. recreate();
  388. } else {
  389. Intent intent = getIntent();
  390. finish();
  391. startActivity(intent);
  392. }
  393. }
  394. })
  395. .setNegativeButton(R.string.cancel,
  396. new DialogInterface.OnClickListener() {
  397. public void onClick(DialogInterface dialog, int id) {
  398. // User cancelled the dialog
  399. }
  400. });
  401. // Create the AlertDialog object
  402. builder.create();
  403. builder.show();
  404. }
  405. /**
  406. * Initializes the Statistics. Creates a table row for every protocol and checks the dabase for the attack count.
  407. * Calls {@link ViewLog#setFirstAndLastAttack()} to set the TextViews.
  408. * @see Logger#getAttackCount()
  409. * @see Logger#getAttackPerProtokolCount(String)
  410. */
  411. private void initStatistic() {
  412. TableLayout table = (TableLayout) findViewById(R.id.layoutContainer);
  413. ArrayList<String> protocols = new ArrayList<String>();
  414. protocols.add("Total");
  415. protocols.addAll(Arrays.asList(getResources().getStringArray(
  416. R.array.protocols)));
  417. for (String protocol : protocols) {
  418. TableRow row = new TableRow(this);
  419. TextView protocolName = new TextView(this);
  420. protocolName.setBackgroundResource(R.color.dark_grey);
  421. protocolName.setText(protocol);
  422. protocolName.setTextAppearance(this,
  423. android.R.style.TextAppearance_Medium);
  424. protocolName.setPadding(6, 0, 0, 0);
  425. row.addView(protocolName);
  426. TextView value = new TextView(this);
  427. value.setBackgroundResource(R.color.light_grey);
  428. value.setTextAppearance(this, android.R.style.TextAppearance_Medium);
  429. value.setGravity(Gravity.RIGHT);
  430. value.setPadding(3, 0, 3, 0);
  431. row.addView(value);
  432. if (protocol.equals("Total")) {
  433. value.setText("" + logger.getAttackCount());
  434. } else {
  435. value.setText("" + logger.getAttackPerProtokolCount(protocol));
  436. }
  437. table.addView(row);
  438. }
  439. setFirstAndLastAttack();
  440. }
  441. /**
  442. * Sets the TextViews for first and last attack.
  443. * @see Logger#getSmallestAttackId()
  444. * @see Logger#getHighestAttackId()
  445. * @see Logger#getRecordOfAttackId(long)
  446. */
  447. private void setFirstAndLastAttack() {
  448. Record firstAttack = logger.getRecordOfAttackId(logger.getSmallestAttackId());
  449. Record lastAttack = logger.getRecordOfAttackId(logger.getHighestAttackId());
  450. if (firstAttack != null) {
  451. Date resultdate = new Date(firstAttack.getTimestamp());
  452. TextView text = (TextView) findViewById(R.id.textFirstAttackValue);
  453. text.setText(sdf.format(resultdate));
  454. text = (TextView) findViewById(R.id.textLastAttackValue);
  455. resultdate = new Date(lastAttack.getTimestamp());
  456. text.setText(sdf.format(resultdate));
  457. } else {
  458. TextView text = (TextView) findViewById(R.id.textFirstAttackValue);
  459. text.setText("-");
  460. text = (TextView) findViewById(R.id.textLastAttackValue);
  461. text.setText("-");
  462. }
  463. }
  464. }