idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
21,100
private Map < String , List < String > > shakeHands ( ) throws WebSocketException { Socket socket = mSocketConnector . getSocket ( ) ; WebSocketInputStream input = openInputStream ( socket ) ; WebSocketOutputStream output = openOutputStream ( socket ) ; String key = generateWebSocketKey ( ) ; writeHandshake ( output , key ) ; Map < String , List < String > > headers = readHandshake ( input , key ) ; mInput = input ; mOutput = output ; return headers ; }
Perform the opening handshake .
21,101
private WebSocketInputStream openInputStream ( Socket socket ) throws WebSocketException { try { return new WebSocketInputStream ( new BufferedInputStream ( socket . getInputStream ( ) ) ) ; } catch ( IOException e ) { throw new WebSocketException ( WebSocketError . SOCKET_INPUT_STREAM_FAILURE , "Failed to get the input stream of the raw socket: " + e . getMessage ( ) , e ) ; } }
Open the input stream of the WebSocket connection . The stream is used by the reading thread .
21,102
private WebSocketOutputStream openOutputStream ( Socket socket ) throws WebSocketException { try { return new WebSocketOutputStream ( new BufferedOutputStream ( socket . getOutputStream ( ) ) ) ; } catch ( IOException e ) { throw new WebSocketException ( WebSocketError . SOCKET_OUTPUT_STREAM_FAILURE , "Failed to get the output stream from the raw socket: " + e . getMessage ( ) , e ) ; } }
Open the output stream of the WebSocket connection . The stream is used by the writing thread .
21,103
private void writeHandshake ( WebSocketOutputStream output , String key ) throws WebSocketException { mHandshakeBuilder . setKey ( key ) ; String requestLine = mHandshakeBuilder . buildRequestLine ( ) ; List < String [ ] > headers = mHandshakeBuilder . buildHeaders ( ) ; String handshake = HandshakeBuilder . build ( requestLine , headers ) ; mListenerManager . callOnSendingHandshake ( requestLine , headers ) ; try { output . write ( handshake ) ; output . flush ( ) ; } catch ( IOException e ) { throw new WebSocketException ( WebSocketError . OPENING_HAHDSHAKE_REQUEST_FAILURE , "Failed to send an opening handshake request to the server: " + e . getMessage ( ) , e ) ; } }
Send an opening handshake request to the WebSocket server .
21,104
private Map < String , List < String > > readHandshake ( WebSocketInputStream input , String key ) throws WebSocketException { return new HandshakeReader ( this ) . readHandshake ( input , key ) ; }
Receive an opening handshake response from the WebSocket server .
21,105
private void startThreads ( ) { ReadingThread readingThread = new ReadingThread ( this ) ; WritingThread writingThread = new WritingThread ( this ) ; synchronized ( mThreadsLock ) { mReadingThread = readingThread ; mWritingThread = writingThread ; } readingThread . callOnThreadCreated ( ) ; writingThread . callOnThreadCreated ( ) ; readingThread . start ( ) ; writingThread . start ( ) ; }
Start both the reading thread and the writing thread .
21,106
private void stopThreads ( long closeDelay ) { ReadingThread readingThread ; WritingThread writingThread ; synchronized ( mThreadsLock ) { readingThread = mReadingThread ; writingThread = mWritingThread ; mReadingThread = null ; mWritingThread = null ; } if ( readingThread != null ) { readingThread . requestStop ( closeDelay ) ; } if ( writingThread != null ) { writingThread . requestStop ( ) ; } }
Stop both the reading thread and the writing thread .
21,107
void onReadingThreadStarted ( ) { boolean bothStarted = false ; synchronized ( mThreadsLock ) { mReadingThreadStarted = true ; if ( mWritingThreadStarted ) { bothStarted = true ; } } callOnConnectedIfNotYet ( ) ; if ( bothStarted ) { onThreadsStarted ( ) ; } }
Called by the reading thread as its first step .
21,108
void onReadingThreadFinished ( WebSocketFrame closeFrame ) { synchronized ( mThreadsLock ) { mReadingThreadFinished = true ; mServerCloseFrame = closeFrame ; if ( mWritingThreadFinished == false ) { return ; } } onThreadsFinished ( ) ; }
Called by the reading thread as its last step .
21,109
void onWritingThreadFinished ( WebSocketFrame closeFrame ) { synchronized ( mThreadsLock ) { mWritingThreadFinished = true ; mClientCloseFrame = closeFrame ; if ( mReadingThreadFinished == false ) { return ; } } onThreadsFinished ( ) ; }
Called by the writing thread as its last step .
21,110
private PerMessageCompressionExtension findAgreedPerMessageCompressionExtension ( ) { if ( mAgreedExtensions == null ) { return null ; } for ( WebSocketExtension extension : mAgreedExtensions ) { if ( extension instanceof PerMessageCompressionExtension ) { return ( PerMessageCompressionExtension ) extension ; } } return null ; }
Find a per - message compression extension from among the agreed extensions .
21,111
public static byte [ ] getBytesUTF8 ( String string ) { if ( string == null ) { return null ; } try { return string . getBytes ( "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { return null ; } }
Get a UTF - 8 byte array representation of the given string .
21,112
public static String toOpcodeName ( int opcode ) { switch ( opcode ) { case CONTINUATION : return "CONTINUATION" ; case TEXT : return "TEXT" ; case BINARY : return "BINARY" ; case CLOSE : return "CLOSE" ; case PING : return "PING" ; case PONG : return "PONG" ; default : break ; } if ( 0x1 <= opcode && opcode <= 0x7 ) { return String . format ( "DATA(0x%X)" , opcode ) ; } if ( 0x8 <= opcode && opcode <= 0xF ) { return String . format ( "CONTROL(0x%X)" , opcode ) ; } return String . format ( "0x%X" , opcode ) ; }
Convert a WebSocket opcode into a string representation .
21,113
public static String readLine ( InputStream in , String charset ) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; while ( true ) { int b = in . read ( ) ; if ( b == - 1 ) { if ( baos . size ( ) == 0 ) { return null ; } else { break ; } } if ( b == '\n' ) { break ; } if ( b != '\r' ) { baos . write ( b ) ; continue ; } int b2 = in . read ( ) ; if ( b2 == - 1 ) { baos . write ( b ) ; break ; } if ( b2 == '\n' ) { break ; } baos . write ( b ) ; baos . write ( b2 ) ; } return baos . toString ( charset ) ; }
Read a line from the given stream .
21,114
public static int min ( int [ ] values ) { int min = Integer . MAX_VALUE ; for ( int i = 0 ; i < values . length ; ++ i ) { if ( values [ i ] < min ) { min = values [ i ] ; } } return min ; }
Find the minimum value from the given array .
21,115
public static int max ( int [ ] values ) { int max = Integer . MIN_VALUE ; for ( int i = 0 ; i < values . length ; ++ i ) { if ( max < values [ i ] ) { max = values [ i ] ; } } return max ; }
Find the maximum value from the given array .
21,116
private static int [ ] createIntArray ( int size , int initialValue ) { int [ ] array = new int [ size ] ; for ( int i = 0 ; i < size ; ++ i ) { array [ i ] = initialValue ; } return array ; }
Create an array whose elements have the given initial value .
21,117
protected < X > Specification < ENTITY > equalsSpecification ( Function < Root < ENTITY > , Expression < X > > metaclassFunction , final X value ) { return ( root , query , builder ) -> builder . equal ( metaclassFunction . apply ( root ) , value ) ; }
Generic method which based on a Root&lt ; ENTITY&gt ; returns an Expression which type is the same as the given value type .
21,118
public T get ( String key ) { purge ( ) ; final Value val = map . get ( key ) ; final long time = System . currentTimeMillis ( ) ; return val != null && time < val . expire ? val . token : null ; }
Get a token from the cache .
21,119
public void put ( String key , T token ) { purge ( ) ; if ( map . containsKey ( key ) ) { map . remove ( key ) ; } final long time = System . currentTimeMillis ( ) ; map . put ( key , new Value ( token , time + expireMillis ) ) ; latestWriteTime = time ; }
Put a token in the cache . If a token already exists for the given key it is replaced .
21,120
protected Parameter createPageParameter ( ParameterContext context ) { ModelReference intModel = createModelRefFactory ( context ) . apply ( resolver . resolve ( Integer . TYPE ) ) ; return new ParameterBuilder ( ) . name ( getPageName ( ) ) . parameterType ( PAGE_TYPE ) . modelRef ( intModel ) . description ( PAGE_DESCRIPTION ) . build ( ) ; }
Create a page parameter . Override it if needed . Set a default value for example .
21,121
protected Parameter createSizeParameter ( ParameterContext context ) { ModelReference intModel = createModelRefFactory ( context ) . apply ( resolver . resolve ( Integer . TYPE ) ) ; return new ParameterBuilder ( ) . name ( getSizeName ( ) ) . parameterType ( SIZE_TYPE ) . modelRef ( intModel ) . description ( SIZE_DESCRIPTION ) . build ( ) ; }
Create a size parameter . Override it if needed . Set a default value for example .
21,122
protected Parameter createSortParameter ( ParameterContext context ) { ModelReference stringModel = createModelRefFactory ( context ) . apply ( resolver . resolve ( List . class , String . class ) ) ; return new ParameterBuilder ( ) . name ( getSortName ( ) ) . parameterType ( SORT_TYPE ) . modelRef ( stringModel ) . allowMultiple ( true ) . description ( SORT_DESCRIPTION ) . build ( ) ; }
Create a sort parameter . Override it if needed . Set a default value or further description for example .
21,123
public V get ( K key ) throws CacheException { logger . debug ( "get key [" + key + "]" ) ; if ( key == null ) { return null ; } try { Object redisCacheKey = getRedisCacheKey ( key ) ; byte [ ] rawValue = redisManager . get ( keySerializer . serialize ( redisCacheKey ) ) ; if ( rawValue == null ) { return null ; } V value = ( V ) valueSerializer . deserialize ( rawValue ) ; return value ; } catch ( SerializationException e ) { throw new CacheException ( e ) ; } }
get shiro authorization redis key - value
21,124
public int size ( ) { Long longSize = 0L ; try { longSize = new Long ( redisManager . dbSize ( keySerializer . serialize ( this . keyPrefix + "*" ) ) ) ; } catch ( SerializationException e ) { logger . error ( "get keys error" , e ) ; } return longSize . intValue ( ) ; }
get all authorization key - value quantity
21,125
public void del ( byte [ ] key ) { if ( key == null ) { return ; } Jedis jedis = getJedis ( ) ; try { jedis . del ( key ) ; } finally { jedis . close ( ) ; } }
Delete a key - value pair .
21,126
public Long dbSize ( byte [ ] pattern ) { long dbSize = 0L ; Jedis jedis = getJedis ( ) ; try { ScanParams params = new ScanParams ( ) ; params . count ( count ) ; params . match ( pattern ) ; byte [ ] cursor = ScanParams . SCAN_POINTER_START_BINARY ; ScanResult < byte [ ] > scanResult ; do { scanResult = jedis . scan ( cursor , params ) ; List < byte [ ] > results = scanResult . getResult ( ) ; for ( byte [ ] result : results ) { dbSize ++ ; } cursor = scanResult . getCursorAsBytes ( ) ; } while ( scanResult . getStringCursor ( ) . compareTo ( ScanParams . SCAN_POINTER_START ) > 0 ) ; } finally { jedis . close ( ) ; } return dbSize ; }
Return the size of redis db .
21,127
public Set < byte [ ] > keys ( byte [ ] pattern ) { Set < byte [ ] > keys = new HashSet < byte [ ] > ( ) ; Jedis jedis = getJedis ( ) ; try { ScanParams params = new ScanParams ( ) ; params . count ( count ) ; params . match ( pattern ) ; byte [ ] cursor = ScanParams . SCAN_POINTER_START_BINARY ; ScanResult < byte [ ] > scanResult ; do { scanResult = jedis . scan ( cursor , params ) ; keys . addAll ( scanResult . getResult ( ) ) ; cursor = scanResult . getCursorAsBytes ( ) ; } while ( scanResult . getStringCursor ( ) . compareTo ( ScanParams . SCAN_POINTER_START ) > 0 ) ; } finally { jedis . close ( ) ; } return keys ; }
Return all the keys of Redis db . Filtered by pattern .
21,128
public static NumberList delta ( Map < String , Object > currentMap , Map < String , Object > previousMap ) { LinkedHashMap < String , Long > values = new LinkedHashMap < String , Long > ( currentMap . size ( ) ) ; if ( currentMap . size ( ) != previousMap . size ( ) ) { throw new IllegalArgumentException ( "Maps must have the same keys" ) ; } for ( Entry < String , Object > k : currentMap . entrySet ( ) ) { Object v = k . getValue ( ) ; Number current = getNumber ( v ) ; Object p = previousMap . get ( k . getKey ( ) ) ; Number previous = null ; if ( p == null ) { previous = 0 ; } else { previous = getNumber ( p ) ; } long d = ( current . longValue ( ) - previous . longValue ( ) ) ; values . put ( k . getKey ( ) , d ) ; } return new NumberList ( values ) ; }
This assumes both maps contain the same keys . If they don t then keys will be lost .
21,129
public static NumberList deltaInverse ( Map < String , Object > map ) { LinkedHashMap < String , Long > values = new LinkedHashMap < String , Long > ( map . size ( ) ) ; for ( Entry < String , Object > k : map . entrySet ( ) ) { Object v = k . getValue ( ) ; Number current = getNumber ( v ) ; long d = - current . longValue ( ) ; values . put ( k . getKey ( ) , d ) ; } return new NumberList ( values ) ; }
Return a NubmerList with the inverse of the given values .
21,130
@ SuppressWarnings ( "unused" ) private static Observable < GroupedObservable < TypeAndNameKey , Map < String , Object > > > aggregateUsingFlattenedGroupBy ( Observable < GroupedObservable < InstanceKey , Map < String , Object > > > stream ) { Observable < Map < String , Object > > allData = stream . flatMap ( instanceStream -> { return instanceStream . map ( ( Map < String , Object > event ) -> { event . put ( "InstanceKey" , instanceStream . getKey ( ) ) ; event . put ( "TypeAndName" , TypeAndNameKey . from ( String . valueOf ( event . get ( "type" ) ) , String . valueOf ( event . get ( "name" ) ) ) ) ; return event ; } ) . compose ( is -> { return tombstone ( is , instanceStream . getKey ( ) ) ; } ) ; } ) ; Observable < GroupedObservable < TypeAndNameKey , Map < String , Object > > > byCommand = allData . groupBy ( ( Map < String , Object > event ) -> { return ( TypeAndNameKey ) event . get ( "TypeAndName" ) ; } ) ; return byCommand . map ( commandGroup -> { Observable < Map < String , Object > > sumOfDeltasForAllInstancesForCommand = commandGroup . groupBy ( ( Map < String , Object > json ) -> { return json . get ( "InstanceKey" ) ; } ) . flatMap ( instanceGroup -> { return instanceGroup . takeUntil ( d -> d . containsKey ( "tombstone" ) ) . startWith ( Collections . < String , Object > emptyMap ( ) ) . map ( data -> { if ( data . containsKey ( "tombstone" ) ) { return Collections . < String , Object > emptyMap ( ) ; } else { return data ; } } ) . buffer ( 2 , 1 ) . filter ( list -> list . size ( ) == 2 ) . map ( StreamAggregator :: previousAndCurrentToDelta ) . filter ( data -> data != null && ! data . isEmpty ( ) ) ; } ) . scan ( new HashMap < String , Object > ( ) , StreamAggregator :: sumOfDelta ) . skip ( 1 ) ; return GroupedObservable . from ( commandGroup . getKey ( ) , sumOfDeltasForAllInstancesForCommand ) ; } ) ; }
Flatten the stream and then do nested groupBy . This matches the mental model and is simple but serializes the stream to a single thread which is bad for performance .
21,131
private static Observable < Map < String , Object > > tombstone ( Observable < Map < String , Object > > instanceStream , InstanceKey instanceKey ) { return instanceStream . publish ( is -> { Observable < Map < String , Object > > tombstone = is . collect ( ( ) -> new HashSet < TypeAndNameKey > ( ) , ( listOfTypeAndName , event ) -> { listOfTypeAndName . add ( ( TypeAndNameKey ) event . get ( "TypeAndName" ) ) ; } ) . flatMap ( listOfTypeAndName -> { return Observable . from ( listOfTypeAndName ) . map ( typeAndName -> { Map < String , Object > tombstoneForTypeAndName = new LinkedHashMap < > ( ) ; tombstoneForTypeAndName . put ( "tombstone" , "true" ) ; tombstoneForTypeAndName . put ( "InstanceKey" , instanceKey ) ; tombstoneForTypeAndName . put ( "TypeAndName" , typeAndName ) ; tombstoneForTypeAndName . put ( "name" , typeAndName . getName ( ) ) ; tombstoneForTypeAndName . put ( "type" , typeAndName . getType ( ) ) ; return tombstoneForTypeAndName ; } ) ; } ) ; return is . mergeWith ( tombstone ) ; } ) ; }
Append tombstone events to each instanceStream when they terminate so that the last values from the stream will be removed from all aggregates down stream .
21,132
public static Properties getFromInstanceConfig ( InstanceConfig defaultInstanceConfig ) { PropertyBasedInstanceConfig config = new PropertyBasedInstanceConfig ( new ConfigCollectionImpl ( defaultInstanceConfig , null ) ) ; return config . getProperties ( ) ; }
Return the default properties given an instance config
21,133
public static InstanceConfig newDefaultInstanceConfig ( BackupProvider provider ) { List < EncodedConfigParser . FieldValue > backupDefaultValues = Lists . newArrayList ( ) ; if ( provider != null ) { for ( BackupConfigSpec spec : provider . getConfigs ( ) ) { backupDefaultValues . add ( new EncodedConfigParser . FieldValue ( spec . getKey ( ) , spec . getDefaultValue ( ) ) ) ; } } final String backupExtraValue = new EncodedConfigParser ( backupDefaultValues ) . toEncoded ( ) ; return new InstanceConfig ( ) { public String getString ( StringConfigs config ) { switch ( config ) { case ZOO_CFG_EXTRA : { return "syncLimit=5&tickTime=2000&initLimit=10" ; } case BACKUP_EXTRA : { return backupExtraValue ; } } return "" ; } public int getInt ( IntConfigs config ) { switch ( config ) { case CLIENT_PORT : { return 2181 ; } case CONNECT_PORT : { return 2888 ; } case ELECTION_PORT : { return 3888 ; } case CHECK_MS : { return ( int ) TimeUnit . MILLISECONDS . convert ( 30 , TimeUnit . SECONDS ) ; } case CLEANUP_PERIOD_MS : { return ( int ) TimeUnit . MILLISECONDS . convert ( 12 , TimeUnit . HOURS ) ; } case CLEANUP_MAX_FILES : { return 3 ; } case BACKUP_PERIOD_MS : { return ( int ) TimeUnit . MILLISECONDS . convert ( 1 , TimeUnit . MINUTES ) ; } case BACKUP_MAX_STORE_MS : { return ( int ) TimeUnit . MILLISECONDS . convert ( 1 , TimeUnit . DAYS ) ; } case AUTO_MANAGE_INSTANCES_SETTLING_PERIOD_MS : { return ( int ) TimeUnit . MILLISECONDS . convert ( 3 , TimeUnit . MINUTES ) ; } case OBSERVER_THRESHOLD : { return 999 ; } case AUTO_MANAGE_INSTANCES_APPLY_ALL_AT_ONCE : { return 1 ; } } return 0 ; } } ; }
Return the standard default properties as an instance config
21,134
public List < String > toDisplayList ( final String separator , ExhibitorArguments . LogDirection logDirection ) { Iterable < String > transformed = Iterables . transform ( queue , new Function < Message , String > ( ) { public String apply ( Message message ) { return message . date + separator + message . type + separator + message . text ; } } ) ; ImmutableList < String > list = ImmutableList . copyOf ( transformed ) ; return ( logDirection == ExhibitorArguments . LogDirection . NATURAL ) ? list : Lists . reverse ( list ) ; }
Return the current window lines
21,135
public void add ( Type type , String message , Throwable exception ) { String queueMessage = message ; if ( ( type == Type . ERROR ) && ( exception != null ) ) { queueMessage += " (" + getExceptionMessage ( exception ) + ")" ; } if ( type . addToUI ( ) ) { while ( queue . size ( ) > windowSizeLines ) { queue . remove ( ) ; } queue . add ( new Message ( queueMessage , type ) ) ; } type . log ( message , exception ) ; }
Add a log message with an exception
21,136
public static String getExceptionMessage ( Throwable exception ) { StringWriter out = new StringWriter ( ) ; exception . printStackTrace ( new PrintWriter ( out ) ) ; BufferedReader in = new BufferedReader ( new StringReader ( out . toString ( ) ) ) ; try { StringBuilder str = new StringBuilder ( ) ; for ( ; ; ) { String line = in . readLine ( ) ; if ( line == null ) { break ; } if ( str . length ( ) > 0 ) { str . append ( ", " ) ; } str . append ( line ) ; } return str . toString ( ) ; } catch ( IOException e ) { } return "n/a" ; }
Convert an exception into a log message
21,137
public String getValue ( final String field ) { FieldValue fieldValue = Iterables . find ( fieldValues , new Predicate < FieldValue > ( ) { public boolean apply ( FieldValue fv ) { return fv . getField ( ) . equals ( field ) ; } } , null ) ; return ( fieldValue != null ) ? fieldValue . getValue ( ) : null ; }
Return the value for the given field or null
21,138
public static DefaultResourceConfig newApplicationConfig ( UIContext context ) { final Set < Object > singletons = getSingletons ( context ) ; final Set < Class < ? > > classes = getClasses ( ) ; return new DefaultResourceConfig ( ) { public Set < Class < ? > > getClasses ( ) { return classes ; } public Set < Object > getSingletons ( ) { return singletons ; } } ; }
Return a new Jersey config instance that correctly supplies all needed Exhibitor objects
21,139
public ServerList filterOutObservers ( ) { Iterable < ServerSpec > filtered = Iterables . filter ( specs , new Predicate < ServerSpec > ( ) { public boolean apply ( ServerSpec spec ) { return spec . getServerType ( ) != ServerType . OBSERVER ; } } ) ; return new ServerList ( Lists . newArrayList ( filtered ) ) ; }
Return this server list with any observers removed
21,140
public void start ( ) { for ( QueueGroups group : QueueGroups . values ( ) ) { final DelayQueue < ActivityHolder > thisQueue = queues . get ( group ) ; service . submit ( new Runnable ( ) { public void run ( ) { try { while ( ! Thread . currentThread ( ) . isInterrupted ( ) ) { ActivityHolder holder = thisQueue . take ( ) ; try { Boolean result = holder . activity . call ( ) ; holder . activity . completed ( ( result != null ) && result ) ; } catch ( Throwable e ) { log . error ( "Unhandled exception in background task" , e ) ; } } } catch ( InterruptedException dummy ) { Thread . currentThread ( ) . interrupt ( ) ; } } } ) ; } }
The queue must be started
21,141
public synchronized void add ( QueueGroups group , Activity activity ) { add ( group , activity , 0 , TimeUnit . MILLISECONDS ) ; }
Add an activity to the given queue
21,142
public synchronized void add ( QueueGroups group , Activity activity , long delay , TimeUnit unit ) { ActivityHolder holder = new ActivityHolder ( activity , TimeUnit . MILLISECONDS . convert ( delay , unit ) ) ; queues . get ( group ) . offer ( holder ) ; }
Add an activity to the given queue that executes after a specified delay
21,143
public synchronized void replace ( QueueGroups group , Activity activity ) { replace ( group , activity , 0 , TimeUnit . MILLISECONDS ) ; }
Replace the given activity in the given queue . If not in the queue adds it to the queue .
21,144
public static String getHostname ( ) { String host = "unknown" ; try { return InetAddress . getLocalHost ( ) . getHostName ( ) ; } catch ( UnknownHostException e ) { } return host ; }
Return this VM s hostname if possible
21,145
public void start ( ) throws Exception { Preconditions . checkState ( state . compareAndSet ( State . LATENT , State . STARTED ) ) ; backupManager . restoreAll ( ) ; activityQueue . start ( ) ; configManager . start ( ) ; monitorRunningInstance . start ( ) ; cleanupManager . start ( ) ; backupManager . start ( ) ; autoInstanceManagement . start ( ) ; if ( servoMonitoring != null ) { servoMonitoring . start ( ) ; } configManager . addConfigListener ( new ConfigListener ( ) { public void configUpdated ( ) { try { resetLocalConnection ( ) ; } catch ( IOException e ) { log . add ( ActivityLog . Type . ERROR , "Resetting connection" , e ) ; } } } ) ; }
Start the app
21,146
public List < BackupMetaData > getAvailableBackups ( ) throws Exception { Map < String , String > config = getBackupConfig ( ) ; return backupProvider . get ( ) . getAvailableBackups ( exhibitor , config ) ; }
Return list of available backups
21,147
public BackupStream getBackupStream ( BackupMetaData metaData ) throws Exception { return backupProvider . get ( ) . getBackupStream ( exhibitor , metaData , getBackupConfig ( ) ) ; }
Return a stream for the specified backup
21,148
public void restoreAll ( ) throws Exception { if ( ! backupProvider . isPresent ( ) ) { log . info ( "No backup provider configured. Skipping restore." ) ; return ; } ZooKeeperLogFiles logFiles = new ZooKeeperLogFiles ( exhibitor ) ; log . info ( "Restoring log files from backup." ) ; if ( ! logFiles . isValid ( ) ) { log . error ( "Backup path invalid. Skipping restore." ) ; return ; } if ( logFiles . getPaths ( ) . isEmpty ( ) ) { log . info ( "Backup path(s) empty. Skipping restore." ) ; return ; } File dataDir = ZooKeeperLogFiles . getDataDir ( exhibitor ) ; for ( BackupMetaData data : getAvailableBackups ( ) ) { String fileName = data . getName ( ) ; log . info ( String . format ( "Restoring file: %s" , fileName ) ) ; File file = new File ( dataDir , fileName ) ; restore ( data , file ) ; } log . info ( "Restoring logs from backup done." ) ; }
Restore all known logs
21,149
public void restore ( BackupMetaData backup , File destinationFile ) throws Exception { File tempFile = File . createTempFile ( "exhibitor-backup" , ".tmp" ) ; OutputStream out = new FileOutputStream ( tempFile ) ; InputStream in = null ; try { backupProvider . get ( ) . downloadBackup ( exhibitor , backup , out , getBackupConfig ( ) ) ; CloseableUtils . closeQuietly ( out ) ; out = null ; out = new FileOutputStream ( destinationFile ) ; in = new GZIPInputStream ( new FileInputStream ( tempFile ) ) ; ByteStreams . copy ( in , out ) ; } finally { CloseableUtils . closeQuietly ( in ) ; CloseableUtils . closeQuietly ( out ) ; if ( ! tempFile . delete ( ) ) { exhibitor . getLog ( ) . add ( ActivityLog . Type . ERROR , "Could not delete temp file (for restore): " + tempFile ) ; } } }
Restore the given key to the given file
21,150
public static By byAttribute ( String attributeName , String attributeValue ) { return By . cssSelector ( String . format ( "[%s='%s']" , attributeName , attributeValue ) ) ; }
Find elements having attribute with given value .
21,151
public static List < String > texts ( Collection < WebElement > elements ) { return elements . stream ( ) . map ( ElementsCollection :: getText ) . collect ( toList ( ) ) ; }
Fail - safe method for retrieving texts of given elements .
21,152
public static String elementsToString ( Driver driver , Collection < WebElement > elements ) { if ( elements == null ) { return "[not loaded yet...]" ; } if ( elements . isEmpty ( ) ) { return "[]" ; } StringBuilder sb = new StringBuilder ( 256 ) ; sb . append ( "[\n\t" ) ; for ( WebElement element : elements ) { if ( sb . length ( ) > 4 ) { sb . append ( ",\n\t" ) ; } sb . append ( Describe . describe ( driver , element ) ) ; } sb . append ( "\n]" ) ; return sb . toString ( ) ; }
Outputs string presentation of the element s collection
21,153
public void start ( ) { proxy . setTrustAllServers ( true ) ; if ( outsideProxy != null ) { proxy . setChainedProxy ( getProxyAddress ( outsideProxy ) ) ; } addRequestFilter ( "authentication" , new AuthenticationFilter ( ) ) ; addRequestFilter ( "requestSizeWatchdog" , new RequestSizeWatchdog ( ) ) ; addResponseFilter ( "responseSizeWatchdog" , new ResponseSizeWatchdog ( ) ) ; addResponseFilter ( "download" , new FileDownloadFilter ( config ) ) ; proxy . start ( config . proxyPort ( ) ) ; port = proxy . getPort ( ) ; }
Start the server
21,154
public Proxy createSeleniumProxy ( ) { return isEmpty ( config . proxyHost ( ) ) ? ClientUtil . createSeleniumProxy ( proxy ) : ClientUtil . createSeleniumProxy ( proxy , inetAddressResolver . getInetAddressByName ( config . proxyHost ( ) ) ) ; }
Converts this proxy to a selenium proxy that can be used by webdriver
21,155
@ SuppressWarnings ( "unchecked" ) public < T extends RequestFilter > T requestFilter ( String name ) { return ( T ) requestFilters . get ( name ) ; }
Get request filter by name
21,156
@ SuppressWarnings ( "unchecked" ) public < T extends ResponseFilter > T responseFilter ( String name ) { return ( T ) responseFilters . get ( name ) ; }
Get response filter by name
21,157
public static Condition value ( final String expectedValue ) { return new Condition ( "value" ) { public boolean apply ( Driver driver , WebElement element ) { return Html . text . contains ( getAttributeValue ( element , "value" ) , expectedValue ) ; } public String toString ( ) { return name + " '" + expectedValue + "'" ; } } ; }
Assert that element has given value attribute as substring NB! Ignores difference in non - visible characters like spaces non - breakable spaces tabs newlines etc .
21,158
public static Condition matchText ( final String regex ) { return new Condition ( "match text" ) { public boolean apply ( Driver driver , WebElement element ) { return Html . text . matches ( element . getText ( ) , regex ) ; } public String toString ( ) { return name + " '" + regex + '\'' ; } } ; }
Assert that given element s text matches given regular expression
21,159
public static Condition selectedText ( final String expectedText ) { return new Condition ( "selectedText" ) { String actualResult = "" ; public boolean apply ( Driver driver , WebElement element ) { actualResult = driver . executeJavaScript ( "return arguments[0].value.substring(arguments[0].selectionStart, arguments[0].selectionEnd);" , element ) ; return actualResult . equals ( expectedText ) ; } public String actualValue ( Driver driver , WebElement element ) { return "'" + actualResult + "'" ; } public String toString ( ) { return name + " '" + expectedText + '\'' ; } } ; }
Checks for selected text on a given input web element
21,160
public static Condition and ( String name , final Condition ... condition ) { return new Condition ( name ) { private Condition lastFailedCondition ; public boolean apply ( Driver driver , WebElement element ) { for ( Condition c : condition ) { if ( ! c . apply ( driver , element ) ) { lastFailedCondition = c ; return false ; } } return true ; } public String actualValue ( Driver driver , WebElement element ) { return lastFailedCondition == null ? null : lastFailedCondition . actualValue ( driver , element ) ; } public String toString ( ) { return lastFailedCondition == null ? super . toString ( ) : lastFailedCondition . toString ( ) ; } } ; }
Check if element matches ALL given conditions .
21,161
private Object convertStringToNearestObjectType ( String value ) { switch ( value ) { case "true" : return true ; case "false" : return false ; default : { if ( NumberUtils . isParsable ( value ) ) { return Integer . parseInt ( value ) ; } return value ; } } }
Converts String to Boolean \ Integer or returns original String .
21,162
private boolean isScrolling ( ) { float scrolledX = Math . abs ( accumulatedScrollOffset . x ) ; int expectedScrollX = Math . abs ( width * monthsScrolledSoFar ) ; return scrolledX < expectedScrollX - 5 || scrolledX > expectedScrollX + 5 ; }
as it maybe off by a few pixels
21,163
private void drawEventsWithPlus ( Canvas canvas , float xPosition , float yPosition , List < Event > eventsList ) { for ( int j = 0 , k = - 2 ; j < 3 ; j ++ , k += 2 ) { Event event = eventsList . get ( j ) ; float xStartPosition = xPosition + ( xIndicatorOffset * k ) ; if ( j == 2 ) { dayPaint . setColor ( multiEventIndicatorColor ) ; dayPaint . setStrokeWidth ( multiDayIndicatorStrokeWidth ) ; canvas . drawLine ( xStartPosition - smallIndicatorRadius , yPosition , xStartPosition + smallIndicatorRadius , yPosition , dayPaint ) ; canvas . drawLine ( xStartPosition , yPosition - smallIndicatorRadius , xStartPosition , yPosition + smallIndicatorRadius , dayPaint ) ; dayPaint . setStrokeWidth ( 0 ) ; } else { drawEventIndicatorCircle ( canvas , xStartPosition , yPosition , event . getColor ( ) ) ; } } }
draw 2 eventsByMonthAndYearMap followed by plus indicator to show there are more than 2 eventsByMonthAndYearMap
21,164
int getDayOfWeek ( Calendar calendar ) { int dayOfWeek = calendar . get ( Calendar . DAY_OF_WEEK ) - firstDayOfWeekToDraw ; dayOfWeek = dayOfWeek < 0 ? 7 + dayOfWeek : dayOfWeek ; return dayOfWeek ; }
it returns 0 - 6 where 0 is Sunday instead of 1
21,165
private void drawCircle ( Canvas canvas , float x , float y , int color , float circleScale ) { dayPaint . setColor ( color ) ; if ( animationStatus == ANIMATE_INDICATORS ) { float maxRadius = circleScale * bigCircleIndicatorRadius * 1.4f ; drawCircle ( canvas , growfactorIndicator > maxRadius ? maxRadius : growfactorIndicator , x , y - ( textHeight / 6 ) ) ; } else { drawCircle ( canvas , circleScale * bigCircleIndicatorRadius , x , y - ( textHeight / 6 ) ) ; } }
Draw Circle on certain days to highlight them
21,166
private String getKeyForCalendarEvent ( Calendar cal ) { return cal . get ( Calendar . YEAR ) + "_" + cal . get ( Calendar . MONTH ) ; }
E . g . 4 2016 becomes 2016_4
21,167
public void unfixDialogDimens ( ) { Logr . d ( "Reset the fixed dimensions to allow for re-measurement" ) ; getLayoutParams ( ) . height = LayoutParams . MATCH_PARENT ; getLayoutParams ( ) . width = LayoutParams . MATCH_PARENT ; requestLayout ( ) ; }
This method should only be called if the calendar is contained in a dialog and it should only be called when the screen has been rotated and the dialog should be re - measured .
21,168
AtomicInteger inflightRequests ( Id id ) { return Utils . computeIfAbsent ( inflightRequests , id , i -> new AtomicInteger ( ) ) ; }
Return the number of inflight requests associated with the given id .
21,169
Function < String , String > limiterForKey ( String key ) { return Utils . computeIfAbsent ( limiters , key , k -> CardinalityLimiters . rollup ( 25 ) ) ; }
Return the cardinality limiter for a given key . This is used to protect the metrics backend from a metrics explosion if some dimensions have a high cardinality .
21,170
void log ( IpcLogEntry entry ) { Level level = entry . getLevel ( ) ; Predicate < Marker > enabled ; BiConsumer < Marker , String > log ; switch ( level ) { case TRACE : enabled = logger :: isTraceEnabled ; log = logger :: trace ; break ; case DEBUG : enabled = logger :: isDebugEnabled ; log = logger :: debug ; break ; case INFO : enabled = logger :: isInfoEnabled ; log = logger :: info ; break ; case WARN : enabled = logger :: isWarnEnabled ; log = logger :: warn ; break ; case ERROR : enabled = logger :: isErrorEnabled ; log = logger :: error ; break ; default : enabled = logger :: isDebugEnabled ; log = logger :: debug ; break ; } if ( enabled . test ( entry . getMarker ( ) ) ) { log . accept ( entry . getMarker ( ) , entry . toString ( ) ) ; } if ( entry . isSuccessful ( ) ) { entry . reset ( ) ; entries . offer ( entry ) ; } else { entry . resetForRetry ( ) ; } }
Called by the entry to log the request .
21,171
public static SeqServerGroup parse ( String asg ) { int d1 = asg . indexOf ( '-' ) ; int d2 = asg . indexOf ( '-' , d1 + 1 ) ; int dN = asg . lastIndexOf ( '-' ) ; if ( dN < 0 || ! isSequence ( asg , dN ) ) { dN = asg . length ( ) ; } return new SeqServerGroup ( asg , d1 , d2 , dN ) ; }
Create a new instance of a server group object by parsing the group name .
21,172
private static CharSequence substr ( CharSequence str , int s , int e ) { return ( s >= e ) ? null : CharBuffer . wrap ( str , s , e ) ; }
The substring method will create a copy of the substring in JDK 8 and probably newer versions . To reduce the number of allocations we use a char buffer to return a view with just that subset .
21,173
public static IdBuilder < Builder > builder ( Registry registry ) { return new IdBuilder < Builder > ( registry ) { protected Builder createTypeBuilder ( Id id ) { return new Builder ( registry , id ) ; } } ; }
Return a builder for configuring and retrieving and instance of a percentile distribution summary . If the distribution summary has dynamic dimensions then the builder can be used with the new dimensions . If the id is the same as an existing distribution summary then it will update the same underlying distribution summaries in the registry .
21,174
private Counter counterFor ( int i ) { Counter c = counters . get ( i ) ; if ( c == null ) { Id counterId = id . withTags ( Statistic . percentile , new BasicTag ( "percentile" , TAG_VALUES [ i ] ) ) ; c = registry . counter ( counterId ) ; counters . set ( i , c ) ; } return c ; }
accessed for a distribution summary .
21,175
public double percentile ( double p ) { long [ ] counts = new long [ PercentileBuckets . length ( ) ] ; for ( int i = 0 ; i < counts . length ; ++ i ) { counts [ i ] = counterFor ( i ) . count ( ) ; } return PercentileBuckets . percentile ( counts , p ) ; }
Computes the specified percentile for this distribution summary .
21,176
public void max ( double v ) { if ( Double . isFinite ( v ) ) { double max = get ( ) ; while ( isGreaterThan ( v , max ) && ! compareAndSet ( max , v ) ) { max = value . get ( ) ; } } }
Set the current value to the maximum of the current value or the provided value .
21,177
static byte [ ] encode ( Map < String , String > commonTags , List < Measurement > measurements ) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; JsonGenerator gen = FACTORY . createGenerator ( baos ) ; gen . writeStartArray ( ) ; Map < String , Integer > strings = buildStringTable ( gen , commonTags , measurements ) ; for ( Measurement m : measurements ) { appendMeasurement ( gen , strings , commonTags , m . id ( ) , m . value ( ) ) ; } gen . writeEndArray ( ) ; gen . close ( ) ; return baos . toByteArray ( ) ; }
Encode the measurements to a JSON payload that can be sent to the aggregator .
21,178
public static SparkValueFunction fromConfig ( Config config , String key ) { return fromPatternList ( config . getConfigList ( key ) ) ; }
Create a value function based on a config .
21,179
@ SuppressWarnings ( "unchecked" ) protected < T extends Meter > T getOrCreate ( Id id , Class < T > cls , T dflt , Function < Id , T > factory ) { try { Preconditions . checkNotNull ( id , "id" ) ; Meter m = Utils . computeIfAbsent ( meters , id , i -> compute ( factory . apply ( i ) , dflt ) ) ; if ( ! cls . isAssignableFrom ( m . getClass ( ) ) ) { logTypeError ( id , cls , m . getClass ( ) ) ; m = dflt ; } return ( T ) m ; } catch ( Exception e ) { propagate ( e ) ; return dflt ; } }
Helper used to get or create an instance of a core meter type . This is mostly used internally to this implementation but may be useful in rare cases for creating customizations based on a core type in a sub - class .
21,180
protected void removeExpiredMeters ( ) { int total = 0 ; int expired = 0 ; Iterator < Map . Entry < Id , Meter > > it = meters . entrySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { ++ total ; Map . Entry < Id , Meter > entry = it . next ( ) ; Meter m = entry . getValue ( ) ; if ( m . hasExpired ( ) ) { ++ expired ; it . remove ( ) ; } } logger . debug ( "removed {} expired meters out of {} total" , expired , total ) ; cleanupCachedState ( ) ; }
Can be called by sub - classes to remove expired meters from the internal map . The SwapMeter types that are returned will lookup a new copy on the next access .
21,181
private void cleanupCachedState ( ) { int total = 0 ; int expired = 0 ; Iterator < Map . Entry < Id , Object > > it = state . entrySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { ++ total ; Map . Entry < Id , Object > entry = it . next ( ) ; Object obj = entry . getValue ( ) ; if ( obj instanceof Meter && ( ( Meter ) obj ) . hasExpired ( ) ) { ++ expired ; it . remove ( ) ; } } logger . debug ( "removed {} expired entries from cache out of {} total" , expired , total ) ; }
Cleanup any expired meter patterns stored in the state . It should only be used as a cache so the entry should get recreated if needed .
21,182
public static BucketDistributionSummary get ( Id id , BucketFunction f ) { return get ( Spectator . globalRegistry ( ) , id , f ) ; }
Creates a distribution summary object that manages a set of distribution summaries based on the bucket function supplied . Calling record will be mapped to the record on the appropriate distribution summary .
21,183
static String getServletPath ( HttpServletRequest request ) { String servletPath = request . getServletPath ( ) ; if ( hackWorks && PACKAGE . equals ( request . getClass ( ) . getPackage ( ) . getName ( ) ) ) { try { Object outer = get ( request , "this$0" ) ; Object servletPipeline = get ( outer , "servletPipeline" ) ; Object servletDefs = get ( servletPipeline , "servletDefinitions" ) ; int length = Array . getLength ( servletDefs ) ; for ( int i = 0 ; i < length ; ++ i ) { Object pattern = get ( Array . get ( servletDefs , i ) , "patternMatcher" ) ; if ( matches ( pattern , servletPath ) ) { servletPath = extractPath ( pattern , servletPath ) ; break ; } } } catch ( Exception e ) { hackWorks = false ; } } return servletPath ; }
Helper to get the servlet path for the request .
21,184
public < E extends Enum < E > > T withTag ( String k , Enum < E > v ) { return withTag ( k , v . name ( ) ) ; }
Add an additional tag value based on the name of the enum .
21,185
public IpcLogEntry withException ( Throwable exception ) { this . exception = exception ; if ( statusDetail == null ) { statusDetail = exception . getClass ( ) . getSimpleName ( ) ; } if ( status == null ) { status = IpcStatus . forException ( exception ) ; } return this ; }
Set the exception that was thrown while trying to execute the request . This will be logged and can be used to fill in the error reason .
21,186
public IpcLogEntry withUri ( String uri , String path ) { this . uri = uri ; this . path = path ; return this ; }
Set the URI and path for the request .
21,187
public void log ( ) { if ( logger != null ) { if ( registry != null ) { if ( isClient ( ) ) { recordClientMetrics ( ) ; } else { recordServerMetrics ( ) ; } } if ( inflightId != null ) { logger . inflightRequests ( inflightId ) . decrementAndGet ( ) ; } logger . log ( this ) ; } else { reset ( ) ; } }
Log the request . This entry will potentially be reused after this is called . The user should not attempt any further modifications to the state of this entry .
21,188
void reset ( ) { logger = null ; level = Level . DEBUG ; marker = null ; startTime = - 1L ; startNanos = - 1L ; latency = - 1L ; owner = null ; result = null ; protocol = null ; status = null ; statusDetail = null ; exception = null ; attempt = null ; attemptFinal = null ; vip = null ; endpoint = null ; clientRegion = null ; clientZone = null ; clientApp = null ; clientCluster = null ; clientAsg = null ; clientNode = null ; serverRegion = null ; serverZone = null ; serverApp = null ; serverCluster = null ; serverAsg = null ; serverNode = null ; httpMethod = null ; httpStatus = - 1 ; uri = null ; path = null ; requestHeaders . clear ( ) ; responseHeaders . clear ( ) ; remoteAddress = null ; remotePort = - 1 ; additionalTags . clear ( ) ; builder . delete ( 0 , builder . length ( ) ) ; inflightId = null ; }
Resets this log entry so the instance can be reused . This helps to reduce allocations .
21,189
void resetForRetry ( ) { startTime = - 1L ; startNanos = - 1L ; latency = - 1L ; result = null ; status = null ; statusDetail = null ; exception = null ; attempt = null ; attemptFinal = null ; vip = null ; serverRegion = null ; serverZone = null ; serverApp = null ; serverCluster = null ; serverAsg = null ; serverNode = null ; httpStatus = - 1 ; requestHeaders . clear ( ) ; responseHeaders . clear ( ) ; remoteAddress = null ; remotePort = - 1 ; builder . delete ( 0 , builder . length ( ) ) ; inflightId = null ; }
Partially reset this log entry so it can be used for another request attempt . Any attributes that can change for a given request need to be cleared .
21,190
public static PatternMatcher compile ( String pattern ) { String p = pattern ; boolean ignoreCase = false ; if ( p . startsWith ( "(?i)" ) ) { ignoreCase = true ; p = pattern . substring ( 4 ) ; } if ( p . length ( ) > 0 ) { p = "^.*(" + p + ").*$" ; } Parser parser = new Parser ( PatternUtils . expandEscapedChars ( p ) ) ; Matcher m = Optimizer . optimize ( parser . parse ( ) ) ; return ignoreCase ? m . ignoreCase ( ) : m ; }
Compile a pattern string and return a matcher that can be used to check if string values match the pattern . Pattern matchers are can be reused many times and are thread safe .
21,191
static IllegalArgumentException error ( String message , String str , int pos ) { return new IllegalArgumentException ( message + "\n" + context ( str , pos ) ) ; }
Create an IllegalArgumentException with a message including context based on the position .
21,192
static UnsupportedOperationException unsupported ( String message , String str , int pos ) { return new UnsupportedOperationException ( message + "\n" + context ( str , pos ) ) ; }
Create an UnsupportedOperationException with a message including context based on the position .
21,193
@ SuppressWarnings ( "PMD.NcssCount" ) static String expandEscapedChars ( String str ) { StringBuilder builder = new StringBuilder ( ) ; for ( int i = 0 ; i < str . length ( ) ; ++ i ) { char c = str . charAt ( i ) ; if ( c == '\\' ) { ++ i ; if ( i >= str . length ( ) ) { throw error ( "dangling escape" , str , i ) ; } c = str . charAt ( i ) ; switch ( c ) { case 't' : builder . append ( '\t' ) ; break ; case 'n' : builder . append ( '\n' ) ; break ; case 'r' : builder . append ( '\r' ) ; break ; case 'f' : builder . append ( '\f' ) ; break ; case 'a' : builder . append ( '\u0007' ) ; break ; case 'e' : builder . append ( '\u001B' ) ; break ; case '0' : int numDigits = 0 ; for ( int j = i + 1 ; j < Math . min ( i + 4 , str . length ( ) ) ; ++ j ) { c = str . charAt ( j ) ; if ( c >= '0' && c <= '7' ) { ++ numDigits ; } else { break ; } } if ( numDigits < 1 || numDigits > 3 ) { throw error ( "invalid octal escape sequence" , str , i ) ; } c = parse ( str . substring ( i + 1 , i + numDigits + 1 ) , 8 , "octal" , str , i ) ; builder . append ( c ) ; i += numDigits ; break ; case 'x' : if ( i + 3 > str . length ( ) ) { throw error ( "invalid hexadecimal escape sequence" , str , i ) ; } c = parse ( str . substring ( i + 1 , i + 3 ) , 16 , "hexadecimal" , str , i ) ; builder . append ( c ) ; i += 2 ; break ; case 'u' : if ( i + 5 > str . length ( ) ) { throw error ( "invalid unicode escape sequence" , str , i ) ; } c = parse ( str . substring ( i + 1 , i + 5 ) , 16 , "unicode" , str , i ) ; builder . append ( c ) ; i += 4 ; break ; default : builder . append ( '\\' ) . append ( c ) ; break ; } } else { builder . append ( c ) ; } } return builder . toString ( ) ; }
Expand escaped characters . Escapes that are needed for structural elements of the pattern will not be expanded .
21,194
@ SuppressWarnings ( "PMD.NcssCount" ) static String escape ( String str ) { StringBuilder builder = new StringBuilder ( ) ; for ( int i = 0 ; i < str . length ( ) ; ++ i ) { char c = str . charAt ( i ) ; switch ( c ) { case '\t' : builder . append ( "\\t" ) ; break ; case '\n' : builder . append ( "\\n" ) ; break ; case '\r' : builder . append ( "\\r" ) ; break ; case '\f' : builder . append ( "\\f" ) ; break ; case '\\' : builder . append ( "\\\\" ) ; break ; case '^' : builder . append ( "\\^" ) ; break ; case '$' : builder . append ( "\\$" ) ; break ; case '.' : builder . append ( "\\." ) ; break ; case '?' : builder . append ( "\\?" ) ; break ; case '*' : builder . append ( "\\*" ) ; break ; case '+' : builder . append ( "\\+" ) ; break ; case '[' : builder . append ( "\\[" ) ; break ; case ']' : builder . append ( "\\]" ) ; break ; case '(' : builder . append ( "\\(" ) ; break ; case ')' : builder . append ( "\\)" ) ; break ; case '{' : builder . append ( "\\{" ) ; break ; case '}' : builder . append ( "\\}" ) ; break ; default : if ( c <= ' ' || c > '~' ) { builder . append ( String . format ( "\\u%04x" , ( int ) c ) ) ; } else { builder . append ( c ) ; } break ; } } return builder . toString ( ) ; }
Escape a string so it will be interpreted as a literal character sequence when processed as a regular expression .
21,195
static Matcher ignoreCase ( Matcher matcher ) { if ( matcher instanceof CharClassMatcher ) { CharClassMatcher m = matcher . as ( ) ; return new CharClassMatcher ( m . set ( ) , true ) ; } else if ( matcher instanceof CharSeqMatcher ) { CharSeqMatcher m = matcher . as ( ) ; return new CharSeqMatcher ( m . pattern ( ) , true ) ; } else if ( matcher instanceof IndexOfMatcher ) { IndexOfMatcher m = matcher . as ( ) ; return new IndexOfMatcher ( m . pattern ( ) , m . next ( ) , true ) ; } else if ( matcher instanceof StartsWithMatcher ) { StartsWithMatcher m = matcher . as ( ) ; return new StartsWithMatcher ( m . pattern ( ) , true ) ; } else { return matcher ; } }
Convert to a matchers that ignores the case .
21,196
static Matcher head ( Matcher matcher ) { if ( matcher instanceof SeqMatcher ) { List < Matcher > ms = matcher . < SeqMatcher > as ( ) . matchers ( ) ; return ms . get ( 0 ) ; } else { return matcher ; } }
Returns the first matcher from a sequence .
21,197
static Matcher tail ( Matcher matcher ) { if ( matcher instanceof SeqMatcher ) { List < Matcher > ms = matcher . < SeqMatcher > as ( ) . matchers ( ) ; return SeqMatcher . create ( ms . subList ( 1 , ms . size ( ) ) ) ; } else { return TrueMatcher . INSTANCE ; } }
Returns all but the first matcher from a sequence or True if there is only a single matcher in the sequence .
21,198
static DefaultPlaceholderId createWithFactories ( String name , Iterable < TagFactory > tagFactories , Registry registry ) { if ( tagFactories == null ) { return new DefaultPlaceholderId ( name , registry ) ; } else { FactorySorterAndDeduplicator sorter = new FactorySorterAndDeduplicator ( tagFactories ) ; return new DefaultPlaceholderId ( name , sorter . asCollection ( ) , registry ) ; } }
Creates a new id with the specified name and collection of factories .
21,199
private DefaultPlaceholderId createNewId ( Consumer < FactorySorterAndDeduplicator > consumer ) { FactorySorterAndDeduplicator sorter = new FactorySorterAndDeduplicator ( tagFactories ) ; consumer . accept ( sorter ) ; return new DefaultPlaceholderId ( name , sorter . asCollection ( ) , registry ) ; }
Creates a new dynamic id based on the factories associated with this id and whatever additions are made by the specified consumer .