idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
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 . 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 .
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 { 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
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 ++ ) { 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 ( ) ] ) ) ; } } } } } return map ; }
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 . 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
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 ( client ) ; addData ( client ) ; queryData ( client ) ; deleteData ( client ) ; } }
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 ( 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 .
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 ( "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
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 ) ; m_appDef = m_session . getAppDef ( ) ; if ( m_config . optimize ) { computeLinkFanouts ( ) ; } }
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 . 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 ; m_logger . info ( "Average fanout for link {}: {}" , fieldName , linkFanout ) ; tableLinkFanoutMap . put ( fieldName , new MutableFloat ( linkFanout ) ) ; } }
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 : 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 .
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 ( ) . 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 .
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 . setStopAtShutdown ( true ) ; return 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 . setIdleTimeout ( SOCKET_TIMEOUT_MILLIS ) ; connector . addBean ( new ConnListener ( ) ) ; return connector ; }
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 ( ) ; 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 .
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 ( 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 .
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 . setStatus ( TaskStatus . FAILED ) ; TaskManagerService . instance ( ) . updateTaskStatus ( m_tenant , m_taskRecord , true ) ; }
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_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 ) ; } 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 .
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 readResponse ( ) ; } catch ( IOException e ) { lastException = e ; m_logger . warn ( "Socket error occurred -- reconnecting" , e ) ; reconnect ( ) ; } } throw new IOException ( "Socket error; all retries failed" , lastException ) ; }
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 , requestBytes , 0 , headerBytes . length ) ; System . arraycopy ( body , 0 , requestBytes , headerBytes . length , body . length ) ; } m_outStream . write ( requestBytes ) ; m_outStream . flush ( ) ; }
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 ( ':' ) ; String headerName = colonInx <= 0 ? headerLine . trim ( ) . toUpperCase ( ) : headerLine . substring ( 0 , colonInx ) . trim ( ) . toUpperCase ( ) ; String headerValue = 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 ) { throw new IOException ( "Invalid content-length value: " + headerLine ) ; } } headerLine = readHeader ( ) ; } if ( ! headerLine . equals ( "\r\n" ) ) { throw new IOException ( "Header not properly terminated: " + headerLine ) ; } byte [ ] body = null ; if ( contentLength > 0 ) { body = readBody ( contentLength ) ; 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 .
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 result = HttpCode . findByCode ( code ) ; if ( result == null ) { throw new IOException ( "Unrecognized result code: " + code ) ; } return result ; } catch ( NumberFormatException e ) { throw new IOException ( "Badly formed response status line: " + statusLine ) ; } }
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 Socket ( ) ; setSocketOptions ( ) ; SocketAddress sockAddr = new InetSocketAddress ( m_host , m_port ) ; m_socket . connect ( sockAddr ) ; } }
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 {} 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
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 . getParam ( "ReplicationFactor" ) != null ) { replication . put ( "replication_factor" , m_dbservice . getParamString ( "ReplicationFactor" ) ) ; } Map < String , Object > ksDefs = m_dbservice . getParamMap ( "ks_defaults" ) ; if ( ksDefs != null ) { if ( ksDefs . containsKey ( "durable_writes" ) ) { durable_writes = Boolean . parseBoolean ( ksDefs . get ( "durable_writes" ) . toString ( ) ) ; } if ( ksDefs . containsKey ( "strategy_class" ) ) { replication . put ( "class" , ksDefs . get ( "strategy_class" ) . toString ( ) ) ; } if ( ksDefs . containsKey ( "strategy_options" ) ) { Object value = ksDefs . get ( "strategy_options" ) ; if ( value instanceof Map ) { Map < String , Object > replOpts = ( Map < String , Object > ) value ; if ( replOpts . containsKey ( "replication_factor" ) ) { replication . put ( "replication_factor" , replOpts . get ( "replication_factor" ) . toString ( ) ) ; } } } } StringBuilder buffer = new StringBuilder ( ) ; buffer . append ( " WITH DURABLE_WRITES=" ) ; buffer . append ( durable_writes ) ; buffer . append ( " AND REPLICATION=" ) ; buffer . append ( mapToCQLString ( replication ) ) ; return buffer . toString ( ) ; }
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 . append ( name ) ; buffer . append ( "':" ) ; Object value = valueMap . get ( name ) ; if ( value instanceof String ) { buffer . append ( "'" ) ; buffer . append ( value . toString ( ) ) ; buffer . append ( "'" ) ; } else { buffer . append ( value . toString ( ) ) ; } } buffer . append ( "}" ) ; return buffer . toString ( ) ; }
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 ( Utils . UTC_TIMEZONE ) ; GregorianCalendar expireDate = m_retentionAge . getExpiredDate ( checkDate ) ; int objsExpired = 0 ; String fixedQuery = buildFixedQuery ( expireDate ) ; String contToken = null ; StringBuilder uriParam = new StringBuilder ( ) ; do { uriParam . setLength ( 0 ) ; uriParam . append ( fixedQuery ) ; if ( ! Utils . isEmpty ( contToken ) ) { uriParam . append ( "&g=" ) ; uriParam . append ( contToken ) ; } ObjectQuery objQuery = new ObjectQuery ( m_tableDef , uriParam . toString ( ) ) ; SearchResultList resultList = SpiderService . instance ( ) . objectQuery ( m_tableDef , objQuery ) ; List < String > objIDs = new ArrayList < > ( ) ; for ( SearchResult result : resultList . results ) { objIDs . add ( result . id ( ) ) ; } if ( deleteBatch ( objIDs ) ) { contToken = resultList . continuation_token ; } else { contToken = null ; } objsExpired += objIDs . size ( ) ; reportProgress ( "Expired " + objsExpired + " objects" ) ; } while ( ! Utils . isEmpty ( contToken ) ) ; m_logger . info ( "Deleted {} objects for {}" , objsExpired , m_tableDef . getTableName ( ) ) ; }
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 . append ( "\"" ) ; fixedParams . append ( "&f=_ID" ) ; fixedParams . append ( "&s=" ) ; fixedParams . append ( QUERY_PAGE_SIZE ) ; return fixedParams . toString ( ) ; }
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 = batchUpdater . deleteBatch ( objIDs ) ; if ( batchResult . isFailed ( ) ) { m_logger . error ( "Batch query failed: {}" , batchResult . getErrorMessage ( ) ) ; return false ; } return true ; }
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 ( transaction ) ; } }
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 . getSession ( ) . executeAsync ( mutation ) ; futureList . add ( future ) ; } m_logger . debug ( "Waiting for {} asynchronous futures" , futureList . size ( ) ) ; for ( ResultSetFuture future : futureList ) { future . getUninterruptibly ( ) ; } }
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 . setString ( 1 , column . getName ( ) ) ; if ( isBinaryValue ) { boundState . setBytes ( 2 , ByteBuffer . wrap ( column . getRawValue ( ) ) ) ; } else { boundState . setString ( 2 , column . getValue ( ) ) ; } return boundState ; }
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 ) ; return boundState ; }
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 . getAppName ( ) ) ) ; uri . append ( "/_shards/" ) ; uri . append ( Utils . urlEncode ( shard ) ) ; RESTResponse response = m_restClient . sendRequest ( HttpMethod . DELETE , uri . toString ( ) ) ; m_logger . debug ( "deleteShard() response: {}" , response . toString ( ) ) ; throwIfErrorResponse ( response ) ; return true ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
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 . getAppName ( ) ) ) ; uri . append ( "/_shards" ) ; RESTResponse response = m_restClient . sendRequest ( HttpMethod . GET , uri . toString ( ) ) ; m_logger . debug ( "mergeShard() response: {}" , response . toString ( ) ) ; throwIfErrorResponse ( response ) ; UNode rootNode = getUNodeResult ( response ) ; UNode appNode = rootNode . getMember ( m_appDef . getAppName ( ) ) ; UNode shardsNode = appNode . getMember ( "shards" ) ; for ( UNode shardNode : shardsNode . getMemberList ( ) ) { shardNames . add ( shardNode . getValue ( ) ) ; } return shardNames ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
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/" ) ; uri . append ( shardName ) ; RESTResponse response = m_restClient . sendRequest ( HttpMethod . GET , uri . toString ( ) ) ; m_logger . debug ( "mergeShard() response: {}" , response . toString ( ) ) ; throwIfErrorResponse ( response ) ; return getUNodeResult ( response ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
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 . urlEncode ( m_appDef . getAppName ( ) ) ) ; uri . append ( "/_shards/" ) ; uri . append ( Utils . urlEncode ( shard ) ) ; if ( expireDate != null ) { uri . append ( "?expire-date=" ) ; uri . append ( Utils . urlEncode ( Utils . formatDateUTC ( expireDate ) ) ) ; } RESTResponse response = m_restClient . sendRequest ( HttpMethod . POST , uri . toString ( ) ) ; m_logger . debug ( "mergeShard() response: {}" , response . toString ( ) ) ; throwIfErrorResponse ( response ) ; return true ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
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 ; } } return true ; }
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 { buffer . append ( "0x" ) ; for ( byte b : value ) { buffer . append ( toHexChar ( ( ( int ) b & 0xF0 ) >> 4 ) ) ; buffer . append ( toHexChar ( ( ( int ) b & 0xF ) ) ) ; } } return buffer . toString ( ) ; }
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 ) ) { result . append ( " " ) ; result . append ( ( ( Text ) childNode ) . getData ( ) ) ; } } return result . toString ( ) . trim ( ) ; }
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 nodes are found their content is concatenated into a single string each separated by a single space . The value returned is trimmed of beginning and ending whitespace . If the element has no child Text nodes or if all child Text nodes are empty or have whitespace - only values an empty string is returned .
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 ) { throw new RuntimeException ( e . getMessage ( ) , e ) ; } }
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 = null ; try { parser = dbf . newDocumentBuilder ( ) ; doc = parser . parse ( inputSource ) ; } catch ( Exception ex ) { throw new IllegalArgumentException ( "Error parsing XML document: " + ex . getMessage ( ) ) ; } return doc . getDocumentElement ( ) ; }
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 ( textValue . trim ( ) . length ( ) == 0 , errMsg + ": " + textValue ) ; } }
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 ( Calendar . DAY_OF_MONTH , - 2 ) ; break ; case Calendar . THURSDAY : result . add ( Calendar . DAY_OF_MONTH , - 3 ) ; break ; case Calendar . FRIDAY : result . add ( Calendar . DAY_OF_MONTH , - 4 ) ; break ; case Calendar . SATURDAY : result . add ( Calendar . DAY_OF_MONTH , - 5 ) ; break ; case Calendar . SUNDAY : result . add ( Calendar . DAY_OF_MONTH , - 6 ) ; break ; default : break ; } return result ; }
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 = request . getContextPath ( ) ; if ( ! Utils . isEmpty ( context ) ) { uri = uri . substring ( context . length ( ) ) ; } ApplicationDefinition appDef = getApplication ( uri , tenant ) ; HttpMethod method = HttpMethod . methodFromString ( request . getMethod ( ) ) ; if ( method == null ) { throw new NotFoundException ( "Request does not match a known URI: " + request . getRequestURL ( ) ) ; } RegisteredCommand cmd = RESTService . instance ( ) . findCommand ( appDef , method , uri , query , variableMap ) ; if ( cmd == null ) { throw new NotFoundException ( "Request does not match a known URI: " + request . getRequestURL ( ) ) ; } validateTenantAccess ( request , tenant , cmd ) ; RESTCallback callback = cmd . getNewCallback ( ) ; callback . setRequest ( new RESTRequest ( tenant , appDef , request , variableMap ) ) ; return callback . invoke ( ) ; }
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 . instance ( ) . getApplication ( tenant , appName ) ; if ( appDef == null ) { throw new NotFoundException ( "Unknown application: " + appName ) ; } return appDef ; }
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 == null ) { throw new NotFoundException ( "Unknown tenant: " + tenantName ) ; } return 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 , password ) ; Permission perm = permissionForMethod ( request . getMethod ( ) ) ; TenantService . instance ( ) . validateTenantAccess ( tenant , userID . toString ( ) , password . toString ( ) , perm , cmdModel . isPrivileged ( ) ) ; }
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 ( ) ) ; List < Pair < String , String > > unusedList = new ArrayList < Pair < String , String > > ( ) ; boolean bRewrite = false ; for ( String part : parts ) { Pair < String , String > param = extractParam ( part ) ; switch ( param . firstItemInPair . toLowerCase ( ) ) { case "api" : bRewrite = true ; restParams . put ( "api" , param . secondItemInPair ) ; break ; case "format" : bRewrite = true ; if ( param . secondItemInPair . equalsIgnoreCase ( "xml" ) ) { restParams . put ( "format" , "text/xml" ) ; } else if ( param . secondItemInPair . equalsIgnoreCase ( "json" ) ) { restParams . put ( "format" , "application/json" ) ; } break ; case "tenant" : bRewrite = true ; restParams . put ( "tenant" , param . secondItemInPair ) ; break ; default : unusedList . add ( param ) ; } } if ( bRewrite ) { buffer . setLength ( 0 ) ; for ( Pair < String , String > pair : unusedList ) { if ( buffer . length ( ) > 0 ) { buffer . append ( "&" ) ; } buffer . append ( Utils . urlEncode ( pair . firstItemInPair ) ) ; if ( pair . secondItemInPair != null ) { buffer . append ( "=" ) ; buffer . append ( Utils . urlEncode ( pair . secondItemInPair ) ) ; } } } return 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 ( "?" ) ; buffer . append ( queryParam ) ; } return buffer . toString ( ) ; }
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 { File f = new File ( spec ) ; if ( f . exists ( ) ) { configUrl = new URL ( "file:///" + f . getCanonicalPath ( ) ) ; } } catch ( Exception ex ) { } } if ( configUrl == null ) { ClassLoader loader = ServerParams . class . getClassLoader ( ) ; configUrl = loader . getResource ( spec ) ; if ( configUrl == null ) { throw new ConfigurationException ( "Can't find file/resource: \"" + spec + "\"." ) ; } } return configUrl ; }
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 , paramValue ) ; } else { parentMap . put ( paramName , paramValue . toString ( ) ) ; } } else { Utils . require ( paramValue instanceof Map , "Parameter '%s' must be a map: %s" , paramName , paramValue . toString ( ) ) ; Map < String , Object > currentMap = ( Map < String , Object > ) currentValue ; Map < String , Object > updateMap = ( Map < String , Object > ) paramValue ; for ( String subParam : updateMap . keySet ( ) ) { updateMap ( currentMap , subParam , updateMap . get ( subParam ) ) ; } } }
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_legacyToModuleMap . get ( legacyParamName ) ; if ( moduleName == null ) { logger . warn ( "Skipping unknown legacy parameter: {}" , legacyParamName ) ; } else { setModuleParam ( moduleName , legacyParamName , paramValue ) ; } }
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 ( ) ) { FieldDefinition fieldDef = new FieldDefinition ( ) ; fieldDef . parse ( childNode . getMember ( fieldName ) ) ; addFieldDefinition ( fieldDef ) ; } } else if ( childName . equals ( "options" ) ) { for ( String optName : childNode . getMemberNames ( ) ) { UNode optNode = childNode . getMember ( optName ) ; Utils . require ( optNode . isValue ( ) , "'option' must be a value: " + optNode ) ; Utils . require ( getOption ( optName ) == null , "Option '" + optName + "' can only be specified once" ) ; setOption ( optName , optNode . getValue ( ) ) ; } } else if ( childName . equals ( "aliases" ) ) { for ( String aliasName : childNode . getMemberNames ( ) ) { AliasDefinition aliasDef = new AliasDefinition ( m_tableName ) ; aliasDef . parse ( childNode . getMember ( aliasName ) ) ; addAliasDefinition ( aliasDef ) ; } } else { Utils . require ( false , "Unrecognized 'table' element: " + childName ) ; } } verify ( ) ; }
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 ( ) ; switch ( m_shardingGranularity ) { case HOUR : shardDate . add ( Calendar . HOUR_OF_DAY , shardNumber - 1 ) ; break ; case DAY : shardDate . add ( Calendar . DAY_OF_MONTH , shardNumber - 1 ) ; break ; case WEEK : shardDate = Utils . truncateToWeek ( m_shardingStartDate ) ; shardDate . add ( Calendar . DAY_OF_MONTH , ( shardNumber - 1 ) * 7 ) ; break ; case MONTH : shardDate . add ( Calendar . MONTH , shardNumber - 1 ) ; shardDate . set ( Calendar . DAY_OF_MONTH , 1 ) ; break ; } result = shardDate . getTime ( ) ; } assert computeShardNumber ( result ) == shardNumber ; return result ; }
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 ( ) < m_shardingStartDate . getTimeInMillis ( ) ) { return 0 ; } int shardNumber = 1 ; switch ( m_shardingGranularity ) { case HOUR : shardNumber += ( objectDate . getTimeInMillis ( ) - m_shardingStartDate . getTimeInMillis ( ) ) / MILLIS_IN_HOUR ; break ; case DAY : shardNumber += ( objectDate . getTimeInMillis ( ) - m_shardingStartDate . getTimeInMillis ( ) ) / MILLIS_IN_DAY ; break ; case WEEK : GregorianCalendar shard1week = Utils . truncateToWeek ( m_shardingStartDate ) ; shardNumber += ( objectDate . getTimeInMillis ( ) - shard1week . getTimeInMillis ( ) ) / MILLIS_IN_WEEK ; break ; case MONTH : int diffInMonths = ( ( objectDate . get ( Calendar . YEAR ) - m_shardingStartDate . get ( Calendar . YEAR ) ) * 12 ) + ( objectDate . get ( Calendar . MONTH ) - m_shardingStartDate . get ( Calendar . MONTH ) ) ; shardNumber += diffInMonths ; break ; default : Utils . require ( false , "Unknown sharding-granularity: " + m_shardingGranularity ) ; } return shardNumber ; }
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 sharding - start date . Otherwise it will be &gt ; = 1 representing the shard in which the object should reside .
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 . put ( optionName . toLowerCase ( ) , optionValue ) ; if ( optionName . equalsIgnoreCase ( CommonDefs . OPT_SHARDING_GRANULARITY ) ) { m_shardingGranularity = ShardingGranularity . fromString ( optionValue ) ; Utils . require ( m_shardingGranularity != null , "Unrecognized 'sharding-granularity' value: " + optionValue ) ; } else if ( optionName . equalsIgnoreCase ( CommonDefs . OPT_SHARDING_START ) ) { Utils . require ( isValidShardDate ( optionValue ) , "'sharding-start' must be YYYY-MM-DD: " + optionValue ) ; m_shardingStartDate = new GregorianCalendar ( Utils . UTC_TIMEZONE ) ; m_shardingStartDate . setTime ( Utils . dateFromString ( optionValue ) ) ; } }
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 , slashInx ) ; String linkValue = colName . substring ( slashInx + 1 ) ; Set < String > valueSet = mvLinkValueMap . get ( fieldName ) ; if ( valueSet == null ) { valueSet = new HashSet < String > ( ) ; mvLinkValueMap . put ( fieldName , valueSet ) ; } valueSet . add ( linkValue ) ; return true ; }
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 not been defined: %s" , xlinkDef . getName ( ) , xlinkDef . getXLinkJunction ( ) ) ) ; Utils . require ( juncFieldDef . getType ( ) == FieldType . TEXT , String . format ( "Junction field for xlink '%s' must be a text field: " , xlinkDef . getName ( ) , xlinkDef . getXLinkJunction ( ) ) ) ; } }
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 ( ByteBuffer . wrap ( col . getRawValue ( ) ) ) ; } } else { String strValue = col . getValue ( ) ; if ( strValue . length ( ) == 0 ) { strValue = DynamoDBService . NULL_COLUMN_MARKER ; } attrValue . setS ( strValue ) ; } return attrValue ; }
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 . length ( ) == 0 ) continue ; result . add ( token ) ; } } return result ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Error parsing field value: " + e . getLocalizedMessage ( ) ) ; } }
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 ( ObjectResult objResult : m_objResultList ) { docsNode . addChildNode ( objResult . toDoc ( ) ) ; } } return result ; }
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 . keySet ( ) ) { String value = propMap . get ( name ) ; if ( Utils . isEmpty ( value ) ) { dbTran . deleteColumn ( TaskManagerService . TASKS_STORE_NAME , taskID , name ) ; } else { dbTran . addColumn ( TaskManagerService . TASKS_STORE_NAME , taskID , name , value ) ; } } if ( bDeleteClaimRecord ) { dbTran . deleteRow ( TaskManagerService . TASKS_STORE_NAME , "_claim/" + taskID ) ; } DBService . instance ( tenant ) . commit ( dbTran ) ; }
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 ( ! colIter . hasNext ( ) ) { taskRecord = storeTaskRecord ( tenant , task ) ; } else { taskRecord = buildTaskRecord ( task . getTaskID ( ) , colIter ) ; } if ( pred . test ( taskRecord . getStatus ( ) ) ) { break ; } try { Thread . sleep ( TASK_CHECK_MILLIS ) ; } catch ( InterruptedException e ) { } } ; return taskRecord ; }
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 ) ; } } } catch ( Throwable e ) { m_logger . warn ( "Could not check tasks for tenant '{}': {}" , tenant . getName ( ) , e ) ; } }
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 ) . getAllColumns ( TaskManagerService . TASKS_STORE_NAME , task . getTaskID ( ) ) . iterator ( ) ; TaskRecord taskRecord = null ; if ( ! colIter . hasNext ( ) ) { taskRecord = storeTaskRecord ( tenant , task ) ; } else { taskRecord = buildTaskRecord ( task . getTaskID ( ) , colIter ) ; } if ( taskShouldExecute ( task , taskRecord ) && canHandleMoreTasks ( ) ) { attemptToExecuteTask ( appDef , task , taskRecord ) ; } } }
Check the given task to see if we should and can execute it .