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 || messag...
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"...
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 , ...
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 . removeAt...
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 ) { ...
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 ) { ...
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 ; DataSour...
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 . ...
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 ( ) ) ; jdbcTemplat...
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 ...
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 ...
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 ( row...
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 ) ...
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 ( ) ) ; } ...
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 , actio...
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...
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 ...
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 res...
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 ...
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 > ...
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 ...
Delete entities from entity group .
1,554
public ClientConfiguration createClientConfiguration ( ) { return ClientConfiguration . builder ( buildTimeSeriesUrl ( ) , username , password ) . connectTimeoutMillis ( connectTimeoutMillis ) . readTimeoutMillis ( readTimeoutMillis ) . pingTimeoutMillis ( pingTimeoutMillis ) . ignoreSSLErrors ( ignoreSSLErrors ) . ski...
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 (...
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_REA...
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 . ...
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...
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 == ...
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 ( ) ) { retur...
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 != n...
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 . conn...
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 ) ; i...
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 Cloud...
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...
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 sid...
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 . fi...
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 != n...
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 != ...
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 . windo...
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 ( ) ...
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 ( ) && systemWindowIns...
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 ...
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 . W...
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 = lay...
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 . Layo...
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...
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 ) ...
Inflates the container which contains the dialog s content if it is not yet inflated .