idx int64 0 165k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
17,800 | private void toJSON ( JSONEmitter json ) { switch ( m_type ) { case ARRAY : json . startArray ( m_name ) ; if ( m_children != null ) { for ( UNode childNode : m_children ) { if ( childNode . isMap ( ) ) { json . startObject ( ) ; childNode . toJSON ( json ) ; json . endObject ( ) ; } else { childNode . toJSON ( json ) ; } } } json . endArray ( ) ; break ; case MAP : json . startGroup ( m_name ) ; if ( m_childNodeMap != null ) { assert m_childNodeMap . size ( ) == m_children . size ( ) ; for ( UNode childNode : m_childNodeMap . values ( ) ) { childNode . toJSON ( json ) ; } } json . endGroup ( ) ; break ; case VALUE : if ( m_bAltFormat && m_tagName != null ) { json . startGroup ( m_tagName ) ; json . addValue ( m_name , m_value ) ; json . endGroup ( ) ; } else if ( m_parent != null && m_parent . isArray ( ) ) { if ( m_name . equals ( "value" ) ) { json . addValue ( m_value ) ; } else { json . addObject ( m_name , m_value ) ; } } else { json . addValue ( m_name , m_value ) ; } break ; default : assert false : "Unknown NodeType: " + m_type ; } } | Add the appropriate JSON syntax for this UNode to the given JSONEmitter . |
17,801 | private static void parseXMLAttributes ( NamedNodeMap attrMap , List < UNode > childUNodeList ) { for ( int index = 0 ; index < attrMap . getLength ( ) ; index ++ ) { Attr attr = ( Attr ) attrMap . item ( index ) ; UNode childNode = createValueNode ( attr . getName ( ) , attr . getValue ( ) , true ) ; childUNodeList . add ( childNode ) ; } } | if to the given child node list . |
17,802 | private static boolean parseXMLChildElems ( Element elem , List < UNode > childUNodeList ) { assert elem != null ; assert childUNodeList != null ; boolean bDupNodeNames = false ; Set < String > nodeNameSet = new HashSet < String > ( ) ; NodeList nodeList = elem . getChildNodes ( ) ; for ( int index = 0 ; index < nodeList . getLength ( ) ; index ++ ) { Node childNode = nodeList . item ( index ) ; if ( childNode instanceof Element ) { UNode childUNode = parseXMLElement ( ( Element ) childNode ) ; childUNodeList . add ( childUNode ) ; if ( nodeNameSet . contains ( childUNode . getName ( ) ) ) { bDupNodeNames = true ; } else { nodeNameSet . add ( childUNode . getName ( ) ) ; } } } return bDupNodeNames ; } | are found while scanning . |
17,803 | private void addXMLAttributes ( Map < String , String > attrMap ) { if ( m_children != null ) { for ( UNode childNode : m_children ) { if ( childNode . m_type == NodeType . VALUE && childNode . m_bAttribute && Utils . isEmpty ( childNode . m_tagName ) ) { assert m_name != null && m_name . length ( ) > 0 ; attrMap . put ( childNode . m_name , childNode . m_value ) ; } } } } | Get the child nodes of this UNode that are VALUE nodes marked as attributes . |
17,804 | private void toStringTree ( StringBuilder builder , int indent ) { for ( int count = 0 ; count < indent ; count ++ ) { builder . append ( " " ) ; } builder . append ( this . toString ( ) ) ; builder . append ( "\n" ) ; if ( m_children != null ) { for ( UNode childNode : m_children ) { childNode . toStringTree ( builder , indent + 3 ) ; } } } | appended with a newline . |
17,805 | void deleteRow ( String storeName , Map < String , AttributeValue > key ) { String tableName = storeToTableName ( storeName ) ; m_logger . debug ( "Deleting row from table {}, key={}" , tableName , DynamoDBService . getDDBKey ( key ) ) ; Timer timer = new Timer ( ) ; boolean bSuccess = false ; for ( int attempts = 1 ; ! bSuccess ; attempts ++ ) { try { m_ddbClient . deleteItem ( tableName , key ) ; if ( attempts > 1 ) { m_logger . info ( "deleteRow() succeeded on attempt #{}" , attempts ) ; } bSuccess = true ; m_logger . debug ( "Time to delete table {}, key={}: {}" , new Object [ ] { tableName , DynamoDBService . getDDBKey ( key ) , timer . toString ( ) } ) ; } catch ( ProvisionedThroughputExceededException e ) { if ( attempts >= m_max_commit_attempts ) { String errMsg = "All retries exceeded; abandoning deleteRow() for table: " + tableName ; m_logger . error ( errMsg , e ) ; throw new RuntimeException ( errMsg , e ) ; } m_logger . warn ( "deleteRow() attempt #{} failed: {}" , attempts , e ) ; try { Thread . sleep ( attempts * m_retry_wait_millis ) ; } catch ( InterruptedException ex2 ) { } } } } | Delete row and back off if ProvisionedThroughputExceededException occurs . |
17,806 | private AWSCredentials getCredentials ( ) { String awsProfile = getParamString ( "aws_profile" ) ; if ( ! Utils . isEmpty ( awsProfile ) ) { m_logger . info ( "Using AWS profile: {}" , awsProfile ) ; ProfileCredentialsProvider credsProvider = null ; String awsCredentialsFile = getParamString ( "aws_credentials_file" ) ; if ( ! Utils . isEmpty ( awsCredentialsFile ) ) { credsProvider = new ProfileCredentialsProvider ( awsCredentialsFile , awsProfile ) ; } else { credsProvider = new ProfileCredentialsProvider ( awsProfile ) ; } return credsProvider . getCredentials ( ) ; } String awsAccessKey = getParamString ( "aws_access_key" ) ; Utils . require ( ! Utils . isEmpty ( awsAccessKey ) , "Either 'aws_profile' or 'aws_access_key' must be defined for tenant: " + m_tenant . getName ( ) ) ; String awsSecretKey = getParamString ( "aws_secret_key" ) ; Utils . require ( ! Utils . isEmpty ( awsSecretKey ) , "'aws_secret_key' must be defined when 'aws_access_key' is defined. " + "'aws_profile' is preferred over aws_access_key/aws_secret_key. Tenant: " + m_tenant . getName ( ) ) ; return new BasicAWSCredentials ( awsAccessKey , awsSecretKey ) ; } | Set the AWS credentials in m_ddbClient |
17,807 | private void setRegionOrEndPoint ( ) { String regionName = getParamString ( "ddb_region" ) ; if ( regionName != null ) { Regions regionEnum = Regions . fromName ( regionName ) ; Utils . require ( regionEnum != null , "Unknown 'ddb_region': " + regionName ) ; m_logger . info ( "Using region: {}" , regionName ) ; m_ddbClient . setRegion ( Region . getRegion ( regionEnum ) ) ; } else { String ddbEndpoint = getParamString ( "ddb_endpoint" ) ; Utils . require ( ddbEndpoint != null , "Either 'ddb_region' or 'ddb_endpoint' must be defined for tenant: " + m_tenant . getName ( ) ) ; m_logger . info ( "Using endpoint: {}" , ddbEndpoint ) ; m_ddbClient . setEndpoint ( ddbEndpoint ) ; } } | Set the region or endpoint in m_ddbClient |
17,808 | private void setDefaultCapacity ( ) { Object capacity = getParam ( "ddb_default_read_capacity" ) ; if ( capacity != null ) { READ_CAPACITY_UNITS = Integer . parseInt ( capacity . toString ( ) ) ; } capacity = getParam ( "ddb_default_write_capacity" ) ; if ( capacity != null ) { WRITE_CAPACITY_UNITS = Integer . parseInt ( capacity . toString ( ) ) ; } m_logger . info ( "Default table capacity: read={}, write={}" , READ_CAPACITY_UNITS , WRITE_CAPACITY_UNITS ) ; } | Set READ_CAPACITY_UNITS and WRITE_CAPACITY_UNITS if overridden . |
17,809 | private ScanResult scan ( ScanRequest scanRequest ) { m_logger . debug ( "Performing scan() request on table {}" , scanRequest . getTableName ( ) ) ; Timer timer = new Timer ( ) ; boolean bSuccess = false ; ScanResult scanResult = null ; for ( int attempts = 1 ; ! bSuccess ; attempts ++ ) { try { scanResult = m_ddbClient . scan ( scanRequest ) ; if ( attempts > 1 ) { m_logger . info ( "scan() succeeded on attempt #{}" , attempts ) ; } bSuccess = true ; m_logger . debug ( "Time to scan table {}: {}" , scanRequest . getTableName ( ) , timer . toString ( ) ) ; } catch ( ProvisionedThroughputExceededException e ) { if ( attempts >= m_max_read_attempts ) { String errMsg = "All retries exceeded; abandoning scan() for table: " + scanRequest . getTableName ( ) ; m_logger . error ( errMsg , e ) ; throw new RuntimeException ( errMsg , e ) ; } m_logger . warn ( "scan() attempt #{} failed: {}" , attempts , e ) ; try { Thread . sleep ( attempts * m_retry_wait_millis ) ; } catch ( InterruptedException ex2 ) { } } } return scanResult ; } | Perform a scan request and retry if ProvisionedThroughputExceededException occurs . |
17,810 | private List < DColumn > loadAttributes ( Map < String , AttributeValue > attributeMap , Predicate < String > colNamePredicate ) { List < DColumn > columns = new ArrayList < > ( ) ; if ( attributeMap != null ) { for ( Map . Entry < String , AttributeValue > mapEntry : attributeMap . entrySet ( ) ) { String colName = mapEntry . getKey ( ) ; if ( ! colName . equals ( DynamoDBService . ROW_KEY_ATTR_NAME ) && colNamePredicate . test ( colName ) ) { AttributeValue attrValue = mapEntry . getValue ( ) ; if ( attrValue . getB ( ) != null ) { columns . add ( new DColumn ( colName , Utils . getBytes ( attrValue . getB ( ) ) ) ) ; } else if ( attrValue . getS ( ) != null ) { String value = attrValue . getS ( ) ; if ( value . equals ( DynamoDBService . NULL_COLUMN_MARKER ) ) { value = "" ; } columns . add ( new DColumn ( colName , value ) ) ; } else { throw new RuntimeException ( "Unknown AttributeValue type: " + attrValue ) ; } } } } Collections . sort ( columns , new Comparator < DColumn > ( ) { public int compare ( DColumn col1 , DColumn col2 ) { return col1 . getName ( ) . compareTo ( col2 . getName ( ) ) ; } } ) ; return columns ; } | Filter store and sort attributes from the given map . |
17,811 | private void deleteTable ( String tableName ) { m_logger . info ( "Deleting table: {}" , tableName ) ; try { m_ddbClient . deleteTable ( new DeleteTableRequest ( tableName ) ) ; for ( int seconds = 0 ; seconds < 10 ; seconds ++ ) { try { m_ddbClient . describeTable ( tableName ) ; Thread . sleep ( 1000 ) ; } catch ( ResourceNotFoundException e ) { break ; } } } catch ( ResourceNotFoundException e ) { } catch ( Exception e ) { throw new RuntimeException ( "Error deleting table: " + tableName , e ) ; } } | Delete the given table and wait for it to be deleted . |
17,812 | public List < String > tokenize ( String text ) { List < String > tokens = new ArrayList < String > ( ) ; text = text . toLowerCase ( ) ; char [ ] array = text . toCharArray ( ) ; for ( int i = 0 ; i < array . length ; i ++ ) { if ( isApostrofe ( array [ i ] ) ) array [ i ] = 0x27 ; } int pos = 0 ; while ( pos < array . length ) { while ( pos < array . length && ! Character . isLetterOrDigit ( array [ pos ] ) ) pos ++ ; int start = pos ; if ( start == array . length ) break ; while ( pos < array . length && isLetterOrDigitOrApostrofe ( array [ pos ] ) ) pos ++ ; int newpos = pos ; while ( newpos > start && isApostrofe ( array [ newpos - 1 ] ) ) newpos -- ; if ( newpos > start ) tokens . add ( new String ( array , start , newpos - start ) ) ; } return tokens ; } | get list of tokens from the text for indexing |
17,813 | public void updateTenant ( Tenant updatedTenant ) { assert m_tenant . getName ( ) . equals ( updatedTenant . getName ( ) ) ; m_tenant = updatedTenant ; } | Update this DBService s Tenant with the given one . This is called when the tenant s definition has been updated in an upward - compatible way such as adding or removing users . |
17,814 | public static boolean isSystemTable ( String storeName ) { return storeName . equals ( SchemaService . APPS_STORE_NAME ) || storeName . equals ( TaskManagerService . TASKS_STORE_NAME ) || storeName . equals ( TenantService . TENANTS_STORE_NAME ) ; } | Return true if the given store name is a system table aka metadata table . System tables store column values as strings . All other tables use binary column values . |
17,815 | private boolean storeExists ( String tableName ) { KeyspaceMetadata ksMetadata = m_cluster . getMetadata ( ) . getKeyspace ( m_keyspace ) ; return ( ksMetadata != null ) && ( ksMetadata . getTable ( tableName ) != null ) ; } | Return true if the given table exists in the given keyspace . |
17,816 | private ResultSet executeQuery ( Query query , String tableName , Object ... values ) { m_logger . debug ( "Executing statement {} on table {}.{}; total params={}" , new Object [ ] { query , m_keyspace , tableName , values . length } ) ; try { PreparedStatement prepState = getPreparedQuery ( query , tableName ) ; BoundStatement boundState = prepState . bind ( values ) ; return m_session . execute ( boundState ) ; } catch ( Exception e ) { String params = "[" + Utils . concatenate ( Arrays . asList ( values ) , "," ) + "]" ; m_logger . error ( "Query failed: query={}, keyspace={}, table={}, params={}; error: {}" , query , m_keyspace , tableName , params , e ) ; throw e ; } } | Execute the given query for the given table using the given values . |
17,817 | private Cluster buildClusterSpecs ( ) { Cluster . Builder builder = Cluster . builder ( ) ; String dbhost = getParamString ( "dbhost" ) ; String [ ] nodeAddresses = dbhost . split ( "," ) ; for ( String address : nodeAddresses ) { builder . addContactPoint ( address ) ; } builder . withPort ( getParamInt ( "dbport" , 9042 ) ) ; SocketOptions socketOpts = new SocketOptions ( ) ; socketOpts . setReadTimeoutMillis ( getParamInt ( "db_timeout_millis" , 10000 ) ) ; socketOpts . setConnectTimeoutMillis ( getParamInt ( "db_connect_retry_wait_millis" , 5000 ) ) ; builder . withSocketOptions ( socketOpts ) ; String dbuser = getParamString ( "dbuser" ) ; if ( ! Utils . isEmpty ( dbuser ) ) { builder . withCredentials ( dbuser , getParamString ( "dbpassword" ) ) ; } builder . withCompression ( Compression . SNAPPY ) ; if ( getParamBoolean ( "dbtls" ) ) { builder . withSSL ( getSSLOptions ( ) ) ; } return builder . build ( ) ; } | Build Cluster object from ServerConfig settings . |
17,818 | private SSLContext getSSLContext ( String truststorePath , String truststorePassword , String keystorePath , String keystorePassword ) throws Exception { FileInputStream tsf = new FileInputStream ( truststorePath ) ; KeyStore ts = KeyStore . getInstance ( "JKS" ) ; ts . load ( tsf , truststorePassword . toCharArray ( ) ) ; TrustManagerFactory tmf = TrustManagerFactory . getInstance ( TrustManagerFactory . getDefaultAlgorithm ( ) ) ; tmf . init ( ts ) ; FileInputStream ksf = new FileInputStream ( keystorePath ) ; KeyStore ks = KeyStore . getInstance ( "JKS" ) ; ks . load ( ksf , keystorePassword . toCharArray ( ) ) ; KeyManagerFactory kmf = KeyManagerFactory . getInstance ( KeyManagerFactory . getDefaultAlgorithm ( ) ) ; kmf . init ( ks , keystorePassword . toCharArray ( ) ) ; SSLContext ctx = SSLContext . getInstance ( "SSL" ) ; ctx . init ( kmf . getKeyManagers ( ) , tmf . getTrustManagers ( ) , new SecureRandom ( ) ) ; return ctx ; } | Build an SSLContext from the given truststore and keystore parameters . |
17,819 | private void connectToCluster ( ) { assert m_cluster != null ; try { m_cluster . init ( ) ; m_session = m_cluster . connect ( ) ; displayClusterInfo ( ) ; } catch ( Exception e ) { m_logger . error ( "Could not connect to Cassandra cluster" , e ) ; throw new DBNotAvailableException ( e ) ; } } | Attempt to connect to the given cluster and throw if it is unavailable . |
17,820 | private void displayClusterInfo ( ) { Metadata metadata = m_cluster . getMetadata ( ) ; m_logger . info ( "Connected to cluster with topography:" ) ; RoundRobinPolicy policy = new RoundRobinPolicy ( ) ; for ( Host host : metadata . getAllHosts ( ) ) { m_logger . info ( " Host {}: datacenter: {}, rack: {}, distance: {}" , new Object [ ] { host . getAddress ( ) , host . getDatacenter ( ) , host . getRack ( ) , policy . distance ( host ) } ) ; } m_logger . info ( "Database contains {} keyspaces" , metadata . getKeyspaces ( ) . size ( ) ) ; } | Display configuration information for the given cluster . |
17,821 | private ContentType getContentType ( ) { String contentTypeValue = m_request . getContentType ( ) ; if ( contentTypeValue == null ) { return ContentType . TEXT_XML ; } return new ContentType ( contentTypeValue ) ; } | Get the request s content - type using XML as the default . |
17,822 | private ContentType getAcceptType ( ) { String format = m_variableMap . get ( "format" ) ; if ( format != null ) { return new ContentType ( format ) ; } String acceptParts = m_request . getHeader ( HttpDefs . ACCEPT ) ; if ( ! Utils . isEmpty ( acceptParts ) ) { for ( String acceptPart : acceptParts . split ( "," ) ) { ContentType acceptType = new ContentType ( acceptPart ) ; if ( acceptType . isJSON ( ) || acceptType . isXML ( ) || acceptType . isPlainText ( ) ) { return acceptType ; } } } return getContentType ( ) ; } | Get the request s accept type defaulting to content - type if none is specified . |
17,823 | private boolean isMessageCompressed ( ) { String contentEncoding = m_request . getHeader ( HttpDefs . CONTENT_ENCODING ) ; if ( contentEncoding != null ) { if ( ! contentEncoding . equalsIgnoreCase ( "gzip" ) ) { throw new IllegalArgumentException ( "Unsupported Content-Encoding: " + contentEncoding ) ; } return true ; } return false ; } | If Content - Encoding is included verify that we support it and return true . |
17,824 | public long stop ( long time ) { m_nesting -- ; if ( m_nesting < 0 ) { m_nesting = 0 ; } if ( m_nesting == 0 ) { long elapsedTime = time - m_startTime ; m_elapsedTime += elapsedTime ; return elapsedTime ; } return 0 ; } | Stop the timer . If timer was started update the elapsed time . |
17,825 | public void addValuesForField ( ) { FieldDefinition fieldDef = m_tableDef . getFieldDef ( m_fieldName ) ; if ( fieldDef == null || ! fieldDef . isCollection ( ) ) { addSVScalar ( ) ; } else { addMVScalar ( ) ; } } | Add scalar value to object record ; add term columns for indexed tokens . |
17,826 | public static Set < String > mergeMVFieldValues ( Collection < String > currValueSet , Collection < String > removeValueSet , Collection < String > newValueSet ) { Set < String > resultSet = new HashSet < > ( ) ; if ( currValueSet != null ) { resultSet . addAll ( currValueSet ) ; } if ( removeValueSet != null ) { resultSet . removeAll ( removeValueSet ) ; } if ( newValueSet != null ) { resultSet . addAll ( newValueSet ) ; } return resultSet ; } | Merge the given current remove and new MV field values into a new set . |
17,827 | private void addFieldTermReferences ( Set < String > termSet ) { Map < String , Set < String > > fieldTermRefsMap = new HashMap < String , Set < String > > ( ) ; fieldTermRefsMap . put ( m_fieldName , termSet ) ; m_dbTran . addTermReferences ( m_tableDef , m_tableDef . getShardNumber ( m_dbObj ) , fieldTermRefsMap ) ; } | Add references to the given terms for used for this field . |
17,828 | private void addMVScalar ( ) { Set < String > values = new HashSet < > ( m_dbObj . getFieldValues ( m_fieldName ) ) ; String fieldValue = Utils . concatenate ( values , CommonDefs . MV_SCALAR_SEP_CHAR ) ; m_dbTran . addScalarValueColumn ( m_tableDef , m_dbObj . getObjectID ( ) , m_fieldName , fieldValue ) ; addTermColumns ( fieldValue ) ; } | Add new MV scalar field . |
17,829 | private void addSVScalar ( ) { String fieldValue = m_dbObj . getFieldValue ( m_fieldName ) ; m_dbTran . addScalarValueColumn ( m_tableDef , m_dbObj . getObjectID ( ) , m_fieldName , fieldValue ) ; addTermColumns ( fieldValue ) ; } | Add new SV scalar field . |
17,830 | private void addTermColumns ( String fieldValue ) { Set < String > termSet = tokenize ( fieldValue ) ; indexTerms ( termSet ) ; addFieldTermReferences ( termSet ) ; addFieldReference ( ) ; } | Add all Terms columns needed for our scalar field . |
17,831 | private void indexTerms ( Set < String > termSet ) { for ( String term : termSet ) { m_dbTran . addTermIndexColumn ( m_tableDef , m_dbObj , m_fieldName , term ) ; } } | Tokenize the given field with the appropriate analyzer and add Terms columns for each term . |
17,832 | private Set < String > tokenize ( String fieldValue ) { FieldAnalyzer analyzer = FieldAnalyzer . findAnalyzer ( m_tableDef , m_fieldName ) ; return analyzer . extractTerms ( fieldValue ) ; } | Tokenize the given field value with the appropriate analyzer . |
17,833 | private boolean updateSVScalar ( String currentValue ) { String newValue = m_dbObj . getFieldValue ( m_fieldName ) ; boolean bUpdated = false ; if ( Utils . isEmpty ( newValue ) ) { if ( ! Utils . isEmpty ( currentValue ) ) { m_dbTran . deleteScalarValueColumn ( m_tableDef , m_dbObj . getObjectID ( ) , m_fieldName ) ; unindexTerms ( currentValue ) ; bUpdated = true ; } } else if ( ! newValue . equals ( currentValue ) ) { updateScalarReplaceValue ( currentValue , newValue ) ; bUpdated = true ; } return bUpdated ; } | Replace our SV scalar s value . |
17,834 | private boolean updateMVScalar ( String currentValue ) { boolean bUpdated = false ; Set < String > currentValues = Utils . split ( currentValue , CommonDefs . MV_SCALAR_SEP_CHAR ) ; Set < String > newValueSet = mergeMVFieldValues ( currentValues , m_dbObj . getRemoveValues ( m_fieldName ) , m_dbObj . getFieldValues ( m_fieldName ) ) ; String newValue = Utils . concatenate ( newValueSet , CommonDefs . MV_SCALAR_SEP_CHAR ) ; if ( ! newValue . equals ( currentValue ) ) { if ( newValue . length ( ) == 0 ) { m_dbTran . deleteScalarValueColumn ( m_tableDef , m_dbObj . getObjectID ( ) , m_fieldName ) ; unindexTerms ( currentValue ) ; } else { updateScalarReplaceValue ( currentValue , newValue ) ; } bUpdated = true ; } return bUpdated ; } | where ~ is the MV value separator . |
17,835 | private void updateScalarReplaceValue ( String currentValue , String newValue ) { m_dbTran . addScalarValueColumn ( m_tableDef , m_dbObj . getObjectID ( ) , m_fieldName , newValue ) ; Set < String > currTermSet = tokenize ( Utils . isEmpty ( currentValue ) ? "" : currentValue ) ; Set < String > newTermSet = tokenize ( newValue ) ; for ( String term : currTermSet ) { if ( ! newTermSet . remove ( term ) ) { unindexTerm ( term ) ; } } indexTerms ( newTermSet ) ; addFieldTermReferences ( newTermSet ) ; if ( Utils . isEmpty ( currentValue ) ) { addFieldReference ( ) ; } } | This works for both SV and MV scalar fields |
17,836 | public static boolean isValidFieldName ( String fieldName ) { return fieldName != null && fieldName . length ( ) > 0 && Utils . isLetter ( fieldName . charAt ( 0 ) ) && Utils . allAlphaNumUnderscore ( fieldName ) ; } | Indicate if the given field name is valid . Currently field names must begin with a letter and consist of all letters digits and underscores . |
17,837 | public void setTableDefinition ( TableDefinition tableDef ) { m_tableDef = tableDef ; if ( m_type . isLinkType ( ) && Utils . isEmpty ( m_linkExtent ) ) { m_linkExtent = tableDef . getTableName ( ) ; } } | Make the given table the owner of this field definition and any nested fields it owns . |
17,838 | public boolean hasNestedField ( String fieldName ) { if ( m_type != FieldType . GROUP ) { return false ; } return m_nestedFieldMap . containsKey ( fieldName ) ; } | Indicate if this group field contains an immediated - nested field with the given name . If this field is not a group false is returned . |
17,839 | public void setName ( String fieldName ) { if ( m_name != null ) { throw new IllegalArgumentException ( "Field name is already set: " + m_name ) ; } if ( ! isValidFieldName ( fieldName ) ) { throw new IllegalArgumentException ( "Invalid field name: " + fieldName ) ; } m_name = fieldName ; } | Set this field s name to the given valid . An IllegalArgumentException is thrown if the name is already assigned or is not valid . |
17,840 | private void verify ( ) { Utils . require ( ! Utils . isEmpty ( m_name ) , "Field name is required" ) ; Utils . require ( m_type != null , "Field type is required" ) ; Utils . require ( m_linkInverse == null || m_type . isLinkType ( ) , "'inverse' not allowed for this field type: " + m_name ) ; Utils . require ( m_linkExtent == null || m_type . isLinkType ( ) , "'table' not allowed for this field type: " + m_name ) ; Utils . require ( ! m_type . isLinkType ( ) || m_linkInverse != null , "Missing 'inverse' option: " + m_name ) ; if ( ! Utils . isEmpty ( m_junctionField ) ) { Utils . require ( m_type == FieldType . XLINK , "'junction' is only allowed for xlinks" ) ; } else if ( m_type == FieldType . XLINK ) { m_junctionField = "_ID" ; } if ( ! m_bIsCollection && m_type . isLinkType ( ) ) { m_bIsCollection = true ; } Utils . require ( m_analyzerName == null || m_type . isScalarType ( ) , "'analyzer' can only be specified for scalar field types: " + m_analyzerName ) ; if ( m_encoding != null ) { Utils . require ( m_type == FieldType . BINARY , "'encoding' is only valid for binary fields" ) ; } else if ( m_type == FieldType . BINARY ) { m_encoding = EncodingType . getDefaultEncoding ( ) ; } Utils . require ( m_type != FieldType . BINARY || ! m_bIsCollection , "Binary fields cannot be collections (multi-valued)" ) ; } | Verify that this field definition is complete and coherent . |
17,841 | public void delete ( ) { for ( int i = 1 ; i < m_nextNo ; i ++ ) { new File ( m_fileName + "_" + i ) . delete ( ) ; } m_nextNo = 1 ; } | Deleting data files . |
17,842 | public ApplicationDefinition getApplicationDefinition ( Tenant tenant , String applicationName ) { if ( tenant == null ) tenant = TenantService . instance ( ) . getDefaultTenant ( ) ; ApplicationDefinition appDef = SchemaService . instance ( ) . getApplication ( tenant , applicationName ) ; return appDef ; } | If tenant is null then default tenant is used . |
17,843 | public void setKeyStore ( String keyStore , String keyPass , String keyManagerType , String keyStoreType ) { if ( ( keyStore == null ) || ( keyPass == null ) ) { this . keyStore = System . getProperty ( "javax.net.ssl.keyStore" ) ; this . keyPass = System . getProperty ( "javax.net.ssl.keyStorePassword" ) ; } else { this . keyStore = keyStore ; this . keyPass = keyPass ; } if ( keyManagerType != null ) { this . keyManagerType = keyManagerType ; } if ( keyStoreType != null ) { this . keyStoreType = keyStoreType ; } isKeyStoreSet = ( keyStore != null ) && ( keyPass != null ) ; } | Set the keystore password certificate type and the store type |
17,844 | public void setKeyStore ( String keyStore , String keyPass ) { setKeyStore ( keyStore , keyPass , null , null ) ; } | Set the keystore and password |
17,845 | public void setTrustStore ( String trustStore , String trustPass , String trustManagerType , String trustStoreType ) { if ( ( trustStore == null ) || ( trustPass == null ) ) { this . trustStore = System . getProperty ( "javax.net.ssl.trustStore" ) ; this . trustPass = System . getProperty ( "javax.net.ssl.trustStorePassword" ) ; } else { this . trustStore = trustStore ; this . trustPass = trustPass ; } if ( trustManagerType != null ) { this . trustManagerType = trustManagerType ; } if ( trustStoreType != null ) { this . trustStoreType = trustStoreType ; } isTrustStoreSet = ( trustStore != null ) && ( trustPass != null ) ; } | Set the truststore password certificate type and the store type |
17,846 | public void setTrustStore ( String trustStore , String trustPass ) { setTrustStore ( trustStore , trustPass , null , null ) ; } | Set the truststore and password |
17,847 | private static int compareNodes ( String node1 , String node2 ) { assert node1 != null ; assert node2 != null ; if ( node1 . equals ( node2 ) ) { return 0 ; } if ( node1 . length ( ) > 0 && node1 . charAt ( 0 ) == '{' ) { if ( node2 . length ( ) > 0 && node2 . charAt ( 0 ) == '{' ) { return 0 ; } return 1 ; } if ( node2 . length ( ) > 0 && node2 . charAt ( 0 ) == '{' ) { return - 1 ; } return node1 . compareTo ( node2 ) ; } | path nodes are query parameters . Either node can be empty but not null . |
17,848 | private static boolean matches ( String value , String component , Map < String , String > variableMap ) { if ( Utils . isEmpty ( component ) ) { return Utils . isEmpty ( value ) ; } if ( component . charAt ( 0 ) == '{' ) { if ( ! Utils . isEmpty ( value ) ) { String varName = getVariableName ( component ) ; variableMap . put ( varName , value ) ; } return true ; } return component . equals ( value ) ; } | variable value is extracted and added to the given map . |
17,849 | private static String getVariableName ( String value ) { assert value . charAt ( 0 ) == '{' ; assert value . charAt ( value . length ( ) - 1 ) == '}' ; return value . substring ( 1 , value . length ( ) - 1 ) ; } | thrown if the trailing } is missing . |
17,850 | private void findParamDescMethods ( ) { for ( Method method : m_commandClass . getMethods ( ) ) { if ( method . isAnnotationPresent ( ParamDescription . class ) ) { try { RESTParameter cmdParam = ( RESTParameter ) method . invoke ( null , ( Object [ ] ) null ) ; addParameter ( cmdParam ) ; } catch ( Exception e ) { LOGGER . warn ( "Method '{}' for class '{}' could not be invoked: {}" , new Object [ ] { method . getName ( ) , m_commandClass . getName ( ) , e . toString ( ) } ) ; } } } } | Look for ParamDescription annotations and attempt to call each annotated method . |
17,851 | private void createCommandDescription ( Description descAnnotation ) { setName ( descAnnotation . name ( ) ) ; setSummary ( descAnnotation . summary ( ) ) ; setMethods ( descAnnotation . methods ( ) ) ; setURI ( descAnnotation . uri ( ) ) ; setInputEntity ( descAnnotation . inputEntity ( ) ) ; setOutputEntity ( descAnnotation . outputEntity ( ) ) ; setPrivileged ( descAnnotation . privileged ( ) ) ; setVisibility ( descAnnotation . visible ( ) ) ; } | Create a CommandDescription object for the given Description annotation . |
17,852 | public static DoradusClient open ( String host , int port , Credentials credentials , String applicationName ) { DoradusClient doradusClient = new DoradusClient ( host , port , null , credentials , applicationName ) ; doradusClient . setCredentials ( credentials ) ; String storageService = lookupStorageServiceByApp ( doradusClient . getRestClient ( ) , applicationName ) ; doradusClient . setStorageService ( storageService ) ; return doradusClient ; } | Static factory method to open a dory client session |
17,853 | public void setApplication ( String appName ) { applicationName = appName ; String storageService = lookupStorageServiceByApp ( getRestClient ( ) , applicationName ) ; setStorageService ( storageService ) ; } | Set the given application name as context for all future commands . This method can be used when an application name was not given in a constructor . |
17,854 | public void setCredentials ( String tenant , String username , String userpassword ) { Credentials credentials = new Credentials ( tenant , username , userpassword ) ; restClient . setCredentials ( credentials ) ; } | Set credentials such as tenant username password for use with a Doradus application . |
17,855 | public Map < String , List < String > > listCommands ( ) { Map < String , List < String > > result = new HashMap < String , List < String > > ( ) ; for ( String cat : restMetadataJson . keySet ( ) ) { JsonObject commands = restMetadataJson . getJsonObject ( cat ) ; List < String > names = new ArrayList < String > ( ) ; for ( String commandName : commands . keySet ( ) ) { names . add ( commandName ) ; } result . put ( cat , names ) ; } return result ; } | Retrieve the map of commands keyed by service name |
17,856 | public JsonObject describeCommand ( String service , String command ) { return Command . matchCommand ( restMetadataJson , command , service ) ; } | Describe command that helps give the idea what client needs to build the command |
17,857 | private static String lookupStorageServiceByApp ( RESTClient restClient , String applicationName ) { Utils . require ( applicationName != null , "Missing application name" ) ; if ( applicationName != null ) { ApplicationDefinition appDef = Command . getAppDef ( restClient , applicationName ) ; Utils . require ( appDef != null , "Unknown application: %s" , applicationName ) ; return appDef . getStorageService ( ) ; } return null ; } | Convenient method to lookup storageService of the application |
17,858 | private synchronized void loadRESTRulesIfNotExist ( RESTClient restClient ) { if ( restMetadataJson == null || restMetadataJson . isEmpty ( ) ) { restMetadataJson = loadRESTCommandsFromServer ( restClient ) ; } } | Load RESTRules once |
17,859 | private JsonObject loadRESTCommandsFromServer ( RESTClient restClient ) { RESTResponse response = null ; try { response = restClient . sendRequest ( HttpMethod . GET , _DESCRIBE_URI , ContentType . APPLICATION_JSON , null ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } if ( ! response . getCode ( ) . isError ( ) ) { JsonReader jsonReader = Json . createReader ( new StringReader ( response . getBody ( ) ) ) ; JsonObject result = jsonReader . readObject ( ) . getJsonObject ( "commands" ) ; jsonReader . close ( ) ; return result ; } else { throw new RuntimeException ( "Describe command error: " + response . getBody ( ) ) ; } } | Load REST commands by calling describe command |
17,860 | private void setMethods ( String methodList ) { String [ ] methodNames = methodList . trim ( ) . split ( "," ) ; for ( String methodName : methodNames ) { HttpMethod method = HttpMethod . valueOf ( methodName . trim ( ) . toUpperCase ( ) ) ; Utils . require ( method != null , "Unknown REST method: " + methodName ) ; m_methods . add ( method ) ; } } | Set methods from a CSV list . |
17,861 | public DBObject makeCopy ( String objID ) { DBObject newObj = new DBObject ( ) ; newObj . m_valueMap . putAll ( m_valueMap ) ; newObj . setObjectID ( objID ) ; newObj . m_valueRemoveMap . putAll ( m_valueRemoveMap ) ; return newObj ; } | Make a copy of this object with the same updates and values but with a new object ID . |
17,862 | public Set < String > getFieldNames ( ) { HashSet < String > result = new LinkedHashSet < > ( m_valueMap . keySet ( ) ) ; return result ; } | Return the field names for which this DBObject has a value . The set does not include fields that have remove values stored . The set is copied . |
17,863 | public Set < String > getRemoveValues ( String fieldName ) { Utils . require ( ! Utils . isEmpty ( fieldName ) , "fieldName" ) ; if ( ! m_valueRemoveMap . containsKey ( fieldName ) ) { return null ; } return new HashSet < > ( m_valueRemoveMap . get ( fieldName ) ) ; } | Get all values marked for removal for the given field . The result will be null if the given field has no values to remove . Otherwise the set is copied . |
17,864 | public String getFieldValue ( String fieldName ) { Utils . require ( ! Utils . isEmpty ( fieldName ) , "fieldName" ) ; List < String > values = m_valueMap . get ( fieldName ) ; if ( values == null || values . size ( ) == 0 ) { return null ; } Utils . require ( values . size ( ) == 1 , "Field has more than 1 value: %s" , fieldName ) ; return values . get ( 0 ) ; } | Get the single value of the field with the given name or null if no value is assigned to the given field . This method is intended to be used for fields expected to have a single value . An exception is thrown if it is called for a field with multiple values . |
17,865 | public boolean isDeleted ( ) { String value = getSystemField ( _DELETED ) ; return value == null ? false : Boolean . parseBoolean ( value ) ; } | Get this object s deleted flag if set . |
17,866 | public void addFieldValue ( String fieldName , String value ) { Utils . require ( ! Utils . isEmpty ( fieldName ) , "fieldName" ) ; if ( fieldName . charAt ( 0 ) == '_' ) { setSystemField ( fieldName , value ) ; } else { List < String > currValues = m_valueMap . get ( fieldName ) ; if ( currValues == null ) { currValues = new ArrayList < > ( ) ; m_valueMap . put ( fieldName , currValues ) ; } currValues . add ( value ) ; } } | Add the given value to the field with the given name . For a system field its existing value if any is replaced . If a null or empty field is added for an SV scalar the field is nullified . |
17,867 | public void clearValues ( String fieldName ) { Utils . require ( ! Utils . isEmpty ( fieldName ) , "fieldName" ) ; m_valueMap . remove ( fieldName ) ; m_valueRemoveMap . remove ( fieldName ) ; } | Clear all values for the given field . Both add and remove values if any are deleted . |
17,868 | public DBObject parse ( UNode docNode ) { Utils . require ( docNode != null , "docNode" ) ; Utils . require ( docNode . getName ( ) . equals ( "doc" ) , "'doc' node expected: %s" , docNode . getName ( ) ) ; for ( String fieldName : docNode . getMemberNames ( ) ) { UNode fieldValue = docNode . getMember ( fieldName ) ; parseFieldUpdate ( fieldName , fieldValue ) ; } return this ; } | Parse an object rooted at the given doc UNode . All values parsed are stored in the object . An exception is thrown if the node structure is incorrect or a field has an invalid value . |
17,869 | public void removeFieldValues ( String fieldName , Collection < String > values ) { Utils . require ( ! Utils . isEmpty ( fieldName ) , "fieldName" ) ; if ( values != null && values . size ( ) > 0 ) { List < String > valueSet = m_valueRemoveMap . get ( fieldName ) ; if ( valueSet == null ) { valueSet = new ArrayList < String > ( ) ; m_valueRemoveMap . put ( fieldName , valueSet ) ; } valueSet . addAll ( values ) ; } } | Add remove values for the given field . This method should only be called for MV scalar and link fields . When the updates in this DBObject are applied to the database the given set of values are removed for the object . An exception is thrown if the field is not MV . If the given set of values is null or empty this method is a no - op . |
17,870 | private void leafFieldtoDoc ( UNode parentNode , String fieldName ) { assert parentNode != null ; Set < String > addSet = null ; if ( m_valueMap . containsKey ( fieldName ) ) { addSet = new TreeSet < String > ( m_valueMap . get ( fieldName ) ) ; } List < String > removeSet = m_valueRemoveMap . get ( fieldName ) ; if ( addSet != null && addSet . size ( ) == 1 && removeSet == null ) { parentNode . addValueNode ( fieldName , addSet . iterator ( ) . next ( ) , "field" ) ; } else { UNode fieldNode = parentNode . addMapNode ( fieldName , "field" ) ; if ( addSet != null && addSet . size ( ) > 0 ) { UNode addNode = fieldNode . addArrayNode ( "add" ) ; for ( String value : addSet ) { addNode . addValueNode ( "value" , value ) ; } } if ( removeSet != null && removeSet . size ( ) > 0 ) { UNode addNode = fieldNode . addArrayNode ( "remove" ) ; for ( String value : removeSet ) { addNode . addValueNode ( "value" , value ) ; } } } } | parent node . |
17,871 | private void groupFieldtoDoc ( UNode parentNode , FieldDefinition groupFieldDef , Set < FieldDefinition > deferredFields ) { assert parentNode != null ; assert groupFieldDef != null && groupFieldDef . isGroupField ( ) ; assert deferredFields != null && deferredFields . size ( ) > 0 ; UNode groupNode = parentNode . addMapNode ( groupFieldDef . getName ( ) , "field" ) ; for ( FieldDefinition nestedFieldDef : groupFieldDef . getNestedFields ( ) ) { if ( ! deferredFields . contains ( nestedFieldDef ) ) { continue ; } if ( nestedFieldDef . isGroupField ( ) ) { groupFieldtoDoc ( groupNode , nestedFieldDef , deferredFields ) ; } else { leafFieldtoDoc ( groupNode , nestedFieldDef . getName ( ) ) ; } } } | given deferred - field map . Recurse is any child fields are also groups . |
17,872 | private void parseFieldUpdate ( String fieldName , UNode valueNode ) { if ( valueNode . isValue ( ) ) { addFieldValue ( fieldName , valueNode . getValue ( ) ) ; } else if ( valueNode . childrenAreValues ( ) ) { parseFieldAdd ( fieldName , valueNode ) ; } else { for ( UNode childNode : valueNode . getMemberList ( ) ) { if ( childNode . isCollection ( ) && childNode . getName ( ) . equals ( "add" ) && childNode . childrenAreValues ( ) ) { parseFieldAdd ( fieldName , childNode ) ; } else if ( childNode . isCollection ( ) && childNode . getName ( ) . equals ( "remove" ) && childNode . childrenAreValues ( ) ) { parseFieldRemove ( fieldName , childNode ) ; } else { parseFieldUpdate ( childNode . getName ( ) , childNode ) ; } } } } | Parse update to outer or nested field . |
17,873 | private String getSystemField ( String fieldName ) { List < String > values = m_valueMap . get ( fieldName ) ; return values == null ? null : values . get ( 0 ) ; } | Get the first value of the given field or null if there is no value . |
17,874 | public void parse ( UNode aliasNode ) { assert aliasNode != null ; setName ( aliasNode . getName ( ) ) ; for ( String childName : aliasNode . getMemberNames ( ) ) { UNode childNode = aliasNode . getMember ( childName ) ; Utils . require ( childNode . isValue ( ) , "Value of alias attribute must be a string: " + childNode ) ; Utils . require ( childName . equals ( "expression" ) , "'expression' expected: " + childName ) ; Utils . require ( m_expression == null , "'expression' can only be specified once" ) ; setExpression ( childNode . getValue ( ) ) ; } Utils . require ( m_expression != null , "Alias definition missing 'expression': " + aliasNode ) ; } | Parse the alias definition rooted at the given UNode copying its properties into this object . |
17,875 | public void update ( AliasDefinition newAliasDef ) { assert m_aliasName . equals ( newAliasDef . m_aliasName ) ; assert m_tableName . equals ( newAliasDef . m_tableName ) ; m_expression = newAliasDef . m_expression ; } | Update this alias definition to match the given updated one . The updated alias must have the same name and table name . |
17,876 | public void addValuesForField ( ) { String objID = m_dbObj . getObjectID ( ) ; assert ! Utils . isEmpty ( objID ) ; m_dbTran . addIDValueColumn ( m_tableDef , objID ) ; m_dbTran . addAllObjectsColumn ( m_tableDef , objID , m_tableDef . getShardNumber ( m_dbObj ) ) ; } | and the encoded object ID as the value . |
17,877 | public void deleteValuesForField ( ) { int shardNo = m_tableDef . getShardNumber ( m_dbObj ) ; m_dbTran . deleteAllObjectsColumn ( m_tableDef , m_dbObj . getObjectID ( ) , shardNo ) ; } | Object is being deleted . Just delete column in all objects row . |
17,878 | public boolean updateValuesForField ( String currentValue ) { Utils . require ( m_dbObj . getObjectID ( ) . equals ( currentValue ) , "Object ID cannot be changed" ) ; return false ; } | Object is being updated but _ID field cannot be changed . |
17,879 | public StorageService findStorageService ( String serviceName ) { Utils . require ( m_bInitialized , "DoradusService has not yet initialized" ) ; for ( StorageService service : m_storageServices ) { if ( service . getClass ( ) . getSimpleName ( ) . equals ( serviceName ) ) { return service ; } } return null ; } | Find a registered storage service with the given name . If there is no storage service with the registered name null is returned . This method can only be called after the DoradusServer has initialized . |
17,880 | public static String getDoradusVersion ( ) { String version = null ; try { Git git = Git . open ( new File ( "../.git" ) ) ; String url = git . getRepository ( ) . getConfig ( ) . getString ( "remote" , "origin" , "url" ) ; instance ( ) . m_logger . info ( "Remote.origin.url: {}" , url ) ; if ( ! Utils . isEmpty ( url ) && url . contains ( "dell-oss/Doradus.git" ) ) { DescribeCommand cmd = git . describe ( ) ; version = cmd . call ( ) ; instance ( ) . m_logger . info ( "Doradus version found from git repo: {}" , version ) ; writeVersionToVerFile ( version ) ; } } catch ( Throwable e ) { instance ( ) . m_logger . info ( "failed to read version from git repo" ) ; } if ( Utils . isEmpty ( version ) ) { try { version = getVersionFromVerFile ( ) ; instance ( ) . m_logger . info ( "Doradus version found from doradus.ver file {}" , version ) ; } catch ( IOException e1 ) { version = null ; } } return version ; } | Get Doradus Version from git repo if it exists ; otherwise get it from the local doradus . ver file |
17,881 | private static void writeVersionToVerFile ( String version ) throws IOException { try ( PrintWriter writer = new PrintWriter ( new File ( DoradusServer . class . getResource ( "/" + VERSION_FILE ) . getPath ( ) ) ) ) { writer . write ( version ) ; } } | Write version to local file |
17,882 | private static String getVersionFromVerFile ( ) throws IOException { try ( BufferedReader br = new BufferedReader ( new InputStreamReader ( DoradusServer . class . getResourceAsStream ( "/" + VERSION_FILE ) , "UTF-8" ) ) ) { return br . readLine ( ) ; } } | Get version from local file |
17,883 | private void addConfiguredStorageServices ( Set < String > serviceSet ) { List < String > ssList = ServerParams . instance ( ) . getModuleParamList ( "DoradusServer" , "storage_services" ) ; if ( ssList != null ) { serviceSet . addAll ( ssList ) ; } } | Add configured storage_services to the given set . |
17,884 | private void addDefaultServices ( Set < String > serviceSet ) { List < String > defaultServices = ServerParams . instance ( ) . getModuleParamList ( "DoradusServer" , "default_services" ) ; if ( defaultServices != null ) { serviceSet . addAll ( defaultServices ) ; } } | Add configured default_services to the given set . |
17,885 | private void initEmbedded ( String [ ] args , String [ ] services ) { if ( m_bInitialized ) { m_logger . warn ( "initEmbedded: Already initialized -- ignoring" ) ; return ; } m_logger . info ( "Initializing embedded mode" ) ; initConfig ( args ) ; initEmbeddedServices ( services ) ; RESTService . instance ( ) . registerCommands ( CMD_CLASSES ) ; m_bInitialized = true ; } | Initialize server configuration and given + required services for embedded running . |
17,886 | private void initEmbeddedServices ( String [ ] requestedServices ) { Set < String > serviceSet = new LinkedHashSet < > ( ) ; if ( requestedServices != null ) { serviceSet . addAll ( Arrays . asList ( requestedServices ) ) ; } addRequiredServices ( serviceSet ) ; initServices ( serviceSet ) ; } | Initialize services required for embedded start . |
17,887 | private void initStandAlone ( String [ ] args ) { if ( m_bInitialized ) { m_logger . warn ( "initStandAlone: Already initialized -- ignoring" ) ; return ; } m_logger . info ( "Initializing standalone mode" ) ; initConfig ( args ) ; initStandaAloneServices ( ) ; RESTService . instance ( ) . registerCommands ( CMD_CLASSES ) ; m_bInitialized = true ; } | Initialize server configuration and all services for stand - alone running . |
17,888 | private void initStandaAloneServices ( ) { Set < String > serviceSet = new LinkedHashSet < > ( ) ; addDefaultServices ( serviceSet ) ; addRequiredServices ( serviceSet ) ; addConfiguredStorageServices ( serviceSet ) ; initServices ( serviceSet ) ; } | Initialize services configured + needed for stand - alone operation . |
17,889 | private void initConfig ( String [ ] args ) { try { ServerParams . load ( args ) ; if ( Utils . isEmpty ( ServerParams . instance ( ) . getModuleParamString ( "DoradusServer" , "super_user" ) ) ) { m_logger . warn ( "'DoradusServer.super_user' parameter is not defined. " + "Privileged commands will be available without authentication." ) ; } } catch ( ConfigurationException e ) { throw new RuntimeException ( "Failed to initialize server configuration" , e ) ; } } | Initialize the ServerParams module which loads the doradus . yaml file . |
17,890 | private void initServices ( Set < String > serviceSet ) { for ( String serviceName : serviceSet ) { Service service = initService ( serviceName ) ; m_initializedServices . add ( service ) ; if ( service instanceof StorageService ) { m_storageServices . add ( ( StorageService ) service ) ; } } if ( m_storageServices . size ( ) == 0 ) { throw new RuntimeException ( "No storage services were configured" ) ; } } | StorageService objects . Throw if a storage service is not requested . |
17,891 | private Service initService ( String serviceName ) { m_logger . debug ( "Initializing service: " + serviceName ) ; try { @ SuppressWarnings ( "unchecked" ) Class < Service > serviceClass = ( Class < Service > ) Class . forName ( serviceName ) ; Method instanceMethod = serviceClass . getMethod ( "instance" , ( Class < ? > [ ] ) null ) ; Service instance = ( Service ) instanceMethod . invoke ( null , ( Object [ ] ) null ) ; instance . initialize ( ) ; return instance ; } catch ( Exception e ) { throw new RuntimeException ( "Error initializing service: " + serviceName , e ) ; } } | Initialize the service with the given package name . |
17,892 | private void start ( ) { if ( m_bRunning ) { m_logger . warn ( "start: Already started -- ignoring" ) ; return ; } Locale . setDefault ( Locale . ROOT ) ; m_logger . info ( "Doradus Version: {}" , getDoradusVersion ( ) ) ; hookShutdownEvent ( ) ; startServices ( ) ; m_bRunning = true ; } | Start the DoradusServer services . |
17,893 | private void startServices ( ) { m_logger . info ( "Starting services: {}" , simpleServiceNames ( m_initializedServices ) ) ; for ( Service service : m_initializedServices ) { m_logger . debug ( "Starting service: " + service . getClass ( ) . getSimpleName ( ) ) ; service . start ( ) ; m_startedServices . add ( service ) ; } } | Start all registered services . |
17,894 | private String simpleServiceNames ( Collection < Service > services ) { StringBuilder buffer = new StringBuilder ( ) ; for ( Service service : services ) { if ( buffer . length ( ) > 0 ) { buffer . append ( "," ) ; } buffer . append ( service . getClass ( ) . getSimpleName ( ) ) ; } return buffer . toString ( ) ; } | Get simple service names as a comma - separated list . |
17,895 | private void stopServices ( ) { m_logger . debug ( "Stopping all services" ) ; ListIterator < Service > iter = m_startedServices . listIterator ( m_startedServices . size ( ) ) ; while ( iter . hasPrevious ( ) ) { Service service = iter . previous ( ) ; m_logger . debug ( "Stopping service: " + service . getClass ( ) . getSimpleName ( ) ) ; service . stop ( ) ; iter . remove ( ) ; } m_initializedServices . clear ( ) ; m_storageServices . clear ( ) ; } | Stop all registered services . |
17,896 | private void stop ( ) { if ( m_bRunning ) { instance ( ) . m_logger . info ( "Doradus Server shutting down" ) ; stopServices ( ) ; ServerParams . unload ( ) ; m_bRunning = false ; m_bInitialized = false ; } } | Shutdown all services and terminate . |
17,897 | public static FieldUpdater createFieldUpdater ( ObjectUpdater objUpdater , DBObject dbObj , String fieldName ) { if ( fieldName . charAt ( 0 ) == '_' ) { if ( fieldName . equals ( CommonDefs . ID_FIELD ) ) { return new IDFieldUpdater ( objUpdater , dbObj ) ; } else { return new NullFieldUpdater ( objUpdater , dbObj , fieldName ) ; } } TableDefinition tableDef = objUpdater . getTableDef ( ) ; if ( tableDef . isLinkField ( fieldName ) ) { return new LinkFieldUpdater ( objUpdater , dbObj , fieldName ) ; } else { Utils . require ( FieldDefinition . isValidFieldName ( fieldName ) , "Invalid field name: %s" , fieldName ) ; return new ScalarFieldUpdater ( objUpdater , dbObj , fieldName ) ; } } | Create a FieldUpdater that will handle updates for the given object and field . |
17,898 | public DBObject getObject ( String tableName , String objectID ) { Utils . require ( ! Utils . isEmpty ( tableName ) , "tableName" ) ; Utils . require ( ! Utils . isEmpty ( objectID ) , "objectID" ) ; TableDefinition tableDef = m_appDef . getTableDef ( tableName ) ; Utils . require ( tableDef != null , "Unknown table for application '%s': %s" , m_appDef . getAppName ( ) , tableName ) ; try { StringBuilder uri = new StringBuilder ( Utils . isEmpty ( m_restClient . getApiPrefix ( ) ) ? "" : "/" + m_restClient . getApiPrefix ( ) ) ; uri . append ( "/" ) ; uri . append ( Utils . urlEncode ( m_appDef . getAppName ( ) ) ) ; uri . append ( "/" ) ; uri . append ( Utils . urlEncode ( tableName ) ) ; uri . append ( "/" ) ; uri . append ( Utils . urlEncode ( objectID ) ) ; RESTResponse response = m_restClient . sendRequest ( HttpMethod . GET , uri . toString ( ) ) ; m_logger . debug ( "getObject() response: {}" , response . toString ( ) ) ; if ( response . getCode ( ) != HttpCode . OK ) { return null ; } return new DBObject ( ) . parse ( getUNodeResult ( response ) ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } | Get the object with the given ID from the given table . Null is returned if there is no such object . |
17,899 | private BatchResult createBatchResult ( RESTResponse response , DBObjectBatch dbObjBatch ) { BatchResult result = null ; if ( response . getCode ( ) . isError ( ) ) { String errMsg = response . getBody ( ) ; if ( errMsg . length ( ) == 0 ) { errMsg = "Unknown error; response code=" + response . getCode ( ) ; } result = BatchResult . newErrorResult ( errMsg ) ; } else { result = new BatchResult ( getUNodeResult ( response ) ) ; copyObjectIDsToBatch ( result , dbObjBatch ) ; } return result ; } | Extract the BatchResult from the given RESTResponse . Could be an error . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.