Input: Remove the key . This touches the lock . So removes are ** not ** fast . [CODESPLIT] @ Override public void remove ( KEY key ) { CacheEntry < KEY , VALUE > entry = map . remove ( key ) ; if ( entry != null ) { list . remove ( entry ) ; } }


Input: Put the value . This touches the lock so puts are ** not ** fast . [CODESPLIT] public void put ( KEY key , VALUE value ) { CacheEntry < KEY , VALUE > entry = map . get ( key ) ; if ( entry == null ) { entry = new CacheEntry <> ( key , value , order ( ) , type , time ( ) ) ; list . add ( entry ) ; map . put ( key , entry ) ; } else { entry . readCount . incrementAndGet ( ) ; entry . value = value ; } evictIfNeeded ( ) ; }


Input: Avoid overflow . [CODESPLIT] private final int order ( ) { int order = count . incrementAndGet ( ) ; if ( order > Integer . MAX_VALUE - 100 ) { count . set ( 0 ) ; } return order ; }


Input: Evict if we are over the size limit . [CODESPLIT] private final void evictIfNeeded ( ) { if ( list . size ( ) > evictSize ) { final List < CacheEntry < KEY , VALUE > > killList = list . sortAndReturnPurgeList ( 0.1f ) ; for ( CacheEntry < KEY , VALUE > cacheEntry : killList ) { map . remove ( cacheEntry . key ) ; } } }


Input: Perform the actual validation . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public ValidatorMessageHolder validate ( Object fieldValue , String fieldLabel ) { ValidatorMessage validatorMessage = new ValidatorMessage ( ) ; if ( fieldValue == null ) { return validatorMessage ; } dynamicallyInitIfNeeded ( fieldValue ) ; if ( ! super . isValueGreaterThanMin ( ( Comparable ) fieldValue ) ) { populateMessage ( underMin , validatorMessage , fieldLabel , min ) ; } else if ( ! super . isValueLessThanMax ( ( Comparable ) fieldValue ) ) { populateMessage ( overMax , validatorMessage , fieldLabel , max ) ; } return validatorMessage ; }


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


Input:
If the type was not initialized we can still figure it out at runtime . [CODESPLIT] private void dynamicallyInitIfNeeded ( Object value ) { /* Check to see if this class was already initialized,
         * if not, initialize it based on the type of the value.
		 */ if ( ! isInitialized ( ) ) { if ( value instanceof Integer ) { init ( new Integer ( min . intValue ( ) ) , new Integer ( max . intValue ( ) ) ) ; } else if ( value instanceof Byte ) { init ( new Byte ( min . byteValue ( ) ) , new Byte ( max . byteValue ( ) ) ) ; } else if ( value instanceof Short ) { init ( new Short ( min . shortValue ( ) ) , new Short ( max . shortValue ( ) ) ) ; } else { init ( min , max ) ; } } }


Input: } [CODESPLIT] public static < V > V [ ] array ( Class < V > type , final Collection < V > array ) { return Conversions . toArray ( type , array ) ; }


Input: This flattens a list . [CODESPLIT] public static Object unifyListOrArray ( Object o , List list ) { if ( o == null ) { return null ; } boolean isArray = o . getClass ( ) . isArray ( ) ; if ( list == null && ! isArray && ! ( o instanceof Iterable ) ) { return o ; } if ( list == null ) { list = new LinkedList ( ) ; } if ( isArray ) { int length = Array . getLength ( o ) ; for ( int index = 0 ; index < length ; index ++ ) { Object o1 = Array . get ( o , index ) ; if ( o1 instanceof Iterable || o . getClass ( ) . isArray ( ) ) { unifyListOrArray ( o1 , list ) ; } else { list . add ( o1 ) ; } } } else if ( o instanceof Collection ) { Collection i = ( ( Collection ) o ) ; for ( Object item : i ) { if ( item instanceof Iterable || o . getClass ( ) . isArray ( ) ) { unifyListOrArray ( item , list ) ; } else { list . add ( item ) ; } } } else { list . add ( o ) ; } return list ; }


Input: This flattens a list . [CODESPLIT] public static Object unifyList ( Object o , List list ) { if ( o == null ) { return null ; } if ( list == null ) { list = new ArrayList ( ) ; } if ( o instanceof Iterable ) { Iterable i = ( ( Iterable ) o ) ; for ( Object item : i ) { unifyListOrArray ( item , list ) ; } } else { list . add ( o ) ; } return list ; }


Input: This gets called from the http post handler or event bus handler . [CODESPLIT] public final ByteBuffer allocateBuffer ( int size ) { if ( RECYCLE_BUFFER ) { ByteBuffer spentBuffer = recycleChannel . poll ( ) ; if ( spentBuffer == null ) { spentBuffer = ByteBuffer . allocateDirect ( size ) ; } spentBuffer . clear ( ) ; return spentBuffer ; } else { return ByteBuffer . allocateDirect ( size ) ; } }


Input: See if it is time to stop We have been interrupted . Should we ignore it or break out of the loop . [CODESPLIT] private boolean determineIfWeShouldExit ( ) { boolean shouldStop = stop . get ( ) ; if ( ! shouldStop ) { Thread . interrupted ( ) ; } else { System . out . println ( "Exiting processing loop as requested" ) ; return true ; } return false ; }


Input: Queue and batch writer main logic . This is where the magic happens . [CODESPLIT] private void manageInputWriterChannel ( ) throws InterruptedException { try { ByteBuffer dataToWriteToFile ; dataToWriteToFile = inputChannel . poll ( ) ; //no wait //If it is null, it means the inputChannel is empty and we need to flush. if ( dataToWriteToFile == null ) { queueEmptyMaybeFlush ( ) ; dataToWriteToFile = inputChannel . poll ( ) ; } //If it is still null, this means that we need to wait //for more items to show up in the inputChannel. if ( dataToWriteToFile == null ) { dataToWriteToFile = waitForNextDataToWrite ( ) ; } //We have to check for null again because we could have been interrupted. if ( dataToWriteToFile != null ) { //Write it writer . nextBufferToWrite ( dataToWriteToFile ) ; //Then give it back if ( RECYCLE_BUFFER ) { recycleChannel . offer ( dataToWriteToFile ) ; } } } catch ( InterruptedException ex ) { throw ex ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; ex . printStackTrace ( System . err ) ; } }


Input:
If we detect that the in - coming transfer outputDataQueue channel is empty then it could be an excellent time to sync to disk . [CODESPLIT] private void queueEmptyMaybeFlush ( ) { if ( PERIODIC_FORCE_FLUSH ) { long currentTime = time . get ( ) ; /* Try not to flush more than once every x times per mili-seconds time period. */ if ( ( currentTime - lastFlushTime ) > FORCE_FLUSH_AFTER_THIS_MANY_MILI_SECONDS ) { /* If the writer had things to flush, and we flushed then
                increment the number of flushes.
                 */ if ( writer . syncToDisk ( ) ) { //could take 100 ms to 1 second this . numberOfFlushesTotal . incrementAndGet ( ) ; } /* We update the flush time no matter what. */ lastFlushTime = time . get ( ) ; } } }


Input: If we don t have any data and we have flushed then we can wait on the outputDataQueue . There is no sense spin - locking . The poll ( time timeunit ) call will block until there is something to do or until the timeout . [CODESPLIT] private ByteBuffer waitForNextDataToWrite ( ) throws InterruptedException { ByteBuffer dataToWriteToFile ; dataToWriteToFile = inputChannel . poll ( FORCE_FLUSH_AFTER_THIS_MANY_MILI_SECONDS , TimeUnit . MILLISECONDS ) ; return dataToWriteToFile ; }


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


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


Input: Gets the item by key from the mapping . [CODESPLIT] @ Override public final Object get ( Object key ) { Object object = null ; /* if the map is null, then we create it. */ if ( map == null ) { buildMap ( ) ; } object = map . get ( key ) ; lazyChopIfNeeded ( object ) ; return object ; }


Input: Perform the actual validation . [CODESPLIT] public ValidatorMessageHolder validate ( Object fieldValue , String fieldLabel ) { ValidatorMessage validatorMessage = new ValidatorMessage ( ) ; if ( fieldValue == null ) { return validatorMessage ; } int len = Boon . len ( fieldValue ) ; if ( ! ( len >= min && len <= max ) ) { populateMessage ( validatorMessage , fieldLabel , min , max ) ; } return validatorMessage ; }


Input:
This is the main criteria plan in case the name was not obvious . [CODESPLIT] private ResultSet mainQueryPlan ( Criteria [ ] expressions ) { ResultSetInternal results = new ResultSetImpl ( this . fields ) ; if ( expressions == null || expressions . length == 0 ) { results . addResults ( searchableCollection . all ( ) ) ; } /* I am sure this looked easy to read when I wrote it.
         * If there is only one expression and first expression is a group then
         * the group is that first expression otherwise wrap
         * all of the expressions in an and clause. */ Group group = expressions . length == 1 && expressions [ 0 ] instanceof Group ? ( Group ) expressions [ 0 ] : ObjectFilter . and ( expressions ) ; /**
         * Run the filter on the group.
         */ doFilterGroup ( group , results ) ; return results ; }


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


Input: } [CODESPLIT] private void applyGroups ( Set < Criteria > expressionSet , ResultSetInternal resultSet ) { if ( expressionSet . size ( ) == 0 ) { return ; } for ( Criteria expression : expressionSet ) { if ( expression instanceof Group ) { doFilterGroup ( ( Group ) expression , resultSet ) ; } } }


Input: / * Creation [CODESPLIT] public static < V > Set < V > set ( Collection < V > collection ) { if ( collection instanceof Set ) { return ( Set < V > ) collection ; } if ( collection == null ) { return Collections . EMPTY_SET ; } return new LinkedHashSet <> ( collection ) ; }


Input: end universal [CODESPLIT] public static List < Map < String , Object > > toListOfMaps ( Set < ? > set ) { return MapObjectConversion . toListOfMaps ( set ) ; }


Input: Recieves a tick from our clock . [CODESPLIT] public void tick ( long time ) { this . time . set ( time ) ; long startTime = fileStartTime . get ( ) ; long duration = time - startTime ; if ( duration > FILE_TIMEOUT_MILISECONDS ) { fileTimeOut . set ( true ) ; } }


Input: flush to disk . [CODESPLIT] public boolean syncToDisk ( ) { /** if we have a stream and we are dirty then flush. */ if ( outputStream != null && dirty ) { try { //outputStream.flush (); if ( outputStream instanceof FileChannel ) { FileChannel channel = ( FileChannel ) outputStream ; channel . force ( true ) ; } dirty = false ; return true ; } catch ( Exception ex ) { cleanupOutputStream ( ) ; return false ; } } else { return false ; } }


Input: Attempts to close down log stream . [CODESPLIT] private void cleanupOutputStream ( ) { if ( outputStream != null ) { try { outputStream . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( System . err ) ; } finally { outputStream = null ; } } }


Input: Writes a buffer of data to the log system . [CODESPLIT] public void nextBufferToWrite ( final ByteBuffer bufferOut ) throws InterruptedException { dirty = true ; final int size = bufferOut . limit ( ) ; write ( bufferOut ) ; /* only increment bytes transferred after a successful write. */ if ( ! error . get ( ) ) { totalBytesTransferred += size ; bytesTransferred += size ; bytesSinceLastFlush += size ; buffersSent ++ ; } if ( this . bytesTransferred >= FILE_SIZE_BYTES || fileTimeOut . get ( ) ) { try { outputStream . close ( ) ; } catch ( IOException e ) { cleanupOutputStream ( ) ; e . printStackTrace ( System . err ) ; } finally { outputStream = null ; } } }


Input: Write the actual data to disk . [CODESPLIT] private void write ( final ByteBuffer bufferOut ) throws InterruptedException { initOutputStream ( ) ; try { if ( outputStream != null ) { outputStream . write ( bufferOut ) ; } else { error . set ( true ) ; } if ( bytesSinceLastFlush > FLUSH_EVERY_N_BYTES ) { syncToDisk ( ) ; bytesSinceLastFlush = 0 ; } } catch ( ClosedByInterruptException cbie ) { throw new InterruptedException ( "File closed by interruption" ) ; } catch ( Exception e ) { cleanupOutputStream ( ) ; error . set ( true ) ; e . printStackTrace ( System . err ) ; diagnose ( ) ; Exceptions . handle ( e ) ; } }


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


Input: Get a value from the key value store . [CODESPLIT] public V load ( K key ) { final String value = store . load ( toKeyString ( key ) ) ; if ( value != null ) { return toValueObject ( value ) ; } else { return null ; } }


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


Input: Put all of these values in the key value store . [CODESPLIT] public void putAll ( Map < K , V > values ) { Set < Map . Entry < K , V > > entries = values . entrySet ( ) ; Map < String , String > map = new HashMap <> ( values . size ( ) ) ; for ( Map . Entry < K , V > entry : entries ) { map . put ( toKeyString ( entry . getKey ( ) ) , toValueString ( entry . getValue ( ) ) ) ; } store . putAll ( map ) ; }


Input: / * Never let the drift get greater than 200 ms . [CODESPLIT] private long checkForDrift ( long time ) { long delta = Math . abs ( System . currentTimeMillis ( ) - time ) ; long lastDelta = lastDeltaTime . getAndSet ( delta ) ; if ( delta > lastDelta + 200 ) { return getTheTime ( time ) ; } return time ; }


Input: Get a value from the key value store . [CODESPLIT] public V load ( K key ) { final byte [ ] bytes = store . load ( toKeyBytes ( key ) ) ; if ( bytes != null ) { return toValueObject ( bytes ) ; } else { return null ; } }


Input: Convert a String key to bytes . [CODESPLIT] protected byte [ ] toKeyBytes ( K key ) { byte [ ] keyBytes = keyCache . get ( key ) ; if ( keyBytes == null ) { keyBytes = this . keyToByteArrayConverter . apply ( key ) ; keyCache . put ( key , keyBytes ) ; } return keyBytes ; }


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


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


Input: Read the meta - data from a properties file . [CODESPLIT] public List < ValidatorMetaData > readMetaData ( Class < ? > clazz , String propertyName ) { /* Load the properties file. */ Properties props = loadMetaDataPropsFile ( clazz ) ; /* Get the raw validation data for the given property. */ String unparsedString = props . getProperty ( propertyName ) ; /* Parse the string into a list of ValidationMetaData. */ return extractMetaDataFromString ( clazz , propertyName , unparsedString ) ; }


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


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


Input:
Read the meta - data from annotation . This copies the meta - data from the annotation into a POJO . It first checks the meta - data cache if the meta data is not found in the cache it then reads it from the class . [CODESPLIT] public List < ValidatorMetaData > readMetaData ( Class < ? > clazz , String propertyName ) { /* Generate a key to the cache based on the classname and the propertyName. */ String propertyKey = clazz . getName ( ) + "." + propertyName ; /* Look up the validation meta data in the cache. */ List < ValidatorMetaData > validatorMetaDataList = metaDataCache . get ( propertyKey ) ; /* If the meta-data was not found, then generate it. */ if ( validatorMetaDataList == null ) { // if not found
 validatorMetaDataList = extractValidatorMetaData ( clazz , propertyName , validatorMetaDataList ) ; /* Put it in the cache to avoid the processing in the future.
             * Design notes: The processing does a lot of reflection, there
             * is no need to do this each time.
             */ metaDataCache . put ( propertyKey , validatorMetaDataList ) ; } return validatorMetaDataList ; }


Input:
Extract BaseValidator Meta Data . [CODESPLIT] private List < ValidatorMetaData > extractValidatorMetaData ( Class < ? > clazz , String propertyName , List < ValidatorMetaData > validatorMetaDataList ) { /* If the meta-data was not found, then generate it. */ if ( validatorMetaDataList == null ) { // if not found
 /* Read the annotation from the class based on the property name. */ Collection < AnnotationData > annotations = Annotations . getAnnotationDataForFieldAndProperty ( clazz , propertyName , this . validationAnnotationPackages ) ; /* Extract the POJO based meta-data from the annotation. */ validatorMetaDataList = extractMetaDataFromAnnotations ( annotations ) ; } return validatorMetaDataList ; }


Input: Extract meta - data from the annotationData we collected thus far . [CODESPLIT] private List < ValidatorMetaData > extractMetaDataFromAnnotations ( Collection < AnnotationData > annotations ) { List < ValidatorMetaData > list = new ArrayList < ValidatorMetaData > ( ) ; for ( AnnotationData annotationData : annotations ) { ValidatorMetaData validatorMetaData = convertAnnotationDataToValidatorMetaData ( annotationData ) ; list . add ( validatorMetaData ) ; } return list ; }


Input: Converts an AnnotationData into a ValidatorMetaData POJO . [CODESPLIT] private ValidatorMetaData convertAnnotationDataToValidatorMetaData ( AnnotationData annotationData ) { ValidatorMetaData metaData = new ValidatorMetaData ( ) ; metaData . setName ( annotationData . getName ( ) ) ; metaData . setProperties ( annotationData . getValues ( ) ) ; return metaData ; }


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


Input: Splits a string into many parts [CODESPLIT] public static String [ ] split ( final String string , final char split , final int limit ) { char [ ] [ ] comps = CharScanner . split ( FastStringUtils . toCharArray ( string ) , split , limit ) ; return Str . fromCharArrayOfArrayToStringArray ( comps ) ; }


Input: Split string by white space [CODESPLIT] public static String [ ] splitByWhiteSpace ( final String string ) { char [ ] [ ] comps = CharScanner . splitByChars ( FastStringUtils . toCharArray ( string ) , WHITE_SPACE ) ; return Str . fromCharArrayOfArrayToStringArray ( comps ) ; }


Input: Split string by a list of delimiters [CODESPLIT] public static String [ ] splitByDelimiters ( final String string , final String delimiters ) { char [ ] [ ] comps = CharScanner . splitByChars ( FastStringUtils . toCharArray ( string ) , delimiters . toCharArray ( ) ) ; return Str . fromCharArrayOfArrayToStringArray ( comps ) ; }


Input: remove chars from a string [CODESPLIT] public static String removeChars ( final String string , final char ... delimiters ) { char [ ] [ ] comps = CharScanner . splitByCharsNoneEmpty ( FastStringUtils . toCharArray ( string ) , delimiters ) ; return new String ( Chr . add ( comps ) ) ; }


Input: Split string by a list of delimiters but none are empty within a range [CODESPLIT] public static String [ ] splitByCharsNoneEmpty ( final String string , int start , int end , final char ... delimiters ) { Exceptions . requireNonNull ( string ) ; char [ ] [ ] comps = CharScanner . splitByCharsNoneEmpty ( FastStringUtils . toCharArray ( string ) , start , end , delimiters ) ; return Str . fromCharArrayOfArrayToStringArray ( comps ) ; }


Input: Parse float [CODESPLIT] public static float parseFloat ( String buffer , int from , int to ) { return CharScanner . parseFloat ( FastStringUtils . toCharArray ( buffer ) , from , to ) ; }


Input: parse a double [CODESPLIT] public static double parseDouble ( String buffer , int from , int to ) { return CharScanner . parseDouble ( FastStringUtils . toCharArray ( buffer ) , from , to ) ; }


Input: parse an int within a range [CODESPLIT] public static int parseInt ( String buffer , int from , int to ) { return CharScanner . parseInt ( FastStringUtils . toCharArray ( buffer ) , from , to ) ; }


Input: parse an long within a range [CODESPLIT] public static long parseLong ( String buffer , int from , int to ) { return CharScanner . parseLong ( FastStringUtils . toCharArray ( buffer ) , from , to ) ; }


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


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


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


Input: Set in a new value no wrapper [CODESPLIT] public long setLong ( int index , int element ) { long oldValue = values [ index ] ; values [ index ] = element ; return oldValue ; }


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


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


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


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


Input: Set in a new value no wrapper [CODESPLIT] public int setInt ( int index , int element ) { int oldValue = values [ index ] ; values [ index ] = element ; return oldValue ; }


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


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


Input: Gets the field value . [CODESPLIT] public FieldAccess field ( ) { FieldAccess field ; if ( path ) { field = BeanUtils . idxField ( objectUnderTest , name . toString ( ) ) ; if ( field == null ) { return fakeField ( ) ; } return field ; } if ( name instanceof Enum ) { name = Str . camelCaseLower ( name . toString ( ) ) ; } field = fields ( ) . get ( name ) ; return field ; }


Input: Gets the field value . [CODESPLIT] public Object fieldValue ( ) { if ( ! path ) { FieldAccess field1 = this . field ( ) ; return field1 . getValue ( objectUnderTest ) ; } else { return BeanUtils . atIndex ( objectUnderTest , name . toString ( ) ) ; } }


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


Input: Gets the field value . [CODESPLIT] public Object value2 ( ) { if ( ! convert2nd ) { FieldAccess field = this . field ( ) ; this . value2 = ( VALUE ) Conversions . coerce ( field . type ( ) , this . value2 ) ; convert2nd = true ; } return value2 ; }


Input: This method handles walking lists of lists . [CODESPLIT] public static Object getPropByPath ( Object item , String ... path ) { Object o = item ; for ( int index = 0 ; index < path . length ; index ++ ) { String propName = path [ index ] ; if ( o == null ) { return null ; } else if ( o . getClass ( ) . isArray ( ) || o instanceof Collection ) { o = getCollectionProp ( o , propName , index , path ) ; break ; } else { o = getProp ( o , propName ) ; } } return Conversions . unifyListOrArray ( o ) ; }


Input: Get fields from object or Map . Allows maps to act like they have fields . [CODESPLIT] public static Map < String , FieldAccess > getFieldsFromObject ( Object object ) { try { Map < String , FieldAccess > fields ; if ( object instanceof Map ) { fields = getFieldsFromMap ( ( Map < String , Object > ) object ) ; } else { fields = getPropertyFieldAccessMap ( object . getClass ( ) ) ; } return fields ; } catch ( Exception ex ) { requireNonNull ( object , "Item cannot be null" ) ; return handle ( Map . class , ex , "Unable to get fields from object" , className ( object ) ) ; } }


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


Input: Get property value loads nested properties [CODESPLIT] public static Class < ? > getPropertyType ( final Object root , final String property ) { Map < String , FieldAccess > fields = getPropertyFieldAccessMap ( root . getClass ( ) ) ; FieldAccess field = fields . get ( property ) ; return field . type ( ) ; }


Input: Get property value [CODESPLIT] public static Object idx ( Object object , String path ) { String [ ] properties = propertyPathAsStringArray ( path ) ; return getPropertyValue ( object , properties ) ; }


Input: Get property value [CODESPLIT] public static Object atIndex ( Object object , String path ) { String [ ] properties = propertyPathAsStringArray ( path ) ; return getPropertyValue ( object , properties ) ; }


Input: Set property value to simulate dependency injection . [CODESPLIT] public static void injectIntoProperty ( Object object , String path , Object value ) { String [ ] properties = propertyPathAsStringArray ( path ) ; setPropertyValue ( object , value , properties ) ; }


Input: Set a static value [CODESPLIT] public static void idx ( Class < ? > cls , String path , Object value ) { String [ ] properties = propertyPathAsStringArray ( path ) ; setPropertyValue ( cls , value , properties ) ; }


Input: This is an amazing little recursive method . It walks a fanout of nested collection to pull out the leaf nodes [CODESPLIT] private static Object getCollectionProp ( Object o , String propName , int index , String [ ] path ) { o = _getFieldValuesFromCollectionOrArray ( o , propName ) ; if ( index + 1 == path . length ) { return o ; } else { index ++ ; return getCollectionProp ( o , path [ index ] , index , path ) ; } }


Input: This is one is forgiving of null paths . This works with getters first i . e . properties . [CODESPLIT] public static Object getProp ( Object object , final String property ) { if ( object == null ) { return null ; } if ( isDigits ( property ) ) { /* We can index numbers and names. */ object = idx ( object , StringScanner . parseInt ( property ) ) ; } Class < ? > cls = object . getClass ( ) ; /** Tries the getters first. */ Map < String , FieldAccess > fields = Reflection . getPropertyFieldAccessors ( cls ) ; if ( ! fields . containsKey ( property ) ) { fields = Reflection . getAllAccessorFields ( cls ) ; } if ( ! fields . containsKey ( property ) ) { return null ; } else { return fields . get ( property ) . getValue ( object ) ; } }


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


Input: Get property value [CODESPLIT] public static int idxInt ( Object object , String path ) { String [ ] properties = propertyPathAsStringArray ( path ) ; return getPropertyInt ( object , properties ) ; }


Input: Get property value [CODESPLIT] public static String idxStr ( Object object , String path ) { final Object val = idx ( object , path ) ; return Conversions . toString ( val ) ; }


Input: Get Property Path TypeType [CODESPLIT] public static Class < ? > getPropertyPathType ( final Object root , final String ... properties ) { Object object = baseForGetProperty ( root , properties ) ; Map < String , FieldAccess > fields = getFieldsFromObject ( object ) ; final String lastProperty = properties [ properties . length - 1 ] ; FieldAccess field = fields . get ( lastProperty ) ; return field . type ( ) ; }


Input: Get Property Path TypeType [CODESPLIT] public static FieldAccess getPropertyPathField ( final Object root , final String ... properties ) { Object object = baseForGetProperty ( root , properties ) ; Map < String , FieldAccess > fields = getFieldsFromObject ( object ) ; final String lastProperty = properties [ properties . length - 1 ] ; FieldAccess field = fields . get ( lastProperty ) ; return field ; }


Input: Get Property Path TypeType [CODESPLIT] public static FieldAccess getPropertyPathField ( final Class root , final String ... properties ) { Class cls = baseForGetProperty ( root , properties ) ; Map < String , FieldAccess > fields = getFieldsFromObject ( cls ) ; final String lastProperty = properties [ properties . length - 1 ] ; FieldAccess field = fields . get ( lastProperty ) ; return field ; }


Input: / * Manages weak references . [CODESPLIT] static Context context ( ) { if ( _context != null ) { return _context ; } else { Context context = weakContext . get ( ) ; if ( context == null ) { context = new Context ( ) ; weakContext = new WeakReference <> ( context ) ; } return context ; } }


Input: Gets a list of fields merges with properties if field is not found . [CODESPLIT] public static Map < String , FieldAccess > getPropertyFieldAccessMapFieldFirst ( Class < ? > clazz ) { Map < String , FieldAccess > combinedFieldsFieldFirst = getCombinedFieldsFieldFirst ( clazz ) ; if ( combinedFieldsFieldFirst != null ) { return combinedFieldsFieldFirst ; } else { /* Fallback map. */ Map < String , FieldAccess > fieldsFallbacks = null ; /* Primary merge into this one. */ Map < String , FieldAccess > fieldsPrimary = null ; /* Try to find the fields first if this is set. */ fieldsPrimary = Reflection . getAllAccessorFields ( clazz , true ) ; fieldsFallbacks = Reflection . getPropertyFieldAccessors ( clazz ) ; combineFieldMaps ( fieldsFallbacks , fieldsPrimary ) ; combinedFieldsFieldFirst = fieldsPrimary ; putCombinedFieldsFieldFirst ( clazz , combinedFieldsFieldFirst ) ; return combinedFieldsFieldFirst ; } }


Input: Gets a list of fields merges with properties if field is not found . [CODESPLIT] public static Map < String , FieldAccess > getPropertyFieldAccessMapFieldFirstForSerializer ( Class < ? > clazz ) { Map < String , FieldAccess > combinedFieldsFieldFirst = getCombinedFieldsFieldFirstForSerializer ( clazz ) ; if ( combinedFieldsFieldFirst != null ) { return combinedFieldsFieldFirst ; } else { /* Fallback map. */ Map < String , FieldAccess > fieldsFallbacks = null ; /* Primary merge into this one. */ Map < String , FieldAccess > fieldsPrimary = null ; /* Try to find the fields first if this is set. */ fieldsPrimary = Reflection . getAllAccessorFields ( clazz , true ) ; fieldsFallbacks = Reflection . getPropertyFieldAccessors ( clazz ) ; fieldsPrimary = removeNonSerializable ( fieldsPrimary ) ; fieldsFallbacks = removeNonSerializable ( fieldsFallbacks ) ; combineFieldMaps ( fieldsFallbacks , fieldsPrimary ) ; combinedFieldsFieldFirst = fieldsPrimary ; putCombinedFieldsFieldFirstForSerializer ( clazz , combinedFieldsFieldFirst ) ; return combinedFieldsFieldFirst ; } }


Input:
The init method tries to generate the message keys . You should only call the init method if you don t inject values into the detailMessage and summaryMessage . [CODESPLIT] public void init ( ) { /* If the parent and name are equal to null,
         * use the classname to load listFromClassLoader.
    	 * */ if ( name == null && parent == null ) { this . setDetailMessage ( "{" + this . getClass ( ) . getName ( ) + DETAIL_KEY + "}" ) ; this . setSummaryMessage ( "{" + this . getClass ( ) . getName ( ) + SUMMARY_KEY + "}" ) ; /* If the parent is null and the name is not,
         * use the name to load listFromClassLoader.
         */ } else if ( name != null && parent == null ) { this . setDetailMessage ( "{" + "message." + getName ( ) + DETAIL_KEY + "}" ) ; this . setSummaryMessage ( "{" + "message." + getName ( ) + SUMMARY_KEY + "}" ) ; /* If the parent is present, initialize the message keys
         * with the parent name.
         */ } else if ( parent != null ) { this . setDetailMessage ( "{" + "message." + parent + DETAIL_KEY + "}" ) ; this . setSummaryMessage ( "{" + "message." + parent + SUMMARY_KEY + "}" ) ; } }


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


Input: Actually creates the message . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) private String doCreateMessage ( String message , Object [ ] actualArgs ) { return ValidationContext . get ( ) . createMessage ( message , getSubject ( ) , actualArgs ) ; }


Input: Convert the keys to values . [CODESPLIT] private Object [ ] keysToValues ( List < String > argKeys ) { List < String > values = new ArrayList <> ( ) ; for ( String key : argKeys ) { values . add ( getMessage ( key ) ) ; } return values . toArray ( ) ; }


Input: Gets the current subject or the configured subject if the current subject is not found . [CODESPLIT] public String getSubject ( ) { return ValidationContext . get ( ) . getCurrentSubject ( ) == null ? this . subject : ValidationContext . get ( ) . getCurrentSubject ( ) ; }


Input: Parse a text representation of a JSON data structure [CODESPLIT] public Object parseText ( String text ) { if ( text == null || text . length ( ) == 0 ) { throw new IllegalArgumentException ( "The JSON input text should neither be null nor empty." ) ; } return JsonFactory . create ( ) . fromJson ( text ) ; }


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


Input: Requests CouchDB deletes a database . [CODESPLIT] public void deleteDB ( String dbName , String confirm ) { assertNotEmpty ( dbName , "dbName" ) ; if ( ! "delete database" . equals ( confirm ) ) throw new IllegalArgumentException ( "Invalid confirm!" ) ; dbc . delete ( buildUri ( dbc . getBaseUri ( ) ) . path ( dbName ) . build ( ) ) ; }


Input: Requests CouchDB creates a new database ; if one doesn t exist . [CODESPLIT] public void createDB ( String dbName ) { assertNotEmpty ( dbName , "dbName" ) ; InputStream getresp = null ; HttpResponse putresp = null ; final URI uri = buildUri ( dbc . getBaseUri ( ) ) . path ( dbName ) . build ( ) ; try { getresp = dbc . get ( uri ) ; } catch ( NoDocumentException e ) { // db doesn't exist final HttpPut put = new HttpPut ( uri ) ; putresp = dbc . executeRequest ( put ) ; log . info ( String . format ( "Created Database: '%s'" , dbName ) ) ; } finally { close ( getresp ) ; close ( putresp ) ; } }


Input: Triggers a database <i > compact< / i > request . [CODESPLIT] public void compact ( ) { HttpResponse response = null ; try { response = dbc . post ( buildUri ( dbc . getDBUri ( ) ) . path ( "_compact" ) . build ( ) , "" ) ; } finally { close ( response ) ; } }


Input: Request a database sends a list of UUIDs . [CODESPLIT] public List < String > uuids ( long count ) { final String uri = String . format ( "%s_uuids?count=%d" , dbc . getBaseUri ( ) , count ) ; final JsonObject json = dbc . findAny ( JsonObject . class , uri ) ; return dbc . getGson ( ) . fromJson ( json . get ( "uuids" ) . toString ( ) , new TypeToken < List < String > > ( ) { } . getType ( ) ) ; }


Input: Adds request / response interceptors for logging and validation . [CODESPLIT] private void registerInterceptors ( HttpClientBuilder clientBuilder ) { clientBuilder . addInterceptorFirst ( new HttpRequestInterceptor ( ) { public void process ( final HttpRequest request , final HttpContext context ) throws IOException { if ( log . isInfoEnabled ( ) ) { RequestLine req = request . getRequestLine ( ) ; log . info ( "> " + req . getMethod ( ) + " " + URLDecoder . decode ( req . getUri ( ) , "UTF-8" ) ) ; } } } ) ; clientBuilder . addInterceptorFirst ( new HttpResponseInterceptor ( ) { public void process ( final HttpResponse response , final HttpContext context ) throws IOException { if ( log . isInfoEnabled ( ) ) { log . info ( "< Status: " + response . getStatusLine ( ) . getStatusCode ( ) ) ; } validate ( response ) ; } } ) ; }


Input: JSON [CODESPLIT] public static < T > T JsonToObject ( Gson gson , JsonElement elem , String key , Class < T > classType ) { return gson . fromJson ( elem . getAsJsonObject ( ) . get ( key ) , classType ) ; }


Input: List directory contents for a resource folder . Not recursive . This is basically a brute - force implementation . Works for regular files and also JARs . [CODESPLIT] public static List < String > listResources ( String path ) { try { Class < CouchDbUtil > clazz = CouchDbUtil . class ; URL dirURL = clazz . getClassLoader ( ) . getResource ( path ) ; if ( dirURL != null && dirURL . getProtocol ( ) . equals ( "file" ) ) { return Arrays . asList ( new File ( dirURL . toURI ( ) ) . list ( ) ) ; } if ( dirURL != null && dirURL . getProtocol ( ) . equals ( "jar" ) ) { String jarPath = dirURL . getPath ( ) . substring ( 5 , dirURL . getPath ( ) . indexOf ( "!" ) ) ; JarFile jar = new JarFile ( URLDecoder . decode ( jarPath , "UTF-8" ) ) ; Enumeration < JarEntry > entries = jar . entries ( ) ; Set < String > result = new HashSet < String > ( ) ; while ( entries . hasMoreElements ( ) ) { String name = entries . nextElement ( ) . getName ( ) ; if ( name . startsWith ( SPRING_BOOT_DIR ) ) { name = name . substring ( SPRING_BOOT_DIR . length ( ) ) ; } if ( name . startsWith ( path ) ) { String entry = name . substring ( path . length ( ) ) ; int checkSubdir = entry . indexOf ( "/" ) ; if ( checkSubdir >= 0 ) { entry = entry . substring ( 0 , checkSubdir ) ; } if ( entry . length ( ) > 0 ) { result . add ( entry ) ; } } } close ( jar ) ; return new ArrayList < String > ( result ) ; } return null ; } catch ( Exception e ) { throw new CouchDbException ( e ) ; } }


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


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


Input: Queries a view as an { [CODESPLIT] public InputStream queryForStream ( ) { URI uri = uriBuilder . build ( ) ; if ( allDocsKeys != null ) { // bulk docs return getStream ( dbc . post ( uri , allDocsKeys ) ) ; } return dbc . get ( uri ) ; }


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


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


Input: Queries for scalar values . Internal use . [CODESPLIT] private < V > V queryValue ( Class < V > classOfV ) { InputStream instream = null ; try { Reader reader = new InputStreamReader ( instream = queryForStream ( ) , Charsets . UTF_8 ) ; JsonArray array = new JsonParser ( ) . parse ( reader ) . getAsJsonObject ( ) . get ( "rows" ) . getAsJsonArray ( ) ; if ( array . size ( ) != 1 ) { throw new NoDocumentException ( "Expecting a single result but was: " + array . size ( ) ) ; } return JsonToObject ( gson , array . get ( 0 ) , "value" , classOfV ) ; } finally { close ( instream ) ; } }


Input: Queries a view for pagination returns a next or a previous page this method figures out which page to return based on the given param that is generated by an earlier call to this method quering the first page is done by passing a { [CODESPLIT] public < T > Page < T > queryPage ( int rowsPerPage , String param , Class < T > classOfT ) { if ( param == null ) { // assume first page return queryNextPage ( rowsPerPage , null , null , null , null , classOfT ) ; } String currentStartKey ; String currentStartKeyDocId ; String startKey ; String startKeyDocId ; String action ; try { // extract fields from the returned HEXed JSON object final JsonObject json = new JsonParser ( ) . parse ( new String ( Base64 . decodeBase64 ( param . getBytes ( ) ) ) ) . getAsJsonObject ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Paging Param Decoded = " + json ) ; } final JsonObject jsonCurrent = json . getAsJsonObject ( CURRENT_KEYS ) ; currentStartKey = jsonCurrent . get ( CURRENT_START_KEY ) . getAsString ( ) ; currentStartKeyDocId = jsonCurrent . get ( CURRENT_START_KEY_DOC_ID ) . getAsString ( ) ; startKey = json . get ( START_KEY ) . getAsString ( ) ; startKeyDocId = json . get ( START_KEY_DOC_ID ) . getAsString ( ) ; action = json . get ( ACTION ) . getAsString ( ) ; } catch ( Exception e ) { throw new CouchDbException ( "could not parse the given param!" , e ) ; } if ( PREVIOUS . equals ( action ) ) { // previous return queryPreviousPage ( rowsPerPage , currentStartKey , currentStartKeyDocId , startKey , startKeyDocId , classOfT ) ; } else { // next return queryNextPage ( rowsPerPage , currentStartKey , currentStartKeyDocId , startKey , startKeyDocId , classOfT ) ; } }


Input: Reverses the reading direction not the sort order . [CODESPLIT] public View descending ( Boolean descending ) { this . descending = Boolean . valueOf ( gson . toJson ( descending ) ) ; uriBuilder . query ( "descending" , this . descending ) ; return this ; }


Input: Supplies a key list when calling <tt > _all_docs< / tt > View . [CODESPLIT] public View keys ( List < ? > keys ) { this . allDocsKeys = String . format ( "{%s:%s}" , gson . toJson ( "keys" ) , gson . toJson ( keys ) ) ; return this ; }


Input: Synchronizes a design document to the Database . <p > This method will first try to find a document in the database with the same id as the given document if it is not found then the given document will be saved to the database . <p > If the document was found in the database it will be compared with the given document using { [CODESPLIT] public Response synchronizeWithDb ( DesignDocument document ) { assertNotEmpty ( document , "Document" ) ; DesignDocument documentFromDb = null ; try { documentFromDb = getFromDb ( document . getId ( ) ) ; } catch ( NoDocumentException e ) { return dbc . save ( document ) ; } if ( ! document . equals ( documentFromDb ) ) { document . setRevision ( documentFromDb . getRevision ( ) ) ; return dbc . update ( document ) ; } return null ; }


Input: Synchronize all design documents on desk to the database . [CODESPLIT] public void synchronizeAllWithDb ( ) { List < DesignDocument > documents = getAllFromDesk ( ) ; for ( DesignDocument dd : documents ) { synchronizeWithDb ( dd ) ; } }


Input: Gets a design document from the database . [CODESPLIT] public DesignDocument getFromDb ( String id ) { assertNotEmpty ( id , "id" ) ; final URI uri = buildUri ( dbc . getDBUri ( ) ) . path ( id ) . build ( ) ; return dbc . get ( uri , DesignDocument . class ) ; }


Input: Gets all design documents from desk . [CODESPLIT] public List < DesignDocument > getAllFromDesk ( ) { final List < DesignDocument > designDocsList = new ArrayList < DesignDocument > ( ) ; for ( String docName : listResources ( format ( "%s/" , DESIGN_DOCS_DIR ) ) ) { designDocsList . add ( getFromDesk ( docName ) ) ; } return designDocsList ; }


Input: Gets a design document from desk . [CODESPLIT] public DesignDocument getFromDesk ( String id ) { assertNotEmpty ( id , "id" ) ; final DesignDocument dd = new DesignDocument ( ) ; final String rootPath = format ( "%s/%s/" , DESIGN_DOCS_DIR , id ) ; final List < String > elements = listResources ( rootPath ) ; if ( elements == null ) { throw new IllegalArgumentException ( "Design docs directory cannot be empty." ) ; } // Views Map < String , MapReduce > views = null ; if ( elements . contains ( VIEWS ) ) { views = new HashMap < String , MapReduce > ( ) ; final String viewsPath = format ( "%s%s/" , rootPath , VIEWS ) ; for ( String viewDirName : listResources ( viewsPath ) ) { // views sub-dirs final MapReduce mr = new MapReduce ( ) ; final String viewPath = format ( "%s%s/" , viewsPath , viewDirName ) ; final List < String > dirList = listResources ( viewPath ) ; for ( String fileName : dirList ) { // view files final String def = readFile ( format ( "/%s%s" , viewPath , fileName ) ) ; if ( MAP_JS . equals ( fileName ) ) mr . setMap ( def ) ; else if ( REDUCE_JS . equals ( fileName ) ) mr . setReduce ( def ) ; } // /foreach view files views . put ( viewDirName , mr ) ; } // /foreach views sub-dirs } // /views dd . setId ( DESIGN_PREFIX + id ) ; dd . setLanguage ( JAVASCRIPT ) ; dd . setViews ( views ) ; dd . setFilters ( populateMap ( rootPath , elements , FILTERS ) ) ; dd . setShows ( populateMap ( rootPath , elements , SHOWS ) ) ; dd . setLists ( populateMap ( rootPath , elements , LISTS ) ) ; dd . setUpdates ( populateMap ( rootPath , elements , UPDATES ) ) ; dd . setValidateDocUpdate ( readContent ( elements , rootPath , VALIDATE_DOC ) ) ; dd . setRewrites ( dbc . getGson ( ) . fromJson ( readContent ( elements , rootPath , REWRITES ) , JsonArray . class ) ) ; dd . setFulltext ( dbc . getGson ( ) . fromJson ( readContent ( elements , rootPath , FULLTEXT ) , JsonObject . class ) ) ; dd . setIndexes ( dbc . getGson ( ) . fromJson ( readContent ( elements , rootPath , INDEXES ) , JsonObject . class ) ) ; return dd ; }


Input: Adds a new document to the replicator database . [CODESPLIT] public Response save ( ) { assertNotEmpty ( replicatorDoc . getSource ( ) , "Source" ) ; assertNotEmpty ( replicatorDoc . getTarget ( ) , "Target" ) ; if ( userCtxName != null ) { UserCtx ctx = replicatorDoc . new UserCtx ( ) ; ctx . setName ( userCtxName ) ; ctx . setRoles ( userCtxRoles ) ; replicatorDoc . setUserCtx ( ctx ) ; } return dbc . put ( dbURI , replicatorDoc , true ) ; }


Input: Finds a document in the replicator database . [CODESPLIT] public ReplicatorDocument find ( ) { assertNotEmpty ( replicatorDoc . getId ( ) , "Doc id" ) ; final URI uri = buildUri ( dbURI ) . path ( replicatorDoc . getId ( ) ) . query ( "rev" , replicatorDoc . getRevision ( ) ) . build ( ) ; return dbc . get ( uri , ReplicatorDocument . class ) ; }


Input: Finds all documents in the replicator database . [CODESPLIT] public List < ReplicatorDocument > findAll ( ) { InputStream instream = null ; try { final URI uri = buildUri ( dbURI ) . path ( "_all_docs" ) . query ( "include_docs" , "true" ) . build ( ) ; final Reader reader = new InputStreamReader ( instream = dbc . get ( uri ) , Charsets . UTF_8 ) ; final JsonArray jsonArray = new JsonParser ( ) . parse ( reader ) . getAsJsonObject ( ) . getAsJsonArray ( "rows" ) ; final List < ReplicatorDocument > list = new ArrayList < ReplicatorDocument > ( ) ; for ( JsonElement jsonElem : jsonArray ) { JsonElement elem = jsonElem . getAsJsonObject ( ) . get ( "doc" ) ; if ( ! getAsString ( elem . getAsJsonObject ( ) , "_id" ) . startsWith ( "_design" ) ) { // skip design docs ReplicatorDocument rd = dbc . getGson ( ) . fromJson ( elem , ReplicatorDocument . class ) ; list . add ( rd ) ; } } return list ; } finally { close ( instream ) ; } }


Input: Removes a document from the replicator database . [CODESPLIT] public Response remove ( ) { assertNotEmpty ( replicatorDoc . getId ( ) , "Doc id" ) ; assertNotEmpty ( replicatorDoc . getRevision ( ) , "Doc rev" ) ; final URI uri = buildUri ( dbURI ) . path ( replicatorDoc . getId ( ) ) . query ( "rev" , replicatorDoc . getRevision ( ) ) . build ( ) ; return dbc . delete ( uri ) ; }


Input: Finds an Object of the specified type . [CODESPLIT] public < T > T find ( Class < T > classType , String id , Params params ) { assertNotEmpty ( classType , "Class" ) ; assertNotEmpty ( id , "id" ) ; final URI uri = buildUri ( getDBUri ( ) ) . pathEncoded ( id ) . query ( params ) . build ( ) ; return get ( uri , classType ) ; }


Input: Finds a document and return the result as { [CODESPLIT] public InputStream find ( String id ) { assertNotEmpty ( id , "id" ) ; return get ( buildUri ( getDBUri ( ) ) . path ( id ) . build ( ) ) ; }


Input: Finds a document given id and revision and returns the result as { [CODESPLIT] public InputStream find ( String id , String rev ) { assertNotEmpty ( id , "id" ) ; assertNotEmpty ( rev , "rev" ) ; final URI uri = buildUri ( getDBUri ( ) ) . path ( id ) . query ( "rev" , rev ) . build ( ) ; return get ( uri ) ; }


Input: Find documents using a declarative JSON querying syntax . [CODESPLIT] public < T > List < T > findDocs ( String jsonQuery , Class < T > classOfT ) { assertNotEmpty ( jsonQuery , "jsonQuery" ) ; HttpResponse response = null ; try { response = post ( buildUri ( getDBUri ( ) ) . path ( "_find" ) . build ( ) , jsonQuery ) ; Reader reader = new InputStreamReader ( getStream ( response ) , Charsets . UTF_8 ) ; JsonArray jsonArray = new JsonParser ( ) . parse ( reader ) . getAsJsonObject ( ) . getAsJsonArray ( "docs" ) ; List < T > list = new ArrayList < T > ( ) ; for ( JsonElement jsonElem : jsonArray ) { JsonElement elem = jsonElem . getAsJsonObject ( ) ; T t = this . gson . fromJson ( elem , classOfT ) ; list . add ( t ) ; } return list ; } finally { close ( response ) ; } }


Input: Checks if a document exist in the database . [CODESPLIT] public boolean contains ( String id ) { assertNotEmpty ( id , "id" ) ; HttpResponse response = null ; try { response = head ( buildUri ( getDBUri ( ) ) . pathEncoded ( id ) . build ( ) ) ; } catch ( NoDocumentException e ) { return false ; } finally { close ( response ) ; } return true ; }


Input: Saves an object in the database using HTTP <tt > POST< / tt > request . <p > The database will be responsible for generating the document id . [CODESPLIT] public Response post ( Object object ) { assertNotEmpty ( object , "object" ) ; HttpResponse response = null ; try { URI uri = buildUri ( getDBUri ( ) ) . build ( ) ; response = post ( uri , getGson ( ) . toJson ( object ) ) ; return getResponse ( response ) ; } finally { close ( response ) ; } }


Input: Saves a document with <tt > batch = ok< / tt > query param . [CODESPLIT] public void batch ( Object object ) { assertNotEmpty ( object , "object" ) ; HttpResponse response = null ; try { URI uri = buildUri ( getDBUri ( ) ) . query ( "batch" , "ok" ) . build ( ) ; response = post ( uri , getGson ( ) . toJson ( object ) ) ; } finally { close ( response ) ; } }


Input: Removes a document from the database given both a document <code > _id< / code > and <code > _rev< / code > values . [CODESPLIT] public Response remove ( String id , String rev ) { assertNotEmpty ( id , "id" ) ; assertNotEmpty ( rev , "rev" ) ; final URI uri = buildUri ( getDBUri ( ) ) . pathEncoded ( id ) . query ( "rev" , rev ) . build ( ) ; return delete ( uri ) ; }


Input: Performs bulk documents create and update request . [CODESPLIT] public List < Response > bulk ( List < ? > objects , boolean newEdits ) { assertNotEmpty ( objects , "objects" ) ; HttpResponse response = null ; try { final String newEditsVal = newEdits ? "\"new_edits\": true, " : "\"new_edits\": false, " ; final String json = String . format ( "{%s%s%s}" , newEditsVal , "\"docs\": " , getGson ( ) . toJson ( objects ) ) ; final URI uri = buildUri ( getDBUri ( ) ) . path ( "_bulk_docs" ) . build ( ) ; response = post ( uri , json ) ; return getResponseList ( response ) ; } finally { close ( response ) ; } }


Input: Saves an attachment to a new document with a generated <tt > UUID< / tt > as the document id . <p > To retrieve an attachment see { [CODESPLIT] public Response saveAttachment ( InputStream in , String name , String contentType ) { assertNotEmpty ( in , "in" ) ; assertNotEmpty ( name , "name" ) ; assertNotEmpty ( contentType , "ContentType" ) ; final URI uri = buildUri ( getDBUri ( ) ) . path ( generateUUID ( ) ) . path ( "/" ) . path ( name ) . build ( ) ; return put ( uri , in , contentType ) ; }


Input: Saves an attachment to an existing document given both a document id and revision or save to a new document given only the id and rev as { [CODESPLIT] public Response saveAttachment ( InputStream in , String name , String contentType , String docId , String docRev ) { assertNotEmpty ( in , "in" ) ; assertNotEmpty ( name , "name" ) ; assertNotEmpty ( contentType , "ContentType" ) ; assertNotEmpty ( docId , "docId" ) ; final URI uri = buildUri ( getDBUri ( ) ) . pathEncoded ( docId ) . path ( "/" ) . path ( name ) . query ( "rev" , docRev ) . build ( ) ; return put ( uri , in , contentType ) ; }


Input: Invokes an Update Handler . <pre > Params params = new Params () . addParam ( field foo ) . addParam ( value bar ) ; String output = dbClient . invokeUpdateHandler ( designDoc / update1 docId params ) ; < / pre > [CODESPLIT] public String invokeUpdateHandler ( String updateHandlerUri , String docId , Params params ) { assertNotEmpty ( updateHandlerUri , "uri" ) ; assertNotEmpty ( docId , "docId" ) ; final String [ ] v = updateHandlerUri . split ( "/" ) ; final String path = String . format ( "_design/%s/_update/%s/" , v [ 0 ] , v [ 1 ] ) ; final URI uri = buildUri ( getDBUri ( ) ) . path ( path ) . path ( docId ) . query ( params ) . build ( ) ; final HttpResponse response = executeRequest ( new HttpPut ( uri ) ) ; return streamToString ( getStream ( response ) ) ; }


Input: Executes a HTTP request . <p > <b > Note< / b > : The response must be closed after use to release the connection . [CODESPLIT] public HttpResponse executeRequest ( HttpRequestBase request ) { try { return httpClient . execute ( host , request , createContext ( ) ) ; } catch ( IOException e ) { request . abort ( ) ; throw new CouchDbException ( "Error executing request. " , e ) ; } }


Input: Performs a HTTP GET request . [CODESPLIT] InputStream get ( HttpGet httpGet ) { HttpResponse response = executeRequest ( httpGet ) ; return getStream ( response ) ; }


Input: Performs a HTTP GET request . [CODESPLIT] InputStream get ( URI uri ) { HttpGet get = new HttpGet ( uri ) ; get . addHeader ( "Accept" , "application/json" ) ; return get ( get ) ; }


Input: Performs a HTTP GET request . [CODESPLIT] < T > T get ( URI uri , Class < T > classType ) { InputStream in = null ; try { in = get ( uri ) ; return getGson ( ) . fromJson ( new InputStreamReader ( in , "UTF-8" ) , classType ) ; } catch ( UnsupportedEncodingException e ) { throw new CouchDbException ( e ) ; } finally { close ( in ) ; } }


Input: Performs a HTTP PUT request saves or updates a document . [CODESPLIT] Response put ( URI uri , Object object , boolean newEntity ) { assertNotEmpty ( object , "object" ) ; HttpResponse response = null ; try { final JsonObject json = getGson ( ) . toJsonTree ( object ) . getAsJsonObject ( ) ; String id = getAsString ( json , "_id" ) ; String rev = getAsString ( json , "_rev" ) ; if ( newEntity ) { // save assertNull ( rev , "rev" ) ; id = ( id == null ) ? generateUUID ( ) : id ; } else { // update assertNotEmpty ( id , "id" ) ; assertNotEmpty ( rev , "rev" ) ; } final HttpPut put = new HttpPut ( buildUri ( uri ) . pathEncoded ( id ) . build ( ) ) ; setEntity ( put , json . toString ( ) ) ; response = executeRequest ( put ) ; return getResponse ( response ) ; } finally { close ( response ) ; } }


Input: Performs a HTTP PUT request saves an attachment . [CODESPLIT] Response put ( URI uri , InputStream instream , String contentType ) { HttpResponse response = null ; try { final HttpPut httpPut = new HttpPut ( uri ) ; final InputStreamEntity entity = new InputStreamEntity ( instream , - 1 ) ; entity . setContentType ( contentType ) ; httpPut . setEntity ( entity ) ; response = executeRequest ( httpPut ) ; return getResponse ( response ) ; } finally { close ( response ) ; } }


Input: Performs a HTTP POST request . [CODESPLIT] HttpResponse post ( URI uri , String json ) { HttpPost post = new HttpPost ( uri ) ; setEntity ( post , json ) ; return executeRequest ( post ) ; }


Input: Performs a HTTP DELETE request . [CODESPLIT] Response delete ( URI uri ) { HttpResponse response = null ; try { HttpDelete delete = new HttpDelete ( uri ) ; response = executeRequest ( delete ) ; return getResponse ( response ) ; } finally { close ( response ) ; } }


Input: Validates a HTTP response ; on error cases logs status and throws relevant exceptions . [CODESPLIT] void validate ( HttpResponse response ) throws IOException { final int code = response . getStatusLine ( ) . getStatusCode ( ) ; if ( code == 200 || code == 201 || code == 202 ) { // success (ok | created | accepted) return ; } String reason = response . getStatusLine ( ) . getReasonPhrase ( ) ; switch ( code ) { case HttpStatus . SC_NOT_FOUND : { throw new NoDocumentException ( reason ) ; } case HttpStatus . SC_CONFLICT : { throw new DocumentConflictException ( reason ) ; } default : { // other errors: 400 | 401 | 500 etc. throw new CouchDbException ( reason += EntityUtils . toString ( response . getEntity ( ) ) ) ; } } }


Input: Sets a JSON String as a request entity . [CODESPLIT] private void setEntity ( HttpEntityEnclosingRequestBase httpRequest , String json ) { StringEntity entity = new StringEntity ( json , "UTF-8" ) ; entity . setContentType ( "application/json" ) ; httpRequest . setEntity ( entity ) ; }


Input: Builds { [CODESPLIT] private Gson initGson ( GsonBuilder gsonBuilder ) { gsonBuilder . registerTypeAdapter ( JsonObject . class , new JsonDeserializer < JsonObject > ( ) { public JsonObject deserialize ( JsonElement json , Type typeOfT , JsonDeserializationContext context ) throws JsonParseException { return json . getAsJsonObject ( ) ; } } ) ; gsonBuilder . registerTypeAdapter ( JsonObject . class , new JsonSerializer < JsonObject > ( ) { public JsonElement serialize ( JsonObject src , Type typeOfSrc , JsonSerializationContext context ) { return src . getAsJsonObject ( ) ; } } ) ; return gsonBuilder . create ( ) ; }


Input: Adds an in - line document attachment . [CODESPLIT] public void addAttachment ( String name , Attachment attachment ) { if ( attachments == null ) attachments = new HashMap < String , Attachment > ( ) ; attachments . put ( name , attachment ) ; }


Input: Requests Change notifications of feed type continuous . <p > Feed notifications are accessed in an <i > iterator< / i > style . [CODESPLIT] public Changes continuousChanges ( ) { final URI uri = uriBuilder . query ( "feed" , "continuous" ) . build ( ) ; httpGet = new HttpGet ( uri ) ; final InputStream in = dbc . get ( httpGet ) ; final InputStreamReader is = new InputStreamReader ( in , Charsets . UTF_8 ) ; setReader ( new BufferedReader ( is ) ) ; return this ; }


Input: Requests Change notifications of feed type normal . [CODESPLIT] public ChangesResult getChanges ( ) { final URI uri = uriBuilder . query ( "feed" , "normal" ) . build ( ) ; return dbc . get ( uri , ChangesResult . class ) ; }


Input: Reads and sets the next feed in the stream . [CODESPLIT] private boolean readNextRow ( ) { boolean hasNext = false ; try { if ( ! stop ) { String row = "" ; do { row = getReader ( ) . readLine ( ) ; } while ( row . length ( ) == 0 ) ; if ( ! row . startsWith ( "{\"last_seq\":" ) ) { setNextRow ( gson . fromJson ( row , Row . class ) ) ; hasNext = true ; } } } catch ( Exception e ) { terminate ( ) ; throw new CouchDbException ( "Error reading continuous stream." , e ) ; } if ( ! hasNext ) terminate ( ) ; return hasNext ; }