<commit_before>package com.smartdevicelink.transport;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.Parcelable;
import android.os.RemoteException;
import android.util.Log;


public class TransportBroker {
	
	private static final String TAG = "SdlTransportBroker";

	private final String WHERE_TO_REPLY_PREFIX	 = "com.sdl.android.";
	private static String appId = null,whereToReply = null;
	private Context currentContext = null;
	
	private Object INIT_LOCK = new Object();
	
	private TransportType queuedOnTransportConnect = null;
	
	Messenger routerService = null;
	final Messenger clientMessenger = new Messenger(new ClientHandler());

	boolean isBound = false, registeredWithRouterService = false;
	private String routerPackage = null, routerClassName = null;
	
	
	
	private ServiceConnection routerConnection;
	
	private void initRouterConnection(){
		routerConnection= new ServiceConnection() {

			public void onServiceConnected(ComponentName className, IBinder service) {
				Log.d(TAG, "Bound to service " + className.toString());

				routerService = new Messenger(service);
				isBound = true;
				//So we just established our connection
				//Register with router service
				sendRegistrationMessage();    
			}

			public void onServiceDisconnected(ComponentName className) {
				Log.d(TAG, "UN-Bound to service");
				routerService = null;
				registeredWithRouterService = false;
				isBound = false;
				onHardwareDisconnected(null);
			}
		};
	}

    private void sendMessageToRouterService(Message message){
    	Log.i(TAG, "Attempting to send message type - " + message.what);
    	if(isBound){
    		if(registeredWithRouterService 
    				|| message.what == TransportConstants.ROUTER_REGISTER_CLIENT){ //We can send a message if we are registered or are attempting to register
    			try {
					routerService.send(message);
				} catch (RemoteException e) {
					e.printStackTrace();
				}
    		}else{
    			Log.e(TAG, "Unable to send message to router service. Not registered.");
    		}
    	}else{
    		Log.e(TAG, "Unable to send message to router service. Not bound.");
    	}
    }
    
    BroadcastReceiver routerDiscoveryReceiver = new BroadcastReceiver(){

		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent!=null){
				if(intent.hasExtra(TransportConstants.BIND_LOCATION_PACKAGE_NAME_EXTRA)
						&& intent.hasExtra(TransportConstants.BIND_LOCATION_CLASS_NAME_EXTRA)){
					//We now know the location of the router service that is currently up and running
					routerPackage = intent.getStringExtra(TransportConstants.BIND_LOCATION_PACKAGE_NAME_EXTRA);
					routerClassName = intent.getStringExtra(TransportConstants.BIND_LOCATION_CLASS_NAME_EXTRA);
					sendBindingIntent(); //TODO check if we actually binded
				}	
			}			
		}
    	
    };
    
    /**
     * Handler of incoming messages from service.
     */
    class ClientHandler extends Handler {
        ClassLoader loader = getClass().getClassLoader();
    	@Override
        public void handleMessage(Message msg) {
        	
        	Bundle bundle = msg.getData();
        	if(bundle!=null){
        		bundle.setClassLoader(loader);
        	}
        	
        	Log.d(TAG, "Bundle: "  + bundle.toString());
            /* DO NOT MOVE
             * This needs to be first to make sure we already know if we are attempting to enter legacy mode or not
             */
        	if(bundle !=null 
        			&& bundle.containsKey(TransportConstants.ENABLE_LEGACY_MODE_EXTRA)){
				boolean enableLegacy = bundle.getBoolean(TransportConstants.ENABLE_LEGACY_MODE_EXTRA, false);
				Log.d(TAG, "Setting legacy mode: " +enableLegacy );
				enableLegacyMode(enableLegacy);
			}
            
        	//Find out what message we have and what to do with it
            switch (msg.what) {//FIXME
            	case TransportConstants.ROUTER_REGISTER_CLIENT_RESPONSE:
            		if(msg.arg1==TransportConstants.REGISTRATION_RESPONSE_SUCESS){
            			//TODO yay! we have been registered. Now what?
            			registeredWithRouterService = true;
            			if(bundle!=null && bundle.containsKey(TransportConstants.CONNECTED_DEVICE_STRING_EXTRA_NAME)){
        					//Keep track if we actually get this
        				}
            			if(queuedOnTransportConnect!=null){
        					onHardwareConnected(queuedOnTransportConnect);
        					queuedOnTransportConnect = null;
        				}	
            		}else{ //We were denied registration to the router service, let's see why
            			registeredWithRouterService = false; 
            			Log.w(TAG, "Registration denied from router service. Reason - " + msg.arg1);
            		}
            	
            		break;
            	case TransportConstants.ROUTER_UNREGISTER_CLIENT_RESPONSE:
            		if(msg.arg1==TransportConstants.UNREGISTRATION_RESPONSE_SUCESS){
            			//TODO We've been unregistered. Now what?
            			
            			
            		}else{ //We were denied our unregister request to the router service, let's see why
            			Log.w(TAG, "Unregister request denied from router service. Reason - " + msg.arg1);
            			//Do we care?
            		}
            	
            		break;
            	case TransportConstants.ROUTER_RECEIVED_PACKET:
					//So the intent has a packet with it. PEFRECT! Let's send it through the library
            		if(bundle.containsKey(TransportConstants.FORMED_PACKET_EXTRA_NAME)){
            			Parcelable packet = bundle.getParcelable(TransportConstants.FORMED_PACKET_EXTRA_NAME);<commit_msg>Fixed issue to give ability for new apps installed while router service is already connected to appear on head unit<commit_after>package com.smartdevicelink.transport;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.Parcelable;
import android.os.RemoteException;
import android.util.Log;


public class TransportBroker {
	
	private static final String TAG = "SdlTransportBroker";

	private final String WHERE_TO_REPLY_PREFIX	 = "com.sdl.android.";
	private static String appId = null,whereToReply = null;
	private Context currentContext = null;
	
	private Object INIT_LOCK = new Object();
	
	private TransportType queuedOnTransportConnect = null;
	
	Messenger routerService = null;
	final Messenger clientMessenger = new Messenger(new ClientHandler());

	boolean isBound = false, registeredWithRouterService = false;
	private String routerPackage = null, routerClassName = null;
	
	
	
	private ServiceConnection routerConnection;
	
	private void initRouterConnection(){
		routerConnection= new ServiceConnection() {

			public void onServiceConnected(ComponentName className, IBinder service) {
				Log.d(TAG, "Bound to service " + className.toString());

				routerService = new Messenger(service);
				isBound = true;
				//So we just established our connection
				//Register with router service
				sendRegistrationMessage();    
			}

			public void onServiceDisconnected(ComponentName className) {
				Log.d(TAG, "UN-Bound to service");
				routerService = null;
				registeredWithRouterService = false;
				isBound = false;
				onHardwareDisconnected(null);
			}
		};
	}

    private void sendMessageToRouterService(Message message){
    	Log.i(TAG, "Attempting to send message type - " + message.what);
    	if(isBound){
    		if(registeredWithRouterService 
    				|| message.what == TransportConstants.ROUTER_REGISTER_CLIENT){ //We can send a message if we are registered or are attempting to register
    			try {
					routerService.send(message);
				} catch (RemoteException e) {
					e.printStackTrace();
				}
    		}else{
    			Log.e(TAG, "Unable to send message to router service. Not registered.");
    		}
    	}else{
    		Log.e(TAG, "Unable to send message to router service. Not bound.");
    	}
    }
    
    BroadcastReceiver routerDiscoveryReceiver = new BroadcastReceiver(){

		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent!=null){
				if(intent.hasExtra(TransportConstants.BIND_LOCATION_PACKAGE_NAME_EXTRA)
						&& intent.hasExtra(TransportConstants.BIND_LOCATION_CLASS_NAME_EXTRA)){
					//We now know the location of the router service that is currently up and running
					routerPackage = intent.getStringExtra(TransportConstants.BIND_LOCATION_PACKAGE_NAME_EXTRA);
					routerClassName = intent.getStringExtra(TransportConstants.BIND_LOCATION_CLASS_NAME_EXTRA);
					sendBindingIntent(); //TODO check if we actually binded
				}	
			}			
		}
    	
    };
    
    /**
     * Handler of incoming messages from service.
     */
    class ClientHandler extends Handler {
        ClassLoader loader = getClass().getClassLoader();
    	@Override
        public void handleMessage(Message msg) {
        	
        	Bundle bundle = msg.getData();
        	if(bundle!=null){
        		bundle.setClassLoader(loader);
        	}
        	
        	Log.d(TAG, "Bundle: "  + bundle.toString());
            /* DO NOT MOVE
             * This needs to be first to make sure we already know if we are attempting to enter legacy mode or not
             */
        	if(bundle !=null 
        			&& bundle.containsKey(TransportConstants.ENABLE_LEGACY_MODE_EXTRA)){
				boolean enableLegacy = bundle.getBoolean(TransportConstants.ENABLE_LEGACY_MODE_EXTRA, false);
				Log.d(TAG, "Setting legacy mode: " +enableLegacy );
				enableLegacyMode(enableLegacy);
			}
            
        	//Find out what message we have and what to do with it
            switch (msg.what) {//FIXME
            	case TransportConstants.ROUTER_REGISTER_CLIENT_RESPONSE:
            		if(msg.arg1==TransportConstants.REGISTRATION_RESPONSE_SUCESS){
            			//TODO yay! we have been registered. Now what?
            			registeredWithRouterService = true;
            			if(bundle!=null && bundle.containsKey(TransportConstants.CONNECTED_DEVICE_STRING_EXTRA_NAME)){
        					//Keep track if we actually get this
        				}
            			if(queuedOnTransportConnect!=null){
        					onHardwareConnected(queuedOnTransportConnect);
        					queuedOnTransportConnect = null;
        				}else if(SdlBroadcastReceiver.isTransportConnected(getContext())){
        					onHardwareConnected(null); //FIXME to include type
        				}
            		}else{ //We were denied registration to the router service, let's see why
            			registeredWithRouterService = false; 
            			Log.w(TAG, "Registration denied from router service. Reason - " + msg.arg1);
            		}
            	
            		break;
            	case TransportConstants.ROUTER_UNREGISTER_CLIENT_RESPONSE:
            		if(msg.arg1==TransportConstants.UNREGISTRATION_RESPONSE_SUCESS){
            			//TODO We've been unregistered. Now what?
            			
            			
            		}else{ //We were denied our unregister request to the router service, let's see why
            			Log.w(TAG, "Unregister request denied from router service. Reason - " + msg.arg1);
            			//Do we care?
            		}
            	
            		break;
            	case TransportConstants.ROUTER_RECEIVED_PACKET:
					//So the intent has a packet with it. PEFRECT! Let's send it through the library
            		if(bundle.containsKey(TransportConstants.FORMED_PACKET_EXTRA_NAME)){
            			Parcelable packet = bundle.getParcelable(TransportConstants.FORMED_PACKET_EXTRA_NAME);
{'fraction_non_alphanumeric': 0.08025682182985554, 'fraction_numerical': 0.0006420545746388443, 'mean_word_length': 2.8819314641744547, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4231456', 'n_tokens_mistral': 3796, 'n_tokens_neox': 3429, 'n_words': 879}