Advertisement
Guest User

Untitled

a guest
Nov 21st, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 21.84 KB | None | 0 0
  1. package com.naviexpert.telematics.b2b.api;
  2.  
  3. import android.annotation.SuppressLint;
  4. import android.os.AsyncTask;
  5. import android.util.Log;
  6.  
  7. import com.naviexpert.telematics.BuildConfig;
  8. import com.naviexpert.telematics.b2b.Const;
  9.  
  10. import org.json.JSONArray;
  11. import org.json.JSONException;
  12. import org.json.JSONObject;
  13.  
  14. import java.io.BufferedReader;
  15. import java.io.DataOutputStream;
  16. import java.io.IOException;
  17. import java.io.InputStream;
  18. import java.io.InputStreamReader;
  19. import java.net.HttpURLConnection;
  20. import java.net.MalformedURLException;
  21. import java.net.URL;
  22. import java.security.cert.CertificateException;
  23. import java.security.cert.X509Certificate;
  24. import java.util.Enumeration;
  25. import java.util.Hashtable;
  26. import java.util.List;
  27. import java.util.Locale;
  28.  
  29. import javax.net.ssl.HostnameVerifier;
  30. import javax.net.ssl.HttpsURLConnection;
  31. import javax.net.ssl.SSLContext;
  32. import javax.net.ssl.SSLSession;
  33. import javax.net.ssl.TrustManager;
  34. import javax.net.ssl.X509TrustManager;
  35.  
  36. /**
  37. * Created by Krzysztof Wachnik on 2017-05-15.
  38. *
  39. */
  40. public class TelematicsApi {
  41.  
  42. /** more logs */
  43. private static final boolean D = true;
  44. /** tag for logs */
  45. private static final String TAG = TelematicsApi.class.getSimpleName();
  46. public static final int SPEED_LIMIT_NO_VALUE = -1;
  47. public static final int SPEED_LIMIT_UNKNOWN_ANGLE = -2;
  48.  
  49. //fields in response
  50. //speed limits
  51. private static final String GEOMETRY = "geometry";
  52. private static final String PROPERTIES = "properties";
  53. private static final String CATEGORY = "category";
  54. private static final String DIRECTION = "direction";
  55. private static final String SPEED_LIMIT_ALONG = "speedLimitAlong";
  56. private static final String SPEED_LIMIT_AGAINST = "speedLimitAgainst";
  57. private static final String COORDINATES = "coordinates";
  58. private static final String FEATURES = "features";
  59. //config
  60. private static final String ACCELERATION = "acceleration";
  61. private static final String DECELERATION = "braking";
  62. private static final String THRESHOLD_MIN = "minThreshold";
  63. private static final String THRESHOLD_MED = "mediumThreshold";
  64. private static final String THRESHOLD_MAX = "strongThreshold";
  65. //access token
  66. private static final String ACCESS_TOKEN = "accessToken";
  67.  
  68. //response ids
  69. public static final int REQ_TYPE_ROADS = 1;
  70. public static final int REQ_TYPE_CONF = 2;
  71. public static final int REQ_TYPE_TOKEN = 3;
  72. public static final int REQ_TYPE_IS_ACTIVE = 4;
  73. //endpoints
  74. private static final String API_REGISTER = "register";
  75. private static final String API_ROADS = "roads";
  76. private static final String API_CONFIG = "config";
  77. private static final String API_IS_ACTIVE = "is_active";
  78.  
  79.  
  80. /** to handle response */
  81. private RequestListener listener;
  82. /** task with send request to api */
  83. private ConnectTask sendTask;
  84. /** TODO to use in future */
  85. private int reqId = 1;
  86. /** for future use - handle cookies before requests */
  87. private static Hashtable<String, String> cookies = new Hashtable<>();
  88. /** instance */
  89. private static TelematicsApi api;
  90. private String accessToken = "";
  91.  
  92. /** to use in future in errors handling */
  93. public class Errors {
  94. public static final int BAD_URL = -10;
  95. public static final int ERR_IO = -11;
  96. public static final int ERR_UNKNOWN = -12;
  97. public static final int ERR_HTTP_UNAUTH = 401;
  98. public static final int ERR_NOT_FOUND = 404;
  99. public static final int ERR_500 = 500;
  100. public static final int ERR_501 = 501;
  101. }
  102.  
  103. public static TelematicsApi getInstance() {
  104. if (api==null) {
  105. if (D) Log.d(TAG,"getInstance: new instance");
  106. api = new TelematicsApi();
  107. }
  108. return api;
  109. }
  110.  
  111. public void setAccessToken(String accessToken) {
  112. this.accessToken = accessToken;
  113. }
  114.  
  115. public interface RequestListener {
  116. public void onSuccess(int id, String response);
  117. public void onError(int id, String message);
  118. }
  119.  
  120. /** @return the listener */
  121. public RequestListener getListener() {
  122. return listener;
  123. }
  124.  
  125. /**
  126. * Returns unformatted response from api.
  127. *
  128. * @param listener the listener to set */
  129. public void setListener(RequestListener listener) {
  130. this.listener = listener;
  131. }
  132.  
  133. /**
  134. * Ask for a section of the road map specified by the coordinates in the parameters
  135. * @param minLon 1st coordinate longtitude
  136. * @param maxLon 2 coordinate longtitude
  137. * @param minLat 1st coordinate latitude
  138. * @param maxLat 2 coordinate latitude
  139. */
  140. public int getRoads(double minLon, double maxLon, double minLat, double maxLat) {
  141. Log.d(TAG, "getRoads: ");
  142. String query=API_ROADS+"?"+"minLon="+minLon+"&maxLon="+maxLon+"&minLat="+minLat+"&maxLat="+maxLat;
  143. // TODO to future use reqId++;
  144. reqId = REQ_TYPE_ROADS;
  145. sendTask = new ConnectTask();
  146. sendTask.execute(query,""+reqId);
  147. return reqId;
  148. }
  149.  
  150. /**
  151. * get thresholds configuration
  152. * @return request type
  153. */
  154. public int getConfig() {
  155. Log.d(TAG, "getConfig: ");
  156. String query=API_CONFIG;
  157. // TODO to future use reqId++;
  158. reqId = REQ_TYPE_CONF;
  159. sendTask = new ConnectTask();
  160. sendTask.execute(query,""+reqId);
  161. return reqId;
  162. }
  163.  
  164. /**
  165. * get authorization token
  166. * @param deviceCode device number
  167. * @param phoneNumber phone number
  168. * @return request type
  169. */
  170. public int getToken(String deviceCode, String phoneNumber) {
  171. Log.d(TAG, "getToken: deviceCode="+deviceCode);
  172. JSONObject jo = new JSONObject();
  173. try {
  174. jo.put("deviceCode",deviceCode);
  175. jo.put("phoneNumber",phoneNumber);
  176. } catch (JSONException e) {
  177. e.printStackTrace();
  178. }
  179. String query = jo.toString();
  180. Log.d(TAG, "getToken: query="+query);
  181. reqId = REQ_TYPE_TOKEN;
  182. sendTask = new ConnectTask();
  183. sendTask.execute(API_REGISTER,""+reqId,query);
  184. return reqId;
  185. }
  186.  
  187. public int sendActive() {
  188. Log.d(TAG, "sendActive: ");
  189. String query=API_IS_ACTIVE;
  190. // TODO to future use reqId++;
  191. reqId = REQ_TYPE_IS_ACTIVE;
  192. sendTask = new ConnectTask();
  193. sendTask.execute(query,""+reqId);
  194. return reqId;
  195. }
  196.  
  197. /**
  198. * Parsing the response from api.
  199. * TODO note to the backend - in response should be the coordinates of the returned area.
  200. * This would easiely allow you to detect any problems with the map (gps or network problem etc.)
  201. */
  202. public Roads parseRoads(String response) {
  203. Roads roads = new Roads();
  204. try {
  205. JSONArray ja = new JSONObject(response).getJSONArray(FEATURES);
  206. for (int i=0;i<ja.length();i++) {
  207. Road road = new Road();
  208. JSONObject jo = ja.getJSONObject(i);
  209. JSONObject geometry = jo.getJSONObject(GEOMETRY);
  210. JSONObject prop = jo.getJSONObject(PROPERTIES);
  211. if (prop.has(CATEGORY)) road.category = prop.getString(CATEGORY);
  212. if (prop.has(DIRECTION)) road.direction = prop.getInt(DIRECTION);
  213. try {
  214. if (prop.has(SPEED_LIMIT_ALONG)) road.speedLimitAlong = prop.getInt(SPEED_LIMIT_ALONG);
  215. } catch (Exception e) {
  216. //e.printStackTrace();
  217. road.speedLimitAlong = SPEED_LIMIT_NO_VALUE;
  218. }
  219. try {
  220. if (prop.has(SPEED_LIMIT_AGAINST)) road.speedLimitAgainst = prop.getInt(SPEED_LIMIT_AGAINST);
  221. } catch (Exception e) {
  222. //e.printStackTrace();
  223. road.speedLimitAgainst = SPEED_LIMIT_NO_VALUE;
  224. }
  225. JSONArray cord = geometry.getJSONArray(COORDINATES);
  226. for (int j=0;j<cord.length();j++) {
  227. double lon = cord.getJSONArray(j).getDouble(0);
  228. double lat = cord.getJSONArray(j).getDouble(1);
  229. road.coordinates.add(new Place(lon,lat));
  230. }
  231. roads.add(road);
  232. }
  233. } catch (JSONException e) {
  234. Log.e(TAG, "parseRoads: "+e.getMessage());
  235. e.printStackTrace();
  236. }
  237. return roads;
  238. }
  239.  
  240. /**
  241. * parse config responce
  242. */
  243. public AppConfig parseConfig(String response) {
  244. AppConfig conf = new AppConfig();
  245. try {
  246. JSONObject jo = new JSONObject(response);
  247. conf.accDetect = (float)jo.getJSONObject(ACCELERATION).getDouble(THRESHOLD_MIN);
  248. conf.accFirst = (float)jo.getJSONObject(ACCELERATION).getDouble(THRESHOLD_MED);
  249. conf.accStrong = (float)jo.getJSONObject(ACCELERATION).getDouble(THRESHOLD_MAX);
  250. conf.decDetect = (float)jo.getJSONObject(DECELERATION).getDouble(THRESHOLD_MIN);
  251. conf.decFirst = (float)jo.getJSONObject(DECELERATION).getDouble(THRESHOLD_MED);
  252. conf.decStrong = (float)jo.getJSONObject(DECELERATION).getDouble(THRESHOLD_MAX);
  253. }catch (JSONException e) {
  254. Log.e(TAG, "parseConfig: "+e.getMessage());
  255. e.printStackTrace();
  256. }
  257. return conf;
  258. }
  259.  
  260. public String parseToken(String response) {
  261. String token = "";
  262. try {
  263. JSONObject jo = new JSONObject(response);
  264. if (jo.has(ACCESS_TOKEN)) token = jo.getString(ACCESS_TOKEN);
  265. } catch (JSONException e) {
  266. Log.e(TAG, "parseToken: "+e.getMessage() );
  267. e.printStackTrace();
  268. }
  269. return token;
  270. }
  271.  
  272. //---------------------------- private ------------------------------------------
  273.  
  274. private class ConnectTask extends AsyncTask<String, String, String> {
  275.  
  276. private int requestId = 0;
  277.  
  278. @Override
  279. protected String doInBackground(String... params) {
  280. String content = "";
  281. String query = params[0];
  282. requestId = Integer.parseInt(params[1]);
  283. if (params.length>2) content = params[2];
  284. Log.d(TAG, "doInBackground: content="+content+" length="+content.length());
  285. if (content!=null && content.length()>0) {
  286. return httpConnectPost(BuildConfig.SERVER_API+query,content);
  287. } else {
  288. return httpConnect(BuildConfig.SERVER_API+query);
  289. }
  290. }
  291.  
  292. @Override
  293. protected void onPostExecute(String result) {
  294. super.onPostExecute(result);
  295. if (result != null && result.length()>4) {
  296. Log.d(TAG,"onPostExecute: result="+result+" length="+result.length());
  297. if (listener!=null) listener.onSuccess(requestId, result);
  298. } else {
  299. if (listener!=null) listener.onError(requestId, result);
  300. }
  301. }
  302. }
  303.  
  304. private String httpConnect(String adress) {
  305. System.setProperty("java.net.ssl","false"); //@see trustAllHosts //TODO remove it in stable version
  306. URL url;
  307. int err = 0;
  308. HttpURLConnection conn = null;
  309. int responseCode = 0;
  310. String result="0";
  311. URL redirectUrl = null; //to use in future in 302
  312. try {
  313. url=new URL(adress);
  314. //----------------------------
  315. if (url.getProtocol().toLowerCase(Locale.getDefault()).equals("https")) {
  316. trustAllHosts();
  317. HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
  318. https.setHostnameVerifier(DO_NOT_VERIFY);
  319. conn = https;
  320. } else {
  321. conn = (HttpURLConnection) url.openConnection();
  322. }
  323. //-------------
  324. conn.setRequestMethod("GET");
  325. conn.setDoInput(true);
  326. conn.setRequestProperty("User-Agent", Const.USER_AGENT);
  327. if (accessToken!=null && accessToken.length()>0)
  328. conn.setRequestProperty ("Authorization", accessToken);
  329. conn.setUseCaches(false);
  330. conn.setFollowRedirects(true);
  331. conn.setInstanceFollowRedirects(true);
  332. //need test:
  333. //conn.setConnectTimeout(15000);
  334. //conn.setReadTimeout(30000);
  335.  
  336. if (D) Log.d(TAG,"httpConnectGet() "+" url="+conn.getURL());
  337.  
  338. //sending cookie
  339. String setCookie = "";
  340. for (Enumeration<String> e = cookies.keys(); e.hasMoreElements();) {
  341. String key = e.nextElement();
  342. String value = cookies.get(key);
  343. setCookie += key+"="+value+" ";
  344. }
  345. if (setCookie.length()>0) conn.setRequestProperty("cookie", setCookie);
  346.  
  347. conn.connect();
  348. if (conn!=null) responseCode = conn.getResponseCode();
  349. if (D) Log.d(TAG,"httpConnectGet: responce Code="+responseCode+" "+conn.getResponseMessage());
  350. if (responseCode==-1) { conn.connect(); }
  351. if (conn!=null) redirectUrl = conn.getURL();
  352.  
  353. //geting cookie
  354. if (conn!=null) {
  355. List<String> cookiesPom = conn.getHeaderFields().get("set-cookie");
  356. if (cookiesPom==null) cookiesPom = conn.getHeaderFields().get("Set-cookie");
  357. if (cookiesPom!=null)
  358. for (int i=0;i<cookiesPom.size();i++) {
  359. String[] cc=cookiesPom.get(i).split(";");
  360. int idxpom = cc[0].indexOf("=");
  361. String cc0 = cc[0].substring(0,idxpom);
  362. String cc1 = cc[0].substring(idxpom+1,cc[0].length())+";";
  363. cookies.put(cc0, cc1);
  364. }
  365. }
  366. //Get Response
  367. InputStream is = conn.getInputStream();
  368. BufferedReader rd = new BufferedReader(new InputStreamReader(is));
  369. String line;
  370. StringBuffer response = new StringBuffer();
  371. while((line = rd.readLine()) != null) {
  372. response.append(line);
  373. response.append('\r');
  374. }
  375. rd.close();
  376. if (D) Log.d(TAG,"httpConnectGet: url="+conn.getURL());
  377. result=response.toString();
  378. //-
  379. } catch (MalformedURLException e) {
  380. err = Errors.BAD_URL;
  381. Log.e(TAG,"httpConnectGet: BAD URL: "+e.getMessage());
  382. } catch (IOException e) {
  383. err = Errors.ERR_IO;
  384. Log.e(TAG,"httpConnectGet: IO Error: "+e.getMessage());
  385. e.printStackTrace();
  386. } catch (Exception e) {
  387. err=-Errors.ERR_UNKNOWN;
  388. e.printStackTrace();
  389. Log.e(TAG,"httpConnectGet: Unknown Error: "+e.getMessage());
  390. }
  391. finally {
  392. if (conn!=null) conn.disconnect();
  393. }
  394. if (D) Log.d(TAG,"httpConnectGet: resp: "+responseCode+" body length: "+result.length());
  395. if (result.length()<4) {
  396. if (responseCode == 200)
  397. result = result + "-----";
  398. else
  399. result = "";
  400. }
  401. if (responseCode>=400 && responseCode<500) {
  402. result = String.valueOf(responseCode);
  403. } else
  404. if (err<0) {
  405. result=((Integer) err).toString();
  406. }
  407. return result;
  408. }
  409.  
  410. private String httpConnectPost(String adress, String query) {
  411. System.setProperty("java.net.ssl","false"); //needed //@see trustAllHosts //TODO remove it in stable version
  412. URL url = null;
  413. int err = 0;
  414. HttpURLConnection conn = null;
  415. int responseCode = 0;
  416. String result="0";
  417.  
  418. URL redirectUrl = null; //to use in future in 302
  419. try {
  420. url=new URL(adress);
  421. //----------------------------
  422. if (url.getProtocol().toLowerCase(Locale.getDefault()).equals("https")) {
  423. trustAllHosts();
  424. HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
  425. https.setHostnameVerifier(DO_NOT_VERIFY);
  426. conn = https;
  427. } else {
  428. conn = (HttpURLConnection) url.openConnection();
  429. }
  430. //-------------
  431. conn.setDoOutput(true);
  432. conn.setRequestMethod("POST");
  433. conn.setDoInput(true);
  434. conn.setRequestProperty("User-Agent",Const.USER_AGENT);
  435. //conn.setRequestProperty("Content-Type", "multipart/form-data");
  436. //conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  437. conn.setRequestProperty("Content-Type", "application/json");
  438. conn.setRequestProperty("Content-Length", Integer.toString(query.length()));
  439. //conn.setUseCaches(false); //may be needed
  440. //conn.setConnectTimeout(15000);
  441. //conn.setReadTimeout(30000);
  442.  
  443. if (D) Log.d(TAG,"httpConnectPost: query.lenght="+query.length()+" query="+query+" url="+conn.getURL());
  444. //sending cookies
  445. String setCookie = "";
  446. for (Enumeration<String> e = cookies.keys(); e.hasMoreElements();) {
  447. String key= (String) e.nextElement();
  448. String value = (String) cookies.get(key);
  449. setCookie += key+"="+value+" ";
  450. }
  451. if (setCookie.length()>0) conn.setRequestProperty("cookie", setCookie);
  452. if (D) Log.d(TAG,"httpConnectPost: wyslane cookie: "+setCookie);
  453.  
  454. DataOutputStream wr = new DataOutputStream (conn.getOutputStream ());
  455. wr.writeBytes(query);
  456. wr.flush ();
  457. wr.close ();
  458.  
  459. responseCode = conn.getResponseCode();
  460. if (D) Log.d(TAG,"httpConnectPost: responseCode="+responseCode+" "+conn.getResponseMessage());
  461. if (responseCode==-1) { conn.connect(); }
  462.  
  463. //get cookies
  464. if (conn!=null) {
  465. List<String> cookiesPom = conn.getHeaderFields().get("set-cookie");
  466. if (cookiesPom==null) cookiesPom = conn.getHeaderFields().get("Set-cookie");
  467. if (cookiesPom!=null)
  468. for (int i=0;i<cookiesPom.size();i++) {
  469. String[] cc=cookiesPom.get(i).split(";");
  470. int idxpom = cc[0].indexOf("=");
  471. String cc0 = cc[0].substring(0,idxpom);
  472. String cc1 = cc[0].substring(idxpom+1,cc[0].length())+";";
  473. cookies.put(cc0, cc1);
  474. }
  475. }
  476. //Get Response
  477. InputStream is = conn.getInputStream();
  478. BufferedReader rd = new BufferedReader(new InputStreamReader(is));
  479. String line;
  480. StringBuffer response = new StringBuffer();
  481. while((line = rd.readLine()) != null) {
  482. response.append(line);
  483. response.append('\r');
  484. }
  485. rd.close();
  486. redirectUrl = conn.getURL();
  487. if (D) Log.d(TAG,"httpConnectPost: url redirect="+conn.getURL());
  488. result=response.toString();
  489. //-
  490. } catch (MalformedURLException e) {
  491. err = Errors.BAD_URL;
  492. Log.e(TAG,"httpConnectPost: BAD URL: "+e.getMessage());
  493. } catch (IOException e) {
  494. err = Errors.ERR_IO;
  495. Log.e(TAG,"httpConnectPost: IO Error: "+e.getMessage());
  496. e.printStackTrace();
  497. } catch (Exception e) {
  498. err=-Errors.ERR_UNKNOWN;
  499. e.printStackTrace();
  500. }
  501. finally {
  502. if (conn!=null) conn.disconnect();
  503. }
  504. if (D) Log.d(TAG,"httpConnectPost: resp: "+responseCode+" body length: "+result.length());
  505. if (result.length()<4) {
  506. if (responseCode == 200)
  507. result = result + "-----";
  508. else
  509. result = "";
  510. }
  511. if (responseCode>=400 && responseCode<600) {
  512. result = String.valueOf(responseCode);
  513. } else
  514. if (err<0) {
  515. result=((Integer) err).toString();
  516. }
  517. return result;
  518. }
  519.  
  520. // ############## TODO ONLY FOR TESTS ###########################################################*/
  521.  
  522. /** always verify the host - dont check for certificate */
  523. final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
  524. public boolean verify(String hostname, SSLSession session) {
  525. return true;
  526. }
  527. };
  528.  
  529. /** Trust every server - dont check for any certificate */
  530. @SuppressLint("TrulyRandom")
  531. private static void trustAllHosts() {
  532. // Create a trust manager that does not validate certificate chains
  533. TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
  534. public java.security.cert.X509Certificate[] getAcceptedIssuers() {
  535. return new java.security.cert.X509Certificate[] {};
  536. }
  537. public void checkClientTrusted(X509Certificate[] chain,
  538. String authType) throws CertificateException {
  539. }
  540. public void checkServerTrusted(X509Certificate[] chain,
  541. String authType) throws CertificateException {
  542. }
  543. } };
  544. // Install the all-trusting trust manager
  545. try {
  546. SSLContext sc = SSLContext.getInstance("TLS");
  547. sc.init(null, trustAllCerts, new java.security.SecureRandom());
  548. HttpsURLConnection
  549. .setDefaultSSLSocketFactory(sc.getSocketFactory());
  550. } catch (Exception e) {
  551. e.printStackTrace();
  552. }
  553. }
  554.  
  555. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement