001 002package gudusoft.gsqlparser.pp.mediator; 003 004import gudusoft.gsqlparser.pp.logger.PPLogger; 005import gudusoft.gsqlparser.pp.mediator.type.AbstractMediator; 006 007import java.util.ArrayList; 008import java.util.List; 009import java.util.Map; 010import java.util.concurrent.ConcurrentHashMap; 011 012public class MediatorFactory 013{ 014 015 /** 016 * the processor container. Package-private, not private, for white-box tests (they read it through the test 017 * helper {@code gudusoft.gsqlparser.pp.mediator.MediatorRegistry}): the shipment obfuscates this name, and the 018 * obfuscation gate remaps a direct field reference but never a reflective {@code getDeclaredField("mediator")}. 019 */ 020 volatile static Map<String, AbstractMediator> mediator = new ConcurrentHashMap<String, AbstractMediator>( ); 021 022 private static Object object = new Object( ); 023 024 public static <E extends AbstractMediator> E getMediator( Class<E> clazz, 025 String sessionId ) 026 { 027 String id = sessionId + clazz.getName( ); 028 if ( !mediator.containsKey( id ) ) 029 { 030 synchronized ( MediatorFactory.class ) 031 { 032 if ( !mediator.containsKey( id ) ) 033 { 034 E processor = newInstance( clazz ); 035 mediator.put( id, processor ); 036 } 037 } 038 } 039 040 return (E) mediator.get( id ); 041 } 042 043 /** 044 * create a new mediator instance 045 * 046 * @param type 047 * the processor type 048 * @return insteance 049 */ 050 public static <E extends AbstractMediator> E newInstance( Class<E> type ) 051 { 052 try 053 { 054 return (E) type.newInstance( ); 055 } 056 catch ( InstantiationException e ) 057 { 058 PPLogger.error( e ); 059 return null; 060 } 061 catch ( IllegalAccessException e ) 062 { 063 PPLogger.error( e ); 064 return null; 065 } 066 } 067 068 public static void clear( String sessionId ) 069 { 070 synchronized ( object ) 071 { 072 List<String> removedKeys = new ArrayList<String>( ); 073 for ( String key : mediator.keySet( ) ) 074 { 075 if ( key.startsWith( sessionId ) ) 076 { 077 removedKeys.add( key ); 078 } 079 } 080 for ( String key : removedKeys ) 081 { 082 mediator.remove( key ); 083 } 084 } 085 } 086}