idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
38,600
private SshConnection connect ( ) { if ( sshConnection != null && sshConnection . isConnected ( ) ) { return sshConnection ; } while ( ! shutdownInProgress ) { SshConnection ssh = null ; try { logger . debug ( "Connecting..." ) ; ssh = SshConnectionFactory . getConnection ( gerritHostName , gerritSshPort , gerritProxy , authentication , authenticationUpdater ) ; gerritVersion = formatVersion ( ssh . executeCommand ( "gerrit version" ) ) ; logger . debug ( "connection seems ok, returning it." ) ; return ssh ; } catch ( SshConnectException sshConEx ) { logger . error ( "Could not connect to Gerrit server! " + "Host: {} Port: {}" , gerritHostName , gerritSshPort ) ; logger . error ( " Proxy: {}" , gerritProxy ) ; logger . error ( " User: {} KeyFile: {}" , authentication . getUsername ( ) , authentication . getPrivateKeyFile ( ) ) ; logger . error ( "ConnectionException: " , sshConEx ) ; } catch ( SshAuthenticationException sshAuthEx ) { logger . error ( "Could not authenticate to Gerrit server!" + "\n\tUsername: {}\n\tKeyFile: {}\n\tPassword: {}" , new Object [ ] { authentication . getUsername ( ) , authentication . getPrivateKeyFile ( ) , authentication . getPrivateKeyFilePassword ( ) , } ) ; logger . error ( "AuthenticationException: " , sshAuthEx ) ; } catch ( IOException ex ) { logger . error ( "Could not connect to Gerrit server! " + "Host: {} Port: {}" , gerritHostName , gerritSshPort ) ; logger . error ( " Proxy: {}" , gerritProxy ) ; logger . error ( " User: {} KeyFile: {}" , authentication . getUsername ( ) , authentication . getPrivateKeyFile ( ) ) ; logger . error ( "IOException: " , ex ) ; } if ( ssh != null ) { logger . trace ( "Disconnecting bad connection." ) ; try { ssh . disconnect ( ) ; } catch ( Exception ex ) { logger . warn ( "Error when disconnecting bad connection." , ex ) ; } finally { ssh = null ; } } if ( ! shutdownInProgress ) { logger . trace ( "Sleeping for a bit." ) ; try { Thread . sleep ( CONNECT_SLEEP ) ; } catch ( InterruptedException ex ) { logger . warn ( "Got interrupted while sleeping." , ex ) ; } } } return null ; }
Connects to the Gerrit server and authenticates as the specified user .
38,601
private String formatVersion ( String version ) { if ( version == null ) { return version ; } String [ ] split = version . split ( GERRIT_VERSION_PREFIX ) ; if ( split . length < 2 ) { return version . trim ( ) ; } return split [ 1 ] . trim ( ) ; }
Removes the gerrit version from the start of the response from gerrit .
38,602
public void notifyListeners ( GerritConnectionEvent event ) { for ( ConnectionListener listener : listeners ) { try { switch ( event ) { case GERRIT_CONNECTION_ESTABLISHED : listener . connectionEstablished ( ) ; break ; case GERRIT_CONNECTION_DOWN : listener . connectionDown ( ) ; break ; default : break ; } } catch ( Exception ex ) { logger . error ( "ConnectionListener threw Exception. " , ex ) ; } } }
Notifies all listeners of a Gerrit connection event .
38,603
protected SshConnection getConnection ( ) throws IOException { if ( ! isPersistedConnectionValid ( ) ) { activeConnection = super . getConnection ( ) ; logger . trace ( "SSH connection is not valid anymore, a new one was created." ) ; } return activeConnection ; }
Returns a fresh SSH connection if the persisted one is not valid . Otherwise returns the existing connection .
38,604
public Map < Change , PatchSet > getChanges ( GerritQueryHandler gerritQueryHandler ) { if ( StringUtils . isEmpty ( name ) ) { logger . error ( "Topic name can not be empty" ) ; return Collections . emptyMap ( ) ; } if ( changes == null ) { Map < Change , PatchSet > temp = new HashMap < Change , PatchSet > ( ) ; try { List < JSONObject > jsonList = gerritQueryHandler . queryCurrentPatchSets ( "topic:{" + name + "}" ) ; for ( JSONObject json : jsonList ) { if ( json . has ( "type" ) && "stats" . equalsIgnoreCase ( json . getString ( "type" ) ) ) { continue ; } if ( json . has ( "currentPatchSet" ) ) { JSONObject currentPatchSet = json . getJSONObject ( "currentPatchSet" ) ; temp . put ( new Change ( json ) , new PatchSet ( currentPatchSet ) ) ; } } changes = temp ; } catch ( IOException e ) { logger . error ( "IOException occured. " , e ) ; } catch ( GerritQueryException e ) { logger . error ( "Bad query. " , e ) ; } } return changes ; }
Gets all change - patchset pairs related to this topic . After first call data is cached .
38,605
private String resolveEndpointURL ( ) { String gerritFrontEndUrl = config . getGerritFrontEndUrl ( ) ; if ( ! gerritFrontEndUrl . endsWith ( "/" ) ) { gerritFrontEndUrl = gerritFrontEndUrl + "/" ; } ChangeId changeId = new ChangeId ( event . getChange ( ) . getProject ( ) , event . getChange ( ) . getBranch ( ) , event . getChange ( ) . getId ( ) ) ; return gerritFrontEndUrl + "a/changes/" + changeId . asUrlPart ( ) + "/revisions/" + event . getPatchSet ( ) . getRevision ( ) + "/review" ; }
What it says resolve Endpoint URL .
38,606
public String getChangeInfo ( String preText ) { StringBuilder s = new StringBuilder ( ) ; s . append ( preText + "\n" ) ; s . append ( "Subject: " + getSubject ( ) + "\n" ) ; s . append ( "Project: " + getProject ( ) + " " + getBranch ( ) + " " + getId ( ) + "\n" ) ; s . append ( "Link: " + getUrl ( ) + "\n" ) ; return s . toString ( ) ; }
Returns change s info in string format .
38,607
public static List < String > getFilesByChange ( GerritQueryHandler gerritQueryHandler , String changeId ) { try { List < JSONObject > jsonList = gerritQueryHandler . queryFiles ( "change:" + changeId ) ; for ( JSONObject json : jsonList ) { if ( json . has ( "type" ) && "stats" . equalsIgnoreCase ( json . getString ( "type" ) ) ) { continue ; } if ( json . has ( "currentPatchSet" ) ) { JSONObject currentPatchSet = json . getJSONObject ( "currentPatchSet" ) ; if ( currentPatchSet . has ( "files" ) ) { JSONArray changedFiles = currentPatchSet . optJSONArray ( "files" ) ; int numberOfFiles = changedFiles . size ( ) ; if ( numberOfFiles > 0 ) { List < String > files = new ArrayList < String > ( numberOfFiles ) ; for ( int i = 0 ; i < changedFiles . size ( ) ; i ++ ) { JSONObject file = changedFiles . getJSONObject ( i ) ; files . add ( file . getString ( "file" ) ) ; } return files ; } } break ; } } } catch ( IOException e ) { logger . error ( "IOException occurred. " , e ) ; } catch ( GerritQueryException e ) { logger . error ( "Bad query. " , e ) ; } return null ; }
Provides list of files related to the change .
38,608
public String getRefName ( ) { if ( refName . startsWith ( REFS_HEADS ) ) { return refName . substring ( REFS_HEADS . length ( ) ) ; } return refName ; }
Ref name within project .
38,609
public String getUrl ( ) { String frontUrl = this . url ; if ( frontUrl != null && ! frontUrl . isEmpty ( ) && ! frontUrl . endsWith ( "/" ) ) { frontUrl += '/' ; } return frontUrl ; }
Get url .
38,610
protected Object readResolve ( ) { if ( proto != null && scheme == null ) { scheme = proto ; proto = null ; } else if ( scheme == null && proto == null ) { scheme = GerritConnection . GERRIT_PROTOCOL_SCHEME_NAME ; } return this ; }
Deserialization handling .
38,611
public List < JSONObject > queryCurrentPatchSets ( String queryString ) throws SshException , IOException , GerritQueryException { return queryJava ( queryString , false , true , false , false ) ; }
Runs the query and returns the result as a list of Java JSONObjects .
38,612
private void runQuery ( String queryString , boolean getPatchSets , boolean getCurrentPatchSet , boolean getFiles , boolean getCommitMessage , boolean getComments , LineVisitor visitor ) throws GerritQueryException , SshException , IOException { StringBuilder str = new StringBuilder ( QUERY_COMMAND ) ; str . append ( " --format=JSON" ) ; if ( getPatchSets ) { str . append ( " --patch-sets" ) ; } if ( getCurrentPatchSet ) { str . append ( " --current-patch-set" ) ; } if ( getFiles ) { str . append ( " --files" ) ; } if ( getComments ) { str . append ( " --comments" ) ; } if ( getCommitMessage ) { str . append ( " --commit-message" ) ; } str . append ( " \"" ) . append ( queryString . replace ( ( CharSequence ) "\"" , ( CharSequence ) "\\\"" ) ) . append ( "\"" ) ; SshConnection ssh = null ; try { ssh = getConnection ( ) ; BufferedReader reader = new BufferedReader ( ssh . executeCommandReader ( str . toString ( ) ) ) ; String incomingLine = null ; while ( ( incomingLine = reader . readLine ( ) ) != null ) { logger . trace ( "Incoming line: {}" , incomingLine ) ; visitor . visit ( incomingLine ) ; } logger . trace ( "Closing reader." ) ; reader . close ( ) ; } finally { cleanupConnection ( ssh ) ; } }
Runs the query on the Gerrit server and lets the provided visitor handle each line in the result .
38,613
protected SshConnection getConnection ( ) throws IOException { return SshConnectionFactory . getConnection ( gerritHostName , gerritSshPort , gerritProxy , authentication , connectionTimeout ) ; }
Creates a new SSH connection used to execute the queries .
38,614
public String getIgnoreEMail ( String serverName ) { if ( serverName != null ) { return ignoreEMails . get ( serverName ) ; } else { return null ; } }
Standard getter for the ignoreEMail .
38,615
public void setIgnoreEMail ( String serverName , String ignoreEMail ) { if ( serverName != null ) { if ( ignoreEMail != null ) { ignoreEMails . put ( serverName , ignoreEMail ) ; } else { ignoreEMails . remove ( serverName ) ; } } }
Standard setter for the ignoreEMail .
38,616
private void queueWork ( Work work ) { try { logger . debug ( "Queueing work {}" , work ) ; executor . submit ( new EventWorker ( work , this ) ) ; } catch ( RejectedExecutionException e ) { logger . error ( "Unable to queue a received event! " , e ) ; } checkQueueSize ( ) ; }
puts work in the queue
38,617
public Collection < GerritEventListener > removeAllEventListeners ( ) { synchronized ( this ) { HashSet < GerritEventListener > listeners = new HashSet < GerritEventListener > ( gerritEventListeners ) ; gerritEventListeners . clear ( ) ; return listeners ; } }
Removes all event listeners and returns those that where removed .
38,618
public void setThreadKeepAliveTime ( int threadKeepAliveTime ) { this . threadKeepAliveTime = Math . max ( MIN_RECEIVE_THREAD_KEEP_ALIVE_TIME , threadKeepAliveTime ) ; executor . setKeepAliveTime ( threadKeepAliveTime , TimeUnit . SECONDS ) ; }
Sets the number of seconds threads well be kept alive .
38,619
public BlockingQueue < Work > getWorkQueue ( ) { BlockingQueue < Work > queue = new LinkedBlockingQueue < Work > ( ) ; BlockingQueue < Runnable > workQueue = executor . getQueue ( ) ; for ( Runnable r : workQueue ) { if ( r instanceof EventWorker ) { queue . add ( ( ( EventWorker ) r ) . work ) ; } } return queue ; }
Returns a snapshot of the current state of the queue in the executor and not the Queue itself .
38,620
private boolean ignoreEvent ( CommentAdded event ) { Account account = event . getAccount ( ) ; if ( account == null ) { return false ; } String accountEmail = account . getEmail ( ) ; if ( StringUtils . isEmpty ( accountEmail ) ) { return false ; } Provider provider = event . getProvider ( ) ; if ( provider != null ) { String ignoreEMail = ignoreEMails . get ( provider . getName ( ) ) ; if ( StringUtils . isNotEmpty ( ignoreEMail ) && accountEmail . endsWith ( ignoreEMail ) ) { return true ; } } return false ; }
Checks if the event should be ignored .
38,621
public Token recoverInline ( Parser recognizer ) throws RecognitionException { throw new RecognitionException ( recognizer , recognizer . getInputStream ( ) , recognizer . getContext ( ) ) ; }
throws RecognitionException to handle in parser s catch block
38,622
protected void consumeUntilGreedy ( Parser recognizer , IntervalSet follow ) { logger . trace ( "CONSUME UNTIL GREEDY {}" , follow . toString ( ) ) ; for ( int ttype = recognizer . getInputStream ( ) . LA ( 1 ) ; ttype != - 1 && ! follow . contains ( ttype ) ; ttype = recognizer . getInputStream ( ) . LA ( 1 ) ) { Token t = recognizer . consume ( ) ; logger . trace ( "Skipped greedy: {}" , t . getText ( ) ) ; } Token t = recognizer . consume ( ) ; logger . trace ( "Skipped greedy: {} follow: {}" , t . getText ( ) , follow ) ; }
Consumes token until lexer state is balanced and token from follow is matched . Matched token is also consumed
38,623
protected void consumeUntilGreedy ( Parser recognizer , IntervalSet set , CSSLexerState . RecoveryMode mode ) { CSSToken t ; do { Token next = recognizer . getInputStream ( ) . LT ( 1 ) ; if ( next instanceof CSSToken ) { t = ( CSSToken ) recognizer . getInputStream ( ) . LT ( 1 ) ; if ( t . getType ( ) == Token . EOF ) { logger . trace ( "token eof " ) ; break ; } } else break ; logger . trace ( "Skipped greedy: {}" , t . getText ( ) ) ; recognizer . consume ( ) ; } while ( ! ( t . getLexerState ( ) . isBalanced ( mode , null , t ) && set . contains ( t . getType ( ) ) ) ) ; }
Consumes token until lexer state is function - balanced and token from follow is matched . Matched token is also consumed
38,624
public void consumeUntilGreedy ( Parser recognizer , IntervalSet follow , CSSLexerState . RecoveryMode mode , CSSLexerState ls ) { consumeUntil ( recognizer , follow , mode , ls ) ; recognizer . getInputStream ( ) . consume ( ) ; }
Consumes token until lexer state is function - balanced and token from follow is matched . Matched token is also consumed .
38,625
public void consumeUntil ( Parser recognizer , IntervalSet follow , CSSLexerState . RecoveryMode mode , CSSLexerState ls ) { CSSToken t ; boolean finish ; TokenStream input = recognizer . getInputStream ( ) ; do { Token next = input . LT ( 1 ) ; if ( next instanceof CSSToken ) { t = ( CSSToken ) input . LT ( 1 ) ; if ( t . getType ( ) == Token . EOF ) { logger . trace ( "token eof " ) ; break ; } } else break ; finish = ( t . getLexerState ( ) . isBalanced ( mode , ls , t ) && follow . contains ( t . getType ( ) ) ) ; if ( ! finish ) { logger . trace ( "Skipped: {}" , t ) ; input . consume ( ) ; } } while ( ! finish ) ; }
Consumes token until lexer state is function - balanced and token from follow is matched .
38,626
public static StringBuilder appendTimes ( StringBuilder sb , String append , int times ) { for ( ; times > 0 ; times -- ) sb . append ( append ) ; return sb ; }
Appends string multiple times to buffer
38,627
public static StringBuilder appendFunctionArgs ( StringBuilder sb , List < Term < ? > > list ) { Term < ? > prev = null , pprev = null ; for ( Term < ? > elem : list ) { boolean sep = true ; if ( elem instanceof TermOperator && ( ( TermOperator ) elem ) . getValue ( ) == ',' ) sep = false ; if ( ( prev != null && prev instanceof TermOperator && ( ( TermOperator ) prev ) . getValue ( ) == '-' ) && ( pprev == null || pprev instanceof TermOperator ) ) sep = false ; if ( prev != null && sep ) sb . append ( SPACE_DELIM ) ; pprev = prev ; prev = elem ; sb . append ( elem . toString ( ) ) ; } return sb ; }
Appends the formatted list of function arguments to a string builder . The individual arguments are separated by spaces with the exception of commas .
38,628
public String getText ( ) { text = super . getText ( ) ; int t ; try { t = typeMapper . inverse ( ) . get ( type ) ; } catch ( NullPointerException e ) { return text ; } switch ( t ) { case FUNCTION : return text . substring ( 0 , text . length ( ) - 1 ) ; case URI : return extractURI ( text ) ; case UNCLOSED_URI : return extractUNCLOSEDURI ( text ) ; case STRING : return extractSTRING ( text ) ; case UNCLOSED_STRING : return extractUNCLOSEDSTRING ( text ) ; case CLASSKEYWORD : return extractCLASSKEYWORD ( text ) ; case HASH : return extractHASH ( text ) ; default : return text ; } }
Returns common text stored in token . Content is not modified .
38,629
public static String extractCHARSET ( String charset ) { final String arg = charset . replace ( "@charset" , "" ) . replace ( ";" , "" ) . trim ( ) ; if ( arg . length ( ) > 2 ) return extractSTRING ( arg ) ; else return "" ; }
extract charset value from CHARSET token
38,630
public Node parentNode ( ) { if ( currentNode == null ) return null ; Node node = getParentNode ( currentNode ) ; if ( node != null ) currentNode = node ; return node ; }
Return the parent Node from the current node after applying filter whatToshow . If result is not null set the current Node .
38,631
public Node firstChild ( ) { if ( currentNode == null ) return null ; Node node = getFirstChild ( currentNode ) ; if ( node != null ) currentNode = node ; return node ; }
Return the first child Node from the current node after applying filter whatToshow . If result is not null set the current Node .
38,632
public Node lastChild ( ) { if ( currentNode == null ) return null ; Node node = getLastChild ( currentNode ) ; if ( node != null ) currentNode = node ; return node ; }
Return the last child Node from the current node after applying filter whatToshow . If result is not null set the current Node .
38,633
public Node previousSibling ( ) { if ( currentNode == null ) return null ; Node node = getPreviousSibling ( currentNode ) ; if ( node != null ) currentNode = node ; return node ; }
Return the previous sibling Node from the current node after applying filter whatToshow . If result is not null set the current Node .
38,634
public Node nextSibling ( ) { if ( currentNode == null ) return null ; Node node = getNextSibling ( currentNode ) ; if ( node != null ) currentNode = node ; return node ; }
Return the next sibling Node from the current node after applying filter whatToshow . If result is not null set the current Node .
38,635
public Node previousNode ( ) { if ( currentNode == null ) return null ; Node result = getPreviousSibling ( currentNode ) ; if ( result == null ) { result = getParentNode ( currentNode ) ; if ( result != null ) { currentNode = result ; return result ; } return null ; } Node lastChild = getLastChild ( result ) ; Node prev = lastChild ; while ( lastChild != null ) { prev = lastChild ; lastChild = getLastChild ( prev ) ; } lastChild = prev ; if ( lastChild != null ) { currentNode = lastChild ; return lastChild ; } currentNode = result ; return result ; }
Return the previous Node from the current node after applying filter whatToshow . If result is not null set the current Node .
38,636
public Node nextNode ( ) { if ( currentNode == null ) return null ; Node result = getFirstChild ( currentNode ) ; if ( result != null ) { currentNode = result ; return result ; } result = getNextSibling ( currentNode ) ; if ( result != null ) { currentNode = result ; return result ; } Node parent = getParentNode ( currentNode ) ; while ( parent != null ) { result = getNextSibling ( parent ) ; if ( result != null ) { currentNode = result ; return result ; } else { parent = getParentNode ( parent ) ; } } return null ; }
Return the next Node from the current node after applying filter whatToshow . If result is not null set the current Node .
38,637
private Node getParentNode ( Node node ) { if ( node == null || node == root ) return null ; Node newNode = node . getParentNode ( ) ; if ( newNode == null ) return null ; int accept = acceptNode ( newNode ) ; if ( accept == NodeFilter . FILTER_ACCEPT ) return newNode ; else return getParentNode ( newNode ) ; }
Internal function . Return the parent Node from the input node after applying filter whatToshow . The current node is not consulted or set .
38,638
private Node getNextSibling ( Node node ) { if ( node == null || node == root ) return null ; Node newNode = node . getNextSibling ( ) ; if ( newNode == null ) { newNode = node . getParentNode ( ) ; if ( newNode == null || node == root ) return null ; int parentAccept = acceptNode ( newNode ) ; if ( parentAccept == NodeFilter . FILTER_SKIP ) { return getNextSibling ( newNode ) ; } return null ; } int accept = acceptNode ( newNode ) ; if ( accept == NodeFilter . FILTER_ACCEPT ) return newNode ; else if ( accept == NodeFilter . FILTER_SKIP ) { Node fChild = getFirstChild ( newNode ) ; if ( fChild == null ) return getNextSibling ( newNode ) ; return fChild ; } else return getNextSibling ( newNode ) ; }
Internal function . Return the nextSibling Node from the input node after applying filter whatToshow . The current node is not consulted or set .
38,639
private Node getPreviousSibling ( Node node ) { if ( node == null || node == root ) return null ; Node newNode = node . getPreviousSibling ( ) ; if ( newNode == null ) { newNode = node . getParentNode ( ) ; if ( newNode == null || node == root ) return null ; int parentAccept = acceptNode ( newNode ) ; if ( parentAccept == NodeFilter . FILTER_SKIP ) return getPreviousSibling ( newNode ) ; return null ; } int accept = acceptNode ( newNode ) ; if ( accept == NodeFilter . FILTER_ACCEPT ) return newNode ; else if ( accept == NodeFilter . FILTER_SKIP ) { Node fChild = getLastChild ( newNode ) ; if ( fChild == null ) return getPreviousSibling ( newNode ) ; return fChild ; } else return getPreviousSibling ( newNode ) ; }
Internal function . Return the previous sibling Node from the input node after applying filter whatToshow . The current node is not consulted or set .
38,640
private Node getFirstChild ( Node node ) { if ( node == null ) return null ; Node newNode = node . getFirstChild ( ) ; if ( newNode == null ) return null ; int accept = acceptNode ( newNode ) ; if ( accept == NodeFilter . FILTER_ACCEPT ) return newNode ; else if ( accept == NodeFilter . FILTER_SKIP && newNode . hasChildNodes ( ) ) return getFirstChild ( newNode ) ; return getNextSibling ( newNode ) ; }
Internal function . Return the first child Node from the input node after applying filter whatToshow . The current node is not consulted or set .
38,641
private Node getLastChild ( Node node ) { if ( node == null ) return null ; Node newNode = node . getLastChild ( ) ; if ( newNode == null ) return null ; int accept = acceptNode ( newNode ) ; if ( accept == NodeFilter . FILTER_ACCEPT ) return newNode ; else if ( accept == NodeFilter . FILTER_SKIP && newNode . hasChildNodes ( ) ) return getLastChild ( newNode ) ; return getPreviousSibling ( newNode ) ; }
Internal function . Return the last child Node from the input node after applying filter whatToshow . The current node is not consulted or set .
38,642
private short acceptNode ( Node node ) { if ( ( whatToShow & ( 1 << node . getNodeType ( ) - 1 ) ) != 0 ) return NodeFilter . FILTER_ACCEPT ; else return NodeFilter . FILTER_SKIP ; }
Internal function . The node whatToShow and the filter are combined into one result .
38,643
public void computeSpecificity ( CombinedSelector . Specificity spec ) { for ( SelectorPart item : list ) { item . computeSpecificity ( spec ) ; } }
Computes specificity of this selector
38,644
private CSSProperty createInherit ( int i ) { try { Class < ? extends CSSProperty > clazz = types . get ( i ) ; CSSProperty property = CSSProperty . Translator . createInherit ( clazz ) ; if ( property != null ) return property ; throw new IllegalAccessException ( "No inherit value for: " + clazz . getName ( ) ) ; } catch ( Exception e ) { throw new UnsupportedOperationException ( "Unable to create inherit value" , e ) ; } }
Creates INHERIT value of given class
38,645
public boolean vary ( Map < String , CSSProperty > properties , Map < String , Term < ? > > values ) { if ( terms . size ( ) == 1 && checkInherit ( ALL_VARIANTS , terms . get ( 0 ) , properties ) ) return true ; for ( IntegerRef i = new IntegerRef ( 0 ) ; i . get ( ) < terms . size ( ) ; i . inc ( ) ) { boolean passed = false ; for ( int v = 0 ; v < variants ; v ++ ) { if ( ! variantCondition ( v , i ) ) continue ; if ( variantPassed [ v ] ) continue ; passed = variant ( v , i , properties , values ) ; if ( passed ) { variantPassed [ v ] = true ; break ; } } if ( ! passed ) return false ; } return true ; }
Test all terms
38,646
public boolean tryOneTermVariant ( int variant , Declaration d , Map < String , CSSProperty > properties , Map < String , Term < ? > > values ) { if ( d . size ( ) != 1 ) return false ; if ( checkInherit ( variant , d . get ( 0 ) , properties ) ) return true ; this . terms = new ArrayList < Term < ? > > ( ) ; this . terms . add ( d . get ( 0 ) ) ; return variant ( variant , new IntegerRef ( 0 ) , properties , values ) ; }
Uses variator functionality to test selected variant on term
38,647
public boolean tryMultiTermVariant ( int variant , Map < String , CSSProperty > properties , Map < String , Term < ? > > values , Term < ? > ... terms ) { this . terms = Arrays . asList ( terms ) ; if ( this . terms . size ( ) == 1 && checkInherit ( variant , this . terms . get ( 0 ) , properties ) ) return true ; return variant ( variant , new IntegerRef ( 0 ) , properties , values ) ; }
Uses variator functionality to test selected variant on more terms . This is used when variant is represented by more terms . Since usually only one term per variant is used only one multiple variant is allowed per variator and should be placed as the last one
38,648
public void assignDefaults ( Map < String , CSSProperty > properties , Map < String , Term < ? > > values ) { SupportedCSS css = CSSFactory . getSupportedCSS ( ) ; for ( String name : names ) { CSSProperty dp = css . getDefaultProperty ( name ) ; if ( dp != null ) properties . put ( name , dp ) ; Term < ? > dv = css . getDefaultValue ( name ) ; if ( dv != null ) values . put ( name , dv ) ; } }
Assigns the default values to all the properties .
38,649
public int getOriginOrder ( ) { if ( important ) { if ( origin == StyleSheet . Origin . AUTHOR ) return 4 ; else if ( origin == StyleSheet . Origin . AGENT ) return 1 ; else return 5 ; } else { if ( origin == StyleSheet . Origin . AUTHOR ) return 3 ; else if ( origin == StyleSheet . Origin . AGENT ) return 1 ; else return 2 ; } }
Computes the priority order of the declaration based on its origin and importance according to the CSS specification .
38,650
public void addDeclaration ( Element el , PseudoElementType pseudo , Declaration decl ) { List < Declaration > list = getOrCreate ( el , pseudo ) ; list . add ( decl ) ; }
Adds a declaration for a specified list . If the list does not exist yet it is created .
38,651
public void sortDeclarations ( Element el , PseudoElementType pseudo ) { List < Declaration > list = get ( el , pseudo ) ; if ( list != null ) Collections . sort ( list ) ; }
Sorts the given list according to the rule specificity .
38,652
private static int [ ] hslToRgb ( float h , float s , float l ) { int [ ] ret = new int [ 3 ] ; float m2 = ( l <= 0.5f ) ? l * ( s + 1 ) : l + s - l * s ; float m1 = l * 2 - m2 ; ret [ 0 ] = Math . round ( hueToRgb ( m1 , m2 , h + 1.0f / 3.0f ) * MAX_VALUE ) ; ret [ 1 ] = Math . round ( hueToRgb ( m1 , m2 , h ) * MAX_VALUE ) ; ret [ 2 ] = Math . round ( hueToRgb ( m1 , m2 , h - 1.0f / 3.0f ) * MAX_VALUE ) ; return ret ; }
Converts the HSL color model to RGB
38,653
public Token nextToken ( ) { if ( lexer . _input == null ) { throw new IllegalStateException ( "nextToken requires a non-null input stream." ) ; } else { int tokenStartMarker = lexer . _input . mark ( ) ; try { Token ttype1 ; label110 : while ( ! lexer . _hitEOF ) { lexer . _token = null ; lexer . _channel = Token . DEFAULT_CHANNEL ; lexer . _tokenStartCharIndex = lexer . _input . index ( ) ; lexer . _tokenStartCharPositionInLine = ( ( LexerATNSimulator ) lexer . getInterpreter ( ) ) . getCharPositionInLine ( ) ; lexer . _tokenStartLine = ( ( LexerATNSimulator ) lexer . getInterpreter ( ) ) . getLine ( ) ; lexer . _text = null ; do { lexer . _type = 0 ; int ttype ; try { ttype = ( ( LexerATNSimulator ) lexer . getInterpreter ( ) ) . match ( lexer . _input , lexer . _mode ) ; } catch ( LexerNoViableAltException var7 ) { lexer . notifyListeners ( var7 ) ; lexer . recover ( var7 ) ; ttype = - 3 ; } if ( lexer . _input . LA ( 1 ) == - 1 ) { lexer . _hitEOF = true ; } if ( lexer . _type == 0 ) { lexer . _type = ttype ; } if ( lexer . _type == - 3 ) { continue label110 ; } } while ( lexer . _type == - 2 ) ; if ( lexer . _token == null ) { lexer . emit ( ) ; } ttype1 = lexer . _token ; return ttype1 ; } eof = true ; if ( ! ls . isBalanced ( ) ) { return generateEOFRecover ( ) ; } log . trace ( "lexer state is balanced - emitEOF" ) ; lexer . emitEOF ( ) ; ttype1 = lexer . _token ; return ttype1 ; } finally { lexer . _input . release ( tokenStartMarker ) ; } } }
Implements Lexer s next token with extra token passing from recovery function
38,654
public CSSToken generateEOFRecover ( ) { CSSToken t = null ; if ( ls . aposOpen ) { ls . aposOpen = false ; t = new CSSToken ( typeMapper . get ( APOS ) , ls , lexerTypeMapper ) ; t . setText ( "'" ) ; } else if ( ls . quotOpen ) { ls . quotOpen = false ; t = new CSSToken ( typeMapper . get ( QUOT ) , ls , lexerTypeMapper ) ; t . setText ( "\"" ) ; } else if ( ls . parenNest != 0 ) { ls . parenNest -- ; t = new CSSToken ( typeMapper . get ( RPAREN ) , ls , lexerTypeMapper ) ; t . setText ( ")" ) ; } else if ( ls . curlyNest != 0 ) { ls . curlyNest -- ; t = new CSSToken ( typeMapper . get ( RCURLY ) , ls , lexerTypeMapper ) ; t . setText ( "}" ) ; } else if ( ls . sqNest != 0 ) { ls . sqNest -- ; t = new CSSToken ( typeMapper . get ( RBRACKET ) , ls , lexerTypeMapper ) ; t . setText ( "]" ) ; } log . debug ( "Recovering from EOF by {}" , t . getText ( ) ) ; return t ; }
Recovers from unexpected EOF by preparing new token
38,655
private void consumeUntilBalanced ( IntervalSet follow ) { log . debug ( "Lexer entered consumeUntilBalanced with {} and follow {}" , ls , follow ) ; int c ; do { c = input . LA ( 1 ) ; if ( c == '\'' && ls . quotOpen == false ) { ls . aposOpen = ! ls . aposOpen ; } else if ( c == '"' && ls . aposOpen == false ) { ls . quotOpen = ! ls . quotOpen ; } else if ( c == '(' ) { ls . parenNest ++ ; } else if ( c == ')' && ls . parenNest > 0 ) { ls . parenNest -- ; } else if ( c == '{' ) { ls . curlyNest ++ ; } else if ( c == '}' && ls . curlyNest > 0 ) { ls . curlyNest -- ; } else if ( c == '\n' ) { if ( ls . quotOpen ) ls . quotOpen = false ; else if ( ls . aposOpen ) ls . aposOpen = false ; } else if ( c == Token . EOF ) { log . info ( "Unexpected EOF during consumeUntilBalanced, EOF not consumed" ) ; return ; } input . consume ( ) ; if ( log . isTraceEnabled ( ) ) log . trace ( "Lexer consumes '{}'({}) until balanced ({})." , new Object [ ] { Character . toString ( ( char ) c ) , Integer . toString ( c ) , ls } ) ; } while ( ! ( ls . isBalanced ( ) && follow . contains ( c ) ) ) ; }
Eats characters until on from follow is found and Lexer state is balanced at the moment
38,656
private boolean consumeAnyButEOF ( ) { int c = input . LA ( 1 ) ; if ( c == CharStream . EOF ) return false ; if ( log . isTraceEnabled ( ) ) log . trace ( "Lexer consumes '{}' while consumeButEOF" , Character . toString ( ( char ) c ) ) ; input . consume ( ) ; return true ; }
Consumes arbitrary character but EOF
38,657
public static final TermFactory getTermFactory ( ) { if ( tf == null ) { try { @ SuppressWarnings ( "unchecked" ) Class < ? extends TermFactory > clazz = ( Class < ? extends TermFactory > ) Class . forName ( DEFAULT_TERM_FACTORY ) ; Method m = clazz . getMethod ( "getInstance" ) ; registerTermFactory ( ( TermFactory ) m . invoke ( null ) ) ; log . debug ( "Retrived {} as default TermFactory implementation." , DEFAULT_TERM_FACTORY ) ; } catch ( Exception e ) { log . error ( "Unable to get TermFactory from default" , e ) ; throw new RuntimeException ( "No TermFactory implementation registered!" ) ; } } return tf ; }
Returns TermFactory registered in step above
38,658
public static final SupportedCSS getSupportedCSS ( ) { if ( css == null ) { try { @ SuppressWarnings ( "unchecked" ) Class < ? extends SupportedCSS > clazz = ( Class < ? extends SupportedCSS > ) Class . forName ( DEFAULT_SUPPORTED_CSS ) ; Method m = clazz . getMethod ( "getInstance" ) ; registerSupportedCSS ( ( SupportedCSS ) m . invoke ( null ) ) ; log . debug ( "Retrived {} as default SupportedCSS implementation." , DEFAULT_SUPPORTED_CSS ) ; } catch ( Exception e ) { log . error ( "Unable to get SupportedCSS from default" , e ) ; throw new RuntimeException ( "No SupportedCSS implementation registered!" ) ; } } return css ; }
Returns registered SupportedCSS
38,659
public static final RuleFactory getRuleFactory ( ) { if ( rf == null ) { try { @ SuppressWarnings ( "unchecked" ) Class < ? extends RuleFactory > clazz = ( Class < ? extends RuleFactory > ) Class . forName ( DEFAULT_RULE_FACTORY ) ; Method m = clazz . getMethod ( "getInstance" ) ; registerRuleFactory ( ( RuleFactory ) m . invoke ( null ) ) ; log . debug ( "Retrived {} as default RuleFactory implementation." , DEFAULT_RULE_FACTORY ) ; } catch ( Exception e ) { log . error ( "Unable to get RuleFactory from default" , e ) ; throw new RuntimeException ( "No RuleFactory implementation registered!" ) ; } } return rf ; }
Returns registered RuleFactory
38,660
public static final DeclarationTransformer getDeclarationTransformer ( ) { if ( dt == null ) { try { @ SuppressWarnings ( "unchecked" ) Class < ? extends DeclarationTransformerImpl > clazz = ( Class < ? extends DeclarationTransformerImpl > ) Class . forName ( DEFAULT_DECLARATION_TRANSFORMER ) ; Method m = clazz . getMethod ( "getInstance" ) ; registerDeclarationTransformer ( ( DeclarationTransformerImpl ) m . invoke ( null ) ) ; log . debug ( "Retrived {} as default DeclarationTransformer implementation." , DEFAULT_DECLARATION_TRANSFORMER ) ; } catch ( Exception e ) { log . error ( "Unable to get DeclarationTransformer from default" , e ) ; throw new RuntimeException ( "No DeclarationTransformer implementation registered!" ) ; } } return dt ; }
Returns the registered DeclarationTransformer
38,661
public static final void registerNodeDataInstance ( Class < ? extends NodeData > clazz ) { try { @ SuppressWarnings ( "unused" ) NodeData test = clazz . newInstance ( ) ; ndImpl = clazz ; } catch ( InstantiationException e ) { throw new RuntimeException ( "NodeData implemenation (" + clazz . getName ( ) + ") doesn't provide sole constructor" , e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( "NodeData implementation (" + clazz . getName ( ) + ") is not accesible" , e ) ; } }
Registers node data instance . Instance must provide no - argument Constructor
38,662
public static final NodeData createNodeData ( ) { if ( ndImpl == null ) { try { @ SuppressWarnings ( "unchecked" ) Class < ? extends NodeData > clazz = ( Class < ? extends NodeData > ) Class . forName ( DEFAULT_NODE_DATA_IMPL ) ; registerNodeDataInstance ( clazz ) ; log . debug ( "Registered {} as default NodeData instance." , DEFAULT_NODE_DATA_IMPL ) ; } catch ( Exception e ) { } } try { return ndImpl . newInstance ( ) ; } catch ( Exception e ) { throw new RuntimeException ( "No NodeData implementation registered" ) ; } }
Creates instance of NodeData
38,663
public static final StyleSheet parse ( String fileName , String encoding ) throws CSSException , IOException { try { File f = new File ( fileName ) ; URL url = f . toURI ( ) . toURL ( ) ; return parse ( url , encoding ) ; } catch ( MalformedURLException e ) { String message = "Unable to construct URL from fileName: " + fileName ; log . error ( message ) ; throw new FileNotFoundException ( message ) ; } }
Parses file into StyleSheet . Internally transforms file to URL
38,664
public static final StyleSheet parse ( String css ) throws IOException , CSSException { URL base = new URL ( "file:///base/url/is/not/specified" ) ; return getCSSParserFactory ( ) . parse ( css , getNetworkProcessor ( ) , null , SourceType . EMBEDDED , base ) ; }
Parses text into StyleSheet
38,665
public boolean matches ( MediaQuery q ) { if ( q . getType ( ) != null ) { if ( q . getType ( ) . equals ( "all" ) ) { if ( q . isNegative ( ) ) return false ; } else if ( q . getType ( ) . equals ( this . getType ( ) ) == q . isNegative ( ) ) return false ; } for ( MediaExpression e : q ) { if ( ! this . matches ( e ) ) return false ; } return true ; }
Checks if this media specification matches a given media query .
38,666
public boolean matches ( MediaExpression e ) { String fs = e . getFeature ( ) ; boolean isMin = false ; boolean isMax = false ; if ( fs . startsWith ( "min-" ) ) { isMin = true ; fs = fs . substring ( 4 ) ; } else if ( fs . startsWith ( "max-" ) ) { isMax = true ; fs = fs . substring ( 4 ) ; } Feature feature = getFeatureByName ( fs ) ; if ( feature != null && ( ! ( isMin || isMax ) || feature . isPrefixed ( ) ) ) { switch ( feature ) { case WIDTH : return valueMatches ( getExpressionLengthPx ( e ) , width , isMin , isMax ) ; case HEIGHT : return valueMatches ( getExpressionLengthPx ( e ) , height , isMin , isMax ) ; case DEVICE_WIDTH : return valueMatches ( getExpressionLengthPx ( e ) , deviceWidth , isMin , isMax ) ; case DEVICE_HEIGHT : return valueMatches ( getExpressionLengthPx ( e ) , deviceHeight , isMin , isMax ) ; case ORIENTATION : String oid = getExpressionIdentifier ( e ) ; if ( oid == null ) return false ; else if ( oid . equals ( "portrait" ) ) return isPortrait ( ) ; else if ( oid . equals ( "landscape" ) ) return ! isPortrait ( ) ; else return false ; case ASPECT_RATIO : return valueMatches ( getExpressionRatio ( e ) , getAspectRatio ( ) , isMin , isMax ) ; case DEVICE_ASPECT_RATIO : return valueMatches ( getExpressionRatio ( e ) , getDeviceAspectRation ( ) , isMin , isMax ) ; case COLOR : return valueMatches ( getExpressionInteger ( e ) , color , isMin , isMax ) ; case COLOR_INDEX : return valueMatches ( getExpressionInteger ( e ) , colorIndex , isMin , isMax ) ; case MONOCHROME : return valueMatches ( getExpressionInteger ( e ) , monochrome , isMin , isMax ) ; case RESOLUTION : return valueMatches ( getExpressionResolution ( e ) , resolution , isMin , isMax ) ; case SCAN : String sid = getExpressionIdentifier ( e ) ; if ( sid == null ) return false ; else if ( sid . equals ( "progressive" ) ) return ! scanInterlace ; else if ( sid . equals ( "interlace" ) ) return scanInterlace ; else return false ; case GRID : Integer gval = getExpressionInteger ( e ) ; if ( gval == null ) return false ; else if ( gval == 0 || gval == 1 ) return gval == grid ; else return false ; default : return false ; } } else return false ; }
Checks if this media specification matches a given media query expression .
38,667
public boolean matchesOneOf ( List < MediaQuery > queries ) { for ( MediaQuery q : queries ) { if ( matches ( q ) ) return true ; } return false ; }
Checks whether this media specification matches to at least one of the given media queries .
38,668
protected Float getExpressionLengthPx ( MediaExpression e ) { if ( e . size ( ) == 1 ) { Term < ? > term = e . get ( 0 ) ; if ( term instanceof TermLength ) return pxLength ( ( TermLength ) term ) ; else return null ; } else return null ; }
Obtains the length specified by the given media query expression .
38,669
protected Float getExpressionResolution ( MediaExpression e ) { if ( e . size ( ) == 1 ) { Term < ? > term = e . get ( 0 ) ; if ( term instanceof TermResolution ) return dpiResolution ( ( TermResolution ) term ) ; else return null ; } else return null ; }
Obtains the resolution specified by the given media query expression .
38,670
protected Float getExpressionRatio ( MediaExpression e ) { if ( e . size ( ) == 2 ) { Term < ? > term1 = e . get ( 0 ) ; Term < ? > term2 = e . get ( 1 ) ; if ( term1 instanceof TermInteger && term2 instanceof TermInteger && ( ( ( TermInteger ) term2 ) . getOperator ( ) == Operator . SLASH ) ) return ( ( TermInteger ) term1 ) . getValue ( ) / ( ( TermInteger ) term2 ) . getValue ( ) ; else return null ; } else return null ; }
Obtains the ratio specified by the given media query expression .
38,671
protected Integer getExpressionInteger ( MediaExpression e ) { if ( e . size ( ) == 1 ) { Term < ? > term = e . get ( 0 ) ; if ( term instanceof TermInteger ) return ( ( TermInteger ) term ) . getIntValue ( ) ; else return null ; } else return null ; }
Obtains the integer specified by the given media query expression .
38,672
protected String getExpressionIdentifier ( MediaExpression e ) { if ( e . size ( ) == 1 ) { Term < ? > term = e . get ( 0 ) ; if ( term instanceof TermIdent ) return ( ( TermIdent ) term ) . getValue ( ) . trim ( ) . toLowerCase ( Locale . ENGLISH ) ; else return null ; } else return null ; }
Obtains the identifier specified by the given media query expression .
38,673
protected Float pxLength ( TermLength spec ) { float nval = spec . getValue ( ) ; TermLength . Unit unit = spec . getUnit ( ) ; switch ( unit ) { case pt : return ( nval * dpi ) / 72.0f ; case in : return nval * dpi ; case cm : return ( nval * dpi ) / 2.54f ; case mm : return ( nval * dpi ) / 25.4f ; case q : return ( nval * dpi ) / ( 2.54f * 40f ) ; case pc : return ( nval * 12 * dpi ) / 72.0f ; case px : return nval ; case em : return em * nval ; case ex : return ex * nval ; default : return null ; } }
Converts a length from a CSS length to px .
38,674
protected Float dpiResolution ( TermResolution spec ) { float nval = spec . getValue ( ) ; TermLength . Unit unit = spec . getUnit ( ) ; switch ( unit ) { case dpi : return nval ; case dpcm : return nval * 2.54f ; case dppx : return nval * getResolution ( ) ; default : return null ; } }
Converts a resolution from a CSS length to dpi .
38,675
protected void loadDefaults ( ) { width = 1100 ; height = 850 ; deviceWidth = 1920 ; deviceHeight = 1200 ; color = 8 ; colorIndex = 0 ; monochrome = 0 ; resolution = 96 ; scanInterlace = false ; grid = 0 ; }
Loads some reasonable defaults that correspond to a normal desktop configuration .
38,676
protected List < TermFunction . Gradient . ColorStop > decodeColorStops ( List < List < Term < ? > > > args , int firstStop ) { boolean valid = true ; List < TermFunction . Gradient . ColorStop > colorStops = null ; if ( args . size ( ) > firstStop ) { colorStops = new ArrayList < > ( ) ; for ( int i = firstStop ; valid && i < args . size ( ) ; i ++ ) { List < Term < ? > > sarg = args . get ( i ) ; if ( sarg . size ( ) == 1 || sarg . size ( ) == 2 ) { Term < ? > tclr = sarg . get ( 0 ) ; Term < ? > tlen = ( sarg . size ( ) == 2 ) ? sarg . get ( 1 ) : null ; if ( tclr instanceof TermColor && ( tlen == null || tlen instanceof TermLengthOrPercent ) ) { TermFunction . Gradient . ColorStop newStop = new ColorStopImpl ( ( TermColor ) tclr , ( TermLengthOrPercent ) tlen ) ; colorStops . add ( newStop ) ; } else { valid = false ; } } else { valid = false ; } } } if ( valid && colorStops != null && ! colorStops . isEmpty ( ) ) return colorStops ; else return null ; }
Loads the color stops from the gunction arguments .
38,677
public D get ( E el , P pseudo ) { D ret ; if ( pseudo == null ) ret = mainMap . get ( el ) ; else { HashMap < P , D > map = pseudoMaps . get ( el ) ; if ( map == null ) ret = null ; else ret = map . get ( pseudo ) ; } return ret ; }
Gets the data for the given element and pseudo - element .
38,678
public D getOrCreate ( E el , P pseudo ) { D ret ; if ( pseudo == null ) { ret = mainMap . get ( el ) ; if ( ret == null ) { ret = createDataInstance ( ) ; mainMap . put ( el , ret ) ; } } else { HashMap < P , D > map = pseudoMaps . get ( el ) ; if ( map == null ) { map = new HashMap < P , D > ( ) ; pseudoMaps . put ( el , map ) ; } ret = map . get ( pseudo ) ; if ( ret == null ) { ret = createDataInstance ( ) ; map . put ( pseudo , ret ) ; } } return ret ; }
Gets the data or creates an empty list if it does not exist yet .
38,679
public void put ( E el , P pseudo , D data ) { if ( pseudo == null ) mainMap . put ( el , data ) ; else { HashMap < P , D > map = pseudoMaps . get ( el ) ; if ( map == null ) { map = new HashMap < P , D > ( ) ; pseudoMaps . put ( el , map ) ; } map . put ( pseudo , data ) ; } }
Sets the data for the specified element and pseudo - element .
38,680
public Set < P > pseudoSet ( E el ) { HashMap < P , D > map = pseudoMaps . get ( el ) ; if ( map == null ) return Collections . emptySet ( ) ; else return map . keySet ( ) ; }
Gets all the pseudo elements that are available for the given element .
38,681
public boolean hasPseudo ( E el , P pseudo ) { HashMap < P , D > map = pseudoMaps . get ( el ) ; if ( map == null ) return false ; else return map . containsKey ( pseudo ) ; }
Checks if the given pseudo element is available for the given element
38,682
private void considerType ( TermFloatValue term ) { TermNumeric . Unit unit = term . getUnit ( ) ; if ( utype == Type . none ) { if ( unit != null && unit . getType ( ) != Type . none ) { utype = unit . getType ( ) ; } else if ( term instanceof TermPercent ) { utype = Type . length ; } else if ( term instanceof TermNumber ) { isint = false ; } } else { if ( unit != null && unit . getType ( ) != Type . none ) { if ( unit . getType ( ) != utype ) valid = false ; } } }
isLength isFrequency isAngle isTime isNumber isInteger
38,683
private URL extractBase ( TerminalNode node ) { CSSToken ct = ( CSSToken ) node . getSymbol ( ) ; return ct . getBase ( ) ; }
extract base from parse tree node
38,684
private String extractIdUnescaped ( String id ) { if ( ! id . isEmpty ( ) && ! Character . isDigit ( id . charAt ( 0 ) ) ) { return org . unbescape . css . CssEscape . unescapeCss ( id ) ; } return null ; }
check if string is valid ID
38,685
private String generateSpaces ( int count ) { String spaces = "" ; for ( int i = 0 ; i < count ; i ++ ) { spaces += " " ; } return spaces ; }
generate spaces for pretty debug printing
38,686
private List < ParseTree > filterSpaceTokens ( List < ParseTree > inputArrayList ) { List < ParseTree > ret = new ArrayList < ParseTree > ( inputArrayList . size ( ) ) ; for ( ParseTree item : inputArrayList ) { if ( ! ( item instanceof TerminalNode ) || ( ( TerminalNodeImpl ) item ) . getSymbol ( ) . getType ( ) != CSSLexer . S ) { ret . add ( item ) ; } } return ret ; }
remove terminal node emtpy tokens from input list
38,687
private boolean ctxHasErrorNode ( ParserRuleContext ctx ) { for ( int i = 0 ; i < ctx . children . size ( ) ; i ++ ) { if ( ctx . getChild ( i ) instanceof ErrorNode ) { return true ; } } return false ; }
check if rule context contains error node
38,688
public void addMatch ( Element e , PseudoClassType pseudoClass ) { if ( elements == null ) elements = new HashMap < Element , Set < PseudoClassType > > ( ) ; Set < PseudoClassType > classes = elements . get ( e ) ; if ( classes == null ) { classes = new HashSet < PseudoClassType > ( 2 ) ; elements . put ( e , classes ) ; } classes . add ( pseudoClass ) ; }
Assigns a pseudo class to the given element . Multiple pseudo classes may be assigned to a single element .
38,689
public void removeMatch ( Element e , PseudoClassType pseudoClass ) { if ( elements != null ) { Set < PseudoClassType > classes = elements . get ( e ) ; if ( classes != null ) classes . remove ( pseudoClass ) ; } }
Removes the pseudo class from the given element .
38,690
public void addMatch ( String name , PseudoClassType pseudoClass ) { if ( names == null ) names = new HashMap < String , Set < PseudoClassType > > ( ) ; Set < PseudoClassType > classes = names . get ( name ) ; if ( classes == null ) { classes = new HashSet < PseudoClassType > ( 2 ) ; names . put ( name , classes ) ; } classes . add ( pseudoClass ) ; }
Assigns a pseudo class to the given element name . Element names are case - insensitive . Multiple pseudo classes may be assigned to a single element name .
38,691
public void removeMatch ( String name , PseudoClassType pseudoClass ) { if ( names != null ) { Set < PseudoClassType > classes = names . get ( name ) ; if ( classes != null ) classes . remove ( pseudoClass ) ; } }
Removes the pseudo class from the given element name . Element names are case - insensitive .
38,692
public StyleMap evaluateDOM ( Document doc , MediaSpec media , final boolean inherit ) { DeclarationMap declarations = assingDeclarationsToDOM ( doc , media , inherit ) ; StyleMap nodes = new StyleMap ( declarations . size ( ) ) ; Traversal < StyleMap > traversal = new Traversal < StyleMap > ( doc , ( Object ) declarations , NodeFilter . SHOW_ELEMENT ) { protected void processNode ( StyleMap result , Node current , Object source ) { NodeData main = CSSFactory . createNodeData ( ) ; List < Declaration > declarations = ( ( DeclarationMap ) source ) . get ( ( Element ) current , null ) ; if ( declarations != null ) { for ( Declaration d : declarations ) { main . push ( d ) ; } if ( inherit ) main . inheritFrom ( result . get ( ( Element ) walker . parentNode ( ) , null ) ) ; } result . put ( ( Element ) current , null , main . concretize ( ) ) ; for ( PseudoElementType pseudo : ( ( DeclarationMap ) source ) . pseudoSet ( ( Element ) current ) ) { NodeData pdata = CSSFactory . createNodeData ( ) ; declarations = ( ( DeclarationMap ) source ) . get ( ( Element ) current , pseudo ) ; if ( declarations != null ) { for ( Declaration d : declarations ) { pdata . push ( d ) ; } pdata . inheritFrom ( main ) ; } result . put ( ( Element ) current , pseudo , pdata . concretize ( ) ) ; } } } ; traversal . levelTraversal ( nodes ) ; return nodes ; }
Evaluates CSS properties of DOM tree
38,693
protected DeclarationMap assingDeclarationsToDOM ( Document doc , MediaSpec media , final boolean inherit ) { classifyAllSheets ( media ) ; DeclarationMap declarations = new DeclarationMap ( ) ; if ( rules != null && ! rules . isEmpty ( ) ) { Traversal < DeclarationMap > traversal = new Traversal < DeclarationMap > ( doc , ( Object ) rules , NodeFilter . SHOW_ELEMENT ) { protected void processNode ( DeclarationMap result , Node current , Object source ) { assignDeclarationsToElement ( result , walker , ( Element ) current , ( Holder ) source ) ; } } ; if ( ! inherit ) traversal . listTraversal ( declarations ) ; else traversal . levelTraversal ( declarations ) ; } return declarations ; }
Creates map of declarations assigned to each element of a DOM tree
38,694
protected void classifyAllSheets ( MediaSpec mediaspec ) { rules = new Holder ( ) ; AnalyzerUtil . classifyAllSheets ( sheets , rules , mediaspec ) ; }
Classifies the rules in all the style sheets .
38,695
public Specificity computeSpecificity ( ) { Specificity spec = new SpecificityImpl ( ) ; for ( Selector s : list ) s . computeSpecificity ( spec ) ; return spec ; }
Computes specificity of selector
38,696
public StyleSheet parse ( Object source , NetworkProcessor network , String encoding , SourceType type , Element inline , boolean inlinePriority , URL base ) throws IOException , CSSException { StyleSheet sheet = ( StyleSheet ) CSSFactory . getRuleFactory ( ) . createStyleSheet ( ) . unlock ( ) ; Preparator preparator = new SimplePreparator ( inline , inlinePriority ) ; return parseAndImport ( source , network , encoding , type , sheet , preparator , base , null ) ; }
Parses source of given type
38,697
public StyleSheet parse ( Object source , NetworkProcessor network , String encoding , SourceType type , URL base ) throws IOException , CSSException { if ( type == SourceType . INLINE ) throw new IllegalArgumentException ( "Missing element for INLINE input" ) ; return parse ( source , network , encoding , type , null , false , base ) ; }
Parses source of given type . Uses no element .
38,698
public StyleSheet append ( Object source , NetworkProcessor network , String encoding , SourceType type , Element inline , boolean inlinePriority , StyleSheet sheet , URL base ) throws IOException , CSSException { Preparator preparator = new SimplePreparator ( inline , inlinePriority ) ; return parseAndImport ( source , network , encoding , type , sheet , preparator , base , null ) ; }
Appends parsed source to passed style sheet . This style sheet must be IMPERATIVELY parsed by this factory to guarantee proper appending
38,699
protected StyleSheet parseAndImport ( Object source , NetworkProcessor network , String encoding , SourceType type , StyleSheet sheet , Preparator preparator , URL base , List < MediaQuery > media ) throws CSSException , IOException { CSSParser parser = createParser ( source , network , encoding , type , base ) ; CSSParserExtractor extractor = parse ( parser , type , preparator , media ) ; for ( int i = 0 ; i < extractor . getImportPaths ( ) . size ( ) ; i ++ ) { String path = extractor . getImportPaths ( ) . get ( i ) ; List < MediaQuery > imedia = extractor . getImportMedia ( ) . get ( i ) ; if ( ( ( imedia == null || imedia . isEmpty ( ) ) && CSSFactory . getAutoImportMedia ( ) . matchesEmpty ( ) ) || CSSFactory . getAutoImportMedia ( ) . matchesOneOf ( imedia ) ) { URL url = DataURLHandler . createURL ( base , path ) ; try { parseAndImport ( url , network , encoding , SourceType . URL , sheet , preparator , url , imedia ) ; } catch ( IOException e ) { log . warn ( "Couldn't read imported style sheet: {}" , e . getMessage ( ) ) ; } } else log . trace ( "Skipping import {} (media not matching)" , path ) ; } return addRulesToStyleSheet ( extractor . getRules ( ) , sheet ) ; }
Parses the source using the given infrastructure and returns the resulting style sheet . The imports are handled recursively .