SQLLogger.java 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. package de.tudarmstadt.informatik.hostage.logging;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.io.UnsupportedEncodingException;
  6. import java.util.ArrayList;
  7. import org.apache.http.HttpResponse;
  8. import org.apache.http.client.ClientProtocolException;
  9. import org.apache.http.client.HttpClient;
  10. import org.apache.http.client.methods.HttpPost;
  11. import org.apache.http.entity.StringEntity;
  12. import de.tudarmstadt.informatik.hostage.R;
  13. import de.tudarmstadt.informatik.hostage.commons.HelperUtils;
  14. import de.tudarmstadt.informatik.hostage.ui.MainActivity;
  15. import de.tudarmstadt.informatik.hostage.ui.ViewLog;
  16. import android.app.NotificationManager;
  17. import android.app.PendingIntent;
  18. import android.content.Context;
  19. import android.content.Intent;
  20. import android.content.SharedPreferences;
  21. import android.content.SharedPreferences.Editor;
  22. import android.os.Environment;
  23. import android.preference.PreferenceManager;
  24. import android.support.v4.app.NotificationCompat;
  25. import android.support.v4.app.TaskStackBuilder;
  26. import android.util.Log;
  27. import android.widget.Toast;
  28. public class SQLLogger implements Logger{
  29. Context context;
  30. DatabaseHandler dbh;
  31. public static final int JSON = 0x01;
  32. private int progressMax;
  33. private NotificationCompat.Builder builder;
  34. private NotificationManager mNotifyManager;
  35. SharedPreferences pref;
  36. Editor editor;
  37. public SQLLogger(Context context){
  38. this.context = context;
  39. dbh = new DatabaseHandler(context);
  40. pref = PreferenceManager.getDefaultSharedPreferences(context);
  41. editor = pref.edit();
  42. }
  43. public synchronized void write(Record record) {
  44. dbh.addRecord(record);
  45. }
  46. public void exportDatabase(int format){
  47. try {
  48. FileOutputStream log;
  49. String filename = "hostage_" + format + "_" + System.currentTimeMillis() + ".log";
  50. boolean externalStorage = pref.getBoolean("pref_external_storage", false);
  51. String externalLocation = pref.getString("pref_external_location", "");
  52. if(externalStorage){
  53. String root = Environment.getExternalStorageDirectory().toString();
  54. if(root != null && HelperUtils.isExternalStorageWritable()){
  55. File dir = new File(root + externalLocation);
  56. dir.mkdirs();
  57. File file = new File(dir, filename);
  58. log = new FileOutputStream(file);
  59. }else {
  60. Toast.makeText(context, "Could not write to SD Card", Toast.LENGTH_SHORT).show();
  61. return;
  62. }
  63. } else{
  64. log = context.openFileOutput("hostage_" + format + "_" + System.currentTimeMillis() + ".log", Context.MODE_PRIVATE);
  65. }
  66. ArrayList<Record> records = dbh.getAllRecords();
  67. for(Record record : records){
  68. log.write((record.toString(format) + "\n").getBytes());
  69. }
  70. log.flush();
  71. log.close();
  72. Toast.makeText(context, externalStorage ? filename + " saved on external memory! " + externalLocation : filename + " saved on internal memory!", Toast.LENGTH_LONG).show();
  73. } catch (Exception e) {
  74. Toast.makeText(context, "Could not write to SD Card", Toast.LENGTH_SHORT).show();
  75. e.printStackTrace();
  76. }
  77. }
  78. public void uploadDatabase(){
  79. final int lastUploadedAttackId = pref.getInt("LAST_UPLOADED_ATTACK_ID", -1);
  80. int currentAttackId = pref.getInt("ATTACK_ID_COUNTER", 0);
  81. if(lastUploadedAttackId == currentAttackId -1){
  82. Toast.makeText(context, "All data have already been uploaded.", Toast.LENGTH_SHORT).show();
  83. return;
  84. }
  85. // Show Upload Notification
  86. builder = new NotificationCompat.Builder(context)
  87. .setContentTitle(context.getString(R.string.app_name))
  88. .setContentText("Upload in progress...")
  89. .setTicker("Uploading Data...")
  90. .setSmallIcon(R.drawable.ic_launcher)
  91. .setWhen(System.currentTimeMillis());
  92. TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
  93. stackBuilder.addParentStack(MainActivity.class);
  94. stackBuilder.addNextIntent(new Intent());
  95. PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
  96. PendingIntent.FLAG_UPDATE_CURRENT);
  97. builder.setContentIntent(resultPendingIntent);
  98. builder.setAutoCancel(true);
  99. builder.setOnlyAlertOnce(false);
  100. mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
  101. mNotifyManager.notify(2, builder.build());
  102. new Thread(new Runnable() {
  103. public void run() {
  104. HttpClient httpclient = HelperUtils.createHttpClient();
  105. ArrayList<Record> recordList = dbh.getRecordOfEachAttack(lastUploadedAttackId);
  106. progressMax = recordList.size();
  107. Log.i("SQLLogger", "Logs to upload: " + progressMax);
  108. HttpPost httppost;
  109. int progressBarStatus = 0;
  110. for(Record record: recordList){
  111. Log.i("SQLLogger", "Uploading log: " + progressBarStatus);
  112. try {
  113. httppost = new HttpPost(pref.getString("pref_upload", "https://ssi.cased.de"));
  114. StringEntity se = new StringEntity(record.toString(JSON));
  115. httppost.setEntity(se);
  116. HttpResponse response = httpclient.execute(httppost);
  117. Log.i("SQLLogger", "Statuscode of log: " + progressBarStatus + " " + response.getStatusLine().getStatusCode());
  118. progressBarStatus++;
  119. builder.setProgress(progressMax, progressBarStatus, false);
  120. // Update the progress bar
  121. mNotifyManager.notify(2, builder.build());
  122. } catch (Exception e) {
  123. Log.i("SQLLogger", "Failed");
  124. // TODO Auto-generated catch block
  125. e.printStackTrace();
  126. }
  127. }
  128. if(progressBarStatus == progressMax){
  129. // When the loop is finished, updates the notification
  130. builder.setContentText("Upload complete")
  131. .setTicker("Upload complete")
  132. // Removes the progress bar
  133. .setProgress(0,0,false);
  134. mNotifyManager.notify(2, builder.build());
  135. }
  136. }}).start();
  137. editor.putInt("LAST_UPLOADED_ATTACK_ID",currentAttackId - 1);
  138. editor.commit();
  139. }
  140. public int getAttackCount(){
  141. return dbh.getAttackCount();
  142. }
  143. public int getAttackPerProtokollCount(String protocol){
  144. return dbh.getAttackPerProtokolCount(protocol);
  145. }
  146. public void clearLog(){
  147. dbh.clearData();
  148. }
  149. @Override
  150. public void close() {
  151. // TODO Auto-generated method stub
  152. }
  153. }