1 17 18 package org.apache.avalon.fortress.impl.lookup; 19 20 import org.apache.avalon.fortress.Container; 21 import org.apache.avalon.fortress.impl.handler.ComponentHandler; 22 import org.apache.avalon.framework.service.ServiceException; 23 import org.apache.avalon.framework.service.ServiceSelector; 24 25 import java.util.Collections ; 26 import java.util.HashMap ; 27 import java.util.Map ; 28 29 37 public class FortressServiceSelector 38 implements ServiceSelector 39 { 40 private final String m_key; 41 private final Container m_container; 42 private final Map m_used; 43 44 49 public FortressServiceSelector( final Container container, 50 final String key ) 51 { 52 if ( null == container ) 53 { 54 throw new NullPointerException ( "impl" ); 55 } 56 if ( null == key ) 57 { 58 throw new NullPointerException ( "key" ); 59 } 60 61 m_key = key; 62 m_container = container; 63 m_used = Collections.synchronizedMap(new HashMap ()); 64 } 65 66 public Object select( final Object hint ) 67 throws ServiceException 68 { 69 try 70 { 71 final ComponentHandler handler = getHandler( hint ); 72 final Object component = handler.get(); 73 m_used.put( new ComponentKey( component ), handler ); 74 return component; 75 } 76 catch ( final ServiceException ce ) 77 { 78 throw ce; } 80 catch ( final Exception e ) 81 { 82 final String name = m_key + "/" + hint.toString(); 83 final String message = "Could not return a reference to the Component"; 84 throw new ServiceException( name, message, e ); 85 } 86 } 87 88 public boolean isSelectable( final Object hint ) 89 { 90 return m_container.has( m_key, hint ); 91 } 92 93 public void release( final Object component ) 94 { 95 final ComponentHandler handler = 96 (ComponentHandler) m_used.remove( new ComponentKey( component ) ); 97 if ( null != handler ) 98 { 99 handler.put( component ); 100 } 101 } 102 103 private ComponentHandler getHandler( final Object hint ) 104 throws ServiceException 105 { 106 if ( null == hint ) 107 { 108 final String message = "hint cannot be null"; 109 throw new IllegalArgumentException ( message ); 110 } 111 112 final ComponentHandler handler = 113 (ComponentHandler) m_container.get( m_key, hint ); 114 if ( null == handler ) 115 { 116 final String message = 117 "The hint does not exist in the ComponentSelector"; 118 throw new ServiceException( m_key + "/" + hint.toString(), 119 message ); 120 } 121 return handler; 122 } 123 124 public String getKey() 125 { 126 return m_key; 127 } 128 } 129 | Popular Tags |