Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.naviexpert.telematics.b2b.api;
- import android.annotation.SuppressLint;
- import android.os.AsyncTask;
- import android.util.Log;
- import com.naviexpert.telematics.BuildConfig;
- import com.naviexpert.telematics.b2b.Const;
- import org.json.JSONArray;
- import org.json.JSONException;
- import org.json.JSONObject;
- import java.io.BufferedReader;
- import java.io.DataOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.net.HttpURLConnection;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.security.cert.CertificateException;
- import java.security.cert.X509Certificate;
- import java.util.Enumeration;
- import java.util.Hashtable;
- import java.util.List;
- import java.util.Locale;
- import javax.net.ssl.HostnameVerifier;
- import javax.net.ssl.HttpsURLConnection;
- import javax.net.ssl.SSLContext;
- import javax.net.ssl.SSLSession;
- import javax.net.ssl.TrustManager;
- import javax.net.ssl.X509TrustManager;
- /**
- * Created by Krzysztof Wachnik on 2017-05-15.
- *
- */
- public class TelematicsApi {
- /** more logs */
- private static final boolean D = true;
- /** tag for logs */
- private static final String TAG = TelematicsApi.class.getSimpleName();
- public static final int SPEED_LIMIT_NO_VALUE = -1;
- public static final int SPEED_LIMIT_UNKNOWN_ANGLE = -2;
- //fields in response
- //speed limits
- private static final String GEOMETRY = "geometry";
- private static final String PROPERTIES = "properties";
- private static final String CATEGORY = "category";
- private static final String DIRECTION = "direction";
- private static final String SPEED_LIMIT_ALONG = "speedLimitAlong";
- private static final String SPEED_LIMIT_AGAINST = "speedLimitAgainst";
- private static final String COORDINATES = "coordinates";
- private static final String FEATURES = "features";
- //config
- private static final String ACCELERATION = "acceleration";
- private static final String DECELERATION = "braking";
- private static final String THRESHOLD_MIN = "minThreshold";
- private static final String THRESHOLD_MED = "mediumThreshold";
- private static final String THRESHOLD_MAX = "strongThreshold";
- //access token
- private static final String ACCESS_TOKEN = "accessToken";
- //response ids
- public static final int REQ_TYPE_ROADS = 1;
- public static final int REQ_TYPE_CONF = 2;
- public static final int REQ_TYPE_TOKEN = 3;
- public static final int REQ_TYPE_IS_ACTIVE = 4;
- //endpoints
- private static final String API_REGISTER = "register";
- private static final String API_ROADS = "roads";
- private static final String API_CONFIG = "config";
- private static final String API_IS_ACTIVE = "is_active";
- /** to handle response */
- private RequestListener listener;
- /** task with send request to api */
- private ConnectTask sendTask;
- /** TODO to use in future */
- private int reqId = 1;
- /** for future use - handle cookies before requests */
- private static Hashtable<String, String> cookies = new Hashtable<>();
- /** instance */
- private static TelematicsApi api;
- private String accessToken = "";
- /** to use in future in errors handling */
- public class Errors {
- public static final int BAD_URL = -10;
- public static final int ERR_IO = -11;
- public static final int ERR_UNKNOWN = -12;
- public static final int ERR_HTTP_UNAUTH = 401;
- public static final int ERR_NOT_FOUND = 404;
- public static final int ERR_500 = 500;
- public static final int ERR_501 = 501;
- }
- public static TelematicsApi getInstance() {
- if (api==null) {
- if (D) Log.d(TAG,"getInstance: new instance");
- api = new TelematicsApi();
- }
- return api;
- }
- public void setAccessToken(String accessToken) {
- this.accessToken = accessToken;
- }
- public interface RequestListener {
- public void onSuccess(int id, String response);
- public void onError(int id, String message);
- }
- /** @return the listener */
- public RequestListener getListener() {
- return listener;
- }
- /**
- * Returns unformatted response from api.
- *
- * @param listener the listener to set */
- public void setListener(RequestListener listener) {
- this.listener = listener;
- }
- /**
- * Ask for a section of the road map specified by the coordinates in the parameters
- * @param minLon 1st coordinate longtitude
- * @param maxLon 2 coordinate longtitude
- * @param minLat 1st coordinate latitude
- * @param maxLat 2 coordinate latitude
- */
- public int getRoads(double minLon, double maxLon, double minLat, double maxLat) {
- Log.d(TAG, "getRoads: ");
- String query=API_ROADS+"?"+"minLon="+minLon+"&maxLon="+maxLon+"&minLat="+minLat+"&maxLat="+maxLat;
- // TODO to future use reqId++;
- reqId = REQ_TYPE_ROADS;
- sendTask = new ConnectTask();
- sendTask.execute(query,""+reqId);
- return reqId;
- }
- /**
- * get thresholds configuration
- * @return request type
- */
- public int getConfig() {
- Log.d(TAG, "getConfig: ");
- String query=API_CONFIG;
- // TODO to future use reqId++;
- reqId = REQ_TYPE_CONF;
- sendTask = new ConnectTask();
- sendTask.execute(query,""+reqId);
- return reqId;
- }
- /**
- * get authorization token
- * @param deviceCode device number
- * @param phoneNumber phone number
- * @return request type
- */
- public int getToken(String deviceCode, String phoneNumber) {
- Log.d(TAG, "getToken: deviceCode="+deviceCode);
- JSONObject jo = new JSONObject();
- try {
- jo.put("deviceCode",deviceCode);
- jo.put("phoneNumber",phoneNumber);
- } catch (JSONException e) {
- e.printStackTrace();
- }
- String query = jo.toString();
- Log.d(TAG, "getToken: query="+query);
- reqId = REQ_TYPE_TOKEN;
- sendTask = new ConnectTask();
- sendTask.execute(API_REGISTER,""+reqId,query);
- return reqId;
- }
- public int sendActive() {
- Log.d(TAG, "sendActive: ");
- String query=API_IS_ACTIVE;
- // TODO to future use reqId++;
- reqId = REQ_TYPE_IS_ACTIVE;
- sendTask = new ConnectTask();
- sendTask.execute(query,""+reqId);
- return reqId;
- }
- /**
- * Parsing the response from api.
- * TODO note to the backend - in response should be the coordinates of the returned area.
- * This would easiely allow you to detect any problems with the map (gps or network problem etc.)
- */
- public Roads parseRoads(String response) {
- Roads roads = new Roads();
- try {
- JSONArray ja = new JSONObject(response).getJSONArray(FEATURES);
- for (int i=0;i<ja.length();i++) {
- Road road = new Road();
- JSONObject jo = ja.getJSONObject(i);
- JSONObject geometry = jo.getJSONObject(GEOMETRY);
- JSONObject prop = jo.getJSONObject(PROPERTIES);
- if (prop.has(CATEGORY)) road.category = prop.getString(CATEGORY);
- if (prop.has(DIRECTION)) road.direction = prop.getInt(DIRECTION);
- try {
- if (prop.has(SPEED_LIMIT_ALONG)) road.speedLimitAlong = prop.getInt(SPEED_LIMIT_ALONG);
- } catch (Exception e) {
- //e.printStackTrace();
- road.speedLimitAlong = SPEED_LIMIT_NO_VALUE;
- }
- try {
- if (prop.has(SPEED_LIMIT_AGAINST)) road.speedLimitAgainst = prop.getInt(SPEED_LIMIT_AGAINST);
- } catch (Exception e) {
- //e.printStackTrace();
- road.speedLimitAgainst = SPEED_LIMIT_NO_VALUE;
- }
- JSONArray cord = geometry.getJSONArray(COORDINATES);
- for (int j=0;j<cord.length();j++) {
- double lon = cord.getJSONArray(j).getDouble(0);
- double lat = cord.getJSONArray(j).getDouble(1);
- road.coordinates.add(new Place(lon,lat));
- }
- roads.add(road);
- }
- } catch (JSONException e) {
- Log.e(TAG, "parseRoads: "+e.getMessage());
- e.printStackTrace();
- }
- return roads;
- }
- /**
- * parse config responce
- */
- public AppConfig parseConfig(String response) {
- AppConfig conf = new AppConfig();
- try {
- JSONObject jo = new JSONObject(response);
- conf.accDetect = (float)jo.getJSONObject(ACCELERATION).getDouble(THRESHOLD_MIN);
- conf.accFirst = (float)jo.getJSONObject(ACCELERATION).getDouble(THRESHOLD_MED);
- conf.accStrong = (float)jo.getJSONObject(ACCELERATION).getDouble(THRESHOLD_MAX);
- conf.decDetect = (float)jo.getJSONObject(DECELERATION).getDouble(THRESHOLD_MIN);
- conf.decFirst = (float)jo.getJSONObject(DECELERATION).getDouble(THRESHOLD_MED);
- conf.decStrong = (float)jo.getJSONObject(DECELERATION).getDouble(THRESHOLD_MAX);
- }catch (JSONException e) {
- Log.e(TAG, "parseConfig: "+e.getMessage());
- e.printStackTrace();
- }
- return conf;
- }
- public String parseToken(String response) {
- String token = "";
- try {
- JSONObject jo = new JSONObject(response);
- if (jo.has(ACCESS_TOKEN)) token = jo.getString(ACCESS_TOKEN);
- } catch (JSONException e) {
- Log.e(TAG, "parseToken: "+e.getMessage() );
- e.printStackTrace();
- }
- return token;
- }
- //---------------------------- private ------------------------------------------
- private class ConnectTask extends AsyncTask<String, String, String> {
- private int requestId = 0;
- @Override
- protected String doInBackground(String... params) {
- String content = "";
- String query = params[0];
- requestId = Integer.parseInt(params[1]);
- if (params.length>2) content = params[2];
- Log.d(TAG, "doInBackground: content="+content+" length="+content.length());
- if (content!=null && content.length()>0) {
- return httpConnectPost(BuildConfig.SERVER_API+query,content);
- } else {
- return httpConnect(BuildConfig.SERVER_API+query);
- }
- }
- @Override
- protected void onPostExecute(String result) {
- super.onPostExecute(result);
- if (result != null && result.length()>4) {
- Log.d(TAG,"onPostExecute: result="+result+" length="+result.length());
- if (listener!=null) listener.onSuccess(requestId, result);
- } else {
- if (listener!=null) listener.onError(requestId, result);
- }
- }
- }
- private String httpConnect(String adress) {
- System.setProperty("java.net.ssl","false"); //@see trustAllHosts //TODO remove it in stable version
- URL url;
- int err = 0;
- HttpURLConnection conn = null;
- int responseCode = 0;
- String result="0";
- URL redirectUrl = null; //to use in future in 302
- try {
- url=new URL(adress);
- //----------------------------
- if (url.getProtocol().toLowerCase(Locale.getDefault()).equals("https")) {
- trustAllHosts();
- HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
- https.setHostnameVerifier(DO_NOT_VERIFY);
- conn = https;
- } else {
- conn = (HttpURLConnection) url.openConnection();
- }
- //-------------
- conn.setRequestMethod("GET");
- conn.setDoInput(true);
- conn.setRequestProperty("User-Agent", Const.USER_AGENT);
- if (accessToken!=null && accessToken.length()>0)
- conn.setRequestProperty ("Authorization", accessToken);
- conn.setUseCaches(false);
- conn.setFollowRedirects(true);
- conn.setInstanceFollowRedirects(true);
- //need test:
- //conn.setConnectTimeout(15000);
- //conn.setReadTimeout(30000);
- if (D) Log.d(TAG,"httpConnectGet() "+" url="+conn.getURL());
- //sending cookie
- String setCookie = "";
- for (Enumeration<String> e = cookies.keys(); e.hasMoreElements();) {
- String key = e.nextElement();
- String value = cookies.get(key);
- setCookie += key+"="+value+" ";
- }
- if (setCookie.length()>0) conn.setRequestProperty("cookie", setCookie);
- conn.connect();
- if (conn!=null) responseCode = conn.getResponseCode();
- if (D) Log.d(TAG,"httpConnectGet: responce Code="+responseCode+" "+conn.getResponseMessage());
- if (responseCode==-1) { conn.connect(); }
- if (conn!=null) redirectUrl = conn.getURL();
- //geting cookie
- if (conn!=null) {
- List<String> cookiesPom = conn.getHeaderFields().get("set-cookie");
- if (cookiesPom==null) cookiesPom = conn.getHeaderFields().get("Set-cookie");
- if (cookiesPom!=null)
- for (int i=0;i<cookiesPom.size();i++) {
- String[] cc=cookiesPom.get(i).split(";");
- int idxpom = cc[0].indexOf("=");
- String cc0 = cc[0].substring(0,idxpom);
- String cc1 = cc[0].substring(idxpom+1,cc[0].length())+";";
- cookies.put(cc0, cc1);
- }
- }
- //Get Response
- InputStream is = conn.getInputStream();
- BufferedReader rd = new BufferedReader(new InputStreamReader(is));
- String line;
- StringBuffer response = new StringBuffer();
- while((line = rd.readLine()) != null) {
- response.append(line);
- response.append('\r');
- }
- rd.close();
- if (D) Log.d(TAG,"httpConnectGet: url="+conn.getURL());
- result=response.toString();
- //-
- } catch (MalformedURLException e) {
- err = Errors.BAD_URL;
- Log.e(TAG,"httpConnectGet: BAD URL: "+e.getMessage());
- } catch (IOException e) {
- err = Errors.ERR_IO;
- Log.e(TAG,"httpConnectGet: IO Error: "+e.getMessage());
- e.printStackTrace();
- } catch (Exception e) {
- err=-Errors.ERR_UNKNOWN;
- e.printStackTrace();
- Log.e(TAG,"httpConnectGet: Unknown Error: "+e.getMessage());
- }
- finally {
- if (conn!=null) conn.disconnect();
- }
- if (D) Log.d(TAG,"httpConnectGet: resp: "+responseCode+" body length: "+result.length());
- if (result.length()<4) {
- if (responseCode == 200)
- result = result + "-----";
- else
- result = "";
- }
- if (responseCode>=400 && responseCode<500) {
- result = String.valueOf(responseCode);
- } else
- if (err<0) {
- result=((Integer) err).toString();
- }
- return result;
- }
- private String httpConnectPost(String adress, String query) {
- System.setProperty("java.net.ssl","false"); //needed //@see trustAllHosts //TODO remove it in stable version
- URL url = null;
- int err = 0;
- HttpURLConnection conn = null;
- int responseCode = 0;
- String result="0";
- URL redirectUrl = null; //to use in future in 302
- try {
- url=new URL(adress);
- //----------------------------
- if (url.getProtocol().toLowerCase(Locale.getDefault()).equals("https")) {
- trustAllHosts();
- HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
- https.setHostnameVerifier(DO_NOT_VERIFY);
- conn = https;
- } else {
- conn = (HttpURLConnection) url.openConnection();
- }
- //-------------
- conn.setDoOutput(true);
- conn.setRequestMethod("POST");
- conn.setDoInput(true);
- conn.setRequestProperty("User-Agent",Const.USER_AGENT);
- //conn.setRequestProperty("Content-Type", "multipart/form-data");
- //conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
- conn.setRequestProperty("Content-Type", "application/json");
- conn.setRequestProperty("Content-Length", Integer.toString(query.length()));
- //conn.setUseCaches(false); //may be needed
- //conn.setConnectTimeout(15000);
- //conn.setReadTimeout(30000);
- if (D) Log.d(TAG,"httpConnectPost: query.lenght="+query.length()+" query="+query+" url="+conn.getURL());
- //sending cookies
- String setCookie = "";
- for (Enumeration<String> e = cookies.keys(); e.hasMoreElements();) {
- String key= (String) e.nextElement();
- String value = (String) cookies.get(key);
- setCookie += key+"="+value+" ";
- }
- if (setCookie.length()>0) conn.setRequestProperty("cookie", setCookie);
- if (D) Log.d(TAG,"httpConnectPost: wyslane cookie: "+setCookie);
- DataOutputStream wr = new DataOutputStream (conn.getOutputStream ());
- wr.writeBytes(query);
- wr.flush ();
- wr.close ();
- responseCode = conn.getResponseCode();
- if (D) Log.d(TAG,"httpConnectPost: responseCode="+responseCode+" "+conn.getResponseMessage());
- if (responseCode==-1) { conn.connect(); }
- //get cookies
- if (conn!=null) {
- List<String> cookiesPom = conn.getHeaderFields().get("set-cookie");
- if (cookiesPom==null) cookiesPom = conn.getHeaderFields().get("Set-cookie");
- if (cookiesPom!=null)
- for (int i=0;i<cookiesPom.size();i++) {
- String[] cc=cookiesPom.get(i).split(";");
- int idxpom = cc[0].indexOf("=");
- String cc0 = cc[0].substring(0,idxpom);
- String cc1 = cc[0].substring(idxpom+1,cc[0].length())+";";
- cookies.put(cc0, cc1);
- }
- }
- //Get Response
- InputStream is = conn.getInputStream();
- BufferedReader rd = new BufferedReader(new InputStreamReader(is));
- String line;
- StringBuffer response = new StringBuffer();
- while((line = rd.readLine()) != null) {
- response.append(line);
- response.append('\r');
- }
- rd.close();
- redirectUrl = conn.getURL();
- if (D) Log.d(TAG,"httpConnectPost: url redirect="+conn.getURL());
- result=response.toString();
- //-
- } catch (MalformedURLException e) {
- err = Errors.BAD_URL;
- Log.e(TAG,"httpConnectPost: BAD URL: "+e.getMessage());
- } catch (IOException e) {
- err = Errors.ERR_IO;
- Log.e(TAG,"httpConnectPost: IO Error: "+e.getMessage());
- e.printStackTrace();
- } catch (Exception e) {
- err=-Errors.ERR_UNKNOWN;
- e.printStackTrace();
- }
- finally {
- if (conn!=null) conn.disconnect();
- }
- if (D) Log.d(TAG,"httpConnectPost: resp: "+responseCode+" body length: "+result.length());
- if (result.length()<4) {
- if (responseCode == 200)
- result = result + "-----";
- else
- result = "";
- }
- if (responseCode>=400 && responseCode<600) {
- result = String.valueOf(responseCode);
- } else
- if (err<0) {
- result=((Integer) err).toString();
- }
- return result;
- }
- // ############## TODO ONLY FOR TESTS ###########################################################*/
- /** always verify the host - dont check for certificate */
- final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
- public boolean verify(String hostname, SSLSession session) {
- return true;
- }
- };
- /** Trust every server - dont check for any certificate */
- @SuppressLint("TrulyRandom")
- private static void trustAllHosts() {
- // Create a trust manager that does not validate certificate chains
- TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
- public java.security.cert.X509Certificate[] getAcceptedIssuers() {
- return new java.security.cert.X509Certificate[] {};
- }
- public void checkClientTrusted(X509Certificate[] chain,
- String authType) throws CertificateException {
- }
- public void checkServerTrusted(X509Certificate[] chain,
- String authType) throws CertificateException {
- }
- } };
- // Install the all-trusting trust manager
- try {
- SSLContext sc = SSLContext.getInstance("TLS");
- sc.init(null, trustAllCerts, new java.security.SecureRandom());
- HttpsURLConnection
- .setDefaultSSLSocketFactory(sc.getSocketFactory());
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement