idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
18,000 | private DBConn createAndConnectConn ( String keyspace ) throws DBNotAvailableException , RuntimeException { DBConn dbConn = new DBConn ( this , keyspace ) ; connectDBConn ( dbConn ) ; return dbConn ; } | the given keyspace does not exist . | 57 | 8 |
18,001 | private String chooseHost ( String [ ] dbHosts ) { String host = null ; synchronized ( m_lastHostLock ) { if ( dbHosts . length == 1 ) { host = dbHosts [ 0 ] ; } else if ( ! Utils . isEmpty ( m_lastHost ) ) { for ( int index = 0 ; host == null && index < dbHosts . length ; index ++ ) { if ( dbHosts [ index ] . equals ( m_lastHost ) ) { host = dbHosts [ ( ++ index ) % dbHosts . length ] ; } } } if ( host == null ) { host = dbHosts [ new Random ( ) . nextInt ( dbHosts . length ) ] ; } m_lastHost = host ; } return host ; } | Choose the next Cassandra host name in the list or a random one . | 169 | 14 |
18,002 | @ Override public void deleteValuesForField ( ) { for ( String targetObjID : m_dbObj . getFieldValues ( m_fieldName ) ) { deleteLinkInverseValue ( targetObjID ) ; } if ( m_linkDef . isSharded ( ) ) { deleteShardedLinkTermRows ( ) ; } } | Clean - up inverses and sharded term rows . | 73 | 12 |
18,003 | private void addInverseLinkValue ( String targetObjID ) { int shardNo = m_tableDef . getShardNumber ( m_dbObj ) ; if ( shardNo > 0 && m_invLinkDef . isSharded ( ) ) { m_dbTran . addShardedLinkValue ( targetObjID , m_invLinkDef , m_dbObj . getObjectID ( ) , shardNo ) ; } else { m_dbTran . addLinkValue ( targetObjID , m_invLinkDef , m_dbObj . getObjectID ( ) ) ; } // Add the "_ID" field to the inverse object's primary record. m_dbTran . addIDValueColumn ( m_invTableDef , targetObjID ) ; // Add the target object's ID to its all-objects row. int targetShardNo = getTargetObjectShardNumber ( targetObjID ) ; m_dbTran . addAllObjectsColumn ( m_invTableDef , targetObjID , targetShardNo ) ; } | for the inverse reference . | 228 | 5 |
18,004 | private void addLinkValue ( String targetObjID ) { int targetShardNo = getTargetObjectShardNumber ( targetObjID ) ; if ( targetShardNo > 0 && m_linkDef . isSharded ( ) ) { m_dbTran . addShardedLinkValue ( m_dbObj . getObjectID ( ) , m_linkDef , targetObjID , targetShardNo ) ; } else { m_dbTran . addLinkValue ( m_dbObj . getObjectID ( ) , m_linkDef , targetObjID ) ; } addInverseLinkValue ( targetObjID ) ; } | Add mutations to add a reference via our link to the given target object ID . | 136 | 16 |
18,005 | private int getTargetObjectShardNumber ( String targetObjID ) { int targetShardNo = 0 ; if ( m_invTableDef . isSharded ( ) && m_targetObjShardNos != null && m_targetObjShardNos . containsKey ( targetObjID ) ) { targetShardNo = m_targetObjShardNos . get ( targetObjID ) ; } return targetShardNo ; } | Get the shard number of the target object ID if cached . | 95 | 13 |
18,006 | private void deleteLinkInverseValue ( String targetObjID ) { int shardNo = m_tableDef . getShardNumber ( m_dbObj ) ; if ( shardNo > 0 && m_invLinkDef . isSharded ( ) ) { m_dbTran . deleteShardedLinkValue ( targetObjID , m_invLinkDef , m_dbObj . getObjectID ( ) , shardNo ) ; } else { m_dbTran . deleteLinkValue ( targetObjID , m_invLinkDef , m_dbObj . getObjectID ( ) ) ; } } | Delete the inverse reference to the given target object ID . | 131 | 11 |
18,007 | private void deleteLinkValue ( String targetObjID ) { int targetShardNo = getTargetObjectShardNumber ( targetObjID ) ; if ( targetShardNo > 0 && m_linkDef . isSharded ( ) ) { m_dbTran . deleteShardedLinkValue ( targetObjID , m_linkDef , m_dbObj . getObjectID ( ) , targetShardNo ) ; } else { m_dbTran . deleteLinkValue ( m_dbObj . getObjectID ( ) , m_linkDef , targetObjID ) ; } deleteLinkInverseValue ( targetObjID ) ; } | Delete the reference via our link to the given target object ID and its inverse . | 136 | 16 |
18,008 | private void deleteShardedLinkTermRows ( ) { // When link is shard, its sharded extent table is also sharded. Set < Integer > shardNums = SpiderService . instance ( ) . getShards ( m_invTableDef ) . keySet ( ) ; for ( Integer shardNumber : shardNums ) { m_dbTran . deleteShardedLinkRow ( m_linkDef , m_dbObj . getObjectID ( ) , shardNumber ) ; } } | Delete all possible term rows that might exist for our sharded link . | 109 | 14 |
18,009 | private boolean updateLinkAddValues ( ) { List < String > linkValues = m_dbObj . getFieldValues ( m_linkDef . getName ( ) ) ; if ( linkValues == null || linkValues . size ( ) == 0 ) { return false ; } Set < String > linkValueSet = new HashSet <> ( linkValues ) ; // remove duplicates for ( String targetObjID : linkValueSet ) { addLinkValue ( targetObjID ) ; } return true ; } | Add new values for our link . Return true if at least one update made . | 105 | 16 |
18,010 | private boolean updateLinkRemoveValues ( ) { Set < String > removeSet = m_dbObj . getRemoveValues ( m_fieldName ) ; List < String > addSet = m_dbObj . getFieldValues ( m_fieldName ) ; if ( removeSet != null && addSet != null ) { removeSet . removeAll ( addSet ) ; // add+remove of same ID negates the remove } if ( removeSet == null || removeSet . size ( ) == 0 ) { return false ; } for ( String removeObjID : removeSet ) { deleteLinkValue ( removeObjID ) ; } return true ; } | Process removes for our link . Return true if at least one update made . | 134 | 15 |
18,011 | public synchronized void clear ( ApplicationDefinition appDef ) { String appName = appDef . getAppName ( ) ; for ( TableDefinition tableDef : appDef . getTableDefinitions ( ) . values ( ) ) { m_cacheMap . remove ( appName + "/" + tableDef . getTableName ( ) ) ; // might have no entry } m_appShardMap . remove ( appName ) ; } | Clear all cached shard information for the given application . | 89 | 11 |
18,012 | public synchronized void verifyShard ( TableDefinition tableDef , int shardNumber ) { assert tableDef != null ; assert tableDef . isSharded ( ) ; assert shardNumber > 0 ; Map < String , Map < Integer , Date > > tableMap = m_appShardMap . get ( tableDef . getAppDef ( ) . getAppName ( ) ) ; if ( tableMap != null ) { Map < Integer , Date > shardMap = tableMap . get ( tableDef . getTableName ( ) ) ; if ( shardMap != null ) { if ( shardMap . containsKey ( shardNumber ) ) { return ; } } } // Unknown app/table/shard number, so start it. Date shardDate = tableDef . computeShardStart ( shardNumber ) ; addShardStart ( tableDef , shardNumber , shardDate ) ; } | Verify that the shard with the given number has been registered for the given table . If it hasn t the shard s starting date is computed the shard is registered in the _shards row and the start date is cached . | 192 | 48 |
18,013 | private void addShardStart ( TableDefinition tableDef , int shardNumber , Date shardDate ) { SpiderTransaction spiderTran = new SpiderTransaction ( ) ; spiderTran . addShardStart ( tableDef , shardNumber , shardDate ) ; Tenant tenant = Tenant . getTenant ( tableDef ) ; DBTransaction dbTran = DBService . instance ( tenant ) . startTransaction ( ) ; spiderTran . applyUpdates ( dbTran ) ; DBService . instance ( tenant ) . commit ( dbTran ) ; synchronized ( this ) { cacheShardValue ( tableDef , shardNumber , shardDate ) ; } } | Create a local transaction to add the register the given shard then cache it . | 146 | 16 |
18,014 | private void cacheShardValue ( TableDefinition tableDef , Integer shardNumber , Date shardStart ) { // Get or create the app name -> table map String appName = tableDef . getAppDef ( ) . getAppName ( ) ; Map < String , Map < Integer , Date > > tableShardNumberMap = m_appShardMap . get ( appName ) ; if ( tableShardNumberMap == null ) { tableShardNumberMap = new HashMap < String , Map < Integer , Date > > ( ) ; m_appShardMap . put ( appName , tableShardNumberMap ) ; } // Get or create the table name -> shard number map String tableName = tableDef . getTableName ( ) ; Map < Integer , Date > shardNumberMap = tableShardNumberMap . get ( tableName ) ; if ( shardNumberMap == null ) { shardNumberMap = new HashMap < Integer , Date > ( ) ; tableShardNumberMap . put ( tableName , shardNumberMap ) ; } // Add the shard number -> start date shardNumberMap . put ( shardNumber , shardStart ) ; m_logger . debug ( "Sharding date for {}.{} shard #{} set to: {} ({})" , new Object [ ] { appName , tableName , shardNumber , shardStart . getTime ( ) , Utils . formatDateUTC ( shardStart ) } ) ; } | Cache the given shard . | 320 | 6 |
18,015 | private void loadShardCache ( TableDefinition tableDef ) { String appName = tableDef . getAppDef ( ) . getAppName ( ) ; String tableName = tableDef . getTableName ( ) ; m_logger . debug ( "Loading shard cache for {}.{}" , appName , tableName ) ; Date cacheDate = new Date ( ) ; String cacheKey = appName + "/" + tableName ; m_cacheMap . put ( cacheKey , cacheDate ) ; Map < String , Map < Integer , Date > > tableMap = m_appShardMap . get ( appName ) ; if ( tableMap == null ) { tableMap = new HashMap <> ( ) ; m_appShardMap . put ( appName , tableMap ) ; } Map < Integer , Date > shardMap = tableMap . get ( tableName ) ; if ( shardMap == null ) { shardMap = new HashMap <> ( ) ; tableMap . put ( tableName , shardMap ) ; } Tenant tenant = Tenant . getTenant ( tableDef ) ; String storeName = SpiderService . termsStoreName ( tableDef ) ; for ( DColumn col : DBService . instance ( tenant ) . getAllColumns ( storeName , SpiderTransaction . SHARDS_ROW_KEY ) ) { Integer shardNum = Integer . parseInt ( col . getName ( ) ) ; Date shardDate = new Date ( Long . parseLong ( col . getValue ( ) ) ) ; shardMap . put ( shardNum , shardDate ) ; } } | worry about concurrency . | 347 | 6 |
18,016 | private boolean isTooOld ( Date cacheDate ) { Date now = new Date ( ) ; return now . getTime ( ) - cacheDate . getTime ( ) > MAX_CACHE_TIME_MILLIS ; } | Return true if given date has exceeded MAX_CACHE_TIME_MILLIS time . | 48 | 20 |
18,017 | public ObjectResult addNewObject ( SpiderTransaction parentTran , DBObject dbObj ) { ObjectResult result = new ObjectResult ( ) ; try { addBrandNewObject ( dbObj ) ; result . setObjectID ( dbObj . getObjectID ( ) ) ; result . setUpdated ( true ) ; parentTran . mergeSubTransaction ( m_dbTran ) ; m_logger . trace ( "addNewObject(): Object added/updated for ID={}" , dbObj . getObjectID ( ) ) ; } catch ( Throwable ex ) { buildErrorStatus ( result , dbObj . getObjectID ( ) , ex ) ; } return result ; } | Add the given DBObject to the database as a new object . No check is made to see if an object with the same ID already exists . If the update is successful updates are merged to the given parent SpiderTransaction . | 141 | 44 |
18,018 | public ObjectResult deleteObject ( SpiderTransaction parentTran , String objID ) { ObjectResult result = new ObjectResult ( objID ) ; try { result . setObjectID ( objID ) ; DBObject dbObj = SpiderService . instance ( ) . getObject ( m_tableDef , objID ) ; if ( dbObj != null ) { deleteObject ( dbObj ) ; result . setUpdated ( true ) ; parentTran . mergeSubTransaction ( m_dbTran ) ; m_logger . trace ( "deleteObject(): object deleted with ID={}" , objID ) ; } else { result . setComment ( "Object not found" ) ; m_logger . trace ( "deleteObject(): no object with ID={}" , objID ) ; } } catch ( Throwable ex ) { buildErrorStatus ( result , objID , ex ) ; } return result ; } | Delete the object with the given object ID . Because of idempotent update semantics it is not an error if the object does not exist . If an object is actually deleted updates are merged to the given parent SpiderTransaction . | 188 | 45 |
18,019 | public ObjectResult updateObject ( SpiderTransaction parentTran , DBObject dbObj , Map < String , String > currScalarMap ) { ObjectResult result = new ObjectResult ( ) ; try { result . setObjectID ( dbObj . getObjectID ( ) ) ; boolean bUpdated = updateExistingObject ( dbObj , currScalarMap ) ; result . setUpdated ( bUpdated ) ; if ( bUpdated ) { m_logger . trace ( "updateObject(): object updated for ID={}" , dbObj . getObjectID ( ) ) ; parentTran . mergeSubTransaction ( m_dbTran ) ; } else { result . setComment ( "No updates made" ) ; m_logger . trace ( "updateObject(): no updates made for ID={}" , dbObj . getObjectID ( ) ) ; } } catch ( Throwable ex ) { buildErrorStatus ( result , dbObj . getObjectID ( ) , ex ) ; } return result ; } | Update the given object whose current values have been pre - fetched . The object must exist and the values in the given DBObject are compared to the given current values to determine which ones are being added or updated . If an update is actually made updates are merged to the given parent SpiderTransaction . | 213 | 59 |
18,020 | private boolean addBrandNewObject ( DBObject dbObj ) { if ( Utils . isEmpty ( dbObj . getObjectID ( ) ) ) { dbObj . setObjectID ( Utils . base64FromBinary ( IDGenerator . nextID ( ) ) ) ; } checkForNewShard ( dbObj ) ; for ( String fieldName : dbObj . getUpdatedFieldNames ( ) ) { FieldUpdater fieldUpdater = FieldUpdater . createFieldUpdater ( this , dbObj , fieldName ) ; fieldUpdater . addValuesForField ( ) ; } return true ; } | Add new object to the database . | 133 | 7 |
18,021 | private void buildErrorStatus ( ObjectResult result , String objID , Throwable ex ) { result . setStatus ( ObjectResult . Status . ERROR ) ; result . setErrorMessage ( ex . getLocalizedMessage ( ) ) ; if ( ! Utils . isEmpty ( objID ) ) { result . setObjectID ( objID ) ; } if ( ex instanceof IllegalArgumentException ) { m_logger . debug ( "Object update error: {}" , ex . toString ( ) ) ; } else { result . setStackTrace ( Utils . getStackTrace ( ex ) ) ; m_logger . debug ( "Object update error: {} stacktrace: {}" , ex . toString ( ) , Utils . getStackTrace ( ex ) ) ; } } | Add error fields to the given ObjectResult due to the given exception . | 169 | 14 |
18,022 | private void checkForNewShard ( DBObject dbObj ) { int shardNumber = m_tableDef . getShardNumber ( dbObj ) ; if ( shardNumber > 0 ) { SpiderService . instance ( ) . verifyShard ( m_tableDef , shardNumber ) ; } } | If object is sharded see if we need to add a new column to the current shards row . | 65 | 20 |
18,023 | private void checkNewlySharded ( DBObject dbObj , Map < String , String > currScalarMap ) { if ( ! m_tableDef . isSharded ( ) ) { return ; } String shardingFieldName = m_tableDef . getShardingField ( ) . getName ( ) ; if ( ! currScalarMap . containsKey ( shardingFieldName ) ) { m_dbTran . addAllObjectsColumn ( m_tableDef , dbObj . getObjectID ( ) , m_tableDef . getShardNumber ( dbObj ) ) ; } } | previously undetermined but is not being assigned to a shard . | 131 | 14 |
18,024 | private void deleteObject ( DBObject dbObj ) { for ( String fieldName : dbObj . getUpdatedFieldNames ( ) ) { FieldUpdater fieldUpdater = FieldUpdater . createFieldUpdater ( this , dbObj , fieldName ) ; fieldUpdater . deleteValuesForField ( ) ; } m_dbTran . deleteObjectRow ( m_tableDef , dbObj . getObjectID ( ) ) ; } | Delete term columns and inverses for field values and the object s primary row . | 96 | 17 |
18,025 | private boolean updateExistingObject ( DBObject dbObj , Map < String , String > currScalarMap ) { if ( objectIsChangingShards ( dbObj , currScalarMap ) ) { return updateShardedObjectMove ( dbObj ) ; } else { return updateObjectSameShard ( dbObj , currScalarMap ) ; } } | Update the given object using the appropriate strategy . | 80 | 9 |
18,026 | private boolean updateObjectSameShard ( DBObject dbObj , Map < String , String > currScalarMap ) { boolean bUpdated = false ; checkForNewShard ( dbObj ) ; checkNewlySharded ( dbObj , currScalarMap ) ; for ( String fieldName : dbObj . getUpdatedFieldNames ( ) ) { FieldUpdater fieldUpdater = FieldUpdater . createFieldUpdater ( this , dbObj , fieldName ) ; bUpdated |= fieldUpdater . updateValuesForField ( currScalarMap . get ( fieldName ) ) ; } return bUpdated ; } | through here . | 140 | 3 |
18,027 | private boolean updateShardedObjectMove ( DBObject dbObj ) { DBObject currDBObj = SpiderService . instance ( ) . getObject ( m_tableDef , dbObj . getObjectID ( ) ) ; m_logger . debug ( "Update forcing move of object {} from shard {} to shard {}" , new Object [ ] { dbObj . getObjectID ( ) , m_tableDef . getShardNumber ( currDBObj ) , m_tableDef . getShardNumber ( dbObj ) } ) ; deleteObject ( currDBObj ) ; mergeAllFieldValues ( dbObj , currDBObj ) ; addBrandNewObject ( currDBObj ) ; return true ; } | delete the current object merge the new fields into it and re - add it . | 154 | 16 |
18,028 | private boolean objectIsChangingShards ( DBObject dbObj , Map < String , String > currScalarMap ) { if ( ! m_tableDef . isSharded ( ) ) { return false ; } // If object had no prior sharding-field value, it is considered in shard 0. int oldShardNumber = 0 ; String shardingFieldName = m_tableDef . getShardingField ( ) . getName ( ) ; String currShardFieldValue = currScalarMap . get ( shardingFieldName ) ; if ( currShardFieldValue != null ) { oldShardNumber = m_tableDef . computeShardNumber ( Utils . dateFromString ( currShardFieldValue ) ) ; } // Propagate old sharding-field value if not being updated now. int newShardNumber = m_tableDef . getShardNumber ( dbObj ) ; String newShardFieldValue = dbObj . getFieldValue ( shardingFieldName ) ; if ( newShardFieldValue == null && currShardFieldValue != null ) { dbObj . addFieldValue ( shardingFieldName , currShardFieldValue ) ; return false ; } // May or may not be moving to a new shard. return oldShardNumber != newShardNumber ; } | moved to a new shard . | 288 | 8 |
18,029 | public RESTClient getClient ( SSLTransportParameters sslParams ) { if ( m_cellRing == null ) { throw new IllegalStateException ( "Empty pool" ) ; } Cell currentCell = m_cellRing ; StringBuilder errorMessage = new StringBuilder ( ) ; do { try { RESTClient client = new RESTClient ( sslParams , m_cellRing . m_hostName , m_port ) ; client . setCredentials ( m_credentials ) ; m_cellRing . m_hostStatus = new HostStatus ( ) ; client . setAcceptType ( m_defaultContentType ) ; client . setCompression ( m_defaultCompression ) ; return client ; } catch ( RuntimeException e ) { m_cellRing . m_hostStatus = new HostStatus ( false , e ) ; errorMessage . append ( "Couldn\'t connect to " + m_cellRing . m_hostName ) . append ( "; reason: " + e . getMessage ( ) + "\n" ) ; } finally { m_cellRing = m_cellRing . next ; } } while ( currentCell != m_cellRing ) ; throw new IllegalStateException ( "No active connections found\n" + errorMessage ) ; } | Tries to connect to the next host . If no host is available IllegalStateException will be raised . | 270 | 21 |
18,030 | public Map < String , HostStatus > getState ( ) { Map < String , HostStatus > map = new HashMap <> ( ) ; if ( m_cellRing != null ) { Cell currentCell = m_cellRing ; do { map . put ( currentCell . m_hostName , currentCell . m_hostStatus ) ; currentCell = currentCell . next ; } while ( currentCell != m_cellRing ) ; } return map ; } | Generates a map of the last state of the attempts of the connections . Useful in a situation when a getClient method ended in exception then this method can show the reasons of refusals . | 97 | 39 |
18,031 | private void addToRing ( String host ) { Cell newCell = new Cell ( ) ; newCell . m_hostName = host ; if ( m_cellRing == null ) { newCell . next = newCell ; } else { newCell . next = m_cellRing . next ; m_cellRing . next = newCell ; } m_cellRing = newCell ; } | Adds a new host to a cells ring . | 82 | 9 |
18,032 | private static Mutation createMutation ( byte [ ] colName , byte [ ] colValue , long timestamp ) { if ( colValue == null ) { colValue = EMPTY_BYTES ; } Column col = new Column ( ) ; col . setName ( colName ) ; col . setValue ( colValue ) ; col . setTimestamp ( timestamp ) ; ColumnOrSuperColumn cosc = new ColumnOrSuperColumn ( ) ; cosc . setColumn ( col ) ; Mutation mutation = new Mutation ( ) ; mutation . setColumn_or_supercolumn ( cosc ) ; return mutation ; } | Create a Mutation with the given column name and column value | 130 | 12 |
18,033 | private static Mutation createDeleteColumnMutation ( byte [ ] colName , long timestamp ) { SlicePredicate slicePred = new SlicePredicate ( ) ; slicePred . addToColumn_names ( ByteBuffer . wrap ( colName ) ) ; Deletion deletion = new Deletion ( ) ; deletion . setPredicate ( slicePred ) ; deletion . setTimestamp ( timestamp ) ; Mutation mutation = new Mutation ( ) ; mutation . setDeletion ( deletion ) ; return mutation ; } | Create a column mutation that deletes the given column name . | 109 | 12 |
18,034 | public static long gcd ( long x , long y ) { if ( x < 0 ) x = - x ; if ( y < 0 ) y = - y ; if ( x < y ) { long temp = x ; x = y ; y = temp ; } long gcd = 1 ; while ( y > 1 ) { if ( ( x & 1 ) == 0 ) { if ( ( y & 1 ) == 0 ) { gcd <<= 1 ; x >>= 1 ; y >>= 1 ; } else { x >>= 1 ; } } else { if ( ( y & 1 ) == 0 ) { y >>= 1 ; } else { x = ( x - y ) >> 1 ; } } if ( x < y ) { long temp = x ; x = y ; y = temp ; } } return y == 1 ? gcd : gcd * x ; } | greatest common divisor | 186 | 6 |
18,035 | ColumnOrSuperColumn getColumn ( ByteBuffer key , ColumnPath colPath ) { m_logger . debug ( "Fetching {}.{}" , new Object [ ] { Utils . toString ( key ) , toString ( colPath ) } ) ; ColumnOrSuperColumn column = null ; boolean bSuccess = false ; for ( int attempts = 1 ; ! bSuccess ; attempts ++ ) { try { // Attempt to retrieve a slice list. Date startDate = new Date ( ) ; column = m_client . get ( key , colPath , ConsistencyLevel . ONE ) ; timing ( "get" , startDate ) ; if ( attempts > 1 ) { m_logger . info ( "get() succeeded on attempt #{}" , attempts ) ; } bSuccess = true ; } catch ( NotFoundException ex ) { return null ; } catch ( InvalidRequestException ex ) { // No point in retrying this one. String errMsg = "get() failed for table: " + colPath . getColumn_family ( ) ; m_bFailed = true ; m_logger . error ( errMsg , ex ) ; throw new RuntimeException ( errMsg , ex ) ; } catch ( Exception ex ) { // Abort if all retries exceeded. if ( attempts >= m_max_read_attempts ) { String errMsg = "All retries exceeded; abandoning get() for table: " + colPath . getColumn_family ( ) ; m_bFailed = true ; m_logger . error ( errMsg , ex ) ; throw new RuntimeException ( errMsg , ex ) ; } // Report retry as a warning. m_logger . warn ( "get() attempt #{} failed: {}" , attempts , ex ) ; try { Thread . sleep ( attempts * m_retry_wait_millis ) ; } catch ( InterruptedException e1 ) { // ignore } reconnect ( ex ) ; } } return column ; } | Fetch a single column . | 420 | 6 |
18,036 | private void commitDeletes ( DBTransaction dbTran , long timestamp ) { Map < String , Set < ByteBuffer > > rowDeleteMap = CassandraTransaction . getRowDeletionMap ( dbTran ) ; if ( rowDeleteMap . size ( ) == 0 ) { return ; } // Iterate through all ColumnFamilies for ( String colFamName : rowDeleteMap . keySet ( ) ) { // Delete each row in this key set. Set < ByteBuffer > rowKeySet = rowDeleteMap . get ( colFamName ) ; for ( ByteBuffer rowKey : rowKeySet ) { removeRow ( timestamp , rowKey , new ColumnPath ( colFamName ) ) ; } } } | Commit all row - deletions in the given MutationMap if any using the given timestamp . | 152 | 20 |
18,037 | private void commitMutations ( DBTransaction dbTran , long timestamp ) { Map < ByteBuffer , Map < String , List < Mutation > > > colMutMap = CassandraTransaction . getUpdateMap ( dbTran , timestamp ) ; if ( colMutMap . size ( ) == 0 ) { return ; } m_logger . debug ( "Committing {} mutations" , CassandraTransaction . totalColumnMutations ( dbTran ) ) ; // The batch_mutate will be retried up to MAX_COMMIT_RETRIES times. boolean bSuccess = false ; for ( int attempts = 1 ; ! bSuccess ; attempts ++ ) { try { // Attempt to commit all updates in the the current mutation map. Date startDate = new Date ( ) ; m_client . batch_mutate ( colMutMap , ConsistencyLevel . ONE ) ; timing ( "commitMutations" , startDate ) ; if ( attempts > 1 ) { // Since we had a failure and warned about it, confirm which attempt succeeded. m_logger . info ( "batch_mutate() succeeded on attempt #{}" , attempts ) ; } bSuccess = true ; } catch ( InvalidRequestException ex ) { // No point in retrying this one. m_bFailed = true ; m_logger . error ( "batch_mutate() failed" , ex ) ; throw new RuntimeException ( "batch_mutate() failed" , ex ) ; } catch ( Exception ex ) { // If we've reached the retry limit, we fail this commit. if ( attempts >= m_max_commit_attempts ) { m_bFailed = true ; m_logger . error ( "All retries exceeded; abandoning batch_mutate()" , ex ) ; throw new RuntimeException ( "All retries exceeded; abandoning batch_mutate()" , ex ) ; } // Report retry as a warning. m_logger . warn ( "batch_mutate() attempt #{} failed: {}" , attempts , ex ) ; try { // We wait more with each failure. Thread . sleep ( attempts * m_retry_wait_millis ) ; } catch ( InterruptedException e1 ) { // ignore } // Experience suggests that even for timeout exceptions, the connection // may be bad, so we attempt to reconnect. If this fails, it will throw // an DBNotAvailableException, which we pass to the caller. reconnect ( ex ) ; } } } | configured maximum number of retries . | 526 | 8 |
18,038 | private void reconnect ( Exception reconnectEx ) { // Log the exception as a warning. m_logger . warn ( "Reconnecting to Cassandra due to error" , reconnectEx ) ; // Reconnect up to the configured number of times, waiting a little between each attempt. boolean bSuccess = false ; for ( int attempt = 1 ; ! bSuccess ; attempt ++ ) { try { close ( ) ; m_dbService . connectDBConn ( this ) ; m_logger . debug ( "Reconnect successful" ) ; bSuccess = true ; } catch ( Exception ex ) { // Abort if all retries failed. if ( attempt >= m_max_reconnect_attempts ) { m_logger . error ( "All reconnect attempts failed; abandoning reconnect" , ex ) ; throw new DBNotAvailableException ( "All reconnect attempts failed" , ex ) ; } m_logger . warn ( "Reconnect attempt #" + attempt + " failed" , ex ) ; try { Thread . sleep ( m_retry_wait_millis * attempt ) ; } catch ( InterruptedException e ) { // Ignore } } } } | an DBNotAvailableException and leave the Thrift connection null . | 247 | 13 |
18,039 | private void timing ( String metric , Date startDate ) { m_logger . trace ( "Time for '{}': {}" , metric , ( ( new Date ( ) ) . getTime ( ) - startDate . getTime ( ) ) + " millis" ) ; } | milliseconds using the given prefix as a label . | 60 | 11 |
18,040 | public void startElement ( String elemName , String attrName , String attrValue ) { AttributesImpl attrs = new AttributesImpl ( ) ; attrs . addAttribute ( "" , attrName , "" , "CDATA" , attrValue ) ; writeStartElement ( elemName , attrs ) ; m_tagStack . push ( elemName ) ; } | Start a new XML element using the given start tag and single attribute . | 81 | 14 |
18,041 | public void startElement ( String elemName , Attributes attrs ) { writeStartElement ( elemName , attrs ) ; m_tagStack . push ( elemName ) ; } | Start a new XML element using the given name and attribute set . | 40 | 13 |
18,042 | public void addDataElement ( String elemName , String content , Attributes attrs ) { writeDataElement ( elemName , attrs , content ) ; } | Same as above but using an attribute set . | 34 | 9 |
18,043 | private Attributes toAttributes ( Map < String , String > attrs ) { AttributesImpl impl = new AttributesImpl ( ) ; for ( Map . Entry < String , String > attr : attrs . entrySet ( ) ) { impl . addAttribute ( "" , attr . getKey ( ) , "" , "CDATA" , attr . getValue ( ) ) ; } return impl ; } | Converts attribute map to Attributes class instance . | 83 | 9 |
18,044 | public static boolean isValidName ( String appName ) { return appName != null && appName . length ( ) > 0 && Utils . isLetter ( appName . charAt ( 0 ) ) && Utils . allAlphaNumUnderscore ( appName ) ; } | Test the given string for validity as an application name . A valid application name must begin with a letter and contain only letters digits and underscores . | 58 | 28 |
18,045 | public void parse ( UNode appNode ) { assert appNode != null ; // Verify application name and save it. setAppName ( appNode . getName ( ) ) ; // Iterate through the application object's members. for ( String childName : appNode . getMemberNames ( ) ) { // See if we recognize this member. UNode childNode = appNode . getMember ( childName ) ; // "key" if ( childName . equals ( "key" ) ) { // Must be a value. Utils . require ( childNode . isValue ( ) , "'key' value must be a string: " + childNode ) ; Utils . require ( m_key == null , "'key' can be specified only once" ) ; m_key = childNode . getValue ( ) ; // "options" } else if ( childName . equals ( "options" ) ) { // Each name in the map is an option name. for ( String optName : childNode . getMemberNames ( ) ) { // Option must be a value. UNode optNode = childNode . getMember ( optName ) ; Utils . require ( optNode . isValue ( ) , "'option' must be a value: " + optNode ) ; setOption ( optNode . getName ( ) , optNode . getValue ( ) ) ; } // "tables" } else if ( childName . equals ( "tables" ) ) { // Should be specified only once. Utils . require ( m_tableMap . size ( ) == 0 , "'tables' can be specified only once" ) ; // Parse the table definitions, adding them to this app def and building // the external link map as we go. for ( UNode tableNode : childNode . getMemberList ( ) ) { // This will throw if the table definition has an error. TableDefinition tableDef = new TableDefinition ( ) ; tableDef . parse ( tableNode ) ; addTable ( tableDef ) ; } // Unrecognized } else { Utils . require ( false , "Unrecognized 'application' element: " + childName ) ; } } verify ( ) ; } | Parse the application definition rooted at given UNode tree and copy its contents into this object . The root node is the application object so its name is the application name and its child nodes are definitions such as key options fields etc . An exception is thrown if the definition contains an error . | 460 | 57 |
18,046 | public boolean allowsAutoTables ( ) { String optValue = getOption ( CommonDefs . AUTO_TABLES ) ; return optValue != null && optValue . equalsIgnoreCase ( "true" ) ; } | Indicate whether or not this application tables to be implicitly created . | 48 | 13 |
18,047 | public void setOption ( String optName , String optValue ) { if ( optValue == null ) { m_optionMap . remove ( optName ) ; } else { m_optionMap . put ( optName , optValue . trim ( ) ) ; } } | Set the option with the given name to the given value . If the option value is null the option is unset . If the option has an existing value it is replaced . | 56 | 35 |
18,048 | public void removeTableDef ( TableDefinition tableDef ) { assert tableDef != null ; assert tableDef . getAppDef ( ) == this ; m_tableMap . remove ( tableDef . getTableName ( ) ) ; } | Remove the given table from this application presumably because it has been deleted . | 48 | 14 |
18,049 | private void verify ( ) { // Copy table defs to avoid ConcurrentModificationException if we add a table. List < TableDefinition > definedTables = new ArrayList <> ( m_tableMap . values ( ) ) ; for ( TableDefinition tableDef : definedTables ) { // Copy field defs for same reason List < FieldDefinition > definedFields = new ArrayList <> ( tableDef . getFieldDefinitions ( ) ) ; for ( FieldDefinition fieldDef : definedFields ) { if ( fieldDef . isLinkType ( ) ) { verifyLink ( tableDef , fieldDef ) ; } } } } | complete and in agreement . | 133 | 5 |
18,050 | private void verifyLink ( TableDefinition tableDef , FieldDefinition linkDef ) { String extent = linkDef . getLinkExtent ( ) ; TableDefinition extentTableDef = getTableDef ( extent ) ; if ( extentTableDef == null ) { extentTableDef = new TableDefinition ( ) ; extentTableDef . setTableName ( extent ) ; tableDef . getAppDef ( ) . addTable ( extentTableDef ) ; } String inverse = linkDef . getLinkInverse ( ) ; FieldDefinition inverseLinkDef = extentTableDef . getFieldDef ( inverse ) ; if ( inverseLinkDef == null ) { inverseLinkDef = new FieldDefinition ( inverse ) ; inverseLinkDef . setType ( linkDef . getType ( ) ) ; inverseLinkDef . setLinkInverse ( linkDef . getName ( ) ) ; inverseLinkDef . setLinkExtent ( tableDef . getTableName ( ) ) ; extentTableDef . addFieldDefinition ( inverseLinkDef ) ; } else { Utils . require ( inverseLinkDef . getType ( ) == linkDef . getType ( ) && // both link or xlink inverseLinkDef . getLinkExtent ( ) . equals ( tableDef . getTableName ( ) ) && inverseLinkDef . getLinkInverse ( ) . equals ( linkDef . getName ( ) ) , "Link '%s' in table '%s' conflicts with inverse field '%s' in table '%s'" , linkDef . getName ( ) , tableDef . getTableName ( ) , inverseLinkDef . getName ( ) , extentTableDef . getTableName ( ) ) ; } } | has not been defined add it automatically . | 348 | 8 |
18,051 | public String replaceAliaces ( String str ) { if ( str == null ) return str ; // for performance if ( str . indexOf ( CommonDefs . ALIAS_FIRST_CHAR ) < 0 ) return str ; PriorityQueue < AliasDefinition > aliasQueue = new PriorityQueue < AliasDefinition > ( 11 , new Comparator < AliasDefinition > ( ) { public int compare ( AliasDefinition alias1 , AliasDefinition alias2 ) { return alias2 . getName ( ) . length ( ) - alias1 . getName ( ) . length ( ) ; } } ) ; for ( TableDefinition tableDef : getTableDefinitions ( ) . values ( ) ) { for ( AliasDefinition aliasDef : tableDef . getAliasDefinitions ( ) ) { aliasQueue . add ( aliasDef ) ; } } while ( true ) { String newstring = str ; while ( aliasQueue . size ( ) != 0 ) { AliasDefinition aliasDef = aliasQueue . poll ( ) ; newstring = newstring . replace ( aliasDef . getName ( ) , aliasDef . getExpression ( ) ) ; } if ( newstring . equals ( str ) ) break ; str = newstring ; } return str ; } | Replaces of all occurences of aliases defined with this table by their expressions . Now a simple string . replace is used . | 259 | 26 |
18,052 | public void register ( ) { try { objectName = consObjectName ( domain , type , keysString ) ; MBeanServer mbs = ManagementFactory . getPlatformMBeanServer ( ) ; mbs . registerMBean ( this , objectName ) ; } catch ( Exception e ) { objectName = null ; throw new RuntimeException ( e ) ; } } | Registers this bean on platform MBeanServer . | 78 | 11 |
18,053 | public void deregister ( ) { if ( objectName == null ) { return ; } try { MBeanServer mbs = ManagementFactory . getPlatformMBeanServer ( ) ; if ( mbs . isRegistered ( objectName ) ) { mbs . unregisterMBean ( objectName ) ; } objectName = null ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } | Deregisters this bean on platform MBeanServer . | 88 | 13 |
18,054 | protected ObjectName consObjectName ( String domain , String type , String keysString ) { String d = domain != null && ! "" . equals ( domain ) ? domain : getDefaultDomain ( ) ; String t = type != null && ! "" . equals ( type ) ? type : getDefaultType ( ) ; String k = keysString != null && ! "" . equals ( keysString ) ? "," + keysString : "" ; try { return new ObjectName ( d + ":type=" + t + k ) ; } catch ( MalformedObjectNameException e ) { throw new IllegalArgumentException ( e ) ; } } | Constructs the ObjectName of bean . | 131 | 8 |
18,055 | private void push ( Construct construct ) { // Make sure we don't blow the stack. check ( m_stackPos < MAX_STACK_DEPTH , "Too many JSON nested levels (maximum=" + MAX_STACK_DEPTH + ")" ) ; m_stack [ m_stackPos ++ ] = construct ; } | Push the given node onto the node stack . | 69 | 9 |
18,056 | public RESTResponse call ( RESTClient restClient ) { String methodName = getMethod ( ) ; String uri = getURI ( ) ; StringBuilder uriBuilder = new StringBuilder ( Utils . isEmpty ( restClient . getApiPrefix ( ) ) ? "" : "/" + restClient . getApiPrefix ( ) ) ; uriBuilder . append ( substitute ( uri ) ) ; uri = uriBuilder . toString ( ) ; try { byte [ ] body = getBody ( methodName ) ; RESTResponse response = sendRequest ( restClient , methodName , uri , body ) ; return response ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } | Call method implementation | 152 | 3 |
18,057 | public void validate ( RESTClient restClient ) { Utils . require ( this . commandName != null , "missing command name" ) ; //validate command name this . metadataJson = matchCommand ( restMetadataJson , this . commandName , commandParams . containsKey ( STORAGE_SERVICE ) ? ( String ) commandParams . get ( STORAGE_SERVICE ) : _SYSTEM ) ; if ( this . metadataJson == null ) { //application command not found, look for system command if ( commandParams . containsKey ( STORAGE_SERVICE ) ) { this . metadataJson = matchCommand ( restMetadataJson , this . commandName , _SYSTEM ) ; } } if ( this . metadataJson == null ) { throw new RuntimeException ( "unsupported command name: " + this . commandName ) ; } //validate required params validateRequiredParams ( ) ; } | Validate the command | 198 | 4 |
18,058 | private void validateRequiredParams ( ) { String [ ] uriStrings = getURI ( ) . split ( "\\?" ) ; if ( uriStrings . length > 0 ) { List < String > requiredParms = extractRequiredParamsInURI ( uriStrings [ 0 ] ) ; for ( String param : requiredParms ) { Utils . require ( commandParams . containsKey ( param ) , "missing param: " + param ) ; } } if ( metadataJson . containsKey ( INPUT_ENTITY ) ) { String paramValue = metadataJson . getString ( INPUT_ENTITY ) ; if ( paramValue != null ) { JsonObject parametersNode = metadataJson . getJsonObject ( PARAMETERS ) ; if ( parametersNode != null ) { if ( parametersNode . keySet ( ) . size ( ) == 1 ) { //parent node usually "params" JsonObject params = parametersNode . getJsonObject ( parametersNode . keySet ( ) . iterator ( ) . next ( ) ) ; for ( String param : params . keySet ( ) ) { JsonObject paramNode = params . getJsonObject ( param ) ; if ( paramNode . keySet ( ) . contains ( _REQUIRED ) ) { setCompound ( true ) ; Utils . require ( commandParams . containsKey ( param ) , "missing param: " + param ) ; } } } } else { Utils . require ( commandParams . containsKey ( paramValue ) , "missing param: " + paramValue ) ; } } } } | Validate Required Params | 342 | 5 |
18,059 | private List < String > extractRequiredParamsInURI ( String uri ) { List < String > matchList = new ArrayList < String > ( ) ; Pattern regex = Pattern . compile ( "\\{(.*?)\\}" ) ; Matcher regexMatcher = regex . matcher ( uri ) ; while ( regexMatcher . find ( ) ) { matchList . add ( regexMatcher . group ( 1 ) ) ; } return matchList ; } | Extract Required Params In URI | 97 | 7 |
18,060 | private String substitute ( String uri ) { List < String > params = extractRequiredParamsInURI ( uri ) ; for ( String param : params ) { if ( param . equals ( PARAMS ) ) { uri = uri . replace ( "{" + PARAMS + "}" , Utils . urlEncode ( getParamsURI ( ) ) ) ; } else { uri = uri . replace ( "{" + param + "}" , ( String ) commandParams . get ( param ) ) ; } } return uri ; } | Substitute the params with values submittted via command builder | 117 | 13 |
18,061 | private byte [ ] getBody ( String method ) { byte [ ] body = null ; String methodsWithInputEntity = HttpMethod . POST . name ( ) + "|" + HttpMethod . PUT . name ( ) + "|" + HttpMethod . DELETE . name ( ) ; if ( method . matches ( methodsWithInputEntity ) ) { if ( isCompound ( ) ) { body = Utils . toBytes ( getQueryInputEntity ( ) ) ; } else { if ( metadataJson . containsKey ( INPUT_ENTITY ) ) { JSONable data = ( JSONable ) commandParams . get ( metadataJson . getString ( INPUT_ENTITY ) ) ; if ( data != null ) { body = Utils . toBytes ( data . toJSON ( ) ) ; } } } } return body ; } | Build the body for request | 183 | 5 |
18,062 | private RESTResponse sendRequest ( RESTClient restClient , String methodName , String uri , byte [ ] body ) throws IOException { RESTResponse response = restClient . sendRequest ( HttpMethod . methodFromString ( methodName ) , uri , ContentType . APPLICATION_JSON , body ) ; logger . debug ( "response: {}" , response . toString ( ) ) ; return response ; } | Make RESTful calls to Doradus server | 86 | 9 |
18,063 | public static JsonObject matchCommand ( JsonObject commandsJson , String commandName , String storageService ) { for ( String key : commandsJson . keySet ( ) ) { if ( key . equals ( storageService ) ) { JsonObject commandCats = commandsJson . getJsonObject ( key ) ; if ( commandCats . containsKey ( commandName ) ) { return commandCats . getJsonObject ( commandName ) ; } } } return null ; } | Finds out if a command is supported by Doradus | 104 | 12 |
18,064 | public void defineApplication ( ApplicationDefinition appDef ) { checkServiceState ( ) ; Tenant tenant = TenantService . instance ( ) . getDefaultTenant ( ) ; defineApplication ( tenant , appDef ) ; } | Create the application with the given name in the default tenant . If the given application already exists the request is treated as an application update . If the update is successfully validated its schema is stored in the database and the appropriate storage service is notified to implement required physical database changes if any . | 46 | 56 |
18,065 | public void defineApplication ( Tenant tenant , ApplicationDefinition appDef ) { checkServiceState ( ) ; appDef . setTenantName ( tenant . getName ( ) ) ; ApplicationDefinition currAppDef = checkApplicationKey ( appDef ) ; StorageService storageService = verifyStorageServiceOption ( currAppDef , appDef ) ; storageService . validateSchema ( appDef ) ; initializeApplication ( currAppDef , appDef ) ; } | Create the application with the given name in the given Tenant . If the given application already exists the request is treated as an application update . If the update is successfully validated its schema is stored in the database and the appropriate storage service is notified to implement required physical database changes if any . | 95 | 57 |
18,066 | private void checkTenants ( ) { m_logger . info ( "The following tenants and applications are defined:" ) ; Collection < Tenant > tenantList = TenantService . instance ( ) . getTenants ( ) ; for ( Tenant tenant : tenantList ) { checkTenantApps ( tenant ) ; } if ( tenantList . size ( ) == 0 ) { m_logger . info ( " <no tenants>" ) ; } } | Check to the applications for this tenant . | 95 | 8 |
18,067 | private void checkTenantApps ( Tenant tenant ) { m_logger . info ( " Tenant: {}" , tenant . getName ( ) ) ; try { Iterator < DRow > rowIter = DBService . instance ( tenant ) . getAllRows ( SchemaService . APPS_STORE_NAME ) . iterator ( ) ; if ( ! rowIter . hasNext ( ) ) { m_logger . info ( " <no applications>" ) ; } while ( rowIter . hasNext ( ) ) { DRow row = rowIter . next ( ) ; ApplicationDefinition appDef = loadAppRow ( tenant , getColumnMap ( row . getAllColumns ( 1024 ) . iterator ( ) ) ) ; if ( appDef != null ) { String appName = appDef . getAppName ( ) ; String ssName = getStorageServiceOption ( appDef ) ; m_logger . info ( " Application '{}': StorageService={}; keyspace={}" , new Object [ ] { appName , ssName , tenant . getName ( ) } ) ; if ( DoradusServer . instance ( ) . findStorageService ( ssName ) == null ) { m_logger . warn ( " >>>Application '{}' uses storage service '{}' which has not been " + "initialized; application will not be accessible via this server" , appDef . getAppName ( ) , ssName ) ; } } } } catch ( Exception e ) { m_logger . warn ( "Could not check tenant '" + tenant . getName ( ) + "'. Applications may be unavailable." , e ) ; } } | Check that this tenant its applications and storage managers are available . | 353 | 12 |
18,068 | private void deleteAppProperties ( ApplicationDefinition appDef ) { Tenant tenant = Tenant . getTenant ( appDef ) ; DBTransaction dbTran = DBService . instance ( tenant ) . startTransaction ( ) ; dbTran . deleteRow ( SchemaService . APPS_STORE_NAME , appDef . getAppName ( ) ) ; DBService . instance ( tenant ) . commit ( dbTran ) ; } | Delete the given application s schema row from the Applications CF . | 96 | 12 |
18,069 | private void initializeApplication ( ApplicationDefinition currAppDef , ApplicationDefinition appDef ) { getStorageService ( appDef ) . initializeApplication ( currAppDef , appDef ) ; storeApplicationSchema ( appDef ) ; } | Initialize storage and store the given schema for the given new or updated application . | 48 | 16 |
18,070 | private void storeApplicationSchema ( ApplicationDefinition appDef ) { String appName = appDef . getAppName ( ) ; Tenant tenant = Tenant . getTenant ( appDef ) ; DBTransaction dbTran = DBService . instance ( tenant ) . startTransaction ( ) ; dbTran . addColumn ( SchemaService . APPS_STORE_NAME , appName , COLNAME_APP_SCHEMA , appDef . toDoc ( ) . toJSON ( ) ) ; dbTran . addColumn ( SchemaService . APPS_STORE_NAME , appName , COLNAME_APP_SCHEMA_FORMAT , ContentType . APPLICATION_JSON . toString ( ) ) ; dbTran . addColumn ( SchemaService . APPS_STORE_NAME , appName , COLNAME_APP_SCHEMA_VERSION , Integer . toString ( CURRENT_SCHEMA_LEVEL ) ) ; DBService . instance ( tenant ) . commit ( dbTran ) ; } | Store the application row with schema version and format . | 223 | 10 |
18,071 | private ApplicationDefinition checkApplicationKey ( ApplicationDefinition appDef ) { Tenant tenant = Tenant . getTenant ( appDef ) ; ApplicationDefinition currAppDef = getApplication ( tenant , appDef . getAppName ( ) ) ; if ( currAppDef == null ) { m_logger . info ( "Defining application: {}" , appDef . getAppName ( ) ) ; } else { m_logger . info ( "Updating application: {}" , appDef . getAppName ( ) ) ; String appKey = currAppDef . getKey ( ) ; Utils . require ( Utils . isEmpty ( appKey ) || appKey . equals ( appDef . getKey ( ) ) , "Application key cannot be changed: %s" , appDef . getKey ( ) ) ; } return currAppDef ; } | Verify key match of an existing application if any and return it s definition . | 184 | 16 |
18,072 | private StorageService verifyStorageServiceOption ( ApplicationDefinition currAppDef , ApplicationDefinition appDef ) { // Verify or assign StorageService String ssName = getStorageServiceOption ( appDef ) ; StorageService storageService = getStorageService ( appDef ) ; Utils . require ( storageService != null , "StorageService is unknown or hasn't been initialized: %s" , ssName ) ; // Currently, StorageService can't be changed. if ( currAppDef != null ) { String currSSName = getStorageServiceOption ( currAppDef ) ; Utils . require ( currSSName . equals ( ssName ) , "'StorageService' cannot be changed for application: %s" , appDef . getAppName ( ) ) ; } return storageService ; } | change ensure it hasn t changed . Return the application s StorageService object . | 165 | 15 |
18,073 | private ApplicationDefinition loadAppRow ( Tenant tenant , Map < String , String > colMap ) { ApplicationDefinition appDef = new ApplicationDefinition ( ) ; String appSchema = colMap . get ( COLNAME_APP_SCHEMA ) ; if ( appSchema == null ) { return null ; // Not a real application definition row } String format = colMap . get ( COLNAME_APP_SCHEMA_FORMAT ) ; ContentType contentType = Utils . isEmpty ( format ) ? ContentType . TEXT_XML : new ContentType ( format ) ; String versionStr = colMap . get ( COLNAME_APP_SCHEMA_VERSION ) ; int schemaVersion = Utils . isEmpty ( versionStr ) ? CURRENT_SCHEMA_LEVEL : Integer . parseInt ( versionStr ) ; if ( schemaVersion > CURRENT_SCHEMA_LEVEL ) { m_logger . warn ( "Skipping schema with advanced version: {}" , schemaVersion ) ; return null ; } try { appDef . parse ( UNode . parse ( appSchema , contentType ) ) ; } catch ( Exception e ) { m_logger . warn ( "Error parsing schema for application '" + appDef . getAppName ( ) + "'; skipped" , e ) ; return null ; } appDef . setTenantName ( tenant . getName ( ) ) ; return appDef ; } | Parse the application schema from the given application row . | 305 | 11 |
18,074 | private ApplicationDefinition getApplicationDefinition ( Tenant tenant , String appName ) { Iterator < DColumn > colIter = DBService . instance ( tenant ) . getAllColumns ( SchemaService . APPS_STORE_NAME , appName ) . iterator ( ) ; if ( ! colIter . hasNext ( ) ) { return null ; } return loadAppRow ( tenant , getColumnMap ( colIter ) ) ; } | Get the given application s application . | 93 | 7 |
18,075 | private Collection < ApplicationDefinition > findAllApplications ( Tenant tenant ) { List < ApplicationDefinition > result = new ArrayList <> ( ) ; Iterator < DRow > rowIter = DBService . instance ( tenant ) . getAllRows ( SchemaService . APPS_STORE_NAME ) . iterator ( ) ; while ( rowIter . hasNext ( ) ) { DRow row = rowIter . next ( ) ; ApplicationDefinition appDef = loadAppRow ( tenant , getColumnMap ( row . getAllColumns ( 1024 ) . iterator ( ) ) ) ; if ( appDef != null ) { result . add ( appDef ) ; } } return result ; } | Get all application definitions for the given Tenant . | 146 | 10 |
18,076 | public SearchResultList objectQuery ( TableDefinition tableDef , OlapQuery olapQuery ) { checkServiceState ( ) ; return m_olap . search ( tableDef . getAppDef ( ) , tableDef . getTableName ( ) , olapQuery ) ; } | Perform an object query on the given table using the given query parameters . | 58 | 15 |
18,077 | public AggregateResult aggregateQuery ( TableDefinition tableDef , OlapAggregate request ) { checkServiceState ( ) ; AggregationResult result = m_olap . aggregate ( tableDef . getAppDef ( ) , tableDef . getTableName ( ) , request ) ; return AggregateResultConverter . create ( result , request ) ; } | Perform an aggregate query on the given table using the given request . | 74 | 14 |
18,078 | public BatchResult addBatch ( ApplicationDefinition appDef , String shardName , OlapBatch batch ) { return addBatch ( appDef , shardName , batch , null ) ; } | Add a batch of updates for the given application to the given shard . Objects can new updated or deleted . | 43 | 22 |
18,079 | public void deleteShard ( ApplicationDefinition appDef , String shard ) { checkServiceState ( ) ; m_olap . deleteShard ( appDef , shard ) ; } | Delete the shard for the given application including all of its data . This method is a no - op if the given shard does not exist or has no data . | 39 | 34 |
18,080 | public UNode getStatistics ( ApplicationDefinition appDef , String shard , Map < String , String > paramMap ) { checkServiceState ( ) ; CubeSearcher searcher = m_olap . getSearcher ( appDef , shard ) ; String file = paramMap . get ( "file" ) ; if ( file != null ) { return OlapStatistics . getFileData ( searcher , file ) ; } String sort = paramMap . get ( "sort" ) ; boolean memStats = ! "false" . equals ( paramMap . get ( "mem" ) ) ; return OlapStatistics . getStatistics ( searcher , sort , memStats ) ; } | Get detailed shard statistics for the given shard . This command is mostly used for development and diagnostics . | 142 | 22 |
18,081 | public Date getExpirationDate ( ApplicationDefinition appDef , String shard ) { checkServiceState ( ) ; return m_olap . getExpirationDate ( appDef , shard ) ; } | Get the expire - date for the given shard name and OLAP application . Null is returned if the shard does not exist or has no expire - date . | 42 | 33 |
18,082 | private boolean getOverwriteOption ( Map < String , String > options ) { boolean bOverwrite = true ; if ( options != null ) { for ( String name : options . keySet ( ) ) { if ( "overwrite" . equals ( name . toLowerCase ( ) ) ) { bOverwrite = Boolean . parseBoolean ( options . get ( name ) ) ; } else { Utils . require ( false , "Unknown OLAP batch option: " + name ) ; } } } return bOverwrite ; } | Get case - insensitive overwrite option . Default to true . | 111 | 11 |
18,083 | private void validateApplication ( ApplicationDefinition appDef ) { boolean bSawAgingFreq = false ; for ( String optName : appDef . getOptionNames ( ) ) { String optValue = appDef . getOption ( optName ) ; switch ( optName ) { case CommonDefs . OPT_STORAGE_SERVICE : assert optValue . equals ( this . getClass ( ) . getSimpleName ( ) ) ; break ; case CommonDefs . OPT_AGING_CHECK_FREQ : new TaskFrequency ( optValue ) ; bSawAgingFreq = true ; break ; case "auto-merge" : new TaskFrequency ( optValue ) ; break ; default : throw new IllegalArgumentException ( "Unknown option for OLAPService application: " + optName ) ; } } for ( TableDefinition tableDef : appDef . getTableDefinitions ( ) . values ( ) ) { validateTable ( tableDef ) ; } if ( ! bSawAgingFreq ) { appDef . setOption ( CommonDefs . OPT_AGING_CHECK_FREQ , "1 DAY" ) ; } } | Validate the given application for OLAP constraints . | 247 | 10 |
18,084 | private void validateTable ( TableDefinition tableDef ) { // No options are currently allowed: for ( String optName : tableDef . getOptionNames ( ) ) { Utils . require ( false , "Unknown option for OLAPService table: " + optName ) ; } for ( FieldDefinition fieldDef : tableDef . getFieldDefinitions ( ) ) { validateField ( fieldDef ) ; } } | Validate the given table for OLAP constraints . | 84 | 10 |
18,085 | public Collection < String > getKeyspaces ( DBConn dbConn ) { List < String > result = new ArrayList <> ( ) ; try { for ( KsDef ksDef : dbConn . getClientSession ( ) . describe_keyspaces ( ) ) { result . add ( ksDef . getName ( ) ) ; } } catch ( Exception e ) { String errMsg = "Failed to get keyspace description" ; m_logger . error ( errMsg , e ) ; throw new RuntimeException ( errMsg , e ) ; } return result ; } | Get a list of all known keyspaces . This method can be used with any DB connection . | 124 | 19 |
18,086 | public void createKeyspace ( DBConn dbConn , String keyspace ) { m_logger . info ( "Creating Keyspace '{}'" , keyspace ) ; try { KsDef ksDef = setKeySpaceOptions ( keyspace ) ; dbConn . getClientSession ( ) . system_add_keyspace ( ksDef ) ; waitForSchemaPropagation ( dbConn ) ; Thread . sleep ( 1000 ) ; // wait for gossip to other Cassandra nodes } catch ( Exception ex ) { String errMsg = "Failed to create Keyspace '" + keyspace + "'" ; m_logger . error ( errMsg , ex ) ; throw new RuntimeException ( errMsg , ex ) ; } } | Create a new keyspace with the given name . The keyspace is created with parameters defined for our DBService instance if any . This method should be used with a no - keyspace DB connection . | 157 | 42 |
18,087 | public boolean keyspaceExists ( DBConn dbConn , String keyspace ) { try { dbConn . getClientSession ( ) . describe_keyspace ( keyspace ) ; return true ; } catch ( Exception e ) { return false ; // Notfound } } | Return true if a keyspace with the given name exists . This method can be used with any DB connection . | 57 | 22 |
18,088 | public void dropKeyspace ( DBConn dbConn , String keyspace ) { m_logger . info ( "Deleting Keyspace '{}'" , keyspace ) ; try { dbConn . getClientSession ( ) . system_drop_keyspace ( keyspace ) ; waitForSchemaPropagation ( dbConn ) ; } catch ( Exception ex ) { String errMsg = "Failed to delete Keyspace '" + keyspace + "'" ; m_logger . error ( errMsg , ex ) ; throw new RuntimeException ( errMsg , ex ) ; } } | Delete the keyspace with the given name . This method can use any DB connection . | 127 | 17 |
18,089 | public void createColumnFamily ( DBConn dbConn , String keyspace , String cfName , boolean bBinaryValues ) { m_logger . info ( "Creating ColumnFamily: {}:{}" , keyspace , cfName ) ; CfDef cfDef = new CfDef ( ) ; cfDef . setKeyspace ( keyspace ) ; cfDef . setName ( cfName ) ; cfDef . setColumn_type ( "Standard" ) ; cfDef . setComparator_type ( "UTF8Type" ) ; cfDef . setKey_validation_class ( "UTF8Type" ) ; if ( bBinaryValues ) { cfDef . setDefault_validation_class ( "BytesType" ) ; } else { cfDef . setDefault_validation_class ( "UTF8Type" ) ; } Map < String , Object > cfOptions = m_service . getParamMap ( "cf_defaults" ) ; if ( cfOptions != null ) { for ( String optName : cfOptions . keySet ( ) ) { Object optValue = cfOptions . get ( optName ) ; CfDef . _Fields fieldEnum = CfDef . _Fields . findByName ( optName ) ; if ( fieldEnum == null ) { m_logger . warn ( "Unknown ColumnFamily option: {}" , optName ) ; continue ; } try { cfDef . setFieldValue ( fieldEnum , optValue ) ; } catch ( Exception e ) { m_logger . warn ( "Error setting ColumnFamily option '" + optName + "' to '" + optValue + "' -- ignoring" , e ) ; } } } // In a multi-node startup, multiple nodes may be trying to create the same CF. for ( int attempt = 1 ; ! columnFamilyExists ( dbConn , keyspace , cfName ) ; attempt ++ ) { try { dbConn . getClientSession ( ) . system_add_column_family ( cfDef ) ; waitForSchemaPropagation ( dbConn ) ; } catch ( Exception ex ) { if ( attempt > m_service . getParamInt ( "max_commit_attempts" , 10 ) ) { String msg = String . format ( "%d attempts to create ColumnFamily %s:%s failed" , attempt , keyspace , cfName ) ; throw new RuntimeException ( msg , ex ) ; } try { Thread . sleep ( 1000 ) ; } catch ( InterruptedException e ) { } } } } | Create a new ColumnFamily with the given parameters . If the new CF is created successfully wait for all nodes in the cluster to receive the schema change before returning . An exception is thrown if the CF create fails . The current DB connection can be connected to any keyspace . | 535 | 54 |
18,090 | public boolean columnFamilyExists ( DBConn dbConn , String keyspace , String cfName ) { KsDef ksDef = null ; try { ksDef = dbConn . getClientSession ( ) . describe_keyspace ( keyspace ) ; } catch ( Exception ex ) { throw new RuntimeException ( "Failed to get keyspace definition for '" + keyspace + "'" , ex ) ; } List < CfDef > cfDefList = ksDef . getCf_defs ( ) ; for ( CfDef cfDef : cfDefList ) { if ( cfDef . getName ( ) . equals ( cfName ) ) { return true ; } } return false ; } | Return true if the given store name currently exists in the given keyspace . This method can be used with a connection connected to any keyspace . | 150 | 29 |
18,091 | public void deleteColumnFamily ( DBConn dbConn , String cfName ) { m_logger . info ( "Deleting ColumnFamily: {}" , cfName ) ; try { dbConn . getClientSession ( ) . system_drop_column_family ( cfName ) ; waitForSchemaPropagation ( dbConn ) ; } catch ( Exception ex ) { throw new RuntimeException ( "drop_column_family failed" , ex ) ; } } | Delete the column family with the given name . The given DB connection must be connected to the keyspace in which the CF is to be deleted . | 100 | 29 |
18,092 | private KsDef setKeySpaceOptions ( String keyspace ) { KsDef ksDef = new KsDef ( ) ; ksDef . setName ( keyspace ) ; Map < String , Object > ksDefs = m_service . getParamMap ( "ks_defaults" ) ; if ( ksDefs != null ) { for ( String name : ksDefs . keySet ( ) ) { Object value = ksDefs . get ( name ) ; try { KsDef . _Fields field = KsDef . _Fields . findByName ( name ) ; if ( field == null ) { m_logger . warn ( "Unknown KeySpace option: {} -- ignoring" , name ) ; } else { ksDef . setFieldValue ( field , value ) ; } } catch ( Exception e ) { m_logger . warn ( "Error setting Keyspace option '" + name + "' to '" + value + "' -- ignoring" , e ) ; } } } // Legacy support: ReplicationFactor -> replication_factor if ( m_service . getParam ( "ReplicationFactor" ) != null ) { Map < String , String > stratOpts = new HashMap <> ( ) ; stratOpts . put ( "replication_factor" , m_service . getParamString ( "ReplicationFactor" ) ) ; ksDef . setStrategy_options ( stratOpts ) ; } // required: strategy_class, strategy_options, replication_factor, cf_defs, durable_writes if ( ! ksDef . isSetStrategy_class ( ) ) { ksDef . setStrategy_class ( DEFAULT_KS_STRATEGY_CLASS ) ; } if ( ! ksDef . isSetStrategy_options ( ) ) { Map < String , String > stratOpts = new HashMap <> ( ) ; stratOpts . put ( "replication_factor" , DEFAULT_KS_REPLICATION_FACTOR ) ; ksDef . setStrategy_options ( stratOpts ) ; } if ( ! ksDef . isSetCf_defs ( ) ) { ksDef . setCf_defs ( DEFAULT_KS_CF_DEFS ) ; } if ( ! ksDef . isSetDurable_writes ( ) ) { ksDef . setDurable_writes ( DEFAULT_KS_DURABLE_WRITES ) ; } return ksDef ; } | Build KsDef from doradus . yaml and DBService - specific options . | 545 | 21 |
18,093 | private void waitForSchemaPropagation ( DBConn dbConn ) { for ( int i = 0 ; i < 5 ; i ++ ) { try { Map < String , List < String > > versions = dbConn . getClientSession ( ) . describe_schema_versions ( ) ; if ( versions . size ( ) <= 1 ) return ; m_logger . info ( "Schema versions are not synchronized yet. Retrying" ) ; Thread . sleep ( 500 + 1000 * i ) ; } catch ( Exception ex ) { m_logger . warn ( "Error waiting for schema propagation: {}" , ex . getMessage ( ) ) ; } m_logger . error ( "Schema versions have not been synchronized" ) ; } } | This method waits until all the nodes have the same schema | 161 | 11 |
18,094 | public static OutputStream outputStream ( File file ) { try { return new FileOutputStream ( file ) ; } catch ( FileNotFoundException e ) { throw E . ioException ( e ) ; } } | Returns a file output stream | 43 | 5 |
18,095 | public static Writer writer ( File file ) { try { return new FileWriter ( file ) ; } catch ( IOException e ) { throw E . ioException ( e ) ; } } | Returns a file writer | 38 | 4 |
18,096 | public static InputStream inputStream ( File file ) { // workaround http://stackoverflow.com/questions/36880692/java-file-does-not-exists-but-file-getabsolutefile-exists if ( ! file . exists ( ) ) { file = file . getAbsoluteFile ( ) ; } if ( ! file . exists ( ) ) { throw E . ioException ( "File does not exists: %s" , file . getPath ( ) ) ; } try { return new FileInputStream ( file ) ; } catch ( FileNotFoundException e ) { throw E . ioException ( e ) ; } } | Returns a file input stream | 141 | 5 |
18,097 | public static InputStream inputStream ( URL url ) { try { return url . openStream ( ) ; } catch ( IOException e ) { throw E . ioException ( e ) ; } } | Create an input stream from a URL . | 40 | 8 |
18,098 | public static Reader reader ( File file ) { E . illegalArgumentIfNot ( file . canRead ( ) , "file not readable: " + file . getPath ( ) ) ; try { return new FileReader ( file ) ; } catch ( IOException e ) { throw E . ioException ( e ) ; } } | Returns a file reader | 68 | 4 |
18,099 | public static String checksum ( InputStream is ) { try { MessageDigest md = MessageDigest . getInstance ( "SHA1" ) ; byte [ ] dataBytes = new byte [ 1024 ] ; int nread ; while ( ( nread = is . read ( dataBytes ) ) != - 1 ) { md . update ( dataBytes , 0 , nread ) ; } byte [ ] mdbytes = md . digest ( ) ; S . Buffer sb = S . buffer ( ) ; for ( int i = 0 ; i < mdbytes . length ; i ++ ) { sb . append ( Integer . toString ( ( mdbytes [ i ] & 0xff ) + 0x100 , 16 ) . substring ( 1 ) ) ; } return sb . toString ( ) ; } catch ( NoSuchAlgorithmException e ) { throw E . unexpected ( "SHA1 algorithm not found" ) ; } catch ( IOException e ) { throw E . ioException ( e ) ; } } | Returns checksum from an input stream . | 211 | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.