idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
17,600
public void started ( ServiceBroker broker ) throws Exception { super . started ( broker ) ; ServiceBrokerConfig cfg = broker . getConfig ( ) ; serviceInvoker = cfg . getServiceInvoker ( ) ; eventbus = cfg . getEventbus ( ) ; uid = cfg . getUidGenerator ( ) ; }
Initializes Default Context Factory instance .
17,601
public void started ( ServiceBroker broker ) throws Exception { super . started ( broker ) ; this . nodeID = broker . getNodeID ( ) ; ServiceBrokerConfig cfg = broker . getConfig ( ) ; this . strategy = cfg . getStrategyFactory ( ) ; this . transporter = cfg . getTransporter ( ) ; this . executor = cfg . getExecutor ( ) ; }
Initializes default EventBus instance .
17,602
protected boolean append ( byte [ ] packet ) { ByteBuffer buffer = ByteBuffer . wrap ( packet ) ; ByteBuffer blocker ; while ( true ) { blocker = blockerBuffer . get ( ) ; if ( blocker == BUFFER_IS_CLOSED ) { return false ; } if ( blockerBuffer . compareAndSet ( blocker , buffer ) ) { queue . add ( buffer ) ; return true ; } } }
Adds a packet to the buffer s queue .
17,603
protected boolean tryToClose ( ) { ByteBuffer blocker = blockerBuffer . get ( ) ; if ( blocker == BUFFER_IS_CLOSED ) { return true ; } if ( blocker != null ) { return false ; } boolean closed = blockerBuffer . compareAndSet ( null , BUFFER_IS_CLOSED ) ; if ( closed ) { closeResources ( ) ; return true ; } return false ; }
Tries to close this buffer .
17,604
protected void write ( ) throws Exception { ByteBuffer buffer = queue . peek ( ) ; if ( buffer == null ) { if ( key != null ) { key . interestOps ( 0 ) ; } return ; } if ( channel != null ) { int count ; while ( true ) { count = channel . write ( buffer ) ; if ( debug ) { logger . info ( count + " bytes submitted to " + channel . getRemoteAddress ( ) + "." ) ; } if ( count == - 1 ) { throw new InvalidPacketDataError ( nodeID , "host" , host , "port" , port ) ; } if ( ! buffer . hasRemaining ( ) ) { queue . poll ( ) ; } if ( queue . isEmpty ( ) ) { if ( blockerBuffer . compareAndSet ( buffer , null ) && key != null ) { key . interestOps ( 0 ) ; } return ; } else { buffer = queue . peek ( ) ; } } } }
Writes N bytes to the target channel .
17,605
public void started ( ServiceBroker broker ) throws Exception { super . started ( broker ) ; ServiceBrokerConfig cfg = broker . getConfig ( ) ; namespace = cfg . getNamespace ( ) ; if ( namespace != null && ! namespace . isEmpty ( ) ) { prefix = prefix + '-' + namespace ; } nodeID = broker . getNodeID ( ) ; serializer . started ( broker ) ; logger . info ( nameOf ( this , true ) + " will use " + nameOf ( serializer , true ) + '.' ) ; executor = cfg . getExecutor ( ) ; scheduler = cfg . getScheduler ( ) ; registry = cfg . getServiceRegistry ( ) ; monitor = cfg . getMonitor ( ) ; eventbus = cfg . getEventbus ( ) ; uid = cfg . getUidGenerator ( ) ; eventChannel = channel ( PACKET_EVENT , nodeID ) ; requestChannel = channel ( PACKET_REQUEST , nodeID ) ; responseChannel = channel ( PACKET_RESPONSE , nodeID ) ; discoverBroadcastChannel = channel ( PACKET_DISCOVER , null ) ; discoverChannel = channel ( PACKET_DISCOVER , nodeID ) ; infoBroadcastChannel = channel ( PACKET_INFO , null ) ; infoChannel = channel ( PACKET_INFO , nodeID ) ; disconnectChannel = channel ( PACKET_DISCONNECT , null ) ; heartbeatChannel = channel ( PACKET_HEARTBEAT , null ) ; pingChannel = channel ( PACKET_PING , nodeID ) ; pongChannel = channel ( PACKET_PONG , nodeID ) ; }
Initializes transporter instance .
17,606
public void started ( ServiceBroker broker ) throws Exception { super . started ( broker ) ; this . nodeID = broker . getNodeID ( ) ; ServiceBrokerConfig cfg = broker . getConfig ( ) ; this . executor = cfg . getExecutor ( ) ; this . scheduler = cfg . getScheduler ( ) ; this . strategyFactory = cfg . getStrategyFactory ( ) ; this . contextFactory = cfg . getContextFactory ( ) ; this . transporter = cfg . getTransporter ( ) ; this . eventbus = cfg . getEventbus ( ) ; this . uid = cfg . getUidGenerator ( ) ; }
Initializes ServiceRegistry instance .
17,607
protected void reschedule ( long minTimeoutAt ) { if ( minTimeoutAt == Long . MAX_VALUE ) { for ( PendingPromise pending : promises . values ( ) ) { if ( pending . timeoutAt > 0 && pending . timeoutAt < minTimeoutAt ) { minTimeoutAt = pending . timeoutAt ; } } long timeoutAt ; requestStreamReadLock . lock ( ) ; try { for ( IncomingStream stream : requestStreams . values ( ) ) { timeoutAt = stream . getTimeoutAt ( ) ; if ( timeoutAt > 0 && timeoutAt < minTimeoutAt ) { minTimeoutAt = timeoutAt ; } } } finally { requestStreamReadLock . unlock ( ) ; } responseStreamReadLock . lock ( ) ; try { for ( IncomingStream stream : responseStreams . values ( ) ) { timeoutAt = stream . getTimeoutAt ( ) ; if ( timeoutAt > 0 && timeoutAt < minTimeoutAt ) { minTimeoutAt = timeoutAt ; } } } finally { responseStreamReadLock . unlock ( ) ; } } long now = System . currentTimeMillis ( ) ; if ( minTimeoutAt == Long . MAX_VALUE ) { ScheduledFuture < ? > t = callTimeoutTimer . get ( ) ; if ( t != null ) { if ( prevTimeoutAt . get ( ) > now ) { t . cancel ( false ) ; prevTimeoutAt . set ( 0 ) ; } else { callTimeoutTimer . set ( null ) ; prevTimeoutAt . set ( 0 ) ; } } } else { minTimeoutAt = ( minTimeoutAt / 100 * 100 ) + 100 ; long prev = prevTimeoutAt . getAndSet ( minTimeoutAt ) ; if ( prev == minTimeoutAt ) { return ; } ScheduledFuture < ? > t = callTimeoutTimer . get ( ) ; if ( t != null ) { t . cancel ( false ) ; } long delay = Math . max ( 10 , minTimeoutAt - now ) ; callTimeoutTimer . set ( scheduler . schedule ( this :: checkTimeouts , delay , TimeUnit . MILLISECONDS ) ) ; } }
Recalculates the next timeout checking time .
17,608
public byte [ ] generateGossipHello ( ) { if ( cachedHelloMessage != null ) { return cachedHelloMessage ; } try { FastBuildTree root = new FastBuildTree ( 4 ) ; root . putUnsafe ( "ver" , ServiceBroker . PROTOCOL_VERSION ) ; root . putUnsafe ( "sender" , nodeID ) ; if ( useHostname ) { root . putUnsafe ( "host" , getHostName ( ) ) ; } else { root . putUnsafe ( "host" , InetAddress . getLocalHost ( ) . getHostAddress ( ) ) ; } root . putUnsafe ( "port" , reader . getCurrentPort ( ) ) ; cachedHelloMessage = serialize ( PACKET_GOSSIP_HELLO_ID , root ) ; } catch ( Exception error ) { throw new MoleculerError ( "Unable to create HELLO message!" , error , "MoleculerError" , "unknown" , false , 500 , "UNABLE_TO_CREATE_HELLO" ) ; } return cachedHelloMessage ; }
Create Gossip HELLO packet . Hello message is invariable so we can cache it .
17,609
public ServiceBroker use ( Collection < Middleware > middlewares ) { if ( serviceRegistry == null ) { this . middlewares . addAll ( middlewares ) ; } else { serviceRegistry . use ( middlewares ) ; } return this ; }
Installs a collection of middlewares .
17,610
public Action getAction ( String actionName , String nodeID ) { return serviceRegistry . getAction ( actionName , nodeID ) ; }
Returns an action by name and nodeID .
17,611
public final Promise get ( String key ) { byte [ ] binaryKey = key . getBytes ( StandardCharsets . UTF_8 ) ; if ( client != null ) { return new Promise ( client . get ( binaryKey ) ) ; } if ( clusteredClient != null ) { return new Promise ( clusteredClient . get ( binaryKey ) ) ; } return Promise . resolve ( ) ; }
Gets a content by a key .
17,612
public final Promise set ( String key , byte [ ] value , SetArgs args ) { byte [ ] binaryKey = key . getBytes ( StandardCharsets . UTF_8 ) ; if ( client != null ) { if ( args == null ) { return new Promise ( client . set ( binaryKey , value ) ) ; } return new Promise ( client . set ( binaryKey , value , args ) ) ; } if ( clusteredClient != null ) { if ( args == null ) { return new Promise ( clusteredClient . set ( binaryKey , value ) ) ; } return new Promise ( clusteredClient . set ( binaryKey , value , args ) ) ; } return Promise . resolve ( ) ; }
Sets a content by key .
17,613
public final Promise clean ( String match ) { ScanArgs args = new ScanArgs ( ) ; args . limit ( 100 ) ; boolean singleStar = match . indexOf ( '*' ) > - 1 ; boolean doubleStar = match . contains ( "**" ) ; if ( doubleStar ) { args . match ( match . replace ( "**" , "*" ) ) ; } else if ( singleStar ) { if ( match . length ( ) > 1 && match . indexOf ( '.' ) == - 1 ) { match += '*' ; } args . match ( match ) ; } else { args . match ( match ) ; } if ( ! singleStar || doubleStar ) { match = null ; } if ( client != null ) { return new Promise ( clean ( client . scan ( args ) , args , match ) ) ; } if ( clusteredClient != null ) { return new Promise ( clean ( clusteredClient . scan ( args ) , args , match ) ) ; } return Promise . resolve ( ) ; }
Deletes a group of items . Removes every key by a match string .
17,614
public int getTotalCpuPercent ( ) { if ( invalidMonitor . get ( ) ) { return 0 ; } long now = System . currentTimeMillis ( ) ; int cpu ; synchronized ( Monitor . class ) { if ( now - cpuDetectedAt > cacheTimeout ) { try { cachedCPU = detectTotalCpuPercent ( ) ; } catch ( Throwable cause ) { logger . info ( "Unable to detect CPU usage!" , cause ) ; invalidMonitor . set ( true ) ; } cpuDetectedAt = now ; } cpu = cachedCPU ; } return cpu ; }
Returns the cached system CPU usage in percents between 0 and 100 .
17,615
public long getPID ( ) { long currentPID = cachedPID . get ( ) ; if ( currentPID != 0 ) { return currentPID ; } try { currentPID = detectPID ( ) ; } catch ( Throwable cause ) { logger . info ( "Unable to detect process ID!" , cause ) ; } if ( currentPID == 0 ) { currentPID = System . nanoTime ( ) ; if ( ! cachedPID . compareAndSet ( 0 , currentPID ) ) { currentPID = cachedPID . get ( ) ; } } else { cachedPID . set ( currentPID ) ; } return currentPID ; }
Returns the cached PID of Java VM .
17,616
public synchronized void reset ( ) { timeoutAt = 0 ; prevSeq = - 1 ; pool . clear ( ) ; stream . closed . set ( false ) ; stream . buffer . clear ( ) ; stream . cause = null ; stream . transferedBytes . set ( 0 ) ; inited . set ( false ) ; }
Used for testing . Resets internal variables .
17,617
public void started ( ServiceBroker broker ) throws Exception { super . started ( broker ) ; if ( prefix == null ) { prefix = ( broker . getNodeID ( ) + ':' ) . toCharArray ( ) ; } }
Initializes UID generator instance .
17,618
public boolean updateSchema ( String text , ContentType contentType ) { Utils . require ( text != null && text . length ( ) > 0 , "text" ) ; Utils . require ( contentType != null , "contentType" ) ; try { byte [ ] body = Utils . toBytes ( text ) ; StringBuilder uri = new StringBuilder ( "/_applications/" ) ; uri . append ( Utils . urlEncode ( m_appDef . getAppName ( ) ) ) ; RESTResponse response = m_restClient . sendRequest ( HttpMethod . PUT , uri . toString ( ) , contentType , body ) ; m_logger . debug ( "updateSchema() response: {}" , response . toString ( ) ) ; throwIfErrorResponse ( response ) ; return true ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Update the schema for this session s application with the given definition . The text must be formatted in XML or JSON as defined by the given content type . True is returned if the update was successful . An exception is thrown if an error occurred .
17,619
protected void throwIfErrorResponse ( RESTResponse response ) { if ( response . getCode ( ) . isError ( ) ) { String errMsg = response . getBody ( ) ; if ( Utils . isEmpty ( errMsg ) ) { errMsg = "Unknown error; response code: " + response . getCode ( ) ; } throw new RuntimeException ( errMsg ) ; } }
If the given response shows an error throw a RuntimeException using its text .
17,620
public String get ( String key ) { if ( requestedKeys == null ) requestedKeys = new HashSet < String > ( ) ; String value = map . get ( key ) ; requestedKeys . add ( key ) ; return value ; }
Gets a value by the key specified . Returns null if the key does not exist .
17,621
public String getString ( String key ) { String value = get ( key ) ; Utils . require ( value != null , key + " parameter is not set" ) ; return value ; }
Gets a value by the key specified . Unlike get checks that the parameter is not null
17,622
public int getInt ( String key ) { String value = get ( key ) ; Utils . require ( value != null , key + " parameter is not set" ) ; try { return Integer . parseInt ( value ) ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( key + " parameter should be a number" ) ; } }
Returns an integer value by the key specified and throws exception if it was not specified
17,623
public int getInt ( String key , int defaultValue ) { String value = get ( key ) ; if ( value == null ) return defaultValue ; try { return Integer . parseInt ( value ) ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( key + " parameter should be a number" ) ; } }
Returns an integer value by the key specified or defaultValue if the key was not provided
17,624
public boolean getBoolean ( String key , boolean defaultValue ) { String value = get ( key ) ; if ( value == null ) return defaultValue ; return XType . getBoolean ( value ) ; }
Returns a boolean value by the key specified or defaultValue if the key was not provided
17,625
public void checkInvalidParameters ( ) { for ( String key : map . keySet ( ) ) { boolean wasRequested = requestedKeys != null && requestedKeys . contains ( key ) ; if ( ! wasRequested ) throw new IllegalArgumentException ( "Unknown parameter " + key ) ; } }
Checks that there are no more parameters than those that have ever been requested . Call this after you processed all parameters you need if you want an IllegalArgumentException to be thrown if there are more parameters
17,626
static KeyRange keyRangeStartRow ( byte [ ] startRowKey ) { KeyRange keyRange = new KeyRange ( ) ; keyRange . setStart_key ( startRowKey ) ; keyRange . setEnd_key ( EMPTY_BYTE_BUFFER ) ; keyRange . setCount ( MAX_ROWS_BATCH_SIZE ) ; return keyRange ; }
Create a KeyRange that begins at the given row key .
17,627
static KeyRange keyRangeSingleRow ( byte [ ] rowKey ) { KeyRange keyRange = new KeyRange ( ) ; keyRange . setStart_key ( rowKey ) ; keyRange . setEnd_key ( rowKey ) ; keyRange . setCount ( 1 ) ; return keyRange ; }
Create a KeyRange that selects a single row with the given key .
17,628
static SlicePredicate slicePredicateColName ( byte [ ] colName ) { SlicePredicate slicePred = new SlicePredicate ( ) ; slicePred . addToColumn_names ( ByteBuffer . wrap ( colName ) ) ; return slicePred ; }
Create a SlicePredicate that selects a single column .
17,629
static SlicePredicate slicePredicateColNames ( Collection < byte [ ] > colNames ) { SlicePredicate slicePred = new SlicePredicate ( ) ; for ( byte [ ] colName : colNames ) { slicePred . addToColumn_names ( ByteBuffer . wrap ( colName ) ) ; } return slicePred ; }
Create a SlicePredicate that selects the given column names .
17,630
public Calendar getTime ( String propName ) { assert propName . endsWith ( "Time" ) ; if ( ! m_properties . containsKey ( propName ) ) { return null ; } Calendar calendar = new GregorianCalendar ( Utils . UTC_TIMEZONE ) ; calendar . setTimeInMillis ( Long . parseLong ( m_properties . get ( propName ) ) ) ; return calendar ; }
Get the value of a time property as a Calendar value . If the given property has not been set or is not a time value null is returned .
17,631
public UNode toDoc ( ) { UNode rootNode = UNode . createMapNode ( m_taskID , "task" ) ; for ( String name : m_properties . keySet ( ) ) { String value = m_properties . get ( name ) ; if ( name . endsWith ( "Time" ) ) { rootNode . addValueNode ( name , formatTimestamp ( value ) ) ; } else { rootNode . addValueNode ( name , value ) ; } } return rootNode ; }
Serialize this task record into a UNode tree . The root UNode is returned which is a map containing one child value node for each TaskRecord property . The map s name is the task ID with a tag name of task . Timestamp values are formatted into friendly display format .
17,632
public final void waitForFullService ( ) { if ( ! m_state . isInitialized ( ) ) { throw new RuntimeException ( "Service has not been initialized" ) ; } synchronized ( m_stateChangeLock ) { while ( ! m_state . isRunning ( ) ) { try { m_stateChangeLock . wait ( ) ; } catch ( InterruptedException e ) { } } if ( m_state . isStopping ( ) ) { throw new RuntimeException ( "Service " + this . getClass ( ) . getSimpleName ( ) + " failed before reaching running state" ) ; } } }
Wait for this service to reach the running state then return . A RuntimeException is thrown if the service has not been initialized .
17,633
public String getParamString ( String paramName ) { Object paramValue = getParam ( paramName ) ; if ( paramValue == null ) { return null ; } return paramValue . toString ( ) ; }
Get the value of the parameter with the given name belonging to this service as a String . If the parameter is not found null is returned .
17,634
public int getParamInt ( String paramName , int defaultValue ) { Object paramValue = getParam ( paramName ) ; if ( paramValue == null ) { return defaultValue ; } try { return Integer . parseInt ( paramValue . toString ( ) ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Value for parameter '" + paramName + "' must be an integer: " + paramValue ) ; } }
Get the value of the parameter with the given name belonging to this service as an integer . If the parameter is not found the given default value is returned . If the parameter is found but cannot be converted to an integer an IllegalArgumentException is thrown .
17,635
public boolean getParamBoolean ( String paramName ) { Object paramValue = getParam ( paramName ) ; if ( paramValue == null ) { return false ; } return Boolean . parseBoolean ( paramValue . toString ( ) ) ; }
Get the value of the parameter with the given name belonging to this service as a boolean . If the parameter is not found false is returned .
17,636
@ SuppressWarnings ( "unchecked" ) public List < String > getParamList ( String paramName ) { Object paramValue = getParam ( paramName ) ; if ( paramValue == null ) { return null ; } if ( ! ( paramValue instanceof List ) ) { throw new IllegalArgumentException ( "Parameter '" + paramName + "' must be a list: " + paramValue ) ; } return ( List < String > ) paramValue ; }
Get the value of the given parameter name belonging to this service as a LIst of Strings . If no such parameter name is known null is returned . If the parameter is defined but is not a list an IllegalArgumentException is thrown .
17,637
@ SuppressWarnings ( "unchecked" ) public Map < String , Object > getParamMap ( String paramName ) { Object paramValue = getParam ( paramName ) ; if ( paramValue == null ) { return null ; } if ( ! ( paramValue instanceof Map ) ) { throw new IllegalArgumentException ( "Parameter '" + paramName + "' must be a map: " + paramValue ) ; } return ( Map < String , Object > ) paramValue ; }
Get the value of the given parameter name as a Map . If no such parameter name is known null is returned . If the parameter is defined but is not a Map an IllegalArgumentException is thrown .
17,638
private void setState ( State newState ) { m_logger . debug ( "Entering state: {}" , newState . toString ( ) ) ; synchronized ( m_stateChangeLock ) { m_state = newState ; m_stateChangeLock . notifyAll ( ) ; } }
Set the service s state and log the change . Notify all waiters of state change .
17,639
public void startService ( ) { m_cmdRegistry . freezeCommandSet ( true ) ; displayCommandSet ( ) ; if ( m_webservice != null ) { try { m_webservice . start ( ) ; } catch ( Exception e ) { throw new RuntimeException ( "Failed to start WebService" , e ) ; } } }
Begin servicing REST requests .
17,640
public void stopService ( ) { try { if ( m_webservice != null ) { m_webservice . stop ( ) ; } } catch ( Exception e ) { m_logger . warn ( "WebService stop failed" , e ) ; } }
Shutdown the REST Service
17,641
private WebServer loadWebServer ( ) { WebServer webServer = null ; if ( ! Utils . isEmpty ( getParamString ( "webserver_class" ) ) ) { try { Class < ? > serviceClass = Class . forName ( getParamString ( "webserver_class" ) ) ; Method instanceMethod = serviceClass . getMethod ( "instance" , ( Class < ? > [ ] ) null ) ; webServer = ( WebServer ) instanceMethod . invoke ( null , ( Object [ ] ) null ) ; webServer . init ( RESTServlet . class . getName ( ) ) ; } catch ( Exception e ) { throw new RuntimeException ( "Error initializing WebServer: " + getParamString ( "webserver_class" ) , e ) ; } } return webServer ; }
Attempt to load the WebServer instance defined by webserver_class .
17,642
private void displayCommandSet ( ) { if ( m_logger . isDebugEnabled ( ) ) { m_logger . debug ( "Registered REST Commands:" ) ; Collection < String > commands = m_cmdRegistry . getCommands ( ) ; for ( String command : commands ) { m_logger . debug ( command ) ; } } }
If DEBUG logging is enabled log all REST commands in sorted order .
17,643
public static ObjectResult newErrorResult ( String errMsg , String objID ) { ObjectResult result = new ObjectResult ( ) ; result . setStatus ( Status . ERROR ) ; result . setErrorMessage ( errMsg ) ; if ( ! Utils . isEmpty ( objID ) ) { result . setObjectID ( objID ) ; } return result ; }
Create an ObjectResult with a status of ERROR and the given error message and optional object ID .
17,644
public Map < String , String > getErrorDetails ( ) { Map < String , String > detailMap = new LinkedHashMap < String , String > ( ) ; if ( m_resultFields . containsKey ( COMMENT ) ) { detailMap . put ( COMMENT , m_resultFields . get ( COMMENT ) ) ; } if ( m_resultFields . containsKey ( STACK_TRACE ) ) { detailMap . put ( STACK_TRACE , m_resultFields . get ( STACK_TRACE ) ) ; } return detailMap ; }
Get the error details for this response object if any exists . The error details is typically a stack trace or comment message . The details are returned as a map of detail names to values .
17,645
public Status getStatus ( ) { String status = m_resultFields . get ( STATUS ) ; if ( status == null ) { return Status . OK ; } else { return Status . valueOf ( status . toUpperCase ( ) ) ; } }
Get the status for this object update result . If a status has not been explicitly defined a value of OK is returned .
17,646
public UNode toDoc ( ) { UNode result = UNode . createMapNode ( "doc" ) ; for ( String fieldName : m_resultFields . keySet ( ) ) { if ( fieldName . equals ( OBJECT_ID ) ) { result . addValueNode ( fieldName , m_resultFields . get ( fieldName ) , "field" ) ; } else { result . addValueNode ( fieldName , m_resultFields . get ( fieldName ) ) ; } } return result ; }
Serialize this ObjectResult into a UNode tree . The root node is called doc .
17,647
private List < DBEntity > collectUninitializedEntities ( DBEntity entity , final String category , final TableDefinition tableDef , final List < String > fields , final String link , final Map < ObjectID , LinkList > cache , final Set < ObjectID > keys , final DBEntitySequenceOptions options ) { DBEntityCollector collector = new DBEntityCollector ( entity ) { protected boolean visit ( DBEntity entity , List < DBEntity > list ) { if ( entity . findIterator ( category ) == null ) { ObjectID id = entity . id ( ) ; LinkList columns = cache . get ( id ) ; if ( columns == null ) { keys . add ( id ) ; list . add ( entity ) ; return ( keys . size ( ) < options . initialLinkBufferDimension ) ; } DBLinkIterator linkIterator = new DBLinkIterator ( entity , link , columns , m_options . linkBuffer , DBEntitySequenceFactory . this , category ) ; entity . addIterator ( category , new DBEntityIterator ( tableDef , entity , linkIterator , fields , DBEntitySequenceFactory . this , category , m_options ) ) ; } return true ; } } ; return collector . collect ( ) ; }
Collects the entities to be initialized with the initial list of links using the link list bulk fetch . Visits all the entities buffered by the iterators of the same category .
17,648
private < C , K , T > LRUCache < K , T > getCache ( Map < C , LRUCache < K , T > > cacheMap , int capacity , C category ) { LRUCache < K , T > cache = cacheMap . get ( category ) ; if ( cache == null ) { cache = new LRUCache < K , T > ( capacity ) ; cacheMap . put ( category , cache ) ; } return cache ; }
Returns the LRU cache of the specified iterator entity or continuationlink category .
17,649
private Map < ObjectID , Map < String , String > > fetchScalarFields ( TableDefinition tableDef , Collection < ObjectID > ids , List < String > fields , String category ) { timers . start ( category , "Init Fields" ) ; Map < ObjectID , Map < String , String > > map = SpiderHelper . getScalarValues ( tableDef , ids , fields ) ; long time = timers . stop ( category , "Init Fields" , ids . size ( ) ) ; log . debug ( "fetch {} {} ({})" , new Object [ ] { ids . size ( ) , category , Timer . toString ( time ) } ) ; return map ; }
Fetches the scalar field values of the specified set of entities
17,650
List < ObjectID > fetchLinks ( TableDefinition tableDef , ObjectID id , String link , ObjectID continuationLink , int count , String category ) { timers . start ( category + " links" , "Continuation" ) ; FieldDefinition linkField = tableDef . getFieldDef ( link ) ; List < ObjectID > list = SpiderHelper . getLinks ( linkField , id , continuationLink , true , count ) ; int resultCount = ( continuationLink == null ) ? list . size ( ) : list . size ( ) - 1 ; long time = timers . stop ( category + " links" , "Continuation" , resultCount ) ; log . debug ( "fetch {} {} continuation links ({})" , new Object [ ] { resultCount , category , Timer . toString ( time ) } ) ; return list ; }
Fetches the link list of the specified iterator category of the specified entity
17,651
private Map < ObjectID , List < ObjectID > > fetchLinks ( TableDefinition tableDef , Collection < ObjectID > ids , String link , int count ) { FieldDefinition linkField = tableDef . getFieldDef ( link ) ; return SpiderHelper . getLinks ( linkField , ids , null , true , count ) ; }
Fetches first N links of the specified type for every specified entity .
17,652
public JSONEmitter addValue ( String value ) { checkComma ( ) ; write ( '"' ) ; write ( encodeString ( value ) ) ; write ( '"' ) ; return this ; }
Add a String value .
17,653
private void write ( String str ) { try { m_writer . write ( str ) ; } catch ( IOException ex ) { throw new RuntimeException ( ex ) ; } }
Write a string and turn any IOException caught into a RuntimeException
17,654
public Map < String , Map < String , List < DColumn > > > getColumnUpdatesMap ( ) { Map < String , Map < String , List < DColumn > > > storeMap = new HashMap < > ( ) ; for ( ColumnUpdate mutation : getColumnUpdates ( ) ) { String storeName = mutation . getStoreName ( ) ; String rowKey = mutation . getRowKey ( ) ; DColumn column = mutation . getColumn ( ) ; Map < String , List < DColumn > > rowMap = storeMap . get ( storeName ) ; if ( rowMap == null ) { rowMap = new HashMap < > ( ) ; storeMap . put ( storeName , rowMap ) ; } List < DColumn > columnsList = rowMap . get ( rowKey ) ; if ( columnsList == null ) { columnsList = new ArrayList < > ( ) ; rowMap . put ( rowKey , columnsList ) ; } columnsList . add ( column ) ; } return storeMap ; }
Get the map of the column updates as storeName - > rowKey - > list of DColumns
17,655
public Map < String , Map < String , List < String > > > getColumnDeletesMap ( ) { Map < String , Map < String , List < String > > > storeMap = new HashMap < > ( ) ; for ( ColumnDelete mutation : getColumnDeletes ( ) ) { String storeName = mutation . getStoreName ( ) ; String rowKey = mutation . getRowKey ( ) ; String column = mutation . getColumnName ( ) ; Map < String , List < String > > rowMap = storeMap . get ( storeName ) ; if ( rowMap == null ) { rowMap = new HashMap < > ( ) ; storeMap . put ( storeName , rowMap ) ; } List < String > columnsList = rowMap . get ( rowKey ) ; if ( columnsList == null ) { columnsList = new ArrayList < > ( ) ; rowMap . put ( rowKey , columnsList ) ; } columnsList . add ( column ) ; } return storeMap ; }
Get the map of the column deletes as storeName - > rowKey - > list of column names
17,656
public Map < String , List < String > > getRowDeletesMap ( ) { Map < String , List < String > > storeMap = new HashMap < > ( ) ; for ( RowDelete mutation : getRowDeletes ( ) ) { String storeName = mutation . getStoreName ( ) ; String rowKey = mutation . getRowKey ( ) ; List < String > rowList = storeMap . get ( storeName ) ; if ( rowList == null ) { rowList = new ArrayList < > ( ) ; storeMap . put ( storeName , rowList ) ; } rowList . add ( rowKey ) ; } return storeMap ; }
Get the map of the row deletes as storeName - > list of row keys
17,657
public void addColumn ( String storeName , String rowKey , String columnName , byte [ ] columnValue ) { m_columnUpdates . add ( new ColumnUpdate ( storeName , rowKey , columnName , columnValue ) ) ; }
Add or set a column with the given binary value .
17,658
public void addColumn ( String storeName , String rowKey , String columnName , String columnValue ) { addColumn ( storeName , rowKey , columnName , Utils . toBytes ( columnValue ) ) ; }
Add or set a column with the given string value . The column value is converted to binary form using UTF - 8 .
17,659
public void deleteRow ( String storeName , String rowKey ) { m_rowDeletes . add ( new RowDelete ( storeName , rowKey ) ) ; }
Add an update that will delete the row with the given row key from the given store .
17,660
public void traceMutations ( Logger logger ) { logger . debug ( "Transaction in " + getTenant ( ) . getName ( ) + ": " + getMutationsCount ( ) + " mutations" ) ; for ( ColumnUpdate mutation : getColumnUpdates ( ) ) { logger . trace ( mutation . toString ( ) ) ; } for ( ColumnDelete mutation : getColumnDeletes ( ) ) { logger . trace ( mutation . toString ( ) ) ; } for ( RowDelete mutation : getRowDeletes ( ) ) { logger . trace ( mutation . toString ( ) ) ; } }
For extreme logging .
17,661
public BatchResult addBatch ( ApplicationDefinition appDef , String shardName , OlapBatch batch ) { Utils . require ( shardName . equals ( MONO_SHARD_NAME ) , "Shard name must be: " + MONO_SHARD_NAME ) ; return OLAPService . instance ( ) . addBatch ( appDef , shardName , batch ) ; }
Store name should always be MONO_SHARD_NAME for OLAPMono .
17,662
public UNode toDoc ( ) { UNode resultsNode = UNode . createMapNode ( "results" ) ; UNode aggNode = resultsNode . addMapNode ( "aggregate" ) ; aggNode . addValueNode ( "metric" , m_metricParam , true ) ; if ( m_queryParam != null ) { aggNode . addValueNode ( "query" , m_queryParam , true ) ; } if ( m_groupingParam != null ) { aggNode . addValueNode ( "group" , m_groupingParam , true ) ; } if ( m_totalObjects >= 0 ) { resultsNode . addValueNode ( "totalobjects" , Long . toString ( m_totalObjects ) ) ; } if ( m_globalValue != null ) { if ( m_groupSetList == null ) { resultsNode . addChildNode ( UNode . createValueNode ( "value" , m_globalValue ) ) ; } else { resultsNode . addChildNode ( UNode . createValueNode ( "summary" , m_globalValue ) ) ; } } UNode parentNode = resultsNode ; boolean bGroupSetsNode = false ; if ( m_groupSetList != null && m_groupSetList . size ( ) > 1 ) { bGroupSetsNode = true ; UNode groupSetsNode = parentNode . addArrayNode ( "groupsets" ) ; parentNode = groupSetsNode ; } if ( m_groupSetList != null ) { for ( AggGroupSet groupSet : m_groupSetList ) { groupSet . addDoc ( parentNode , bGroupSetsNode ) ; } } return resultsNode ; }
Serialize this AggregateResult object into a UNode tree and return the root node . The root node is results .
17,663
public static byte [ ] nextID ( ) { byte [ ] ID = new byte [ 15 ] ; synchronized ( LOCK ) { long timestamp = System . currentTimeMillis ( ) ; if ( timestamp != LAST_TIMESTAMP ) { LAST_TIMESTAMP = timestamp ; LAST_SEQUENCE = 0 ; TIMESTAMP_BUFFER [ 0 ] = ( byte ) ( timestamp >>> 48 ) ; TIMESTAMP_BUFFER [ 1 ] = ( byte ) ( timestamp >>> 40 ) ; TIMESTAMP_BUFFER [ 2 ] = ( byte ) ( timestamp >>> 32 ) ; TIMESTAMP_BUFFER [ 3 ] = ( byte ) ( timestamp >>> 24 ) ; TIMESTAMP_BUFFER [ 4 ] = ( byte ) ( timestamp >>> 16 ) ; TIMESTAMP_BUFFER [ 5 ] = ( byte ) ( timestamp >>> 8 ) ; TIMESTAMP_BUFFER [ 6 ] = ( byte ) ( timestamp >>> 0 ) ; } else if ( ++ LAST_SEQUENCE == 0 ) { throw new RuntimeException ( "Same ID generated in a single milliscond!" ) ; } ByteBuffer bb = ByteBuffer . wrap ( ID ) ; bb . put ( TIMESTAMP_BUFFER ) ; bb . put ( MAC ) ; bb . putShort ( LAST_SEQUENCE ) ; } return ID ; }
Return the next unique ID . See the class description for the format of an ID .
17,664
private static byte [ ] chooseMACAddress ( ) { byte [ ] result = new byte [ 6 ] ; boolean bFound = false ; try { Enumeration < NetworkInterface > ifaces = NetworkInterface . getNetworkInterfaces ( ) ; while ( ! bFound && ifaces . hasMoreElements ( ) ) { NetworkInterface iface = ifaces . nextElement ( ) ; try { byte [ ] hwAddress = iface . getHardwareAddress ( ) ; if ( hwAddress != null ) { int copyBytes = Math . min ( result . length , hwAddress . length ) ; for ( int index = 0 ; index < copyBytes ; index ++ ) { result [ index ] = hwAddress [ index ] ; } bFound = true ; } } catch ( SocketException e ) { } } } catch ( SocketException e ) { } if ( ! bFound ) { ( new Random ( ) ) . nextBytes ( result ) ; } return result ; }
Choose a MAC address from one of this machine s NICs or a random value .
17,665
public boolean Add ( T value ) { if ( m_Count < m_Capacity ) { m_Array [ ++ m_Count ] = value ; UpHeap ( ) ; } else if ( greaterThan ( m_Array [ 1 ] , value ) ) { m_Array [ 1 ] = value ; DownHeap ( ) ; } else return false ; return true ; }
returns true if the value has been added
17,666
public static void checkShard ( Olap olap , ApplicationDefinition appDef , String shard ) { VDirectory appDir = olap . getRoot ( appDef ) ; VDirectory shardDir = appDir . getDirectory ( shard ) ; checkShard ( shardDir ) ; }
check that all segments in the shard are valid
17,667
public static void deleteSegment ( Olap olap , ApplicationDefinition appDef , String shard , String segment ) { VDirectory appDir = olap . getRoot ( appDef ) ; VDirectory shardDir = appDir . getDirectory ( shard ) ; VDirectory segmentDir = shardDir . getDirectory ( segment ) ; segmentDir . delete ( ) ; }
delete a particular segment in the shard .
17,668
public Collection < String > getCommands ( ) { List < String > commands = new ArrayList < String > ( ) ; for ( String cmdOwner : m_cmdsByOwnerMap . keySet ( ) ) { SortedMap < String , RESTCommand > ownerCmdMap = m_cmdsByOwnerMap . get ( cmdOwner ) ; for ( String name : ownerCmdMap . keySet ( ) ) { RESTCommand cmd = ownerCmdMap . get ( name ) ; commands . add ( String . format ( "%s: %s = %s" , cmdOwner , name , cmd . toString ( ) ) ) ; } } return commands ; }
Get all REST commands as a list of strings for debugging purposes .
17,669
private void registerCommand ( String cmdOwner , RegisteredCommand cmd ) { Map < String , RESTCommand > nameMap = getCmdNameMap ( cmdOwner ) ; String cmdName = cmd . getName ( ) ; RESTCommand oldCmd = nameMap . put ( cmdName , cmd ) ; if ( oldCmd != null ) { throw new RuntimeException ( "Duplicate REST command with same owner/name: " + "owner=" + cmdOwner + ", name=" + cmdName + ", [1]=" + cmd + ", [2]=" + oldCmd ) ; } Map < HttpMethod , SortedSet < RegisteredCommand > > evalMap = getCmdEvalMap ( cmdOwner ) ; for ( HttpMethod method : cmd . getMethods ( ) ) { SortedSet < RegisteredCommand > methodSet = evalMap . get ( method ) ; if ( methodSet == null ) { methodSet = new TreeSet < > ( ) ; evalMap . put ( method , methodSet ) ; } if ( ! methodSet . add ( cmd ) ) { throw new RuntimeException ( "Duplicate REST command: owner=" + cmdOwner + ", name=" + cmdName + ", commmand=" + cmd ) ; } } }
Register the given command and throw if is a duplicate name or command .
17,670
private Map < String , RESTCommand > getCmdNameMap ( String cmdOwner ) { SortedMap < String , RESTCommand > cmdNameMap = m_cmdsByOwnerMap . get ( cmdOwner ) ; if ( cmdNameMap == null ) { cmdNameMap = new TreeMap < > ( ) ; m_cmdsByOwnerMap . put ( cmdOwner , cmdNameMap ) ; } return cmdNameMap ; }
Get the method - > command map for the given owner .
17,671
private Map < HttpMethod , SortedSet < RegisteredCommand > > getCmdEvalMap ( String cmdOwner ) { Map < HttpMethod , SortedSet < RegisteredCommand > > evalMap = m_cmdEvalMap . get ( cmdOwner ) ; if ( evalMap == null ) { evalMap = new HashMap < > ( ) ; m_cmdEvalMap . put ( cmdOwner , evalMap ) ; } return evalMap ; }
Get the method - > sorted command map for the given owner .
17,672
private RegisteredCommand searchCommands ( String cmdOwner , HttpMethod method , String uri , String query , Map < String , String > variableMap ) { Map < HttpMethod , SortedSet < RegisteredCommand > > evalMap = getCmdEvalMap ( cmdOwner ) ; if ( evalMap == null ) { return null ; } SortedSet < RegisteredCommand > cmdSet = evalMap . get ( method ) ; if ( cmdSet == null ) { return null ; } List < String > pathNodeList = new ArrayList < > ( ) ; String [ ] pathNodes = uri . split ( "/" ) ; for ( String pathNode : pathNodes ) { if ( pathNode . length ( ) > 0 ) { pathNodeList . add ( pathNode ) ; } } for ( RegisteredCommand cmd : cmdSet ) { if ( cmd . matches ( pathNodeList , query , variableMap ) ) { return cmd ; } } return null ; }
Search the given command owner for a matching command .
17,673
public boolean deleteApplication ( String appName , String key ) { Utils . require ( ! m_restClient . isClosed ( ) , "Client has been closed" ) ; Utils . require ( appName != null && appName . length ( ) > 0 , "appName" ) ; try { StringBuilder uri = new StringBuilder ( Utils . isEmpty ( m_apiPrefix ) ? "" : "/" + m_apiPrefix ) ; uri . append ( "/_applications/" ) ; uri . append ( Utils . urlEncode ( appName ) ) ; if ( ! Utils . isEmpty ( key ) ) { uri . append ( "/" ) ; uri . append ( Utils . urlEncode ( key ) ) ; } RESTResponse response = m_restClient . sendRequest ( HttpMethod . DELETE , uri . toString ( ) ) ; m_logger . debug ( "deleteApplication() response: {}" , response . toString ( ) ) ; if ( response . getCode ( ) != HttpCode . NOT_FOUND ) { throwIfErrorResponse ( response ) ; } return true ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Delete an existing application from the current Doradus tenant including all of its tables and data . Because updates are idempotent deleting an already - deleted application is acceptable . Hence if no error is thrown the result is always true . An exception is thrown if an error occurs .
17,674
private static ApplicationSession openApplication ( ApplicationDefinition appDef , RESTClient restClient ) { String storageService = appDef . getStorageService ( ) ; if ( storageService == null || storageService . length ( ) <= "Service" . length ( ) || ! storageService . endsWith ( "Service" ) ) { throw new RuntimeException ( "Unknown storage-service for application '" + appDef . getAppName ( ) + "': " + storageService ) ; } try { String prefix = storageService . substring ( 0 , storageService . length ( ) - "Service" . length ( ) ) ; String className = Client . class . getPackage ( ) . getName ( ) + "." + prefix + "Session" ; @ SuppressWarnings ( "unchecked" ) Class < ApplicationSession > appClass = ( Class < ApplicationSession > ) Class . forName ( className ) ; Constructor < ApplicationSession > constructor = appClass . getConstructor ( ApplicationDefinition . class , RESTClient . class ) ; ApplicationSession appSession = constructor . newInstance ( appDef , restClient ) ; return appSession ; } catch ( Exception e ) { restClient . close ( ) ; throw new RuntimeException ( "Unable to load session class" , e ) ; } }
the given restClient . If the open fails the restClient is closed .
17,675
public ServerMonitorMXBean createServerMonitorProxy ( ) throws IOException { String beanName = ServerMonitorMXBean . JMX_DOMAIN_NAME + ":type=" + ServerMonitorMXBean . JMX_TYPE_NAME ; return createMXBeanProxy ( beanName , ServerMonitorMXBean . class ) ; }
Makes the proxy for ServerMonitorMXBean .
17,676
public StorageManagerMXBean createStorageManagerProxy ( ) throws IOException { String beanName = StorageManagerMXBean . JMX_DOMAIN_NAME + ":type=" + StorageManagerMXBean . JMX_TYPE_NAME ; return createMXBeanProxy ( beanName , StorageManagerMXBean . class ) ; }
Makes the proxy for StorageManagerMXBean .
17,677
public String getOperationMode ( ) { String mode = getNode ( ) . getOperationMode ( ) ; if ( mode != null && NORMAL . equals ( mode . toUpperCase ( ) ) ) { mode = NORMAL ; } return mode ; }
The operation mode of the Cassandra node .
17,678
private void collectGroupValues ( Entity obj , PathEntry entry , GroupSetEntry groupSetEntry , Set < String > [ ] groupKeys ) { if ( entry . query != null ) { timers . start ( "Where" , entry . queryText ) ; boolean result = entry . checkCondition ( obj ) ; timers . stop ( "Where" , entry . queryText , result ? 1 : 0 ) ; if ( ! result ) return ; } for ( PathEntry field : entry . leafBranches ) { String fieldName = field . name ; int groupIndex = field . groupIndex ; if ( fieldName == PathEntry . ANY ) { groupSetEntry . m_groupPaths [ groupIndex ] . addValueKeys ( groupKeys [ groupIndex ] , obj . id ( ) . toString ( ) ) ; } else { String value = obj . get ( fieldName ) ; if ( value == null || value . indexOf ( CommonDefs . MV_SCALAR_SEP_CHAR ) == - 1 ) { groupSetEntry . m_groupPaths [ groupIndex ] . addValueKeys ( groupKeys [ groupIndex ] , value ) ; } else { String [ ] values = value . split ( CommonDefs . MV_SCALAR_SEP_CHAR ) ; for ( String collectionValue : values ) { groupSetEntry . m_groupPaths [ groupIndex ] . addValueKeys ( groupKeys [ groupIndex ] , collectionValue ) ; } } } } for ( PathEntry child : entry . linkBranches ) { boolean hasLinkedEntities = false ; if ( child . nestedLinks == null || child . nestedLinks . size ( ) == 0 ) { for ( Entity linkedObj : obj . getLinkedEntities ( child . name , child . fieldNames ) ) { hasLinkedEntities = true ; collectGroupValues ( linkedObj , child , groupSetEntry , groupKeys ) ; } } else { for ( LinkInfo linkInfo : child . nestedLinks ) { for ( Entity linkedObj : obj . getLinkedEntities ( linkInfo . name , child . fieldNames ) ) { hasLinkedEntities = true ; collectGroupValues ( linkedObj , child , groupSetEntry , groupKeys ) ; } } } if ( ! hasLinkedEntities && ! child . hasUnderlyingQuery ( ) ) nullifyGroupKeys ( child , groupSetEntry , groupKeys ) ; } }
Collect all values from all object found in the path subtree
17,679
private void updateMetric ( String value , GroupSetEntry groupSetEntry , Set < String > [ ] groupKeys ) { updateMetric ( value , groupSetEntry . m_totalGroup , groupKeys , 0 ) ; if ( groupSetEntry . m_isComposite ) { updateMetric ( value , groupSetEntry . m_compositeGroup , groupKeys , groupKeys . length - 1 ) ; } }
add value to the aggregation groups
17,680
private synchronized void updateMetric ( String value , Group group , Set < String > [ ] groupKeys , int index ) { group . update ( value ) ; if ( index < groupKeys . length ) { for ( String key : groupKeys [ index ] ) { Group subgroup = group . subgroup ( key ) ; updateMetric ( value , subgroup , groupKeys , index + 1 ) ; } } }
add value to the aggregation group and all subgroups in accordance with the groupKeys paths .
17,681
public GregorianCalendar getExpiredDate ( GregorianCalendar relativeDate ) { GregorianCalendar expiredDate = ( GregorianCalendar ) relativeDate . clone ( ) ; switch ( m_units ) { case DAYS : expiredDate . add ( Calendar . DAY_OF_MONTH , - m_value ) ; break ; case MONTHS : expiredDate . add ( Calendar . MONTH , - m_value ) ; break ; case YEARS : expiredDate . add ( Calendar . YEAR , - m_value ) ; break ; default : throw new AssertionError ( "Unknown RetentionUnits: " + m_units ) ; } return expiredDate ; }
Find the date on or before which objects expire based on the given date and the retention age specified in this object . The given date is cloned and then adjusted downward by the units and value in this RetentionAge .
17,682
public PreparedStatement getPreparedQuery ( String tableName , Query query ) { synchronized ( m_prepQueryMap ) { Map < Query , PreparedStatement > statementMap = m_prepQueryMap . get ( tableName ) ; if ( statementMap == null ) { statementMap = new HashMap < > ( ) ; m_prepQueryMap . put ( tableName , statementMap ) ; } PreparedStatement prepState = statementMap . get ( query ) ; if ( prepState == null ) { prepState = prepareQuery ( tableName , query ) ; statementMap . put ( query , prepState ) ; } return prepState ; } }
Get the given prepared statement for the given table and query . Upon first invocation for a given combo the query is parsed and cached .
17,683
public PreparedStatement getPreparedUpdate ( String tableName , Update update ) { synchronized ( m_prepUpdateMap ) { Map < Update , PreparedStatement > statementMap = m_prepUpdateMap . get ( tableName ) ; if ( statementMap == null ) { statementMap = new HashMap < > ( ) ; m_prepUpdateMap . put ( tableName , statementMap ) ; } PreparedStatement prepState = statementMap . get ( update ) ; if ( prepState == null ) { prepState = prepareUpdate ( tableName , update ) ; statementMap . put ( update , prepState ) ; } return prepState ; } }
Get the given prepared statement for the given table and update . Upon first invocation for a given combo the query is parsed and cached .
17,684
public static Tenant getTenant ( ApplicationDefinition appDef ) { String tenantName = appDef . getTenantName ( ) ; if ( Utils . isEmpty ( tenantName ) ) { return TenantService . instance ( ) . getDefaultTenant ( ) ; } TenantDefinition tenantDef = TenantService . instance ( ) . getTenantDefinition ( tenantName ) ; Utils . require ( tenantDef != null , "Tenant definition does not exist: %s" , tenantName ) ; return new Tenant ( tenantDef ) ; }
Create a Tenant object from the given application definition . If the application does not define a tenant the Tenant for the default database is returned .
17,685
public DBService getDefaultDB ( ) { String defaultTenantName = TenantService . instance ( ) . getDefaultTenantName ( ) ; synchronized ( m_tenantDBMap ) { DBService dbservice = m_tenantDBMap . get ( defaultTenantName ) ; assert dbservice != null : "Database for default tenant not found" ; return dbservice ; } }
Get the DBService for the default database . This object is created when the DBManagerService is started .
17,686
public DBService getTenantDB ( Tenant tenant ) { synchronized ( m_tenantDBMap ) { DBService dbservice = m_tenantDBMap . get ( tenant . getName ( ) ) ; if ( dbservice == null ) { dbservice = createTenantDBService ( tenant ) ; m_tenantDBMap . put ( tenant . getName ( ) , dbservice ) ; } else if ( ! sameTenantDefs ( dbservice . getTenant ( ) . getDefinition ( ) , tenant . getDefinition ( ) ) ) { m_logger . info ( "Purging obsolete DBService for redefined tenant: {}" , tenant . getName ( ) ) ; dbservice . stop ( ) ; dbservice = createTenantDBService ( tenant ) ; m_tenantDBMap . put ( tenant . getName ( ) , dbservice ) ; } return dbservice ; } }
Get the DBService for the given tenant . The DBService is created if necessary causing it to connect to its underlying DB . An exception is thrown if the DB cannot be connected .
17,687
public void updateTenantDef ( TenantDefinition tenantDef ) { synchronized ( m_tenantDBMap ) { DBService dbservice = m_tenantDBMap . get ( tenantDef . getName ( ) ) ; if ( dbservice != null ) { Tenant updatedTenant = new Tenant ( tenantDef ) ; m_logger . info ( "Updating DBService for tenant: {}" , updatedTenant . getName ( ) ) ; dbservice . updateTenant ( updatedTenant ) ; } } }
Update the corresponding DBService with the given tenant definition . This method is called when an existing tenant is modified . If the DBService for the tenant has not yet been cached this method is a no - op . Otherwise the cached DBService is updated with the new tenant definition .
17,688
public void deleteTenantDB ( Tenant tenant ) { synchronized ( m_tenantDBMap ) { DBService dbservice = m_tenantDBMap . remove ( tenant . getName ( ) ) ; if ( dbservice != null ) { m_logger . info ( "Stopping DBService for deleted tenant: {}" , tenant . getName ( ) ) ; dbservice . stop ( ) ; } } }
Close the DBService for the given tenant if is has been cached . This is called when a tenant is deleted .
17,689
public SortedMap < String , SortedMap < String , Object > > getActiveTenantInfo ( ) { SortedMap < String , SortedMap < String , Object > > activeTenantMap = new TreeMap < > ( ) ; synchronized ( m_tenantDBMap ) { for ( String tenantName : m_tenantDBMap . keySet ( ) ) { DBService dbservice = m_tenantDBMap . get ( tenantName ) ; Map < String , Object > dbServiceParams = dbservice . getAllParams ( ) ; activeTenantMap . put ( tenantName , new TreeMap < String , Object > ( dbServiceParams ) ) ; } } return activeTenantMap ; }
Get the information about all active tenants which are those whose DBService has been created . The is keyed by tenant name and its value is a map of parameters configured for the corresponding DBService .
17,690
private DBService createDefaultDBService ( ) { m_logger . info ( "Creating DBService for default tenant" ) ; String dbServiceName = ServerParams . instance ( ) . getModuleParamString ( "DBService" , "dbservice" ) ; if ( Utils . isEmpty ( dbServiceName ) ) { throw new RuntimeException ( "'DBService.dbservice' parameter is not defined." ) ; } DBService dbservice = null ; Tenant defaultTenant = TenantService . instance ( ) . getDefaultTenant ( ) ; boolean bDBOpened = false ; while ( ! bDBOpened ) { try { @ SuppressWarnings ( "unchecked" ) Class < DBService > serviceClass = ( Class < DBService > ) Class . forName ( dbServiceName ) ; Constructor < DBService > constructor = serviceClass . getConstructor ( Tenant . class ) ; dbservice = constructor . newInstance ( defaultTenant ) ; dbservice . initialize ( ) ; dbservice . start ( ) ; bDBOpened = true ; } catch ( IllegalArgumentException e ) { throw new RuntimeException ( "Cannot load specified 'dbservice': " + dbServiceName , e ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( "Could not load dbservice class '" + dbServiceName + "'" , e ) ; } catch ( NoSuchMethodException e ) { throw new RuntimeException ( "Required constructor missing for dbservice class: " + dbServiceName , e ) ; } catch ( SecurityException | InstantiationException | IllegalAccessException e ) { throw new RuntimeException ( "Could not invoke constructor for dbservice class: " + dbServiceName , e ) ; } catch ( InvocationTargetException e ) { if ( ! ( e . getTargetException ( ) instanceof DBNotAvailableException ) ) { throw new RuntimeException ( "Could not invoke constructor for dbservice class: " + dbServiceName , e ) ; } } catch ( DBNotAvailableException e ) { } catch ( Throwable e ) { throw new RuntimeException ( "Failed to initialize default DBService: " + dbServiceName , e ) ; } if ( ! bDBOpened ) { m_logger . info ( "Database is not reachable. Waiting to retry" ) ; try { Thread . sleep ( db_connect_retry_wait_millis ) ; } catch ( InterruptedException ex2 ) { } } } return dbservice ; }
throws a DBNotAvailableException keep trying .
17,691
private DBService createTenantDBService ( Tenant tenant ) { m_logger . info ( "Creating DBService for tenant: {}" , tenant . getName ( ) ) ; Map < String , Object > dbServiceParams = tenant . getDefinition ( ) . getOptionMap ( "DBService" ) ; String dbServiceName = null ; if ( dbServiceParams == null || ! dbServiceParams . containsKey ( "dbservice" ) ) { dbServiceName = ServerParams . instance ( ) . getModuleParamString ( "DBService" , "dbservice" ) ; Utils . require ( ! Utils . isEmpty ( dbServiceName ) , "DBService.dbservice parameter is not defined" ) ; } else { dbServiceName = dbServiceParams . get ( "dbservice" ) . toString ( ) ; } DBService dbservice = null ; try { @ SuppressWarnings ( "unchecked" ) Class < DBService > serviceClass = ( Class < DBService > ) Class . forName ( dbServiceName ) ; Constructor < DBService > constructor = serviceClass . getConstructor ( Tenant . class ) ; dbservice = constructor . newInstance ( tenant ) ; dbservice . initialize ( ) ; dbservice . start ( ) ; } catch ( IllegalArgumentException e ) { throw new RuntimeException ( "Cannot load specified 'dbservice': " + dbServiceName , e ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( "Could not load dbservice class '" + dbServiceName + "'" , e ) ; } catch ( NoSuchMethodException e ) { throw new RuntimeException ( "Required constructor missing for dbservice class: " + dbServiceName , e ) ; } catch ( SecurityException | InstantiationException | IllegalAccessException | InvocationTargetException e ) { throw new RuntimeException ( "Could not invoke constructor for dbservice class: " + dbServiceName , e ) ; } catch ( Throwable e ) { throw new RuntimeException ( "Failed to initialize DBService '" + dbServiceName + "' for tenant: " + tenant . getName ( ) , e ) ; } return dbservice ; }
Create a new DBService for the given tenant .
17,692
private static boolean sameTenantDefs ( TenantDefinition tenantDef1 , TenantDefinition tenantDef2 ) { return isEqual ( tenantDef1 . getProperty ( TenantService . CREATED_ON_PROP ) , tenantDef2 . getProperty ( TenantService . CREATED_ON_PROP ) ) && isEqual ( tenantDef1 . getProperty ( TenantService . CREATED_ON_PROP ) , tenantDef2 . getProperty ( TenantService . CREATED_ON_PROP ) ) ; }
stamps allowing for either property to be null for older definitions .
17,693
private static boolean isEqual ( String string1 , String string2 ) { return ( string1 == null && string2 == null ) || ( string1 != null && string1 . equals ( string2 ) ) ; }
Both strings are null or equal .
17,694
private void createApplication ( ) { String schema = getSchema ( ) ; ContentType contentType = null ; if ( m_config . schema . toLowerCase ( ) . endsWith ( ".json" ) ) { contentType = ContentType . APPLICATION_JSON ; } else if ( m_config . schema . toLowerCase ( ) . endsWith ( ".xml" ) ) { contentType = ContentType . TEXT_XML ; } else { logErrorThrow ( "Unknown file type for schema: {}" , m_config . schema ) ; } try { m_logger . info ( "Creating application '{}' with schema: {}" , m_config . app , m_config . schema ) ; m_client . createApplication ( schema , contentType ) ; } catch ( Exception e ) { logErrorThrow ( "Error creating schema: {}" , e ) ; } try { m_session = m_client . openApplication ( m_config . app ) ; } catch ( RuntimeException e ) { logErrorThrow ( "Application '{}' not found after creation: {}." , m_config . app , e . toString ( ) ) ; } String ss = m_session . getAppDef ( ) . getStorageService ( ) ; if ( ! Utils . isEmpty ( ss ) && ss . startsWith ( "OLAP" ) ) { m_bOLAPApp = true ; } loadTables ( ) ; }
Create the application from the configured schema file name .
17,695
private void deleteApplication ( ) { ApplicationDefinition appDef = m_client . getAppDef ( m_config . app ) ; if ( appDef != null ) { m_logger . info ( "Deleting existing application: {}" , appDef . getAppName ( ) ) ; m_client . deleteApplication ( appDef . getAppName ( ) , appDef . getKey ( ) ) ; } }
Delete existing application if it exists .
17,696
private TableDefinition determineTableFromFileName ( String fileName ) { ApplicationDefinition appDef = m_session . getAppDef ( ) ; for ( String tableName : m_tableNameList ) { if ( fileName . regionMatches ( true , 0 , tableName , 0 , tableName . length ( ) ) ) { return appDef . getTableDef ( tableName ) ; } } return null ; }
table name that matches the starting characters of the CSV file name .
17,697
private List < String > getFieldListFromHeader ( BufferedReader reader ) { String header = null ; try { header = reader . readLine ( ) ; } catch ( IOException e ) { } if ( Utils . isEmpty ( header ) ) { logErrorThrow ( "No header found in file" ) ; } if ( header . charAt ( 0 ) == '\uFEFF' ) { header = header . substring ( 1 ) ; } String [ ] tokens = header . split ( "," ) ; List < String > result = new ArrayList < String > ( ) ; for ( String token : tokens ) { String fieldName = token . trim ( ) ; if ( fieldName . equals ( m_config . id ) ) { result . add ( CommonDefs . ID_FIELD ) ; } else { result . add ( token . trim ( ) ) ; } } return result ; }
Extract the field names from the given CSV header line and return as a list .
17,698
private String getSchema ( ) { if ( Utils . isEmpty ( m_config . schema ) ) { m_config . schema = m_config . root + m_config . app + ".xml" ; } File schemaFile = new File ( m_config . schema ) ; if ( ! schemaFile . exists ( ) ) { logErrorThrow ( "Schema file not found: {}" , m_config . schema ) ; } StringBuilder schemaBuffer = new StringBuilder ( ) ; char [ ] charBuffer = new char [ 65536 ] ; try ( FileReader reader = new FileReader ( schemaFile ) ) { for ( int bytesRead = reader . read ( charBuffer ) ; bytesRead > 0 ; bytesRead = reader . read ( charBuffer ) ) { schemaBuffer . append ( charBuffer , 0 , bytesRead ) ; } } catch ( Exception e ) { logErrorThrow ( "Cannot read schema file '{}': {}" , m_config . schema , e ) ; } return schemaBuffer . toString ( ) ; }
Load schema contents from m_config . schema file .
17,699
private void loadTables ( ) { ApplicationDefinition appDef = m_session . getAppDef ( ) ; m_tableNameList = new ArrayList < String > ( appDef . getTableDefinitions ( ) . keySet ( ) ) ; Collections . sort ( m_tableNameList , new Comparator < String > ( ) { public int compare ( String s1 , String s2 ) { return s2 . length ( ) - s1 . length ( ) ; } } ) ; }
ordering to match CSV file names correctly .