idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
17,900
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 . getObjec...
within the given DBObjectBatch .
17,901
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 .
17,902
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 { StringB...
12 . 23 . 345bla - bla = > 012023 . 345
17,903
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 ...
family - dir - > snapshot - dir - list
17,904
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 . g...
keyspace - dir - > snapshot - dir
17,905
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 ...
Create a Dory client connection and execute the example commands .
17,906
private void deleteApplication ( DoradusClient client ) { Command command = Command . builder ( ) . withName ( "DeleteAppWithKey" ) . withParam ( "application" , "HelloSpider" ) . withParam ( "key" , "Arachnid" ) . build ( ) ; client . runCommand ( command ) ; }
Delete the existing HelloSpider application if present .
17,907
private void createApplication ( DoradusClient client ) { ApplicationDefinition appDef = ApplicationDefinition . builder ( ) . withName ( "HelloSpider" ) . withKey ( "Arachnid" ) . withOption ( "StorageService" , "SpiderService" ) . withTable ( TableDefinition . builder ( ) . withName ( "Movies" ) . withField ( FieldDe...
Create the HelloSpider application definition .
17,908
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 ( "...
Delete data by ID
17,909
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 ) ; ...
Connect to the Doradus server and download the requested application s schema .
17,910
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 . getFieldDefinition...
Compute link fanouts for the given table
17,911
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 .
17,912
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 .
17,913
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 :...
Log elapsed time of all named timers if the condition is true .
17,914
public void parse ( UNode rootNode ) { assert rootNode != null ; Utils . require ( rootNode . getName ( ) . equals ( "batch" ) , "'batch' expected: " + rootNode . getName ( ) ) ; for ( String memberName : rootNode . getMemberNames ( ) ) { UNode childNode = rootNode . getMember ( memberName ) ; if ( childNode . getName ...
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 .
17,915
public UNode toDoc ( ) { UNode batchNode = UNode . createMapNode ( "batch" ) ; 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 .
17,916
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 .
17,917
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...
Create configure and return the Jetty Server object .
17,918
private ServerConnector configureConnector ( ) { ServerConnector connector = null ; if ( m_tls ) { connector = createSSLConnector ( ) ; } else { connector = new ServerConnector ( m_jettyServer ) ; } if ( m_restaddr != null ) { connector . setHost ( m_restaddr ) ; } connector . setPort ( m_restport ) ; connector . setId...
Create configure and return the ServerConnector object .
17,919
private ServletHandler configureHandler ( String servletClassName ) { ServletHandler handler = new ServletHandler ( ) ; handler . addServletWithMapping ( servletClassName , "/*" ) ; return handler ; }
Create configure and return the ServletHandler object .
17,920
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 ( ) ; s...
Called by the TaskManagerService to begin the execution of the task .
17,921
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 ( Tas...
Update the job status record that shows this job has started .
17,922
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 ....
Update the job status record that shows this job has failed .
17,923
private void reconnect ( ) throws IOException { close ( ) ; 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
17,924
private RESTResponse sendAndReceive ( HttpMethod method , String uri , Map < String , String > headers , byte [ ] body ) throws IOException { assert headers != null ; headers . put ( HttpDefs . HOST , m_host ) ; headers . put ( HttpDefs . ACCEPT , m_acceptFormat . toString ( ) ) ; headers . put ( HttpDefs . CONTENT_LEN...
Add standard headers to the given request and send it .
17,925
private RESTResponse sendAndReceive ( String header , byte [ ] body ) throws IOException { 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 read...
we reconnect and retry up to MAX_SOCKET_RETRIES before giving up .
17,926
private void sendRequest ( String header , byte [ ] body ) throws IOException { 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 , r...
Send the request represented by the given header and optional body .
17,927
private RESTResponse readResponse ( ) throws IOException { HttpCode resultCode = readStatusLine ( ) ; Map < String , String > headers = new HashMap < String , String > ( ) ; int contentLength = 0 ; String headerLine = readHeader ( ) ; while ( headerLine . length ( ) > 2 ) { int colonInx = headerLine . indexOf ( ':' ) ;...
a RESTResponse object .
17,928
private HttpCode readStatusLine ( ) throws IOException { String statusLine = readHeader ( ) ; String [ ] parts = statusLine . split ( " +" ) ; if ( parts . length < 3 ) { throw new IOException ( "Badly formed response status line: " + statusLine ) ; } try { int code = Integer . parseInt ( parts [ 1 ] ) ; HttpCode resul...
Read a REST response status line and return the status code from it .
17,929
private void createSocket ( ) throws Exception { 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 So...
Create a socket connection setting m_socket using configured parameters .
17,930
private void setSocketOptions ( ) throws SocketException { if ( DISABLE_NAGLES ) { m_socket . setTcpNoDelay ( true ) ; m_logger . debug ( "Nagle's algorithm disabled." ) ; } if ( USE_CUSTOM_BUFFER_SIZE ) { if ( m_socket . getSendBufferSize ( ) < NET_BUFFER_SIZE ) { m_logger . debug ( "SendBufferSize increased from {} t...
Customize socket options
17,931
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
17,932
@ SuppressWarnings ( "unchecked" ) private String keyspaceDefaultsToCQLString ( ) { boolean durable_writes = true ; Map < String , Object > replication = new HashMap < String , Object > ( ) ; replication . put ( "class" , "SimpleStrategy" ) ; replication . put ( "replication_factor" , "1" ) ; if ( m_dbservice . getPara...
Allow RF to be overridden with ReplicationFactor in the given options .
17,933
private static String mapToCQLString ( Map < String , Object > valueMap ) { StringBuffer buffer = new StringBuffer ( ) ; buffer . append ( "{" ) ; boolean bFirst = true ; for ( String name : valueMap . keySet ( ) ) { if ( bFirst ) { bFirst = false ; } else { buffer . append ( "," ) ; } buffer . append ( "'" ) ; buffer ...
Values must be quoted if they aren t literals .
17,934
private ResultSet executeCQL ( String cql ) { m_logger . debug ( "Executing CQL: {}" , cql ) ; try { return m_dbservice . getSession ( ) . execute ( cql ) ; } catch ( Exception e ) { m_logger . error ( "CQL query failed" , e ) ; m_logger . info ( " Query={}" , cql ) ; throw e ; } }
Execute and optionally log the given CQL statement .
17,935
private void checkTable ( ) { if ( m_retentionAge . getValue ( ) == 0 ) { m_logger . info ( "Data aging disabled for table: {}" , m_tableDef . getTableName ( ) ) ; return ; } m_logger . info ( "Checking expired objects for: {}" , m_tableDef . getTableName ( ) ) ; GregorianCalendar checkDate = new GregorianCalendar ( Ut...
Scan the given table for expired objects relative to the given date .
17,936
private String buildFixedQuery ( GregorianCalendar expireDate ) { StringBuilder fixedParams = new StringBuilder ( ) ; fixedParams . append ( "q=" ) ; fixedParams . append ( m_agingFieldDef . getName ( ) ) ; fixedParams . append ( " <= \"" ) ; fixedParams . append ( Utils . formatDate ( expireDate ) ) ; fixedParams . ap...
Build the fixed part of the query that fetches a batch of object IDs .
17,937
private boolean deleteBatch ( List < String > objIDs ) { if ( objIDs . size ( ) == 0 ) { return false ; } m_logger . debug ( "Deleting batch of {} objects from {}" , objIDs . size ( ) , m_tableDef . getTableName ( ) ) ; BatchObjectUpdater batchUpdater = new BatchObjectUpdater ( m_tableDef ) ; BatchResult batchResult = ...
update failed or we didn t execute an update .
17,938
public void commit ( DBTransaction transaction ) { try { applyUpdates ( transaction ) ; } catch ( Exception e ) { m_logger . error ( "Updates failed" , e ) ; throw e ; } finally { transaction . clear ( ) ; } }
Apply the updates accumulated in this transaction . The updates are cleared even if the update fails .
17,939
private void applyUpdates ( DBTransaction transaction ) { if ( transaction . getMutationsCount ( ) == 0 ) { m_logger . debug ( "Skipping commit with no updates" ) ; } else if ( m_dbservice . getParamBoolean ( "async_updates" ) ) { executeUpdatesAsynchronous ( transaction ) ; } else { executeUpdatesSynchronous ( transac...
Execute a batch statement that applies all updates in this transaction .
17,940
private void executeUpdatesAsynchronous ( DBTransaction transaction ) { Collection < BoundStatement > mutations = getMutations ( transaction ) ; List < ResultSetFuture > futureList = new ArrayList < > ( mutations . size ( ) ) ; for ( BoundStatement mutation : mutations ) { ResultSetFuture future = m_dbservice . getSess...
Execute all updates asynchronously and wait for results .
17,941
private void executeUpdatesSynchronous ( DBTransaction transaction ) { BatchStatement batchState = new BatchStatement ( Type . UNLOGGED ) ; batchState . addAll ( getMutations ( transaction ) ) ; executeBatch ( batchState ) ; }
Execute all updates and deletes using synchronous statements .
17,942
private BoundStatement addColumnUpdate ( String tableName , String key , DColumn column , boolean isBinaryValue ) { PreparedStatement prepState = m_dbservice . getPreparedUpdate ( Update . INSERT_ROW , tableName ) ; BoundStatement boundState = prepState . bind ( ) ; boundState . setString ( 0 , key ) ; boundState . set...
Create and return a BoundStatement for the given column update .
17,943
private BoundStatement addColumnDelete ( String tableName , String key , String colName ) { PreparedStatement prepState = m_dbservice . getPreparedUpdate ( Update . DELETE_COLUMN , tableName ) ; BoundStatement boundState = prepState . bind ( ) ; boundState . setString ( 0 , key ) ; boundState . setString ( 1 , colName ...
Create and return a BoundStatement that deletes the given column .
17,944
private BoundStatement addRowDelete ( String tableName , String key ) { PreparedStatement prepState = m_dbservice . getPreparedUpdate ( Update . DELETE_ROW , tableName ) ; BoundStatement boundState = prepState . bind ( ) ; boundState . setString ( 0 , key ) ; return boundState ; }
Create and return a BoundStatement that deletes the given row .
17,945
private void executeBatch ( BatchStatement batchState ) { if ( batchState . size ( ) > 0 ) { m_logger . debug ( "Executing synchronous batch with {} statements" , batchState . size ( ) ) ; m_dbservice . getSession ( ) . execute ( batchState ) ; } }
Execute and given update statement .
17,946
public synchronized void onRequestRejected ( String reason ) { allRequestsTracker . onRequestRejected ( reason ) ; recentRequestsTracker . onRequestRejected ( reason ) ; meter . mark ( ) ; }
Registers an invalid request rejected by the server .
17,947
public boolean deleteShard ( String shard ) { Utils . require ( ! Utils . isEmpty ( shard ) , "shard" ) ; try { StringBuilder uri = new StringBuilder ( Utils . isEmpty ( m_restClient . getApiPrefix ( ) ) ? "" : "/" + m_restClient . getApiPrefix ( ) ) ; uri . append ( "/" ) ; uri . append ( Utils . urlEncode ( m_appDef ...
Delete the OLAP shard with the given name belonging to this session s application . True is returned if the delete was successful . An exception is thrown if an error occurred .
17,948
public Collection < String > getShardNames ( ) { List < String > shardNames = new ArrayList < > ( ) ; try { StringBuilder uri = new StringBuilder ( Utils . isEmpty ( m_restClient . getApiPrefix ( ) ) ? "" : "/" + m_restClient . getApiPrefix ( ) ) ; uri . append ( "/" ) ; uri . append ( Utils . urlEncode ( m_appDef . ge...
Get a list of all shard names owned by this application . If there are no shards with data yet an empty collection is returned .
17,949
public UNode getShardStats ( String shardName ) { try { StringBuilder uri = new StringBuilder ( Utils . isEmpty ( m_restClient . getApiPrefix ( ) ) ? "" : "/" + m_restClient . getApiPrefix ( ) ) ; uri . append ( "/" ) ; uri . append ( Utils . urlEncode ( m_appDef . getAppName ( ) ) ) ; uri . append ( "/_shards/" ) ; ur...
Get statistics for the given shard name . Since the response to this command is subject to change the command result is parsed into a UNode and the root object is returned . An exception is thrown if the given shard name does not exist or does not have any data .
17,950
public boolean mergeShard ( String shard , Date expireDate ) { Utils . require ( ! Utils . isEmpty ( shard ) , "shard" ) ; try { StringBuilder uri = new StringBuilder ( Utils . isEmpty ( m_restClient . getApiPrefix ( ) ) ? "" : "/" + m_restClient . getApiPrefix ( ) ) ; uri . append ( "/" ) ; uri . append ( Utils . urlE...
Request a merge of the OLAP shard with the given name belonging to this session s application . Optionally set the shard s expire - date to the given value . True is returned if the merge was successful . An exception is thrown if an error occurred .
17,951
public static boolean allAlphaNumUnderscore ( String string ) { if ( string == null || string . length ( ) == 0 ) { return false ; } for ( int index = 0 ; index < string . length ( ) ; index ++ ) { char ch = string . charAt ( index ) ; if ( ! isLetter ( ch ) && ! isDigit ( ch ) && ch != '_' ) { return false ; } } retur...
Return true if the given string contains only letters digits and underscores .
17,952
public static String base64ToHex ( String base64Value ) throws IllegalArgumentException { byte [ ] binary = base64ToBinary ( base64Value ) ; return DatatypeConverter . printHexBinary ( binary ) ; }
Decode the given Base64 - encoded String to binary and then return as a string of hex digits .
17,953
public static String base64FromHex ( String hexValue ) throws IllegalArgumentException { byte [ ] binary = DatatypeConverter . parseHexBinary ( hexValue ) ; return base64FromBinary ( binary ) ; }
Decode the given hex string to binary and then re - encoded it as a Base64 string .
17,954
public static String base64ToString ( String base64Value ) { Utils . require ( base64Value . length ( ) % 4 == 0 , "Invalid base64 value (must be a multiple of 4 chars): " + base64Value ) ; byte [ ] utf8String = DatatypeConverter . parseBase64Binary ( base64Value ) ; return toString ( utf8String ) ; }
Decode the given base64 value to binary then decode the result as a UTF - 8 sequence and return the resulting String .
17,955
public static long getTimeMicros ( ) { synchronized ( g_lastMicroLock ) { long newValue = System . currentTimeMillis ( ) * 1000 ; if ( newValue <= g_lastMicroValue ) { newValue = g_lastMicroValue + 1 ; } g_lastMicroValue = newValue ; return newValue ; } }
Get the current time in microseconds since the epoch . This method is synchronized and guarantees that each successive call even by different threads returns increasing values .
17,956
public static String deWhite ( byte [ ] value ) { StringBuilder buffer = new StringBuilder ( ) ; boolean bAllPrintable = true ; for ( byte b : value ) { if ( ( int ) ( b & 0xFF ) < ' ' ) { bAllPrintable = false ; break ; } } if ( bAllPrintable ) { for ( byte b : value ) { buffer . append ( ( char ) b ) ; } } else { buf...
Create a String by converting each byte directly into a character . However if any byte in the given value is less than a space a hex string is returned instead .
17,957
public static boolean getBooleanValue ( String value ) throws IllegalArgumentException { require ( "true" . equalsIgnoreCase ( value ) || "false" . equalsIgnoreCase ( value ) , "'true' or 'false' expected: " + value ) ; return "true" . equalsIgnoreCase ( value ) ; }
Verify that the given value is either true or false and return the corresponding boolean value . If the value is invalid an IllegalArgumentException is thrown .
17,958
public static String getElementText ( Element elem ) { StringBuilder result = new StringBuilder ( ) ; NodeList nodeList = elem . getChildNodes ( ) ; for ( int index = 0 ; index < nodeList . getLength ( ) ; index ++ ) { Node childNode = nodeList . item ( index ) ; if ( childNode != null && ( childNode instanceof Text ) ...
Get the concatenated value of all Text nodes that are immediate children of the given Element . If the element has no content it will not have a child Text node . If it does have content it will usually have a single child Text node . But in rare cases it could have multiple child Text nodes . If multiple child Text no...
17,959
public static String md5Encode ( String strIn ) { try { MessageDigest md5 = MessageDigest . getInstance ( "md5" ) ; byte [ ] bin = toBytes ( strIn ) ; byte [ ] bout = md5 . digest ( bin ) ; String strOut = javax . xml . bind . DatatypeConverter . printBase64Binary ( bout ) ; return strOut ; } catch ( Exception e ) { th...
Compute the MD5 of the given string and return it as a Base64 - encoded value . The string is first converted to bytes using UTF - 8 and the MD5 is computed on that value . The MD5 value is 16 bytes but the Base64 - encoded string is 24 chars .
17,960
public static Element parseXMLDocument ( String xmlDoc ) throws IllegalArgumentException { Reader stringReader = new StringReader ( xmlDoc ) ; InputSource inputSource = new InputSource ( stringReader ) ; DocumentBuilderFactory dbf = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder parser = null ; Document doc...
Parse the given XML document creating a DOM tree whose root Document object is returned . An IllegalArgumentException is thrown if the XML is malformed .
17,961
public static void requireEmptyText ( Node node , String errMsg ) throws IllegalArgumentException { require ( ( node instanceof Text ) || ( node instanceof Comment ) , errMsg + ": " + node . toString ( ) ) ; if ( node instanceof Text ) { Text text = ( Text ) node ; String textValue = text . getData ( ) ; require ( text...
Assert that the given org . w3c . doc . Node is a comment element or a Text element and that it ontains whitespace only otherwise throw an IllegalArgumentException using the given error message . This is helpful when nothing is expected at a certain place in a DOM tree yet comments or whitespace text nodes can appear .
17,962
private static byte [ ] toAsciiBytes ( String str ) { for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str . charAt ( i ) > 127 ) return null ; } byte [ ] bytes = new byte [ str . length ( ) ] ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { bytes [ i ] = ( byte ) str . charAt ( i ) ; } return bytes ; }
return string as bytes if it has only ascii symbols or null
17,963
private static String toAsciiString ( byte [ ] bytes ) { for ( int i = 0 ; i < bytes . length ; i ++ ) { if ( bytes [ i ] < 0 ) return null ; } char [ ] chars = new char [ bytes . length ] ; for ( int i = 0 ; i < bytes . length ; i ++ ) { chars [ i ] = ( char ) bytes [ i ] ; } return new String ( chars ) ; }
return string if bytes have only ascii symbols or null
17,964
public static GregorianCalendar truncateToWeek ( GregorianCalendar date ) { GregorianCalendar result = ( GregorianCalendar ) date . clone ( ) ; switch ( result . get ( Calendar . DAY_OF_WEEK ) ) { case Calendar . TUESDAY : result . add ( Calendar . DAY_OF_MONTH , - 1 ) ; break ; case Calendar . WEDNESDAY : result . add...
Truncate the given GregorianCalendar date to the nearest week . This is done by cloning it and rounding the value down to the closest Monday . If the given date already occurs on a Monday a copy of the same date is returned .
17,965
private RESTResponse validateAndExecuteRequest ( HttpServletRequest request ) { Map < String , String > variableMap = new HashMap < String , String > ( ) ; String query = extractQueryParam ( request , variableMap ) ; Tenant tenant = getTenant ( variableMap ) ; String uri = request . getRequestURI ( ) ; String context =...
Execute the given request and return a RESTResponse or throw an appropriate error .
17,966
private ApplicationDefinition getApplication ( String uri , Tenant tenant ) { if ( uri . length ( ) < 2 || uri . startsWith ( "/_" ) ) { return null ; } String [ ] pathNodes = uri . substring ( 1 ) . split ( "/" ) ; String appName = Utils . urlDecode ( pathNodes [ 0 ] ) ; ApplicationDefinition appDef = SchemaService . ...
Get the definition of the referenced application or null if there is none .
17,967
private Tenant getTenant ( Map < String , String > variableMap ) { String tenantName = variableMap . get ( "tenant" ) ; if ( Utils . isEmpty ( tenantName ) ) { tenantName = TenantService . instance ( ) . getDefaultTenantName ( ) ; } Tenant tenant = TenantService . instance ( ) . getTenant ( tenantName ) ; if ( tenant =...
Get the Tenant context for this command and multi - tenant configuration options .
17,968
private void validateTenantAccess ( HttpServletRequest request , Tenant tenant , RegisteredCommand cmdModel ) { String authString = request . getHeader ( "Authorization" ) ; StringBuilder userID = new StringBuilder ( ) ; StringBuilder password = new StringBuilder ( ) ; decodeAuthorizationHeader ( authString , userID , ...
Extract Authorization header if any and validate this command for the given tenant .
17,969
private Permission permissionForMethod ( String method ) { switch ( method . toUpperCase ( ) ) { case "GET" : return Permission . READ ; case "PUT" : case "DELETE" : return Permission . UPDATE ; case "POST" : return Permission . APPEND ; default : throw new RuntimeException ( "Unexpected REST method: " + method ) ; } }
Map an HTTP method to the permission needed to execute it .
17,970
private String extractQueryParam ( HttpServletRequest request , Map < String , String > restParams ) { String query = request . getQueryString ( ) ; if ( Utils . isEmpty ( query ) ) { return "" ; } StringBuilder buffer = new StringBuilder ( query ) ; String [ ] parts = Utils . splitURIQuery ( buffer . toString ( ) ) ; ...
format = y and tenant = z if present to rest parameters .
17,971
private String getFullURI ( HttpServletRequest request ) { StringBuilder buffer = new StringBuilder ( request . getMethod ( ) ) ; buffer . append ( " " ) ; buffer . append ( request . getRequestURI ( ) ) ; String queryParam = request . getQueryString ( ) ; if ( ! Utils . isEmpty ( queryParam ) ) { buffer . append ( "?"...
Reconstruct the entire URI from the given request .
17,972
private static void setLegacy ( String moduleName , String legacyParamName ) { String oldValue = g_legacyToModuleMap . put ( legacyParamName , moduleName ) ; if ( oldValue != null ) { logger . warn ( "Legacy parameter name used twice: {}" , legacyParamName ) ; } }
Register the given legacy parameter name as owned by the given module name .
17,973
private static void setLegacy ( String moduleName , String ... legacyParamNames ) { for ( String legacyParamName : legacyParamNames ) { setLegacy ( moduleName , legacyParamName ) ; } }
Register the given legacy parameter names as owned by the given module name .
17,974
private static URL getConfigUrl ( ) throws ConfigurationException { String spec = System . getProperty ( CONFIG_URL_PROPERTY_NAME ) ; if ( spec == null ) { spec = DEFAULT_CONFIG_URL ; } URL configUrl = null ; try { configUrl = new URL ( spec ) ; configUrl . openStream ( ) . close ( ) ; } catch ( Exception e ) { try { F...
Inspect the classpath to find configuration file
17,975
@ SuppressWarnings ( "unchecked" ) private void updateMap ( Map < String , Object > parentMap , String paramName , Object paramValue ) { Object currentValue = parentMap . get ( paramName ) ; if ( currentValue == null || ! ( currentValue instanceof Map ) ) { if ( paramValue instanceof Map ) { parentMap . put ( paramName...
Replace or add the given parameter name and value to the given map .
17,976
private void setLegacyParam ( String legacyParamName , Object paramValue ) { if ( ! m_bWarnedLegacyParam ) { logger . warn ( "Parameter '{}': Legacy parameter format is being phased-out. " + "Please use new module/parameter format." , legacyParamName ) ; m_bWarnedLegacyParam = true ; } String moduleName = g_legacyToMod...
Sets a parameter using a legacy name .
17,977
public void parse ( UNode tableNode ) { assert tableNode != null ; setTableName ( tableNode . getName ( ) ) ; for ( String childName : tableNode . getMemberNames ( ) ) { UNode childNode = tableNode . getMember ( childName ) ; if ( childName . equals ( "fields" ) ) { for ( String fieldName : childNode . getMemberNames (...
Parse a table definition rooted at the given UNode . The given node is the table definition hence its name is the table name . The node must be a MAP whose child nodes are table definitions such as options and fields .
17,978
public static boolean isValidTableName ( String tableName ) { return tableName != null && tableName . length ( ) > 0 && Utils . isLetter ( tableName . charAt ( 0 ) ) && Utils . allAlphaNumUnderscore ( tableName ) ; }
Indicate if the given string is a valid table name . Table names must begin with a letter and consist of all letters digits and underscores .
17,979
public Date computeShardStart ( int shardNumber ) { assert isSharded ( ) ; assert shardNumber > 0 ; assert m_shardingStartDate != null ; Date result = null ; if ( shardNumber == 1 ) { result = m_shardingStartDate . getTime ( ) ; } else { GregorianCalendar shardDate = ( GregorianCalendar ) m_shardingStartDate . clone ( ...
Compute and return the date at which the shard with the given number starts based on this table s sharding options . For example if sharding - granularity is MONTH and the sharding - start is 2012 - 10 - 15 then shard 2 starts on 2012 - 11 - 01 .
17,980
public int computeShardNumber ( Date shardingFieldValue ) { assert shardingFieldValue != null ; assert isSharded ( ) ; assert m_shardingStartDate != null ; GregorianCalendar objectDate = new GregorianCalendar ( Utils . UTC_TIMEZONE ) ; objectDate . setTime ( shardingFieldValue ) ; if ( objectDate . getTimeInMillis ( ) ...
Compute the shard number of an object belong to this table with the given sharding - field value . This method should only be called on a sharded table for which the sharding - field sharding - granularity and sharding - start options have been set . The value returned will be 0 if the given date falls before the shard...
17,981
public boolean isCollection ( String fieldName ) { FieldDefinition fieldDef = m_fieldDefMap . get ( fieldName ) ; return fieldDef != null && fieldDef . isScalarField ( ) && fieldDef . isCollection ( ) ; }
Return true if the given field name is an MV scalar field . Since scalar fields must be declared as MV only predefined fields can be MV .
17,982
public boolean isLinkField ( String fieldName ) { FieldDefinition fieldDef = m_fieldDefMap . get ( fieldName ) ; return fieldDef != null && fieldDef . isLinkField ( ) ; }
Return true if this table definition possesses a FieldDefinition with the given name that defines a Link field .
17,983
public void setOption ( String optionName , String optionValue ) { Utils . require ( optionName != null , "optionName" ) ; Utils . require ( optionValue != null && optionValue . trim ( ) . length ( ) > 0 , "Value for option '" + optionName + "' can not be empty" ) ; optionValue = optionValue . trim ( ) ; m_optionMap . ...
Set the option with the given name to the given value . This method does not validate that the given option name and value are valid since options are storage service - specific .
17,984
public TableDefinition getLinkExtentTableDef ( FieldDefinition linkDef ) { assert linkDef != null ; assert linkDef . isLinkType ( ) ; assert m_appDef != null ; TableDefinition tableDef = m_appDef . getTableDef ( linkDef . getLinkExtent ( ) ) ; assert tableDef != null ; return tableDef ; }
Get the TableDefinition of the extent table for the given link field .
17,985
public boolean extractLinkValue ( String colName , Map < String , Set < String > > mvLinkValueMap ) { if ( colName . length ( ) == 0 || colName . charAt ( 0 ) != '~' ) { return false ; } int slashInx = colName . indexOf ( '/' ) ; if ( slashInx < 0 ) { return false ; } String fieldName = colName . substring ( 1 , slashI...
Examine the given column name and if it represents an MV link value add it to the given MV link value map . If a link value is successfully extracted true is returned . If the column name is not in the format used for MV link values false is returned .
17,986
private void addAliasDefinition ( AliasDefinition aliasDef ) { assert aliasDef != null ; assert ! m_aliasDefMap . containsKey ( aliasDef . getName ( ) ) ; assert aliasDef . getTableName ( ) . equals ( this . getTableName ( ) ) ; m_aliasDefMap . put ( aliasDef . getName ( ) , aliasDef ) ; }
Add the given alias definition to this table definition .
17,987
private void verifyJunctionField ( FieldDefinition xlinkDef ) { String juncField = xlinkDef . getXLinkJunction ( ) ; if ( ! "_ID" . equals ( juncField ) ) { FieldDefinition juncFieldDef = m_fieldDefMap . get ( juncField ) ; Utils . require ( juncFieldDef != null , String . format ( "Junction field for xlink '%s' has no...
Verify that the given xlink s junction field is either _ID or an SV text field .
17,988
private AttributeValue mapColumnValue ( String storeName , DColumn col ) { AttributeValue attrValue = new AttributeValue ( ) ; if ( ! DBService . isSystemTable ( storeName ) ) { if ( col . getRawValue ( ) . length == 0 ) { attrValue . setS ( DynamoDBService . NULL_COLUMN_MARKER ) ; } else { attrValue . setB ( ByteBuffe...
Create the appropriate AttributeValue for the given column value type and length .
17,989
public Set < String > extractTerms ( String value ) { try { Set < String > result = new HashSet < String > ( ) ; Set < String > split = Utils . split ( value . toLowerCase ( ) , CommonDefs . MV_SCALAR_SEP_CHAR ) ; for ( String s : split ) { String [ ] tokens = tokenize ( s ) ; for ( String token : tokens ) { if ( token...
Analyze the given String value and return the set of terms that should be indexed .
17,990
public static BatchResult newErrorResult ( String errMsg ) { BatchResult result = new BatchResult ( ) ; result . setStatus ( Status . ERROR ) ; result . setErrorMessage ( errMsg ) ; return result ; }
Create a new BatchResult with an ERROR status and the given error message .
17,991
public boolean hasUpdates ( ) { String hasUpdates = m_resultFields . get ( HAS_UPDATES ) ; return hasUpdates != null && Boolean . parseBoolean ( hasUpdates ) ; }
Return true if this batch result has at least one object that was updated .
17,992
public UNode toDoc ( ) { UNode result = UNode . createMapNode ( "batch-result" ) ; for ( String fieldName : m_resultFields . keySet ( ) ) { result . addValueNode ( fieldName , m_resultFields . get ( fieldName ) ) ; } if ( m_objResultList . size ( ) > 0 ) { UNode docsNode = result . addArrayNode ( "docs" ) ; for ( Objec...
Serialize this BatchResult result into a UNode tree . The root node is called batch - result .
17,993
void registerTaskStarted ( Task task ) { synchronized ( m_activeTasks ) { String mapKey = createMapKey ( task . getTenant ( ) , task . getTaskID ( ) ) ; if ( m_activeTasks . put ( mapKey , task ) != null ) { m_logger . warn ( "Task {} registered as started but was already running" , mapKey ) ; } } }
Called by a Task when it s thread starts . This lets the task manager know which tasks are its own .
17,994
void registerTaskEnded ( Task task ) { synchronized ( m_activeTasks ) { String mapKey = createMapKey ( task . getTenant ( ) , task . getTaskID ( ) ) ; if ( m_activeTasks . remove ( mapKey ) == null ) { m_logger . warn ( "Task {} registered as ended but was not running" , mapKey ) ; } } }
Called by a Task when it s thread finishes . This lets the task manager know that another slot has opened - up .
17,995
void updateTaskStatus ( Tenant tenant , TaskRecord taskRecord , boolean bDeleteClaimRecord ) { String taskID = taskRecord . getTaskID ( ) ; DBTransaction dbTran = DBService . instance ( tenant ) . startTransaction ( ) ; Map < String , String > propMap = taskRecord . getProperties ( ) ; for ( String name : propMap . key...
Add or update a task status record and optionally delete the task s claim record at the same time .
17,996
private TaskRecord waitForTaskStatus ( Tenant tenant , Task task , Predicate < TaskStatus > pred ) { TaskRecord taskRecord = null ; while ( true ) { Iterator < DColumn > colIter = DBService . instance ( tenant ) . getAllColumns ( TaskManagerService . TASKS_STORE_NAME , task . getTaskID ( ) ) . iterator ( ) ; if ( ! col...
latest status record . If it has never run a never - run task record is stored .
17,997
private void manageTasks ( ) { setHostAddress ( ) ; while ( ! m_bShutdown ) { checkAllTasks ( ) ; checkForDeadTasks ( ) ; try { Thread . sleep ( SLEEP_TIME_MILLIS ) ; } catch ( InterruptedException e ) { } } m_executor . shutdown ( ) ; }
tasks we can run . Shutdown when told to do so .
17,998
private void checkTenantTasks ( Tenant tenant ) { m_logger . debug ( "Checking tenant '{}' for needy tasks" , tenant ) ; try { for ( ApplicationDefinition appDef : SchemaService . instance ( ) . getAllApplications ( tenant ) ) { for ( Task task : getAppTasks ( appDef ) ) { checkTaskForExecution ( appDef , task ) ; } } ...
Check the given tenant for tasks that need execution .
17,999
private void checkTaskForExecution ( ApplicationDefinition appDef , Task task ) { Tenant tenant = Tenant . getTenant ( appDef ) ; m_logger . debug ( "Checking task '{}' in tenant '{}'" , task . getTaskID ( ) , tenant ) ; synchronized ( m_executeLock ) { Iterator < DColumn > colIter = DBService . instance ( tenant ) . g...
Check the given task to see if we should and can execute it .