idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
32,200
public static ConnectionException ToConnectionPoolException ( Throwable e ) { if ( e instanceof ConnectionException ) { return ( ConnectionException ) e ; } LOGGER . debug ( e . getMessage ( ) ) ; if ( e instanceof InvalidRequestException ) { return new com . netflix . astyanax . connectionpool . exceptions . BadRequestException ( e ) ; } else if ( e instanceof TProtocolException ) { return new com . netflix . astyanax . connectionpool . exceptions . BadRequestException ( e ) ; } else if ( e instanceof UnavailableException ) { return new TokenRangeOfflineException ( e ) ; } else if ( e instanceof SocketTimeoutException ) { return new TimeoutException ( e ) ; } else if ( e instanceof TimedOutException ) { return new OperationTimeoutException ( e ) ; } else if ( e instanceof NotFoundException ) { return new com . netflix . astyanax . connectionpool . exceptions . NotFoundException ( e ) ; } else if ( e instanceof TApplicationException ) { return new ThriftStateException ( e ) ; } else if ( e instanceof AuthenticationException || e instanceof AuthorizationException ) { return new com . netflix . astyanax . connectionpool . exceptions . AuthenticationException ( e ) ; } else if ( e instanceof SchemaDisagreementException ) { return new com . netflix . astyanax . connectionpool . exceptions . SchemaDisagreementException ( e ) ; } else if ( e instanceof TTransportException ) { if ( e . getCause ( ) != null ) { if ( e . getCause ( ) instanceof SocketTimeoutException ) { return new TimeoutException ( e ) ; } if ( e . getCause ( ) . getMessage ( ) != null ) { if ( e . getCause ( ) . getMessage ( ) . toLowerCase ( ) . contains ( "connection abort" ) || e . getCause ( ) . getMessage ( ) . toLowerCase ( ) . contains ( "connection reset" ) ) { return new ConnectionAbortedException ( e ) ; } } } return new TransportException ( e ) ; } else { return new UnknownException ( e ) ; } }
Convert from Thrift exceptions to an internal ConnectionPoolException
32,201
public Connection < CL > borrowConnection ( int timeout ) throws ConnectionException { Connection < CL > connection = null ; long startTime = System . currentTimeMillis ( ) ; try { connection = availableConnections . poll ( ) ; if ( connection != null ) { return connection ; } boolean isOpenning = tryOpenAsync ( ) ; if ( timeout > 0 ) { connection = waitForConnection ( isOpenning ? config . getConnectTimeout ( ) : timeout ) ; return connection ; } else throw new PoolTimeoutException ( "Fast fail waiting for connection from pool" ) . setHost ( getHost ( ) ) . setLatency ( System . currentTimeMillis ( ) - startTime ) ; } finally { if ( connection != null ) { borrowedCount . incrementAndGet ( ) ; monitor . incConnectionBorrowed ( host , System . currentTimeMillis ( ) - startTime ) ; } } }
Create a connection as long the max hasn t been reached
32,202
private Connection < CL > waitForConnection ( int timeout ) throws ConnectionException { Connection < CL > connection = null ; long startTime = System . currentTimeMillis ( ) ; try { blockedThreads . incrementAndGet ( ) ; connection = availableConnections . poll ( timeout , TimeUnit . MILLISECONDS ) ; if ( connection != null ) return connection ; throw new PoolTimeoutException ( "Timed out waiting for connection" ) . setHost ( getHost ( ) ) . setLatency ( System . currentTimeMillis ( ) - startTime ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; throw new InterruptedOperationException ( "Thread interrupted waiting for connection" ) . setHost ( getHost ( ) ) . setLatency ( System . currentTimeMillis ( ) - startTime ) ; } finally { blockedThreads . decrementAndGet ( ) ; } }
Internal method to wait for a connection from the available connection pool .
32,203
public boolean returnConnection ( Connection < CL > connection ) { returnedCount . incrementAndGet ( ) ; monitor . incConnectionReturned ( host ) ; ConnectionException ce = connection . getLastException ( ) ; if ( ce != null ) { if ( ce instanceof IsDeadConnectionException ) { noteError ( ce ) ; internalCloseConnection ( connection ) ; return true ; } } errorsSinceLastSuccess . set ( 0 ) ; if ( activeCount . get ( ) <= config . getMaxConnsPerHost ( ) ) { availableConnections . add ( connection ) ; if ( isShutdown ( ) ) { discardIdleConnections ( ) ; return true ; } } else { internalCloseConnection ( connection ) ; return true ; } return false ; }
Return a connection to this host
32,204
public void markAsDown ( ConnectionException reason ) { if ( isReconnecting . compareAndSet ( false , true ) ) { markedDownCount . incrementAndGet ( ) ; if ( reason != null && ! ( reason instanceof TimeoutException ) ) { discardIdleConnections ( ) ; } listener . onHostDown ( this ) ; monitor . onHostDown ( getHost ( ) , reason ) ; retryContext . begin ( ) ; try { long delay = retryContext . getNextDelay ( ) ; executor . schedule ( new Runnable ( ) { public void run ( ) { Thread . currentThread ( ) . setName ( "RetryService : " + host . getName ( ) ) ; try { if ( activeCount . get ( ) == 0 ) reconnect ( ) ; try { retryContext . success ( ) ; if ( isReconnecting . compareAndSet ( true , false ) ) { monitor . onHostReactivated ( host , SimpleHostConnectionPool . this ) ; listener . onHostUp ( SimpleHostConnectionPool . this ) ; } } catch ( Throwable t ) { LOG . error ( "Error reconnecting client" , t ) ; } return ; } catch ( Throwable t ) { } if ( ! isShutdown ( ) ) { long delay = retryContext . getNextDelay ( ) ; executor . schedule ( this , delay , TimeUnit . MILLISECONDS ) ; } } } , delay , TimeUnit . MILLISECONDS ) ; } catch ( Exception e ) { LOG . error ( "Failed to schedule retry task for " + host . getHostName ( ) , e ) ; } } }
Mark the host as down . No new connections will be created from this host . Connections currently in use will be allowed to continue processing .
32,205
private boolean tryOpenAsync ( ) { Connection < CL > connection = null ; if ( activeCount . get ( ) < config . getMaxConnsPerHost ( ) ) { try { if ( activeCount . incrementAndGet ( ) <= config . getMaxConnsPerHost ( ) ) { if ( pendingConnections . incrementAndGet ( ) > config . getMaxPendingConnectionsPerHost ( ) ) { pendingConnections . decrementAndGet ( ) ; } else { try { connectAttempt . incrementAndGet ( ) ; connection = factory . createConnection ( this ) ; connection . openAsync ( new Connection . AsyncOpenCallback < CL > ( ) { public void success ( Connection < CL > connection ) { openConnections . incrementAndGet ( ) ; pendingConnections . decrementAndGet ( ) ; availableConnections . add ( connection ) ; if ( isShutdown ( ) ) { discardIdleConnections ( ) ; } } public void failure ( Connection < CL > conn , ConnectionException e ) { failedOpenConnections . incrementAndGet ( ) ; pendingConnections . decrementAndGet ( ) ; activeCount . decrementAndGet ( ) ; if ( e instanceof IsDeadConnectionException ) { noteError ( e ) ; } } } ) ; return true ; } catch ( ThrottledException e ) { } finally { if ( connection == null ) pendingConnections . decrementAndGet ( ) ; } } } } finally { if ( connection == null ) { activeCount . decrementAndGet ( ) ; } } } return false ; }
Try to open a new connection asynchronously . We don t actually return a connection here . Instead the connection will be added to idle queue when it s ready .
32,206
private void discardIdleConnections ( ) { List < Connection < CL > > connections = Lists . newArrayList ( ) ; availableConnections . drainTo ( connections ) ; activeCount . addAndGet ( - connections . size ( ) ) ; for ( Connection < CL > connection : connections ) { try { closedConnections . incrementAndGet ( ) ; connection . close ( ) ; } catch ( Throwable t ) { } } }
Drain all idle connections and close them . Connections that are currently borrowed will not be closed here .
32,207
public void fillMutationBatch ( ColumnListMutation < ByteBuffer > clm , Object entity ) throws IllegalArgumentException , IllegalAccessException { List < ? > list = ( List < ? > ) containerField . get ( entity ) ; if ( list != null ) { for ( Object element : list ) { fillColumnMutation ( clm , element ) ; } } }
Iterate through the list and create a column for each element
32,208
public void fillColumnMutation ( ColumnListMutation < ByteBuffer > clm , Object entity ) { try { ByteBuffer columnName = toColumnName ( entity ) ; ByteBuffer value = valueMapper . toByteBuffer ( entity ) ; clm . putColumn ( columnName , value ) ; } catch ( Exception e ) { throw new PersistenceException ( "failed to fill mutation batch" , e ) ; } }
Add a column based on the provided entity
32,209
public boolean setField ( Object entity , ColumnList < ByteBuffer > columns ) throws Exception { List < Object > list = getOrCreateField ( entity ) ; for ( com . netflix . astyanax . model . Column < ByteBuffer > c : columns ) { list . add ( fromColumn ( c ) ) ; } return true ; }
Set the collection field using the provided column list of embedded entities
32,210
public List < ByteBuffer > getBufferList ( ) { List < ByteBuffer > result = buffers ; reset ( ) ; for ( ByteBuffer buffer : result ) { buffer . flip ( ) ; } return result ; }
Returns all data written and resets the stream to be empty .
32,211
public void prepend ( List < ByteBuffer > lists ) { for ( ByteBuffer buffer : lists ) { buffer . position ( buffer . limit ( ) ) ; } buffers . addAll ( 0 , lists ) ; }
Prepend a list of ByteBuffers to this stream .
32,212
public < C2 > ColumnPath < C > append ( C2 name , Serializer < C2 > ser ) { path . add ( ByteBuffer . wrap ( ser . toBytes ( name ) ) ) ; return this ; }
Add a depth to the path
32,213
public static java . util . UUID getUniqueTimeUUIDinMillis ( ) { return new java . util . UUID ( UUIDGen . newTime ( ) , UUIDGen . getClockSeqAndNode ( ) ) ; }
Gets a new and unique time uuid in milliseconds . It is useful to use in a TimeUUIDType sorted column family .
32,214
public static ByteBuffer asByteBuffer ( java . util . UUID uuid ) { if ( uuid == null ) { return null ; } return ByteBuffer . wrap ( asByteArray ( uuid ) ) ; }
Coverts a java . util . UUID into a ByteBuffer .
32,215
public static UUID uuid ( ByteBuffer bb ) { bb = bb . slice ( ) ; return new UUID ( bb . getLong ( ) , bb . getLong ( ) ) ; }
Converts a ByteBuffer containing a UUID into a java . util . UUID
32,216
private ByteBuffer toColumnName ( Object obj ) { SimpleCompositeBuilder composite = new SimpleCompositeBuilder ( bufferSize , Equality . EQUAL ) ; for ( FieldMapper < ? > mapper : components ) { try { composite . addWithoutControl ( mapper . toByteBuffer ( obj ) ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } return composite . get ( ) ; }
Return the column name byte buffer for this entity
32,217
T constructEntity ( K id , com . netflix . astyanax . model . Column < ByteBuffer > column ) { try { T entity = clazz . newInstance ( ) ; idMapper . setValue ( entity , id ) ; setEntityFieldsFromColumnName ( entity , column . getRawName ( ) . duplicate ( ) ) ; valueMapper . setField ( entity , column . getByteBufferValue ( ) . duplicate ( ) ) ; return entity ; } catch ( Exception e ) { throw new PersistenceException ( "failed to construct entity" , e ) ; } }
Construct an entity object from a row key and column list .
32,218
Object fromColumn ( K id , com . netflix . astyanax . model . Column < ByteBuffer > c ) { try { Object entity = clazz . newInstance ( ) ; idMapper . setValue ( entity , id ) ; setEntityFieldsFromColumnName ( entity , c . getRawName ( ) . duplicate ( ) ) ; valueMapper . setField ( entity , c . getByteBufferValue ( ) . duplicate ( ) ) ; return entity ; } catch ( Exception e ) { throw new PersistenceException ( "failed to construct entity" , e ) ; } }
Return an object from the column
32,219
public String getComparatorType ( ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "CompositeType(" ) ; sb . append ( StringUtils . join ( Collections2 . transform ( components , new Function < FieldMapper < ? > , String > ( ) { public String apply ( FieldMapper < ? > input ) { return input . serializer . getComparatorType ( ) . getTypeName ( ) ; } } ) , "," ) ) ; sb . append ( ")" ) ; return sb . toString ( ) ; }
Return the cassandra comparator type for this composite structure
32,220
public ByteBuffer readData ( ) throws Exception { ColumnList < C > result = keyspace . prepareQuery ( columnFamily ) . setConsistencyLevel ( consistencyLevel ) . getKey ( key ) . execute ( ) . getResult ( ) ; boolean hasColumn = false ; ByteBuffer data = null ; for ( Column < C > column : result ) { if ( column . getTtl ( ) == 0 ) { if ( hasColumn ) { throw new IllegalStateException ( "Row has multiple uniquneness locks" ) ; } hasColumn = true ; data = column . getByteBufferValue ( ) ; } } if ( ! hasColumn ) { throw new NotFoundException ( this . key . toString ( ) + " has no uniquness lock" ) ; } return data ; }
Read the data stored with the unique row . This data is normally a foreign key to another column family .
32,221
public static < T > Callable < T > decorateWithBarrier ( CyclicBarrier barrier , Callable < T > callable ) { return new BarrierCallableDecorator < T > ( barrier , callable ) ; }
Create a callable that waits on a barrier before starting execution
32,222
private synchronized < R > OperationResult < R > executeDdlOperation ( AbstractOperationImpl < R > operation , RetryPolicy retry ) throws OperationException , ConnectionException { ConnectionException lastException = null ; for ( int i = 0 ; i < 2 ; i ++ ) { operation . setPinnedHost ( ddlHost ) ; try { OperationResult < R > result = connectionPool . executeWithFailover ( operation , retry ) ; ddlHost = result . getHost ( ) ; return result ; } catch ( ConnectionException e ) { lastException = e ; if ( e instanceof IsDeadConnectionException ) { ddlHost = null ; } } } throw lastException ; }
Attempt to execute the DDL operation on the same host
32,223
private void precheckSchemaAgreement ( Client client ) throws Exception { Map < String , List < String > > schemas = client . describe_schema_versions ( ) ; if ( schemas . size ( ) > 1 ) { throw new SchemaDisagreementException ( "Can't change schema due to pending schema agreement" ) ; } }
Do a quick check to see if there is a schema disagreement . This is done as an extra precaution to reduce the chances of putting the cluster into a bad state . This will not gurantee however that by the time a schema change is made the cluster will be in the same state .
32,224
private ThriftColumnFamilyDefinitionImpl toThriftColumnFamilyDefinition ( Map < String , Object > options , ColumnFamily columnFamily ) { ThriftColumnFamilyDefinitionImpl def = new ThriftColumnFamilyDefinitionImpl ( ) ; Map < String , Object > internalOptions = Maps . newHashMap ( ) ; if ( options != null ) internalOptions . putAll ( options ) ; internalOptions . put ( "keyspace" , getKeyspaceName ( ) ) ; if ( columnFamily != null ) { internalOptions . put ( "name" , columnFamily . getName ( ) ) ; if ( ! internalOptions . containsKey ( "comparator_type" ) ) internalOptions . put ( "comparator_type" , columnFamily . getColumnSerializer ( ) . getComparatorType ( ) . getTypeName ( ) ) ; if ( ! internalOptions . containsKey ( "key_validation_class" ) ) internalOptions . put ( "key_validation_class" , columnFamily . getKeySerializer ( ) . getComparatorType ( ) . getTypeName ( ) ) ; if ( columnFamily . getDefaultValueSerializer ( ) != null && ! internalOptions . containsKey ( "default_validation_class" ) ) internalOptions . put ( "default_validation_class" , columnFamily . getDefaultValueSerializer ( ) . getComparatorType ( ) . getTypeName ( ) ) ; } def . setFields ( internalOptions ) ; return def ; }
Convert a Map of options to an internal thrift column family definition
32,225
private ThriftKeyspaceDefinitionImpl toThriftKeyspaceDefinition ( final Map < String , Object > options ) { ThriftKeyspaceDefinitionImpl def = new ThriftKeyspaceDefinitionImpl ( ) ; Map < String , Object > internalOptions = Maps . newHashMap ( ) ; if ( options != null ) internalOptions . putAll ( options ) ; if ( internalOptions . containsKey ( "name" ) && ! internalOptions . get ( "name" ) . equals ( getKeyspaceName ( ) ) ) { throw new RuntimeException ( String . format ( "'name' attribute must match keyspace name. Expected '%s' but got '%s'" , getKeyspaceName ( ) , internalOptions . get ( "name" ) ) ) ; } else { internalOptions . put ( "name" , getKeyspaceName ( ) ) ; } def . setFields ( internalOptions ) ; return def ; }
Convert a Map of options to an internal thrift keyspace definition
32,226
private List < Future < Boolean > > startTasks ( ExecutorService executor , List < Callable < Boolean > > callables ) { List < Future < Boolean > > tasks = Lists . newArrayList ( ) ; for ( Callable < Boolean > callable : callables ) { tasks . add ( executor . submit ( callable ) ) ; } return tasks ; }
Submit all the callables to the executor by synchronize their execution so they all start AFTER the have all been submitted .
32,227
public < T , K > void remove ( ColumnFamily < K , String > columnFamily , T item ) throws Exception { @ SuppressWarnings ( { "unchecked" } ) Class < T > clazz = ( Class < T > ) item . getClass ( ) ; Mapping < T > mapping = getMapping ( clazz ) ; @ SuppressWarnings ( { "unchecked" } ) Class < K > idFieldClass = ( Class < K > ) mapping . getIdFieldClass ( ) ; MutationBatch mutationBatch = keyspace . prepareMutationBatch ( ) ; mutationBatch . withRow ( columnFamily , mapping . getIdValue ( item , idFieldClass ) ) . delete ( ) ; mutationBatch . execute ( ) ; }
Remove the given item
32,228
public < T , K > List < T > getAll ( ColumnFamily < K , String > columnFamily , Class < T > itemClass ) throws Exception { Mapping < T > mapping = getMapping ( itemClass ) ; Rows < K , String > result = keyspace . prepareQuery ( columnFamily ) . getAllRows ( ) . execute ( ) . getResult ( ) ; return mapping . getAll ( result ) ; }
Get all rows of the specified item
32,229
public < T > Mapping < T > getMapping ( Class < T > clazz ) { return ( cache != null ) ? cache . getMapping ( clazz , annotationSet ) : new Mapping < T > ( clazz , annotationSet ) ; }
Return the mapping instance for the given class
32,230
public void start ( ) { ConnectionPoolMBeanManager . getInstance ( ) . registerMonitor ( config . getName ( ) , this ) ; String seeds = config . getSeeds ( ) ; if ( seeds != null && ! seeds . isEmpty ( ) ) { setHosts ( config . getSeedHosts ( ) ) ; } config . getLatencyScoreStrategy ( ) . start ( new Listener ( ) { public void onUpdate ( ) { rebuildPartitions ( ) ; } public void onReset ( ) { rebuildPartitions ( ) ; } } ) ; }
Starts the conn pool and resources associated with it
32,231
public void shutdown ( ) { ConnectionPoolMBeanManager . getInstance ( ) . unregisterMonitor ( config . getName ( ) , this ) ; for ( Entry < Host , HostConnectionPool < CL > > pool : hosts . entrySet ( ) ) { pool . getValue ( ) . shutdown ( ) ; } config . getLatencyScoreStrategy ( ) . shutdown ( ) ; config . shutdown ( ) ; }
Clean up resources associated with the conn pool
32,232
public final synchronized boolean addHost ( Host host , boolean refresh ) { if ( hosts . containsKey ( host ) ) { Host existingHost = hosts . get ( host ) . getHost ( ) ; if ( existingHost . getTokenRanges ( ) . size ( ) != host . getTokenRanges ( ) . size ( ) ) { existingHost . setTokenRanges ( host . getTokenRanges ( ) ) ; return true ; } ArrayList < TokenRange > currentTokens = Lists . newArrayList ( existingHost . getTokenRanges ( ) ) ; ArrayList < TokenRange > newTokens = Lists . newArrayList ( host . getTokenRanges ( ) ) ; Collections . sort ( currentTokens , compareByStartToken ) ; Collections . sort ( newTokens , compareByStartToken ) ; for ( int i = 0 ; i < currentTokens . size ( ) ; i ++ ) { if ( ! currentTokens . get ( i ) . getStartToken ( ) . equals ( newTokens . get ( i ) . getStartToken ( ) ) || ! currentTokens . get ( i ) . getEndToken ( ) . equals ( newTokens . get ( i ) . getEndToken ( ) ) ) { return false ; } } existingHost . setTokenRanges ( host . getTokenRanges ( ) ) ; return true ; } else { HostConnectionPool < CL > pool = newHostConnectionPool ( host , factory , config ) ; if ( null == hosts . putIfAbsent ( host , pool ) ) { try { monitor . onHostAdded ( host , pool ) ; if ( refresh ) { topology . addPool ( pool ) ; rebuildPartitions ( ) ; } pool . primeConnections ( config . getInitConnsPerHost ( ) ) ; } catch ( Exception e ) { } return true ; } else { return false ; } } }
Add host to the system . May need to rebuild the partition map of the system
32,233
public List < HostConnectionPool < CL > > getActivePools ( ) { return ImmutableList . copyOf ( topology . getAllPools ( ) . getPools ( ) ) ; }
list of all active pools
32,234
public synchronized boolean removeHost ( Host host , boolean refresh ) { HostConnectionPool < CL > pool = hosts . remove ( host ) ; if ( pool != null ) { topology . removePool ( pool ) ; rebuildPartitions ( ) ; monitor . onHostRemoved ( host ) ; pool . shutdown ( ) ; return true ; } else { return false ; } }
Remove host from the system . Shuts down pool associated with the host and rebuilds partition map
32,235
public < R > OperationResult < R > executeWithFailover ( Operation < CL , R > op , RetryPolicy retry ) throws ConnectionException { OperationTracer opsTracer = config . getOperationTracer ( ) ; final AstyanaxContext context = opsTracer . getAstyanaxContext ( ) ; if ( context != null ) { opsTracer . onCall ( context , op ) ; } retry . begin ( ) ; ConnectionException lastException = null ; do { try { OperationResult < R > result = newExecuteWithFailover ( op ) . tryOperation ( op ) ; retry . success ( ) ; if ( context != null ) opsTracer . onSuccess ( context , op ) ; return result ; } catch ( OperationException e ) { if ( context != null ) opsTracer . onException ( context , op , e ) ; retry . failure ( e ) ; throw e ; } catch ( ConnectionException e ) { lastException = e ; } if ( retry . allowRetry ( ) ) { LOG . debug ( "Retry policy[" + retry . toString ( ) + "] will allow a subsequent retry for operation [" + op . getClass ( ) + "] on keyspace [" + op . getKeyspace ( ) + "] on pinned host[" + op . getPinnedHost ( ) + "]" ) ; } } while ( retry . allowRetry ( ) ) ; if ( context != null && lastException != null ) opsTracer . onException ( context , op , lastException ) ; retry . failure ( lastException ) ; throw lastException ; }
Executes the operation using failover and retry strategy
32,236
public BoundStatement getBoundStatement ( Q query , boolean useCaching ) { PreparedStatement pStatement = getPreparedStatement ( query , useCaching ) ; return bindValues ( pStatement , query ) ; }
Get the bound statement from the prepared statement
32,237
private Where addWhereClauseForRowRange ( String keyAlias , Select select , RowRange < ? > rowRange ) { Where where = null ; boolean keyIsPresent = false ; boolean tokenIsPresent = false ; if ( rowRange . getStartKey ( ) != null || rowRange . getEndKey ( ) != null ) { keyIsPresent = true ; } if ( rowRange . getStartToken ( ) != null || rowRange . getEndToken ( ) != null ) { tokenIsPresent = true ; } if ( keyIsPresent && tokenIsPresent ) { throw new RuntimeException ( "Cannot provide both token and keys for range query" ) ; } if ( keyIsPresent ) { if ( rowRange . getStartKey ( ) != null && rowRange . getEndKey ( ) != null ) { where = select . where ( gte ( keyAlias , BIND_MARKER ) ) . and ( lte ( keyAlias , BIND_MARKER ) ) ; } else if ( rowRange . getStartKey ( ) != null ) { where = select . where ( gte ( keyAlias , BIND_MARKER ) ) ; } else if ( rowRange . getEndKey ( ) != null ) { where = select . where ( lte ( keyAlias , BIND_MARKER ) ) ; } } else if ( tokenIsPresent ) { String tokenOfKey = "token(" + keyAlias + ")" ; if ( rowRange . getStartToken ( ) != null && rowRange . getEndToken ( ) != null ) { where = select . where ( gte ( tokenOfKey , BIND_MARKER ) ) . and ( lte ( tokenOfKey , BIND_MARKER ) ) ; } else if ( rowRange . getStartToken ( ) != null ) { where = select . where ( gte ( tokenOfKey , BIND_MARKER ) ) ; } else if ( rowRange . getEndToken ( ) != null ) { where = select . where ( lte ( tokenOfKey , BIND_MARKER ) ) ; } } else { where = select . where ( ) ; } if ( rowRange . getCount ( ) > 0 ) { } return where ; }
Private helper for constructing the where clause for row ranges
32,238
private void bindWhereClauseForRowRange ( List < Object > values , RowRange < ? > rowRange ) { boolean keyIsPresent = false ; boolean tokenIsPresent = false ; if ( rowRange . getStartKey ( ) != null || rowRange . getEndKey ( ) != null ) { keyIsPresent = true ; } if ( rowRange . getStartToken ( ) != null || rowRange . getEndToken ( ) != null ) { tokenIsPresent = true ; } if ( keyIsPresent && tokenIsPresent ) { throw new RuntimeException ( "Cannot provide both token and keys for range query" ) ; } if ( keyIsPresent ) { if ( rowRange . getStartKey ( ) != null ) { values . add ( rowRange . getStartKey ( ) ) ; } if ( rowRange . getEndKey ( ) != null ) { values . add ( rowRange . getEndKey ( ) ) ; } } else if ( tokenIsPresent ) { BigInteger startTokenB = rowRange . getStartToken ( ) != null ? new BigInteger ( rowRange . getStartToken ( ) ) : null ; BigInteger endTokenB = rowRange . getEndToken ( ) != null ? new BigInteger ( rowRange . getEndToken ( ) ) : null ; Long startToken = startTokenB . longValue ( ) ; Long endToken = endTokenB . longValue ( ) ; if ( startToken != null && endToken != null ) { if ( startToken != null ) { values . add ( startToken ) ; } if ( endToken != null ) { values . add ( endToken ) ; } } if ( rowRange . getCount ( ) > 0 ) { } return ; } }
Private helper for constructing the bind values for the given row range . Note that the assumption here is that we have a previously constructed prepared statement that we can bind these values with .
32,239
public OperationResult < R > tryOperation ( Operation < CL , R > operation ) throws ConnectionException { Operation < CL , R > filteredOperation = config . getOperationFilterFactory ( ) . attachFilter ( operation ) ; while ( true ) { attemptCounter ++ ; try { connection = borrowConnection ( filteredOperation ) ; startTime = System . currentTimeMillis ( ) ; OperationResult < R > result = connection . execute ( filteredOperation ) ; result . setAttemptsCount ( attemptCounter ) ; monitor . incOperationSuccess ( getCurrentHost ( ) , result . getLatency ( ) ) ; return result ; } catch ( Exception e ) { ConnectionException ce = ( e instanceof ConnectionException ) ? ( ConnectionException ) e : new UnknownException ( e ) ; try { informException ( ce ) ; monitor . incFailover ( ce . getHost ( ) , ce ) ; } catch ( ConnectionException ex ) { monitor . incOperationFailure ( getCurrentHost ( ) , ex ) ; throw ex ; } } finally { releaseConnection ( ) ; } } }
Basic impl that repeatedly borrows a conn and tries to execute the operation while maintaining metrics for success conn attempts failures and latencies for operation executions
32,240
public String getVersion ( ) throws ConnectionException { return connectionPool . executeWithFailover ( new AbstractOperationImpl < String > ( tracerFactory . newTracer ( CassandraOperationType . GET_VERSION ) ) { public String internalExecute ( Client client , ConnectionContext state ) throws Exception { return client . describe_version ( ) ; } } , config . getRetryPolicy ( ) . duplicate ( ) ) . getResult ( ) ; }
Get the version from the cluster
32,241
public Boolean call ( ) throws Exception { error . set ( null ) ; List < Callable < Boolean > > subtasks = Lists . newArrayList ( ) ; if ( this . concurrencyLevel != null || startToken != null || endToken != null ) { List < TokenRange > tokens = partitioner . splitTokenRange ( startToken == null ? partitioner . getMinToken ( ) : startToken , endToken == null ? partitioner . getMinToken ( ) : endToken , this . concurrencyLevel == null ? 1 : this . concurrencyLevel ) ; for ( TokenRange range : tokens ) { subtasks . add ( makeTokenRangeTask ( range . getStartToken ( ) , range . getEndToken ( ) ) ) ; } } else { List < TokenRange > ranges = keyspace . describeRing ( dc , rack ) ; for ( TokenRange range : ranges ) { if ( range . getStartToken ( ) . equals ( range . getEndToken ( ) ) ) subtasks . add ( makeTokenRangeTask ( range . getStartToken ( ) , range . getEndToken ( ) ) ) ; else subtasks . add ( makeTokenRangeTask ( partitioner . getTokenMinusOne ( range . getStartToken ( ) ) , range . getEndToken ( ) ) ) ; } } try { if ( executor == null ) { ExecutorService localExecutor = Executors . newFixedThreadPool ( subtasks . size ( ) , new ThreadFactoryBuilder ( ) . setDaemon ( true ) . setNameFormat ( "AstyanaxAllRowsReader-%d" ) . build ( ) ) ; try { futures . addAll ( startTasks ( localExecutor , subtasks ) ) ; return waitForTasksToFinish ( ) ; } finally { localExecutor . shutdownNow ( ) ; } } else { futures . addAll ( startTasks ( executor , subtasks ) ) ; return waitForTasksToFinish ( ) ; } } catch ( Exception e ) { error . compareAndSet ( null , e ) ; LOG . warn ( "AllRowsReader terminated. " + e . getMessage ( ) , e ) ; cancel ( ) ; throw error . get ( ) ; } }
Main execution block for the all rows query .
32,242
protected XMLStreamReader createStreamReader ( InputStream input ) throws XMLStreamException { if ( inputFactory == null ) { inputFactory = XMLInputFactory . newInstance ( ) ; } return inputFactory . createXMLStreamReader ( input ) ; }
Get a new XML stream reader .
32,243
public ThriftType getThriftType ( Type javaType ) throws IllegalArgumentException { ThriftType thriftType = getThriftTypeFromCache ( javaType ) ; if ( thriftType == null ) { thriftType = buildThriftType ( javaType ) ; } return thriftType ; }
Gets the ThriftType for the specified Java type . The native Thrift type for the Java type will be inferred from the Java type and if necessary type coercions will be applied .
32,244
public < T extends Enum < T > > ThriftEnumMetadata < ? > getThriftEnumMetadata ( Class < ? > enumClass ) { ThriftEnumMetadata < ? > enumMetadata = enums . get ( enumClass ) ; if ( enumMetadata == null ) { enumMetadata = new ThriftEnumMetadataBuilder < > ( ( Class < T > ) enumClass ) . build ( ) ; ThriftEnumMetadata < ? > current = enums . putIfAbsent ( enumClass , enumMetadata ) ; if ( current != null ) { enumMetadata = current ; } } return enumMetadata ; }
Gets the ThriftEnumMetadata for the specified enum class . If the enum class contains a method annotated with
32,245
public < T > ThriftStructMetadata getThriftStructMetadata ( Type structType ) { ThriftStructMetadata structMetadata = structs . get ( structType ) ; Class < ? > structClass = TypeToken . of ( structType ) . getRawType ( ) ; if ( structMetadata == null ) { if ( structClass . isAnnotationPresent ( ThriftStruct . class ) ) { structMetadata = extractThriftStructMetadata ( structType ) ; } else if ( structClass . isAnnotationPresent ( ThriftUnion . class ) ) { structMetadata = extractThriftUnionMetadata ( structType ) ; } else { throw new IllegalStateException ( "getThriftStructMetadata called on a class that has no @ThriftStruct or @ThriftUnion annotation" ) ; } ThriftStructMetadata current = structs . putIfAbsent ( structType , structMetadata ) ; if ( current != null ) { structMetadata = current ; } } return structMetadata ; }
Gets the ThriftStructMetadata for the specified struct class . The struct class must be annotated with
32,246
private FieldDefinition declareTypeField ( ) { FieldDefinition typeField = new FieldDefinition ( a ( PRIVATE , FINAL ) , "type" , type ( ThriftType . class ) ) ; classDefinition . addField ( typeField ) ; parameters . add ( typeField , ThriftType . struct ( metadata ) ) ; return typeField ; }
Declares the private ThriftType field type .
32,247
private Map < Short , FieldDefinition > declareCodecFields ( ) { Map < Short , FieldDefinition > codecFields = new TreeMap < > ( ) ; for ( ThriftFieldMetadata fieldMetadata : metadata . getFields ( ) ) { if ( needsCodec ( fieldMetadata ) ) { ThriftCodec < ? > codec = codecManager . getCodec ( fieldMetadata . getThriftType ( ) ) ; String fieldName = fieldMetadata . getName ( ) + "Codec" ; FieldDefinition codecField = new FieldDefinition ( a ( PRIVATE , FINAL ) , fieldName , type ( codec . getClass ( ) ) ) ; classDefinition . addField ( codecField ) ; codecFields . put ( fieldMetadata . getId ( ) , codecField ) ; parameters . add ( codecField , codec ) ; } } return codecFields ; }
Declares a field for each delegate codec
32,248
private void defineConstructor ( ) { MethodDefinition constructor = new MethodDefinition ( a ( PUBLIC ) , "<init>" , type ( void . class ) , parameters . getParameters ( ) ) ; constructor . loadThis ( ) . invokeConstructor ( type ( Object . class ) ) ; for ( FieldDefinition fieldDefinition : parameters . getFields ( ) ) { constructor . loadThis ( ) . loadVariable ( fieldDefinition . getName ( ) ) . putField ( codecType , fieldDefinition ) ; } constructor . ret ( ) ; classDefinition . addMethod ( constructor ) ; }
Defines the constructor with a parameter for the ThriftType and the delegate codecs . The constructor simply assigns these parameters to the class fields .
32,249
private void defineGetTypeMethod ( ) { classDefinition . addMethod ( new MethodDefinition ( a ( PUBLIC ) , "getType" , type ( ThriftType . class ) ) . loadThis ( ) . getField ( codecType , typeField ) . retObject ( ) ) ; }
Defines the getType method which simply returns the value of the type field .
32,250
private void defineReadStructMethod ( ) { MethodDefinition read = new MethodDefinition ( a ( PUBLIC ) , "read" , structType , arg ( "protocol" , TProtocol . class ) ) . addException ( Exception . class ) ; read . addLocalVariable ( type ( TProtocolReader . class ) , "reader" ) ; read . newObject ( TProtocolReader . class ) ; read . dup ( ) ; read . loadVariable ( "protocol" ) ; read . invokeConstructor ( type ( TProtocolReader . class ) , type ( TProtocol . class ) ) ; read . storeVariable ( "reader" ) ; Map < Short , LocalVariableDefinition > structData = readFieldValues ( read ) ; LocalVariableDefinition result = buildStruct ( read , structData ) ; read . loadVariable ( result ) . retObject ( ) ; classDefinition . addMethod ( read ) ; }
Defines the read method for a struct .
32,251
private void injectStructFields ( MethodDefinition read , LocalVariableDefinition instance , Map < Short , LocalVariableDefinition > structData ) { for ( ThriftFieldMetadata field : metadata . getFields ( THRIFT_FIELD ) ) { injectField ( read , field , instance , structData . get ( field . getId ( ) ) ) ; } }
Defines the code to inject data into the struct public fields .
32,252
private void injectStructMethods ( MethodDefinition read , LocalVariableDefinition instance , Map < Short , LocalVariableDefinition > structData ) { for ( ThriftMethodInjection methodInjection : metadata . getMethodInjections ( ) ) { injectMethod ( read , methodInjection , instance , structData ) ; } }
Defines the code to inject data into the struct methods .
32,253
private void defineReadUnionMethod ( ) { MethodDefinition read = new MethodDefinition ( a ( PUBLIC ) , "read" , structType , arg ( "protocol" , TProtocol . class ) ) . addException ( Exception . class ) ; read . addLocalVariable ( type ( TProtocolReader . class ) , "reader" ) ; read . newObject ( TProtocolReader . class ) ; read . dup ( ) ; read . loadVariable ( "protocol" ) ; read . invokeConstructor ( type ( TProtocolReader . class ) , type ( TProtocol . class ) ) ; read . storeVariable ( "reader" ) ; read . addInitializedLocalVariable ( type ( short . class ) , "fieldId" ) ; Map < Short , LocalVariableDefinition > unionData = readSingleFieldValue ( read ) ; LocalVariableDefinition result = buildUnion ( read , unionData ) ; read . loadVariable ( result ) . retObject ( ) ; classDefinition . addMethod ( read ) ; }
Defines the read method for an union .
32,254
private Map < Short , LocalVariableDefinition > readSingleFieldValue ( MethodDefinition read ) { LocalVariableDefinition protocol = read . getLocalVariable ( "reader" ) ; Map < Short , LocalVariableDefinition > unionData = new TreeMap < > ( ) ; for ( ThriftFieldMetadata field : metadata . getFields ( THRIFT_FIELD ) ) { LocalVariableDefinition variable = read . addInitializedLocalVariable ( toParameterizedType ( field . getThriftType ( ) ) , "f_" + field . getName ( ) ) ; unionData . put ( field . getId ( ) , variable ) ; } read . loadVariable ( protocol ) . invokeVirtual ( TProtocolReader . class , "readStructBegin" , void . class ) ; read . visitLabel ( "while-begin" ) ; read . loadVariable ( protocol ) . invokeVirtual ( TProtocolReader . class , "nextField" , boolean . class ) ; read . ifZeroGoto ( "while-end" ) ; read . loadVariable ( protocol ) . invokeVirtual ( TProtocolReader . class , "getFieldId" , short . class ) ; read . storeVariable ( "fieldId" ) ; read . loadVariable ( "fieldId" ) ; List < CaseStatement > cases = new ArrayList < > ( ) ; for ( ThriftFieldMetadata field : metadata . getFields ( THRIFT_FIELD ) ) { cases . add ( caseStatement ( field . getId ( ) , field . getName ( ) + "-field" ) ) ; } read . switchStatement ( "default" , cases ) ; for ( ThriftFieldMetadata field : metadata . getFields ( THRIFT_FIELD ) ) { read . visitLabel ( field . getName ( ) + "-field" ) ; read . loadVariable ( protocol ) ; FieldDefinition codecField = codecFields . get ( field . getId ( ) ) ; if ( codecField != null ) { read . loadThis ( ) . getField ( codecType , codecField ) ; } Method readMethod = getReadMethod ( field . getThriftType ( ) ) ; if ( readMethod == null ) { throw new IllegalArgumentException ( "Unsupported field type " + field . getThriftType ( ) . getProtocolType ( ) ) ; } read . invokeVirtual ( readMethod ) ; if ( needsCastAfterRead ( field , readMethod ) ) { read . checkCast ( toParameterizedType ( field . getThriftType ( ) ) ) ; } if ( field . getCoercion ( ) . isPresent ( ) ) { read . invokeStatic ( field . getCoercion ( ) . get ( ) . getFromThrift ( ) ) ; } read . storeVariable ( unionData . get ( field . getId ( ) ) ) ; read . gotoLabel ( "while-begin" ) ; } read . visitLabel ( "default" ) . loadVariable ( protocol ) . invokeVirtual ( TProtocolReader . class , "skipFieldData" , void . class ) . gotoLabel ( "while-begin" ) ; read . visitLabel ( "while-end" ) ; read . loadVariable ( protocol ) . invokeVirtual ( TProtocolReader . class , "readStructEnd" , void . class ) ; return unionData ; }
Defines the code to read all of the data from the protocol into local variables .
32,255
private void invokeFactoryMethod ( MethodDefinition read , Map < Short , LocalVariableDefinition > structData , LocalVariableDefinition instance ) { if ( metadata . getBuilderMethod ( ) . isPresent ( ) ) { ThriftMethodInjection builderMethod = metadata . getBuilderMethod ( ) . get ( ) ; read . loadVariable ( instance ) ; for ( ThriftParameterInjection parameter : builderMethod . getParameters ( ) ) { read . loadVariable ( structData . get ( parameter . getId ( ) ) ) ; } read . invokeVirtual ( builderMethod . getMethod ( ) ) . storeVariable ( instance ) ; } }
Defines the code that calls the builder factory method .
32,256
private void defineReadBridgeMethod ( ) { classDefinition . addMethod ( new MethodDefinition ( a ( PUBLIC , BRIDGE , SYNTHETIC ) , "read" , type ( Object . class ) , arg ( "protocol" , TProtocol . class ) ) . addException ( Exception . class ) . loadThis ( ) . loadVariable ( "protocol" ) . invokeVirtual ( codecType , "read" , structType , type ( TProtocol . class ) ) . retObject ( ) ) ; }
Defines the generics bridge method with untyped args to the type specific read method .
32,257
private void defineWriteBridgeMethod ( ) { classDefinition . addMethod ( new MethodDefinition ( a ( PUBLIC , BRIDGE , SYNTHETIC ) , "write" , null , arg ( "struct" , Object . class ) , arg ( "protocol" , TProtocol . class ) ) . addException ( Exception . class ) . loadThis ( ) . loadVariable ( "struct" , structType ) . loadVariable ( "protocol" ) . invokeVirtual ( codecType , "write" , type ( void . class ) , structType , type ( TProtocol . class ) ) . ret ( ) ) ; }
Defines the generics bridge method with untyped args to the type specific write method .
32,258
public static ScopedBindingBuilder bindFrameCodecFactory ( Binder binder , String key , Class < ? extends ThriftFrameCodecFactory > frameCodecFactoryClass ) { return newMapBinder ( binder , String . class , ThriftFrameCodecFactory . class ) . addBinding ( key ) . to ( frameCodecFactoryClass ) ; }
helpers for binding frame codec factories
32,259
public static ScopedBindingBuilder bindProtocolFactory ( Binder binder , String key , Class < ? extends TDuplexProtocolFactory > protocolFactoryClass ) { return newMapBinder ( binder , String . class , TDuplexProtocolFactory . class ) . addBinding ( key ) . to ( protocolFactoryClass ) ; }
helpers for binding protocol factories
32,260
public static ScopedBindingBuilder bindWorkerExecutor ( Binder binder , String key , Class < ? extends ExecutorService > executorServiceClass ) { return workerExecutorBinder ( binder ) . addBinding ( key ) . to ( executorServiceClass ) ; }
Helpers for binding worker executors
32,261
public static Collection < Method > findAnnotatedMethods ( Class < ? > type , Class < ? extends Annotation > annotation ) { List < Method > result = new ArrayList < > ( ) ; for ( Method method : type . getMethods ( ) ) { if ( method . isSynthetic ( ) || method . isBridge ( ) || isStatic ( method . getModifiers ( ) ) ) { continue ; } Method managedMethod = findAnnotatedMethod ( type , annotation , method . getName ( ) , method . getParameterTypes ( ) ) ; if ( managedMethod != null ) { result . add ( managedMethod ) ; } } return result ; }
Find methods that are tagged with a given annotation somewhere in the hierarchy
32,262
public Void read ( TProtocol protocol ) throws Exception { Preconditions . checkNotNull ( protocol , "protocol is null" ) ; return null ; }
Always returns null without reading anything from the stream .
32,263
public void write ( Void value , TProtocol protocol ) throws Exception { Preconditions . checkNotNull ( protocol , "protocol is null" ) ; }
Always returns without writing to the stream .
32,264
@ Config ( "thrift.max-frame-size" ) public ThriftServerConfig setMaxFrameSize ( DataSize maxFrameSize ) { checkArgument ( maxFrameSize . toBytes ( ) <= 0x3FFFFFFF ) ; this . maxFrameSize = maxFrameSize ; return this ; }
Sets a maximum frame size
32,265
public HostAndPort getRemoteAddress ( Object client ) { NiftyClientChannel niftyChannel = getNiftyChannel ( client ) ; try { Channel nettyChannel = niftyChannel . getNettyChannel ( ) ; SocketAddress address = nettyChannel . getRemoteAddress ( ) ; InetSocketAddress inetAddress = ( InetSocketAddress ) address ; return HostAndPort . fromParts ( inetAddress . getHostString ( ) , inetAddress . getPort ( ) ) ; } catch ( NullPointerException | ClassCastException e ) { throw new IllegalArgumentException ( "Invalid swift client object" , e ) ; } }
Returns the remote address that a Swift client is connected to
32,266
protected final Set < String > inferThriftFieldIds ( ) { Set < String > fieldsWithConflictingIds = new HashSet < > ( ) ; Multimap < String , FieldMetadata > fieldsByExplicitOrExtractedName = Multimaps . index ( fields , getOrExtractThriftFieldName ( ) ) ; inferThriftFieldIds ( fieldsByExplicitOrExtractedName , fieldsWithConflictingIds ) ; Multimap < String , FieldMetadata > fieldsByExtractedName = Multimaps . index ( fields , extractThriftFieldName ( ) ) ; inferThriftFieldIds ( fieldsByExtractedName , fieldsWithConflictingIds ) ; return fieldsWithConflictingIds ; }
Assigns all fields an id if possible . Fields are grouped by name and for each group if there is a single id all fields in the group are assigned this id . If the group has multiple ids an error is reported .
32,267
protected final void verifyFieldType ( short id , String name , Collection < FieldMetadata > fields , ThriftCatalog catalog ) { boolean isSupportedType = true ; for ( FieldMetadata field : fields ) { if ( ! catalog . isSupportedStructFieldType ( field . getJavaType ( ) ) ) { metadataErrors . addError ( "Thrift class '%s' field '%s(%s)' type '%s' is not a supported Java type" , structName , name , id , TypeToken . of ( field . getJavaType ( ) ) ) ; isSupportedType = false ; break ; } } if ( isSupportedType ) { Set < ThriftTypeReference > types = new HashSet < > ( ) ; for ( FieldMetadata field : fields ) { types . add ( catalog . getFieldThriftTypeReference ( field ) ) ; } if ( types . size ( ) > 1 ) { metadataErrors . addError ( "Thrift class '%s' field '%s(%s)' has multiple types: %s" , structName , name , id , types ) ; } } }
Verifies that the the fields all have a supported Java type and that all fields map to the exact same ThriftType .
32,268
private static String escapeJavaString ( String input ) { int len = input . length ( ) ; StringBuilder out = new StringBuilder ( len + 10 ) ; for ( int i = 0 ; i < len ; i ++ ) { char c = input . charAt ( i ) ; if ( c >= 32 && c <= 0x7f ) { if ( c == '"' ) { out . append ( '\\' ) ; out . append ( '"' ) ; } else if ( c == '\\' ) { out . append ( '\\' ) ; out . append ( '\\' ) ; } else { out . append ( c ) ; } } else { out . append ( '\\' ) ; out . append ( 'u' ) ; out . append ( Integer . toHexString ( c | 0x10000 ) . substring ( 1 ) ) ; } } return out . toString ( ) ; }
in Guava 15 when released
32,269
public void addCodec ( ThriftCodec < ? > codec ) { catalog . addThriftType ( codec . getType ( ) ) ; typeCodecs . put ( codec . getType ( ) , codec ) ; }
Adds or replaces the codec associated with the type contained in the codec . This does not replace any current users of the existing codec associated with the type .
32,270
private Object convertToThrift ( Class < ? > cls ) { Set < ThriftService > serviceAnnotations = ReflectionHelper . getEffectiveClassAnnotations ( cls , ThriftService . class ) ; if ( ! serviceAnnotations . isEmpty ( ) ) { ThriftServiceMetadata serviceMetadata = new ThriftServiceMetadata ( cls , codecManager . getCatalog ( ) ) ; if ( verbose ) { LOG . info ( "Found thrift service: %s" , cls . getSimpleName ( ) ) ; } return serviceMetadata ; } else { ThriftType thriftType = codecManager . getCatalog ( ) . getThriftType ( cls ) ; if ( verbose ) { LOG . info ( "Found thrift type: %s" , thriftTypeRenderer . toString ( thriftType ) ) ; } return thriftType ; } }
returns ThriftType ThriftServiceMetadata or null
32,271
static String parse ( final byte content [ ] , final Metadata metadata , final int limit ) throws TikaException , IOException { SecurityManager sm = System . getSecurityManager ( ) ; if ( sm != null ) { sm . checkPermission ( new SpecialPermission ( ) ) ; } try { return AccessController . doPrivileged ( new PrivilegedExceptionAction < String > ( ) { public String run ( ) throws TikaException , IOException { return TIKA_INSTANCE . parseToString ( StreamInput . wrap ( content ) , metadata , limit ) ; } } ) ; } catch ( PrivilegedActionException e ) { Throwable cause = e . getCause ( ) ; if ( cause instanceof TikaException ) { throw ( TikaException ) cause ; } else if ( cause instanceof IOException ) { throw ( IOException ) cause ; } else { throw new AssertionError ( cause ) ; } } }
only package private for testing!
32,272
public static void initializeSmsRadarService ( Context context , SmsListener smsListener ) { SmsRadar . smsListener = smsListener ; Intent intent = new Intent ( context , SmsRadarService . class ) ; context . startService ( intent ) ; }
Starts the service and store the listener to be notified when a new incoming or outgoing sms be processed inside the SMS content provider
32,273
public static void stopSmsRadarService ( Context context ) { SmsRadar . smsListener = null ; Intent intent = new Intent ( context , SmsRadarService . class ) ; context . stopService ( intent ) ; }
Stops the service and remove the SmsListener added when the SmsRadar was initialized
32,274
private void saveAttributesBeforeInclude ( final Invocation inv ) { ServletRequest request = inv . getRequest ( ) ; logger . debug ( "Taking snapshot of request attributes before include" ) ; Map < String , Object > attributesSnapshot = new HashMap < String , Object > ( ) ; Enumeration < ? > attrNames = request . getAttributeNames ( ) ; while ( attrNames . hasMoreElements ( ) ) { String attrName = ( String ) attrNames . nextElement ( ) ; attributesSnapshot . put ( attrName , request . getAttribute ( attrName ) ) ; } inv . setAttribute ( "$$paoding-rose.attributesBeforeInclude" , attributesSnapshot ) ; }
Keep a snapshot of the request attributes in case of an include to be able to restore the original attributes after the include .
32,275
private void restoreRequestAttributesAfterInclude ( Invocation inv ) { logger . debug ( "Restoring snapshot of request attributes after include" ) ; HttpServletRequest request = inv . getRequest ( ) ; @ SuppressWarnings ( "unchecked" ) Map < String , Object > attributesSnapshot = ( Map < String , Object > ) inv . getAttribute ( "$$paoding-rose.attributesBeforeInclude" ) ; Set < String > attrsToCheck = new HashSet < String > ( ) ; Enumeration < ? > attrNames = request . getAttributeNames ( ) ; while ( attrNames . hasMoreElements ( ) ) { String attrName = ( String ) attrNames . nextElement ( ) ; attrsToCheck . add ( attrName ) ; } for ( String attrName : attrsToCheck ) { Object attrValue = attributesSnapshot . get ( attrName ) ; if ( attrValue != null ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Restoring original value of attribute [" + attrName + "] after include" ) ; } request . setAttribute ( attrName , attrValue ) ; } else { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Removing attribute [" + attrName + "] after include" ) ; } request . removeAttribute ( attrName ) ; } } }
Restore the request attributes after an include .
32,276
protected boolean isCandidateComponent ( MetadataReader metadataReader ) throws IOException { for ( TypeFilter tf : this . excludeFilters ) { if ( tf . match ( metadataReader , this . metadataReaderFactory ) ) { return false ; } } for ( TypeFilter tf : this . includeFilters ) { if ( tf . match ( metadataReader , this . metadataReaderFactory ) ) { return true ; } } return false ; }
Determine whether the given class does not match any exclude filter and does match at least one include filter .
32,277
protected AbstractPropertyBindingResult getInternalBindingResult ( ) { AbstractPropertyBindingResult bindingResult = super . getInternalBindingResult ( ) ; PropertyEditorRegistry registry = bindingResult . getPropertyEditorRegistry ( ) ; registry . registerCustomEditor ( Date . class , new DateEditor ( Date . class ) ) ; registry . registerCustomEditor ( java . sql . Date . class , new DateEditor ( java . sql . Date . class ) ) ; registry . registerCustomEditor ( java . sql . Time . class , new DateEditor ( java . sql . Time . class ) ) ; registry . registerCustomEditor ( java . sql . Timestamp . class , new DateEditor ( java . sql . Timestamp . class ) ) ; return bindingResult ; }
Return the internal BindingResult held by this DataBinder as AbstractPropertyBindingResult .
32,278
public final byte [ ] decode ( byte [ ] source , int off , int len ) { int len34 = len * 3 / 4 ; byte [ ] outBuff = new byte [ len34 ] ; int outBuffPosn = 0 ; byte [ ] b4 = new byte [ 4 ] ; int b4Posn = 0 ; int i = 0 ; byte sbiCrop = 0 ; byte sbiDecode = 0 ; for ( i = off ; i < off + len ; i ++ ) { sbiCrop = ( byte ) ( source [ i ] & 0x7f ) ; sbiDecode = DECODABET [ sbiCrop ] ; if ( sbiDecode >= WHITE_SPACE_ENC ) { if ( sbiDecode >= PADDING_CHAR_ENC ) { b4 [ b4Posn ++ ] = sbiCrop ; if ( b4Posn > 3 ) { outBuffPosn += decode4to3 ( b4 , 0 , outBuff , outBuffPosn ) ; b4Posn = 0 ; if ( sbiCrop == PADDING_CHAR ) { break ; } } } } else { } } byte [ ] out = new byte [ outBuffPosn ] ; System . arraycopy ( outBuff , 0 , out , 0 , outBuffPosn ) ; return out ; }
Very low - level access to decoding ASCII characters in the form of a byte array .
32,279
protected void initialize ( ) { this . mappedFields = new HashMap < String , PropertyDescriptor > ( ) ; PropertyDescriptor [ ] pds = BeanUtils . getPropertyDescriptors ( mappedClass ) ; if ( checkProperties ) { mappedProperties = new HashSet < String > ( ) ; } for ( int i = 0 ; i < pds . length ; i ++ ) { PropertyDescriptor pd = pds [ i ] ; if ( pd . getWriteMethod ( ) != null ) { if ( checkProperties ) { this . mappedProperties . add ( pd . getName ( ) ) ; } this . mappedFields . put ( pd . getName ( ) . toLowerCase ( ) , pd ) ; for ( String underscoredName : underscoreName ( pd . getName ( ) ) ) { if ( underscoredName != null && ! pd . getName ( ) . toLowerCase ( ) . equals ( underscoredName ) ) { this . mappedFields . put ( underscoredName , pd ) ; } } } } }
Initialize the mapping metadata for the given class .
32,280
private String [ ] underscoreName ( String camelCaseName ) { StringBuilder result = new StringBuilder ( ) ; if ( camelCaseName != null && camelCaseName . length ( ) > 0 ) { result . append ( camelCaseName . substring ( 0 , 1 ) . toLowerCase ( ) ) ; for ( int i = 1 ; i < camelCaseName . length ( ) ; i ++ ) { char ch = camelCaseName . charAt ( i ) ; if ( Character . isUpperCase ( ch ) ) { result . append ( "_" ) ; result . append ( Character . toLowerCase ( ch ) ) ; } else { result . append ( ch ) ; } } } String name = result . toString ( ) ; String name2 = null ; boolean digitFound = false ; for ( int i = name . length ( ) - 1 ; i >= 0 ; i -- ) { if ( Character . isDigit ( name . charAt ( i ) ) ) { digitFound = true ; continue ; } if ( digitFound && i < name . length ( ) - 1 && i > 0 ) { if ( name2 == null ) { name2 = name ; } name2 = name2 . substring ( 0 , i + 1 ) + "_" + name2 . substring ( i + 1 ) ; } digitFound = false ; } return new String [ ] { name , name2 } ; }
Convert a name in camelCase to an underscored name in lower case . Any upper case letters are converted to lower case with a preceding underscore .
32,281
public Options createOptions ( OptionsConfiguration optionsConfiguration ) throws MojoExecutionException { final Options options = new Options ( ) ; options . verbose = optionsConfiguration . isVerbose ( ) ; options . debugMode = optionsConfiguration . isDebugMode ( ) ; options . classpaths . addAll ( optionsConfiguration . getPlugins ( ) ) ; options . target = createSpecVersion ( optionsConfiguration . getSpecVersion ( ) ) ; final String encoding = optionsConfiguration . getEncoding ( ) ; if ( encoding != null ) { options . encoding = createEncoding ( encoding ) ; } options . setSchemaLanguage ( createLanguage ( optionsConfiguration . getSchemaLanguage ( ) ) ) ; options . entityResolver = optionsConfiguration . getEntityResolver ( ) ; for ( InputSource grammar : optionsConfiguration . getGrammars ( ) ) { options . addGrammar ( grammar ) ; } for ( InputSource bindFile : optionsConfiguration . getBindFiles ( ) ) { options . addBindFile ( bindFile ) ; } options . defaultPackage = optionsConfiguration . getGeneratePackage ( ) ; options . targetDir = optionsConfiguration . getGenerateDirectory ( ) ; options . strictCheck = optionsConfiguration . isStrict ( ) ; options . readOnly = optionsConfiguration . isReadOnly ( ) ; options . packageLevelAnnotations = optionsConfiguration . isPackageLevelAnnotations ( ) ; options . noFileHeader = optionsConfiguration . isNoFileHeader ( ) ; options . enableIntrospection = optionsConfiguration . isEnableIntrospection ( ) ; options . disableXmlSecurity = optionsConfiguration . isDisableXmlSecurity ( ) ; if ( optionsConfiguration . getAccessExternalSchema ( ) != null ) { System . setProperty ( "javax.xml.accessExternalSchema" , optionsConfiguration . getAccessExternalSchema ( ) ) ; } if ( optionsConfiguration . getAccessExternalDTD ( ) != null ) { System . setProperty ( "javax.xml.accessExternalDTD" , optionsConfiguration . getAccessExternalDTD ( ) ) ; } if ( optionsConfiguration . isEnableExternalEntityProcessing ( ) ) { System . setProperty ( "enableExternalEntityProcessing" , Boolean . TRUE . toString ( ) ) ; } options . contentForWildcard = optionsConfiguration . isContentForWildcard ( ) ; if ( optionsConfiguration . isExtension ( ) ) { options . compatibilityMode = Options . EXTENSION ; } final List < String > arguments = optionsConfiguration . getArguments ( ) ; try { options . parseArguments ( arguments . toArray ( new String [ arguments . size ( ) ] ) ) ; } catch ( BadCommandLineException bclex ) { throw new MojoExecutionException ( "Error parsing the command line [" + arguments + "]" , bclex ) ; } return options ; }
Creates and initializes an instance of XJC options .
32,282
public static InputSource getInputSource ( File file ) { try { final URL url = file . toURI ( ) . toURL ( ) ; return getInputSource ( url ) ; } catch ( MalformedURLException e ) { return new InputSource ( file . getPath ( ) ) ; } }
Creates an input source for the given file .
32,283
public void execute ( ) throws MojoExecutionException { synchronized ( lock ) { injectDependencyDefaults ( ) ; resolveArtifacts ( ) ; final ClassLoader currentClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; final ClassLoader classLoader = createClassLoader ( currentClassLoader ) ; Thread . currentThread ( ) . setContextClassLoader ( classLoader ) ; final Locale currentDefaultLocale = Locale . getDefault ( ) ; try { final Locale locale = LocaleUtils . valueOf ( getLocale ( ) ) ; Locale . setDefault ( locale ) ; doExecute ( ) ; } finally { Locale . setDefault ( currentDefaultLocale ) ; Thread . currentThread ( ) . setContextClassLoader ( currentClassLoader ) ; } } }
Execute the maven2 mojo to invoke the xjc2 compiler based on any configuration settings .
32,284
protected void setupMavenPaths ( ) { if ( getAddCompileSourceRoot ( ) ) { getProject ( ) . addCompileSourceRoot ( getGenerateDirectory ( ) . getPath ( ) ) ; } if ( getAddTestCompileSourceRoot ( ) ) { getProject ( ) . addTestCompileSourceRoot ( getGenerateDirectory ( ) . getPath ( ) ) ; } if ( getEpisode ( ) && getEpisodeFile ( ) != null ) { final String episodeFilePath = getEpisodeFile ( ) . getAbsolutePath ( ) ; final String generatedDirectoryPath = getGenerateDirectory ( ) . getAbsolutePath ( ) ; if ( episodeFilePath . startsWith ( generatedDirectoryPath + File . separator ) ) { final String path = episodeFilePath . substring ( generatedDirectoryPath . length ( ) + 1 ) ; final Resource resource = new Resource ( ) ; resource . setDirectory ( generatedDirectoryPath ) ; resource . addInclude ( path ) ; if ( getAddCompileSourceRoot ( ) ) { getProject ( ) . addResource ( resource ) ; } if ( getAddTestCompileSourceRoot ( ) ) { getProject ( ) . addTestResource ( resource ) ; } } } }
Augments Maven paths with generated resources .
32,285
protected void logConfiguration ( ) throws MojoExecutionException { super . logConfiguration ( ) ; getLog ( ) . info ( "catalogURIs (calculated):" + getCatalogURIs ( ) ) ; getLog ( ) . info ( "resolvedCatalogURIs (calculated):" + getResolvedCatalogURIs ( ) ) ; getLog ( ) . info ( "schemaFiles (calculated):" + getSchemaFiles ( ) ) ; getLog ( ) . info ( "schemaURIs (calculated):" + getSchemaURIs ( ) ) ; getLog ( ) . info ( "resolvedSchemaURIs (calculated):" + getResolvedSchemaURIs ( ) ) ; getLog ( ) . info ( "bindingFiles (calculated):" + getBindingFiles ( ) ) ; getLog ( ) . info ( "bindingURIs (calculated):" + getBindingURIs ( ) ) ; getLog ( ) . info ( "resolvedBindingURIs (calculated):" + getResolvedBindingURIs ( ) ) ; getLog ( ) . info ( "xjcPluginArtifacts (resolved):" + getXjcPluginArtifacts ( ) ) ; getLog ( ) . info ( "xjcPluginFiles (resolved):" + getXjcPluginFiles ( ) ) ; getLog ( ) . info ( "xjcPluginURLs (resolved):" + getXjcPluginURLs ( ) ) ; getLog ( ) . info ( "episodeArtifacts (resolved):" + getEpisodeArtifacts ( ) ) ; getLog ( ) . info ( "episodeFiles (resolved):" + getEpisodeFiles ( ) ) ; getLog ( ) . info ( "dependsURIs (resolved):" + getDependsURIs ( ) ) ; }
Log the configuration settings . Shown when exception thrown or when verbose is true .
32,286
protected CatalogResolver createCatalogResolver ( ) throws MojoExecutionException { final CatalogManager catalogManager = new CatalogManager ( ) ; catalogManager . setIgnoreMissingProperties ( true ) ; catalogManager . setUseStaticCatalog ( false ) ; if ( getLog ( ) . isDebugEnabled ( ) ) { catalogManager . setVerbosity ( Integer . MAX_VALUE ) ; } if ( getCatalogResolver ( ) == null ) { return new MavenCatalogResolver ( catalogManager , this , getLog ( ) ) ; } else { final String catalogResolverClassName = getCatalogResolver ( ) . trim ( ) ; return createCatalogResolverByClassName ( catalogResolverClassName ) ; } }
Creates an instance of catalog resolver .
32,287
MeetMeRoomImpl getOrCreateRoomImpl ( String roomNumber ) { MeetMeRoomImpl room ; boolean created = false ; synchronized ( rooms ) { room = rooms . get ( roomNumber ) ; if ( room == null ) { room = new MeetMeRoomImpl ( server , roomNumber ) ; populateRoom ( room ) ; rooms . put ( roomNumber , room ) ; created = true ; } } if ( created ) { logger . debug ( "Created MeetMeRoom " + roomNumber ) ; } return room ; }
Returns the room with the given number or creates a new one if none is there yet .
32,288
public String getDecodedMessage ( ) { if ( message == null ) { return null ; } return new String ( Base64 . base64ToByteArray ( message ) , Charset . forName ( "UTF-8" ) ) ; }
Returns the decoded message .
32,289
public static CallerID buildFromComponents ( final String firstname , final String lastname , final String number ) { String name = "" ; if ( firstname != null ) { name += firstname . trim ( ) ; } if ( lastname != null ) { if ( name . length ( ) > 0 ) { name += " " ; } name += lastname . trim ( ) ; } return PBXFactory . getActivePBX ( ) . buildCallerID ( number , name ) ; }
This is a little helper class which will buid the name component of a clid from the first and lastnames . If both firstname and lastname are null then the name component will be an empty string .
32,290
void idChanged ( Date date , String id ) { final String oldId = this . id ; if ( oldId != null && oldId . equals ( id ) ) { return ; } this . id = id ; firePropertyChange ( PROPERTY_ID , oldId , id ) ; }
Changes the id of this channel .
32,291
void nameChanged ( Date date , String name ) { final String oldName = this . name ; if ( oldName != null && oldName . equals ( name ) ) { return ; } this . name = name ; firePropertyChange ( PROPERTY_NAME , oldName , name ) ; }
Changes the name of this channel .
32,292
void setCallerId ( final CallerId callerId ) { final CallerId oldCallerId = this . callerId ; this . callerId = callerId ; firePropertyChange ( PROPERTY_CALLER_ID , oldCallerId , callerId ) ; }
Sets the caller id of this channel .
32,293
synchronized void stateChanged ( Date date , ChannelState state ) { final ChannelStateHistoryEntry historyEntry ; final ChannelState oldState = this . state ; if ( oldState == state ) { return ; } historyEntry = new ChannelStateHistoryEntry ( date , state ) ; synchronized ( stateHistory ) { stateHistory . add ( historyEntry ) ; } this . state = state ; firePropertyChange ( PROPERTY_STATE , oldState , state ) ; }
Changes the state of this channel .
32,294
void setAccount ( String account ) { final String oldAccount = this . account ; this . account = account ; firePropertyChange ( PROPERTY_ACCOUNT , oldAccount , account ) ; }
Sets the account code used to bill this channel .
32,295
void extensionVisited ( Date date , Extension extension ) { final Extension oldCurrentExtension = getCurrentExtension ( ) ; final ExtensionHistoryEntry historyEntry ; historyEntry = new ExtensionHistoryEntry ( date , extension ) ; synchronized ( extensionHistory ) { extensionHistory . add ( historyEntry ) ; } firePropertyChange ( PROPERTY_CURRENT_EXTENSION , oldCurrentExtension , extension ) ; }
Adds a visted dialplan entry to the history .
32,296
public List < AsteriskChannel > getDialedChannels ( ) { final List < AsteriskChannel > copy ; synchronized ( dialedChannels ) { copy = new ArrayList < > ( dialedChannels ) ; } return copy ; }
Retrives the conplete List of all dialed channels associated to ths calls
32,297
synchronized void channelLinked ( Date date , AsteriskChannel linkedChannel ) { final AsteriskChannel oldLinkedChannel ; synchronized ( this . linkedChannels ) { if ( this . linkedChannels . isEmpty ( ) ) { oldLinkedChannel = null ; this . linkedChannels . add ( linkedChannel ) ; } else { oldLinkedChannel = this . linkedChannels . get ( 0 ) ; this . linkedChannels . set ( 0 , linkedChannel ) ; } } final LinkedChannelHistoryEntry historyEntry ; historyEntry = new LinkedChannelHistoryEntry ( date , linkedChannel ) ; synchronized ( linkedChannelHistory ) { linkedChannelHistory . add ( historyEntry ) ; } this . wasLinked = true ; firePropertyChange ( PROPERTY_LINKED_CHANNEL , oldLinkedChannel , linkedChannel ) ; }
Sets the channel this channel is bridged with .
32,298
protected AsteriskVersion determineVersionByCoreSettings ( ) throws Exception { ManagerResponse response = sendAction ( new CoreSettingsAction ( ) ) ; if ( ! ( response instanceof CoreSettingsResponse ) ) { logger . info ( "Could not get core settings, do we have the necessary permissions?" ) ; return null ; } String ver = ( ( CoreSettingsResponse ) response ) . getAsteriskVersion ( ) ; return AsteriskVersion . getDetermineVersionFromString ( "Asterisk " + ver ) ; }
Get asterisk version by core settings actions . This is supported from Asterisk 1 . 6 onwards .
32,299
protected AsteriskVersion determineVersionByCoreShowVersion ( ) throws Exception { final ManagerResponse coreShowVersionResponse = sendAction ( new CommandAction ( CMD_SHOW_VERSION ) ) ; if ( coreShowVersionResponse == null || ! ( coreShowVersionResponse instanceof CommandResponse ) ) { logger . info ( "Could not get response for 'core show version'" ) ; return null ; } final List < String > coreShowVersionResult = ( ( CommandResponse ) coreShowVersionResponse ) . getResult ( ) ; if ( coreShowVersionResult == null || coreShowVersionResult . isEmpty ( ) ) { logger . warn ( "Got empty response for 'core show version'" ) ; return null ; } final String coreLine = coreShowVersionResult . get ( 0 ) ; return AsteriskVersion . getDetermineVersionFromString ( coreLine ) ; }
Determine version by the core show version command . This needs command permissions .