idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
17,700
private void loadCSVFile ( TableDefinition tableDef , File file ) throws IOException { try ( BufferedReader reader = new BufferedReader ( new InputStreamReader ( new FileInputStream ( file ) , Utils . UTF8_CHARSET ) ) ) { loadCSVFromReader ( tableDef , file . getAbsolutePath ( ) , file . length ( ) , reader ) ; } }
Load the records in the given file into the given table .
17,701
private void loadFolder ( File folder ) { m_logger . info ( "Scanning for files in folder: {}" , folder . getAbsolutePath ( ) ) ; File [ ] files = folder . listFiles ( ) ; if ( files == null || files . length == 0 ) { m_logger . error ( "No files found in folder: {}" , folder . getAbsolutePath ( ) ) ; return ; } for ( File file : files ) { String fileName = file . getName ( ) . toLowerCase ( ) ; if ( ! fileName . endsWith ( ".csv" ) && ! fileName . endsWith ( ".zip" ) ) { continue ; } TableDefinition tableDef = determineTableFromFileName ( file . getName ( ) ) ; if ( tableDef == null ) { m_logger . error ( "Ignoring file; unknown corresponding table: {}" , file . getName ( ) ) ; continue ; } try { if ( fileName . endsWith ( ".csv" ) ) { loadCSVFile ( tableDef , file ) ; } else { loadZIPFile ( tableDef , file ) ; } } catch ( IOException ex ) { m_logger . error ( "I/O error scanning file '{}': {}" , file . getName ( ) , ex ) ; } } }
Load all files in the given folder whose name matches a known table .
17,702
private void openDatabase ( ) { m_client = new Client ( m_config . host , m_config . port , m_config . getTLSParams ( ) ) ; m_client . setCredentials ( m_config . getCredentials ( ) ) ; }
Open Doradus database setting m_client .
17,703
private void parseArgs ( String [ ] args ) { int index = 0 ; while ( index < args . length ) { String name = args [ index ] ; if ( name . equals ( "-?" ) || name . equalsIgnoreCase ( "-help" ) ) { usage ( ) ; } if ( name . charAt ( 0 ) != '-' ) { m_logger . error ( "Unrecognized parameter: {}" , name ) ; usage ( ) ; } if ( ++ index >= args . length ) { m_logger . error ( "Another parameter expected after '{}'" , name ) ; usage ( ) ; } String value = args [ index ] ; try { m_config . set ( name . substring ( 1 ) , value ) ; } catch ( Exception e ) { m_logger . error ( e . toString ( ) ) ; usage ( ) ; } index ++ ; } }
Parse args into CSVConfig object .
17,704
private void loadCSVFromReader ( TableDefinition tableDef , String csvName , long byteLength , BufferedReader reader ) { m_logger . info ( "Loading CSV file: {}" , csvName ) ; List < String > fieldList = getFieldListFromHeader ( reader ) ; CSVFile csvFile = new CSVFile ( csvName , tableDef , fieldList ) ; long startTime = System . currentTimeMillis ( ) ; long recsLoaded = 0 ; int lineNo = 0 ; while ( true ) { Map < String , String > fieldMap = new HashMap < String , String > ( ) ; if ( ! tokenizeCSVLine ( csvFile , reader , fieldMap ) ) { break ; } lineNo ++ ; m_totalLines ++ ; try { m_workerQueue . put ( new Record ( csvFile , fieldMap ) ) ; } catch ( InterruptedException e ) { logErrorThrow ( "Error posting to queue" , e . toString ( ) ) ; } if ( ( ++ recsLoaded % 10000 ) == 0 ) { m_logger . info ( "...loaded {} records." , recsLoaded ) ; } } m_totalFiles ++ ; m_totalBytes += byteLength ; long stopTime = System . currentTimeMillis ( ) ; long totalMillis = stopTime - startTime ; if ( totalMillis == 0 ) { totalMillis = 1 ; } m_logger . info ( "File '{}': time={} millis; lines={}" , new Object [ ] { csvFile . m_fileName , totalMillis , lineNo } ) ; }
CSVFile . The caller must pass an opened stream and close it .
17,705
private void startWorkers ( ) { m_logger . info ( "Starting {} workers" , m_config . workers ) ; for ( int workerNo = 1 ; workerNo <= m_config . workers ; workerNo ++ ) { LoadWorker loadWorker = new LoadWorker ( workerNo ) ; loadWorker . start ( ) ; m_workerList . add ( loadWorker ) ; } }
Launch the requested number of workers . Quit if any can t be started .
17,706
private void stopWorkers ( ) { Record sentinel = Record . SENTINEL ; for ( int inx = 0 ; inx < m_workerList . size ( ) ; inx ++ ) { try { m_workerQueue . put ( sentinel ) ; } catch ( InterruptedException e ) { } } for ( LoadWorker loadWorker : m_workerList ) { try { loadWorker . join ( ) ; } catch ( InterruptedException e ) { } } }
Add a sentinel to the queue for each worker and wait all to finish .
17,707
private boolean tokenizeCSVLine ( CSVFile csvFile , BufferedReader reader , Map < String , String > fieldMap ) { fieldMap . clear ( ) ; m_token . setLength ( 0 ) ; List < String > tokenList = new ArrayList < String > ( ) ; boolean bInQuote = false ; int aChar = 0 ; try { while ( true ) { aChar = reader . read ( ) ; if ( aChar < 0 ) { break ; } if ( ! bInQuote && aChar == ',' ) { tokenList . add ( m_token . toString ( ) ) ; m_token . setLength ( 0 ) ; } else if ( ! bInQuote && aChar == '\r' ) { tokenList . add ( m_token . toString ( ) ) ; m_token . setLength ( 0 ) ; reader . mark ( 1 ) ; aChar = reader . read ( ) ; if ( aChar == - 1 ) { break ; } if ( aChar != '\n' ) { reader . reset ( ) ; } break ; } else if ( ! bInQuote && aChar == '\n' ) { tokenList . add ( m_token . toString ( ) ) ; m_token . setLength ( 0 ) ; break ; } else if ( aChar == '"' ) { bInQuote = ! bInQuote ; } else { m_token . append ( ( char ) aChar ) ; } } } catch ( IOException e ) { logErrorThrow ( "I/O error reading file" , e . toString ( ) ) ; } if ( m_token . length ( ) > 0 ) { tokenList . add ( m_token . toString ( ) ) ; m_token . setLength ( 0 ) ; } if ( tokenList . size ( ) > 0 ) { for ( int index = 0 ; index < tokenList . size ( ) ; index ++ ) { String token = tokenList . get ( index ) . trim ( ) ; if ( token . length ( ) > 0 ) { String fieldName = csvFile . m_fieldList . get ( index ) ; fieldMap . put ( fieldName , token ) ; } } return true ; } return aChar != - 1 ; }
into the given field map .
17,708
private void logErrorThrow ( String format , Object ... args ) { String msg = MessageFormatter . arrayFormat ( format , args ) . getMessage ( ) ; m_logger . error ( msg ) ; throw new RuntimeException ( msg ) ; }
a RuntimeException .
17,709
private void validateRootFolder ( ) { File rootDir = new File ( m_config . root ) ; if ( ! rootDir . exists ( ) ) { logErrorThrow ( "Root directory does not exist: {}" , m_config . root ) ; } else if ( ! rootDir . isDirectory ( ) ) { logErrorThrow ( "Root directory must be a folder: {}" , m_config . root ) ; } else if ( ! m_config . root . endsWith ( File . separator ) ) { m_config . root = m_config . root + File . separator ; } }
Root directory must exist and be a folder
17,710
public void add ( long value ) { int index = Arrays . binarySearch ( bins , value ) ; if ( index < 0 ) { index = - index - 1 ; } hits . incrementAndGet ( index ) ; }
Increments the hits in interval containing given value rounding UP .
17,711
public long getMean ( ) { int n = bins . length ; if ( hits . get ( n ) > 0 ) { return Long . MAX_VALUE ; } long cnt = 0 ; long sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { cnt += hits . get ( i ) ; sum += hits . get ( i ) * bins [ i ] ; } return ( long ) Math . ceil ( ( double ) sum / cnt ) ; }
The mean histogram value . If the histogram overflowed returns Long . MAX_VALUE .
17,712
public long getMin ( ) { for ( int i = 0 ; i < hits . length ( ) ; i ++ ) { if ( hits . get ( i ) > 0 ) { return i == 0 ? 0 : 1 + bins [ i - 1 ] ; } } return 0 ; }
The starting point of interval that contains the smallest value added to this histogram .
17,713
public long getMax ( ) { int lastBin = hits . length ( ) - 1 ; if ( hits . get ( lastBin ) > 0 ) { return Long . MAX_VALUE ; } for ( int i = lastBin - 1 ; i >= 0 ; i -- ) { if ( hits . get ( i ) > 0 ) { return bins [ i ] ; } } return 0 ; }
The end - point of interval that contains the largest value added to this histogram . If the histogram overflowed returns Long . MAX_VALUE .
17,714
public IntervalHistogram snapshot ( boolean reset ) { if ( reset ) { return new IntervalHistogram ( bins , getAndResetHits ( ) ) ; } return new IntervalHistogram ( bins , getHits ( ) ) ; }
Clones this histogram and zeroizes out hits afterwards if the reset is true .
17,715
@ SuppressWarnings ( "unchecked" ) public Map < String , Object > getOptionMap ( String optName ) { Object optValue = m_options . get ( optName ) ; if ( optValue == null ) { return null ; } if ( ! ( optValue instanceof Map ) ) { throw new IllegalArgumentException ( "Tenant option '" + optName + "' should be a map: " + optValue ) ; } return ( Map < String , Object > ) optValue ; }
Get the value of the option with the given name as a Map . If the option is not defined null is returned . If the option value is not a Map an IllegalArgumentException is thrown .
17,716
@ SuppressWarnings ( "unchecked" ) private UNode optionValueToUNode ( String optName , Object optValue ) { if ( ! ( optValue instanceof Map ) ) { if ( optValue == null ) { optValue = "" ; } return UNode . createValueNode ( optName , optValue . toString ( ) , "option" ) ; } UNode optNode = UNode . createMapNode ( optName , "option" ) ; Map < String , Object > suboptMap = ( Map < String , Object > ) optValue ; for ( String suboptName : suboptMap . keySet ( ) ) { optNode . addChildNode ( optionValueToUNode ( suboptName , suboptMap . get ( suboptName ) ) ) ; } return optNode ; }
Return a UNode that represents the given option s serialized value .
17,717
public void setOption ( String optName , Object optValue ) { if ( optValue == null ) { m_options . remove ( optName ) ; } else { m_options . put ( optName , optValue ) ; } }
Set the given option . If the option was previously defined the value is overwritten . If the given value is null the existing option is removed .
17,718
public void parse ( UNode tenantNode ) { assert tenantNode != null ; m_name = tenantNode . getName ( ) ; for ( String childName : tenantNode . getMemberNames ( ) ) { UNode childNode = tenantNode . getMember ( childName ) ; switch ( childNode . getName ( ) ) { case "options" : for ( UNode optNode : childNode . getMemberList ( ) ) { m_options . put ( optNode . getName ( ) , parseOption ( optNode ) ) ; } break ; case "users" : for ( UNode userNode : childNode . getMemberList ( ) ) { UserDefinition userDef = new UserDefinition ( ) ; userDef . parse ( userNode ) ; m_users . put ( userDef . getID ( ) , userDef ) ; } break ; case "properties" : for ( UNode propNode : childNode . getMemberList ( ) ) { Utils . require ( propNode . isValue ( ) , "'property' must be a value: " + propNode ) ; m_properties . put ( propNode . getName ( ) , propNode . getValue ( ) ) ; } break ; default : Utils . require ( false , "Unknown tenant property: " + childNode ) ; } } }
Parse the tenant definition rooted at given UNode tree and update this object to match . The root node is the tenant object so its name is the tenant name and its child nodes are tenant definitions such as users and options . An exception is thrown if the definition contains an error .
17,719
private Object parseOption ( UNode optionNode ) { if ( optionNode . isValue ( ) ) { return optionNode . getValue ( ) ; } Map < String , Object > optValueMap = new HashMap < > ( ) ; for ( UNode suboptNode : optionNode . getMemberList ( ) ) { optValueMap . put ( suboptNode . getName ( ) , parseOption ( suboptNode ) ) ; } return optValueMap ; }
Parse an option UNode which may be a value or a map .
17,720
@ SuppressWarnings ( "unchecked" ) public static ServerConfig load ( String [ ] args ) throws ConfigurationException { if ( config != null ) { logger . warn ( "Configuration is loaded already. Use ServerConfig.getInstance() method. " ) ; return config ; } try { URL url = getConfigUrl ( ) ; logger . info ( "Trying to load settings from: " + url ) ; InputStream input = null ; try { input = url . openStream ( ) ; } catch ( IOException e ) { throw new AssertionError ( e ) ; } Yaml yaml = new Yaml ( ) ; LinkedHashMap < String , ? > dataColl = ( LinkedHashMap < String , ? > ) yaml . load ( input ) ; config = new ServerConfig ( ) ; setParams ( dataColl ) ; logger . info ( "Ok. Configuration loaded." ) ; } catch ( ConfigurationException e ) { logger . warn ( e . getMessage ( ) + " -- Ignoring." ) ; } catch ( YAMLException e ) { logger . warn ( e . getMessage ( ) + " -- Ignoring." ) ; } if ( config == null ) { logger . info ( "Initializing configuration by default settings." ) ; config = new ServerConfig ( ) ; } try { if ( args != null && args . length > 0 ) { logger . info ( "Parsing the command line arguments..." ) ; parseCommandLineArgs ( args ) ; logger . info ( "Ok. Arguments parsed." ) ; } } catch ( ConfigurationException e ) { logger . error ( "Fatal configuration error" , e ) ; System . err . println ( e . getMessage ( ) + "\nFatal configuration error. Unable to start server. See log for stacktrace." ) ; throw e ; } if ( ! Utils . isEmpty ( config . param_override_filename ) ) { try { InputStream overrideFile = new FileInputStream ( config . param_override_filename ) ; Yaml yaml = new Yaml ( ) ; LinkedHashMap < String , ? > overrideColl = ( LinkedHashMap < String , ? > ) yaml . load ( overrideFile ) ; setParams ( overrideColl ) ; } catch ( Exception e ) { logger . warn ( e . getMessage ( ) + " -- Ignoring." ) ; } } return config ; }
Creates and initializes the ServerConfig singleton .
17,721
private static void setCollectionParam ( String name , List < ? > values ) throws ConfigurationException { try { Field field = config . getClass ( ) . getDeclaredField ( name ) ; Class < ? > fieldClass = field . getType ( ) ; if ( Map . class . isAssignableFrom ( fieldClass ) ) { setMapParam ( field , values ) ; } else if ( List . class . isAssignableFrom ( fieldClass ) ) { setListParam ( field , values ) ; } else { throw new ConfigurationException ( "Invalid value type for parameter: " + name ) ; } } catch ( SecurityException | NoSuchFieldException e ) { throw new ConfigurationException ( "Unknown configuration parameter: " + name ) ; } }
Set a configuration parameter with a Collection type .
17,722
public TenantDefinition modifyTenant ( String tenantName , TenantDefinition newTenantDef ) { checkServiceState ( ) ; TenantDefinition oldTenantDef = getTenantDef ( tenantName ) ; Utils . require ( oldTenantDef != null , "Tenant '%s' does not exist" , tenantName ) ; modifyTenantProperties ( oldTenantDef , newTenantDef ) ; validateTenantUsers ( newTenantDef ) ; validateTenantUpdate ( oldTenantDef , newTenantDef ) ; storeTenantDefinition ( newTenantDef ) ; DBManagerService . instance ( ) . updateTenantDef ( newTenantDef ) ; TenantDefinition updatedTenantDef = getTenantDef ( tenantName ) ; if ( updatedTenantDef == null ) { throw new RuntimeException ( "Tenant definition could not be retrieved after creation: " + tenantName ) ; } removeUserHashes ( updatedTenantDef ) ; return updatedTenantDef ; }
Modify the tenant with the given name to match the given definition and return the updated definition .
17,723
public void deleteTenant ( String tenantName , Map < String , String > options ) { checkServiceState ( ) ; TenantDefinition tenantDef = getTenantDef ( tenantName ) ; if ( tenantDef == null ) { return ; } Tenant tenant = new Tenant ( tenantDef ) ; try { DBService . instance ( tenant ) . dropNamespace ( ) ; } catch ( RuntimeException e ) { if ( options == null || ! "true" . equalsIgnoreCase ( options . get ( "ignoreTenantDBNotAvailable" ) ) ) { throw e ; } m_logger . warn ( "Drop namespace skipped for tenant '{}'" , tenantName ) ; } Tenant defaultTenant = getDefaultTenant ( ) ; DBTransaction dbTran = new DBTransaction ( defaultTenant ) ; dbTran . deleteRow ( TENANTS_STORE_NAME , tenantName ) ; DBService . instance ( defaultTenant ) . commit ( dbTran ) ; DBManagerService . instance ( ) . deleteTenantDB ( tenant ) ; }
Delete an existing tenant with the given options . The tenant s keyspace is dropped which deletes all user and system tables and the tenant s users are deleted . The given options are currently used for testing only . This method is a no - op if the given tenant does not exist .
17,724
private void initializeDefaultTenant ( ) { DBService dbService = DBService . instance ( ) ; dbService . createNamespace ( ) ; dbService . createStoreIfAbsent ( SchemaService . APPS_STORE_NAME , false ) ; dbService . createStoreIfAbsent ( TaskManagerService . TASKS_STORE_NAME , false ) ; dbService . createStoreIfAbsent ( TENANTS_STORE_NAME , false ) ; storeInitialDefaultTenantDef ( ) ; }
Ensure that the default tenant and its required metadata tables exist .
17,725
private void modifyTenantProperties ( TenantDefinition oldTenantDef , TenantDefinition newTenantDef ) { newTenantDef . setProperty ( CREATED_ON_PROP , oldTenantDef . getProperty ( CREATED_ON_PROP ) ) ; newTenantDef . setProperty ( MODIFIED_ON_PROP , Utils . formatDate ( new Date ( ) . getTime ( ) ) ) ; }
Set required properties in a new Tenant Definition .
17,726
private void storeInitialDefaultTenantDef ( ) { TenantDefinition tenantDef = getTenantDef ( m_defaultTenantName ) ; if ( tenantDef == null ) { tenantDef = createDefaultTenantDefinition ( ) ; storeTenantDefinition ( tenantDef ) ; } }
Store a tenant definition for the default tenant if one doesn t already exist .
17,727
private void migrateTenantDefinitions ( ) { DBService dbservice = DBService . instance ( ) ; List < String > keyspaces = null ; if ( dbservice instanceof ThriftService ) { keyspaces = ( ( ThriftService ) dbservice ) . getDoradusKeyspaces ( ) ; } else if ( dbservice instanceof CQLService ) { keyspaces = ( ( CQLService ) dbservice ) . getDoradusKeyspaces ( ) ; } else { return ; } for ( String keyspace : keyspaces ) { migrateTenantDefinition ( keyspace ) ; } }
default database .
17,728
private void migrateTenantDefinition ( String keyspace ) { TenantDefinition tempTenantDef = new TenantDefinition ( ) ; tempTenantDef . setName ( keyspace ) ; Tenant migratingTenant = new Tenant ( tempTenantDef ) ; DColumn col = DBService . instance ( migratingTenant ) . getColumn ( "Applications" , "_tenant" , "Definition" ) ; if ( col == null ) { return ; } m_logger . info ( "Migrating tenant definition from keyspace {}" , keyspace ) ; TenantDefinition migratingTenantDef = new TenantDefinition ( ) ; try { migratingTenantDef . parse ( UNode . parseJSON ( col . getValue ( ) ) ) ; } catch ( Exception e ) { m_logger . warn ( "Couldn't parse tenant definition; skipping migration of keyspace: " + keyspace , e ) ; return ; } storeTenantDefinition ( migratingTenantDef ) ; DBTransaction dbTran = new DBTransaction ( migratingTenant ) ; dbTran . deleteRow ( "Applications" , "_tenant" ) ; DBService . instance ( migratingTenant ) . commit ( dbTran ) ; }
Migrate legacy _tenant row if it exists to the Tenants table .
17,729
private void defineNewTenant ( TenantDefinition tenantDef ) { validateTenantUsers ( tenantDef ) ; addTenantOptions ( tenantDef ) ; addTenantProperties ( tenantDef ) ; Tenant tenant = new Tenant ( tenantDef ) ; DBService dbService = DBService . instance ( tenant ) ; dbService . createNamespace ( ) ; initializeTenantStores ( tenant ) ; storeTenantDefinition ( tenantDef ) ; }
Define a new tenant
17,730
private void initializeTenantStores ( Tenant tenant ) { DBService . instance ( tenant ) . createStoreIfAbsent ( SchemaService . APPS_STORE_NAME , false ) ; DBService . instance ( tenant ) . createStoreIfAbsent ( TaskManagerService . TASKS_STORE_NAME , false ) ; }
Ensure required tenant stores exist .
17,731
private void addTenantOptions ( TenantDefinition tenantDef ) { if ( tenantDef . getOption ( "namespace" ) == null ) { tenantDef . setOption ( "namespace" , tenantDef . getName ( ) ) ; } }
By default each tenant s namespace is the same as their tenant name .
17,732
private void addTenantProperties ( TenantDefinition tenantDef ) { tenantDef . setProperty ( CREATED_ON_PROP , Utils . formatDate ( new Date ( ) . getTime ( ) ) ) ; tenantDef . setProperty ( MODIFIED_ON_PROP , tenantDef . getProperty ( CREATED_ON_PROP ) ) ; }
Set system - defined properties for a new tenant .
17,733
private void validateTenantUsers ( TenantDefinition tenantDef ) { for ( UserDefinition userDef : tenantDef . getUsers ( ) . values ( ) ) { Utils . require ( ! Utils . isEmpty ( userDef . getPassword ( ) ) , "Password is required; user ID=" + userDef . getID ( ) ) ; userDef . setHash ( PasswordManager . hash ( userDef . getPassword ( ) ) ) ; userDef . setPassword ( null ) ; } }
hashed format .
17,734
private void storeTenantDefinition ( TenantDefinition tenantDef ) { String tenantDefJSON = tenantDef . toDoc ( ) . toJSON ( ) ; DBTransaction dbTran = DBService . instance ( ) . startTransaction ( ) ; dbTran . addColumn ( TENANTS_STORE_NAME , tenantDef . getName ( ) , TENANT_DEF_COL_NAME , tenantDefJSON ) ; DBService . instance ( ) . commit ( dbTran ) ; }
Store the given tenant definition the Tenants table in the default database .
17,735
private boolean isValidTenantUserAccess ( Tenant tenant , String userid , String password , Permission permNeeded ) { TenantDefinition tenantDef = tenant . getDefinition ( ) ; assert tenantDef != null ; if ( tenantDef . getUsers ( ) . size ( ) == 0 ) { return tenant . getName ( ) . equals ( m_defaultTenantName ) ; } UserDefinition userDef = tenantDef . getUser ( userid ) ; if ( userDef == null || Utils . isEmpty ( password ) ) { return false ; } if ( userDef . getHash ( ) != null ) { if ( ! PasswordManager . checkPassword ( password , userDef . getHash ( ) ) ) { return false ; } } else { if ( ! password . equals ( userDef . getPassword ( ) ) ) { return false ; } } return isValidUserAccess ( userDef , permNeeded ) ; }
Validate the given user ID and password .
17,736
private boolean isValidUserAccess ( UserDefinition userDef , Permission permNeeded ) { Set < Permission > permList = userDef . getPermissions ( ) ; if ( permList . size ( ) == 0 || permList . contains ( Permission . ALL ) ) { return true ; } switch ( permNeeded ) { case APPEND : return permList . contains ( Permission . APPEND ) || permList . contains ( Permission . UPDATE ) ; case READ : return permList . contains ( Permission . READ ) ; case UPDATE : return permList . contains ( Permission . UPDATE ) ; default : return false ; } }
Validate user s permission vs . the given required permission .
17,737
private TenantDefinition getTenantDef ( String tenantName ) { DRow tenantDefRow = DBService . instance ( ) . getRow ( TENANTS_STORE_NAME , tenantName ) ; if ( tenantDefRow == null ) { return null ; } return loadTenantDefinition ( tenantDefRow ) ; }
Get the TenantDefinition for the given tenant . Return null if unknown .
17,738
private Map < String , TenantDefinition > getAllTenantDefs ( ) { Map < String , TenantDefinition > tenantMap = new HashMap < > ( ) ; Iterable < DRow > rowIter = DBService . instance ( ) . getAllRows ( TENANTS_STORE_NAME ) ; for ( DRow row : rowIter ) { TenantDefinition tenantDef = loadTenantDefinition ( row ) ; if ( tenantDef != null ) { tenantMap . put ( tenantDef . getName ( ) , tenantDef ) ; } } return tenantMap ; }
Get all tenants including the default tenant .
17,739
private TenantDefinition loadTenantDefinition ( DRow tenantDefRow ) { String tenantName = tenantDefRow . getKey ( ) ; m_logger . debug ( "Loading definition for tenant: {}" , tenantName ) ; DColumn tenantDefCol = tenantDefRow . getColumn ( TENANT_DEF_COL_NAME ) ; if ( tenantDefCol == null ) { return null ; } String tenantDefJSON = tenantDefCol . getValue ( ) ; TenantDefinition tenantDef = new TenantDefinition ( ) ; try { tenantDef . parse ( UNode . parseJSON ( tenantDefJSON ) ) ; Utils . require ( tenantDef . getName ( ) . equals ( tenantName ) , "Tenant definition (%s) did not match row name (%s)" , tenantDef . getName ( ) , tenantName ) ; } catch ( Exception e ) { m_logger . warn ( "Skipping malformed tenant definition; tenant=" + tenantName , e ) ; return null ; } return tenantDef ; }
Load a TenantDefinition from the Applications table .
17,740
private void validateTenantUpdate ( TenantDefinition oldTenantDef , TenantDefinition newTenantDef ) { Utils . require ( oldTenantDef . getName ( ) . equals ( newTenantDef . getName ( ) ) , "Tenant name cannot be changed: %s" , newTenantDef . getName ( ) ) ; Map < String , Object > oldDBServiceOpts = oldTenantDef . getOptionMap ( "DBService" ) ; String oldDBService = oldDBServiceOpts == null ? null : ( String ) oldDBServiceOpts . get ( "dbservice" ) ; Map < String , Object > newDBServiceOpts = newTenantDef . getOptionMap ( "DBService" ) ; String newDBService = newDBServiceOpts == null ? null : ( String ) newDBServiceOpts . get ( "dbservice" ) ; Utils . require ( ( oldDBService == null && newDBService == null ) || oldDBService . equals ( newDBService ) , "'DBService.dbservice' parameter cannot be changed: tenant=%s, previous=%s, new=%s" , newTenantDef . getName ( ) , oldDBService , newDBService ) ; }
Validate that the given modifications are allowed ; throw any transgressions found .
17,741
private void removeUserHashes ( TenantDefinition tenantDef ) { for ( UserDefinition userDef : tenantDef . getUsers ( ) . values ( ) ) { userDef . setHash ( null ) ; } }
Remove hash value from user definitions .
17,742
public void deleteApplication ( ApplicationDefinition appDef ) { checkServiceState ( ) ; deleteApplicationCFs ( appDef ) ; m_shardCache . clear ( appDef ) ; }
Delete all CFs used by the given application .
17,743
public void initializeApplication ( ApplicationDefinition oldAppDef , ApplicationDefinition appDef ) { checkServiceState ( ) ; verifyApplicationCFs ( oldAppDef , appDef ) ; }
Create all CFs needed for the given application .
17,744
private String getDataAgingFreq ( TableDefinition tableDef ) { if ( Utils . isEmpty ( tableDef . getOption ( CommonDefs . OPT_AGING_FIELD ) ) ) { return null ; } String dataAgingFreq = tableDef . getOption ( CommonDefs . OPT_AGING_CHECK_FREQ ) ; if ( ! Utils . isEmpty ( dataAgingFreq ) ) { return dataAgingFreq ; } return tableDef . getAppDef ( ) . getOption ( CommonDefs . OPT_AGING_CHECK_FREQ ) ; }
frequency is defined at either the table or application level .
17,745
public DBObject getObject ( TableDefinition tableDef , String objID ) { checkServiceState ( ) ; String storeName = objectsStoreName ( tableDef ) ; Tenant tenant = Tenant . getTenant ( tableDef ) ; Iterator < DColumn > colIter = DBService . instance ( tenant ) . getAllColumns ( storeName , objID ) . iterator ( ) ; if ( ! colIter . hasNext ( ) ) { return null ; } DBObject dbObj = createObject ( tableDef , objID , colIter ) ; addShardedLinkValues ( tableDef , dbObj ) ; return dbObj ; }
Get all scalar and link fields for the object in the given table with the given ID .
17,746
public AggregateResult aggregateQuery ( TableDefinition tableDef , Aggregate aggParams ) { checkServiceState ( ) ; aggParams . execute ( ) ; return aggParams . getResult ( ) ; }
Perform an aggregate query on the given table using the given query parameters .
17,747
public BatchResult deleteBatch ( TableDefinition tableDef , DBObjectBatch batch ) { checkServiceState ( ) ; List < String > objIDs = new ArrayList < > ( ) ; for ( DBObject dbObj : batch . getObjects ( ) ) { Utils . require ( ! Utils . isEmpty ( dbObj . getObjectID ( ) ) , "All objects must have _ID defined" ) ; objIDs . add ( dbObj . getObjectID ( ) ) ; } BatchObjectUpdater batchUpdater = new BatchObjectUpdater ( tableDef ) ; return batchUpdater . deleteBatch ( objIDs ) ; }
Delete a batch of objects from the given table . All objects must have an ID assigned . Deleting an already - deleted object is a no - op .
17,748
public static String termIndexRowKey ( TableDefinition tableDef , DBObject dbObj , String fieldName , String term ) { StringBuilder termRecKey = new StringBuilder ( ) ; int shardNumber = tableDef . getShardNumber ( dbObj ) ; if ( shardNumber > 0 ) { termRecKey . append ( shardNumber ) ; termRecKey . append ( "/" ) ; } termRecKey . append ( FieldAnalyzer . makeTermKey ( fieldName , term ) ) ; return termRecKey . toString ( ) ; }
Create the Terms row key for the given table object field name and term .
17,749
public void verifyShard ( TableDefinition tableDef , int shardNumber ) { assert tableDef . isSharded ( ) ; assert shardNumber > 0 ; checkServiceState ( ) ; m_shardCache . verifyShard ( tableDef , shardNumber ) ; }
Get the starting date of the shard with the given number in the given sharded table . If the given table has not yet started the given shard null is returned .
17,750
public Map < Integer , Date > getShards ( TableDefinition tableDef ) { checkServiceState ( ) ; if ( tableDef . isSharded ( ) ) { return m_shardCache . getShardMap ( tableDef ) ; } else { return new HashMap < > ( ) ; } }
Get all known shards for the given table . Each shard is defined in a column in the _shards row of the table s Terms store . If the given table is not sharded an empty map is returned .
17,751
private TableDefinition addAutoTable ( ApplicationDefinition appDef , String tableName ) { m_logger . debug ( "Adding implicit table '{}' to application '{}'" , tableName , appDef . getAppName ( ) ) ; Tenant tenant = Tenant . getTenant ( appDef ) ; TableDefinition tableDef = new TableDefinition ( appDef ) ; tableDef . setTableName ( tableName ) ; appDef . addTable ( tableDef ) ; SchemaService . instance ( ) . defineApplication ( tenant , appDef ) ; appDef = SchemaService . instance ( ) . getApplication ( tenant , appDef . getAppName ( ) ) ; return appDef . getTableDef ( tableName ) ; }
Add an implicit table to the given application and return its new TableDefinition .
17,752
private void addShardedLinkValues ( TableDefinition tableDef , DBObject dbObj ) { for ( FieldDefinition fieldDef : tableDef . getFieldDefinitions ( ) ) { if ( fieldDef . isLinkField ( ) && fieldDef . isSharded ( ) ) { TableDefinition extentTableDef = tableDef . getLinkExtentTableDef ( fieldDef ) ; Set < Integer > shardNums = getShards ( extentTableDef ) . keySet ( ) ; Set < String > values = getShardedLinkValues ( dbObj . getObjectID ( ) , fieldDef , shardNums ) ; dbObj . addFieldValues ( fieldDef . getName ( ) , values ) ; } } }
Add sharded link values if any to the given DBObject .
17,753
private void deleteApplicationCFs ( ApplicationDefinition appDef ) { Tenant tenant = Tenant . getTenant ( appDef ) ; for ( TableDefinition tableDef : appDef . getTableDefinitions ( ) . values ( ) ) { DBService . instance ( tenant ) . deleteStoreIfPresent ( objectsStoreName ( tableDef ) ) ; DBService . instance ( tenant ) . deleteStoreIfPresent ( termsStoreName ( tableDef ) ) ; } }
actually exist in case a previous delete - app failed .
17,754
private Set < String > getShardedLinkValues ( String objID , FieldDefinition linkDef , Set < Integer > shardNums ) { Set < String > values = new HashSet < String > ( ) ; if ( shardNums . size ( ) == 0 ) { return values ; } Set < String > termRowKeys = new HashSet < String > ( ) ; for ( Integer shardNumber : shardNums ) { termRowKeys . add ( shardedLinkTermRowKey ( linkDef , objID , shardNumber ) ) ; } TableDefinition tableDef = linkDef . getTableDef ( ) ; String termStore = termsStoreName ( tableDef ) ; Tenant tenant = Tenant . getTenant ( tableDef ) ; for ( DRow row : DBService . instance ( tenant ) . getRows ( termStore , termRowKeys ) ) { for ( DColumn column : row . getAllColumns ( 1024 ) ) { values . add ( column . getName ( ) ) ; } } return values ; }
Get all target object IDs for the given sharded link .
17,755
private boolean isValidShardDate ( String shardDate ) { try { Utils . dateFromString ( shardDate ) ; return true ; } catch ( IllegalArgumentException ex ) { return false ; } }
is bad just return false .
17,756
private void validateBooleanOption ( String optName , String optValue ) { if ( ! optValue . equalsIgnoreCase ( "true" ) && ! optValue . equalsIgnoreCase ( "false" ) ) { throw new IllegalArgumentException ( "Boolean value expected for '" + optName + "' option: " + optValue ) ; } }
Validate that the given string is a valid Booleab value .
17,757
private void validateField ( FieldDefinition fieldDef ) { Utils . require ( ! fieldDef . isXLinkField ( ) , "Xlink fields are not allowed in Spider applications" ) ; if ( fieldDef . isScalarField ( ) ) { String analyzerName = fieldDef . getAnalyzerName ( ) ; if ( Utils . isEmpty ( analyzerName ) ) { analyzerName = FieldType . getDefaultAnalyzer ( fieldDef . getType ( ) ) ; fieldDef . setAnalyzer ( analyzerName ) ; } FieldAnalyzer . verifyAnalyzer ( fieldDef ) ; } }
Validate the given field against SpiderService - specific constraints .
17,758
private void validateTable ( TableDefinition tableDef ) { for ( String optName : tableDef . getOptionNames ( ) ) { String optValue = tableDef . getOption ( optName ) ; switch ( optName ) { case CommonDefs . OPT_AGING_FIELD : validateTableOptionAgingField ( tableDef , optValue ) ; break ; case CommonDefs . OPT_RETENTION_AGE : validateTableOptionRetentionAge ( tableDef , optValue ) ; break ; case CommonDefs . OPT_SHARDING_FIELD : validateTableOptionShardingField ( tableDef , optValue ) ; break ; case CommonDefs . OPT_SHARDING_GRANULARITY : validateTableOptionShardingGranularity ( tableDef , optValue ) ; break ; case CommonDefs . OPT_SHARDING_START : validateTableOptionShardingStart ( tableDef , optValue ) ; break ; case CommonDefs . OPT_AGING_CHECK_FREQ : validateTableOptionAgingCheckFrequency ( tableDef , optValue ) ; break ; default : Utils . require ( false , "Unknown option for SpiderService table: " + optName ) ; } } for ( FieldDefinition fieldDef : tableDef . getFieldDefinitions ( ) ) { validateField ( fieldDef ) ; } if ( tableDef . getOption ( CommonDefs . OPT_AGING_FIELD ) != null && tableDef . getOption ( CommonDefs . OPT_AGING_CHECK_FREQ ) == null ) { String agingCheckFreq = tableDef . getAppDef ( ) . getOption ( CommonDefs . OPT_AGING_CHECK_FREQ ) ; if ( Utils . isEmpty ( agingCheckFreq ) ) { agingCheckFreq = "1 DAY" ; } tableDef . setOption ( CommonDefs . OPT_AGING_CHECK_FREQ , agingCheckFreq ) ; } }
Validate the given table against SpiderService - specific constraints .
17,759
private void validateTableOptionAgingCheckFrequency ( TableDefinition tableDef , String optValue ) { new TaskFrequency ( optValue ) ; Utils . require ( tableDef . getOption ( CommonDefs . OPT_AGING_FIELD ) != null , "Option 'aging-check-frequency' requires option 'aging-field'" ) ; }
Validate the table option aging - check - frequency
17,760
private void validateTableOptionAgingField ( TableDefinition tableDef , String optValue ) { FieldDefinition agingFieldDef = tableDef . getFieldDef ( optValue ) ; Utils . require ( agingFieldDef != null , "Aging field has not been defined: " + optValue ) ; assert agingFieldDef != null ; Utils . require ( agingFieldDef . getType ( ) == FieldType . TIMESTAMP , "Aging field must be a timestamp field: " + optValue ) ; Utils . require ( tableDef . getOption ( CommonDefs . OPT_RETENTION_AGE ) != null , "Option 'aging-field' requires option 'retention-age'" ) ; }
Validate the table option aging - field .
17,761
private void validateTableOptionRetentionAge ( TableDefinition tableDef , String optValue ) { RetentionAge retAge = new RetentionAge ( optValue ) ; optValue = retAge . toString ( ) ; tableDef . setOption ( CommonDefs . OPT_RETENTION_AGE , optValue ) ; Utils . require ( tableDef . getOption ( CommonDefs . OPT_AGING_FIELD ) != null , "Option 'retention-age' requires option 'aging-field'" ) ; }
Validate the table option retention - age .
17,762
private void validateTableOptionShardingField ( TableDefinition tableDef , String optValue ) { FieldDefinition shardingFieldDef = tableDef . getFieldDef ( optValue ) ; Utils . require ( shardingFieldDef != null , "Sharding field has not been defined: " + optValue ) ; assert shardingFieldDef != null ; Utils . require ( shardingFieldDef . getType ( ) == FieldType . TIMESTAMP , "Sharding field must be a timestamp field: " + optValue ) ; Utils . require ( ! shardingFieldDef . isCollection ( ) , "Sharding field cannot be a collection: " + optValue ) ; if ( tableDef . getOption ( CommonDefs . OPT_SHARDING_GRANULARITY ) == null ) { tableDef . setOption ( CommonDefs . OPT_SHARDING_GRANULARITY , "MONTH" ) ; } if ( tableDef . getOption ( CommonDefs . OPT_SHARDING_START ) == null ) { GregorianCalendar startDate = new GregorianCalendar ( Utils . UTC_TIMEZONE ) ; startDate . add ( Calendar . DAY_OF_MONTH , 1 ) ; String startOpt = String . format ( "%04d-%02d-%02d" , startDate . get ( Calendar . YEAR ) , startDate . get ( Calendar . MONTH ) + 1 , startDate . get ( Calendar . DAY_OF_MONTH ) ) ; tableDef . setOption ( CommonDefs . OPT_SHARDING_START , startOpt ) ; } }
Validate the table option sharding - field .
17,763
private void validateTableOptionShardingGranularity ( TableDefinition tableDef , String optValue ) { ShardingGranularity shardingGranularity = ShardingGranularity . fromString ( optValue ) ; Utils . require ( shardingGranularity != null , "Unrecognized 'sharding-granularity' value: " + optValue ) ; Utils . require ( tableDef . getOption ( CommonDefs . OPT_SHARDING_FIELD ) != null , "Option 'sharding-granularity' requires option 'sharding-field'" ) ; }
Validate the table option sharding - granularity .
17,764
private void validateTableOptionShardingStart ( TableDefinition tableDef , String optValue ) { Utils . require ( isValidShardDate ( optValue ) , "'sharding-start' must be YYYY-MM-DD: " + optValue ) ; GregorianCalendar shardingStartDate = new GregorianCalendar ( Utils . UTC_TIMEZONE ) ; shardingStartDate . setTime ( Utils . dateFromString ( optValue ) ) ; Utils . require ( tableDef . getOption ( CommonDefs . OPT_SHARDING_FIELD ) != null , "Option 'sharding-start' requires option 'sharding-field'" ) ; }
Validate the table option sharding - start .
17,765
private void verifyApplicationCFs ( ApplicationDefinition oldAppDef , ApplicationDefinition appDef ) { Tenant tenant = Tenant . getTenant ( appDef ) ; DBService dbService = DBService . instance ( tenant ) ; for ( TableDefinition tableDef : appDef . getTableDefinitions ( ) . values ( ) ) { dbService . createStoreIfAbsent ( objectsStoreName ( tableDef ) , true ) ; dbService . createStoreIfAbsent ( termsStoreName ( tableDef ) , true ) ; } if ( oldAppDef != null ) { for ( TableDefinition oldTableDef : oldAppDef . getTableDefinitions ( ) . values ( ) ) { if ( appDef . getTableDef ( oldTableDef . getTableName ( ) ) == null ) { dbService . deleteStoreIfPresent ( objectsStoreName ( oldTableDef ) ) ; dbService . deleteStoreIfPresent ( termsStoreName ( oldTableDef ) ) ; } } } }
Verify that all ColumnFamilies needed for the given application exist .
17,766
public long getDuration ( ) { Status s = status ; if ( s == Status . READY ) return 0 ; if ( s == Status . RUNNING ) return System . currentTimeMillis ( ) - startTime ; return finishTime - startTime ; }
The current or final time in milliseconds during which the job either is executed or was executed .
17,767
public synchronized RequestsTracker snapshot ( boolean reset ) { long t = executing . getCount ( ) ; long r = rejected . getCount ( ) ; long f = failed . getCount ( ) ; TimeCounter c = counter . snapshot ( reset ) ; IntervalHistogram h = histogram . snapshot ( reset ) ; if ( reset ) { executing . reset ( ) ; rejected . reset ( ) ; failed . reset ( ) ; succeeded . reset ( ) ; } return new RequestsTracker ( t , r , f , c , h , lastFailureReason , lastRejectReason ) ; }
Clones this tracker and zeroizes out it afterwards if the reset is true .
17,768
public synchronized void reset ( ) { executing . reset ( ) ; rejected . reset ( ) ; failed . reset ( ) ; succeeded . reset ( ) ; counter . reset ( ) ; histogram . reset ( ) ; lastFailureReason = null ; lastRejectReason = null ; }
Zeroizes out this tracker .
17,769
private int getCommonPart ( List < AggregationGroup > groups ) { if ( groups . size ( ) < 2 ) return 0 ; for ( int i = 0 ; i < groups . size ( ) ; i ++ ) { if ( groups . get ( i ) . filter != null ) return 0 ; } int itemsCount = groups . get ( 0 ) . items . size ( ) - 1 ; for ( int i = 1 ; i < groups . size ( ) ; i ++ ) { itemsCount = Math . min ( itemsCount , groups . get ( i ) . items . size ( ) - 1 ) ; } if ( itemsCount <= 0 ) return 0 ; int itemIndex = 0 ; for ( ; itemIndex < itemsCount ; itemIndex ++ ) { boolean eq = true ; AggregationGroupItem item = groups . get ( 0 ) . items . get ( itemIndex ) ; if ( item . xlinkContext != null ) break ; for ( int i = 1 ; i < groups . size ( ) ; i ++ ) { AggregationGroupItem item2 = groups . get ( i ) . items . get ( itemIndex ) ; if ( ! item . equals ( item2 ) || item . xlinkContext != null ) { eq = false ; break ; } } if ( ! eq ) break ; } if ( itemIndex > 0 ) { LOG . info ( "Found common path for groups: " + itemIndex ) ; } return itemIndex ; }
Support for common paths in groups
17,770
public void addLinkValue ( String ownerObjID , FieldDefinition linkDef , String targetObjID ) { addColumn ( SpiderService . objectsStoreName ( linkDef . getTableDef ( ) ) , ownerObjID , SpiderService . linkColumnName ( linkDef , targetObjID ) ) ; }
Add a link value column to the objects store of the given object ID .
17,771
public void addScalarValueColumn ( TableDefinition tableDef , String objID , String fieldName , String fieldValue ) { addColumn ( SpiderService . objectsStoreName ( tableDef ) , objID , fieldName , SpiderService . scalarValueToBinary ( tableDef , fieldName , fieldValue ) ) ; }
Add the column needed to add or replace the given scalar field belonging to the object with the given ID in the given table .
17,772
public void addShardedLinkValue ( String ownerObjID , FieldDefinition linkDef , String targetObjID , int targetShardNo ) { assert linkDef . isSharded ( ) ; assert targetShardNo > 0 ; addColumn ( SpiderService . termsStoreName ( linkDef . getTableDef ( ) ) , SpiderService . shardedLinkTermRowKey ( linkDef , ownerObjID , targetShardNo ) , targetObjID ) ; }
Add a link value column on behalf of the given owner object referencing the given target object ID . This is used when a link is sharded and the owner s shard number is > 0 . The link value column is added to a special term record .
17,773
public void deleteAllObjectsColumn ( TableDefinition tableDef , String objID , int shardNo ) { String rowKey = ALL_OBJECTS_ROW_KEY ; if ( shardNo > 0 ) { rowKey = shardNo + "/" + ALL_OBJECTS_ROW_KEY ; } deleteColumn ( SpiderService . termsStoreName ( tableDef ) , rowKey , objID ) ; }
Delete the all objects column with the given object ID from the given table .
17,774
public void deleteObjectRow ( TableDefinition tableDef , String objID ) { deleteRow ( SpiderService . objectsStoreName ( tableDef ) , objID ) ; }
Delete the primary field storage row for the given object . This usually called when the object is being deleted .
17,775
public void deleteScalarValueColumn ( TableDefinition tableDef , String objID , String fieldName ) { deleteColumn ( SpiderService . objectsStoreName ( tableDef ) , objID , fieldName ) ; }
Delete a scalar value column with the given field name for the given object ID from the given table .
17,776
public void deleteTermIndexColumn ( TableDefinition tableDef , DBObject dbObj , String fieldName , String term ) { deleteColumn ( SpiderService . termsStoreName ( tableDef ) , SpiderService . termIndexRowKey ( tableDef , dbObj , fieldName , term ) , dbObj . getObjectID ( ) ) ; }
Un - index the given term by deleting the Terms column for the given DBObject field name and term .
17,777
public void deleteLinkValue ( String ownerObjID , FieldDefinition linkDef , String targetObjID ) { deleteColumn ( SpiderService . objectsStoreName ( linkDef . getTableDef ( ) ) , ownerObjID , SpiderService . linkColumnName ( linkDef , targetObjID ) ) ; }
Delete a link value column in the object table of the given owning object .
17,778
public void deleteShardedLinkRow ( FieldDefinition linkDef , String owningObjID , int shardNumber ) { assert linkDef . isSharded ( ) ; assert shardNumber > 0 ; deleteRow ( SpiderService . termsStoreName ( linkDef . getTableDef ( ) ) , SpiderService . shardedLinkTermRowKey ( linkDef , owningObjID , shardNumber ) ) ; }
Delete the shard row for the given sharded link and shard number .
17,779
public void deleteShardedLinkValue ( String objID , FieldDefinition linkDef , String targetObjID , int shardNo ) { assert linkDef . isSharded ( ) ; assert shardNo > 0 ; deleteColumn ( SpiderService . termsStoreName ( linkDef . getTableDef ( ) ) , SpiderService . shardedLinkTermRowKey ( linkDef , objID , shardNo ) , targetObjID ) ; }
Delete a link value column in the Terms store for a sharded link .
17,780
private void addColumn ( String storeName , String rowKey , String colName ) { addColumn ( storeName , rowKey , colName , null ) ; }
Add the given column update with a null column value .
17,781
private void addColumn ( String storeName , String rowKey , String colName , byte [ ] colValue ) { Map < String , Map < String , byte [ ] > > rowMap = m_columnAdds . get ( storeName ) ; if ( rowMap == null ) { rowMap = new HashMap < > ( ) ; m_columnAdds . put ( storeName , rowMap ) ; } Map < String , byte [ ] > colMap = rowMap . get ( rowKey ) ; if ( colMap == null ) { colMap = new HashMap < > ( ) ; rowMap . put ( rowKey , colMap ) ; } byte [ ] oldValue = colMap . put ( colName , colValue ) ; if ( oldValue == null ) { m_totalUpdates ++ ; } else if ( ! Arrays . equals ( oldValue , colValue ) ) { m_logger . debug ( "Warning: duplicate column mutation with different value: " + "store={}, row={}, col={}, old={}, new={}" , new Object [ ] { storeName , rowKey , colName , oldValue , colValue } ) ; } }
Add the given column update ; the value may be null .
17,782
private void deleteColumn ( String storeName , String rowKey , String colName ) { Map < String , List < String > > rowMap = m_columnDeletes . get ( storeName ) ; if ( rowMap == null ) { rowMap = new HashMap < > ( ) ; m_columnDeletes . put ( storeName , rowMap ) ; } List < String > colNames = rowMap . get ( rowKey ) ; if ( colNames == null ) { colNames = new ArrayList < > ( ) ; rowMap . put ( rowKey , colNames ) ; } colNames . add ( colName ) ; m_totalUpdates ++ ; }
Add the given column deletion .
17,783
private void deleteColumns ( String storeName , String rowKey , Collection < String > colNames ) { Map < String , List < String > > rowMap = m_columnDeletes . get ( storeName ) ; if ( rowMap == null ) { rowMap = new HashMap < > ( ) ; m_columnDeletes . put ( storeName , rowMap ) ; } List < String > colList = rowMap . get ( rowKey ) ; if ( colList == null ) { colList = new ArrayList < > ( ) ; rowMap . put ( rowKey , colList ) ; } colList . addAll ( colNames ) ; m_totalUpdates += colNames . size ( ) ; }
Add column deletions for all given column names .
17,784
private void deleteRow ( String storeName , String rowKey ) { List < String > rowKeys = m_rowDeletes . get ( storeName ) ; if ( rowKeys == null ) { rowKeys = new ArrayList < > ( ) ; m_rowDeletes . put ( storeName , rowKeys ) ; } rowKeys . add ( rowKey ) ; m_totalUpdates ++ ; }
Add the following row deletion .
17,785
public static UNode createMapNode ( String name ) { return new UNode ( name , NodeType . MAP , null , false , "" ) ; }
Create a MAP UNode with the given node name .
17,786
public static UNode createArrayNode ( String name ) { return new UNode ( name , NodeType . ARRAY , null , false , "" ) ; }
Create an ARRAY UNode with the given node name .
17,787
public static UNode createValueNode ( String name , String value ) { String nodeValue = value == null ? "" : value ; return new UNode ( name , NodeType . VALUE , nodeValue , false , "" ) ; }
Create a VALUE UNode with the given node name and value .
17,788
public static UNode parse ( String text , ContentType contentType ) throws IllegalArgumentException { UNode result = null ; if ( contentType . isJSON ( ) ) { result = parseJSON ( text ) ; } else if ( contentType . isXML ( ) ) { result = parseXML ( text ) ; } else { Utils . require ( false , "Unsupported content-type: " + contentType ) ; } return result ; }
Parse the given text formatted with the given content - type into a UNode tree and return the root node .
17,789
public static UNode parse ( Reader reader , ContentType contentType ) throws IllegalArgumentException { UNode result = null ; if ( contentType . isJSON ( ) ) { result = parseJSON ( reader ) ; } else if ( contentType . isXML ( ) ) { result = parseXML ( reader ) ; } else { Utils . require ( false , "Unsupported content-type: " + contentType ) ; } return result ; }
Parse the text from the given character reader formatted with the given content - type into a UNode tree and return the root node . The reader is closed when finished .
17,790
public static UNode parseXML ( String text ) throws IllegalArgumentException { assert text != null && text . length ( ) > 0 ; Element rootElem = Utils . parseXMLDocument ( text ) ; return parseXMLElement ( rootElem ) ; }
Parse the given XML text and return the appropriate UNode object . The UNode returned is a MAP whose child nodes are built from the attributes and child elements of the document s root element .
17,791
public static UNode parseXML ( Reader reader ) throws IllegalArgumentException { assert reader != null ; Element rootElem = Utils . parseXMLDocument ( reader ) ; UNode rootNode = parseXMLElement ( rootElem ) ; return rootNode ; }
Parse XML from the given Reader and return the appropriate UNode object . The UNode returned is a MAP whose child nodes are built from the attributes and child elements of the document s root element .
17,792
public UNode getMember ( int index ) { assert isCollection ( ) ; if ( m_children == null || index >= m_children . size ( ) ) { return null ; } return m_children . get ( index ) ; }
Get the child member with the given index . The node must be a MAP or ARRAY . Child members are retained in the order they are added . If the given index is out of bounds null is returned .
17,793
public Iterable < UNode > getMemberList ( ) { assert m_type == NodeType . MAP || m_type == NodeType . ARRAY ; if ( m_children == null ) { m_children = new ArrayList < UNode > ( ) ; } return m_children ; }
Get the list of child nodes of this collection UNode as an Iterable UNode object . The UNode must be a MAP or an ARRAY .
17,794
public String toJSON ( ) { JSONEmitter json = new JSONEmitter ( ) ; json . startDocument ( ) ; toJSON ( json ) ; json . endDocument ( ) ; return json . toString ( ) ; }
Convert the DOM tree rooted at this UNode into a JSON document .
17,795
public String toJSON ( boolean bPretty ) { int indent = bPretty ? 3 : 0 ; JSONEmitter json = new JSONEmitter ( indent ) ; json . startDocument ( ) ; toJSON ( json ) ; json . endDocument ( ) ; return json . toString ( ) ; }
Convert the DOM tree rooted at this UNode into a JSON document . Optionally format the text with indenting to make it look pretty .
17,796
public byte [ ] toCompressedJSON ( ) throws IOException { ByteArrayOutputStream bytesOut = new ByteArrayOutputStream ( ) ; GZIPOutputStream gzipOut = new GZIPOutputStream ( bytesOut ) ; OutputStreamWriter writer = new OutputStreamWriter ( gzipOut , Utils . UTF8_CHARSET ) ; JSONEmitter json = new JSONEmitter ( writer ) ; json . startDocument ( ) ; toJSON ( json ) ; json . endDocument ( ) ; writer . flush ( ) ; gzipOut . finish ( ) ; return bytesOut . toByteArray ( ) ; }
Convert the DOM tree rooted at this UNode into a JSON document compressed with GZIP .
17,797
public String toXML ( boolean bPretty ) throws IllegalArgumentException { int indent = bPretty ? 3 : 0 ; XMLBuilder xml = new XMLBuilder ( indent ) ; xml . startDocument ( ) ; toXML ( xml ) ; xml . endDocument ( ) ; return xml . toString ( ) ; }
Convert the DOM tree rooted at this UNode into an XML document optionally indenting each XML level to product a pretty structured output .
17,798
public void toXML ( XMLBuilder xml ) throws IllegalArgumentException { assert xml != null ; Map < String , String > attrMap = new LinkedHashMap < > ( ) ; String elemName = m_name ; if ( m_tagName . length ( ) > 0 ) { attrMap . put ( "name" , m_name ) ; elemName = m_tagName ; } addXMLAttributes ( attrMap ) ; switch ( m_type ) { case ARRAY : if ( attrMap . size ( ) > 0 ) { xml . startElement ( elemName , attrMap ) ; } else { xml . startElement ( elemName ) ; } if ( m_children != null ) { for ( UNode childNode : m_children ) { if ( childNode . m_type != NodeType . VALUE || ! childNode . m_bAttribute ) { childNode . toXML ( xml ) ; } } } xml . endElement ( ) ; break ; case MAP : if ( attrMap . size ( ) > 0 ) { xml . startElement ( elemName , attrMap ) ; } else { xml . startElement ( elemName ) ; } if ( m_childNodeMap != null ) { assert m_childNodeMap . size ( ) == m_children . size ( ) ; for ( UNode childNode : m_childNodeMap . values ( ) ) { if ( childNode . m_type != NodeType . VALUE || ! childNode . m_bAttribute ) { childNode . toXML ( xml ) ; } } } xml . endElement ( ) ; break ; case VALUE : String value = m_value ; if ( Utils . containsIllegalXML ( value ) ) { value = Utils . base64FromString ( m_value ) ; attrMap . put ( "encoding" , "base64" ) ; } if ( attrMap . size ( ) > 0 ) { xml . addDataElement ( elemName , value , attrMap ) ; } else { xml . addDataElement ( elemName , value ) ; } break ; default : assert false : "Unexpected NodeType: " + m_type ; } }
Add the XML required for this node to the given XMLBuilder .
17,799
public void removeMember ( String childName ) { assert isMap ( ) : "'removeMember' allowed only for MAP nodes" ; if ( m_childNodeMap != null ) { UNode removeNode = m_childNodeMap . remove ( childName ) ; if ( removeNode != null ) { m_children . remove ( removeNode ) ; } } }
Delete the child node of this MAP node with the given name if it exists . This node must be a MAP . The child node name may or may not exist .