<commit_before>/*
 * $Header$
 * 
 * Copyright (c) OSGi Alliance (2005). All Rights Reserved.
 * 
 * Implementation of certain elements of the OSGi Specification may be subject
 * to third party intellectual property rights, including without limitation,
 * patent rights (such a third party may or may not be a member of the OSGi
 * Alliance). The OSGi Alliance is not responsible and shall not be held
 * responsible in any manner for identifying or failing to identify any or all
 * such third party intellectual property rights.
 * 
 * This document and the information contained herein are provided on an "AS IS"
 * basis and THE OSGI ALLIANCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION
 * HEREIN WILL NOT INFRINGE ANY RIGHTS AND ANY IMPLIED WARRANTIES OF
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL THE
 * OSGI ALLIANCE BE LIABLE FOR ANY LOSS OF PROFITS, LOSS OF BUSINESS, LOSS OF
 * USE OF DATA, INTERRUPTION OF BUSINESS, OR FOR DIRECT, INDIRECT, SPECIAL OR
 * EXEMPLARY, INCIDENTIAL, PUNITIVE OR CONSEQUENTIAL DAMAGES OF ANY KIND IN
 * CONNECTION WITH THIS DOCUMENT OR THE INFORMATION CONTAINED HEREIN, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH LOSS OR DAMAGE.
 * 
 * All Company, brand and product names may be trademarks that are the sole
 * property of their respective owners. All rights reserved.
 */

package org.osgi.impl.bundle.midletcontainer;

import java.lang.reflect.*;
import java.security.*;
import java.util.*;

import org.osgi.framework.*;
import org.osgi.application.*;
import org.osgi.service.application.*;
import org.osgi.service.log.LogService;

public class OATApplicationContextImpl implements ApplicationContext, ServiceListener {
	
	BundleContext bc = null;
	Map startupParams = null;
	LinkedList serviceList = null;
	LinkedList registeredServiceList = null;
	LinkedList serviceListenerList = null;
	Vector mandatoryServiceList = null;
	Vector mandatoryTargetList = null;
	OATApplicationData oatAppData = null;
	ApplicationHandle appHandle = null;
	Object mainClass = null;
	
	String instanceId = null;
	String applicationId = null;

	class Service {
		OATServiceData    serviceData;
		Object            serviceObject;
		ServiceReference  serviceReference;
	}
	
	class ServiceListenerImpl {
		
		public ServiceListenerImpl( ApplicationServiceListener listener, String []interfaces, Filter []filters ) {
			this.listener = listener;
			this.filters = filters;
			this.interfaces = interfaces;
		}
		
		public boolean match( String []ifaces, Hashtable props ) {
			for( int n=0; n != ifaces.length; n++ )
				for( int p=0; p != interfaces.length; p++ ) {
					if( ifaces[ n ].equals( interfaces[ p ])) {
						if( filters[ n ] == null )
							return true;
						if( filters[ n ].match( props ) )
							return true;
					}
				}
			return false;
		}
		
		ApplicationServiceListener listener;
		Filter []filters;
		String []interfaces;
	}
		
	public OATApplicationContextImpl( Bundle bundle, Map startupParams, OATApplicationData appData, ApplicationHandle appHandle, Object mainClass ) {
		bc = frameworkHook( bundle );
		this.startupParams = startupParams;
		this.mainClass = mainClass;
		serviceList = new LinkedList();
		registeredServiceList = new LinkedList();
		serviceListenerList = new LinkedList();
		oatAppData = appData;
		
		mandatoryServiceList = new Vector();
		mandatoryTargetList = new Vector();
		
		for( int i=0; i != appData.getServices().length; i++ ) {
			OATServiceData service = appData.getServices()[ i ];
			if( service.getCardinality() == OATServiceData.CARDINALITY1_1 ||
					service.getCardinality() == OATServiceData.CARDINALITY1_n )
				mandatoryServiceList.add( service.getInterface() );
			  mandatoryTargetList.add( service.getTarget() );
		}			
		
		this.appHandle = appHandle;
		bc.addServiceListener( this );
		
		instanceId = appHandle.getInstanceId();
		applicationId = appHandle.getApplicationDescriptor().getApplicationId();
	}

	public void addServiceListener(ApplicationServiceListener listener, String referenceName)
	throws IllegalArgumentException {
		if( referenceName == null )
			throw new NullPointerException( "Reference name cannot be null!" );
		
		addServiceListener( listener, new String[] {referenceName} );
	}

	public void addServiceListener(ApplicationServiceListener listener, String []referenceNames)
			throws IllegalArgumentException {
		
		if( listener == null )
			throw new NullPointerException( "ApplicationServiceListener cannot be null!" );
		if( referenceNames == null )
			throw new NullPointerException( "Reference names cannot be null!" );
		if( referenceNames.length == 0 )
			throw new IllegalArgumentException( "At least one reference name must be given!" );
		
		if( appHandle == null )
			throw new IllegalStateException( "Application is not running!" );

		Filter filters[] = new Filter[ referenceNames.length ];
		String interfaces[] = new String[ referenceNames.length ];
		
		for( int q=0 ; q != referenceNames.length; q++ ) {
			int i = 0;
			for( ; i != oatAppData.getServices().length; i++ )
				if( oatAppData.getServices()[ i ].getName().equals( referenceNames[ q ] )) {
					interfaces[ q ] = oatAppData.getServices()[ i ].getInterface();
					try {
						String filterStr = oatAppData.getServices()[ i ].getTarget();
						filters[ q ] = filterStr == null ? null : bc.createFilter( filterStr );
					}catch( InvalidSyntaxException e ) {
						throw new IllegalArgumentException();
					}
					break;
				}
			if( i == oatAppData.getServices().length )
				throw new IllegalArgumentException();
		}

		removeServiceListener( listener );		
		serviceListenerList.add( new ServiceListenerImpl( listener, interfaces, filters ) );
	}
	
	public Map getStartupParameters() {
		if( appHandle == null )
			throw new IllegalStateException( "Application is not running!" );
		
		return startupParams;
	}
	
	public Object locateService(String referenceName) {
		if( referenceName == null )
			throw new NullPointerException( "Reference name cannot be null!" );
		if( appHandle == null )
			throw new IllegalStateException( "Application is not running!" );
		
		for( int i=0; i != oatAppData.getServices().length; i++ ) {
			if( oatAppData.getServices()[ i ].getName().equals( referenceName )) {				
				
				/* checks whether a reference exists in the service list */
				
				Iterator iterator = serviceList.iterator();
				while( iterator.hasNext() ) {
					Service serv = (Service)iterator.next();
					
					if( serv.serviceData.getName().equals( referenceName ) ) {
						if( serv.serviceReference.getBundle() == null ) {
							if( removeService( serv ) )
								throw new RuntimeException( "Static service terminated!" ); /* termination is requested */
							iterator = serviceList.iterator();
						} else							
						  return serv.serviceObject;
					}
				}
				
				/* getting the service references */
				
				OATServiceData service = oatAppData.getServices()[ i ];
				
				ServiceReference refs[] = null;
				
				try {
		      refs = bc.getServiceReferences( service.getInterface(),
		    	                                service.getTarget() );
				}catch( InvalidSyntaxException e ) 
				{
					Activator.log( LogService.LOG_ERROR, "Invalid filter syntax for reference '" + referenceName + "'!", e );
					throw new IllegalArgumentException();
				}
				
		    if( refs == null || refs.length == 0 ) {
		    	if( service.getCardinality() == OATServiceData.CARDINALITY1_1 || 
		    			service.getCardinality() == OATServiceData.CARDINALITY1_n ) {
		    		requestTermination();
		    		throw new RuntimeException( "The requested service not found!" );
		    	}
		    	return null;
		    }
		    
		    ServiceReference selectedReference = refs[ 0 ];
		    
		    Integer selRanking = (Integer)refs[ 0 ].getProperty( Constants.SERVICE_RANKING );		    
		    int              selectedRanking   = (selRanking == null) ? 0 : selRanking.intValue();
		    long             selectedServiceId = ((Long)refs[ 0 ].getProperty( Constants.SERVICE_ID )).longValue(); 
		    
		    for( int j=1; j < refs.length; j++ ) {
			    Integer rankW = (Integer)refs[ j ].getProperty( Constants.SERVICE_RANKING );		    
			    int  rank = (rankW == null) ? 0 : rankW.intValue();
		    	long serviceID = ((Long)refs[ j ].getProperty( Constants.SERVICE_ID )).longValue();
		    	
		    	if( rank > selectedRanking || ( rank == selectedRanking && serviceID < selectedServiceId) )
		    		selectedReference = refs[ j ];
		    }

		    Service srv = new Service();
		    srv.serviceData = service;
		    srv.serviceReference = selectedReference;
		    srv.serviceObject = bc.getService( selectedReference );
		    
		    serviceList.add( srv );
		    return srv.serviceObject;
			}
		}
		throw new IllegalArgumentException();
	}
	
	public Object[] locateServices(String referenceName) {
		if( referenceName == null ) /* TODO: add it into the specification!!! */
			throw new NullPointerException( "Reference name cannot be null!" );
		if( appHandle == null )
			throw new IllegalStateException( "Application is not running!" );
		
		for( int i=0; i != oatAppData.getServices().length; i++ ) {
			if( oatAppData.getServices()[ i ].getName().equals( referenceName )) {
								
				/* getting the service references */
				
				OATServiceData service = oatAppData.getServices()[ i ];
				
				ServiceReference refs[] = null;
				
				try {
		      refs = bc.getServiceReferences( service.getInterface(),
		    	                                service.getTarget() );
				}catch( InvalidSyntaxException e ) 
				{
					Activator.log( LogService.LOG_ERROR, "Invalid filter syntax for reference '" + referenceName + "'!", e );
					return new Object[ 0 ];
				}
				
				if( refs == null || refs.length == 0 ) {
		    	if( service.getCardinality() == OATServiceData.CARDINALITY1_1 || 
		    			service.getCardinality() == OATServiceData.CARDINALITY1_n ) {
		    		requestTermination();
		    		throw new RuntimeException( "The requested service not found!" );
		    	}
		    	return null;					
				}
				
				Object[] result = new Object[ refs.length ];
				for( int j=0; j != refs.length; j++ ) {
					Service serv = getServiceByReference( refs[ j ] );
					if( serv != null )
						result[ j ] = serv.serviceObject;
					else {
				    serv = new Service();
				    serv.serviceData = service;
				    serv.serviceReference = refs[ j ];
				    result[ j ] = serv.serviceObject = bc.getService( refs[ j ] );						
					}
				}
				return result;
			}
		}
		throw new IllegalArgumentException();
	}
	
	public ServiceRegistration registerService(String clazz, Object service,
			Dictionary properties) {
		if( appHandle == null )
			throw new IllegalStateException( "Application is not running!" );
		
		if( service == null )
			throw new IllegalArgumentException( "Service cannot be null!" );
		
		if( service == mainClass )
			throw new SecurityException( "Registering the base class of the application is insecure and forbidden!" );
		
		ServiceRegistration servReg = bc.registerService( clazz, service, properties );
		registeredServiceList.add( servReg );
		return servReg;
	}<commit_msg>FIXED: getServiceProperties doesn't work after locateServices<commit_after>/*
 * $Header$
 * 
 * Copyright (c) OSGi Alliance (2005). All Rights Reserved.
 * 
 * Implementation of certain elements of the OSGi Specification may be subject
 * to third party intellectual property rights, including without limitation,
 * patent rights (such a third party may or may not be a member of the OSGi
 * Alliance). The OSGi Alliance is not responsible and shall not be held
 * responsible in any manner for identifying or failing to identify any or all
 * such third party intellectual property rights.
 * 
 * This document and the information contained herein are provided on an "AS IS"
 * basis and THE OSGI ALLIANCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION
 * HEREIN WILL NOT INFRINGE ANY RIGHTS AND ANY IMPLIED WARRANTIES OF
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT WILL THE
 * OSGI ALLIANCE BE LIABLE FOR ANY LOSS OF PROFITS, LOSS OF BUSINESS, LOSS OF
 * USE OF DATA, INTERRUPTION OF BUSINESS, OR FOR DIRECT, INDIRECT, SPECIAL OR
 * EXEMPLARY, INCIDENTIAL, PUNITIVE OR CONSEQUENTIAL DAMAGES OF ANY KIND IN
 * CONNECTION WITH THIS DOCUMENT OR THE INFORMATION CONTAINED HEREIN, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH LOSS OR DAMAGE.
 * 
 * All Company, brand and product names may be trademarks that are the sole
 * property of their respective owners. All rights reserved.
 */

package org.osgi.impl.bundle.midletcontainer;

import java.lang.reflect.*;
import java.security.*;
import java.util.*;

import org.osgi.framework.*;
import org.osgi.application.*;
import org.osgi.service.application.*;
import org.osgi.service.log.LogService;

public class OATApplicationContextImpl implements ApplicationContext, ServiceListener {
	
	BundleContext bc = null;
	Map startupParams = null;
	LinkedList serviceList = null;
	LinkedList registeredServiceList = null;
	LinkedList serviceListenerList = null;
	Vector mandatoryServiceList = null;
	Vector mandatoryTargetList = null;
	OATApplicationData oatAppData = null;
	ApplicationHandle appHandle = null;
	Object mainClass = null;
	
	String instanceId = null;
	String applicationId = null;

	class Service {
		OATServiceData    serviceData;
		Object            serviceObject;
		ServiceReference  serviceReference;
	}
	
	class ServiceListenerImpl {
		
		public ServiceListenerImpl( ApplicationServiceListener listener, String []interfaces, Filter []filters ) {
			this.listener = listener;
			this.filters = filters;
			this.interfaces = interfaces;
		}
		
		public boolean match( String []ifaces, Hashtable props ) {
			for( int n=0; n != ifaces.length; n++ )
				for( int p=0; p != interfaces.length; p++ ) {
					if( ifaces[ n ].equals( interfaces[ p ])) {
						if( filters[ n ] == null )
							return true;
						if( filters[ n ].match( props ) )
							return true;
					}
				}
			return false;
		}
		
		ApplicationServiceListener listener;
		Filter []filters;
		String []interfaces;
	}
		
	public OATApplicationContextImpl( Bundle bundle, Map startupParams, OATApplicationData appData, ApplicationHandle appHandle, Object mainClass ) {
		bc = frameworkHook( bundle );
		this.startupParams = startupParams;
		this.mainClass = mainClass;
		serviceList = new LinkedList();
		registeredServiceList = new LinkedList();
		serviceListenerList = new LinkedList();
		oatAppData = appData;
		
		mandatoryServiceList = new Vector();
		mandatoryTargetList = new Vector();
		
		for( int i=0; i != appData.getServices().length; i++ ) {
			OATServiceData service = appData.getServices()[ i ];
			if( service.getCardinality() == OATServiceData.CARDINALITY1_1 ||
					service.getCardinality() == OATServiceData.CARDINALITY1_n )
				mandatoryServiceList.add( service.getInterface() );
			  mandatoryTargetList.add( service.getTarget() );
		}			
		
		this.appHandle = appHandle;
		bc.addServiceListener( this );
		
		instanceId = appHandle.getInstanceId();
		applicationId = appHandle.getApplicationDescriptor().getApplicationId();
	}

	public void addServiceListener(ApplicationServiceListener listener, String referenceName)
	throws IllegalArgumentException {
		if( referenceName == null )
			throw new NullPointerException( "Reference name cannot be null!" );
		
		addServiceListener( listener, new String[] {referenceName} );
	}

	public void addServiceListener(ApplicationServiceListener listener, String []referenceNames)
			throws IllegalArgumentException {
		
		if( listener == null )
			throw new NullPointerException( "ApplicationServiceListener cannot be null!" );
		if( referenceNames == null )
			throw new NullPointerException( "Reference names cannot be null!" );
		if( referenceNames.length == 0 )
			throw new IllegalArgumentException( "At least one reference name must be given!" );
		
		if( appHandle == null )
			throw new IllegalStateException( "Application is not running!" );

		Filter filters[] = new Filter[ referenceNames.length ];
		String interfaces[] = new String[ referenceNames.length ];
		
		for( int q=0 ; q != referenceNames.length; q++ ) {
			int i = 0;
			for( ; i != oatAppData.getServices().length; i++ )
				if( oatAppData.getServices()[ i ].getName().equals( referenceNames[ q ] )) {
					interfaces[ q ] = oatAppData.getServices()[ i ].getInterface();
					try {
						String filterStr = oatAppData.getServices()[ i ].getTarget();
						filters[ q ] = filterStr == null ? null : bc.createFilter( filterStr );
					}catch( InvalidSyntaxException e ) {
						throw new IllegalArgumentException();
					}
					break;
				}
			if( i == oatAppData.getServices().length )
				throw new IllegalArgumentException();
		}

		removeServiceListener( listener );		
		serviceListenerList.add( new ServiceListenerImpl( listener, interfaces, filters ) );
	}
	
	public Map getStartupParameters() {
		if( appHandle == null )
			throw new IllegalStateException( "Application is not running!" );
		
		return startupParams;
	}
	
	public Object locateService(String referenceName) {
		if( referenceName == null )
			throw new NullPointerException( "Reference name cannot be null!" );
		if( appHandle == null )
			throw new IllegalStateException( "Application is not running!" );
		
		for( int i=0; i != oatAppData.getServices().length; i++ ) {
			if( oatAppData.getServices()[ i ].getName().equals( referenceName )) {				
				
				/* checks whether a reference exists in the service list */
				
				Iterator iterator = serviceList.iterator();
				while( iterator.hasNext() ) {
					Service serv = (Service)iterator.next();
					
					if( serv.serviceData.getName().equals( referenceName ) ) {
						if( serv.serviceReference.getBundle() == null ) {
							if( removeService( serv ) )
								throw new RuntimeException( "Static service terminated!" ); /* termination is requested */
							iterator = serviceList.iterator();
						} else							
						  return serv.serviceObject;
					}
				}
				
				/* getting the service references */
				
				OATServiceData service = oatAppData.getServices()[ i ];
				
				ServiceReference refs[] = null;
				
				try {
		      refs = bc.getServiceReferences( service.getInterface(),
		    	                                service.getTarget() );
				}catch( InvalidSyntaxException e ) 
				{
					Activator.log( LogService.LOG_ERROR, "Invalid filter syntax for reference '" + referenceName + "'!", e );
					throw new IllegalArgumentException();
				}
				
		    if( refs == null || refs.length == 0 ) {
		    	if( service.getCardinality() == OATServiceData.CARDINALITY1_1 || 
		    			service.getCardinality() == OATServiceData.CARDINALITY1_n ) {
		    		requestTermination();
		    		throw new RuntimeException( "The requested service not found!" );
		    	}
		    	return null;
		    }
		    
		    ServiceReference selectedReference = refs[ 0 ];
		    
		    Integer selRanking = (Integer)refs[ 0 ].getProperty( Constants.SERVICE_RANKING );		    
		    int              selectedRanking   = (selRanking == null) ? 0 : selRanking.intValue();
		    long             selectedServiceId = ((Long)refs[ 0 ].getProperty( Constants.SERVICE_ID )).longValue(); 
		    
		    for( int j=1; j < refs.length; j++ ) {
			    Integer rankW = (Integer)refs[ j ].getProperty( Constants.SERVICE_RANKING );		    
			    int  rank = (rankW == null) ? 0 : rankW.intValue();
		    	long serviceID = ((Long)refs[ j ].getProperty( Constants.SERVICE_ID )).longValue();
		    	
		    	if( rank > selectedRanking || ( rank == selectedRanking && serviceID < selectedServiceId) )
		    		selectedReference = refs[ j ];
		    }

		    Service srv = new Service();
		    srv.serviceData = service;
		    srv.serviceReference = selectedReference;
		    srv.serviceObject = bc.getService( selectedReference );
		    
		    serviceList.add( srv );
		    return srv.serviceObject;
			}
		}
		throw new IllegalArgumentException();
	}
	
	public Object[] locateServices(String referenceName) {
		if( referenceName == null ) /* TODO: add it into the specification!!! */
			throw new NullPointerException( "Reference name cannot be null!" );
		if( appHandle == null )
			throw new IllegalStateException( "Application is not running!" );
		
		for( int i=0; i != oatAppData.getServices().length; i++ ) {
			if( oatAppData.getServices()[ i ].getName().equals( referenceName )) {
								
				/* getting the service references */
				
				OATServiceData service = oatAppData.getServices()[ i ];
				
				ServiceReference refs[] = null;
				
				try {
		      refs = bc.getServiceReferences( service.getInterface(),
		    	                                service.getTarget() );
				}catch( InvalidSyntaxException e ) 
				{
					Activator.log( LogService.LOG_ERROR, "Invalid filter syntax for reference '" + referenceName + "'!", e );
					return new Object[ 0 ];
				}
				
				if( refs == null || refs.length == 0 ) {
		    	if( service.getCardinality() == OATServiceData.CARDINALITY1_1 || 
		    			service.getCardinality() == OATServiceData.CARDINALITY1_n ) {
		    		requestTermination();
		    		throw new RuntimeException( "The requested service not found!" );
		    	}
		    	return null;					
				}
				
				Object[] result = new Object[ refs.length ];
				for( int j=0; j != refs.length; j++ ) {
					Service serv = getServiceByReference( refs[ j ] );
					if( serv != null )
						result[ j ] = serv.serviceObject;
					else {
				    serv = new Service();
				    serv.serviceData = service;
				    serv.serviceReference = refs[ j ];
				    result[ j ] = serv.serviceObject = bc.getService( refs[ j ] );						
				    serviceList.add( serv );
					}
				}
				return result;
			}
		}
		throw new IllegalArgumentException();
	}
	
	public ServiceRegistration registerService(String clazz, Object service,
			Dictionary properties) {
		if( appHandle == null )
			throw new IllegalStateException( "Application is not running!" );
		
		if( service == null )
			throw new IllegalArgumentException( "Service cannot be null!" );
		
		if( service == mainClass )
			throw new SecurityException( "Registering the base class of the application is insecure and forbidden!" );
		
		ServiceRegistration servReg = bc.registerService( clazz, service, properties );
		registeredServiceList.add( servReg );
		return servReg;
	}
{'fraction_non_alphanumeric': 0.1018020022246941, 'fraction_numerical': 0.002758620689655172, 'mean_word_length': 3.2439577039274923, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1225699', 'n_tokens_mistral': 7470, 'n_tokens_neox': 6077, 'n_words': 1941}