idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
17,800
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 .
51
12
17,801
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 .
157
9
17,802
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 .
229
9
17,803
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
173
10
17,804
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 .
59
27
17,805
public void setTableDefinition ( TableDefinition tableDef ) { m_tableDef = tableDef ; // LINK and XLINK 'table' defaults to owning table. 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 .
76
17
17,806
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 .
44
29
17,807
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 .
81
28
17,808
private void verify ( ) { Utils . require ( ! Utils . isEmpty ( m_name ) , "Field name is required" ) ; Utils . require ( m_type != null , "Field type is required" ) ; // If an 'inverse' or 'table' was specified, type must be LINK or XLINK. 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 ) ; // LINK and XLINK require an 'inverse'. Utils . require ( ! m_type . isLinkType ( ) || m_linkInverse != null , "Missing 'inverse' option: " + m_name ) ; // XLINK requires a junction field: default is "_ID". 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 collection was not explicitly set, set to true for links and false for scalars if ( ! m_bIsCollection && m_type . isLinkType ( ) ) { m_bIsCollection = true ; } // 'analyzer' can only be set for scalar field types, but don't verify value here. Utils . require ( m_analyzerName == null || m_type . isScalarType ( ) , "'analyzer' can only be specified for scalar field types: " + m_analyzerName ) ; // If this is a binary field, ensure "encoding" is set. 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 ( ) ; } // Binary fields cannot be collections. Utils . require ( m_type != FieldType . BINARY || ! m_bIsCollection , "Binary fields cannot be collections (multi-valued)" ) ; }
Verify that this field definition is complete and coherent .
537
11
17,809
public void delete ( ) { for ( int i = 1 ; i < m_nextNo ; i ++ ) { new File ( m_fileName + "_" + i ) . delete ( ) ; } m_nextNo = 1 ; }
Deleting data files .
51
6
17,810
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 .
66
10
17,811
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
171
11
17,812
public void setKeyStore ( String keyStore , String keyPass ) { setKeyStore ( keyStore , keyPass , null , null ) ; }
Set the keystore and password
31
6
17,813
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
171
11
17,814
public void setTrustStore ( String trustStore , String trustPass ) { setTrustStore ( trustStore , trustPass , null , null ) ; }
Set the truststore and password
31
6
17,815
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 ; // Both nodes are parameters; names are irrelevant } return 1 ; // r1 is a parameter but r2 is not, so r2 should come first } if ( node2 . length ( ) > 0 && node2 . charAt ( 0 ) == ' ' ) { return - 1 ; // r2 is a parameter but r1 is not, so r1 should come first } return node1 . compareTo ( node2 ) ; // neither node is a parameter }
path nodes are query parameters . Either node can be empty but not null .
192
15
17,816
private static boolean matches ( String value , String component , Map < String , String > variableMap ) { if ( Utils . isEmpty ( component ) ) { return Utils . isEmpty ( value ) ; } if ( component . charAt ( 0 ) == ' ' ) { // The component is a variable, so it always matches. 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 .
119
11
17,817
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 .
59
9
17,818
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 .
140
14
17,819
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 .
116
11
17,820
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
114
10
17,821
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 .
45
28
17,822
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 .
48
16
17,823
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
129
11
17,824
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
32
15
17,825
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
99
10
17,826
private synchronized void loadRESTRulesIfNotExist ( RESTClient restClient ) { if ( restMetadataJson == null || restMetadataJson . isEmpty ( ) ) { restMetadataJson = loadRESTCommandsFromServer ( restClient ) ; } }
Load RESTRules once
60
5
17,827
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
177
7
17,828
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 .
98
7
17,829
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 .
74
19
17,830
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 .
41
30
17,831
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 .
78
32
17,832
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 .
107
54
17,833
public boolean isDeleted ( ) { String value = getSystemField ( _DELETED ) ; return value == null ? false : Boolean . parseBoolean ( value ) ; }
Get this object s deleted flag if set .
38
9
17,834
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 .
131
43
17,835
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 .
56
18
17,836
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 .
113
39
17,837
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 .
120
74
17,838
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 .
280
3
17,839
private void groupFieldtoDoc ( UNode parentNode , FieldDefinition groupFieldDef , Set < FieldDefinition > deferredFields ) { // Prerequisities: 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 .
193
16
17,840
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 ( ) ) { // "add" for an MV field parseFieldAdd ( fieldName , childNode ) ; } else if ( childNode . isCollection ( ) && childNode . getName ( ) . equals ( "remove" ) && childNode . childrenAreValues ( ) ) { // "remove" for an MV field parseFieldRemove ( fieldName , childNode ) ; } else { parseFieldUpdate ( childNode . getName ( ) , childNode ) ; } } } }
Parse update to outer or nested field .
221
9
17,841
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 .
43
16
17,842
public void parse ( UNode aliasNode ) { assert aliasNode != null ; // Ensure the alias name is valid and save it. setName ( aliasNode . getName ( ) ) ; // The only child element we expect is "expression". for ( String childName : aliasNode . getMemberNames ( ) ) { // All child nodes must be values. 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 ( ) ) ; } // Ensure expression was specified. 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 .
211
18
17,843
public void update ( AliasDefinition newAliasDef ) { assert m_aliasName . equals ( newAliasDef . m_aliasName ) ; assert m_tableName . equals ( newAliasDef . m_tableName ) ; // Currently, all we have to do is copy over the "expression" property. 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 .
78
23
17,844
@ Override 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 .
97
9
17,845
@ Override 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 .
67
13
17,846
@ Override 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 .
50
12
17,847
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 .
78
39
17,848
public static String getDoradusVersion ( ) { String version = null ; try { //first read from the local git repository 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 not found, reading from local file 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
305
25
17,849
private static void writeVersionToVerFile ( String version ) throws IOException { //declared in a try-with-resource statement, it will be closed regardless of it completes normally or not try ( PrintWriter writer = new PrintWriter ( new File ( DoradusServer . class . getResource ( "/" + VERSION_FILE ) . getPath ( ) ) ) ) { writer . write ( version ) ; } }
Write version to local file
88
5
17,850
private static String getVersionFromVerFile ( ) throws IOException { //declared in a try-with-resource statement, it will be closed regardless of it completes normally or not try ( BufferedReader br = new BufferedReader ( new InputStreamReader ( DoradusServer . class . getResourceAsStream ( "/" + VERSION_FILE ) , "UTF-8" ) ) ) { return br . readLine ( ) ; } }
Get version from local file
94
5
17,851
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 .
71
10
17,852
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 .
69
10
17,853
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 .
104
13
17,854
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 .
73
8
17,855
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 .
102
13
17,856
private void initStandaAloneServices ( ) { Set < String > serviceSet = new LinkedHashSet <> ( ) ; addDefaultServices ( serviceSet ) ; addRequiredServices ( serviceSet ) ; addConfiguredStorageServices ( serviceSet ) ; initServices ( serviceSet ) ; }
Initialize services configured + needed for stand - alone operation .
62
12
17,857
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 .
125
19
17,858
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 .
98
13
17,859
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 .
147
10
17,860
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 .
94
8
17,861
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 .
88
5
17,862
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 .
79
11
17,863
private void stopServices ( ) { // Stop services in reverse order of starting. 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 .
135
5
17,864
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 .
66
7
17,865
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 { // Allow but skip all other system fields (e.g., "_table") 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 .
227
17
17,866
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 { // Send a GET request to "/{application}/{table}/{object ID}" 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 the response is not "OK", return null. 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 .
388
22
17,867
private BatchResult createBatchResult ( RESTResponse response , DBObjectBatch dbObjBatch ) { // See what kind of message payload, if any, we received. 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 .
154
17
17,868
private void copyObjectIDsToBatch ( BatchResult batchResult , DBObjectBatch dbObjBatch ) { if ( batchResult . getResultObjectCount ( ) < dbObjBatch . getObjectCount ( ) ) { m_logger . warn ( "Batch result returned fewer objects ({}) than input batch ({})" , batchResult . getResultObjectCount ( ) , dbObjBatch . getObjectCount ( ) ) ; } Iterator < ObjectResult > resultIter = batchResult . getResultObjects ( ) . iterator ( ) ; Iterator < DBObject > objectIter = dbObjBatch . getObjects ( ) . iterator ( ) ; while ( resultIter . hasNext ( ) ) { if ( ! objectIter . hasNext ( ) ) { m_logger . warn ( "Batch result has more objects ({}) than input batch ({})!" , batchResult . getResultObjectCount ( ) , dbObjBatch . getObjectCount ( ) ) ; break ; } ObjectResult objResult = resultIter . next ( ) ; DBObject dbObj = objectIter . next ( ) ; if ( Utils . isEmpty ( dbObj . getObjectID ( ) ) ) { dbObj . setObjectID ( objResult . getObjectID ( ) ) ; } else if ( ! dbObj . getObjectID ( ) . equals ( objResult . getObjectID ( ) ) ) { m_logger . warn ( "Batch results out of order: expected ID '{}', got '{}'" , dbObj . getObjectID ( ) , objResult . getObjectID ( ) ) ; } } }
within the given DBObjectBatch .
349
8
17,869
private void verifyApplication ( ) { String ss = m_appDef . getStorageService ( ) ; if ( Utils . isEmpty ( ss ) || ! ss . startsWith ( "Spider" ) ) { throw new RuntimeException ( "Application '" + m_appDef . getAppName ( ) + "' is not an Spider application" ) ; } }
Throw if this session s AppDef is not for a Spider app .
76
14
17,870
double getVersionNumber ( ) { if ( cassandraVersion > 0 ) { return cassandraVersion ; } String version = getReleaseVersion ( ) ; if ( version == null ) { throw new IllegalStateException ( "Can't get Cassandra release version." ) ; } String [ ] toks = version . split ( "\\." ) ; if ( toks . length >= 3 ) { try { StringBuilder b = new StringBuilder ( ) ; int len = toks [ 0 ] . length ( ) ; if ( len == 1 ) { b . append ( "00" ) ; } else if ( len == 2 ) { b . append ( "0" ) ; } b . append ( toks [ 0 ] ) ; len = toks [ 1 ] . length ( ) ; if ( len == 1 ) { b . append ( "00" ) ; } else if ( len == 2 ) { b . append ( "0" ) ; } b . append ( toks [ 1 ] ) ; for ( int i = 0 ; i < toks [ 2 ] . length ( ) ; i ++ ) { char c = toks [ 2 ] . charAt ( i ) ; if ( Character . isDigit ( c ) ) { if ( i == 0 ) { b . append ( ' ' ) ; } b . append ( c ) ; } else { break ; } } cassandraVersion = Double . valueOf ( b . toString ( ) ) ; return cassandraVersion ; } catch ( Exception e ) { } } throw new IllegalStateException ( "Can't parse Cassandra release version string: \"" + version + "\"" ) ; }
12 . 23 . 345bla - bla = > 012023 . 345
346
17
17,871
private Map < File , File [ ] > getDataMap_1_1 ( String [ ] dataDirs ) { Map < File , File [ ] > map = new HashMap < File , File [ ] > ( ) ; boolean doLog = false ; if ( ! lockedMessages . contains ( "getDataMap" ) ) { lockedMessages . add ( "getDataMap" ) ; doLog = true ; } for ( int i = 0 ; i < dataDirs . length ; i ++ ) { File dir = new File ( dataDirs [ i ] ) ; if ( ! dir . canRead ( ) ) { if ( doLog ) { logger . warn ( "Can't read: " + dir ) ; } continue ; } File [ ] ksList = dir . listFiles ( ) ; for ( int j = 0 ; j < ksList . length ; j ++ ) { if ( ksList [ j ] . isDirectory ( ) ) { File [ ] familyList = ksList [ j ] . listFiles ( ) ; for ( int n = 0 ; n < familyList . length ; n ++ ) { if ( familyList [ n ] . isDirectory ( ) ) { ArrayList < File > snapshots = new ArrayList < File > ( ) ; File snDir = new File ( familyList [ n ] , SNAPSHOTS_DIR_NAME ) ; if ( snDir . isDirectory ( ) ) { File [ ] snList = snDir . listFiles ( ) ; for ( int k = 0 ; k < snList . length ; k ++ ) { if ( snList [ k ] . isDirectory ( ) ) { snapshots . add ( snList [ k ] ) ; } } } map . put ( familyList [ n ] , snapshots . toArray ( new File [ snapshots . size ( ) ] ) ) ; } } } } } // if(doLog) { // logger.debug("familiesCount=" + map.size()); // // for(File f : map.keySet()) { // File[] snaps = map.get(f); // logger.debug("family: " + f.getAbsolutePath() + ", snapshotsCount=" + snaps.length); // // for(int i = 0; i < snaps.length; i++) { // logger.debug("snaps[" + i + "]: " + snaps[i]); // } // } // } return map ; }
family - dir - > snapshot - dir - list
515
10
17,872
private Map < File , File > getDataMap ( int vcode , String [ ] dataDirs , String snapshotName ) { Map < File , File > map = new HashMap < File , File > ( ) ; Map < File , File [ ] > src = vcode == 0 ? getDataMap_1_0 ( dataDirs ) : getDataMap_1_1 ( dataDirs ) ; for ( File ks : src . keySet ( ) ) { File [ ] sn = src . get ( ks ) ; if ( sn != null ) { for ( int i = 0 ; i < sn . length ; i ++ ) { if ( snapshotName . equals ( sn [ i ] . getName ( ) ) ) { map . put ( ks , sn [ i ] ) ; break ; } } } } return map ; }
keyspace - dir - > snapshot - dir
180
9
17,873
private void run ( String [ ] args ) { if ( args . length != 2 ) { usage ( ) ; } System . out . println ( "Opening Doradus server: " + args [ 0 ] + ":" + args [ 1 ] ) ; try ( DoradusClient client = new DoradusClient ( args [ 0 ] , Integer . parseInt ( args [ 1 ] ) ) ) { deleteApplication ( client ) ; createApplication ( client ) ; addData ( client ) ; queryData ( client ) ; deleteData ( client ) ; } }
Create a Dory client connection and execute the example commands .
117
12
17,874
private void deleteApplication ( DoradusClient client ) { Command command = Command . builder ( ) . withName ( "DeleteAppWithKey" ) . withParam ( "application" , "HelloSpider" ) . withParam ( "key" , "Arachnid" ) . build ( ) ; client . runCommand ( command ) ; // Ignore response }
Delete the existing HelloSpider application if present .
76
9
17,875
private void createApplication ( DoradusClient client ) { ApplicationDefinition appDef = ApplicationDefinition . builder ( ) . withName ( "HelloSpider" ) . withKey ( "Arachnid" ) . withOption ( "StorageService" , "SpiderService" ) . withTable ( TableDefinition . builder ( ) . withName ( "Movies" ) . withField ( FieldDefinition . builder ( ) . withName ( "Name" ) . withType ( FieldType . TEXT ) . build ( ) ) . withField ( FieldDefinition . builder ( ) . withName ( "ReleaseDate" ) . withType ( FieldType . TIMESTAMP ) . build ( ) ) . withField ( FieldDefinition . builder ( ) . withName ( "Cancelled" ) . withType ( FieldType . BOOLEAN ) . build ( ) ) . withField ( FieldDefinition . builder ( ) . withName ( "Director" ) . withType ( FieldType . TEXT ) . build ( ) ) . withField ( FieldDefinition . builder ( ) . withName ( "Leads" ) . withType ( FieldType . LINK ) . withExtent ( "Actors" ) . withInverse ( "ActedIn" ) . build ( ) ) . withField ( FieldDefinition . builder ( ) . withName ( "Budget" ) . withType ( FieldType . INTEGER ) . build ( ) ) . build ( ) ) . withTable ( TableDefinition . builder ( ) . withName ( "Actors" ) . withField ( FieldDefinition . builder ( ) . withName ( "FirstName" ) . withType ( FieldType . TEXT ) . build ( ) ) . withField ( FieldDefinition . builder ( ) . withName ( "LastName" ) . withType ( FieldType . TEXT ) . build ( ) ) . withField ( FieldDefinition . builder ( ) . withName ( "ActedIn" ) . withType ( FieldType . LINK ) . withExtent ( "Movies" ) . withInverse ( "Leads" ) . build ( ) ) . build ( ) ) . build ( ) ; Command command = Command . builder ( ) . withName ( "DefineApp" ) . withParam ( "ApplicationDefinition" , appDef ) . build ( ) ; RESTResponse response = client . runCommand ( command ) ; if ( response . isFailed ( ) ) { throw new RuntimeException ( "DefineApp failed: " + response ) ; } }
Create the HelloSpider application definition .
529
7
17,876
private void deleteData ( DoradusClient client ) { DBObject dbObject = DBObject . builder ( ) . withValue ( "_ID" , "TMaguire" ) . build ( ) ; DBObjectBatch dbObjectBatch = DBObjectBatch . builder ( ) . withObject ( dbObject ) . build ( ) ; Command command = Command . builder ( ) . withName ( "Delete" ) . withParam ( "application" , "HelloSpider" ) . withParam ( "table" , "Actors" ) . withParam ( "batch" , dbObjectBatch ) . build ( ) ; RESTResponse response = client . runCommand ( command ) ; if ( response . isFailed ( ) ) { throw new RuntimeException ( "Delete batch failed: " + response . getBody ( ) ) ; } }
Delete data by ID
176
4
17,877
private void loadSchema ( ) { m_logger . info ( "Loading schema for application: {}" , m_config . app ) ; m_client = new Client ( m_config . host , m_config . port , m_config . getTLSParams ( ) ) ; m_client . setCredentials ( m_config . getCredentials ( ) ) ; m_session = m_client . openApplication ( m_config . app ) ; // throws if unknown app m_appDef = m_session . getAppDef ( ) ; if ( m_config . optimize ) { computeLinkFanouts ( ) ; } }
Connect to the Doradus server and download the requested application s schema .
140
15
17,878
private void computeLinkFanouts ( TableDefinition tableDef , Map < String , MutableFloat > tableLinkFanoutMap ) { m_logger . info ( "Computing link field fanouts for table: {}" , tableDef . getTableName ( ) ) ; StringBuilder buffer = new StringBuilder ( ) ; for ( FieldDefinition fieldDef : tableDef . getFieldDefinitions ( ) ) { if ( fieldDef . isLinkField ( ) ) { if ( buffer . length ( ) > 0 ) { buffer . append ( "," ) ; } buffer . append ( fieldDef . getName ( ) ) ; } } if ( buffer . length ( ) == 0 ) { return ; } Map < String , String > queryParams = new HashMap <> ( ) ; queryParams . put ( "q" , "*" ) ; queryParams . put ( "f" , buffer . toString ( ) ) ; queryParams . put ( "s" , Integer . toString ( LINK_FANOUT_SAMPLE_SIZE ) ) ; if ( m_session instanceof OLAPSession ) { queryParams . put ( "shards" , m_config . shard ) ; } QueryResult qResult = m_session . objectQuery ( tableDef . getTableName ( ) , queryParams ) ; Collection < DBObject > objectSet = qResult . getResultObjects ( ) ; if ( objectSet . size ( ) == 0 ) { return ; } Map < String , AtomicInteger > linkValueCounts = new HashMap < String , AtomicInteger > ( ) ; int totalObjs = 0 ; for ( DBObject dbObj : objectSet ) { totalObjs ++ ; for ( String fieldName : dbObj . getFieldNames ( ) ) { if ( tableDef . isLinkField ( fieldName ) ) { Collection < String > linkValues = dbObj . getFieldValues ( fieldName ) ; AtomicInteger totalLinkValues = linkValueCounts . get ( fieldName ) ; if ( totalLinkValues == null ) { linkValueCounts . put ( fieldName , new AtomicInteger ( linkValues . size ( ) ) ) ; } else { totalLinkValues . addAndGet ( linkValues . size ( ) ) ; } } } } for ( String fieldName : linkValueCounts . keySet ( ) ) { AtomicInteger totalLinkValues = linkValueCounts . get ( fieldName ) ; float linkFanout = totalLinkValues . get ( ) / ( float ) totalObjs ; // may round to 0 m_logger . info ( "Average fanout for link {}: {}" , fieldName , linkFanout ) ; tableLinkFanoutMap . put ( fieldName , new MutableFloat ( linkFanout ) ) ; } }
Compute link fanouts for the given table
592
9
17,879
private void start ( long time , String name ) { name = getName ( name ) ; TimerGroupItem timer = m_timers . get ( name ) ; if ( timer == null ) { timer = new TimerGroupItem ( name ) ; m_timers . put ( name , timer ) ; } timer . start ( time ) ; m_total . start ( time ) ; }
Start the named timer if the condition is true .
83
10
17,880
private long stop ( long time , String name ) { m_total . stop ( time ) ; TimerGroupItem timer = m_timers . get ( getName ( name ) ) ; long elapsedTime = 0 ; if ( timer != null ) { elapsedTime = timer . stop ( time ) ; } checkLog ( time ) ; return elapsedTime ; }
Stop the named timer if the condition is true .
75
10
17,881
private void log ( boolean finalLog , String format , Object ... args ) { if ( m_condition ) { if ( format != null ) { m_logger . debug ( String . format ( format , args ) ) ; } ArrayList < String > timerNames = new ArrayList < String > ( m_timers . keySet ( ) ) ; Collections . sort ( timerNames ) ; for ( String name : timerNames ) { TimerGroupItem timer = m_timers . get ( name ) ; if ( finalLog || timer . changed ( ) ) { m_logger . debug ( timer . toString ( finalLog ) ) ; } } m_logger . debug ( m_total . toString ( finalLog ) ) ; ArrayList < String > counterNames = new ArrayList < String > ( m_counters . keySet ( ) ) ; Collections . sort ( counterNames ) ; for ( String name : counterNames ) { Counter counter = m_counters . get ( name ) ; if ( finalLog || counter . changed ( ) ) { String text = String . format ( "%s: (%s)" , name , counter . toString ( finalLog ) ) ; m_logger . debug ( text ) ; } } } }
Log elapsed time of all named timers if the condition is true .
265
13
17,882
public void parse ( UNode rootNode ) { assert rootNode != null ; // Ensure root node is named "batch". Utils . require ( rootNode . getName ( ) . equals ( "batch" ) , "'batch' expected: " + rootNode . getName ( ) ) ; // Parse child nodes. for ( String memberName : rootNode . getMemberNames ( ) ) { UNode childNode = rootNode . getMember ( memberName ) ; if ( childNode . getName ( ) . equals ( "docs" ) ) { Utils . require ( childNode . isCollection ( ) , "'docs' must be a collection: " + childNode ) ; for ( UNode docNode : childNode . getMemberList ( ) ) { Utils . require ( docNode . getName ( ) . equals ( "doc" ) , "'doc' node expected as child of 'docs': " + docNode ) ; addObject ( new DBObject ( ) ) . parse ( docNode ) ; } } else { Utils . require ( false , "Unrecognized child node of 'batch': " + memberName ) ; } } }
Parse a batch object update rooted at the given UNode . The root node must be a MAP named batch . Child nodes must be a recognized option or a docs array containing doc objects . An exception is thrown if the batch is malformed .
243
49
17,883
public UNode toDoc ( ) { // Root object is a MAP called "batch". UNode batchNode = UNode . createMapNode ( "batch" ) ; // Add a "docs" node as an array. UNode docsNode = batchNode . addArrayNode ( "docs" ) ; for ( DBObject dbObj : m_dbObjList ) { docsNode . addChildNode ( dbObj . toDoc ( ) ) ; } return batchNode ; }
Serialize this DBObjectBatch object into a UNode tree and return the root node .
99
19
17,884
public DBObject addObject ( String objID , String tableName ) { DBObject dbObj = new DBObject ( objID , tableName ) ; m_dbObjList . add ( dbObj ) ; return dbObj ; }
Create a new DBObject with the given object ID and table name add it to this DBObjectBatch and return it .
48
25
17,885
private Server configureJettyServer ( ) { LinkedBlockingQueue < Runnable > taskQueue = new LinkedBlockingQueue < Runnable > ( m_maxTaskQueue ) ; QueuedThreadPool threadPool = new QueuedThreadPool ( m_maxconns , m_defaultMinThreads , m_defaultIdleTimeout , taskQueue ) ; Server server = new Server ( threadPool ) ; server . setStopAtShutdown ( true ) ; return server ; }
Create configure and return the Jetty Server object .
103
10
17,886
private ServerConnector configureConnector ( ) { ServerConnector connector = null ; if ( m_tls ) { connector = createSSLConnector ( ) ; } else { // Unsecured connector connector = new ServerConnector ( m_jettyServer ) ; } if ( m_restaddr != null ) { connector . setHost ( m_restaddr ) ; } connector . setPort ( m_restport ) ; connector . setIdleTimeout ( SOCKET_TIMEOUT_MILLIS ) ; connector . addBean ( new ConnListener ( ) ) ; // invokes registered callbacks, if any return connector ; }
Create configure and return the ServerConnector object .
130
9
17,887
private ServletHandler configureHandler ( String servletClassName ) { ServletHandler handler = new ServletHandler ( ) ; handler . addServletWithMapping ( servletClassName , "/*" ) ; return handler ; }
Create configure and return the ServletHandler object .
49
10
17,888
@ Override public final void run ( ) { String taskID = m_taskRecord . getTaskID ( ) ; m_logger . debug ( "Starting task '{}' in tenant '{}'" , taskID , m_tenant ) ; try { TaskManagerService . instance ( ) . registerTaskStarted ( this ) ; m_lastProgressTimestamp = System . currentTimeMillis ( ) ; setTaskStart ( ) ; execute ( ) ; setTaskFinish ( ) ; } catch ( Throwable e ) { m_logger . error ( "Task '" + taskID + "' failed" , e ) ; String stackTrace = Utils . getStackTrace ( e ) ; setTaskFailed ( stackTrace ) ; } finally { TaskManagerService . instance ( ) . registerTaskEnded ( this ) ; } }
Called by the TaskManagerService to begin the execution of the task .
182
15
17,889
private void setTaskStart ( ) { m_taskRecord . setProperty ( TaskRecord . PROP_EXECUTOR , m_hostID ) ; m_taskRecord . setProperty ( TaskRecord . PROP_START_TIME , Long . toString ( System . currentTimeMillis ( ) ) ) ; m_taskRecord . setProperty ( TaskRecord . PROP_FINISH_TIME , null ) ; m_taskRecord . setProperty ( TaskRecord . PROP_PROGRESS , null ) ; m_taskRecord . setProperty ( TaskRecord . PROP_PROGRESS_TIME , null ) ; m_taskRecord . setProperty ( TaskRecord . PROP_FAIL_REASON , null ) ; m_taskRecord . setStatus ( TaskStatus . IN_PROGRESS ) ; TaskManagerService . instance ( ) . updateTaskStatus ( m_tenant , m_taskRecord , false ) ; }
Update the job status record that shows this job has started .
201
12
17,890
private void setTaskFailed ( String reason ) { m_taskRecord . setProperty ( TaskRecord . PROP_EXECUTOR , m_hostID ) ; m_taskRecord . setProperty ( TaskRecord . PROP_FINISH_TIME , Long . toString ( System . currentTimeMillis ( ) ) ) ; m_taskRecord . setProperty ( TaskRecord . PROP_FAIL_REASON , reason ) ; m_taskRecord . setStatus ( TaskStatus . FAILED ) ; TaskManagerService . instance ( ) . updateTaskStatus ( m_tenant , m_taskRecord , true ) ; }
Update the job status record that shows this job has failed .
136
12
17,891
private void reconnect ( ) throws IOException { // First ensure we're closed. close ( ) ; // Attempt to re-open. try { createSocket ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; throw new IOException ( "Cannot connect to server" , e ) ; } m_inStream = m_socket . getInputStream ( ) ; m_outStream = m_socket . getOutputStream ( ) ; }
Attempt to reconnect to the Doradus server
98
9
17,892
private RESTResponse sendAndReceive ( HttpMethod method , String uri , Map < String , String > headers , byte [ ] body ) throws IOException { // Add standard headers assert headers != null ; headers . put ( HttpDefs . HOST , m_host ) ; headers . put ( HttpDefs . ACCEPT , m_acceptFormat . toString ( ) ) ; headers . put ( HttpDefs . CONTENT_LENGTH , Integer . toString ( body == null ? 0 : body . length ) ) ; if ( m_bCompress ) { headers . put ( HttpDefs . ACCEPT_ENCODING , "gzip" ) ; } if ( m_credentials != null ) { String authString = "Basic " + Utils . base64FromString ( m_credentials . getUserid ( ) + ":" + m_credentials . getPassword ( ) ) ; headers . put ( "Authorization" , authString ) ; } // Form the message header. StringBuilder buffer = new StringBuilder ( ) ; buffer . append ( method . toString ( ) ) ; buffer . append ( " " ) ; buffer . append ( addTenantParam ( uri ) ) ; buffer . append ( " HTTP/1.1\r\n" ) ; for ( String name : headers . keySet ( ) ) { buffer . append ( name ) ; buffer . append ( ": " ) ; buffer . append ( headers . get ( name ) ) ; buffer . append ( "\r\n" ) ; } buffer . append ( "\r\n" ) ; m_logger . debug ( "Sending request to uri '{}'; message length={}" , uri , headers . get ( HttpDefs . CONTENT_LENGTH ) ) ; return sendAndReceive ( buffer . toString ( ) , body ) ; }
Add standard headers to the given request and send it .
408
11
17,893
private RESTResponse sendAndReceive ( String header , byte [ ] body ) throws IOException { // Fail before trying if socket has been closed. if ( isClosed ( ) ) { throw new IOException ( "Socket has been closed" ) ; } Exception lastException = null ; for ( int attempt = 0 ; attempt < MAX_SOCKET_RETRIES ; attempt ++ ) { try { sendRequest ( header , body ) ; return readResponse ( ) ; } catch ( IOException e ) { // Attempt to reconnect; if this fails, the server's probably down and we // let reconnect's IOException pass through. lastException = e ; m_logger . warn ( "Socket error occurred -- reconnecting" , e ) ; reconnect ( ) ; } } // Here, all reconnects succeeded but retries failed; something else is wrong with // the server or the request. throw new IOException ( "Socket error; all retries failed" , lastException ) ; }
we reconnect and retry up to MAX_SOCKET_RETRIES before giving up .
205
20
17,894
private void sendRequest ( String header , byte [ ] body ) throws IOException { // Send entire message in one write, else suffer the fate of weird TCP/IP stacks. byte [ ] headerBytes = Utils . toBytes ( header ) ; byte [ ] requestBytes = headerBytes ; if ( body != null && body . length > 0 ) { requestBytes = new byte [ headerBytes . length + body . length ] ; System . arraycopy ( headerBytes , 0 , requestBytes , 0 , headerBytes . length ) ; System . arraycopy ( body , 0 , requestBytes , headerBytes . length , body . length ) ; } // Send the header and body (if any) and flush the result. m_outStream . write ( requestBytes ) ; m_outStream . flush ( ) ; }
Send the request represented by the given header and optional body .
169
12
17,895
private RESTResponse readResponse ( ) throws IOException { // Read response code from the header line. HttpCode resultCode = readStatusLine ( ) ; // Read and save headers, keeping track of content-length if we find it. Map < String , String > headers = new HashMap < String , String > ( ) ; int contentLength = 0 ; String headerLine = readHeader ( ) ; while ( headerLine . length ( ) > 2 ) { // Read header and split into parts based on ":" separator. Both parts are // trimmed, and the header is up-cased. int colonInx = headerLine . indexOf ( ' ' ) ; String headerName = // Use the whole line if there's no colon colonInx <= 0 ? headerLine . trim ( ) . toUpperCase ( ) : headerLine . substring ( 0 , colonInx ) . trim ( ) . toUpperCase ( ) ; String headerValue = // Use an empty string if there's no colon colonInx <= 0 ? "" : headerLine . substring ( colonInx + 1 ) . trim ( ) ; headers . put ( headerName , headerValue ) ; if ( headerName . equals ( HttpDefs . CONTENT_LENGTH ) ) { try { contentLength = Integer . parseInt ( headerValue ) ; } catch ( NumberFormatException e ) { // Turn into IOException throw new IOException ( "Invalid content-length value: " + headerLine ) ; } } headerLine = readHeader ( ) ; } // Final header line should be CRLF if ( ! headerLine . equals ( "\r\n" ) ) { throw new IOException ( "Header not properly terminated: " + headerLine ) ; } // If we have a response entity, read that now. byte [ ] body = null ; if ( contentLength > 0 ) { body = readBody ( contentLength ) ; // Decompress output entity if needed. String contentEncoding = headers . get ( HttpDefs . CONTENT_ENCODING ) ; if ( contentEncoding != null ) { Utils . require ( contentEncoding . equalsIgnoreCase ( "gzip" ) , "Unrecognized output Content-Encoding: " + contentEncoding ) ; body = Utils . decompressGZIP ( body ) ; } } return new RESTResponse ( resultCode , body , headers ) ; }
a RESTResponse object .
510
5
17,896
private HttpCode readStatusLine ( ) throws IOException { // Read a line of text, which should be in the format HTTP/<version <code> <reason> String statusLine = readHeader ( ) ; String [ ] parts = statusLine . split ( " +" ) ; if ( parts . length < 3 ) { throw new IOException ( "Badly formed response status line: " + statusLine ) ; } try { // Attempt to convert the return code into an enum. int code = Integer . parseInt ( parts [ 1 ] ) ; HttpCode result = HttpCode . findByCode ( code ) ; if ( result == null ) { throw new IOException ( "Unrecognized result code: " + code ) ; } return result ; } catch ( NumberFormatException e ) { // Turn into a bad response line error. throw new IOException ( "Badly formed response status line: " + statusLine ) ; } }
Read a REST response status line and return the status code from it .
199
14
17,897
private void createSocket ( ) throws Exception { // Some socket options, notably setReceiveBufferSize, must be set before the // socket is connected. So, first create the socket, then set options, then connect. if ( m_sslParams != null ) { SSLSocketFactory factory = m_sslParams . createSSLContext ( ) . getSocketFactory ( ) ; m_socket = factory . createSocket ( m_host , m_port ) ; setSocketOptions ( ) ; ( ( SSLSocket ) m_socket ) . startHandshake ( ) ; } else { m_socket = new Socket ( ) ; setSocketOptions ( ) ; SocketAddress sockAddr = new InetSocketAddress ( m_host , m_port ) ; m_socket . connect ( sockAddr ) ; } }
Create a socket connection setting m_socket using configured parameters .
173
12
17,898
private void setSocketOptions ( ) throws SocketException { if ( DISABLE_NAGLES ) { // Disable Nagle's algorithm (significant on Windows). m_socket . setTcpNoDelay ( true ) ; m_logger . debug ( "Nagle's algorithm disabled." ) ; } if ( USE_CUSTOM_BUFFER_SIZE ) { // Improve default send/receive buffer sizes from default (often 8K). if ( m_socket . getSendBufferSize ( ) < NET_BUFFER_SIZE ) { m_logger . debug ( "SendBufferSize increased from {} to {}" , m_socket . getSendBufferSize ( ) , NET_BUFFER_SIZE ) ; m_socket . setSendBufferSize ( NET_BUFFER_SIZE ) ; } if ( m_socket . getReceiveBufferSize ( ) < NET_BUFFER_SIZE ) { m_logger . debug ( "ReceiveBufferSize increased from {} to {}" , m_socket . getReceiveBufferSize ( ) , NET_BUFFER_SIZE ) ; m_socket . setReceiveBufferSize ( NET_BUFFER_SIZE ) ; } } }
Customize socket options
251
4
17,899
public void set ( int [ ] indexes , int [ ] offsets , int [ ] lengths ) { m_size = indexes . length ; m_valuesCount = offsets . length ; m_offsets = offsets ; m_lengths = lengths ; m_prefixes = new int [ offsets . length ] ; m_suffixes = new int [ offsets . length ] ; m_indexes = indexes ; }
for synthetic fields
86
3