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 . createArtifact...
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_Cl...
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...
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 ) ; reportMissingSignatur...
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 . registerServic...
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 ; BaseNsCo...
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 == Simple...
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 ; } el...
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 ( IOExceptio...
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()" ) ; } ret...
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 , fully...
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 < PrefixedN...
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 , mNsA...
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 (...
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 { i...
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 . l...
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 ...
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...
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 f...
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 )...
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 ( v...
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 ...
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...
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 ( mInputBuf...
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 [ ...
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 ) ) ; c...
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 ...
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 =...
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 ...
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 , ...
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 " + tokenTypeD...
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 ; t...
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 ++ ] : d...
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 )...
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 ...
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 { mCurrAttrDefaul...
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 . wri...
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 ( c...
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 , s...
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 , m...
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 = mCurr...
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 && pr...
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 !=...
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 ( ) ;...
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 ( path...
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 ) ...
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 ( ) ) ; ...
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 ) ; sw...
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 ( ) ) { rc...
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 ) ) ) { Strin...
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 i...
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 )...
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 ...
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 ) ...
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 , getValueStartOff...
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 ] . mValueStartOffse...
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...
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 ==...
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 . toHexStr...
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 . tok...
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 (...
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 ) || ( m...
true if valid else false