/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the License).  You may not use this file except in
 * compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */
package com.sun.appserv.management.base;

import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import java.util.Collections;
import java.util.HashMap;
import java.lang.reflect.Field;


/**
	Map all types from XTypes to their respective MBean interfaces.
	
	@see AllTypesMapper
	@see com.sun.appserv.management.j2ee.J2EETypesMapper
 */
public class TypesMapper
{
	private final Map<String,Class>	mMap;
	
		public
	TypesMapper( final Class[] interfaces )
	{
		mMap	= init( interfaces );
	}
	
	/**
		Map all types to interfaces.
	 */
		private Map<String,Class>
	init( final Class[] interfaces )
	{
		final Map<String,Class>	m	= new HashMap<String,Class>();

		for( int i = 0; i < interfaces.length; ++i )
		{
			final Class	theInterface	= interfaces[ i ];
			
			try
			{
				final Field	field	= theInterface.getField( "J2EE_TYPE" );
				final String value	= (String)field.get( theInterface );
				if ( m.containsKey( value ) )
				{
					final String	msg	=
						"TypesMapper: key already present: " +
						value + " for " + theInterface.getName();
					
					assert(  false ): msg;
					throw new RuntimeException( msg );
				}
				m.put( value, theInterface );
			}
			catch( Exception e )
			{
				e.printStackTrace();
				assert( false );
				throw new IllegalArgumentException( theInterface.getName() );
			}
		}
		
		return( m );
	}
	
	/**
		Return the Class associated with a given type.
	 */
		public Class
	getInterfaceForType( final String type )
	{
		final Class theClass	= mMap.get( type );
		
		return( theClass );
	}
	
	    public Set<String>
	getJ2EETypes()
	{
	    return Collections.unmodifiableSet( mMap.keySet() );
	}
	
	    public Set<Class>
	getClasses()
	{
	    final Set<Class>    classes = new HashSet<Class>();
	    classes.addAll( mMap.values() );
	    return Collections.unmodifiableSet( classes );
	}
}











