All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.eg.agent.android.MobileAgentUpload Maven / Gradle / Ivy

The newest version!
package com.eg.agent.android;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import org.json.JSONException;
import org.json.JSONObject;

import com.eg.agent.android.analytics.Attributes;
import com.eg.agent.android.analytics.BaseController;
import com.eg.agent.android.harvest.DataReaper;
import com.eg.agent.android.instrumentation.activityinstrumentation.AppAgent;
import com.eg.agent.android.instrumentation.httphelper.TransactionData;
import com.eg.agent.android.logging.EGAgentLog;
import com.eg.agent.android.logging.EGAgentLogManager;
import com.eg.agent.android.metric.Names;
import com.eg.agent.android.stats.StatisticsEngine;
import com.eg.agent.android.trace.TracerMachine;
import com.eg.agent.android.util.ParameterConstants;
import com.eg.agent.android.util.Utils;
import com.eg.google.gson.Gson;

import android.opengl.EGLObjectHandle;
import android.os.StrictMode;

public class MobileAgentUpload {
	public static volatile boolean isLaunched;
	public static long start_time = System.currentTimeMillis();
	static Gson gson = new Gson();

	static EGAgentLog agentLog = EGAgentLogManager.getAgentLog();
	private static BaseAndroidAgent androidAgentimpl = BaseAndroidAgent.getInstance();
	private static EGAgentConfig agentConfiguration = androidAgentimpl.getAgentConfiguration();
	static String dev_info = null;
	static String app_info = null;
	static String res_info = null;

	static void clean() {
		dev_info = null;
		app_info = null;
		res_info = null;
	}

	public static void setAgent(BaseAndroidAgent agent) {
		if (agent != null) {
			androidAgentimpl = agent;
			agentConfiguration = agent.getAgentConfiguration();
		}
	}

	static BaseAndroidAgent getAgent() {
		if (androidAgentimpl == null) {
			androidAgentimpl = BaseAndroidAgent.getInstance();
		}
		androidAgentimpl.loadMemoryUsage();
		androidAgentimpl.loadBatteryStatus();
		androidAgentimpl.loadCPUUsage();
		app_info = androidAgentimpl.getApplicationInformation().asJsonObject().toString();
		dev_info = gson.toJson(androidAgentimpl.getDeviceInformation());
		res_info = androidAgentimpl.getResourceInforamtion().asJsonObject().toString();
		return androidAgentimpl;
	}

	public static String getDevInfo() {
		getAgent();
		if (dev_info == null) {
			dev_info = gson.toJson(androidAgentimpl.getDeviceInformation());
		}
		return dev_info;
	}

	public static String getAppinfo() {
		getAgent();
		if (app_info == null) {
			app_info = androidAgentimpl.getApplicationInformation().asJsonObject().toString();
		}
		return app_info;
	}

	public static String getResInfo() {
		getAgent();
		if (res_info == null) {
			res_info = androidAgentimpl.getResourceInforamtion().asJsonObject().toString();
		}
		return res_info;
	}
	
	public static String getUserInfo() {
		getAgent();
		long sessionDuration = DataReaper.getMillisSinceStart();
        if (sessionDuration == 0) {
        	agentLog.error("Session duration is invalid!");
            StatisticsEngine.get().inc(Names.SUPPORTABILITY_SESSION_INVALID_DURATION);
        }
        float sessionDurationAsSeconds = ((float) sessionDuration) / 1000.0f;
		BaseController.getInstance().setAttribute(Attributes.SESSION_DURATION_ATTRIBUTE, ParameterConstants.FORMATTER.format(sessionDurationAsSeconds)+" (in Secs)", false);
		Map data = androidAgentimpl.getUserdata();
		agentLog.debug("MobileAgentUpload::getUserInfo:::data:::"+data);
		JSONObject jsonObj = new JSONObject(data);
		Set attributes = BaseController.getInstance().getUserAttributes();
		try {
			
			for (Attributes attribute : attributes) {
				jsonObj.put(attribute.getName(), attribute.valueAsString());
			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return jsonObj.toString();
	}
	
	public static String getCustomInfo() {
//		getAgent();
//		agentLog.debug("MobileAgentUpload::getCustomInfo:::customData:::"+androidAgentimpl.getCustomData());
		return new JSONObject().toString();
	}

	public static JSONObject getJSONObjet(String type, AppAgent applicationStateMonitor) {
		JSONObject mainJson = new JSONObject();
		if (android.os.Build.VERSION.SDK_INT > 9) {
			Utils.addStrictMode();
		}
		try {
			getAgent();
			if (androidAgentimpl.getApplicationInformation() == null
					|| agentConfiguration.getApplicationToken().trim().length() == 0
					|| agentConfiguration.getApplicationToken() == null) {

			} else {

				mainJson.put(ParameterConstants.appName, androidAgentimpl.getApplicationInformation().getAppName());
				mainJson.put(ParameterConstants.instrumentationType, ParameterConstants.activity);
				mainJson.put(ParameterConstants.activityName, applicationStateMonitor.getActivityName());
				mainJson.put(ParameterConstants.deviceName, androidAgentimpl.getDeviceInformation().getDeviceName());
				mainJson.put(ParameterConstants.osName, androidAgentimpl.getDeviceInformation().getOsName());
				mainJson.put(ParameterConstants.osVersion, androidAgentimpl.getDeviceInformation().getOsVersion());
				mainJson.put(ParameterConstants.appToken, agentConfiguration.getApplicationToken());

				
				mainJson.put(ParameterConstants.executionTime, applicationStateMonitor.getExecutionTime());
				mainJson.put(ParameterConstants.activityStartTime, applicationStateMonitor.getActivityStartTime());
				mainJson.put(ParameterConstants.activityEndTime, applicationStateMonitor.getActivityEndTime());

				mainJson.put(ParameterConstants.activityStatus, applicationStateMonitor.getApplicationStatus());
				//mainJson.put(ParameterConstants.launcherActivity, applicationStateMonitor.getLauncherActivity());
				mainJson.put(ParameterConstants.launcherActivity, androidAgentimpl.getApplicationInformation().getLauncherActivity());
				mainJson.put(ParameterConstants.country, androidAgentimpl.getApplicationInformation().getCountry());
				mainJson.put(ParameterConstants.deviceInformation, getDevInfo());
				mainJson.put(ParameterConstants.applicationInformation, getAppinfo());
				mainJson.put(ParameterConstants.resourceInformatin, getResInfo());
				
//				mainJson.put(ParameterConstants.customInformation, getCustomInfo());
				mainJson.put(ParameterConstants.userInformation, getUserInfo());
				

			}
		} catch (Exception e) {
			agentLog.error(e.getMessage(), e);
		} finally {
			clean();
		}
		return mainJson;
	}

	/*
	 * Activity instrumentation Api call
	 */
	public static void SendToCollector(String type, AppAgent applicationStateMonitor) {

		JSONObject mainJson = getJSONObjet(type, applicationStateMonitor);
		if (agentConfiguration.getApplicationToken() == null || agentConfiguration.getApplicationToken().isEmpty()) {
			agentLog.info("Application Token is empty. eG Agent can't able to send data to server");
		} else if (agentConfiguration.getCollectorHost() == null || agentConfiguration.getCollectorHost().isEmpty()) {
			agentLog.info("Collector Host is empty. eG Agent can't able to send data to server");
		} else {
			agentLog.info("[Send Data : " + applicationStateMonitor.getActivityName() + "][Collector :"
					+ agentConfiguration.getCollectorHost() + ParameterConstants.mobileServlet + "] [Data]:"
					+ mainJson.toString());
			postDataToServer(mainJson);

		}

	}

	public static JSONObject getJSONObjet(TransactionData transactionState) {
		if (Queue.isExcluded(transactionState.getFullActivityClassName())) {
			return null;
		}
		JSONObject mainJson = new JSONObject();
		if (android.os.Build.VERSION.SDK_INT > 9) {
			Utils.addStrictMode();
		}
		try {
			getAgent();

			if (androidAgentimpl.getApplicationInformation() == null
					|| agentConfiguration.getApplicationToken().trim().length() == 0
					|| agentConfiguration.getApplicationToken() == null) {

			} else {

				transactionState.setExecutionTime(transactionState.getEndTime() - transactionState.getStartTime());
				String networkData = gson.toJson(transactionState.asJsonObject());
				boolean isPage = isPage(transactionState.getUrl());
				agentLog.debug("MobileAgentUpload:transactionState.getUrl():"+transactionState.getUrl()+"\t isPage::"+isPage);		
				mainJson.put(ParameterConstants.appName, androidAgentimpl.getApplicationInformation().getAppName());
//				agentLog.debug("MobileAgentUpload:getJSONObjet(transactionState):::mainJson0:::"+mainJson.toString());
				mainJson.put(ParameterConstants.instrumentationType, "HTTP");
//				agentLog.debug("MobileAgentUpload:getJSONObjet(transactionState):::mainJson1:::"+mainJson.toString());
				mainJson.put(ParameterConstants.activityName, transactionState.getActivityClasName());
				mainJson.put(ParameterConstants.deviceName, androidAgentimpl.getDeviceInformation().getDeviceName());
				mainJson.put(ParameterConstants.osName, androidAgentimpl.getDeviceInformation().getOsName());
				mainJson.put(ParameterConstants.osVersion, androidAgentimpl.getDeviceInformation().getOsVersion());
				mainJson.put(ParameterConstants.appToken, agentConfiguration.getApplicationToken());
//				agentLog.debug("MobileAgentUpload:getJSONObjet(transactionState):::mainJson2:::"+mainJson.toString());
				mainJson.put(ParameterConstants.deviceInformation, getDevInfo());
				mainJson.put(ParameterConstants.applicationInformation, getAppinfo());
				mainJson.put(ParameterConstants.resourceInformatin, getResInfo());
				if(isPage) {
					mainJson.put(ParameterConstants.instrumentationType, "Page");
					mainJson.put(ParameterConstants.pageInformation, networkData);
				} else {
					mainJson.put(ParameterConstants.instrumentationType, "HTTP");
					mainJson.put(ParameterConstants.httpInformation, networkData);
				}
				mainJson.put(ParameterConstants.executionTime, transactionState.getExecutionTime());
				mainJson.put(ParameterConstants.country, androidAgentimpl.getApplicationInformation().getCountry());
				
//				mainJson.put(ParameterConstants.customInformation, getCustomInfo());
				mainJson.put(ParameterConstants.userInformation, getUserInfo());
				
//				agentLog.debug("MobileAgentUpload:getJSONObjet(transactionState):::mainJson3:::"+mainJson.toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
			agentLog.error(e.getMessage(), e);
		} finally {
			clean();
		}
//		agentLog.debug("MobileAgentUpload:getJSONObjet(transactionState):::mainJson4:::"+mainJson.toString());
		return mainJson;
	}
	
	public static boolean isPage(String hostname) {
		
//		return hostname != null && hostname.indexOf(BaseAndroidAgent.getLocalIpAddress()) > -1;
		
		boolean isPage  =  hostname.startsWith("file://") || hostname.indexOf("localhost") > -1 
				|| hostname.indexOf("127.0.0.1") > -1 /* || hostname.indexOf("192.168.") > -1 */ ||
				hostname.indexOf("10.0.") > -1 || hostname.indexOf(".local") > -1;
		String[] pageArr = new String[]{"localhost", "127.0.0.1", "10.0.", "::1", BaseAndroidAgent.getLocalIpAddress()};
		agentLog.debug("MobileAgentUpload:URL1:"+hostname+"\t isPage::"+isPage);		
		List pages = Arrays.asList(pageArr);
		agentLog.debug("MobileAgentUpload:Pages1::"+pages);
		isPage = isPage || pages.contains(hostname);
		agentLog.debug("MobileAgentUpload:URL2:"+hostname+"\t isPage::"+isPage);		
		return isPage;
	}

	/*
	 * Http instrumentation Api call
	 */
	public static void sendData(TransactionData transactionState) {
		JSONObject mainJson = getJSONObjet(transactionState);

		if (agentConfiguration.getApplicationToken() == null || agentConfiguration.getApplicationToken().isEmpty()) {
			agentLog.info("Application Token is empty. eG Agent can't able to send data to server");
		} else if (agentConfiguration.getCollectorHost() == null || agentConfiguration.getCollectorHost().isEmpty()) {
			agentLog.info("Collector Host is empty. eG Agent can't able to send data to server");
		} else {
			agentLog.info("[Send Data : " + transactionState.getClass().getSimpleName() + "][Collector :"
					+ agentConfiguration.getCollectorHost() + ParameterConstants.mobileServlet + "] [Data]:"
					+ mainJson.toString());
			postDataToServer(mainJson);

		}

	}

	public static JSONObject getJSONObject(String string, String method, String category, long excution_time,
			String ApiType) throws IOException {
		JSONObject mainJson = new JSONObject();
		try {
			if (android.os.Build.VERSION.SDK_INT > 9) {
				Utils.addStrictMode();
			}
			androidAgentimpl = getAgent();
			agentLog.debug("MobileAgentUpload:getJSONObject:::androidAgentimpl::"+androidAgentimpl);
			agentLog.debug("MobileAgentUpload:getJSONObject:::androidAgentimpl.getApplicationInformation::"+androidAgentimpl.getApplicationInformation());
			agentLog.debug("MobileAgentUpload:getJSONObject:::agentConfiguration.getApplicationToken::"+agentConfiguration.getApplicationToken());
			if (androidAgentimpl.getApplicationInformation() == null
					|| agentConfiguration.getApplicationToken().trim().length() == 0
					|| agentConfiguration.getApplicationToken() == null) {

			} else {

				mainJson.put(ParameterConstants.appName, androidAgentimpl.getApplicationInformation().getAppName());
				mainJson.put(ParameterConstants.instrumentationType, ApiType);
				mainJson.put(ParameterConstants.activityName, string);
				mainJson.put(ParameterConstants.deviceName, androidAgentimpl.getDeviceInformation().getDeviceName());
				mainJson.put(ParameterConstants.osName, androidAgentimpl.getDeviceInformation().getOsName());
				mainJson.put(ParameterConstants.osVersion, androidAgentimpl.getDeviceInformation().getOsVersion());
				mainJson.put(ParameterConstants.appToken, agentConfiguration.getApplicationToken());

				if (ApiType.equalsIgnoreCase("SQliteDatabase")) {
					mainJson.put(ParameterConstants.querytable, category);
				}
				mainJson.put(ParameterConstants.deviceInformation, getDevInfo());
				agentLog.debug("MobileAgentUpload:getJSONObject:::ApiType::"+ApiType+", isLaunched::"+androidAgentimpl.getApplicationInformation().isLaunched() +", MobileAgentUpload.isLaunched="+MobileAgentUpload.isLaunched);
				androidAgentimpl.getApplicationInformation().setLaunched(ApiType.equalsIgnoreCase("Activity") && !androidAgentimpl.getApplicationInformation().isLaunched() && !MobileAgentUpload.isLaunched);
				if (androidAgentimpl.getApplicationInformation().isLaunched()) {
					MobileAgentUpload.isLaunched = true;
				}
				agentLog.debug("MobileAgentUpload:getJSONObject::activityName::"+string+":ApiType::"+ApiType+":getAppinfo1::"+getAppinfo());
				mainJson.put(ParameterConstants.applicationInformation, getAppinfo());
				agentLog.debug("MobileAgentUpload:getJSONObject:::activityName::"+string+":ApiType::"+ApiType+":mainJson.get("+ParameterConstants.applicationInformation+")::"+mainJson.getString(ParameterConstants.applicationInformation));
				mainJson.put(ParameterConstants.resourceInformatin, getResInfo());
				mainJson.put(ParameterConstants.executionMethodName, new String(method.getBytes(), "UTF-8"));
				mainJson.put(ParameterConstants.executionTime, excution_time);

				if (ApiType.equals("Fragment")) {
					mainJson.put(ParameterConstants.activityStartTime, TracerMachine.getEntryTime());
					mainJson.put(ParameterConstants.activityEndTime, TracerMachine.getExitTime());
					mainJson.put(ParameterConstants.activityStatus, TracerMachine.getStatus());
				}
				if (TracerMachine.getRootTrace() != null) {
					//mainJson.put(ParameterConstants.launcherActivity, TracerMachine.getRootTrace().displayName);
					mainJson.put(ParameterConstants.launcherActivity, androidAgentimpl.getApplicationInformation().getLauncherActivity());

				}
				mainJson.put(ParameterConstants.country, androidAgentimpl.getApplicationInformation().getCountry());
				
//				mainJson.put(ParameterConstants.customInformation, getCustomInfo());
				mainJson.put(ParameterConstants.userInformation, getUserInfo());
				
				agentLog.debug("MobileAgentUpload:getJSONObject:"+mainJson.toString());
				agentLog.debug("MobileAgentUpload:getJSONObject:::activityName::"+string+":ApiType:"+ApiType+":mainJson.get("+ParameterConstants.applicationInformation+"):end::"+mainJson.getString(ParameterConstants.applicationInformation));
			}
			
		} catch (Exception e) {
			agentLog.error(e.getMessage(), e);
		} finally {
			clean();
		}

		agentLog.debug("MobileAgentUpload:getJSONObject:::mainJson::" + mainJson);
		return mainJson;
	}

	/*
	 * Sqlite, Async,method trace, Bitmap instrumentation Api call
	 */
	public static void SendData(String string, String method, String category, long excution_time, String ApiType)
			throws IOException {

		JSONObject mainJson = getJSONObject(string, method, category, excution_time, ApiType);
		if (agentConfiguration.getApplicationToken() == null || agentConfiguration.getApplicationToken().isEmpty()) {
			agentLog.info("Application Token is empty. eG Agent can't able to send data to server");
		} else if (agentConfiguration.getCollectorHost() == null || agentConfiguration.getCollectorHost().isEmpty()) {
			agentLog.info("Collector Host is empty. eG Agent can't able to send data to server");
		} else {
			agentLog.info("[Send Data : " + string + "][Collector :" + agentConfiguration.getCollectorHost()
					+ ParameterConstants.mobileServlet + "] [Data]:" + mainJson.toString());
			postDataToServer(mainJson);
		}

	}

	public static boolean getInstrumentationStatus() throws Exception {
		String urlStr = agentConfiguration.getCollectorHost() + ParameterConstants.mobileServlet
				+ ParameterConstants.instrumentationStatusParam;
//		System.out.println("MobileAgentUpload:getInstrumentationStatus::url:::" + urlStr);
		int SDK_INT = android.os.Build.VERSION.SDK_INT;
	    if (SDK_INT > 8) 
	    {
	        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
	                .permitAll().build();
	        StrictMode.setThreadPolicy(policy);

			String response = "";
			URL url = new URL(urlStr);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestProperty("Accept-Encoding", "identity");
			connection.setRequestMethod("GET");
			int responseCode = connection.getResponseCode();
			if (responseCode == HttpURLConnection.HTTP_OK)
			{
				BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
				String input;
				while ((input = br.readLine()) != null) {
					response += input;
				}
				br.close();
			}
			else
			{
				agentLog.debug("MobileAgentUpload::getInstrumentationStatus request failed with response code: " + responseCode);
			}
			connection.disconnect();
			JSONObject instrmenationStatusJson = new JSONObject();
			boolean blInstrumentationStatus = false;
			if(response!=null && response.trim().length()>0)
			{
				instrmenationStatusJson = new JSONObject(response);
				if(instrmenationStatusJson.has("instrumentationStatus"))
				{
					String str_insStatus = instrmenationStatusJson.getString("instrumentationStatus");
					if(str_insStatus.equalsIgnoreCase("true"))
					{
						blInstrumentationStatus = true;
					}
					else
					{
						blInstrumentationStatus = false;
					}
				}
			}
			return blInstrumentationStatus;
	    }
		return false;
	}

	@SuppressWarnings("unchecked")
	public static void postDataToServer(final JSONObject mainJson) {
		try {

			class Post implements Runnable {
				JSONObject mainJson1 = null;

				Post(JSONObject mainJso) {
					mainJson1 = mainJso;
				}

				@Override
				public void run() {

					try {

						final URL obj = new URL(
								agentConfiguration.getCollectorHost() + ParameterConstants.mobileServlet);
						HttpURLConnection con = (HttpURLConnection) obj.openConnection();
						agentLog.debug("MobileAgentUpload::postdata::EGAgentConfig.getInstance().useSsl():: "
								+ EGAgentConfig.getInstance().useSsl());
						if (EGAgentConfig.getInstance().useSsl()) {
							agentLog.debug("MobileAgentUpload::postdata::EGAgentConfig.getInstance().isUnsigned():: "
									+ EGAgentConfig.getInstance().isUnsigned());
							if (EGAgentConfig.getInstance().useSsl() || EGAgentConfig.getInstance().isUnsigned()) {

								TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
									public java.security.cert.X509Certificate[] getAcceptedIssuers() {
										return new X509Certificate[0];
									}

									public void checkClientTrusted(java.security.cert.X509Certificate[] certs,
											String authType) {
									}

									public void checkServerTrusted(java.security.cert.X509Certificate[] certs,
											String authType) {
									}
								} };
								try {
									SSLContext sc = SSLContext.getInstance("TLS");
									sc.init(null, trustAllCerts, new java.security.SecureRandom());
									((HttpsURLConnection) con).setSSLSocketFactory(sc.getSocketFactory());
									((HttpsURLConnection) con).setHostnameVerifier(new HostnameVerifier() {
										@Override
										public boolean verify(String hostname, SSLSession session) {
											agentLog.debug("MobuileAgentupload:postData:HostnameVerifier::(" + hostname
													+ ".equals(" + obj.getHost() + ")::"
													+ obj.getHost().equals(hostname));

											HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
											agentLog.debug(
													"MobuileAgentupload:postData:HostnameVerifier::hv.verify(obj.getHost(), session);:: "
															+ hv.verify(obj.getHost(), session));
											return hostname.equals(obj.getHost());
										}
									});
								} catch (Exception e) {
									e.printStackTrace();
								}
							} else {
								SSLSocketFactory factory = HttpsURLConnection.getDefaultSSLSocketFactory();
								SSLSocket socket = (SSLSocket) factory.createSocket(obj.getHost(), obj.getPort());

								// Connect to the server
								socket.startHandshake();

								// Retrieve the server's certificate chain
								java.security.cert.Certificate[] serverCerts = socket.getSession()
										.getPeerCertificates();

								// Close the socket
								socket.close();

								String keyStoreType = KeyStore.getDefaultType();
								KeyStore keyStore = KeyStore.getInstance(keyStoreType);
								try {
									keyStore.load(null, null);
									keyStore.setKeyEntry(null, null, serverCerts);
								} catch (Exception e) {
									agentLog.error(e.getMessage(), e);
								}
								TrustManagerFactory tmf = TrustManagerFactory
										.getInstance(TrustManagerFactory.getDefaultAlgorithm());
								// Initialise the TMF as you normally would, for example:
								tmf.init(keyStore);

								TrustManager[] trustManagers = tmf.getTrustManagers();
								final X509TrustManager origTrustmanager = (X509TrustManager) trustManagers[0];

								TrustManager[] wrappedTrustManagers = new TrustManager[] { new X509TrustManager() {

									@Override
									public X509Certificate[] getAcceptedIssuers() {
										return origTrustmanager.getAcceptedIssuers();
									}

									@Override
									public void checkServerTrusted(X509Certificate[] certs, String authType)
											throws CertificateException {
										try {
											origTrustmanager.checkServerTrusted(certs, authType);
										} catch (CertificateExpiredException e) {
										}
									}

									@Override
									public void checkClientTrusted(X509Certificate[] certs, String authType)
											throws CertificateException {
										origTrustmanager.checkClientTrusted(certs, authType);
									}
								} };
								SSLContext sc = SSLContext.getInstance("TLS");
								sc.init(null, wrappedTrustManagers, null);

								SSLSocketFactory socketFactory = (SSLSocketFactory) sc.getSocketFactory();
								((HttpsURLConnection) con).setSSLSocketFactory(socketFactory);
							}
						}

						con.setRequestMethod("POST");
						con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
						con.setDoOutput(false);
						agentLog.debug("MobuileAgentupload:postData:json;:: " + mainJson1);

						DataOutputStream wr = new DataOutputStream(con.getOutputStream());

//						GZIPOutputStream gzip = new GZIPOutputStream(con.getOutputStream());
//					    gzip.write(mainJson1.toString().getBytes(StandardCharsets.UTF_8));
//					    gzip.flush();
//					    gzip.close();

						wr.write(mainJson1.toString().getBytes(StandardCharsets.UTF_8));
						wr.flush();
						wr.close();
						BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
						String inputLine;
						StringBuffer response = new StringBuffer();

						while ((inputLine = in.readLine()) != null) {
							response.append(inputLine);
						}
						agentLog.debug("Response " + response);
						in.close();

						//
						Queue.synchronousDequeue();
						//
					} catch (Exception e) {
						agentLog.error(e.getMessage(), e);

					} finally {
					}

				}

			}
			if (mainJson == null || !eGAndroidAgent.isStarted()) {
				return;
			}
			Thread t = new Thread(new Post(mainJson));
			t.start();
			t.join(0);
		} catch (Exception e) {
			e.printStackTrace();
			agentLog.error(e.getMessage());
		} finally {
			clean();

		}
	}

	public static JSONObject getJSONObjet(JSONObject mainJson) {
		try {
			getAgent();

			mainJson.put(ParameterConstants.appName, androidAgentimpl.getApplicationInformation().getAppName());
			mainJson.put(ParameterConstants.deviceName, androidAgentimpl.getDeviceInformation().getDeviceName());
			mainJson.put(ParameterConstants.osName, androidAgentimpl.getDeviceInformation().getOsName());
			mainJson.put(ParameterConstants.osVersion, androidAgentimpl.getDeviceInformation().getOsVersion());
			mainJson.put(ParameterConstants.appToken, agentConfiguration.getApplicationToken());

			mainJson.put(ParameterConstants.deviceInformation, getDevInfo());
			mainJson.put(ParameterConstants.applicationInformation, getAppinfo());
			mainJson.put(ParameterConstants.resourceInformatin, getResInfo());

//			mainJson.put(ParameterConstants.customInformation, getCustomInfo());
			mainJson.put(ParameterConstants.userInformation, getUserInfo());
			
			mainJson.put(ParameterConstants.country, androidAgentimpl.getApplicationInformation().getCountry());

		} catch (Exception e) {
			agentLog.error(e.getMessage());
		} finally {
			clean();
		}
		return mainJson;
	}

	public static void sendData(JSONObject mainJson) {
		try {
			getAgent();

			mainJson = getJSONObjet(mainJson);

			if (agentConfiguration.getApplicationToken() == null
					|| agentConfiguration.getApplicationToken().isEmpty()) {
				agentLog.info("Application Token is empty. eG Agent can't able to send data to server");
			} else if (agentConfiguration.getCollectorHost() == null
					|| agentConfiguration.getCollectorHost().isEmpty()) {
				agentLog.info("Collector Host is empty. eG Agent can't able to send data to server");
			} else {
				agentLog.info("[Send Data : " + mainJson.getString(ParameterConstants.activityName) + "][Collector :"
						+ agentConfiguration.getCollectorHost() + ParameterConstants.mobileServlet + "] [Data]:"
						+ mainJson.toString());
				postDataToServer(mainJson);

			}
		} catch (Exception e) {
			agentLog.error(e.getMessage());
		} finally {
			clean();
		}
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy