signature:
public class ValidationContext { /** * The doGetMessageFromBundle does a bit of magic . If the message starts with {
 * than it assumes it is an i18N message and looks it up in the
 * resource bundle . If it starts with # { it assumes it is an expression
 * and uses OGNL , JSF EL , or the Universal EL to look up the expression
 * in the context . */
private String doGetMessageFromBundle ( String key ) { } }

implementation:
if ( resourceBundleLocator == null ) { return null ; } /* Find the resourceBundle . */
ResourceBundle bundle = this . resourceBundleLocator . getBundle ( ) ; if ( bundle == null ) { return null ; } String message = null ; // holds the message
/* If the message starts with an i18nMarker look it up
 * in the resource bundle . */
if ( key . startsWith ( this . i18nMarker ) ) { try { key = key . substring ( 1 , key . length ( ) - 1 ) ; message = lookupMessageInBundle ( key , bundle , message ) ; } catch ( MissingResourceException mre ) { message = key ; } } else { /* * If it does not start with those markers see if it has a " . " . If
 * it has a dot , try to look it up . If it is not found then just
 * return the key as the message . */
if ( key . contains ( "." ) ) { try { message = lookupMessageInBundle ( key , bundle , message ) ; } catch ( MissingResourceException mre ) { message = key ; } } else { message = key ; } } return message ;


signature:
public class SortingInternal { /** * This is the work horse . It does all of the sorting work for the simple cases .
 * Nulls are last by default .
 * @ param list the list you want to sort .
 * @ param sortBy what you want to sort the list by .
 * @ param fields the reflection fields
 * @ param ascending true for ascending */
public static void sort ( List list , String sortBy , Map < String , FieldAccess > fields , boolean ascending ) { } }

implementation: sort ( list , sortBy , fields , ascending , false ) ;


signature:
public class SortingInternal { /** * This is the work horse . It does all of the sorting work for the simple cases .
 * @ param list the list you want to sort .
 * @ param sortBy what you want to sort the list by .
 * @ param fields the reflection fields
 * @ param ascending true for ascending */
public static void sort ( List list , String sortBy , Map < String , FieldAccess > fields , boolean ascending , boolean nullsFirst ) { } }

implementation:
try { /* If this list is null or empty , we have nothing to do so return . */
if ( list == null || list . size ( ) == 0 ) { return ; } /* Grab the first item in the list and see what it is . */
Object o = list . get ( 0 ) ; /* if the sort by string is is this , and the object is comparable then use the objects
 themselves for the sort . */
if ( sortBy . equals ( "this" ) ) { Collections . sort ( list , thisUniversalComparator ( ascending , nullsFirst ) ) ; return ; } /* If you did not sort by " this " , then sort by the field . */
final FieldAccess field = fields . get ( sortBy ) ; if ( field != null ) { Collections . sort ( list , Sorting . universalComparator ( field , ascending , nullsFirst ) ) ; } } catch ( Exception ex ) { Exceptions . handle ( ex , "list" , list , "\nsortBy" , sortBy , "fields" , fields , "ascending" , ascending , "nullFirst" , nullsFirst ) ; }


signature:
public class ResponseHandler { /** * Main exit from system .
 * If you are debugging something not coming out of the system .
 * Start here . */
private void handleResponseFromDataStore ( Result result ) { } }

implementation: if ( debug ) { logger . info ( "ResponseHandler::handleResponseFromDataStore" , result ) ; } if ( result instanceof SingleResult ) { SingleResult singleResult = ( SingleResult ) result ; int size = handleSingleResult ( singleResult ) ; counter ( size , singleResult . source ( ) ) ; } else if ( result instanceof SearchBatchResult ) { SearchBatchResult searchBatchResult = ( SearchBatchResult ) result ; sendBatchResponse ( ( BatchResult ) result ) ; int size = searchBatchResult . getResults ( ) . size ( ) ; counter ( size , searchBatchResult . source ( ) ) ; } else if ( result instanceof BatchResult ) { BatchResult batchResult = ( BatchResult ) result ; int size = handleBatchResult ( batchResult ) ; counter ( size , batchResult . source ( ) ) ; } else if ( result instanceof ErrorResult ) { ErrorResult errorResult = ( ErrorResult ) result ; int size = handleErrorResult ( errorResult ) ; counter ( size , errorResult . source ( ) ) ; }


signature:
public class MapperComplex { /** * fromMap converts a map into a java object
 * @ param map map to create the object from .
 * @ param cls class type of new object
 * @ param < T > map to create teh object from .
 * @ return new object of type cls < T > */
@ Override public < T > T fromMap ( final Map < String , Object > map , final Class < T > cls ) { } }

implementation:
T toObject = Reflection . newInstance ( cls ) ; Map < String , FieldAccess > fields = fieldsAccessor . getFields ( toObject . getClass ( ) ) ; Set < Map . Entry < String , Object > > mapKeyValuesEntrySet = map . entrySet ( ) ; /* Iterate through the map keys / values . */
for ( Map . Entry < String , Object > mapEntry : mapKeyValuesEntrySet ) { /* Get the field name . */
String key = mapEntry . getKey ( ) ; if ( ignoreSet != null ) { if ( ignoreSet . contains ( key ) ) { continue ; } } /* Get the field and if it missing then ignore this map entry . */
FieldAccess field = fields . get ( fieldsAccessor . isCaseInsensitive ( ) ? key . toLowerCase ( ) : key ) ; if ( field == null ) { continue ; } /* Check the view if it is active . */
if ( view != null ) { if ( ! field . isViewActive ( view ) ) { continue ; } } /* Check respects ignore is active .
 * Then needs to be a chain of responsibilities . */
if ( respectIgnore ) { if ( field . ignore ( ) ) { continue ; } } /* Get the value from the map . */
Object value = mapEntry . getValue ( ) ; /* If the value is a Value ( a index overlay ) , then convert ensure it is not a container and inject
 it into the field , and we are done so continue . */
if ( value instanceof Value ) { if ( ( ( Value ) value ) . isContainer ( ) ) { value = ( ( Value ) value ) . toValue ( ) ; } else { field . setFromValue ( toObject , ( Value ) value ) ; continue ; } } /* If the value is null , then inject an null value into the field .
 * Notice we do not check to see if the field is a primitive , if
 * it is we die which is the expected behavior . */
if ( value == null ) { field . setObject ( toObject , null ) ; continue ; } /* if the value ' s type and the field type are the same or
 the field just takes an object , then inject what we have as is . */
if ( value . getClass ( ) == field . type ( ) || field . type ( ) == Object . class ) { field . setValue ( toObject , value ) ; } else if ( Typ . isBasicType ( value ) ) { field . setValue ( toObject , value ) ; } /* See if it is a map < string , object > , and if it is then process it .
 * REFACTOR :
 * It looks like we are using some utility classes here that we could have used in
 * oldMatchAndConvertArgs .
 * REFACTOR */
else if ( value instanceof Map ) { setFieldValueFromMap ( toObject , field , ( Map ) value ) ; } else if ( value instanceof Collection ) { /* It is a collection so process it that way . */
processCollectionFromMapUsingFields ( toObject , field , ( Collection ) value ) ; } else if ( value instanceof Map [ ] ) { /* It is an array of maps so , we need to process it as such . */
processArrayOfMaps ( toObject , field , ( Map < String , Object > [ ] ) value ) ; } else { /* If we could not determine how to convert it into some field
 object then we just go ahead an inject it using setValue which
 will call Conversion . coerce . */
field . setValue ( toObject , value ) ; } } return toObject ;


signature:
public class MapperComplex { /** * Inject a map into an object ' s field .
 * @ param field field we are injecting a value into */
private void setFieldValueFromMap ( final Object parentObject , final FieldAccess field , final Map mapInner ) { } }

implementation:
Class < ? > fieldClassType = field . type ( ) ; Object value = null ; /* Is the field not a map . */
if ( ! Typ . isMap ( fieldClassType ) ) { if ( ! fieldClassType . isInterface ( ) && ! Typ . isAbstract ( fieldClassType ) ) { value = fromMap ( mapInner , field . type ( ) ) ; } else { Object oClassName = mapInner . get ( "class" ) ; if ( oClassName != null ) { value = fromMap ( mapInner , Reflection . loadClass ( oClassName . toString ( ) ) ) ; } else { value = null ; } } /* REFACTOR :
 This is at least the third time that I have seen this code in the class .
 It was either cut and pasted or I forgot I wrote it three times .
 REFACTOR : */
} else if ( Typ . isMap ( fieldClassType ) ) { Class keyType = ( Class ) field . getParameterizedType ( ) . getActualTypeArguments ( ) [ 0 ] ; Class valueType = ( Class ) field . getParameterizedType ( ) . getActualTypeArguments ( ) [ 1 ] ; Set < Map . Entry > set = mapInner . entrySet ( ) ; Map newMap = new LinkedHashMap ( ) ; for ( Map . Entry entry : set ) { Object evalue = entry . getValue ( ) ; Object key = entry . getKey ( ) ; if ( evalue instanceof ValueContainer ) { evalue = ( ( ValueContainer ) evalue ) . toValue ( ) ; } key = Conversions . coerce ( keyType , key ) ; evalue = Conversions . coerce ( valueType , evalue ) ; newMap . put ( key , evalue ) ; } value = newMap ; } field . setValue ( parentObject , value ) ;


signature:
public class MapperComplex { /** * Convert an object to a list .
 * @ param object the object we want to convert to a list
 * @ return new list from an object */
@ Override public List < ? > toList ( Object object ) { } }

implementation: TypeType instanceType = TypeType . getInstanceType ( object ) ; switch ( instanceType ) { case NULL : return Lists . list ( ( Object ) null ) ; case ARRAY : case ARRAY_INT : case ARRAY_BYTE : case ARRAY_SHORT : case ARRAY_FLOAT : case ARRAY_DOUBLE : case ARRAY_LONG : case ARRAY_STRING : case ARRAY_OBJECT : return Conversions . toList ( object ) ; case INSTANCE : if ( Reflection . respondsTo ( object , "toList" ) ) { return ( List < ? > ) Reflection . invoke ( object , "toList" ) ; } break ; } return Lists . list ( object ) ;


signature:
public class MatchAllRegexValidator { /** * Compiles a match .
 * @ return the resulting pattern object */
private Pattern compileRegex ( String match ) { } }

implementation: Pattern pattern = compiledRegexCache . get ( match ) ; if ( pattern == null ) { pattern = Pattern . compile ( match ) ; compiledRegexCache . put ( match , pattern ) ; } return pattern ;


signature: public class BaseVersionedMySQLSupport { @ Override public KeyValueIterable < String , VersionedEntry < String , byte [ ] > > loadAll ( ) { } }

implementation: if ( debug ) logger . info ( "LOAD ALL  " ) ; initIfNeeded ( ) ; try { final ResultSet resultSet = loadAll . executeQuery ( ) ; return new KeyValueIterable < String , VersionedEntry < String , byte [ ] > > ( ) { @ Override public void close ( ) { closeResultSet ( resultSet ) ; } @ Override public Iterator < Entry < String , VersionedEntry < String , byte [ ] > > > iterator ( ) { return new Iterator < Entry < String , VersionedEntry < String , byte [ ] > > > ( ) { @ Override public boolean hasNext ( ) { return resultSetNext ( resultSet ) ; } @ Override public Entry < String , VersionedEntry < String , byte [ ] > > next ( ) { try { String key = resultSet . getString ( KEY_POS ) ; byte [ ] value = getValueColumn ( VALUE_POS , resultSet ) ; long version = resultSet . getLong ( VERSION_POS ) ; long update = resultSet . getLong ( UPDATE_POS ) ; long create = resultSet . getLong ( CREATE_POS ) ; VersionedEntry < String , byte [ ] > returnValue = new VersionedEntry < > ( key , value ) ; returnValue . setCreateTimestamp ( create ) ; returnValue . setUpdateTimestamp ( update ) ; returnValue . setVersion ( version ) ; return new Entry < > ( key , returnValue ) ; } catch ( SQLException e ) { handle ( "Unable to extract values for loadAllByKeys query" , e ) ; return null ; } } @ Override public void remove ( ) { } } ; } } ; } catch ( SQLException e ) { handle ( "Unable to load all records" , e ) ; return null ; }


signature:
public class BaseVersionedMySQLSupport { /** * Create load all keys SQL .
 * @ param table table */
protected void createLoadAllVersionDataSQL ( String table ) { } }

implementation: CharBuf buf = CharBuf . create ( 100 ) ; buf . add ( "select kv_key, 1, version, update_timestamp, create_timestamp from `" ) ; buf . add ( table ) ; buf . add ( "` where kv_key in (" ) ; buf . multiply ( "?," , this . loadKeyCount ) ; buf . removeLastChar ( ) ; buf . add ( ");" ) ; this . loadAllVersionDataByKeysSQL = buf . toString ( ) ;


signature:
public class Lists { /** * Clones each list item into a new instance with copied fields .
 * It is like doing a clone operation .
 * If the passed list is a LinkedList then the returned list will be a
 * LinkedList .
 * If the passed list is a CopyOnWriteArrayList then the returned list will
 * be a CopyOnWriteArrayList list .
 * All other lists become ArrayList .
 * @ param list list to clone
 * @ param < V > generics
 * @ return new list */
@ Universal public static < V > List < V > deepCopy ( List < V > list ) { } }

implementation: if ( list instanceof LinkedList ) { return deepCopyToList ( list , new LinkedList < V > ( ) ) ; } else if ( list instanceof CopyOnWriteArrayList ) { return deepCopyToList ( list , new CopyOnWriteArrayList < V > ( ) ) ; } else { return deepCopy ( ( Collection ) list ) ; }


signature:
public class Lists { /** * / * End universal methods . */
private static < T > int calculateIndex ( List < T > list , int originalIndex ) { } }

implementation:
final int length = list . size ( ) ; int index = originalIndex ; /* Adjust for reading from the right as in
 -1 reads the 4th element if the length is 5 */
if ( index < 0 ) { index = ( length + index ) ; } /* Bounds check
 if it is still less than 0 , then they
 have an negative index that is greater than length */
if ( index < 0 ) { index = 0 ; } if ( index > length ) { index = length ; } return index ;


signature:
public class Fields { /** * Checks to see if we have a string field .
 * @ param value1
 * @ param name
 * @ return */
public static boolean hasStringField ( final Object value1 , final String name ) { } }

implementation: Class < ? > clz = value1 . getClass ( ) ; return classHasStringField ( clz , name ) ;


signature:
public class Fields { /** * Checks to see if this class has a string field .
 * @ param clz
 * @ param name
 * @ return */
public static boolean classHasStringField ( Class < ? > clz , String name ) { } }

implementation: List < Field > fields = Reflection . getAllFields ( clz ) ; for ( Field field : fields ) { if ( field . getType ( ) . equals ( Typ . string ) && field . getName ( ) . equals ( name ) && ! Modifier . isStatic ( field . getModifiers ( ) ) && field . getDeclaringClass ( ) == clz ) { return true ; } } return false ;


signature:
public class Fields { /** * Checks to see if a class has a field .
 * @ param clz
 * @ param name
 * @ return */
public static boolean classHasField ( Class < ? > clz , String name ) { } }

implementation: List < Field > fields = Reflection . getAllFields ( clz ) ; for ( Field field : fields ) { if ( field . getName ( ) . equals ( name ) && ! Modifier . isStatic ( field . getModifiers ( ) ) && field . getDeclaringClass ( ) == clz ) { return true ; } } return false ;


signature:
public class Fields { /** * This can be used for default sort .
 * @ param clz class we are analyzing
 * @ return first field that is comparable or primitive or null if not found . */
public static String getFirstComparableOrPrimitiveFromClass ( Class < ? > clz ) { } }

implementation: List < Field > fields = Reflection . getAllFields ( clz ) ; for ( Field field : fields ) { if ( ( field . getType ( ) . isPrimitive ( ) || Typ . isComparable ( field . getType ( ) ) && ! Modifier . isStatic ( field . getModifiers ( ) ) && field . getDeclaringClass ( ) == clz ) ) { return field . getName ( ) ; } } return null ;


signature:
public class Fields { /** * getFirstStringFieldNameEndsWith
 * @ param value object we are looking at
 * @ param name name
 * @ return field name or null */
public static String getFirstStringFieldNameEndsWith ( Object value , String name ) { } }

implementation: return getFirstStringFieldNameEndsWithFromClass ( value . getClass ( ) , name ) ;


signature:
public class Fields { /** * getFirstStringFieldNameEndsWithFromClass
 * @ param clz class we are looking at
 * @ param name name
 * @ return field name or null */
public static String getFirstStringFieldNameEndsWithFromClass ( Class < ? > clz , String name ) { } }

implementation: List < Field > fields = Reflection . getAllFields ( clz ) ; for ( Field field : fields ) { if ( field . getName ( ) . endsWith ( name ) && field . getType ( ) . equals ( Typ . string ) && ! Modifier . isStatic ( field . getModifiers ( ) ) && field . getDeclaringClass ( ) == clz ) { return field . getName ( ) ; } } return null ;


signature:
public class Fields { /** * Gets the first sortable fields found .
 * @ param value1
 * @ return sortable field */
public static String getSortableField ( Object value1 ) { } }

implementation: if ( value1 instanceof Map ) { return getSortableFieldFromMap ( ( Map < String , ? > ) value1 ) ; } else { return getSortableFieldFromClass ( value1 . getClass ( ) ) ; }


signature:
public class CacheEntry { /** * Comparison of entries this determines what we will order the cache by
 * which determines which type of cache it is .
 * @ param other the other entry
 * @ return results */
@ Override public final int compareTo ( CacheEntry other ) { } }

implementation: switch ( type ) { case LFU : return compareToLFU ( other ) ; case LRU : return compareToLRU ( other ) ; case FIFO : return compareToFIFO ( other ) ; default : die ( ) ; return 0 ; }


signature:
public class CacheEntry { /** * Compare the time .
 * @ param other the other entry
 * @ return results */
private final int compareTime ( CacheEntry other ) { } }

implementation:
if ( time > other . time ) { // this time stamp is greater so it has higher priority
return 1 ; } else if ( time < other . time ) { // this time stamp is lower so it has lower priority
return - 1 ; } else if ( time == other . time ) { // equal priority
return 0 ; } die ( ) ; return 0 ;


signature:
public class Sorting { /** * Takes a list an an array or sorts
 * @ param list list to sorts
 * @ param sorts what you want to sore the list by */
public static void sort ( List list , Sort ... sorts ) { } }

implementation: Sort . sorts ( sorts ) . sort ( list ) ;


signature:
public class Sorting { /** * Sort a list .
 * @ param list the list you want to sort
 * @ param sortBy what you want to sort the list by
 * @ param ascending do you want ascending order
 * @ param nullsFirst do you want nulls first */
public static void sort ( List list , String sortBy , boolean ascending , boolean nullsFirst ) { } }

implementation: if ( list == null || list . size ( ) == 0 ) { return ; } if ( sortBy . equals ( "this" ) ) { Collections . sort ( list , thisUniversalComparator ( ascending , nullsFirst ) ) ; return ; } Iterator iterator = list . iterator ( ) ; Object object = iterator . next ( ) ; Map < String , FieldAccess > fields = null ; if ( object != null ) { fields = BeanUtils . getFieldsFromObject ( object ) ; } else { while ( iterator . hasNext ( ) ) { object = iterator . next ( ) ; if ( object != null ) { fields = BeanUtils . getFieldsFromObject ( object ) ; break ; } } } if ( fields != null ) { final FieldAccess field = fields . get ( sortBy ) ; if ( field != null ) { Collections . sort ( list , Sorting . universalComparator ( field , ascending , nullsFirst ) ) ; } }


signature:
public class Sorting { /** * Sort collection .
 * @ param collection the collection you want to sort
 * @ param sortBy what you want to sort the list by
 * @ param ascending do you want ascending order
 * @ param nullsFirst do you want nulls first */
public static < V > Collection < V > sort ( Class < V > componentType , Collection < V > collection , String sortBy , boolean ascending , boolean nullsFirst ) { } }

implementation: if ( collection instanceof List ) { sort ( ( List ) collection , sortBy , ascending , nullsFirst ) ; return collection ; } else { V [ ] array = toArray ( componentType , collection ) ; sort ( array , sortBy , ascending , nullsFirst ) ; if ( collection instanceof LinkedHashSet ) { return new LinkedHashSet < > ( Lists . list ( array ) ) ; } else { return Lists . list ( array ) ; } }


signature:
public class Sorting { /** * Sort map entries .
 * @ param map the map entries you want to sort
 * @ param sortBy what you want to sort the list by
 * @ param ascending do you want ascending order
 * @ param nullsFirst do you want nulls first */
public static < K , V > Collection < Map . Entry < K , V > > sortEntries ( Class < V > componentType , Map < K , V > map , String sortBy , boolean ascending , boolean nullsFirst ) { } }

implementation: return sort ( ( Class ) componentType , ( Collection ) map . entrySet ( ) , sortBy , ascending , nullsFirst ) ;


signature:
public class Sorting { /** * Sort map values .
 * @ param map the map entries you want to sort
 * @ param sortBy what you want to sort the list by
 * @ param ascending do you want ascending order
 * @ param nullsFirst do you want nulls first */
public static < K , V > Collection < Map . Entry < K , V > > sortValues ( Class < V > componentType , Map < K , V > map , String sortBy , boolean ascending , boolean nullsFirst ) { } }

implementation: return sort ( ( Class ) componentType , ( Collection ) map . values ( ) , sortBy , ascending , nullsFirst ) ;


signature:
public class Sorting { /** * Sort map keys .
 * @ param map the map entries you want to sort
 * @ param sortBy what you want to sort the list by
 * @ param ascending do you want ascending order
 * @ param nullsFirst do you want nulls first */
public static < K , V > Collection < Map . Entry < K , V > > sortKeys ( Class < V > componentType , Map < K , V > map , String sortBy , boolean ascending , boolean nullsFirst ) { } }

implementation: return sort ( ( Class ) componentType , ( Collection ) map . keySet ( ) , sortBy , ascending , nullsFirst ) ;


signature:
public class Sorting { /** * Sort collection .
 * @ param iterable the iterable you want to sort
 * @ param sortBy what you want to sort the list by
 * @ param ascending do you want ascending order
 * @ param nullsFirst do you want nulls first */
public static < V > Iterable < V > sort ( Class < V > componentType , Iterable < V > iterable , String sortBy , boolean ascending , boolean nullsFirst ) { } }

implementation: if ( iterable instanceof List ) { sort ( ( List ) iterable , sortBy , ascending , nullsFirst ) ; return iterable ; } else if ( iterable instanceof Collection ) { return sort ( componentType , ( Collection < V > ) iterable , sortBy , ascending , nullsFirst ) ; } else { List < V > list = Lists . list ( iterable ) ; sort ( list , sortBy , ascending , nullsFirst ) ; return list ; }


signature:
public class Sorting { /** * Sort an array .
 * @ param array the list you want to sort
 * @ param sortBy what you want to sort the list by
 * @ param ascending do you want ascending order
 * @ param nullsFirst do you want nulls first */
public static < T > void sort ( T [ ] array , String sortBy , boolean ascending , boolean nullsFirst ) { } }

implementation: if ( array == null || array . length == 0 ) { return ; } if ( sortBy . equals ( "this" ) ) { Arrays . sort ( array , thisUniversalComparator ( ascending , nullsFirst ) ) ; return ; } Object object = array [ 0 ] ; Map < String , FieldAccess > fields = null ; if ( object != null ) { fields = BeanUtils . getFieldsFromObject ( object ) ; } else { for ( int index = 1 ; index < array . length ; index ++ ) { object = array [ index ] ; if ( object != null ) { fields = BeanUtils . getFieldsFromObject ( object ) ; break ; } } } if ( fields != null ) { final FieldAccess field = fields . get ( sortBy ) ; if ( field != null ) { Arrays . sort ( array , Sorting . universalComparator ( field , ascending , nullsFirst ) ) ; } }


signature:
public class Sorting { /** * This creates the universal comparator object which is used by the sort work horse .
 * @ param field The field we are sorting on .
 * @ param ascending if this should be ascending or descending .
 * @ return */
public static Comparator universalComparator ( final FieldAccess field , final boolean ascending , final boolean nullsFirst ) { } }

implementation: return new Comparator ( ) { @ Override public int compare ( Object o1 , Object o2 ) { Object value1 = null ; Object value2 = null ; if ( ascending ) { value1 = field . getValue ( o1 ) ; value2 = field . getValue ( o2 ) ; } else { value1 = field . getValue ( o2 ) ; value2 = field . getValue ( o1 ) ; } return Sorting . compare ( value1 , value2 , nullsFirst ) ; } } ;


signature:
public class Sorting { /** * This creates the universal comparator object used for " this " .
 * @ param ascending if this should be ascending or descending .
 * @ return */
public static Comparator thisUniversalComparator ( final boolean ascending , final boolean nullsFirst ) { } }

implementation: return new Comparator ( ) { @ Override public int compare ( Object o1 , Object o2 ) { Object value1 ; Object value2 ; if ( ascending ) { value1 = ( o1 ) ; value2 = ( o2 ) ; } else { value1 = ( o2 ) ; value2 = ( o1 ) ; } return Sorting . compare ( value1 , value2 , nullsFirst ) ; } } ;


signature:
public class FastConcurrentReadLruLfuFifoCache { /** * Get the value from the cache . It does not touch the lock so
 * reads are fast .
 * This does not touch the order list so it is fast .
 * @ param key the key
 * @ return value */
public VALUE get ( KEY key ) { } }

implementation: CacheEntry < KEY , VALUE > cacheEntry = map . get ( key ) ; if ( cacheEntry != null ) { cacheEntry . readCount . incrementAndGet ( ) ; return cacheEntry . value ; } else { return null ; }


signature:
public class FastConcurrentReadLruLfuFifoCache { /** * Used for testing as it gets the value without updating stats
 * @ param key key
 * @ return value */
public VALUE getSilent ( KEY key ) { } }

implementation: CacheEntry < KEY , VALUE > cacheEntry = map . get ( key ) ; if ( cacheEntry != null ) { return cacheEntry . value ; } else { return null ; }


signature:
public class FastConcurrentReadLruLfuFifoCache { /** * Remove the key . This touches the lock .
 * So removes are * * not * * fast .
 * @ param key key */
@ Override public void remove ( KEY key ) { } }

implementation: CacheEntry < KEY , VALUE > entry = map . remove ( key ) ; if ( entry != null ) { list . remove ( entry ) ; }


signature:
public class FastConcurrentReadLruLfuFifoCache { /** * Put the value . This touches the lock so puts are * * not * * fast .
 * @ param key the key key
 * @ param value the value value */
public void put ( KEY key , VALUE value ) { } }

implementation: CacheEntry < KEY , VALUE > entry = map . get ( key ) ; if ( entry == null ) { entry = new CacheEntry < > ( key , value , order ( ) , type , time ( ) ) ; list . add ( entry ) ; map . put ( key , entry ) ; } else { entry . readCount . incrementAndGet ( ) ; entry . value = value ; } evictIfNeeded ( ) ;


signature:
public class FastConcurrentReadLruLfuFifoCache { /** * Avoid overflow . */
private final int order ( ) { } }

implementation: int order = count . incrementAndGet ( ) ; if ( order > Integer . MAX_VALUE - 100 ) { count . set ( 0 ) ; } return order ;


signature:
public class FastConcurrentReadLruLfuFifoCache { /** * Evict if we are over the size limit . */
private final void evictIfNeeded ( ) { } }

implementation: if ( list . size ( ) > evictSize ) { final List < CacheEntry < KEY , VALUE > > killList = list . sortAndReturnPurgeList ( 0.1f ) ; for ( CacheEntry < KEY , VALUE > cacheEntry : killList ) { map . remove ( cacheEntry . key ) ; } }


signature:
public class LongRangeValidator { /** * Perform the actual validation .
 * @ param fieldValue the value to validate
 * @ param fieldLabel the logical name of the value used for generating error messages */
@ SuppressWarnings ( "unchecked" ) public ValidatorMessageHolder validate ( Object fieldValue , String fieldLabel ) { } }

implementation: ValidatorMessage validatorMessage = new ValidatorMessage ( ) ; if ( fieldValue == null ) { return validatorMessage ; } dynamicallyInitIfNeeded ( fieldValue ) ; if ( ! super . isValueGreaterThanMin ( ( Comparable ) fieldValue ) ) { populateMessage ( underMin , validatorMessage , fieldLabel , min ) ; } else if ( ! super . isValueLessThanMax ( ( Comparable ) fieldValue ) ) { populateMessage ( overMax , validatorMessage , fieldLabel , max ) ; } return validatorMessage ;


signature:
public class LongRangeValidator { /** * / * Initialize this instance . */
public void init ( ) { } }

implementation:
/* If the underMin message was not injected , create a default . */
if ( underMin == null ) { underMin = new MessageSpecification ( ) ; underMin . setDetailMessage ( "{validator.range.underMin.detail}" ) ; underMin . setSummaryMessage ( "{validator.range.underMin.summary}" ) ; } /* If the overMax message was not injected , create a default . */
if ( overMax == null ) { overMax = new MessageSpecification ( ) ; overMax . setDetailMessage ( "{validator.range.overMax.detail}" ) ; overMax . setSummaryMessage ( "{validator.range.overMax.summary" ) ; } /* If the type was not injected , stop initialization . */
if ( type == null ) { return ; } /* Initialize based on type for all Integer value
 * so that LongRangeValidator can be used
 * for int , short , byte , and long . */
if ( ! isInitialized ( ) ) { if ( type . equals ( Integer . class ) ) { init ( new Integer ( min . intValue ( ) ) , new Integer ( max . intValue ( ) ) ) ; } else if ( type . equals ( Byte . class ) ) { init ( new Byte ( min . byteValue ( ) ) , new Byte ( max . byteValue ( ) ) ) ; } else if ( type . equals ( Short . class ) ) { init ( new Short ( min . byteValue ( ) ) , new Short ( max . byteValue ( ) ) ) ; } else { init ( min , max ) ; } }


signature:
public class LongRangeValidator { /** * If the type was not initialized , we can still figure it out at runtime .
 * @ param value */
private void dynamicallyInitIfNeeded ( Object value ) { } }

implementation:
/* Check to see if this class was already initialized ,
 * if not , initialize it based on the type of the value . */
if ( ! isInitialized ( ) ) { if ( value instanceof Integer ) { init ( new Integer ( min . intValue ( ) ) , new Integer ( max . intValue ( ) ) ) ; } else if ( value instanceof Byte ) { init ( new Byte ( min . byteValue ( ) ) , new Byte ( max . byteValue ( ) ) ) ; } else if ( value instanceof Short ) { init ( new Short ( min . shortValue ( ) ) , new Short ( max . shortValue ( ) ) ) ; } else { init ( min , max ) ; } }


signature: public class Conversions { public static < V > V [ ] array ( Class < V > type , final Collection < V > array ) { } }

implementation: return Conversions . toArray ( type , array ) ;


signature:
public class Conversions { /** * This flattens a list .
 * @ param o object that might be a list
 * @ param list list to add o to or all of o ' s items to .
 * @ return an object or a list */
public static Object unifyListOrArray ( Object o , List list ) { } }

implementation: if ( o == null ) { return null ; } boolean isArray = o . getClass ( ) . isArray ( ) ; if ( list == null && ! isArray && ! ( o instanceof Iterable ) ) { return o ; } if ( list == null ) { list = new LinkedList ( ) ; } if ( isArray ) { int length = Array . getLength ( o ) ; for ( int index = 0 ; index < length ; index ++ ) { Object o1 = Array . get ( o , index ) ; if ( o1 instanceof Iterable || o . getClass ( ) . isArray ( ) ) { unifyListOrArray ( o1 , list ) ; } else { list . add ( o1 ) ; } } } else if ( o instanceof Collection ) { Collection i = ( ( Collection ) o ) ; for ( Object item : i ) { if ( item instanceof Iterable || o . getClass ( ) . isArray ( ) ) { unifyListOrArray ( item , list ) ; } else { list . add ( item ) ; } } } else { list . add ( o ) ; } return list ;


signature:
public class Conversions { /** * This flattens a list .
 * @ param o object that might be a list
 * @ param list list to add o to or all of o ' s items to .
 * @ return an object or a list */
public static Object unifyList ( Object o , List list ) { } }

implementation: if ( o == null ) { return null ; } if ( list == null ) { list = new ArrayList ( ) ; } if ( o instanceof Iterable ) { Iterable i = ( ( Iterable ) o ) ; for ( Object item : i ) { unifyListOrArray ( item , list ) ; } } else { list . add ( o ) ; } return list ;


signature:
public class CollectorManager { /** * This gets called from the http post handler or event bus handler .
 * @ param size the size of the buffer that you would like .
 * @ return */
public final ByteBuffer allocateBuffer ( int size ) { } }

implementation: if ( RECYCLE_BUFFER ) { ByteBuffer spentBuffer = recycleChannel . poll ( ) ; if ( spentBuffer == null ) { spentBuffer = ByteBuffer . allocateDirect ( size ) ; } spentBuffer . clear ( ) ; return spentBuffer ; } else { return ByteBuffer . allocateDirect ( size ) ; }


signature:
public class CollectorManager { /** * See if it is time to stop
 * We have been interrupted . Should we ignore it or break out of the loop .
 * @ return */
private boolean determineIfWeShouldExit ( ) { } }

implementation: boolean shouldStop = stop . get ( ) ; if ( ! shouldStop ) { Thread . interrupted ( ) ; } else { System . out . println ( "Exiting processing loop as requested" ) ; return true ; } return false ;


signature:
public class CollectorManager { /** * Queue and batch writer main logic .
 * This is where the magic happens .
 * @ throws InterruptedException */
private void manageInputWriterChannel ( ) throws InterruptedException { } }

implementation:
try { ByteBuffer dataToWriteToFile ; dataToWriteToFile = inputChannel . poll ( ) ; // no wait
// If it is null , it means the inputChannel is empty and we need to flush .
if ( dataToWriteToFile == null ) { queueEmptyMaybeFlush ( ) ; dataToWriteToFile = inputChannel . poll ( ) ; } // If it is still null , this means that we need to wait
// for more items to show up in the inputChannel .
if ( dataToWriteToFile == null ) { dataToWriteToFile = waitForNextDataToWrite ( ) ; } // We have to check for null again because we could have been interrupted .
if ( dataToWriteToFile != null ) { // Write it
writer . nextBufferToWrite ( dataToWriteToFile ) ; // Then give it back
if ( RECYCLE_BUFFER ) { recycleChannel . offer ( dataToWriteToFile ) ; } } } catch ( InterruptedException ex ) { throw ex ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; ex . printStackTrace ( System . err ) ; }


signature:
public class CollectorManager { /** * If we detect that the in - coming transfer outputDataQueue channel is empty
 * then it could be an excellent time to sync to disk . */
private void queueEmptyMaybeFlush ( ) { } }

implementation:
if ( PERIODIC_FORCE_FLUSH ) { long currentTime = time . get ( ) ; /* Try not to flush more than once every x times per mili - seconds time period . */
if ( ( currentTime - lastFlushTime ) > FORCE_FLUSH_AFTER_THIS_MANY_MILI_SECONDS ) { /* If the writer had things to flush , and we flushed then
 increment the number of flushes . */
if ( writer . syncToDisk ( ) ) { // could take 100 ms to 1 second
this . numberOfFlushesTotal . incrementAndGet ( ) ; } /* We update the flush time no matter what . */
lastFlushTime = time . get ( ) ; } }


signature:
public class CollectorManager { /** * If we don ' t have any data , and we have flushed ,
 * then we can wait on the outputDataQueue . There is no sense spin - locking .
 * The poll ( time , timeunit ) call will block until there is something to do
 * or until the timeout .
 * @ return the next byte buffer .
 * @ throws InterruptedException */
private ByteBuffer waitForNextDataToWrite ( ) throws InterruptedException { } }

implementation: ByteBuffer dataToWriteToFile ; dataToWriteToFile = inputChannel . poll ( FORCE_FLUSH_AFTER_THIS_MANY_MILI_SECONDS , TimeUnit . MILLISECONDS ) ; return dataToWriteToFile ;


signature:
public class CollectorManager { /** * Start up the health monitor . */
private void startMonitor ( ) { } }

implementation: final ScheduledExecutorService monitor = Executors . newScheduledThreadPool ( 2 , new ThreadFactory ( ) { @ Override public Thread newThread ( Runnable runnable ) { Thread thread = new Thread ( runnable ) ; thread . setPriority ( Thread . NORM_PRIORITY + 1 ) ; return thread ; } } ) ; monitorFuture = monitor . scheduleAtFixedRate ( new Runnable ( ) { @ Override public void run ( ) { monitor ( ) ; } } , MONITOR_INTERVAL_SECONDS , MONITOR_INTERVAL_SECONDS , TimeUnit . SECONDS ) ; Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( new Runnable ( ) { @ Override public void run ( ) { System . err . println ( "shutting down...." ) ; monitor ( ) ; } } ) ) ;


signature:
public class CollectorManager { /** * Starts up the batch writer . */
public void start ( final TimeAware receiver ) { } }

implementation:
// This starts itself up again every 1/2 second if something really bad
// happens like disk full . As soon as the problem gets corrected
// then things start working again . . . happy day . Only
// one is running per instance of CollectionManagerImpl .
writerFuture = scheduledExecutorService . scheduleAtFixedRate ( new Runnable ( ) { @ Override public void run ( ) { processWrites ( ) ; } } , 0 , 500 , TimeUnit . MILLISECONDS ) ; startMonitor ( ) ; tickTock = this . scheduledExecutorService . scheduleAtFixedRate ( new Runnable ( ) { @ Override public void run ( ) { long time = System . nanoTime ( ) / 1_000_000 ; if ( receiver != null ) { receiver . tick ( time ) ; } tick ( time ) ; } } , 0 , 20 , TimeUnit . MILLISECONDS ) ;


signature:
public class LazyValueMap { /** * Gets the item by key from the mapping .
 * @ param key to lookupWithDefault
 * @ return */
@ Override public final Object get ( Object key ) { } }

implementation:
Object object = null ; /* if the map is null , then we create it . */
if ( map == null ) { buildMap ( ) ; } object = map . get ( key ) ; lazyChopIfNeeded ( object ) ; return object ;


signature:
public class LengthValidator { /** * Perform the actual validation .
 * @ param fieldValue the value to validate
 * @ param fieldLabel the logical name of the value used for generating error messages */
public ValidatorMessageHolder validate ( Object fieldValue , String fieldLabel ) { } }

implementation: ValidatorMessage validatorMessage = new ValidatorMessage ( ) ; if ( fieldValue == null ) { return validatorMessage ; } int len = Boon . len ( fieldValue ) ; if ( ! ( len >= min && len <= max ) ) { populateMessage ( validatorMessage , fieldLabel , min , max ) ; } return validatorMessage ;


signature:
public class FilterDefault { /** * Run the filter on the group .
 * @ param group here is the group
 * @ param results here are the results */
private void doFilterGroup ( Group group , ResultSetInternal results ) { } }

implementation:
/* The group was n or group so handle it that way . */
if ( group . getGrouping ( ) == Grouping . OR ) { /* nice short method name , or . */
or ( group . getExpressions ( ) , fields , results ) ; } else { /* create a result internal ( why ? ) , wrap the fields in the result set
 internal , and pass that to the and method . */
ResultSetInternal resultsForAnd = new ResultSetImpl ( fields ) ; and ( group . getExpressions ( ) , fields , resultsForAnd ) ; results . addResults ( resultsForAnd . asList ( ) ) ; }


signature: public class FilterDefault { private void applyGroups ( Set < Criteria > expressionSet , ResultSetInternal resultSet ) { } }

implementation: if ( expressionSet . size ( ) == 0 ) { return ; } for ( Criteria expression : expressionSet ) { if ( expression instanceof Group ) { doFilterGroup ( ( Group ) expression , resultSet ) ; } }


signature:
public class Sets { /** * / * Creation */
public static < V > Set < V > set ( Collection < V > collection ) { } }

implementation: if ( collection instanceof Set ) { return ( Set < V > ) collection ; } if ( collection == null ) { return Collections . EMPTY_SET ; } return new LinkedHashSet < > ( collection ) ;


signature:
public class Sets { /** * end universal */
public static List < Map < String , Object > > toListOfMaps ( Set < ? > set ) { } }

implementation: return MapObjectConversion . toListOfMaps ( set ) ;


signature:
public class BatchFileWriter { /** * Recieves a tick from our clock . */
public void tick ( long time ) { } }

implementation: this . time . set ( time ) ; long startTime = fileStartTime . get ( ) ; long duration = time - startTime ; if ( duration > FILE_TIMEOUT_MILISECONDS ) { fileTimeOut . set ( true ) ; }


signature:
public class BatchFileWriter { /** * Attempts to close down log stream . */
private void cleanupOutputStream ( ) { } }

implementation: if ( outputStream != null ) { try { outputStream . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( System . err ) ; } finally { outputStream = null ; } }


signature:
public class BatchFileWriter { /** * Writes a buffer of data to the log system . */
public void nextBufferToWrite ( final ByteBuffer bufferOut ) throws InterruptedException { } }

implementation:
dirty = true ; final int size = bufferOut . limit ( ) ; write ( bufferOut ) ; /* only increment bytes transferred after a successful write . */
if ( ! error . get ( ) ) { totalBytesTransferred += size ; bytesTransferred += size ; bytesSinceLastFlush += size ; buffersSent ++ ; } if ( this . bytesTransferred >= FILE_SIZE_BYTES || fileTimeOut . get ( ) ) { try { outputStream . close ( ) ; } catch ( IOException e ) { cleanupOutputStream ( ) ; e . printStackTrace ( System . err ) ; } finally { outputStream = null ; } }


signature:
public class BatchFileWriter { /** * Write the actual data to disk . */
private void write ( final ByteBuffer bufferOut ) throws InterruptedException { } }

implementation: initOutputStream ( ) ; try { if ( outputStream != null ) { outputStream . write ( bufferOut ) ; } else { error . set ( true ) ; } if ( bytesSinceLastFlush > FLUSH_EVERY_N_BYTES ) { syncToDisk ( ) ; bytesSinceLastFlush = 0 ; } } catch ( ClosedByInterruptException cbie ) { throw new InterruptedException ( "File closed by interruption" ) ; } catch ( Exception e ) { cleanupOutputStream ( ) ; error . set ( true ) ; e . printStackTrace ( System . err ) ; diagnose ( ) ; Exceptions . handle ( e ) ; }


signature:
public class BatchFileWriter { /** * Initialize the output stream . */
private void initOutputStream ( ) { } }

implementation: long time = this . time . get ( ) ; if ( error . get ( ) || this . totalBytesTransferred == 0 ) { cleanupOutputStream ( ) ; error . set ( false ) ; time = System . nanoTime ( ) / 1_000_000 ; } if ( outputStream != null ) { return ; } fileName = LogFilesConfig . getLogFileName ( FORMAT_PATTERN , outputDirPath ( ) , numFiles , time , SERVER_NAME ) ; try { fileTimeOut . set ( false ) ; outputStream = streamCreator ( ) ; fileStartTime . set ( time ) ; bytesTransferred = 0 ; bytesSinceLastFlush = 0 ; } catch ( Exception ex ) { cleanupOutputStream ( ) ; error . set ( true ) ; Exceptions . handle ( ex ) ; } finally { numFiles ++ ; }


signature:
public class BaseStringStringKeyValueStore { /** * Get a value from the key value store .
 * @ param key key
 * @ return */
public V load ( K key ) { } }

implementation: final String value = store . load ( toKeyString ( key ) ) ; if ( value != null ) { return toValueObject ( value ) ; } else { return null ; }


signature:
public class BaseStringStringKeyValueStore { /** * Put a value in the key / value store .
 * @ param key key
 * @ param value value */
public void put ( K key , V value ) { } }

implementation: store . put ( toKeyString ( key ) , toValueString ( value ) ) ;


signature:
public class BaseStringStringKeyValueStore { /** * Put all of these values in the key value store .
 * @ param values values */
public void putAll ( Map < K , V > values ) { } }

implementation: Set < Map . Entry < K , V > > entries = values . entrySet ( ) ; Map < String , String > map = new HashMap < > ( values . size ( ) ) ; for ( Map . Entry < K , V > entry : entries ) { map . put ( toKeyString ( entry . getKey ( ) ) , toValueString ( entry . getValue ( ) ) ) ; } store . putAll ( map ) ;


signature:
public class TimeKeeperBasic { /** * / * Never let the drift get greater than 200 ms . */
private long checkForDrift ( long time ) { } }

implementation: long delta = Math . abs ( System . currentTimeMillis ( ) - time ) ; long lastDelta = lastDeltaTime . getAndSet ( delta ) ; if ( delta > lastDelta + 200 ) { return getTheTime ( time ) ; } return time ;


signature:
public class BaseSimpleSerializationKeyValueStore { /** * Get a value from the key value store .
 * @ param key key
 * @ return */
public V load ( K key ) { } }

implementation: final byte [ ] bytes = store . load ( toKeyBytes ( key ) ) ; if ( bytes != null ) { return toValueObject ( bytes ) ; } else { return null ; }


signature:
public class BaseSimpleSerializationKeyValueStore { /** * Convert a String key to bytes .
 * @ param key key to convert
 * @ return value */
protected byte [ ] toKeyBytes ( K key ) { } }

implementation: byte [ ] keyBytes = keyCache . get ( key ) ; if ( keyBytes == null ) { keyBytes = this . keyToByteArrayConverter . apply ( key ) ; keyCache . put ( key , keyBytes ) ; } return keyBytes ;


signature:
public class BaseSimpleSerializationKeyValueStore { /** * Put a value in the key / value store .
 * @ param key key
 * @ param value value */
public void put ( K key , V value ) { } }

implementation: store . put ( toKeyBytes ( key ) , toValueBytes ( value ) ) ;


signature:
public class BaseSimpleSerializationKeyValueStore { /** * Remove all of these values from the key value store .
 * @ param keys */
public void removeAll ( Iterable < K > keys ) { } }

implementation: List < byte [ ] > list = new ArrayList < > ( ) ; for ( K key : keys ) { list . add ( toKeyBytes ( key ) ) ; } store . removeAll ( list ) ;


signature:
public class PropertiesFileValidatorMetaDataReader { /** * Read the meta - data from a properties file . */
public List < ValidatorMetaData > readMetaData ( Class < ? > clazz , String propertyName ) { } }

implementation:
/* Load the properties file . */
Properties props = loadMetaDataPropsFile ( clazz ) ; /* Get the raw validation data for the given property . */
String unparsedString = props . getProperty ( propertyName ) ; /* Parse the string into a list of ValidationMetaData . */
return extractMetaDataFromString ( clazz , propertyName , unparsedString ) ;


signature:
public class PropertiesFileValidatorMetaDataReader { /** * This method loads the MetaData properties file . The Properties are cached
 * in < b > metaDataPropsCache < / b > and will not be reloaded twice .
 * @ param clazzWhoseValidationMetaDataWeAreReading
 * The class whose property meta - data we are retrieving .
 * @ return */
private Properties loadMetaDataPropsFile ( Class < ? > clazzWhoseValidationMetaDataWeAreReading ) { } }

implementation:
String className = clazzWhoseValidationMetaDataWeAreReading . getName ( ) ; /* * If the class is proxied there will be a $ CGLIB on the end of it .
 * Remove this . */
className = className . split ( "[$]" ) [ 0 ] ; /* * The resourceName is as follows : If the class name is com . foo . Foo Then
 * the resource name is com . foo . Foo . properties . */
String [ ] sourceParts = className . split ( "[.]" ) ; String resourceName = ( sourceParts [ sourceParts . length - 1 ] ) + ".properties" ; /* Check to see if this properties file was already loaded . */
Properties validationMetaDataProps = metaDataPropsCache . get ( resourceName ) ; /* If the properties file was not loaded , then load it . */
if ( validationMetaDataProps == null ) { validationMetaDataProps = new Properties ( ) ; try { /* * Try to load the properties file that contains the validation
 * meta - data . */
validationMetaDataProps . load ( this . getClass ( ) . getClassLoader ( ) . getResourceAsStream ( resourceName ) ) ; } catch ( IOException ioex ) { /* * This can happen and is not an error . It just means there is
 * no validation for this guy . Maybe we should log this .
 * Note self . . . addObject logging capability to this project ! . */
} /* * Put the properties file into the cache so we don ' t have to read
 * it again . */
metaDataPropsCache . put ( resourceName , validationMetaDataProps ) ; } assert validationMetaDataProps != null : "Properties for validation meta-data were loaded" ; return validationMetaDataProps ;


signature:
public class PropertiesFileValidatorMetaDataReader { /** * This method extracts meta - data from a string .
 * @ param clazz
 * @ param propertyName
 * @ param unparsedString
 * @ return */
private List < ValidatorMetaData > extractMetaDataFromString ( Class < ? > clazz , String propertyName , String unparsedString ) { } }

implementation:
String propertyKey = clazz . getName ( ) + "." + propertyName ; /* See if we parsed this bad boy already . */
List < ValidatorMetaData > validatorMetaDataList = metaDataCache . get ( propertyKey ) ; /* If we did not find the list , then we have some work to do . */
if ( validatorMetaDataList == null ) { /* Initialize a new list . */
validatorMetaDataList = new ArrayList < ValidatorMetaData > ( ) ; /* Remember we have a string that looks like this :
 * required ; length min = 10 , max = 100
 * So we need to split on semi - colon . */
String [ ] validatorsParts = unparsedString . split ( "[;]" ) ; /* Now we have the two strings as follows :
 * [ " required " ,
 * [ " length min = 10 , max = 100 " ] */
for ( String validatorString : validatorsParts ) { ValidatorMetaData validatorMetaData = new ValidatorMetaData ( ) ; validatorMetaDataList . add ( validatorMetaData ) ; /* Now we split one of the string ( we will use length )
 * as follows :
 * parts = [ " length " , " min = 10 " , " max = 100 " ] */
String [ ] parts = validatorString . trim ( ) . split ( "[ ,]" ) ; /* The first part is the name of the validation ,
 * e . g . , " length " . */
validatorMetaData . setName ( parts [ 0 ] ) ; /* If the string has more than one part , then there must
 * be arguments as in : [ " min = 10 " , " max = 100 " ]
 * Parse the arguments and addObject them to the list as well . */
if ( parts . length > 1 ) { /* This line converts :
 * [ " length " , " min = 10 " , " max = 100 " ]
 * into :
 * [ " min = 10 " , " max = 100 " ] */
List < String > values = Arrays . asList ( parts ) . subList ( 1 , parts . length ) ; /* For each value convert it into name value pairs . */
for ( String value : values ) { if ( value . indexOf ( "=" ) != - 1 ) { /* Split " min = 10 " into [ " min " , " 10 " ] */
String [ ] valueParts = value . split ( "[=]" ) ; /* Stick this value into validatorMetaData ' s
 * list of properties . */
validatorMetaData . getProperties ( ) . put ( valueParts [ 0 ] , valueParts [ 1 ] ) ; } } } } metaDataCache . put ( propertyKey , validatorMetaDataList ) ; } return validatorMetaDataList ;


signature:
public class AnnotationValidatorMetaDataReader { /** * Read the meta - data from annotation . This copies the meta - data
 * from the annotation into a POJO . It first checks the meta - data cache ,
 * if the meta data is not found in the cache it then reads it from the
 * class .
 * @ param clazz The class that contains the annotation .
 * @ param propertyName The name of the property that we are reading
 * the annotation meta - data from . */
public List < ValidatorMetaData > readMetaData ( Class < ? > clazz , String propertyName ) { } }

implementation:
/* Generate a key to the cache based on the classname and the propertyName . */
String propertyKey = clazz . getName ( ) + "." + propertyName ; /* Look up the validation meta data in the cache . */
List < ValidatorMetaData > validatorMetaDataList = metaDataCache . get ( propertyKey ) ; /* If the meta - data was not found , then generate it . */
if ( validatorMetaDataList == null ) { // if not found
validatorMetaDataList = extractValidatorMetaData ( clazz , propertyName , validatorMetaDataList ) ; /* Put it in the cache to avoid the processing in the future .
 * Design notes : The processing does a lot of reflection , there
 * is no need to do this each time . */
metaDataCache . put ( propertyKey , validatorMetaDataList ) ; } return validatorMetaDataList ;


signature:
public class AnnotationValidatorMetaDataReader { /** * Extract BaseValidator Meta Data .
 * @ param clazz class
 * @ param propertyName property name
 * @ param validatorMetaDataList validatorMetaDataList
 * @ return validator meta data */
private List < ValidatorMetaData > extractValidatorMetaData ( Class < ? > clazz , String propertyName , List < ValidatorMetaData > validatorMetaDataList ) { } }

implementation:
/* If the meta - data was not found , then generate it . */
if ( validatorMetaDataList == null ) { // if not found
/* Read the annotation from the class based on the property name . */
Collection < AnnotationData > annotations = Annotations . getAnnotationDataForFieldAndProperty ( clazz , propertyName , this . validationAnnotationPackages ) ; /* Extract the POJO based meta - data from the annotation . */
validatorMetaDataList = extractMetaDataFromAnnotations ( annotations ) ; } return validatorMetaDataList ;


signature:
public class AnnotationValidatorMetaDataReader { /** * Extract meta - data from the annotationData we collected thus far .
 * @ param annotations The annotationData ( preprocessed annotation ) .
 * @ return list of validation meta data . */
private List < ValidatorMetaData > extractMetaDataFromAnnotations ( Collection < AnnotationData > annotations ) { } }

implementation: List < ValidatorMetaData > list = new ArrayList < ValidatorMetaData > ( ) ; for ( AnnotationData annotationData : annotations ) { ValidatorMetaData validatorMetaData = convertAnnotationDataToValidatorMetaData ( annotationData ) ; list . add ( validatorMetaData ) ; } return list ;


signature:
public class AnnotationValidatorMetaDataReader { /** * Converts an AnnotationData into a ValidatorMetaData POJO .
 * @ param annotationData annotationData
 * @ return validator meta data
 * TODO
 * @ NeedsRefactoring ( " This method shows we are calling annotationData . getValues a lot . " +
 * " Therefore , we must cache the results of getValues as the annoationData is static " +
 * " per property per class . " ) */
private ValidatorMetaData convertAnnotationDataToValidatorMetaData ( AnnotationData annotationData ) { } }

implementation: ValidatorMetaData metaData = new ValidatorMetaData ( ) ; metaData . setName ( annotationData . getName ( ) ) ; metaData . setProperties ( annotationData . getValues ( ) ) ; return metaData ;


signature:
public class RegexValidator { /** * Compiles a match .
 * @ return the resulting pattern object */
private Pattern compileRegex ( ) { } }

implementation: Pattern pattern = compiledRegexCache . get ( getMatch ( ) ) ; if ( pattern == null ) { pattern = Pattern . compile ( getMatch ( ) ) ; compiledRegexCache . put ( getMatch ( ) , pattern ) ; } return pattern ;


signature:
public class StringScanner { /** * Splits a string into many parts
 * @ param string input string
 * @ param split char to split by
 * @ param limit the limit of the times you want it split up
 * @ return the split string */
public static String [ ] split ( final String string , final char split , final int limit ) { } }

implementation: char [ ] [ ] comps = CharScanner . split ( FastStringUtils . toCharArray ( string ) , split , limit ) ; return Str . fromCharArrayOfArrayToStringArray ( comps ) ;


signature:
public class StringScanner { /** * Split string by white space
 * @ param string string to split
 * @ return the split up string */
public static String [ ] splitByWhiteSpace ( final String string ) { } }

implementation: char [ ] [ ] comps = CharScanner . splitByChars ( FastStringUtils . toCharArray ( string ) , WHITE_SPACE ) ; return Str . fromCharArrayOfArrayToStringArray ( comps ) ;


signature:
public class StringScanner { /** * Split string by a list of delimiters
 * @ param string string to split
 * @ param delimiters delimeters to split it by
 * @ return the split up string */
public static String [ ] splitByDelimiters ( final String string , final String delimiters ) { } }

implementation: char [ ] [ ] comps = CharScanner . splitByChars ( FastStringUtils . toCharArray ( string ) , delimiters . toCharArray ( ) ) ; return Str . fromCharArrayOfArrayToStringArray ( comps ) ;


signature:
public class StringScanner { /** * remove chars from a string
 * @ param string string to split
 * @ param delimiters delimeters to remove
 * @ return the split up string */
public static String removeChars ( final String string , final char ... delimiters ) { } }

implementation: char [ ] [ ] comps = CharScanner . splitByCharsNoneEmpty ( FastStringUtils . toCharArray ( string ) , delimiters ) ; return new String ( Chr . add ( comps ) ) ;


signature:
public class StringScanner { /** * Split string by a list of delimiters but none are empty within a range
 * @ param string string to split
 * @ param delimiters delimeters to split it by
 * @ return the split up string */
public static String [ ] splitByCharsNoneEmpty ( final String string , int start , int end , final char ... delimiters ) { } }

implementation: Exceptions . requireNonNull ( string ) ; char [ ] [ ] comps = CharScanner . splitByCharsNoneEmpty ( FastStringUtils . toCharArray ( string ) , start , end , delimiters ) ; return Str . fromCharArrayOfArrayToStringArray ( comps ) ;


signature:
public class StringScanner { /** * Parse float
 * @ param buffer input buffer
 * @ param from from
 * @ param to to
 * @ return value */
public static float parseFloat ( String buffer , int from , int to ) { } }

implementation: return CharScanner . parseFloat ( FastStringUtils . toCharArray ( buffer ) , from , to ) ;


signature:
public class StringScanner { /** * parse a double
 * @ param buffer input string
 * @ return value */
public static double parseDouble ( String buffer , int from , int to ) { } }

implementation: return CharScanner . parseDouble ( FastStringUtils . toCharArray ( buffer ) , from , to ) ;


signature:
public class StringScanner { /** * parse an int within a range
 * @ param buffer input string
 * @ return value */
public static int parseInt ( String buffer , int from , int to ) { } }

implementation: return CharScanner . parseInt ( FastStringUtils . toCharArray ( buffer ) , from , to ) ;


signature:
public class StringScanner { /** * parse an long within a range
 * @ param buffer input string
 * @ return value */
public static long parseLong ( String buffer , int from , int to ) { } }

implementation: return CharScanner . parseLong ( FastStringUtils . toCharArray ( buffer ) , from , to ) ;


signature:
public class LongList { /** * Creates a primitive list based on an input list and a property path
 * @ param inputList input list
 * @ param propertyPath property path
 * @ return primitive list */
public static LongList toLongList ( Collection < ? > inputList , String propertyPath ) { } }

implementation: if ( inputList . size ( ) == 0 ) { return new LongList ( 0 ) ; } LongList outputList = new LongList ( inputList . size ( ) ) ; if ( propertyPath . contains ( "." ) || propertyPath . contains ( "[" ) ) { String [ ] properties = StringScanner . splitByDelimiters ( propertyPath , ".[]" ) ; for ( Object o : inputList ) { outputList . add ( BeanUtils . getPropertyLong ( o , properties ) ) ; } } else { Map < String , FieldAccess > fields = BeanUtils . getFieldsFromObject ( inputList . iterator ( ) . next ( ) ) ; FieldAccess fieldAccess = fields . get ( propertyPath ) ; for ( Object o : inputList ) { outputList . add ( fieldAccess . getLong ( o ) ) ; } } return outputList ;


signature:
public class LongList { /** * Add a new value to the list but don ' t employ a wrapper .
 * @ param integer new value
 * @ return was able to add . */
public boolean addLong ( long integer ) { } }

implementation: if ( end + 1 >= values . length ) { values = grow ( values ) ; } values [ end ] = integer ; end ++ ; return true ;


signature:
public class LongList { /** * Add a new value to the list but don ' t employ a wrapper .
 * @ param integer new value
 * @ return was able to add . */
public LongList add ( long integer ) { } }

implementation: if ( end + 1 >= values . length ) { values = grow ( values ) ; } values [ end ] = integer ; end ++ ; return this ;


signature:
public class LongList { /** * Set in a new value no wrapper
 * @ param index index
 * @ param element new value
 * @ return old value at this index */
public long setLong ( int index , int element ) { } }

implementation: long oldValue = values [ index ] ; values [ index ] = element ; return oldValue ;


signature:
public class IntList { /** * Creates a primitive list based on an input list and a property path
 * @ param inputList input list
 * @ param propertyPath property path
 * @ return primitive list */
public static IntList toIntList ( Collection < ? > inputList , String propertyPath ) { } }

implementation: if ( inputList . size ( ) == 0 ) { return new IntList ( 0 ) ; } IntList outputList = new IntList ( inputList . size ( ) ) ; if ( propertyPath . contains ( "." ) || propertyPath . contains ( "[" ) ) { String [ ] properties = StringScanner . splitByDelimiters ( propertyPath , ".[]" ) ; for ( Object o : inputList ) { outputList . add ( BeanUtils . getPropertyInt ( o , properties ) ) ; } } else { Map < String , FieldAccess > fields = BeanUtils . getFieldsFromObject ( inputList . iterator ( ) . next ( ) ) ; FieldAccess fieldAccess = fields . get ( propertyPath ) ; for ( Object o : inputList ) { outputList . add ( fieldAccess . getInt ( o ) ) ; } } return outputList ;


signature:
public class IntList { /** * Add a new value to the list but don ' t employ a wrapper .
 * @ param integer new value
 * @ return was able to add . */
public boolean addInt ( int integer ) { } }


signature:
public class IntList { /** * Add a new value to the list but don ' t employ a wrapper .
 * @ param integer new value
 * @ return was able to add . */
public IntList add ( int integer ) { } }


signature:
public class IntList { /** * Set a value in the list .
 * @ param index index
 * @ param element new value
 * @ return old value at this index */
@ Override public Integer set ( int index , Integer element ) { } }

implementation: int oldValue = values [ index ] ; values [ index ] = element ; return oldValue ;


signature:
public class IntList { /** * Set in a new value no wrapper
 * @ param index index
 * @ param element new value
 * @ return old value at this index */
public int setInt ( int index , int element ) { } }


signature:
public class IntList { /** * This would be a good opportunity to reintroduce dynamic invoke
 * @ param function function
 * @ return */
public long reduceBy ( Object function , String name ) { } }

implementation: return Int . reduceBy ( values , end , function , name ) ;


signature:
public class ServerProxy { /** * RESPONSES FROM SERVER .
 * @ param message */
private void handleMessageFromServer ( String message ) { } }

implementation: if ( verbose ) { puts ( "WEBSOCKET RESPONSE" , ProtocolConstants . prettyPrintMessage ( message ) ) ; puts ( "WEBSOCKET RESPONSE" ) ; puts ( ProtocolConstants . prettyPrintMessageWithLinesTabs ( message ) ) ; } try { if ( message . startsWith ( Action . GET . response ( ) . startsWith ( ) ) || message . startsWith ( Action . SET_BROADCAST . response ( ) . startsWith ( ) ) ) { final SingleResult singleResult = SingleResult . fromTextMessage ( message ) ; queue . put ( singleResult ) ; } else if ( message . startsWith ( Action . BATCH_READ . response ( ) . startsWith ( ) ) ) { queue . put ( BatchResult . fromTextMessage ( message ) ) ; } else { if ( verbose ) { puts ( "Unknown action" , message ) ; } } } catch ( Exception ex ) { logger . error ( ex , "ServerProxy::handleMessageFromServer\n" , message ) ; }


signature:
public class Criterion { /** * Gets the field value .
 * @ return the value of the field */
public FieldAccess field ( ) { } }

implementation: FieldAccess field ; if ( path ) { field = BeanUtils . idxField ( objectUnderTest , name . toString ( ) ) ; if ( field == null ) { return fakeField ( ) ; } return field ; } if ( name instanceof Enum ) { name = Str . camelCaseLower ( name . toString ( ) ) ; } field = fields ( ) . get ( name ) ; return field ;


signature:
public class Criterion { /** * Gets the field value .
 * @ return the value of the field */
public Object fieldValue ( ) { } }

implementation: if ( ! path ) { FieldAccess field1 = this . field ( ) ; return field1 . getValue ( objectUnderTest ) ; } else { return BeanUtils . atIndex ( objectUnderTest , name . toString ( ) ) ; }


signature:
public class Criterion { /** * Gets the field value .
 * @ return the value of the field */
public Object value ( ) { } }

implementation: if ( ! convert1st ) { FieldAccess field = field ( ) ; if ( field != null ) { switch ( field . typeEnum ( ) ) { case NUMBER : this . value = ( VALUE ) Conversions . coerce ( field . type ( ) , this . value ) ; return new MyNumber ( this . value ) ; case ARRAY : case ARRAY_INT : case ARRAY_BYTE : case ARRAY_SHORT : case ARRAY_FLOAT : case ARRAY_DOUBLE : case ARRAY_LONG : case ARRAY_STRING : case ARRAY_OBJECT : case COLLECTION : case SET : case LIST : this . value = ( VALUE ) Conversions . coerce ( field . getComponentClass ( ) , this . value ) ; break ; default : this . value = ( VALUE ) Conversions . coerce ( field . type ( ) , this . value ) ; } } convert1st = true ; } return value ;


signature:
public class Criterion { /** * Gets the field value .
 * @ return the value of the field */
public Object value2 ( ) { } }

implementation: if ( ! convert2nd ) { FieldAccess field = this . field ( ) ; this . value2 = ( VALUE ) Conversions . coerce ( field . type ( ) , this . value2 ) ; convert2nd = true ; } return value2 ;


signature:
public class BeanUtils { /** * This method handles walking lists of lists .
 * @ param item
 * @ param path
 * @ return */
public static Object getPropByPath ( Object item , String ... path ) { } }

implementation: Object o = item ; for ( int index = 0 ; index < path . length ; index ++ ) { String propName = path [ index ] ; if ( o == null ) { return null ; } else if ( o . getClass ( ) . isArray ( ) || o instanceof Collection ) { o = getCollectionProp ( o , propName , index , path ) ; break ; } else { o = getProp ( o , propName ) ; } } return Conversions . unifyListOrArray ( o ) ;


signature:
public class BeanUtils { /** * Get fields from object or Map .
 * Allows maps to act like they have fields .
 * @ param object
 * @ return */
public static Map < String , FieldAccess > getFieldsFromObject ( Object object ) { } }

implementation: try { Map < String , FieldAccess > fields ; if ( object instanceof Map ) { fields = getFieldsFromMap ( ( Map < String , Object > ) object ) ; } else { fields = getPropertyFieldAccessMap ( object . getClass ( ) ) ; } return fields ; } catch ( Exception ex ) { requireNonNull ( object , "Item cannot be null" ) ; return handle ( Map . class , ex , "Unable to get fields from object" , className ( object ) ) ; }


signature:
public class BeanUtils { /** * Get fields from map .
 * @ param map
 * @ return */
private static Map < String , FieldAccess > getFieldsFromMap ( final Map < String , Object > map ) { } }

implementation: return new Map < String , FieldAccess > ( ) { @ Override public int size ( ) { return map . size ( ) ; } @ Override public boolean isEmpty ( ) { return map . isEmpty ( ) ; } @ Override public boolean containsKey ( Object key ) { return map . containsKey ( key ) ; } @ Override public boolean containsValue ( Object value ) { return true ; } @ Override public FieldAccess get ( final Object key ) { return new FieldAccess ( ) { @ Override public boolean injectable ( ) { return false ; } @ Override public boolean requiresInjection ( ) { return false ; } @ Override public boolean isNamed ( ) { return false ; } @ Override public boolean hasAlias ( ) { return false ; } @ Override public String alias ( ) { return null ; } @ Override public String named ( ) { return key . toString ( ) ; } @ Override public String name ( ) { return key . toString ( ) ; } @ Override public Object getValue ( Object obj ) { return map . get ( key ) ; } @ Override public void setValue ( Object obj , Object value ) { map . put ( key . toString ( ) , value ) ; } @ Override public void setFromValue ( Object obj , Value value ) { map . put ( key . toString ( ) , value . toValue ( ) ) ; } @ Override public boolean getBoolean ( Object obj ) { return Conversions . toBoolean ( getValue ( key ) ) ; } @ Override public void setBoolean ( Object obj , boolean value ) { setValue ( map , value ) ; } @ Override public int getInt ( Object obj ) { return Conversions . toInt ( getValue ( key ) ) ; } @ Override public void setInt ( Object obj , int value ) { setValue ( map , value ) ; } @ Override public short getShort ( Object obj ) { return Conversions . toShort ( getValue ( key ) ) ; } @ Override public void setShort ( Object obj , short value ) { setValue ( map , value ) ; } @ Override public char getChar ( Object obj ) { return Conversions . toChar ( getValue ( key ) ) ; } @ Override public void setChar ( Object obj , char value ) { setValue ( map , value ) ; } @ Override public long getLong ( Object obj ) { return Conversions . toChar ( getValue ( key ) ) ; } @ Override public void setLong ( Object obj , long value ) { setValue ( map , value ) ; } @ Override public double getDouble ( Object obj ) { return Conversions . toDouble ( getValue ( key ) ) ; } @ Override public void setDouble ( Object obj , double value ) { setValue ( map , value ) ; } @ Override public float getFloat ( Object obj ) { return Conversions . toFloat ( getValue ( key ) ) ; } @ Override public void setFloat ( Object obj , float value ) { setValue ( map , value ) ; } @ Override public byte getByte ( Object obj ) { return Conversions . toByte ( getValue ( key ) ) ; } @ Override public void setByte ( Object obj , byte value ) { setValue ( map , value ) ; } @ Override public Object getObject ( Object obj ) { return getValue ( obj ) ; } @ Override public void setObject ( Object obj , Object value ) { this . setValue ( obj , value ) ; } @ Override public TypeType typeEnum ( ) { return TypeType . OBJECT ; } @ Override public boolean isPrimitive ( ) { return false ; } @ Override public boolean isFinal ( ) { return false ; } @ Override public boolean isStatic ( ) { return false ; } @ Override public boolean isVolatile ( ) { return false ; } @ Override public boolean isQualified ( ) { return false ; } @ Override public boolean isReadOnly ( ) { return false ; } @ Override public boolean isWriteOnly ( ) { return false ; } @ Override public Class < ? > type ( ) { return Object . class ; } @ Override public Class < ? > declaringParent ( ) { return null ; } @ Override public Object parent ( ) { return map ; } @ Override public Field getField ( ) { return null ; } @ Override public boolean include ( ) { return true ; } @ Override public boolean ignore ( ) { return false ; } @ Override public ParameterizedType getParameterizedType ( ) { return null ; } @ Override public Class < ? > getComponentClass ( ) { return null ; } @ Override public boolean hasAnnotation ( String annotationName ) { return false ; } @ Override public Map < String , Object > getAnnotationData ( String annotationName ) { return null ; } @ Override public boolean isViewActive ( String activeView ) { return false ; } @ Override public void setStaticValue ( Object newValue ) { } @ Override public TypeType componentType ( ) { return null ; } } ; } @ Override public FieldAccess put ( String key , FieldAccess value ) { return null ; } @ Override public FieldAccess remove ( Object key ) { return null ; } @ Override public void putAll ( Map < ? extends String , ? extends FieldAccess > m ) { } @ Override public void clear ( ) { } @ Override public Set < String > keySet ( ) { return null ; } @ Override public Collection < FieldAccess > values ( ) { return null ; } @ Override public Set < Entry < String , FieldAccess > > entrySet ( ) { return null ; } } ;


signature:
public class BeanUtils { /** * Get property value , loads nested properties
 * @ param root
 * @ param property
 * @ return */
public static Class < ? > getPropertyType ( final Object root , final String property ) { } }

implementation: Map < String , FieldAccess > fields = getPropertyFieldAccessMap ( root . getClass ( ) ) ; FieldAccess field = fields . get ( property ) ; return field . type ( ) ;


signature:
public class BeanUtils { /** * Get property value
 * @ param object
 * @ param path in dotted notation
 * @ return */
public static Object idx ( Object object , String path ) { } }

implementation: String [ ] properties = propertyPathAsStringArray ( path ) ; return getPropertyValue ( object , properties ) ;


signature:
public class BeanUtils { /** * Get property value
 * @ param object
 * @ param path in dotted notation
 * @ return */
public static Object atIndex ( Object object , String path ) { } }


signature:
public class BeanUtils { /** * Set property value to simulate dependency injection .
 * @ param object
 * @ param path in dotted notation
 * @ return */
public static void injectIntoProperty ( Object object , String path , Object value ) { } }

implementation: String [ ] properties = propertyPathAsStringArray ( path ) ; setPropertyValue ( object , value , properties ) ;


signature:
public class BeanUtils { /** * Set a static value
 * @ param cls
 * @ param path in dotted notation
 * @ return */
public static void idx ( Class < ? > cls , String path , Object value ) { } }

implementation: String [ ] properties = propertyPathAsStringArray ( path ) ; setPropertyValue ( cls , value , properties ) ;


signature:
public class BeanUtils { /** * This is an amazing little recursive method . It walks a fanout of
 * nested collection to pull out the leaf nodes */
private static Object getCollectionProp ( Object o , String propName , int index , String [ ] path ) { } }

implementation: o = _getFieldValuesFromCollectionOrArray ( o , propName ) ; if ( index + 1 == path . length ) { return o ; } else { index ++ ; return getCollectionProp ( o , path [ index ] , index , path ) ; }


signature:
public class BeanUtils { /** * Get an int property . */
public static int getPropertyInt ( final Object root , final String ... properties ) { } }

implementation: final String lastProperty = properties [ properties . length - 1 ] ; if ( isDigits ( lastProperty ) ) { return Conversions . toInt ( getPropertyValue ( root , properties ) ) ; } Object object = baseForGetProperty ( root , properties ) ; Map < String , FieldAccess > fields = getFieldsFromObject ( object ) ; FieldAccess field = fields . get ( lastProperty ) ; if ( field . type ( ) == Typ . intgr ) { return field . getInt ( object ) ; } else { return Conversions . toInt ( field . getValue ( object ) ) ; }


signature:
public class BeanUtils { /** * Get property value
 * @ param object
 * @ param path in dotted notation
 * @ return */
public static int idxInt ( Object object , String path ) { } }

implementation: String [ ] properties = propertyPathAsStringArray ( path ) ; return getPropertyInt ( object , properties ) ;


signature:
public class BeanUtils { /** * Get property value
 * @ param object
 * @ param path in dotted notation
 * @ return */
public static String idxStr ( Object object , String path ) { } }

implementation: final Object val = idx ( object , path ) ; return Conversions . toString ( val ) ;


signature:
public class BeanUtils { /** * Get Property Path TypeType
 * @ param root
 * @ param properties
 * @ return */
public static Class < ? > getPropertyPathType ( final Object root , final String ... properties ) { } }

implementation: Object object = baseForGetProperty ( root , properties ) ; Map < String , FieldAccess > fields = getFieldsFromObject ( object ) ; final String lastProperty = properties [ properties . length - 1 ] ; FieldAccess field = fields . get ( lastProperty ) ; return field . type ( ) ;


signature:
public class BeanUtils { /** * Get Property Path TypeType
 * @ param root
 * @ param properties
 * @ return */
public static FieldAccess getPropertyPathField ( final Object root , final String ... properties ) { } }

implementation: Object object = baseForGetProperty ( root , properties ) ; Map < String , FieldAccess > fields = getFieldsFromObject ( object ) ; final String lastProperty = properties [ properties . length - 1 ] ; FieldAccess field = fields . get ( lastProperty ) ; return field ;


signature:
public class BeanUtils { /** * Get Property Path TypeType
 * @ param root
 * @ param properties
 * @ return */
public static FieldAccess getPropertyPathField ( final Class root , final String ... properties ) { } }

implementation: Class cls = baseForGetProperty ( root , properties ) ; Map < String , FieldAccess > fields = getFieldsFromObject ( cls ) ; final String lastProperty = properties [ properties . length - 1 ] ; FieldAccess field = fields . get ( lastProperty ) ; return field ;


signature:
public class Reflection { /** * / * Manages weak references . */
static Context context ( ) { } }

implementation: if ( _context != null ) { return _context ; } else { Context context = weakContext . get ( ) ; if ( context == null ) { context = new Context ( ) ; weakContext = new WeakReference < > ( context ) ; } return context ; }


signature:
public class Reflection { /** * Gets a list of fields merges with properties if field is not found .
 * @ param clazz get the properties or fields
 * @ return */
public static Map < String , FieldAccess > getPropertyFieldAccessMapFieldFirst ( Class < ? > clazz ) { } }

implementation:
Map < String , FieldAccess > combinedFieldsFieldFirst = getCombinedFieldsFieldFirst ( clazz ) ; if ( combinedFieldsFieldFirst != null ) { return combinedFieldsFieldFirst ; } else { /* Fallback map . */
Map < String , FieldAccess > fieldsFallbacks = null ; /* Primary merge into this one . */
Map < String , FieldAccess > fieldsPrimary = null ; /* Try to find the fields first if this is set . */
fieldsPrimary = Reflection . getAllAccessorFields ( clazz , true ) ; fieldsFallbacks = Reflection . getPropertyFieldAccessors ( clazz ) ; combineFieldMaps ( fieldsFallbacks , fieldsPrimary ) ; combinedFieldsFieldFirst = fieldsPrimary ; putCombinedFieldsFieldFirst ( clazz , combinedFieldsFieldFirst ) ; return combinedFieldsFieldFirst ; }


signature:
public class Reflection { /** * Gets a list of fields merges with properties if field is not found .
 * @ param clazz get the properties or fields
 * @ return */
public static Map < String , FieldAccess > getPropertyFieldAccessMapFieldFirstForSerializer ( Class < ? > clazz ) { } }

implementation:
Map < String , FieldAccess > combinedFieldsFieldFirst = getCombinedFieldsFieldFirstForSerializer ( clazz ) ; if ( combinedFieldsFieldFirst != null ) { return combinedFieldsFieldFirst ; } else { /* Fallback map . */
Map < String , FieldAccess > fieldsFallbacks = null ; /* Primary merge into this one . */
Map < String , FieldAccess > fieldsPrimary = null ; /* Try to find the fields first if this is set . */
fieldsPrimary = Reflection . getAllAccessorFields ( clazz , true ) ; fieldsFallbacks = Reflection . getPropertyFieldAccessors ( clazz ) ; fieldsPrimary = removeNonSerializable ( fieldsPrimary ) ; fieldsFallbacks = removeNonSerializable ( fieldsFallbacks ) ; combineFieldMaps ( fieldsFallbacks , fieldsPrimary ) ; combinedFieldsFieldFirst = fieldsPrimary ; putCombinedFieldsFieldFirstForSerializer ( clazz , combinedFieldsFieldFirst ) ; return combinedFieldsFieldFirst ; }


signature:
public class MessageSpecification { /** * The init method tries to generate the message keys .
 * You should only call the init method if you don ' t inject
 * values into the detailMessage and summaryMessage . */
public void init ( ) { } }

implementation:
/* If the parent and name are equal to null ,
 * use the classname to load listFromClassLoader . */
if ( name == null && parent == null ) { this . setDetailMessage ( "{" + this . getClass ( ) . getName ( ) + DETAIL_KEY + "}" ) ; this . setSummaryMessage ( "{" + this . getClass ( ) . getName ( ) + SUMMARY_KEY + "}" ) ; /* If the parent is null and the name is not ,
 * use the name to load listFromClassLoader . */
} else if ( name != null && parent == null ) { this . setDetailMessage ( "{" + "message." + getName ( ) + DETAIL_KEY + "}" ) ; this . setSummaryMessage ( "{" + "message." + getName ( ) + SUMMARY_KEY + "}" ) ; /* If the parent is present , initialize the message keys
 * with the parent name . */
} else if ( parent != null ) { this . setDetailMessage ( "{" + "message." + parent + DETAIL_KEY + "}" ) ; this . setSummaryMessage ( "{" + "message." + parent + SUMMARY_KEY + "}" ) ; }


signature:
public class MessageSpecification { /** * Creates a message .
 * @ param argKeys arguments to lookupWithDefault that were configured .
 * @ param args Arguments that were passed via the object that wants to
 * generate the message */
public String createMessage ( String key , List < String > argKeys , Object ... args ) { } }

implementation:
/* Look up the message . */
String message = getMessage ( key ) ; /* Holds the actual arguments . */
Object [ ] actualArgs ; /* If they passed arguments ,
 * then use this as the actual arguments . */
if ( args . length > 0 ) { actualArgs = args ; /* If they did not pass arguments , use the configured ones . */
} else if ( argKeys != null ) { /* Convert the keys to values . */
actualArgs = keysToValues ( argKeys ) ; } else { actualArgs = new Object [ ] { } ; } return doCreateMessage ( message , actualArgs ) ;


signature:
public class MessageSpecification { /** * Actually creates the message .
 * @ param message The message that was looked up .
 * @ param actualArgs Arguments to the message .
 * @ return */
@ SuppressWarnings ( "unchecked" ) private String doCreateMessage ( String message , Object [ ] actualArgs ) { } }

implementation: return ValidationContext . get ( ) . createMessage ( message , getSubject ( ) , actualArgs ) ;


signature:
public class MessageSpecification { /** * Convert the keys to values . */
private Object [ ] keysToValues ( List < String > argKeys ) { } }

implementation: List < String > values = new ArrayList < > ( ) ; for ( String key : argKeys ) { values . add ( getMessage ( key ) ) ; } return values . toArray ( ) ;


signature:
public class MessageSpecification { /** * Gets the current subject or the configured subject if the
 * current subject is not found . */
public String getSubject ( ) { } }

implementation: return ValidationContext . get ( ) . getCurrentSubject ( ) == null ? this . subject : ValidationContext . get ( ) . getCurrentSubject ( ) ;


signature:
public class JsonSlurper { /** * Parse a text representation of a JSON data structure
 * @ param text JSON text to parse
 * @ return a data structure of lists and maps */
public Object parseText ( String text ) { } }

implementation: if ( text == null || text . length ( ) == 0 ) { throw new IllegalArgumentException ( "The JSON input text should neither be null nor empty." ) ; } return JsonFactory . create ( ) . fromJson ( text ) ;


signature:
public class EtcdClient { /** * This actually sends the request .
 * @ param request request
 * @ param responseHandler handler */
private void sendHttpRequest ( final Request request , final org . boon . core . Handler < Response > responseHandler ) { } }

implementation: final HttpClientRequest httpClientRequest = httpClient . request ( request . getMethod ( ) , request . uri ( ) , handleResponse ( request , responseHandler ) ) ; final Runnable runnable = new Runnable ( ) { @ Override public void run ( ) { if ( ! request . getMethod ( ) . equals ( "GET" ) ) { httpClientRequest . putHeader ( "Content-Type" , "application/x-www-form-urlencoded" ) . end ( request . paramBody ( ) ) ; } else { httpClientRequest . end ( ) ; } } } ; if ( closed . get ( ) ) { this . scheduledExecutorService . schedule ( new Runnable ( ) { @ Override public void run ( ) { connect ( ) ; int retry = 0 ; while ( closed . get ( ) ) { Sys . sleep ( 1000 ) ; if ( ! closed . get ( ) ) { break ; } retry ++ ; if ( retry > 10 ) { break ; } if ( retry % 3 == 0 ) { connect ( ) ; } } if ( ! closed . get ( ) ) { runnable . run ( ) ; } else { responseHandler . handle ( new Response ( "TIMEOUT" , - 1 , new Error ( - 1 , "Timeout" , "Timeout" , - 1L ) ) ) ; } } } , 10 , TimeUnit . MILLISECONDS ) ; } else { runnable . run ( ) ; }


signature:
public class CouchDbContext { /** * Requests CouchDB deletes a database .
 * @ param dbName The database name
 * @ param confirm A confirmation string with the value : < tt > delete database < / tt > */
public void deleteDB ( String dbName , String confirm ) { } }

implementation: assertNotEmpty ( dbName , "dbName" ) ; if ( ! "delete database" . equals ( confirm ) ) throw new IllegalArgumentException ( "Invalid confirm!" ) ; dbc . delete ( buildUri ( dbc . getBaseUri ( ) ) . path ( dbName ) . build ( ) ) ;


signature:
public class CouchDbContext { /** * Requests CouchDB creates a new database ; if one doesn ' t exist .
 * @ param dbName The Database name */
public void createDB ( String dbName ) { } }

implementation:
assertNotEmpty ( dbName , "dbName" ) ; InputStream getresp = null ; HttpResponse putresp = null ; final URI uri = buildUri ( dbc . getBaseUri ( ) ) . path ( dbName ) . build ( ) ; try { getresp = dbc . get ( uri ) ; } catch ( NoDocumentException e ) { // db doesn ' t exist
final HttpPut put = new HttpPut ( uri ) ; putresp = dbc . executeRequest ( put ) ; log . info ( String . format ( "Created Database: '%s'" , dbName ) ) ; } finally { close ( getresp ) ; close ( putresp ) ; }


signature:
public class CouchDbContext { /** * Triggers a database < i > compact < / i > request . */
public void compact ( ) { } }

implementation: HttpResponse response = null ; try { response = dbc . post ( buildUri ( dbc . getDBUri ( ) ) . path ( "_compact" ) . build ( ) , "" ) ; } finally { close ( response ) ; }


signature:
public class CouchDbContext { /** * Request a database sends a list of UUIDs .
 * @ param count The count of UUIDs .
 * @ return a list of UUIDs */
public List < String > uuids ( long count ) { } }

implementation: final String uri = String . format ( "%s_uuids?count=%d" , dbc . getBaseUri ( ) , count ) ; final JsonObject json = dbc . findAny ( JsonObject . class , uri ) ; return dbc . getGson ( ) . fromJson ( json . get ( "uuids" ) . toString ( ) , new TypeToken < List < String > > ( ) { } . getType ( ) ) ;


signature:
public class CouchDbClient { /** * Adds request / response interceptors for logging and validation .
 * @ param clientBuilder */
private void registerInterceptors ( HttpClientBuilder clientBuilder ) { } }

implementation: clientBuilder . addInterceptorFirst ( new HttpRequestInterceptor ( ) { public void process ( final HttpRequest request , final HttpContext context ) throws IOException { if ( log . isInfoEnabled ( ) ) { RequestLine req = request . getRequestLine ( ) ; log . info ( "> " + req . getMethod ( ) + " " + URLDecoder . decode ( req . getUri ( ) , "UTF-8" ) ) ; } } } ) ; clientBuilder . addInterceptorFirst ( new HttpResponseInterceptor ( ) { public void process ( final HttpResponse response , final HttpContext context ) throws IOException { if ( log . isInfoEnabled ( ) ) { log . info ( "< Status: " + response . getStatusLine ( ) . getStatusCode ( ) ) ; } validate ( response ) ; } } ) ;


signature:
public class CouchDbUtil { /** * JSON */
public static < T > T JsonToObject ( Gson gson , JsonElement elem , String key , Class < T > classType ) { } }

implementation: return gson . fromJson ( elem . getAsJsonObject ( ) . get ( key ) , classType ) ;


signature:
public class CouchDbUtil { /** * List directory contents for a resource folder . Not recursive .
 * This is basically a brute - force implementation .
 * Works for regular files and also JARs .
 * @ author Greg Briggs
 * @ param path Should end with " / " , but not start with one .
 * @ return Just the name of each member item , not the full paths . */
public static List < String > listResources ( String path ) { } }

implementation: try { Class < CouchDbUtil > clazz = CouchDbUtil . class ; URL dirURL = clazz . getClassLoader ( ) . getResource ( path ) ; if ( dirURL != null && dirURL . getProtocol ( ) . equals ( "file" ) ) { return Arrays . asList ( new File ( dirURL . toURI ( ) ) . list ( ) ) ; } if ( dirURL != null && dirURL . getProtocol ( ) . equals ( "jar" ) ) { String jarPath = dirURL . getPath ( ) . substring ( 5 , dirURL . getPath ( ) . indexOf ( "!" ) ) ; JarFile jar = new JarFile ( URLDecoder . decode ( jarPath , "UTF-8" ) ) ; Enumeration < JarEntry > entries = jar . entries ( ) ; Set < String > result = new HashSet < String > ( ) ; while ( entries . hasMoreElements ( ) ) { String name = entries . nextElement ( ) . getName ( ) ; if ( name . startsWith ( SPRING_BOOT_DIR ) ) { name = name . substring ( SPRING_BOOT_DIR . length ( ) ) ; } if ( name . startsWith ( path ) ) { String entry = name . substring ( path . length ( ) ) ; int checkSubdir = entry . indexOf ( "/" ) ; if ( checkSubdir >= 0 ) { entry = entry . substring ( 0 , checkSubdir ) ; } if ( entry . length ( ) > 0 ) { result . add ( entry ) ; } } } close ( jar ) ; return new ArrayList < String > ( result ) ; } return null ; } catch ( Exception e ) { throw new CouchDbException ( e ) ; }


signature:
public class Replication { /** * Triggers a replication request .
 * @ return { @ link ReplicationResult } */
public ReplicationResult trigger ( ) { } }

implementation: assertNotEmpty ( source , "Source" ) ; assertNotEmpty ( target , "Target" ) ; HttpResponse response = null ; try { JsonObject json = createJson ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( json ) ; } final URI uri = buildUri ( dbc . getBaseUri ( ) ) . path ( "_replicate" ) . build ( ) ; response = dbc . post ( uri , json . toString ( ) ) ; final InputStreamReader reader = new InputStreamReader ( getStream ( response ) , Charsets . UTF_8 ) ; return dbc . getGson ( ) . fromJson ( reader , ReplicationResult . class ) ; } finally { close ( response ) ; }


signature:
public class Replication { /** * helper */
private JsonObject createJson ( ) { } }

implementation: JsonObject json = new JsonObject ( ) ; addProperty ( json , "source" , source ) ; addProperty ( json , "cancel" , cancel ) ; addProperty ( json , "continuous" , continuous ) ; addProperty ( json , "filter" , filter ) ; if ( queryParams != null ) json . add ( "query_params" , queryParams ) ; if ( docIds != null ) json . add ( "doc_ids" , dbc . getGson ( ) . toJsonTree ( docIds , String [ ] . class ) ) ; addProperty ( json , "proxy" , proxy ) ; addProperty ( json , "since_seq" , sinceSeq ) ; addProperty ( json , "create_target" , createTarget ) ; if ( targetOauth != null ) { JsonObject auth = new JsonObject ( ) ; JsonObject oauth = new JsonObject ( ) ; addProperty ( oauth , "consumer_secret" , consumerSecret ) ; addProperty ( oauth , "consumer_key" , consumerKey ) ; addProperty ( oauth , "token_secret" , tokenSecret ) ; addProperty ( oauth , "token" , token ) ; addProperty ( targetOauth , "url" , target ) ; auth . add ( "oauth" , oauth ) ; targetOauth . add ( "auth" , auth ) ; json . add ( "target" , targetOauth ) ; } else { addProperty ( json , "target" , target ) ; } return json ;


signature:
public class View { /** * Queries a view as an { @ link InputStream }
 * < p > The stream should be properly closed after usage , as to avoid connection leaks .
 * @ return The result as an { @ link InputStream } . */
public InputStream queryForStream ( ) { } }

implementation:
URI uri = uriBuilder . build ( ) ; if ( allDocsKeys != null ) { // bulk docs
return getStream ( dbc . post ( uri , allDocsKeys ) ) ; } return dbc . get ( uri ) ;


signature:
public class View { /** * Queries a view .
 * @ param < T > Object type T
 * @ param classOfT The class of type T
 * @ return The result of the view query as a { @ code List < T > } */
public < T > List < T > query ( Class < T > classOfT ) { } }

implementation: InputStream instream = null ; try { Reader reader = new InputStreamReader ( instream = queryForStream ( ) , Charsets . UTF_8 ) ; JsonArray jsonArray = new JsonParser ( ) . parse ( reader ) . getAsJsonObject ( ) . getAsJsonArray ( "rows" ) ; List < T > list = new ArrayList < T > ( ) ; for ( JsonElement jsonElem : jsonArray ) { JsonElement elem = jsonElem . getAsJsonObject ( ) ; if ( Boolean . TRUE . equals ( this . includeDocs ) ) { elem = jsonElem . getAsJsonObject ( ) . get ( "doc" ) ; } T t = this . gson . fromJson ( elem , classOfT ) ; list . add ( t ) ; } return list ; } finally { close ( instream ) ; }


signature:
public class View { /** * Queries a view .
 * @ param < K > Object type K ( key )
 * @ param < V > Object type V ( value )
 * @ param < T > The class type
 * @ param classOfK The class of type K .
 * @ param classOfV The class of type V .
 * @ param classOfT The class of type T .
 * @ return The View result entries . */
public < K , V , T > ViewResult < K , V , T > queryView ( Class < K > classOfK , Class < V > classOfV , Class < T > classOfT ) { } }

implementation: InputStream instream = null ; try { Reader reader = new InputStreamReader ( instream = queryForStream ( ) , Charsets . UTF_8 ) ; JsonObject json = new JsonParser ( ) . parse ( reader ) . getAsJsonObject ( ) ; ViewResult < K , V , T > vr = new ViewResult < K , V , T > ( ) ; vr . setTotalRows ( getAsLong ( json , "total_rows" ) ) ; vr . setOffset ( getAsInt ( json , "offset" ) ) ; vr . setUpdateSeq ( getAsString ( json , "update_seq" ) ) ; JsonArray jsonArray = json . getAsJsonArray ( "rows" ) ; for ( JsonElement e : jsonArray ) { ViewResult < K , V , T > . Rows row = vr . new Rows ( ) ; row . setId ( JsonToObject ( gson , e , "id" , String . class ) ) ; if ( classOfK != null ) { row . setKey ( JsonToObject ( gson , e , "key" , classOfK ) ) ; } if ( classOfV != null ) { row . setValue ( JsonToObject ( gson , e , "value" , classOfV ) ) ; } if ( Boolean . TRUE . equals ( this . includeDocs ) ) { row . setDoc ( JsonToObject ( gson , e , "doc" , classOfT ) ) ; } vr . getRows ( ) . add ( row ) ; } return vr ; } finally { close ( instream ) ; }


signature:
public class View { /** * Queries for scalar values . Internal use . */
private < V > V queryValue ( Class < V > classOfV ) { } }

implementation: InputStream instream = null ; try { Reader reader = new InputStreamReader ( instream = queryForStream ( ) , Charsets . UTF_8 ) ; JsonArray array = new JsonParser ( ) . parse ( reader ) . getAsJsonObject ( ) . get ( "rows" ) . getAsJsonArray ( ) ; if ( array . size ( ) != 1 ) { throw new NoDocumentException ( "Expecting a single result but was: " + array . size ( ) ) ; } return JsonToObject ( gson , array . get ( 0 ) , "value" , classOfV ) ; } finally { close ( instream ) ; }


signature:
public class View { /** * Queries a view for pagination , returns a next or a previous page , this method
 * figures out which page to return based on the given param that is generated by an
 * earlier call to this method , quering the first page is done by passing a { @ code null } param .
 * @ param < T > Object type T
 * @ param rowsPerPage The number of rows per page .
 * @ param param The request parameter to use to query a page , or { @ code null } to return the first page .
 * @ param classOfT The class of type T .
 * @ return { @ link Page } */
public < T > Page < T > queryPage ( int rowsPerPage , String param , Class < T > classOfT ) { } }

implementation:
if ( param == null ) { // assume first page
return queryNextPage ( rowsPerPage , null , null , null , null , classOfT ) ; } String currentStartKey ; String currentStartKeyDocId ; String startKey ; String startKeyDocId ; String action ; try { // extract fields from the returned HEXed JSON object
final JsonObject json = new JsonParser ( ) . parse ( new String ( Base64 . decodeBase64 ( param . getBytes ( ) ) ) ) . getAsJsonObject ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Paging Param Decoded = " + json ) ; } final JsonObject jsonCurrent = json . getAsJsonObject ( CURRENT_KEYS ) ; currentStartKey = jsonCurrent . get ( CURRENT_START_KEY ) . getAsString ( ) ; currentStartKeyDocId = jsonCurrent . get ( CURRENT_START_KEY_DOC_ID ) . getAsString ( ) ; startKey = json . get ( START_KEY ) . getAsString ( ) ; startKeyDocId = json . get ( START_KEY_DOC_ID ) . getAsString ( ) ; action = json . get ( ACTION ) . getAsString ( ) ; } catch ( Exception e ) { throw new CouchDbException ( "could not parse the given param!" , e ) ; } if ( PREVIOUS . equals ( action ) ) { // previous
return queryPreviousPage ( rowsPerPage , currentStartKey , currentStartKeyDocId , startKey , startKeyDocId , classOfT ) ; } else { // next
return queryNextPage ( rowsPerPage , currentStartKey , currentStartKeyDocId , startKey , startKeyDocId , classOfT ) ; }


signature:
public class View { /** * Reverses the reading direction , not the sort order .
 * @ param descending The descending value true | false
 * @ return { @ link View } */
public View descending ( Boolean descending ) { } }

implementation: this . descending = Boolean . valueOf ( gson . toJson ( descending ) ) ; uriBuilder . query ( "descending" , this . descending ) ; return this ;


signature:
public class View { /** * Supplies a key list when calling < tt > _ all _ docs < / tt > View .
 * @ param keys The list of keys
 * @ return { @ link View } */
public View keys ( List < ? > keys ) { } }

implementation: this . allDocsKeys = String . format ( "{%s:%s}" , gson . toJson ( "keys" ) , gson . toJson ( keys ) ) ; return this ;


signature:
public class CouchDbDesign { /** * Synchronizes a design document to the Database .
 * < p > This method will first try to find a document in the database with the same id
 * as the given document , if it is not found then the given document will be saved to the database .
 * < p > If the document was found in the database , it will be compared with the given document using
 * { @ code equals ( ) } . If both documents are not equal , then the given document will be saved to the
 * database and updates the existing document .
 * @ param document The design document to synchronize
 * @ return { @ link Response } as a result of a document save or update , or returns { @ code null } if no
 * action was taken and the document in the database is up - to - date with the given document . */
public Response synchronizeWithDb ( DesignDocument document ) { } }

implementation: assertNotEmpty ( document , "Document" ) ; DesignDocument documentFromDb = null ; try { documentFromDb = getFromDb ( document . getId ( ) ) ; } catch ( NoDocumentException e ) { return dbc . save ( document ) ; } if ( ! document . equals ( documentFromDb ) ) { document . setRevision ( documentFromDb . getRevision ( ) ) ; return dbc . update ( document ) ; } return null ;