signature:
public class QueryParametersParser { /** * Get an array of arguments suitable for a method invocation . This method did its best to fill the arguments array . The
 * logic is simple : ignore query extra parameters and set to null the missing ones . Both cases are recorded to debug log .
 * Returned arguments array has the same size as requested formal parameters array .
 * Parameter values from parsed { @ link # parameters } are converted to requested type using { @ link # asObject ( String , Type ) }
 * utility method . If formal parameters has a single type that has no converter uses reflection to map query parameters to
 * object field by name .
 * Note that because parameter names are not preserved on run - time , query parameters are mapped by position to invocation
 * arguments . This means is caller responsibility to match formal parameters order and type with actual query string
 * parameters .
 * @ param formalParameters formal parameters list .
 * @ return invocation arguments array .
 * @ throws ConverterException if string value cannot be converted to requested type .
 * @ throws BugError if type is generic and is not an array like . */
public Object [ ] getArguments ( Type [ ] formalParameters ) { } }

implementation:
if ( formalParameters . length == 0 ) { return new Object [ 0 ] ; } Object [ ] arguments = new Object [ formalParameters . length ] ; if ( isObject ( formalParameters ) ) { // if there is single formal parameter and it is not a value type create object instance and initialize fields from
// request parameters ; object class should have no arguments constructor
Class < ? > type = ( Class < ? > ) formalParameters [ 0 ] ; Object object = Classes . newInstance ( type ) ; for ( Parameter parameter : parameters ) { Field field = Classes . getField ( type , Strings . toMemberName ( parameter . getName ( ) ) ) ; Classes . setFieldValue ( object , field , asObject ( parameter . getValue ( ) , field . getType ( ) ) ) ; } return new Object [ ] { object } ; } int i = 0 , argumentsCount = Math . min ( formalParameters . length , parameters . size ( ) ) ; for ( i = 0 ; i < argumentsCount ; ++ i ) { arguments [ i ] = asObject ( parameters . get ( i ) . getValue ( ) , formalParameters [ i ] ) ; } for ( ; i < formalParameters . length ; ++ i ) { log . debug ( "Missing request parameter |%s|. Set it to null." , i , formalParameters [ i ] ) ; arguments [ i ] = null ; } for ( ; i < parameters . size ( ) ; ++ i ) { log . debug ( "Unused request parameter |%s|. Ignore it." , parameters . get ( i ) ) ; } return arguments ;


signature:
public class QueryParametersParser { /** * Helper method to convert string parameter to an instance of a given type . Requested < code > type < / code > should be a value
 * type as accepted by converter package or an array / collection of value types . In the later case < code > value < / code >
 * should be a comma separated string of items . If given < code > value < / code > is null returns an empty value as defined by
 * { @ link Types # getEmptyValue ( Type ) } .
 * @ param value parameter value , possible null ,
 * @ param type parameter type .
 * @ param < T > instance type .
 * @ return newly created parameter type instance .
 * @ throws ConverterException if string value cannot be converted to requested type .
 * @ throws BugError if type is generic and is not an array like . */
@ SuppressWarnings ( "unchecked" ) private static < T > T asObject ( String value , Type type ) { } }

implementation:
if ( value == null ) { return ( T ) Types . getEmptyValue ( type ) ; } if ( ! Types . isArrayLike ( type ) ) { if ( ! ( type instanceof Class ) ) { throw new BugError ( "Generic value types are not supported." ) ; } if ( ConverterRegistry . hasType ( type ) ) { return ConverterRegistry . getConverter ( ) . asObject ( value , ( Class < T > ) type ) ; } log . debug ( "Missing converter for query parameter of type |%s|." , type ) ; return ( T ) Types . getEmptyValue ( type ) ; } // here we have an array / collection represented as comma separated primitives
List < String > strings = Strings . split ( value , ',' ) ; if ( type == String [ ] . class ) { return ( T ) strings . toArray ( new String [ strings . size ( ) ] ) ; } if ( Types . isKindOf ( type , Collection . class ) ) { Type collectionType = type ; Class < ? > itemType = String . class ; if ( type instanceof ParameterizedType ) { collectionType = ( ( ParameterizedType ) type ) . getRawType ( ) ; itemType = ( Class < ? > ) ( ( ParameterizedType ) type ) . getActualTypeArguments ( ) [ 0 ] ; } Collection < Object > collection = Classes . newCollection ( collectionType ) ; Converter converter = ConverterRegistry . getConverter ( ) ; for ( String s : strings ) { collection . add ( converter . asObject ( s . trim ( ) , itemType ) ) ; } return ( T ) collection ; } throw new BugError ( "Type not supported |%s|." , type ) ;


signature:
public class QueryParametersParser { /** * Test if method formal parameters designates a strict object , that is , is not primitive , array , collection or map .
 * @ param formalParameters method formal parameters list .
 * @ return true if formal parameters designates a strict object . */
private static boolean isObject ( Type [ ] formalParameters ) { } }

implementation: if ( formalParameters . length != 1 ) { return false ; } final Type type = formalParameters [ 0 ] ; if ( ! ( type instanceof Class ) ) { return false ; } if ( Types . isPrimitive ( type ) ) { return false ; } if ( Types . isArrayLike ( type ) ) { return false ; } if ( Types . isMap ( type ) ) { return false ; } if ( ConverterRegistry . hasType ( type ) ) { return false ; } return true ;


signature:
public class JsonArgumentsReader { /** * Uses JSON deserializer to parse method invocation arguments accordingly formal parameters list .
 * @ param httpRequest HTTP request ,
 * @ param formalParameters formal parameter types .
 * @ return arguments array .
 * @ throws IOException if reading from request input stream fails .
 * @ throws IllegalArgumentException if arguments from HTTP request cannot be parsed .
 * @ throws JsonException if JSON parsing fails due to invalid stream format . */
@ Override public Object [ ] read ( HttpServletRequest httpRequest , Type [ ] formalParameters ) throws IOException , IllegalArgumentException { } }

implementation: JsonReader reader = new JsonReader ( httpRequest . getInputStream ( ) , expectedStartSequence ( formalParameters ) ) ; try { return json . parse ( reader , formalParameters ) ; } catch ( JsonException e ) { throw new IllegalArgumentException ( e . getMessage ( ) ) ; } finally { reader . close ( ) ; }


signature:
public class JsonArgumentsReader { /** * Parse JSON from input stream accordingly given type . Return parsed object .
 * @ param inputStream JSON input stream ,
 * @ param type expected type .
 * @ return parsed object .
 * @ throws IllegalArgumentException if JSON parse or reading from stream fails . */
@ Override public Object read ( InputStream inputStream , Type type ) throws IOException { } }

implementation: try { return json . parse ( new InputStreamReader ( inputStream , "UTF-8" ) , type ) ; } catch ( JsonException | ClassCastException | UnsupportedEncodingException e ) { throw new IllegalArgumentException ( e . getMessage ( ) ) ; }


signature:
public class ArgumentsProcessor { /** * Pre - process constructor arguments for local managed classes . A managed class is < code > local < / code > if is of
 * { @ link InstanceType # POJO } or { @ link InstanceType # PROXY } type . Attempting to pre - process arguments for other managed class
 * types is silently ignored . This method delegates
 * { @ link # preProcessArguments ( ManagedClassSPI , Member , Class [ ] , Object . . . ) } .
 * @ param managedClass managed class ,
 * @ param args constructor arguments .
 * @ return processed arguments . */
public Object [ ] preProcessArguments ( ManagedClassSPI managedClass , Object ... args ) { } }

implementation:
// arguments can be null if on invocations chain there is Proxy handler invoked with no arguments
if ( args == null ) { args = EMPTY_ARGS ; } if ( managedClass . getImplementationClass ( ) == null ) { return args ; } Constructor < ? > constructor = managedClass . getConstructor ( ) ; // managed class constructor parameters have the same limitation as injected fields : they must be a managed
// class on their turn ; it is considered a bug trying to use not managed classes as constructor argument
// because managed class is not generic is safe to use getParameterTypes instead of getGenericParameterTypes
final Class < ? > [ ] types = constructor . getParameterTypes ( ) ; return preProcessArguments ( managedClass , constructor , types , args ) ;


signature:
public class ArgumentsProcessor { /** * Pre - process managed method invocation arguments . This processor prepares invocation arguments for given managed method ;
 * it just delegates { @ link # preProcessArguments ( ManagedClassSPI , Member , Class [ ] , Object . . . ) } .
 * @ param managedMethod managed method ,
 * @ param args method invocation arguments .
 * @ return processed arguments . */
public Object [ ] preProcessArguments ( ManagedMethodSPI managedMethod , Object ... args ) { } }

implementation:
// arguments can be null if on invocations chain there is Proxy handler invoked with no arguments
if ( args == null ) { args = EMPTY_ARGS ; } final ManagedClassSPI managedClass = managedMethod . getDeclaringClass ( ) ; final Method method = managedMethod . getMethod ( ) ; final Class < ? > [ ] types = method . getParameterTypes ( ) ; return preProcessArguments ( managedClass , method , types , args ) ;


signature:
public class ArgumentsProcessor { /** * Update and validate invocation arguments against given formal parameter types . If formal parameters is not empty but no
 * invocation arguments this method will inject dependency using { @ link # getDependencyValue ( ManagedClassSPI , Class ) } . This
 * method also performs arguments validity check against formal parameters throwing illegal arguments if validation fails .
 * @ param managedClass managed class owning constructor or method ,
 * @ param member constructor or method for given arguments ,
 * @ param formalParameters formal parameter types ,
 * @ param args constructor or method invocation arguments .
 * @ return given arguments updated and validated . */
private static Object [ ] preProcessArguments ( ManagedClassSPI managedClass , Member member , Class < ? > [ ] formalParameters , Object ... args ) { } }

implementation:
switch ( args . length ) { case 0 : args = new Object [ formalParameters . length ] ; for ( int i = 0 ; i < args . length ; i ++ ) { args [ i ] = getDependencyValue ( managedClass , formalParameters [ i ] ) ; } break ; case 1 : // TODO : refine variable arguments : test for formal parameters type , document and test
if ( args [ 0 ] instanceof VarArgs && formalParameters . length == 1 && formalParameters [ 0 ] . isArray ( ) ) { args [ 0 ] = ( ( VarArgs < ? > ) args [ 0 ] ) . getArguments ( ) ; } break ; } // arguments validity test against formal parameters : count and types
if ( formalParameters . length != args . length ) { throw new IllegalArgumentException ( "Invalid arguments count on method |%s|. Expected |%d| but got |%d|." , member , formalParameters . length , args . length ) ; } for ( int i = 0 ; i < formalParameters . length ; ++ i ) { if ( args [ i ] != null && ! Types . isInstanceOf ( args [ i ] , formalParameters [ i ] ) ) { throw new IllegalArgumentException ( "Invalid argument type at position |%d| on method |%s|. Expected |%s| but got |%s|." , i , member , formalParameters [ i ] , args [ i ] . getClass ( ) ) ; } } return args ;


signature:
public class FitUtils { /** * extracts and removes parameters from a cell .
 * @ param cell cell to process
 * @ return the extracted parameter or { @ code null } */
public static String extractCellParameter ( FitCell cell ) { } }

implementation: final Matcher matcher = PARAMETER_PATTERN . matcher ( cell . getFitValue ( ) ) ; if ( matcher . matches ( ) ) { cell . setFitValue ( matcher . group ( 1 ) ) ; return matcher . group ( 2 ) ; } else { return null ; }


signature:
public class TypedQueryAccessor { /** * javax . persistence . Query & javax . persistence . TypedQuery */
@ Override public java . util . Map < java . lang . String , java . lang . Object > getHints ( ) { } }

implementation: return this . q . getHints ( ) ;


signature:
public class FixtureRunner { /** * / * Altered by Rick Mugridge to dispatch on the first Fixture */
public void doDocument ( FitDocument document ) { } }

implementation: summary . put ( "run date" , new Date ( ) ) ; summary . put ( "run elapsed time" , new RunTime ( ) ) ; if ( document != null ) { interpretTables ( document ) ; }


signature:
public class FixtureRunner { /** * / * Added by Rick Mugridge */
private void interpretTables ( FitDocument documents ) { } }

implementation: for ( FitTable table : documents . tables ( ) ) { try { Fixture fixture = getLinkedFixtureWithArgs ( table ) ; fixture . doTable ( table ) ; counts . tally ( table . getCounts ( ) ) ; } catch ( Throwable e ) { table . exception ( e ) ; counts . exceptions ++ ; } }


signature:
public class FixtureRunner { /** * / * Added from FitNesse */
protected Fixture getLinkedFixtureWithArgs ( FitTable table ) { } }

implementation: Fixture fixture = loadFixture ( table . getFixtureClass ( ) ) ; fixture . setParams ( getArgsForTable ( table ) ) ; return fixture ;


signature:
public class FixtureRunner { /** * Loads a fixutre by its fully quallified { @ code className } .
 * If the { @ code className } is an alias , the referenced class is used .
 * @ param fixtureName name of the fixture to load .
 * @ return instance of the class which is referenced by { @ code fixtureName }
 * @ throws RuntimeException propagated to fit ,
 * thrown if something different went wrong */
private Fixture loadFixture ( final String fixtureName ) { } }

implementation: AliasHelper helper = DependencyManager . getOrCreate ( AliasHelper . class ) ; String realName = helper . getClazz ( fixtureName ) ; return loadFixtureByName ( realName ) ;


signature:
public class SetupFixture { /** * Sets the SSL parameter of the mail { @ link SetupHelper } .
 * @ param ssl indicates whether SSL shall be used
 * @ see SetupHelper # setSSL ( boolean ) SetupHelper . setSSL ( boolean ) */
public void ssl ( final String ssl ) { } }

implementation: DependencyManager . getOrCreate ( SetupHelper . class ) . setSSL ( BooleanTypeHandler . parseBool ( ssl ) ) ;


signature:
public class SetupFixture { /** * Sets the port parameter of the mail { @ link SetupHelper } .
 * @ param port port to use
 * @ see SetupHelper # setPort ( int ) SetupHelper . setPort ( int ) */
public void port ( final String port ) { } }

implementation: DependencyManager . getOrCreate ( SetupHelper . class ) . setPort ( Integer . parseInt ( port ) ) ;


signature:
public class HttpHeader { /** * Test if given HTTP request is performed via XMLHttpRequest .
 * @ param httpRequest HTTP request .
 * @ return true if X - Requested - With header is XMLHttpRequest . */
public static boolean isXHR ( HttpServletRequest httpRequest ) { } }

implementation: String requestedWith = httpRequest . getHeader ( X_REQUESTED_WITH ) ; return requestedWith != null ? requestedWith . equalsIgnoreCase ( XML_HTTP_REQUEST ) : false ;


signature:
public class HttpHeader { /** * Test if HTTP request is from Android .
 * @ param httpRequest HTTP request .
 * @ return true if X - Requested - With header contains j ( s ) - lib android signature . */
public static boolean isAndroid ( HttpServletRequest httpRequest ) { } }

implementation: String requestedWith = httpRequest . getHeader ( X_REQUESTED_WITH ) ; return requestedWith != null ? requestedWith . equalsIgnoreCase ( ANDROID_USER_AGENT ) : false ;


signature:
public class EmptyArgumentsReader { /** * This method is enacted for empty formal parameters . It just return { @ link # EMPTY _ ARGUMENTS } .
 * @ param httpRequest unused HTTP request ,
 * @ param formalParameters unused empty formal parameters list .
 * @ return always return { @ link # EMPTY _ ARGUMENTS } . */
@ Override public Object [ ] read ( HttpServletRequest httpRequest , Type [ ] formalParameters ) throws IOException , IllegalArgumentException { } }

implementation: return EMPTY_ARGUMENTS ;


signature:
public class TimedActionFixture { /** * Traversal / / / / / */
@ Override protected void doRow ( FitRow row ) throws Exception { } }

implementation: Date start = time ( ) ; super . doRow ( row ) ; long split = time ( ) . getTime ( ) - start . getTime ( ) ; FitCell cell = row . append ( ) ; cell . setDisplayValue ( format . format ( start ) ) ; cell . info ( "time" ) ; cell = row . append ( ) ; cell . setDisplayValueRaw ( split < 1000 ? " " : Double . toString ( ( split ) / 1000.0 ) ) ; cell . info ( "split" ) ;


signature:
public class FitTable { /** * FIXME : test ! */
public void remove ( int index ) { } }

implementation: table . select ( TAG ) . get ( index + contentStartPosition ) . remove ( ) ; rows . remove ( index ) ; updateIndices ( ) ;


signature:
public class FitTable { /** * FIXME : test ! */
public FitRow insert ( int index ) { } }

implementation: Element tr = new Element ( Tag . valueOf ( TAG ) , table . baseUri ( ) ) ; FitRow row = new FitRow ( this , tr ) ; Element tbody = table . select ( "tbody" ) . first ( ) ; tbody . insertChildren ( index + contentStartPosition , Collections . singleton ( tr ) ) ; rows . add ( index , row ) ; updateIndices ( ) ; return row ;


signature:
public class StreamArgumentsReader { /** * This method is a this wrapper for { @ link StreamFactory # getInstance ( InputStream , Type ) } .
 * @ param inputStream input stream ,
 * @ param type expected type .
 * @ return stream instance accordingly requested type .
 * @ throws IOException if newly stream creation fails .
 * @ throws IllegalArgumentException if there requested type is not supported . */
@ Override public Object read ( InputStream inputStream , Type type ) throws IOException { } }

implementation: Closeable closeable = StreamFactory . getInstance ( inputStream , type ) ; threadLocal . set ( closeable ) ; return closeable ;


signature:
public class ApplicationScopeFactory { /** * Persist instance bound to given managed instance key . This method simply uses provided < code > instanceKey < / code > argument
 * to add instance to { @ link # instancesPool } . Both arguments should to be not null .
 * @ param instanceKey managed instance key ,
 * @ param instance managed instance . */
@ Override public void persistInstance ( InstanceKey instanceKey , Object instance ) { } }

implementation:
// at this point managed class and instance are guaranteed to be non null
instancesPool . put ( instanceKey , instance ) ;


signature:
public class AbstractCollectionView { /** * Refresh when child elements are created or updated */
@ Subscribe public void handle ( ElementEvent < TEntity > message ) { } }

implementation: if ( message . getEndpoint ( ) . getEntityType ( ) == this . endpoint . getEntityType ( ) ) { refresh ( ) ; }


signature:
public class SetupFixture { /** * Processes the content of { @ code cells } .
 * @ param cells cells to process */
@ Override protected void doCells ( List < FitCell > cells ) { } }

implementation: String name = cells . get ( 0 ) . getFitValue ( ) ; processRowWithCommand ( cells , name ) ;


signature:
public class BeanUtils { /** * Lists all properties on a bean type . Ensures properties annotated with
 * { @ link Id } or called " name " are always listed first .
 * @ param beanType The type of bean to check for properties .
 * @ return A list of properties . */
@ SneakyThrows public static List < PropertyDescriptor > getProperties ( Class < ? > beanType ) { } }

implementation: LinkedList < PropertyDescriptor > properties = new LinkedList < > ( ) ; for ( PropertyDescriptor property : Introspector . getBeanInfo ( beanType ) . getPropertyDescriptors ( ) ) { if ( getAnnotation ( beanType , property , Id . class ) . isPresent ( ) || property . getName ( ) . equals ( "name" ) ) { properties . addFirst ( property ) ; } else { properties . add ( property ) ; } } return properties ;


signature:
public class BeanUtils { /** * Lists all properties on a bean type that have a specific annotation on
 * their getter or backing field .
 * @ param < TAnnotation > The annotation type to look for .
 * @ param beanType The type of bean to check for properties .
 * @ param annotationType The annotation type to look for .
 * @ return A list of matching properties . */
public static < TAnnotation extends Annotation > List < PropertyDescriptor > getPropertiesWithAnnotation ( Class < ? > beanType , Class < TAnnotation > annotationType ) { } }

implementation: LinkedList < PropertyDescriptor > result = new LinkedList < > ( ) ; getProperties ( beanType ) . forEach ( property -> { if ( property . getReadMethod ( ) != null && property . getReadMethod ( ) . getAnnotation ( annotationType ) != null || isFieldAnnotated ( beanType , property . getName ( ) , annotationType ) ) { result . add ( property ) ; } } ) ; return result ;


signature:
public class BeanUtils { /** * Returns an annotation of a specific type on a property ' s getter or its
 * backing field .
 * @ param < TAnnotation > The type of annotation to look for .
 * @ param beanType The type of bean the property is declared on .
 * @ param property The property to check for the annotation .
 * @ param annotationType The type of annotation to look for .
 * @ return The annotation if present . */
public static < TAnnotation extends Annotation > Optional < TAnnotation > getAnnotation ( Class < ? > beanType , PropertyDescriptor property , Class < TAnnotation > annotationType ) { } }

implementation: Optional < TAnnotation > annotation = stream ( property . getReadMethod ( ) . getAnnotationsByType ( annotationType ) ) . findAny ( ) ; return annotation . isPresent ( ) ? annotation : getAnnotationOnField ( beanType , property . getName ( ) , annotationType ) ;


signature:
public class FileFixture { /** * Sets the filename pattern to { @ code pattern } .
 * @ param pattern pattern to use */
public void pattern ( final String pattern ) { } }

implementation: FileFixtureHelper helper = DependencyManager . getOrCreate ( FileFixtureHelper . class ) ; helper . setPattern ( pattern ) ;


signature:
public class FileFixture { /** * Sets the directory to { @ code directory } .
 * @ param directory directory to use */
public void directory ( final String directory ) { } }

implementation: FileFixtureHelper helper = DependencyManager . getOrCreate ( FileFixtureHelper . class ) ; helper . setDirectory ( new File ( directory ) ) ;


signature:
public class FileFixture { /** * Sets the encoding to { @ code encoding } .
 * @ param encoding encoding to use */
public void encoding ( final String encoding ) { } }

implementation: FileFixtureHelper helper = DependencyManager . getOrCreate ( FileFixtureHelper . class ) ; helper . setEncoding ( encoding ) ;


signature:
public class Server { /** * Log formatted message to Java logger since framework logger is not yet initialized .
 * @ param message message with optional formatting elements as supported by { @ link String # format ( String , Object . . . ) } ,
 * @ param args optional arguments .
 * @ return formatted message . */
private static String log ( String message , Object ... args ) { } }

implementation: message = String . format ( message , args ) ; java . util . logging . Logger . getLogger ( Server . class . getCanonicalName ( ) ) . log ( java . util . logging . Level . SEVERE , message ) ; return message ;


signature:
public class JRubyWhois { /** * Uses the Ruby Whois gem to perform a whois lookup
 * @ param domain
 * domain name to lookup
 * @ param timeout
 * timeout in seconds
 * @ return */
public WhoisResult lookup ( String domain , int timeout ) { } }

implementation: container . put ( "domain" , domain ) ; container . put ( "timeout_param" , timeout ) ; try { return ( WhoisResult ) container . runScriptlet ( JRubyWhois . class . getResourceAsStream ( "jruby-whois.rb" ) , "jruby-whois.rb" ) ; } catch ( EvalFailedException e ) { if ( e . getMessage ( ) . startsWith ( "(ServerNotFound)" ) ) { throw new ServerNotFoundException ( e ) ; } if ( e . getMessage ( ) . startsWith ( "(WebInterfaceError" ) ) { throw new WebInterfaceErrorException ( e ) ; } throw e ; }


signature:
public class JRubyWhois { /** * Check if Ruby Whois gem has a parser for a specific registrar
 * @ param whoisHost
 * whois server to check
 * @ return */
public boolean hasParserForWhoisHost ( String whoisHost ) { } }

implementation: container . put ( "host" , whoisHost ) ; return ( Boolean ) container . runScriptlet ( JRubyWhois . class . getResourceAsStream ( "jruby-has-parser.rb" ) , "jruby-has-parser.rb" ) ;


signature:
public class HttpRmiServlet { /** * HTTP - RMI request service . This is the implementation of the
 * { @ link AppServlet # service ( javax . servlet . ServletRequest , javax . servlet . ServletResponse ) } abstract method . It locates
 * remote managed method addressed by request path , deserialize actual parameters from HTTP request , reflexively invoke the
 * method and serialize method returned value to HTTP response .
 * Actual parameters are transported into HTTP request body and are encoded accordingly < code > Content - Type < / code > request
 * header ; for supported parameters encodings please see
 * { @ link ServerEncoders # getArgumentsReader ( HttpServletRequest , Type [ ] ) } factory method . On its side , returned value is
 * transported into HTTP response body too and is encoded accordingly its type - see
 * { @ link ServerEncoders # getValueWriter ( ContentType ) } for supported encodings for returned value .
 * @ param context HTTP request context .
 * @ throws IOException if HTTP request reading fails for any reason . */
@ Override public void handleRequest ( RequestContext context ) throws IOException { } }

implementation:
HttpServletRequest httpRequest = context . getRequest ( ) ; HttpServletResponse httpResponse = context . getResponse ( ) ; Matcher matcher = REQUEST_PATH_PATTERN . matcher ( context . getRequestPath ( ) ) ; if ( ! matcher . find ( ) ) { sendBadRequest ( context ) ; return ; } String interfaceName = className ( matcher . group ( 1 ) ) ; String methodName = matcher . group ( 2 ) ; ManagedMethodSPI managedMethod = null ; ArgumentsReader argumentsReader = null ; Object value = null ; try { ManagedClassSPI managedClass = getManagedClass ( container , interfaceName , httpRequest . getRequestURI ( ) ) ; managedMethod = getManagedMethod ( managedClass , methodName , httpRequest . getRequestURI ( ) ) ; final Type [ ] formalParameters = managedMethod . getParameterTypes ( ) ; argumentsReader = argumentsReaderFactory . getArgumentsReader ( httpRequest , formalParameters ) ; Object [ ] arguments = argumentsReader . read ( httpRequest , formalParameters ) ; Object instance = container . getInstance ( managedClass ) ; value = managedMethod . invoke ( instance , arguments ) ; } catch ( AuthorizationException e ) { sendUnauthorized ( context ) ; return ; } catch ( Throwable t ) { // all exception , including class not found , no such method and illegal argument are send back to client as they are
sendError ( context , t ) ; return ; } finally { if ( argumentsReader != null ) { argumentsReader . clean ( ) ; } } httpResponse . setCharacterEncoding ( "UTF-8" ) ; if ( managedMethod . isVoid ( ) ) { httpResponse . setStatus ( HttpServletResponse . SC_NO_CONTENT ) ; return ; } ContentType contentType = valueWriterFactory . getContentTypeForValue ( value ) ; httpResponse . setStatus ( HttpServletResponse . SC_OK ) ; httpResponse . setContentType ( contentType . getValue ( ) ) ; ValueWriter valueWriter = valueWriterFactory . getValueWriter ( contentType ) ; valueWriter . write ( httpResponse , value ) ;


signature:
public class HttpRmiServlet { /** * Get remotely accessible managed class registered to a certain interface class .
 * @ param container parent container ,
 * @ param interfaceName name of the interface class identifying requested managed class ,
 * @ param requestURI request URI for logging .
 * @ return managed class , never null .
 * @ throws ClassNotFoundException if interface class not found on run - time class path , managed class not defined or is not
 * remotely accessible . */
private static ManagedClassSPI getManagedClass ( ContainerSPI container , String interfaceName , String requestURI ) throws ClassNotFoundException { } }

implementation: Class < ? > interfaceClass = Classes . forOptionalName ( interfaceName ) ; if ( interfaceClass == null ) { log . error ( "HTTP-RMI request for not existing class |%s|." , interfaceName ) ; throw new ClassNotFoundException ( requestURI ) ; } ManagedClassSPI managedClass = container . getManagedClass ( interfaceClass ) ; if ( managedClass == null ) { log . error ( "HTTP-RMI request for not existing managed class |%s|." , interfaceName ) ; throw new ClassNotFoundException ( requestURI ) ; } if ( ! managedClass . isRemotelyAccessible ( ) ) { log . error ( "HTTP-RMI request for local managed class |%s|. See @Remote annotation." , interfaceName ) ; throw new ClassNotFoundException ( requestURI ) ; } return managedClass ;


signature:
public class HttpRmiServlet { /** * Get managed method that is remotely accessible and has requested name .
 * @ param managedClass managed class where method is supposed to be declared ,
 * @ param methodName method name ,
 * @ param requestURI request URI for logging .
 * @ return managed method , never null .
 * @ throws NoSuchMethodException if managed class has not any method with requested name , managed method was found but is
 * not remotely accessible or it returns a { @ link Resource } . */
private static ManagedMethodSPI getManagedMethod ( ManagedClassSPI managedClass , String methodName , String requestURI ) throws NoSuchMethodException { } }

implementation: ManagedMethodSPI managedMethod = managedClass . getNetMethod ( methodName ) ; if ( managedMethod == null ) { log . error ( "HTTP-RMI request for not existing managed method |%s#%s|." , managedClass . getInterfaceClass ( ) . getName ( ) , methodName ) ; throw new NoSuchMethodException ( requestURI ) ; } if ( ! managedMethod . isRemotelyAccessible ( ) ) { log . error ( "HTTP-RMI request for local managed method |%s#%s|. See @Remote annotation." , managedClass . getInterfaceClass ( ) . getName ( ) , methodName ) ; throw new NoSuchMethodException ( requestURI ) ; } if ( Types . isKindOf ( managedMethod . getReturnType ( ) , Resource . class ) ) { log . error ( "HTTP-RMI request for managed method |%s#%s| returning a resource." , managedClass . getInterfaceClass ( ) . getName ( ) , methodName ) ; throw new NoSuchMethodException ( requestURI ) ; } return managedMethod ;


signature:
public class HttpRmiServlet { /** * Extract qualified class name , including inner classes , from class path part of the request path . Class path parameter is
 * the class name but with slash as separator , e . g . < code > / sixqs / site / controller / ParticipantController < / code > . This helper
 * handles inner classes using standard notation with ' $ ' separator ; for example
 * < code > / js / test / net / RmiController / Query < / code > is converted to < code > js . test . net . RmiController $ Query < / code > .
 * Class nesting is not restricted to a single level . For example < code > / js / test / net / RmiController / Query / Item < / code > is
 * converted to < code > js . test . net . RmiController $ Query $ Item < / code > .
 * It is expected that class path argument to be well formed . If class path argument is not valid this method behavior is
 * not defined .
 * @ param classPath qualified class name using slash as separator and with leading path separator .
 * @ return qualified class name using dollar notation for inner classes . */
private static String className ( String classPath ) { } }

implementation:
StringBuilder className = new StringBuilder ( ) ; char separator = '.' ; char c = classPath . charAt ( 1 ) ; // i = 1 to skip leading path separator
for ( int i = 1 ; ; ) { if ( c == '/' ) { c = separator ; } className . append ( c ) ; if ( ++ i == classPath . length ( ) ) { break ; } c = classPath . charAt ( i ) ; // after first class detected change separator to dollar since rest are inner classes
// this solution copes well with not restricted inner level
if ( Character . isUpperCase ( c ) ) { separator = '$' ; } } return className . toString ( ) ;


signature:
public class LogEventAnalyzer { /** * Checks whether the log messages contain the expected exception .
 * @ param parameters parameters to filter the processing
 * ( see { @ link AbstractLoggingEventMatcher } */
public void processNotContainsException ( Map < String , String > parameters ) { } }

implementation: LoggingEvent match = getMessageWithException ( parameters ) ; if ( match == null ) { cell . right ( ) ; } else { cell . wrong ( match . getThrowableInformation ( ) . getThrowableStrRep ( ) [ 0 ] ) ; }


signature:
public class LogEventAnalyzer { /** * Checks whether the log messages do not contain the expected text .
 * @ param parameters parameters to filter the processing
 * ( see { @ link AbstractLoggingEventMatcher } */
public void processNotContains ( Map < String , String > parameters ) { } }

implementation: LoggingEvent match = getMessageWithString ( parameters ) ; if ( match == null ) { cell . right ( ) ; } else { cell . wrong ( match . getMessage ( ) . toString ( ) ) ; }


signature:
public class ResultSetImpl { /** * Get Primitive Wrappers */
public Boolean getBoolean2 ( String columnLabel ) throws java . sql . SQLException { } }

implementation: boolean value = this . rs . getBoolean ( columnLabel ) ; return ! this . rs . wasNull ( ) ? value : null ;


signature:
public class ResultSetImpl { /** * java . sql . Wrapper */
@ Override public boolean isWrapperFor ( java . lang . Class < ? > arg0 ) throws java . sql . SQLException { } }

implementation: return this . rs . isWrapperFor ( arg0 ) ;


signature:
public class Argument { /** * Replaces variables ( if defined ) in the value .
 * @ param vars
 * Variables to use . */
public final void init ( final Map < String , String > vars ) { } }

implementation: value = Utils4J . replaceVars ( getValue ( ) , vars ) ;


signature:
public class AbstractView { /** * Set common HTTP response headers and delegates actual serialization to subclass . This method disables cache and set
 * content type to value returned by subclass .
 * @ param httpResponse HTTP response to serialize view to .
 * @ throws IOException if view serialization fails for whatever reasons . */
@ Override public void serialize ( HttpServletResponse httpResponse ) throws IOException { } }

implementation: httpResponse . setHeader ( HttpHeader . CACHE_CONTROL , HttpHeader . NO_CACHE ) ; httpResponse . addHeader ( HttpHeader . CACHE_CONTROL , HttpHeader . NO_STORE ) ; httpResponse . setHeader ( HttpHeader . PRAGMA , HttpHeader . NO_CACHE ) ; httpResponse . setDateHeader ( HttpHeader . EXPIRES , 0 ) ; httpResponse . setContentType ( getContentType ( ) . getValue ( ) ) ; serialize ( httpResponse . getOutputStream ( ) ) ;


signature:
public class Cookies { /** * Get value of the named cookie or null if cookie does not exist .
 * @ param name cookie name , not null or empty .
 * @ return cookie cookie value or null if there is no cookie with requested name .
 * @ throws IllegalArgumentException if < code > name < / code > argument is null or empty . */
public String get ( String name ) { } }

implementation: Params . notNullOrEmpty ( name , "Cookie name" ) ; if ( cookies == null ) { return null ; } for ( Cookie cookie : cookies ) { if ( name . equals ( cookie . getName ( ) ) ) { return cookie . getValue ( ) ; } } return null ;


signature:
public class Cookies { /** * Add cookie to HTTP response of the current request context . Override cookie value if already exists .
 * @ param name cookie name , not null or empty ,
 * @ param value cookie value , not null or empty .
 * @ throws IllegalArgumentException if < code > name < / code > argument is null or empty .
 * @ throws IllegalArgumentException if < code > value < / code > argument is null or empty . */
public void add ( String name , String value ) { } }

implementation: Params . notNullOrEmpty ( name , "Cookie name" ) ; Params . notNull ( value , "Cookie value" ) ; Cookie cookie = new Cookie ( name , value ) ; cookie . setPath ( "/" ) ; httpResponse . addCookie ( cookie ) ;


signature:
public class Cookies { /** * Convert value object to string and delegates { @ link # add ( String , String ) } . String conversion is performed by
 * { @ link Converter } and may throw { @ link ConverterException } .
 * @ param name cookie name , not null or empty ,
 * @ param value cookie value , not null or empty .
 * @ throws IllegalArgumentException if < code > name < / code > argument is null or empty .
 * @ throws IllegalArgumentException if < code > value < / code > argument is null or empty .
 * @ throws ConverterException if value object has no converter registered or object value serialization fails . */
public void add ( String name , Object value ) { } }

implementation: add ( name , ConverterRegistry . getConverter ( ) . asString ( value ) ) ;


signature:
public class Cookies { /** * Remove cookie from HTTP response . If named cookie does not exist this method does nothing .
 * @ param name the name of the cookie to be removed , not null or empty .
 * @ throws IllegalArgumentException if < code > name < / code > argument is null or empty . */
public void remove ( String name ) { } }

implementation: Params . notNullOrEmpty ( name , "Cookie name" ) ; if ( cookies == null ) { return ; } for ( Cookie cookie : cookies ) { if ( name . equals ( cookie . getName ( ) ) ) { cookie . setMaxAge ( 0 ) ; cookie . setValue ( "" ) ; cookie . setPath ( "/" ) ; httpResponse . addCookie ( cookie ) ; break ; } }


signature:
public class Cookies { /** * Get cookies iterator . Return empty iterator if not cookies on HTTP request .
 * @ return cookies iterator , possible empty . */
public Iterator < Cookie > iterator ( ) { } }

implementation: if ( cookies == null ) { return Collections . emptyIterator ( ) ; } return Arrays . asList ( cookies ) . iterator ( ) ;


signature:
public class ConfigurableInstanceProcessor { /** * Configure instance with configuration object provided by instance managed class . In order to perform instance
 * configuration , instance should implement { @ link Configurable } and managed class should have configuration object , see
 * { @ link ManagedClassSPI # getConfig ( ) } . If both conditions are satisfied this method executes
 * { @ link Configurable # config ( Config ) } on instance .
 * @ param managedClass managed class ,
 * @ param instance instance of given managed class .
 * @ throws BugError if instance configuration fails either due to invalid configuration object or exception on configuration
 * user defined logic . */
@ Override public void postProcessInstance ( ManagedClassSPI managedClass , Object instance ) { } }

implementation: if ( ! ( instance instanceof Configurable ) ) { return ; } Config config = managedClass . getConfig ( ) ; if ( config == null ) { if ( ! ( instance instanceof OptionalConfigurable ) ) { return ; } log . info ( "Default configuration for managed class |%s|." , managedClass ) ; } try { ( ( Configurable ) instance ) . config ( config ) ; } catch ( ConfigException e ) { throw new BugError ( "Invalid configuration for managed class |%s|:\r\n\t- %s" , managedClass , e ) ; } catch ( Throwable t ) { throw new BugError ( t ) ; }


signature:
public class TargetFileListProducerConfig { /** * Returns an existing target file list producer instance or creates a new one if it ' s the first call to this method .
 * @ return TargetFileListProducer of type { @ link # className } . */
public final TargetFileListProducer getTargetFileListProducer ( ) { } }

implementation: if ( tflProducer != null ) { return tflProducer ; } final Object obj = Utils4J . createInstance ( className ) ; if ( ! ( obj instanceof TargetFileListProducer ) ) { throw new IllegalStateException ( "Expected class to be of type '" + TargetFileListProducer . class . getName ( ) + "', but was: " + className ) ; } tflProducer = ( TargetFileListProducer ) obj ; return tflProducer ;


signature:
public class DynamicObjectFactory { /** * Adds a public field to the constructed class .
 * @ param type type of the field
 * @ param name name of the field
 * @ throws ClassNotFoundException indicates a problem with { @ code type } */
public void add ( final Class < ? > type , final String name ) throws ClassNotFoundException { } }

implementation: FieldGen fg ; if ( result != null ) { throw new IllegalStateException ( "Class already generated" ) ; } fg = new FieldGen ( Constants . ACC_PUBLIC | Constants . ACC_SUPER , Type . getType ( type ) , name , cg . getConstantPool ( ) ) ; cg . addField ( fg . getField ( ) ) ;


signature:
public class DynamicObjectFactory { /** * Compiles the class and returns a class object which contains all
 * added fields .
 * @ return dynamic generated class with all added fields . */
public final Class < ? > compile ( ) { } }

implementation: if ( result == null ) { loader . loadJavaClass ( cg . getClassName ( ) , cg . getJavaClass ( ) ) ; try { result = loader . loadClass ( cg . getClassName ( ) ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( e ) ; } } return result ;


signature:
public class Challenge { /** * Test that selected image identified by given token is the right response .
 * @ param token unique token identifying selected image , null or empty tolerated .
 * @ return true if token identifies this challenge response . */
public boolean verifyResponse ( String token ) throws NullPointerException { } }

implementation: return value . equals ( getValue ( tokenedImageFiles . get ( token ) ) ) ;


signature:
public class Challenge { /** * Challenge value associated with image file . File name is converted to lower case , extension removed and non letter
 * characters replaces with space , that is , non letters are considered words separators .
 * @ param file image file , null tolerated .
 * @ return challenge value or null if given file is null . */
private static String getValue ( File file ) throws NullPointerException { } }

implementation: if ( file == null ) { return null ; } return file . getName ( ) . toLowerCase ( ) . replaceAll ( EXTENSION_REX , "" ) . replaceAll ( NOT_LETTERS_REX , " " ) ;


signature:
public class URIUtils { /** * Adds a trailing slash to the URI if it does not already have one .
 * @ param uri The original URI .
 * @ return The URI with appended slash . */
@ SneakyThrows public static URI ensureTrailingSlash ( URI uri ) { } }

implementation: URIBuilder builder = new URIBuilder ( uri ) ; if ( ! builder . getPath ( ) . endsWith ( "/" ) ) { builder . setPath ( builder . getPath ( ) + "/" ) ; } return builder . build ( ) ;


signature:
public class SetupHelper { /** * Generates a properties object which can be used by
 * { @ link de . cologneintelligence . fitgoodies . mail . providers . JavaMailMessageProvider } .
 * Default values are not set .
 * @ return properties object */
public Properties generateProperties ( ) { } }

implementation: Properties result = new Properties ( ) ; if ( proto == null ) { throw new RuntimeException ( "no protocol selected" ) ; } String protocol = proto . toLowerCase ( ) ; setProperty ( result , "mail.store.protocol" , protocol ) ; setProperty ( result , "mail." + protocol + ".host" , host ) ; setProperty ( result , "mail.username" , user ) ; setProperty ( result , "mail.password" , pass ) ; if ( port != 0 ) { setProperty ( result , "mail." + protocol + ".port" , Integer . toString ( port ) ) ; } if ( ssl ) { setProperty ( result , "mail." + protocol + ".ssl" , "true" ) ; } if ( protocol . equals ( "pop3" ) ) { setProperty ( result , "mail.inbox" , "INBOX" ) ; } else { if ( inbox == null ) { throw new RuntimeException ( "no inbox selected" ) ; } setProperty ( result , "mail.inbox" , inbox ) ; } return result ;


signature:
public class TinyContainer { /** * Release resources used by this tiny container instance . After execution this method no HTTP requests can be handled .
 * < b > Implementation note : < / b > tiny container destruction logic is based on assumption that this
 * < code > contextDestroyed < / code > handler is called after all web application ' s servlets destruction . Here is the relevant
 * excerpt from API - DOC : < em > All servlets and filters have been destroy ( ) ed before any ServletContextListeners are notified
 * of context destruction . < / em >
 * @ param contextEvent context event provided by servlet container . */
@ Override public void contextDestroyed ( ServletContextEvent contextEvent ) { } }

implementation: log . debug ( "Context |%s| destroying." , appName ) ; try { destroy ( ) ; } catch ( Throwable t ) { log . dump ( String . format ( "Fatal error on container |%s| destroy:" , appName ) , t ) ; }


signature:
public class TinyContainer { /** * SECURITY CONTEXT INTERFACE */
@ Override public boolean login ( String username , String password ) { } }

implementation:
try { getHttpServletRequest ( ) . login ( username , password ) ; } catch ( ServletException e ) { // exception is thrown if request is already authenticated , servlet container authentication is not enabled or
// credentials are not accepted
// consider all these conditions as login fail but record the event to application logger
log . debug ( e ) ; return false ; } return true ;


signature:
public class TinyContainer { /** * Get HTTP request from current request context .
 * @ return current HTTP request .
 * @ throws BugError if attempt to use not initialized HTTP request . */
private HttpServletRequest getHttpServletRequest ( ) { } }

implementation: RequestContext context = getInstance ( RequestContext . class ) ; HttpServletRequest request = context . getRequest ( ) ; if ( request == null ) { throw new BugError ( "Attempt to use not initialized HTTP request." ) ; } return request ;


signature:
public class ManagedProxyHandler { /** * Invocation handler implementation . Every method invocation on managed class interface is routed to this point . Here
 * actual container services are implemented and method is invoked against wrapped instance .
 * @ param proxy instance of dynamically generated Java Proxy ,
 * @ param method interface Java method about to invoke ,
 * @ param args method invocation arguments .
 * @ return value returned by implementation method .
 * @ throws Throwable forward any exception rose by implementation method . */
@ Override public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { } }

implementation:
final ManagedMethodSPI managedMethod = managedClass . getManagedMethod ( method ) ; log . trace ( "Invoke |%s|." , managedMethod ) ; if ( ! managedMethod . isTransactional ( ) ) { // execute managed method that is not included within transactional boundaries
try { return managedMethod . invoke ( managedInstance , args ) ; } catch ( Throwable t ) { throw throwable ( t , "Non transactional method |%s| invocation fails." , managedMethod ) ; } } if ( managedMethod . isImmutable ( ) ) { return executeImmutableTransaction ( managedMethod , args ) ; } return executeMutableTransaction ( managedMethod , args ) ;


signature:
public class ManagedProxyHandler { /** * Helper method for mutable transaction execution .
 * @ param managedMethod managed method to be executed into transactional scope ,
 * @ param args managed method arguments .
 * @ return value returned by managed method .
 * @ throws Throwable forward any error rose by method execution . */
private Object executeMutableTransaction ( ManagedMethodSPI managedMethod , Object [ ] args ) throws Throwable { } }

implementation:
// store transaction session on current thread via transactional resource utility
// it may happen to have multiple nested transaction on current thread
// since all are created by the same transactional resource , all are part of the same session
// and there is no harm if storeSession is invoked multiple times
// also performance penalty is comparable with the effort to prevent this multiple write
Transaction transaction = transactionalResource . createTransaction ( ) ; transactionalResource . storeSession ( transaction . getSession ( ) ) ; try { Object result = managedMethod . invoke ( managedInstance , args ) ; transaction . commit ( ) ; if ( transaction . unused ( ) ) { log . debug ( "Method |%s| superfluously declared transactional." , managedMethod ) ; } return result ; } catch ( Throwable throwable ) { transaction . rollback ( ) ; throw throwable ( throwable , "Mutable transactional method |%s| invocation fail." , managedMethod ) ; } finally { if ( transaction . close ( ) ) { // it may happen to have multiple nested transaction on this thread
// if this is the case , remove session from current thread only if outermost transaction is closed
// of course if not nested transactions , remove at once
transactionalResource . releaseSession ( ) ; } }


signature:
public class ManagedProxyHandler { /** * Helper method for immutable transaction execution .
 * @ param managedMethod managed method to be executed into transactional scope ,
 * @ param args managed method arguments .
 * @ return value returned by managed method .
 * @ throws Throwable forward any error rose by method execution . */
private Object executeImmutableTransaction ( ManagedMethodSPI managedMethod , Object [ ] args ) throws Throwable { } }

implementation:
Transaction transaction = transactionalResource . createReadOnlyTransaction ( ) ; // see mutable transaction comment
transactionalResource . storeSession ( transaction . getSession ( ) ) ; try { Object result = managedMethod . invoke ( managedInstance , args ) ; if ( transaction . unused ( ) ) { log . debug ( "Method |%s| superfluously declared transactional." , managedMethod ) ; } return result ; } catch ( Throwable throwable ) { throw throwable ( throwable , "Immutable transactional method |%s| invocation fail." , managedMethod ) ; } finally { if ( transaction . close ( ) ) { // see mutable transaction comment
transactionalResource . releaseSession ( ) ; } }


signature:
public class ManagedProxyHandler { /** * Prepare given throwable and dump it to logger with formatted message . Return prepared throwable . If throwable is
 * { @ link InvocationTargetException } or its unchecked related version , { @ link InvocationException } replace it with root
 * cause .
 * @ param throwable throwable instance ,
 * @ param message formatted error message ,
 * @ param args optional formatted message arguments .
 * @ return prepared throwable . */
private static Throwable throwable ( Throwable throwable , String message , Object ... args ) { } }

implementation: Throwable t = throwable ; if ( t instanceof InvocationException && t . getCause ( ) != null ) { t = t . getCause ( ) ; } if ( t instanceof InvocationTargetException && ( ( InvocationTargetException ) t ) . getTargetException ( ) != null ) { t = ( ( InvocationTargetException ) t ) . getTargetException ( ) ; } message = String . format ( message , args ) ; log . dump ( message , t ) ; return t ;


signature:
public class FileSelector { /** * Returns the only file that matches the pattern . If no file matches , a
 * < code > null < / code > . If more than one file matches , a
 * { @ link FilenameNotUniqueException } is thrown .
 * @ return the matching file or < code > null < / code > if no file matched
 * @ throws FilenameNotUniqueException more than one file matched the pattern
 * @ throws FileNotFoundException thrown , if the directory does not exist . */
public File getUniqueFile ( ) throws FilenameNotUniqueException , FileNotFoundException { } }

implementation: File [ ] files = directory . listFiles ( filter ) ; if ( files == null || files . length == 0 ) { throw new FileNotFoundException ( ) ; } if ( files . length > 1 ) { throw new FilenameNotUniqueException ( filter . getPattern ( ) ) ; } return files [ 0 ] ;


signature:
public class FileSelector { /** * Returns a list of all matching files .
 * @ return all files which match the pattern */
public File [ ] getFiles ( ) { } }

implementation: final File [ ] files = directory . listFiles ( filter ) ; if ( files == null ) { return new File [ 0 ] ; } else { return files ; }


signature:
public class FileSelector { /** * Returns the last matching file .
 * @ return the matching file or < code > null < / code > if no file matches
 * @ throws FileNotFoundException thrown , if the directory does not exist */
public File getLastFile ( ) throws FileNotFoundException { } }

implementation: File [ ] files = directory . listFiles ( filter ) ; if ( files == null || files . length == 0 ) { throw new FileNotFoundException ( ) ; } return files [ files . length - 1 ] ;


signature:
public class LogFixture { /** * Processes the table row { @ code cells } .
 * @ param cells row to parse and process */
@ Override protected void doCells ( List < FitCell > cells ) { } }

implementation: this . cells = cells ; this . appender = getAppender ( ) ; if ( appender != null ) { try { executeCommand ( ) ; } catch ( final IllegalArgumentException e ) { cells . get ( COMMAND_COLUMN ) . exception ( "Illegal Format" ) ; } }


signature:
public class ThreadScopeFactory { /** * Retrieve instance from current thread , bound to given managed class or null if none found . Uses provided managed instance
 * key to get instance from { @ link # instancesPool } . Instance key argument should be not null .
 * @ param instanceKey managed instance key .
 * @ return current thread managed instance or null . */
@ Override public Object getInstance ( InstanceKey instanceKey ) { } }

implementation:
// at this point managed class is guaranteed to be non null
ThreadLocal < Object > tls = instancesPool . get ( instanceKey ) ; if ( tls == null ) { synchronized ( instancesPool ) { tls = instancesPool . get ( instanceKey ) ; if ( tls == null ) { tls = new ThreadLocal < > ( ) ; instancesPool . put ( instanceKey , tls ) ; } } return null ; } return tls . get ( ) ;


signature:
public class ThreadScopeFactory { /** * Persist instance on current thread bound to given managed class . This method simply uses provided instance key argument
 * to add instance to { @ link # instancesPool } . Both arguments should to be not null .
 * @ param instanceKey managed instance key ,
 * @ param instance managed instance . */
@ Override public void persistInstance ( InstanceKey instanceKey , Object instance ) { } }

implementation:
// at this point managed class and instance are guaranteed to be non null
ThreadLocal < Object > tls = instancesPool . get ( instanceKey ) ; if ( tls == null ) { throw new BugError ( "Invalid methods invocation sequence. Ensure getInstance() is invoked before and is executed in the same thread." ) ; } tls . set ( instance ) ;


signature:
public class ThreadScopeFactory { /** * Clear all threads local storage and { @ link # instancesPool } . */
@ Override public void clear ( ) { } }

implementation: for ( ThreadLocal < Object > threadLocal : instancesPool . values ( ) ) { threadLocal . remove ( ) ; } instancesPool . clear ( ) ;


signature:
public class EventStreamServlet { /** * Beside initialization inherited from { @ link AppServlet # init ( ServletConfig ) } this method takes care to initialize event
 * stream manager reference .
 * @ param config servlet configuration object .
 * @ throws UnavailableException if servlet initialization fails . */
@ Override public void init ( ServletConfig config ) throws UnavailableException { } }

implementation: super . init ( config ) ; log . trace ( "init(ServletConfig)" ) ; eventStreamManager = container . getInstance ( EventStreamManager . class ) ;


signature:
public class EventStreamServlet { /** * Create { @ link EventStream } for session ID from request URI and run { @ link EventStream # loop ( ) } as far it returns true .
 * This method takes also care to handle connections errors due to network or client failure . At event stream loop exit ,
 * graceful or due to error , unbind event stream from manager .
 * If event stream cannot be created due to bad session ID responds with bad request , error code 400.
 * Note that this method does not return as long client requesting for event stream is connected , keeping HTTP request
 * thread and servlet allocated , even there is no event to send for this particular client .
 * @ param context HTTP request context .
 * @ throws IOException if HTTP response output stream fail to open . */
@ Override protected void handleRequest ( RequestContext context ) throws IOException { } }

implementation:
log . trace ( "handleRequest(RequestContext)" ) ; final HttpServletResponse httpResponse = context . getResponse ( ) ; final String sessionID = getEventStreamSessionID ( context . getRequestPath ( ) ) ; EventStream eventStream = eventStreamManager . createEventStream ( sessionID ) ; if ( eventStream == null ) { // a bad or heavy loaded client may send this request after session expiration or attempt to reuse old session ID
sendBadRequest ( context ) ; return ; } // 1 . headers and content type should be initialized before response commit
// 2 . it seems that ServletResponse # getWriter ( ) updates character set
// excerpt from apidoc :
// If the response ' s character encoding has not been specified as described in getCharacterEncoding ( i . e . , the method
// just returns the default value ISO - 8859-1 ) , getWriter updates it to ISO - 8859-1.
// so need to be sure headers are updated before writer opened
httpResponse . setContentType ( "text/event-stream;charset=UTF-8" ) ; // no need to explicitly set character encoding since is already set by content type
// httpResponse . setCharacterEncoding ( " UTF - 8 " ) ;
httpResponse . setHeader ( HttpHeader . CACHE_CONTROL , HttpHeader . NO_CACHE ) ; httpResponse . addHeader ( HttpHeader . CACHE_CONTROL , HttpHeader . NO_STORE ) ; httpResponse . setHeader ( HttpHeader . PRAGMA , HttpHeader . NO_CACHE ) ; httpResponse . setDateHeader ( HttpHeader . EXPIRES , 0 ) ; httpResponse . setHeader ( HttpHeader . CONNECTION , HttpHeader . KEEP_ALIVE ) ; eventStream . setRemoteHost ( context . getRemoteHost ( ) ) ; eventStream . setWriter ( httpResponse . getWriter ( ) ) ; try { eventStream . onOpen ( ) ; log . debug ( "Event stream |%s| opened." , eventStream ) ; while ( eventStream . loop ( ) ) { } } finally { eventStream . onClose ( ) ; eventStreamManager . destroyEventStream ( eventStream ) ; log . debug ( "Event stream |%s| closed." , sessionID ) ; }


signature:
public class EventStreamServlet { /** * Extract event stream session ID from request path . This method extracts last path component from request path with
 * extension removed , if present . It is a sort of < code > basename < / code > from file path . All next request paths with return
 * the same session ID , < code > 1234 < / code > :
 * < ul >
 * < li > / 1234 . event ,
 * < li > / event / 1234,
 * < li > / 1234,
 * < li > / admin / 1234 . event
 * < li > / admin / event / 1234
 * < / ul >
 * This allows for flexible event stream servlet mapping on deployment descriptor . Both mapping by path and extension can be
 * used . Also extension can be anything . Anyway , this flexibility comes with a constraint : session ID cannot contain slash
 * ( / ) or dot ( . ) .
 * Session ID is generated by event stream manager when client subscribes , see
 * { @ link EventStreamManager # subscribe ( EventStreamConfig ) } , then client sends session ID back to this servlet , as a HTTP
 * request .
 * @ param requestPath request path , not null and with leading path separator .
 * @ return event stream session ID , never null . */
private static String getEventStreamSessionID ( String requestPath ) { } }

implementation:
int extensionSeparator = requestPath . lastIndexOf ( '.' ) ; if ( extensionSeparator == - 1 ) { extensionSeparator = requestPath . length ( ) ; } // request URI is guaranteed to start with path separator
// anyway , if missing below pathSeparator will be - 1 + 1 = 0 , pointing to entire request URI
int pathSeparator = requestPath . lastIndexOf ( '/' , extensionSeparator ) + 1 ; return requestPath . substring ( pathSeparator , extensionSeparator ) ;


signature:
public class AbstractElementView { /** * Saves the input and closes the { @ link Window } ( if present ) . */
public void save ( ) { } }

implementation:
try { onSave ( ) ; close ( ) ; } catch ( IOException | IllegalArgumentException | IllegalAccessException | Validator . InvalidValueException ex ) { onError ( ex ) ; } catch ( IllegalStateException ex ) { // This usually inidicates a " lost update "
ConfirmDialog . show ( getUI ( ) , ex . getLocalizedMessage ( ) + "\nDo you want to refresh this page loosing any changes you have made?" , ( ConfirmDialog cd ) -> { if ( cd . isConfirmed ( ) ) { refresh ( ) ; } } ) ; }


signature:
public class SetupHelper { /** * Sets the database driver . { @ code driverName } must be a fully
 * qualified class name and the class must be in java ' s class path .
 * Unless the driver is already registered , { @ code setProvider }
 * registers it at the { @ code java . sql . DriverManager } .
 * @ param driverName fully qualified class name of a { @ code java . sql . Driver } .
 * @ throws Exception thrown if the class could not be found , casted or
 * registered . */
public static void setProvider ( final String driverName ) throws Exception { } }

implementation: Driver driver = ( Driver ) Class . forName ( driverName ) . newInstance ( ) ; Enumeration < Driver > drivers = DriverManager . getDrivers ( ) ; while ( drivers . hasMoreElements ( ) ) { if ( drivers . nextElement ( ) . getClass ( ) . equals ( driver . getClass ( ) ) ) { return ; } } DriverManager . registerDriver ( driver ) ;


signature:
public class AbstractParser { /** * Returns the parser configuration .
 * @ param config
 * Wrapping parser configuration that contains the concrete one .
 * @ return Parser specific configuration . */
@ SuppressWarnings ( "unchecked" ) protected final CONFIG_TYPE getConcreteConfig ( final ParserConfig config ) { } }

implementation: final Config < ParserConfig > cfg = config . getConfig ( ) ; if ( cfg == null ) { throw new IllegalStateException ( "The configuration is expected to be of type '" + concreteConfigClass . getName ( ) + "', but was: null" ) ; } else { if ( ! ( concreteConfigClass . isAssignableFrom ( cfg . getConfig ( ) . getClass ( ) ) ) ) { throw new IllegalStateException ( "The configuration is expected to be of type '" + concreteConfigClass . getName ( ) + "', but was: " + cfg . getConfig ( ) . getClass ( ) . getName ( ) + " - Did you add the configuration class to the JXB context?" ) ; } } return ( CONFIG_TYPE ) cfg . getConfig ( ) ;


signature:
public class RequestPreprocessor { /** * Load locale codes and security domains lists from filter parameters . Filter parameter is a list of command separated
 * items . If related filter parameter is not declared , field is initialized to empty list .
 * This filter loads tiny container reference from servlet context attribute { @ link TinyContainer # ATTR _ INSTANCE } . If there
 * is no servlet context attribute with the that name this initialization fails with filter permanently unavailable .
 * @ param config filter configuration object .
 * @ throws UnavailableException if tiny container is not properly initialized . */
@ Override public void init ( FilterConfig config ) throws UnavailableException { } }

implementation:
log . trace ( "init(FilterConfig)" ) ; // is safe to store container reference on filter instance since container has application life span
container = ( ContainerSPI ) config . getServletContext ( ) . getAttribute ( TinyContainer . ATTR_INSTANCE ) ; if ( container == null ) { log . fatal ( "Tiny container instance not properly created, probably misconfigured. Request preprocessor permanently unvailable." ) ; throw new UnavailableException ( "Tiny container instance not properly created, probably misconfigured." ) ; } String localeParameter = config . getInitParameter ( PARAM_LOCALE ) ; if ( localeParameter != null ) { locales = Strings . split ( localeParameter , ',' ) ; for ( String locale : locales ) { log . debug ( "Register locale |%s| for request pre-processing." , locale ) ; } } String securityDomainParameter = config . getInitParameter ( PARAM_SECURITY_DOMAIN ) ; if ( securityDomainParameter != null ) { securityDomains = Strings . split ( securityDomainParameter , ',' ) ; for ( String securityDomain : securityDomains ) { log . debug ( "Register security domain |%s| for request pre-processing." , securityDomain ) ; } }


signature:
public class RequestPreprocessor { /** * Search request URI for locale and security domain , by comparing with internal lists , and remove found values . Update
 * locale , security domain and request path on context request from current thread , see
 * { @ link RequestContext # setLocale ( Locale ) } , { @ link RequestContext # setSecurityDomain ( String ) } and
 * { @ link RequestContext # setRequestPath ( String ) } .
 * Remove locale and security context from current request URI and forward it . If current request URI is for a static
 * resource , that is , an existing file this filter does nothing .
 * It is considered a resource not found and rejected with 404 if a request URI contains a locale code that is not listed
 * into filter parameter . If < code > locale < / code > filter parameter is not declared all locale code that may be present into
 * request URI are passed unprocessed . If request URI contains a security domain that is not listed into
 * < code > security - domain < / code > filter parameter , it is forwarded unprocessed .
 * @ param request servlet request ,
 * @ param response servlet response ,
 * @ param chain filter chain .
 * @ throws IOException for failure on underlying request and response streams .
 * @ throws ServletException if filter chaining or request forwarding fails . */
@ Override public void doFilter ( ServletRequest request , ServletResponse response , FilterChain chain ) throws IOException , ServletException { } }

implementation:
HttpServletRequest httpRequest = ( HttpServletRequest ) request ; String requestURI = httpRequest . getRequestURI ( ) ; String contextPath = httpRequest . getContextPath ( ) ; String requestPath = requestURI . substring ( contextPath . length ( ) ) ; // request - uri = context - path request - path
// context - path = " / " path - component
// request - path = 1 * ( " / " path - component )
File file = new File ( request . getServletContext ( ) . getRealPath ( requestPath ) ) ; if ( file . exists ( ) ) { chain . doFilter ( request , response ) ; return ; } // request - path = [ " / " locale ] [ " / " security - domain ] 1 * ( " / " path - component )
RequestContext context = container . getInstance ( RequestContext . class ) ; String queryString = httpRequest . getQueryString ( ) ; context . setRequestURL ( queryString != null ? Strings . concat ( requestURI , '?' , queryString ) : requestURI ) ; if ( ! locales . isEmpty ( ) ) { for ( String locale : locales ) { if ( startsWith ( requestPath , locale ) ) { requestPath = requestPath . substring ( locale . length ( ) + 1 ) ; context . setLocale ( new Locale ( locale ) ) ; break ; } } } for ( String securityDomain : securityDomains ) { if ( startsWith ( requestPath , securityDomain ) ) { requestPath = requestPath . substring ( securityDomain . length ( ) + 1 ) ; context . setSecurityDomain ( securityDomain ) ; break ; } } context . setRequestPath ( requestPath ) ; request . getRequestDispatcher ( requestPath ) . forward ( request , response ) ;


signature:
public class RequestPreprocessor { /** * Test if request path starts with path component . This predicate returns true if first path component from given request
 * path equals requested path component . Comparison is not case sensitive . Request path should start with path separator ,
 * otherwise this predicate returns false .
 * @ param requestPath request path to test ,
 * @ param pathComponent path component that is compared with first path component from request path .
 * @ return true if request path starts with path component . */
private static boolean startsWith ( String requestPath , String pathComponent ) { } }

implementation: if ( requestPath . charAt ( 0 ) != '/' ) { return false ; } int i = 1 ; for ( int j = 0 ; i < requestPath . length ( ) ; ++ i , ++ j ) { if ( requestPath . charAt ( i ) == '/' ) { return j == pathComponent . length ( ) ; } if ( j == pathComponent . length ( ) ) { return false ; } if ( Character . toLowerCase ( requestPath . charAt ( i ) ) != Character . toLowerCase ( pathComponent . charAt ( j ) ) ) { return false ; } } return false ;


signature:
public class EMFGeneratorConfig { /** * Returns a list of factories for the given model type .
 * @ param modelType
 * Model type to return artifact factories for .
 * @ return List of factories that accept the given model type .
 * @ param < MODEL >
 * Type of the model to create an artifact for . */
@ SuppressWarnings ( "unchecked" ) @ NotNull public final < MODEL > List < ArtifactFactory < MODEL > > getFactories ( final Class < MODEL > modelType ) { } }

implementation: final List < ArtifactFactory < MODEL > > list = new ArrayList < ArtifactFactory < MODEL > > ( ) ; if ( factories == null ) { factories = new ArrayList < ArtifactFactory < ? > > ( ) ; if ( factoryConfigs != null ) { for ( final ArtifactFactoryConfig factoryConfig : factoryConfigs ) { factories . add ( factoryConfig . getFactory ( ) ) ; } } } for ( final ArtifactFactory < ? > factory : factories ) { if ( modelType . isAssignableFrom ( factory . getModelType ( ) ) ) { list . add ( ( ArtifactFactory < MODEL > ) factory ) ; } } return list ;


signature:
public class FitDateHelper { /** * Parses { @ code string } and returns a valid Date object .
 * For parsing , a { @ link SimpleDateFormat } object is used .
 * @ param string the string which represents the date
 * @ return the date which is represented by { @ code string }
 * @ throws ParseException thrown , if { @ code string } can not be parsed . */
public Date getDate ( final String string ) throws ParseException { } }

implementation: return getDateFormat ( format , locale ) . parse ( string ) ;


signature:
public class FitDateHelper { /** * Parses { @ code string } and returns a valid Date object .
 * For parsing , a { @ link SimpleDateFormat } object is used .
 * @ param string the string which represents the date
 * @ param formatString a valid SimpleDateFormat format string
 * @ param localeName the name of the locale to use , for example en _ US
 * @ return the date which is represented by { @ code string }
 * @ throws ParseException thrown , if { @ code string } can not be parsed . */
public Date getDate ( final String string , final String formatString , final String localeName ) throws ParseException { } }

implementation: return getDateFormat ( formatString , parseLocale ( localeName ) ) . parse ( string ) ;


signature:
public class ViewComponent { /** * Wraps the control in a { @ link Window } .
 * @ return The newly created window . */
protected Window asWindow ( ) { } }

implementation: if ( containingWindow == null ) { containingWindow = new Window ( getCaption ( ) , this ) ; containingWindow . setWidth ( 80 , Unit . PERCENTAGE ) ; containingWindow . setHeight ( 80 , Unit . PERCENTAGE ) ; containingWindow . center ( ) ; } return containingWindow ;


signature:
public class SessionScopeFactory { /** * Retrieve instance from current HTTP session , bound to given instance key or null if none found . Uses provided instance
 * key argument as HTTP session attribute name . Managed instance key argument should be not null .
 * Access to HTTP session is obtained from HTTP request ; therefore , it is considered a bug if attempt to use this method
 * outside a HTTP request thread .
 * Implementation note : this method could have side effect . It < b > creates the HTTP session < / b > if there is none on current
 * HTTP request .
 * @ param instanceKey managed instance key ,
 * @ return managed instance or null .
 * @ throws BugError if attempt to use this method outside a HTTP request . */
@ Override public Object getInstance ( InstanceKey instanceKey ) { } }

implementation:
// at this point managed instance key is guaranteed to be non null
// SESSION instances are stored on current HTTP session as named attribute value , using provided instance key
// HTTP session is created on the fly if necessary
// if HTTP session exists and possesses an attribute with instance key , simply returns stored instance
// when HTTP session expires attribute values are removed and SESSION instances are garbage collected
HttpSession httpSession = getSession ( instanceKey ) ; return httpSession . getAttribute ( instanceKey . getValue ( ) ) ;


signature:
public class SessionScopeFactory { /** * Persist instance on current HTTP session , bound to given managed instance key . This method simply uses
 * < code > instanceKey < / code > to add instance as HTTP session attribute . Both arguments should to be not null .
 * Access to HTTP session is obtained from HTTP request ; therefore , it is considered a bug if attempt to use this method
 * outside a HTTP request thread .
 * Implementation note : this method could have side effect . It < b > creates the HTTP session < / b > if there is none on current
 * HTTP request .
 * @ param instanceKey managed instance key ,
 * @ param instance managed instance .
 * @ throws BugError if attempt to use this method outside a HTTP request . */
@ Override public void persistInstance ( InstanceKey instanceKey , Object instance ) { } }

implementation:
// at this point key and instance arguments are guaranteed to be non null
HttpSession httpSession = getSession ( instanceKey ) ; httpSession . setAttribute ( instanceKey . getValue ( ) , instance ) ;


signature:
public class SessionScopeFactory { /** * Get HTTP session from current request , creating it if necessary . This method should be call inside a request context
 * otherwise bug error is thrown .
 * @ param instanceKey managed instance key .
 * @ return current request HTTP session .
 * @ throws BugError if attempt to use this method outside a HTTP request . */
private HttpSession getSession ( InstanceKey instanceKey ) { } }

implementation:
RequestContext requestContext = appFactory . getInstance ( RequestContext . class ) ; HttpServletRequest httpRequest = requestContext . getRequest ( ) ; if ( httpRequest == null ) { throw new BugError ( "Invalid web context due to null HTTP request. Cannot create managed instance for |%s| with scope SESSION." , instanceKey ) ; } // create HTTP session if missing ; accordingly API httpSession is never null if ' create ' flag is true
return httpRequest . getSession ( true ) ;


signature:
public class FileResource { /** * Serialize this file resource to HTTP response . Disable cache and set content type and content length .
 * @ param httpResponse HTTP response .
 * @ throws IOException if writing to underlying stream fails . */
@ Override public void serialize ( HttpServletResponse httpResponse ) throws IOException { } }

implementation: httpResponse . setHeader ( HttpHeader . CACHE_CONTROL , HttpHeader . NO_CACHE ) ; httpResponse . addHeader ( HttpHeader . CACHE_CONTROL , HttpHeader . NO_STORE ) ; httpResponse . setHeader ( HttpHeader . PRAGMA , HttpHeader . NO_CACHE ) ; httpResponse . setDateHeader ( HttpHeader . EXPIRES , 0 ) ; httpResponse . setContentType ( contentType ) ; httpResponse . setHeader ( HttpHeader . CONTENT_LENGTH , Long . toString ( file . length ( ) ) ) ; Files . copy ( file , httpResponse . getOutputStream ( ) ) ;


signature:
public class ColumnFixture { /** * Replacement of { @ code doRows ( Parse ) } which resolves question marks
 * in the first row and calls fit . ColumnFixture . doRows ( Parse ) .
 * Question marks represent method calls ,
 * so getValue ( ) and getValue ? are equivalent .
 * @ param rows rows to be processed */
@ Override protected void doRows ( final List < FitRow > rows ) throws Exception { } }

implementation: FitRow headerRow = rows . get ( 0 ) ; columnParameters = extractColumnParameters ( headerRow ) ; bind ( headerRow ) ; super . doRows ( rows . subList ( 1 , rows . size ( ) ) ) ;


signature:
public class ColumnFixture { /** * Replacement of { @ code doCell } which resolves cross - references
 * before calling the original { @ code doCell } method of fit .
 * @ param cell the cell to check
 * @ param column the selected column
 * @ see Fixture # doCell ( FitCell , int ) fit . Fixture . doCell ( Parse , int ) */
@ Override protected void doCell ( final FitCell cell , final int column ) { } }

implementation: ValueReceiver receiver = columnBindings [ column ] ; String currentCellParameter = saveGet ( column , columnParameters ) ; if ( receiver != null && ! cell . getFitValue ( ) . trim ( ) . isEmpty ( ) && receiver . canSet ( ) ) { setValue ( cell , receiver , currentCellParameter ) ; } else { check ( cell , receiver , currentCellParameter ) ; }


signature:
public class ColumnFixture { /** * Utility / / / / / */
protected void bind ( FitRow heads ) { } }

implementation: columnBindings = new ValueReceiver [ heads . size ( ) ] ; for ( int i = 0 ; i < columnBindings . length ; i ++ ) { FitCell cell = heads . cells ( ) . get ( i ) ; String name = cell . getFitValue ( ) ; try { columnBindings [ i ] = createReceiver ( this , name ) ; } catch ( Exception e ) { cell . exception ( e ) ; } }


signature:
public class EntryEndpoint { /** * Fetches meta data such as links from the server .
 * @ throws IOException Network communication failed .
 * @ throws IllegalArgumentException { @ link HttpStatus # SC _ BAD _ REQUEST }
 * @ throws IllegalAccessException { @ link HttpStatus # SC _ UNAUTHORIZED } or
 * { @ link HttpStatus # SC _ FORBIDDEN }
 * @ throws FileNotFoundException { @ link HttpStatus # SC _ NOT _ FOUND } or
 * { @ link HttpStatus # SC _ GONE }
 * @ throws IllegalStateException { @ link HttpStatus # SC _ CONFLICT }
 * @ throws RuntimeException Other non - success status code . */
public void readMeta ( ) throws IOException , IllegalArgumentException , IllegalAccessException , FileNotFoundException , IllegalStateException { } }

implementation: executeAndHandle ( Request . Get ( uri ) ) ;


signature:
public class MemoryStream { /** * Implements Serializable */
private void writeObject ( ObjectOutputStream out ) throws IOException { } }

implementation: out . writeInt ( this . blockSize ) ; out . writeLong ( this . count ) ; out . writeInt ( this . lastLen ) ; out . writeInt ( getNodeCount ( ) ) ; Node n = this . nodeList . first ; while ( n != null ) { out . writeObject ( n . buf ) ; n = n . next ; }


signature:
public class ResourceServlet { /** * Beside initialization performed by { @ link AppServlet # init ( ServletConfig ) } this method takes care to load resource methods
 * cache . A resource method is a remotely accessible method that returns a { @ link Resource } . Map storage key is generated by
 * { @ link # key ( ManagedMethodSPI ) } based on controller and resource method request paths and is paired with retrieval key -
 * { @ link # key ( String ) } , generated from request path when method invocation occurs .
 * @ param config servlet configuration object .
 * @ throws UnavailableException if tiny container is not properly initialized . */
@ Override public void init ( ServletConfig config ) throws UnavailableException { } }

implementation: super . init ( config ) ; for ( ManagedMethodSPI method : container . getManagedMethods ( ) ) { if ( Types . isKindOf ( method . getReturnType ( ) , Resource . class ) ) { resourceMethods . put ( key ( method ) , method ) ; } }


signature:
public class ResourceServlet { /** * Handle request for a resource . Locate resource method based on request path from request context , execute method and
 * serialize back to client returned resource . See class description for general behavior .
 * @ param context request context .
 * @ throws ServletException if a servlet container service fails .
 * @ throws IOException if reading from HTTP request or writing to HTTP response fail . */
@ Override protected void handleRequest ( RequestContext context ) throws ServletException , IOException { } }

implementation:
// for exceptions generated before response commit uses HttpServletResponse . sendError
// on send error , servlet container prepares error response using container internal HTML for response body
// if < error - page > is configured into deployment descriptor servlet container uses that HTML for response body
final HttpServletRequest httpRequest = context . getRequest ( ) ; final HttpServletResponse httpResponse = context . getResponse ( ) ; ArgumentsReader argumentsReader = null ; Resource resource = null ; try { ManagedMethodSPI method = resourceMethods . get ( key ( context . getRequestPath ( ) ) ) ; if ( method == null ) { throw new NoSuchMethodException ( httpRequest . getRequestURI ( ) ) ; } final Type [ ] formalParameters = method . getParameterTypes ( ) ; argumentsReader = argumentsReaderFactory . getArgumentsReader ( httpRequest , formalParameters ) ; Object [ ] arguments = argumentsReader . read ( httpRequest , formalParameters ) ; Object controller = container . getInstance ( method . getDeclaringClass ( ) ) ; resource = method . invoke ( controller , arguments ) ; if ( resource == null ) { throw new BugError ( "Null resource |%s|." , httpRequest . getRequestURI ( ) ) ; } } catch ( AuthorizationException e ) { // at this point , resource is private and need to redirect to a login page
// if application provides one , tiny container is configured with , and use it
// otherwise servlet container should have one
// if no login page found send back servlet container error - that could be custom error page , if declared
String loginPage = container . getLoginPage ( ) ; if ( loginPage != null ) { httpResponse . sendRedirect ( loginPage ) ; } else { // expected servlet container behavior :
// if < login - config > section exist into web . xml do what is configured there
// else send back internal page with message about SC _ UNAUTHORIZED
// authenticate can throw ServletException if fails , perhaps because is not configured
// let servlet container handle this error , that could be custom error page is configured
httpRequest . authenticate ( httpResponse ) ; } return ; } catch ( NoSuchMethodException | IllegalArgumentException e ) { // do not use AppServlet # sendError since it is encoded JSON and for resources need HTML
dumpError ( context , e ) ; httpResponse . sendError ( HttpServletResponse . SC_NOT_FOUND , httpRequest . getRequestURI ( ) ) ; return ; } catch ( InvocationException e ) { // do not use AppServlet # sendError since it is encoded JSON and for resources need HTML
dumpError ( context , e ) ; if ( e . getCause ( ) instanceof NoSuchResourceException ) { httpResponse . sendError ( HttpServletResponse . SC_NOT_FOUND , httpRequest . getRequestURI ( ) ) ; } else { httpResponse . sendError ( HttpServletResponse . SC_INTERNAL_SERVER_ERROR , e . getCause ( ) . getMessage ( ) ) ; } return ; } finally { if ( argumentsReader != null ) { argumentsReader . clean ( ) ; } } // once serialization process started response becomes committed
// and is not longer possible to use HttpServletResponse # sendError
// let servlet container handle IO exceptions but since client already start rendering
// there is no so much to do beside closing or reseting connection
httpResponse . setStatus ( HttpServletResponse . SC_OK ) ; resource . serialize ( httpResponse ) ;


signature:
public class ResourceServlet { /** * Generate storage key for resource methods cache . This key is create from controller and resource method request paths and
 * is used on cache initialization . It is paired with { @ link # key ( String ) } created from request path on actual method
 * invocation .
 * Here is storage key syntax that should be identical with retrieval key . Key has optional controller path - missing if use
 * default controller and resource method path . Controller path is the declaring class request path ,
 * { @ link ManagedClassSPI # getRequestPath ( ) } and resource path is managed method request path ,
 * { @ link ManagedMethodSPI # getRequestPath ( ) } .
 * < pre >
 * key = [ " / " controller - path ] " / " resource - path
 * controller - path = declaring class request path
 * resource - path = managed method request path
 * < / pre >
 * @ param resourceMethod resource method .
 * @ return resource method key . */
private static String key ( ManagedMethodSPI resourceMethod ) { } }

implementation: StringBuilder key = new StringBuilder ( ) ; if ( resourceMethod . getDeclaringClass ( ) . getRequestPath ( ) != null ) { key . append ( '/' ) ; key . append ( resourceMethod . getDeclaringClass ( ) . getRequestPath ( ) ) ; } key . append ( '/' ) ; key . append ( resourceMethod . getRequestPath ( ) ) ; return key . toString ( ) ;


signature:
public class AbstractETagEndpoint { /** * Performs an HTTP GET request on the { @ link Endpoint # getUri ( ) } and caches
 * the response if the server sends an ETag header .
 * Sends { @ link HttpHeaders # IF _ NONE _ MATCH } if there is already a cached
 * ETag .
 * @ return The response of the request or the cached response if the server
 * responded with { @ link HttpStatus # SC _ NOT _ MODIFIED } .
 * @ throws IOException Network communication failed .
 * @ throws IllegalArgumentException { @ link HttpStatus # SC _ BAD _ REQUEST }
 * @ throws IllegalAccessException { @ link HttpStatus # SC _ UNAUTHORIZED } or
 * { @ link HttpStatus # SC _ FORBIDDEN }
 * @ throws FileNotFoundException { @ link HttpStatus # SC _ NOT _ FOUND } or
 * { @ link HttpStatus # SC _ GONE }
 * @ throws IllegalStateException { @ link HttpStatus # SC _ CONFLICT }
 * @ throws RuntimeException Other non - success status code . */
protected HttpEntity getContent ( ) throws IOException , IllegalArgumentException , IllegalAccessException , FileNotFoundException , IllegalStateException { } }

implementation: Request request = Request . Get ( uri ) ; if ( last != null ) { request = request . addHeader ( IF_NONE_MATCH , last . etag ) ; } HttpResponse response = execute ( request ) ; if ( response . getStatusLine ( ) . getStatusCode ( ) == SC_NOT_MODIFIED && last != null ) { return last . content ; } handleResponse ( response , request ) ; Header etagHeader = response . getFirstHeader ( HttpHeaders . ETAG ) ; last = ( etagHeader == null ) ? null : new Memory ( etagHeader . getValue ( ) , response . getEntity ( ) ) ; return response . getEntity ( ) ;


signature:
public class AbstractETagEndpoint { /** * Performs an HTTP PUT request on the { @ link Endpoint # getUri ( ) } . Sets
 * { @ link HttpHeaders # IF _ MATCH } if there is a cached ETag to detect lost
 * updates .
 * @ param content The content to send to the server .
 * @ return The response message .
 * @ throws IOException Network communication failed .
 * @ throws IllegalArgumentException { @ link HttpStatus # SC _ BAD _ REQUEST }
 * @ throws IllegalAccessException { @ link HttpStatus # SC _ UNAUTHORIZED } or
 * { @ link HttpStatus # SC _ FORBIDDEN }
 * @ throws FileNotFoundException { @ link HttpStatus # SC _ NOT _ FOUND } or
 * { @ link HttpStatus # SC _ GONE }
 * @ throws IllegalStateException The content has changed since it was last
 * retrieved with { @ link # getContent ( ) } . Your changes were rejected to
 * prevent a lost update .
 * @ throws RuntimeException Other non - success status code . */
protected HttpResponse putContent ( HttpEntity content ) throws IOException , IllegalArgumentException , IllegalAccessException , FileNotFoundException , IllegalStateException { } }

implementation: Request request = Request . Put ( uri ) . body ( content ) ; if ( last != null ) { request . addHeader ( HttpHeaders . IF_MATCH , last . etag ) ; } return executeAndHandle ( request ) ;


signature:
public class AbstractETagEndpoint { /** * Performs an HTTP DELETE request on the { @ link Endpoint # getUri ( ) } . Sets
 * { @ link HttpHeaders # IF _ MATCH } if there is a cached ETag to detect lost
 * updates .
 * @ return The response message .
 * @ throws IOException Network communication failed .
 * @ throws IllegalArgumentException { @ link HttpStatus # SC _ BAD _ REQUEST }
 * @ throws IllegalAccessException { @ link HttpStatus # SC _ UNAUTHORIZED } or
 * { @ link HttpStatus # SC _ FORBIDDEN }
 * @ throws FileNotFoundException { @ link HttpStatus # SC _ NOT _ FOUND } or
 * { @ link HttpStatus # SC _ GONE }
 * @ throws IllegalStateException The entity has changed since it was last
 * retrieved with { @ link # getContent ( ) } . Your delete call was rejected to
 * prevent a lost update .
 * @ throws RuntimeException Other non - success status code . */
protected HttpResponse deleteContent ( ) throws IOException , IllegalArgumentException , IllegalAccessException , FileNotFoundException , IllegalStateException { } }

implementation: Request request = Request . Delete ( uri ) ; if ( last != null ) { request . addHeader ( HttpHeaders . IF_MATCH , last . etag ) ; } return executeAndHandle ( request ) ;


signature:
public class FitFilenameComparator { /** * Compare two < code > FileInformation < / code > objects . See { @ link FitFilenameComparator }
 * for more information .
 * @ param lhs left hand side
 * @ param rhs right hand side
 * @ return & lt ; 0 if < code > lhs < / code > is greater , & gt ; 0 if < code > rhr < / code >
 * is greater , 0 if they are equal . */
@ Override public final int compare ( final T lhs , final T rhs ) { } }

implementation: int c = compareDirectoryNames ( lhs , rhs ) ; if ( c == EQUAL ) { if ( isSetupFile ( lhs ) || isTearDownFile ( rhs ) ) { return LEFT_IS_SMALLER ; } else if ( isSetupFile ( rhs ) || isTearDownFile ( lhs ) ) { return RIGHT_IS_SMALLER ; } else { return compareFullnames ( lhs , rhs ) ; } } else if ( c <= LEFT_IS_SMALLER ) { return subCompare ( lhs , rhs ) ; } else { return - subCompare ( rhs , lhs ) ; }


signature:
public class TableFixture { /** * Closes the SQL statement .
 * @ throws Exception propagated to fit . */
@ Override public void tearDown ( ) throws Exception { } }

implementation: if ( statement != null ) { statement . close ( ) ; statement = null ; } super . tearDown ( ) ;


signature:
public class TableFixture { /** * Generates a { @ code java . sql . ResultSet } by using the saved connection .
 * This method queries the table { @ code tableName } and appends
 * { @ code where } as an optional where clause .
 * @ return the { @ code ResultSet } which the query returned */
protected ResultSet getResultSet ( ) { } }

implementation: if ( table == null ) { throw new IllegalArgumentException ( "missing parameter: table" ) ; } String whereClause = "" ; if ( where != null ) { whereClause = " WHERE " + where ; } try { statement = connection . createStatement ( ) ; return statement . executeQuery ( "SELECT * FROM " + table + whereClause ) ; } catch ( SQLException e ) { throw new RuntimeException ( e ) ; }


signature:
public class PostConstructInstanceProcessor { /** * Execute post - construct on managed instance . In order to perform instance post - construction , managed instance should
 * implement { @ link ManagedPostConstruct } interface .
 * @ param managedClass managed class ,
 * @ param instance instance of given managed class .
 * @ throws BugError if instance post - construction fails due to exception of user defined logic . */
@ Override public void postProcessInstance ( ManagedClassSPI managedClass , Object instance ) { } }

implementation: if ( ! ( instance instanceof ManagedPostConstruct ) ) { return ; } ManagedPostConstruct managedInstance = ( ManagedPostConstruct ) instance ; log . debug ( "Post-construct managed instance |%s|" , managedInstance . getClass ( ) ) ; try { managedInstance . postConstruct ( ) ; } catch ( Throwable t ) { throw new BugError ( "Managed instance |%s| post-construct fail: %s" , instance , t ) ; }


signature:
public class EventStreamManagerImpl { /** * Closes all event streams still opened when event stream manager is destroyed . */
@ Override public void preDestroy ( ) { } }

implementation:
if ( eventStreams . isEmpty ( ) ) { return ; } // EventStream # close signals stream loop that breaks
// as a consequence , EventStreamServlet ends current request processing and call this # closeEventStream
// this # closeEventStream removes event stream from this # eventStreams list resulting in concurrent change
// to cope with this concurrent change uses a temporary array
// toArray API is a little confusing for me regarding returned array
// to be on safe side let toArray to determine array size
// also I presume returned array is not altered by list updates
for ( EventStream eventStream : eventStreams . toArray ( new EventStream [ 0 ] ) ) { log . debug ( "Force close stale event stream |%s|." , eventStream ) ; eventStream . close ( ) ; }


signature:
public class EventStreamManagerImpl { /** * Subscribes to events stream and returns session ID . This method is remote accessible and public . It returns a session ID
 * with a short life time , for about 10 seconds .
 * This method creates a new { @ link SessionID } and stores given configuration object to { @ link # sessions } map , with created
 * session ID as key . Session storage is ephemere . It lasts only for { @ link # SUBSCRIBE _ TTL } period of time ; after that
 * session ID becomes stale .
 * This method should be followed by { @ link # createEventStream ( String ) } , with returned session ID as argument .
 * @ param config events stream configuration object .
 * @ return events stream session ID . */
@ Remote @ Public public String subscribe ( EventStreamConfig config ) { } }

implementation: SessionID sessionID = new SessionID ( ) ; log . debug ( "Store event stream parameters for session |%s|." , sessionID ) ; sessions . put ( sessionID , config ) ; return sessionID . getValue ( ) ;


signature:
public class AbstractBlobView { /** * Enables or disabled buttons based on the " Allow " HTTP header . */
protected void handleAllowedMethods ( ) { } }

implementation: endpoint . isDownloadAllowed ( ) . ifPresent ( this :: setDownloadEnabled ) ; endpoint . isUploadAllowed ( ) . ifPresent ( this :: setUploadEnabled ) ; endpoint . isDeleteAllowed ( ) . ifPresent ( this :: setDeleteEnabled ) ;


signature:
public class AbstractBlobView { /** * Called to upload new blob data to the server . */
protected void upload ( ) { } }

implementation: try { onUpload ( ) ; eventBus . post ( new BlobUploadEvent ( endpoint ) ) ; Notification . show ( "Success" , "Upload complete" , Notification . Type . TRAY_NOTIFICATION ) ; } catch ( IOException | IllegalArgumentException | IllegalAccessException | IllegalStateException ex ) { onError ( ex ) ; }


signature:
public class AbstractBlobView { /** * Deletes the blob . */
protected void delete ( ) { } }

implementation:
String question = "Are you sure you want to delete the data from the server?" ; ConfirmDialog . show ( getUI ( ) , question , new ConfirmDialog . Listener ( ) { @ Override public void onClose ( ConfirmDialog cd ) { if ( cd . isConfirmed ( ) ) { try { endpoint . delete ( ) ; close ( ) ; } catch ( IOException | IllegalArgumentException | IllegalAccessException | IllegalStateException ex ) { onError ( ex ) ; } catch ( RuntimeException ex ) { // Must explicitly send unhandled exceptions to error handler .
// Would otherwise get swallowed silently within callback handler .
getUI ( ) . getErrorHandler ( ) . error ( new com . vaadin . server . ErrorEvent ( ex ) ) ; } } } } ) ;


signature:
public class SqlTimestampTypeHandler { /** * Parses a string and converts it into a { @ code java . sql . Timestamp } object .
 * @ param s { @ code String } which will be converted
 * @ return { @ code java . sql . Timestamp } object which is represented by { @ code s }
 * @ throws ParseException if the date could not be parsed */
@ Override public final Timestamp unsafeParse ( final String s ) throws ParseException { } }

implementation: try { return Timestamp . valueOf ( s ) ; } catch ( final IllegalArgumentException e ) { return new Timestamp ( dateFitDateHelper . parse ( s , parameter ) . getTime ( ) ) ; }


signature:
public class Fixture { /** * Finds an argument in an given argument list .
 * The search for an argument is case - insensitive and whitespaces at the
 * beginning and the end are ignored . The argument ' s name and its value are
 * separated by an equal sign . All these inputs will result in
 * & quot ; world & quot ; , if you look up & quot ; hello & quot ; :
 * & quot ; hello = world & quot ; , & quot ; hello = world & quot ; ,
 * & quot ; HeLLo = world & quot ; . < / p >
 * Note : the case of the value is unchanged .
 * @ param argName the argument name to look up
 * @ param defaultValue the result value if the argument does not exist
 * @ return the argument ' s value without namespaces , or defaultValue
 * @ see # getArgNames ( ) getArgs
 * @ see # copyParamsToFixture ( ) copyParamsToFixture */
public String getArg ( final String argName , final String defaultValue ) { } }

implementation: if ( args == null || ! args . containsKey ( argName ) ) { return defaultValue ; } else { return validator . preProcess ( args . get ( argName ) ) ; }


signature:
public class Fixture { /** * Initializes the fixture arguments , call { @ code setUp } ,
 * { @ code fit . Fixture . doTable ( Parse ) } and { @ code tearDown ( ) } .
 * @ param table the table to be processed */
public void doTable ( FitTable table ) { } }

implementation: copyParamsToFixture ( ) ; try { setUp ( ) ; try { doRows ( table . rows ( ) ) ; } catch ( Exception e ) { table . exception ( e ) ; } tearDown ( ) ; } catch ( final Exception e ) { table . exception ( e ) ; } table . finishExecution ( ) ;


signature:
public class Fixture { /** * extracts and removes parameters from a row .
 * @ param row row to process
 * @ return extracted parameters */
protected String [ ] extractColumnParameters ( FitRow row ) { } }

implementation: final List < String > result = new ArrayList < > ( ) ; for ( FitCell cell : row . cells ( ) ) { result . add ( FitUtils . extractCellParameter ( cell ) ) ; } return result . toArray ( new String [ result . size ( ) ] ) ;