idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
17,600 | public final void waitForFullService ( ) { if ( ! m_state . isInitialized ( ) ) { throw new RuntimeException ( "Service has not been initialized" ) ; } synchronized ( m_stateChangeLock ) { // Loop until state >= RUNNING 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 . | 137 | 25 |
17,601 | 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 . | 44 | 28 |
17,602 | 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 . | 94 | 51 |
17,603 | 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 . | 52 | 28 |
17,604 | @ 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 . | 100 | 49 |
17,605 | @ 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 . | 104 | 41 |
17,606 | 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 . | 63 | 19 |
17,607 | @ Override 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 . | 81 | 5 |
17,608 | @ Override 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 | 62 | 5 |
17,609 | 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 . | 177 | 14 |
17,610 | 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 . | 75 | 13 |
17,611 | 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 . | 76 | 19 |
17,612 | public Map < String , String > getErrorDetails ( ) { // Add stacktrace and/or comment fields. 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 . | 135 | 37 |
17,613 | 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 . | 55 | 24 |
17,614 | public UNode toDoc ( ) { // Root node is called "doc". UNode result = UNode . createMapNode ( "doc" ) ; // Each child of "doc" is a simple VALUE node. for ( String fieldName : m_resultFields . keySet ( ) ) { // In XML, we want the element name to be "field" when the node name is "_ID". 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 . | 157 | 18 |
17,615 | 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 ) { @ Override 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 . | 282 | 36 |
17,616 | 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 . | 97 | 15 |
17,617 | 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 | 151 | 14 |
17,618 | 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 | 176 | 15 |
17,619 | 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 . | 71 | 15 |
17,620 | public JSONEmitter addValue ( String value ) { checkComma ( ) ; write ( ' ' ) ; write ( encodeString ( value ) ) ; write ( ' ' ) ; return this ; } | Add a String value . | 42 | 5 |
17,621 | 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 | 37 | 13 |
17,622 | 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 | 216 | 21 |
17,623 | 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 | 212 | 21 |
17,624 | 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 | 139 | 17 |
17,625 | 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 . | 51 | 11 |
17,626 | 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 . | 46 | 24 |
17,627 | 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 . | 35 | 18 |
17,628 | public void traceMutations ( Logger logger ) { logger . debug ( "Transaction in " + getTenant ( ) . getName ( ) + ": " + getMutationsCount ( ) + " mutations" ) ; for ( ColumnUpdate mutation : getColumnUpdates ( ) ) { logger . trace ( mutation . toString ( ) ) ; } //2. delete columns for ( ColumnDelete mutation : getColumnDeletes ( ) ) { logger . trace ( mutation . toString ( ) ) ; } //3. delete rows for ( RowDelete mutation : getRowDeletes ( ) ) { logger . trace ( mutation . toString ( ) ) ; } } | For extreme logging . | 139 | 4 |
17,629 | 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 . | 87 | 18 |
17,630 | public UNode toDoc ( ) { // Root "results" node. UNode resultsNode = UNode . createMapNode ( "results" ) ; // "aggregate" node. 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 ) ; } // Add "totalobjects" if used. if ( m_totalObjects >= 0 ) { resultsNode . addValueNode ( "totalobjects" , Long . toString ( m_totalObjects ) ) ; } // Add global or summary value if present. if ( m_globalValue != null ) { if ( m_groupSetList == null ) { resultsNode . addChildNode ( UNode . createValueNode ( "value" , m_globalValue ) ) ; } else { resultsNode . addChildNode ( UNode . createValueNode ( "summary" , m_globalValue ) ) ; } } // If needed, the "groupsets" node becomes the new parent. UNode parentNode = resultsNode ; boolean bGroupSetsNode = false ; if ( m_groupSetList != null && m_groupSetList . size ( ) > 1 ) { bGroupSetsNode = true ; UNode groupSetsNode = parentNode . addArrayNode ( "groupsets" ) ; parentNode = groupSetsNode ; } // Add groupsets, if any, to the parent node. 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 . | 425 | 24 |
17,631 | 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 . | 286 | 17 |
17,632 | private static byte [ ] chooseMACAddress ( ) { byte [ ] result = new byte [ 6 ] ; boolean bFound = false ; try { Enumeration < NetworkInterface > ifaces = NetworkInterface . getNetworkInterfaces ( ) ; while ( ! bFound && ifaces . hasMoreElements ( ) ) { // Look for a real NIC. 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 ) { // Try next NIC } } } catch ( SocketException e ) { // Possibly no NICs on this system? } if ( ! bFound ) { ( new Random ( ) ) . nextBytes ( result ) ; } return result ; } | Choose a MAC address from one of this machine s NICs or a random value . | 225 | 17 |
17,633 | 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 | 81 | 9 |
17,634 | 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 | 63 | 10 |
17,635 | 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 . | 79 | 9 |
17,636 | 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 . | 143 | 13 |
17,637 | private void registerCommand ( String cmdOwner , RegisteredCommand cmd ) { // Add to owner map in RESTCatalog. 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 ) ; } // Add to local evaluation map. 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 . | 281 | 14 |
17,638 | 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 . | 95 | 12 |
17,639 | 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 . | 97 | 13 |
17,640 | 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 ; } // Find the sorted command set for the given HTTP method. SortedSet < RegisteredCommand > cmdSet = evalMap . get ( method ) ; if ( cmdSet == null ) { return null ; } // Split uri into a list of non-empty nodes. List < String > pathNodeList = new ArrayList <> ( ) ; String [ ] pathNodes = uri . split ( "/" ) ; for ( String pathNode : pathNodes ) { if ( pathNode . length ( ) > 0 ) { pathNodeList . add ( pathNode ) ; } } // Attempt to match commands in this set in order. for ( RegisteredCommand cmd : cmdSet ) { if ( cmd . matches ( pathNodeList , query , variableMap ) ) { return cmd ; } } return null ; } | Search the given command owner for a matching command . | 241 | 10 |
17,641 | 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 { // Send a DELETE request to "/_applications/{application}/{key}". 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 ) { // Notfound is acceptable 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 . | 296 | 56 |
17,642 | 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 ) ; } // Using the application's StorageService, attempt to create an instance of the // ApplicationSession subclass XxxSession where Xxx is the storage prefix. 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 . | 301 | 15 |
17,643 | 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 . | 72 | 11 |
17,644 | 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 . | 72 | 11 |
17,645 | @ Override 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 . | 57 | 8 |
17,646 | 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 | 513 | 12 |
17,647 | 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 | 91 | 6 |
17,648 | 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 . | 87 | 18 |
17,649 | public GregorianCalendar getExpiredDate ( GregorianCalendar relativeDate ) { // Get today's date and adjust by the specified age. 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 : // New value we forgot to add here? 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 . | 165 | 44 |
17,650 | 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 . | 136 | 26 |
17,651 | 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 . | 136 | 26 |
17,652 | 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 . | 117 | 29 |
17,653 | 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 . | 92 | 23 |
17,654 | 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 . | 222 | 40 |
17,655 | 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 . | 122 | 61 |
17,656 | 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 . | 99 | 25 |
17,657 | 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 . | 161 | 43 |
17,658 | 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 { // Find and call the constructor DBService(Tenant). @ 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 ) { // This is thrown when a constructor is invoked via reflection. if ( ! ( e . getTargetException ( ) instanceof DBNotAvailableException ) ) { throw new RuntimeException ( "Could not invoke constructor for dbservice class: " + dbServiceName , e ) ; } } catch ( DBNotAvailableException e ) { // Fall through to retry. } 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 ) { // ignore } } } return dbservice ; } | throws a DBNotAvailableException keep trying . | 617 | 10 |
17,659 | 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 . | 518 | 12 |
17,660 | 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 . | 116 | 13 |
17,661 | private static boolean isEqual ( String string1 , String string2 ) { return ( string1 == null && string2 == null ) || ( string1 != null && string1 . equals ( string2 ) ) ; } | Both strings are null or equal . | 46 | 7 |
17,662 | 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 . | 310 | 10 |
17,663 | 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 . | 89 | 7 |
17,664 | 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 . | 87 | 13 |
17,665 | private List < String > getFieldListFromHeader ( BufferedReader reader ) { // Read the first line and watch out for BOM at the front of the header. String header = null ; try { header = reader . readLine ( ) ; } catch ( IOException e ) { // Leave header null } if ( Utils . isEmpty ( header ) ) { logErrorThrow ( "No header found in file" ) ; } if ( header . charAt ( 0 ) == ' ' ) { header = header . substring ( 1 ) ; } // Split around commas, though this will include spaces. String [ ] tokens = header . split ( "," ) ; List < String > result = new ArrayList < String > ( ) ; for ( String token : tokens ) { // If this field matches the _ID field, add it with that name. 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 . | 237 | 17 |
17,666 | 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 . | 223 | 11 |
17,667 | private void loadTables ( ) { ApplicationDefinition appDef = m_session . getAppDef ( ) ; m_tableNameList = new ArrayList < String > ( appDef . getTableDefinitions ( ) . keySet ( ) ) ; Collections . sort ( m_tableNameList , new Comparator < String > ( ) { @ Override public int compare ( String s1 , String s2 ) { // We want longer table names to be first. So, if s1 == "a" and s2 == "aa", // "a".length() - "aa".length() == -1, which means "aa" appears first. We // don't care about the order of same-length names. return s2 . length ( ) - s1 . length ( ) ; } // compare } ) ; } | ordering to match CSV file names correctly . | 173 | 8 |
17,668 | 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 . | 86 | 12 |
17,669 | 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 . | 288 | 14 |
17,670 | 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 . | 61 | 10 |
17,671 | 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 . | 193 | 8 |
17,672 | private void loadCSVFromReader ( TableDefinition tableDef , String csvName , long byteLength , BufferedReader reader ) { m_logger . info ( "Loading CSV file: {}" , csvName ) ; // Determine the order in which fields in this file appear. Wrap this in a CSVFile. 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 ) ; } } // Always close the file and display stats even if an error occurred. m_totalFiles ++ ; m_totalBytes += byteLength ; long stopTime = System . currentTimeMillis ( ) ; long totalMillis = stopTime - startTime ; if ( totalMillis == 0 ) { totalMillis = 1 ; // You never know } 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 . | 396 | 15 |
17,673 | 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 . | 88 | 15 |
17,674 | private void stopWorkers ( ) { Record sentinel = Record . SENTINEL ; for ( int inx = 0 ; inx < m_workerList . size ( ) ; inx ++ ) { try { m_workerQueue . put ( sentinel ) ; } catch ( InterruptedException e ) { // ignore } } for ( LoadWorker loadWorker : m_workerList ) { try { loadWorker . join ( ) ; } catch ( InterruptedException e ) { // ignore } } } | Add a sentinel to the queue for each worker and wait all to finish . | 109 | 16 |
17,675 | private boolean tokenizeCSVLine ( CSVFile csvFile , BufferedReader reader , Map < String , String > fieldMap ) { fieldMap . clear ( ) ; m_token . setLength ( 0 ) ; // First build a list of tokens found in the order they are found. 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 == ' ' ) { tokenList . add ( m_token . toString ( ) ) ; m_token . setLength ( 0 ) ; reader . mark ( 1 ) ; aChar = reader . read ( ) ; if ( aChar == - 1 ) { break ; } if ( aChar != ' ' ) { reader . reset ( ) ; // put back non-LF } break ; } else if ( ! bInQuote && aChar == ' ' ) { 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 we hit EOF without a final EOL, we could have a token in the buffer. 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 ; } // No tokens found; return false if EOF. return aChar != - 1 ; } | into the given field map . | 533 | 6 |
17,676 | private void logErrorThrow ( String format , Object ... args ) { String msg = MessageFormatter . arrayFormat ( format , args ) . getMessage ( ) ; m_logger . error ( msg ) ; throw new RuntimeException ( msg ) ; } | a RuntimeException . | 53 | 4 |
17,677 | 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 | 130 | 8 |
17,678 | public void add ( long value ) { int index = Arrays . binarySearch ( bins , value ) ; if ( index < 0 ) { // inexact match, take the first bin higher than value index = - index - 1 ; } hits . incrementAndGet ( index ) ; } | Increments the hits in interval containing given value rounding UP . | 59 | 12 |
17,679 | 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 . | 105 | 19 |
17,680 | 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 . | 60 | 16 |
17,681 | 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 . | 85 | 30 |
17,682 | 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 . | 53 | 17 |
17,683 | @ 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 . | 109 | 40 |
17,684 | @ 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 . | 175 | 14 |
17,685 | 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 . | 50 | 29 |
17,686 | 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 . | 278 | 56 |
17,687 | 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 . | 99 | 15 |
17,688 | @ 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 ; } //overrides with params from the file 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 . | 524 | 11 |
17,689 | 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 . | 159 | 9 |
17,690 | 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 . | 214 | 19 |
17,691 | 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 ) ; } // Delete tenant definition in default database. 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 . | 241 | 57 |
17,692 | 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 . | 115 | 13 |
17,693 | private void modifyTenantProperties ( TenantDefinition oldTenantDef , TenantDefinition newTenantDef ) { // _CreatedOn must be the same. _ModifiedOn must be updated. 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 . | 111 | 10 |
17,694 | 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 . | 60 | 15 |
17,695 | 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 . | 146 | 3 |
17,696 | 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 . | 262 | 16 |
17,697 | 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 | 99 | 5 |
17,698 | 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 . | 77 | 7 |
17,699 | 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 . | 53 | 14 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.