Added own crash handler for debugging
[DHBWCampusApp.git] / app / src / main / java / de / dhbwloe / campusapp / CampusAppExceptionHandler.java
1 package de.dhbwloe.campusapp;
2
3 import android.app.Activity;
4 import android.content.Intent;
5 import android.util.Log;
6
7 import com.loopj.android.http.AsyncHttpClient;
8 import com.loopj.android.http.AsyncHttpResponseHandler;
9 import com.loopj.android.http.RequestParams;
10
11 import java.io.BufferedReader;
12 import java.io.BufferedWriter;
13 import java.io.FileReader;
14 import java.io.FileWriter;
15 import java.io.IOException;
16 import java.io.PrintWriter;
17 import java.io.StringWriter;
18 import java.io.Writer;
19 import java.text.SimpleDateFormat;
20 import java.util.ArrayList;
21 import java.util.Date;
22 import java.util.List;
23
24 import cz.msebera.android.httpclient.Header;
25 import cz.msebera.android.httpclient.NameValuePair;
26 import cz.msebera.android.httpclient.client.entity.UrlEncodedFormEntity;
27 import cz.msebera.android.httpclient.client.methods.HttpPost;
28 import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
29 import cz.msebera.android.httpclient.message.BasicNameValuePair;
30 import cz.msebera.android.httpclient.protocol.HTTP;
31
32 /**
33  * Created by pk910 on 11.03.2016.
34  */
35 public class CampusAppExceptionHandler {
36     private static String CRASHLOG_UPLOAD = "http://dev.pk910.de/DHBWCampusCourses";
37     private String localPath;
38
39     private static boolean crashLogWindowOpened = false;
40
41     public void handleUncaughtException(Thread thread, Throwable e) {
42         // automatically send crash log to my server for debuggging.
43         // disable this for productive use! (CampusAppContext.DEBUG)
44
45         final Writer result = new StringWriter();
46         final PrintWriter printWriter = new PrintWriter(result);
47         e.printStackTrace(printWriter);
48         String stacktrace = result.toString();
49         printWriter.close();
50
51         SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd-HHmmss");
52         String crashdate = dateFormat.format(new Date());
53         String filename = crashdate + ".stacktrace";
54
55         CampusAppContext context;
56         Activity mainActivity = null;
57         try {
58             /*Wir greifen nun auf einen Code zurück, aus welchem die unbehandelte Exception stammt.
59             * Dies ist womöglich keine gute Idee, daher müssen wir sämmtliche Exceptions abfangen und verwerfen (Exception inception :D)
60             * und hoffen, dass die App noch so weit "funktioniert" ;)
61             */
62             context = CampusAppContext.getInstance();
63
64             if(context != null) {
65                 mainActivity = context.getMainActivity();
66             }
67             if(mainActivity != null) {
68                 localPath = mainActivity.getApplicationContext().getFilesDir().getAbsolutePath();
69             }
70         } catch (Exception ex) {}
71
72         if(localPath != null)
73             writeToFile(stacktrace, filename);
74
75         // start crash screen
76         if(!crashLogWindowOpened) {
77             try {
78                 Intent intent = new Intent();
79                 intent.setAction("de.dhbw.campusapp.CRASH_LOG");
80                 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // required when starting from Application
81                 intent.putExtra("crashdate", crashdate);
82                 mainActivity.startActivity(intent);
83                 crashLogWindowOpened = true;
84             } catch (Exception ex) {
85             }
86         }
87     }
88
89     private void writeToFile(String stacktrace, String filename) {
90         try {
91             BufferedWriter bos = new BufferedWriter(new FileWriter(
92                     localPath + "/" + filename));
93             bos.write(stacktrace);
94             bos.flush();
95             bos.close();
96         } catch (Exception e) {
97             e.printStackTrace();
98         }
99     }
100
101     public void postprocessException(Activity crashLogScreen, String crashdate) {
102         localPath = crashLogScreen.getApplicationContext().getFilesDir().getAbsolutePath();
103         String fileName = localPath + "/" + crashdate + ".stacktrace";
104         StringBuilder stackTrace = new StringBuilder();
105
106         try {
107             BufferedReader br = new BufferedReader(new FileReader(fileName));
108             String line;
109
110             while ((line = br.readLine()) != null) {
111                 stackTrace.append(line);
112                 stackTrace.append('\n');
113             }
114             br.close();
115         }
116         catch (IOException e) {
117             //You'll need to add proper error handling here
118         }
119
120         sendToServer(CRASHLOG_UPLOAD, stackTrace.toString(), crashdate);
121     }
122
123     private void sendToServer(String url, String stacktrace, String crashdate) {
124         AsyncHttpClient client = new AsyncHttpClient();
125         RequestParams params = new RequestParams();
126         params.add("stacktrace", stacktrace);
127         params.add("crashdate", crashdate);
128
129         client.post(url, params, new AsyncHttpResponseHandler() {
130
131             @Override
132             public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
133                 Log.i("CrashLog", "OK: "+(responseBody != null ? new String(responseBody) : null));
134             }
135
136             @Override
137             public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
138                 Log.i("CrashLog", "Failed: "+(responseBody != null ? new String(responseBody) : null));
139             }
140         });
141     }
142
143 }