signature:
public class ManagedClass { /** * Load optional implementation class from class descriptor and applies insanity checks . Load implementation class from
 * < code > class < / code > attribute from descriptor . If < code > class < / code > attribute not present return null .
 * Beside loading implementation class this utility method performs sanity checks and throws configuration exception if :
 * < ul >
 * < li > instance type requires implementation but < code > class < / code > attribute is missing ,
 * < li > instance type does not require implementation but < code > class < / code > attribute is present ,
 * < li > class not found on run - time class path ,
 * < li > implementation class is a Java interface ,
 * < li > implementation class is abstract ,
 * < li > implementation class implements managed life cycle but instance scope is not { @ link InstanceScope # APPLICATION } .
 * < / ul >
 * @ param descriptor class descriptor .
 * @ return loaded implementation class or null .
 * @ throws ConfigException if sanity check fails . */
private Class < ? > loadImplementationClass ( Config descriptor ) throws ConfigException { } }

implementation: String implementationName = descriptor . getAttribute ( "class" ) ; if ( implementationName == null ) { if ( instanceType . requiresImplementation ( ) ) { throw new ConfigException ( "Managed type |%s| requires <class> attribute. See class descriptor |%s|." , instanceType , descriptor ) ; } return null ; } if ( ! instanceType . requiresImplementation ( ) ) { throw new ConfigException ( "Managed type |%s| forbids <class> attribute. See class descriptor |%s|." , instanceType , descriptor ) ; } Class < ? > implementationClass = Classes . forOptionalName ( implementationName ) ; if ( implementationClass == null ) { throw new ConfigException ( "Managed class implementation |%s| not found." , implementationName ) ; } if ( implementationClass . isInterface ( ) ) { throw new ConfigException ( "Managed class implementation |%s| cannot be an interface. See class descriptor |%s|." , implementationClass , descriptor ) ; } int implementationModifiers = implementationClass . getModifiers ( ) ; if ( Modifier . isAbstract ( implementationModifiers ) ) { throw new ConfigException ( "Managed class implementation |%s| cannot be abstract. See class descriptor |%s|." , implementationClass , descriptor ) ; } if ( Types . isKindOf ( implementationClass , ManagedLifeCycle . class ) && ! InstanceScope . APPLICATION . equals ( instanceScope ) ) { throw new ConfigException ( "Bad scope |%s| used with managed life cycle. See class descriptor |%s|." , instanceScope , descriptor ) ; } return implementationClass ;


signature:
public class ManagedClass { /** * Load interface classes from class descriptor . Attempt to load interface classes from < code > interface < / code > attribute or
 * child elements . If none found returns implementation class that should be already initialized .
 * Perform sanity checks on loaded interface classes and throws configuration exception is :
 * < ul >
 * < li > instance type requires interface but none found ,
 * < li > < code > name < / code > attribute is missing from child element ,
 * < li > interface class not found on run - time class path ,
 * < li > implementation class is not implemented by already configured implementation class .
 * < / ul >
 * This utility method should be loaded after { @ link # loadImplementationClass ( Config ) } otherwise behavior is not defined .
 * @ param descriptor class descriptor .
 * @ return interface classes array .
 * @ throws ConfigException if sanity check fails . */
private Class < ? > [ ] loadInterfaceClasses ( Config descriptor ) throws ConfigException { } }

implementation:
List < String > interfaceNames = new ArrayList < > ( ) ; if ( ! descriptor . hasChildren ( ) ) { if ( ! descriptor . hasAttribute ( "interface" ) ) { if ( instanceType . requiresInterface ( ) ) { throw new ConfigException ( "Managed type |%s| requires <interface> attribute. See class descriptor |%s|." , instanceType , descriptor ) ; } // if interface is not required and is missing uses implementation class
return new Class < ? > [ ] { implementationClass } ; } interfaceNames . add ( descriptor . getAttribute ( "interface" ) ) ; if ( "REMOTE" . equals ( descriptor . getAttribute ( "type" ) ) ) { String url = descriptor . getAttribute ( "url" ) ; if ( url == null || url . isEmpty ( ) ) { throw new ConfigException ( "Managed type REMOTE requires <url> attribute. See class descriptor |%s|." , descriptor ) ; } if ( url . startsWith ( "${" ) ) { throw new ConfigException ( "Remote implementation <url> property not resolved. See class descriptor |%s|." , descriptor ) ; } } } else { for ( int i = 0 ; i < descriptor . getChildrenCount ( ) ; ++ i ) { String interfaceName = descriptor . getChild ( i ) . getAttribute ( "name" ) ; if ( interfaceName == null ) { throw new ConfigException ( "Missing <name> attribute from interface declaration. See class descriptor |%s|." , descriptor ) ; } interfaceNames . add ( interfaceName ) ; } } Class < ? > [ ] interfaceClasses = new Class < ? > [ interfaceNames . size ( ) ] ; for ( int i = 0 ; i < interfaceNames . size ( ) ; ++ i ) { final String interfaceName = interfaceNames . get ( i ) ; final Class < ? > interfaceClass = Classes . forOptionalName ( interfaceName ) ; if ( interfaceClass == null ) { throw new ConfigException ( "Managed class interface |%s| not found." , interfaceName ) ; } if ( Types . isKindOf ( interfaceClass , ManagedLifeCycle . class ) ) { autoInstanceCreation = true ; } if ( instanceType . requiresInterface ( ) && ! interfaceClass . isInterface ( ) ) { throw new ConfigException ( "Managed type |%s| requires interface to make Java Proxy happy but got |%s|." , instanceType , interfaceClass ) ; } if ( implementationClass != null && ! Types . isKindOf ( implementationClass , interfaceClass ) ) { throw new ConfigException ( "Implementation |%s| is not a kind of interface |%s|." , implementationClass , interfaceClass ) ; } interfaceClasses [ i ] = interfaceClass ; } return interfaceClasses ;


signature:
public class ManagedClass { /** * Return instance scope loaded from class descriptor , < code > scope < / code > attribute . If scope is not defined use
 * { @ link InstanceScope # APPLICATION } as default value .
 * @ param descriptor managed class descriptor .
 * @ return loaded instance scope .
 * @ throws ConfigException if there is no { @ link ScopeFactory } registered for loaded instance scope . */
private InstanceScope loadInstanceScope ( Config descriptor ) throws ConfigException { } }

implementation: InstanceScope instanceScope = descriptor . getAttribute ( "scope" , InstanceScope . class , InstanceScope . APPLICATION ) ; if ( ! container . hasScopeFactory ( instanceScope ) ) { throw new ConfigException ( "Not registered managed instance scope value |%s|. See class descriptor |%s|." , instanceScope , descriptor ) ; } return instanceScope ;


signature:
public class ManagedClass { /** * Return instance type loaded from class descriptor , < code > type < / code > attribute . If type is not defined uses
 * { @ link InstanceType # POJO } as default value .
 * @ param descriptor managed class descriptor .
 * @ return loaded instance type .
 * @ throws ConfigException if there is no { @ link InstanceFactory } registered for loaded instance type . */
private InstanceType loadInstanceType ( Config descriptor ) throws ConfigException { } }

implementation: InstanceType instanceType = descriptor . getAttribute ( "type" , InstanceType . class , InstanceType . POJO ) ; if ( ! container . hasInstanceFactory ( instanceType ) ) { throw new ConfigException ( "Not registered managed instance type value |%s|. See class descriptor |%s|." , instanceType , descriptor ) ; } return instanceType ;


signature:
public class ManagedClass { /** * Load remote class URL from class descriptor , < code > url < / code > attribute . This getter does not perform URL validation ; it
 * returns URL value as declared by attribute .
 * @ param descriptor class descriptor .
 * @ return remote class URL value .
 * @ throws ConfigException if instance type is { @ link InstanceType # REMOTE } and < code > url < / code > attribute is missing . */
private String loadImplementationURL ( Config descriptor ) throws ConfigException { } }

implementation: String implementationURL = descriptor . getAttribute ( "url" ) ; if ( instanceType . equals ( InstanceType . REMOTE ) && implementationURL == null ) { throw new ConfigException ( "Remote managed class requires <url> attribute. See class descriptor |%s|." , descriptor ) ; } return implementationURL ;


signature:
public class ManagedClass { /** * Get implementation class constructor . Managed class mandates a single constructor with parameters , no matter if private
 * or formal parameters count . If both default constructor and constructor with parameters are defined this method returns
 * constructor with parameters . Returns null if implementation class is missing .
 * @ param implementationClass implementation class , possible null .
 * @ return implementation class constructor or null if given implementation class is null .
 * @ throws BugError if implementation class is an interface , primitive or array and has no constructor at all .
 * @ throws BugError if implementation class has more constructors with parameters . */
private static Constructor < ? > getDeclaredConstructor ( Class < ? > implementationClass ) { } }

implementation:
if ( implementationClass == null ) { return null ; } Constructor < ? > [ ] declaredConstructors = ( Constructor < ? > [ ] ) implementationClass . getDeclaredConstructors ( ) ; if ( declaredConstructors . length == 0 ) { throw new BugError ( "Invalid implementation class |%s|. Missing constructor." , implementationClass ) ; } Constructor < ? > constructor = null ; for ( Constructor < ? > declaredConstructor : declaredConstructors ) { // synthetic constructors are created by compiler to circumvent JVM limitations , JVM that is not evolving with
// the same speed as the language ; for example , to allow outer class to access private members on a nested class
// compiler creates a constructor with a single argument of very nested class type
if ( declaredConstructor . isSynthetic ( ) ) { continue ; } if ( declaredConstructor . getParameterTypes ( ) . length == 0 ) { continue ; } if ( declaredConstructor . getAnnotation ( Test . class ) != null ) { continue ; } if ( constructor != null ) { throw new BugError ( "Implementation class |%s| has not a single constructor with parameters." , implementationClass ) ; } constructor = declaredConstructor ; } if ( constructor == null ) { constructor = declaredConstructors [ 0 ] ; } constructor . setAccessible ( true ) ; return constructor ;


signature:
public class ManagedClass { /** * Scan class dependencies declared by { @ link Inject } annotation . This method scans all fields , no matter private , protected
 * or public . Anyway it is considered a bug if inject annotation is found on final or static field .
 * Returns a collection of reflective fields with accessibility set but in not particular order . If given class argument is
 * null returns empty collection .
 * @ param clazz class to scan dependencies for , null tolerated .
 * @ return dependencies collection , in no particular order .
 * @ throws BugError if inject annotation is used on final or static field . */
private static Collection < Field > scanDependencies ( Class < ? > clazz ) { } }

implementation: if ( clazz == null ) { return Collections . emptyList ( ) ; } Collection < Field > dependencies = new ArrayList < > ( ) ; for ( Field field : clazz . getDeclaredFields ( ) ) { if ( ! field . isAnnotationPresent ( Inject . class ) ) { continue ; } if ( Modifier . isFinal ( field . getModifiers ( ) ) ) { throw new BugError ( "Attempt to inject final field |%s|." , field . getName ( ) ) ; } if ( Modifier . isStatic ( field . getModifiers ( ) ) ) { throw new BugError ( "Attempt to inject static field |%s|." , field . getName ( ) ) ; } field . setAccessible ( true ) ; dependencies . add ( field ) ; } return dependencies ;


signature:
public class ManagedClass { /** * Initialize implementation class static , not final , fields . Static initializer reads name / value pairs from
 * < code > static - field < / code > configuration element , see sample below . String value is converted to instance field type using
 * { @ link Converter # asObject ( String , Class ) } utility . This means that configured value should be convertible to field type ,
 * otherwise { @ link ConverterException } is thrown .
 * In sample there is a < code > person < / code > managed instance that has a configuration section . Configuration declares three
 * static fields that will be initialized with defined values when managed class is created .
 * < pre >
 * & lt ; managed - classes & gt ;
 * & lt ; person class = " js . app . Person " / & gt ;
 * & lt ; / managed - classes & gt ;
 * & lt ; person & gt ;
 * & lt ; static - field name = ' name ' value = ' John Doe ' / & gt ;
 * & lt ; static - field name = ' age ' value = ' 54 ' / & gt ;
 * & lt ; static - field name = ' married ' value = ' false ' / & gt ;
 * & lt ; / person & gt ;
 * class Person {
 * private static String name ;
 * private static int age ;
 * private static boolean married ;
 * < / pre >
 * @ throws ConfigException if static field descriptor is invalid , field is missing or is instance field . */
private void initializeStaticFields ( ) throws ConfigException { } }

implementation: if ( config == null ) { return ; } for ( Config config : config . findChildren ( "static-field" ) ) { String fieldName = config . getAttribute ( "name" ) ; if ( fieldName == null ) { throw new ConfigException ( "Missing <name> attribute from static field initialization |%s|." , config . getParent ( ) ) ; } if ( ! config . hasAttribute ( "value" ) ) { throw new ConfigException ( "Missing <value> attribute from static field initialization |%s|." , config . getParent ( ) ) ; } Field field = Classes . getOptionalField ( implementationClass , fieldName ) ; if ( field == null ) { throw new ConfigException ( "Missing managed class static field |%s#%s|." , implementationClass , fieldName ) ; } int modifiers = field . getModifiers ( ) ; if ( ! Modifier . isStatic ( modifiers ) ) { throw new ConfigException ( "Attempt to execute static initialization on instance field |%s#%s|." , implementationClass , fieldName ) ; } Object value = config . getAttribute ( "value" , field . getType ( ) ) ; log . debug ( "Intialize static field |%s#%s| |%s|" , implementationClass , fieldName , value ) ; Classes . setFieldValue ( null , field , config . getAttribute ( "value" , field . getType ( ) ) ) ; }


signature:
public class ManagedClass { /** * Build and return this managed class string representation .
 * @ param descriptor managed class descriptor .
 * @ return this managed class string representation . */
private String buildStringRepresentation ( Config descriptor ) { } }

implementation: StringBuilder builder = new StringBuilder ( ) ; builder . append ( descriptor . getName ( ) ) ; builder . append ( ':' ) ; if ( implementationClass != null ) { builder . append ( implementationClass . getName ( ) ) ; builder . append ( ':' ) ; } for ( Class < ? > interfaceClass : interfaceClasses ) { builder . append ( interfaceClass . getName ( ) ) ; builder . append ( ':' ) ; } builder . append ( instanceType ) ; builder . append ( ':' ) ; builder . append ( instanceScope ) ; builder . append ( ':' ) ; builder . append ( remotelyAccessible ? "NET" : "LOCAL" ) ; if ( implementationURL != null ) { builder . append ( ':' ) ; builder . append ( implementationURL ) ; } return builder . toString ( ) ;


signature:
public class ManagedClass { /** * Get class annotation or null if none found . This getter uses extended annotation searching scope : it searches first on
 * given class then tries with all class interfaces . Note that only interfaces are used as alternative for annotation
 * search . Super class is not included .
 * Returns null if no annotation found on base class or interfaces .
 * @ param clazz base class to search for annotation ,
 * @ param annotationClass annotation to search for .
 * @ param < T > annotation type .
 * @ return annotation instance or null if none found . */
private static < T extends Annotation > T getAnnotation ( Class < ? > clazz , Class < T > annotationClass ) { } }

implementation: T annotation = clazz . getAnnotation ( annotationClass ) ; if ( annotation == null ) { for ( Class < ? > interfaceClass : clazz . getInterfaces ( ) ) { annotation = interfaceClass . getAnnotation ( annotationClass ) ; if ( annotation != null ) { break ; } } } return annotation ;


signature:
public class ManagedClass { /** * Test if class has requested annotation . This predicate uses extended annotation searching scope : it searches first on
 * given class then tries with all class interfaces . Note that only interfaces are used as alternative for annotation
 * search . Super class is not included .
 * Returns false if no annotation found on base class or interfaces .
 * @ param clazz base class to search for annotation ,
 * @ param annotationClass annotation to search for .
 * @ return true if annotation found . */
private static boolean hasAnnotation ( Class < ? > clazz , Class < ? extends Annotation > annotationClass ) { } }

implementation: Annotation annotation = clazz . getAnnotation ( annotationClass ) ; if ( annotation != null ) { return true ; } for ( Class < ? > interfaceClass : clazz . getInterfaces ( ) ) { annotation = interfaceClass . getAnnotation ( annotationClass ) ; if ( annotation != null ) { return true ; } } return false ;


signature:
public class ManagedClass { /** * Get method annotation or null if none found . This getter uses extended annotation searching scope : it searches first on
 * given method declaring class then tries with all class interfaces . Note that only interfaces are used as alternative for
 * method annotation search . Super class is not included .
 * Returns null if no method annotation found on base class or interfaces .
 * @ param method method to search for annotation ,
 * @ param annotationClass annotation to search for .
 * @ param < T > annotation type .
 * @ return annotation instance or null if none found . */
private static < T extends Annotation > T getAnnotation ( Method method , Class < T > annotationClass ) { } }

implementation: T annotation = method . getAnnotation ( annotationClass ) ; if ( annotation == null ) { for ( Class < ? > interfaceClass : method . getDeclaringClass ( ) . getInterfaces ( ) ) { try { annotation = interfaceClass . getMethod ( method . getName ( ) , method . getParameterTypes ( ) ) . getAnnotation ( annotationClass ) ; if ( annotation != null ) { return annotation ; } } catch ( NoSuchMethodException unused ) { } } } return annotation ;


signature:
public class ManagedClass { /** * Get Java reflective method from interface . This getter attempt to locate a method with the same signature as requested
 * base class method in any interface the declaring class may have . If no method found in interfaces or no interface present
 * return given base class method . If requested base class method is declared in multiple interfaces this getter returns the
 * first found but there is no guarantee for order .
 * @ param method base class method , not null .
 * @ return interface method or given base class method if no interface method found . */
private static Method getInterfaceMethod ( Method method ) { } }

implementation: for ( Class < ? > interfaceClass : method . getDeclaringClass ( ) . getInterfaces ( ) ) { try { return interfaceClass . getMethod ( method . getName ( ) , method . getParameterTypes ( ) ) ; } catch ( NoSuchMethodException unused ) { } } return method ;


signature:
public class ManagedClass { /** * Get class value of intercepted annotation of a given class . Returns null if given class has no { @ link Intercepted }
 * annotation .
 * @ param clazz annotated class .
 * @ return interceptor class or null if intercepted annotation is missing . */
private static Class < ? extends Interceptor > getInterceptorClass ( Class < ? > clazz ) { } }

implementation: Intercepted intercepted = getAnnotation ( clazz , Intercepted . class ) ; return intercepted != null ? intercepted . value ( ) : null ;


signature:
public class ManagedClass { /** * Get class value of intercepted annotation of a given method . Returns null if given method has no { @ link Intercepted }
 * annotation .
 * @ param method annotated method .
 * @ return interceptor class or null if intercepted annotation is missing . */
private static Class < ? extends Interceptor > getInterceptorClass ( Method method ) { } }

implementation: Intercepted intercepted = getAnnotation ( method , Intercepted . class ) ; return intercepted != null ? intercepted . value ( ) : null ;


signature:
public class TypeHandlerFactory { /** * Returns a new instance of < class > typeAdapter < / class > , passing
 * < class > baseTypeAdapter < / class > as the only constructor argument .
 * @ param typeAdapter subclass of { @ link TypeHandler }
 * which is used to create the new adapter .
 * @ param parameter column / row parameter
 * @ return an instance of { @ code typeAdapter } */
private TypeHandler < ? > instantiate ( Class < ? extends TypeHandler < ? > > typeAdapter , String parameter ) { } }

implementation: try { final Constructor < ? extends TypeHandler < ? > > constructor = typeAdapter . getConstructor ( String . class ) ; return constructor . newInstance ( parameter ) ; } catch ( final Exception e ) { throw new RuntimeException ( e ) ; }


signature:
public class TypeHandlerFactory { /** * Instantiates a new { @ code TypeAdapter } which is capable of handling
 * { @ code type } .
 * If no such adapter exists , the old one is returned .
 * @ param type { @ code Class } to process
 * @ param parameter Column / row parameter
 * @ return an instance of { @ code TypeAdapter } , either a specialized one ,
 * or { @ code typeAdapter } itself . */
public TypeHandler getHandler ( Class < ? > type , String parameter ) { } }

implementation: if ( type == null ) { return null ; } else if ( type . isArray ( ) ) { return new ArrayTypeHandler ( parameter , getHandler ( type . getComponentType ( ) , parameter ) ) ; } else if ( adapters . containsKey ( type ) ) { return instantiate ( adapters . get ( type ) , parameter ) ; } else { throw new IllegalArgumentException ( "Unknown type: " + type . getName ( ) ) ; }


signature:
public class TypeHandlerFactory { /** * Registers a new { @ code AbstractTypeAdapter } .
 * After registering an adapter , { @ link # getHandler ( Class , String ) }
 * is able to return it .
 * @ param adapterClass subclass of { @ code AbstractTypeAdapter } to register */
public void register ( Class < ? extends TypeHandler < ? > > adapterClass ) { } }

implementation: final Class < ? > targetType = ( ( TypeHandler < ? > ) instantiate ( adapterClass , null ) ) . getType ( ) ; adapters . put ( targetType , adapterClass ) ;


signature:
public class FitFileRunner { /** * Processes { @ code inputFile } , write output to { @ code outputFile }
 * and return the resulting counts using most of fit ' s default components .
 * @ param inputFile file to process
 * @ param outputFile file to write output to
 * @ return resulting counts */
@ Override public final Counts run ( final File inputFile , final File outputFile ) { } }

implementation: Counts result = null ; FileSystemDirectoryHelper dirHelper = new FileSystemDirectoryHelper ( ) ; RunnerHelper currentRunner = DependencyManager . getOrCreate ( RunnerHelper . class ) ; RunnerHelper helper = new RunnerHelper ( ) ; DependencyManager . inject ( RunnerHelper . class , helper ) ; helper . setFile ( dirHelper . rel2abs ( System . getProperty ( "user.dir" ) , inputFile . toString ( ) ) ) ; helper . setResultFile ( dirHelper . rel2abs ( System . getProperty ( "user.dir" ) , outputFile . toString ( ) ) ) ; helper . setRunner ( this ) ; helper . setHelper ( dirHelper ) ; try { result = process ( inputFile , outputFile ) ; } catch ( Exception e ) { System . err . printf ( "%s while processing %s -> %s%n" , e , inputFile , outputFile ) ; System . err . println ( e . getMessage ( ) ) ; e . printStackTrace ( ) ; } finally { DependencyManager . inject ( RunnerHelper . class , currentRunner ) ; } return result ;


signature:
public class FormObject { /** * Set value to object field identified by object property path . Form this class perspective an object is a graph of value
 * types . A value type is a primitive value or a related boxing class . Also any class that can be converted to a primitive
 * are included ; for example { @ link File } or { @ link URL } are value types since can be converted to / from strings . Opposite to
 * value types are compound entities , that is , objects , arrays and collections that aggregates value types or other compound
 * entities .
 * To sum up , an object is a graph with compound entities and value types as nodes where value types are leafs . The
 * < code > propertyPath < / code > is the path through graph nodes till reach the value type and basically is a dot separated
 * field names list .
 * @ param propertyPath object property path ,
 * @ param value value to set .
 * @ throws ConverterException if value is primitive and fail to convert to field type .
 * @ throws IllegalAccessException this exception is required by reflective field signature but never thrown . */
private void setValue ( String propertyPath , Object value ) throws ConverterException , IllegalAccessException { } }

implementation: List < String > nodeIDs = Strings . split ( propertyPath , '.' ) ; int lastNodeIndex = nodeIDs . size ( ) - 1 ; Node node = new ObjectNode ( object ) ; for ( int index = 0 ; index < lastNodeIndex ; index ++ ) { node = node . getChild ( nodeIDs . get ( index ) ) ; if ( node == null ) { return ; } } node . setValue ( nodeIDs . get ( lastNodeIndex ) , value ) ;


signature:
public class FormObject { /** * Return field class or actual type argument if given field is a list .
 * @ param field Java reflective class field .
 * @ return field type . */
private static Class < ? > type ( Field field ) { } }

implementation:
if ( Types . isKindOf ( field . getType ( ) , List . class ) ) { // for the purpose of this implementation only first parameterized
// type matters , as result from list declaration List < E >
return ( Class < ? > ) ( ( ParameterizedType ) field . getGenericType ( ) ) . getActualTypeArguments ( ) [ 0 ] ; } return field . getType ( ) ;


signature:
public class DependencyProcessor { /** * Get dependency value of requested type . See class description for a discussion about supported types and circular
 * dependencies .
 * @ param hostManagedClass managed class defining the context on which dependency is resolved ,
 * @ param type dependency type .
 * @ return dependency instance , reused from container caches or fresh created .
 * @ throws BugError if dependency value cannot be created or circular dependency is detected . */
@ SuppressWarnings ( "unchecked" ) protected static Object getDependencyValue ( ManagedClassSPI hostManagedClass , Class < ? > type ) { } }

implementation:
Stack < Class < ? > > stackTrace = dependenciesStack . get ( ) ; if ( stackTrace == null ) { stackTrace = new Stack < > ( ) ; dependenciesStack . set ( stackTrace ) ; } ContainerSPI container = hostManagedClass . getContainer ( ) ; if ( stackTrace . contains ( type ) ) { try { // add current dependency class to reveal what dependency from stack is circular
stackTrace . add ( type ) ; StringBuilder builder = new StringBuilder ( ) ; builder . append ( "Circular dependency. Dependencies trace follows:\r\n" ) ; for ( Class < ? > stackTraceClass : stackTrace ) { builder . append ( "\t- " ) ; builder . append ( stackTraceClass . getName ( ) ) ; builder . append ( "\r\n" ) ; } log . error ( builder . toString ( ) ) ; throw new BugError ( "Circular dependency for |%s|." , type . getName ( ) ) ; } finally { // takes care to current thread stack trace is removed
dependenciesStack . remove ( ) ; } } stackTrace . push ( type ) ; try { ManagedClassSPI dependencyManagedClass = container . getManagedClass ( type ) ; if ( isProxyRequired ( hostManagedClass , dependencyManagedClass ) ) { // if scope proxy is required returns a Java Proxy handled by ScopeProxyHandler
ScopeProxyHandler < ? > handler = new ScopeProxyHandler < > ( container , type ) ; return Proxy . newProxyInstance ( dependencyManagedClass . getImplementationClass ( ) . getClassLoader ( ) , dependencyManagedClass . getInterfaceClasses ( ) , handler ) ; } Object value = container . getOptionalInstance ( ( Class < ? super Object > ) type ) ; if ( value != null ) { // if dependency type is a managed class returns it value from factory
return value ; } if ( Types . isKindOf ( type , AppFactory . class ) ) { // handle ApFactory and its hierarchy since it is a special case
return container ; } if ( Classes . isInstantiable ( type ) ) { // if requested type is instantiable POJO create a new empty instance of requested type
return Classes . newInstance ( type ) ; } // TODO : test value instance of
// if FactoryBean consider it as factory and substitute value
// e . g . value = ( ( FactoryBean ) value ) . getInstance ( value . getClass ( ) )
// all attempts to create dependency value has fallen
throw new BugError ( "Dependency |%s| not resolved for |%s|." , type . getName ( ) , hostManagedClass ) ; } finally { stackTrace . pop ( ) ; // do not remove stack trace after outermost call finished , i . e . when stack trace is empty
// leave it on thread local for reuse , in order to avoid unnecessary object creation
}


signature:
public class DependencyProcessor { /** * Compare host and dependency managed classes scope and decide if scope proxy is required . Current implementation enable
 * scope proxy only when dependency has { @ link InstanceScope # SESSION } scope .
 * @ param hostManagedClass managed class defining the context on which dependency is resolved ,
 * @ param dependencyManagedClass dependency managed class , possible null .
 * @ return true if scope proxy is required . */
private static boolean isProxyRequired ( ManagedClassSPI hostManagedClass , ManagedClassSPI dependencyManagedClass ) { } }

implementation: if ( dependencyManagedClass != null ) { InstanceScope dependencyScope = dependencyManagedClass . getInstanceScope ( ) ; if ( InstanceScope . THREAD . equals ( dependencyScope ) ) { return InstanceScope . APPLICATION . equals ( hostManagedClass . getInstanceScope ( ) ) ; } return InstanceScope . SESSION . equals ( dependencyScope ) ; } return false ;


signature:
public class GeneratedFile { /** * Compares the content of the temporary file with the possibly existing target file . If both are equal the temporary file is deleted .
 * Otherwise the old target file is deleted and the new generated file is renamed . This prevents time stamp changes for the target file
 * if nothing changed since the last generation . */
public final void persist ( ) { } }

implementation:
if ( persisted ) { // Do nothing if already done
return ; } try { // Compare new and old file
if ( FileUtils . contentEquals ( tmpFile , file ) ) { LOG . debug ( "Omitted: {} {}" , getPath ( ) , logInfo ) ; if ( ! tmpFile . delete ( ) ) { tmpFile . deleteOnExit ( ) ; } } else { if ( file . exists ( ) && ! file . delete ( ) ) { throw new IOException ( "Wasn't able to delete file " + file ) ; } if ( ! tmpFile . renameTo ( file ) ) { throw new IOException ( "Wasn't able to rename temporary file " + tmpFile + " to " + file ) ; } LOG . info ( "Generated: {} {}" , getPath ( ) , logInfo ) ; } persisted = true ; } catch ( final IOException ex ) { throw new RuntimeException ( "Error comparing content: tmp=" + tmpFile + ", target=" + file + logInfo , ex ) ; }


signature:
public class PollingEndpointImpl { /** * Provides an observable stream of element states . Compares entities using
 * { @ link Object # equals ( java . lang . Object ) } to detect changes .
 * @ param pollingInterval The interval in milliseconds in which to send
 * requests to the server .
 * @ param endCondition An optional predicate determining which entity state
 * ends the polling process .
 * @ param scheduler The scheduler used to run the background thread .
 * @ return An observable stream of element states . */
StoppableObservable < TEntity > getObservable ( Scheduler scheduler ) { } }

implementation: return runAsync ( scheduler , ( rx . Observer < ? super TEntity > observer , Subscription subscription ) -> { TEntity previousEntity ; try { previousEntity = read ( ) ; } catch ( IOException | IllegalArgumentException | IllegalAccessException ex ) { observer . onError ( ex ) ; return ; } observer . onNext ( previousEntity ) ; while ( endCondition == null || ! endCondition . test ( previousEntity ) ) { try { sleep ( pollingInterval * 1000 ) ; } catch ( InterruptedException ex ) { } if ( subscription . isUnsubscribed ( ) ) { break ; } TEntity newEntity ; try { newEntity = read ( ) ; } catch ( IOException | IllegalArgumentException | IllegalAccessException ex ) { observer . onError ( ex ) ; return ; } if ( ! newEntity . equals ( previousEntity ) ) { observer . onNext ( newEntity ) ; } previousEntity = newEntity ; } observer . onCompleted ( ) ; } ) ;


signature:
public class AbstractEndpoint { /** * Registers one or more default links for a specific relation type . These
 * links are used when no links with this relation type are provided by the
 * server .
 * This method is not thread - safe ! Call this before performing any requests .
 * @ param rel The relation type of the links to add .
 * @ param hrefs The hrefs of links relative to this endpoint ' s URI . Use
 * < code > null < / code > or an empty list to remove all previous entries for the
 * relation type .
 * @ see Endpoint # getLinks ( java . lang . String )
 * @ see Endpoint # getLinksWithTitles ( java . lang . String )
 * @ see Endpoint # link ( java . lang . String ) */
public final void setDefaultLink ( String rel , String ... hrefs ) { } }

implementation: if ( hrefs == null || hrefs . length == 0 ) { defaultLinks . remove ( rel ) ; } else { defaultLinks . put ( rel , stream ( hrefs ) . map ( uri :: resolve ) . collect ( toSet ( ) ) ) ; }


signature:
public class AbstractEndpoint { /** * Registers a default link template for a specific relation type . This
 * template is used when no template with this relation type is provided by
 * the server .
 * This method is not thread - safe ! Call this before performing any requests .
 * @ param rel The relation type of the link template to add .
 * @ param href The href of the link template relative to this endpoint ' s
 * URI . Use < code > null < / code > to remove any previous entry for the relation
 * type .
 * @ see Endpoint # linkTemplate ( java . lang . String ) */
public final void setDefaultLinkTemplate ( String rel , String href ) { } }

implementation: if ( href == null ) { defaultLinkTemplates . remove ( rel ) ; } else { defaultLinkTemplates . put ( rel , href ) ; }


signature:
public class AbstractEndpoint { /** * Executes a REST request and wraps HTTP status codes in appropriate
 * { @ link Exception } types .
 * @ param request The request to execute .
 * @ return The HTTP response to the request .
 * @ throws IOException Network communication failed .
 * @ throws IllegalArgumentException { @ link HttpStatus # SC _ BAD _ REQUEST }
 * @ throws IllegalAccessException { @ link HttpStatus # SC _ UNAUTHORIZED } or
 * { @ link HttpStatus # SC _ FORBIDDEN }
 * @ throws FileNotFoundException { @ link HttpStatus # SC _ NOT _ FOUND } or
 * { @ link HttpStatus # SC _ GONE }
 * @ throws IllegalStateException
 * { @ link HttpStatus # SC _ CONFLICT } , { @ link HttpStatus # SC _ PRECONDITION _ FAILED }
 * or { @ link HttpStatus # SC _ REQUESTED _ RANGE _ NOT _ SATISFIABLE }
 * @ throws RuntimeException Other non - success status code . */
protected HttpResponse executeAndHandle ( Request request ) throws IOException , IllegalArgumentException , IllegalAccessException , FileNotFoundException , IllegalStateException { } }

implementation: HttpResponse response = execute ( request ) ; handleResponse ( response , request ) ; return response ;


signature:
public class AbstractEndpoint { /** * Executes a REST request adding any configured { @ link # defaultHeaders } .
 * @ param request The request to execute .
 * @ return The HTTP response to the request .
 * @ throws IOException Network communication failed .
 * @ throws RuntimeException Other non - success status code . */
protected HttpResponse execute ( Request request ) throws IOException { } }

implementation: defaultHeaders . forEach ( request :: addHeader ) ; return executor . execute ( request ) . returnResponse ( ) ;


signature:
public class AbstractEndpoint { /** * Handles the response of a REST request and wraps HTTP status codes in
 * appropriate { @ link Exception } types .
 * @ param response The response to handle .
 * @ param request The original request the reponse is for .
 * @ throws IOException Network communication failed .
 * @ throws IllegalArgumentException { @ link HttpStatus # SC _ BAD _ REQUEST }
 * @ throws IllegalAccessException { @ link HttpStatus # SC _ UNAUTHORIZED } or
 * { @ link HttpStatus # SC _ FORBIDDEN }
 * @ throws FileNotFoundException { @ link HttpStatus # SC _ NOT _ FOUND } or
 * { @ link HttpStatus # SC _ GONE }
 * @ throws IllegalStateException
 * { @ link HttpStatus # SC _ CONFLICT } , { @ link HttpStatus # SC _ PRECONDITION _ FAILED }
 * or { @ link HttpStatus # SC _ REQUESTED _ RANGE _ NOT _ SATISFIABLE }
 * @ throws RuntimeException Other non - success status code . */
protected void handleResponse ( HttpResponse response , Request request ) throws IOException , IllegalArgumentException , IllegalAccessException , FileNotFoundException , IllegalStateException { } }

implementation: handleLinks ( response ) ; handleCapabilities ( response ) ; handleErrors ( response , request ) ;


signature:
public class AbstractEndpoint { /** * Wraps HTTP status codes in appropriate { @ link Exception } types .
 * @ param response The response to check for errors .
 * @ param request The original request the reponse is for .
 * @ throws IOException Network communication failed .
 * @ throws IllegalArgumentException { @ link HttpStatus # SC _ BAD _ REQUEST }
 * @ throws IllegalAccessException { @ link HttpStatus # SC _ UNAUTHORIZED } or
 * { @ link HttpStatus # SC _ FORBIDDEN }
 * @ throws FileNotFoundException { @ link HttpStatus # SC _ NOT _ FOUND } or
 * { @ link HttpStatus # SC _ GONE }
 * @ throws IllegalStateException
 * { @ link HttpStatus # SC _ CONFLICT } , { @ link HttpStatus # SC _ PRECONDITION _ FAILED }
 * or { @ link HttpStatus # SC _ REQUESTED _ RANGE _ NOT _ SATISFIABLE }
 * @ throws RuntimeException Other non - success status code . */
protected void handleErrors ( HttpResponse response , Request request ) throws IOException , IllegalArgumentException , IllegalAccessException , FileNotFoundException , IllegalStateException { } }

implementation:
StatusLine statusLine = response . getStatusLine ( ) ; if ( statusLine . getStatusCode ( ) <= 299 ) { return ; } String message = request + " responded with " + statusLine . getStatusCode ( ) + " " + statusLine . getReasonPhrase ( ) ; HttpEntity entity = response . getEntity ( ) ; String body ; if ( entity == null ) { body = null ; } else { body = EntityUtils . toString ( entity ) ; Header contentType = entity . getContentType ( ) ; if ( ( contentType != null ) && contentType . getValue ( ) . startsWith ( "application/json" ) ) { try { JsonNode messageNode = serializer . readTree ( body ) . get ( "message" ) ; if ( messageNode != null ) { message = messageNode . asText ( ) ; } } catch ( JsonProcessingException ex ) { } } } Exception inner = ( body == null ) ? null : new HttpException ( body ) ; switch ( statusLine . getStatusCode ( ) ) { case HttpStatus . SC_BAD_REQUEST : throw new IllegalArgumentException ( message , inner ) ; case HttpStatus . SC_UNAUTHORIZED : // throw new InvalidCredentialException ( message ) ;
throw new IllegalAccessException ( message ) ; case HttpStatus . SC_FORBIDDEN : throw new IllegalAccessException ( message ) ; case HttpStatus . SC_NOT_FOUND : case HttpStatus . SC_GONE : throw new FileNotFoundException ( message ) ; case HttpStatus . SC_CONFLICT : throw new IllegalStateException ( message , inner ) ; case HttpStatus . SC_PRECONDITION_FAILED : // throw new VersionNotFoundException ( message , inner ) ;
throw new IllegalStateException ( message , inner ) ; case HttpStatus . SC_REQUESTED_RANGE_NOT_SATISFIABLE : // throw new IndexOutOfBoundsException ( message ) ;
throw new IllegalStateException ( message , inner ) ; case HttpStatus . SC_REQUEST_TIMEOUT : // throw new TimeoutException ( message ) ;
default : throw new RuntimeException ( message , inner ) ; }


signature:
public class AbstractEndpoint { /** * Handles links embedded in an HTTP response .
 * @ param response The response to check for links . */
@ SuppressWarnings ( "LocalVariableHidesMemberVariable" ) private void handleLinks ( HttpResponse response ) { } }

implementation:
Map < String , Map < URI , String > > links = new HashMap < > ( ) ; Map < String , String > linkTemplates = new HashMap < > ( ) ; handleHeaderLinks ( response , links , linkTemplates ) ; HttpEntity entity = response . getEntity ( ) ; if ( entity != null ) { Header contentType = entity . getContentType ( ) ; if ( ( contentType != null ) && contentType . getValue ( ) . startsWith ( "application/json" ) ) { try { handleBodyLinks ( serializer . readTree ( entity . getContent ( ) ) , links , linkTemplates ) ; } catch ( IOException ex ) { throw new RuntimeException ( ) ; // Body error handling is done elsewhere
} } } this . links = unmodifiableMap ( links ) ; this . linkTemplates = unmodifiableMap ( linkTemplates ) ;


signature:
public class AbstractEndpoint { /** * Handles links embedded in HTTP response headers .
 * @ param response The response to check for links .
 * @ param links A dictionary to add found links to .
 * @ param linkTemplates A dictionary to add found link templates to . */
protected void handleHeaderLinks ( HttpResponse response , Map < String , Map < URI , String > > links , Map < String , String > linkTemplates ) { } }

implementation: getLinkHeaders ( response ) . forEach ( header -> { if ( header . getRel ( ) == null ) { return ; } if ( header . isTemplated ( ) ) { linkTemplates . put ( header . getRel ( ) , header . getHref ( ) ) ; } else { getOrAdd ( links , header . getRel ( ) ) . put ( uri . resolve ( header . getHref ( ) ) , header . getTitle ( ) ) ; } } ) ;


signature:
public class AbstractEndpoint { /** * Handles links embedded in JSON response bodies .
 * @ param jsonBody The body to check for links .
 * @ param links A dictionary to add found links to .
 * @ param linkTemplates A dictionary to add found link templates to . */
protected void handleBodyLinks ( JsonNode jsonBody , Map < String , Map < URI , String > > links , Map < String , String > linkTemplates ) { } }

implementation: if ( jsonBody . getNodeType ( ) != JsonNodeType . OBJECT ) { return ; } JsonNode linksNode = jsonBody . get ( "_links" ) ; if ( linksNode == null ) { linksNode = jsonBody . get ( "links" ) ; } if ( linksNode == null ) { return ; } linksNode . fields ( ) . forEachRemaining ( x -> { String rel = x . getKey ( ) ; Map < URI , String > linksForRel = getOrAdd ( links , rel ) ; switch ( x . getValue ( ) . getNodeType ( ) ) { case ARRAY : x . getValue ( ) . forEach ( subobj -> { if ( subobj . getNodeType ( ) == JsonNodeType . OBJECT ) { parseLinkObject ( rel , ( ObjectNode ) subobj , linksForRel , linkTemplates ) ; } } ) ; break ; case OBJECT : parseLinkObject ( rel , ( ObjectNode ) x . getValue ( ) , linksForRel , linkTemplates ) ; break ; } } ) ;


signature:
public class AbstractEndpoint { /** * Parses a JSON object for link information .
 * @ param rel The relation type of the link .
 * @ param obj The JSON object to parse for link information .
 * @ param linksForRel A dictionary to add found links to . Maps hrefs to
 * titles .
 * @ param linkTemplates A dictionary to add found link templates to . Maps
 * rels to templated hrefs . */
private void parseLinkObject ( String rel , ObjectNode obj , Map < URI , String > linksForRel , Map < String , String > linkTemplates ) { } }

implementation: JsonNode href = obj . findValue ( "href" ) ; if ( href == null ) { return ; } JsonNode templated = obj . findValue ( "templated" ) ; if ( templated != null && templated . isBoolean ( ) && templated . asBoolean ( ) ) { linkTemplates . put ( rel , href . asText ( ) ) ; } else { JsonNode title = obj . findValue ( "title" ) ; linksForRel . put ( uri . resolve ( href . asText ( ) ) , ( title != null && title . getNodeType ( ) == JsonNodeType . STRING ) ? title . asText ( ) : null ) ; }


signature:
public class AbstractEndpoint { /** * Returns the element with the specified key from the map . Creates , adds
 * and returns a new element if no match was found .
 * @ param map The map to look in .
 * @ param key The key to look for .
 * @ return The existing or new element . */
private static Map < URI , String > getOrAdd ( Map < String , Map < URI , String > > map , String key ) { } }

implementation: Map < URI , String > value = map . get ( key ) ; if ( value == null ) { map . put ( key , value = new HashMap < > ( ) ) ; } return value ;


signature:
public class AbstractEndpoint { /** * Handles allowed HTTP methods and other capabilities reported by the
 * server .
 * @ param response The response to check for the " Allow " header . */
protected void handleCapabilities ( HttpResponse response ) { } }

implementation: allowedMethods = unmodifiableSet ( stream ( response . getHeaders ( "Allow" ) ) . filter ( x -> x . getName ( ) . equals ( "Allow" ) ) . flatMap ( x -> stream ( x . getElements ( ) ) ) . map ( x -> x . getName ( ) ) . collect ( toSet ( ) ) ) ;


signature:
public class AbstractEndpoint { /** * Shows whether the server has indicated that a specific HTTP method is
 * currently allowed .
 * Uses cached data from last response .
 * @ param method The HTTP method ( e . g . GET , POST , . . . ) to check .
 * @ return An indicator whether the method is allowed . If no request has been
 * sent yet or the server did not specify allowed methods
 * { @ link Optional # empty ( ) } is returned . */
protected Optional < Boolean > isMethodAllowed ( String method ) { } }

implementation: if ( allowedMethods . isEmpty ( ) ) { return Optional . empty ( ) ; } return Optional . of ( allowedMethods . contains ( method ) ) ;


signature:
public class ResultSetWrapper { /** * Generates an array which represents the whole { @ code ResultSet } .
 * Each element equates to one row in the { @ code ResultSet } .
 * The elements have public fields with the same name as the { @ code ResultSet } columns .
 * The { @ link ScientificDouble } class is automatically used .
 * They can be read them using reflections .
 * @ return array of dynamic objects
 * @ throws SQLException thrown , if the { @ code ResultSet } throws an Exception */
public final Object [ ] getRows ( ) throws SQLException { } }

implementation: List < Object > result = new ArrayList < > ( ) ; while ( rows . size ( ) > 0 ) { Object [ ] copy = rows . remove ( 0 ) ; Object o = createContainerObject ( ) ; for ( int i = 0 ; i < columnCount ; ++ i ) { setObjectValue ( o , names . get ( i ) , copy [ i ] ) ; } result . add ( o ) ; } while ( resultSet . next ( ) ) { Object o = createContainerObject ( ) ; for ( int col = 0 ; col < columnCount ; ++ col ) { setObjectValue ( o , names . get ( col ) , resultSet . getObject ( col + 1 ) ) ; } result . add ( o ) ; } return result . toArray ( ) ;


signature:
public class ThrowableUtils { /** * Concatenates the { @ link Throwable # getLocalizedMessage ( ) } s of the entire
 * { @ link Throwable # getCause ( ) } tree .
 * @ param throwable The top - level throwable to walk for messages .
 * @ return A newline separated list of messages . */
@ SuppressWarnings ( "ThrowableResultIgnored" ) public static String getFullMessage ( Throwable throwable ) { } }

implementation: StringBuilder builder = new StringBuilder ( ) ; do { builder . append ( throwable . getLocalizedMessage ( ) ) . append ( "\n" ) ; throwable = throwable . getCause ( ) ; } while ( throwable != null ) ; return builder . toString ( ) ;


signature:
public class RemoteInstanceFactory { /** * Create a new instance for given remote managed class . Managed class should be declared as remote into class descriptor .
 * Also { @ link ManagedClassSPI # getImplementationURL ( ) } should be not null , that is , implementation URL should be present
 * into class descriptor . Returned value is a Java proxy that delegates a HTTP - RMI client .
 * This factory method does not check managed class argument validity . It should be not null and configured for remote
 * invocation .
 * @ param managedClass managed class ,
 * @ param args remote instance factory does not support constructor arguments .
 * @ param < T > managed instance type . */
@ SuppressWarnings ( "unchecked" ) @ Override public < T > T newInstance ( ManagedClassSPI managedClass , Object ... args ) { } }

implementation: if ( args . length > 0 ) { throw new IllegalArgumentException ( "REMOTE instance factory does not support arguments." ) ; } return getRemoteInstance ( managedClass . getImplementationURL ( ) , ( Class < ? super T > ) managedClass . getInterfaceClass ( ) ) ;


signature:
public class RemoteInstanceFactory { /** * Alternative to { @ link # newInstance ( ManagedClassSPI , Object . . . ) } when implementation URL is obtained at run - time , perhaps
 * from user interface . Returned value is a Java proxy that delegates a HTTP - RMI client . This method is designed
 * specifically for { @ link AppFactory # getRemoteInstance ( String , Class ) } .
 * This factory method does not check arguments validity . Both should be not null and interface class should be an actual
 * Java interface .
 * @ param implementationURL the URL of remote implementation ,
 * @ param interfaceClass interface implemented by remote class .
 * @ param < T > managed class implementation .
 * @ return remote class proxy instance .
 * @ throws UnsupportedProtocolException if URL protocol is not supported or arguments are otherwise not valid or null - in
 * which case root cause has details about erroneous argument . */
@ Override public < T > T getRemoteInstance ( String implementationURL , Class < ? super T > interfaceClass ) throws UnsupportedProtocolException { } }

implementation: if ( implementationURL == null ) { throw new UnsupportedProtocolException ( new NullPointerException ( "Null remote implementation URL." ) ) ; } String protocol = Strings . getProtocol ( implementationURL ) ; if ( protocol == null ) { throw new UnsupportedProtocolException ( new MalformedURLException ( "Protocol not found on " + implementationURL ) ) ; } RemoteFactory remoteFactory = remoteFactories . get ( protocol ) ; if ( remoteFactory == null ) { throw new UnsupportedProtocolException ( "No remote factory registered for protocol |%s|." , protocol ) ; } return remoteFactory . getRemoteInstance ( implementationURL , interfaceClass ) ;


signature:
public class Container { /** * Register all instance post - processors . */
protected void registerInstanceProcessor ( ) { } }

implementation: registerInstanceProcessor ( new InstanceFieldsInjectionProcessor ( ) ) ; registerInstanceProcessor ( new InstanceFieldsInitializationProcessor ( ) ) ; registerInstanceProcessor ( new ConfigurableInstanceProcessor ( ) ) ; registerInstanceProcessor ( new PostConstructInstanceProcessor ( ) ) ; registerInstanceProcessor ( new CronMethodsProcessor ( cronManager ) ) ; registerInstanceProcessor ( new LoggerInstanceProcessor ( ) ) ;


signature:
public class Container { /** * Register scope factory for the instance scope returned by { @ link ScopeFactory # getInstanceScope ( ) } .
 * @ param scopeFactory scope factory instance , possible null for local scope .
 * @ throws BugError if instance scope is already registered . */
protected void registerScopeFactory ( ScopeFactory scopeFactory ) { } }

implementation: if ( scopeFactory == null ) { log . debug ( "Register null scope factory to |%s|." , InstanceScope . LOCAL ) ; scopeFactories . put ( InstanceScope . LOCAL , null ) ; return ; } final InstanceScope instanceScope = scopeFactory . getInstanceScope ( ) ; log . debug ( "Register scope factory |%s| to |%s|." , scopeFactory . getClass ( ) , instanceScope ) ; if ( scopeFactories . put ( instanceScope , scopeFactory ) != null ) { throw new BugError ( "Attempt to override instance scope |%s|." , instanceScope ) ; }


signature:
public class Container { /** * Register instance factory to requested instance type .
 * @ param instanceType instance type used as key for instance factory ,
 * @ param instanceFactory instance factory .
 * @ throws BugError if instance type is already registered . */
protected void registerInstanceFactory ( InstanceType instanceType , InstanceFactory instanceFactory ) { } }

implementation: log . debug ( "Register instance factory |%s| to |%s|." , instanceFactory . getClass ( ) , instanceType ) ; if ( instanceFactories . put ( instanceType , instanceFactory ) != null ) { throw new BugError ( "Attempt to override instance type |%s|." , instanceType ) ; }


signature:
public class Container { /** * Register instance processor . Only a single instance per processor class is allowed .
 * @ param instanceProcessor instance processor .
 * @ throws BugError if instance processor class is already registered .
 * @ see # instanceProcessors */
protected void registerInstanceProcessor ( InstanceProcessor instanceProcessor ) { } }

implementation: for ( InstanceProcessor existingInstanceProcessoor : instanceProcessors ) { if ( existingInstanceProcessoor . getClass ( ) . equals ( instanceProcessor . getClass ( ) ) ) { throw new BugError ( "Attempt to override instance processor |%s|." , instanceProcessor . getClass ( ) ) ; } } log . debug ( "Register instance processor |%s|." , instanceProcessor . getClass ( ) ) ; instanceProcessors . add ( instanceProcessor ) ;


signature:
public class Container { /** * Register global processors for managed classes . Post - processors are singletons and only one post - processor instance of a
 * type is allowed .
 * @ param classProcessor managed class post - processor .
 * @ throws BugError if class processor class is already registered .
 * @ see # classProcessors */
protected void registerClassProcessor ( ClassProcessor classProcessor ) { } }

implementation: for ( ClassProcessor existingClassProcessoor : classProcessors ) { if ( existingClassProcessoor . getClass ( ) . equals ( classProcessor . getClass ( ) ) ) { throw new BugError ( "Attempt to override class processor |%s|." , classProcessor . getClass ( ) ) ; } } log . debug ( "Register class processor |%s|." , classProcessor . getClass ( ) ) ; classProcessors . add ( classProcessor ) ;


signature:
public class Container { /** * Create all managed instances registered to this container via external application descriptor . See
 * < a href = " # descriptors " > Descriptors < / a > for details about application and class descriptors .
 * @ param config container configuration object .
 * @ throws ConfigException if container configuration fails .
 * @ throws BugError for insane condition that prevent managed classes initialization . */
@ Override public void config ( Config config ) throws ConfigException { } }

implementation:
log . trace ( "config(Config)" ) ; // normalized class descriptors with overrides resolves ; should preserve order from external files
// it is legal for application descriptor to override already defined class descriptor
// for example user defined ro . gnotis . Fax2MailApp overrides library declared js . core . App
// < app interface = ' js . core . App ' class = ' ro . gnotis . Fax2MailApp ' / >
// when found an overridden class descriptor replace it with most recent version
// only class descriptors with single interface can be overridden
List < Config > classDescriptors = new ArrayList < > ( ) ; for ( Config descriptorsSection : config . findChildren ( "managed-classes" , "web-sockets" ) ) { CLASS_DESCRIPTORS : for ( Config classDescriptor : descriptorsSection . getChildren ( ) ) { if ( ! classDescriptor . hasChildren ( ) ) { if ( ! classDescriptor . hasAttribute ( "interface" ) ) { classDescriptor . setAttribute ( "interface" , classDescriptor . getAttribute ( "class" ) ) ; } String interfaceClass = classDescriptor . getAttribute ( "interface" ) ; for ( int i = 0 ; i < classDescriptors . size ( ) ; ++ i ) { if ( classDescriptors . get ( i ) . hasAttribute ( "interface" , interfaceClass ) ) { log . debug ( "Override class descriptor for interface |%s|." , interfaceClass ) ; classDescriptors . set ( i , classDescriptor ) ; continue CLASS_DESCRIPTORS ; } } } classDescriptors . add ( classDescriptor ) ; } } // second step is to actually populate the classes pool from normalized class descriptors list
for ( Config classDescriptor : classDescriptors ) { // create managed class , a single one per class descriptor , even if there are multiple interfaces
// if multiple interfaces register the same managed class multiple times , once per interface
// this way , no mater which interface is used to retrieve the instance it uses in the end the same managed class
ManagedClass managedClass = new ManagedClass ( this , classDescriptor ) ; log . debug ( "Register managed class |%s|." , managedClass ) ; for ( Class < ? > interfaceClass : managedClass . getInterfaceClasses ( ) ) { classesPool . put ( interfaceClass , managedClass ) ; } for ( ClassProcessor classProcessor : classProcessors ) { classProcessor . postProcessClass ( managedClass ) ; } } convertersInitialization ( config ) ; pojoStaticInitialization ( config ) ; // special handling for this container instance accessed via application context
// need to ensure this container instance is reused and not to create a new one
ManagedClassSPI appContext = classesPool . get ( AppContext . class ) ; // application context can be null on tests
// also on tests application context interface can be implemented by mock class not in container hierarchy
if ( appContext != null && Types . isKindOf ( appContext . getImplementationClass ( ) , ContainerSPI . class ) ) { log . debug ( "Persist container instance on application scope." ) ; scopeFactories . get ( InstanceScope . APPLICATION ) . persistInstance ( new InstanceKey ( appContext . getKey ( ) ) , this ) ; }


signature:
public class Container { /** * Ensure all managed classes with managed life cycle are instantiated . Invoked at a final stage of container initialization
 * this method checks every managed class that implements { @ link ManagedLifeCycle } interface and ensure is instantiated .
 * Takes care to instantiate , configure if the case , and execute post - construct in the order from application descriptor .
 * This is critical for assuring that { @ link App } is created first ; { @ link App } class descriptor is declared first into
 * application descriptor .
 * Note that this method does not explicitly execute { @ link ManagedLifeCycle # postConstruct ( ) } hooks ; this hooks are actually
 * executed by instance processor , see { link { @ link PostConstructInstanceProcessor } . */
@ SuppressWarnings ( "unchecked" ) public void start ( ) { } }

implementation:
log . trace ( "start()" ) ; // classes pool is not sorted ; it is a hash map for performance reasons
// also , a managed class may appear multiple times if have multiple interfaces
// bellow sorted set is used to ensure ascending order on managed classes instantiation
// comparison is based on managed class key that is created incrementally
Set < ManagedClassSPI > sortedClasses = new TreeSet < > ( new Comparator < ManagedClassSPI > ( ) { @ Override public int compare ( ManagedClassSPI o1 , ManagedClassSPI o2 ) { // compare first with second to ensure ascending sorting
return o1 . getKey ( ) . compareTo ( o2 . getKey ( ) ) ; } } ) ; for ( ManagedClassSPI managedClass : classesPool . values ( ) ) { if ( managedClass . isAutoInstanceCreation ( ) ) { sortedClasses . add ( managedClass ) ; } // process only implementations of managed life cycle interface
// if ( Types . isKindOf ( managedClass . getImplementationClass ( ) , ManagedLifeCycle . class ) ) {
// sortedClasses . add ( managedClass ) ;
} for ( ManagedClassSPI managedClass : sortedClasses ) { // call getInstance to ensure managed instance with managed life cycle is started
// if there are more than one single interface peek one , no matter which ; the simple way is to peek the first
// getInstance ( ) will create instance only if not already exist ; returned value is ignored
log . debug ( "Create managed instance with managed life cycle |%s|." , managedClass . getInterfaceClass ( ) ) ; getInstance ( ( Class < ? super Object > ) managedClass . getInterfaceClass ( ) ) ; }


signature:
public class Container { /** * Destroy container and release caches , factories and processors . This is container global clean - up invoked at application
 * unload ; after executing this method no managed instance can be created or reused . Attempting to use { @ link AppFactory }
 * after container destroy may lead to not predictable behavior .
 * Before caches clean - up , this method invokes { @ link ManagedPreDestroy } on all managed instances that are active , that is ,
 * cached in all scope factories . Takes care to execute pre - destroy in reverse order from application descriptor
 * declarations . This ensure { @ link App } is destroyed last since App class descriptor is declared first into application
 * descriptor . */
public void destroy ( ) { } }

implementation:
log . trace ( "destroy()" ) ; // cron manager should be destroyed first to avoid invoking cron methods on cleaned managed instance
cronManager . destroy ( ) ; // classes pool is not sorted ; it is a hash map for performance reasons
// also , a managed class may appear multiple times if have multiple interfaces
// bellow sorted set is used to ensure reverse order on managed classes destruction
// comparison is based on managed class key that is created incrementally
Set < ManagedClassSPI > sortedClasses = new TreeSet < > ( new Comparator < ManagedClassSPI > ( ) { @ Override public int compare ( ManagedClassSPI o1 , ManagedClassSPI o2 ) { // compare second with first to ensure descending sorting
return o2 . getKey ( ) . compareTo ( o1 . getKey ( ) ) ; } } ) ; for ( ManagedClassSPI managedClass : classesPool . values ( ) ) { // process only implementations of managed pre - destroy interface
if ( Types . isKindOf ( managedClass . getImplementationClass ( ) , ManagedPreDestroy . class ) ) { sortedClasses . add ( managedClass ) ; } } for ( ManagedClassSPI managedClass : sortedClasses ) { ScopeFactory scopeFactory = scopeFactories . get ( managedClass . getInstanceScope ( ) ) ; InstanceKey instanceKey = new InstanceKey ( managedClass . getKey ( ) ) ; Object instance = scopeFactory . getInstance ( instanceKey ) ; if ( instance == null ) { continue ; } // sorted managed classes contains only implementations of pre - destroy interface
// in case instance is a Java Proxy takes care to execute pre - destroy hook on wrapped instance
// in order to avoid adding container services to this finalization hook
ManagedPreDestroy managedInstance = ( ManagedPreDestroy ) Classes . unproxy ( instance ) ; log . debug ( "Pre-destroy managed instance |%s|." , managedInstance . getClass ( ) ) ; try { managedInstance . preDestroy ( ) ; } catch ( Throwable t ) { log . dump ( String . format ( "Managed instance |%s| pre-destroy fail:" , instance . getClass ( ) ) , t ) ; } } for ( ScopeFactory scopeFactory : scopeFactories . values ( ) ) { // local scope has null factory
if ( scopeFactory != null ) { scopeFactory . clear ( ) ; } } classesPool . clear ( ) ; instanceProcessors . clear ( ) ; scopeFactories . clear ( ) ; instanceFactories . clear ( ) ;


signature:
public class Container { /** * INSTANCE RETRIEVAL ALGORITHM */
@ Override public < T > T getInstance ( Class < ? super T > interfaceClass , Object ... args ) { } }

implementation: Params . notNull ( interfaceClass , "Interface class" ) ; ManagedClassSPI managedClass = classesPool . get ( interfaceClass ) ; if ( managedClass == null ) { throw new BugError ( "No managed class associated with interface class |%s|." , interfaceClass ) ; } InstanceKey instanceKey = new InstanceKey ( managedClass . getKey ( ) ) ; return getInstance ( managedClass , instanceKey , args ) ;


signature:
public class Container { /** * Utility method that implements the core of managed instances retrieval algorithm . This method gets existing managed
 * instance from container caches or creates a new instance . If instance is fresh created add instance services via
 * registered instance processors .
 * Here is managed instance retrieval algorithm part implemented by this method .
 * < ol >
 * < li > get scope and instance factories for managed class instance scope and type ; if managed class instance scope is local
 * there is no scope factory ,
 * < li > if scope factory is null execute local instance factory , that creates a new instance , and returns it ; applies
 * arguments processing on local instance but not instance processors ,
 * < li > if there is scope factory do next steps into synchronized block ,
 * < li > try to retrieve instance from scope factory cache ,
 * < li > if no cached instance pre - process arguments , create a new instance using instance factory and persist instance on
 * scope factory ,
 * < li > end synchronized block ,
 * < li > arguments pre - processing takes care to inject constructor dependencies ,
 * < li > if new instance is created execute instance post - processors into registration order .
 * < / ol >
 * @ param managedClass managed class for which instance is to be retrieved ,
 * @ param instanceKey managed instance key ,
 * @ param args optional constructor arguments , used only if new local instance is created .
 * @ param < T > managed instance type .
 * @ return managed instance , created on the fly or reused from caches , but never null .
 * @ throws InvocationException if instance is local and constructor fails .
 * @ throws NoProviderException if interface is a service and no provider found on run - time .
 * @ throws ConverterException if attempt to initialize a field with a type for which there is no converter ,
 * @ throws BugError if dependency value cannot be created or circular dependency is detected .
 * @ throws BugError if instance configuration fails either due to bad configuration object or fail on configuration user
 * defined logic .
 * @ throws BugError if instance post - construction fails due to exception of user defined logic .
 * @ throws BugError if attempt to assign field to not POJO type . */
@ SuppressWarnings ( "unchecked" ) private < T > T getInstance ( ManagedClassSPI managedClass , InstanceKey instanceKey , Object ... args ) { } }

implementation:
// if ( managedClass . getInstanceType ( ) . isREMOTE ( ) ) {
// return getRemoteInstance ( new URL ( managedClass . getImplementationURL ( ) ) , ( Class < ? super T > )
// managedClass . getInterfaceClass ( ) ) ;
ScopeFactory scopeFactory = scopeFactories . get ( managedClass . getInstanceScope ( ) ) ; InstanceFactory instanceFactory = instanceFactories . get ( managedClass . getInstanceType ( ) ) ; if ( scopeFactory == null ) { args = argumentsProcessor . preProcessArguments ( managedClass , args ) ; return instanceFactory . newInstance ( managedClass , args ) ; } boolean postProcessingEnabled = false ; Object instance = null ; synchronized ( scopeMutex ) { instance = scopeFactory . getInstance ( instanceKey ) ; if ( instance == null ) { postProcessingEnabled = true ; args = argumentsProcessor . preProcessArguments ( managedClass , args ) ; instance = instanceFactory . newInstance ( managedClass , args ) ; scopeFactory . persistInstance ( instanceKey , instance ) ; } } if ( ! postProcessingEnabled ) { return ( T ) instance ; } // post - processors operate on bare POJO instances but is possible for instance factory to return a Java Proxy
// if instance is a Java Proxy that uses InstanceInvocationHandler extract wrapped POJO instance
// if instance is a Java Proxy that does not use InstanceInvocationHandler post - processing is not performed at all
// if instance is not a Java Proxy execute post - processing on it
Object pojoInstance = null ; if ( instance instanceof Proxy ) { if ( Proxy . getInvocationHandler ( instance ) instanceof InstanceInvocationHandler ) { InstanceInvocationHandler < T > handler = ( InstanceInvocationHandler < T > ) Proxy . getInvocationHandler ( instance ) ; pojoInstance = handler . getWrappedInstance ( ) ; } } else { pojoInstance = instance ; } if ( pojoInstance != null ) { for ( InstanceProcessor instanceProcessor : instanceProcessors ) { instanceProcessor . postProcessInstance ( managedClass , pojoInstance ) ; } } return ( T ) instance ;


signature:
public class Container { /** * Declarative converters registration . This utility scans for < code > converters < / code > section into given configuration
 * object and register converters via { @ link ConverterRegistry # registerConverter ( Class , Class ) } .
 * Configuration converter section should respect below syntax .
 * < pre >
 * & lt ; converters & gt ;
 * & lt ; type class = " java . io . File " converter = " js . converter . FileConverter " / & gt ;
 * & lt ; type class = " java . net . URL " converter = " js . converter . UrlConverter " / & gt ;
 * & lt ; type class = " java . util . TimeZone " converter = " js . converter . TimeZoneConverter " / & gt ;
 * & lt ; / converters & gt ;
 * < / pre >
 * @ param config configuration object .
 * @ throws ConfigException if declared < code > class < / code > or < code > converter < / code > not found on run - time class path . */
private static void convertersInitialization ( Config config ) throws ConfigException { } }

implementation: Config section = config . getChild ( "converters" ) ; if ( section == null ) { return ; } for ( Config el : section . findChildren ( "type" ) ) { String className = el . getAttribute ( "class" ) ; Class < ? > valueType = Classes . forOptionalName ( className ) ; if ( valueType == null ) { throw new ConfigException ( "Invalid converter configuration. Value type class |%s| not found." , className ) ; } String converterName = el . getAttribute ( "converter" ) ; Class < ? extends Converter > converterClass = Classes . forOptionalName ( converterName ) ; if ( converterClass == null ) { throw new ConfigException ( "Invalid converter configuration. Converter class |%s| not found." , converterName ) ; } ConverterRegistry . getInstance ( ) . registerConverter ( valueType , converterClass ) ; }


signature:
public class Container { /** * Plain Java objects static initialization . Inject static fields value into arbitrary Java classes . Note that this
 * mechanism is not related to managed classes ; it acts on regular Java classes and only on static fields .
 * Here is a sample configuration for Java objects static injection . There is < code > pojo - classes < / code > section that list
 * all involved classes , with aliases . For every Java class alias there is a section with the same name that has
 * < code > static < / code > name / value elements related by name to class static fields .
 * < pre >
 * & lt ; pojo - classes & gt ;
 * & lt ; email - reader class = " com . mobile . EmailReader " / & gt ;
 * & lt ; / pojo - classes & gt ;
 * & lt ; email - reader & gt ;
 * & lt ; static - field name = " USER _ NAME " value = " johndoe " / & gt ;
 * & lt ; static - field name = " PASSWORD " value = " secret " / & gt ;
 * & lt ; / email - reader & gt ;
 * < / pre >
 * Static values from above configuration sample are injected into class static fields with the same name . String value from
 * configuration object is converted to field type .
 * < pre >
 * public class EmailReader {
 * private static String USER _ NAME ;
 * private static String PASSWORD ;
 * < / pre >
 * This initializer has side effects : it loads configured Java classes at container startup .
 * @ param config configuration object .
 * @ throws ConfigException if configuration object is not valid or class or field not found .
 * @ throws ConverterException if there is no converter registered for a specific field type . */
private static void pojoStaticInitialization ( Config config ) throws ConfigException { } }

implementation: Config pojoClassesSection = config . getChild ( "pojo-classes" ) ; if ( pojoClassesSection == null ) { return ; } for ( Config pojoClassElement : pojoClassesSection . getChildren ( ) ) { String pojoClassName = pojoClassElement . getAttribute ( "class" ) ; if ( pojoClassName == null ) { throw new ConfigException ( "Invalid POJO class element. Missing <class> attribute." ) ; } Config configSection = config . getChild ( pojoClassElement . getName ( ) ) ; Class < ? > pojoClass = Classes . forOptionalName ( pojoClassName ) ; if ( pojoClass == null ) { throw new ConfigException ( "Missing configured POJO class |%s|." , pojoClassName ) ; } if ( configSection == null ) { continue ; } for ( Config staticElement : configSection . findChildren ( "static-field" ) ) { String fieldName = staticElement . getAttribute ( "name" ) ; if ( fieldName == null ) { throw new ConfigException ( "Missing <name> attribute from static field initialization |%s|." , configSection ) ; } if ( ! staticElement . hasAttribute ( "value" ) ) { throw new ConfigException ( "Missing <value> attribute from static field initialization |%s|." , configSection ) ; } Field staticField = Classes . getOptionalField ( pojoClass , fieldName ) ; if ( staticField == null ) { throw new ConfigException ( "Missing POJO static field |%s#%s|." , pojoClassName , fieldName ) ; } int modifiers = staticField . getModifiers ( ) ; if ( ! Modifier . isStatic ( modifiers ) ) { throw new ConfigException ( "Attempt to execute POJO |%s| static initialization on instance field |%s|." , pojoClassName , fieldName ) ; } Object value = staticElement . getAttribute ( "value" , staticField . getType ( ) ) ; log . debug ( "Intialize static field |%s#%s| |%s|" , pojoClassName , fieldName , value ) ; Classes . setFieldValue ( null , staticField , value ) ; } }


signature:
public class ParameterizedTemplateModel { /** * Adds an argument to the template . If the list of arguments does not exist , it will be created .
 * @ param argument
 * Arguments to add . */
public final void addArgument ( @ NotNull final Argument argument ) { } }

implementation: if ( arguments == null ) { arguments = new ArrayList < Argument > ( ) ; } arguments . add ( argument ) ;


signature:
public class ParameterizedTemplateModel { /** * Returns the list of target files . Either by using the producer or by simply returning the internal list .
 * @ return Target files - Never NULL and has at least one entry . */
public final List < TargetFile > createTargetFileList ( ) { } }

implementation: if ( tflProducerConfig == null ) { LOG . info ( "Using target file list: {} elements" , targetFiles . size ( ) ) ; return targetFiles ; } final TargetFileListProducer producer = tflProducerConfig . getTargetFileListProducer ( ) ; LOG . info ( "Using target file list producer: {}" , producer . getClass ( ) . getName ( ) ) ; return producer . createTargetFiles ( ) ;


signature:
public class ParameterizedTemplateModel { /** * Marshals the object to XML .
 * @ param file
 * File to write the instance to . */
public final void writeToXml ( final File file ) { } }

implementation: try { final JaxbHelper helper = new JaxbHelper ( ) ; helper . write ( this , file , createJaxbContext ( ) ) ; } catch ( final MarshalObjectException ex ) { throw new RuntimeException ( ex ) ; }


signature:
public class ParameterizedTemplateModel { /** * Marshals the object to an XML String .
 * @ return XML String . */
public final String toXml ( ) { } }

implementation: try { final JaxbHelper helper = new JaxbHelper ( ) ; return helper . write ( this , createJaxbContext ( ) ) ; } catch ( final MarshalObjectException ex ) { throw new RuntimeException ( ex ) ; }


signature:
public class ParameterizedTemplateModel { /** * Marshals the object to XML .
 * @ param writer
 * Writer to write the instance to . */
public final void writeToXml ( final Writer writer ) { } }

implementation: try { final JaxbHelper helper = new JaxbHelper ( ) ; helper . write ( this , writer , createJaxbContext ( ) ) ; } catch ( final MarshalObjectException ex ) { throw new RuntimeException ( ex ) ; }


signature:
public class ParameterizedTemplateModel { /** * Initializes the model .
 * @ param context
 * Current context .
 * @ param vars
 * Variables to use . */
public final void init ( final SrcGen4JContext context , final Map < String , String > vars ) { } }

implementation: if ( template != null ) { template = Utils4J . replaceVars ( template , vars ) ; } if ( arguments != null ) { for ( final Argument argument : arguments ) { argument . init ( vars ) ; } } if ( targetFiles != null ) { for ( final TargetFile targetFile : targetFiles ) { targetFile . init ( vars ) ; } } if ( tflProducerConfig != null ) { tflProducerConfig . init ( context , this , vars ) ; }


signature:
public class ParameterizedTemplateModel { /** * Checks if this model has a reference to the given template file .
 * @ param templateDir
 * Directory where all template files are located - Cannot be NULL .
 * @ param templateFile
 * Template file to check - Cannot be NULL .
 * @ return If the template is referenced TRUE else FALSE . */
public final boolean hasReferenceTo ( final File templateDir , final File templateFile ) { } }

implementation: final String p1 = Utils4J . getCanonicalPath ( new File ( templateDir , template ) ) ; final String p2 = Utils4J . getCanonicalPath ( templateFile ) ; return p1 . equals ( p2 ) ;


signature:
public class ParameterizedTemplateModel { /** * Creates an instance by reading the XML from a reader .
 * @ param reader
 * Reader to use .
 * @ return New instance . */
public static ParameterizedTemplateModel create ( final Reader reader ) { } }

implementation: try { final JaxbHelper helper = new JaxbHelper ( ) ; final ParameterizedTemplateModel pc = helper . create ( reader , createJaxbContext ( ) ) ; Contract . requireValid ( pc ) ; return pc ; } catch ( final UnmarshalObjectException ex ) { throw new RuntimeException ( ex ) ; }


signature:
public class ParameterizedTemplateModel { /** * Creates an instance by reading the XML from a file .
 * @ param file
 * File to read .
 * @ return New instance . */
public static ParameterizedTemplateModel create ( final File file ) { } }

implementation: try { final JaxbHelper helper = new JaxbHelper ( ) ; final ParameterizedTemplateModel pc = helper . create ( file , createJaxbContext ( ) ) ; pc . setFile ( file ) ; Contract . requireValid ( pc ) ; return pc ; } catch ( final UnmarshalObjectException ex ) { throw new RuntimeException ( ex ) ; }


signature:
public class InstanceFieldsInjectionProcessor { /** * Inject dependencies described by given managed class into related managed instance . For every dependency field retrieve
 * its value using { @ link DependencyProcessor # getDependencyValue ( ManagedClassSPI , Class ) } and inject it reflexively .
 * @ param managedClass managed class ,
 * @ param instance instance of given managed class .
 * @ throws BugError if a field dependency cannot be resolved . */
@ Override public void postProcessInstance ( ManagedClassSPI managedClass , Object instance ) { } }

implementation:
if ( instance == null ) { // null instance is silently ignored since container ensure not null instance argument
return ; } for ( Field dependency : managedClass . getDependencies ( ) ) { if ( dependency . isSynthetic ( ) ) { // it seems there can be injected fields , created via byte code manipulation , when run with test coverage active
// not clear why and how but was consistently observed on mock object from unit test run with coverage
continue ; } Classes . setFieldValue ( instance , dependency , getDependencyValue ( managedClass , dependency . getType ( ) ) ) ; }


signature:
public class ManagedMethod { /** * Set this method request URI path , that is , the path component by which this method is referred into request URI . If given
 * request URI path is null uses method name converted to dashed case .
 * @ param requestPath request URI path for this method , possible null . */
void setRequestPath ( String requestPath ) { } }

implementation: this . requestPath = requestPath != null ? requestPath : Strings . toDashCase ( method . getName ( ) ) ;


signature:
public class ManagedMethod { /** * Invoke managed method and applies method level services . Delegates this managed method { @ link # invoker } ; accordingly
 * selected strategy invoker can be { @ link DefaultInvoker } or { @ link InterceptedInvoker } , if this managed method is
 * annotated with { @ link Interceptor } . Also takes care to update { @ link # meter } .
 * @ param object managed instance against which method is executed ,
 * @ param args optional managed method invocation arguments .
 * @ param < T > returned value type .
 * @ return value returned by method or null for void .
 * @ throws AuthorizationException if method is private and { @ link SecurityContext } is not authenticated .
 * @ throws IllegalArgumentException if invocation arguments does not match method signature .
 * @ throws InvocationException if method execution fails for whatever reason . */
@ SuppressWarnings ( "unchecked" ) @ Override public < T > T invoke ( Object object , Object ... args ) throws AuthorizationException , IllegalArgumentException , InvocationException { } }

implementation:
if ( remotelyAccessible && ! isPublic ( ) && ! container . isAuthenticated ( ) ) { log . info ( "Reject not authenticated access to |%s|." , method ) ; throw new AuthorizationException ( ) ; } // arguments processor converts < args > to empty array if it is null
// it can be null if on invocation chain there is Proxy invoked with no arguments
args = argumentsProcessor . preProcessArguments ( this , args ) ; if ( object instanceof Proxy ) { // if object is a Java Proxy does not apply method services implemented by below block
// instead directly invoke Java method on the Proxy instance
// container will call again this method but with the real object instance , in which case executes the next logic
try { return ( T ) method . invoke ( object , args ) ; } catch ( InvocationTargetException e ) { throw new InvocationException ( e . getTargetException ( ) ) ; } catch ( IllegalAccessException e ) { throw new BugError ( "Illegal access on method with accessibility set true." ) ; } } if ( meter == null ) { try { return ( T ) invoker . invoke ( object , args ) ; } catch ( InvocationTargetException e ) { throw new InvocationException ( e . getTargetException ( ) ) ; } catch ( IllegalAccessException e ) { throw new BugError ( "Illegal access on method with accessibility set true." ) ; } } meter . incrementInvocationsCount ( ) ; meter . startProcessing ( ) ; T returnValue = null ; try { returnValue = ( T ) invoker . invoke ( object , args ) ; } catch ( InvocationTargetException e ) { meter . incrementExceptionsCount ( ) ; throw new InvocationException ( e . getTargetException ( ) ) ; } catch ( IllegalAccessException e ) { // this condition is a bug ; do not increment exceptions count
throw new BugError ( "Illegal access on method with accessibility set true." ) ; } meter . stopProcessing ( ) ; return returnValue ;


signature:
public class WaitForResult { /** * Invokes the method multiple times , either until it returns true , or
 * until maxtime is over . After each invoke , the class waits
 * { @ code sleepTime } milliseconds .
 * @ param target Object which receives the call .
 * @ param method Method to invoke on { @ code target } .
 * @ param maxTime Maximum time to wait before causing a failure .
 * @ param sleepTime Time to sleep between method calls . */
public void wait ( Object target , Method method , long maxTime , long sleepTime ) { } }

implementation: long remaining = maxTime ; lastCallWasSuccessful = invokeMethod ( target , method ) ; while ( ! lastCallWasSuccessful && remaining > 0 ) { systemTime . sleep ( sleepTime ) ; remaining -= sleepTime ; lastCallWasSuccessful = invokeMethod ( target , method ) ; } lastElapsedTime = maxTime - remaining ;


signature:
public class FormIteratorImpl { /** * Test if there are more parts on this form iterator . This implementation has side effects : it takes care to close form
 * parts while traversing form iterator .
 * @ return true if there is at least one available form part . */
@ Override public boolean hasNext ( ) { } }

implementation: try { if ( currentPart != null ) { currentPart . close ( ) ; } if ( ! fileItemIterator . hasNext ( ) ) { return false ; } FileItemStream fileItemStream = fileItemIterator . next ( ) ; if ( fileItemStream . isFormField ( ) ) { currentPart = new FormFieldImpl ( fileItemStream ) ; } else { currentPart = new UploadStreamImpl ( fileItemStream ) ; } return true ; } catch ( IOException | FileUploadException e ) { log . error ( e ) ; } return false ;


signature:
public class ServerEncoders { /** * Get arguments reader able to process arguments from HTTP request accordingly expected argument types . If HTTP request has
 * no content type returns { @ link EncoderKey # APPLICATION _ JSON } reader , that is , tiny container default content type is JSON .
 * This departs from HTTP standard that mandates using bytes stream when no content type is provided on request .
 * If formal parameters are empty returns { @ link EmptyArgumentsReader } . If formal parameters are provided attempts to
 * retrieve a reader for expected argument types . If none found try using content type solely .
 * @ param httpRequest HTTP request carrying arguments to read ,
 * @ param formalParameters expected argument types , possible empty .
 * @ return arguments reader , never null .
 * @ throws IllegalArgumentException if no reader found for requested HTTP request and expected argument types . */
@ Override public ArgumentsReader getArgumentsReader ( HttpServletRequest httpRequest , Type [ ] formalParameters ) { } }

implementation: if ( formalParameters . length == 0 ) { return EmptyArgumentsReader . getInstance ( ) ; } if ( httpRequest . getQueryString ( ) != null ) { return readers . get ( null ) ; } return getArgumentsReader ( httpRequest . getContentType ( ) , formalParameters [ 0 ] ) ;


signature:
public class ServerEncoders { /** * Get arguments reader for requested content and parameter types . This factory method tries to retrieve a reader for
 * expected parameter type . If none found it tries using content type solely .
 * If content type is null this utility method returns { @ link EncoderKey # APPLICATION _ JSON } reader since tiny container
 * default content type is JSON . This departs from HTTP standard that mandates using bytes stream when no content type is
 * provided on request .
 * @ param contentType content type , possible null ,
 * @ param parameterType parameter type .
 * @ return reader instance , never null .
 * @ throws IllegalArgumentException if no reader found for requested content and parameter types . */
private ArgumentsReader getArgumentsReader ( String contentType , Type parameterType ) { } }

implementation: if ( contentType == null ) { return readers . get ( EncoderKey . APPLICATION_JSON ) ; } EncoderKey key = new EncoderKey ( ContentType . valueOf ( contentType ) , parameterType ) ; ArgumentsReader reader = readers . get ( key ) ; if ( reader != null ) { return reader ; } key = new EncoderKey ( ContentType . valueOf ( contentType ) ) ; reader = readers . get ( key ) ; if ( reader == null ) { throw new IllegalArgumentException ( "Unsupported content type |%s|. There is no arguments reader registered for it." , key ) ; } return reader ;


signature:
public class ServerEncoders { /** * Determine content type usable to retrieve a writer able to handle given object value . This method is used in tandem with
 * { @ link # getValueWriter ( ContentType ) } .
 * There is a heuristic to determine content type based on object value class . If no suitable content type found returns
 * { @ link ContentType # APPLICATION _ JSON } .
 * @ param value object value .
 * @ return content type for given object value . */
@ Override public ContentType getContentTypeForValue ( Object value ) { } }

implementation: if ( value instanceof Document ) { return ContentType . TEXT_XML ; } if ( value instanceof StreamHandler ) { return ContentType . APPLICATION_STREAM ; } return ContentType . APPLICATION_JSON ;


signature:
public class ServerEncoders { /** * Get return value writer able to handle requested content type . Content type argument should identify a registered value
 * writer . If no writer found throws bug error .
 * Recommend way to use this method is to provide content type instance returned by { @ link # getContentTypeForValue ( Object ) } .
 * < pre >
 * Object value = . . .
 * ContentType contentType = encoders . getContentTypeForValue ( value ) ;
 * ValueWriter writer = encoders . getValueWriter ( contentType ) ;
 * < / pre >
 * @ param contentType content type for return value .
 * @ return return value writer , never null .
 * @ throws BugError if no value writer registered for requested content type . */
@ Override public ValueWriter getValueWriter ( ContentType contentType ) { } }

implementation: ValueWriter writer = writers . get ( contentType ) ; if ( writer == null ) { throw new BugError ( "No return value writer for content type |%s|." , contentType ) ; } return writer ;


signature:
public class PrimitiveFixture { /** * answer comparisons / / / / / */
public void check ( FitCell cell , String value ) { } }

implementation: if ( cell . getFitValue ( ) . equals ( value ) ) { cell . right ( ) ; } else { cell . wrong ( value ) ; }


signature:
public class AbstractStreamEndpoint { /** * Provides an observable stream of elements .
 * @ param startIndex The index of the first element to return in the stream .
 * Use negative values to start counting from the end of the stream .
 * @ param scheduler The scheduler used to run the background thread .
 * @ return An observable stream of elements . */
StoppableObservable < TEntity > getObservable ( final long startIndex , Scheduler scheduler ) { } }

implementation:
return runAsync ( scheduler , ( rx . Observer < ? super TEntity > observer , Subscription subscription ) -> { long currentStartIndex = startIndex ; while ( ! subscription . isUnsubscribed ( ) ) { PartialResponse < TEntity > response ; try { response = ( currentStartIndex >= 0 ) ? readRange ( currentStartIndex , null ) : readRange ( null , - currentStartIndex ) ; } catch ( IllegalStateException ex ) { // No new data available yet , keep polling
continue ; } catch ( IOException | IllegalArgumentException | IllegalAccessException error ) { observer . onError ( error ) ; return ; } response . getElements ( ) . stream ( ) . forEach ( observer :: onNext ) ; if ( response . isEndReached ( ) ) { observer . onCompleted ( ) ; return ; } // Continue polling for more data
currentStartIndex = response . getTo ( ) + 1 ; } } ) ;


signature:
public class InstanceScope { /** * Create a scope instance from its string value . */
@ SuppressWarnings ( "unchecked" ) @ Override public < T > T asObject ( String string , Class < T > valueType ) { } }

implementation: return ( T ) new InstanceScope ( string ) ;


signature:
public class DateTypeHandler { /** * Parses a string and converts it into a { @ code java . util . Date } object .
 * @ param s { @ code String } which will be converted
 * @ return { @ code java . util . Date } object which is represented by { @ code s } . */
@ Override public final Date unsafeParse ( final String s ) throws ParseException { } }

implementation: return dateFitDateHelper . parse ( s , parameter ) ;


signature:
public class ContextParamProcessor { /** * Initialize field from named context parameter .
 * @ param field field to be initialized , both class and instance fields accepted ,
 * @ param parameterName name for context parameter ,
 * @ param instance optional instance , null for class fields . */
private void setField ( Field field , String parameterName , Object instance ) { } }

implementation: final Object value = context . getProperty ( parameterName , field . getType ( ) ) ; try { field . set ( instance , value ) ; } catch ( Exception e ) { throw new BugError ( e ) ; }


signature:
public class ChameriaWebView { /** * Save dialog requested ( unsupported content ) .
 * @ param reply the url */
public void save ( QNetworkReply reply ) { } }

implementation: m_logger . info ( "Unsupported Content : " + reply . url ( ) . toString ( ) + " - Download request" ) ; m_factory . save ( reply ) ;


signature:
public class LogHelper { /** * Adds a new CaptureAppender to an existing logger .
 * @ param logger logger to use
 * @ param appenderName name of an existing appender which will be captured */
public void addCaptureToLogger ( final AppenderAttachable logger , final String appenderName ) { } }

implementation: Appender currentAppender = logger . getAppender ( appenderName ) ; Appender captureAppender = CaptureAppender . newAppenderFrom ( currentAppender ) ; logger . addAppender ( captureAppender ) ;


signature:
public class LogHelper { /** * Returns the CaptureAppender which captures < code > appenderName < / code > .
 * @ param logger logger to use
 * @ param appenderName name of existing appender
 * @ return responsible CaptureAppender */
public Appender getCaptureAppender ( final AppenderAttachable logger , final String appenderName ) { } }

implementation: return logger . getAppender ( CaptureAppender . getAppenderNameFor ( appenderName ) ) ;


signature:
public class LogHelper { /** * Removes a CaptureAppender from a logger .
 * @ param logger logger to use
 * @ param appenderName name of the appender which is captured */
public void remove ( final AppenderAttachable logger , final String appenderName ) { } }

implementation: logger . removeAppender ( CaptureAppender . getAppenderNameFor ( appenderName ) ) ;


signature:
public class LogHelper { /** * Deletes all cached log entries .
 * @ param logger logger to use
 * @ param appenderName name of the appender which will be cleared */
public void clear ( final AppenderAttachable logger , final String appenderName ) { } }

implementation: ( ( CaptureAppender ) logger . getAppender ( CaptureAppender . getAppenderNameFor ( appenderName ) ) ) . clear ( ) ;


signature:
public class MultipartMixedArgumentsReader { /** * Read mixed body entities from HTTP request , creating and initializing arguments accordingly given formal parameters . The
 * number and order of arguments from multipart mixed message should respect formal parameter types . Also stream argument ,
 * if present , should be a single one and the last on arguments list .
 * @ param httpRequest HTTP request ,
 * @ param formalParameters formal parameter types .
 * @ return arguments array .
 * @ throws IOException if reading from request input stream fails .
 * @ throws IllegalArgumentException if arguments from HTTP request cannot be parsed .
 * @ throws IllegalArgumentException if content type for a mixed entity body is not supported .
 * @ throws IllegalArgumentException if there is a stream argument but is not the last on arguments list . */
@ Override public Object [ ] read ( HttpServletRequest httpRequest , Type [ ] formalParameters ) throws IOException , IllegalArgumentException { } }

implementation:
try { Object [ ] arguments = new Object [ formalParameters . length ] ; int argumentIndex = 0 ; ServletFileUpload multipart = new ServletFileUpload ( ) ; FileItemIterator iterator = multipart . getItemIterator ( httpRequest ) ; FileItemStream fileItemStream = null ; while ( iterator . hasNext ( ) ) { fileItemStream = iterator . next ( ) ; String contentType = fileItemStream . getContentType ( ) ; Type parameterType = formalParameters [ argumentIndex ] ; ArgumentPartReader reader = argumentsReaderFactory . getArgumentPartReader ( contentType , parameterType ) ; boolean streamArgument = StreamFactory . isStream ( parameterType ) ; ArgumentPartReader argumentPartReader = ( ArgumentPartReader ) reader ; InputStream inputStream = streamArgument ? new LazyFileItemStream ( fileItemStream ) : fileItemStream . openStream ( ) ; arguments [ argumentIndex ] = argumentPartReader . read ( inputStream , parameterType ) ; ++ argumentIndex ; // stream argument should be last on mixed arguments list
// save it to local thread storage for clean - up after arguments processed by application
if ( streamArgument ) { threadLocal . set ( inputStream ) ; break ; } inputStream . close ( ) ; } if ( argumentIndex != formalParameters . length ) { throw new IllegalArgumentException ( "Not all parameters processed due to stream argument that is not the last on arguments list." ) ; } return arguments ; } catch ( FileUploadException e ) { throw new IOException ( e . getMessage ( ) ) ; }


signature:
public class ConnectionImpl { /** * AutoCloseable */
@ Override public void close ( ) throws java . sql . SQLException { } }

implementation: if ( ! this . conn . isClosed ( ) ) { ConnectionImpl outer = this . outer ; this . conn . close ( ) ; this . outer = null ; CONNECTION_HOLDER . set ( outer ) ; }


signature:
public class AbstractEMFParser { /** * Parses all model files in the directories and all resources . y */
protected final void parseModel ( ) { } }

implementation:
if ( ( fileExtensions == null ) || ( fileExtensions . size ( ) == 0 ) ) { throw new IllegalStateException ( "No file extensions for EMF model files set!" ) ; } // Drop previous resource set
resourceSet = new ResourceSetImpl ( ) ; error = false ; parseDirs ( ) ; parseResources ( ) ;


signature:
public class AbstractEMFParser { /** * Tries to resolve all proxies . */
protected final void resolveProxies ( ) { } }

implementation: final List < String > unresolved = new ArrayList < String > ( ) ; if ( ! resolvedAllProxies ( unresolved , 0 ) ) { LOG . warn ( "Could not resolve the following proxies ({}):" , unresolved . size ( ) ) ; for ( final String ref : unresolved ) { LOG . warn ( "Not found: {}" , ref ) ; } final Iterator < Notifier > it = resourceSet . getAllContents ( ) ; while ( it . hasNext ( ) ) { final Notifier next = it . next ( ) ; if ( next instanceof EObject ) { final EObject obj = ( EObject ) next ; if ( obj . eIsProxy ( ) ) { try { it . remove ( ) ; } catch ( final UnsupportedOperationException ex ) { LOG . error ( "Could not remove proxy: " + obj , ex ) ; } } } } }