Input:
Scan annotations for managed classes that requires implementation . Annotations are processed only for managed classes that have { @link #implementationClass } that is primary source scanned for annotation . If an annotation is not present into implementation class try to find it on interface ( s ) . See <a href = #annotations > Annotations< / a > section from class description . [CODESPLIT] private void scanAnnotations ( ) { // set remote type and request URI path from @Remote, @Controller or @Service
 boolean remoteType = false ; Controller controllerAnnotation = getAnnotation ( implementationClass , Controller . class ) ; if ( controllerAnnotation != null ) { remoteType = true ; requestPath = controllerAnnotation . value ( ) ; } Service serviceAnnotation = getAnnotation ( implementationClass , Service . class ) ; if ( serviceAnnotation != null ) { remoteType = true ; requestPath = serviceAnnotation . value ( ) ; } Remote remoteAnnotation = getAnnotation ( implementationClass , Remote . class ) ; if ( remoteAnnotation != null ) { remoteType = true ; } RequestPath requestPathAnnotation = getAnnotation ( implementationClass , RequestPath . class ) ; if ( requestPathAnnotation != null ) { requestPath = requestPathAnnotation . value ( ) ; } if ( requestPath != null && requestPath . isEmpty ( ) ) { requestPath = null ; } if ( remoteType ) { remotelyAccessible = true ; } // set transactional and immutable type
 boolean transactionalType = hasAnnotation ( implementationClass , Transactional . class ) ; boolean immutableType = hasAnnotation ( implementationClass , Immutable . class ) ; if ( ! transactionalType && immutableType ) { throw new BugError ( "@Immutable annotation without @Transactional on class |%s|." , implementationClass . getName ( ) ) ; } if ( transactionalType && ! instanceType . isPROXY ( ) ) { throw new BugError ( "@Transactional requires |%s| type but found |%s| on |%s|." , InstanceType . PROXY , instanceType , implementationClass ) ; } Class < ? extends Interceptor > classInterceptor = getInterceptorClass ( implementationClass ) ; boolean publicType = hasAnnotation ( implementationClass , Public . class ) ; // managed classes does not support public inheritance
 for ( Method method : implementationClass . getDeclaredMethods ( ) ) { final int modifiers = method . getModifiers ( ) ; if ( Modifier . isStatic ( modifiers ) || ! Modifier . isPublic ( modifiers ) ) { // scans only public and non-static methods
 continue ; } Method interfaceMethod = getInterfaceMethod ( method ) ; ManagedMethod managedMethod = null ; boolean remoteMethod = hasAnnotation ( method , Remote . class ) ; if ( ! remoteMethod ) { remoteMethod = remoteType ; } if ( hasAnnotation ( method , Local . class ) ) { if ( ! remoteMethod ) { throw new BugError ( "@Local annotation on not remote method |%s|." , method ) ; } remoteMethod = false ; } if ( remoteMethod ) { // if at least one owned managed method is remote this managed class become remote too
 remotelyAccessible = true ; } // load method interceptor annotation and if missing uses class annotation; is legal for both to be null
 Class < ? extends Interceptor > methodInterceptor = getInterceptorClass ( method ) ; if ( methodInterceptor == null ) { methodInterceptor = classInterceptor ; } // if method is intercepted, either by method or class annotation, create intercepted managed method
 if ( methodInterceptor != null ) { if ( ! instanceType . isPROXY ( ) && ! remotelyAccessible ) { throw new BugError ( "@Intercepted method |%s| supported only on PROXY type or remote accessible classes." , method ) ; } managedMethod = new ManagedMethod ( this , methodInterceptor , interfaceMethod ) ; } // handle remote accessible methods
 boolean publicMethod = hasAnnotation ( method , Public . class ) ; if ( publicMethod && ! remotelyAccessible ) { throw new BugError ( "@Public annotation on not remote method |%s|." , method ) ; } if ( ! publicMethod ) { publicMethod = publicType ; } if ( hasAnnotation ( method , Private . class ) ) { if ( ! remotelyAccessible ) { throw new BugError ( "@Private annotation on not remote method |%s|." , method ) ; } publicMethod = false ; } RequestPath methodPath = getAnnotation ( method , RequestPath . class ) ; if ( ! remotelyAccessible && methodPath != null ) { throw new BugError ( "@MethodPath annotation on not remote method |%s|." , method ) ; } if ( remoteMethod ) { if ( managedMethod == null ) { managedMethod = new ManagedMethod ( this , interfaceMethod ) ; } managedMethod . setRequestPath ( methodPath != null ? methodPath . value ( ) : null ) ; managedMethod . setRemotelyAccessible ( remoteMethod ) ; managedMethod . setAccess ( publicMethod ? Access . PUBLIC : Access . PRIVATE ) ; } // handle declarative transaction
 // 1. allow transactional only on PROXY
 // 2. do not allow immutable on method if not transactional
 // 3. do not allow mutable on method if not transactional
 // 4. if PROXY create managed method if not already created from above remote method logic
 if ( ! transactionalType ) { transactionalType = hasAnnotation ( method , Transactional . class ) ; } if ( transactionalType ) { transactional = true ; if ( ! instanceType . isPROXY ( ) ) { throw new BugError ( "@Transactional requires |%s| type but found |%s|." , InstanceType . PROXY , instanceType ) ; } } boolean immutable = hasAnnotation ( method , Immutable . class ) ; if ( immutable && ! transactional ) { log . debug ( "@Immutable annotation without @Transactional on method |%s|." , method ) ; } if ( ! immutable ) { immutable = immutableType ; } if ( hasAnnotation ( method , Mutable . class ) ) { if ( ! transactional ) { log . debug ( "@Mutable annotation without @Transactional on method |%s|." , method ) ; } immutable = false ; } if ( instanceType . isPROXY ( ) && managedMethod == null ) { managedMethod = new ManagedMethod ( this , interfaceMethod ) ; } if ( transactional ) { managedMethod . setTransactional ( true ) ; managedMethod . setImmutable ( immutable ) ; } // handle asynchronous mode
 // 1. instance type should be PROXY or managed class should be flagged for remote access
 // 2. transactional method cannot be executed asynchronously
 // 3. asynchronous method should be void
 boolean asynchronousMethod = hasAnnotation ( method , Asynchronous . class ) ; if ( asynchronousMethod ) { if ( ! instanceType . isPROXY ( ) && ! remotelyAccessible ) { throw new BugError ( "Not supported instance type |%s| for asynchronous method |%s|." , instanceType , method ) ; } if ( transactional ) { throw new BugError ( "Transactional method |%s| cannot be executed asynchronous." , method ) ; } if ( ! Types . isVoid ( method . getReturnType ( ) ) ) { throw new BugError ( "Asynchronous method |%s| must be void." , method ) ; } // at this point either instance type is PROXY or remote flag is true; checked by above bug error
 // both conditions has been already processed with managed method creation
 // so managed method must be already created
 managedMethod . setAsynchronous ( asynchronousMethod ) ; } Cron cronMethod = getAnnotation ( method , Cron . class ) ; if ( cronMethod != null ) { // if (!instanceType.isPROXY()) {
 // throw new BugError("Not supported instance type |%s| for cron method |%s|.", instanceType, method);
 // }
 if ( remotelyAccessible ) { throw new BugError ( "Remote accessible method |%s| cannot be executed by cron." , method ) ; } if ( transactional ) { throw new BugError ( "Transactional method |%s| cannot be executed by cron." , method ) ; } if ( ! Types . isVoid ( method . getReturnType ( ) ) ) { throw new BugError ( "Cron method |%s| must be void." , method ) ; } if ( managedMethod == null ) { managedMethod = new ManagedMethod ( this , interfaceMethod ) ; } managedMethod . setCronExpression ( cronMethod . value ( ) ) ; cronMethodsPool . add ( managedMethod ) ; autoInstanceCreation = true ; } // store managed method, if created, to managed methods pool
 if ( managedMethod != null ) { methodsPool . put ( interfaceMethod , managedMethod ) ; if ( managedMethod . isRemotelyAccessible ( ) && netMethodsPool . put ( method . getName ( ) , managedMethod ) != null ) { throw new BugError ( "Overloading is not supported for net method |%s|." , managedMethod ) ; } } } for ( Field field : implementationClass . getDeclaredFields ( ) ) { ContextParam contextParam = field . getAnnotation ( ContextParam . class ) ; if ( contextParam != null ) { field . setAccessible ( true ) ; contextParamFields . put ( contextParam . value ( ) , field ) ; } } }


Input: 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 . <p > 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 > [CODESPLIT] private Class < ? > loadImplementationClass ( Config descriptor ) throws ConfigException { 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 ; }


Input:
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 . <p > 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 > <p > This utility method should be loaded after { @link #loadImplementationClass ( Config ) } otherwise behavior is not defined . [CODESPLIT] private Class < ? > [ ] loadInterfaceClasses ( Config descriptor ) throws ConfigException { 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 ; }


Input: Return instance scope loaded from class descriptor <code > scope< / code > attribute . If scope is not defined use { @link InstanceScope#APPLICATION } as default value . [CODESPLIT] private InstanceScope loadInstanceScope ( Config descriptor ) throws ConfigException { 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 ; }


Input: Return instance type loaded from class descriptor <code > type< / code > attribute . If type is not defined uses { @link InstanceType#POJO } as default value . [CODESPLIT] private InstanceType loadInstanceType ( Config descriptor ) throws ConfigException { 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 ; }


Input: 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 . [CODESPLIT] private String loadImplementationURL ( Config descriptor ) throws ConfigException { 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 ; }


Input:
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 . [CODESPLIT] private static Constructor < ? > getDeclaredConstructor ( Class < ? > implementationClass ) { 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 ; }


Input: 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 . <p > Returns a collection of reflective fields with accessibility set but in not particular order . If given class argument is null returns empty collection . [CODESPLIT] private static Collection < Field > scanDependencies ( Class < ? > clazz ) { 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 ; }


Input: 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 . <p > 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 . [CODESPLIT] private void initializeStaticFields ( ) throws ConfigException { 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 ( ) ) ) ; } }


Input: Build and return this managed class string representation . [CODESPLIT] private String buildStringRepresentation ( Config descriptor ) { 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 ( ) ; }


Input: 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 . <p > Returns null if no annotation found on base class or interfaces . [CODESPLIT] private static < T extends Annotation > T getAnnotation ( Class < ? > clazz , Class < T > annotationClass ) { T annotation = clazz . getAnnotation ( annotationClass ) ; if ( annotation == null ) { for ( Class < ? > interfaceClass : clazz . getInterfaces ( ) ) { annotation = interfaceClass . getAnnotation ( annotationClass ) ; if ( annotation != null ) { break ; } } } return annotation ; }


Input: 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 . <p > Returns false if no annotation found on base class or interfaces . [CODESPLIT] private static boolean hasAnnotation ( Class < ? > clazz , Class < ? extends Annotation > annotationClass ) { 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 ; }


Input: 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 . <p > Returns null if no method annotation found on base class or interfaces . [CODESPLIT] private static < T extends Annotation > T getAnnotation ( Method method , Class < T > annotationClass ) { 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 ; }


Input: 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 . [CODESPLIT] private static Method getInterfaceMethod ( Method method ) { for ( Class < ? > interfaceClass : method . getDeclaringClass ( ) . getInterfaces ( ) ) { try { return interfaceClass . getMethod ( method . getName ( ) , method . getParameterTypes ( ) ) ; } catch ( NoSuchMethodException unused ) { } } return method ; }


Input: Get class value of intercepted annotation of a given class . Returns null if given class has no { @link Intercepted } annotation . [CODESPLIT] private static Class < ? extends Interceptor > getInterceptorClass ( Class < ? > clazz ) { Intercepted intercepted = getAnnotation ( clazz , Intercepted . class ) ; return intercepted != null ? intercepted . value ( ) : null ; }


Input: Get class value of intercepted annotation of a given method . Returns null if given method has no { @link Intercepted } annotation . [CODESPLIT] private static Class < ? extends Interceptor > getInterceptorClass ( Method method ) { Intercepted intercepted = getAnnotation ( method , Intercepted . class ) ; return intercepted != null ? intercepted . value ( ) : null ; }


Input: Returns a new instance of <class > typeAdapter< / class > passing <class > baseTypeAdapter< / class > as the only constructor argument . [CODESPLIT] private TypeHandler < ? > instantiate ( Class < ? extends TypeHandler < ? > > typeAdapter , String parameter ) { try { final Constructor < ? extends TypeHandler < ? > > constructor = typeAdapter . getConstructor ( String . class ) ; return constructor . newInstance ( parameter ) ; } catch ( final Exception e ) { throw new RuntimeException ( e ) ; } }


Input: Instantiates a new { @code TypeAdapter } which is capable of handling { @code type } . <p > If no such adapter exists the old one is returned . [CODESPLIT] public TypeHandler getHandler ( Class < ? > type , String parameter ) { 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 ( ) ) ; } }


Input: Registers a new { @code AbstractTypeAdapter } . <p > After registering an adapter { @link #getHandler ( Class String ) } is able to return it . [CODESPLIT] public void register ( Class < ? extends TypeHandler < ? > > adapterClass ) { final Class < ? > targetType = ( ( TypeHandler < ? > ) instantiate ( adapterClass , null ) ) . getType ( ) ; adapters . put ( targetType , adapterClass ) ; }


Input: Processes { @code inputFile } write output to { @code outputFile } and return the resulting counts using most of fit s default components . [CODESPLIT] @ Override public final Counts run ( final File inputFile , final File outputFile ) { 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 ; }


Input: 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 . <p > 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 . [CODESPLIT] private void setValue ( String propertyPath , Object value ) throws ConverterException , IllegalAccessException { 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 ) ; }


Input:
Return field class or actual type argument if given field is a list . [CODESPLIT] private static Class < ? > type ( Field field ) { 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 ( ) ; }


Input:
Get dependency value of requested type . See class description for a discussion about supported types and circular dependencies . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) protected static Object getDependencyValue ( ManagedClassSPI hostManagedClass , Class < ? > type ) { 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
 } }


Input: 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 . [CODESPLIT] private static boolean isProxyRequired ( ManagedClassSPI hostManagedClass , ManagedClassSPI dependencyManagedClass ) { 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 ; }


Input:
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 . [CODESPLIT] public final void persist ( ) { 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 ) ; } }


Input: Provides an observable stream of element states . Compares entities using { @link Object#equals ( java . lang . Object ) } to detect changes . [CODESPLIT] StoppableObservable < TEntity > getObservable ( Scheduler scheduler ) { 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 ( ) ; } ) ; }


Input: 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 . [CODESPLIT] public final void setDefaultLink ( String rel , String ... hrefs ) { if ( hrefs == null || hrefs . length == 0 ) { defaultLinks . remove ( rel ) ; } else { defaultLinks . put ( rel , stream ( hrefs ) . map ( uri :: resolve ) . collect ( toSet ( ) ) ) ; } }


Input: 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 . [CODESPLIT] public final void setDefaultLinkTemplate ( String rel , String href ) { if ( href == null ) { defaultLinkTemplates . remove ( rel ) ; } else { defaultLinkTemplates . put ( rel , href ) ; } }


Input: Executes a REST request and wraps HTTP status codes in appropriate { @link Exception } types . [CODESPLIT] protected HttpResponse executeAndHandle ( Request request ) throws IOException , IllegalArgumentException , IllegalAccessException , FileNotFoundException , IllegalStateException { HttpResponse response = execute ( request ) ; handleResponse ( response , request ) ; return response ; }


Input: Executes a REST request adding any configured { @link #defaultHeaders } . [CODESPLIT] protected HttpResponse execute ( Request request ) throws IOException { defaultHeaders . forEach ( request :: addHeader ) ; return executor . execute ( request ) . returnResponse ( ) ; }


Input: Handles the response of a REST request and wraps HTTP status codes in appropriate { @link Exception } types . [CODESPLIT] protected void handleResponse ( HttpResponse response , Request request ) throws IOException , IllegalArgumentException , IllegalAccessException , FileNotFoundException , IllegalStateException { handleLinks ( response ) ; handleCapabilities ( response ) ; handleErrors ( response , request ) ; }


Input: Wraps HTTP status codes in appropriate { @link Exception } types . [CODESPLIT] protected void handleErrors ( HttpResponse response , Request request ) throws IOException , IllegalArgumentException , IllegalAccessException , FileNotFoundException , IllegalStateException { 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 ) ; } }


Input: Handles links embedded in an HTTP response . [CODESPLIT] @ SuppressWarnings ( "LocalVariableHidesMemberVariable" ) private void handleLinks ( HttpResponse response ) { 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 ) ; }


Input: Handles links embedded in HTTP response headers . [CODESPLIT] protected void handleHeaderLinks ( HttpResponse response , Map < String , Map < URI , String > > links , Map < String , String > linkTemplates ) { 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 ( ) ) ; } } ) ; }


Input: Handles links embedded in JSON response bodies . [CODESPLIT] protected void handleBodyLinks ( JsonNode jsonBody , Map < String , Map < URI , String > > links , Map < String , String > linkTemplates ) { 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 ; } } ) ; }


Input: Parses a JSON object for link information . [CODESPLIT] private void parseLinkObject ( String rel , ObjectNode obj , Map < URI , String > linksForRel , Map < String , String > linkTemplates ) { 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 ) ; } }


Input: Returns the element with the specified key from the map . Creates adds and returns a new element if no match was found . [CODESPLIT] private static Map < URI , String > getOrAdd ( Map < String , Map < URI , String > > map , String key ) { Map < URI , String > value = map . get ( key ) ; if ( value == null ) { map . put ( key , value = new HashMap <> ( ) ) ; } return value ; }


Input: Handles allowed HTTP methods and other capabilities reported by the server . [CODESPLIT] protected void handleCapabilities ( HttpResponse response ) { allowedMethods = unmodifiableSet ( stream ( response . getHeaders ( "Allow" ) ) . filter ( x -> x . getName ( ) . equals ( "Allow" ) ) . flatMap ( x -> stream ( x . getElements ( ) ) ) . map ( x -> x . getName ( ) ) . collect ( toSet ( ) ) ) ; }


Input: Shows whether the server has indicated that a specific HTTP method is currently allowed . [CODESPLIT] protected Optional < Boolean > isMethodAllowed ( String method ) { if ( allowedMethods . isEmpty ( ) ) { return Optional . empty ( ) ; } return Optional . of ( allowedMethods . contains ( method ) ) ; }


Input: 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 . [CODESPLIT] public final Object [ ] getRows ( ) throws SQLException { 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 ( ) ; }


Input: Concatenates the { @link Throwable#getLocalizedMessage () } s of the entire { @link Throwable#getCause () } tree . [CODESPLIT] @ SuppressWarnings ( "ThrowableResultIgnored" ) public static String getFullMessage ( Throwable throwable ) { StringBuilder builder = new StringBuilder ( ) ; do { builder . append ( throwable . getLocalizedMessage ( ) ) . append ( "\n" ) ; throwable = throwable . getCause ( ) ; } while ( throwable != null ) ; return builder . toString ( ) ; }


Input: 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 . <p > This factory method does not check managed class argument validity . It should be not null and configured for remote invocation . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) @ Override public < T > T newInstance ( ManagedClassSPI managedClass , Object ... args ) { if ( args . length > 0 ) { throw new IllegalArgumentException ( "REMOTE instance factory does not support arguments." ) ; } return getRemoteInstance ( managedClass . getImplementationURL ( ) , ( Class < ? super T > ) managedClass . getInterfaceClass ( ) ) ; }


Input: 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 ) } . <p > This factory method does not check arguments validity . Both should be not null and interface class should be an actual Java interface . [CODESPLIT] @ Override public < T > T getRemoteInstance ( String implementationURL , Class < ? super T > interfaceClass ) throws UnsupportedProtocolException { 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 ) ; }


Input: Register all instance post - processors . [CODESPLIT] protected void registerInstanceProcessor ( ) { registerInstanceProcessor ( new InstanceFieldsInjectionProcessor ( ) ) ; registerInstanceProcessor ( new InstanceFieldsInitializationProcessor ( ) ) ; registerInstanceProcessor ( new ConfigurableInstanceProcessor ( ) ) ; registerInstanceProcessor ( new PostConstructInstanceProcessor ( ) ) ; registerInstanceProcessor ( new CronMethodsProcessor ( cronManager ) ) ; registerInstanceProcessor ( new LoggerInstanceProcessor ( ) ) ; }


Input: Register scope factory for the instance scope returned by { @link ScopeFactory#getInstanceScope () } . [CODESPLIT] protected void registerScopeFactory ( ScopeFactory scopeFactory ) { 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 ) ; } }


Input: Register instance factory to requested instance type . [CODESPLIT] protected void registerInstanceFactory ( InstanceType instanceType , InstanceFactory instanceFactory ) { 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 ) ; } }


Input: Register instance processor . Only a single instance per processor class is allowed . [CODESPLIT] protected void registerInstanceProcessor ( InstanceProcessor instanceProcessor ) { 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 ) ; }


Input: Register global processors for managed classes . Post - processors are singletons and only one post - processor instance of a type is allowed . [CODESPLIT] protected void registerClassProcessor ( ClassProcessor classProcessor ) { 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 ) ; }


Input:
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 . [CODESPLIT] @ Override public void config ( Config config ) throws ConfigException { 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 ) ; } }


Input:
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 { [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public void start ( ) { 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 ( ) ) ; } }


Input:
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 { [CODESPLIT] public void destroy ( ) { 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 ( ) ; }


Input: INSTANCE RETRIEVAL ALGORITHM [CODESPLIT] @ Override public < T > T getInstance ( Class < ? super T > interfaceClass , Object ... args ) { 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 ) ; }


Input:
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 . <p > 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 > [CODESPLIT] @ SuppressWarnings ( "unchecked" ) private < T > T getInstance ( ManagedClassSPI managedClass , InstanceKey instanceKey , Object ... args ) { // 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 ; }


Input: Declarative converters registration . This utility scans for <code > converters< / code > section into given configuration object and register converters via { @link ConverterRegistry#registerConverter ( Class Class ) } . <p > Configuration converter section should respect below syntax . [CODESPLIT] private static void convertersInitialization ( Config config ) throws ConfigException { 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 ) ; } }


Input: 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 . <p > 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 . [CODESPLIT] private static void pojoStaticInitialization ( Config config ) throws ConfigException { 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 ) ; } } }


Input: Adds an argument to the template . If the list of arguments does not exist it will be created . [CODESPLIT] public final void addArgument ( @ NotNull final Argument argument ) { if ( arguments == null ) { arguments = new ArrayList < Argument > ( ) ; } arguments . add ( argument ) ; }


Input: Returns the list of target files . Either by using the producer or by simply returning the internal list . [CODESPLIT] public final List < TargetFile > createTargetFileList ( ) { 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 ( ) ; }


Input: Marshals the object to XML . [CODESPLIT] public final void writeToXml ( final File file ) { try { final JaxbHelper helper = new JaxbHelper ( ) ; helper . write ( this , file , createJaxbContext ( ) ) ; } catch ( final MarshalObjectException ex ) { throw new RuntimeException ( ex ) ; } }


Input: Marshals the object to an XML String . [CODESPLIT] public final String toXml ( ) { try { final JaxbHelper helper = new JaxbHelper ( ) ; return helper . write ( this , createJaxbContext ( ) ) ; } catch ( final MarshalObjectException ex ) { throw new RuntimeException ( ex ) ; } }


Input: Marshals the object to XML . [CODESPLIT] public final void writeToXml ( final Writer writer ) { try { final JaxbHelper helper = new JaxbHelper ( ) ; helper . write ( this , writer , createJaxbContext ( ) ) ; } catch ( final MarshalObjectException ex ) { throw new RuntimeException ( ex ) ; } }


Input: Initializes the model . [CODESPLIT] public final void init ( final SrcGen4JContext context , final Map < String , String > vars ) { 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 ) ; } }


Input: Checks if this model has a reference to the given template file . [CODESPLIT] public final boolean hasReferenceTo ( final File templateDir , final File templateFile ) { final String p1 = Utils4J . getCanonicalPath ( new File ( templateDir , template ) ) ; final String p2 = Utils4J . getCanonicalPath ( templateFile ) ; return p1 . equals ( p2 ) ; }


Input: Creates an instance by reading the XML from a reader . [CODESPLIT] public static ParameterizedTemplateModel create ( final Reader reader ) { 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 ) ; } }


Input: Creates an instance by reading the XML from a file . [CODESPLIT] public static ParameterizedTemplateModel create ( final File file ) { 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 ) ; } }


Input:
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 . [CODESPLIT] @ Override public void postProcessInstance ( ManagedClassSPI managedClass , Object instance ) { 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 ( ) ) ) ; } }


Input: 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 . [CODESPLIT] void setRequestPath ( String requestPath ) { this . requestPath = requestPath != null ? requestPath : Strings . toDashCase ( method . getName ( ) ) ; }


Input:
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 } . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) @ Override public < T > T invoke ( Object object , Object ... args ) throws AuthorizationException , IllegalArgumentException , InvocationException { 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 ; }


Input: Invokes the method multiple times either until it returns true or until maxtime is over . After each invoke the class waits { @code sleepTime } milliseconds . [CODESPLIT] public void wait ( Object target , Method method , long maxTime , long sleepTime ) { long remaining = maxTime ; lastCallWasSuccessful = invokeMethod ( target , method ) ; while ( ! lastCallWasSuccessful && remaining > 0 ) { systemTime . sleep ( sleepTime ) ; remaining -= sleepTime ; lastCallWasSuccessful = invokeMethod ( target , method ) ; } lastElapsedTime = maxTime - remaining ; }


Input: 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 . [CODESPLIT] @ Override public boolean hasNext ( ) { 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 ; }


Input: 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 . <p > 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 . [CODESPLIT] @ Override public ArgumentsReader getArgumentsReader ( HttpServletRequest httpRequest , Type [ ] formalParameters ) { if ( formalParameters . length == 0 ) { return EmptyArgumentsReader . getInstance ( ) ; } if ( httpRequest . getQueryString ( ) != null ) { return readers . get ( null ) ; } return getArgumentsReader ( httpRequest . getContentType ( ) , formalParameters [ 0 ] ) ; }


Input: 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 . <p > 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 . [CODESPLIT] private ArgumentsReader getArgumentsReader ( String contentType , Type parameterType ) { 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 ; }


Input: Determine content type usable to retrieve a writer able to handle given object value . This method is used in tandem with { @link #getValueWriter ( ContentType ) } . <p > There is a heuristic to determine content type based on object value class . If no suitable content type found returns { @link ContentType#APPLICATION_JSON } . [CODESPLIT] @ Override public ContentType getContentTypeForValue ( Object value ) { if ( value instanceof Document ) { return ContentType . TEXT_XML ; } if ( value instanceof StreamHandler ) { return ContentType . APPLICATION_STREAM ; } return ContentType . APPLICATION_JSON ; }


Input: 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 . <p > Recommend way to use this method is to provide content type instance returned by { @link #getContentTypeForValue ( Object ) } . [CODESPLIT] @ Override public ValueWriter getValueWriter ( ContentType contentType ) { ValueWriter writer = writers . get ( contentType ) ; if ( writer == null ) { throw new BugError ( "No return value writer for content type |%s|." , contentType ) ; } return writer ; }


Input: answer comparisons /////////////////////// [CODESPLIT] public void check ( FitCell cell , String value ) { if ( cell . getFitValue ( ) . equals ( value ) ) { cell . right ( ) ; } else { cell . wrong ( value ) ; } }


Input: Provides an observable stream of elements . [CODESPLIT] StoppableObservable < TEntity > getObservable ( final long startIndex , Scheduler scheduler ) { 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 ; } } ) ; }


Input: Create a scope instance from its string value . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) @ Override public < T > T asObject ( String string , Class < T > valueType ) { return ( T ) new InstanceScope ( string ) ; }


Input: Parses a string and converts it into a { @code java . util . Date } object . [CODESPLIT] @ Override public final Date unsafeParse ( final String s ) throws ParseException { return dateFitDateHelper . parse ( s , parameter ) ; }


Input: Initialize field from named context parameter . [CODESPLIT] private void setField ( Field field , String parameterName , Object instance ) { final Object value = context . getProperty ( parameterName , field . getType ( ) ) ; try { field . set ( instance , value ) ; } catch ( Exception e ) { throw new BugError ( e ) ; } }


Input: Save dialog requested ( unsupported content ) . [CODESPLIT] public void save ( QNetworkReply reply ) { m_logger . info ( "Unsupported Content : " + reply . url ( ) . toString ( ) + " - Download request" ) ; m_factory . save ( reply ) ; }


Input: Adds a new CaptureAppender to an existing logger . [CODESPLIT] public void addCaptureToLogger ( final AppenderAttachable logger , final String appenderName ) { Appender currentAppender = logger . getAppender ( appenderName ) ; Appender captureAppender = CaptureAppender . newAppenderFrom ( currentAppender ) ; logger . addAppender ( captureAppender ) ; }


Input: Returns the CaptureAppender which captures <code > appenderName< / code > . [CODESPLIT] public Appender getCaptureAppender ( final AppenderAttachable logger , final String appenderName ) { return logger . getAppender ( CaptureAppender . getAppenderNameFor ( appenderName ) ) ; }


Input: Removes a CaptureAppender from a logger . [CODESPLIT] public void remove ( final AppenderAttachable logger , final String appenderName ) { logger . removeAppender ( CaptureAppender . getAppenderNameFor ( appenderName ) ) ; }


Input: Deletes all cached log entries . [CODESPLIT] public void clear ( final AppenderAttachable logger , final String appenderName ) { ( ( CaptureAppender ) logger . getAppender ( CaptureAppender . getAppenderNameFor ( appenderName ) ) ) . clear ( ) ; }


Input:
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 . [CODESPLIT] @ Override public Object [ ] read ( HttpServletRequest httpRequest , Type [ ] formalParameters ) throws IOException , IllegalArgumentException { 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 ( ) ) ; } }


Input: AutoCloseable [CODESPLIT] @ Override public void close ( ) throws java . sql . SQLException { if ( ! this . conn . isClosed ( ) ) { ConnectionImpl outer = this . outer ; this . conn . close ( ) ; this . outer = null ; CONNECTION_HOLDER . set ( outer ) ; } }


Input:
Parses all model files in the directories and all resources . y [CODESPLIT] protected final void parseModel ( ) { 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 ( ) ; }


Input: Tries to resolve all proxies . [CODESPLIT] protected final void resolveProxies ( ) { 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 ) ; } } } } } }


Input: Returns files that end with java and all directories . Files and directories started with a . are excluded . [CODESPLIT] private File [ ] getFiles ( final File dir ) { final File [ ] files = dir . listFiles ( new FileFilter ( ) { @ Override public boolean accept ( final File file ) { final boolean pointFile = file . getName ( ) . startsWith ( "." ) ; final String extension = FilenameUtils . getExtension ( file . getName ( ) ) ; return ( ! pointFile && fileExtensions . contains ( extension ) ) || file . isDirectory ( ) ; } } ) ; return files ; }


Input: Parse the directory and it s sub directory . [CODESPLIT] private void parseDir ( final File dir ) { LOG . debug ( "Parse: {}" , dir ) ; final File [ ] files = getFiles ( dir ) ; if ( ( files == null ) || ( files . length == 0 ) ) { LOG . debug ( "No files found in directory: {}" , dir ) ; } else { for ( final File file : files ) { if ( file . isFile ( ) ) { final Resource resource = resourceSet . getResource ( URI . createFileURI ( Utils4J . getCanonicalPath ( file ) ) , true ) ; final EList < Diagnostic > diagnostics = resource . getErrors ( ) ; if ( diagnostics . size ( ) == 0 ) { LOG . debug ( "Parsed {}" , file ) ; } else { error = true ; LOG . error ( "Parsed {} with errors: {}" , file , diagnostics ) ; } } else { parseDir ( file ) ; } } } }


Input: Determines if all proxies in the model are resolved . [CODESPLIT] public boolean isModelFullyResolved ( ) { boolean resolved = true ; final Set < EObject > eObjects = findAllEObjects ( resourceSet ) ; final Iterator < EObject > it = eObjects . iterator ( ) ; while ( it . hasNext ( ) ) { final EObject eObj = it . next ( ) ; if ( eObj instanceof InternalEObject ) { final InternalEObject iObj = ( InternalEObject ) eObj ; for ( final EObject crossRef : iObj . eCrossReferences ( ) ) { if ( crossRef . eIsProxy ( ) ) { LOG . error ( "Unresolved: {}" , crossRef ) ; resolved = false ; } } } } return resolved ; }


Input: Returns a list of all objects . [CODESPLIT] private static Set < EObject > findAllEObjects ( final ResourceSet resourceSet ) { final Set < EObject > list = new HashSet < EObject > ( ) ; for ( final Iterator < Notifier > i = resourceSet . getAllContents ( ) ; i . hasNext ( ) ; ) { final Notifier next = i . next ( ) ; if ( next instanceof EObject ) { list . add ( ( EObject ) next ) ; } } return list ; }


Input: Sets the model directories to parse . If no list exists internally it will be created if necessary . [CODESPLIT] protected final void setModelDirs ( final File ... modelDirs ) { if ( modelDirs == null ) { this . modelDirs = null ; } else { this . modelDirs = new ArrayList < File > ( ) ; this . modelDirs . addAll ( Arrays . asList ( modelDirs ) ) ; } }


Input: Sets the list of file extensions . If no list exists internally it will be created if necessary . [CODESPLIT] protected final void setFileExtensions ( final String ... fileExtensions ) { if ( fileExtensions == null ) { this . fileExtensions = null ; } else { this . fileExtensions = new ArrayList < String > ( ) ; this . fileExtensions . addAll ( Arrays . asList ( fileExtensions ) ) ; } }


Input: Sets the model resources to parse . If no list exists internally it will be created if necessary . [CODESPLIT] protected final void setModelResources ( final URI ... modelResources ) { if ( modelResources == null ) { this . modelResources = null ; } else { this . modelResources = new ArrayList < URI > ( ) ; this . modelResources . addAll ( Arrays . asList ( modelResources ) ) ; } }


Input: Reads the next row . [CODESPLIT] @ Override public final boolean nextRecord ( ) throws IOException { final String line = reader . readLine ( ) ; if ( line == null ) { parts = null ; return false ; } final List < String > newParts = splitLine ( line ) ; parts = newParts . toArray ( new String [ newParts . size ( ) ] ) ; partIndex = 0 ; return true ; }


Input: Sorts and compare two lists . It is assumed that all items in { [CODESPLIT] private void multiLevelMatch ( List < FitRow > expected , List < Object > computed , int col ) { boolean cantGoDeeper = col >= columnNames . length ; if ( cantGoDeeper ) { check ( expected , computed ) ; } else { boolean isComment = isComment ( col ) ; if ( isComment ) { multiLevelMatch ( expected , computed , col + 1 ) ; } else { groupAndMatch ( expected , computed , col ) ; } } }


Input: Groups both lists by column { [CODESPLIT] private void groupAndMatch ( List < FitRow > expected , List < Object > computed , int col ) { Map < Object , List < FitRow > > expectedMap = groupExpectedByColumn ( expected , col ) ; Map < Object , List < Object > > computedMap = groupComputedByColumn ( computed , col ) ; Set keys = union ( expectedMap . keySet ( ) , computedMap . keySet ( ) ) ; for ( Object key : keys ) { List < FitRow > expectedList = expectedMap . get ( key ) ; List < Object > computedList = computedMap . get ( key ) ; boolean isAmbiguous = hasMultipleEntries ( expectedList ) && hasMultipleEntries ( computedList ) ; if ( isAmbiguous ) { multiLevelMatch ( expectedList , computedList , col + 1 ) ; } else { check ( expectedList , computedList ) ; } } }


Input: Compares two lists . <ul > <li > if { @code expectedList } is empty all { @code computedList } items are surplus< / li > <li > if { @code computedList } is empty all { @code expectedList } items are missing< / li > <li > otherwise match the first rows and compare the rest recursively< / li > < / ul > [CODESPLIT] protected void check ( List < FitRow > expectedList , List < Object > computedList ) { if ( expectedList == null || expectedList . size ( ) == 0 ) { surplus . addAll ( computedList ) ; } else if ( computedList == null || computedList . size ( ) == 0 ) { missing . addAll ( expectedList ) ; } else { Object computedRow = computedList . remove ( 0 ) ; List < FitCell > expectedRow = expectedList . remove ( 0 ) . cells ( ) ; compareRow ( computedRow , expectedRow ) ; check ( expectedList , computedList ) ; } }


Input: Compares two rows item by item using { [CODESPLIT] private void compareRow ( Object computedRow , List < FitCell > expectedCells ) { for ( int i = 0 ; i < columnNames . length && expectedCells != null ; i ++ ) { try { ValueReceiver valueReceiver ; if ( isComment ( i ) ) { valueReceiver = null ; } else { valueReceiver = createReceiver ( computedRow , columnNames [ i ] ) ; } String columnParameter = FitUtils . saveGet ( i , columnParameters ) ; check ( expectedCells . get ( i ) , valueReceiver , columnParameter ) ; } catch ( NoSuchMethodException | NoSuchFieldException e ) { expectedCells . indexOf ( e ) ; } } }


Input: <p > This method performs property variable substitution on the specified value . If the specified value contains the syntax <tt > $ { &lt ; prop - name&gt ; } < / tt > where <tt > &lt ; prop - name&gt ; < / tt > refers to either a configuration property or a system property then the corresponding property value is substituted for the variable placeholder . Multiple variable placeholders may exist in the specified value as well as nested variable placeholders which are substituted from inner most to outer most . Configuration properties override system properties . < / p > [CODESPLIT] @ SuppressWarnings ( { "rawtypes" , "unchecked" } ) public static String substVars ( String val , String currentKey , Map cycleMap , Properties configProps ) throws IllegalArgumentException { // If there is currently no cycle map, then create // one for detecting cycles for this invocation. if ( cycleMap == null ) { cycleMap = new HashMap ( ) ; } // Put the current key in the cycle map. cycleMap . put ( currentKey , currentKey ) ; // Assume we have a value that is something like: // "leading ${foo.${bar}} middle ${baz} trailing" // Find the first ending '}' variable delimiter, which // will correspond to the first deepest nested variable // placeholder. int stopDelim = - 1 ; int startDelim = - 1 ; do { stopDelim = val . indexOf ( DELIM_STOP , stopDelim + 1 ) ; // If there is no stopping delimiter, then just return // the value since there is no variable declared. if ( stopDelim < 0 ) { return val ; } // Try to find the matching start delimiter by // looping until we find a start delimiter that is // greater than the stop delimiter we have found. startDelim = val . indexOf ( DELIM_START ) ; // If there is no starting delimiter, then just return // the value since there is no variable declared. if ( startDelim < 0 ) { return val ; } while ( stopDelim >= 0 ) { int idx = val . indexOf ( DELIM_START , startDelim + DELIM_START . length ( ) ) ; if ( ( idx < 0 ) || ( idx > stopDelim ) ) { break ; } else if ( idx < stopDelim ) { startDelim = idx ; } } } while ( ( startDelim > stopDelim ) && ( stopDelim >= 0 ) ) ; // At this point, we have found a variable placeholder so // we must perform a variable substitution on it. // Using the start and stop delimiter indices, extract // the first, deepest nested variable placeholder. String variable = val . substring ( startDelim + DELIM_START . length ( ) , stopDelim ) ; // Verify that this is not a recursive variable reference. if ( cycleMap . get ( variable ) != null ) { throw new IllegalArgumentException ( "recursive variable reference: " + variable ) ; } // Get the value of the deepest nested variable placeholder. // Try to configuration properties first. String substValue = ( configProps != null ) ? configProps . getProperty ( variable , null ) : null ; if ( substValue == null ) { // Ignore unknown property values. substValue = System . getProperty ( variable , "" ) ; } // Remove the found variable from the cycle map, since // it may appear more than once in the value and we don't // want such situations to appear as a recursive reference. cycleMap . remove ( variable ) ; // Append the leading characters, the substituted value of // the variable, and the trailing characters to get the new // value. val = val . substring ( 0 , startDelim ) + substValue + val . substring ( stopDelim + DELIM_STOP . length ( ) , val . length ( ) ) ; // Now perform substitution again, since there could still // be substitutions to make. val = substVars ( val , currentKey , cycleMap , configProps ) ; // Return the value. return val ; }


Input: Converts a { @code String } into a { @code Array } . [CODESPLIT] @ Override public Object unsafeParse ( final String s ) throws ParseException { final StringTokenizer t = new StringTokenizer ( s , "," ) ; final Object array = Array . newInstance ( componentAdapter . getType ( ) , t . countTokens ( ) ) ; for ( int i = 0 ; t . hasMoreTokens ( ) ; i ++ ) { Array . set ( array , i , componentAdapter . parse ( t . nextToken ( ) . trim ( ) ) ) ; } return array ; }


Input: Checks whether two Arrays { @code a } and { @code b } are equal . <p > A type specific { @code TypeAdapter } is used to compare the items . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) @ Override public boolean unsafeEquals ( Object a , Object b ) { final int length = Array . getLength ( a ) ; if ( length != Array . getLength ( b ) ) { return false ; } for ( int i = 0 ; i < length ; i ++ ) { if ( ! componentAdapter . unsafeEquals ( Array . get ( a , i ) , Array . get ( b , i ) ) ) { return false ; } } return true ; }


Input: Creates a LogEventAnalyzer which is capable to analyze the events { @code events } using the condition defined in { @code conditionCell } . [CODESPLIT] public LogEventAnalyzer getLogEventAnalyzerFor ( Validator validator , FitCell conditionCell , LoggingEvent [ ] events ) { return new LogEventAnalyzer ( validator , conditionCell , events ) ; }


Input:
Uses template engine to inject model and serialize view on HTTP response . If meta - view contains { @link #OPERATOR_SERIALIZATION } property enable engine operators serialization . [CODESPLIT] @ Override protected void serialize ( OutputStream outputStream ) throws IOException { // refrain to use HttpResponse#getWriter()
 // this library always uses output stream since servlet response API does not allow mixing characters and bytes streams
 Writer writer = new BufferedWriter ( new OutputStreamWriter ( outputStream , "UTF-8" ) ) ; TemplateEngine templateEngine = Classes . loadService ( TemplateEngine . class ) ; Template template = templateEngine . getTemplate ( meta . getTemplateFile ( ) ) ; boolean operatorSerialization = Boolean . parseBoolean ( meta . getProperty ( OPERATOR_SERIALIZATION ) ) ; if ( operatorSerialization ) { template . setProperty ( "js.template.serialize.operator" , true ) ; } // if model is null template serializes itself skipping injection operation
 template . serialize ( model , writer ) ; // there is no need to flush response stream on error so no need for try/finally
 writer . flush ( ) ; }


Input: Execute Results [CODESPLIT] public < K , V > Map < K , V > executeMap ( ResultSetMapper < K > key , ResultSetMapper < V > value , Map < K , V > newMap ) throws java . sql . SQLException { try ( ResultSetImpl rs = this . executeResult ( ) ) { while ( rs . next ( ) ) { K k = key . map ( rs ) ; V v = value . map ( rs ) ; newMap . put ( k , v ) ; } return newMap ; } }


Input: type IN ( [CODESPLIT] public void setStringArray ( String parameterName , String ... values ) throws java . sql . SQLException { int arrayLen = this . getSql ( ) . getArrayLen ( parameterName ) ; AssertUtils . assertTrue ( values . length <= arrayLen ) ; for ( int i = 0 ; i < arrayLen ; i ++ ) { setString2 ( Sql . toParamName ( parameterName , i ) , ( i < values . length ) ? values [ i ] : null ) ; } }


Input: Set Nullable Parameters [CODESPLIT] public void setBoolean2 ( String parameterName , Boolean value ) throws java . sql . SQLException { if ( value == null ) { setNull ( parameterName , Types . BIT ) ; } else { setBoolean ( parameterName , value ) ; } }


Input: java . sql . Statement [CODESPLIT] @ Override public long executeLargeUpdate ( java . lang . String sql , int [ ] columnIndexes ) throws java . sql . SQLException { return this . stat . executeLargeUpdate ( sql , columnIndexes ) ; }


Input: Checks if the arguments contains the argument <code > arg< / code > . [CODESPLIT] public static boolean containsArgument ( String [ ] args , String arg ) { if ( args == null || arg == null || arg . length ( ) == 0 || args . length == 0 ) { return false ; } else { for ( String a : args ) { if ( a . equalsIgnoreCase ( arg ) ) { return true ; } else if ( a . startsWith ( arg + "=" ) ) { return true ; } } return false ; } }


Input: Gets the argument value . <ul > <li > for arg = value it returns value < / li > <li > for arg value it returns value < / li > [CODESPLIT] public static String getArgumentValue ( String args [ ] , String arg ) { if ( args == null || arg == null || arg . length ( ) == 0 || args . length == 0 ) { return null ; } else { for ( int i = 0 ; i < args . length ; i ++ ) { String a = args [ i ] ; if ( a . equalsIgnoreCase ( arg ) ) { // Case 'arg value' : Look for arg + 1; if ( args . length > i + 1 ) { return args [ i + 1 ] ; } } else if ( a . startsWith ( arg + "=" ) ) { // Case 'arg=value' : Parse the value int index = a . indexOf ( ' ' ) + 1 ; return a . substring ( index ) ; } } return null ; } }


Input: Create an instance type from its string value . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) @ Override public < T > T asObject ( String string , Class < T > valueType ) throws IllegalArgumentException , ConverterException { return ( T ) new InstanceType ( string ) ; }