idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
34,500
public final Timestamp addDay ( int amount ) { long delta = ( long ) amount * 24 * 60 * 60 * 1000 ; return addMillisForPrecision ( delta , Precision . DAY , false ) ; }
Returns a timestamp relative to this one by the given number of days .
34,501
public static void printStringCodePoint ( Appendable out , int codePoint ) throws IOException { printCodePoint ( out , codePoint , EscapeMode . ION_STRING ) ; }
Prints a single Unicode code point for use in an ASCII - safe Ion string .
34,502
public static void printSymbolCodePoint ( Appendable out , int codePoint ) throws IOException { printCodePoint ( out , codePoint , EscapeMode . ION_SYMBOL ) ; }
Prints a single Unicode code point for use in an ASCII - safe Ion symbol .
34,503
public static void printJsonCodePoint ( Appendable out , int codePoint ) throws IOException { printCodePoint ( out , codePoint , EscapeMode . JSON ) ; }
Prints a single Unicode code point for use in an ASCII - safe JSON string .
34,504
private static void printCodePoint ( Appendable out , int c , EscapeMode mode ) throws IOException { switch ( c ) { case 0 : out . append ( mode == EscapeMode . JSON ? "\\u0000" : "\\0" ) ; return ; case '\t' : out . append ( "\\t" ) ; return ; case '\n' : if ( mode == EscapeMode . ION_LONG_STRING ) { out . append ( '\n' ) ; } else { out . append ( "\\n" ) ; } return ; case '\r' : out . append ( "\\r" ) ; return ; case '\f' : out . append ( "\\f" ) ; return ; case '\u0008' : out . append ( "\\b" ) ; return ; case '\u0007' : out . append ( mode == EscapeMode . JSON ? "\\u0007" : "\\a" ) ; return ; case '\u000B' : out . append ( mode == EscapeMode . JSON ? "\\u000b" : "\\v" ) ; return ; case '\"' : if ( mode == EscapeMode . JSON || mode == EscapeMode . ION_STRING ) { out . append ( "\\\"" ) ; return ; } break ; case '\'' : if ( mode == EscapeMode . ION_SYMBOL || mode == EscapeMode . ION_LONG_STRING ) { out . append ( "\\\'" ) ; return ; } break ; case '\\' : out . append ( "\\\\" ) ; return ; default : break ; } if ( c < 32 ) { if ( mode == EscapeMode . JSON ) { printCodePointAsFourHexDigits ( out , c ) ; } else { printCodePointAsTwoHexDigits ( out , c ) ; } } else if ( c < 0x7F ) { out . append ( ( char ) c ) ; } else if ( c <= 0xFF ) { if ( mode == EscapeMode . JSON ) { printCodePointAsFourHexDigits ( out , c ) ; } else { printCodePointAsTwoHexDigits ( out , c ) ; } } else if ( c <= 0xFFFF ) { printCodePointAsFourHexDigits ( out , c ) ; } else { if ( mode == EscapeMode . JSON ) { printCodePointAsSurrogatePairHexDigits ( out , c ) ; } else { printCodePointAsEightHexDigits ( out , c ) ; } } }
Prints a single code point ASCII safe .
34,505
public static String printCodePointAsString ( int codePoint ) { StringBuilder builder = new StringBuilder ( 12 ) ; builder . append ( '"' ) ; try { printStringCodePoint ( builder , codePoint ) ; } catch ( IOException e ) { throw new Error ( e ) ; } builder . append ( '"' ) ; return builder . toString ( ) ; }
Builds a String denoting an ASCII - encoded Ion string with double - quotes surrounding a single Unicode code point .
34,506
public void truncate ( final long position ) { final int index = index ( position ) ; final int offset = offset ( position ) ; final Block block = blocks . get ( index ) ; this . index = index ; block . limit = offset ; current = block ; }
Resets the write buffer to a particular point .
34,507
public int getUInt8At ( final long position ) { final int index = index ( position ) ; final int offset = offset ( position ) ; final Block block = blocks . get ( index ) ; return block . data [ offset ] & OCTET_MASK ; }
Returns the octet at the logical position given .
34,508
public void writeByte ( final byte octet ) { if ( remaining ( ) < 1 ) { if ( index == blocks . size ( ) - 1 ) { allocateNewBlock ( ) ; } index ++ ; current = blocks . get ( index ) ; } final Block block = current ; block . data [ block . limit ] = octet ; block . limit ++ ; }
Writes a single octet to the buffer expanding if necessary .
34,509
private void writeBytesSlow ( final byte [ ] bytes , int off , int len ) { while ( len > 0 ) { final Block block = current ; final int amount = Math . min ( len , block . remaining ( ) ) ; System . arraycopy ( bytes , off , block . data , block . limit , amount ) ; block . limit += amount ; off += amount ; len -= amount ; if ( block . remaining ( ) == 0 ) { if ( index == blocks . size ( ) - 1 ) { allocateNewBlock ( ) ; } index ++ ; current = blocks . get ( index ) ; } } }
slow in the sense that we do all kind of block boundary checking
34,510
public void writeBytes ( final byte [ ] bytes , final int off , final int len ) { if ( len > remaining ( ) ) { writeBytesSlow ( bytes , off , len ) ; return ; } final Block block = current ; System . arraycopy ( bytes , off , block . data , block . limit , len ) ; block . limit += len ; }
Writes an array of bytes to the buffer expanding if necessary .
34,511
private int writeUTF8Slow ( final CharSequence chars , int off , int len ) { int octets = 0 ; while ( len > 0 ) { final char ch = chars . charAt ( off ) ; if ( ch >= LOW_SURROGATE_FIRST && ch <= LOW_SURROGATE_LAST ) { throw new IllegalArgumentException ( "Unpaired low surrogate: " + ( int ) ch ) ; } if ( ( ch >= HIGH_SURROGATE_FIRST && ch <= HIGH_SURROGATE_LAST ) ) { off ++ ; len -- ; if ( len == 0 ) { throw new IllegalArgumentException ( "Unpaired low surrogate at end of character sequence: " + ch ) ; } final int ch2 = chars . charAt ( off ) ; if ( ch2 < LOW_SURROGATE_FIRST || ch2 > LOW_SURROGATE_LAST ) { throw new IllegalArgumentException ( "Low surrogate with unpaired high surrogate: " + ch + " + " + ch2 ) ; } final int codepoint = ( ( ( ch - HIGH_SURROGATE_FIRST ) << BITS_PER_SURROGATE ) | ( ch2 - LOW_SURROGATE_FIRST ) ) + SURROGATE_BASE ; writeByte ( ( byte ) ( UTF8_4_OCTET_PREFIX_MASK | ( codepoint >> UTF8_4_OCTET_SHIFT ) ) ) ; writeByte ( ( byte ) ( UTF8_FOLLOW_PREFIX_MASK | ( ( codepoint >> UTF8_3_OCTET_SHIFT ) & UTF8_FOLLOW_MASK ) ) ) ; writeByte ( ( byte ) ( UTF8_FOLLOW_PREFIX_MASK | ( ( codepoint >> UTF8_2_OCTET_SHIFT ) & UTF8_FOLLOW_MASK ) ) ) ; writeByte ( ( byte ) ( UTF8_FOLLOW_PREFIX_MASK | ( codepoint & UTF8_FOLLOW_MASK ) ) ) ; octets += 4 ; } else if ( ch < UTF8_2_OCTET_MIN_VALUE ) { writeByte ( ( byte ) ch ) ; octets ++ ; } else if ( ch < UTF8_3_OCTET_MIN_VALUE ) { writeByte ( ( byte ) ( UTF8_2_OCTET_PREFIX_MASK | ( ch >> UTF8_2_OCTET_SHIFT ) ) ) ; writeByte ( ( byte ) ( UTF8_FOLLOW_PREFIX_MASK | ( ch & UTF8_FOLLOW_MASK ) ) ) ; octets += 2 ; } else { writeByte ( ( byte ) ( UTF8_3_OCTET_PREFIX_MASK | ( ch >> UTF8_3_OCTET_SHIFT ) ) ) ; writeByte ( ( byte ) ( UTF8_FOLLOW_PREFIX_MASK | ( ( ch >> UTF8_2_OCTET_SHIFT ) & UTF8_FOLLOW_MASK ) ) ) ; writeByte ( ( byte ) ( UTF8_FOLLOW_PREFIX_MASK | ( ch & UTF8_FOLLOW_MASK ) ) ) ; octets += 3 ; } off ++ ; len -- ; } return octets ; }
slow in the sense that we deal with any kind of UTF - 8 sequence and block boundaries
34,512
public void writeTo ( final OutputStream out ) throws IOException { for ( int i = 0 ; i <= index ; i ++ ) { Block block = blocks . get ( i ) ; out . write ( block . data , 0 , block . limit ) ; } }
Write the entire buffer to output stream .
34,513
public void writeTo ( final OutputStream out , long position , long length ) throws IOException { while ( length > 0 ) { final int index = index ( position ) ; final int offset = offset ( position ) ; final Block block = blocks . get ( index ) ; final int amount = ( int ) Math . min ( block . data . length - offset , length ) ; out . write ( block . data , offset , amount ) ; position += amount ; length -= amount ; } }
Write a specific segment of data from the buffer to a stream .
34,514
public static _Private_IonTextAppender forAppendable ( Appendable out ) { _Private_FastAppendable fast = new AppendableFastAppendable ( out ) ; boolean escapeNonAscii = false ; return new _Private_IonTextAppender ( fast , escapeNonAscii ) ; }
Doesn t escape non - ASCII characters .
34,515
public final void printString ( CharSequence text ) throws IOException { if ( text == null ) { appendAscii ( "null.string" ) ; } else { appendAscii ( '"' ) ; printCodePoints ( text , STRING_ESCAPE_CODES ) ; appendAscii ( '"' ) ; } }
Print an Ion String type
34,516
public final void printLongString ( CharSequence text ) throws IOException { if ( text == null ) { appendAscii ( "null.string" ) ; } else { appendAscii ( TRIPLE_QUOTES ) ; printCodePoints ( text , LONG_STRING_ESCAPE_CODES ) ; appendAscii ( TRIPLE_QUOTES ) ; } }
Print an Ion triple - quoted string
34,517
public final void printJsonString ( CharSequence text ) throws IOException { if ( text == null ) { appendAscii ( "null" ) ; } else { appendAscii ( '"' ) ; printCodePoints ( text , JSON_ESCAPE_CODES ) ; appendAscii ( '"' ) ; } }
Print a JSON string
34,518
public final void printSymbol ( CharSequence text ) throws IOException { if ( text == null ) { appendAscii ( "null.symbol" ) ; } else if ( symbolNeedsQuoting ( text , true ) ) { appendAscii ( '\'' ) ; printCodePoints ( text , SYMBOL_ESCAPE_CODES ) ; appendAscii ( '\'' ) ; } else { appendAscii ( text ) ; } }
Print an Ion Symbol type . This method will check if symbol needs quoting
34,519
public final void printQuotedSymbol ( CharSequence text ) throws IOException { if ( text == null ) { appendAscii ( "null.symbol" ) ; } else { appendAscii ( '\'' ) ; printCodePoints ( text , SYMBOL_ESCAPE_CODES ) ; appendAscii ( '\'' ) ; } }
Print single - quoted Ion Symbol type
34,520
public SymbolTable getSymbolTable ( ) { SymbolTable symtab = super . getSymbolTable ( ) ; if ( symtab == null ) { symtab = _system_symtab ; } return symtab ; }
Horrible temporary hack .
34,521
public _Private_IonManagedBinaryWriterBuilder withFlatImports ( final SymbolTable ... tables ) { if ( tables != null ) { return withFlatImports ( Arrays . asList ( tables ) ) ; } return this ; }
Adds imports flattening them to make lookup more efficient . This is particularly useful when a builder instance is long lived .
34,522
public void writeValue ( IonReader reader ) throws IOException { IonType type = reader . getType ( ) ; writeValueRecursively ( type , reader ) ; }
Overrides can optimize special cases .
34,523
boolean attemptClearSymbolIDValues ( ) { boolean sidsRemain = false ; if ( _fieldName != null ) { _fieldId = UNKNOWN_SYMBOL_ID ; } else if ( _fieldId > UNKNOWN_SYMBOL_ID ) { sidsRemain = true ; } if ( _annotations != null ) { for ( int i = 0 ; i < _annotations . length ; i ++ ) { SymbolToken annotation = _annotations [ i ] ; if ( annotation == null ) break ; String text = annotation . getText ( ) ; if ( text != null && annotation . getSid ( ) != UNKNOWN_SYMBOL_ID ) { _annotations [ i ] = newSymbolToken ( text , UNKNOWN_SYMBOL_ID ) ; } } } return ! sidsRemain ; }
Sets this value s symbol table to null and erases any SIDs here and recursively .
34,524
final void setFieldNameSymbol ( SymbolToken name ) { assert _fieldId == UNKNOWN_SYMBOL_ID && _fieldName == null ; _fieldName = name . getText ( ) ; _fieldId = name . getSid ( ) ; if ( UNKNOWN_SYMBOL_ID != _fieldId && ! _isSymbolIdPresent ( ) ) { cascadeSIDPresentToContextRoot ( ) ; } }
Sets the field name and ID based on a SymbolToken . Both parts of the SymbolToken are trusted!
34,525
final void detachFromContainer ( ) { checkForLock ( ) ; clearSymbolIDValues ( ) ; _context = ContainerlessContext . wrap ( getSystem ( ) ) ; _fieldName = null ; _fieldId = UNKNOWN_SYMBOL_ID ; _elementid ( 0 ) ; }
Removes this value from its container ensuring that all data stays available . Dirties this value and it s original container .
34,526
public final static int convertToUTF8Bytes ( int unicodeScalar , byte [ ] outputBytes , int offset , int maxLength ) { int dst = offset ; int end = offset + maxLength ; switch ( getUTF8ByteCount ( unicodeScalar ) ) { case 1 : if ( dst >= end ) throw new ArrayIndexOutOfBoundsException ( ) ; outputBytes [ dst ++ ] = ( byte ) ( unicodeScalar & 0xff ) ; break ; case 2 : if ( dst + 1 >= end ) throw new ArrayIndexOutOfBoundsException ( ) ; outputBytes [ dst ++ ] = getByte1Of2 ( unicodeScalar ) ; outputBytes [ dst ++ ] = getByte2Of2 ( unicodeScalar ) ; break ; case 3 : if ( dst + 2 >= end ) throw new ArrayIndexOutOfBoundsException ( ) ; outputBytes [ dst ++ ] = getByte1Of3 ( unicodeScalar ) ; outputBytes [ dst ++ ] = getByte2Of3 ( unicodeScalar ) ; outputBytes [ dst ++ ] = getByte3Of3 ( unicodeScalar ) ; break ; case 4 : if ( dst + 3 >= end ) throw new ArrayIndexOutOfBoundsException ( ) ; outputBytes [ dst ++ ] = getByte1Of4 ( unicodeScalar ) ; outputBytes [ dst ++ ] = getByte2Of4 ( unicodeScalar ) ; outputBytes [ dst ++ ] = getByte3Of4 ( unicodeScalar ) ; outputBytes [ dst ++ ] = getByte4Of4 ( unicodeScalar ) ; break ; } return dst - offset ; }
this helper converts the unicodeScalar to a sequence of utf8 bytes and copies those bytes into the supplied outputBytes array . If there is insufficient room in the array to hold the generated bytes it will throw an ArrayIndexOutOfBoundsException . It does not check for the validity of the passed in unicodeScalar thoroughly however it will throw an InvalidUnicodeCodePoint if the value is less than negative or the UTF8 encoding would exceed 4 bytes .
34,527
public byte [ ] getBytes ( ) { int length = _eob - _start ; byte [ ] copy = new byte [ length ] ; System . arraycopy ( _bytes , _start , copy , 0 , length ) ; return copy ; }
Makes a copy of the internal byte array .
34,528
private void prepareValue ( ) { if ( isInStruct ( ) && currentFieldSid == null ) { throw new IllegalStateException ( "IonWriter.setFieldName() must be called before writing a value into a struct." ) ; } if ( currentFieldSid != null ) { checkSid ( currentFieldSid ) ; writeVarUInt ( currentFieldSid ) ; currentFieldSid = null ; } if ( ! currentAnnotationSids . isEmpty ( ) ) { updateLength ( preallocationMode . typedLength ) ; pushContainer ( ContainerType . ANNOTATION ) ; buffer . writeBytes ( preallocationMode . annotationsTypedPreallocatedBytes ) ; final long annotationsLengthPosition = buffer . position ( ) ; buffer . writeVarUInt ( 0L ) ; int annotationsLength = 0 ; for ( final int symbol : currentAnnotationSids ) { checkSid ( symbol ) ; final int symbolLength = buffer . writeVarUInt ( symbol ) ; annotationsLength += symbolLength ; } if ( annotationsLength > MAX_ANNOTATION_LENGTH ) { throw new IonException ( "Annotations too large: " + currentAnnotationSids ) ; } updateLength ( 1 + annotationsLength ) ; buffer . writeVarUIntDirect1At ( annotationsLengthPosition , annotationsLength ) ; currentAnnotationSids . clear ( ) ; hasTopLevelSymbolTableAnnotation = false ; } }
prepare to write values with field name and annotations .
34,529
private void finishValue ( ) { final ContainerInfo current = currentContainer ( ) ; if ( current != null && current . type == ContainerType . ANNOTATION ) { popContainer ( ) ; } hasWrittenValuesSinceFinished = true ; hasWrittenValuesSinceConstructed = true ; }
Closes out annotations .
34,530
public static SymbolToken symbol ( final String name , final int val ) { if ( name == null ) { throw new NullPointerException ( ) ; } if ( val <= 0 ) { throw new IllegalArgumentException ( "Symbol value must be positive: " + val ) ; } return new SymbolToken ( ) { public String getText ( ) { return name ; } public String assumeText ( ) { return name ; } public int getSid ( ) { return val ; } public String toString ( ) { return "(symbol '" + getText ( ) + "' " + getSid ( ) + ")" ; } } ; }
Constructs a token with a non - null name and positive value .
34,531
public static Iterator < String > symbolNameIterator ( final Iterator < SymbolToken > tokenIter ) { return new Iterator < String > ( ) { public boolean hasNext ( ) { return tokenIter . hasNext ( ) ; } public String next ( ) { return tokenIter . next ( ) . getText ( ) ; } public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; }
Lazy iterator over the symbol names of an iterator of symbol tokens .
34,532
public static SymbolToken systemSymbol ( final int sid ) { if ( sid < 1 || sid > ION_1_0_MAX_ID ) { throw new IllegalArgumentException ( "No such system SID: " + sid ) ; } return SYSTEM_TOKENS . get ( sid - 1 ) ; }
Returns a symbol token for a system SID .
34,533
public static SymbolTable unknownSharedSymbolTable ( final String name , final int version , final int maxId ) { return new AbstractSymbolTable ( name , version ) { public Iterator < String > iterateDeclaredSymbolNames ( ) { return new Iterator < String > ( ) { int id = 1 ; public boolean hasNext ( ) { return id <= maxId ; } public String next ( ) { if ( ! hasNext ( ) ) { throw new NoSuchElementException ( ) ; } id ++ ; return null ; } public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; } public boolean isSystemTable ( ) { return false ; } public boolean isSubstitute ( ) { return true ; } public boolean isSharedTable ( ) { return true ; } public boolean isReadOnly ( ) { return true ; } public boolean isLocalTable ( ) { return false ; } public SymbolToken intern ( String text ) { throw new UnsupportedOperationException ( "Cannot intern into substitute unknown shared symbol table: " + name + " version " + version ) ; } public SymbolTable getSystemSymbolTable ( ) { return systemSymbolTable ( ) ; } public int getMaxId ( ) { return maxId ; } public SymbolTable [ ] getImportedTables ( ) { return null ; } public int getImportedMaxId ( ) { return 0 ; } public String findKnownSymbol ( int id ) { return null ; } public SymbolToken find ( String text ) { return null ; } } ; }
Returns a substitute shared symbol table where none of the symbols are known .
34,534
public static void main ( String [ ] args ) throws IOException { process_command_line ( args ) ; info = new JarInfo ( ) ; if ( printVersion ) { doPrintVersion ( ) ; } if ( printHelp ) { doPrintHelp ( ) ; } }
This main simply prints the version information to allow users to identify the build version of the Jar .
34,535
public static IonSystem newSystem ( IonCatalog catalog ) { return IonSystemBuilder . standard ( ) . withCatalog ( catalog ) . build ( ) ; }
Constructs a new system instance with the given catalog .
34,536
protected void tokenValueIsFinished ( ) { _scanner . tokenIsFinished ( ) ; if ( IonType . BLOB . equals ( _value_type ) || IonType . CLOB . equals ( _value_type ) ) { int state_after_scalar = get_state_after_value ( ) ; set_state ( state_after_scalar ) ; } }
called by super classes to tell us that the current token has been consumed .
34,537
public boolean isInStruct ( ) { boolean in_struct = false ; IonType container = getContainerType ( ) ; if ( IonType . STRUCT . equals ( container ) ) { if ( getDepth ( ) > 0 ) { in_struct = true ; } else { assert ( IonType . STRUCT . equals ( _nesting_parent ) == true ) ; } } return in_struct ; }
we re not really in a struct we at the top level
34,538
private boolean is_in_struct_internal ( ) { boolean in_struct = false ; IonType container = getContainerType ( ) ; if ( IonType . STRUCT . equals ( container ) ) { in_struct = true ; } return in_struct ; }
have to ignore
34,539
public long getPosition ( ) { long file_pos = 0 ; UnifiedDataPageX page = _buffer . getCurrentPage ( ) ; if ( page != null ) { file_pos = page . getFilePosition ( _pos ) ; } return file_pos ; }
used to find the current position of this stream in the input source .
34,540
public final int read ( byte [ ] dst , int offset , int length ) throws IOException { if ( ! is_byte_data ( ) ) { throw new IOException ( "byte read is not support over character sources" ) ; } int remaining = length ; while ( remaining > 0 && ! isEOF ( ) ) { int ready = _limit - _pos ; if ( ready > remaining ) { ready = remaining ; } System . arraycopy ( _bytes , _pos , dst , offset , ready ) ; _pos += ready ; offset += ready ; remaining -= ready ; if ( remaining == 0 || _pos < _limit || refill_helper ( ) ) { break ; } } return length - remaining ; }
It is unclear what the implication to the rest of the system to make it conform
34,541
protected int refill ( ) throws IOException { UnifiedDataPageX curr = _buffer . getCurrentPage ( ) ; SavePoint sp = _save_points . savePointActiveTop ( ) ; if ( ! can_fill_new_page ( ) ) { return refill_is_eof ( ) ; } if ( sp != null && sp . getEndIdx ( ) == _buffer . getCurrentPageIdx ( ) ) { return refill_is_eof ( ) ; } long file_position ; int start_pos = UNREAD_LIMIT ; if ( curr == null ) { file_position = 0 ; start_pos = 0 ; } else { file_position = curr . getFilePosition ( _pos ) ; if ( file_position == 0 ) { start_pos = 0 ; } } int new_idx = _buffer . getNextFilledPageIdx ( ) ; if ( new_idx < 0 ) { curr = _buffer . getCurrentPage ( ) ; boolean needs_new_page = ( curr == null ) ; new_idx = _buffer . getCurrentPageIdx ( ) ; if ( _save_points . isSavePointOpen ( ) ) { new_idx ++ ; needs_new_page = true ; } if ( needs_new_page ) { curr = _buffer . getEmptyPageIdx ( ) ; } int read = load ( curr , start_pos , file_position ) ; if ( read < 1 ) { return refill_is_eof ( ) ; } assert ( curr != null && curr . getOffsetOfFilePosition ( file_position ) == start_pos ) ; set_current_page ( new_idx , curr , start_pos ) ; } else { assert ( ! isEOF ( ) ) ; if ( sp != null ) { int endidx = sp . getEndIdx ( ) ; if ( endidx != - 1 && endidx < new_idx ) { return refill_is_eof ( ) ; } } curr = _buffer . getPage ( new_idx ) ; assert ( curr . getStartingFileOffset ( ) == file_position ) ; set_current_page ( new_idx , curr , curr . getStartingOffset ( ) ) ; if ( sp != null && sp . getEndIdx ( ) == new_idx ) { _limit = sp . getEndPos ( ) ; } } assert ( isEOF ( ) ^ ( _limit > 0 ) ) ; return _limit ; }
the refill method is the key override that is filled in by the various subclasses . It fills either the byte or char array with a block of data from the input source . As this is a virtual function the right version will get called for each source type . Since it is only called once per block and from then on the final method which pulls data from the block can return the value this should be a reasonable performance trade off .
34,542
private bbBlock init ( int initialSize , bbBlock initialBlock ) { this . _lastCapacity = BlockedBuffer . _defaultBlockSizeMin ; this . _blockSizeUpperLimit = BlockedBuffer . _defaultBlockSizeUpperLimit ; while ( this . _lastCapacity < initialSize && this . _lastCapacity < this . _blockSizeUpperLimit ) { this . nextBlockSize ( this , 0 ) ; } int count = initialSize / this . _lastCapacity ; if ( initialBlock != null ) count = 1 ; this . _blocks = new ArrayList < bbBlock > ( count ) ; if ( initialBlock == null ) { initialBlock = new bbBlock ( this . nextBlockSize ( this , 0 ) ) ; } this . _blocks . add ( initialBlock ) ; this . _next_block_position = 1 ; bbBlock b ; for ( int need = initialSize - initialBlock . blockCapacity ( ) ; need > 0 ; need -= b . blockCapacity ( ) ) { b = new bbBlock ( this . nextBlockSize ( this , 0 ) ) ; b . _idx = - 1 ; this . _blocks . add ( b ) ; } return initialBlock ; }
Initializes the various members such as the block arraylist the initial block and the various values like the block size upper limit .
34,543
private void clear ( Object caller , int version ) { assert mutation_in_progress ( caller , version ) ; _buf_limit = 0 ; for ( int ii = 0 ; ii < _blocks . size ( ) ; ii ++ ) { _blocks . get ( ii ) . clearBlock ( ) ; } bbBlock first = _blocks . get ( 0 ) ; first . _idx = 0 ; first . _offset = 0 ; first . _limit = 0 ; _next_block_position = 1 ; return ; }
empties the entire contents of the buffer
34,544
bbBlock truncate ( Object caller , int version , int pos ) { assert mutation_in_progress ( caller , version ) ; if ( 0 > pos || pos > this . _buf_limit ) throw new IllegalArgumentException ( ) ; bbBlock b = null ; for ( int idx = this . _next_block_position - 1 ; idx >= 0 ; idx -- ) { b = this . _blocks . get ( idx ) ; if ( b . _offset <= pos ) break ; b . clearBlock ( ) ; } if ( b == null ) { throw new IllegalStateException ( "block missing at position " + pos ) ; } this . _next_block_position = b . _idx + 1 ; b . _limit = pos - b . _offset ; this . _buf_limit = pos ; b = this . findBlockForRead ( pos , version , b , pos ) ; return b ; }
treat the limit as the end of file
34,545
int insert ( Object caller , int version , bbBlock curr , int pos , int len ) { assert mutation_in_progress ( caller , version ) ; int neededSpace = len - curr . unusedBlockCapacity ( ) ; if ( neededSpace <= 0 ) { insertInCurrOnly ( caller , version , curr , pos , len ) ; } else { bbBlock next = null ; if ( curr . _idx < this . _next_block_position - 1 ) { next = this . _blocks . get ( curr . _idx + 1 ) ; } if ( next != null && ( neededSpace <= next . unusedBlockCapacity ( ) ) ) { insertInCurrAndNext ( caller , version , curr , pos , len , next ) ; } else { int lenNeededInLastAddedBlock = neededSpace % _blockSizeUpperLimit ; int tailLen = curr . bytesAvailableToRead ( pos ) ; if ( lenNeededInLastAddedBlock < tailLen ) lenNeededInLastAddedBlock = tailLen ; if ( lenNeededInLastAddedBlock < neededSpace && neededSpace < this . _blockSizeUpperLimit ) { lenNeededInLastAddedBlock = neededSpace ; } bbBlock newblock = insertMakeNewTailBlock ( caller , version , curr , lenNeededInLastAddedBlock ) ; if ( len <= ( curr . unusedBlockCapacity ( ) + newblock . unusedBlockCapacity ( ) ) ) { insertBlock ( newblock ) ; insertInCurrAndNext ( caller , version , curr , pos , len , newblock ) ; } else { insertAsManyBlocksAsNeeded ( caller , version , curr , pos , len , newblock ) ; } } } assert _validate ( ) ; return len ; }
dispatcher for the various forms of insert we encounter calls one of the four helpers depending on the case that is needed to inser here
34,546
private int insertInCurrOnly ( Object caller , int version , bbBlock curr , int pos , int len ) { assert mutation_in_progress ( caller , version ) ; assert curr . unusedBlockCapacity ( ) >= len ; System . arraycopy ( curr . _buffer , curr . blockOffsetFromAbsolute ( pos ) , curr . _buffer , curr . blockOffsetFromAbsolute ( pos ) + len , curr . bytesAvailableToRead ( pos ) ) ; curr . _limit += len ; this . adjustOffsets ( curr . _idx , len , 0 ) ; notifyInsert ( pos , len ) ; return len ; }
this handles insert when there s enough room in the current block
34,547
private int readVarInt ( int firstByte ) throws IOException { long retValue = 0 ; int b = firstByte ; boolean isNegative = false ; for ( ; ; ) { if ( b < 0 ) throwUnexpectedEOFException ( ) ; if ( ( b & 0x40 ) != 0 ) { isNegative = true ; } retValue = ( b & 0x3F ) ; if ( ( b & 0x80 ) != 0 ) break ; if ( ( b = read ( ) ) < 0 ) throwUnexpectedEOFException ( ) ; retValue = ( retValue << 7 ) | ( b & 0x7F ) ; if ( ( b & 0x80 ) != 0 ) break ; if ( ( b = read ( ) ) < 0 ) throwUnexpectedEOFException ( ) ; retValue = ( retValue << 7 ) | ( b & 0x7F ) ; if ( ( b & 0x80 ) != 0 ) break ; if ( ( b = read ( ) ) < 0 ) throwUnexpectedEOFException ( ) ; retValue = ( retValue << 7 ) | ( b & 0x7F ) ; if ( ( b & 0x80 ) != 0 ) break ; if ( ( b = read ( ) ) < 0 ) throwUnexpectedEOFException ( ) ; retValue = ( retValue << 7 ) | ( b & 0x7F ) ; if ( ( b & 0x80 ) != 0 ) break ; throwVarIntOverflowException ( ) ; } if ( isNegative ) { retValue = - retValue ; } int retValueAsInt = ( int ) retValue ; if ( retValue != ( ( long ) retValueAsInt ) ) { throwVarIntOverflowException ( ) ; } return retValueAsInt ; }
reads a varInt after the first byte was read . The first byte is used to specify the sign and - 0 has different representation on the protected API that was called
34,548
public Type next ( boolean is_in_expression ) throws IOException { inQuotedContent = false ; int c = this . readIgnoreWhitespace ( ) ; return next ( c , is_in_expression ) ; }
Java handles the tail optimization )
34,549
private boolean twoMoreSingleQuotes ( ) throws IOException { int c = read ( ) ; if ( c == '\'' ) { int c2 = read ( ) ; if ( c2 == '\'' ) { return true ; } unread ( c2 ) ; } unread ( c ) ; return false ; }
If two single quotes are next on the input consume them and return true . Otherwise leave them on the input and return false .
34,550
public final static int typeNameKeyWordFromMask ( int possible_names , int length ) { int kw = KEYWORD_unrecognized ; if ( possible_names != IonTokenConstsX . KW_ALL_BITS ) { for ( int ii = 0 ; ii < typeNameBits . length ; ii ++ ) { int tb = typeNameBits [ ii ] ; if ( tb == possible_names ) { if ( typeNameNames [ ii ] . length ( ) == length ) { kw = typeNameKeyWordIds [ ii ] ; } break ; } } } return kw ; }
this can be faster but it s pretty unusual to be called .
34,551
public final IonTextWriterBuilder withIvmMinimizing ( IvmMinimizing minimizing ) { IonTextWriterBuilder b = mutable ( ) ; b . setIvmMinimizing ( minimizing ) ; return b ; }
Declares the strategy for reducing or eliminating non - initial Ion version markers returning a new mutable builder if this is immutable . When null IVMs are emitted as they are written .
34,552
public final IonTextWriterBuilder withLongStringThreshold ( int threshold ) { IonTextWriterBuilder b = mutable ( ) ; b . setLongStringThreshold ( threshold ) ; return b ; }
Declares the length beyond which string and clob content will be rendered as triple - quoted long strings . At present such content will only line - break on extant newlines .
34,553
private void startLocalSymbolTableIfNeeded ( final boolean writeIVM ) throws IOException { if ( symbolState == SymbolState . SYSTEM_SYMBOLS ) { if ( writeIVM ) { symbols . writeIonVersionMarker ( ) ; } symbols . addTypeAnnotationSymbol ( systemSymbol ( ION_SYMBOL_TABLE_SID ) ) ; symbols . stepIn ( STRUCT ) ; { if ( imports . parents . size ( ) > 0 ) { symbols . setFieldNameSymbol ( systemSymbol ( IMPORTS_SID ) ) ; symbols . stepIn ( LIST ) ; for ( final SymbolTable st : imports . parents ) { symbols . stepIn ( STRUCT ) ; { symbols . setFieldNameSymbol ( systemSymbol ( NAME_SID ) ) ; symbols . writeString ( st . getName ( ) ) ; symbols . setFieldNameSymbol ( systemSymbol ( VERSION_SID ) ) ; symbols . writeInt ( st . getVersion ( ) ) ; symbols . setFieldNameSymbol ( systemSymbol ( MAX_ID_SID ) ) ; symbols . writeInt ( st . getMaxId ( ) ) ; } symbols . stepOut ( ) ; } symbols . stepOut ( ) ; } } symbolState = SymbolState . LOCAL_SYMBOLS_WITH_IMPORTS_ONLY ; } }
Symbol Table Management
34,554
public void setFieldName ( final String name ) { if ( ! isInStruct ( ) ) { throw new IllegalStateException ( "IonWriter.setFieldName() must be called before writing a value into a struct." ) ; } if ( name == null ) { throw new NullPointerException ( "Null field name is not allowed." ) ; } final SymbolToken token = intern ( name ) ; user . setFieldNameSymbol ( token ) ; }
Current Value Meta
34,555
public SymbolTable removeTable ( String name , int version ) { SymbolTable removed = null ; synchronized ( myTablesByName ) { TreeMap < Integer , SymbolTable > versions = myTablesByName . get ( name ) ; if ( versions != null ) { synchronized ( versions ) { removed = versions . remove ( version ) ; if ( versions . isEmpty ( ) ) { myTablesByName . remove ( name ) ; } } } } return removed ; }
Removes a symbol table from this catalog .
34,556
public Iterator < SymbolTable > iterator ( ) { ArrayList < SymbolTable > tables ; synchronized ( myTablesByName ) { tables = new ArrayList < SymbolTable > ( myTablesByName . size ( ) ) ; Collection < TreeMap < Integer , SymbolTable > > symtabNames = myTablesByName . values ( ) ; for ( TreeMap < Integer , SymbolTable > versions : symtabNames ) { synchronized ( versions ) { tables . addAll ( versions . values ( ) ) ; } } } return tables . iterator ( ) ; }
Constructs an iterator that enumerates all of the shared symbol tables in this catalog at the time of method invocation . The result represents a snapshot of the state of this catalog .
34,557
void validateNewChild ( IonValue child ) throws ContainedValueException , NullPointerException , IllegalArgumentException { if ( child . getContainer ( ) != null ) { throw new ContainedValueException ( ) ; } if ( child . isReadOnly ( ) ) throw new ReadOnlyValueException ( ) ; if ( child instanceof IonDatagram ) { String message = "IonDatagram can not be inserted into another IonContainer." ; throw new IllegalArgumentException ( message ) ; } assert child instanceof IonValueLite : "Child was not created by the same ValueFactory" ; assert getSystem ( ) == child . getSystem ( ) || getSystem ( ) . getClass ( ) . equals ( child . getSystem ( ) . getClass ( ) ) ; }
Ensures that a potential new child is non - null has no container is not read - only and is not a datagram .
34,558
protected int add_child ( int idx , IonValueLite child ) { _isNullValue ( false ) ; child . setContext ( this . getContextForIndex ( child , idx ) ) ; if ( _children == null || _child_count >= _children . length ) { int old_len = ( _children == null ) ? 0 : _children . length ; int new_len = this . nextSize ( old_len , true ) ; assert ( new_len > idx ) ; IonValueLite [ ] temp = new IonValueLite [ new_len ] ; if ( old_len > 0 ) { System . arraycopy ( _children , 0 , temp , 0 , old_len ) ; } _children = temp ; } if ( idx < _child_count ) { System . arraycopy ( _children , idx , _children , idx + 1 , _child_count - idx ) ; } _child_count ++ ; _children [ idx ] = child ; structuralModificationCount ++ ; child . _elementid ( idx ) ; if ( ! _isSymbolIdPresent ( ) && child . _isSymbolIdPresent ( ) ) { cascadeSIDPresentToContextRoot ( ) ; } return idx ; }
Does not validate the child or check locks .
34,559
void remove_child ( int idx ) { assert ( idx >= 0 ) ; assert ( idx < get_child_count ( ) ) ; assert get_child ( idx ) != null : "No child at index " + idx ; _children [ idx ] . detachFromContainer ( ) ; int children_to_move = _child_count - idx - 1 ; if ( children_to_move > 0 ) { System . arraycopy ( _children , idx + 1 , _children , idx , children_to_move ) ; } _child_count -- ; _children [ _child_count ] = null ; structuralModificationCount ++ ; }
Does not check locks .
34,560
public void put ( String fieldName , IonValue value ) { checkForLock ( ) ; validateFieldName ( fieldName ) ; if ( value != null ) validateNewChild ( value ) ; int lowestRemovedIndex = get_child_count ( ) ; boolean any_removed = false ; if ( _field_map != null && _field_map_duplicate_count == 0 ) { Integer idx = _field_map . get ( fieldName ) ; if ( idx != null ) { lowestRemovedIndex = idx . intValue ( ) ; remove_field_from_field_map ( fieldName , lowestRemovedIndex ) ; remove_child ( lowestRemovedIndex ) ; any_removed = true ; } } else { int copies_removed = 0 ; for ( int ii = get_child_count ( ) ; ii > 0 ; ) { ii -- ; IonValueLite child = get_child ( ii ) ; if ( fieldName . equals ( child . getFieldNameSymbol ( ) . getText ( ) ) ) { remove_child ( ii ) ; lowestRemovedIndex = ii ; copies_removed ++ ; any_removed = true ; } } if ( any_removed ) { remove_field ( fieldName , lowestRemovedIndex , copies_removed ) ; } } if ( any_removed ) { patch_map_elements_helper ( lowestRemovedIndex ) ; patch_elements_helper ( lowestRemovedIndex ) ; } if ( value != null ) { add ( fieldName , value ) ; } }
put is make this value the one and only value associated with this fieldName . The side effect is that if there were multiple fields with this name when put is complete there will only be the one value in the collection .
34,561
protected int lobHashCode ( int seed , SymbolTableProvider symbolTableProvider ) { int result = seed ; if ( ! isNullValue ( ) ) { CRC32 crc = new CRC32 ( ) ; crc . update ( getBytes ( ) ) ; result ^= ( int ) crc . getValue ( ) ; } return hashTypeAnnotations ( result , symbolTableProvider ) ; }
Calculate LOB hash code as XOR of seed with CRC - 32 of the LOB data . This distinguishes BLOBs from CLOBs
34,562
public final boolean skipDoubleColon ( ) throws IOException { int c = skip_over_whitespace ( ) ; if ( c != ':' ) { unread_char ( c ) ; return false ; } c = read_char ( ) ; if ( c != ':' ) { unread_char ( c ) ; unread_char ( ':' ) ; return false ; } return true ; }
peeks into the input stream to see if the next token would be a double colon . If indeed this is the case it skips the two colons and returns true . If not it unreads the 1 or 2 real characters it read and return false . It always consumes any preceding whitespace .
34,563
public final int peekNullTypeSymbol ( ) throws IOException { int c = read_char ( ) ; if ( c != '.' ) { unread_char ( c ) ; return IonTokenConstsX . KEYWORD_none ; } int [ ] read_ahead = new int [ IonTokenConstsX . TN_MAX_NAME_LENGTH + 1 ] ; int read_count = 0 ; int possible_names = IonTokenConstsX . KW_ALL_BITS ; while ( read_count < IonTokenConstsX . TN_MAX_NAME_LENGTH + 1 ) { c = read_char ( ) ; read_ahead [ read_count ++ ] = c ; int letter_idx = IonTokenConstsX . typeNameLetterIdx ( c ) ; if ( letter_idx < 1 ) { if ( IonTokenConstsX . isValidTerminatingCharForInf ( c ) ) { break ; } return peekNullTypeSymbolUndo ( read_ahead , read_count ) ; } int mask = IonTokenConstsX . typeNamePossibilityMask ( read_count - 1 , letter_idx ) ; possible_names &= mask ; if ( possible_names == 0 ) { return peekNullTypeSymbolUndo ( read_ahead , read_count ) ; } } int kw = IonTokenConstsX . typeNameKeyWordFromMask ( possible_names , read_count - 1 ) ; if ( kw == IonTokenConstsX . KEYWORD_unrecognized ) { peekNullTypeSymbolUndo ( read_ahead , read_count ) ; } else { unread_char ( c ) ; } return kw ; }
peeks into the input stream to see if we have an unquoted symbol that resolves to one of the ion types . If it does it consumes the input and returns the type keyword id . If not is unreads the non - whitespace characters and the dot which the input argument c should be .
34,564
public final int peekLobStartPunctuation ( ) throws IOException { int c = skip_over_lob_whitespace ( ) ; if ( c == '"' ) { return IonTokenConstsX . TOKEN_STRING_DOUBLE_QUOTE ; } if ( c != '\'' ) { unread_char ( c ) ; return IonTokenConstsX . TOKEN_ERROR ; } c = read_char ( ) ; if ( c != '\'' ) { unread_char ( c ) ; unread_char ( '\'' ) ; return IonTokenConstsX . TOKEN_ERROR ; } c = read_char ( ) ; if ( c != '\'' ) { unread_char ( c ) ; unread_char ( '\'' ) ; unread_char ( '\'' ) ; return IonTokenConstsX . TOKEN_ERROR ; } return IonTokenConstsX . TOKEN_STRING_TRIPLE_QUOTE ; }
peeks into the input stream to see what non - whitespace character is coming up . If it is a double quote or a triple quote this returns true as either distinguished the contents of a lob as distinctly a clob . Otherwise it returns false . In either case it unreads whatever non - whitespace it read to decide .
34,565
protected final void skip_clob_close_punctuation ( ) throws IOException { int c = skip_over_clob_whitespace ( ) ; if ( c == '}' ) { c = read_char ( ) ; if ( c == '}' ) { return ; } unread_char ( c ) ; c = '}' ; } unread_char ( c ) ; error ( "invalid closing puctuation for CLOB" ) ; }
Expects optional whitespace then }}
34,566
private final boolean skip_whitespace ( CommentStrategy commentStrategy ) throws IOException { boolean any_whitespace = false ; int c ; loop : for ( ; ; ) { c = read_char ( ) ; switch ( c ) { case - 1 : break loop ; case ' ' : case '\t' : case CharacterSequence . CHAR_SEQ_NEWLINE_SEQUENCE_1 : case CharacterSequence . CHAR_SEQ_NEWLINE_SEQUENCE_2 : case CharacterSequence . CHAR_SEQ_NEWLINE_SEQUENCE_3 : case CharacterSequence . CHAR_SEQ_ESCAPED_NEWLINE_SEQUENCE_1 : case CharacterSequence . CHAR_SEQ_ESCAPED_NEWLINE_SEQUENCE_2 : case CharacterSequence . CHAR_SEQ_ESCAPED_NEWLINE_SEQUENCE_3 : any_whitespace = true ; break ; case '/' : if ( ! commentStrategy . onComment ( this ) ) { break loop ; } any_whitespace = true ; break ; default : break loop ; } } unread_char ( c ) ; return any_whitespace ; }
Skips whitespace and applies the given CommentStrategy to any comments found . Finishes at the starting position of the next token .
34,567
private final boolean is_2_single_quotes_helper ( ) throws IOException { int c = read_char ( ) ; if ( c != '\'' ) { unread_char ( c ) ; return false ; } c = read_char ( ) ; if ( c != '\'' ) { unread_char ( c ) ; unread_char ( '\'' ) ; return false ; } return true ; }
this peeks ahead to see if the next two characters are single quotes . this would finish off a triple quote when the first quote has been read . if it succeeds it consumes the two quotes it reads . if it fails it unreads
34,568
private final int scan_negative_for_numeric_type ( int c ) throws IOException { assert ( c == '-' ) ; c = read_char ( ) ; int t = scan_for_numeric_type ( c ) ; if ( t == IonTokenConstsX . TOKEN_TIMESTAMP ) { bad_token ( c ) ; } unread_char ( c ) ; return t ; }
variant of scan_numeric_type where the passed in start character was preceded by a minus sign . this will also unread the minus sign .
34,569
protected void load_raw_characters ( StringBuilder sb ) throws IOException { int c = read_char ( ) ; for ( ; ; ) { c = read_char ( ) ; switch ( c ) { case CharacterSequence . CHAR_SEQ_ESCAPED_NEWLINE_SEQUENCE_1 : case CharacterSequence . CHAR_SEQ_ESCAPED_NEWLINE_SEQUENCE_2 : case CharacterSequence . CHAR_SEQ_ESCAPED_NEWLINE_SEQUENCE_3 : continue ; case - 1 : return ; default : if ( ! IonTokenConstsX . is7bitValue ( c ) ) { c = read_large_char_sequence ( c ) ; } } if ( IonUTF8 . needsSurrogateEncoding ( c ) ) { sb . append ( IonUTF8 . highSurrogate ( c ) ) ; c = IonUTF8 . lowSurrogate ( c ) ; } sb . append ( ( char ) c ) ; } }
this is used to load a previously marked set of bytes into the StringBuilder without escaping . It expects the caller to have set a save point so that the EOF will stop us at the right time . This does handle UTF8 decoding and surrogate encoding as the bytes are transfered .
34,570
private final int skip_timestamp_past_digits ( int min , int max ) throws IOException { int c ; while ( min > 0 ) { c = read_char ( ) ; if ( ! IonTokenConstsX . isDigit ( c ) ) { error ( "invalid character '" + ( char ) c + "' encountered in timestamp" ) ; } -- min ; -- max ; } while ( max > 0 ) { c = read_char ( ) ; if ( ! IonTokenConstsX . isDigit ( c ) ) { return c ; } -- max ; } return read_char ( ) ; }
Helper method for skipping embedded digits inside a timestamp value This overload skips at least min and at most max digits and errors if a non - digit is encountered in the first min characters read
34,571
private final int load_exponent ( StringBuilder sb ) throws IOException { int c = read_char ( ) ; if ( c == '-' || c == '+' ) { sb . append ( ( char ) c ) ; c = read_char ( ) ; } c = load_digits ( sb , c ) ; if ( c == '.' ) { sb . append ( ( char ) c ) ; c = read_char ( ) ; c = load_digits ( sb , c ) ; } return c ; }
can unread it
34,572
private final int load_digits ( StringBuilder sb , int c ) throws IOException { if ( ! IonTokenConstsX . isDigit ( c ) ) { return c ; } sb . append ( ( char ) c ) ; return readNumeric ( sb , Radix . DECIMAL , NumericState . DIGIT ) ; }
Accumulates digits into the buffer starting with the given character .
34,573
protected void skip_over_lob ( int lobToken , SavePoint sp ) throws IOException { switch ( lobToken ) { case IonTokenConstsX . TOKEN_STRING_DOUBLE_QUOTE : skip_double_quoted_string ( sp ) ; skip_clob_close_punctuation ( ) ; break ; case IonTokenConstsX . TOKEN_STRING_TRIPLE_QUOTE : skip_triple_quoted_clob_string ( sp ) ; skip_clob_close_punctuation ( ) ; break ; case IonTokenConstsX . TOKEN_OPEN_DOUBLE_BRACE : skip_over_blob ( sp ) ; break ; default : error ( "unexpected token " + IonTokenConstsX . getTokenName ( lobToken ) + " encountered for lob content" ) ; } }
Skips over the closing }} too .
34,574
public void writeRaw ( byte [ ] value , int start , int len ) throws IOException { startValue ( TID_RAW ) ; _writer . write ( value , start , len ) ; _patch . patchValue ( len ) ; closeValue ( ) ; }
just transfer the bytes into the current patch as proper ion binary serialization
34,575
int writeBytes ( OutputStream userstream ) throws IOException { if ( _patch . getParent ( ) != null ) { throw new IllegalStateException ( "Tried to flush while not on top-level" ) ; } try { BlockedByteInputStream datastream = new BlockedByteInputStream ( _manager . buffer ( ) ) ; int size = writeRecursive ( datastream , userstream , _patch ) ; return size ; } finally { _patch . reset ( ) ; } }
Writes everything we ve got into the output stream performing all necessary patches along the way .
34,576
private IonDatagramLite load_helper ( IonReader reader ) throws IOException { IonDatagramLite datagram = new IonDatagramLite ( _system , _catalog ) ; IonWriter writer = _Private_IonWriterFactory . makeWriter ( datagram ) ; writer . writeValues ( reader ) ; return datagram ; }
This doesn t wrap IOException because some callers need to propagate it .
34,577
IonStruct getIonRepresentation ( ) { synchronized ( this ) { IonStruct image = myImage ; if ( image == null ) { myImage = image = makeIonRepresentation ( myImageFactory ) ; } return image ; } }
Only valid on local symtabs that already have an _image_factory set .
34,578
private IonStruct makeIonRepresentation ( ValueFactory factory ) { IonStruct ionRep = factory . newEmptyStruct ( ) ; ionRep . addTypeAnnotation ( ION_SYMBOL_TABLE ) ; SymbolTable [ ] importedTables = getImportedTablesNoCopy ( ) ; if ( importedTables . length > 1 ) { IonList importsList = factory . newEmptyList ( ) ; for ( int i = 1 ; i < importedTables . length ; i ++ ) { SymbolTable importedTable = importedTables [ i ] ; IonStruct importStruct = factory . newEmptyStruct ( ) ; importStruct . add ( NAME , factory . newString ( importedTable . getName ( ) ) ) ; importStruct . add ( VERSION , factory . newInt ( importedTable . getVersion ( ) ) ) ; importStruct . add ( MAX_ID , factory . newInt ( importedTable . getMaxId ( ) ) ) ; importsList . add ( importStruct ) ; } ionRep . add ( IMPORTS , importsList ) ; } if ( mySymbolsCount > 0 ) { int sid = myFirstLocalSid ; for ( int offset = 0 ; offset < mySymbolsCount ; offset ++ , sid ++ ) { String symbolName = mySymbolNames [ offset ] ; recordLocalSymbolInIonRep ( ionRep , symbolName , sid ) ; } } return ionRep ; }
NOT SYNCHRONIZED! Call only from a synch d method .
34,579
private void recordLocalSymbolInIonRep ( IonStruct ionRep , String symbolName , int sid ) { assert sid >= myFirstLocalSid ; ValueFactory sys = ionRep . getSystem ( ) ; IonValue syms = ionRep . get ( SYMBOLS ) ; while ( syms != null && syms . getType ( ) != IonType . LIST ) { ionRep . remove ( syms ) ; syms = ionRep . get ( SYMBOLS ) ; } if ( syms == null ) { syms = sys . newEmptyList ( ) ; ionRep . put ( SYMBOLS , syms ) ; } int this_offset = sid - myFirstLocalSid ; IonValue name = sys . newString ( symbolName ) ; ( ( IonList ) syms ) . add ( this_offset , name ) ; }
NOT SYNCHRONIZED! Call within constructor or from synched method .
34,580
public int read ( ) throws IOException { int nextChar = super . read ( ) ; if ( nextChar != - 1 ) { if ( nextChar == '\n' ) { m_line ++ ; pushColumn ( m_column ) ; m_column = 0 ; } else if ( nextChar == '\r' ) { int aheadChar = super . read ( ) ; if ( aheadChar != '\n' ) { unreadImpl ( aheadChar , false ) ; } m_line ++ ; pushColumn ( m_column ) ; m_column = 0 ; nextChar = '\n' ; } else { m_column ++ ; } m_consumed ++ ; } return nextChar ; }
Uses the push back implementation but normalizes newlines to \ n .
34,581
private void unreadImpl ( int c , boolean updateCounts ) throws IOException { if ( c != - 1 ) { if ( updateCounts ) { if ( c == '\n' ) { m_line -- ; m_column = popColumn ( ) ; } else { m_column -- ; } m_consumed -- ; } super . unread ( c ) ; } }
Performs ths actual unread operation .
34,582
public static void verifyBinaryVersionMarker ( Reader reader ) throws IonException { try { int pos = reader . position ( ) ; byte [ ] bvm = new byte [ BINARY_VERSION_MARKER_SIZE ] ; int len = readFully ( reader , bvm ) ; if ( len < BINARY_VERSION_MARKER_SIZE ) { String message = "Binary data is too short: at least " + BINARY_VERSION_MARKER_SIZE + " bytes are required, but only " + len + " were found." ; throw new IonException ( message ) ; } if ( ! isIonBinary ( bvm ) ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( "Binary data has unrecognized header" ) ; for ( int i = 0 ; i < bvm . length ; i ++ ) { int b = bvm [ i ] & 0xFF ; buf . append ( " 0x" ) ; buf . append ( Integer . toHexString ( b ) . toUpperCase ( ) ) ; } throw new IonException ( buf . toString ( ) ) ; } reader . setPosition ( pos ) ; } catch ( IOException e ) { throw new IonException ( e ) ; } }
Verifies that a reader starts with a valid Ion cookie throwing an exception if it does not .
34,583
public static int lenVarUInt ( long longVal ) { assert longVal >= 0 ; if ( longVal < ( 1L << ( 7 * 1 ) ) ) return 1 ; if ( longVal < ( 1L << ( 7 * 2 ) ) ) return 2 ; if ( longVal < ( 1L << ( 7 * 3 ) ) ) return 3 ; if ( longVal < ( 1L << ( 7 * 4 ) ) ) return 4 ; if ( longVal < ( 1L << ( 7 * 5 ) ) ) return 5 ; if ( longVal < ( 1L << ( 7 * 6 ) ) ) return 6 ; if ( longVal < ( 1L << ( 7 * 7 ) ) ) return 7 ; if ( longVal < ( 1L << ( 7 * 8 ) ) ) return 8 ; if ( longVal < ( 1L << ( 7 * 9 ) ) ) return 9 ; return 10 ; }
Variable - length high - bit - terminating integer 7 data bits per byte .
34,584
public static int lenIonTimestamp ( Timestamp di ) { if ( di == null ) return 0 ; int len = 0 ; switch ( di . getPrecision ( ) ) { case FRACTION : case SECOND : { BigDecimal fraction = di . getFractionalSecond ( ) ; if ( fraction != null ) { assert fraction . signum ( ) >= 0 && ! fraction . equals ( BigDecimal . ZERO ) : "Bad timestamp fraction: " + fraction ; int fracLen = IonBinary . lenIonDecimal ( fraction ) ; assert fracLen > 0 ; len += fracLen ; } len ++ ; } case MINUTE : len += 2 ; case DAY : len += 1 ; case MONTH : len += 1 ; case YEAR : len += IonBinary . lenVarUInt ( di . getZYear ( ) ) ; } Integer offset = di . getLocalOffset ( ) ; if ( offset == null ) { len ++ ; } else if ( offset == 0 ) { len ++ ; } else { len += IonBinary . lenVarInt ( offset . longValue ( ) ) ; } return len ; }
this method computes the output length of this timestamp value in the Ion binary format . It does not include the length of the typedesc byte that preceeds the actual value . The output length of a null value is 0 as a result this this .
34,585
private final int stateFirstInStruct ( ) { int new_state ; if ( hasName ( ) ) { new_state = S_NAME ; } else if ( hasMaxId ( ) ) { new_state = S_MAX_ID ; } else if ( hasImports ( ) ) { new_state = S_IMPORT_LIST ; } else if ( hasLocalSymbols ( ) ) { new_state = S_SYMBOL_LIST ; } else { new_state = S_STRUCT_CLOSE ; } return new_state ; }
details of the symbol table we re reading .
34,586
public IonType next ( ) { if ( has_next_helper ( ) == false ) { return null ; } int new_state ; switch ( _current_state ) { case S_BOF : new_state = S_STRUCT ; break ; case S_STRUCT : new_state = S_EOF ; break ; case S_IN_STRUCT : new_state = stateFirstInStruct ( ) ; loadStateData ( new_state ) ; break ; case S_NAME : assert ( hasVersion ( ) ) ; new_state = S_VERSION ; loadStateData ( new_state ) ; break ; case S_VERSION : if ( hasMaxId ( ) ) { new_state = S_MAX_ID ; loadStateData ( new_state ) ; } else { new_state = stateFollowingMaxId ( ) ; } break ; case S_MAX_ID : new_state = stateFollowingMaxId ( ) ; break ; case S_IMPORT_LIST : new_state = this . stateFollowingImportList ( Op . NEXT ) ; break ; case S_IN_IMPORTS : case S_IMPORT_STRUCT : assert ( _import_iterator != null ) ; new_state = nextImport ( ) ; break ; case S_IN_IMPORT_STRUCT : new_state = S_IMPORT_NAME ; loadStateData ( new_state ) ; break ; case S_IMPORT_NAME : new_state = S_IMPORT_VERSION ; loadStateData ( new_state ) ; break ; case S_IMPORT_VERSION : new_state = S_IMPORT_MAX_ID ; loadStateData ( new_state ) ; break ; case S_IMPORT_MAX_ID : new_state = S_IMPORT_STRUCT_CLOSE ; break ; case S_IMPORT_STRUCT_CLOSE : new_state = S_IMPORT_STRUCT_CLOSE ; break ; case S_IMPORT_LIST_CLOSE : new_state = S_IMPORT_LIST_CLOSE ; break ; case S_AFTER_IMPORT_LIST : assert ( _symbol_table . getImportedMaxId ( ) < _maxId ) ; new_state = S_SYMBOL_LIST ; break ; case S_SYMBOL_LIST : assert ( _symbol_table . getImportedMaxId ( ) < _maxId ) ; new_state = stateFollowingLocalSymbols ( ) ; break ; case S_IN_SYMBOLS : assert ( _local_symbols != null ) ; assert ( _local_symbols . hasNext ( ) == true ) ; case S_SYMBOL : if ( _local_symbols . hasNext ( ) ) { _string_value = _local_symbols . next ( ) ; new_state = S_SYMBOL ; } else { new_state = S_SYMBOL_LIST_CLOSE ; } break ; case S_SYMBOL_LIST_CLOSE : new_state = S_SYMBOL_LIST_CLOSE ; break ; case S_STRUCT_CLOSE : new_state = S_STRUCT_CLOSE ; break ; case S_EOF : new_state = S_EOF ; break ; default : throwUnrecognizedState ( _current_state ) ; new_state = - 1 ; break ; } _current_state = new_state ; return stateType ( _current_state ) ; }
this computes the actual move to the next state
34,587
private int growBuffer ( int offset ) { assert offset < 0 ; byte [ ] oldBuf = myBuffer ; int oldLen = oldBuf . length ; byte [ ] newBuf = new byte [ ( - offset + oldLen ) << 1 ] ; int oldBegin = newBuf . length - oldLen ; System . arraycopy ( oldBuf , 0 , newBuf , oldBegin , oldLen ) ; myBuffer = newBuf ; myOffset += oldBegin ; return offset + oldBegin ; }
Grows the current buffer and returns the updated offset .
34,588
private void writeIonValue ( IonValue value ) throws IonException { final int valueOffset = myBuffer . length - myOffset ; switch ( value . getType ( ) ) { case BLOB : writeIonBlobContent ( ( IonBlob ) value ) ; break ; case BOOL : writeIonBoolContent ( ( IonBool ) value ) ; break ; case CLOB : writeIonClobContent ( ( IonClob ) value ) ; break ; case DECIMAL : writeIonDecimalContent ( ( IonDecimal ) value ) ; break ; case FLOAT : writeIonFloatContent ( ( IonFloat ) value ) ; break ; case INT : writeIonIntContent ( ( IonInt ) value ) ; break ; case NULL : writeIonNullContent ( ) ; break ; case STRING : writeIonStringContent ( ( IonString ) value ) ; break ; case SYMBOL : writeIonSymbolContent ( ( IonSymbol ) value ) ; break ; case TIMESTAMP : writeIonTimestampContent ( ( IonTimestamp ) value ) ; break ; case LIST : writeIonListContent ( ( IonList ) value ) ; break ; case SEXP : writeIonSexpContent ( ( IonSexp ) value ) ; break ; case STRUCT : writeIonStructContent ( ( IonStruct ) value ) ; break ; case DATAGRAM : writeIonDatagramContent ( ( IonDatagram ) value ) ; break ; default : throw new IonException ( "IonType is unknown: " + value . getType ( ) ) ; } writeAnnotations ( value , valueOffset ) ; }
Writes the IonValue and its nested values recursively including annotations .
34,589
private void writeSymbolsField ( SymbolTable symTab ) { int importedMaxId = symTab . getImportedMaxId ( ) ; int maxId = symTab . getMaxId ( ) ; if ( importedMaxId == maxId ) { return ; } final int originalOffset = myBuffer . length - myOffset ; for ( int i = maxId ; i > importedMaxId ; i -- ) { String str = symTab . findKnownSymbol ( i ) ; if ( str == null ) { writeByte ( ( byte ) ( TYPE_STRING | NULL_LENGTH_MASK ) ) ; } else { writeIonStringContent ( str ) ; } } writePrefix ( TYPE_LIST , myBuffer . length - myOffset - originalOffset ) ; writeByte ( ( byte ) ( 0x80 | SYMBOLS_SID ) ) ; }
Write declared local symbol names if any exists .
34,590
private List < String > getPercolationMatches ( JsonMetric jsonMetric ) throws IOException { HttpURLConnection connection = openConnection ( "/" + currentIndexName + "/" + jsonMetric . type ( ) + "/_percolate" , "POST" ) ; if ( connection == null ) { LOGGER . error ( "Could not connect to any configured elasticsearch instances for percolation: {}" , Arrays . asList ( hosts ) ) ; return Collections . emptyList ( ) ; } Map < String , Object > data = new HashMap < > ( 1 ) ; data . put ( "doc" , jsonMetric ) ; objectMapper . writeValue ( connection . getOutputStream ( ) , data ) ; closeConnection ( connection ) ; if ( connection . getResponseCode ( ) != 200 ) { throw new RuntimeException ( "Error percolating " + jsonMetric ) ; } Map < String , Object > input = objectMapper . readValue ( connection . getInputStream ( ) , new TypeReference < Map < String , Object > > ( ) { } ) ; List < String > matches = new ArrayList < > ( ) ; if ( input . containsKey ( "matches" ) && input . get ( "matches" ) instanceof List ) { List < Map < String , String > > foundMatches = ( List < Map < String , String > > ) input . get ( "matches" ) ; for ( Map < String , String > entry : foundMatches ) { if ( entry . containsKey ( "_id" ) ) { matches . add ( entry . get ( "_id" ) ) ; } } } return matches ; }
Execute a percolation request for the specified metric
34,591
private void addJsonMetricToPercolationIfMatching ( JsonMetric < ? extends Metric > jsonMetric , List < JsonMetric > percolationMetrics ) { if ( percolationFilter != null && percolationFilter . matches ( jsonMetric . name ( ) , jsonMetric . value ( ) ) ) { percolationMetrics . add ( jsonMetric ) ; } }
Add metric to list of matched percolation if needed
34,592
private HttpURLConnection createNewConnectionIfBulkSizeReached ( HttpURLConnection connection , int entriesWritten ) throws IOException { if ( entriesWritten % bulkSize == 0 ) { closeConnection ( connection ) ; return openConnection ( "/_bulk" , "POST" ) ; } return connection ; }
Create a new connection when the bulk size has hit the limit Checked on every write of a metric
34,593
private void writeJsonMetric ( JsonMetric jsonMetric , ObjectWriter writer , OutputStream out ) throws IOException { writer . writeValue ( out , new BulkIndexOperationHeader ( currentIndexName , jsonMetric . type ( ) ) ) ; out . write ( "\n" . getBytes ( ) ) ; writer . writeValue ( out , jsonMetric ) ; out . write ( "\n" . getBytes ( ) ) ; out . flush ( ) ; }
serialize a JSON metric over the outputstream in a bulk request
34,594
private HttpURLConnection openConnection ( String uri , String method ) { for ( String host : hosts ) { try { URL templateUrl = new URL ( "http://" + host + uri ) ; HttpURLConnection connection = ( HttpURLConnection ) templateUrl . openConnection ( ) ; connection . setRequestMethod ( method ) ; connection . setConnectTimeout ( timeout ) ; connection . setUseCaches ( false ) ; if ( method . equalsIgnoreCase ( "POST" ) || method . equalsIgnoreCase ( "PUT" ) ) { connection . setDoOutput ( true ) ; } connection . connect ( ) ; return connection ; } catch ( IOException e ) { LOGGER . error ( "Error connecting to {}: {}" , host , e ) ; } } return null ; }
Open a new HttpUrlConnection in case it fails it tries for the next host in the configured list
34,595
private void checkForIndexTemplate ( ) { try { HttpURLConnection connection = openConnection ( "/_template/metrics_template" , "HEAD" ) ; if ( connection == null ) { LOGGER . error ( "Could not connect to any configured elasticsearch instances: {}" , Arrays . asList ( hosts ) ) ; return ; } connection . disconnect ( ) ; boolean isTemplateMissing = connection . getResponseCode ( ) == HttpURLConnection . HTTP_NOT_FOUND ; if ( isTemplateMissing ) { LOGGER . debug ( "No metrics template found in elasticsearch. Adding..." ) ; HttpURLConnection putTemplateConnection = openConnection ( "/_template/metrics_template" , "PUT" ) ; if ( putTemplateConnection == null ) { LOGGER . error ( "Error adding metrics template to elasticsearch" ) ; return ; } JsonGenerator json = new JsonFactory ( ) . createGenerator ( putTemplateConnection . getOutputStream ( ) ) ; json . writeStartObject ( ) ; json . writeStringField ( "template" , index + "*" ) ; json . writeObjectFieldStart ( "mappings" ) ; json . writeObjectFieldStart ( "_default_" ) ; json . writeObjectFieldStart ( "_all" ) ; json . writeBooleanField ( "enabled" , false ) ; json . writeEndObject ( ) ; json . writeObjectFieldStart ( "properties" ) ; json . writeObjectFieldStart ( "name" ) ; json . writeObjectField ( "type" , "string" ) ; json . writeObjectField ( "index" , "not_analyzed" ) ; json . writeEndObject ( ) ; json . writeEndObject ( ) ; json . writeEndObject ( ) ; json . writeEndObject ( ) ; json . writeEndObject ( ) ; json . flush ( ) ; putTemplateConnection . disconnect ( ) ; if ( putTemplateConnection . getResponseCode ( ) != 200 ) { LOGGER . error ( "Error adding metrics template to elasticsearch: {}/{}" + putTemplateConnection . getResponseCode ( ) , putTemplateConnection . getResponseMessage ( ) ) ; } } checkedForIndexTemplate = true ; } catch ( IOException e ) { LOGGER . error ( "Error when checking/adding metrics template to elasticsearch" , e ) ; } }
This index template is automatically applied to all indices which start with the index name The index template simply configures the name not to be analyzed
34,596
public void post ( Notification event ) { for ( Map . Entry < Object , List < SubscriberMethod > > entry : listeners . entrySet ( ) ) { for ( SubscriberMethod method : entry . getValue ( ) ) { if ( method . eventTypeToInvokeOn . isInstance ( event ) ) { try { method . methodToInvokeOnEvent . invoke ( entry . getKey ( ) , event ) ; } catch ( InvocationTargetException e ) { LOGGER . log ( Level . SEVERE , "Subscriber invocation failed for method \"" + method . toString ( ) + "\"" , e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( EventBus . class . getName ( ) + " could not access " + "subscriber " + method . toString ( ) , e ) ; } } } } }
Post an event to the bus . All subscribers to the event class type posted will be notified .
34,597
public Void call ( SQLDatabase db ) throws DocumentStoreException { SortedMap < String , Long > leafs = new TreeMap < String , Long > ( Collections . reverseOrder ( new GenerationComparator ( ) ) ) ; Cursor cursor = null ; try { cursor = db . rawQuery ( GET_NON_DELETED_LEAFS , new String [ ] { Long . toString ( docNumericId ) } ) ; while ( cursor . moveToNext ( ) ) { leafs . put ( cursor . getString ( 0 ) , cursor . getLong ( 1 ) ) ; } } catch ( SQLException sqe ) { throw new DocumentStoreException ( "Exception thrown whilst trying to fetch non-deleted " + "leaf nodes." , sqe ) ; } finally { DatabaseUtils . closeCursorQuietly ( cursor ) ; } if ( leafs . size ( ) == 0 ) { try { cursor = db . rawQuery ( GET_ALL_LEAFS , new String [ ] { Long . toString ( docNumericId ) } ) ; while ( cursor . moveToNext ( ) ) { leafs . put ( cursor . getString ( 0 ) , cursor . getLong ( 1 ) ) ; } } catch ( SQLException sqe ) { throw new DocumentStoreException ( "Exception thrown whilst trying to fetch all leaf " + "nodes." , sqe ) ; } finally { DatabaseUtils . closeCursorQuietly ( cursor ) ; } } long newWinnerSeq = leafs . get ( leafs . firstKey ( ) ) ; ContentValues currentTrue = new ContentValues ( ) ; currentTrue . put ( "current" , 1 ) ; db . update ( "revs" , currentTrue , "sequence=?" , new String [ ] { Long . toString ( newWinnerSeq ) } ) ; ContentValues currentFalse = new ContentValues ( ) ; currentFalse . put ( "current" , 0 ) ; db . update ( "revs" , currentFalse , "sequence!=? AND doc_id=? AND sequence NOT IN " + "(SELECT DISTINCT parent FROM revs revs_inner WHERE parent NOT NULL AND revs_inner.doc_id=revs.doc_id)" , new String [ ] { Long . toString ( newWinnerSeq ) , Long . toString ( docNumericId ) } ) ; return null ; }
Execute the callable selecting and marking the new winning revision .
34,598
public static byte [ ] encryptAES ( SecretKey key , byte [ ] iv , byte [ ] unencryptedBytes ) throws NoSuchPaddingException , NoSuchAlgorithmException , InvalidAlgorithmParameterException , InvalidKeyException , BadPaddingException , IllegalBlockSizeException { Cipher aesCipher = Cipher . getInstance ( "AES/CBC/PKCS5Padding" ) ; IvParameterSpec ivParameter = new IvParameterSpec ( iv ) ; Key encryptionKey = new SecretKeySpec ( key . getEncoded ( ) , "AES" ) ; aesCipher . init ( Cipher . ENCRYPT_MODE , encryptionKey , ivParameter ) ; return aesCipher . doFinal ( unencryptedBytes ) ; }
AES Encrypt a byte array
34,599
public static byte [ ] decryptAES ( SecretKey key , byte [ ] iv , byte [ ] encryptedBytes ) throws NoSuchPaddingException , NoSuchAlgorithmException , InvalidAlgorithmParameterException , InvalidKeyException , BadPaddingException , IllegalBlockSizeException { Cipher aesCipher = Cipher . getInstance ( "AES/CBC/PKCS5Padding" ) ; IvParameterSpec ivParameter = new IvParameterSpec ( iv ) ; Key encryptionKey = new SecretKeySpec ( key . getEncoded ( ) , "AES" ) ; aesCipher . init ( Cipher . DECRYPT_MODE , encryptionKey , ivParameter ) ; return aesCipher . doFinal ( encryptedBytes ) ; }
Decrypt an AES encrypted byte array