idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
400
@ SuppressWarnings ( "unused" ) public static ClassReader readAndPatchClass ( InputStream in ) throws IOException { final byte [ ] bytecode = readStream ( in ) ; if ( false ) patchClassMajorVersion ( bytecode , Opcodes . V10 + 1 , Opcodes . V10 ) ; return new ClassReader ( bytecode ) ; }
Utility method to load class files of later Java versions by patching them so ASM can read them . Does nothing at the moment .
401
Artifact createArtifact ( ArtifactFactory artifactFactory ) { if ( groupId == null || artifactId == null || version == null || type == null ) { throw new NullPointerException ( "signaturesArtifact is missing some properties. Required are: groupId, artifactId, version, type" ) ; } return artifactFactory . createArtifactWithClassifier ( groupId , artifactId , version , type , classifier ) ; }
Used by the mojo to fetch the artifact
402
private ClassSignature loadClassFromJigsaw ( String classname ) throws IOException { if ( method_Class_getModule == null || method_Module_getName == null ) { return null ; } final Class < ? > clazz ; final String moduleName ; try { clazz = Class . forName ( classname , false , loader ) ; final Object module = method_Class_getModule . invoke ( clazz ) ; moduleName = ( String ) method_Module_getName . invoke ( module ) ; } catch ( Exception e ) { return null ; } return new ClassSignature ( clazz , AsmUtils . isRuntimeModule ( moduleName ) ) ; }
Loads the class from Java9 s module system and uses reflection to get methods and fields .
403
public void parseSignaturesFile ( URL url ) throws IOException , ParseException { parseSignaturesFile ( url . openStream ( ) , url . toString ( ) ) ; }
Reads a list of API signatures from the given URL .
404
public void parseSignaturesFile ( File f ) throws IOException , ParseException { parseSignaturesFile ( new FileInputStream ( f ) , f . toString ( ) ) ; }
Reads a list of API signatures from the given file .
405
private int checkClass ( final ClassReader reader , Pattern suppressAnnotationsPattern ) throws ForbiddenApiException { final String className = Type . getObjectType ( reader . getClassName ( ) ) . getClassName ( ) ; final ClassScanner scanner = new ClassScanner ( this , forbiddenSignatures , suppressAnnotationsPattern ) ; try { reader . accept ( scanner , ClassReader . SKIP_FRAMES ) ; } catch ( RelatedClassLoadingException rcle ) { final Exception cause = rcle . getException ( ) ; final StringBuilder msg = new StringBuilder ( ) . append ( "Check for forbidden API calls failed while scanning class '" ) . append ( className ) . append ( '\'' ) ; final String source = scanner . getSourceFile ( ) ; if ( source != null ) { msg . append ( " (" ) . append ( source ) . append ( ')' ) ; } msg . append ( ": " ) . append ( cause ) ; msg . append ( " (while looking up details about referenced class '" ) . append ( rcle . getClassName ( ) ) . append ( "')" ) ; assert cause != null && ( cause instanceof IOException || cause instanceof ClassNotFoundException ) ; throw new ForbiddenApiException ( msg . toString ( ) , cause ) ; } final List < ForbiddenViolation > violations = scanner . getSortedViolations ( ) ; final Pattern splitter = Pattern . compile ( Pattern . quote ( ForbiddenViolation . SEPARATOR ) ) ; for ( final ForbiddenViolation v : violations ) { for ( final String line : splitter . split ( v . format ( className , scanner . getSourceFile ( ) ) ) ) { logger . error ( line ) ; } } return violations . size ( ) ; }
Parses a class and checks for valid method invocations
406
public void parseSignaturesString ( String signatures ) throws IOException , ParseException { logger . info ( "Reading inline API signatures..." ) ; final Set < String > missingClasses = new TreeSet < String > ( ) ; parseSignaturesFile ( new StringReader ( signatures ) , false , missingClasses ) ; reportMissingSignatureClasses ( missingClasses ) ; }
Reads a list of API signatures from a String .
407
public BundledSignaturesType createBundledSignatures ( ) { final BundledSignaturesType s = new BundledSignaturesType ( ) ; s . setProject ( getProject ( ) ) ; bundledSignatures . add ( s ) ; return s ; }
Creates a bundled signatures instance
408
public void start ( BundleContext ctxt ) { InputFactoryProviderImpl inputP = new InputFactoryProviderImpl ( ) ; ctxt . registerService ( Stax2InputFactoryProvider . class . getName ( ) , inputP , inputP . getProperties ( ) ) ; OutputFactoryProviderImpl outputP = new OutputFactoryProviderImpl ( ) ; ctxt . registerService ( Stax2OutputFactoryProvider . class . getName ( ) , outputP , outputP . getProperties ( ) ) ; ValidationSchemaFactoryProviderImpl [ ] impls = ValidationSchemaFactoryProviderImpl . createAll ( ) ; for ( int i = 0 , len = impls . length ; i < len ; ++ i ) { ValidationSchemaFactoryProviderImpl impl = impls [ i ] ; ctxt . registerService ( Stax2ValidationSchemaFactoryProvider . class . getName ( ) , impl , impl . getProperties ( ) ) ; } }
Method called on activation . We need to register all providers we have at this point .
409
public BaseNsContext createNonTransientNsContext ( Location loc ) { if ( mLastNsContext != null ) { return mLastNsContext ; } int totalNsSize = mNamespaces . size ( ) ; if ( totalNsSize < 1 ) { return ( mLastNsContext = EmptyNamespaceContext . getInstance ( ) ) ; } int localCount = getCurrentNsCount ( ) << 1 ; BaseNsContext nsCtxt = new CompactNsContext ( loc , mNamespaces . asArray ( ) , totalNsSize , totalNsSize - localCount ) ; if ( localCount == 0 ) { mLastNsContext = nsCtxt ; } return nsCtxt ; }
Method called to construct a non - transient NamespaceContext instance ; generally needed when creating events to return from event - based iterators .
410
public int addDefaultAttribute ( String localName , String uri , String prefix , String value ) throws XMLStreamException { return mAttrCollector . addDefaultAttribute ( localName , uri , prefix , value ) ; }
Method called by actual validator instances when attributes with default values have no explicit values for the element ; if so default value needs to be added as if it was parsed from the element .
411
public ModelNode cloneModel ( ) { int len = mSubModels . length ; ModelNode [ ] newModels = new ModelNode [ len ] ; for ( int i = 0 ; i < len ; ++ i ) { newModels [ i ] = mSubModels [ i ] . cloneModel ( ) ; } return new ChoiceModel ( newModels ) ; }
Method that has to create a deep copy of the model without sharing any of existing Objects .
412
protected final String findOrCreateAttrPrefix ( String suggPrefix , String nsURI , SimpleOutputElement elem ) throws XMLStreamException { if ( nsURI == null || nsURI . length ( ) == 0 ) { return null ; } if ( suggPrefix != null ) { int status = elem . isPrefixValid ( suggPrefix , nsURI , false ) ; if ( status == SimpleOutputElement . PREFIX_OK ) { return suggPrefix ; } if ( status == SimpleOutputElement . PREFIX_UNBOUND ) { elem . addPrefix ( suggPrefix , nsURI ) ; doWriteNamespace ( suggPrefix , nsURI ) ; return suggPrefix ; } } String prefix = elem . getExplicitPrefix ( nsURI ) ; if ( prefix != null ) { return prefix ; } if ( suggPrefix != null ) { prefix = suggPrefix ; } else if ( mSuggestedPrefixes != null ) { prefix = mSuggestedPrefixes . get ( nsURI ) ; } if ( prefix != null ) { if ( prefix . length ( ) == 0 || ( elem . getNamespaceURI ( prefix ) != null ) ) { prefix = null ; } } if ( prefix == null ) { if ( mAutoNsSeq == null ) { mAutoNsSeq = new int [ 1 ] ; mAutoNsSeq [ 0 ] = 1 ; } prefix = mCurrElem . generateMapping ( mAutomaticNsPrefix , nsURI , mAutoNsSeq ) ; } elem . addPrefix ( prefix , nsURI ) ; doWriteNamespace ( prefix , nsURI ) ; return prefix ; }
Method called to somehow find a prefix for given namespace to be used for a new start element ; either use an existing one or generate a new one . If a new mapping needs to be generated it will also be automatically bound and necessary namespace declaration output .
413
public XMLStreamReader2 createXMLStreamReader ( File f ) throws XMLStreamException { return createSR ( f , false , true ) ; }
Convenience factory method that allows for parsing a document stored in the specified file .
414
public DTDSubset combineWithExternalSubset ( InputProblemReporter rep , DTDSubset extSubset ) throws XMLStreamException { HashMap < String , EntityDecl > ge1 = getGeneralEntityMap ( ) ; HashMap < String , EntityDecl > ge2 = extSubset . getGeneralEntityMap ( ) ; if ( ge1 == null || ge1 . isEmpty ( ) ) { ge1 = ge2 ; } else { if ( ge2 != null && ! ge2 . isEmpty ( ) ) { combineMaps ( ge1 , ge2 ) ; } } HashMap < String , NotationDeclaration > n1 = getNotationMap ( ) ; HashMap < String , NotationDeclaration > n2 = extSubset . getNotationMap ( ) ; if ( n1 == null || n1 . isEmpty ( ) ) { n1 = n2 ; } else { if ( n2 != null && ! n2 . isEmpty ( ) ) { checkNotations ( n1 , n2 ) ; combineMaps ( n1 , n2 ) ; } } HashMap < PrefixedName , DTDElement > e1 = getElementMap ( ) ; HashMap < PrefixedName , DTDElement > e2 = extSubset . getElementMap ( ) ; if ( e1 == null || e1 . isEmpty ( ) ) { e1 = e2 ; } else { if ( e2 != null && ! e2 . isEmpty ( ) ) { combineElements ( rep , e1 , e2 ) ; } } return constructInstance ( false , ge1 , null , null , null , n1 , e1 , mFullyValidating ) ; }
Method that will combine definitions from internal and external subsets producing a single DTD set .
415
public void dtdNotationDecl ( String name , String publicId , String systemId , URL baseURL ) throws XMLStreamException { if ( mDTDHandler != null ) { if ( systemId != null && systemId . indexOf ( ':' ) < 0 ) { try { systemId = URLUtil . urlFromSystemId ( systemId , baseURL ) . toExternalForm ( ) ; } catch ( IOException ioe ) { throw new WstxIOException ( ioe ) ; } } try { mDTDHandler . notationDecl ( name , publicId , systemId ) ; } catch ( SAXException sex ) { throw new WrappedSaxException ( sex ) ; } } }
DTD declarations that must be exposed
416
public void attributeDecl ( String eName , String aName , String type , String mode , String value ) { if ( mDeclHandler != null ) { try { mDeclHandler . attributeDecl ( eName , aName , type , mode , value ) ; } catch ( SAXException sex ) { throw new WrappedSaxException ( sex ) ; } } }
DTD declarations that can be exposed
417
public static DTDElement createDefined ( ReaderConfig cfg , Location loc , PrefixedName name , StructValidator val , int allowedContent ) { if ( allowedContent == XMLValidator . CONTENT_ALLOW_UNDEFINED ) { ExceptionUtil . throwInternal ( "trying to use XMLValidator.CONTENT_ALLOW_UNDEFINED via createDefined()" ) ; } return new DTDElement ( loc , name , val , allowedContent , cfg . willSupportNamespaces ( ) , cfg . isXml11 ( ) ) ; }
Method called to create an actual element definition matching an ELEMENT directive in a DTD subset .
418
public static DTDElement createPlaceholder ( ReaderConfig cfg , Location loc , PrefixedName name ) { return new DTDElement ( loc , name , null , XMLValidator . CONTENT_ALLOW_UNDEFINED , cfg . willSupportNamespaces ( ) , cfg . isXml11 ( ) ) ; }
Method called to create a placeholder element definition needed to contain attribute definitions .
419
public void defineFrom ( InputProblemReporter rep , DTDElement definedElem , boolean fullyValidate ) throws XMLStreamException { if ( fullyValidate ) { verifyUndefined ( ) ; } mValidator = definedElem . mValidator ; mAllowedContent = definedElem . mAllowedContent ; mergeMissingAttributesFrom ( rep , definedElem , fullyValidate ) ; }
Method called to upgrade a placeholder using a defined element including adding attributes .
420
public DTDAttribute addAttribute ( InputProblemReporter rep , PrefixedName attrName , int valueType , DefaultAttrValue defValue , WordResolver enumValues , boolean fullyValidate ) throws XMLStreamException { HashMap < PrefixedName , DTDAttribute > m = mAttrMap ; if ( m == null ) { mAttrMap = m = new HashMap < PrefixedName , DTDAttribute > ( ) ; } List < DTDAttribute > specList = defValue . isSpecial ( ) ? getSpecialList ( ) : null ; DTDAttribute attr ; int specIndex = ( specList == null ) ? - 1 : specList . size ( ) ; switch ( valueType ) { case DTDAttribute . TYPE_CDATA : attr = new DTDCdataAttr ( attrName , defValue , specIndex , mNsAware , mXml11 ) ; break ; case DTDAttribute . TYPE_ENUMERATED : attr = new DTDEnumAttr ( attrName , defValue , specIndex , mNsAware , mXml11 , enumValues ) ; break ; case DTDAttribute . TYPE_ID : attr = new DTDIdAttr ( attrName , defValue , specIndex , mNsAware , mXml11 ) ; break ; case DTDAttribute . TYPE_IDREF : attr = new DTDIdRefAttr ( attrName , defValue , specIndex , mNsAware , mXml11 ) ; break ; case DTDAttribute . TYPE_IDREFS : attr = new DTDIdRefsAttr ( attrName , defValue , specIndex , mNsAware , mXml11 ) ; break ; case DTDAttribute . TYPE_ENTITY : attr = new DTDEntityAttr ( attrName , defValue , specIndex , mNsAware , mXml11 ) ; break ; case DTDAttribute . TYPE_ENTITIES : attr = new DTDEntitiesAttr ( attrName , defValue , specIndex , mNsAware , mXml11 ) ; break ; case DTDAttribute . TYPE_NOTATION : attr = new DTDNotationAttr ( attrName , defValue , specIndex , mNsAware , mXml11 , enumValues ) ; break ; case DTDAttribute . TYPE_NMTOKEN : attr = new DTDNmTokenAttr ( attrName , defValue , specIndex , mNsAware , mXml11 ) ; break ; case DTDAttribute . TYPE_NMTOKENS : attr = new DTDNmTokensAttr ( attrName , defValue , specIndex , mNsAware , mXml11 ) ; break ; default : ExceptionUtil . throwGenericInternal ( ) ; attr = null ; } DTDAttribute old = doAddAttribute ( m , rep , attr , specList , fullyValidate ) ; return ( old == null ) ? attr : null ; }
Method called by DTD parser when it has read information about an attribute that belong to this element
421
public DTDAttribute addNsDefault ( InputProblemReporter rep , PrefixedName attrName , int valueType , DefaultAttrValue defValue , boolean fullyValidate ) throws XMLStreamException { DTDAttribute nsAttr ; switch ( valueType ) { case DTDAttribute . TYPE_CDATA : nsAttr = new DTDCdataAttr ( attrName , defValue , - 1 , mNsAware , mXml11 ) ; break ; default : nsAttr = new DTDNmTokenAttr ( attrName , defValue , - 1 , mNsAware , mXml11 ) ; break ; } String prefix = attrName . getPrefix ( ) ; if ( prefix == null || prefix . length ( ) == 0 ) { prefix = "" ; } else { prefix = attrName . getLocalName ( ) ; } if ( mNsDefaults == null ) { mNsDefaults = new HashMap < String , DTDAttribute > ( ) ; } else { if ( mNsDefaults . containsKey ( prefix ) ) { return null ; } } mNsDefaults . put ( prefix , nsAttr ) ; return nsAttr ; }
Method called to add a definition of a namespace - declaration pseudo - attribute with a default value .
422
@ SuppressWarnings ( "resource" ) private XMLStreamWriter2 createSW ( OutputStream out , Writer w , String enc , boolean requireAutoClose ) throws XMLStreamException { WriterConfig cfg = mConfig . createNonShared ( ) ; XmlWriter xw ; boolean autoCloseOutput = requireAutoClose || mConfig . willAutoCloseOutput ( ) ; if ( w == null ) { if ( enc == null ) { enc = WstxOutputProperties . DEFAULT_OUTPUT_ENCODING ; } else { if ( enc != CharsetNames . CS_UTF8 && enc != CharsetNames . CS_ISO_LATIN1 && enc != CharsetNames . CS_US_ASCII ) { enc = CharsetNames . normalize ( enc ) ; } } try { if ( enc == CharsetNames . CS_UTF8 ) { w = new UTF8Writer ( cfg , out , autoCloseOutput ) ; xw = new BufferingXmlWriter ( w , cfg , enc , autoCloseOutput , out , 16 ) ; } else if ( enc == CharsetNames . CS_ISO_LATIN1 ) { xw = new ISOLatin1XmlWriter ( out , cfg , autoCloseOutput ) ; } else if ( enc == CharsetNames . CS_US_ASCII ) { xw = new AsciiXmlWriter ( out , cfg , autoCloseOutput ) ; } else { w = new OutputStreamWriter ( out , enc ) ; xw = new BufferingXmlWriter ( w , cfg , enc , autoCloseOutput , out , - 1 ) ; } } catch ( IOException ex ) { throw new XMLStreamException ( ex ) ; } } else { if ( enc == null ) { enc = CharsetNames . findEncodingFor ( w ) ; } try { xw = new BufferingXmlWriter ( w , cfg , enc , autoCloseOutput , null , - 1 ) ; } catch ( IOException ex ) { throw new XMLStreamException ( ex ) ; } } return createSW ( enc , cfg , xw ) ; }
Bottleneck factory method used internally ; needs to take care of passing proper settings to stream writer .
423
public final int isPrefixValid ( String prefix , String nsURI , boolean isElement ) throws XMLStreamException { if ( nsURI == null ) { nsURI = "" ; } if ( prefix == null || prefix . length ( ) == 0 ) { if ( isElement ) { if ( nsURI == mDefaultNsURI || nsURI . equals ( mDefaultNsURI ) ) { return PREFIX_OK ; } } else { if ( nsURI . length ( ) == 0 ) { return PREFIX_OK ; } } return PREFIX_MISBOUND ; } if ( prefix . equals ( sXmlNsPrefix ) ) { if ( ! nsURI . equals ( sXmlNsURI ) ) { throwOutputError ( "Namespace prefix '" + sXmlNsPrefix + "' can not be bound to non-default namespace ('" + nsURI + "'); has to be the default '" + sXmlNsURI + "'" ) ; } return PREFIX_OK ; } String act ; if ( mNsMapping != null ) { act = mNsMapping . findUriByPrefix ( prefix ) ; } else { act = null ; } if ( act == null && mRootNsContext != null ) { act = mRootNsContext . getNamespaceURI ( prefix ) ; } if ( act == null ) { return PREFIX_UNBOUND ; } return ( act == nsURI || act . equals ( nsURI ) ) ? PREFIX_OK : PREFIX_MISBOUND ; }
Method that verifies that passed - in prefix indeed maps to the specified namespace URI ; and depending on how it goes returns a status for caller .
424
public void writeAttribute ( String localName , String value ) throws XMLStreamException { if ( ! mStartElementOpen && mCheckStructure ) { reportNwfStructure ( ErrorConsts . WERR_ATTR_NO_ELEM ) ; } doWriteAttr ( localName , null , null , value ) ; }
It s assumed calling this method implies caller just wants to add an attribute that does not belong to any namespace ; as such no namespace checking or prefix generation is needed .
425
public final void writeTypedElement ( AsciiValueEncoder enc ) throws IOException { if ( mSurrogate != 0 ) { throwUnpairedSurrogate ( ) ; } if ( enc . bufferNeedsFlush ( mOutputBuffer . length - mOutputPtr ) ) { flush ( ) ; } while ( true ) { mOutputPtr = enc . encodeMore ( mOutputBuffer , mOutputPtr , mOutputBuffer . length ) ; if ( enc . isCompleted ( ) ) { break ; } flush ( ) ; } }
Non - validating version of typed write method
426
public final void writeTypedElement ( AsciiValueEncoder enc , XMLValidator validator , char [ ] copyBuffer ) throws IOException , XMLStreamException { if ( mSurrogate != 0 ) { throwUnpairedSurrogate ( ) ; } final int copyBufferLen = copyBuffer . length ; do { int ptr = enc . encodeMore ( copyBuffer , 0 , copyBufferLen ) ; validator . validateText ( copyBuffer , 0 , ptr , false ) ; writeRawAscii ( copyBuffer , 0 , ptr ) ; } while ( ! enc . isCompleted ( ) ) ; }
Validating version of typed write method
427
protected final int writeAsEntity ( int c ) throws IOException { byte [ ] buf = mOutputBuffer ; int ptr = mOutputPtr ; if ( ( ptr + 10 ) >= buf . length ) { flushBuffer ( ) ; ptr = mOutputPtr ; } buf [ ptr ++ ] = BYTE_AMP ; if ( c < 256 ) { if ( c == '&' ) { buf [ ptr ++ ] = BYTE_A ; buf [ ptr ++ ] = BYTE_M ; buf [ ptr ++ ] = BYTE_P ; } else if ( c == '<' ) { buf [ ptr ++ ] = BYTE_L ; buf [ ptr ++ ] = BYTE_T ; } else if ( c == '>' ) { buf [ ptr ++ ] = BYTE_G ; buf [ ptr ++ ] = BYTE_T ; } else if ( c == '\'' ) { buf [ ptr ++ ] = BYTE_A ; buf [ ptr ++ ] = BYTE_P ; buf [ ptr ++ ] = BYTE_O ; buf [ ptr ++ ] = BYTE_S ; } else if ( c == '"' ) { buf [ ptr ++ ] = BYTE_Q ; buf [ ptr ++ ] = BYTE_U ; buf [ ptr ++ ] = BYTE_O ; buf [ ptr ++ ] = BYTE_T ; } else { buf [ ptr ++ ] = BYTE_HASH ; buf [ ptr ++ ] = BYTE_X ; if ( c >= 16 ) { int digit = ( c >> 4 ) ; buf [ ptr ++ ] = ( byte ) ( ( digit < 10 ) ? ( '0' + digit ) : ( ( 'a' - 10 ) + digit ) ) ; c &= 0xF ; } buf [ ptr ++ ] = ( byte ) ( ( c < 10 ) ? ( '0' + c ) : ( ( 'a' - 10 ) + c ) ) ; } } else { buf [ ptr ++ ] = BYTE_HASH ; buf [ ptr ++ ] = BYTE_X ; int shift = 20 ; int origPtr = ptr ; do { int digit = ( c >> shift ) & 0xF ; if ( digit > 0 || ( ptr != origPtr ) ) { buf [ ptr ++ ] = ( byte ) ( ( digit < 10 ) ? ( '0' + digit ) : ( ( 'a' - 10 ) + digit ) ) ; } shift -= 4 ; } while ( shift > 0 ) ; c &= 0xF ; buf [ ptr ++ ] = ( byte ) ( ( c < 10 ) ? ( '0' + c ) : ( ( 'a' - 10 ) + c ) ) ; } buf [ ptr ++ ] = BYTE_SEMICOLON ; mOutputPtr = ptr ; return ptr ; }
Entity writing can be optimized quite nicely since it only needs to output ascii characters .
428
public static < T > boolean anyValuesInCommon ( Collection < T > c1 , Collection < T > c2 ) { if ( c1 . size ( ) > c2 . size ( ) ) { Collection < T > tmp = c1 ; c1 = c2 ; c2 = tmp ; } Iterator < T > it = c1 . iterator ( ) ; while ( it . hasNext ( ) ) { if ( c2 . contains ( it . next ( ) ) ) { return true ; } } return false ; }
Method that can be used to efficiently check if 2 collections share at least one common element .
429
protected void throwLazyError ( Exception e ) { if ( e instanceof XMLStreamException ) { WstxLazyException . throwLazily ( ( XMLStreamException ) e ) ; } ExceptionUtil . throwRuntimeException ( e ) ; }
Method called to report an error when caller s signature only allows runtime exceptions to be thrown .
430
protected boolean loadMore ( ) throws XMLStreamException { WstxInputSource input = mInput ; do { mCurrInputProcessed += mInputEnd ; verifyLimit ( "Maximum document characters" , mConfig . getMaxCharacters ( ) , mCurrInputProcessed ) ; mCurrInputRowStart -= mInputEnd ; int count ; try { count = input . readInto ( this ) ; if ( count > 0 ) { return true ; } input . close ( ) ; } catch ( IOException ioe ) { throw constructFromIOE ( ioe ) ; } if ( input == mRootInput ) { return false ; } WstxInputSource parent = input . getParent ( ) ; if ( parent == null ) { throwNullParent ( input ) ; } if ( mCurrDepth != input . getScopeId ( ) ) { handleIncompleteEntityProblem ( input ) ; } mInput = input = parent ; input . restoreContext ( this ) ; mInputTopDepth = input . getScopeId ( ) ; if ( ! mNormalizeLFs ) { mNormalizeLFs = ! input . fromInternalEntity ( ) ; } } while ( mInputPtr >= mInputEnd ) ; return true ; }
Method that will try to read one or more characters from currently open input sources ; closing input sources if necessary .
431
private final void validateChar ( int value ) throws XMLStreamException { if ( value >= 0xD800 ) { if ( value < 0xE000 ) { reportIllegalChar ( value ) ; } if ( value > 0xFFFF ) { if ( value > MAX_UNICODE_CHAR ) { reportUnicodeOverflow ( ) ; } } else if ( value >= 0xFFFE ) { reportIllegalChar ( value ) ; } } else if ( value < 32 ) { if ( value == 0 ) { throwParseError ( "Invalid character reference: null character not allowed in XML content." ) ; } if ( ! mXml11 && ! mAllowXml11EscapedCharsInXml10 && ( value != 0x9 && value != 0xA && value != 0xD ) ) { reportIllegalChar ( value ) ; } } }
Method that will verify that expanded Unicode codepoint is a valid XML content character .
432
protected DOMOutputElement createAndAttachChild ( Element element ) { if ( mRootNode != null ) { mRootNode . appendChild ( element ) ; } else { mElement . appendChild ( element ) ; } return createChild ( element ) ; }
Simplest factory method which gets called when a 1 - argument element output method is called . It is then assumed to use the default namespace . Will both create the child element and attach it to parent element or lacking own owner document .
433
public void decode ( TypedValueDecoder tvd ) throws IllegalArgumentException { char [ ] buf ; int start , end ; if ( mInputStart >= 0 ) { buf = mInputBuffer ; start = mInputStart ; end = start + mInputLen ; } else { buf = getTextBuffer ( ) ; start = 0 ; end = mSegmentSize + mCurrentSize ; } while ( true ) { if ( start >= end ) { tvd . handleEmptyValue ( ) ; return ; } if ( ! StringUtil . isSpace ( buf [ start ] ) ) { break ; } ++ start ; } while ( -- end > start && StringUtil . isSpace ( buf [ end ] ) ) { } tvd . decode ( buf , start , end + 1 ) ; }
Generic pass - through method which call given decoder with accumulated data
434
public int decodeElements ( TypedArrayDecoder tad , InputProblemReporter rep ) throws TypedXMLStreamException { int count = 0 ; if ( mInputStart < 0 ) { if ( mHasSegments ) { mInputBuffer = buildResultArray ( ) ; mInputLen = mInputBuffer . length ; clearSegments ( ) ; } else { mInputBuffer = mCurrentSegment ; mInputLen = mCurrentSize ; } mInputStart = 0 ; } int ptr = mInputStart ; final int end = ptr + mInputLen ; final char [ ] buf = mInputBuffer ; int start = ptr ; try { decode_loop : while ( ptr < end ) { while ( buf [ ptr ] <= INT_SPACE ) { if ( ++ ptr >= end ) { break decode_loop ; } } start = ptr ; ++ ptr ; while ( ptr < end && buf [ ptr ] > INT_SPACE ) { ++ ptr ; } ++ count ; int tokenEnd = ptr ; ++ ptr ; if ( tad . decodeValue ( buf , start , tokenEnd ) ) { break ; } } } catch ( IllegalArgumentException iae ) { Location loc = rep . getLocation ( ) ; String lexical = new String ( buf , start , ( ptr - start - 1 ) ) ; throw new TypedXMLStreamException ( lexical , iae . getMessage ( ) , loc , iae ) ; } finally { mInputStart = ptr ; mInputLen = end - ptr ; } return count ; }
Pass - through decode method called to find find the next token decode it and repeat the process as long as there are more tokens and the array decoder accepts more entries . All tokens processed will be consumed such that they will not be visible via buffer .
435
public void initBinaryChunks ( Base64Variant v , CharArrayBase64Decoder dec , boolean firstChunk ) { if ( mInputStart < 0 ) { dec . init ( v , firstChunk , mCurrentSegment , 0 , mCurrentSize , mSegments ) ; } else { dec . init ( v , firstChunk , mInputBuffer , mInputStart , mInputLen , null ) ; } }
Method that needs to be called to configure given base64 decoder with textual contents collected by this buffer .
436
public int rawContentsTo ( Writer w ) throws IOException { if ( mResultArray != null ) { w . write ( mResultArray ) ; return mResultArray . length ; } if ( mResultString != null ) { w . write ( mResultString ) ; return mResultString . length ( ) ; } if ( mInputStart >= 0 ) { if ( mInputLen > 0 ) { w . write ( mInputBuffer , mInputStart , mInputLen ) ; } return mInputLen ; } int rlen = 0 ; if ( mSegments != null ) { for ( int i = 0 , len = mSegments . size ( ) ; i < len ; ++ i ) { char [ ] ch = mSegments . get ( i ) ; w . write ( ch ) ; rlen += ch . length ; } } if ( mCurrentSize > 0 ) { w . write ( mCurrentSegment , 0 , mCurrentSize ) ; rlen += mCurrentSize ; } return rlen ; }
Method that will stream contents of this buffer into specified Writer .
437
public boolean endsWith ( String str ) { if ( mInputStart >= 0 ) { unshare ( 16 ) ; } int segIndex = ( mSegments == null ) ? 0 : mSegments . size ( ) ; int inIndex = str . length ( ) - 1 ; char [ ] buf = mCurrentSegment ; int bufIndex = mCurrentSize - 1 ; while ( inIndex >= 0 ) { if ( str . charAt ( inIndex ) != buf [ bufIndex ] ) { return false ; } if ( -- inIndex == 0 ) { break ; } if ( -- bufIndex < 0 ) { if ( -- segIndex < 0 ) { return false ; } buf = mSegments . get ( segIndex ) ; bufIndex = buf . length - 1 ; } } return true ; }
Method that can be used to check if the contents of the buffer end in specified String .
438
private int calcNewSize ( int latestSize ) { int incr = ( latestSize < 8000 ) ? latestSize : ( latestSize >> 1 ) ; int size = latestSize + incr ; return Math . min ( size , MAX_SEGMENT_LENGTH ) ; }
Method used to determine size of the next segment to allocate to contain textual content .
439
private void expand ( int roomNeeded ) { if ( mSegments == null ) { mSegments = new ArrayList < char [ ] > ( ) ; } char [ ] curr = mCurrentSegment ; mHasSegments = true ; mSegments . add ( curr ) ; int oldLen = curr . length ; mSegmentSize += oldLen ; int newSize = Math . max ( roomNeeded , calcNewSize ( oldLen ) ) ; curr = new char [ newSize ] ; mCurrentSize = 0 ; mCurrentSegment = curr ; }
Method called when current segment is full to allocate new segment .
440
public void endBranch ( int endOffset ) { if ( mBranchBuffer != null ) { if ( endOffset > mBranchStartOffset ) { appendBranched ( mBranchStartOffset , endOffset ) ; } mBranchBuffer = null ; } }
Currently this input source does not implement branching
441
public final void verifyNameValidity ( String name , boolean checkNs ) throws XMLStreamException { if ( name == null || name . length ( ) == 0 ) { reportNwfName ( ErrorConsts . WERR_NAME_EMPTY ) ; } int illegalIx = WstxInputData . findIllegalNameChar ( name , checkNs , mXml11 ) ; if ( illegalIx >= 0 ) { if ( illegalIx == 0 ) { reportNwfName ( ErrorConsts . WERR_NAME_ILLEGAL_FIRST_CHAR , WstxInputData . getCharDesc ( name . charAt ( 0 ) ) ) ; } reportNwfName ( ErrorConsts . WERR_NAME_ILLEGAL_CHAR , WstxInputData . getCharDesc ( name . charAt ( illegalIx ) ) ) ; } }
Method called to verify that the name is a legal XML name .
442
public int addDefaultAttribute ( String localName , String uri , String prefix , String value ) { return - 1 ; }
Adding default attribute values does not usually make sense on output side so the implementation is a NOP for now .
443
private final void handleStartElem ( char c ) throws XMLStreamException { mTokenState = TOKEN_FULL_COALESCED ; boolean empty ; if ( mCfgNsEnabled ) { String str = parseLocalName ( c ) ; c = ( mInputPtr < mInputEnd ) ? mInputBuffer [ mInputPtr ++ ] : getNextCharFromCurrent ( SUFFIX_EOF_EXP_NAME ) ; if ( c == ':' ) { c = ( mInputPtr < mInputEnd ) ? mInputBuffer [ mInputPtr ++ ] : getNextCharFromCurrent ( SUFFIX_EOF_EXP_NAME ) ; mElementStack . push ( str , parseLocalName ( c ) ) ; c = ( mInputPtr < mInputEnd ) ? mInputBuffer [ mInputPtr ++ ] : getNextCharFromCurrent ( SUFFIX_IN_ELEMENT ) ; } else { mElementStack . push ( null , str ) ; } empty = ( c == '>' ) ? false : handleNsAttrs ( c ) ; } else { mElementStack . push ( null , parseFullName ( c ) ) ; c = ( mInputPtr < mInputEnd ) ? mInputBuffer [ mInputPtr ++ ] : getNextCharFromCurrent ( SUFFIX_IN_ELEMENT ) ; empty = ( c == '>' ) ? false : handleNonNsAttrs ( c ) ; } if ( ! empty ) { ++ mCurrDepth ; } mStEmptyElem = empty ; int vld = mElementStack . resolveAndValidateElement ( ) ; mVldContent = vld ; mValidateText = ( vld == XMLValidator . CONTENT_ALLOW_VALIDATABLE_TEXT ) ; }
Method that takes care of parsing of start elements ; including full parsing of namespace declarations and attributes as well as namespace resolution .
444
private void readPI ( ) throws XMLStreamException { int ptr = mInputPtr ; int start = ptr ; char [ ] inputBuf = mInputBuffer ; int inputLen = mInputEnd ; outer_loop : while ( ptr < inputLen ) { char c = inputBuf [ ptr ++ ] ; if ( c < CHAR_SPACE ) { if ( c == '\n' ) { markLF ( ptr ) ; } else if ( c == '\r' ) { if ( ptr < inputLen && ! mNormalizeLFs ) { if ( inputBuf [ ptr ] == '\n' ) { ++ ptr ; } markLF ( ptr ) ; } else { -- ptr ; break ; } } else if ( c != '\t' ) { throwInvalidSpace ( c ) ; } } else if ( c == '?' ) { while ( true ) { if ( ptr >= inputLen ) { -- ptr ; break outer_loop ; } c = inputBuf [ ptr ++ ] ; if ( c == '>' ) { mInputPtr = ptr ; mTextBuffer . resetWithShared ( inputBuf , start , ptr - start - 2 ) ; return ; } if ( c != '?' ) { -- ptr ; break ; } } } } mInputPtr = ptr ; mTextBuffer . resetWithCopy ( inputBuf , start , ptr - start ) ; readPI2 ( mTextBuffer ) ; }
Method that parses a processing instruction s data portion ; at this point target has been parsed .
445
private final boolean readSpacePrimary ( char c , boolean prologWS ) throws XMLStreamException { int ptr = mInputPtr ; char [ ] inputBuf = mInputBuffer ; int inputLen = mInputEnd ; int start = ptr - 1 ; while ( true ) { if ( c > CHAR_SPACE ) { mInputPtr = -- ptr ; mTextBuffer . resetWithShared ( mInputBuffer , start , ptr - start ) ; return true ; } if ( c == '\n' ) { markLF ( ptr ) ; } else if ( c == '\r' ) { if ( ptr >= mInputEnd ) { -- ptr ; break ; } if ( mNormalizeLFs ) { if ( inputBuf [ ptr ] == '\n' ) { -- ptr ; break ; } inputBuf [ ptr - 1 ] = '\n' ; } else { if ( inputBuf [ ptr ] == '\n' ) { ++ ptr ; } } markLF ( ptr ) ; } else if ( c != CHAR_SPACE && c != '\t' ) { throwInvalidSpace ( c ) ; } if ( ptr >= inputLen ) { break ; } c = inputBuf [ ptr ++ ] ; } mInputPtr = ptr ; mTextBuffer . resetWithShared ( inputBuf , start , ptr - start ) ; return false ; }
Reading whitespace should be very similar to reading normal text ; although couple of simplifications can be made . Further since this method is very unlikely to be of much performance concern some optimizations are left out where it simplifies code .
446
protected XMLStreamException _constructUnexpectedInTyped ( int nextToken ) { if ( nextToken == START_ELEMENT ) { return _constructTypeException ( "Element content can not contain child START_ELEMENT when using Typed Access methods" , null ) ; } return _constructTypeException ( "Expected a text token, got " + tokenTypeDesc ( nextToken ) , null ) ; }
Method called to report a problem with
447
public static DTDSubset readInternalSubset ( WstxInputData srcData , WstxInputSource input , ReaderConfig cfg , boolean constructFully , int xmlVersion ) throws XMLStreamException { FullDTDReader r = new FullDTDReader ( input , cfg , constructFully , xmlVersion ) ; r . copyBufferStateFrom ( srcData ) ; DTDSubset ss ; try { ss = r . parseDTD ( ) ; } finally { srcData . copyBufferStateFrom ( r ) ; } return ss ; }
Method called to read in the internal subset definition .
448
public static DTDSubset readExternalSubset ( WstxInputSource src , ReaderConfig cfg , DTDSubset intSubset , boolean constructFully , int xmlVersion ) throws XMLStreamException { FullDTDReader r = new FullDTDReader ( src , cfg , intSubset , constructFully , xmlVersion ) ; return r . parseDTD ( ) ; }
Method called to read in the external subset definition .
449
public void setFlattenWriter ( Writer w , boolean inclComments , boolean inclConditionals , boolean inclPEs ) { mFlattenWriter = new DTDWriter ( w , inclComments , inclConditionals , inclPEs ) ; }
Method that will set specified Writer as the flattening writer ; writer used to output flattened version of DTD read in . This is similar to running a C - preprocessor on C - sources except that defining writer will not prevent normal parsing of DTD itself .
450
private void expandPE ( ) throws XMLStreamException { String id ; char c ; if ( mCheckForbiddenPEs ) { throwForbiddenPE ( ) ; } if ( mFlattenWriter != null ) { mFlattenWriter . flush ( mInputBuffer , mInputPtr - 1 ) ; mFlattenWriter . disableOutput ( ) ; c = ( mInputPtr < mInputEnd ) ? mInputBuffer [ mInputPtr ++ ] : dtdNextFromCurr ( ) ; id = readDTDName ( c ) ; try { c = ( mInputPtr < mInputEnd ) ? mInputBuffer [ mInputPtr ++ ] : dtdNextFromCurr ( ) ; } finally { mFlattenWriter . enableOutput ( mInputPtr ) ; } } else { c = ( mInputPtr < mInputEnd ) ? mInputBuffer [ mInputPtr ++ ] : dtdNextFromCurr ( ) ; id = readDTDName ( c ) ; c = ( mInputPtr < mInputEnd ) ? mInputBuffer [ mInputPtr ++ ] : dtdNextFromCurr ( ) ; } if ( c != ';' ) { throwDTDUnexpectedChar ( c , "; expected ';' to end parameter entity name" ) ; } mExpandingPE = true ; expandEntity ( id , true , ENTITY_EXP_PE ) ; }
Method called to handle expansion of parameter entities . When called % character has been encountered as a reference indicator and now we should get parameter entity name .
451
protected String checkDTDKeyword ( String exp ) throws XMLStreamException { int i = 0 ; int len = exp . length ( ) ; char c = ' ' ; for ( ; i < len ; ++ i ) { if ( mInputPtr < mInputEnd ) { c = mInputBuffer [ mInputPtr ++ ] ; } else { c = dtdNextIfAvailable ( ) ; if ( c == CHAR_NULL ) { return exp . substring ( 0 , i ) ; } } if ( c != exp . charAt ( i ) ) { break ; } } if ( i == len ) { c = dtdNextIfAvailable ( ) ; if ( c == CHAR_NULL ) { return null ; } if ( ! isNameChar ( c ) ) { -- mInputPtr ; return null ; } } StringBuilder sb = new StringBuilder ( exp . substring ( 0 , i ) ) ; sb . append ( c ) ; while ( true ) { c = dtdNextIfAvailable ( ) ; if ( c == CHAR_NULL ) { break ; } if ( ! isNameChar ( c ) && c != ':' ) { -- mInputPtr ; break ; } sb . append ( c ) ; } return sb . toString ( ) ; }
Method called to verify whether input has specified keyword ; if it has returns null and points to char after the keyword ; if not returns whatever constitutes a keyword matched for error reporting purposes .
452
private StructValidator readMixedSpec ( PrefixedName elemName , boolean construct ) throws XMLStreamException { String keyw = checkDTDKeyword ( "PCDATA" ) ; if ( keyw != null ) { _reportWFCViolation ( "Unrecognized directive #" + keyw + "'; expected #PCDATA (or element name)" ) ; } HashMap < PrefixedName , ContentSpec > m = new LinkedHashMap < PrefixedName , ContentSpec > ( ) ; while ( true ) { char c = skipDtdWs ( true ) ; if ( c == ')' ) { break ; } if ( c == '|' ) { c = skipDtdWs ( true ) ; } else if ( c == ',' ) { throwDTDUnexpectedChar ( c , " (sequences not allowed within mixed content)" ) ; } else if ( c == '(' ) { throwDTDUnexpectedChar ( c , " (sub-content specs not allowed within mixed content)" ) ; } else { throwDTDUnexpectedChar ( c , "; expected either '|' to separate elements, or ')' to close the list" ) ; } PrefixedName n = readDTDQName ( c ) ; Object old = m . put ( n , TokenContentSpec . construct ( ' ' , n ) ) ; if ( old != null ) { if ( mCfgFullyValidating ) { throwDTDElemError ( "duplicate child element <" + n + "> in mixed content model" , elemName ) ; } } } char c = ( mInputPtr < mInputEnd ) ? mInputBuffer [ mInputPtr ++ ] : getNextChar ( getErrorMsg ( ) ) ; if ( c != '*' ) { if ( m . size ( ) > 0 ) { _reportWFCViolation ( "Missing trailing '*' after a non-empty mixed content specification" ) ; } -- mInputPtr ; } if ( ! construct ) { return null ; } if ( m . isEmpty ( ) ) { return EmptyValidator . getPcdataInstance ( ) ; } ContentSpec spec = ChoiceContentSpec . constructMixed ( mCfgNsEnabled , m . values ( ) ) ; StructValidator val = spec . getSimpleValidator ( ) ; if ( val == null ) { DFAState dfa = DFAState . constructDFA ( spec ) ; val = new DFAValidator ( dfa ) ; } return val ; }
Method called to parse what seems like a mixed content specification .
453
protected void handleUndeclaredEntity ( String id ) throws XMLStreamException { _reportVCViolation ( "Undeclared parameter entity '" + id + "'." ) ; if ( mCurrAttrDefault != null ) { Location loc = getLastCharLocation ( ) ; if ( mExpandingPE ) { mCurrAttrDefault . addUndeclaredPE ( id , loc ) ; } else { mCurrAttrDefault . addUndeclaredGE ( id , loc ) ; } } if ( mEventListener != null ) { if ( mExpandingPE ) { mEventListener . dtdSkippedEntity ( "%" + id ) ; } } }
Undeclared parameter entity is a VC not WFC ...
454
public void outputNamespaceDeclarations ( XMLStreamWriter w ) throws XMLStreamException { for ( int i = 0 , len = mNamespaces . size ( ) ; i < len ; ++ i ) { Namespace ns = mNamespaces . get ( i ) ; if ( ns . isDefaultNamespaceDeclaration ( ) ) { w . writeDefaultNamespace ( ns . getNamespaceURI ( ) ) ; } else { w . writeNamespace ( ns . getPrefix ( ) , ns . getNamespaceURI ( ) ) ; } } }
Method called by the matching start element class to output all namespace declarations active in current namespace scope if any .
455
public char [ ] allocMediumCBuffer ( int minSize ) { if ( mCurrRecycler != null ) { char [ ] result = mCurrRecycler . getMediumCBuffer ( minSize ) ; if ( result != null ) { return result ; } } return new char [ minSize ] ; }
Method called to allocate intermediate recyclable copy buffers
456
public static BranchingReaderSource constructDocumentSource ( ReaderConfig cfg , InputBootstrapper bs , String pubId , SystemId sysId , Reader r , boolean realClose ) { URL url = cfg . getBaseURL ( ) ; if ( url != null ) { sysId = SystemId . construct ( url ) ; } BranchingReaderSource rs = new BranchingReaderSource ( cfg , pubId , sysId , r , realClose ) ; if ( bs != null ) { rs . setInputOffsets ( bs . getInputTotal ( ) , bs . getInputRow ( ) , - bs . getInputColumn ( ) ) ; } return rs ; }
Factory method used for creating the main - level document reader source .
457
public static WstxInputSource constructCharArraySource ( WstxInputSource parent , String fromEntity , char [ ] text , int offset , int len , Location loc , URL src ) { SystemId sysId = SystemId . construct ( loc . getSystemId ( ) , src ) ; return new CharArraySource ( parent , fromEntity , text , offset , len , loc , sysId ) ; }
Factory method usually used to expand internal parsed entities ; in which case context remains mostly the same .
458
protected SimpleOutputElement createChild ( String localName ) { mAttrSet = null ; return new SimpleOutputElement ( this , null , localName , mDefaultNsURI , mNsMapping ) ; }
Simplest factory method which gets called when a 1 - argument element output method is called . It is then assumed to use the default namespce .
459
protected SimpleOutputElement createChild ( String prefix , String localName , String uri ) { mAttrSet = null ; return new SimpleOutputElement ( this , prefix , localName , uri , mNsMapping ) ; }
Full factory method used for normal namespace qualified output methods .
460
public void configureForSpeed ( ) { doCoalesceText ( false ) ; doPreserveLocation ( false ) ; doReportPrologWhitespace ( false ) ; doInternNsURIs ( true ) ; doXmlIdUniqChecks ( false ) ; doCacheDTDs ( true ) ; doParseLazily ( true ) ; setShortestReportedTextSegment ( 16 ) ; setInputBufferLength ( 8000 ) ; }
Method to call to make the Reader created be as fast as possible reading documents especially for long - running processes where caching is likely to help .
461
@ SuppressWarnings ( "cast" ) public static int calcHash ( char [ ] buffer , int start , int len ) { int hash = ( int ) buffer [ start ] ; for ( int i = 1 ; i < len ; ++ i ) { hash = ( hash * 31 ) + ( int ) buffer [ start + i ] ; } return hash ; }
Implementation of a hashing method for variable length Strings . Most of the time intention is that this calculation is done by caller during parsing not here ; however sometimes it needs to be done for parsed String too .
462
private void copyArrays ( ) { String [ ] oldSyms = mSymbols ; int size = oldSyms . length ; mSymbols = new String [ size ] ; System . arraycopy ( oldSyms , 0 , mSymbols , 0 , size ) ; Bucket [ ] oldBuckets = mBuckets ; size = oldBuckets . length ; mBuckets = new Bucket [ size ] ; System . arraycopy ( oldBuckets , 0 , mBuckets , 0 , size ) ; }
Method called when copy - on - write is needed ; generally when first change is made to a derived symbol table .
463
public void normalizeDefault ( ) { String val = mDefValue . getValue ( ) ; if ( val . length ( ) > 0 ) { char [ ] cbuf = val . toCharArray ( ) ; String str = StringUtil . normalizeSpaces ( cbuf , 0 , cbuf . length ) ; if ( str != null ) { mDefValue . setValue ( str ) ; } } }
Method called to do initial normalization of the default attribute value without trying to verify its validity . Thus it s called independent of whether we are fully validating the document .
464
protected String reportValidationProblem ( InputProblemReporter rep , String msg ) throws XMLStreamException { rep . reportValidationProblem ( "Attribute definition '" + mName + "': " + msg ) ; return null ; }
Method called during parsing of DTD schema to report a problem . Note that unlike during actual validation we have no option of just gracefully listing problems and ignoring them ; an exception is always thrown .
465
protected void createStartElem ( String nsURI , String prefix , String localName , boolean isEmpty ) throws XMLStreamException { DOMOutputElement elem ; if ( ! mNsAware ) { if ( nsURI != null && nsURI . length ( ) > 0 ) { throwOutputError ( "Can not specify non-empty uri/prefix in non-namespace mode" ) ; } elem = mCurrElem . createAndAttachChild ( mDocument . createElement ( localName ) ) ; } else { if ( mNsRepairing ) { String actPrefix = validateElemPrefix ( prefix , nsURI , mCurrElem ) ; if ( actPrefix != null ) { if ( actPrefix . length ( ) != 0 ) { elem = mCurrElem . createAndAttachChild ( mDocument . createElementNS ( nsURI , actPrefix + ":" + localName ) ) ; } else { elem = mCurrElem . createAndAttachChild ( mDocument . createElementNS ( nsURI , localName ) ) ; } } else { if ( prefix == null ) { prefix = "" ; } actPrefix = generateElemPrefix ( prefix , nsURI , mCurrElem ) ; boolean hasPrefix = ( actPrefix . length ( ) != 0 ) ; if ( hasPrefix ) { localName = actPrefix + ":" + localName ; } elem = mCurrElem . createAndAttachChild ( mDocument . createElementNS ( nsURI , localName ) ) ; mOpenElement = elem ; if ( hasPrefix ) { writeNamespace ( actPrefix , nsURI ) ; elem . addPrefix ( actPrefix , nsURI ) ; } else { writeDefaultNamespace ( nsURI ) ; elem . setDefaultNsUri ( nsURI ) ; } } } else { if ( prefix == null && nsURI != null && nsURI . length ( ) > 0 ) { prefix = ( mSuggestedPrefixes == null ) ? null : mSuggestedPrefixes . get ( nsURI ) ; if ( prefix == null ) { throwOutputError ( "Can not find prefix for namespace \"" + nsURI + "\"" ) ; } } if ( prefix != null && prefix . length ( ) != 0 ) { localName = prefix + ":" + localName ; } elem = mCurrElem . createAndAttachChild ( mDocument . createElementNS ( nsURI , localName ) ) ; } } mOpenElement = elem ; if ( ! isEmpty ) { mCurrElem = elem ; } }
Method called by all start element write methods .
466
public void copyStartElement ( InputElementStack elemStack , AttributeCollector attrCollector ) throws IOException , XMLStreamException { String ln = elemStack . getLocalName ( ) ; boolean nsAware = elemStack . isNamespaceAware ( ) ; if ( nsAware ) { String prefix = elemStack . getPrefix ( ) ; if ( prefix != null && prefix . length ( ) > 0 ) { ln = prefix + ":" + ln ; } } writeStartElement ( ln ) ; if ( nsAware ) { int nsCount = elemStack . getCurrentNsCount ( ) ; if ( nsCount > 0 ) { for ( int i = 0 ; i < nsCount ; ++ i ) { String prefix = elemStack . getLocalNsPrefix ( i ) ; if ( prefix == null || prefix . length ( ) == 0 ) { prefix = XMLConstants . XML_NS_PREFIX ; } else { prefix = "xmlns:" + prefix ; } writeAttribute ( prefix , elemStack . getLocalNsURI ( i ) ) ; } } } int attrCount = mCfgCopyDefaultAttrs ? attrCollector . getCount ( ) : attrCollector . getSpecifiedCount ( ) ; if ( attrCount > 0 ) { for ( int i = 0 ; i < attrCount ; ++ i ) { attrCollector . writeAttribute ( i , mWriter , mValidator ) ; } } }
Element copier method implementation suitable to be used with non - namespace - aware writers . The only special thing here is that the copier can convert namespace declarations to equivalent attribute writes .
467
public final static int findIllegalNameChar ( String name , boolean nsAware , boolean xml11 ) { int len = name . length ( ) ; if ( len < 1 ) { return - 1 ; } char c = name . charAt ( 0 ) ; if ( c <= 0x7A ) { if ( c < 0x61 ) { if ( c < 0x41 ) { if ( c != ':' || nsAware ) { return 0 ; } } else if ( ( c > 0x5A ) && ( c != '_' ) ) { return 0 ; } } } else { if ( xml11 ) { if ( ! XmlChars . is11NameStartChar ( c ) ) { return 0 ; } } else { if ( ! XmlChars . is10NameStartChar ( c ) ) { return 0 ; } } } for ( int i = 1 ; i < len ; ++ i ) { c = name . charAt ( i ) ; if ( c <= 0x7A ) { if ( c >= 0x61 ) { continue ; } if ( c <= 0x5A ) { if ( c >= 0x41 ) { continue ; } if ( ( c >= 0x30 && c <= 0x39 ) || ( c == '.' ) || ( c == '-' ) ) { continue ; } if ( c == ':' && ! nsAware ) { continue ; } } else if ( c == 0x5F ) { continue ; } } else { if ( xml11 ) { if ( XmlChars . is11NameChar ( c ) ) { continue ; } } else { if ( XmlChars . is10NameChar ( c ) ) { continue ; } } } return i ; } return - 1 ; }
Method that can be called to check whether given String contains any characters that are not legal XML names .
468
public static String findEncodingFor ( Writer w ) { if ( w instanceof OutputStreamWriter ) { String enc = ( ( OutputStreamWriter ) w ) . getEncoding ( ) ; return normalize ( enc ) ; } return null ; }
Because of legacy encodings used by earlier JDK versions we need to be careful when accessing encoding names via JDK classes .
469
public static void throwRuntimeException ( Throwable t ) { throwIfUnchecked ( t ) ; throw new RuntimeException ( "[was " + t . getClass ( ) + "] " + t . getMessage ( ) , t ) ; }
Method that can be used to convert any Throwable to a RuntimeException ; conversion is only done for checked exceptions .
470
public static String trimEncoding ( String str , boolean upperCase ) { int i = 0 ; int len = str . length ( ) ; for ( ; i < len ; ++ i ) { char c = str . charAt ( i ) ; if ( c <= CHAR_SPACE || ! Character . isLetterOrDigit ( c ) ) { break ; } } if ( i == len ) { return str ; } StringBuilder sb = new StringBuilder ( ) ; if ( i > 0 ) { sb . append ( str . substring ( 0 , i ) ) ; } for ( ; i < len ; ++ i ) { char c = str . charAt ( i ) ; if ( c > CHAR_SPACE && Character . isLetterOrDigit ( c ) ) { if ( upperCase ) { c = Character . toUpperCase ( c ) ; } sb . append ( c ) ; } } return sb . toString ( ) ; }
Method that will remove all non - alphanumeric characters and optionally upper - case included letters from the given String .
471
public static URL urlFromCurrentDir ( ) throws IOException { File parent = new File ( "a" ) . getAbsoluteFile ( ) . getParentFile ( ) ; return toURL ( parent ) ; }
Method that tries to create and return URL that denotes current working directory . Usually used to create a context when one is not explicitly passed .
472
private static void throwIOException ( Exception mex , String sysId ) throws IOException { String msg = "[resolving systemId '" + sysId + "']: " + mex . toString ( ) ; throw ExceptionUtil . constructIOException ( msg , mex ) ; }
Helper method that tries to fully convert strange URL - specific exception to more general IO exception . Also to try to use JDK 1 . 4 feature without creating requirement uses reflection to try to set the root cause if we are running on JDK1 . 4
473
@ SuppressWarnings ( "unchecked" ) protected StartElement createStartElement ( QName name , Iterator < ? > attr , Iterator < ? > ns , NamespaceContext ctxt ) { return SimpleStartElement . construct ( mLocation , name , ( Iterator < Attribute > ) attr , ( Iterator < Namespace > ) ns , ctxt ) ; }
Must override this method to use a more efficient StartElement implementation
474
public static WstxInputSource resolveEntity ( WstxInputSource parent , URL pathCtxt , String entityName , String publicId , String systemId , XMLResolver customResolver , ReaderConfig cfg , int xmlVersion ) throws IOException , XMLStreamException { if ( pathCtxt == null ) { pathCtxt = parent . getSource ( ) ; if ( pathCtxt == null ) { pathCtxt = URLUtil . urlFromCurrentDir ( ) ; } } if ( customResolver != null ) { Object source = customResolver . resolveEntity ( publicId , systemId , pathCtxt . toExternalForm ( ) , entityName ) ; if ( source != null ) { return sourceFrom ( parent , cfg , entityName , xmlVersion , source ) ; } } if ( systemId == null ) { throw new XMLStreamException ( "Can not resolve " + ( ( entityName == null ) ? "[External DTD subset]" : ( "entity '" + entityName + "'" ) ) + " without a system id (public id '" + publicId + "')" ) ; } URL url = URLUtil . urlFromSystemId ( systemId , pathCtxt ) ; return sourceFromURL ( parent , cfg , entityName , xmlVersion , url , publicId ) ; }
Basic external resource resolver implementation ; usable both with DTD and entity resolution .
475
public static WstxInputSource resolveEntityUsing ( WstxInputSource refCtxt , String entityName , String publicId , String systemId , XMLResolver resolver , ReaderConfig cfg , int xmlVersion ) throws IOException , XMLStreamException { URL ctxt = ( refCtxt == null ) ? null : refCtxt . getSource ( ) ; if ( ctxt == null ) { ctxt = URLUtil . urlFromCurrentDir ( ) ; } Object source = resolver . resolveEntity ( publicId , systemId , ctxt . toExternalForm ( ) , entityName ) ; return ( source == null ) ? null : sourceFrom ( refCtxt , cfg , entityName , xmlVersion , source ) ; }
A very simple utility expansion method used generally when the only way to resolve an entity is via passed resolver ; and where failing to resolve it is not fatal .
476
public void reportValidationProblem ( XMLValidationProblem prob ) throws XMLStreamException { if ( mVldProbHandler != null ) { mVldProbHandler . reportProblem ( prob ) ; } else { super . reportValidationProblem ( prob ) ; } }
If there is an error handler established call it .
477
private URI resolveExtSubsetPath ( String systemId ) throws IOException { URL ctxt = ( mInput == null ) ? null : mInput . getSource ( ) ; if ( ctxt == null ) { return URLUtil . uriFromSystemId ( systemId ) ; } URL url = URLUtil . urlFromSystemId ( systemId , ctxt ) ; try { return new URI ( url . toExternalForm ( ) ) ; } catch ( URISyntaxException e ) { throw new IOException ( "Failed to construct URI for external subset, URL = " + url . toExternalForm ( ) + ": " + e . getMessage ( ) ) ; } }
Method called to resolve path to external DTD subset given system identifier .
478
public static StreamBootstrapper getInstance ( String pubId , SystemId sysId , InputStream in ) { return new StreamBootstrapper ( pubId , sysId , in ) ; }
Factory method used when the underlying data provider is an actual stream .
479
public static StreamBootstrapper getInstance ( String pubId , SystemId sysId , byte [ ] data , int start , int end ) { return new StreamBootstrapper ( pubId , sysId , data , start , end ) ; }
Factory method used when the underlying data provider is a pre - allocated block source and no stream is used . Additionally the buffer passed is not owned by the bootstrapper or Reader that is created so it is not to be recycled .
480
protected void resolveStreamEncoding ( ) throws IOException , WstxException { mBytesPerChar = 0 ; mBigEndian = true ; if ( ensureLoaded ( 4 ) ) { bomblock : do { int quartet = ( mByteBuffer [ 0 ] << 24 ) | ( ( mByteBuffer [ 1 ] & 0xFF ) << 16 ) | ( ( mByteBuffer [ 2 ] & 0xFF ) << 8 ) | ( mByteBuffer [ 3 ] & 0xFF ) ; switch ( quartet ) { case 0x0000FEFF : mBigEndian = true ; mInputPtr = mBytesPerChar = 4 ; break bomblock ; case 0xFFFE0000 : mInputPtr = mBytesPerChar = 4 ; mBigEndian = false ; break bomblock ; case 0x0000FFFE : reportWeirdUCS4 ( "2143" ) ; break bomblock ; case 0x0FEFF0000 : reportWeirdUCS4 ( "3412" ) ; break bomblock ; } int msw = quartet >>> 16 ; if ( msw == 0xFEFF ) { mInputPtr = mBytesPerChar = 2 ; mBigEndian = true ; break ; } if ( msw == 0xFFFE ) { mInputPtr = mBytesPerChar = 2 ; mBigEndian = false ; break ; } if ( ( quartet >>> 8 ) == 0xEFBBBF ) { mInputPtr = 3 ; mBytesPerChar = 1 ; mBigEndian = true ; break ; } switch ( quartet ) { case 0x0000003c : mBigEndian = true ; mBytesPerChar = 4 ; break bomblock ; case 0x3c000000 : mBytesPerChar = 4 ; mBigEndian = false ; break bomblock ; case 0x00003c00 : reportWeirdUCS4 ( "2143" ) ; break bomblock ; case 0x003c0000 : reportWeirdUCS4 ( "3412" ) ; break bomblock ; case 0x003c003f : mBytesPerChar = 2 ; mBigEndian = true ; break bomblock ; case 0x3c003f00 : mBytesPerChar = 2 ; mBigEndian = false ; break bomblock ; case 0x3c3f786d : mBytesPerChar = 1 ; mBigEndian = true ; break bomblock ; case 0x4c6fa794 : mBytesPerChar = - 1 ; mEBCDIC = true ; mSingleByteTranslation = EBCDICCodec . getCp037Mapping ( ) ; break bomblock ; } } while ( false ) ; mHadBOM = ( mInputPtr > 0 ) ; mInputProcessed = - mInputPtr ; mInputRowStart = mInputPtr ; } mByteSizeFound = ( mBytesPerChar != 0 ) ; if ( ! mByteSizeFound ) { mBytesPerChar = 1 ; mBigEndian = true ; } }
Method called to try to figure out physical encoding the underlying input stream uses .
481
@ SuppressWarnings ( "resource" ) protected XMLValidationSchema doCreateSchema ( ReaderConfig rcfg , InputBootstrapper bs , String publicId , String systemIdStr , URL ctxt ) throws XMLStreamException { try { Reader r = bs . bootstrapInput ( rcfg , false , XmlConsts . XML_V_UNKNOWN ) ; if ( bs . declaredXml11 ( ) ) { rcfg . enableXml11 ( true ) ; } if ( ctxt == null ) { ctxt = URLUtil . urlFromCurrentDir ( ) ; } SystemId systemId = SystemId . construct ( systemIdStr , ctxt ) ; WstxInputSource src = InputSourceFactory . constructEntitySource ( rcfg , null , null , bs , publicId , systemId , XmlConsts . XML_V_UNKNOWN , r ) ; return FullDTDReader . readExternalSubset ( src , rcfg , null , true , bs . getDeclaredVersion ( ) ) ; } catch ( IOException ioe ) { throw new WstxIOException ( ioe ) ; } }
The main validator construction method called by all externally visible methods .
482
protected void doInitInputLocation ( WstxInputData reader ) { reader . mCurrInputProcessed = mInputProcessed ; reader . mCurrInputRow = mInputRow ; reader . mCurrInputRowStart = mInputRowStart ; }
Input location is easy to set as we ll start from the beginning of a File .
483
public String addMapping ( String prefix , String uri ) { String [ ] strs = mNsStrings ; int phash = prefix . hashCode ( ) ; for ( int ix = mScopeStart , end = mScopeEnd ; ix < end ; ix += 2 ) { String thisP = strs [ ix ] ; if ( thisP == prefix || ( thisP . hashCode ( ) == phash && thisP . equals ( prefix ) ) ) { String old = strs [ ix + 1 ] ; strs [ ix + 1 ] = uri ; return old ; } } if ( mScopeEnd >= strs . length ) { strs = DataUtil . growArrayBy ( strs , strs . length ) ; mNsStrings = strs ; } strs [ mScopeEnd ++ ] = prefix ; strs [ mScopeEnd ++ ] = uri ; return null ; }
Method to add a new prefix - to - URI mapping for the current scope . Note that it should NOT be used for the default namespace declaration
484
public String addGeneratedMapping ( String prefixBase , NamespaceContext ctxt , String uri , int [ ] seqArr ) { String [ ] strs = mNsStrings ; int seqNr = seqArr [ 0 ] ; String prefix ; main_loop : while ( true ) { prefix = ( prefixBase + seqNr ) . intern ( ) ; ++ seqNr ; int phash = prefix . hashCode ( ) ; for ( int ix = mScopeEnd - 2 ; ix >= 0 ; ix -= 2 ) { String thisP = strs [ ix ] ; if ( thisP == prefix || ( thisP . hashCode ( ) == phash && thisP . equals ( prefix ) ) ) { continue main_loop ; } } if ( ctxt != null && ctxt . getNamespaceURI ( prefix ) != null ) { continue ; } break ; } seqArr [ 0 ] = seqNr ; if ( mScopeEnd >= strs . length ) { strs = DataUtil . growArrayBy ( strs , strs . length ) ; mNsStrings = strs ; } strs [ mScopeEnd ++ ] = prefix ; strs [ mScopeEnd ++ ] = uri ; return prefix ; }
Method used to add a dynamic binding and return the prefix used to bind the specified namespace URI .
485
public int getAttributeAsArray ( int index , TypedArrayDecoder tad ) throws XMLStreamException { if ( mCurrToken != START_ELEMENT ) { throw new IllegalStateException ( ErrorConsts . ERR_STATE_NOT_STELEM ) ; } return mAttrCollector . decodeValues ( index , tad , this ) ; }
Method that allows reading contents of an attribute as an array of whitespace - separate tokens decoded using specified decoder .
486
public Reader bootstrapInput ( ReaderConfig cfg , boolean mainDoc , int xmlVersion ) throws IOException , XMLStreamException { mCharBuffer = ( cfg == null ) ? new char [ 128 ] : cfg . allocSmallCBuffer ( 128 ) ; initialLoad ( 7 ) ; if ( mInputEnd >= 7 ) { char c = mCharBuffer [ mInputPtr ] ; if ( c == CHAR_BOM_MARKER ) { c = mCharBuffer [ ++ mInputPtr ] ; } if ( c == '<' ) { if ( mCharBuffer [ mInputPtr + 1 ] == '?' && mCharBuffer [ mInputPtr + 2 ] == 'x' && mCharBuffer [ mInputPtr + 3 ] == 'm' && mCharBuffer [ mInputPtr + 4 ] == 'l' && mCharBuffer [ mInputPtr + 5 ] <= CHAR_SPACE ) { mInputPtr += 6 ; readXmlDecl ( mainDoc , xmlVersion ) ; if ( mFoundEncoding != null && mInputEncoding != null ) { verifyXmlEncoding ( cfg ) ; } } } else { if ( c == 0xEF ) { throw new WstxIOException ( "Unexpected first character (char code 0xEF), not valid in xml document: could be mangled UTF-8 BOM marker. Make sure that the Reader uses correct encoding or pass an InputStream instead" ) ; } } } if ( mInputPtr < mInputEnd ) { return new MergedReader ( cfg , mIn , mCharBuffer , mInputPtr , mInputEnd ) ; } return mIn ; }
Method called to do actual bootstrapping .
487
public String getValueByLocalName ( String localName ) { switch ( mAttrCount ) { case 4 : if ( mAttributes [ 0 ] . hasLocalName ( localName ) ) return getValue ( 0 ) ; if ( mAttributes [ 1 ] . hasLocalName ( localName ) ) return getValue ( 1 ) ; if ( mAttributes [ 2 ] . hasLocalName ( localName ) ) return getValue ( 2 ) ; if ( mAttributes [ 3 ] . hasLocalName ( localName ) ) return getValue ( 3 ) ; return null ; case 3 : if ( mAttributes [ 0 ] . hasLocalName ( localName ) ) return getValue ( 0 ) ; if ( mAttributes [ 1 ] . hasLocalName ( localName ) ) return getValue ( 1 ) ; if ( mAttributes [ 2 ] . hasLocalName ( localName ) ) return getValue ( 2 ) ; return null ; case 2 : if ( mAttributes [ 0 ] . hasLocalName ( localName ) ) return getValue ( 0 ) ; if ( mAttributes [ 1 ] . hasLocalName ( localName ) ) return getValue ( 1 ) ; return null ; case 1 : if ( mAttributes [ 0 ] . hasLocalName ( localName ) ) return getValue ( 0 ) ; return null ; case 0 : return null ; default : for ( int i = 0 , end = mAttrCount ; i < end ; ++ i ) { if ( mAttributes [ i ] . hasLocalName ( localName ) ) { return getValue ( i ) ; } } return null ; } }
Specialized version in which namespace information is completely ignored .
488
public final void decodeValue ( int index , TypedValueDecoder tvd ) throws IllegalArgumentException { if ( index < 0 || index >= mAttrCount ) { throwIndex ( index ) ; } char [ ] buf = mValueBuilder . getCharBuffer ( ) ; int start = mAttributes [ index ] . mValueStartOffset ; int end = getValueStartOffset ( index + 1 ) ; while ( true ) { if ( start >= end ) { tvd . handleEmptyValue ( ) ; return ; } if ( ! StringUtil . isSpace ( buf [ start ] ) ) { break ; } ++ start ; } while ( -- end > start && StringUtil . isSpace ( buf [ end ] ) ) { } tvd . decode ( buf , start , end + 1 ) ; }
Method called to decode the whole attribute value as a single typed value . Decoding is done using the decoder provided .
489
public final int decodeValues ( int index , TypedArrayDecoder tad , InputProblemReporter rep ) throws XMLStreamException { if ( index < 0 || index >= mAttrCount ) { throwIndex ( index ) ; } return decodeValues ( tad , rep , mValueBuilder . getCharBuffer ( ) , mAttributes [ index ] . mValueStartOffset , getValueStartOffset ( index + 1 ) ) ; }
Method called to decode the attribute value that consists of zero or more space - separated tokens . Decoding is done using the decoder provided .
490
private final static boolean checkExpand ( TypedArrayDecoder tad ) { if ( tad instanceof ValueDecoderFactory . BaseArrayDecoder ) { ( ( ValueDecoderFactory . BaseArrayDecoder ) tad ) . expand ( ) ; return true ; } return false ; }
Internal method used to see if we can expand the buffer that the array decoder has . Bit messy but simpler than having separately typed instances ; and called rarely so that performance downside of instanceof is irrelevant .
491
protected Attribute resolveNamespaceDecl ( int index , boolean internURI ) { Attribute ns = mNamespaces [ index ] ; String full = mNamespaceBuilder . getAllValues ( ) ; String uri ; if ( mNsCount == 0 ) { uri = full ; } else { ++ index ; if ( index < mNsCount ) { int endOffset = mNamespaces [ index ] . mValueStartOffset ; uri = ns . getValue ( full , endOffset ) ; } else { uri = ns . getValue ( full ) ; } } if ( internURI && uri . length ( ) > 0 ) { uri = sInternCache . intern ( uri ) ; } ns . mNamespaceURI = uri ; return ns ; }
Method called to resolve and initialize specified collected namespace declaration
492
public int addDefaultAttribute ( String localName , String uri , String prefix , String value ) throws XMLStreamException { int attrIndex = mAttrCount ; if ( attrIndex < 1 ) { initHashArea ( ) ; } int hash = localName . hashCode ( ) ; if ( uri != null && uri . length ( ) > 0 ) { hash ^= uri . hashCode ( ) ; } int index = hash & ( mAttrHashSize - 1 ) ; int [ ] map = mAttrMap ; if ( map [ index ] == 0 ) { map [ index ] = attrIndex + 1 ; } else { int currIndex = map [ index ] - 1 ; int spillIndex = mAttrSpillEnd ; map = spillAttr ( uri , localName , map , currIndex , spillIndex , hash , mAttrHashSize ) ; if ( map == null ) { return - 1 ; } map [ ++ spillIndex ] = attrIndex ; mAttrMap = map ; mAttrSpillEnd = ++ spillIndex ; } getAttrBuilder ( prefix , localName ) ; Attribute attr = mAttributes [ mAttrCount - 1 ] ; attr . mNamespaceURI = uri ; attr . setValue ( value ) ; return ( mAttrCount - 1 ) ; }
Method called by validator to insert an attribute that has a default value and wasn t yet included in collector s attribute set .
493
protected final void allocBuffers ( ) { if ( mAttributes == null ) { mAttributes = new Attribute [ 8 ] ; } if ( mValueBuilder == null ) { mValueBuilder = new TextBuilder ( EXP_ATTR_COUNT ) ; } }
Method called to initialize buffers that need not be immediately initialized
494
protected void skipInternalSubset ( ) throws XMLStreamException { while ( true ) { int i = getNextAfterWS ( ) ; if ( i < 0 ) { throwUnexpectedEOF ( SUFFIX_IN_DTD_INTERNAL ) ; } if ( i == '%' ) { skipPE ( ) ; continue ; } if ( i == '<' ) { char c = getNextSkippingPEs ( ) ; if ( c == '?' ) { skipPI ( ) ; } else if ( c == '!' ) { c = getNextSkippingPEs ( ) ; if ( c == '[' ) { ; } else if ( c == '-' ) { skipComment ( ) ; } else if ( c >= 'A' && c <= 'Z' ) { skipDeclaration ( c ) ; } else { skipDeclaration ( c ) ; } } else { -- mInputPtr ; } continue ; } if ( i == ']' ) { if ( mInput != mRootInput ) { throwParseError ( "Encountered int. subset end marker ']]>' in an expanded entity; has to be at main level." ) ; } break ; } throwUnexpectedChar ( i , SUFFIX_IN_DTD_INTERNAL + "; expected a '<' to start a directive, or \"]>\" to end internal subset." ) ; } }
Method that will skip through internal DTD subset without doing any parsing except for trying to match end of subset properly .
495
protected void doInitInputLocation ( WstxInputData reader ) { reader . mCurrInputProcessed = mContentStart . getCharacterOffset ( ) ; reader . mCurrInputRow = mContentStart . getLineNumber ( ) ; reader . mCurrInputRowStart = - mContentStart . getColumnNumber ( ) + 1 ; }
Unlike with reader source we won t start from beginning of a file but usually from somewhere in the middle ...
496
private final int _convertSurrogate ( int secondPart ) throws IOException { int firstPart = mSurrogate ; mSurrogate = 0 ; if ( secondPart < SURR2_FIRST || secondPart > SURR2_LAST ) { throw new IOException ( "Broken surrogate pair: first char 0x" + Integer . toHexString ( firstPart ) + ", second 0x" + Integer . toHexString ( secondPart ) + "; illegal combination" ) ; } return 0x10000 + ( ( firstPart - SURR1_FIRST ) << 10 ) + ( secondPart - SURR2_FIRST ) ; }
Method called to calculate UTF codepoint from a surrogate pair .
497
protected String getErrorDesc ( int errorType , int currEvent ) { switch ( errorType ) { case ERR_GETELEMTEXT_NOT_START_ELEM : return ErrorConsts . ERR_STATE_NOT_STELEM + ", got " + ErrorConsts . tokenTypeDesc ( currEvent ) ; case ERR_GETELEMTEXT_NON_TEXT_EVENT : return "Expected a text token, got " + ErrorConsts . tokenTypeDesc ( currEvent ) ; case ERR_NEXTTAG_NON_WS_TEXT : return "Only all-whitespace CHARACTERS/CDATA (or SPACE) allowed for nextTag(), got " + ErrorConsts . tokenTypeDesc ( currEvent ) ; case ERR_NEXTTAG_WRONG_TYPE : return "Got " + ErrorConsts . tokenTypeDesc ( currEvent ) + ", instead of START_ELEMENT, END_ELEMENT or SPACE" ; } return null ; }
Method called upon encountering a problem that should result in an exception being thrown . If non - null String is returned . that will be used as the message of exception thrown ; if null a standard message will be used instead .
498
final int getLeapMonth ( int cycle , int yearOfCycle ) { int [ ] leapMonths = this . getLeapMonths ( ) ; int elapsedYears = ( cycle - 1 ) * 60 + yearOfCycle - 1 ; int index = 2 * ( ( elapsedYears - leapMonths [ 0 ] ) / 3 ) ; int lm = 0 ; while ( ( index < leapMonths . length ) ) { int test = leapMonths [ index ] ; if ( test < elapsedYears ) { index += Math . max ( 2 * ( ( elapsedYears - test ) / 3 ) , 2 ) ; } else if ( test > elapsedYears ) { break ; } else { lm = leapMonths [ index + 1 ] ; break ; } } return lm ; }
number of leap month or zero if no leap year
499
boolean isValid ( int cycle , int yearOfCycle , EastAsianMonth month , int dayOfMonth ) { if ( ( cycle < 72 ) || ( cycle > 94 ) || ( yearOfCycle < 1 ) || ( yearOfCycle > 60 ) || ( ( cycle == 72 ) && ( yearOfCycle < 22 ) ) || ( ( cycle == 94 ) && ( yearOfCycle > 56 ) ) || ( dayOfMonth < 1 ) || ( dayOfMonth > 30 ) || ( month == null ) || ( month . isLeap ( ) && ( month . getNumber ( ) != this . getLeapMonth ( cycle , yearOfCycle ) ) ) ) { return false ; } else if ( dayOfMonth == 30 ) { long monthStart = this . firstDayOfMonth ( cycle , yearOfCycle , month ) ; long nextNewMoon = this . newMoonOnOrAfter ( monthStart + 1 ) ; return ( nextNewMoon - monthStart == 30 ) ; } return true ; }
true if valid else false