idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
1,500
public Set < Flag > extract ( List < String > messages ) throws ExtractionException { boolean gotFetch = false ; Set < Flag > result = null ; String fetchStr = null ; for ( int i = 0 , messagesSize = messages . size ( ) ; i < messagesSize ; i ++ ) { String message = messages . get ( i ) ; if ( null == message || message . isEmpty ( ) ) continue ; fetchStr = matchAndGetGroup1 ( FETCH_FLAG_PATT , message ) ; if ( fetchStr != null ) { if ( gotFetch ) { throw new ExtractionException ( "STORE_FLAGS RESPONSE: Got more than one FETCH response " + message ) ; } gotFetch = true ; result = Flag . parseFlagList ( Parsing . tokenize ( fetchStr ) ) ; } else { if ( matchAndGetGroup1 ( OK_PATT , message ) != null ) { if ( ! gotFetch ) { throw new ExtractionException ( "STORE_FLAGS RESPONSE: no FLAGS received." + message ) ; } } else if ( matchAndGetGroup1 ( BAD_PATT , message ) != null || matchAndGetGroup1 ( NO_PATT , message ) != null ) { throw new ExtractionException ( "STORE_FLAGS RESPONSE: " + message ) ; } } } return result ; }
Parse the response which includes new flag settings and command status . We expect only one FETCH response as we only set flags on one msg .
1,501
protected Element getArticleTitle ( ) { Element articleTitle = mDocument . createElement ( "h1" ) ; articleTitle . html ( mDocument . title ( ) ) ; return articleTitle ; }
Get the article title as an H1 . Currently just uses document . title we might want to be smarter in the future .
1,502
protected void prepDocument ( ) { if ( mDocument . body ( ) == null ) { mDocument . appendElement ( "body" ) ; } Elements elementsToRemove = mDocument . getElementsByTag ( "script" ) ; for ( Element script : elementsToRemove ) { script . remove ( ) ; } elementsToRemove = getElementsByTag ( mDocument . head ( ) , "link" ) ; for ( Element styleSheet : elementsToRemove ) { if ( "stylesheet" . equalsIgnoreCase ( styleSheet . attr ( "rel" ) ) ) { styleSheet . remove ( ) ; } } elementsToRemove = mDocument . getElementsByTag ( "style" ) ; for ( Element styleTag : elementsToRemove ) { styleTag . remove ( ) ; } mDocument . body ( ) . html ( mDocument . body ( ) . html ( ) . replaceAll ( Patterns . REGEX_REPLACE_BRS , "</p><p>" ) . replaceAll ( Patterns . REGEX_REPLACE_FONTS , "<$1span>" ) ) ; }
Prepare the HTML document for readability to scrape it . This includes things like stripping javascript CSS and handling terrible markup .
1,503
private void prepArticle ( Element articleContent ) { cleanStyles ( articleContent ) ; killBreaks ( articleContent ) ; clean ( articleContent , "form" ) ; clean ( articleContent , "object" ) ; clean ( articleContent , "h1" ) ; if ( getElementsByTag ( articleContent , "h2" ) . size ( ) == 1 ) { clean ( articleContent , "h2" ) ; } clean ( articleContent , "iframe" ) ; cleanHeaders ( articleContent ) ; cleanConditionally ( articleContent , "table" ) ; cleanConditionally ( articleContent , "ul" ) ; cleanConditionally ( articleContent , "div" ) ; Elements articleParagraphs = getElementsByTag ( articleContent , "p" ) ; for ( Element articleParagraph : articleParagraphs ) { int imgCount = getElementsByTag ( articleParagraph , "img" ) . size ( ) ; int embedCount = getElementsByTag ( articleParagraph , "embed" ) . size ( ) ; int objectCount = getElementsByTag ( articleParagraph , "object" ) . size ( ) ; if ( imgCount == 0 && embedCount == 0 && objectCount == 0 && isEmpty ( getInnerText ( articleParagraph , false ) ) ) { articleParagraph . remove ( ) ; } } try { articleContent . html ( articleContent . html ( ) . replaceAll ( "(?i)<br[^>]*>\\s*<p" , "<p" ) ) ; } catch ( Exception e ) { dbg ( "Cleaning innerHTML of breaks failed. This is an IE strict-block-elements bug. Ignoring." , e ) ; } }
Prepare the article node for display . Clean out any inline styles iframes forms strip extraneous &lt ; p&gt ; tags etc .
1,504
private static String getInnerText ( Element e , boolean normalizeSpaces ) { String textContent = e . text ( ) . trim ( ) ; if ( normalizeSpaces ) { textContent = textContent . replaceAll ( Patterns . REGEX_NORMALIZE , "" ) ; } return textContent ; }
Get the inner text of a node - cross browser compatibly . This also strips out any excess whitespace to be found .
1,505
private static int getCharCount ( Element e , String s ) { if ( s == null || s . length ( ) == 0 ) { s = "," ; } return getInnerText ( e , true ) . split ( s ) . length ; }
Get the number of times a string s appears in the node e .
1,506
private static void cleanStyles ( Element e ) { if ( e == null ) { return ; } Element cur = e . children ( ) . first ( ) ; if ( ! "readability-styled" . equals ( e . className ( ) ) ) { e . removeAttr ( "style" ) ; } while ( cur != null ) { if ( ! "readability-styled" . equals ( cur . className ( ) ) ) { cur . removeAttr ( "style" ) ; } cleanStyles ( cur ) ; cur = cur . nextElementSibling ( ) ; } }
Remove the style attribute on every e and under .
1,507
private static float getLinkDensity ( Element e ) { Elements links = getElementsByTag ( e , "a" ) ; int textLength = getInnerText ( e , true ) . length ( ) ; float linkLength = 0.0F ; for ( Element link : links ) { linkLength += getInnerText ( link , true ) . length ( ) ; } return linkLength / textLength ; }
Get the density of links as a percentage of the content . This is the amount of text that is inside a link divided by the total text in the node .
1,508
private static void killBreaks ( Element e ) { e . html ( e . html ( ) . replaceAll ( Patterns . REGEX_KILL_BREAKS , "<br />" ) ) ; }
Remove extraneous break tags from a node .
1,509
private void cleanConditionally ( Element e , String tag ) { Elements tagsList = getElementsByTag ( e , tag ) ; for ( Element node : tagsList ) { int weight = getClassWeight ( node ) ; dbg ( "Cleaning Conditionally (" + node . className ( ) + ":" + node . id ( ) + ")" + getContentScore ( node ) ) ; if ( weight < 0 ) { node . remove ( ) ; } else if ( getCharCount ( node , "," ) < 10 ) { int p = getElementsByTag ( node , "p" ) . size ( ) ; int img = getElementsByTag ( node , "img" ) . size ( ) ; int li = getElementsByTag ( node , "li" ) . size ( ) - 100 ; int input = getElementsByTag ( node , "input" ) . size ( ) ; int embedCount = 0 ; Elements embeds = getElementsByTag ( node , "embed" ) ; for ( Element embed : embeds ) { if ( ! Patterns . get ( Patterns . RegEx . VIDEO ) . matcher ( embed . absUrl ( "src" ) ) . find ( ) ) { embedCount ++ ; } } float linkDensity = getLinkDensity ( node ) ; int contentLength = getInnerText ( node , true ) . length ( ) ; boolean toRemove = false ; if ( img > p ) { toRemove = true ; } else if ( li > p && ! "ul" . equalsIgnoreCase ( tag ) && ! "ol" . equalsIgnoreCase ( tag ) ) { toRemove = true ; } else if ( input > Math . floor ( p / 3 ) ) { toRemove = true ; } else if ( contentLength < 25 && ( img == 0 || img > 2 ) ) { toRemove = true ; } else if ( weight < 25 && linkDensity > 0.2f ) { toRemove = true ; } else if ( weight > 25 && linkDensity > 0.5f ) { toRemove = true ; } else if ( ( embedCount == 1 && contentLength < 75 ) || embedCount > 1 ) { toRemove = true ; } if ( toRemove ) { node . remove ( ) ; } } } }
Clean an element of all tags of type tag if they look fishy . Fishy is an algorithm based on content length classnames link density number of images & embeds etc .
1,510
private static void cleanHeaders ( Element e ) { for ( int headerIndex = 1 ; headerIndex < 7 ; headerIndex ++ ) { Elements headers = getElementsByTag ( e , "h" + headerIndex ) ; for ( Element header : headers ) { if ( getClassWeight ( header ) < 0 || getLinkDensity ( header ) > 0.33f ) { header . remove ( ) ; } } } }
Clean out spurious headers from an Element . Checks things like classnames and link density .
1,511
protected void dbg ( String msg , Throwable t ) { System . out . println ( msg + ( t != null ? ( "\n" + t . getMessage ( ) ) : "" ) + ( t != null ? ( "\n" + t . getStackTrace ( ) ) : "" ) ) ; }
Print debug logs with stack trace
1,512
private static int getContentScore ( Element node ) { try { return Integer . parseInt ( node . attr ( CONTENT_SCORE ) ) ; } catch ( NumberFormatException e ) { return 0 ; } }
Reads the content score .
1,513
private static Element scaleContentScore ( Element node , float scale ) { int contentScore = getContentScore ( node ) ; contentScore *= scale ; node . attr ( CONTENT_SCORE , Integer . toString ( contentScore ) ) ; return node ; }
Scales the content score for an Element with a factor of scale .
1,514
private static String stty ( final String args ) throws IOException , InterruptedException { return runCommand ( new String [ ] { "sh" , "-c" , String . format ( "stty %s < /dev/tty" , args ) } ) ; }
Run the stty command with arguments in the active terminal .
1,515
private static String runCommand ( final String [ ] cmd ) throws IOException , InterruptedException { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; Process process = Runtime . getRuntime ( ) . exec ( cmd ) ; int c ; InputStream in = process . getInputStream ( ) ; while ( ( c = in . read ( ) ) != - 1 ) { baos . write ( c ) ; } in = process . getErrorStream ( ) ; while ( ( c = in . read ( ) ) != - 1 ) { baos . write ( c ) ; } process . waitFor ( ) ; return new String ( baos . toByteArray ( ) ) ; }
Run the command synchronously and return clubbed standard error and output stream s data .
1,516
private DataSource processSql ( String insertStmntStr ) { Program pgm = DCompiler . compileSql ( insertStmntStr ) ; if ( ! ( pgm instanceof InsertProgram ) ) { log . error ( "Ignoring program {} . Only inserts are supported" , insertStmntStr ) ; return null ; } InsertProgram insertPgm = ( InsertProgram ) pgm ; DataSource ds = new DataSource ( ) ; switch ( insertPgm . getStmntType ( ) ) { case INSERT : BasicInsertMeta stmt = ( BasicInsertMeta ) insertPgm . nthStmnt ( 0 ) ; Interval interval = stmt . granularitySpec . interval ; long startTime = getDateTime ( interval . startTime ) . withMinuteOfHour ( 0 ) . withSecondOfMinute ( 0 ) . withMillisOfSecond ( 0 ) . getMillis ( ) ; ds . setName ( stmt . dataSource ) . setDelimiter ( stmt . delimiter ) . setListDelimiter ( stmt . listDelimiter ) . setTemplatePath ( stmt . dataPath ) . setStartTime ( startTime ) . setSpinFromTime ( startTime ) . setFrequency ( JobFreq . valueOf ( stmt . granularitySpec . gran ) ) . setEndTime ( getDateTime ( interval . endTime ) . getMillis ( ) ) . setStatus ( JobStatus . not_done ) . setTemplateSql ( templatizeSql ( insertStmntStr , interval ) ) ; break ; case INSERT_HADOOP : BatchInsertMeta bStmt = ( BatchInsertMeta ) insertPgm . nthStmnt ( 0 ) ; Interval bInterval = bStmt . granularitySpec . interval ; long startBTime = getDateTime ( bInterval . startTime ) . withMinuteOfHour ( 0 ) . withSecondOfMinute ( 0 ) . withMillisOfSecond ( 0 ) . getMillis ( ) ; ds . setName ( bStmt . dataSource ) . setDelimiter ( bStmt . delimiter ) . setListDelimiter ( bStmt . listDelimiter ) . setTemplatePath ( bStmt . inputSpec . getRawPath ( ) ) . setStartTime ( startBTime ) . setSpinFromTime ( startBTime ) . setFrequency ( JobFreq . valueOf ( bStmt . granularitySpec . gran ) ) . setEndTime ( getDateTime ( bInterval . endTime ) . getMillis ( ) ) . setStatus ( JobStatus . not_done ) . setTemplateSql ( templatizeSql ( insertStmntStr , bInterval ) ) ; break ; case INSERT_REALTIME : log . error ( "Realtime insert currently unsupported {}" , pgm ) ; return null ; } return ds ; }
Creates DataSource for the given Sql insert statement .
1,517
public T get ( int index ) { if ( index < 0 || index >= size ) { return null ; } if ( ! wasFullAtleastOnce && index >= emptyItemIndex ) { return null ; } return ( T ) ( items [ index ] ) ; }
To exactly get item at index .
1,518
public T getDown ( ) { if ( navigator < 0 ) { return null ; } if ( ( wasFullAtleastOnce && navigator == size - 1 ) || ( ! wasFullAtleastOnce && navigator == emptyItemIndex - 1 ) ) { try { return ( T ) ( items [ navigator ] ) ; } finally { navigator = 0 ; } } return ( T ) ( items [ navigator ++ ] ) ; }
Think of this method conceptually as navigating using down arrow in history list of commands .
1,519
public T getUp ( ) { if ( navigator < 0 ) { return null ; } if ( navigator == 0 ) { try { return ( T ) ( items [ navigator ] ) ; } finally { if ( wasFullAtleastOnce ) { navigator = size - 1 ; } else { navigator = emptyItemIndex - 1 ; } } } return ( T ) ( items [ navigator -- ] ) ; }
Think of this method conceptually as navigating using down up in history list of commands .
1,520
public void add ( T item ) { hasElements = true ; navigator = emptyItemIndex ; items [ emptyItemIndex ] = item ; if ( emptyItemIndex == size - 1 ) { wasFullAtleastOnce = true ; } emptyItemIndex = ( emptyItemIndex + 1 ) % size ; }
Navigator should point to most recent added element .
1,521
public TaskStatus pollTaskStatus ( String taskId , Map < String , String > reqHeaders ) { CloseableHttpResponse resp = null ; String url = format ( "%s/%s/status" , format ( overlordUrl , overlordHost , overlordPort ) , taskId ) ; try { resp = get ( url , reqHeaders ) ; JSONObject respJson = new JSONObject ( IOUtils . toString ( resp . getEntity ( ) . getContent ( ) ) ) ; JSONObject status = respJson . optJSONObject ( "status" ) ; if ( status != null && null != status . getString ( "status" ) ) { switch ( status . getString ( "status" ) ) { case "SUCCESS" : return TaskStatus . SUCCESS ; case "RUNNING" : return TaskStatus . RUNNING ; default : return TaskStatus . FAILED ; } } } catch ( IOException ex ) { log . error ( "Error polling for task status {}" , ExceptionUtils . getStackTrace ( ex ) ) ; } finally { returnClient ( resp ) ; } return TaskStatus . UNKNOWN ; }
Poll for task s status for tasks fired with 0 wait time .
1,522
private Cancellable scheduleCron ( int initialDelay , int interval , MessageTypes message ) { return scheduler . schedule ( secs ( initialDelay ) , secs ( interval ) , getSelf ( ) , message , getContext ( ) . dispatcher ( ) , null ) ; }
Schedules messages ever interval seconds .
1,523
private void bootFromDsqls ( String path ) { File [ ] files = new File ( path ) . listFiles ( new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { return name . endsWith ( ".sql" ) ; } } ) ; for ( File file : files ) { sqlSniffer . onCreate ( Paths . get ( file . toURI ( ) ) ) ; } }
Read off a bunch of sql files expecting insert statements within them .
1,524
private static synchronized void proxyInit ( ) { if ( PROXY_HOST != null && customRouterPlanner == null ) { HttpHost proxy = new HttpHost ( PROXY_HOST , PROXY_PORT ) ; customRouterPlanner = new DefaultProxyRoutePlanner ( proxy ) ; } }
To ensure customRouterPlanner is initialized only once .
1,525
public void returnClient ( CloseableHttpResponse resp ) { try { if ( resp != null ) { EntityUtils . consume ( resp . getEntity ( ) ) ; } } catch ( IOException ex ) { log . error ( "Error returning client to pool {}" , ExceptionUtils . getStackTrace ( ex ) ) ; } }
This ensures the response body is completely consumed and hence the HttpClient object will be return back to the pool successfully .
1,526
public boolean execute ( Map < String , String > params , String query ) { final AtomicBoolean result = new AtomicBoolean ( false ) ; Tuple2 < DataSource , Connection > conn = null ; try { conn = getConnection ( ) ; NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate ( conn . _1 ( ) ) ; jdbcTemplate . execute ( query , params , new PreparedStatementCallback < Void > ( ) { public Void doInPreparedStatement ( PreparedStatement ps ) { try { result . set ( ps . execute ( ) ) ; } catch ( SQLException e ) { result . set ( false ) ; } return null ; } } ) ; } catch ( Exception ex ) { Logger . getLogger ( MysqlAccessor . class . getName ( ) ) . log ( Level . SEVERE , null , ex ) ; result . set ( false ) ; } finally { returnConnection ( conn ) ; } return result . get ( ) ; }
Suitable for CRUD operations where no result set is expected .
1,527
public static QueryMeta checkAndPromoteToTimeSeries ( QueryMeta qMeta ) { if ( qMeta instanceof GroupByQueryMeta ) { if ( ( ( GroupByQueryMeta ) qMeta ) . fetchDimensions == null ) { return TimeSeriesQueryMeta . promote ( qMeta ) ; } } return qMeta ; }
Every query starts with GroupBy . Call this method after GROUP BY clause .
1,528
public void filterSegments ( List < Interval > allSegments ) { segmentsToDelete = Lists . newArrayList ( Iterables . filter ( allSegments , new Predicate < Interval > ( ) { public boolean apply ( Interval i ) { return i . fallsIn ( interval ) ; } } ) ) ; }
Retain segments only overlapping with the range .
1,529
public Interval getTimeBoundary ( String dataSource , Map < String , String > reqHeaders ) throws IllegalAccessException { Program < BaseStatementMeta > pgm = DCompiler . compileSql ( format ( "SELECT FROM %s" , dataSource ) ) ; Either < String , Either < Mapper4All , JSONArray > > res = fireQuery ( pgm . nthStmnt ( 0 ) . toString ( ) , reqHeaders , true ) ; if ( res . isLeft ( ) ) { throw new IllegalAccessException ( format ( "DataSource %s does not exist(or) check if druid is accessible, faced exception %s" , dataSource , res . left ( ) . get ( ) ) ) ; } Mapper4All finalRes = res . right ( ) . get ( ) . left ( ) . get ( ) ; int min = finalRes . baseFieldNames . indexOf ( "minTime" ) ; int max = finalRes . baseFieldNames . indexOf ( "maxTime" ) ; if ( finalRes . baseAllRows . isEmpty ( ) ) { throw new IllegalAccessException ( "Either table does not exist(or) druid is not accessible" ) ; } List < Object > row = finalRes . baseAllRows . get ( 0 ) ; return new Interval ( row . get ( min ) . toString ( ) , row . get ( max ) . toString ( ) ) ; }
Get timeboundary .
1,530
public Program < BaseStatementMeta > getCompiledAST ( String sqlQuery , NamedParameters namedParams , Map < String , String > reqHeaders ) throws Exception { Program < BaseStatementMeta > pgm = DCompiler . compileSql ( preprocessSqlQuery ( sqlQuery , namedParams ) ) ; for ( BaseStatementMeta stmnt : pgm . getAllStmnts ( ) ) { if ( stmnt instanceof QueryMeta ) { QueryMeta query = ( QueryMeta ) stmnt ; if ( query . queryType == RequestType . SELECT ) { Either < String , Tuple2 < List < String > , List < String > > > dataSourceDescRes = coordinator . aboutDataSource ( stmnt . dataSource , reqHeaders ) ; if ( dataSourceDescRes . isLeft ( ) ) { throw new Exception ( "Datasource info either not available (or)could not be loaded ." + dataSourceDescRes . left ( ) . get ( ) ) ; } else { ( ( SelectQueryMeta ) query ) . postProcess ( dataSourceDescRes . right ( ) . get ( ) ) ; } } } else if ( stmnt instanceof InsertMeta ) { } else if ( stmnt instanceof DeleteMeta ) { } else if ( stmnt instanceof DropMeta ) { } } pgm . isValid ( ) ; return pgm ; }
Get an in memory representation of broken SQL query . This may require contacting druid for resolving dimensions Vs metrics for SELECT queries hence it also optionally accepts HTTP request headers to be sent out .
1,531
public Either < String , Either < Joiner4All , Mapper4All > > query ( String sqlQuery , Map < String , String > reqHeaders ) { return query ( sqlQuery , null , reqHeaders , false , "sql" ) ; }
Query and return the Json response .
1,532
private T extractKeyAndRow ( String timestamp , JSONObject jsonRow ) { T rowValues = null ; try { rowValues = rowMapper . newInstance ( ) ; rowValues . getClass ( ) . getMethod ( "setTimestamp" , String . class ) . invoke ( rowValues , timestamp ) ; for ( Object key : jsonRow . keySet ( ) ) { Util . applyKVToBean ( rowValues , key . toString ( ) , jsonRow . get ( key . toString ( ) ) ) ; } } catch ( InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException ex ) { Logger . getLogger ( Mapper4Bean . class . getName ( ) ) . log ( Level . SEVERE , null , ex ) ; } return rowValues ; }
Extract v = all fields from json . The first field is always timestamp and is not extracted here .
1,533
private List < Object > extractKeyAndRow ( String timestamp , JSONObject jsonRow ) { List < Object > rowValues = new ArrayList < > ( ) ; rowValues . add ( timestamp ) ; for ( Object key : jsonRow . keySet ( ) ) { rowValues . add ( jsonRow . get ( key . toString ( ) ) ) ; } return rowValues ; }
Extract v = all fields from json . The first field is always timestamp and is passed to the method not extracted .
1,534
public static List < String > getDimensions ( Map < String , String > fetchDimensions ) { return new ArrayList < > ( fetchDimensions . keySet ( ) ) ; }
This method actually returns everything ( including timestamp which is first field .
1,535
public void markTask ( StatusTrail st , boolean success ) { st . setStatus ( success ? JobStatus . done : JobStatus . not_done ) ; st . setAttemptsDone ( st . getAttemptsDone ( ) + 1 ) ; st . setGivenUp ( st . getAttemptsDone ( ) >= getMaxTaskAttempts ( ) ? 1 : 0 ) ; updateStatusTrail ( st ) ; }
Change the status of a task .
1,536
private Either < String , Either < JSONArray , JSONObject > > fireCommand ( String endPoint , String optData , Map < String , String > reqHeaders ) { CloseableHttpResponse resp = null ; String respStr ; String url = format ( coordinatorUrl + endPoint , coordinatorHost , coordinatorPort ) ; try { if ( optData != null ) { resp = postJson ( url , optData , reqHeaders ) ; } else { resp = get ( url , reqHeaders ) ; } respStr = IOUtils . toString ( resp . getEntity ( ) . getContent ( ) ) ; } catch ( IOException ex ) { return new Left < > ( format ( "Http %s, faced exception %s\n" , resp , ex ) ) ; } finally { returnClient ( resp ) ; } try { return new Right < > ( Util . asJsonType ( respStr ) ) ; } catch ( JSONException je ) { return new Left < > ( format ( "Recieved data %s not in json format, faced exception %s\n" , respStr , je ) ) ; } }
All commands . If data is null then GET else POST .
1,537
public Either < String , List < String > > dataSources ( Map < String , String > reqHeaders ) { Either < String , Either < JSONArray , JSONObject > > resp = fireCommand ( "druid/coordinator/v1/metadata/datasources" , null , reqHeaders ) ; if ( resp . isLeft ( ) ) { return new Left < > ( resp . left ( ) . get ( ) ) ; } Either < JSONArray , JSONObject > goodResp = resp . right ( ) . get ( ) ; if ( goodResp . isLeft ( ) ) { JSONArray dataSources = goodResp . left ( ) . get ( ) ; List < String > dataSourceList = new ArrayList < > ( ) ; for ( int i = 0 ; i < dataSources . length ( ) ; i ++ ) { dataSourceList . add ( dataSources . getString ( i ) ) ; } return new Right < > ( dataSourceList ) ; } return new Left < > ( resp . left ( ) . get ( ) ) ; }
Retrieve all the datasources provisioned in Druid .
1,538
public T removeFirst ( ) { try { modifyLock . lock ( ) ; Iterator < T > it = iterator ( ) ; if ( it . hasNext ( ) ) { T item = it . next ( ) ; it . remove ( ) ; return item ; } } finally { modifyLock . unlock ( ) ; } return null ; }
Special method that removes head element .
1,539
public void join ( JSONArray jsonAllRows , List < String > joinFields , ActionType action ) { if ( jsonAllRows . length ( ) == 0 ) { return ; } JSONObject sample = jsonAllRows . getJSONObject ( 0 ) ; if ( sample . has ( "event" ) ) { extractAndTakeAction ( null , jsonAllRows , joinFields , RequestType . GROUPBY , action ) ; } else if ( sample . has ( "result" ) ) { if ( sample . optJSONObject ( "result" ) != null ) { extractAndTakeAction ( null , jsonAllRows , joinFields , RequestType . TIMESERIES , action ) ; } else if ( sample . optJSONArray ( "result" ) != null ) { JSONObject jsonItem = jsonAllRows . getJSONObject ( 0 ) ; JSONArray result = jsonItem . getJSONArray ( "result" ) ; extractAndTakeAction ( jsonItem . optString ( "timestamp" ) , result , joinFields , RequestType . TOPN , action ) ; } } }
If action if FIRST_CUT then the values are added directly to the result else rows will be filtered on key .
1,540
public static Program compileSql ( String query ) { try { ANTLRStringStream in = new ANTLRStringStream ( query ) ; druidGLexer lexer = new druidGLexer ( in ) ; CommonTokenStream tokens = new CommonTokenStream ( lexer ) ; druidGParser parser = new druidGParser ( tokens ) ; Program pgm = parser . program ( ) ; return pgm ; } catch ( RecognitionException ex ) { System . out . println ( ex ) ; Logger . getLogger ( DCompiler . class . getName ( ) ) . log ( Level . SEVERE , null , ex ) ; } return null ; }
Sql - > Json .
1,541
protected void tryRefillHeaders ( JSONObject eachRow ) { if ( eachRow == null ) { return ; } if ( eachRow . keySet ( ) . size ( ) > baseFieldNames . size ( ) - 1 ) { baseFieldNames . clear ( ) ; baseFieldNames . add ( "timestamp" ) ; baseFieldNames . addAll ( eachRow . keySet ( ) ) ; } }
Will attempt to refill headers if we see more fields .
1,542
public Map < String , Object > getJsonMap ( ) { Map < String , Object > map = new LinkedHashMap < > ( ) ; map . put ( "type" , gComplex != null && gComplex . isLeft ( ) ? "duration" : "period" ) ; if ( gComplex != null ) { if ( gComplex . isLeft ( ) ) { map . put ( "duration" , gComplex . left ( ) . get ( ) ) ; } else { map . put ( "period" , gComplex . right ( ) . get ( ) ) ; } if ( origin != null ) { map . put ( "origin" , origin ) ; } if ( timeZone != null ) { map . put ( "timeZone" , timeZone ) ; } } return map ; }
Basic type when granularity is just string is taken care in QueryMeta class . For duration and period types we get Json from here .
1,543
public Map < String , Object > getSpec ( ) { return ImmutableMap . < String , Object > of ( "ioConfig" , getIoConfig ( ) , "dataSchema" , getDataSchema ( ) , "tuningConfig" , getTuningConfig ( ) ) ; }
be removed in future .
1,544
public List < String > removeSavedPlainCommands ( ) { if ( saved . isEmpty ( ) ) { return Collections . emptyList ( ) ; } List < String > result = new ArrayList < > ( saved ) ; saved . clear ( ) ; if ( ! result . isEmpty ( ) ) { log . info ( "{} commands are removed from saved list" , result . size ( ) ) ; } return result ; }
Stable work is not guaranteed
1,545
public long getAsLong ( final String name , final long defaultValue ) { return AtsdUtil . getPropertyLongValue ( fullName ( name ) , clientProperties , defaultValue ) ; }
Get property by name as long value
1,546
public int getAsInt ( final String name , final int defaultValue ) { return AtsdUtil . getPropertyIntValue ( fullName ( name ) , clientProperties , defaultValue ) ; }
Get property by name as int value
1,547
public boolean getAsBoolean ( final String name , final boolean defaultValue ) { return AtsdUtil . getPropertyBoolValue ( fullName ( name ) , clientProperties , defaultValue ) ; }
Get property by name as boolean value
1,548
public static ClientConfigurationBuilder builder ( final String url , final String username , final String password ) { return new ClientConfigurationBuilder ( url , username , password ) ; }
Create builder with unnecessary args .
1,549
public boolean createOrReplaceMetric ( Metric metric ) { String metricName = metric . getName ( ) ; checkMetricIsEmpty ( metricName ) ; QueryPart < Metric > queryPart = new Query < Metric > ( "metrics" ) . path ( metricName , true ) ; return httpClientManager . updateMetaData ( queryPart , put ( metric ) ) ; }
create or replace metric
1,550
public boolean createOrReplaceEntity ( Entity entity ) { String entityName = entity . getName ( ) ; checkEntityIsEmpty ( entityName ) ; QueryPart < Entity > queryPart = new Query < Entity > ( "entities" ) . path ( entityName , true ) ; return httpClientManager . updateMetaData ( queryPart , put ( entity ) ) ; }
Create or replace
1,551
public boolean deleteEntityGroup ( EntityGroup entityGroup ) { String entityGroupName = entityGroup . getName ( ) ; checkEntityGroupIsEmpty ( entityGroupName ) ; QueryPart < EntityGroup > query = new Query < EntityGroup > ( "entity-groups" ) . path ( entityGroupName , true ) ; return httpClientManager . updateMetaData ( query , delete ( ) ) ; }
Delete entity group
1,552
public boolean addGroupEntities ( String entityGroupName , Boolean createEntities , Entity ... entities ) { checkEntityGroupIsEmpty ( entityGroupName ) ; List < String > entitiesNames = new ArrayList < > ( ) ; for ( Entity entity : entities ) { entitiesNames . add ( entity . getName ( ) ) ; } QueryPart < EntityGroup > query = new Query < EntityGroup > ( "entity-groups" ) . path ( entityGroupName , true ) . path ( "entities/add" ) . param ( "createEntities" , createEntities ) ; return httpClientManager . updateData ( query , post ( entitiesNames ) ) ; }
Add specified entities to entity group .
1,553
public boolean deleteGroupEntities ( String entityGroupName , Entity ... entities ) { checkEntityGroupIsEmpty ( entityGroupName ) ; List < String > entitiesNames = new ArrayList < > ( ) ; for ( Entity entity : entities ) { entitiesNames . add ( entity . getName ( ) ) ; } QueryPart < Entity > query = new Query < Entity > ( "entity-groups" ) . path ( entityGroupName , true ) . path ( "entities/delete" ) ; return httpClientManager . updateMetaData ( query , post ( entitiesNames ) ) ; }
Delete entities from entity group .
1,554
public ClientConfiguration createClientConfiguration ( ) { return ClientConfiguration . builder ( buildTimeSeriesUrl ( ) , username , password ) . connectTimeoutMillis ( connectTimeoutMillis ) . readTimeoutMillis ( readTimeoutMillis ) . pingTimeoutMillis ( pingTimeoutMillis ) . ignoreSSLErrors ( ignoreSSLErrors ) . skipStreamingControl ( skipStreamingControl ) . enableBatchCompression ( enableGzipCompression ) . userAgent ( userAgent ) . build ( ) ; }
Build client configuration from set properties .
1,555
@ SuppressWarnings ( "unchecked" ) public T finish ( ) throws IOException { if ( _open ) { _closeChild ( ) ; _open = false ; if ( _closeGenerator ) { _generator . close ( ) ; } else if ( Feature . FLUSH_AFTER_WRITE_VALUE . isEnabled ( _features ) ) { _generator . flush ( ) ; } } if ( _result == null ) { Object x ; if ( _stringWriter != null ) { x = _stringWriter . getAndClear ( ) ; _stringWriter = null ; } else if ( _byteWriter != null ) { x = _byteWriter . toByteArray ( ) ; _byteWriter = null ; } else { x = _generator . getOutputTarget ( ) ; } _result = ( T ) x ; } return _result ; }
Method to call to complete composition flush any pending content and return instance of specified result type .
1,556
public TypeBindings withUnboundVariable ( String name ) { int len = ( _unboundVariables == null ) ? 0 : _unboundVariables . length ; String [ ] names = ( len == 0 ) ? new String [ 1 ] : Arrays . copyOf ( _unboundVariables , len + 1 ) ; names [ len ] = name ; return new TypeBindings ( _names , _types , names ) ; }
Method for creating an instance that has same bindings as this object plus an indicator for additional type variable that may be unbound within this context ; this is needed to resolve recursive self - references .
1,557
public ValueReader findReader ( Class < ? > raw ) { ClassKey k = ( _key == null ) ? new ClassKey ( raw , _features ) : _key . with ( raw , _features ) ; ValueReader vr = _knownReaders . get ( k ) ; if ( vr != null ) { return vr ; } vr = createReader ( null , raw , raw ) ; if ( _knownReaders . size ( ) >= MAX_CACHED_READERS ) { _knownReaders . clear ( ) ; } _knownReaders . putIfAbsent ( new ClassKey ( raw , _features ) , vr ) ; return vr ; }
Method used during deserialization to find handler for given non - generic type .
1,558
public JSON with ( Feature ... features ) { int flags = _features ; for ( Feature feature : features ) { flags |= feature . mask ( ) ; } return _with ( flags ) ; }
Mutant factory for constructing an instance with specified features enabled .
1,559
protected final JSON _with ( int features ) { if ( _features == features ) { return this ; } return _with ( features , _streamFactory , _treeCodec , _reader , _writer , _prettyPrinter ) ; }
Internal mutant factory method used for constructing
1,560
public List < ResolvedType > typeParametersFor ( Class < ? > erasedSupertype ) { ResolvedType type = findSupertype ( erasedSupertype ) ; if ( type != null ) { return type . typeParams ( ) ; } return null ; }
Method that will try to find type parameterization this type has for specified super type
1,561
public List < Reference > getPath ( ) { if ( _path == null ) { return Collections . emptyList ( ) ; } return Collections . unmodifiableList ( _path ) ; }
Method for accessing full structural path within type hierarchy down to problematic property .
1,562
public Object read ( JSONReader r , JsonParser p ) throws IOException { if ( p . isExpectedStartObjectToken ( ) ) { final Object bean ; try { bean = create ( ) ; } catch ( Exception e ) { return _reportFailureToCreate ( p , e ) ; } p . setCurrentValue ( bean ) ; return _readBean ( r , p , bean ) ; } try { switch ( p . currentTokenId ( ) ) { case JsonTokenId . ID_NULL : return null ; case JsonTokenId . ID_STRING : return create ( p . getText ( ) ) ; case JsonTokenId . ID_NUMBER_INT : return create ( p . getLongValue ( ) ) ; default : } } catch ( Exception e ) { return _reportFailureToCreate ( p , e ) ; } throw JSONObjectException . from ( p , "Can not create a %s instance out of %s" , _type . getName ( ) , _tokenDesc ( p ) ) ; }
Method used for deserialization ; will read an instance of the bean type using given parser .
1,563
@ SuppressWarnings ( "unchecked" ) public < T > T readBean ( Class < T > type ) throws IOException { ValueReader vr = _readerLocator . findReader ( type ) ; return ( T ) vr . read ( this , _parser ) ; }
Method for reading a JSON Object from input and building a Bean of specified type out of it ; Bean has to conform to standard Java Bean specification by having setters for passing JSON Object properties .
1,564
protected Object unknownVariable ( JexlException xjexl ) { if ( ! silent ) { logger . trace ( xjexl . getMessage ( ) ) ; } return null ; }
Triggered when variable can not be resolved .
1,565
public boolean toBoolean ( Object val ) { if ( val == null ) { controlNullOperand ( ) ; return false ; } else if ( val instanceof Boolean ) { return ( Boolean ) val ; } else if ( val instanceof Number ) { double number = toDouble ( val ) ; return ! Double . isNaN ( number ) && number != 0.d ; } else if ( val instanceof String ) { String strval = val . toString ( ) ; return strval . length ( ) > 0 && ! "false" . equals ( strval ) ; } else if ( val instanceof Collection ) { return CollectionUtils . isNotEmpty ( ( Collection ) val ) ; } return true ; }
using the original implementation added check for empty lists defaulting to true
1,566
@ SuppressWarnings ( "deprecation" ) public JexlPropertyGet getPropertyGet ( Object obj , Object identifier , JexlInfo info ) { JexlPropertyGet get = getJadeGetExecutor ( obj , identifier ) ; if ( get == null && obj != null && identifier != null ) { get = getIndexedGet ( obj , identifier . toString ( ) ) ; if ( get == null ) { Field field = getField ( obj , identifier . toString ( ) , info ) ; if ( field != null ) { return new FieldPropertyGet ( field ) ; } } } return get ; }
Overwriting method to replace getGetExecutor call with getJadeGetExecutor
1,567
public final AbstractExecutor . Get getJadeGetExecutor ( Object obj , Object identifier ) { final Class < ? > claz = obj . getClass ( ) ; final String property = toString ( identifier ) ; AbstractExecutor . Get executor ; executor = new MapGetExecutor ( this , claz , identifier ) ; if ( executor . isAlive ( ) ) { return executor ; } if ( property != null ) { executor = new PropertyGetExecutor ( this , claz , property ) ; if ( executor . isAlive ( ) ) { return executor ; } executor = new BooleanGetExecutor ( this , claz , property ) ; if ( executor . isAlive ( ) ) { return executor ; } } Integer index = toInteger ( identifier ) ; if ( index != null ) { executor = new ListGetExecutor ( this , claz , index ) ; if ( executor . isAlive ( ) ) { return executor ; } } executor = new DuckGetExecutor ( this , claz , identifier ) ; if ( executor . isAlive ( ) ) { return executor ; } executor = new DuckGetExecutor ( this , claz , property ) ; if ( executor . isAlive ( ) ) { return executor ; } return null ; }
Identical to getGetExecutor but does check for map first . Mainly to avoid problems with class properties .
1,568
public ICloudSpannerConnection getConnection ( ) throws SQLException { if ( con == null ) { SQLException sqlException = new CloudSpannerSQLException ( "This PooledConnection has already been closed." , Code . FAILED_PRECONDITION ) ; fireConnectionFatalError ( sqlException ) ; throw sqlException ; } try { if ( last != null ) { last . close ( ) ; if ( ! con . getAutoCommit ( ) ) { rollbackAndIgnoreException ( ) ; } con . clearWarnings ( ) ; } if ( ! isXA ) { con . setAutoCommit ( autoCommit ) ; } } catch ( SQLException sqlException ) { fireConnectionFatalError ( sqlException ) ; throw ( SQLException ) sqlException . fillInStackTrace ( ) ; } ConnectionHandler handler = new ConnectionHandler ( con ) ; last = handler ; ICloudSpannerConnection proxyCon = ( ICloudSpannerConnection ) Proxy . newProxyInstance ( getClass ( ) . getClassLoader ( ) , new Class [ ] { Connection . class , ICloudSpannerConnection . class } , handler ) ; last . setProxy ( proxyCon ) ; return proxyCon ; }
Gets a handle for a client to use . This is a wrapper around the physical connection so the client can call close and it will just return the connection to the pool without really closing the physical connection .
1,569
void fireConnectionFatalError ( SQLException e ) { ConnectionEvent evt = null ; ConnectionEventListener [ ] local = listeners . toArray ( new ConnectionEventListener [ listeners . size ( ) ] ) ; for ( ConnectionEventListener listener : local ) { if ( evt == null ) { evt = createConnectionEvent ( e ) ; } listener . connectionErrorOccurred ( evt ) ; } }
Used to fire a connection error event to all listeners .
1,570
private void fireConnectionError ( SQLException e ) { Code code = Code . UNKNOWN ; if ( e instanceof CloudSpannerSQLException ) { code = ( ( CloudSpannerSQLException ) e ) . getCode ( ) ; } if ( ! isFatalState ( code ) ) { return ; } fireConnectionFatalError ( e ) ; }
Fires a connection error event but only if we think the exception is fatal .
1,571
public void visit ( Column column ) { String stringValue = column . getColumnName ( ) ; if ( stringValue . equalsIgnoreCase ( "true" ) || stringValue . equalsIgnoreCase ( "false" ) ) { setValue ( Boolean . valueOf ( stringValue ) , Types . BOOLEAN ) ; } }
Booleans are not recognized by the parser but are seen as column names .
1,572
protected String formatDDLStatement ( String sql ) { String result = removeComments ( sql ) ; String [ ] parts = getTokens ( sql , 0 ) ; if ( parts . length > 2 && parts [ 0 ] . equalsIgnoreCase ( "create" ) && parts [ 1 ] . equalsIgnoreCase ( "table" ) ) { String sqlWithSingleSpaces = String . join ( " " , parts ) ; int primaryKeyIndex = sqlWithSingleSpaces . toUpperCase ( ) . indexOf ( ", PRIMARY KEY (" ) ; if ( primaryKeyIndex > - 1 ) { int endPrimaryKeyIndex = sqlWithSingleSpaces . indexOf ( ')' , primaryKeyIndex ) ; String primaryKeySpec = sqlWithSingleSpaces . substring ( primaryKeyIndex + 2 , endPrimaryKeyIndex + 1 ) ; sqlWithSingleSpaces = sqlWithSingleSpaces . replace ( ", " + primaryKeySpec , "" ) ; sqlWithSingleSpaces = sqlWithSingleSpaces + " " + primaryKeySpec ; result = sqlWithSingleSpaces . replaceAll ( "\\s+\\)" , ")" ) ; } } return result ; }
Does some formatting to DDL statements that might have been generated by standard SQL generators to make it compatible with Google Cloud Spanner . We also need to get rid of any comments as Google Cloud Spanner does not accept comments in DDL - statements .
1,573
protected boolean isDDLStatement ( String [ ] sqlTokens ) { if ( sqlTokens . length > 0 ) { for ( String statement : DDL_STATEMENTS ) { if ( sqlTokens [ 0 ] . equalsIgnoreCase ( statement ) ) return true ; } } return false ; }
Do a quick check if this SQL statement is a DDL statement
1,574
protected String [ ] getTokens ( String sql , int limit ) { String result = removeComments ( sql ) ; String generated = result . replaceFirst ( "=" , " = " ) ; return generated . split ( "\\s+" , limit ) ; }
Remove comments from the given sql string and split it into parts based on all space characters
1,575
protected CustomDriverStatement getCustomDriverStatement ( String [ ] sqlTokens ) { if ( sqlTokens . length > 0 ) { for ( CustomDriverStatement statement : customDriverStatements ) { if ( sqlTokens [ 0 ] . equalsIgnoreCase ( statement . statement ) ) { return statement ; } } } return null ; }
Checks if a sql statement is a custom statement only recognized by this driver
1,576
public int setDynamicConnectionProperty ( String propertyName , String propertyValue ) throws SQLException { return getPropertySetter ( propertyName ) . apply ( Boolean . valueOf ( propertyValue ) ) ; }
Set a dynamic connection property such as AsyncDdlOperations
1,577
public int resetDynamicConnectionProperty ( String propertyName ) throws SQLException { return getPropertySetter ( propertyName ) . apply ( getOriginalValueGetter ( propertyName ) . get ( ) ) ; }
Reset a dynamic connection property to its original value such as AsyncDdlOperations
1,578
private ResultSet getVersionColumnsOrBestRowIdentifier ( ) throws SQLException { String sql = VERSION_AND_IDENTIFIER_COLUMNS_SELECT_STATEMENT + FROM_STATEMENT_WITHOUT_RESULTS ; CloudSpannerPreparedStatement statement = prepareStatement ( sql ) ; return statement . executeQuery ( ) ; }
A simple private method that combines the result of two methods that return exactly the same result
1,579
public CloudSpannerConnection connect ( String url , Properties info ) throws SQLException { if ( ! acceptsURL ( url ) ) return null ; ConnectionProperties properties = ConnectionProperties . parse ( url ) ; properties . setAdditionalConnectionProperties ( info ) ; CloudSpannerDatabaseSpecification database = new CloudSpannerDatabaseSpecification ( properties . project , properties . instance , properties . database ) ; CloudSpannerConnection connection = new CloudSpannerConnection ( this , url , database , properties . keyFile , properties . oauthToken , info , properties . useCustomHost ) ; connection . setSimulateProductName ( properties . productName ) ; connection . setSimulateMajorVersion ( properties . majorVersion ) ; connection . setSimulateMinorVersion ( properties . minorVersion ) ; connection . setAllowExtendedMode ( properties . allowExtendedMode ) ; connection . setOriginalAllowExtendedMode ( properties . allowExtendedMode ) ; connection . setAsyncDdlOperations ( properties . asyncDdlOperations ) ; connection . setOriginalAsyncDdlOperations ( properties . asyncDdlOperations ) ; connection . setAutoBatchDdlOperations ( properties . autoBatchDdlOperations ) ; connection . setOriginalAutoBatchDdlOperations ( properties . autoBatchDdlOperations ) ; connection . setReportDefaultSchemaAsNull ( properties . reportDefaultSchemaAsNull ) ; connection . setOriginalReportDefaultSchemaAsNull ( properties . reportDefaultSchemaAsNull ) ; connection . setBatchReadOnly ( properties . batchReadOnlyMode ) ; connection . setOriginalBatchReadOnly ( properties . batchReadOnlyMode ) ; connection . setUseCustomHost ( properties . useCustomHost ) ; registerConnection ( connection ) ; return connection ; }
Connects to a Google Cloud Spanner database .
1,580
public synchronized void closeSpanner ( ) { try { for ( Entry < Spanner , List < CloudSpannerConnection > > entry : connections . entrySet ( ) ) { List < CloudSpannerConnection > list = entry . getValue ( ) ; for ( CloudSpannerConnection con : list ) { if ( ! con . isClosed ( ) ) { con . rollback ( ) ; con . markClosed ( ) ; } } entry . getKey ( ) . close ( ) ; } connections . clear ( ) ; spanners . clear ( ) ; } catch ( SQLException e ) { throw SpannerExceptionFactory . newSpannerException ( e ) ; } }
Closes all connections to Google Cloud Spanner that have been opened by this driver during the lifetime of this application . You should call this method when you want to shutdown your application as this frees up all connections and sessions to Google Cloud Spanner . Failure to do so will keep sessions open server side and can eventually lead to resource exhaustion . Any open JDBC connection to Cloud Spanner opened by this driver will also be closed by this method . This method is also called automatically in a shutdown hook when the JVM is stopped orderly .
1,581
private View inflateHeader ( ) { if ( getRootView ( ) != null ) { if ( header == null ) { LayoutInflater layoutInflater = LayoutInflater . from ( getContext ( ) ) ; header = ( ViewGroup ) layoutInflater . inflate ( R . layout . material_dialog_header , getRootView ( ) , false ) ; headerBackgroundImageView = header . findViewById ( R . id . header_background_image_view ) ; headerContentContainer = header . findViewById ( R . id . header_content_container ) ; headerDivider = header . findViewById ( R . id . header_divider ) ; } headerContentContainer . removeAllViews ( ) ; if ( customHeaderView != null ) { headerContentContainer . addView ( customHeaderView ) ; } else if ( customHeaderViewId != - 1 ) { LayoutInflater layoutInflater = LayoutInflater . from ( getContext ( ) ) ; View view = layoutInflater . inflate ( customHeaderViewId , headerContentContainer , false ) ; headerContentContainer . addView ( view ) ; } else { LayoutInflater layoutInflater = LayoutInflater . from ( getContext ( ) ) ; View view = layoutInflater . inflate ( R . layout . header_icon_image_view , headerContentContainer , false ) ; headerContentContainer . addView ( view ) ; } View iconView = headerContentContainer . findViewById ( android . R . id . icon ) ; headerIconImageView = iconView instanceof ImageView ? ( ImageView ) iconView : null ; return header ; } return null ; }
Inflates the dialog s header .
1,582
private void adaptHeaderVisibility ( ) { if ( header != null ) { if ( showHeader ) { header . setVisibility ( View . VISIBLE ) ; notifyOnAreaShown ( Area . HEADER ) ; } else { header . setVisibility ( View . GONE ) ; notifyOnAreaHidden ( Area . HEADER ) ; } } }
Adapts the visibility of the dialog s header .
1,583
private void adaptHeaderHeight ( ) { if ( header != null ) { ViewGroup . LayoutParams layoutParams = header . getLayoutParams ( ) ; layoutParams . height = headerHeight ; } }
Adapts the height of the dialog s header .
1,584
private void adaptHeaderBackground ( final BackgroundAnimation animation ) { if ( headerBackgroundImageView != null ) { Drawable newBackground = headerBackground ; if ( animation != null && newBackground != null ) { Drawable previousBackground = headerBackgroundImageView . getDrawable ( ) ; if ( previousBackground != null ) { if ( previousBackground instanceof AbstractTransitionDrawable ) { previousBackground = ( ( AbstractTransitionDrawable ) previousBackground ) . getDrawable ( 1 ) ; } if ( animation instanceof CircleTransitionAnimation ) { CircleTransitionAnimation circleTransitionAnimation = ( CircleTransitionAnimation ) animation ; CircleTransitionDrawable transition = new CircleTransitionDrawable ( new Drawable [ ] { previousBackground , newBackground } ) ; transition . setRadius ( circleTransitionAnimation . getRadius ( ) ) ; transition . setListener ( circleTransitionAnimation . getListener ( ) ) ; if ( circleTransitionAnimation . getX ( ) != null ) { transition . setX ( circleTransitionAnimation . getX ( ) ) ; } if ( circleTransitionAnimation . getY ( ) != null ) { transition . setY ( circleTransitionAnimation . getY ( ) ) ; } transition . startTransition ( circleTransitionAnimation . getDuration ( ) ) ; newBackground = transition ; } else if ( animation instanceof CrossFadeTransitionAnimation ) { CrossFadeTransitionDrawable transition = new CrossFadeTransitionDrawable ( new Drawable [ ] { previousBackground , newBackground } ) ; transition . setListener ( animation . getListener ( ) ) ; transition . startTransition ( animation . getDuration ( ) ) ; newBackground = transition ; } else { throw new RuntimeException ( "Unknown type of animation: " + animation . getClass ( ) . getSimpleName ( ) ) ; } } } headerBackgroundImageView . setImageDrawable ( newBackground ) ; } }
Adapts the background of the dialog s header .
1,585
private void adaptHeaderIcon ( final DrawableAnimation animation ) { if ( headerIconImageView != null ) { ImageViewCompat . setImageTintList ( headerIconImageView , headerIconTintList ) ; ImageViewCompat . setImageTintMode ( headerIconImageView , headerIconTintMode ) ; Drawable newIcon = headerIcon ; if ( animation != null && newIcon != null ) { Drawable previousIcon = headerIconImageView . getDrawable ( ) ; if ( previousIcon != null ) { if ( previousIcon instanceof AbstractTransitionDrawable ) { previousIcon = ( ( AbstractTransitionDrawable ) previousIcon ) . getDrawable ( 1 ) ; } if ( animation instanceof ScaleTransitionAnimation ) { ScaleTransitionDrawable transition = new ScaleTransitionDrawable ( new Drawable [ ] { previousIcon , newIcon } ) ; transition . setListener ( animation . getListener ( ) ) ; transition . startTransition ( animation . getDuration ( ) ) ; newIcon = transition ; } else if ( animation instanceof CircleTransitionAnimation ) { CircleTransitionAnimation circleTransitionAnimation = ( CircleTransitionAnimation ) animation ; CircleTransitionDrawable transition = new CircleTransitionDrawable ( new Drawable [ ] { previousIcon , newIcon } ) ; transition . setRadius ( circleTransitionAnimation . getRadius ( ) ) ; transition . setListener ( circleTransitionAnimation . getListener ( ) ) ; if ( circleTransitionAnimation . getX ( ) != null ) { transition . setX ( circleTransitionAnimation . getX ( ) ) ; } if ( circleTransitionAnimation . getY ( ) != null ) { transition . setY ( circleTransitionAnimation . getY ( ) ) ; } transition . startTransition ( circleTransitionAnimation . getDuration ( ) ) ; newIcon = transition ; } else if ( animation instanceof CrossFadeTransitionAnimation ) { CrossFadeTransitionDrawable transition = new CrossFadeTransitionDrawable ( new Drawable [ ] { previousIcon , newIcon } ) ; transition . setCrossFade ( true ) ; transition . setListener ( animation . getListener ( ) ) ; transition . startTransition ( animation . getDuration ( ) ) ; newIcon = transition ; } else { throw new RuntimeException ( "Unknown type of animation: " + animation . getClass ( ) . getSimpleName ( ) ) ; } } } headerIconImageView . setImageDrawable ( newIcon ) ; } }
Adapt s the icon of the dialog s header .
1,586
private void adaptHeaderDividerVisibility ( ) { if ( headerDivider != null ) { headerDivider . setVisibility ( showHeaderDivider ? View . VISIBLE : View . GONE ) ; } }
Adapts the visibility of the divider of the dialog s header .
1,587
public final Map < ViewType , View > attach ( final Window window , final View view , final Map < ViewType , View > areas , final ParamType param ) { Condition . INSTANCE . ensureNotNull ( window , "The window may not be null" ) ; Condition . INSTANCE . ensureNotNull ( view , "The view may not be null" ) ; this . window = window ; this . view = view ; this . dialogRootView = view . findViewById ( R . id . dialog_root_view ) ; return onAttach ( window , view , areas , param ) ; }
Attaches the decorator to the view hierarchy . This enables the decorator to modify the view hierarchy until it is detached .
1,588
public final void addAreaListener ( final AreaListener listener ) { Condition . INSTANCE . ensureNotNull ( listener , "The listener may not be null" ) ; this . areaListeners . add ( listener ) ; }
Adds a new listener which should be notified when an area is modified by the dialog .
1,589
public final void removeAreaListener ( final AreaListener listener ) { Condition . INSTANCE . ensureNotNull ( listener , "The listener may not be null" ) ; this . areaListeners . remove ( listener ) ; }
Removes a specific listener which should not be notified when an area is modified by the decorator anymore .
1,590
protected final void notifyOnAreaShown ( final Area area ) { for ( AreaListener listener : areaListeners ) { listener . onAreaShown ( area ) ; } }
Notifies the listeners which have been registered to be notified when the visibility of the dialog s areas has been changed about an area being shown .
1,591
protected final void notifyOnAreaHidden ( final Area area ) { for ( AreaListener listener : areaListeners ) { listener . onAreaHidden ( area ) ; } }
Notifies the listeners which have been registered to be notified when the visibility of the dialog s areas has been changed about an area being hidden .
1,592
private OnApplyWindowInsetsListener createWindowInsetsListener ( ) { return new OnApplyWindowInsetsListener ( ) { public WindowInsetsCompat onApplyWindowInsets ( final View v , final WindowInsetsCompat insets ) { systemWindowInsets = insets . hasSystemWindowInsets ( ) ? new Rect ( insets . getSystemWindowInsetLeft ( ) , insets . getSystemWindowInsetTop ( ) , insets . getSystemWindowInsetRight ( ) , insets . getSystemWindowInsetBottom ( ) ) : null ; adaptLayoutParams ( ) ; return insets ; } } ; }
Creates and returns a listener which allows to observe when window insets are applied to the root view of the view hierarchy which is modified by the decorator .
1,593
private RelativeLayout . LayoutParams createLayoutParams ( ) { Rect windowDimensions = new Rect ( ) ; Window window = getWindow ( ) ; assert window != null ; window . getDecorView ( ) . getWindowVisibleDisplayFrame ( windowDimensions ) ; int leftInset = isFitsSystemWindowsLeft ( ) && isFullscreen ( ) && systemWindowInsets != null ? systemWindowInsets . left : 0 ; int topInset = isFitsSystemWindowsTop ( ) && isFullscreen ( ) && systemWindowInsets != null ? systemWindowInsets . top : 0 ; int rightInset = isFitsSystemWindowsRight ( ) && isFullscreen ( ) && systemWindowInsets != null ? systemWindowInsets . right : 0 ; int bottomInset = isFitsSystemWindowsBottom ( ) && isFullscreen ( ) && systemWindowInsets != null ? systemWindowInsets . bottom : 0 ; int leftMargin = getLeftMargin ( ) - getWindowInsetLeft ( ) + leftInset ; int topMargin = getTopMargin ( ) - getWindowInsetTop ( ) + topInset ; int rightMargin = getRightMargin ( ) - getWindowInsetRight ( ) + rightInset ; int bottomMargin = getBottomMargin ( ) - getWindowInsetBottom ( ) + bottomInset ; int width = getLayoutDimension ( getWidth ( ) , leftMargin + rightMargin , windowDimensions . right ) ; int height = getLayoutDimension ( getHeight ( ) , topMargin + bottomMargin , windowDimensions . bottom ) ; RelativeLayout . LayoutParams layoutParams = new RelativeLayout . LayoutParams ( width , height ) ; layoutParams . leftMargin = leftMargin ; layoutParams . topMargin = topMargin ; layoutParams . rightMargin = rightMargin ; layoutParams . bottomMargin = bottomMargin ; if ( ( getGravity ( ) & Gravity . CENTER_HORIZONTAL ) == Gravity . CENTER_HORIZONTAL ) { layoutParams . addRule ( RelativeLayout . CENTER_HORIZONTAL , RelativeLayout . TRUE ) ; } if ( ( getGravity ( ) & Gravity . CENTER_VERTICAL ) == Gravity . CENTER_VERTICAL ) { layoutParams . addRule ( RelativeLayout . CENTER_VERTICAL , RelativeLayout . TRUE ) ; } if ( ( getGravity ( ) & Gravity . LEFT ) == Gravity . LEFT ) { layoutParams . addRule ( RelativeLayout . ALIGN_PARENT_LEFT , RelativeLayout . TRUE ) ; } if ( ( getGravity ( ) & Gravity . TOP ) == Gravity . TOP ) { layoutParams . addRule ( RelativeLayout . ALIGN_PARENT_TOP , RelativeLayout . TRUE ) ; } if ( ( getGravity ( ) & Gravity . RIGHT ) == Gravity . RIGHT ) { layoutParams . addRule ( RelativeLayout . ALIGN_PARENT_RIGHT , RelativeLayout . TRUE ) ; } if ( ( getGravity ( ) & Gravity . BOTTOM ) == Gravity . BOTTOM ) { layoutParams . addRule ( RelativeLayout . ALIGN_PARENT_BOTTOM , RelativeLayout . TRUE ) ; } return layoutParams ; }
Creates and returns the layout params which should be used by the dialog s root view .
1,594
private View inflateTitleView ( ) { if ( getRootView ( ) != null ) { inflateTitleContainer ( ) ; if ( customTitleView != null ) { titleContainer . addView ( customTitleView ) ; } else if ( customTitleViewId != - 1 ) { LayoutInflater layoutInflater = LayoutInflater . from ( getContext ( ) ) ; View view = layoutInflater . inflate ( customTitleViewId , titleContainer , false ) ; titleContainer . addView ( view ) ; } else { LayoutInflater layoutInflater = LayoutInflater . from ( getContext ( ) ) ; View view = layoutInflater . inflate ( R . layout . material_dialog_title , titleContainer , false ) ; titleContainer . addView ( view ) ; } View titleView = titleContainer . findViewById ( android . R . id . title ) ; titleTextView = titleView instanceof TextView ? ( TextView ) titleView : null ; View iconView = titleContainer . findViewById ( android . R . id . icon ) ; iconImageView = iconView instanceof ImageView ? ( ImageView ) iconView : null ; return titleContainer ; } return null ; }
Inflates the view which is used to show the dialog s title . The view may either be the default one or a custom view if one has been set before .
1,595
private void inflateTitleContainer ( ) { if ( titleContainer == null ) { titleContainer = new RelativeLayout ( getContext ( ) ) ; titleContainer . setId ( R . id . title_container ) ; titleContainer . setLayoutParams ( new ViewGroup . LayoutParams ( ViewGroup . LayoutParams . MATCH_PARENT , ViewGroup . LayoutParams . WRAP_CONTENT ) ) ; } else { titleContainer . removeAllViews ( ) ; } }
Inflates the container which contains the dialog s title if it is not yet inflated .
1,596
private View inflateMessageView ( ) { if ( getRootView ( ) != null ) { inflateMessageContainer ( ) ; if ( customMessageView != null ) { messageContainer . addView ( customMessageView ) ; } else if ( customMessageViewId != - 1 ) { LayoutInflater layoutInflater = LayoutInflater . from ( getContext ( ) ) ; View view = layoutInflater . inflate ( customMessageViewId , messageContainer , false ) ; messageContainer . addView ( view ) ; } else { LayoutInflater layoutInflater = LayoutInflater . from ( getContext ( ) ) ; View view = layoutInflater . inflate ( R . layout . material_dialog_message , messageContainer , false ) ; messageContainer . addView ( view ) ; } View messageView = messageContainer . findViewById ( android . R . id . message ) ; messageTextView = messageView instanceof TextView ? ( TextView ) messageView : null ; return messageContainer ; } return null ; }
Inflates the view which is used to show the dialog s message . The view may either be the default one or a custom view if one has been set before .
1,597
private void inflateMessageContainer ( ) { if ( messageContainer == null ) { messageContainer = new RelativeLayout ( getContext ( ) ) ; messageContainer . setId ( R . id . message_container ) ; messageContainer . setLayoutParams ( new ViewGroup . LayoutParams ( ViewGroup . LayoutParams . MATCH_PARENT , ViewGroup . LayoutParams . WRAP_CONTENT ) ) ; } else { messageContainer . removeAllViews ( ) ; } }
Inflates the container which contains the dialog s message if it is not yet inflated .
1,598
private View inflateContentView ( ) { if ( getRootView ( ) != null ) { inflateContentContainer ( ) ; if ( customView != null ) { contentContainer . addView ( customView ) ; } else if ( customViewId != - 1 ) { LayoutInflater layoutInflater = LayoutInflater . from ( getContext ( ) ) ; View view = layoutInflater . inflate ( customViewId , contentContainer , false ) ; contentContainer . addView ( view ) ; } adaptContentContainerVisibility ( ) ; return contentContainer ; } return null ; }
Inflates the view which is used to show the dialog s content . The view may either be the default one or a custom view if one has been set before .
1,599
private void inflateContentContainer ( ) { if ( contentContainer == null ) { contentContainer = new RelativeLayout ( getContext ( ) ) ; contentContainer . setId ( R . id . content_container ) ; LinearLayout . LayoutParams layoutParams = new LinearLayout . LayoutParams ( LinearLayout . LayoutParams . MATCH_PARENT , 0 ) ; layoutParams . weight = 1 ; contentContainer . setLayoutParams ( layoutParams ) ; } else { contentContainer . removeAllViews ( ) ; } }
Inflates the container which contains the dialog s content if it is not yet inflated .