idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
32,200
protected void extendArray ( int k ) { if ( this . size + k > this . keys . length ) { int newCapacity ; if ( this . keys . length < 1024 ) { newCapacity = 2 * ( this . size + k ) ; } else { newCapacity = 5 * ( this . size + k ) / 4 ; } this . keys = Arrays . copyOf ( this . keys , newCapacity ) ; this . values = Arrays . copyOf ( this . values , newCapacity ) ; } }
make sure there is capacity for at least k more elements
32,201
public ContainerPointer getContainerPointer ( final int startIndex ) { return new ContainerPointer ( ) { int k = startIndex ; public void advance ( ) { ++ k ; } public ContainerPointer clone ( ) { try { return ( ContainerPointer ) super . clone ( ) ; } catch ( CloneNotSupportedException e ) { return null ; } } public int compareTo ( ContainerPointer o ) { if ( key ( ) != o . key ( ) ) { return Util . toIntUnsigned ( key ( ) ) - Util . toIntUnsigned ( o . key ( ) ) ; } return o . getCardinality ( ) - getCardinality ( ) ; } public int getCardinality ( ) { return getContainer ( ) . getCardinality ( ) ; } public Container getContainer ( ) { if ( k >= RoaringArray . this . size ) { return null ; } return RoaringArray . this . values [ k ] ; } public boolean isBitmapContainer ( ) { return getContainer ( ) instanceof BitmapContainer ; } public boolean isRunContainer ( ) { return getContainer ( ) instanceof RunContainer ; } public short key ( ) { return RoaringArray . this . keys [ k ] ; } } ; }
Create a ContainerPointer for this RoaringArray
32,202
protected void insertNewKeyValueAt ( int i , short key , Container value ) { extendArray ( 1 ) ; System . arraycopy ( keys , i , keys , i + 1 , size - i ) ; keys [ i ] = key ; System . arraycopy ( values , i , values , i + 1 , size - i ) ; values [ i ] = value ; size ++ ; }
insert a new key it is assumed that it does not exist
32,203
public int first ( ) { assertNonEmpty ( ) ; short firstKey = keys [ 0 ] ; Container container = values [ 0 ] ; return firstKey << 16 | container . first ( ) ; }
Gets the first value in the array
32,204
public int last ( ) { assertNonEmpty ( ) ; short lastKey = keys [ size - 1 ] ; Container container = values [ size - 1 ] ; return lastKey << 16 | container . last ( ) ; }
Gets the last value in the array
32,205
public long select ( final long j ) throws IllegalArgumentException { if ( ! doCacheCardinalities ) { return selectNoCache ( j ) ; } int indexOk = ensureCumulatives ( highestHigh ( ) ) ; if ( highToBitmap . isEmpty ( ) ) { return throwSelectInvalidIndex ( j ) ; } int position = Arrays . binarySearch ( sortedCumulatedCardinality , 0 , indexOk , j ) ; if ( position >= 0 ) { if ( position == indexOk - 1 ) { return throwSelectInvalidIndex ( j ) ; } int high = sortedHighs [ position + 1 ] ; BitmapDataProvider nextBitmap = highToBitmap . get ( high ) ; return RoaringIntPacking . pack ( high , nextBitmap . select ( 0 ) ) ; } else { int insertionPoint = - position - 1 ; final long previousBucketCardinality ; if ( insertionPoint == 0 ) { previousBucketCardinality = 0L ; } else if ( insertionPoint >= indexOk ) { return throwSelectInvalidIndex ( j ) ; } else { previousBucketCardinality = sortedCumulatedCardinality [ insertionPoint - 1 ] ; } final int givenBitmapSelect = ( int ) ( j - previousBucketCardinality ) ; int high = sortedHighs [ insertionPoint ] ; BitmapDataProvider lowBitmap = highToBitmap . get ( high ) ; int low = lowBitmap . select ( givenBitmapSelect ) ; return RoaringIntPacking . pack ( high , low ) ; } }
Return the jth value stored in this bitmap .
32,206
public void serialize ( DataOutput out ) throws IOException { out . writeBoolean ( signedLongs ) ; out . writeInt ( highToBitmap . size ( ) ) ; for ( Entry < Integer , BitmapDataProvider > entry : highToBitmap . entrySet ( ) ) { out . writeInt ( entry . getKey ( ) . intValue ( ) ) ; entry . getValue ( ) . serialize ( out ) ; } }
Serialize this bitmap .
32,207
public long [ ] toArray ( ) { long cardinality = this . getLongCardinality ( ) ; if ( cardinality > Integer . MAX_VALUE ) { throw new IllegalStateException ( "The cardinality does not fit in an array" ) ; } final long [ ] array = new long [ ( int ) cardinality ] ; int pos = 0 ; LongIterator it = getLongIterator ( ) ; while ( it . hasNext ( ) ) { array [ pos ++ ] = it . next ( ) ; } return array ; }
Return the set values as an array if the cardinality is smaller than 2147483648 . The long values are in sorted order .
32,208
public static Roaring64NavigableMap bitmapOf ( final long ... dat ) { final Roaring64NavigableMap ans = new Roaring64NavigableMap ( ) ; ans . add ( dat ) ; return ans ; }
Generate a bitmap with the specified values set to true . The provided longs values don t have to be in sorted order but it may be preferable to sort them from a performance point of view .
32,209
public void add ( final long rangeStart , final long rangeEnd ) { int startHigh = high ( rangeStart ) ; int startLow = low ( rangeStart ) ; int endHigh = high ( rangeEnd ) ; int endLow = low ( rangeEnd ) ; for ( int high = startHigh ; high <= endHigh ; high ++ ) { final int currentStartLow ; if ( startHigh == high ) { currentStartLow = startLow ; } else { currentStartLow = 0 ; } long startLowAsLong = Util . toUnsignedLong ( currentStartLow ) ; final long endLowAsLong ; if ( endHigh == high ) { endLowAsLong = Util . toUnsignedLong ( endLow ) ; } else { endLowAsLong = Util . toUnsignedLong ( - 1 ) + 1 ; } if ( endLowAsLong > startLowAsLong ) { BitmapDataProvider bitmap = highToBitmap . get ( high ) ; if ( bitmap == null ) { bitmap = new MutableRoaringBitmap ( ) ; pushBitmapForHigh ( high , bitmap ) ; } if ( bitmap instanceof RoaringBitmap ) { ( ( RoaringBitmap ) bitmap ) . add ( startLowAsLong , endLowAsLong ) ; } else if ( bitmap instanceof MutableRoaringBitmap ) { ( ( MutableRoaringBitmap ) bitmap ) . add ( startLowAsLong , endLowAsLong ) ; } else { throw new UnsupportedOperationException ( "TODO. Not for " + bitmap . getClass ( ) ) ; } } } invalidateAboveHigh ( startHigh ) ; }
Add to the current bitmap all longs in [ rangeStart rangeEnd ) .
32,210
public int serializedSizeInBytes ( ) { int count = headerSize ( ) ; for ( int k = 0 ; k < this . size ; ++ k ) { count += values [ k ] . getArraySizeInBytes ( ) ; } return count ; }
Report the number of bytes required for serialization .
32,211
private void appendValueLength ( int value , int index ) { int previousValue = toIntUnsigned ( getValue ( index ) ) ; int length = toIntUnsigned ( getLength ( index ) ) ; int offset = value - previousValue ; if ( offset > length ) { setLength ( index , ( short ) offset ) ; } }
Append a value length with all values until a given value
32,212
private boolean canPrependValueLength ( int value , int index ) { if ( index < this . nbrruns ) { int nextValue = toIntUnsigned ( getValue ( index ) ) ; if ( nextValue == value + 1 ) { return true ; } } return false ; }
To check if a value length can be prepended with a given value
32,213
private void closeValueLength ( int value , int index ) { int initialValue = toIntUnsigned ( getValue ( index ) ) ; setLength ( index , ( short ) ( value - initialValue ) ) ; }
To set the last value of a value length
32,214
public static boolean contains ( ByteBuffer buf , int position , short x , final int numRuns ) { int index = bufferedUnsignedInterleavedBinarySearch ( buf , position , 0 , numRuns , x ) ; if ( index >= 0 ) { return true ; } index = - index - 2 ; if ( index != - 1 ) { int offset = toIntUnsigned ( x ) - toIntUnsigned ( buf . getShort ( position + index * 2 * 2 ) ) ; int le = toIntUnsigned ( buf . getShort ( position + index * 2 * 2 + 2 ) ) ; if ( offset <= le ) { return true ; } } return false ; }
Checks whether the run container contains x .
32,215
private void prependValueLength ( int value , int index ) { int initialValue = toIntUnsigned ( getValue ( index ) ) ; int length = toIntUnsigned ( getLength ( index ) ) ; setValue ( index , ( short ) value ) ; setLength ( index , ( short ) ( initialValue - value + length ) ) ; }
Prepend a value length with all values starting from a given value
32,216
private void smartAppend ( short [ ] vl , short val ) { int oldend ; if ( ( nbrruns == 0 ) || ( toIntUnsigned ( val ) > ( oldend = toIntUnsigned ( vl [ 2 * ( nbrruns - 1 ) ] ) + toIntUnsigned ( vl [ 2 * ( nbrruns - 1 ) + 1 ] ) ) + 1 ) ) { vl [ 2 * nbrruns ] = val ; vl [ 2 * nbrruns + 1 ] = 0 ; nbrruns ++ ; return ; } if ( val == ( short ) ( oldend + 1 ) ) { vl [ 2 * ( nbrruns - 1 ) + 1 ] ++ ; } }
to return ArrayContainer or BitmapContainer
32,217
private boolean valueLengthContains ( int value , int index ) { int initialValue = toIntUnsigned ( getValue ( index ) ) ; int length = toIntUnsigned ( getLength ( index ) ) ; return value <= initialValue + length ; }
To check if a value length contains a given value
32,218
static int [ ] negate ( int [ ] x , int Max ) { int [ ] ans = new int [ Max - x . length ] ; int i = 0 ; int c = 0 ; for ( int j = 0 ; j < x . length ; ++ j ) { int v = x [ j ] ; for ( ; i < v ; ++ i ) ans [ c ++ ] = i ; ++ i ; } while ( c < ans . length ) ans [ c ++ ] = i ++ ; return ans ; }
output all integers from the range [ 0 Max ) that are not in the array
32,219
public static boolean contains ( ByteBuffer buf , int position , final short i ) { final int x = toIntUnsigned ( i ) ; return ( buf . getLong ( x / 64 * 8 + position ) & ( 1L << x ) ) != 0 ; }
Checks whether the container contains the value i .
32,220
public int nextClearBit ( final int i ) { int x = i >> 6 ; long w = ~ bitmap . get ( x ) ; w >>>= i ; if ( w != 0 ) { return i + numberOfTrailingZeros ( w ) ; } int length = bitmap . limit ( ) ; for ( ++ x ; x < length ; ++ x ) { long map = ~ bitmap . get ( x ) ; if ( map != 0L ) { return x * 64 + numberOfTrailingZeros ( map ) ; } } return MAX_CAPACITY ; }
Find the index of the next clear bit greater or equal to i .
32,221
public int prevClearBit ( final int i ) { int x = i >> 6 ; long w = ~ bitmap . get ( x ) ; w <<= 64 - i - 1 ; if ( w != 0L ) { return i - Long . numberOfLeadingZeros ( w ) ; } for ( -- x ; x >= 0 ; -- x ) { long map = ~ bitmap . get ( x ) ; if ( map != 0L ) { return x * 64 + 63 - Long . numberOfLeadingZeros ( map ) ; } } return - 1 ; }
Find the index of the previous clear bit less than or equal to i .
32,222
public long [ ] toLongArray ( ) { long [ ] answer = new long [ bitmap . limit ( ) ] ; bitmap . rewind ( ) ; bitmap . get ( answer ) ; return answer ; }
Create a copy of the content of this container as a long array . This creates a copy .
32,223
public LongBuffer toLongBuffer ( ) { LongBuffer lb = LongBuffer . allocate ( bitmap . length ) ; lb . put ( bitmap ) ; return lb ; }
Return the content of this container as a LongBuffer . This creates a copy and might be relatively slow .
32,224
public static boolean contains ( ByteBuffer buf , int position , final short x , int cardinality ) { return BufferUtil . unsignedBinarySearch ( buf , position , 0 , cardinality , x ) >= 0 ; }
Checks whether the container contains the value x .
32,225
private void increaseCapacity ( boolean allowIllegalSize ) { int newCapacity = ( this . content . length == 0 ) ? DEFAULT_INIT_SIZE : this . content . length < 64 ? this . content . length * 2 : this . content . length < 1067 ? this . content . length * 3 / 2 : this . content . length * 5 / 4 ; if ( newCapacity > ArrayContainer . DEFAULT_MAX_SIZE && ! allowIllegalSize ) { newCapacity = ArrayContainer . DEFAULT_MAX_SIZE ; } if ( newCapacity > ArrayContainer . DEFAULT_MAX_SIZE - ArrayContainer . DEFAULT_MAX_SIZE / 16 && ! allowIllegalSize ) { newCapacity = ArrayContainer . DEFAULT_MAX_SIZE ; } this . content = Arrays . copyOf ( this . content , newCapacity ) ; }
the illegal container does not return it .
32,226
private void preComputeCardinalities ( ) { if ( ! cumulatedCardinalitiesCacheIsValid ) { int nbBuckets = highLowContainer . size ( ) ; if ( highToCumulatedCardinality == null || highToCumulatedCardinality . length != nbBuckets ) { highToCumulatedCardinality = new int [ nbBuckets ] ; } if ( highToCumulatedCardinality . length >= 1 ) { highToCumulatedCardinality [ 0 ] = highLowContainer . getContainerAtIndex ( 0 ) . getCardinality ( ) ; for ( int i = 1 ; i < highToCumulatedCardinality . length ; i ++ ) { highToCumulatedCardinality [ i ] = highToCumulatedCardinality [ i - 1 ] + highLowContainer . getContainerAtIndex ( i ) . getCardinality ( ) ; } } cumulatedCardinalitiesCacheIsValid = true ; } }
On any . rank or . select operation we pre - compute all cumulated cardinalities . It will enable using a binary - search to spot the relevant underlying bucket . We may prefer to cache cardinality only up - to the selected rank but it would lead to a more complex implementation
32,227
public boolean contains ( long minimum , long supremum ) { MutableRoaringBitmap . rangeSanityCheck ( minimum , supremum ) ; short firstKey = highbits ( minimum ) ; short lastKey = highbits ( supremum ) ; int span = BufferUtil . toIntUnsigned ( lastKey ) - BufferUtil . toIntUnsigned ( firstKey ) ; int len = highLowContainer . size ( ) ; if ( len < span ) { return false ; } int begin = highLowContainer . getIndex ( firstKey ) ; int end = highLowContainer . getIndex ( lastKey ) ; end = end < 0 ? - end - 1 : end ; if ( begin < 0 || end - begin != span ) { return false ; } int min = ( short ) minimum & 0xFFFF ; int sup = ( short ) supremum & 0xFFFF ; if ( firstKey == lastKey ) { return highLowContainer . getContainerAtIndex ( begin ) . contains ( min , sup ) ; } if ( ! highLowContainer . getContainerAtIndex ( begin ) . contains ( min , 1 << 16 ) ) { return false ; } if ( end < len && ! highLowContainer . getContainerAtIndex ( end ) . contains ( 0 , sup ) ) { return false ; } for ( int i = begin + 1 ; i < end ; ++ i ) { if ( highLowContainer . getContainerAtIndex ( i ) . getCardinality ( ) != 1 << 16 ) { return false ; } } return true ; }
Checks if the bitmap contains the range .
32,228
public int [ ] toArray ( ) { final int [ ] array = new int [ this . getCardinality ( ) ] ; int pos = 0 , pos2 = 0 ; while ( pos < this . highLowContainer . size ( ) ) { final int hs = BufferUtil . toIntUnsigned ( this . highLowContainer . getKeyAtIndex ( pos ) ) << 16 ; final MappeableContainer c = this . highLowContainer . getContainerAtIndex ( pos ++ ) ; c . fillLeastSignificant16bits ( array , pos2 , hs ) ; pos2 += c . getCardinality ( ) ; } return array ; }
Return the set values as an array if the cardinality is less than 2147483648 . The integer values are in sorted order .
32,229
public MutableRoaringBitmap toMutableRoaringBitmap ( ) { MutableRoaringBitmap c = new MutableRoaringBitmap ( ) ; MappeableContainerPointer mcp = highLowContainer . getContainerPointer ( ) ; while ( mcp . hasContainer ( ) ) { c . getMappeableRoaringArray ( ) . appendCopy ( mcp . key ( ) , mcp . getContainer ( ) ) ; mcp . advance ( ) ; } return c ; }
Copies the content of this bitmap to a bitmap that can be modified .
32,230
public static BitmapStatistics analyse ( RoaringBitmap r ) { int acCount = 0 ; int acCardinalitySum = 0 ; int bcCount = 0 ; int rcCount = 0 ; ContainerPointer cp = r . getContainerPointer ( ) ; while ( cp . getContainer ( ) != null ) { if ( cp . isBitmapContainer ( ) ) { bcCount += 1 ; } else if ( cp . isRunContainer ( ) ) { rcCount += 1 ; } else { acCount += 1 ; acCardinalitySum += cp . getCardinality ( ) ; } cp . advance ( ) ; } BitmapStatistics . ArrayContainersStats acStats = new BitmapStatistics . ArrayContainersStats ( acCount , acCardinalitySum ) ; return new BitmapStatistics ( acStats , bcCount , rcCount ) ; }
Analyze the internal representation of bitmap
32,231
public static BitmapStatistics analyse ( Collection < ? extends RoaringBitmap > bitmaps ) { return bitmaps . stream ( ) . reduce ( BitmapStatistics . empty , ( acc , r ) -> acc . merge ( BitmapAnalyser . analyse ( r ) ) , BitmapStatistics :: merge ) ; }
Analyze the internal representation of bitmaps
32,232
protected static int getSizeInBytesFromCardinalityEtc ( int card , int numRuns , boolean isRunEncoded ) { if ( isRunEncoded ) { return 2 + numRuns * 2 * 2 ; } boolean isBitmap = card > MappeableArrayContainer . DEFAULT_MAX_SIZE ; if ( isBitmap ) { return MappeableBitmapContainer . MAX_CAPACITY / 8 ; } else { return card * 2 ; } }
From the cardinality of a container compute the corresponding size in bytes of the container . Additional information is required if the container is run encoded .
32,233
public static boolean unsignedIntersects ( ShortBuffer set1 , int length1 , ShortBuffer set2 , int length2 ) { if ( ( 0 == length1 ) || ( 0 == length2 ) ) { return false ; } int k1 = 0 ; int k2 = 0 ; short s1 = set1 . get ( k1 ) ; short s2 = set2 . get ( k2 ) ; mainwhile : while ( true ) { if ( toIntUnsigned ( s2 ) < toIntUnsigned ( s1 ) ) { do { ++ k2 ; if ( k2 == length2 ) { break mainwhile ; } s2 = set2 . get ( k2 ) ; } while ( toIntUnsigned ( s2 ) < toIntUnsigned ( s1 ) ) ; } if ( toIntUnsigned ( s1 ) < toIntUnsigned ( s2 ) ) { do { ++ k1 ; if ( k1 == length1 ) { break mainwhile ; } s1 = set1 . get ( k1 ) ; } while ( toIntUnsigned ( s1 ) < toIntUnsigned ( s2 ) ) ; } else { return true ; } } return false ; }
Checks if two arrays intersect
32,234
public static void fillArrayANDNOT ( final short [ ] container , final long [ ] bitmap1 , final long [ ] bitmap2 ) { int pos = 0 ; if ( bitmap1 . length != bitmap2 . length ) { throw new IllegalArgumentException ( "not supported" ) ; } for ( int k = 0 ; k < bitmap1 . length ; ++ k ) { long bitset = bitmap1 [ k ] & ( ~ bitmap2 [ k ] ) ; while ( bitset != 0 ) { container [ pos ++ ] = ( short ) ( k * 64 + numberOfTrailingZeros ( bitset ) ) ; bitset &= ( bitset - 1 ) ; } } }
Compute the bitwise ANDNOT between two long arrays and write the set bits in the container .
32,235
public static void flipBitmapRange ( long [ ] bitmap , int start , int end ) { if ( start == end ) { return ; } int firstword = start / 64 ; int endword = ( end - 1 ) / 64 ; bitmap [ firstword ] ^= ~ ( ~ 0L << start ) ; for ( int i = firstword ; i < endword ; i ++ ) { bitmap [ i ] = ~ bitmap [ i ] ; } bitmap [ endword ] ^= ~ 0L >>> - end ; }
flip bits at start start + 1 ... end - 1
32,236
protected static int hybridUnsignedBinarySearch ( final short [ ] array , final int begin , final int end , final short k ) { int ikey = toIntUnsigned ( k ) ; if ( ( end > 0 ) && ( toIntUnsigned ( array [ end - 1 ] ) < ikey ) ) { return - end - 1 ; } int low = begin ; int high = end - 1 ; while ( low + 32 <= high ) { final int middleIndex = ( low + high ) >>> 1 ; final int middleValue = toIntUnsigned ( array [ middleIndex ] ) ; if ( middleValue < ikey ) { low = middleIndex + 1 ; } else if ( middleValue > ikey ) { high = middleIndex - 1 ; } else { return middleIndex ; } } int x = low ; for ( ; x <= high ; ++ x ) { final int val = toIntUnsigned ( array [ x ] ) ; if ( val >= ikey ) { if ( val == ikey ) { return x ; } break ; } } return - ( x + 1 ) ; }
starts with binary search and finishes with a sequential search
32,237
public static void setBitmapRange ( long [ ] bitmap , int start , int end ) { if ( start == end ) { return ; } int firstword = start / 64 ; int endword = ( end - 1 ) / 64 ; if ( firstword == endword ) { bitmap [ firstword ] |= ( ~ 0L << start ) & ( ~ 0L >>> - end ) ; return ; } bitmap [ firstword ] |= ~ 0L << start ; for ( int i = firstword + 1 ; i < endword ; i ++ ) { bitmap [ i ] = ~ 0L ; } bitmap [ endword ] |= ~ 0L >>> - end ; }
set bits at start start + 1 ... end - 1
32,238
public static int unsignedIntersect2by2 ( final short [ ] set1 , final int length1 , final short [ ] set2 , final int length2 , final short [ ] buffer ) { final int THRESHOLD = 25 ; if ( set1 . length * THRESHOLD < set2 . length ) { return unsignedOneSidedGallopingIntersect2by2 ( set1 , length1 , set2 , length2 , buffer ) ; } else if ( set2 . length * THRESHOLD < set1 . length ) { return unsignedOneSidedGallopingIntersect2by2 ( set2 , length2 , set1 , length1 , buffer ) ; } else { return unsignedLocalIntersect2by2 ( set1 , length1 , set2 , length2 , buffer ) ; } }
Intersect two sorted lists and write the result to the provided output array
32,239
public static int unsignedUnion2by2 ( final short [ ] set1 , final int offset1 , final int length1 , final short [ ] set2 , final int offset2 , final int length2 , final short [ ] buffer ) { if ( 0 == length2 ) { System . arraycopy ( set1 , offset1 , buffer , 0 , length1 ) ; return length1 ; } if ( 0 == length1 ) { System . arraycopy ( set2 , offset2 , buffer , 0 , length2 ) ; return length2 ; } int pos = 0 ; int k1 = offset1 , k2 = offset2 ; short s1 = set1 [ k1 ] ; short s2 = set2 [ k2 ] ; while ( true ) { int v1 = toIntUnsigned ( s1 ) ; int v2 = toIntUnsigned ( s2 ) ; if ( v1 < v2 ) { buffer [ pos ++ ] = s1 ; ++ k1 ; if ( k1 >= length1 + offset1 ) { System . arraycopy ( set2 , k2 , buffer , pos , length2 - k2 + offset2 ) ; return pos + length2 - k2 + offset2 ; } s1 = set1 [ k1 ] ; } else if ( v1 == v2 ) { buffer [ pos ++ ] = s1 ; ++ k1 ; ++ k2 ; if ( k1 >= length1 + offset1 ) { System . arraycopy ( set2 , k2 , buffer , pos , length2 - k2 + offset2 ) ; return pos + length2 - k2 + offset2 ; } if ( k2 >= length2 + offset2 ) { System . arraycopy ( set1 , k1 , buffer , pos , length1 - k1 + offset1 ) ; return pos + length1 - k1 + offset1 ; } s1 = set1 [ k1 ] ; s2 = set2 [ k2 ] ; } else { buffer [ pos ++ ] = s2 ; ++ k2 ; if ( k2 >= length2 + offset2 ) { System . arraycopy ( set1 , k1 , buffer , pos , length1 - k1 + offset1 ) ; return pos + length1 - k1 + offset1 ; } s2 = set2 [ k2 ] ; } } }
Unite two sorted lists and write the result to the provided output array
32,240
public static void partialRadixSort ( int [ ] data ) { final int radix = 8 ; int shift = 16 ; int mask = 0xFF0000 ; int [ ] copy = new int [ data . length ] ; int [ ] histogram = new int [ ( 1 << radix ) + 1 ] ; while ( shift < 32 ) { for ( int i = 0 ; i < data . length ; ++ i ) { ++ histogram [ ( ( data [ i ] & mask ) >>> shift ) + 1 ] ; } for ( int i = 0 ; i < 1 << radix ; ++ i ) { histogram [ i + 1 ] += histogram [ i ] ; } for ( int i = 0 ; i < data . length ; ++ i ) { copy [ histogram [ ( data [ i ] & mask ) >>> shift ] ++ ] = data [ i ] ; } System . arraycopy ( copy , 0 , data , 0 , data . length ) ; shift += radix ; mask <<= radix ; Arrays . fill ( histogram , 0 ) ; } }
Sorts the data by the 16 bit prefix .
32,241
public static RoaringBitmap bitmapOfUnordered ( final int ... data ) { RoaringBitmapWriter < RoaringBitmap > writer = writer ( ) . constantMemory ( ) . doPartialRadixSort ( ) . get ( ) ; writer . addMany ( data ) ; writer . flush ( ) ; return writer . getUnderlying ( ) ; }
Efficiently builds a RoaringBitmap from unordered data
32,242
public static boolean intersects ( final RoaringBitmap x1 , final RoaringBitmap x2 ) { final int length1 = x1 . highLowContainer . size ( ) , length2 = x2 . highLowContainer . size ( ) ; int pos1 = 0 , pos2 = 0 ; while ( pos1 < length1 && pos2 < length2 ) { final short s1 = x1 . highLowContainer . getKeyAtIndex ( pos1 ) ; final short s2 = x2 . highLowContainer . getKeyAtIndex ( pos2 ) ; if ( s1 == s2 ) { final Container c1 = x1 . highLowContainer . getContainerAtIndex ( pos1 ) ; final Container c2 = x2 . highLowContainer . getContainerAtIndex ( pos2 ) ; if ( c1 . intersects ( c2 ) ) { return true ; } ++ pos1 ; ++ pos2 ; } else if ( Util . compareUnsigned ( s1 , s2 ) < 0 ) { pos1 = x1 . highLowContainer . advanceUntil ( s2 , pos1 ) ; } else { pos2 = x2 . highLowContainer . advanceUntil ( s1 , pos2 ) ; } } return false ; }
Checks whether the two bitmaps intersect . This can be much faster than calling and and checking the cardinality of the result .
32,243
public void add ( final long rangeStart , final long rangeEnd ) { rangeSanityCheck ( rangeStart , rangeEnd ) ; if ( rangeStart >= rangeEnd ) { return ; } final int hbStart = Util . toIntUnsigned ( Util . highbits ( rangeStart ) ) ; final int lbStart = Util . toIntUnsigned ( Util . lowbits ( rangeStart ) ) ; final int hbLast = Util . toIntUnsigned ( Util . highbits ( rangeEnd - 1 ) ) ; final int lbLast = Util . toIntUnsigned ( Util . lowbits ( rangeEnd - 1 ) ) ; for ( int hb = hbStart ; hb <= hbLast ; ++ hb ) { final int containerStart = ( hb == hbStart ) ? lbStart : 0 ; final int containerLast = ( hb == hbLast ) ? lbLast : Util . maxLowBitAsInteger ( ) ; final int i = highLowContainer . getIndex ( ( short ) hb ) ; if ( i >= 0 ) { final Container c = highLowContainer . getContainerAtIndex ( i ) . iadd ( containerStart , containerLast + 1 ) ; highLowContainer . setContainerAtIndex ( i , c ) ; } else { highLowContainer . insertNewKeyValueAt ( - i - 1 , ( short ) hb , Container . rangeOfOnes ( containerStart , containerLast + 1 ) ) ; } } }
Add to the current bitmap all integers in [ rangeStart rangeEnd ) .
32,244
public boolean isHammingSimilar ( RoaringBitmap other , int tolerance ) { final int size1 = highLowContainer . size ( ) ; final int size2 = other . highLowContainer . size ( ) ; int pos1 = 0 ; int pos2 = 0 ; int budget = tolerance ; while ( budget >= 0 && pos1 < size1 && pos2 < size2 ) { final short key1 = this . highLowContainer . getKeyAtIndex ( pos1 ) ; final short key2 = other . highLowContainer . getKeyAtIndex ( pos2 ) ; Container left = highLowContainer . getContainerAtIndex ( pos1 ) ; Container right = other . highLowContainer . getContainerAtIndex ( pos2 ) ; if ( key1 == key2 ) { budget -= left . xorCardinality ( right ) ; ++ pos1 ; ++ pos2 ; } else if ( Util . compareUnsigned ( key1 , key2 ) < 0 ) { budget -= left . getCardinality ( ) ; ++ pos1 ; } else { budget -= right . getCardinality ( ) ; ++ pos2 ; } } while ( budget >= 0 && pos1 < size1 ) { Container container = highLowContainer . getContainerAtIndex ( pos1 ++ ) ; budget -= container . getCardinality ( ) ; } while ( budget >= 0 && pos2 < size2 ) { Container container = other . highLowContainer . getContainerAtIndex ( pos2 ++ ) ; budget -= container . getCardinality ( ) ; } return budget >= 0 ; }
Returns true if the other bitmap has no more than tolerance bits differing from this bitmap . The other may be transformed into a bitmap equal to this bitmap in no more than tolerance bit flips if this method returns true .
32,245
public boolean hasRunCompression ( ) { for ( int i = 0 ; i < this . highLowContainer . size ( ) ; i ++ ) { Container c = this . highLowContainer . getContainerAtIndex ( i ) ; if ( c instanceof RunContainer ) { return true ; } } return false ; }
Check whether this bitmap has had its runs compressed .
32,246
public boolean runOptimize ( ) { boolean answer = false ; for ( int i = 0 ; i < this . highLowContainer . size ( ) ; i ++ ) { Container c = this . highLowContainer . getContainerAtIndex ( i ) . runOptimize ( ) ; if ( c instanceof RunContainer ) { answer = true ; } this . highLowContainer . setContainerAtIndex ( i , c ) ; } return answer ; }
Use a run - length encoding where it is more space efficient
32,247
public int select ( int j ) { long leftover = Util . toUnsignedLong ( j ) ; for ( int i = 0 ; i < this . highLowContainer . size ( ) ; i ++ ) { Container c = this . highLowContainer . getContainerAtIndex ( i ) ; int thiscard = c . getCardinality ( ) ; if ( thiscard > leftover ) { int keycontrib = this . highLowContainer . getKeyAtIndex ( i ) << 16 ; int lowcontrib = Util . toIntUnsigned ( c . select ( ( int ) leftover ) ) ; return lowcontrib + keycontrib ; } leftover -= thiscard ; } throw new IllegalArgumentException ( "You are trying to select the " + j + "th value when the cardinality is " + this . getCardinality ( ) + "." ) ; }
Return the jth value stored in this bitmap . The provided value needs to be smaller than the cardinality otherwise an IllegalArgumentException exception is thrown .
32,248
public static long maximumSerializedSize ( long cardinality , long universe_size ) { long contnbr = ( universe_size + 65535 ) / 65536 ; if ( contnbr > cardinality ) { contnbr = cardinality ; } final long headermax = Math . max ( 8 , 4 + ( contnbr + 7 ) / 8 ) + 8 * contnbr ; final long valsarray = 2 * cardinality ; final long valsbitmap = contnbr * 8192 ; final long valsbest = Math . min ( valsarray , valsbitmap ) ; return valsbest + headermax ; }
Assume that one wants to store cardinality integers in [ 0 universe_size ) this function returns an upper bound on the serialized size in bytes .
32,249
private static RoaringBitmap selectRangeWithoutCopy ( RoaringBitmap rb , final long rangeStart , final long rangeEnd ) { final int hbStart = Util . toIntUnsigned ( Util . highbits ( rangeStart ) ) ; final int lbStart = Util . toIntUnsigned ( Util . lowbits ( rangeStart ) ) ; final int hbLast = Util . toIntUnsigned ( Util . highbits ( rangeEnd - 1 ) ) ; final int lbLast = Util . toIntUnsigned ( Util . lowbits ( rangeEnd - 1 ) ) ; RoaringBitmap answer = new RoaringBitmap ( ) ; assert ( rangeStart >= 0 && rangeEnd >= 0 ) ; if ( rangeEnd <= rangeStart ) { return answer ; } if ( hbStart == hbLast ) { final int i = rb . highLowContainer . getIndex ( ( short ) hbStart ) ; if ( i >= 0 ) { final Container c = rb . highLowContainer . getContainerAtIndex ( i ) . remove ( 0 , lbStart ) . iremove ( lbLast + 1 , Util . maxLowBitAsInteger ( ) + 1 ) ; if ( ! c . isEmpty ( ) ) { answer . highLowContainer . append ( ( short ) hbStart , c ) ; } } return answer ; } int ifirst = rb . highLowContainer . getIndex ( ( short ) hbStart ) ; int ilast = rb . highLowContainer . getIndex ( ( short ) hbLast ) ; if ( ifirst >= 0 ) { final Container c = rb . highLowContainer . getContainerAtIndex ( ifirst ) . remove ( 0 , lbStart ) ; if ( ! c . isEmpty ( ) ) { answer . highLowContainer . append ( ( short ) hbStart , c ) ; } } for ( int hb = hbStart + 1 ; hb <= hbLast - 1 ; ++ hb ) { final int i = rb . highLowContainer . getIndex ( ( short ) hb ) ; final int j = answer . highLowContainer . getIndex ( ( short ) hb ) ; assert j < 0 ; if ( i >= 0 ) { final Container c = rb . highLowContainer . getContainerAtIndex ( i ) ; answer . highLowContainer . insertNewKeyValueAt ( - j - 1 , ( short ) hb , c ) ; } } if ( ilast >= 0 ) { final Container c = rb . highLowContainer . getContainerAtIndex ( ilast ) . remove ( lbLast + 1 , Util . maxLowBitAsInteger ( ) + 1 ) ; if ( ! c . isEmpty ( ) ) { answer . highLowContainer . append ( ( short ) hbLast , c ) ; } } return answer ; }
had formerly failed if rangeEnd == 0
32,250
public int [ ] toArray ( ) { final int [ ] array = new int [ this . getCardinality ( ) ] ; int pos = 0 , pos2 = 0 ; while ( pos < this . highLowContainer . size ( ) ) { final int hs = this . highLowContainer . getKeyAtIndex ( pos ) << 16 ; Container c = this . highLowContainer . getContainerAtIndex ( pos ++ ) ; c . fillLeastSignificant16bits ( array , pos2 , hs ) ; pos2 += c . getCardinality ( ) ; } return array ; }
Return the set values as an array if the cardinality is smaller than 2147483648 . The integer values are in sorted order .
32,251
public static Iterator < ImmutableRoaringBitmap > convertToImmutable ( final Iterator < MutableRoaringBitmap > i ) { return new Iterator < ImmutableRoaringBitmap > ( ) { public boolean hasNext ( ) { return i . hasNext ( ) ; } public ImmutableRoaringBitmap next ( ) { return i . next ( ) ; } public void remove ( ) { } ; } ; }
Convenience method converting one type of iterator into another to avoid unnecessary warnings .
32,252
public Response execute ( String httpUrl , String methodName , Map < String , Object > headers , Map < String , Object > queryParams , Object body ) throws Exception { httpclient = createHttpClient ( ) ; String reqBodyAsString = handleRequestBody ( body ) ; httpUrl = handleUrlAndQueryParams ( httpUrl , queryParams ) ; RequestBuilder requestBuilder = createRequestBuilder ( httpUrl , methodName , headers , reqBodyAsString ) ; handleHeaders ( headers , requestBuilder ) ; addCookieToHeader ( requestBuilder ) ; CloseableHttpResponse httpResponse = httpclient . execute ( requestBuilder . build ( ) ) ; return handleResponse ( httpResponse ) ; }
Override this method in case you want to execute the http call differently via your http client . Otherwise the framework falls back to this implementation by default .
32,253
public Response handleResponse ( CloseableHttpResponse httpResponse ) throws IOException { Response serverResponse = createCharsetResponse ( httpResponse ) ; Header [ ] allHeaders = httpResponse . getAllHeaders ( ) ; Response . ResponseBuilder responseBuilder = Response . fromResponse ( serverResponse ) ; for ( Header thisHeader : allHeaders ) { String headerKey = thisHeader . getName ( ) ; responseBuilder = responseBuilder . header ( headerKey , thisHeader . getValue ( ) ) ; handleHttpSession ( serverResponse , headerKey ) ; } return responseBuilder . build ( ) ; }
Once the client executes the http call then it receives the http response . This method takes care of handling that . In case you need to handle it differently you can override this method .
32,254
public RequestBuilder createDefaultRequestBuilder ( String httpUrl , String methodName , String reqBodyAsString ) { RequestBuilder requestBuilder = RequestBuilder . create ( methodName ) . setUri ( httpUrl ) ; if ( reqBodyAsString != null ) { HttpEntity httpEntity = EntityBuilder . create ( ) . setContentType ( APPLICATION_JSON ) . setText ( reqBodyAsString ) . build ( ) ; requestBuilder . setEntity ( httpEntity ) ; } return requestBuilder ; }
This is the usual http request builder most widely used using Apache Http Client . In case you want to build or prepare the requests differently you can override this method .
32,255
public RequestBuilder createFileUploadRequestBuilder ( String httpUrl , String methodName , String reqBodyAsString ) throws IOException { Map < String , Object > fileFieldNameValueMap = getFileFieldNameValue ( reqBodyAsString ) ; List < String > fileFieldsList = ( List < String > ) fileFieldNameValueMap . get ( FILES_FIELD ) ; MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder . create ( ) ; if ( fileFieldsList != null ) { buildAllFilesToUpload ( fileFieldsList , multipartEntityBuilder ) ; } buildOtherRequestParams ( fileFieldNameValueMap , multipartEntityBuilder ) ; buildMultiPartBoundary ( fileFieldNameValueMap , multipartEntityBuilder ) ; return createUploadRequestBuilder ( httpUrl , methodName , multipartEntityBuilder ) ; }
This is the http request builder for file uploads using Apache Http Client . In case you want to build or prepare the requests differently you can override this method .
32,256
public void handleHttpSession ( Response serverResponse , String headerKey ) { if ( "Set-Cookie" . equals ( headerKey ) ) { COOKIE_JSESSIONID_VALUE = serverResponse . getMetadata ( ) . get ( headerKey ) ; } }
This method handles the http session to be maintained between the calls . In case the session is not needed or to be handled differently then this method can be overridden to do nothing or to roll your own feature .
32,257
void digReplaceContent ( Map < String , Object > map ) { map . entrySet ( ) . stream ( ) . forEach ( entry -> { Object value = entry . getValue ( ) ; if ( value instanceof Map ) { digReplaceContent ( ( Map < String , Object > ) value ) ; } else { LOGGER . debug ( "Leaf node found = {}, checking for any external json file..." , value ) ; if ( value != null && value . toString ( ) . contains ( JSON_PAYLOAD_FILE ) ) { LOGGER . info ( "Found external JSON file place holder = {}. Replacing with content" , value ) ; String valueString = value . toString ( ) ; String token = getJsonFilePhToken ( valueString ) ; if ( token != null && token . startsWith ( JSON_PAYLOAD_FILE ) ) { String resourceJsonFile = token . substring ( JSON_PAYLOAD_FILE . length ( ) ) ; try { Object jsonFileContent = objectMapper . readTree ( readJsonAsString ( resourceJsonFile ) ) ; entry . setValue ( jsonFileContent ) ; } catch ( Exception exx ) { LOGGER . error ( "External file reference exception - {}" , exx . getMessage ( ) ) ; throw new RuntimeException ( exx ) ; } } } } } ) ; }
Digs deep into the nested map and looks for external file reference if found replaces the place holder with the file content . This is handy when the engineers wants to drive the common contents from a central place .
32,258
protected List < ScenarioSpec > getChildren ( ) { TestPackageRoot rootPackageAnnotation = testClass . getAnnotation ( TestPackageRoot . class ) ; JsonTestCases jsonTestCasesAnnotation = testClass . getAnnotation ( JsonTestCases . class ) ; validateSuiteAnnotationPresent ( rootPackageAnnotation , jsonTestCasesAnnotation ) ; if ( rootPackageAnnotation != null ) { smartUtils . checkDuplicateScenarios ( rootPackageAnnotation . value ( ) ) ; return smartUtils . getScenarioSpecListByPackage ( rootPackageAnnotation . value ( ) ) ; } else { List < JsonTestCase > jsonTestCases = Arrays . asList ( testClass . getAnnotationsByType ( JsonTestCase . class ) ) ; List < String > allEndPointFiles = jsonTestCases . stream ( ) . map ( thisTestCase -> thisTestCase . value ( ) ) . collect ( Collectors . toList ( ) ) ; return allEndPointFiles . stream ( ) . map ( testResource -> { try { return smartUtils . jsonFileToJava ( testResource , ScenarioSpec . class ) ; } catch ( IOException e ) { throw new RuntimeException ( "Exception while deserializing to Spec. Details: " + e ) ; } } ) . collect ( Collectors . toList ( ) ) ; } }
Returns a list of objects that define the children of this Runner .
32,259
private int maxEntryLengthOf ( List < AssertionReport > failureReportList ) { final Integer maxLength = ofNullable ( failureReportList ) . orElse ( Collections . emptyList ( ) ) . stream ( ) . map ( report -> report . toString ( ) . length ( ) ) . max ( Comparator . naturalOrder ( ) ) . get ( ) ; return maxLength > MAX_LINE_LENGTH ? MAX_LINE_LENGTH : maxLength ; }
all private functions below
32,260
public void setHocr ( boolean hocr ) { this . renderedFormat = hocr ? RenderedFormat . HOCR : RenderedFormat . TEXT ; prop . setProperty ( "tessedit_create_hocr" , hocr ? "1" : "0" ) ; }
Enables hocr output .
32,261
public void setTessVariable ( String key , String value ) { prop . setProperty ( key , value ) ; }
Set the value of Tesseract s internal parameter .
32,262
protected void init ( ) { handle = TessBaseAPICreate ( ) ; StringArray sarray = new StringArray ( configList . toArray ( new String [ 0 ] ) ) ; PointerByReference configs = new PointerByReference ( ) ; configs . setPointer ( sarray ) ; TessBaseAPIInit1 ( handle , datapath , language , ocrEngineMode , configs , configList . size ( ) ) ; if ( psm > - 1 ) { TessBaseAPISetPageSegMode ( handle , psm ) ; } }
Initializes Tesseract engine .
32,263
protected void setTessVariables ( ) { Enumeration < ? > em = prop . propertyNames ( ) ; while ( em . hasMoreElements ( ) ) { String key = ( String ) em . nextElement ( ) ; TessBaseAPISetVariable ( handle , key , prop . getProperty ( key ) ) ; } }
Sets Tesseract s internal parameters .
32,264
public void createDocuments ( String filename , String outputbase , List < RenderedFormat > formats ) throws TesseractException { createDocuments ( new String [ ] { filename } , new String [ ] { outputbase } , formats ) ; }
Creates documents for given renderer .
32,265
public List < Rectangle > getSegmentedRegions ( BufferedImage bi , int pageIteratorLevel ) throws TesseractException { init ( ) ; setTessVariables ( ) ; try { List < Rectangle > list = new ArrayList < Rectangle > ( ) ; setImage ( bi , null ) ; Boxa boxes = TessBaseAPIGetComponentImages ( handle , pageIteratorLevel , TRUE , null , null ) ; int boxCount = Leptonica1 . boxaGetCount ( boxes ) ; for ( int i = 0 ; i < boxCount ; i ++ ) { Box box = Leptonica1 . boxaGetBox ( boxes , i , L_CLONE ) ; if ( box == null ) { continue ; } list . add ( new Rectangle ( box . x , box . y , box . w , box . h ) ) ; PointerByReference pRef = new PointerByReference ( ) ; pRef . setValue ( box . getPointer ( ) ) ; Leptonica1 . boxDestroy ( pRef ) ; } PointerByReference pRef = new PointerByReference ( ) ; pRef . setValue ( boxes . getPointer ( ) ) ; Leptonica1 . boxaDestroy ( pRef ) ; return list ; } catch ( IOException ioe ) { logger . warn ( ioe . getMessage ( ) , ioe ) ; throw new TesseractException ( ioe ) ; } finally { dispose ( ) ; } }
Gets segmented regions at specified page iterator level .
32,266
public List < OCRResult > createDocumentsWithResults ( String [ ] filenames , String [ ] outputbases , List < ITesseract . RenderedFormat > formats , int pageIteratorLevel ) throws TesseractException { if ( filenames . length != outputbases . length ) { throw new RuntimeException ( "The two arrays must match in length." ) ; } init ( ) ; setTessVariables ( ) ; List < OCRResult > results = new ArrayList < OCRResult > ( ) ; try { for ( int i = 0 ; i < filenames . length ; i ++ ) { File inputFile = new File ( filenames [ i ] ) ; File imageFile = null ; try { imageFile = ImageIOHelper . getImageFile ( inputFile ) ; TessResultRenderer renderer = createRenderers ( outputbases [ i ] , formats ) ; int meanTextConfidence = createDocuments ( imageFile . getPath ( ) , renderer ) ; List < Word > words = meanTextConfidence > 0 ? getRecognizedWords ( pageIteratorLevel ) : new ArrayList < Word > ( ) ; results . add ( new OCRResult ( meanTextConfidence , words ) ) ; TessDeleteResultRenderer ( renderer ) ; } catch ( Exception e ) { logger . warn ( e . getMessage ( ) , e ) ; } finally { if ( imageFile != null && imageFile . exists ( ) && imageFile != inputFile && imageFile . getName ( ) . startsWith ( "multipage" ) && imageFile . getName ( ) . endsWith ( ImageIOHelper . TIFF_EXT ) ) { imageFile . delete ( ) ; } } } } finally { dispose ( ) ; } return results ; }
Creates documents with OCR results for given renderers at specified page iterator level .
32,267
public static synchronized File extractTessResources ( String resourceName ) { File targetPath = null ; try { targetPath = new File ( TESS4J_TEMP_DIR , resourceName ) ; Enumeration < URL > resources = LoadLibs . class . getClassLoader ( ) . getResources ( resourceName ) ; while ( resources . hasMoreElements ( ) ) { URL resourceUrl = resources . nextElement ( ) ; copyResources ( resourceUrl , targetPath ) ; } } catch ( IOException | URISyntaxException e ) { logger . warn ( e . getMessage ( ) , e ) ; } return targetPath ; }
Extracts tesseract resources to temp folder .
32,268
static void copyResources ( URL resourceUrl , File targetPath ) throws IOException , URISyntaxException { if ( resourceUrl == null ) { return ; } URLConnection urlConnection = resourceUrl . openConnection ( ) ; if ( urlConnection instanceof JarURLConnection ) { copyJarResourceToPath ( ( JarURLConnection ) urlConnection , targetPath ) ; } else if ( VFS_PROTOCOL . equals ( resourceUrl . getProtocol ( ) ) ) { VirtualFile virtualFileOrFolder = VFS . getChild ( resourceUrl . toURI ( ) ) ; copyFromWarToFolder ( virtualFileOrFolder , targetPath ) ; } else { File file = new File ( resourceUrl . getPath ( ) ) ; if ( file . isDirectory ( ) ) { for ( File resourceFile : FileUtils . listFiles ( file , null , true ) ) { int index = resourceFile . getPath ( ) . lastIndexOf ( targetPath . getName ( ) ) + targetPath . getName ( ) . length ( ) ; File targetFile = new File ( targetPath , resourceFile . getPath ( ) . substring ( index ) ) ; if ( ! targetFile . exists ( ) || targetFile . length ( ) != resourceFile . length ( ) ) { if ( resourceFile . isFile ( ) ) { FileUtils . copyFile ( resourceFile , targetFile ) ; } } } } else { if ( ! targetPath . exists ( ) || targetPath . length ( ) != file . length ( ) ) { FileUtils . copyFile ( file , targetPath ) ; } } } }
Copies resources to target folder .
32,269
static void copyJarResourceToPath ( JarURLConnection jarConnection , File destPath ) { try ( JarFile jarFile = jarConnection . getJarFile ( ) ) { String jarConnectionEntryName = jarConnection . getEntryName ( ) ; if ( ! jarConnectionEntryName . endsWith ( "/" ) ) { jarConnectionEntryName += "/" ; } for ( Enumeration < JarEntry > e = jarFile . entries ( ) ; e . hasMoreElements ( ) ; ) { JarEntry jarEntry = e . nextElement ( ) ; String jarEntryName = jarEntry . getName ( ) ; if ( jarEntryName . startsWith ( jarConnectionEntryName ) ) { String filename = jarEntryName . substring ( jarConnectionEntryName . length ( ) ) ; File targetFile = new File ( destPath , filename ) ; if ( jarEntry . isDirectory ( ) ) { targetFile . mkdirs ( ) ; } else { if ( ! targetFile . exists ( ) || targetFile . length ( ) != jarEntry . getSize ( ) ) { try ( InputStream is = jarFile . getInputStream ( jarEntry ) ; OutputStream out = FileUtils . openOutputStream ( targetFile ) ) { IOUtils . copy ( is , out ) ; } } } } } } catch ( IOException e ) { logger . warn ( e . getMessage ( ) , e ) ; } }
Copies resources from the jar file of the current thread and extract it to the destination path .
32,270
static void copyFromWarToFolder ( VirtualFile virtualFileOrFolder , File targetFolder ) throws IOException { if ( virtualFileOrFolder . isDirectory ( ) && ! virtualFileOrFolder . getName ( ) . contains ( "." ) ) { if ( targetFolder . getName ( ) . equalsIgnoreCase ( virtualFileOrFolder . getName ( ) ) ) { for ( VirtualFile innerFileOrFolder : virtualFileOrFolder . getChildren ( ) ) { copyFromWarToFolder ( innerFileOrFolder , targetFolder ) ; } } else { File innerTargetFolder = new File ( targetFolder , virtualFileOrFolder . getName ( ) ) ; innerTargetFolder . mkdir ( ) ; for ( VirtualFile innerFileOrFolder : virtualFileOrFolder . getChildren ( ) ) { copyFromWarToFolder ( innerFileOrFolder , innerTargetFolder ) ; } } } else { File targetFile = new File ( targetFolder , virtualFileOrFolder . getName ( ) ) ; if ( ! targetFile . exists ( ) || targetFile . length ( ) != virtualFileOrFolder . getSize ( ) ) { FileUtils . copyURLToFile ( virtualFileOrFolder . asFileURL ( ) , targetFile ) ; } } }
Copies resources from WAR to target folder .
32,271
public double getSkewAngle ( ) { ImageDeskew . HoughLine [ ] hl ; double sum = 0.0 ; int count = 0 ; calc ( ) ; hl = getTop ( 20 ) ; if ( hl . length >= 20 ) { for ( int i = 0 ; i < 19 ; i ++ ) { sum += hl [ i ] . alpha ; count ++ ; } return ( sum / count ) ; } else { return 0.0d ; } }
Calculates the skew angle of the image cImage .
32,272
private ImageDeskew . HoughLine [ ] getTop ( int count ) { ImageDeskew . HoughLine [ ] hl = new ImageDeskew . HoughLine [ count ] ; for ( int i = 0 ; i < count ; i ++ ) { hl [ i ] = new ImageDeskew . HoughLine ( ) ; } ImageDeskew . HoughLine tmp ; for ( int i = 0 ; i < ( this . cHMatrix . length - 1 ) ; i ++ ) { if ( this . cHMatrix [ i ] > hl [ count - 1 ] . count ) { hl [ count - 1 ] . count = this . cHMatrix [ i ] ; hl [ count - 1 ] . index = i ; int j = count - 1 ; while ( ( j > 0 ) && ( hl [ j ] . count > hl [ j - 1 ] . count ) ) { tmp = hl [ j ] ; hl [ j ] = hl [ j - 1 ] ; hl [ j - 1 ] = tmp ; j -- ; } } } int alphaIndex ; int dIndex ; for ( int i = 0 ; i < count ; i ++ ) { dIndex = hl [ i ] . index / cSteps ; alphaIndex = hl [ i ] . index - dIndex * cSteps ; hl [ i ] . alpha = getAlpha ( alphaIndex ) ; hl [ i ] . d = dIndex + cDMin ; } return hl ; }
calculate the count lines in the image with most points
32,273
private static IIOMetadata setDPIViaAPI ( IIOMetadata imageMetadata , int dpiX , int dpiY ) throws IIOInvalidTreeException { TIFFDirectory dir = TIFFDirectory . createFromMetadata ( imageMetadata ) ; BaselineTIFFTagSet base = BaselineTIFFTagSet . getInstance ( ) ; TIFFTag tagXRes = base . getTag ( BaselineTIFFTagSet . TAG_X_RESOLUTION ) ; TIFFTag tagYRes = base . getTag ( BaselineTIFFTagSet . TAG_Y_RESOLUTION ) ; TIFFField fieldXRes = new TIFFField ( tagXRes , TIFFTag . TIFF_RATIONAL , 1 , new long [ ] [ ] { { dpiX , 1 } } ) ; TIFFField fieldYRes = new TIFFField ( tagYRes , TIFFTag . TIFF_RATIONAL , 1 , new long [ ] [ ] { { dpiY , 1 } } ) ; dir . addTIFFField ( fieldXRes ) ; dir . addTIFFField ( fieldYRes ) ; IIOMetadata metadata = dir . getAsMetadata ( ) ; IIOMetadataNode root = new IIOMetadataNode ( "javax_imageio_1.0" ) ; IIOMetadataNode horiz = new IIOMetadataNode ( "HorizontalPixelSize" ) ; horiz . setAttribute ( "value" , Double . toString ( 25.4f / dpiX ) ) ; IIOMetadataNode vert = new IIOMetadataNode ( "VerticalPixelSize" ) ; vert . setAttribute ( "value" , Double . toString ( 25.4f / dpiY ) ) ; IIOMetadataNode dim = new IIOMetadataNode ( "Dimension" ) ; dim . appendChild ( horiz ) ; dim . appendChild ( vert ) ; root . appendChild ( dim ) ; metadata . mergeTree ( "javax_imageio_1.0" , root ) ; return metadata ; }
Set DPI using API .
32,274
public static String getImageFileFormat ( File imageFile ) { String imageFileName = imageFile . getName ( ) ; String imageFormat = imageFileName . substring ( imageFileName . lastIndexOf ( '.' ) + 1 ) ; if ( imageFormat . matches ( "(pbm|pgm|ppm)" ) ) { imageFormat = "pnm" ; } else if ( imageFormat . matches ( "(jp2|j2k|jpf|jpx|jpm)" ) ) { imageFormat = "jpeg2000" ; } return imageFormat ; }
Gets image file format .
32,275
public static File getImageFile ( File inputFile ) throws IOException { File imageFile = inputFile ; if ( inputFile . getName ( ) . toLowerCase ( ) . endsWith ( ".pdf" ) ) { imageFile = PdfUtilities . convertPdf2Tiff ( inputFile ) ; } return imageFile ; }
Gets image file . Convert to multi - page TIFF if given PDF .
32,276
public static File deskewImage ( File imageFile , double minimumDeskewThreshold ) throws IOException { List < BufferedImage > imageList = getImageList ( imageFile ) ; for ( int i = 0 ; i < imageList . size ( ) ; i ++ ) { BufferedImage bi = imageList . get ( i ) ; ImageDeskew deskew = new ImageDeskew ( bi ) ; double imageSkewAngle = deskew . getSkewAngle ( ) ; if ( ( imageSkewAngle > minimumDeskewThreshold || imageSkewAngle < - ( minimumDeskewThreshold ) ) ) { bi = ImageUtil . rotate ( bi , - imageSkewAngle , bi . getWidth ( ) / 2 , bi . getHeight ( ) / 2 ) ; imageList . set ( i , bi ) ; } } File tempImageFile = File . createTempFile ( FilenameUtils . getBaseName ( imageFile . getName ( ) ) , ".tif" ) ; mergeTiff ( imageList . toArray ( new BufferedImage [ 0 ] ) , tempImageFile ) ; return tempImageFile ; }
Deskews image .
32,277
public static Map < String , String > readImageData ( IIOImage oimage ) { Map < String , String > dict = new HashMap < String , String > ( ) ; IIOMetadata imageMetadata = oimage . getMetadata ( ) ; if ( imageMetadata != null ) { IIOMetadataNode dimNode = ( IIOMetadataNode ) imageMetadata . getAsTree ( "javax_imageio_1.0" ) ; NodeList nodes = dimNode . getElementsByTagName ( "HorizontalPixelSize" ) ; int dpiX ; if ( nodes . getLength ( ) > 0 ) { float dpcWidth = Float . parseFloat ( nodes . item ( 0 ) . getAttributes ( ) . item ( 0 ) . getNodeValue ( ) ) ; dpiX = ( int ) Math . round ( 25.4f / dpcWidth ) ; } else { dpiX = Toolkit . getDefaultToolkit ( ) . getScreenResolution ( ) ; } dict . put ( "dpiX" , String . valueOf ( dpiX ) ) ; nodes = dimNode . getElementsByTagName ( "VerticalPixelSize" ) ; int dpiY ; if ( nodes . getLength ( ) > 0 ) { float dpcHeight = Float . parseFloat ( nodes . item ( 0 ) . getAttributes ( ) . item ( 0 ) . getNodeValue ( ) ) ; dpiY = ( int ) Math . round ( 25.4f / dpcHeight ) ; } else { dpiY = Toolkit . getDefaultToolkit ( ) . getScreenResolution ( ) ; } dict . put ( "dpiY" , String . valueOf ( dpiY ) ) ; } return dict ; }
Reads image meta data .
32,278
public static BufferedImage convertImageToGrayscale ( BufferedImage image ) { BufferedImage tmp = new BufferedImage ( image . getWidth ( ) , image . getHeight ( ) , BufferedImage . TYPE_BYTE_GRAY ) ; Graphics2D g2 = tmp . createGraphics ( ) ; g2 . drawImage ( image , 0 , 0 , null ) ; g2 . dispose ( ) ; return tmp ; }
A simple method to convert an image to gray scale .
32,279
public static BufferedImage invertImageColor ( BufferedImage image ) { BufferedImage tmp = new BufferedImage ( image . getWidth ( ) , image . getHeight ( ) , image . getType ( ) ) ; BufferedImageOp invertOp = new LookupOp ( new ShortLookupTable ( 0 , invertTable ) , null ) ; return invertOp . filter ( image , tmp ) ; }
Inverts image color .
32,280
public static BufferedImage rotateImage ( BufferedImage image , double angle ) { double theta = Math . toRadians ( angle ) ; double sin = Math . abs ( Math . sin ( theta ) ) ; double cos = Math . abs ( Math . cos ( theta ) ) ; int w = image . getWidth ( ) ; int h = image . getHeight ( ) ; int newW = ( int ) Math . floor ( w * cos + h * sin ) ; int newH = ( int ) Math . floor ( h * cos + w * sin ) ; BufferedImage tmp = new BufferedImage ( newW , newH , image . getType ( ) ) ; Graphics2D g2d = tmp . createGraphics ( ) ; g2d . setRenderingHint ( RenderingHints . KEY_INTERPOLATION , RenderingHints . VALUE_INTERPOLATION_BICUBIC ) ; g2d . translate ( ( newW - w ) / 2 , ( newH - h ) / 2 ) ; g2d . rotate ( theta , w / 2 , h / 2 ) ; g2d . drawImage ( image , 0 , 0 , null ) ; g2d . dispose ( ) ; return tmp ; }
Rotates an image .
32,281
public static Image getClipboardImage ( ) { Clipboard clipboard = Toolkit . getDefaultToolkit ( ) . getSystemClipboard ( ) ; try { return ( Image ) clipboard . getData ( DataFlavor . imageFlavor ) ; } catch ( Exception e ) { return null ; } }
Gets an image from Clipboard .
32,282
public static BufferedImage rotate ( BufferedImage image , double angle , int cx , int cy ) { int width = image . getWidth ( null ) ; int height = image . getHeight ( null ) ; int minX , minY , maxX , maxY ; minX = minY = maxX = maxY = 0 ; int [ ] corners = { 0 , 0 , width , 0 , width , height , 0 , height } ; double theta = Math . toRadians ( angle ) ; for ( int i = 0 ; i < corners . length ; i += 2 ) { int x = ( int ) ( Math . cos ( theta ) * ( corners [ i ] - cx ) - Math . sin ( theta ) * ( corners [ i + 1 ] - cy ) + cx ) ; int y = ( int ) ( Math . sin ( theta ) * ( corners [ i ] - cx ) + Math . cos ( theta ) * ( corners [ i + 1 ] - cy ) + cy ) ; if ( x > maxX ) { maxX = x ; } if ( x < minX ) { minX = x ; } if ( y > maxY ) { maxY = y ; } if ( y < minY ) { minY = y ; } } cx = ( cx - minX ) ; cy = ( cy - minY ) ; BufferedImage bi = new BufferedImage ( ( maxX - minX ) , ( maxY - minY ) , image . getType ( ) ) ; Graphics2D g2 = bi . createGraphics ( ) ; g2 . setRenderingHint ( RenderingHints . KEY_INTERPOLATION , RenderingHints . VALUE_INTERPOLATION_BICUBIC ) ; g2 . setBackground ( Color . white ) ; g2 . fillRect ( 0 , 0 , bi . getWidth ( ) , bi . getHeight ( ) ) ; AffineTransform at = new AffineTransform ( ) ; at . rotate ( theta , cx , cy ) ; g2 . setTransform ( at ) ; g2 . drawImage ( image , - minX , - minY , null ) ; g2 . dispose ( ) ; return bi ; }
Rotates image .
32,283
public static void writeFile ( byte [ ] data , File outFile ) throws IOException { if ( outFile . getParentFile ( ) != null ) { outFile . getParentFile ( ) . mkdirs ( ) ; } try ( FileOutputStream fos = new FileOutputStream ( outFile ) ) { fos . write ( data ) ; } }
Writes byte array to file .
32,284
public static String getConstantName ( Object value , Class c ) { for ( Field f : c . getDeclaredFields ( ) ) { int mod = f . getModifiers ( ) ; if ( Modifier . isStatic ( mod ) && Modifier . isPublic ( mod ) && Modifier . isFinal ( mod ) ) { try { if ( f . get ( null ) . equals ( value ) ) { return f . getName ( ) ; } } catch ( IllegalAccessException e ) { return String . valueOf ( value ) ; } } } return String . valueOf ( value ) ; }
Gets user - friendly name of the public static final constant defined in a class or an interface for display purpose .
32,285
protected void setImage ( int xsize , int ysize , ByteBuffer buf , Rectangle rect , int bpp ) { int bytespp = bpp / 8 ; int bytespl = ( int ) Math . ceil ( xsize * bpp / 8.0 ) ; api . TessBaseAPISetImage ( handle , buf , xsize , ysize , bytespp , bytespl ) ; if ( rect != null && ! rect . isEmpty ( ) ) { api . TessBaseAPISetRectangle ( handle , rect . x , rect . y , rect . width , rect . height ) ; } }
Sets image to be processed .
32,286
protected String getOCRText ( String filename , int pageNum ) { if ( filename != null && ! filename . isEmpty ( ) ) { api . TessBaseAPISetInputName ( handle , filename ) ; } Pointer utf8Text = renderedFormat == RenderedFormat . HOCR ? api . TessBaseAPIGetHOCRText ( handle , pageNum - 1 ) : api . TessBaseAPIGetUTF8Text ( handle ) ; String str = utf8Text . getString ( 0 ) ; api . TessDeleteText ( utf8Text ) ; return str ; }
Gets recognized text .
32,287
private TessResultRenderer createRenderers ( String outputbase , List < RenderedFormat > formats ) { TessResultRenderer renderer = null ; for ( RenderedFormat format : formats ) { switch ( format ) { case TEXT : if ( renderer == null ) { renderer = api . TessTextRendererCreate ( outputbase ) ; } else { api . TessResultRendererInsert ( renderer , api . TessTextRendererCreate ( outputbase ) ) ; } break ; case HOCR : if ( renderer == null ) { renderer = api . TessHOcrRendererCreate ( outputbase ) ; } else { api . TessResultRendererInsert ( renderer , api . TessHOcrRendererCreate ( outputbase ) ) ; } break ; case PDF : String dataPath = api . TessBaseAPIGetDatapath ( handle ) ; boolean textonly = String . valueOf ( TRUE ) . equals ( prop . getProperty ( "textonly_pdf" ) ) ; if ( renderer == null ) { renderer = api . TessPDFRendererCreate ( outputbase , dataPath , textonly ? TRUE : FALSE ) ; } else { api . TessResultRendererInsert ( renderer , api . TessPDFRendererCreate ( outputbase , dataPath , textonly ? TRUE : FALSE ) ) ; } break ; case BOX : if ( renderer == null ) { renderer = api . TessBoxTextRendererCreate ( outputbase ) ; } else { api . TessResultRendererInsert ( renderer , api . TessBoxTextRendererCreate ( outputbase ) ) ; } break ; case UNLV : if ( renderer == null ) { renderer = api . TessUnlvRendererCreate ( outputbase ) ; } else { api . TessResultRendererInsert ( renderer , api . TessUnlvRendererCreate ( outputbase ) ) ; } break ; case ALTO : if ( renderer == null ) { renderer = api . TessAltoRendererCreate ( outputbase ) ; } else { api . TessResultRendererInsert ( renderer , api . TessAltoRendererCreate ( outputbase ) ) ; } break ; case TSV : if ( renderer == null ) { renderer = api . TessTsvRendererCreate ( outputbase ) ; } else { api . TessResultRendererInsert ( renderer , api . TessTsvRendererCreate ( outputbase ) ) ; } break ; case LSTMBOX : if ( renderer == null ) { renderer = api . TessLSTMBoxRendererCreate ( outputbase ) ; } else { api . TessResultRendererInsert ( renderer , api . TessLSTMBoxRendererCreate ( outputbase ) ) ; } break ; case WORDSTRBOX : if ( renderer == null ) { renderer = api . TessWordStrBoxRendererCreate ( outputbase ) ; } else { api . TessResultRendererInsert ( renderer , api . TessWordStrBoxRendererCreate ( outputbase ) ) ; } break ; } } return renderer ; }
Creates renderers for given formats .
32,288
private List < Word > getRecognizedWords ( int pageIteratorLevel ) { List < Word > words = new ArrayList < Word > ( ) ; try { TessResultIterator ri = api . TessBaseAPIGetIterator ( handle ) ; TessPageIterator pi = api . TessResultIteratorGetPageIterator ( ri ) ; api . TessPageIteratorBegin ( pi ) ; do { Pointer ptr = api . TessResultIteratorGetUTF8Text ( ri , pageIteratorLevel ) ; String text = ptr . getString ( 0 ) ; api . TessDeleteText ( ptr ) ; float confidence = api . TessResultIteratorConfidence ( ri , pageIteratorLevel ) ; IntBuffer leftB = IntBuffer . allocate ( 1 ) ; IntBuffer topB = IntBuffer . allocate ( 1 ) ; IntBuffer rightB = IntBuffer . allocate ( 1 ) ; IntBuffer bottomB = IntBuffer . allocate ( 1 ) ; api . TessPageIteratorBoundingBox ( pi , pageIteratorLevel , leftB , topB , rightB , bottomB ) ; int left = leftB . get ( ) ; int top = topB . get ( ) ; int right = rightB . get ( ) ; int bottom = bottomB . get ( ) ; Word word = new Word ( text , confidence , new Rectangle ( left , top , right - left , bottom - top ) ) ; words . add ( word ) ; } while ( api . TessPageIteratorNext ( pi , pageIteratorLevel ) == TRUE ) ; } catch ( Exception e ) { logger . warn ( e . getMessage ( ) , e ) ; } return words ; }
Gets result words at specified page iterator level from recognized pages .
32,289
protected void initInstanceRevisionAndJanitor ( ) throws Exception { databaseRevision = new DatabaseRevision ( ) ; long localFileRevision = 0L ; if ( getRevision ( ) != null ) { InstanceRevision currentFileRevision = new FileRevision ( new File ( getRevision ( ) ) , true ) ; localFileRevision = currentFileRevision . get ( ) ; currentFileRevision . close ( ) ; } long localRevision = databaseRevision . init ( localFileRevision ) ; log . info ( "Initialized local revision to " + localRevision ) ; if ( janitorEnabled ) { janitorThread = new Thread ( new RevisionTableJanitor ( ) , "Jackrabbit-ClusterRevisionJanitor" ) ; janitorThread . setDaemon ( true ) ; janitorThread . start ( ) ; log . info ( "Cluster revision janitor thread started; first run scheduled at " + janitorNextRun . getTime ( ) ) ; } else { log . info ( "Cluster revision janitor thread not started" ) ; } }
Initialize the instance revision manager and the janitor thread .
32,290
protected void append ( AppendRecord record , InputStream in , int length ) throws JournalException { try { conHelper . exec ( insertRevisionStmtSQL , record . getRevision ( ) , getId ( ) , record . getProducerId ( ) , new StreamWrapper ( in , length ) ) ; } catch ( SQLException e ) { String msg = "Unable to append revision " + lockedRevision + "." ; throw new JournalException ( msg , e ) ; } }
We have already saved away the revision for this record .
32,291
private void checkLocalRevisionSchema ( ) throws Exception { InputStream localRevisionDDLStream = null ; InputStream in = org . apache . jackrabbit . core . journal . DatabaseJournal . class . getResourceAsStream ( databaseType + ".ddl" ) ; try { BufferedReader reader = new BufferedReader ( new InputStreamReader ( in ) ) ; String sql = reader . readLine ( ) ; while ( sql != null ) { if ( ! sql . startsWith ( "#" ) && sql . length ( ) > 0 && sql . indexOf ( LOCAL_REVISIONS_TABLE ) != - 1 ) { localRevisionDDLStream = new ByteArrayInputStream ( sql . getBytes ( ) ) ; break ; } sql = reader . readLine ( ) ; } } finally { IOUtils . closeQuietly ( in ) ; } new CheckSchemaOperation ( conHelper , localRevisionDDLStream , schemaObjectPrefix + LOCAL_REVISIONS_TABLE ) . addVariableReplacement ( CheckSchemaOperation . SCHEMA_OBJECT_PREFIX_VARIABLE , schemaObjectPrefix ) . run ( ) ; }
Checks if the local revision schema objects exist and creates them if they don t exist yet .
32,292
public StringIndex getNameIndex ( ) { try { if ( nameIndex == null ) { FileSystemResource res = new FileSystemResource ( context . getFileSystem ( ) , RES_NAME_INDEX ) ; if ( res . exists ( ) ) { nameIndex = super . getNameIndex ( ) ; } else { nameIndex = createDbNameIndex ( ) ; } } return nameIndex ; } catch ( Exception e ) { IllegalStateException exception = new IllegalStateException ( "Unable to create nsIndex" ) ; exception . initCause ( e ) ; throw exception ; } }
Returns the local name index
32,293
protected Object [ ] getKey ( NodeId id ) { if ( getStorageModel ( ) == SM_BINARY_KEYS ) { return new Object [ ] { id . getRawBytes ( ) } ; } else { return new Object [ ] { id . getMostSignificantBits ( ) , id . getLeastSignificantBits ( ) } ; } }
Constructs a parameter list for a PreparedStatement for the given node identifier .
32,294
private NodePropBundle readBundle ( NodeId id , ResultSet rs , int column ) throws SQLException { try { InputStream in ; if ( rs . getMetaData ( ) . getColumnType ( column ) == Types . BLOB ) { in = rs . getBlob ( column ) . getBinaryStream ( ) ; } else { in = rs . getBinaryStream ( column ) ; } try { return binding . readBundle ( in , id ) ; } finally { in . close ( ) ; } } catch ( IOException e ) { SQLException exception = new SQLException ( "Failed to parse bundle " + id ) ; exception . initCause ( e ) ; throw exception ; } }
Reads and parses a bundle from the BLOB in the given column of the current row of the given result set . This is a helper method to circumvent issues JCR - 1039 and JCR - 1474 .
32,295
protected void buildSQLStatements ( ) { if ( getStorageModel ( ) == SM_BINARY_KEYS ) { bundleInsertSQL = "insert into " + schemaObjectPrefix + "BUNDLE (BUNDLE_DATA, NODE_ID) values (?, ?)" ; bundleUpdateSQL = "update " + schemaObjectPrefix + "BUNDLE set BUNDLE_DATA = ? where NODE_ID = ?" ; bundleSelectSQL = "select BUNDLE_DATA from " + schemaObjectPrefix + "BUNDLE where NODE_ID = ?" ; bundleDeleteSQL = "delete from " + schemaObjectPrefix + "BUNDLE where NODE_ID = ?" ; nodeReferenceInsertSQL = "insert into " + schemaObjectPrefix + "REFS (REFS_DATA, NODE_ID) values (?, ?)" ; nodeReferenceUpdateSQL = "update " + schemaObjectPrefix + "REFS set REFS_DATA = ? where NODE_ID = ?" ; nodeReferenceSelectSQL = "select REFS_DATA from " + schemaObjectPrefix + "REFS where NODE_ID = ?" ; nodeReferenceDeleteSQL = "delete from " + schemaObjectPrefix + "REFS where NODE_ID = ?" ; bundleSelectAllIdsSQL = "select NODE_ID from " + schemaObjectPrefix + "BUNDLE ORDER BY NODE_ID" ; bundleSelectAllIdsFromSQL = "select NODE_ID from " + schemaObjectPrefix + "BUNDLE WHERE NODE_ID > ? ORDER BY NODE_ID" ; bundleSelectAllBundlesSQL = "select NODE_ID, BUNDLE_DATA from " + schemaObjectPrefix + "BUNDLE ORDER BY NODE_ID" ; bundleSelectAllBundlesFromSQL = "select NODE_ID, BUNDLE_DATA from " + schemaObjectPrefix + "BUNDLE WHERE NODE_ID > ? ORDER BY NODE_ID" ; } else { bundleInsertSQL = "insert into " + schemaObjectPrefix + "BUNDLE (BUNDLE_DATA, NODE_ID_HI, NODE_ID_LO) values (?, ?, ?)" ; bundleUpdateSQL = "update " + schemaObjectPrefix + "BUNDLE set BUNDLE_DATA = ? where NODE_ID_HI = ? and NODE_ID_LO = ?" ; bundleSelectSQL = "select BUNDLE_DATA from " + schemaObjectPrefix + "BUNDLE where NODE_ID_HI = ? and NODE_ID_LO = ?" ; bundleDeleteSQL = "delete from " + schemaObjectPrefix + "BUNDLE where NODE_ID_HI = ? and NODE_ID_LO = ?" ; nodeReferenceInsertSQL = "insert into " + schemaObjectPrefix + "REFS" + " (REFS_DATA, NODE_ID_HI, NODE_ID_LO) values (?, ?, ?)" ; nodeReferenceUpdateSQL = "update " + schemaObjectPrefix + "REFS" + " set REFS_DATA = ? where NODE_ID_HI = ? and NODE_ID_LO = ?" ; nodeReferenceSelectSQL = "select REFS_DATA from " + schemaObjectPrefix + "REFS where NODE_ID_HI = ? and NODE_ID_LO = ?" ; nodeReferenceDeleteSQL = "delete from " + schemaObjectPrefix + "REFS where NODE_ID_HI = ? and NODE_ID_LO = ?" ; bundleSelectAllIdsSQL = "select NODE_ID_HI, NODE_ID_LO from " + schemaObjectPrefix + "BUNDLE ORDER BY NODE_ID_HI, NODE_ID_LO" ; bundleSelectAllIdsFromSQL = "select NODE_ID_HI, NODE_ID_LO from " + schemaObjectPrefix + "BUNDLE" + " WHERE (NODE_ID_HI >= ?) AND (? IS NOT NULL)" + " ORDER BY NODE_ID_HI, NODE_ID_LO" ; bundleSelectAllBundlesSQL = "select NODE_ID_HI, NODE_ID_LO, BUNDLE_DATA from " + schemaObjectPrefix + "BUNDLE ORDER BY NODE_ID_HI, NODE_ID_LO" ; bundleSelectAllBundlesFromSQL = "select NODE_ID_HI, NODE_ID_LO, BUNDLE_DATA from " + schemaObjectPrefix + "BUNDLE" + " WHERE (NODE_ID_HI >= ?) AND (? IS NOT NULL)" + " ORDER BY NODE_ID_HI, NODE_ID_LO" ; } }
Initializes the SQL strings .
32,296
private void fetchRecord ( ) throws SQLException { if ( rs . next ( ) ) { long revision = rs . getLong ( 1 ) ; String journalId = rs . getString ( 2 ) ; String producerId = rs . getString ( 3 ) ; DataInputStream dataIn = new DataInputStream ( rs . getBinaryStream ( 4 ) ) ; record = new ReadRecord ( journalId , producerId , revision , dataIn , 0 , resolver , npResolver ) ; } else { isEOF = true ; } }
Fetch the next record .
32,297
private static void close ( ReadRecord record ) { if ( record != null ) { try { record . close ( ) ; } catch ( IOException e ) { String msg = "Error while closing record." ; log . warn ( msg , e ) ; } } }
Close a record .
32,298
public void setTableSpace ( String tableSpace ) { if ( tableSpace != null && tableSpace . length ( ) > 0 ) { this . tableSpace = "on " + tableSpace . trim ( ) ; } else { this . tableSpace = "" ; } }
Sets the MS SQL table space .
32,299
public AttrReq addAttrReq ( String name ) throws InvalidArgumentException { if ( name == null || name . isEmpty ( ) ) { throw new InvalidArgumentException ( "name may not be null or empty." ) ; } return new AttrReq ( name ) ; }
Add attribute to certificate .