Input: This method applies the properties from the validationMetaData to the validator uses Spring s BeanWrapperImpl . [CODESPLIT] private void applyValidationMetaDataPropertiesToValidator ( ValidatorMetaData metaData , FieldValidator validator ) { Map < String , Object > properties = metaData . getProperties ( ) ; ifPropertyBlankRemove ( properties , "detailMessage" ) ; ifPropertyBlankRemove ( properties , "summaryMessage" ) ; BeanUtils . copyProperties ( validator , properties ) ; }


Input: Removes a property if it is null or an empty string . This allows the property to have a null or emtpy string in the meta - data but we don t copy it to the validator if the property is not set . [CODESPLIT] private void ifPropertyBlankRemove ( Map < String , Object > properties , String property ) { Object object = properties . get ( property ) ; if ( object == null ) { properties . remove ( property ) ; } else if ( object instanceof String ) { String string = ( String ) object ; if ( "" . equals ( string . trim ( ) ) ) { properties . remove ( property ) ; } } }


Input: Load the listFromClassLoader [CODESPLIT] public static List < String > listFromClassLoader ( ClassLoader loader , String resource ) { final List < URL > resourceURLs = Classpaths . classpathResources ( loader , resource ) ; final List < String > resourcePaths = Lists . list ( String . class ) ; final Map < URI , FileSystem > pathToZipFileSystems = new HashMap <> ( ) ; //So you don't have to keep loading the same jar/zip file. for ( URL resourceURL : resourceURLs ) { if ( resourceURL . getProtocol ( ) . equals ( "jar" ) ) { resourcesFromJar ( resourcePaths , resourceURL , pathToZipFileSystems ) ; } else { resourcesFromFileSystem ( resourcePaths , resourceURL ) ; } } return resourcePaths ; }


Input: Load the listFromClassLoader [CODESPLIT] public static List < Path > pathsFromClassLoader ( ClassLoader loader , String resource ) { final List < URL > resourceURLs = Classpaths . classpathResources ( loader , resource ) ; final List < Path > resourcePaths = Lists . list ( Path . class ) ; final Map < URI , FileSystem > pathToZipFileSystems = new HashMap <> ( ) ; //So you don't have to keep loading the same jar/zip file. for ( URL resourceURL : resourceURLs ) { if ( resourceURL . getProtocol ( ) . equals ( "jar" ) ) { pathsFromJar ( resourcePaths , resourceURL , pathToZipFileSystems ) ; } else { pathsFromFileSystem ( resourcePaths , resourceURL ) ; } } return resourcePaths ; }


Input:
Calculate utc time . This gets called every 20 mili - seconds or so . [CODESPLIT] @ Override public void tick ( long time ) { this . time . set ( time ) ; /*Foreign thread    every 20 or so mili-seconds so we don't spend too
         much time figuring out utc time. */ approxTime . set ( Dates . utcNow ( ) ) ; }


Input: Get the size of the cache . This is not 100% accurate if cache is being concurrenly accessed . [CODESPLIT] @ Override public int size ( ) { int size = 0 ; for ( SimpleCache < K , V > cache : cacheRegions ) { size += cache . size ( ) ; } return size ; }


Input: Calculate the hash . [CODESPLIT] private final int hash ( Object k ) { int h = hashSeed ; h ^= k . hashCode ( ) ; h ^= ( h >>> 20 ) ^ ( h >>> 12 ) ; return h ^ ( h >>> 7 ) ^ ( h >>> 4 ) ; }


Input: Configures default options . [CODESPLIT] private Options defaultOptions ( ) { Options options = new Options ( ) ; options . createIfMissing ( true ) ; options . blockSize ( 32_768 ) ; //32K options . cacheSize ( 67_108_864 ) ; //64MB return options ; }


Input: Opens the database [CODESPLIT] private boolean openDB ( File file , Options options ) { try { database = JniDBFactory . factory . open ( file , options ) ; logger . info ( "Using JNI Level DB" ) ; return true ; } catch ( IOException ex1 ) { try { database = Iq80DBFactory . factory . open ( file , options ) ; logger . info ( "Using Java Level DB" ) ; return false ; } catch ( IOException ex2 ) { return Exceptions . handle ( Boolean . class , ex2 ) ; } } }


Input: Puts values into the key value store in batch mode [CODESPLIT] @ Override public void putAll ( Map < byte [ ] , byte [ ] > values ) { WriteBatch batch = database . createWriteBatch ( ) ; try { for ( Map . Entry < byte [ ] , byte [ ] > entry : values . entrySet ( ) ) { batch . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } if ( putAllWriteCount . addAndGet ( values . size ( ) ) > 10_000 ) { putAllWriteCount . set ( 0 ) ; database . write ( batch , flush ) ; } else { database . write ( batch , writeOptions ) ; } } finally { closeBatch ( batch ) ; } }


Input: Remove all of the keys passed . [CODESPLIT] @ Override public void removeAll ( Iterable < byte [ ] > keys ) { WriteBatch batch = database . createWriteBatch ( ) ; try { for ( byte [ ] key : keys ) { batch . delete ( key ) ; } database . write ( batch ) ; } finally { closeBatch ( batch ) ; } }


Input: Search to a certain location . [CODESPLIT] @ Override public KeyValueIterable < byte [ ] , byte [ ] > search ( byte [ ] startKey ) { final DBIterator iterator = database . iterator ( ) ; iterator . seek ( startKey ) ; return new KeyValueIterable < byte [ ] , byte [ ] > ( ) { @ Override public void close ( ) { closeIterator ( iterator ) ; } @ Override public Iterator < Entry < byte [ ] , byte [ ] > > iterator ( ) { return new Iterator < Entry < byte [ ] , byte [ ] > > ( ) { @ Override public boolean hasNext ( ) { return iterator . hasNext ( ) ; } @ Override public Entry < byte [ ] , byte [ ] > next ( ) { Map . Entry < byte [ ] , byte [ ] > next = iterator . next ( ) ; return new Entry <> ( next . getKey ( ) , next . getValue ( ) ) ; } @ Override public void remove ( ) { iterator . remove ( ) ; } } ; } } ; }


Input: Load all of the key / values from the store . [CODESPLIT] @ Override public KeyValueIterable < byte [ ] , byte [ ] > loadAll ( ) { final DBIterator iterator = database . iterator ( ) ; iterator . seekToFirst ( ) ; return new KeyValueIterable < byte [ ] , byte [ ] > ( ) { @ Override public void close ( ) { closeIterator ( iterator ) ; } @ Override public Iterator < Entry < byte [ ] , byte [ ] > > iterator ( ) { return new Iterator < Entry < byte [ ] , byte [ ] > > ( ) { @ Override public boolean hasNext ( ) { return iterator . hasNext ( ) ; } @ Override public Entry < byte [ ] , byte [ ] > next ( ) { Map . Entry < byte [ ] , byte [ ] > next = iterator . next ( ) ; return new Entry <> ( next . getKey ( ) , next . getValue ( ) ) ; } @ Override public void remove ( ) { iterator . remove ( ) ; } } ; } } ; }


Input: Keys are expected to be sorted [CODESPLIT] @ Override public Map < byte [ ] , byte [ ] > loadAllByKeys ( Collection < byte [ ] > keys ) { if ( keys == null || keys . size ( ) == 0 ) { return Collections . EMPTY_MAP ; } Map < byte [ ] , byte [ ] > results = new LinkedHashMap <> ( keys . size ( ) ) ; DBIterator iterator = null ; try { iterator = database . iterator ( ) ; iterator . seek ( keys . iterator ( ) . next ( ) ) ; while ( iterator . hasNext ( ) ) { final Map . Entry < byte [ ] , byte [ ] > next = iterator . next ( ) ; results . put ( next . getKey ( ) , next . getValue ( ) ) ; } } finally { try { if ( iterator != null ) { iterator . close ( ) ; } } catch ( IOException e ) { Exceptions . handle ( e ) ; } } return results ; }


Input: Close the database connection . [CODESPLIT] @ Override public void close ( ) { try { flush ( ) ; database . close ( ) ; } catch ( Exception e ) { Exceptions . handle ( e ) ; } }


Input:
/ * End universal methods . [CODESPLIT] private static int calculateEndIndex ( double [ ] array , int originalIndex ) { final int length = array . length ; Exceptions . requireNonNull ( array , "array cannot be null" ) ; 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
         */ /* 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 ; }


Input: Reduce by functional support for int arrays . [CODESPLIT] public static < T > double reduceBy ( final double [ ] array , T object ) { if ( object . getClass ( ) . isAnonymousClass ( ) ) { return reduceByR ( array , object ) ; } try { ConstantCallSite callSite = Invoker . invokeReducerLongIntReturnLongMethodHandle ( object ) ; MethodHandle methodHandle = callSite . dynamicInvoker ( ) ; try { double sum = 0 ; for ( double v : array ) { sum = ( double ) methodHandle . invokeExact ( sum , v ) ; } return sum ; } catch ( Throwable throwable ) { return handle ( Long . class , throwable , "Unable to perform reduceBy" ) ; } } catch ( Exception ex ) { return reduceByR ( array , object ) ; } }


Input: Fallback to reflection if the call - site will not work or did not work [CODESPLIT] private static < T > double reduceByR ( final double [ ] array , T object ) { try { Method method = Invoker . invokeReducerLongIntReturnLongMethod ( object ) ; double sum = 0 ; for ( double v : array ) { sum = ( double ) method . invoke ( object , sum , v ) ; } return sum ; } catch ( Throwable throwable ) { return handle ( Long . class , throwable , "Unable to perform reduceBy" ) ; } }


Input: Min [CODESPLIT] public static double min ( double [ ] values , final int start , final int length ) { double min = Float . MAX_VALUE ; for ( int index = start ; index < length ; index ++ ) { if ( values [ index ] < min ) min = values [ index ] ; } return min ; }


Input: Calculate Variance . [CODESPLIT] public static double varianceDouble ( double [ ] values , final int start , final int length ) { double mean = mean ( values , start , length ) ; double temp = 0 ; for ( int index = start ; index < length ; index ++ ) { double a = values [ index ] ; temp += ( mean - a ) * ( mean - a ) ; } return temp / length ; }


Input:
/ * End universal methods . [CODESPLIT] private static int calculateIndex ( long [ ] array , int originalIndex ) { final int length = array . length ; Exceptions . requireNonNull ( array , "array cannot be null" ) ; 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
         */ /* 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 - 1 ; } return index ; }


Input: Max [CODESPLIT] public static long max ( long [ ] values , final int start , final int length ) { long max = Long . MIN_VALUE ; for ( int index = start ; index < length ; index ++ ) { if ( values [ index ] > max ) { max = values [ index ] ; } } return max ; }


Input: Min [CODESPLIT] public static long min ( long [ ] values , final int start , final int length ) { long min = Long . MAX_VALUE ; for ( int index = start ; index < length ; index ++ ) { if ( values [ index ] < min ) min = values [ index ] ; } return min ; }


Input: Average [CODESPLIT] public static long mean ( long [ ] values , final int start , final int length ) { return ( long ) Math . round ( meanDouble ( values , start , length ) ) ; }


Input: Calculates variance [CODESPLIT] public static long variance ( long [ ] values , final int start , final int length ) { return ( long ) Math . round ( varianceDouble ( values , start , length ) ) ; }


Input: Used internally to avoid loss and rounding errors a bit . [CODESPLIT] public static double meanDouble ( long [ ] values , final int start , final int length ) { double mean = ( ( double ) sum ( values , start , length ) ) / ( ( double ) length ) ; return mean ; }


Input: Calculate Median [CODESPLIT] public static long median ( long [ ] values , final int start , final int length ) { long [ ] sorted = new long [ length ] ; System . arraycopy ( values , start , sorted , 0 , length ) ; Arrays . sort ( sorted ) ; if ( length % 2 == 0 ) { int middle = sorted . length / 2 ; double median = ( sorted [ middle - 1 ] + sorted [ middle ] ) / 2.0 ; return Math . round ( median ) ; } else { return sorted [ sorted . length / 2 ] ; } }


Input: Main entry into system . <p / > <p / > <p / > If you are debugging something not coming into the system . <p / > Start here! [CODESPLIT] @ ServiceMethod public void mainRequestHandler ( DataStoreRequest dataStoreRequest ) { if ( verbose || debug ) { logger . info ( "RequestHandler::mainRequestHandler" , dataStoreRequest ) ; } switch ( dataStoreRequest . action ( ) ) { case GET : masterDataStore . get ( ( GetRequest ) dataStoreRequest ) ; break ; case GET_LOCAL_DB : handleGetLocalDbVerb ( dataStoreRequest ) ; break ; case GET_MEM : handleGetMemVerb ( dataStoreRequest ) ; break ; case SET : masterDataStore . set ( ( SetRequest ) dataStoreRequest ) ; break ; case SET_BROADCAST : handleSetAndBroadCastVerb ( dataStoreRequest ) ; break ; case SET_IF_NOT_EXIST : handleSetIfNotExistsVerb ( dataStoreRequest ) ; break ; case SET_BATCH : handleSetBatch ( dataStoreRequest ) ; break ; case SET_BATCH_IF_NOT_EXISTS : handleSetBatchIfNotExists ( dataStoreRequest ) ; break ; case SET_SOURCE : handleSetSource ( dataStoreRequest ) ; break ; case GET_SOURCE : handleGetSource ( dataStoreRequest ) ; break ; case BATCH_READ : handleBatchRead ( dataStoreRequest ) ; break ; case CLEAR_STATS : handleClearStats ( dataStoreRequest ) ; break ; case GET_STATS : handleGetStats ( dataStoreRequest ) ; break ; case REMOVE : handleRemove ( dataStoreRequest ) ; break ; case REMOVE_SOURCE : handleRemoveSource ( dataStoreRequest ) ; break ; case METHOD_CALL : handleMethodCall ( ( MethodCall ) dataStoreRequest ) ; break ; case SEARCH : handleSearchVerb ( dataStoreRequest ) ; break ; default : puts ( dataStoreRequest ) ; } trackCall ( dataStoreRequest . action ( ) ) ; }


Input: / * Allows this base class to be initialized by the subclasses . [CODESPLIT] protected void init ( Comparable min , Comparable max ) { this . realMin = min ; this . realMax = max ; assert min . compareTo ( max ) < 0 ; isInitialized = true ; }


Input: Invokes method from list or map depending on what the Object arg is . [CODESPLIT] public static Object invokeMethodFromObjectArg ( Object object , MethodAccess method , Object args ) { return invokeMethodFromObjectArg ( false , null , null , object , method , args ) ; }


Input: A very fast reduce by . If performance is your thing this seems to be as fast a plain for loop when benchmarking with JMH . [CODESPLIT] public static double reduceBy ( final float [ ] array , ReduceBy reduceBy ) { double sum = 0 ; for ( float v : array ) { sum = reduceBy . reduce ( sum , v ) ; } return sum ; }


Input: Big Sum [CODESPLIT] public static double bigSum ( float [ ] values , int start , int length ) { double sum = 0 ; for ( int index = start ; index < length ; index ++ ) { sum += values [ index ] ; } return sum ; }


Input: Max [CODESPLIT] public static float max ( float [ ] values , final int start , final int length ) { float max = Float . MIN_VALUE ; for ( int index = start ; index < length ; index ++ ) { if ( values [ index ] > max ) { max = values [ index ] ; } } return max ; }


Input: Calculate standard deviation . [CODESPLIT] public static float standardDeviation ( float [ ] values , final int start , final int length ) { double variance = varianceDouble ( values , start , length ) ; return ( float ) Math . sqrt ( variance ) ; }


Input: Useful for generated file names and generated work directories . [CODESPLIT] public static String euroUTCSystemDateString ( long timestamp ) { Calendar calendar = Calendar . getInstance ( ) ; calendar . setTimeInMillis ( timestamp ) ; calendar . setTimeZone ( UTC_TIME_ZONE ) ; int day = calendar . get ( Calendar . DAY_OF_MONTH ) ; int month = calendar . get ( Calendar . MONTH ) ; int year = calendar . get ( Calendar . YEAR ) ; int hour = calendar . get ( Calendar . HOUR_OF_DAY ) ; int minute = calendar . get ( Calendar . MINUTE ) ; int second = calendar . get ( Calendar . SECOND ) ; CharBuf buf = CharBuf . create ( 16 ) ; buf . add ( Str . zfill ( day , 2 ) ) . add ( ' ' ) ; buf . add ( Str . zfill ( month , 2 ) ) . add ( ' ' ) ; buf . add ( year ) . add ( ' ' ) ; buf . add ( Str . zfill ( hour , 2 ) ) . add ( ' ' ) ; buf . add ( Str . zfill ( minute , 2 ) ) . add ( ' ' ) ; buf . add ( Str . zfill ( second , 2 ) ) . add ( "_utc_euro" ) ; return buf . toString ( ) ; }


Input: Does the object match this expression . An expression is a collection of criteria . [CODESPLIT] public static boolean matches ( Object obj , Criteria ... exp ) { return ObjectFilter . and ( exp ) . test ( obj ) ; }


Input: This has to convert values to field type . [CODESPLIT] public static Criterion notIn ( final Object name , final Object ... values ) { return new Criterion < Object > ( name . toString ( ) , Operator . NOT_IN , values ) { @ Override public boolean resolve ( Object owner ) { Object fieldValue = fieldValue ( ) ; if ( value == null ) { return false ; } return ! valueSet ( ) . contains ( fieldValue ) ; } } ; }


Input: } [CODESPLIT] public static Criterion ltLong ( final Object name , final long compareValue ) { return new Criterion ( name . toString ( ) , Operator . LESS_THAN , compareValue ) { @ Override public boolean resolve ( final Object owner ) { long value = fieldLong ( ) ; return value < compareValue ; } } ; }


Input: Make criteria configurable [CODESPLIT] public static Criteria createCriteria ( String name , Operator operator , TypeType type , Class < Object > classType , List < ? > values ) { okOrDie ( "Values must be passed" , values ) ; Object value = values . get ( 0 ) ; switch ( operator ) { case EQUAL : switch ( type ) { case CHAR : return eqChar ( name , Conversions . toChar ( value ) ) ; case BYTE : return eqByte ( name , Conversions . toByte ( value ) ) ; case BOOLEAN : return eqBoolean ( name , Conversions . toBoolean ( value ) ) ; case INT : return eqInt ( name , Conversions . toInt ( value ) ) ; case FLOAT : return eqFloat ( name , Conversions . toFloat ( value ) ) ; case SHORT : return eqShort ( name , Conversions . toShort ( value ) ) ; case DOUBLE : return eqDouble ( name , Conversions . toDouble ( value ) ) ; case LONG : return eqLong ( name , Conversions . toLong ( value ) ) ; default : return eq ( name , Conversions . coerce ( classType , value ) ) ; } case NOT_EQUAL : switch ( type ) { case CHAR : return notEqChar ( name , Conversions . toChar ( value ) ) ; case BYTE : return notEqByte ( name , Conversions . toByte ( value ) ) ; case BOOLEAN : return notEqBoolean ( name , Conversions . toBoolean ( value ) ) ; case INT : return notEqInt ( name , Conversions . toInt ( value ) ) ; case FLOAT : return notEqFloat ( name , Conversions . toFloat ( value ) ) ; case SHORT : return notEqShort ( name , Conversions . toShort ( value ) ) ; case DOUBLE : return notEqDouble ( name , Conversions . toDouble ( value ) ) ; case LONG : return notEqLong ( name , Conversions . toLong ( value ) ) ; default : return notEq ( name , Conversions . coerce ( classType , value ) ) ; } case GREATER_THAN : switch ( type ) { case CHAR : return gtChar ( name , Conversions . toChar ( value ) ) ; case BYTE : return gtByte ( name , Conversions . toByte ( value ) ) ; case INT : return gtInt ( name , Conversions . toInt ( value ) ) ; case FLOAT : return gtFloat ( name , Conversions . toFloat ( value ) ) ; case SHORT : return gtShort ( name , Conversions . toShort ( value ) ) ; case DOUBLE : return gtDouble ( name , Conversions . toDouble ( value ) ) ; case LONG : return gtLong ( name , Conversions . toLong ( value ) ) ; default : return gt ( name , Conversions . coerce ( classType , value ) ) ; } case LESS_THAN : switch ( type ) { case CHAR : return ltChar ( name , Conversions . toChar ( value ) ) ; case BYTE : return ltByte ( name , Conversions . toByte ( value ) ) ; case INT : return ltInt ( name , Conversions . toInt ( value ) ) ; case FLOAT : return ltFloat ( name , Conversions . toFloat ( value ) ) ; case SHORT : return ltShort ( name , Conversions . toShort ( value ) ) ; case DOUBLE : return ltDouble ( name , Conversions . toDouble ( value ) ) ; case LONG : return ltLong ( name , Conversions . toLong ( value ) ) ; default : return lt ( name , Conversions . coerce ( classType , value ) ) ; } case GREATER_THAN_EQUAL : switch ( type ) { case CHAR : return gteChar ( name , Conversions . toChar ( value ) ) ; case BYTE : return gteByte ( name , Conversions . toByte ( value ) ) ; case INT : return gteInt ( name , Conversions . toInt ( value ) ) ; case FLOAT : return gteFloat ( name , Conversions . toFloat ( value ) ) ; case SHORT : return gteShort ( name , Conversions . toShort ( value ) ) ; case DOUBLE : return gteDouble ( name , Conversions . toDouble ( value ) ) ; case LONG : return gteLong ( name , Conversions . toLong ( value ) ) ; default : return gte ( name , Conversions . coerce ( classType , value ) ) ; } case LESS_THAN_EQUAL : switch ( type ) { case CHAR : return lteChar ( name , Conversions . toChar ( value ) ) ; case BYTE : return lteByte ( name , Conversions . toByte ( value ) ) ; case INT : return lteInt ( name , Conversions . toInt ( value ) ) ; case FLOAT : return lteFloat ( name , Conversions . toFloat ( value ) ) ; case SHORT : return lteShort ( name , Conversions . toShort ( value ) ) ; case DOUBLE : return lteDouble ( name , Conversions . toDouble ( value ) ) ; case LONG : return lteLong ( name , Conversions . toLong ( value ) ) ; default : return lte ( name , Conversions . coerce ( classType , value ) ) ; } case BETWEEN : okOrDie ( "Values must be at least 2 in size" , values . size ( ) > 1 ) ; Object value2 = values . get ( 1 ) ; switch ( type ) { case CHAR : return betweenChar ( name , Conversions . toChar ( value ) , Conversions . toChar ( value2 ) ) ; case BYTE : return betweenByte ( name , Conversions . toByte ( value ) , Conversions . toByte ( value2 ) ) ; case INT : return betweenInt ( name , Conversions . toInt ( value ) , Conversions . toInt ( value2 ) ) ; case FLOAT : return betweenFloat ( name , Conversions . toFloat ( value ) , Conversions . toFloat ( value2 ) ) ; case SHORT : return betweenShort ( name , Conversions . toShort ( value ) , Conversions . toShort ( value2 ) ) ; case DOUBLE : return betweenDouble ( name , Conversions . toDouble ( value ) , Conversions . toDouble ( value2 ) ) ; case LONG : return betweenLong ( name , Conversions . toLong ( value ) , Conversions . toLong ( value2 ) ) ; default : return between ( name , Conversions . coerce ( classType , value ) , Conversions . coerce ( classType , value2 ) ) ; } case IN : switch ( type ) { case CHAR : return inChars ( name , Conversions . carray ( values ) ) ; case BYTE : return inBytes ( name , Conversions . barray ( values ) ) ; case INT : return inInts ( name , Conversions . iarray ( values ) ) ; case FLOAT : return inFloats ( name , Conversions . farray ( values ) ) ; case SHORT : return inShorts ( name , Conversions . sarray ( values ) ) ; case DOUBLE : return inDoubles ( name , Conversions . darray ( values ) ) ; case LONG : return inLongs ( name , Conversions . larray ( values ) ) ; default : return in ( name , Conversions . toArray ( classType , ( List < Object > ) values ) ) ; } case NOT_IN : switch ( type ) { case CHAR : return notInChars ( name , Conversions . carray ( values ) ) ; case BYTE : return notInBytes ( name , Conversions . barray ( values ) ) ; case INT : return notInInts ( name , Conversions . iarray ( values ) ) ; case FLOAT : return notInFloats ( name , Conversions . farray ( values ) ) ; case SHORT : return notInShorts ( name , Conversions . sarray ( values ) ) ; case DOUBLE : return notInDoubles ( name , Conversions . darray ( values ) ) ; case LONG : return notInLongs ( name , Conversions . larray ( values ) ) ; default : return notIn ( name , Conversions . toArray ( classType , ( List < Object > ) values ) ) ; } case CONTAINS : return contains ( name , Conversions . coerce ( classType , value ) ) ; case NOT_CONTAINS : return notContains ( name , Conversions . coerce ( classType , value ) ) ; case STARTS_WITH : return startsWith ( name , value ) ; case ENDS_WITH : return endsWith ( name , value ) ; case NOT_EMPTY : return notEmpty ( name ) ; case IS_EMPTY : return empty ( name ) ; } return die ( Criteria . class , "Not Found" , name , operator , type , values ) ; }


Input: Make criteria configurable [CODESPLIT] public static Criteria createCriteriaFromClass ( String name , Class < ? > cls , Operator operator , List < ? > values ) { if ( operator == Operator . AND ) { return new Group . And ( cls , values ) ; } else if ( operator == Operator . OR ) { return new Group . Or ( cls , values ) ; } else { FieldAccess fieldAccess = BeanUtils . idxField ( cls , name ) ; return createCriteria ( name , operator , fieldAccess . typeEnum ( ) , ( Class < Object > ) fieldAccess . type ( ) , values ) ; } }


Input: Creates criteria from a list . This is used to configure Criteria in JSON . [CODESPLIT] public static Criteria criteriaFromList ( List < ? > list ) { List < Object > args = new ArrayList ( list ) ; Object o = atIndex ( args , - 1 ) ; if ( ! ( o instanceof List ) ) { atIndex ( args , - 1 , Collections . singletonList ( o ) ) ; } return ( Criteria ) Invoker . invokeFromList ( ObjectFilter . class , "createCriteriaFromClass" , args ) ; }


Input: Converts a JSON string into a Criteria . [CODESPLIT] public static Criteria criteriaFromJson ( String json ) { return ( Criteria ) Invoker . invokeFromObject ( ObjectFilter . class , "createCriteriaFromClass" , fromJson ( json ) ) ; }


Input: Creates a primitive list based on an input list and a property path [CODESPLIT] public static DoubleList toDoubleList ( Collection < ? > inputList , String propertyPath ) { if ( inputList . size ( ) == 0 ) { return new DoubleList ( 0 ) ; } DoubleList outputList = new DoubleList ( inputList . size ( ) ) ; if ( propertyPath . contains ( "." ) || propertyPath . contains ( "[" ) ) { String [ ] properties = StringScanner . splitByDelimiters ( propertyPath , ".[]" ) ; for ( Object o : inputList ) { outputList . add ( BeanUtils . getPropertyDouble ( o , properties ) ) ; } } else { Map < String , FieldAccess > fields = BeanUtils . getFieldsFromObject ( inputList . iterator ( ) . next ( ) ) ; FieldAccess fieldAccess = fields . get ( propertyPath ) ; for ( Object o : inputList ) { outputList . add ( fieldAccess . getDouble ( o ) ) ; } } return outputList ; }


Input: Add a new value to the list but don t employ a wrapper . [CODESPLIT] public boolean addFloat ( double value ) { if ( end + 1 >= values . length ) { values = grow ( values ) ; } values [ end ] = value ; end ++ ; return true ; }


Input: Add a new value to the list but don t employ a wrapper . [CODESPLIT] public DoubleList add ( double integer ) { if ( end + 1 >= values . length ) { values = grow ( values ) ; } values [ end ] = integer ; end ++ ; return this ; }


Input: Add a new array to the list . [CODESPLIT] public boolean addArray ( double ... integers ) { if ( end + integers . length >= values . length ) { values = grow ( values , ( values . length + integers . length ) * 2 ) ; } System . arraycopy ( integers , 0 , values , end , integers . length ) ; end += integers . length ; return true ; }


Input: Set a value in the list . [CODESPLIT] @ Override public Double set ( int index , Double element ) { double oldValue = values [ index ] ; values [ index ] = element ; return oldValue ; }


Input: This would be a good opportunity to reintroduce dynamic invoke [CODESPLIT] public double reduceBy ( Object function , String name ) { return Dbl . reduceBy ( values , end , function , name ) ; }


Input: Does a binary search [CODESPLIT] public static < T > T search ( List < T > list , T item ) { if ( list . size ( ) > 1 ) { Object o = list ; int index = Collections . binarySearch ( ( List < ? extends Comparable < ? super T > > ) o , item ) ; return list . get ( index ) ; } else { return null ; } }


Input: Does a binary search [CODESPLIT] public static int searchForIndex ( List < ? > list , Object item ) { if ( list . size ( ) > 1 ) { Object o = list ; return Collections . binarySearch ( ( List < ? extends Comparable < ? super Object > > ) o , item ) ; } else { return - 1 ; } }


Input: Gets the max item from the array . Sorts the list descending first . [CODESPLIT] public static < T > T max ( T [ ] array ) { if ( array . length > 1 ) { Sorting . sortDesc ( array ) ; return array [ 0 ] ; } else { return null ; } }


Input: From the sorts this is the first few items . [CODESPLIT] public static < T > List < T > firstOf ( List < T > list , int count , Sort ... sorts ) { if ( list . size ( ) > 1 ) { Sorting . sort ( list , sorts ) ; return Lists . sliceOf ( list , 0 , count ) ; } else { return null ; } }


Input: Grabs the last items after the sort . [CODESPLIT] public static < T > T lastOf ( List < T > list , Sort ... sorts ) { if ( list . size ( ) > 1 ) { Sorting . sort ( list , sorts ) ; return list . get ( list . size ( ) - 1 ) ; } else { return null ; } }


Input: Grabs the last few items from the list . [CODESPLIT] public static < T > List < T > lastOf ( List < T > list , int count , Sort ... sorts ) { if ( list . size ( ) > 1 ) { Sorting . sort ( list , sorts ) ; return Lists . endSliceOf ( list , count * - 1 ) ; } else { return null ; } }


Input: Returns the max value of the object with the property given . [CODESPLIT] public static < T > T max ( List < T > list , String sortBy ) { if ( list . size ( ) > 1 ) { Sorting . sortDesc ( list , sortBy ) ; return list . get ( 0 ) ; } else { return null ; } }


Input: Returns the max value of the object with the property given . [CODESPLIT] public static < T > T max ( T [ ] array , String sortBy ) { if ( array . length > 1 ) { Sorting . sortDesc ( array , sortBy ) ; return array [ 0 ] ; } else { return null ; } }


Input: Returns the least few . [CODESPLIT] public static < T > List < T > least ( List < T > list , int count ) { if ( list . size ( ) > 1 ) { Sorting . sort ( list ) ; return Lists . sliceOf ( list , 0 , count ) ; } else { return null ; } }


Input: Returns the min value using a natural sort . [CODESPLIT] public static < T > T min ( List < T > list ) { if ( list . size ( ) > 1 ) { Sorting . sort ( list ) ; return list . get ( 0 ) ; } else { return null ; } }


Input: Returns the max value of the object with the property given . [CODESPLIT] public static < T > T min ( T [ ] array ) { if ( array . length > 1 ) { Sorting . sort ( array ) ; return array [ 0 ] ; } else { return null ; } }


Input: Returns the min value of the object with the property given . [CODESPLIT] public static < T > T min ( T [ ] array , String sortBy ) { if ( array . length > 1 ) { Sorting . sort ( array , sortBy ) ; return array [ 0 ] ; } else { return null ; } }


Input: This converts a list of maps to objects . I always forget that this exists . I need to remember . [CODESPLIT] @ Override public < T > List < T > convertListOfMapsToObjects ( List < Map > list , Class < T > componentType ) { List < Object > newList = new ArrayList <> ( list . size ( ) ) ; for ( Object obj : list ) { if ( obj instanceof Value ) { obj = ( ( Value ) obj ) . toValue ( ) ; } if ( obj instanceof Map ) { Map map = ( Map ) obj ; if ( map instanceof ValueMapImpl ) { newList . add ( fromValueMap ( ( Map < String , Value > ) map , componentType ) ) ; } else { newList . add ( fromMap ( map , componentType ) ) ; } } else { newList . add ( Conversions . coerce ( componentType , obj ) ) ; } } return ( List < T > ) newList ; }


Input: Processes an array of maps . [CODESPLIT] private void processArrayOfMaps ( Object newInstance , FieldAccess field , Map < String , Object > [ ] maps ) { List < Map < String , Object > > list = Lists . list ( maps ) ; handleCollectionOfMaps ( newInstance , field , list ) ; }


Input: Processes an collection of maps . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) private void handleCollectionOfMaps ( Object newInstance , FieldAccess field , Collection < Map < String , Object > > collectionOfMaps ) { Collection < Object > newCollection = Conversions . createCollection ( field . type ( ) , collectionOfMaps . size ( ) ) ; Class < ? > componentClass = field . getComponentClass ( ) ; if ( componentClass != null ) { for ( Map < String , Object > mapComponent : collectionOfMaps ) { newCollection . add ( fromMap ( mapComponent , componentClass ) ) ; } field . setObject ( newInstance , newCollection ) ; } }


Input:
This converts / coerce a constructor argument to the given parameter type . [CODESPLIT] private boolean matchAndConvertArgs ( List < Object > convertedArgumentList , BaseAccess methodAccess , Class [ ] parameterTypes , int index , boolean [ ] flag , boolean loose ) { Object value = null ; try { Class parameterClass ; Object item ; parameterClass = parameterTypes [ index ] ; item = convertedArgumentList . get ( index ) ; final TypeType parameterType = TypeType . getType ( parameterClass ) ; if ( item instanceof ValueContainer ) { item = ( ( ValueContainer ) item ) . toValue ( ) ; convertedArgumentList . set ( index , item ) ; } if ( item == null ) { return true ; } switch ( parameterType ) { case INT : case SHORT : case BYTE : case BOOLEAN : case CHAR : case FLOAT : case DOUBLE : case LONG : if ( item == null ) { return false ; } case INTEGER_WRAPPER : case BYTE_WRAPPER : case SHORT_WRAPPER : case BOOLEAN_WRAPPER : case CHAR_WRAPPER : case FLOAT_WRAPPER : case DOUBLE_WRAPPER : case CHAR_SEQUENCE : case NUMBER : case LONG_WRAPPER : if ( ! loose ) { if ( item instanceof Number ) { value = Conversions . coerceWithFlag ( parameterType , parameterClass , flag , item ) ; convertedArgumentList . set ( index , value ) ; return flag [ 0 ] ; } else { return false ; } } else { value = Conversions . coerceWithFlag ( parameterType , parameterClass , flag , item ) ; convertedArgumentList . set ( index , value ) ; return flag [ 0 ] ; } case ENUM : if ( item instanceof Enum ) { return true ; } if ( item instanceof CharSequence ) { value = toEnum ( parameterClass , item . toString ( ) ) ; convertedArgumentList . set ( index , value ) ; return value != null ; } else if ( item instanceof Number ) { value = toEnum ( parameterClass , ( ( Number ) item ) . intValue ( ) ) ; convertedArgumentList . set ( index , value ) ; return value != null ; } else { return false ; } case CLASS : if ( item instanceof Class ) { return true ; } value = Conversions . coerceWithFlag ( parameterType , parameterClass , flag , item ) ; convertedArgumentList . set ( index , value ) ; return flag [ 0 ] ; case STRING : if ( item instanceof String ) { return true ; } if ( item instanceof CharSequence ) { value = item . toString ( ) ; convertedArgumentList . set ( index , value ) ; return true ; } else if ( loose ) { value = item . toString ( ) ; convertedArgumentList . set ( index , value ) ; return true ; } else { return false ; } case MAP : case VALUE_MAP : if ( item instanceof Map ) { Map itemMap = ( Map ) item ; /* This code creates a map based on the parameterized types of the constructor arg.
                     *  This does ninja level generics manipulations and needs to be captured in some
                     *  reusable way.
                      * */ Type type = methodAccess . getGenericParameterTypes ( ) [ index ] ; if ( type instanceof ParameterizedType ) { ParameterizedType pType = ( ParameterizedType ) type ; Class < ? > keyType = ( Class < ? > ) pType . getActualTypeArguments ( ) [ 0 ] ; Class < ? > valueType = ( Class < ? > ) pType . getActualTypeArguments ( ) [ 1 ] ; Map newMap = Conversions . createMap ( parameterClass , itemMap . size ( ) ) ; /* Iterate through the map items and convert the keys/values to match
                    the parameterized constructor parameter args.
                     */ for ( Object o : itemMap . entrySet ( ) ) { Map . Entry entry = ( Map . Entry ) o ; Object key = entry . getKey ( ) ; value = entry . getValue ( ) ; key = ValueContainer . toObject ( key ) ; value = ValueContainer . toObject ( value ) ; /* Here is the actual conversion from a list or a map of some object.
                        This can be captured in helper method the duplication is obvious.
                         */ if ( value instanceof List ) { value = fromList ( ( List ) value , valueType ) ; } else if ( value instanceof Map ) { value = fromMap ( ( Map ) value , valueType ) ; } else { value = coerce ( valueType , value ) ; } if ( key instanceof List ) { key = fromList ( ( List ) key , keyType ) ; } else if ( value instanceof Map ) { key = fromMap ( ( Map ) key , keyType ) ; } else { key = coerce ( keyType , key ) ; } newMap . put ( key , value ) ; } convertedArgumentList . set ( index , newMap ) ; return true ; } } break ; case INSTANCE : if ( parameterClass . isInstance ( item ) ) { return true ; } if ( item instanceof Map ) { item = fromMap ( ( Map < String , Object > ) item , parameterClass ) ; convertedArgumentList . set ( index , item ) ; return true ; } else if ( item instanceof List ) { List < Object > listItem = null ; listItem = ( List < Object > ) item ; value = fromList ( listItem , parameterClass ) ; convertedArgumentList . set ( index , value ) ; return true ; } else { convertedArgumentList . set ( index , coerce ( parameterClass , item ) ) ; return true ; } //break; case INTERFACE : case ABSTRACT : if ( parameterClass . isInstance ( item ) ) { return true ; } if ( item instanceof Map ) { /** Handle conversion of user define interfaces. */ String className = ( String ) ( ( Map ) item ) . get ( "class" ) ; if ( className != null ) { item = fromMap ( ( Map < String , Object > ) item , Reflection . loadClass ( className ) ) ; convertedArgumentList . set ( index , item ) ; return true ; } else { return false ; } } break ; 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 : item = Conversions . toList ( item ) ; case SET : case COLLECTION : case LIST : if ( item instanceof List ) { List < Object > itemList = ( List < Object > ) item ; /* Items have stuff in it, the item is a list of lists.
                         * This is like we did earlier with the map.
                         * Here is some more ninja generics Java programming that needs to be captured in one place.
                         * */ if ( itemList . size ( ) > 0 && ( itemList . get ( 0 ) instanceof List || itemList . get ( 0 ) instanceof ValueContainer ) ) { /** Grab the generic type of the list. */ Type type = methodAccess . getGenericParameterTypes ( ) [ index ] ; /*  Try to pull the generic type information out so you can create
                               a strongly typed list to inject.
                             */ if ( type instanceof ParameterizedType ) { ParameterizedType pType = ( ParameterizedType ) type ; Class < ? > componentType ; if ( ! ( pType . getActualTypeArguments ( ) [ 0 ] instanceof Class ) ) { componentType = Object . class ; } else { componentType = ( Class < ? > ) pType . getActualTypeArguments ( ) [ 0 ] ; } Collection newList = Conversions . createCollection ( parameterClass , itemList . size ( ) ) ; for ( Object o : itemList ) { if ( o instanceof ValueContainer ) { o = ( ( ValueContainer ) o ) . toValue ( ) ; } if ( componentType == Object . class ) { newList . add ( o ) ; } else { List fromList = ( List ) o ; o = fromList ( fromList , componentType ) ; newList . add ( o ) ; } } convertedArgumentList . set ( index , newList ) ; return true ; } } else { /* Just a list not a list of lists so see if it has generics and pull out the
                        * type information and created a strong typed list. This looks a bit familiar.
                        * There is a big opportunity for some reuse here. */ Type type = methodAccess . getGenericParameterTypes ( ) [ index ] ; if ( type instanceof ParameterizedType ) { ParameterizedType pType = ( ParameterizedType ) type ; Class < ? > componentType = pType . getActualTypeArguments ( ) [ 0 ] instanceof Class ? ( Class < ? > ) pType . getActualTypeArguments ( ) [ 0 ] : Object . class ; Collection newList = Conversions . createCollection ( parameterClass , itemList . size ( ) ) ; for ( Object o : itemList ) { if ( o instanceof ValueContainer ) { o = ( ( ValueContainer ) o ) . toValue ( ) ; } if ( o instanceof List ) { if ( componentType != Object . class ) { List fromList = ( List ) o ; o = fromList ( fromList , componentType ) ; } newList . add ( o ) ; } else if ( o instanceof Map ) { Map fromMap = ( Map ) o ; o = fromMap ( fromMap , componentType ) ; newList . add ( o ) ; } else { newList . add ( Conversions . coerce ( componentType , o ) ) ; } } convertedArgumentList . set ( index , newList ) ; return true ; } } } return false ; default : final TypeType itemType = TypeType . getInstanceType ( item ) ; switch ( itemType ) { case LIST : convertedArgumentList . set ( index , fromList ( ( List < Object > ) item , parameterClass ) ) ; return true ; case MAP : case VALUE_MAP : convertedArgumentList . set ( index , fromMap ( ( Map < String , Object > ) item , parameterClass ) ) ; return true ; case NUMBER : case BOOLEAN : case INT : case SHORT : case BYTE : case FLOAT : case DOUBLE : case LONG : case DOUBLE_WRAPPER : case FLOAT_WRAPPER : case INTEGER_WRAPPER : case SHORT_WRAPPER : case BOOLEAN_WRAPPER : case BYTE_WRAPPER : case LONG_WRAPPER : case CLASS : case VALUE : value = Conversions . coerceWithFlag ( parameterClass , flag , item ) ; if ( flag [ 0 ] == false ) { return false ; } convertedArgumentList . set ( index , value ) ; return true ; case CHAR_SEQUENCE : case STRING : value = Conversions . coerceWithFlag ( parameterClass , flag , item ) ; if ( flag [ 0 ] == false ) { return false ; } convertedArgumentList . set ( index , value ) ; return true ; } } if ( parameterClass . isInstance ( item ) ) { return true ; } } catch ( Exception ex ) { Boon . error ( ex , "PROBLEM WITH oldMatchAndConvertArgs" , "fieldsAccessor" , fieldsAccessor , "list" , convertedArgumentList , "constructor" , methodAccess , "parameters" , parameterTypes , "index" , index ) ; return false ; } return false ; }


Input:
Processes an collection of maps . This can inject into an array and appears to be using some of the TypeType lib . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) private void handleCollectionOfValues ( Object newInstance , FieldAccess field , Collection < Value > acollectionOfValues ) { Collection collectionOfValues = acollectionOfValues ; if ( null == collectionOfValues ) { field . setObject ( newInstance , null ) ; return ; } if ( field . typeEnum ( ) == INSTANCE ) { field . setObject ( newInstance , fromList ( ( List ) acollectionOfValues , field . type ( ) ) ) ; return ; } if ( collectionOfValues instanceof ValueList ) { collectionOfValues = ( ( ValueList ) collectionOfValues ) . list ( ) ; } Class < ? > componentClass = field . getComponentClass ( ) ; /** If the field is a collection than try to convert the items in the collection to
         * the field type.
         */ switch ( field . typeEnum ( ) ) { case LIST : case SET : case COLLECTION : Collection < Object > newCollection = Conversions . createCollection ( field . type ( ) , collectionOfValues . size ( ) ) ; for ( Value value : ( List < Value > ) collectionOfValues ) { if ( value . isContainer ( ) ) { Object oValue = value . toValue ( ) ; if ( oValue instanceof Map ) { newCollection . add ( fromValueMap ( ( Map ) oValue , componentClass ) ) ; } } else { newCollection . add ( Conversions . coerce ( componentClass , value . toValue ( ) ) ) ; } } field . setObject ( newInstance , newCollection ) ; break ; 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 : TypeType componentType = field . componentType ( ) ; int index = 0 ; switch ( componentType ) { case INT : int [ ] iarray = new int [ collectionOfValues . size ( ) ] ; for ( Value value : ( List < Value > ) collectionOfValues ) { iarray [ index ] = value . intValue ( ) ; index ++ ; } field . setObject ( newInstance , iarray ) ; return ; case SHORT : short [ ] sarray = new short [ collectionOfValues . size ( ) ] ; for ( Value value : ( List < Value > ) collectionOfValues ) { sarray [ index ] = value . shortValue ( ) ; index ++ ; } field . setObject ( newInstance , sarray ) ; return ; case DOUBLE : double [ ] darray = new double [ collectionOfValues . size ( ) ] ; for ( Value value : ( List < Value > ) collectionOfValues ) { darray [ index ] = value . doubleValue ( ) ; index ++ ; } field . setObject ( newInstance , darray ) ; return ; case FLOAT : float [ ] farray = new float [ collectionOfValues . size ( ) ] ; for ( Value value : ( List < Value > ) collectionOfValues ) { farray [ index ] = value . floatValue ( ) ; index ++ ; } field . setObject ( newInstance , farray ) ; return ; case LONG : long [ ] larray = new long [ collectionOfValues . size ( ) ] ; for ( Value value : ( List < Value > ) collectionOfValues ) { larray [ index ] = value . longValue ( ) ; index ++ ; } field . setObject ( newInstance , larray ) ; return ; case BYTE : byte [ ] barray = new byte [ collectionOfValues . size ( ) ] ; for ( Value value : ( List < Value > ) collectionOfValues ) { barray [ index ] = value . byteValue ( ) ; index ++ ; } field . setObject ( newInstance , barray ) ; return ; case CHAR : char [ ] chars = new char [ collectionOfValues . size ( ) ] ; for ( Value value : ( List < Value > ) collectionOfValues ) { chars [ index ] = value . charValue ( ) ; index ++ ; } field . setObject ( newInstance , chars ) ; return ; case STRING : CharBuf buffer = CharBuf . create ( 100 ) ; String [ ] strings = new String [ collectionOfValues . size ( ) ] ; for ( Value value : ( List < Value > ) collectionOfValues ) { strings [ index ] = value . stringValue ( buffer ) ; index ++ ; } field . setObject ( newInstance , strings ) ; return ; default : Object array = Array . newInstance ( componentClass , collectionOfValues . size ( ) ) ; Object o ; for ( Value value : ( List < Value > ) collectionOfValues ) { if ( value instanceof ValueContainer ) { o = value . toValue ( ) ; if ( o instanceof List ) { o = fromList ( ( List ) o , componentClass ) ; if ( componentClass . isInstance ( o ) ) { Array . set ( array , index , o ) ; } else { break ; } } else if ( o instanceof Map ) { o = fromMap ( ( Map ) o , componentClass ) ; if ( componentClass . isInstance ( o ) ) { Array . set ( array , index , o ) ; } else { break ; } } } else { o = value . toValue ( ) ; if ( componentClass . isInstance ( o ) ) { Array . set ( array , index , o ) ; } else { Array . set ( array , index , Conversions . coerce ( componentClass , o ) ) ; } } index ++ ; } field . setValue ( newInstance , array ) ; } break ; } }


Input:
Helper method to extract collection of values into some field collection . REFACTOR : This could be refactored to use the org . boon . core . TypeType system which should be faster . REFACTOR [CODESPLIT] private void processCollectionFromMapUsingFields ( final Object newInstance , final FieldAccess field , final Collection < ? > collection ) { final Class < ? > fieldComponentClass = field . getComponentClass ( ) ; final Class < ? > valueComponentClass = Reflection . getComponentType ( collection ) ; /** See if we have a collection of maps because if we do, then we have some
         * recursive processing to do.
         */ if ( Typ . isMap ( valueComponentClass ) ) { handleCollectionOfMaps ( newInstance , field , ( Collection < Map < String , Object > > ) collection ) ; return ; } /** See if this is a value object of some sort. */ if ( Typ . isValue ( valueComponentClass ) ) { handleCollectionOfValues ( newInstance , field , ( Collection < Value > ) collection ) ; return ; } /**
         * See if the collection implements the same type as the field.
         * I saw a few places that could have used this helper method earlier in the file but were not.
         */ if ( Typ . implementsInterface ( collection . getClass ( ) , field . type ( ) ) ) { if ( fieldComponentClass != null && fieldComponentClass . isAssignableFrom ( valueComponentClass ) ) { field . setValue ( newInstance , collection ) ; return ; } } /** See if this is some sort of collection.
         * TODO we need a coerce that needs a respectIgnore
         *
         * REFACTOR:
         * Note we are assuming it is a collection of instances.
         * We don't handle enums here.
         *
         * We do in other places.
         *
         * We handle all sorts of generics but not here.
         *
         * REFACTOR
         *
         **/ if ( ! field . typeEnum ( ) . isCollection ( ) ) { if ( collection instanceof List ) { try { Object value = fromList ( ( List ) collection , field . getComponentClass ( ) ) ; field . setValue ( newInstance , value ) ; } catch ( Exception ex ) { //There is an edge case that needs this. We need a coerce that takes respectIngore, etc. field . setValue ( newInstance , collection ) ; } } else { field . setValue ( newInstance , collection ) ; } return ; } /**
         * Create a new collection. if the types already match then just copy them over.
         * Note that this is currently untyped in the null case.
         * We are relying on the fact that the field.setValue calls the Conversion.coerce.
         */ Collection < Object > newCollection = Conversions . createCollection ( field . type ( ) , collection . size ( ) ) ; if ( fieldComponentClass == null || fieldComponentClass . isAssignableFrom ( valueComponentClass ) ) { newCollection . addAll ( collection ) ; field . setValue ( newInstance , newCollection ) ; return ; } /* Here we try to do the coercion for each individual collection item. */ for ( Object itemValue : collection ) { newCollection . add ( Conversions . coerce ( fieldComponentClass , itemValue ) ) ; field . setValue ( newInstance , newCollection ) ; } }


Input: fromMap converts a map into a Java object . This version will see if there is a class parameter in the map and dies if there is not . [CODESPLIT] @ Override public Object fromMap ( Map < String , Object > map ) { String clazz = ( String ) map . get ( "class" ) ; Class cls = Reflection . loadClass ( clazz ) ; return fromMap ( map , cls ) ; }


Input: Creates a list of maps from a list of class instances . [CODESPLIT] @ Override public List < Map < String , Object > > toListOfMaps ( Collection < ? > collection ) { List < Map < String , Object > > list = new ArrayList <> ( ) ; for ( Object o : collection ) { list . add ( toMap ( o ) ) ; } return list ; }


Input: Key [CODESPLIT] @ Override public void put ( KEY key , VALUE value ) { VALUE oldValue = map . put ( key , value ) ; if ( oldValue != null ) { removeThenAddKey ( key ) ; } else { addKey ( key ) ; } if ( map . size ( ) > limit ) { map . remove ( removeLast ( ) ) ; } }


Input: Get the value at key [CODESPLIT] @ Override public VALUE get ( KEY key ) { removeThenAddKey ( key ) ; return map . get ( key ) ; }


Input: Get the field label . [CODESPLIT] public static String getLabel ( final String fieldName , final ResourceBundle bundle ) { String label ; /** Look for fieldName, e.g., firstName. */ try { label = bundle . getString ( fieldName ) ; } catch ( MissingResourceException mre ) { label = generateLabelValue ( fieldName ) ; } return label ; }


Input: Get the field label . [CODESPLIT] public static String createLabelWithNameSpace ( final String namespace , final String fieldName , final ResourceBundle bundle ) { String label ; try { try { /** Look for name-space + . + fieldName, e.g., Employee.firstName. */ label = bundle . getString ( namespace + ' ' + fieldName ) ; } catch ( MissingResourceException mre ) { /** Look for fieldName only, e.g., firstName. */ label = bundle . getString ( fieldName ) ; } } catch ( MissingResourceException mre ) { /** If you can't find the label, generate it thus, "firstName" becomes "First Name".*/ label = generateLabelValue ( fieldName ) ; } return label ; }


Input: Get the tool tip . [CODESPLIT] public static String createToolTipWithNameSpace ( final String namespace , final String fieldName , final ResourceBundle bundle , final String toolTipType ) { String toolTip = null ; try { try { /** Look for name-space + . + fieldName, e.g., Employee.firstName.toolTip. */ toolTip = bundle . getString ( namespace + ' ' + fieldName + ' ' + toolTipType ) ; } catch ( MissingResourceException mre ) { /** Look for fieldName only, e.g., firstName.toolTip. */ toolTip = bundle . getString ( fieldName + ' ' + toolTipType ) ; } } catch ( MissingResourceException mre ) { } return toolTip ; }


Input:
Generate the field . Transforms firstName into First Name . This allows reasonable defaults for labels . [CODESPLIT] public static String generateLabelValue ( final String fieldName ) { final StringBuilder buffer = new StringBuilder ( fieldName . length ( ) * 2 ) ; class GenerationCommand { boolean capNextChar = false ; boolean lastCharWasUpperCase = false ; boolean lastCharWasNumber = false ; boolean lastCharWasSpecial = false ; boolean shouldContinue = true ; char [ ] chars = fieldName . toCharArray ( ) ; void processFieldName ( ) { for ( int index = 0 ; index < chars . length ; index ++ ) { char cchar = chars [ index ] ; shouldContinue = true ; processCharWasNumber ( buffer , index , cchar ) ; if ( ! shouldContinue ) { continue ; } processCharWasUpperCase ( buffer , index , cchar ) ; if ( ! shouldContinue ) { continue ; } processSpecialChars ( buffer , cchar ) ; if ( ! shouldContinue ) { continue ; } cchar = processCapitalizeCommand ( cchar ) ; cchar = processFirstCharacterCheck ( buffer , index , cchar ) ; if ( ! shouldContinue ) { continue ; } buffer . append ( cchar ) ; } } private void processCharWasNumber ( StringBuilder buffer , int index , char cchar ) { if ( lastCharWasSpecial ) { return ; } if ( Character . isDigit ( cchar ) ) { if ( index != 0 && ! lastCharWasNumber ) { buffer . append ( ' ' ) ; } lastCharWasNumber = true ; buffer . append ( cchar ) ; this . shouldContinue = false ; } else { lastCharWasNumber = false ; } } private char processFirstCharacterCheck ( final StringBuilder buffer , int index , char cchar ) { /* Always capitalize the first character. */ if ( index == 0 ) { cchar = Character . toUpperCase ( cchar ) ; buffer . append ( cchar ) ; this . shouldContinue = false ; } return cchar ; } private char processCapitalizeCommand ( char cchar ) { /* Capitalize the character. */ if ( capNextChar ) { capNextChar = false ; cchar = Character . toUpperCase ( cchar ) ; } return cchar ; } private void processSpecialChars ( final StringBuilder buffer , char cchar ) { lastCharWasSpecial = false ; /* If the character is '.' or '_' then append a space and mark
                 * the next iteration to capitalize.
				 */ if ( cchar == ' ' || cchar == ' ' ) { buffer . append ( ' ' ) ; capNextChar = true ; lastCharWasSpecial = false ; this . shouldContinue = false ; } } private void processCharWasUpperCase ( final StringBuilder buffer , int index , char cchar ) { /* If the character is uppercase, append a space and keep track
                 * that the last character was uppercase for the next iteration.
				 */ if ( Character . isUpperCase ( cchar ) ) { if ( index != 0 && ! lastCharWasUpperCase ) { buffer . append ( ' ' ) ; } lastCharWasUpperCase = true ; buffer . append ( cchar ) ; this . shouldContinue = false ; } else { lastCharWasUpperCase = false ; } } } GenerationCommand gc = new GenerationCommand ( ) ; gc . processFieldName ( ) ; /* This is a hack to get address.line_1 to work. */ return buffer . toString ( ) . replace ( "  " , " " ) ; }


Input: Turn a single bytes into two hex character representation . [CODESPLIT] public CharSequence addHex ( final int decoded ) { int _location = location ; char [ ] _buffer = buffer ; int _capacity = capacity ; if ( 2 + _location > _capacity ) { _buffer = Chr . grow ( _buffer ) ; _capacity = _buffer . length ; } _buffer [ _location ] = ( char ) encodeNibbleToHexAsciiCharByte ( ( decoded >> 4 ) & 0x0F ) ; _location ++ ; _buffer [ _location ] = ( char ) encodeNibbleToHexAsciiCharByte ( decoded & 0x0F ) ; ; _location ++ ; location = _location ; buffer = _buffer ; capacity = _capacity ; return this ; }


Input: RESPONSES FROM SERVER . [CODESPLIT] private void handleMessageFromServer ( String textResponse ) { if ( verbose ) { puts ( "RESPONSE" , url , ProtocolConstants . prettyPrintMessage ( textResponse ) ) ; puts ( "RESPONSE" , url ) ; puts ( ProtocolConstants . prettyPrintMessageWithLinesTabs ( textResponse ) ) ; } if ( textResponse . startsWith ( Action . GET . response ( ) . startsWith ( ) ) || textResponse . startsWith ( Action . SET_BROADCAST . response ( ) . startsWith ( ) ) ) { queue . put ( SingleResult . fromTextMessage ( textResponse ) ) ; } else if ( textResponse . startsWith ( Action . BATCH_READ . response ( ) . startsWith ( ) ) ) { queue . put ( BatchResult . fromTextMessage ( textResponse ) ) ; } else if ( textResponse . startsWith ( Action . GET_STATS . response ( ) . startsWith ( ) ) ) { queue . put ( StatsResults . fromTextMessage ( textResponse ) ) ; } else { if ( verbose ) { puts ( textResponse ) ; } } }


Input: public SetRequest ( DataStoreSource source Action action long id String clientId long version long createTimeStamp long updateTimeStamp String key String payload ) { [CODESPLIT] @ Override public void set ( DataStoreSource source , String key , Object value ) { SetRequest request = new SetRequest ( source , Action . SET_SOURCE , messageId , clientId , 0 , 0 , 0 , key , serializer . serialize ( value ) . toString ( ) ) ; send ( request ) ; }


Input: Search for a key in the key / value store . [CODESPLIT] public KeyValueIterable < K , V > search ( K startKey ) { final KeyValueIterable < String , byte [ ] > search = store . search ( toKeyString ( startKey ) ) ; final Iterator < Entry < String , byte [ ] > > iterator = search . iterator ( ) ; return new KeyValueIterable < K , V > ( ) { @ Override public void close ( ) { search . close ( ) ; } @ Override public Iterator < Entry < K , V > > iterator ( ) { return new Iterator < Entry < K , V > > ( ) { @ Override public boolean hasNext ( ) { return iterator . hasNext ( ) ; } @ Override public Entry < K , V > next ( ) { final Entry < String , byte [ ] > next = iterator . next ( ) ; return new Entry <> ( toKeyObject ( next . key ( ) ) , toValueObject ( next . value ( ) ) ) ; } @ Override public void remove ( ) { iterator . remove ( ) ; } } ; } } ; }


Input: Put a value in the key / value store . [CODESPLIT] public void put ( K key , V value ) { store . put ( toKeyString ( key ) , toValueBytes ( value ) ) ; }


Input: Remove all of these values from the key value store . [CODESPLIT] public void removeAll ( Iterable < K > keys ) { List < String > list = new ArrayList <> ( ) ; for ( K key : keys ) { list . add ( toKeyString ( key ) ) ; } store . removeAll ( list ) ; }


Input: Called from worker thread . [CODESPLIT] private void processReadQueue ( ) throws InterruptedException { ReadStatus readStatus = new ReadStatus ( ) ; while ( true ) { DataStoreRequest request = readOperationsQueue . poll ( dataStoreConfig . pollTimeoutMS ( ) , TimeUnit . MILLISECONDS ) ; while ( request != null ) { readStatus . tracker . addCall ( request , outputDataQueue ) ; readOperationsBatch . add ( request ) ; if ( readOperationsBatch . size ( ) > dataStoreConfig . processQueueMaxBatchSize ( ) ) { break ; } request = readOperationsQueue . poll ( ) ; } if ( readOperationsBatch . size ( ) > 0 ) { try { recievedReadBatch ( new ArrayList <> ( readOperationsBatch ) ) ; } finally { readOperationsBatch . clear ( ) ; } } else { flushReadsIfNeeded ( ) ; } if ( readStatus . readBatchSize . size ( ) > 1_000 ) { StatCount count ; final long now = Timer . timer ( ) . time ( ) ; count = new StatCount ( now , DataStoreSource . SERVER , Action . GET_STATS , "Thread TIME USER  BaseDataStore " + Thread . currentThread ( ) . getName ( ) , Sys . threadUserTime ( ) ) ; this . outputDataQueue . put ( count ) ; count = new StatCount ( now , DataStoreSource . SERVER , Action . GET_STATS , "Thread TIME CPU  BaseDataStore " + Thread . currentThread ( ) . getName ( ) , Sys . threadCPUTime ( ) ) ; this . outputDataQueue . put ( count ) ; count = new StatCount ( now , source , Action . GET , "BaseDataStore readStatus.readBatchSize.max" , readStatus . readBatchSize . max ( ) ) ; outputDataQueue . put ( count ) ; count = new StatCount ( now , source , Action . GET , "BaseDataStore readStatus.readBatchSize.min" , readStatus . readBatchSize . min ( ) ) ; outputDataQueue . put ( count ) ; count = new StatCount ( now , source , Action . GET , "BaseDataStore readStatus.readBatchSize.median" , readStatus . readBatchSize . median ( ) ) ; outputDataQueue . put ( count ) ; count = new StatCount ( now , source , Action . GET , "BaseDataStore readStatus.readBatchSize.mean" , readStatus . readBatchSize . mean ( ) ) ; outputDataQueue . put ( count ) ; count = new StatCount ( now , source , Action . GET , "BaseDataStore readStatus.readBatchSize.standardDeviation" , readStatus . readBatchSize . standardDeviation ( ) ) ; outputDataQueue . put ( count ) ; count = new StatCount ( now , source , Action . GET , "BaseDataStore readStatus.readBatchSize.variance" , readStatus . readBatchSize . variance ( ) ) ; outputDataQueue . put ( count ) ; readStatus . readBatchSize . clear ( ) ; } } }


Input: Called from worker thread . Processes the incoming queue for read and writes . [CODESPLIT] private void processWriteQueue ( ) throws InterruptedException { WriteStatus status = new WriteStatus ( ) ; while ( true ) { DataStoreRequest operation = writeOperationsQueue . poll ( dataStoreConfig . pollTimeoutMS ( ) , TimeUnit . MILLISECONDS ) ; while ( operation != null ) { status . tracker . addCall ( operation , outputDataQueue ) ; writeOperationsBatch . add ( operation ) ; if ( writeOperationsBatch . size ( ) > dataStoreConfig . processQueueMaxBatchSize ( ) ) { break ; } operation = writeOperationsQueue . poll ( ) ; } if ( writeOperationsBatch . size ( ) > 0 ) { try { status . writeBatchSize . add ( writeOperationsBatch . size ( ) ) ; recievedWriteBatch ( new ArrayList <> ( writeOperationsBatch ) ) ; } finally { writeOperationsBatch . clear ( ) ; } } else { flushWritesIfNeeded ( ) ; } if ( status . writeBatchSize . size ( ) > 1000 ) { status . sendBatchSize ( source , outputDataQueue ) ; } } }


Input: Start up the queue handlers . [CODESPLIT] public void start ( ) { scheduledExecutorService = Executors . newScheduledThreadPool ( 2 , new ThreadFactory ( ) { @ Override public Thread newThread ( Runnable runnable ) { Thread thread = new Thread ( runnable ) ; thread . setName ( " DataQueue Process " + source ) ; return thread ; } } ) ; future = scheduledExecutorService . scheduleAtFixedRate ( new Runnable ( ) { @ Override public void run ( ) { if ( stop . get ( ) ) { return ; } try { processWriteQueue ( ) ; } catch ( InterruptedException ex ) { //let it restart or stop } catch ( Exception ex ) { logger . fatal ( ex ) ; } } } , 0 , dataStoreConfig . threadErrorResumeTimeMS ( ) , TimeUnit . MILLISECONDS ) ; future = scheduledExecutorService . scheduleAtFixedRate ( new Runnable ( ) { @ Override public void run ( ) { if ( stop . get ( ) ) { return ; } try { processReadQueue ( ) ; } catch ( InterruptedException ex ) { //let it restart or stop } catch ( Exception ex ) { logger . fatal ( ex , "Problem with base data store running scheduled job" ) ; } } } , 0 , dataStoreConfig . threadErrorResumeTimeMS ( ) , TimeUnit . MILLISECONDS ) ; }


Input: Puts character at index [CODESPLIT] @ Universal public static String atIndex ( String str , int index , char c ) { return idx ( str , index , c ) ; }


Input: Gets slice of a string . [CODESPLIT] @ Universal public static String slc ( String str , int start ) { return FastStringUtils . noCopyStringFromChars ( Chr . slc ( FastStringUtils . toCharArray ( str ) , start ) ) ; }


Input: See if chars is in another string [CODESPLIT] @ Universal public static boolean in ( char [ ] chars , String str ) { return Chr . in ( chars , FastStringUtils . toCharArray ( str ) ) ; }


Input: Add a char to a string [CODESPLIT] @ Universal public static String add ( String str , char c ) { return FastStringUtils . noCopyStringFromChars ( Chr . add ( FastStringUtils . toCharArray ( str ) , c ) ) ; }


Input: Add many objects converted to strings together . Null are ignored so be careful . [CODESPLIT] public static String addObjects ( Object ... objects ) { int length = 0 ; for ( Object obj : objects ) { if ( obj == null ) { continue ; } length += obj . toString ( ) . length ( ) ; } CharBuf builder = CharBuf . createExact ( length ) ; for ( Object str : objects ) { if ( str == null ) { continue ; } builder . add ( str . toString ( ) ) ; } return builder . toString ( ) ; }


Input: Gets rid of null characters lurking in the string [CODESPLIT] public static String compact ( String str ) { return FastStringUtils . noCopyStringFromChars ( Chr . compact ( FastStringUtils . toCharArray ( str ) ) ) ; }


Input: Split a string [CODESPLIT] public static String [ ] split ( String str ) { char [ ] [ ] split = Chr . split ( FastStringUtils . toCharArray ( str ) ) ; return fromCharArrayOfArrayToStringArray ( split ) ; }


Input: Split a string by space [CODESPLIT] public static String [ ] splitBySpace ( String str ) { char [ ] [ ] split = CharScanner . splitBySpace ( FastStringUtils . toCharArray ( str ) ) ; return fromCharArrayOfArrayToStringArray ( split ) ; }


Input: Split a string by pipe [CODESPLIT] public static String [ ] splitByPipe ( String str ) { char [ ] [ ] split = CharScanner . splitByPipe ( FastStringUtils . toCharArray ( str ) ) ; return fromCharArrayOfArrayToStringArray ( split ) ; }


Input: Convert arrays of chars to arrays of strings [CODESPLIT] public static String [ ] fromCharArrayOfArrayToStringArray ( char [ ] [ ] split ) { String [ ] results = new String [ split . length ] ; char [ ] array ; for ( int index = 0 ; index < split . length ; index ++ ) { array = split [ index ] ; results [ index ] = array . length == 0 ? EMPTY_STRING : FastStringUtils . noCopyStringFromChars ( array ) ; } return results ; }


Input: Convert to camel case and pass upper or lower [CODESPLIT] public static String camelCase ( String inStr , boolean upper ) { char [ ] in = FastStringUtils . toCharArray ( inStr ) ; char [ ] out = Chr . camelCase ( in , upper ) ; return FastStringUtils . noCopyStringFromChars ( out ) ; }


Input: Checks to see if a string is inside of another [CODESPLIT] public static boolean insideOf ( String start , String inStr , String end ) { return Chr . insideOf ( FastStringUtils . toCharArray ( start ) , FastStringUtils . toCharArray ( inStr ) , FastStringUtils . toCharArray ( end ) ) ; }


Input: Convert to under bar case [CODESPLIT] public static String underBarCase ( String inStr ) { char [ ] in = FastStringUtils . toCharArray ( inStr ) ; char [ ] out = Chr . underBarCase ( in ) ; return FastStringUtils . noCopyStringFromChars ( out ) ; }


Input: See if they are equal or die [CODESPLIT] public static void equalsOrDie ( CharSequence a , CharSequence b ) { char [ ] ac = FastStringUtils . toCharArray ( a ) ; char [ ] bc = FastStringUtils . toCharArray ( b ) ; Chr . equalsOrDie ( ac , bc ) ; }


Input: See if they are equal or die [CODESPLIT] public static void equalsOrDie ( String a , String b ) { if ( a == null && b == null ) { return ; } if ( a == null || b == null ) { die ( "Values not equal value a=" , a , "value b=" , b ) ; } char [ ] ac = FastStringUtils . toCharArray ( a ) ; char [ ] bc = FastStringUtils . toCharArray ( b ) ; Chr . equalsOrDie ( ac , bc ) ; }


Input: Do a nice pretty print of a number . Add commas and such . [CODESPLIT] public static String num ( Number count ) { if ( count == null ) { return "" ; } if ( count instanceof Double || count instanceof BigDecimal ) { String s = count . toString ( ) ; if ( idx ( s , 1 ) == ' ' && s . length ( ) > 7 ) { s = slc ( s , 0 , 5 ) ; return s ; } else { return s ; } } else if ( count instanceof Integer || count instanceof Long || count instanceof Short || count instanceof BigInteger ) { String s = count . toString ( ) ; s = new StringBuilder ( s ) . reverse ( ) . toString ( ) ; CharBuf buf = CharBuf . create ( s . length ( ) ) ; int index = 0 ; for ( char c : s . toCharArray ( ) ) { index ++ ; buf . add ( c ) ; if ( index % 3 == 0 ) { buf . add ( ' ' ) ; } } if ( buf . lastChar ( ) == ' ' ) { buf . removeLastChar ( ) ; } s = buf . toString ( ) ; s = new StringBuilder ( s ) . reverse ( ) . toString ( ) ; return s ; } return count . toString ( ) ; }


Input: Helper method to create a Sort that is a composite of other sorts . [CODESPLIT] public static Sort sorts ( Sort ... sorts ) { if ( sorts == null || sorts . length == 0 ) { return null ; } Sort main = sorts [ 0 ] ; for ( int index = 1 ; index < sorts . length ; index ++ ) { main . then ( sorts [ index ] ) ; } return main ; }


Input: Sort if you already know the reflection fields . [CODESPLIT] public void sort ( List list , Map < String , FieldAccess > fields ) { Collections . sort ( list , this . comparator ( fields ) ) ; }


Input: Sort and you look up the reflection fields . [CODESPLIT] public void sort ( List list ) { if ( list == null || list . size ( ) == 0 ) { return ; } Object item = list . iterator ( ) . next ( ) ; Map < String , FieldAccess > fields = BeanUtils . getFieldsFromObject ( item ) ; Collections . sort ( list , this . comparator ( fields ) ) ; }


Input: Sort and you look up the reflection fields . [CODESPLIT] public < T > Collection < T > sort ( Class < T > componentClass , Collection < T > collection ) { if ( collection instanceof List ) { sort ( ( List ) collection ) ; return collection ; } if ( collection == null || collection . size ( ) == 0 ) { return Collections . EMPTY_LIST ; } Map < String , FieldAccess > fields = BeanUtils . getFieldsFromObject ( componentClass ) ; T [ ] array = toArray ( componentClass , collection ) ; Arrays . sort ( array , this . comparator ( fields ) ) ; if ( collection instanceof Set ) { return new LinkedHashSet <> ( Lists . list ( array ) ) ; } else { return Lists . list ( array ) ; } }


Input: Sort and you look up the reflection fields . [CODESPLIT] public < T > Iterable < T > sort ( Class < T > componentClass , Iterable < T > iterable ) { if ( iterable instanceof List ) { sort ( ( List ) iterable ) ; return iterable ; } if ( iterable instanceof Collection ) { return sort ( componentClass , ( Collection ) iterable ) ; } if ( iterable == null ) { return Collections . EMPTY_LIST ; } List < T > list = Lists . list ( iterable ) ; sort ( list ) ; return list ; }


Input: Sort and you look up the reflection fields . [CODESPLIT] public < T > void sort ( T [ ] array ) { if ( array == null || array . length == 0 ) { return ; } Object item = array [ 0 ] ; Map < String , FieldAccess > fields = BeanUtils . getFieldsFromObject ( item ) ; Arrays . sort ( array , this . comparator ( fields ) ) ; }


Input: This is what really does the magic . This is the comparator creator . [CODESPLIT] public Comparator comparator ( Map < String , FieldAccess > fields ) { if ( comparator == null ) { comparator = universalComparator ( this . getName ( ) , fields , this . getType ( ) , this . childComparators ( fields ) ) ; } return comparator ; }


Input: This creates a list of children comparators based on the child list . [CODESPLIT] private List < Comparator > childComparators ( Map < String , FieldAccess > fields ) { if ( this . comparators == null ) { this . comparators = new ArrayList <> ( this . sorts . size ( ) + 1 ) ; for ( Sort sort : sorts ) { Comparator comparator = universalComparator ( sort . getName ( ) , fields , sort . getType ( ) , sort . childComparators ( fields ) ) ; this . comparators . add ( comparator ) ; } } return this . comparators ; }


Input: Grabs the last value from a tree map ( Navigable map ) . [CODESPLIT] @ Universal public static < K , V > V last ( NavigableMap < K , V > map ) { return map . lastEntry ( ) . getValue ( ) ; }


Input: Grabs the value after this key from a tree map ( Navigable map ) . [CODESPLIT] @ Universal public static < K , V > V after ( NavigableMap < K , V > map , final K index ) { return map . get ( map . higherKey ( index ) ) ; }


Input: Grabs the value before this key from a tree map ( Navigable map ) . [CODESPLIT] @ Universal public static < K , V > V before ( NavigableMap < K , V > map , final K index ) { return map . get ( map . lowerKey ( index ) ) ; }


Input: End universal methods . [CODESPLIT] public static < K , V > boolean valueIn ( V value , Map < K , V > map ) { return map . containsValue ( value ) ; }


Input: Checks to see if two values are the same [CODESPLIT] public static boolean equalsOrDie ( int expected , int got ) { if ( expected != got ) { return die ( Boolean . class , "Expected was" , expected , "but we got " , got ) ; } return true ; }


Input: Checks to see if two arrays are equals [CODESPLIT] public static boolean equalsOrDie ( int [ ] expected , int [ ] got ) { if ( expected . length != got . length ) { die ( "Lengths did not match, expected length" , expected . length , "but got" , got . length ) ; } for ( int index = 0 ; index < expected . length ; index ++ ) { if ( expected [ index ] != got [ index ] ) { die ( "value at index did not match index" , index , "expected value" , expected [ index ] , "but got" , got [ index ] ) ; } } return true ; }


Input: Sum Provides overflow protection . [CODESPLIT] public static int sum ( int [ ] values , int start , int length ) { long sum = 0 ; for ( int index = start ; index < length ; index ++ ) { sum += values [ index ] ; } if ( sum < Integer . MIN_VALUE ) { die ( "overflow the sum is too small" , sum ) ; } if ( sum > Integer . MAX_VALUE ) { die ( "overflow the sum is too big" , sum ) ; } return ( int ) sum ; }


Input: Max [CODESPLIT] public static int max ( int [ ] values , final int start , final int length ) { int max = Integer . MIN_VALUE ; for ( int index = start ; index < length ; index ++ ) { if ( values [ index ] > max ) { max = values [ index ] ; } } return max ; }


Input: Min [CODESPLIT] public static int min ( int [ ] values , final int start , final int length ) { int min = Integer . MAX_VALUE ; for ( int index = start ; index < length ; index ++ ) { if ( values [ index ] < min ) min = values [ index ] ; } return min ; }


Input: Calculate standard deviation . [CODESPLIT] public static double standardDeviation ( Collection < ? > inputList , String propertyPath ) { double variance = variance ( inputList , propertyPath ) ; return Math . round ( Math . sqrt ( variance ) ) ; }


Input: Calculate standard deviation . [CODESPLIT] public static int median ( Collection < ? > inputList , String propertyPath ) { return IntList . toIntList ( inputList , propertyPath ) . median ( ) ; }


Input: Round up to the nearest power of 2 [CODESPLIT] public static int roundUpToPowerOf2 ( int number ) { int rounded = number >= 1_000 ? 1_000 : ( rounded = Integer . highestOneBit ( number ) ) != 0 ? ( Integer . bitCount ( number ) > 1 ) ? rounded << 1 : rounded : 1 ; return rounded ; }


Input:
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 . [CODESPLIT] private String doGetMessageFromBundle ( String key ) { 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 ; }


Input: This is the work horse . It does all of the sorting work for the simple cases . Nulls are last by default . [CODESPLIT] public static void sort ( List list , String sortBy , Map < String , FieldAccess > fields , boolean ascending ) { sort ( list , sortBy , fields , ascending , false ) ; }


Input:
This is the work horse . It does all of the sorting work for the simple cases . [CODESPLIT] public static void sort ( List list , String sortBy , Map < String , FieldAccess > fields , boolean ascending , boolean nullsFirst ) { 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 ) ; } }


Input: Main exit from system . <p / > <p / > If you are debugging something not coming out of the system . Start here . [CODESPLIT] private void handleResponseFromDataStore ( Result result ) { 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 ( ) ) ; } }


Input:
fromMap converts a map into a java object [CODESPLIT] @ Override public < T > T fromMap ( final Map < String , Object > map , final Class < T > cls ) { 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 ; }


Input:
Inject a map into an object s field . [CODESPLIT] private void setFieldValueFromMap ( final Object parentObject , final FieldAccess field , final Map mapInner ) { 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 ) ; }


Input: Convert an object to a list . [CODESPLIT] @ Override public List < ? > toList ( Object object ) { 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 ) ; }


Input: Compiles a match . [CODESPLIT] private Pattern compileRegex ( String match ) { Pattern pattern = compiledRegexCache . get ( match ) ; if ( pattern == null ) { pattern = Pattern . compile ( match ) ; compiledRegexCache . put ( match , pattern ) ; } return pattern ; }


Input: / * [CODESPLIT] @ Override public KeyValueIterable < String , VersionedEntry < String , byte [ ] > > loadAll ( ) { 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 ; } }


Input: Create load all keys SQL . [CODESPLIT] protected void createLoadAllVersionDataSQL ( String table ) { 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 ( ) ; }


Input: Clones each list item into a new instance with copied fields . It is like doing a clone operation . [CODESPLIT] @ Universal public static < V > List < V > deepCopy ( List < V > list ) { 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 ) ; } }


Input:
/ * End universal methods . [CODESPLIT] private static < T > int calculateIndex ( List < T > list , int originalIndex ) { 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 ; }


Input: Checks to see if we have a string field . [CODESPLIT] public static boolean hasStringField ( final Object value1 , final String name ) { Class < ? > clz = value1 . getClass ( ) ; return classHasStringField ( clz , name ) ; }


Input: Checks to see if this class has a string field . [CODESPLIT] public static boolean classHasStringField ( Class < ? > clz , String name ) { 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 ; }


Input: Checks to see if a class has a field . [CODESPLIT] public static boolean classHasField ( Class < ? > clz , String name ) { 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 ; }


Input: This can be used for default sort . [CODESPLIT] public static String getFirstComparableOrPrimitiveFromClass ( Class < ? > clz ) { 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 ; }


Input: getFirstStringFieldNameEndsWith [CODESPLIT] public static String getFirstStringFieldNameEndsWith ( Object value , String name ) { return getFirstStringFieldNameEndsWithFromClass ( value . getClass ( ) , name ) ; }


Input: getFirstStringFieldNameEndsWithFromClass [CODESPLIT] public static String getFirstStringFieldNameEndsWithFromClass ( Class < ? > clz , String name ) { 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 ; }


Input: Gets the first sortable fields found . [CODESPLIT] public static String getSortableField ( Object value1 ) { if ( value1 instanceof Map ) { return getSortableFieldFromMap ( ( Map < String , ? > ) value1 ) ; } else { return getSortableFieldFromClass ( value1 . getClass ( ) ) ; } }


Input: Comparison of entries this determines what we will order the cache by which determines which type of cache it is . [CODESPLIT] @ Override public final int compareTo ( CacheEntry other ) { switch ( type ) { case LFU : return compareToLFU ( other ) ; case LRU : return compareToLRU ( other ) ; case FIFO : return compareToFIFO ( other ) ; default : die ( ) ; return 0 ; } }


Input: Compare the time . [CODESPLIT] private final int compareTime ( CacheEntry other ) { 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 ; }


Input: Takes a list an an array or sorts [CODESPLIT] public static void sort ( List list , Sort ... sorts ) { Sort . sorts ( sorts ) . sort ( list ) ; }


Input: Sort a list . [CODESPLIT] public static void sort ( List list , String sortBy , boolean ascending , boolean nullsFirst ) { 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 ) ) ; } } }


Input: Sort collection . [CODESPLIT] public static < V > Collection < V > sort ( Class < V > componentType , Collection < V > collection , String sortBy , boolean ascending , boolean nullsFirst ) { 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 ) ; } } }


Input: Sort map entries . [CODESPLIT] public static < K , V > Collection < Map . Entry < K , V > > sortEntries ( Class < V > componentType , Map < K , V > map , String sortBy , boolean ascending , boolean nullsFirst ) { return sort ( ( Class ) componentType , ( Collection ) map . entrySet ( ) , sortBy , ascending , nullsFirst ) ; }


Input: Sort map values . [CODESPLIT] public static < K , V > Collection < Map . Entry < K , V > > sortValues ( Class < V > componentType , Map < K , V > map , String sortBy , boolean ascending , boolean nullsFirst ) { return sort ( ( Class ) componentType , ( Collection ) map . values ( ) , sortBy , ascending , nullsFirst ) ; }


Input: Sort map keys . [CODESPLIT] public static < K , V > Collection < Map . Entry < K , V > > sortKeys ( Class < V > componentType , Map < K , V > map , String sortBy , boolean ascending , boolean nullsFirst ) { return sort ( ( Class ) componentType , ( Collection ) map . keySet ( ) , sortBy , ascending , nullsFirst ) ; }


Input: Sort collection . [CODESPLIT] public static < V > Iterable < V > sort ( Class < V > componentType , Iterable < V > iterable , String sortBy , boolean ascending , boolean nullsFirst ) { 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 ; } }


Input: Sort an array . [CODESPLIT] public static < T > void sort ( T [ ] array , String sortBy , boolean ascending , boolean nullsFirst ) { 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 ) ) ; } } }


Input: This creates the universal comparator object which is used by the sort work horse . [CODESPLIT] public static Comparator universalComparator ( final FieldAccess field , final boolean ascending , final boolean nullsFirst ) { 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 ) ; } } ; }


Input: This creates the universal comparator object used for this . [CODESPLIT] public static Comparator thisUniversalComparator ( final boolean ascending , final boolean nullsFirst ) { 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 ) ; } } ; }


Input:
This compares two values . If the objects are strings ( CharSequence ) they are always compared lexicographically . If the objects are comparable they are always compared using a natural order . [CODESPLIT] public static int compare ( Object value1 , Object value2 , boolean nullsLast ) { if ( value1 == null && value2 == null ) { return 0 ; } else if ( value1 == null && value2 != null ) { return nullsLast ? - 1 : 1 ; } else if ( value1 != null && value2 == null ) { return nullsLast ? 1 : - 1 ; } /** Objects are string like so compare using collator. */ if ( value1 instanceof CharSequence ) { String str1 = Conversions . toString ( value1 ) ; String str2 = Conversions . toString ( value2 ) ; Collator collator = Collator . getInstance ( ) ; return collator . compare ( str1 , str2 ) ; /** Objects are comparable, yeah! */ } else if ( Typ . isComparable ( value1 ) && value1 . getClass ( ) == value2 . getClass ( ) ) { Comparable c1 = Conversions . comparable ( value1 ) ; Comparable c2 = Conversions . comparable ( value2 ) ; return c1 . compareTo ( c2 ) ; } else if ( value1 instanceof Integer && value2 instanceof Integer ) { Comparable c1 = Conversions . comparable ( value1 ) ; Comparable c2 = Conversions . comparable ( value2 ) ; return c1 . compareTo ( c2 ) ; } else if ( value1 instanceof Double && value2 instanceof Double ) { Comparable c1 = Conversions . comparable ( value1 ) ; Comparable c2 = Conversions . comparable ( value2 ) ; return c1 . compareTo ( c2 ) ; } else if ( value1 instanceof Long && value2 instanceof Long ) { Comparable c1 = Conversions . comparable ( value1 ) ; Comparable c2 = Conversions . comparable ( value2 ) ; return c1 . compareTo ( c2 ) ; } else if ( value1 instanceof Number && value2 instanceof Number ) { Double c1 = Conversions . toDouble ( value1 ) ; Double c2 = Conversions . toDouble ( value2 ) ; return c1 . compareTo ( c2 ) ; } else { /** Object are neither String like or comparable.
             * Ours it not to reason why, ours it to do or die.
             * Find the first sortable field and sort by that.
             * */ String name = Fields . getSortableField ( value1 ) ; String sv1 = ( String ) BeanUtils . getPropByPath ( value1 , name ) ; String sv2 = ( String ) BeanUtils . getPropByPath ( value2 , name ) ; return Sorting . compare ( sv1 , sv2 ) ; } }


Input: 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 . [CODESPLIT] public VALUE get ( KEY key ) { CacheEntry < KEY , VALUE > cacheEntry = map . get ( key ) ; if ( cacheEntry != null ) { cacheEntry . readCount . incrementAndGet ( ) ; return cacheEntry . value ; } else { return null ; } }


Input: Used for testing as it gets the value without updating stats [CODESPLIT] public VALUE getSilent ( KEY key ) { CacheEntry < KEY , VALUE > cacheEntry = map . get ( key ) ; if ( cacheEntry != null ) { return cacheEntry . value ; } else { return null ; } }