Advertisement
Guest User

Untitled

a guest
Sep 18th, 2018
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 44.14 KB | None | 0 0
  1. package user_monitoring.nctu_hscc_ac.ocs_v1;
  2.  
  3. import android.content.BroadcastReceiver;
  4. import android.content.Context;
  5. import android.content.Intent;
  6. import android.content.SharedPreferences;
  7. import android.database.Cursor;
  8. import android.database.sqlite.SQLiteDatabase;
  9. import android.net.ConnectivityManager;
  10. import android.net.NetworkInfo;
  11. import android.os.AsyncTask;
  12. import android.os.Environment;
  13. import android.os.Handler;
  14. import android.util.Log;
  15.  
  16. import org.javatuples.Decade;
  17. import org.javatuples.Octet;
  18. import org.javatuples.Pair;
  19. import org.javatuples.Quartet;
  20. import org.javatuples.Quintet;
  21. import org.javatuples.Septet;
  22. import org.javatuples.Triplet;
  23. import org.json.JSONArray;
  24. import org.json.JSONException;
  25. import org.json.JSONObject;
  26.  
  27. import java.io.BufferedReader;
  28. import java.io.File;
  29. import java.io.FileWriter;
  30. import java.io.IOException;
  31. import java.io.InputStream;
  32. import java.io.InputStreamReader;
  33. import java.io.OutputStreamWriter;
  34. import java.net.HttpURLConnection;
  35. import java.net.MalformedURLException;
  36. import java.net.ProtocolException;
  37. import java.net.URL;
  38. import java.security.KeyManagementException;
  39. import java.security.NoSuchAlgorithmException;
  40. import java.security.cert.CertificateException;
  41. import java.security.cert.X509Certificate;
  42. import java.text.ParseException;
  43. import java.text.SimpleDateFormat;
  44. import java.util.Calendar;
  45. import java.util.Date;
  46. import java.util.TimeZone;
  47.  
  48. import javax.net.ssl.HostnameVerifier;
  49. import javax.net.ssl.HttpsURLConnection;
  50. import javax.net.ssl.SSLContext;
  51. import javax.net.ssl.SSLSession;
  52. import javax.net.ssl.TrustManager;
  53. import javax.net.ssl.X509TrustManager;
  54.  
  55. import labelingStudy.nctu.minuku.DBHelper.DBHelper;
  56. import labelingStudy.nctu.minuku.Utilities.ScheduleAndSampleManager;
  57. import labelingStudy.nctu.minuku.config.Constants;
  58. import labelingStudy.nctu.minuku.manager.DBManager;
  59. import labelingStudy.nctu.minuku.streamgenerator.ConnectivityStreamGenerator;
  60.  
  61. import com.android.volley.AuthFailureError;
  62. import com.android.volley.Request;
  63. import com.android.volley.Response;
  64. import com.android.volley.VolleyError;
  65. import com.android.volley.toolbox.StringRequest;
  66. import com.android.volley.toolbox.Volley;
  67.  
  68. import java.util.HashMap;
  69. import java.util.Map;
  70.  
  71. /**
  72. * Created by Lawrence on 2017/8/16.
  73. */
  74.  
  75. public class WifiReceiver extends BroadcastReceiver {
  76.  
  77. private final String TAG = "WifiReceiver";
  78.  
  79. private Handler handler;
  80.  
  81. private SharedPreferences sharedPrefs;
  82.  
  83. private Runnable runnable = null;
  84.  
  85. private int year,month,day,hour,min;
  86.  
  87. private long latestUpdatedTime = -9999;
  88. private long nowTime = -9999;
  89. private long startTime = -9999;
  90. private long endTime = -9999;
  91.  
  92. private long startTripTime = -9999;
  93.  
  94. public static final int HTTP_TIMEOUT = 10000; // millisecond
  95. public static final int SOCKET_TIMEOUT = 10000; // millisecond
  96.  
  97. public static int mainThreadUpdateFrequencyInSeconds = 10;
  98. public static long mainThreadUpdateFrequencyInMilliseconds = mainThreadUpdateFrequencyInSeconds * Constants.MILLISECONDS_PER_SECOND;
  99. String requestUrl = "http://140.113.86.142/phppost/receiver_data.php";
  100. String final_data="";
  101. Context con;
  102. // public ClientSocket client;
  103.  
  104. @Override
  105. public void onReceive(Context context, Intent intent) {
  106.  
  107. Log.d(TAG, "onReceive");
  108.  
  109. ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  110. NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
  111.  
  112. //get timzone //prevent the issue when the user start the app in wifi available environment.
  113. TimeZone tz = TimeZone.getDefault();
  114. Calendar cal = Calendar.getInstance(tz);
  115. int mYear = cal.get(Calendar.YEAR);
  116. int mMonth = cal.get(Calendar.MONTH)+1;
  117. int mDay = cal.get(Calendar.DAY_OF_MONTH);
  118.  
  119. sharedPrefs = context.getSharedPreferences(Constants.sharedPrefString, context.MODE_PRIVATE);
  120.  
  121. year = sharedPrefs.getInt("StartYear", mYear);
  122. month = sharedPrefs.getInt("StartMonth", mMonth);
  123. day = sharedPrefs.getInt("StartDay", mDay);
  124.  
  125. Constants.USER_ID = sharedPrefs.getString("userid","NA");
  126. Constants.GROUP_NUM = sharedPrefs.getString("groupNum","NA");
  127.  
  128. hour = sharedPrefs.getInt("StartHour", Calendar.getInstance().get(Calendar.HOUR_OF_DAY));
  129. min = sharedPrefs.getInt("StartMin",Calendar.getInstance().get(Calendar.MINUTE));
  130.  
  131. Log.d(TAG, "year : "+ year+" month : "+ month+" day : "+ day+" hour : "+ hour+" min : "+ min);
  132.  
  133. if (activeNetwork != null) {
  134. // connected to the internet
  135. if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
  136. // connected to wifi
  137. Log.d(TAG,"Wifi activeNetwork");
  138.  
  139. if(runnable==null) {
  140.  
  141. // //Log.d(TAG, "there is no runnable running yet.");
  142.  
  143. MakingJsonDataMainThread();
  144. }
  145. } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
  146. //we might no need to use this.
  147. // connected to the mobile provider's data plan
  148. Log.d(TAG, "MOBILE activeNetwork" ) ;
  149. if(runnable==null) {
  150.  
  151. // //Log.d(TAG, "there is no runnable running yet.");
  152.  
  153. MakingJsonDataMainThread();
  154. }
  155. }
  156. } else {
  157. // not connected to the internet
  158. Log.d(TAG, "no Network" ) ;
  159.  
  160. }
  161. }
  162. public void setContext(Context con){
  163. this.con = con;
  164. }
  165.  
  166. public void sendingDumpData(){
  167.  
  168. Log.d(TAG, "sendingDumpData");
  169.  
  170. JSONObject data = new JSONObject();
  171.  
  172. try {
  173.  
  174. // data.put("device_id", Constants.DEVICE_ID);
  175. data.put("startTime", String.valueOf(startTime));
  176. data.put("endTime", String.valueOf(endTime));
  177. data.put("startTimeString", ScheduleAndSampleManager.getTimeString(startTime));
  178. data.put("endTimeString", ScheduleAndSampleManager.getTimeString(endTime));
  179. }catch (JSONException e){
  180.  
  181. }
  182. storeTransportation(data);
  183. storeLocation(data);
  184. storeActivityRecognition(data);
  185. storeRinger(data);
  186. storeConnectivity(data);
  187. storeBattery(data);
  188. storeAppUsage(data);
  189. storeTelephony(data);
  190. storeSensor(data);
  191. storeAccessibility(data);
  192.  
  193.  
  194. final_data = data.toString();
  195. Log.d(TAG,"final data : "+ data.toString());
  196.  
  197. //code arta
  198. StringRequest stringRequest = new StringRequest(Request.Method.POST, requestUrl, new Response.Listener<String>() {
  199. @Override
  200. public void onResponse(String response) {
  201. // cek apakah server respon / sudah terima data
  202. // bs print sesuatu biar detect klo emgn server sudah receive
  203. Log.d("Volley-Result", ""+response); //the response contains the result from the server, a json string or any other object returned by your server
  204.  
  205. }
  206. }, new Response.ErrorListener() {
  207. @Override
  208. public void onErrorResponse(VolleyError error) {
  209. // print error
  210. error.printStackTrace(); //log the error resulting from the request for diagnosis/debugging
  211.  
  212. }
  213. }){
  214.  
  215. @Override
  216. protected Map<String, String> getParams() throws AuthFailureError {
  217. Map<String, String> postMap = new HashMap<>();
  218. // Set up nama variable post dan setup value yang akan dikirim datanya ke server
  219. postMap.put("data_iot", final_data);
  220. // postMap.put("param2", value2);
  221. //..... Add as many key value pairs in the map as necessary for your request
  222. return postMap;
  223. }
  224. };
  225.  
  226.  
  227. // panggil fungsinya
  228. ////
  229. if(con != null) {
  230. Volley.newRequestQueue(con).add(stringRequest);
  231. Log.d("Volley call", "fungsi volley kepanggil");
  232. }
  233. else {
  234.  
  235. Log.d("Volley call", "fungsi volley gagal");
  236. }
  237. // try {
  238. //
  239. //// MainActivity.client.sendDataString(data.toString());
  240. // }catch (NullPointerException e){
  241. // e.printStackTrace();
  242. // }
  243. //TODO change to client socekt
  244.  
  245. }
  246.  
  247.  
  248.  
  249. public void MakingJsonDataMainThread(){
  250.  
  251. handler = new Handler();
  252.  
  253. runnable = new Runnable() {
  254.  
  255. @Override
  256. public void run() {
  257.  
  258. Log.d(TAG, "MakingJsonDataMainThread runnable");
  259.  
  260. if (ConnectivityStreamGenerator.mIsWifiConnected) {
  261.  
  262. //TODO update endtime to get the latest data's time from MongoDB
  263. //TODO endtime = latest data's time + nextinterval
  264.  
  265. long lastSentStarttime = sharedPrefs.getLong("lastSentStarttime", 0);
  266.  
  267. if (lastSentStarttime == 0) {
  268.  
  269. //if it doesn't reponse the setting with initialize ones
  270. //initialize
  271. long startstartTime = getSpecialTimeInMillis(makingDataFormat(year, month, day, hour, min));
  272. // long startstartTime = ScheduleAndSampleManager.getCurrentTimeInMillis();
  273. startTime = sharedPrefs.getLong("StartTime", startstartTime); //default
  274. Log.d(TAG, "StartTimeString : " + ScheduleAndSampleManager.getTimeString(startTime));
  275.  
  276. long startendTime = getSpecialTimeInMillis(makingDataFormat(year, month, day, hour, min+30));
  277. // long startendTime = startstartTime + Constants.MILLISECONDS_PER_HOUR;
  278. endTime = sharedPrefs.getLong("EndTime", startendTime);
  279. Log.d(TAG, "EndTimeString : " + ScheduleAndSampleManager.getTimeString(endTime));
  280. } else {
  281.  
  282. //if it do reponse the setting with initialize ones
  283. startTime = Long.valueOf(lastSentStarttime);
  284. Log.d(TAG, "StartTimeString : " + ScheduleAndSampleManager.getTimeString(startTime));
  285.  
  286. long nextinterval = Constants.MILLISECONDS_PER_HOUR / 2; //1 hr
  287. endTime = Long.valueOf(lastSentStarttime) + nextinterval;
  288. Log.d(TAG, "EndTimeString : " + ScheduleAndSampleManager.getTimeString(endTime));
  289. }
  290.  
  291. nowTime = ScheduleAndSampleManager.getCurrentTimeInMillis();
  292. System.out.println("nowTime = " + nowTime);
  293. System.out.println("endTime = " + endTime);
  294. Log.d(TAG, "NowTimeString : " + ScheduleAndSampleManager.getTimeString(nowTime));
  295.  
  296. if (nowTime > endTime && (ConnectivityStreamGenerator.mIsWifiConnected || ConnectivityStreamGenerator.mIsMobileConnected)) {
  297.  
  298. Log.d(TAG,"wifi is connected and ready sending data");
  299. sendingDumpData();
  300.  
  301. //setting nextime interval
  302. latestUpdatedTime = endTime;
  303. startTime = latestUpdatedTime;
  304.  
  305. long nextinterval = Constants.MILLISECONDS_PER_HOUR / 2; //1 hr
  306.  
  307. endTime = startTime + nextinterval;
  308.  
  309. sharedPrefs.edit().putLong("lastSentStarttime", startTime).apply();
  310. }
  311. }
  312.  
  313. // }
  314.  
  315. handler.postDelayed(this, mainThreadUpdateFrequencyInMilliseconds);
  316. }
  317. };
  318.  
  319. handler.post(runnable);
  320.  
  321. }
  322.  
  323. //use HTTPAsyncTask to poHttpAsyncPostJsonTaskst data
  324. private class HttpAsyncPostJsonTask extends AsyncTask<String, Void, String> {
  325.  
  326. @Override
  327. protected String doInBackground(String... params) {
  328.  
  329. String result=null;
  330. String url = params[0];
  331. String data = params[1];
  332. String dataType = params[2];
  333. String lastSyncTime = params[3];
  334.  
  335. postJSON(url, data, dataType, lastSyncTime);
  336.  
  337. return result;
  338. }
  339.  
  340. @Override
  341. protected void onPostExecute(String result) {
  342. Log.d(TAG, "get http post result : " + result);
  343. }
  344.  
  345. }
  346.  
  347. public HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
  348.  
  349. public boolean verify(String hostname, SSLSession session) {
  350. return true;
  351. }
  352. };
  353.  
  354. public String postJSON (String address, String json, String dataType, String lastSyncTime) {
  355.  
  356. Log.d(TAG, "[postJSON] testbackend post data to " + address);
  357.  
  358. InputStream inputStream = null;
  359. String result = "";
  360. HttpURLConnection conn = null;
  361. try {
  362.  
  363. URL url = new URL(address);
  364. conn = (HttpURLConnection) url.openConnection();
  365. Log.d(TAG, "[postJSON] testbackend connecting to " + address);
  366.  
  367. if (url.getProtocol().toLowerCase().equals("https")) {
  368. Log.d(TAG, "[postJSON] [using https]");
  369. trustAllHosts();
  370. HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
  371. https.setHostnameVerifier(DO_NOT_VERIFY);
  372. conn = https;
  373. } else {
  374. conn = (HttpURLConnection) url.openConnection();
  375. }
  376.  
  377. SSLContext sc;
  378. sc = SSLContext.getInstance("TLS");
  379. sc.init(null, null, new java.security.SecureRandom());
  380.  
  381. conn.setReadTimeout(HTTP_TIMEOUT);
  382. conn.setConnectTimeout(SOCKET_TIMEOUT);
  383. conn.setRequestMethod("POST");
  384. conn.setDoInput(true);
  385. conn.setDoOutput(true);
  386. conn.setRequestProperty("Content-Type","application/json");
  387. conn.connect();
  388.  
  389. OutputStreamWriter wr= new OutputStreamWriter(conn.getOutputStream());
  390. wr.write(json);
  391. wr.close();
  392.  
  393. Log.d(TAG, "Post:\t" + dataType + "\t" + "for lastSyncTime:" + lastSyncTime);
  394.  
  395. int responseCode = conn.getResponseCode();
  396.  
  397. if(responseCode >= 400)
  398. inputStream = conn.getErrorStream();
  399. else
  400. inputStream = conn.getInputStream();
  401.  
  402. result = convertInputStreamToString(inputStream);
  403.  
  404. Log.d(TAG, "[postJSON] the result response code is " + responseCode);
  405. Log.d(TAG, "[postJSON] the result is " + result);
  406.  
  407. if (conn!=null)
  408. conn.disconnect();
  409.  
  410. } catch (NoSuchAlgorithmException e) {
  411. e.printStackTrace();
  412. } catch (KeyManagementException e) {
  413. e.printStackTrace();
  414. } catch (ProtocolException e) {
  415. e.printStackTrace();
  416. } catch (MalformedURLException e) {
  417. e.printStackTrace();
  418. } catch (java.net.SocketTimeoutException e){
  419.  
  420. Log.d(TAG, "SocketTimeoutException EE", e);
  421. } catch (IOException e) {
  422. e.printStackTrace();
  423. }finally {
  424.  
  425. if (conn != null) {
  426.  
  427. try {
  428.  
  429. conn.disconnect();
  430. } catch (Exception e) {
  431.  
  432. Log.d(TAG, "exception", e);
  433. }
  434. }
  435. }
  436.  
  437. return result;
  438. }
  439.  
  440. private String convertInputStreamToString(InputStream inputStream) throws IOException{
  441.  
  442. BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
  443. String line = "";
  444. String result = "";
  445. while((line = bufferedReader.readLine()) != null){
  446. // Log.d(LOG_TAG, "[syncWithRemoteDatabase] " + line);
  447. result += line;
  448. }
  449.  
  450. inputStream.close();
  451. return result;
  452.  
  453. }
  454.  
  455. /***
  456. * trust all hsot....
  457. */
  458. private void trustAllHosts() {
  459.  
  460. X509TrustManager easyTrustManager = new X509TrustManager() {
  461.  
  462. public void checkClientTrusted(
  463. X509Certificate[] chain,
  464. String authType) throws CertificateException {
  465. // Oh, I am easy!
  466. }
  467.  
  468. public void checkServerTrusted(
  469. X509Certificate[] chain,
  470. String authType) throws CertificateException {
  471. // Oh, I am easy!
  472. }
  473.  
  474. public X509Certificate[] getAcceptedIssuers() {
  475. return null;
  476. }
  477.  
  478.  
  479. };
  480.  
  481. // Create a trust manager that does not validate certificate chains
  482. TrustManager[] trustAllCerts = new TrustManager[] {easyTrustManager};
  483.  
  484. // Install the all-trusting trust manager
  485. try {
  486. SSLContext sc = SSLContext.getInstance("TLS");
  487.  
  488. sc.init(null, trustAllCerts, new java.security.SecureRandom());
  489.  
  490. HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
  491.  
  492. } catch (Exception e) {
  493. e.printStackTrace();
  494. }
  495. }
  496.  
  497. private JSONObject storeTrip(){
  498.  
  499. Log.d(TAG, "storeTrip");
  500.  
  501. JSONObject tripJson = new JSONObject();
  502.  
  503. try {
  504.  
  505. SQLiteDatabase db = DBManager.getInstance().openDatabase();
  506. Cursor tripCursor = db.rawQuery("SELECT * FROM "+DBHelper.annotate_table+ " WHERE " + DBHelper.uploaded_col + " = '" + false + "' ", null); //cause pos start from 0.
  507. Log.d(TAG,"SELECT * FROM "+ DBHelper.annotate_table+ " WHERE " + DBHelper.uploaded_col + " = '" + false + "' "); //+" WHERE "+DBHelper.TIME+" BETWEEN"+" '"+startTime+"' "+"AND"+" '"+endTime+"' "
  508.  
  509. int rows = tripCursor.getCount();
  510.  
  511. Log.d(TAG, "rows : "+rows);
  512.  
  513. if(rows!=0){
  514. tripCursor.moveToFirst();
  515. for(int i=0;i<rows;i++) {
  516.  
  517. String _id = tripCursor.getString(0);
  518.  
  519. JSONObject dataJson = new JSONObject();
  520.  
  521. String startTime = tripCursor.getString(1);
  522. String endTime = tripCursor.getString(2);
  523. String startTimeString = tripCursor.getString(3);
  524. String endTimeString = tripCursor.getString(4);
  525. String sessionid = tripCursor.getString(5);
  526.  
  527. JSONObject annotation_Json = new JSONObject();
  528.  
  529. String activity = tripCursor.getString(6);
  530. String annotation_Goal = tripCursor.getString(7);
  531. String annotation_SpecialEvent = tripCursor.getString(8);
  532.  
  533. String siteName = tripCursor.getString(10);
  534.  
  535. Log.d(TAG,"_id : "+_id+" startTime : "+startTime+" endTime : "+endTime+" sessionid : "+sessionid);
  536. Log.d(TAG,"activity : "+activity+" annotation_Goal : "+annotation_Goal+" annotation_SpecialEvent : "+annotation_SpecialEvent);
  537.  
  538. annotation_Json.put("activity", activity);
  539. annotation_Json.put("annotation_Goal", annotation_Goal);
  540. annotation_Json.put("annotation_SpecialEvent", annotation_SpecialEvent);
  541.  
  542. dataJson.put("device_id", Constants.DEVICE_ID);
  543. dataJson.put("uid", _id); //we can't call "_id" because of MongoDB, it will have its own.
  544. dataJson.put("startTime", startTime);
  545. dataJson.put("endTime", endTime);
  546. dataJson.put("startTimeString", startTimeString);
  547. dataJson.put("endTimeString", endTimeString);
  548. dataJson.put("sessionid", sessionid);
  549. dataJson.put("annotation", annotation_Json);
  550. dataJson.put("siteName", siteName);
  551.  
  552. tripJson = dataJson;
  553.  
  554. // tripJson.put(_id, dataJson);
  555.  
  556. tripCursor.moveToNext();
  557. }
  558.  
  559. Log.d(TAG,"tripJson : "+ tripJson.toString());
  560.  
  561. }
  562.  
  563. }catch (JSONException e){
  564. e.printStackTrace();
  565. }catch(NullPointerException e){
  566. e.printStackTrace();
  567. }
  568.  
  569. return tripJson;
  570. }
  571.  
  572. private void storeTransportation(JSONObject data){
  573.  
  574. try {
  575.  
  576. JSONArray transportationAndtimestampsJson = new JSONArray();
  577.  
  578. SQLiteDatabase db = DBManager.getInstance().openDatabase();
  579. Cursor cursor = db.rawQuery("SELECT * FROM "+DBHelper.transportationMode_table+" WHERE "+DBHelper.TIME+" BETWEEN"+" '"+startTime+"' "+"AND"+" '"+endTime+"' ", null); //cause pos start from 0.
  580.  
  581. int rows = cursor.getCount();
  582. if(rows!=0){
  583.  
  584. cursor.moveToFirst();
  585. for(int i=0;i<rows;i++) {
  586.  
  587. String timestamp = cursor.getString(1);
  588. String transportation = cursor.getString(2);
  589.  
  590.  
  591. //<timestamps, Transportation>
  592. Pair<String, String> transportationTuple = new Pair<>(timestamp, transportation);
  593.  
  594. String dataInPythonTuple = Utils.toPythonTuple(transportationTuple);
  595.  
  596. transportationAndtimestampsJson.put(dataInPythonTuple);
  597.  
  598. cursor.moveToNext();
  599. }
  600.  
  601. data.put("TransportationMode",transportationAndtimestampsJson);
  602. }
  603. }catch (JSONException e){
  604. }catch(NullPointerException e){
  605. }
  606. }
  607.  
  608. private void storeLocation(JSONObject data){
  609.  
  610. try {
  611. JSONArray locationAndtimestampsJson = new JSONArray();
  612.  
  613. SQLiteDatabase db = DBManager.getInstance().openDatabase();
  614. Cursor cursor = db.rawQuery("SELECT * FROM "+DBHelper.location_table +" WHERE "+DBHelper.TIME+" BETWEEN"+" '"+startTime+"' "+"AND"+" '"+endTime+"' ", null); //cause pos start from 0.
  615. //Log.d(TAG,"SELECT * FROM "+DBHelper.STREAM_TYPE_LOCATION +" WHERE "+DBHelper.TIME+" BETWEEN"+" '"+startTime+"' "+"AND"+" '"+endTime+"' ");
  616.  
  617. int rows = cursor.getCount();
  618.  
  619. if(rows!=0){
  620.  
  621. cursor.moveToFirst();
  622. for(int i=0;i<rows;i++) {
  623.  
  624. String timestamp = cursor.getString(1);
  625. String latitude = cursor.getString(2);
  626. String longtitude = cursor.getString(3);
  627. String accuracy = cursor.getString(4);
  628.  
  629. Quartet<String, String, String, String> locationTuple =
  630. new Quartet<>(timestamp, latitude, longtitude, accuracy);
  631.  
  632. String dataInPythonTuple = Utils.toPythonTuple(locationTuple);
  633.  
  634. locationAndtimestampsJson.put(dataInPythonTuple);
  635.  
  636. cursor.moveToNext();
  637. }
  638.  
  639. data.put("Location",locationAndtimestampsJson);
  640. }
  641. }catch (JSONException e){
  642. }catch(NullPointerException e){
  643. }
  644. }
  645.  
  646. private void storeActivityRecognition(JSONObject data){
  647.  
  648. try {
  649. JSONArray arAndtimestampsJson = new JSONArray();
  650.  
  651. SQLiteDatabase db = DBManager.getInstance().openDatabase();
  652. Cursor cursor = db.rawQuery("SELECT * FROM "+DBHelper.activityRecognition_table+" WHERE "+DBHelper.TIME+" BETWEEN"+" '"+startTime+"' "+"AND"+" '"+endTime+"' ", null); //cause pos start from 0.
  653.  
  654. int rows = cursor.getCount();
  655.  
  656. if(rows!=0){
  657.  
  658. cursor.moveToFirst();
  659. for(int i=0;i<rows;i++) {
  660.  
  661. String timestamp = cursor.getString(1);
  662. String mostProbableActivity = cursor.getString(2);
  663. String probableActivities = cursor.getString(3);
  664.  
  665. //split the mostProbableActivity into "type:conf"
  666. String[] subMostActivity = mostProbableActivity.split(",");
  667.  
  668. String type = subMostActivity[0].split("=")[1];
  669. String confidence = subMostActivity[1].split("=")[1].replaceAll("]","");
  670.  
  671. mostProbableActivity = type+":"+confidence;
  672.  
  673. //choose the top two of the probableActivities and split it into "type:conf"
  674. String[] subprobableActivities = probableActivities.split("\\,");
  675. // //Log.d(TAG, "subprobableActivities : "+ subprobableActivities);
  676.  
  677. int lastIndex = 0;
  678. int count = 0;
  679.  
  680. while(lastIndex != -1){
  681.  
  682. lastIndex = probableActivities.indexOf("DetectedActivity",lastIndex);
  683.  
  684. if(lastIndex != -1){
  685. count ++;
  686. lastIndex += "DetectedActivity".length();
  687. }
  688. }
  689.  
  690. if(count == 1){
  691. String type1 = subprobableActivities[0].split("=")[1];
  692. String confidence1 = subprobableActivities[1].split("=")[1].replaceAll("]","");
  693.  
  694. probableActivities = type1+":"+confidence1;
  695.  
  696. }else if(count > 1){
  697. String type1 = subprobableActivities[0].split("=")[1];
  698. String confidence1 = subprobableActivities[1].split("=")[1].replaceAll("]","");
  699. String type2 = subprobableActivities[2].split("=")[1];
  700. String confidence2 = subprobableActivities[3].split("=")[1].replaceAll("]","");
  701.  
  702. probableActivities = type1+":"+confidence1+Constants.DELIMITER+type2+":"+confidence2;
  703.  
  704. }
  705.  
  706. Triplet<String, String, String> arTuple =
  707. new Triplet<>(timestamp, mostProbableActivity, probableActivities);
  708.  
  709. String dataInPythonTuple = Utils.toPythonTuple(arTuple);
  710.  
  711. arAndtimestampsJson.put(dataInPythonTuple);
  712.  
  713. cursor.moveToNext();
  714. }
  715.  
  716. data.put("ActivityRecognition",arAndtimestampsJson);
  717. }
  718. }catch (JSONException e){
  719. }catch(NullPointerException e){
  720. }
  721. }
  722.  
  723. private void storeRinger(JSONObject data){
  724.  
  725. try {
  726. JSONArray ringerAndtimestampsJson = new JSONArray();
  727.  
  728. SQLiteDatabase db = DBManager.getInstance().openDatabase();
  729. Cursor cursor = db.rawQuery("SELECT * FROM "+DBHelper.ringer_table+" WHERE "+DBHelper.TIME+" BETWEEN"+" '"+startTime+"' "+"AND"+" '"+endTime+"' ", null); //cause pos start from 0.
  730.  
  731. int rows = cursor.getCount();
  732.  
  733. if(rows!=0){
  734.  
  735. cursor.moveToFirst();
  736. for(int i=0;i<rows;i++) {
  737.  
  738. String timestamp = cursor.getString(1);
  739. String ringerMode = cursor.getString(2);
  740. String audioMode = cursor.getString(3);
  741. String streamVolumeMusic = cursor.getString(4);
  742. String streamVolumeNotification = cursor.getString(5);
  743. String streamVolumeRing = cursor.getString(6);
  744. String streamVolumeVoicecall = cursor.getString(7);
  745. String streamVolumeSystem = cursor.getString(8);
  746.  
  747. Octet<String, String, String, String, String, String, String, String> ringerTuple
  748. = new Octet<>(timestamp, streamVolumeSystem, streamVolumeVoicecall, streamVolumeRing,
  749. streamVolumeNotification, streamVolumeMusic, audioMode, ringerMode);
  750.  
  751. String dataInPythonTuple = Utils.toPythonTuple(ringerTuple);
  752.  
  753. ringerAndtimestampsJson.put(dataInPythonTuple);
  754.  
  755. cursor.moveToNext();
  756. }
  757.  
  758. data.put("Ringer",ringerAndtimestampsJson);
  759. }
  760. }catch (JSONException e){
  761. }catch(NullPointerException e){
  762. }
  763. }
  764.  
  765. private void storeConnectivity(JSONObject data){
  766.  
  767. try {
  768.  
  769. JSONArray connectivityAndtimestampsJson = new JSONArray();
  770.  
  771. SQLiteDatabase db = DBManager.getInstance().openDatabase();
  772. Cursor cursor = db.rawQuery("SELECT * FROM "+DBHelper.connectivity_table+" WHERE "+DBHelper.TIME+" BETWEEN"+" '"+startTime+"' "+"AND"+" '"+endTime+"' ", null); //cause pos start from 0.
  773.  
  774. int rows = cursor.getCount();
  775.  
  776. if(rows!=0){
  777.  
  778. cursor.moveToFirst();
  779. for(int i=0;i<rows;i++) {
  780.  
  781. String timestamp = cursor.getString(1);
  782. String NetworkType = cursor.getString(2);
  783. String IsNetworkAvailable = cursor.getString(3);
  784. String IsConnected = cursor.getString(4);
  785. String IsWifiAvailable = cursor.getString(5);
  786. String IsMobileAvailable = cursor.getString(6);
  787. String IsWifiConnected = cursor.getString(7);
  788. String IsMobileConnected = cursor.getString(8);
  789.  
  790. Octet<String, String, String, String, String, String, String, String> connectivityTuple
  791. = new Octet<>(timestamp, IsMobileConnected, IsWifiConnected, IsMobileAvailable,
  792. IsWifiAvailable, IsConnected, IsNetworkAvailable, NetworkType);
  793.  
  794. String dataInPythonTuple = Utils.toPythonTuple(connectivityTuple);
  795.  
  796. connectivityAndtimestampsJson.put(dataInPythonTuple);
  797.  
  798. cursor.moveToNext();
  799. }
  800.  
  801. data.put("Connectivity",connectivityAndtimestampsJson);
  802. }
  803. }catch (JSONException e){
  804. }catch(NullPointerException e){
  805. }
  806. }
  807.  
  808. private void storeBattery(JSONObject data){
  809. try {
  810.  
  811. JSONArray batteryAndtimestampsJson = new JSONArray();
  812.  
  813. SQLiteDatabase db = DBManager.getInstance().openDatabase();
  814. Cursor cursor = db.rawQuery("SELECT * FROM "+DBHelper.battery_table+" WHERE "+DBHelper.TIME+" BETWEEN"+" '"+startTime+"' "+"AND"+" '"+endTime+"' ", null); //cause pos start from 0.
  815.  
  816. int rows = cursor.getCount();
  817.  
  818. if(rows!=0){
  819.  
  820. cursor.moveToFirst();
  821. for(int i=0;i<rows;i++) {
  822.  
  823. String timestamp = cursor.getString(1);
  824. String BatteryLevel = cursor.getString(2);
  825. String BatteryPercentage = cursor.getString(3);
  826. String BatteryChargingState = cursor.getString(4);
  827. String isCharging = cursor.getString(5);
  828.  
  829.  
  830. Quintet<String, String, String, String, String> batteryTuple
  831. = new Quintet<>(timestamp, isCharging, BatteryChargingState, BatteryPercentage, BatteryLevel);
  832.  
  833. String dataInPythonTuple = Utils.toPythonTuple(batteryTuple);
  834.  
  835. batteryAndtimestampsJson.put(dataInPythonTuple);
  836.  
  837. cursor.moveToNext();
  838. }
  839.  
  840. data.put("Battery", batteryAndtimestampsJson);
  841. }
  842. }catch (JSONException e){
  843. }catch(NullPointerException e){
  844. }
  845. }
  846.  
  847. private void storeAppUsage(JSONObject data){
  848. try {
  849.  
  850. JSONArray appUsageAndtimestampsJson = new JSONArray();
  851.  
  852. SQLiteDatabase db = DBManager.getInstance().openDatabase();
  853. Cursor cursor = db.rawQuery("SELECT * FROM "+DBHelper.appUsage_table+" WHERE "+DBHelper.TIME+" BETWEEN"+" '"+startTime+"' "+"AND"+" '"+endTime+"' ", null); //cause pos start from 0.
  854.  
  855. int rows = cursor.getCount();
  856.  
  857. if(rows!=0){
  858.  
  859. cursor.moveToFirst();
  860.  
  861. for(int i=0;i<rows;i++) {
  862.  
  863. String timestamp = cursor.getString(1);
  864. String ScreenStatus = cursor.getString(2);
  865. String Latest_Used_App = cursor.getString(3);
  866. String Latest_Foreground_Activity = cursor.getString(4);
  867.  
  868. // String timestampInSec = timestamp.substring(0, timestamp.length()-3);
  869.  
  870. //<timestamp, ScreenStatus, Latest_Used_App, Latest_Foreground_Activity>
  871. Quartet<String, String, String, String> appUsageTuple
  872. = new Quartet<>(timestamp, ScreenStatus, Latest_Used_App, Latest_Foreground_Activity);
  873.  
  874. String dataInPythonTuple = Utils.toPythonTuple(appUsageTuple);
  875.  
  876. appUsageAndtimestampsJson.put(dataInPythonTuple);
  877.  
  878. cursor.moveToNext();
  879. }
  880.  
  881. data.put("AppUsage",appUsageAndtimestampsJson);
  882. }
  883. }catch (JSONException e){
  884. }catch(NullPointerException e){
  885. }
  886. }
  887.  
  888. public void storeTelephony(JSONObject data){
  889.  
  890. try {
  891.  
  892. JSONArray telephonyAndtimestampsJson = new JSONArray();
  893.  
  894. SQLiteDatabase db = DBManager.getInstance().openDatabase();
  895. Cursor cursor = db.rawQuery("SELECT * FROM "+DBHelper.telephony_table+" WHERE "+DBHelper.TIME+" BETWEEN"+" '"+startTime+"' "+"AND"+" '"+endTime+"' ", null); //cause pos start from 0.
  896.  
  897. int rows = cursor.getCount();
  898.  
  899. if(rows!=0){
  900.  
  901. cursor.moveToFirst();
  902.  
  903. for(int i=0;i<rows;i++) {
  904.  
  905. String timestamp = cursor.getString(1);
  906. String networkOperatorName = cursor.getString(2);
  907. String callState = cursor.getString(3);
  908. String phoneSignalType = cursor.getString(4);
  909. String gsmSignalStrength = cursor.getString(5);
  910. String LTESignalStrength = cursor.getString(6);
  911. String CdmaSignalStrengthLevel = cursor.getString(7);
  912.  
  913. // String timestampInSec = timestamp.substring(0, timestamp.length()-3);
  914.  
  915. //<timestamp, networkOperatorName, CallState, PhoneSignalType_col, gsmSignalStrength, LTESignalStrength, CdmaSignalStrengthLevel>
  916. Septet<String, String, String, String, String, String ,String> telephonyTuple
  917. = new Septet<>(timestamp, networkOperatorName, callState, phoneSignalType, gsmSignalStrength, LTESignalStrength, CdmaSignalStrengthLevel);
  918.  
  919. String dataInPythonTuple = Utils.toPythonTuple(telephonyTuple);
  920.  
  921. telephonyAndtimestampsJson.put(dataInPythonTuple);
  922.  
  923. cursor.moveToNext();
  924. }
  925.  
  926. data.put("Telephony",telephonyAndtimestampsJson);
  927. }
  928. }catch (JSONException e){
  929. }catch(NullPointerException e){
  930. }
  931. }
  932.  
  933. public void storeSensor(JSONObject data){
  934.  
  935. try {
  936.  
  937. JSONArray sensorAndtimestampsJson = new JSONArray();
  938.  
  939. SQLiteDatabase db = DBManager.getInstance().openDatabase();
  940. Cursor cursor = db.rawQuery("SELECT * FROM "+DBHelper.sensor_table+" WHERE "+DBHelper.TIME+" BETWEEN"+" '"+startTime+"' "+"AND"+" '"+endTime+"' ", null); //cause pos start from 0.
  941.  
  942. int rows = cursor.getCount();
  943.  
  944. if(rows!=0){
  945.  
  946. cursor.moveToFirst();
  947.  
  948. for(int i=0;i<rows;i++) {
  949.  
  950. String timestamp = cursor.getString(1);
  951. String accelerometer = cursor.getString(2);
  952. String gyroscope = cursor.getString(3);
  953. String gravity = cursor.getString(4);
  954. String linear_acceleration = cursor.getString(5);
  955. String rotation_vector = cursor.getString(6);
  956. String proximity = cursor.getString(7);
  957. String magnetic_field = cursor.getString(8);
  958. String light = cursor.getString(9);
  959. String pressure = cursor.getString(10);
  960.  
  961. // String timestampInSec = timestamp.substring(0, timestamp.length()-3);
  962.  
  963. //<timestamp, accelerometer, gyroscope, gravity, linear_acceleration, ROTATION_VECTOR, PROXIMITY, MAGNETIC_FIELD, LIGHT, PRESSURE>
  964. Decade<String, String, String, String, String, String ,String, String, String, String> sensorTuple1
  965. = new Decade<>(timestamp, accelerometer, gyroscope, gravity, linear_acceleration, rotation_vector, proximity, magnetic_field, light, pressure);
  966.  
  967. String relative_humidity = cursor.getString(11);
  968. String ambient_temperature = cursor.getString(12);
  969.  
  970. //<RELATIVE_HUMIDITY, AMBIENT_TEMPERATURE>
  971. Pair<String, String> sensorTuple2 = new Pair<>(relative_humidity, ambient_temperature);
  972.  
  973. String dataInPythonTuple = Utils.tupleConcat(sensorTuple1, sensorTuple2);
  974.  
  975. Log.d(TAG, "Sensor data : "+dataInPythonTuple);
  976.  
  977. sensorAndtimestampsJson.put(dataInPythonTuple);
  978.  
  979. cursor.moveToNext();
  980. }
  981.  
  982. data.put("Sensor",sensorAndtimestampsJson);
  983. }
  984. }catch (JSONException e){
  985. }catch(NullPointerException e){
  986. }
  987. }
  988.  
  989. public void storeAccessibility(JSONObject data){
  990.  
  991. try {
  992.  
  993. JSONArray accessibilityAndtimestampsJson = new JSONArray();
  994.  
  995. SQLiteDatabase db = DBManager.getInstance().openDatabase();
  996. Cursor cursor = db.rawQuery("SELECT * FROM "+DBHelper.sensor_table+" WHERE "+DBHelper.TIME+" BETWEEN"+" '"+startTime+"' "+"AND"+" '"+endTime+"' ", null); //cause pos start from 0.
  997.  
  998. int rows = cursor.getCount();
  999.  
  1000. if(rows!=0){
  1001.  
  1002. cursor.moveToFirst();
  1003.  
  1004. for(int i=0;i<rows;i++) {
  1005.  
  1006. String timestamp = cursor.getString(1);
  1007. String pack = cursor.getString(2);
  1008. String text = cursor.getString(3);
  1009. String type = cursor.getString(4);
  1010. String extra = cursor.getString(5);
  1011.  
  1012. // String timestampInSec = timestamp.substring(0, timestamp.length()-3);
  1013.  
  1014. //<timestamp, pack, text, type, extra>
  1015. Quintet<String, String, String, String, String> accessibilityTuple
  1016. = new Quintet<>(timestamp, pack, text, type, extra);
  1017.  
  1018. String dataInPythonTuple = Utils.toPythonTuple(accessibilityTuple);
  1019.  
  1020. accessibilityAndtimestampsJson.put(dataInPythonTuple);
  1021.  
  1022. cursor.moveToNext();
  1023. }
  1024.  
  1025. data.put("Accessibility", accessibilityAndtimestampsJson);
  1026. }
  1027. }catch (JSONException e){
  1028. }catch(NullPointerException e){
  1029. }
  1030. }
  1031.  
  1032. private long getSpecialTimeInMillis(String givenDateFormat){
  1033. SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT_NOW);
  1034. long timeInMilliseconds = 0;
  1035. try {
  1036. Date mDate = sdf.parse(givenDateFormat);
  1037. timeInMilliseconds = mDate.getTime();
  1038. Log.d(TAG,"Date in milli :: " + timeInMilliseconds);
  1039. } catch (ParseException e) {
  1040. e.printStackTrace();
  1041. }
  1042. return timeInMilliseconds;
  1043. }
  1044.  
  1045. private long getSpecialTimeInMillis(int year,int month,int date,int hour,int min){
  1046. // TimeZone tz = TimeZone.getDefault(); tz
  1047. Calendar cal = Calendar.getInstance();
  1048. // cal.set(year,month,date,hour,min,0);
  1049. cal.set(Calendar.YEAR, year);
  1050. cal.set(Calendar.MONTH, month);
  1051. cal.set(Calendar.DAY_OF_MONTH, date);
  1052. cal.set(Calendar.HOUR_OF_DAY, hour);
  1053. cal.set(Calendar.MINUTE, min);
  1054. cal.set(Calendar.SECOND, 0);
  1055.  
  1056. long t = cal.getTimeInMillis();
  1057.  
  1058. return t;
  1059. }
  1060.  
  1061. private void storeTripToLocalFolder(JSONObject completedJson){
  1062. Log.d(TAG, "storeTripToLocalFolder");
  1063.  
  1064. String sFileName = "Trip_"+getTimeString(startTime)+"_"+getTimeString(endTime)+".json";
  1065.  
  1066. Log.d(TAG, "sFileName : "+ sFileName);
  1067.  
  1068. try {
  1069. File root = new File(Environment.getExternalStorageDirectory() + Constants.PACKAGE_DIRECTORY_PATH);
  1070. if (!root.exists()) {
  1071. root.mkdirs();
  1072. }
  1073.  
  1074. Log.d(TAG, "root : " + root);
  1075.  
  1076. FileWriter fileWriter = new FileWriter(root+sFileName, true);
  1077. fileWriter.write(completedJson.toString());
  1078. fileWriter.close();
  1079. } catch(IOException e) {
  1080. e.printStackTrace();
  1081. }
  1082.  
  1083. }
  1084.  
  1085. private void storeToLocalFolder(JSONObject completedJson, int count){
  1086. Log.d(TAG, "storeToLocalFolder");
  1087.  
  1088. // String sFileName = "Dump_"+getTimeString(startTime)+"_"+getTimeString(endTime)+".json";
  1089.  
  1090. count ++ ;
  1091.  
  1092. String sFileName = "Dump_"+count+".json";
  1093.  
  1094. Log.d(TAG, "sFileName : "+ sFileName);
  1095.  
  1096. try {
  1097. File root = new File(Environment.getExternalStorageDirectory() + Constants.PACKAGE_DIRECTORY_PATH);
  1098. if (!root.exists()) {
  1099. root.mkdirs();
  1100. }
  1101.  
  1102. Log.d(TAG, "root : " + root);
  1103.  
  1104. FileWriter fileWriter = new FileWriter(root+sFileName, true);
  1105. fileWriter.write(completedJson.toString());
  1106. fileWriter.close();
  1107.  
  1108. } catch(IOException e) {
  1109. e.printStackTrace();
  1110. }
  1111.  
  1112. }
  1113. //TODO remember the format is different from the normal one.
  1114. public static String getTimeString(long time){
  1115.  
  1116. SimpleDateFormat sdf_now = new SimpleDateFormat(Constants.DATE_FORMAT_for_storing);
  1117. String currentTimeString = sdf_now.format(time);
  1118.  
  1119. return currentTimeString;
  1120. }
  1121.  
  1122. public String makingDataFormat(int year,int month,int date,int hour,int min){
  1123. String dataformat= "";
  1124.  
  1125. dataformat = addZero(year)+"/"+addZero(month)+"/"+addZero(date)+" "+addZero(hour)+":"+addZero(min)+":00";
  1126. Log.d(TAG,"dataformat : " + dataformat);
  1127.  
  1128. return dataformat;
  1129. }
  1130.  
  1131. public String getDateCurrentTimeZone(long timestamp) {
  1132. try{
  1133. Calendar calendar = Calendar.getInstance();
  1134. TimeZone tz = TimeZone.getDefault();
  1135. calendar.setTimeInMillis(timestamp);
  1136. calendar.add(Calendar.MILLISECOND, tz.getOffset(calendar.getTimeInMillis()));
  1137. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  1138. Date currenTimeZone = (Date) calendar.getTime();
  1139. return sdf.format(currenTimeZone);
  1140. }catch (Exception e) {
  1141. e.printStackTrace();
  1142. }
  1143. return "";
  1144. }
  1145.  
  1146. private String getmillisecondToDateWithTime(long timeStamp){
  1147.  
  1148. Calendar calendar = Calendar.getInstance();
  1149. calendar.setTimeInMillis(timeStamp);
  1150.  
  1151. int mYear = calendar.get(Calendar.YEAR);
  1152. int mMonth = calendar.get(Calendar.MONTH)+1;
  1153. int mDay = calendar.get(Calendar.DAY_OF_MONTH);
  1154. int mhour = calendar.get(Calendar.HOUR_OF_DAY);
  1155. int mMin = calendar.get(Calendar.MINUTE);
  1156. int mSec = calendar.get(Calendar.SECOND);
  1157.  
  1158. return addZero(mYear)+"/"+addZero(mMonth)+"/"+addZero(mDay)+" "+addZero(mhour)+":"+addZero(mMin)+":"+addZero(mSec);
  1159.  
  1160. }
  1161.  
  1162. private String addZero(int date){
  1163. if(date<10)
  1164. return String.valueOf("0"+date);
  1165. else
  1166. return String.valueOf(date);
  1167. }
  1168.  
  1169. /**get the current time in milliseconds**/
  1170. private long getCurrentTimeInMillis(){
  1171. //get timzone
  1172. TimeZone tz = TimeZone.getDefault();
  1173. Calendar cal = Calendar.getInstance(tz);
  1174. //get the date of now: the first month is Jan:0
  1175. int year = cal.get(Calendar.YEAR);
  1176. int month = cal.get(Calendar.MONTH) + 1;
  1177. int day = cal.get(Calendar.DAY_OF_MONTH);
  1178. int Hour = cal.get(Calendar.HOUR);
  1179. int Min = cal.get(Calendar.MINUTE);
  1180.  
  1181. long t = getSpecialTimeInMillis(year,month,day,Hour,Min);
  1182. return t;
  1183. }
  1184. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement