idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
26,700
public < T > T get ( String key , Class < T > clazz , T defaultValue ) { Object obj = argMap . get ( key ) ; if ( obj == null ) { return defaultValue ; } return Reflection . toType ( obj , clazz ) ; }
Get the specified key s value from the unit input anc cast it into the type you want .
26,701
@ SuppressWarnings ( "unchecked" ) public < T > Set < T > getSet ( String key ) { return Reflection . toType ( get ( key ) , Set . class ) ; }
Get the set . Note you must be sure with the generic type or a class cast exception will be thrown .
26,702
public < T > T getArgBean ( Class < ? extends T > beanClass ) { return Reflection . toType ( argMap , beanClass ) ; }
Convert this unit request s argument map into java bean .
26,703
public static UnitRequest create ( String group , String unit ) { return new UnitRequest ( ) . setContext ( RequestContext . create ( ) . setGroup ( group ) . setUnit ( unit ) ) ; }
Create a new UnitRequest instance with the group and unit name .
26,704
public static UnitRequest create ( Class < ? extends Unit > unitClass ) { Unit unit = LocalUnitsManager . getUnitByUnitClass ( unitClass ) ; return create ( unit . getGroup ( ) . getName ( ) , unit . getName ( ) ) ; }
Create a new UnitRequest instance by the Unit class .
26,705
public void start ( ) throws Exception { Preconditions . checkState ( state . compareAndSet ( State . LATENT , State . STARTED ) , "Cannot be started more than once" ) ; startTask . set ( AfterConnectionEstablished . execute ( client , new Runnable ( ) { public void run ( ) { try { internalStart ( ) ; } finally { startTask . set ( null ) ; } } } ) ) ; }
Add this instance to the leadership election and attempt to acquire leadership .
26,706
public void start ( ) throws Exception { if ( ! state . compareAndSet ( State . LATENT , State . STARTED ) ) { throw new IllegalStateException ( ) ; } try { client . create ( ) . creatingParentContainersIfNeeded ( ) . forPath ( queuePath ) ; } catch ( KeeperException . NodeExistsException ignore ) { } if ( lockPath != null ) { try { client . create ( ) . creatingParentContainersIfNeeded ( ) . forPath ( lockPath ) ; } catch ( KeeperException . NodeExistsException ignore ) { } } if ( ! isProducerOnly || ( maxItems != QueueBuilder . NOT_SET ) ) { childrenCache . start ( ) ; } if ( ! isProducerOnly ) { service . submit ( new Callable < Object > ( ) { public Object call ( ) { runLoop ( ) ; return null ; } } ) ; } }
Start the queue . No other methods work until this is called
26,707
public boolean flushPuts ( long waitTime , TimeUnit timeUnit ) throws InterruptedException { long msWaitRemaining = TimeUnit . MILLISECONDS . convert ( waitTime , timeUnit ) ; synchronized ( putCount ) { while ( putCount . get ( ) > 0 ) { if ( msWaitRemaining <= 0 ) { return false ; } long startMs = System . currentTimeMillis ( ) ; putCount . wait ( msWaitRemaining ) ; long elapsedMs = System . currentTimeMillis ( ) - startMs ; msWaitRemaining -= elapsedMs ; } } return true ; }
Wait until any pending puts are committed
26,708
public int remove ( String id ) throws Exception { id = Preconditions . checkNotNull ( id , "id cannot be null" ) ; queue . checkState ( ) ; int count = 0 ; for ( String name : queue . getChildren ( ) ) { if ( parseId ( name ) . id . equals ( id ) ) { if ( queue . tryRemove ( name ) ) { ++ count ; } } } return count ; }
Remove any items with the given Id
26,709
private static String extendedKey ( Properties properties , String key ) { String extendedKey = extendedKey ( key ) ; return properties . containsKey ( extendedKey ) ? extendedKey : key ; }
For internal use only please do not rely on this method .
26,710
public void start ( ) { Preconditions . checkState ( Thread . currentThread ( ) . equals ( ourThread ) , "Not in the correct thread" ) ; client . addParentWatcher ( watcher ) ; }
SessionFailRetryLoop must be started
26,711
public void close ( ) { Preconditions . checkState ( Thread . currentThread ( ) . equals ( ourThread ) , "Not in the correct thread" ) ; failedSessionThreads . remove ( ourThread ) ; client . removeParentWatcher ( watcher ) ; }
Must be called in a finally handler when done with the loop
26,712
public static boolean verifyEnvironment ( ) { if ( ! PRODUCTION . equals ( getEnv ( ) ) ) { return true ; } else { File tokenFile = new File ( "/etc/xian/xian_runtime_production.token" ) ; if ( tokenFile . exists ( ) && tokenFile . isFile ( ) ) { String token = PlainFileUtil . readAll ( tokenFile ) ; return "cbab75c745ac9707cf75b719a76e81284abc04c0ae96e2506fd247e9a3d9ca04" . equals ( token ) ; } return false ; } }
Production safety check . Protection for production env .
26,713
public static CuratorFramework newClient ( String connectString , RetryPolicy retryPolicy ) { return newClient ( connectString , DEFAULT_SESSION_TIMEOUT_MS , DEFAULT_CONNECTION_TIMEOUT_MS , retryPolicy ) ; }
Create a new client with default session timeout and default connection timeout
26,714
public static CuratorFramework newClient ( String connectString , int sessionTimeoutMs , int connectionTimeoutMs , RetryPolicy retryPolicy ) { return builder ( ) . connectString ( connectString ) . sessionTimeoutMs ( sessionTimeoutMs ) . connectionTimeoutMs ( connectionTimeoutMs ) . retryPolicy ( retryPolicy ) . build ( ) ; }
Create a new client
26,715
public void invokeSlackWebhook ( ) { RestTemplate restTemplate = new RestTemplate ( ) ; RichMessage richMessage = new RichMessage ( "Just to test Slack's incoming webhooks." ) ; Attachment [ ] attachments = new Attachment [ 1 ] ; attachments [ 0 ] = new Attachment ( ) ; attachments [ 0 ] . setText ( "Some data relevant to your users." ) ; richMessage . setAttachments ( attachments ) ; try { logger . debug ( "Reply (RichMessage): {}" , new ObjectMapper ( ) . writeValueAsString ( richMessage ) ) ; } catch ( JsonProcessingException e ) { logger . debug ( "Error parsing RichMessage: " , e ) ; } try { restTemplate . postForEntity ( slackIncomingWebhookUrl , richMessage . encodedMessage ( ) , String . class ) ; } catch ( RestClientException e ) { logger . error ( "Error posting to Slack Incoming Webhook: " , e ) ; } }
Make a POST call to the incoming webhook url .
26,716
public void afterConnectionClosed ( WebSocketSession session , CloseStatus status ) { logger . debug ( "WebSocket closed: {}, Close Status: {}" , session , status . toString ( ) ) ; }
Invoked after the web socket connection is closed . You can override this method in the child classes .
26,717
protected void startRTMAndWebSocketConnection ( ) { slackService . connectRTM ( getSlackToken ( ) ) ; if ( slackService . getWebSocketUrl ( ) != null ) { webSocketManager = new WebSocketConnectionManager ( client ( ) , handler ( ) , slackService . getWebSocketUrl ( ) ) ; webSocketManager . start ( ) ; } else { logger . error ( "No web socket url returned by Slack." ) ; } }
Entry point where the web socket connection starts and after which your bot becomes live .
26,718
@ Controller ( events = EventType . QUICK_REPLY , pattern = "(yes|no)" ) public void onReceiveQuickReply ( Event event ) { if ( "yes" . equals ( event . getMessage ( ) . getQuickReply ( ) . getPayload ( ) ) ) { reply ( event , "Cool! You can type: \n 1) Show Buttons \n 2) Show List \n 3) Setup meeting" ) ; } else { reply ( event , "See you soon!" ) ; } }
This method gets invoked when the user clicks on a quick reply button whose payload is either yes or no .
26,719
@ Controller ( events = EventType . MESSAGE , pattern = "(?i)(bye|tata|ttyl|cya|see you)" ) public void showGithubLink ( Event event ) { reply ( event , new Message ( ) . setAttachment ( new Attachment ( ) . setType ( "template" ) . setPayload ( new Payload ( ) . setTemplateType ( "button" ) . setText ( "Bye. Happy coding!" ) . setButtons ( new Button [ ] { new Button ( ) . setType ( "web_url" ) . setTitle ( "View code" ) . setUrl ( "https://github.com/ramswaroop/jbot" ) } ) ) ) ) ; }
Show the github project url when the user says bye .
26,720
@ Controller ( events = EventType . PIN_ADDED ) public void onPinAdded ( WebSocketSession session , Event event ) { reply ( session , event , "Thanks for the pin! You can find all pinned items under channel details." ) ; }
Invoked when an item is pinned in the channel .
26,721
public void connectRTM ( String slackToken ) { RTM rtm = restTemplate . getForEntity ( slackApiEndpoints . getRtmConnectApi ( ) , RTM . class , slackToken ) . getBody ( ) ; currentUser = rtm . getSelf ( ) ; webSocketUrl = rtm . getUrl ( ) ; getImChannels ( slackToken , 200 , "" ) ; }
Start a RTM connection . Fetch the web socket url to connect to current user details and list of channel ids where the current user has had conversation .
26,722
private void getImChannels ( String slackToken , int limit , String nextCursor ) { try { Event event = restTemplate . getForEntity ( slackApiEndpoints . getImListApi ( ) , Event . class , slackToken , limit , nextCursor ) . getBody ( ) ; imChannelIds . addAll ( Arrays . stream ( event . getIms ( ) ) . map ( Channel :: getId ) . collect ( Collectors . toList ( ) ) ) ; if ( event . getResponseMetadata ( ) != null && ! StringUtils . isEmpty ( event . getResponseMetadata ( ) . getNextCursor ( ) ) ) { Thread . sleep ( 5000L ) ; getImChannels ( slackToken , limit , event . getResponseMetadata ( ) . getNextCursor ( ) ) ; } } catch ( Exception e ) { logger . error ( "Error fetching im channels for the bot: " , e ) ; } }
Fetch all im channels to determine direct message to the bot .
26,723
protected final void startConversation ( Event event , String methodName ) { startConversation ( event . getSender ( ) . getId ( ) , methodName ) ; }
Call this method to start a conversation .
26,724
private void invokeChainedMethod ( Event event ) { Queue < MethodWrapper > queue = conversationQueueMap . get ( event . getSender ( ) . getId ( ) ) ; if ( queue != null && ! queue . isEmpty ( ) ) { MethodWrapper methodWrapper = queue . peek ( ) ; try { EventType [ ] eventTypes = methodWrapper . getMethod ( ) . getAnnotation ( Controller . class ) . events ( ) ; for ( EventType eventType : eventTypes ) { if ( eventType . name ( ) . equalsIgnoreCase ( event . getType ( ) . name ( ) ) ) { methodWrapper . getMethod ( ) . invoke ( this , event ) ; return ; } } } catch ( Exception e ) { logger . error ( "Error invoking chained method: " , e ) ; } } }
Invoke the appropriate method in a conversation .
26,725
private String getPatternFromEventType ( Event event ) { switch ( event . getType ( ) ) { case MESSAGE : return event . getMessage ( ) . getText ( ) ; case QUICK_REPLY : return event . getMessage ( ) . getQuickReply ( ) . getPayload ( ) ; case POSTBACK : return event . getPostback ( ) . getPayload ( ) ; default : return event . getMessage ( ) . getText ( ) ; } }
Match the pattern with different attributes based on the event type .
26,726
private Queue < MethodWrapper > formConversationQueue ( Queue < MethodWrapper > queue , String methodName ) { MethodWrapper methodWrapper = methodNameMap . get ( methodName ) ; queue . add ( methodWrapper ) ; if ( StringUtils . isEmpty ( methodName ) ) { return queue ; } else { return formConversationQueue ( queue , methodWrapper . getNext ( ) ) ; } }
Form a Queue with all the methods responsible for a particular conversation .
26,727
@ SuppressWarnings ( "fallthrough" ) public static int murmur2 ( final byte [ ] data ) { int length = data . length ; int seed = 0x9747b28c ; final int m = 0x5bd1e995 ; final int r = 24 ; int h = seed ^ length ; int length4 = length / 4 ; for ( int i = 0 ; i < length4 ; i ++ ) { final int i4 = i * 4 ; int k = ( data [ i4 + 0 ] & 0xff ) + ( ( data [ i4 + 1 ] & 0xff ) << 8 ) + ( ( data [ i4 + 2 ] & 0xff ) << 16 ) + ( ( data [ i4 + 3 ] & 0xff ) << 24 ) ; k *= m ; k ^= k >>> r ; k *= m ; h *= m ; h ^= k ; } switch ( length % 4 ) { case 3 : h ^= ( data [ ( length & ~ 3 ) + 2 ] & 0xff ) << 16 ; case 2 : h ^= ( data [ ( length & ~ 3 ) + 1 ] & 0xff ) << 8 ; case 1 : h ^= data [ length & ~ 3 ] & 0xff ; h *= m ; default : } h ^= h >>> 13 ; h *= m ; h ^= h >>> 15 ; return h ; }
Generates 32 bit murmur2 hash from byte array
26,728
private void prepareTopic ( final Map < String , InternalTopicMetadata > topicPartitions ) { log . debug ( "Starting to validate internal topics {} in partition assignor." , topicPartitions ) ; final Map < String , InternalTopicConfig > topicsToMakeReady = new HashMap < > ( ) ; for ( final InternalTopicMetadata metadata : topicPartitions . values ( ) ) { final InternalTopicConfig topic = metadata . config ; final int numPartitions = metadata . numPartitions ; if ( numPartitions < 0 ) { throw new StreamsException ( String . format ( "%sTopic [%s] number of partitions not defined" , logPrefix , topic . name ( ) ) ) ; } topic . setNumberOfPartitions ( numPartitions ) ; topicsToMakeReady . put ( topic . name ( ) , topic ) ; } if ( ! topicsToMakeReady . isEmpty ( ) ) { internalTopicManager . makeReady ( topicsToMakeReady ) ; } log . debug ( "Completed validating internal topics {} in partition assignor." , topicPartitions ) ; }
Internal helper function that creates a Kafka topic
26,729
ColumnRange removeColumn ( int column ) { if ( isSingleCol ( ) ) { return null ; } else if ( column == left ) { left ++ ; return this ; } else if ( column + 1 == right ) { right -- ; return this ; } else { ColumnRange created = new ColumnRange ( this . element , this . locator , column + 1 , this . right ) ; created . next = this . next ; this . next = created ; this . right = column ; return created ; } }
Removes a column from the range possibly asking it to be destroyed or splitting it .
26,730
private State checkh ( State state ) throws DatatypeException , IOException { if ( state . context . length ( ) == 0 ) { state = appendToContext ( state ) ; } state . current = state . reader . read ( ) ; state = appendToContext ( state ) ; state = skipSpaces ( state ) ; boolean expectNumber = true ; for ( ; ; ) { switch ( state . current ) { default : if ( expectNumber ) reportNonNumber ( 'h' , state . current , state . context ) ; return state ; case '+' : case '-' : case '.' : case '0' : case '1' : case '2' : case '3' : case '4' : case '5' : case '6' : case '7' : case '8' : case '9' : break ; } state = checkArg ( 'h' , "x coordinate" , state ) ; state = skipCommaSpaces2 ( state ) ; expectNumber = state . skipped ; } }
Checks an h command .
26,731
private State skipSubPath ( State state ) throws IOException { for ( ; ; ) { switch ( state . current ) { case - 1 : case 'm' : case 'M' : return state ; default : break ; } state . current = state . reader . read ( ) ; state = appendToContext ( state ) ; } }
Skips a sub - path .
26,732
private State skipSpaces ( State state ) throws IOException { for ( ; ; ) { switch ( state . current ) { default : return state ; case 0x20 : case 0x09 : case 0x0D : case 0x0A : } state . current = state . reader . read ( ) ; state = appendToContext ( state ) ; } }
Skips the whitespaces in the current reader .
26,733
private void appendColumnRange ( ColumnRange colRange ) { if ( last == null ) { first = colRange ; last = colRange ; } else { last . setNext ( colRange ) ; last = colRange ; } }
Appends a column range to the linked list of column ranges .
26,734
public void characters ( char [ ] ch , int start , int length ) throws SAXException { try { for ( int j = 0 ; j < length ; j ++ ) { char c = ch [ start + j ] ; switch ( c ) { case '<' : this . writer . write ( "&lt;" ) ; break ; case '>' : this . writer . write ( "&gt;" ) ; break ; case '&' : this . writer . write ( "&amp;" ) ; break ; default : this . writer . write ( c ) ; } } } catch ( IOException ioe ) { throw ( SAXException ) new SAXException ( ioe ) . initCause ( ioe ) ; } }
Writes out characters .
26,735
public void endDocument ( ) throws SAXException { try { this . writer . close ( ) ; } catch ( IOException ioe ) { throw ( SAXException ) new SAXException ( ioe ) . initCause ( ioe ) ; } }
Must be called in the end .
26,736
public void endElement ( String namespaceURI , String localName , String qName ) throws SAXException { try { if ( XHTML_NS . equals ( namespaceURI ) && Arrays . binarySearch ( emptyElements , localName ) < 0 ) { this . writer . write ( "</" ) ; this . writer . write ( localName ) ; this . writer . write ( '>' ) ; } } catch ( IOException ioe ) { throw ( SAXException ) new SAXException ( ioe ) . initCause ( ioe ) ; } }
Writes an end tag if the element is an XHTML element and is not an empty element in HTML 4 . 01 Strict .
26,737
public void startDocument ( ) throws SAXException { try { switch ( doctype ) { case NO_DOCTYPE : return ; case DOCTYPE_HTML5 : writer . write ( "<!DOCTYPE html>\n" ) ; return ; case DOCTYPE_HTML401_STRICT : writer . write ( "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n" ) ; return ; case DOCTYPE_HTML401_TRANSITIONAL : writer . write ( "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n" ) ; return ; } } catch ( IOException ioe ) { throw ( SAXException ) new SAXException ( ioe ) . initCause ( ioe ) ; } }
Must be called first .
26,738
public void startElement ( String namespaceURI , String localName , String qName , Attributes atts ) throws SAXException { try { if ( XHTML_NS . equals ( namespaceURI ) ) { if ( "meta" . equals ( localName ) && ( ( atts . getIndex ( "" , "http-equiv" ) != - 1 ) || ( atts . getIndex ( "" , "httpequiv" ) != - 1 ) ) ) { return ; } this . writer . write ( '<' ) ; this . writer . write ( localName ) ; int length = atts . getLength ( ) ; boolean langPrinted = false ; for ( int i = 0 ; i < length ; i ++ ) { String ns = atts . getURI ( i ) ; String name = null ; if ( "" . equals ( ns ) ) { name = atts . getLocalName ( i ) ; } else if ( "http://www.w3.org/XML/1998/namespace" . equals ( ns ) && "lang" . equals ( atts . getLocalName ( i ) ) ) { name = "lang" ; } if ( name != null && ! ( langPrinted && "lang" . equals ( name ) ) ) { this . writer . write ( ' ' ) ; this . writer . write ( name ) ; if ( "lang" . equals ( name ) ) { langPrinted = true ; } if ( Arrays . binarySearch ( booleanAttributes , name ) < 0 ) { this . writer . write ( "=\"" ) ; String value = atts . getValue ( i ) ; for ( int j = 0 ; j < value . length ( ) ; j ++ ) { char c = value . charAt ( j ) ; switch ( c ) { case '<' : this . writer . write ( "&lt;" ) ; break ; case '>' : this . writer . write ( "&gt;" ) ; break ; case '&' : this . writer . write ( "&amp;" ) ; break ; case '"' : this . writer . write ( "&quot;" ) ; break ; default : this . writer . write ( c ) ; } } this . writer . write ( '"' ) ; } } } this . writer . write ( '>' ) ; if ( emitMeta && "head" . equals ( localName ) ) { this . writer . write ( "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=" ) ; this . writer . write ( encoding ) ; this . writer . write ( "\">" ) ; } } } catch ( IOException ioe ) { throw ( SAXException ) new SAXException ( ioe ) . initCause ( ioe ) ; } }
Writes a start tag if the element is an XHTML element .
26,739
private void fatal ( String message , char textFound , String textExpected ) throws SAXException { fatal ( message , Character . valueOf ( textFound ) . toString ( ) , textExpected ) ; }
Report a serious error .
26,740
private void parseComment ( ) throws Exception { boolean saved = expandPE ; expandPE = false ; parseUntil ( endDelimComment ) ; require ( '>' ) ; expandPE = saved ; handler . comment ( dataBuffer , 0 , dataBufferPos ) ; dataBufferPos = 0 ; }
Skip a comment .
26,741
private void parsePI ( ) throws SAXException , IOException { String name ; boolean saved = expandPE ; expandPE = false ; name = readNmtoken ( true ) ; if ( name . indexOf ( ':' ) >= 0 ) { fatal ( "Illegal character(':') in processing instruction name " , name , null ) ; } if ( "xml" . equalsIgnoreCase ( name ) ) { fatal ( "Illegal processing instruction target" , name , null ) ; } if ( ! tryRead ( endDelimPI ) ) { requireWhitespace ( ) ; parseUntil ( endDelimPI ) ; } expandPE = saved ; handler . processingInstruction ( name , dataBufferToString ( ) ) ; }
Parse a processing instruction and do a call - back .
26,742
private String parseXMLDecl ( String encoding ) throws SAXException , IOException { String version ; String encodingName = null ; String standalone = null ; int flags = LIT_DISABLE_CREF | LIT_DISABLE_PE | LIT_DISABLE_EREF ; require ( "version" ) ; parseEq ( ) ; checkLegalVersion ( version = readLiteral ( flags ) ) ; if ( ! version . equals ( "1.0" ) ) { if ( version . equals ( "1.1" ) ) { fatal ( "XML 1.1 not supported." ) ; } else { fatal ( "illegal XML version" , version , "1.0" ) ; } } else { xmlVersion = XML_10 ; } boolean white = tryWhitespace ( ) ; if ( tryRead ( "encoding" ) ) { if ( ! white ) { fatal ( "whitespace required before 'encoding='" ) ; } parseEq ( ) ; encodingName = readLiteral ( flags ) ; checkEncodingLiteral ( encodingName ) ; if ( reader == null ) { draconianInputStreamReader ( encodingName , is , true ) ; } else { checkEncodingMatch ( encoding , encodingName ) ; } } if ( encodingName != null ) { white = tryWhitespace ( ) ; } else { if ( encoding == null ) { draconianInputStreamReader ( "UTF-8" , is , false ) ; } warnAboutLackOfEncodingDecl ( encoding ) ; } if ( tryRead ( "standalone" ) ) { if ( ! white ) { fatal ( "whitespace required before 'standalone='" ) ; } parseEq ( ) ; standalone = readLiteral ( flags ) ; if ( "yes" . equals ( standalone ) ) { docIsStandalone = true ; } else if ( ! "no" . equals ( standalone ) ) { fatal ( "standalone flag must be 'yes' or 'no'" ) ; } } skipWhitespace ( ) ; require ( "?>" ) ; return encodingName ; }
Parse the XML declaration .
26,743
private void checkEncodingLiteral ( String encodingName ) throws SAXException { if ( encodingName == null ) { return ; } if ( encodingName . length ( ) == 0 ) { fatal ( "The empty string does not a legal encoding name." ) ; } char c = encodingName . charAt ( 0 ) ; if ( ! ( ( ( c >= 'a' ) && ( c <= 'z' ) ) || ( ( c >= 'A' ) && ( c <= 'Z' ) ) ) ) { fatal ( "The encoding name must start with an ASCII letter." ) ; } for ( int i = 1 ; i < encodingName . length ( ) ; i ++ ) { c = encodingName . charAt ( i ) ; if ( ! ( ( ( c >= 'a' ) && ( c <= 'z' ) ) || ( ( c >= 'A' ) && ( c <= 'Z' ) ) || ( ( c >= '0' ) && ( c <= '9' ) ) || ( c == '.' ) || ( c == '_' ) || ( c == '-' ) ) ) { fatal ( "Illegal character in encoding name: U+" + Integer . toHexString ( c ) + "." ) ; } } }
hsivonen 2006 - 04 - 28
26,744
private String parseTextDecl ( String encoding ) throws SAXException , IOException { String encodingName = null ; int flags = LIT_DISABLE_CREF | LIT_DISABLE_PE | LIT_DISABLE_EREF ; if ( tryRead ( "version" ) ) { String version ; parseEq ( ) ; checkLegalVersion ( version = readLiteral ( flags ) ) ; if ( ! version . equals ( "1.0" ) ) { if ( version . equals ( "1.1" ) ) { fatal ( "XML 1.1 not supported." ) ; } else { fatal ( "illegal XML version" , version , "1.0" ) ; } } requireWhitespace ( ) ; } require ( "encoding" ) ; parseEq ( ) ; encodingName = readLiteral ( flags ) ; checkEncodingLiteral ( encodingName ) ; if ( reader == null ) { draconianInputStreamReader ( encodingName , is , true ) ; } else { checkEncodingMatch ( encoding , encodingName ) ; } skipWhitespace ( ) ; require ( "?>" ) ; return encodingName ; }
Parse a text declaration .
26,745
private void parseMisc ( ) throws Exception { while ( true ) { skipWhitespace ( ) ; if ( tryRead ( startDelimPI ) ) { parsePI ( ) ; } else if ( tryRead ( startDelimComment ) ) { parseComment ( ) ; } else { return ; } } }
Parse miscellaneous markup outside the document element and DOCTYPE declaration .
26,746
private void parseDoctypedecl ( ) throws Exception { String rootName ; ExternalIdentifiers ids ; requireWhitespace ( ) ; rootName = readNmtoken ( true ) ; skipWhitespace ( ) ; ids = readExternalIds ( false , true ) ; handler . doctypeDecl ( rootName , ids . publicId , ids . systemId ) ; skipWhitespace ( ) ; if ( tryRead ( '[' ) ) { while ( true ) { doReport = expandPE = true ; skipWhitespace ( ) ; doReport = expandPE = false ; if ( tryRead ( ']' ) ) { break ; } else { peIsError = expandPE = true ; parseMarkupdecl ( ) ; peIsError = expandPE = false ; } } } skipWhitespace ( ) ; require ( '>' ) ; InputSource subset ; if ( ids . systemId == null ) { subset = handler . getExternalSubset ( rootName , handler . getSystemId ( ) ) ; } else { subset = null ; } if ( ( ids . systemId != null ) || ( subset != null ) ) { pushString ( null , ">" ) ; if ( ids . systemId != null ) { pushURL ( true , "[dtd]" , ids , null , null , null , true ) ; } else { handler . warn ( "modifying document by adding external subset" ) ; pushURL ( true , "[dtd]" , new ExternalIdentifiers ( subset . getPublicId ( ) , subset . getSystemId ( ) , null ) , subset . getCharacterStream ( ) , subset . getByteStream ( ) , subset . getEncoding ( ) , false ) ; } while ( true ) { doReport = expandPE = true ; skipWhitespace ( ) ; doReport = expandPE = false ; if ( tryRead ( '>' ) ) { break ; } else { expandPE = true ; parseMarkupdecl ( ) ; expandPE = false ; } } if ( inputStack . size ( ) != 1 ) { fatal ( "external subset has unmatched '>'" ) ; } } handler . endDoctype ( ) ; expandPE = false ; doReport = true ; }
Parse a document type declaration .
26,747
private void parseMarkupdecl ( ) throws Exception { char [ ] saved = null ; boolean savedPE = expandPE ; require ( '<' ) ; unread ( '<' ) ; expandPE = false ; if ( tryRead ( "<!ELEMENT" ) ) { saved = readBuffer ; expandPE = savedPE ; parseElementDecl ( ) ; } else if ( tryRead ( "<!ATTLIST" ) ) { saved = readBuffer ; expandPE = savedPE ; parseAttlistDecl ( ) ; } else if ( tryRead ( "<!ENTITY" ) ) { saved = readBuffer ; expandPE = savedPE ; parseEntityDecl ( ) ; } else if ( tryRead ( "<!NOTATION" ) ) { saved = readBuffer ; expandPE = savedPE ; parseNotationDecl ( ) ; } else if ( tryRead ( startDelimPI ) ) { saved = readBuffer ; expandPE = savedPE ; parsePI ( ) ; } else if ( tryRead ( startDelimComment ) ) { saved = readBuffer ; expandPE = savedPE ; parseComment ( ) ; } else if ( tryRead ( "<![" ) ) { saved = readBuffer ; expandPE = savedPE ; if ( inputStack . size ( ) > 0 ) { parseConditionalSect ( saved ) ; } else { fatal ( "conditional sections illegal in internal subset" ) ; } } else { fatal ( "expected markup declaration" ) ; } if ( readBuffer != saved ) { handler . verror ( "Illegal Declaration/PE nesting" ) ; } }
Parse a markup declaration in the internal or external DTD subset .
26,748
private void parseElement ( boolean maybeGetSubset ) throws Exception { String gi ; char c ; int oldElementContent = currentElementContent ; String oldElement = currentElement ; ElementDecl element ; tagAttributePos = 0 ; gi = readNmtoken ( true ) ; if ( maybeGetSubset ) { InputSource subset = handler . getExternalSubset ( gi , handler . getSystemId ( ) ) ; if ( subset != null ) { String publicId = subset . getPublicId ( ) ; String systemId = subset . getSystemId ( ) ; handler . warn ( "modifying document by adding DTD" ) ; handler . doctypeDecl ( gi , publicId , systemId ) ; pushString ( null , ">" ) ; pushURL ( true , "[dtd]" , new ExternalIdentifiers ( publicId , systemId , null ) , subset . getCharacterStream ( ) , subset . getByteStream ( ) , subset . getEncoding ( ) , false ) ; while ( true ) { doReport = expandPE = true ; skipWhitespace ( ) ; doReport = expandPE = false ; if ( tryRead ( '>' ) ) { break ; } else { expandPE = true ; parseMarkupdecl ( ) ; expandPE = false ; } } if ( inputStack . size ( ) != 1 ) { fatal ( "external subset has unmatched '>'" ) ; } handler . endDoctype ( ) ; } } currentElement = gi ; element = elementInfo . get ( gi ) ; currentElementContent = getContentType ( element , CONTENT_ANY ) ; boolean white = tryWhitespace ( ) ; c = readCh ( ) ; while ( ( c != '/' ) && ( c != '>' ) ) { unread ( c ) ; if ( ! white ) { fatal ( "need whitespace between attributes" ) ; } parseAttribute ( gi ) ; white = tryWhitespace ( ) ; c = readCh ( ) ; } Iterator < String > atts = declaredAttributes ( element ) ; if ( atts != null ) { String aname ; loop : while ( atts . hasNext ( ) ) { aname = atts . next ( ) ; for ( int i = 0 ; i < tagAttributePos ; i ++ ) { if ( tagAttributes [ i ] == aname ) { continue loop ; } } String value = getAttributeDefaultValue ( gi , aname ) ; if ( value == null ) { continue ; } handler . attribute ( aname , value , false ) ; } } switch ( c ) { case '>' : handler . startElement ( gi ) ; parseContent ( ) ; break ; case '/' : require ( '>' ) ; handler . startElement ( gi ) ; handler . endElement ( gi ) ; break ; } currentElement = oldElement ; currentElementContent = oldElementContent ; }
Parse an element with its tags .
26,749
private void parseAttribute ( String name ) throws Exception { String aname ; String type ; String value ; int flags = LIT_ATTRIBUTE | LIT_ENTITY_REF ; aname = readNmtoken ( true ) ; type = getAttributeType ( name , aname ) ; parseEq ( ) ; if ( handler . stringInterning ) { if ( ( type == "CDATA" ) || ( type == null ) ) { value = readLiteral ( flags ) ; } else { value = readLiteral ( flags | LIT_NORMALIZE ) ; } } else { if ( ( type == null ) || type . equals ( "CDATA" ) ) { value = readLiteral ( flags ) ; } else { value = readLiteral ( flags | LIT_NORMALIZE ) ; } } for ( int i = 0 ; i < tagAttributePos ; i ++ ) { if ( aname . equals ( tagAttributes [ i ] ) ) { fatal ( "duplicate attribute" , aname , null ) ; } } handler . attribute ( aname , value , true ) ; dataBufferPos = 0 ; if ( tagAttributePos == tagAttributes . length ) { String newAttrib [ ] = new String [ tagAttributes . length * 2 ] ; System . arraycopy ( tagAttributes , 0 , newAttrib , 0 , tagAttributePos ) ; tagAttributes = newAttrib ; } tagAttributes [ tagAttributePos ++ ] = aname ; }
Parse an attribute assignment .
26,750
private void parseContent ( ) throws Exception { char c ; while ( true ) { parseCharData ( ) ; c = readCh ( ) ; switch ( c ) { case '&' : c = readCh ( ) ; if ( c == '#' ) { parseCharRef ( ) ; } else { unread ( c ) ; parseEntityRef ( true ) ; } isDirtyCurrentElement = true ; break ; case '<' : dataBufferFlush ( ) ; c = readCh ( ) ; switch ( c ) { case '!' : c = readCh ( ) ; switch ( c ) { case '-' : require ( '-' ) ; isDirtyCurrentElement = false ; parseComment ( ) ; break ; case '[' : isDirtyCurrentElement = false ; require ( "CDATA[" ) ; handler . startCDATA ( ) ; inCDATA = true ; parseCDSect ( ) ; inCDATA = false ; handler . endCDATA ( ) ; break ; default : fatal ( "expected comment or CDATA section" , c , null ) ; break ; } break ; case '?' : isDirtyCurrentElement = false ; parsePI ( ) ; break ; case '/' : isDirtyCurrentElement = false ; parseETag ( ) ; return ; default : isDirtyCurrentElement = false ; unread ( c ) ; parseElement ( false ) ; break ; } } } }
Parse the content of an element .
26,751
private void parseElementDecl ( ) throws Exception { String name ; requireWhitespace ( ) ; name = readNmtoken ( true ) ; requireWhitespace ( ) ; parseContentspec ( name ) ; skipWhitespace ( ) ; require ( '>' ) ; }
Parse an element type declaration .
26,752
private void parseContentspec ( String name ) throws Exception { if ( tryRead ( "EMPTY" ) ) { setElement ( name , CONTENT_EMPTY , null , null ) ; if ( ! skippedPE ) { handler . getDeclHandler ( ) . elementDecl ( name , "EMPTY" ) ; } return ; } else if ( tryRead ( "ANY" ) ) { setElement ( name , CONTENT_ANY , null , null ) ; if ( ! skippedPE ) { handler . getDeclHandler ( ) . elementDecl ( name , "ANY" ) ; } return ; } else { String model ; char [ ] saved ; require ( '(' ) ; saved = readBuffer ; dataBufferAppend ( '(' ) ; skipWhitespace ( ) ; if ( tryRead ( "#PCDATA" ) ) { dataBufferAppend ( "#PCDATA" ) ; parseMixed ( saved ) ; model = dataBufferToString ( ) ; setElement ( name , CONTENT_MIXED , model , null ) ; } else { parseElements ( saved ) ; model = dataBufferToString ( ) ; setElement ( name , CONTENT_ELEMENTS , model , null ) ; } if ( ! skippedPE ) { handler . getDeclHandler ( ) . elementDecl ( name , model ) ; } } }
Content specification .
26,753
private void parseElements ( char [ ] saved ) throws Exception { char c ; char sep ; skipWhitespace ( ) ; parseCp ( ) ; skipWhitespace ( ) ; c = readCh ( ) ; switch ( c ) { case ')' : if ( readBuffer != saved ) { handler . verror ( "Illegal Group/PE nesting" ) ; } dataBufferAppend ( ')' ) ; c = readCh ( ) ; switch ( c ) { case '*' : case '+' : case '?' : dataBufferAppend ( c ) ; break ; default : unread ( c ) ; } return ; case ',' : case '|' : sep = c ; dataBufferAppend ( c ) ; break ; default : fatal ( "bad separator in content model" , c , null ) ; return ; } while ( true ) { skipWhitespace ( ) ; parseCp ( ) ; skipWhitespace ( ) ; c = readCh ( ) ; if ( c == ')' ) { if ( readBuffer != saved ) { handler . verror ( "Illegal Group/PE nesting" ) ; } dataBufferAppend ( ')' ) ; break ; } else if ( c != sep ) { fatal ( "bad separator in content model" , c , null ) ; return ; } else { dataBufferAppend ( c ) ; } } c = readCh ( ) ; switch ( c ) { case '?' : case '*' : case '+' : dataBufferAppend ( c ) ; return ; default : unread ( c ) ; return ; } }
Parse an element - content model .
26,754
private void parseCp ( ) throws Exception { if ( tryRead ( '(' ) ) { dataBufferAppend ( '(' ) ; parseElements ( readBuffer ) ; } else { dataBufferAppend ( readNmtoken ( true ) ) ; char c = readCh ( ) ; switch ( c ) { case '?' : case '*' : case '+' : dataBufferAppend ( c ) ; break ; default : unread ( c ) ; break ; } } }
Parse a content particle .
26,755
private void parseMixed ( char [ ] saved ) throws Exception { skipWhitespace ( ) ; if ( tryRead ( ')' ) ) { if ( readBuffer != saved ) { handler . verror ( "Illegal Group/PE nesting" ) ; } dataBufferAppend ( ")*" ) ; tryRead ( '*' ) ; return ; } skipWhitespace ( ) ; while ( ! tryRead ( ")" ) ) { require ( '|' ) ; dataBufferAppend ( '|' ) ; skipWhitespace ( ) ; dataBufferAppend ( readNmtoken ( true ) ) ; skipWhitespace ( ) ; } if ( readBuffer != saved ) { handler . verror ( "Illegal Group/PE nesting" ) ; } require ( '*' ) ; dataBufferAppend ( ")*" ) ; }
Parse mixed content .
26,756
private void parseAttlistDecl ( ) throws Exception { String elementName ; requireWhitespace ( ) ; elementName = readNmtoken ( true ) ; boolean white = tryWhitespace ( ) ; while ( ! tryRead ( '>' ) ) { if ( ! white ) { fatal ( "whitespace required before attribute definition" ) ; } parseAttDef ( elementName ) ; white = tryWhitespace ( ) ; } }
Parse an attribute list declaration .
26,757
private void parseAttDef ( String elementName ) throws Exception { String name ; String type ; String enumer = null ; name = readNmtoken ( true ) ; requireWhitespace ( ) ; type = readAttType ( ) ; if ( handler . stringInterning ) { if ( ( "ENUMERATION" == type ) || ( "NOTATION" == type ) ) { enumer = dataBufferToString ( ) ; } } else { if ( "ENUMERATION" . equals ( type ) || "NOTATION" . equals ( type ) ) { enumer = dataBufferToString ( ) ; } } requireWhitespace ( ) ; parseDefault ( elementName , name , type , enumer ) ; }
Parse a single attribute definition .
26,758
private String readAttType ( ) throws Exception { if ( tryRead ( '(' ) ) { parseEnumeration ( false ) ; return "ENUMERATION" ; } else { String typeString = readNmtoken ( true ) ; if ( handler . stringInterning ) { if ( "NOTATION" == typeString ) { parseNotationType ( ) ; return typeString ; } else if ( ( "CDATA" == typeString ) || ( "ID" == typeString ) || ( "IDREF" == typeString ) || ( "IDREFS" == typeString ) || ( "ENTITY" == typeString ) || ( "ENTITIES" == typeString ) || ( "NMTOKEN" == typeString ) || ( "NMTOKENS" == typeString ) ) { return typeString ; } } else { if ( "NOTATION" . equals ( typeString ) ) { parseNotationType ( ) ; return typeString ; } else if ( "CDATA" . equals ( typeString ) || "ID" . equals ( typeString ) || "IDREF" . equals ( typeString ) || "IDREFS" . equals ( typeString ) || "ENTITY" . equals ( typeString ) || "ENTITIES" . equals ( typeString ) || "NMTOKEN" . equals ( typeString ) || "NMTOKENS" . equals ( typeString ) ) { return typeString ; } } fatal ( "illegal attribute type" , typeString , null ) ; return null ; } }
Parse the attribute type .
26,759
private void parseEnumeration ( boolean isNames ) throws Exception { dataBufferAppend ( '(' ) ; skipWhitespace ( ) ; dataBufferAppend ( readNmtoken ( isNames ) ) ; skipWhitespace ( ) ; while ( ! tryRead ( ')' ) ) { require ( '|' ) ; dataBufferAppend ( '|' ) ; skipWhitespace ( ) ; dataBufferAppend ( readNmtoken ( isNames ) ) ; skipWhitespace ( ) ; } dataBufferAppend ( ')' ) ; }
Parse an enumeration .
26,760
private void parseDefault ( String elementName , String name , String type , String enumer ) throws Exception { int valueType = ATTRIBUTE_DEFAULT_SPECIFIED ; String value = null ; int flags = LIT_ATTRIBUTE ; boolean saved = expandPE ; String defaultType = null ; if ( ! skippedPE ) { flags |= LIT_ENTITY_REF ; if ( handler . stringInterning ) { if ( "CDATA" != type ) { flags |= LIT_NORMALIZE ; } } else { if ( ! "CDATA" . equals ( type ) ) { flags |= LIT_NORMALIZE ; } } } expandPE = false ; if ( tryRead ( '#' ) ) { if ( tryRead ( "FIXED" ) ) { defaultType = "#FIXED" ; valueType = ATTRIBUTE_DEFAULT_FIXED ; requireWhitespace ( ) ; value = readLiteral ( flags ) ; } else if ( tryRead ( "REQUIRED" ) ) { defaultType = "#REQUIRED" ; valueType = ATTRIBUTE_DEFAULT_REQUIRED ; } else if ( tryRead ( "IMPLIED" ) ) { defaultType = "#IMPLIED" ; valueType = ATTRIBUTE_DEFAULT_IMPLIED ; } else { fatal ( "illegal keyword for attribute default value" ) ; } } else { value = readLiteral ( flags ) ; } expandPE = saved ; setAttribute ( elementName , name , type , enumer , value , valueType ) ; if ( handler . stringInterning ) { if ( "ENUMERATION" == type ) { type = enumer ; } else if ( "NOTATION" == type ) { type = "NOTATION " + enumer ; } } else { if ( "ENUMERATION" . equals ( type ) ) { type = enumer ; } else if ( "NOTATION" . equals ( type ) ) { type = "NOTATION " + enumer ; } } if ( ! skippedPE ) { handler . getDeclHandler ( ) . attributeDecl ( elementName , name , type , defaultType , value ) ; } }
Parse the default value for an attribute .
26,761
private void parseConditionalSect ( char [ ] saved ) throws Exception { skipWhitespace ( ) ; if ( tryRead ( "INCLUDE" ) ) { skipWhitespace ( ) ; require ( '[' ) ; if ( readBuffer != saved ) { handler . verror ( "Illegal Conditional Section/PE nesting" ) ; } skipWhitespace ( ) ; while ( ! tryRead ( "]]>" ) ) { parseMarkupdecl ( ) ; skipWhitespace ( ) ; } } else if ( tryRead ( "IGNORE" ) ) { skipWhitespace ( ) ; require ( '[' ) ; if ( readBuffer != saved ) { handler . verror ( "Illegal Conditional Section/PE nesting" ) ; } char c ; expandPE = false ; for ( int nest = 1 ; nest > 0 ; ) { c = readCh ( ) ; switch ( c ) { case '<' : if ( tryRead ( "![" ) ) { nest ++ ; } break ; case ']' : if ( tryRead ( "]>" ) ) { nest -- ; } } } expandPE = true ; } else { fatal ( "conditional section must begin with INCLUDE or IGNORE" ) ; } }
Parse a conditional section .
26,762
private void parseCharRef ( boolean doFlush ) throws SAXException , IOException { int value = 0 ; char c ; if ( tryRead ( 'x' ) ) { loop1 : while ( true ) { c = readCh ( ) ; if ( c == ';' ) { break loop1 ; } else { int n = Character . digit ( c , 16 ) ; if ( n == - 1 ) { fatal ( "illegal character in character reference" , c , null ) ; break loop1 ; } value *= 16 ; value += n ; } } } else { loop2 : while ( true ) { c = readCh ( ) ; if ( c == ';' ) { break loop2 ; } else { int n = Character . digit ( c , 10 ) ; if ( n == - 1 ) { fatal ( "illegal character in character reference" , c , null ) ; break loop2 ; } value *= 10 ; value += c - '0' ; } } } if ( ( ( value < 0x0020 ) && ! ( ( value == '\n' ) || ( value == '\t' ) || ( value == '\r' ) ) ) || ( ( value >= 0xD800 ) && ( value <= 0xDFFF ) ) || ( value == 0xFFFE ) || ( value == 0xFFFF ) || ( value > 0x0010ffff ) ) { fatal ( "illegal XML character reference U+" + Integer . toHexString ( value ) ) ; } else if ( ( value >= 0x007F ) && ( value <= 0x009F ) ) { handler . warn ( "Character reference expands to a control character: U+00" + Integer . toHexString ( value ) + "." ) ; } if ( isPrivateUse ( value ) ) { warnAboutPrivateUseChar ( ) ; } if ( value <= 0x0000ffff ) { dataBufferAppend ( ( char ) value ) ; } else if ( value <= 0x0010ffff ) { value -= 0x10000 ; dataBufferAppend ( ( char ) ( 0xd800 | ( value >> 10 ) ) ) ; dataBufferAppend ( ( char ) ( 0xdc00 | ( value & 0x0003ff ) ) ) ; } else { fatal ( "character reference " + value + " is too large for UTF-16" , Integer . valueOf ( value ) . toString ( ) , null ) ; } if ( doFlush ) { dataBufferFlush ( ) ; } }
Read and interpret a character reference .
26,763
private void parseEntityRef ( boolean externalAllowed ) throws SAXException , IOException { String name ; name = readNmtoken ( true ) ; require ( ';' ) ; switch ( getEntityType ( name ) ) { case ENTITY_UNDECLARED : String message ; message = "reference to undeclared general entity " + name ; if ( skippedPE && ! docIsStandalone ) { handler . verror ( message ) ; if ( externalAllowed ) { handler . skippedEntity ( name ) ; } } else { fatal ( message ) ; } break ; case ENTITY_INTERNAL : pushString ( name , getEntityValue ( name ) ) ; char t = readCh ( ) ; unread ( t ) ; int bufferPosMark = readBufferPos ; int end = readBufferPos + getEntityValue ( name ) . length ( ) ; for ( int k = readBufferPos ; k < end ; k ++ ) { t = readCh ( ) ; if ( t == '&' ) { t = readCh ( ) ; if ( t == '#' ) { tryReadCharRef ( ) ; if ( readBufferPos >= end ) { break ; } k = readBufferPos ; continue ; } else if ( Character . isLetter ( t ) ) { unread ( t ) ; readNmtoken ( true ) ; require ( ';' ) ; if ( readBufferPos >= end ) { break ; } k = readBufferPos ; continue ; } fatal ( " malformed entity reference" ) ; } } readBufferPos = bufferPosMark ; break ; case ENTITY_TEXT : if ( externalAllowed ) { pushURL ( false , name , getEntityIds ( name ) , null , null , null , true ) ; } else { fatal ( "reference to external entity in attribute value." , name , null ) ; } break ; case ENTITY_NDATA : if ( externalAllowed ) { fatal ( "unparsed entity reference in content" , name , null ) ; } else { fatal ( "reference to external entity in attribute value." , name , null ) ; } break ; default : throw new RuntimeException ( ) ; } }
Parse and expand an entity reference .
26,764
private void parsePEReference ( ) throws SAXException , IOException { String name ; name = "%" + readNmtoken ( true ) ; require ( ';' ) ; switch ( getEntityType ( name ) ) { case ENTITY_UNDECLARED : handler . verror ( "reference to undeclared parameter entity " + name ) ; break ; case ENTITY_INTERNAL : if ( inLiteral ) { pushString ( name , getEntityValue ( name ) ) ; } else { pushString ( name , ' ' + getEntityValue ( name ) + ' ' ) ; } break ; case ENTITY_TEXT : if ( ! inLiteral ) { pushString ( null , " " ) ; } pushURL ( true , name , getEntityIds ( name ) , null , null , null , true ) ; if ( ! inLiteral ) { pushString ( null , " " ) ; } break ; } }
Parse and expand a parameter entity reference .
26,765
private void parseEntityDecl ( ) throws Exception { boolean peFlag = false ; int flags = 0 ; expandPE = false ; requireWhitespace ( ) ; if ( tryRead ( '%' ) ) { peFlag = true ; requireWhitespace ( ) ; } expandPE = true ; String name = readNmtoken ( true ) ; if ( name . indexOf ( ':' ) >= 0 ) { fatal ( "Illegal character(':') in entity name " , name , null ) ; } if ( peFlag ) { name = "%" + name ; } requireWhitespace ( ) ; char c = readCh ( ) ; unread ( c ) ; if ( ( c == '"' ) || ( c == '\'' ) ) { String value = readLiteral ( flags ) ; setInternalEntity ( name , value ) ; } else { ExternalIdentifiers ids = readExternalIds ( false , false ) ; boolean white = tryWhitespace ( ) ; if ( ! peFlag && tryRead ( "NDATA" ) ) { if ( ! white ) { fatal ( "whitespace required before NDATA" ) ; } requireWhitespace ( ) ; String notationName = readNmtoken ( true ) ; if ( ! skippedPE ) { setExternalEntity ( name , ENTITY_NDATA , ids , notationName ) ; handler . unparsedEntityDecl ( name , ids . publicId , ids . systemId , ids . baseUri , notationName ) ; } } else if ( ! skippedPE ) { setExternalEntity ( name , ENTITY_TEXT , ids , null ) ; handler . getDeclHandler ( ) . externalEntityDecl ( name , ids . publicId , handler . resolveURIs ( ) ? handler . absolutize ( ids . baseUri , ids . systemId , false ) : ids . systemId ) ; } } skipWhitespace ( ) ; require ( '>' ) ; }
Parse an entity declaration .
26,766
private void parseNotationDecl ( ) throws Exception { String nname ; ExternalIdentifiers ids ; requireWhitespace ( ) ; nname = readNmtoken ( true ) ; if ( nname . indexOf ( ':' ) >= 0 ) { fatal ( "Illegal character(':') in notation name " , nname , null ) ; } requireWhitespace ( ) ; ids = readExternalIds ( true , false ) ; setNotation ( nname , ids ) ; skipWhitespace ( ) ; require ( '>' ) ; }
Parse a notation declaration .
26,767
private void parseCharData ( ) throws Exception { char c ; int state = 0 ; boolean pureWhite = false ; if ( ( currentElementContent == CONTENT_ELEMENTS ) && ! isDirtyCurrentElement ) { pureWhite = true ; } while ( true ) { int i ; loop : for ( i = readBufferPos ; i < readBufferLength ; i ++ ) { advanceLocation ( ) ; switch ( c = readBuffer [ i ] ) { case '\n' : nextCharOnNewLine = true ; break ; case '\r' : case '\t' : case ' ' : break ; case '&' : case '<' : state = 1 ; rollbackLocation ( ) ; break loop ; case ']' : pureWhite = false ; if ( readBufferOverflow == - 1 ) { if ( ( i + 2 ) >= readBufferLength ) { reportText ( pureWhite , i ) ; readBufferOverflow = ']' ; fillBuffer ( ) ; i = readBufferPos ; } if ( ( readBuffer [ i + 1 ] == ']' ) && ( readBuffer [ i + 2 ] == '>' ) ) { state = 2 ; rollbackLocation ( ) ; break loop ; } } break ; default : if ( ( ( c < 0x0020 ) || ( c > 0xFFFD ) ) || ( ( c >= 0x007f ) && ( c <= 0x009f ) && ( c != 0x0085 ) && ( xmlVersion == XML_11 ) ) ) { fatal ( "illegal XML character U+" + Integer . toHexString ( c ) ) ; } else if ( ( c >= '\u007F' ) && ( c <= '\u009F' ) ) { handler . warn ( "Saw a control character: U+00" + Integer . toHexString ( c ) + "." ) ; } pureWhite = false ; } } reportText ( pureWhite , i ) ; if ( state != 0 ) { break ; } unread ( readCh ( ) ) ; } if ( ! pureWhite ) { isDirtyCurrentElement = true ; } if ( state != 1 ) { fatal ( "character data may not contain ']]>'" ) ; } }
Parse character data .
26,768
private void requireWhitespace ( ) throws SAXException , IOException { char c = readCh ( ) ; if ( isWhitespace ( c ) ) { skipWhitespace ( ) ; } else { fatal ( "whitespace required" , c , null ) ; } }
Require whitespace characters .
26,769
private void skipWhitespace ( ) throws SAXException , IOException { char c = readCh ( ) ; while ( isWhitespace ( c ) ) { c = readCh ( ) ; } unread ( c ) ; }
Skip whitespace characters .
26,770
private ExternalIdentifiers readExternalIds ( boolean inNotation , boolean isSubset ) throws Exception { char c ; ExternalIdentifiers ids = new ExternalIdentifiers ( ) ; int flags = LIT_DISABLE_CREF | LIT_DISABLE_PE | LIT_DISABLE_EREF ; if ( tryRead ( "PUBLIC" ) ) { requireWhitespace ( ) ; ids . publicId = readLiteral ( LIT_NORMALIZE | LIT_PUBID | flags ) ; if ( inNotation ) { skipWhitespace ( ) ; c = readCh ( ) ; unread ( c ) ; if ( ( c == '"' ) || ( c == '\'' ) ) { ids . systemId = readLiteral ( flags ) ; } } else { requireWhitespace ( ) ; ids . systemId = readLiteral ( flags ) ; } for ( int i = 0 ; i < ids . publicId . length ( ) ; i ++ ) { c = ids . publicId . charAt ( i ) ; if ( ( c >= 'a' ) && ( c <= 'z' ) ) { continue ; } if ( ( c >= 'A' ) && ( c <= 'Z' ) ) { continue ; } if ( " \r\n0123456789-' ()+,./:=?;!*#@$_%" . indexOf ( c ) != - 1 ) { continue ; } fatal ( "illegal PUBLIC id character U+" + Integer . toHexString ( c ) ) ; } } else if ( tryRead ( "SYSTEM" ) ) { requireWhitespace ( ) ; ids . systemId = readLiteral ( flags ) ; } else if ( ! isSubset ) { fatal ( "missing SYSTEM or PUBLIC keyword" ) ; } if ( ids . systemId != null ) { if ( ids . systemId . indexOf ( '#' ) != - 1 ) { handler . verror ( "SYSTEM id has a URI fragment: " + ids . systemId ) ; } ids . baseUri = handler . getSystemId ( ) ; if ( ( ids . baseUri == null ) && uriWarnings ) { handler . warn ( "No base URI; hope URI is absolute: " + ids . systemId ) ; } } return ids ; }
Try reading external identifiers . A system identifier is not required for notations .
26,771
private boolean isWhitespace ( char c ) { if ( c > 0x20 ) { return false ; } if ( ( c == 0x20 ) || ( c == 0x0a ) || ( c == 0x09 ) || ( c == 0x0d ) ) { return true ; } return false ; }
Test if a character is whitespace .
26,772
private void dataBufferAppend ( char c ) { if ( dataBufferPos >= dataBuffer . length ) { dataBuffer = ( char [ ] ) extendArray ( dataBuffer , dataBuffer . length , dataBufferPos ) ; } dataBuffer [ dataBufferPos ++ ] = c ; }
Add a character to the data buffer .
26,773
private void dataBufferNormalize ( ) { int i = 0 ; int j = 0 ; int end = dataBufferPos ; while ( ( j < end ) && ( dataBuffer [ j ] == ' ' ) ) { j ++ ; } while ( ( end > j ) && ( dataBuffer [ end - 1 ] == ' ' ) ) { end -- ; } while ( j < end ) { char c = dataBuffer [ j ++ ] ; if ( c == ' ' ) { while ( ( j < end ) && ( dataBuffer [ j ++ ] == ' ' ) ) { continue ; } dataBuffer [ i ++ ] = ' ' ; dataBuffer [ i ++ ] = dataBuffer [ j - 1 ] ; } else { dataBuffer [ i ++ ] = c ; } } dataBufferPos = i ; }
Normalise space characters in the data buffer .
26,774
private void dataBufferFlush ( ) throws SAXException { int saveLine = line ; int saveColumn = column ; line = linePrev ; column = columnPrev ; if ( ( currentElementContent == CONTENT_ELEMENTS ) && ( dataBufferPos > 0 ) && ! inCDATA ) { for ( int i = 0 ; i < dataBufferPos ; i ++ ) { if ( ! isWhitespace ( dataBuffer [ i ] ) ) { handler . charData ( dataBuffer , 0 , dataBufferPos ) ; dataBufferPos = 0 ; } } if ( dataBufferPos > 0 ) { handler . ignorableWhitespace ( dataBuffer , 0 , dataBufferPos ) ; dataBufferPos = 0 ; } } else if ( dataBufferPos > 0 ) { handler . charData ( dataBuffer , 0 , dataBufferPos ) ; dataBufferPos = 0 ; } line = saveLine ; column = saveColumn ; }
Flush the contents of the data buffer to the handler as appropriate and reset the buffer for new input .
26,775
private void require ( char delim ) throws SAXException , IOException { char c = readCh ( ) ; if ( c != delim ) { fatal ( "required character" , c , Character . valueOf ( delim ) . toString ( ) ) ; } }
Require a character to appear or throw an exception .
26,776
private Object extendArray ( Object array , int currentSize , int requiredSize ) { if ( requiredSize < currentSize ) { return array ; } else { Object newArray = null ; int newSize = currentSize * 2 ; if ( newSize <= requiredSize ) { newSize = requiredSize + 1 ; } if ( array instanceof char [ ] ) { newArray = new char [ newSize ] ; } else if ( array instanceof Object [ ] ) { newArray = new Object [ newSize ] ; } else { throw new RuntimeException ( ) ; } System . arraycopy ( array , 0 , newArray , 0 , currentSize ) ; return newArray ; } }
Ensure the capacity of an array allocating a new one if necessary . Usually extends only for name hash collisions .
26,777
private void filterCR ( boolean moreData ) { int i , j ; readBufferOverflow = - 1 ; loop : for ( i = j = readBufferPos ; j < readBufferLength ; i ++ , j ++ ) { switch ( readBuffer [ j ] ) { case '\r' : if ( j == readBufferLength - 1 ) { if ( moreData ) { readBufferOverflow = '\r' ; readBufferLength -- ; } else { readBuffer [ i ++ ] = '\n' ; } break loop ; } else if ( readBuffer [ j + 1 ] == '\n' ) { j ++ ; } readBuffer [ i ] = '\n' ; break ; case '\n' : default : readBuffer [ i ] = readBuffer [ j ] ; break ; } } readBufferLength = i ; }
Filter carriage returns in the read buffer . CRLF becomes LF ; CR becomes LF .
26,778
private void initializeVariables ( ) throws SAXException { prev = '\u0000' ; line = 0 ; column = 1 ; linePrev = 0 ; columnPrev = 1 ; nextCharOnNewLine = true ; dataBufferPos = 0 ; dataBuffer = new char [ DATA_BUFFER_INITIAL ] ; nameBufferPos = 0 ; nameBuffer = new char [ NAME_BUFFER_INITIAL ] ; elementInfo = new HashMap < > ( ) ; entityInfo = new HashMap < > ( ) ; notationInfo = new HashMap < > ( ) ; skippedPE = false ; currentElement = null ; currentElementContent = CONTENT_UNDECLARED ; sourceType = INPUT_NONE ; inputStack = new LinkedList < > ( ) ; entityStack = new LinkedList < > ( ) ; tagAttributePos = 0 ; tagAttributes = new String [ 100 ] ; readBufferOverflow = - 1 ; inLiteral = false ; expandPE = false ; peIsError = false ; doReport = false ; inCDATA = false ; symbolTable = new Object [ SYMBOL_TABLE_LENGTH ] [ ] ; if ( handler . checkNormalization ) { normalizationChecker = new NormalizationChecker ( handler ) ; normalizationChecker . setErrorHandler ( handler . getErrorHandler ( ) ) ; normalizationChecker . start ( ) ; } else { normalizationChecker = null ; } if ( handler . characterHandler != null ) { characterHandler = handler . characterHandler ; handler . characterHandler = null ; characterHandler . start ( ) ; } else { characterHandler = null ; } }
Re - initialize the variables for each parse .
26,779
@ SuppressWarnings ( "deprecation" ) public void characters ( char [ ] ch , int start , int length ) throws SAXException { if ( alreadyComplainedAboutThisRun ) { return ; } if ( atStartOfRun ) { char c = ch [ start ] ; if ( pos == 1 ) { if ( isComposingChar ( UCharacter . getCodePoint ( buf [ 0 ] , c ) ) ) { warn ( "Text run starts with a composing character." ) ; } atStartOfRun = false ; } else { if ( length == 1 && UCharacter . isHighSurrogate ( c ) ) { buf [ 0 ] = c ; pos = 1 ; return ; } else { if ( UCharacter . isHighSurrogate ( c ) ) { if ( isComposingChar ( UCharacter . getCodePoint ( c , ch [ start + 1 ] ) ) ) { warn ( "Text run starts with a composing character." ) ; } } else { if ( isComposingCharOrSurrogate ( c ) ) { warn ( "Text run starts with a composing character." ) ; } } atStartOfRun = false ; } } } int i = start ; int stop = start + length ; if ( pos > 0 ) { while ( i < stop && isComposingCharOrSurrogate ( ch [ i ] ) ) { i ++ ; } appendToBuf ( ch , start , i ) ; if ( i == stop ) { return ; } else { if ( ! Normalizer . isNormalized ( buf , 0 , pos , Normalizer . NFC , 0 ) ) { errAboutTextRun ( ) ; } pos = 0 ; } } if ( i < stop ) { start = i ; i = stop - 1 ; while ( i > start && isComposingCharOrSurrogate ( ch [ i ] ) ) { i -- ; } if ( i > start && ! Normalizer . isNormalized ( ch , start , i , Normalizer . NFC , 0 ) ) { errAboutTextRun ( ) ; } appendToBuf ( ch , i , stop ) ; } }
In the normal mode this method has the usual SAX semantics . In the source text mode this method is used for reporting the source text .
26,780
private void appendToBuf ( char [ ] ch , int start , int end ) { if ( start == end ) { return ; } int neededBufLen = pos + ( end - start ) ; if ( neededBufLen > buf . length ) { char [ ] newBuf = new char [ neededBufLen ] ; System . arraycopy ( buf , 0 , newBuf , 0 , pos ) ; if ( bufHolder == null ) { bufHolder = buf ; } buf = newBuf ; } System . arraycopy ( ch , start , buf , pos , end - start ) ; pos += ( end - start ) ; }
Appends a slice of an UTF - 16 code unit array to the internal buffer .
26,781
void verror ( String message ) throws SAXException { SAXParseException err ; err = new SAXParseException ( message , this ) ; errorHandler . error ( err ) ; }
make layered SAX2 DTD validation more conformant
26,782
public static void setParams ( int connectionTimeout , int socketTimeout , int maxRequests ) { PrudentHttpEntityResolver . maxRequests = maxRequests ; PoolingHttpClientConnectionManager phcConnMgr ; Registry < ConnectionSocketFactory > registry = RegistryBuilder . < ConnectionSocketFactory > create ( ) . register ( "http" , PlainConnectionSocketFactory . getSocketFactory ( ) ) . register ( "https" , SSLConnectionSocketFactory . getSocketFactory ( ) ) . build ( ) ; HttpClientBuilder builder = HttpClients . custom ( ) . useSystemProperties ( ) ; builder . setRedirectStrategy ( new LaxRedirectStrategy ( ) ) ; builder . setMaxConnPerRoute ( maxRequests ) ; builder . setMaxConnTotal ( Integer . parseInt ( System . getProperty ( "nu.validator.servlet.max-total-connections" , "200" ) ) ) ; if ( "true" . equals ( System . getProperty ( "nu.validator.xml.promiscuous-ssl" , "true" ) ) ) { try { SSLContext promiscuousSSLContext = new SSLContextBuilder ( ) . loadTrustMaterial ( null , new TrustStrategy ( ) { public boolean isTrusted ( X509Certificate [ ] arg0 , String arg1 ) throws CertificateException { return true ; } } ) . build ( ) ; builder . setSslcontext ( promiscuousSSLContext ) ; HostnameVerifier verifier = SSLConnectionSocketFactory . ALLOW_ALL_HOSTNAME_VERIFIER ; SSLConnectionSocketFactory promiscuousSSLConnSocketFactory = new SSLConnectionSocketFactory ( promiscuousSSLContext , verifier ) ; registry = RegistryBuilder . < ConnectionSocketFactory > create ( ) . register ( "https" , promiscuousSSLConnSocketFactory ) . register ( "http" , PlainConnectionSocketFactory . getSocketFactory ( ) ) . build ( ) ; } catch ( KeyManagementException | KeyStoreException | NoSuchAlgorithmException | NumberFormatException e ) { e . printStackTrace ( ) ; } } phcConnMgr = new PoolingHttpClientConnectionManager ( registry ) ; phcConnMgr . setDefaultMaxPerRoute ( maxRequests ) ; phcConnMgr . setMaxTotal ( 200 ) ; builder . setConnectionManager ( phcConnMgr ) ; RequestConfig . Builder config = RequestConfig . custom ( ) ; config . setCircularRedirectsAllowed ( true ) ; config . setMaxRedirects ( Integer . parseInt ( System . getProperty ( "nu.validator.servlet.max-redirects" , "20" ) ) ) ; config . setConnectTimeout ( connectionTimeout ) ; config . setCookieSpec ( CookieSpecs . BEST_MATCH ) ; config . setSocketTimeout ( socketTimeout ) ; config . setCookieSpec ( CookieSpecs . IGNORE_COOKIES ) ; client = builder . setDefaultRequestConfig ( config . build ( ) ) . build ( ) ; }
Sets the timeouts of the HTTP client .
26,783
public void errOnHorizontalOverlap ( Cell laterCell ) throws SAXException { if ( ! ( ( laterCell . right <= left ) || ( right <= laterCell . left ) ) ) { this . err ( "Table cell is overlapped by later table cell." ) ; laterCell . err ( "Table cell overlaps an earlier table cell." ) ; } }
Emit errors if this cell and the argument overlap horizontally .
26,784
public void warn ( String message ) throws SAXException { if ( errorHandler != null ) { SAXParseException spe = new SAXParseException ( message , locator ) ; errorHandler . warning ( spe ) ; } }
Emit a warning . The locator is used .
26,785
public void warn ( String message , Locator overrideLocator ) throws SAXException { if ( errorHandler != null ) { SAXParseException spe = new SAXParseException ( message , overrideLocator ) ; errorHandler . warning ( spe ) ; } }
Emit a warning with specified locator .
26,786
public void err ( String message , Locator overrideLocator ) throws SAXException { if ( errorHandler != null ) { SAXParseException spe = new SAXParseException ( message , overrideLocator ) ; errorHandler . error ( spe ) ; } }
Emit an error with specified locator .
26,787
public void err ( String message ) throws SAXException { if ( errorHandler != null ) { SAXParseException spe = new SAXParseException ( message , locator ) ; errorHandler . error ( spe ) ; } }
Emit an error . The locator is used .
26,788
public String validate ( Path path ) throws IOException , SAXException { try ( OneOffValidator validator = new OneOffValidator ( asciiQuotes , detectLanguages , forceHTML , lineOffset , loadEntities , noStream , outputFormat , schemaUrl ) ) { return validator . validate ( path ) ; } }
Validate the file at the given path
26,789
public String validate ( InputStream in ) throws IOException , SAXException { try ( OneOffValidator validator = new OneOffValidator ( asciiQuotes , detectLanguages , forceHTML , lineOffset , loadEntities , noStream , outputFormat , schemaUrl ) ) { return validator . validate ( in ) ; } }
Validate the input source
26,790
private void pop ( ) throws SAXException { if ( current == null ) { throw new IllegalStateException ( "Bug!" ) ; } current . end ( ) ; if ( stack . isEmpty ( ) ) { current = null ; } else { current = stack . removeLast ( ) ; } }
Ends the current table discards it and pops the top of the stack to be the new current table .
26,791
public static String [ ] split ( String value ) { if ( value == null || "" . equals ( value ) ) { return EMPTY_STRING_ARRAY ; } int len = value . length ( ) ; List < String > list = new LinkedList < > ( ) ; boolean collectingSpace = true ; int start = 0 ; for ( int i = 0 ; i < len ; i ++ ) { char c = value . charAt ( i ) ; if ( c == ' ' || c == '\t' || c == '\n' || c == '\r' ) { if ( ! collectingSpace ) { list . add ( value . substring ( start , i ) ) ; collectingSpace = true ; } } else { if ( collectingSpace ) { start = i ; collectingSpace = false ; } } } if ( start < len ) { int end = len ; for ( int i = 1 ; len > i ; i ++ ) { char c = value . charAt ( len - i ) ; if ( c == ' ' || c == '\t' || c == '\n' || c == '\r' ) { end -- ; continue ; } break ; } list . add ( value . substring ( start , end ) ) ; } return list . toArray ( EMPTY_STRING_ARRAY ) ; }
Splits the argument on white space .
26,792
public Object evaluate ( Input input ) { if ( noInput ( input ) ) { return NO_INPUT ; } String line = input . words ( ) . stream ( ) . collect ( Collectors . joining ( " " ) ) . trim ( ) ; String command = findLongestCommand ( line ) ; List < String > words = input . words ( ) ; if ( command != null ) { MethodTarget methodTarget = methodTargets . get ( command ) ; Availability availability = methodTarget . getAvailability ( ) ; if ( availability . isAvailable ( ) ) { List < String > wordsForArgs = wordsForArguments ( command , words ) ; Method method = methodTarget . getMethod ( ) ; Thread commandThread = Thread . currentThread ( ) ; Object sh = Signals . register ( "INT" , ( ) -> commandThread . interrupt ( ) ) ; try { Object [ ] args = resolveArgs ( method , wordsForArgs ) ; validateArgs ( args , methodTarget ) ; return ReflectionUtils . invokeMethod ( method , methodTarget . getBean ( ) , args ) ; } catch ( UndeclaredThrowableException e ) { if ( e . getCause ( ) instanceof InterruptedException || e . getCause ( ) instanceof ClosedByInterruptException ) { Thread . interrupted ( ) ; } return e . getCause ( ) ; } catch ( Exception e ) { return e ; } finally { Signals . unregister ( "INT" , sh ) ; } } else { return new CommandNotCurrentlyAvailable ( command , availability ) ; } } else { return new CommandNotFound ( words ) ; } }
Evaluate a single line of input from the user by trying to map words to a command and arguments .
26,793
public TableBuilder addOutlineBorder ( BorderStyle style ) { this . addBorder ( 0 , 0 , model . getRowCount ( ) , model . getColumnCount ( ) , OUTLINE , style ) ; return this ; }
Set a border on the outline of the whole table .
26,794
public TableBuilder addHeaderBorder ( BorderStyle style ) { this . addBorder ( 0 , 0 , 1 , model . getColumnCount ( ) , OUTLINE , style ) ; return addOutlineBorder ( style ) ; }
Set a border on the outline of the whole table as well as around the first row .
26,795
public TableBuilder addFullBorder ( BorderStyle style ) { this . addBorder ( 0 , 0 , model . getRowCount ( ) , model . getColumnCount ( ) , FULL , style ) ; return this ; }
Set a border around each and every cell of the table .
26,796
public TableBuilder addHeaderAndVerticalsBorders ( BorderStyle style ) { this . addBorder ( 0 , 0 , 1 , model . getColumnCount ( ) , OUTLINE , style ) ; this . addBorder ( 0 , 0 , model . getRowCount ( ) , model . getColumnCount ( ) , OUTLINE | INNER_VERTICAL , style ) ; return this ; }
Set a border on the outline of the whole table around the first row and draw vertical lines around each column .
26,797
public TableBuilder addInnerBorder ( BorderStyle style ) { this . addBorder ( 0 , 0 , model . getRowCount ( ) , model . getColumnCount ( ) , INNER , style ) ; return this ; }
Set a border on the inner verticals and horizontals of the table but not on the outline .
26,798
public static TableBuilder configureKeyValueRendering ( TableBuilder builder , String delimiter ) { return builder . on ( CellMatchers . ofType ( Map . class ) ) . addFormatter ( new MapFormatter ( delimiter ) ) . addAligner ( new KeyValueHorizontalAligner ( delimiter . trim ( ) ) ) . addSizer ( new KeyValueSizeConstraints ( delimiter ) ) . addWrapper ( new KeyValueTextWrapper ( delimiter ) ) . and ( ) ; }
Install all the necessary formatters aligners etc for key - value rendering of Maps .
26,799
public static void disable ( ConfigurableEnvironment environment ) { environment . getPropertySources ( ) . addFirst ( new MapPropertySource ( "interactive.override" , Collections . singletonMap ( SPRING_SHELL_INTERACTIVE_ENABLED , "false" ) ) ) ; }
Helper method to dynamically disable this runner .