idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
17,900 | @ SuppressWarnings ( "unchecked" ) private String keyspaceDefaultsToCQLString ( ) { // Default defaults: boolean durable_writes = true ; Map < String , Object > replication = new HashMap < String , Object > ( ) ; replication . put ( "class" , "SimpleStrategy" ) ; replication . put ( "replication_factor" , "1" ) ; // Legacy support: ReplicationFactor if ( m_dbservice . getParam ( "ReplicationFactor" ) != null ) { replication . put ( "replication_factor" , m_dbservice . getParamString ( "ReplicationFactor" ) ) ; } // Override any options specified in ks_defaults 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 . | 491 | 15 |
17,901 | 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 . | 185 | 11 |
17,902 | 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 . | 98 | 11 |
17,903 | private void checkTable ( ) { // Documentation says that "0 xxx" means data-aging is disabled. 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 . | 440 | 13 |
17,904 | private String buildFixedQuery ( GregorianCalendar expireDate ) { // Query: '{aging field} <= "{expire date}"', fetching the _ID and // aging field, up to a batch full at a time. StringBuilder fixedParams = new StringBuilder ( ) ; fixedParams . append ( "q=" ) ; fixedParams . append ( m_agingFieldDef . getName ( ) ) ; fixedParams . append ( " <= \"" ) ; fixedParams . append ( Utils . formatDate ( expireDate ) ) ; fixedParams . append ( "\"" ) ; // Fields: _ID. fixedParams . append ( "&f=_ID" ) ; // Size: QUERY_PAGE_SIZE 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 . | 198 | 16 |
17,905 | 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 . | 158 | 10 |
17,906 | 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 . | 55 | 18 |
17,907 | 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 . | 92 | 13 |
17,908 | 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 . | 137 | 12 |
17,909 | 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 . | 55 | 12 |
17,910 | 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 . | 150 | 12 |
17,911 | 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 . | 91 | 13 |
17,912 | 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 . | 74 | 13 |
17,913 | 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 . | 71 | 7 |
17,914 | public synchronized void onRequestRejected ( String reason ) { allRequestsTracker . onRequestRejected ( reason ) ; recentRequestsTracker . onRequestRejected ( reason ) ; meter . mark ( ) ; } | Registers an invalid request rejected by the server . | 45 | 10 |
17,915 | public boolean deleteShard ( String shard ) { Utils . require ( ! Utils . isEmpty ( shard ) , "shard" ) ; try { // Send a DELETE request to "/{application}/_shards/{shard}" 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 . | 248 | 35 |
17,916 | public Collection < String > getShardNames ( ) { List < String > shardNames = new ArrayList <> ( ) ; try { // Send a GET request to "/{application}/_shards" 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 ) ; // Response should be UNode tree in the form /Results/{application}/shards // where "shards" is an array of shard names. 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 . | 342 | 27 |
17,917 | public UNode getShardStats ( String shardName ) { try { // Send a GET request to "/{application}/_shards/{shard}" 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 . | 225 | 55 |
17,918 | public boolean mergeShard ( String shard , Date expireDate ) { Utils . require ( ! Utils . isEmpty ( shard ) , "shard" ) ; try { // Send a POST request to "/{application}/_shards/{shard}[?expire-date=<date>]" 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 . | 308 | 53 |
17,919 | 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 . | 95 | 13 |
17,920 | 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 . | 54 | 21 |
17,921 | 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 . | 52 | 20 |
17,922 | 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 . | 89 | 25 |
17,923 | public static long getTimeMicros ( ) { // Use use a dedicated lock object rather than synchronizing on the method, which // would synchronize on the Utils.class object, which is too coarse-grained. synchronized ( g_lastMicroLock ) { // We use System.currentTimeMillis() * 1000 for compatibility with the CLI and // other tools. This makes our timestamps "milliseconds since the epoch". long newValue = System . currentTimeMillis ( ) * 1000 ; if ( newValue <= g_lastMicroValue ) { // Either two threads called us very quickly or the system clock was set // back a little. Just return the last value allocated + 1. Eventually, // the system clock will catch up. 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 . | 183 | 29 |
17,924 | public static String deWhite ( byte [ ] value ) { // If the value contains anything less than a space. StringBuilder buffer = new StringBuilder ( ) ; boolean bAllPrintable = true ; for ( byte b : value ) { if ( ( int ) ( b & 0xFF ) < ' ' ) { bAllPrintable = false ; break ; } } if ( bAllPrintable ) { // All >= space; convert directly to chars. for ( byte b : value ) { buffer . append ( ( char ) b ) ; } } else { // At least one non-printable. Convert to hex. 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 . | 206 | 32 |
17,925 | 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 . | 71 | 31 |
17,926 | 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 . | 127 | 126 |
17,927 | 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 . | 115 | 59 |
17,928 | public static Element parseXMLDocument ( String xmlDoc ) throws IllegalArgumentException { // Parse the given XML document returning its root document Element if it parses. // Wrap the document payload as an InputSource. Reader stringReader = new StringReader ( xmlDoc ) ; InputSource inputSource = new InputSource ( stringReader ) ; // Parse the document into a DOM tree. DocumentBuilderFactory dbf = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder parser = null ; Document doc = null ; try { parser = dbf . newDocumentBuilder ( ) ; doc = parser . parse ( inputSource ) ; } catch ( Exception ex ) { // Turn ParserConfigurationException, SAXException, etc. into an IllegalArgumentException 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 . | 189 | 31 |
17,929 | 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 . | 106 | 68 |
17,930 | 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 | 105 | 14 |
17,931 | 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 | 97 | 12 |
17,932 | public static GregorianCalendar truncateToWeek ( GregorianCalendar date ) { // Round the date down to the MONDAY of the same week. 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 . | 234 | 49 |
17,933 | private RESTResponse validateAndExecuteRequest ( HttpServletRequest request ) { Map < String , String > variableMap = new HashMap < String , String > ( ) ; String query = extractQueryParam ( request , variableMap ) ; Tenant tenant = getTenant ( variableMap ) ; // Command matching expects an encoded URI but without the servlet context, if any. 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 . | 320 | 16 |
17,934 | private ApplicationDefinition getApplication ( String uri , Tenant tenant ) { if ( uri . length ( ) < 2 || uri . startsWith ( "/_" ) ) { return null ; // Non-application request } 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 . | 140 | 14 |
17,935 | 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 . | 113 | 15 |
17,936 | 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 . | 133 | 15 |
17,937 | 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 . | 84 | 12 |
17,938 | private String extractQueryParam ( HttpServletRequest request , Map < String , String > restParams ) { String query = request . getQueryString ( ) ; if ( Utils . isEmpty ( query ) ) { return "" ; } StringBuilder buffer = new StringBuilder ( query ) ; // Split query component into decoded, &-separate components. 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 we extracted any fixed params, rewrite the query parameter. 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 . | 476 | 13 |
17,939 | 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 . | 103 | 11 |
17,940 | 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 . | 69 | 14 |
17,941 | 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 . | 44 | 14 |
17,942 | 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 ( ) ; // catches well-formed but bogus URLs } 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 | 218 | 9 |
17,943 | @ 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 . | 225 | 15 |
17,944 | 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 . | 148 | 9 |
17,945 | public void parse ( UNode tableNode ) { assert tableNode != null ; // Verify table name and save it. setTableName ( tableNode . getName ( ) ) ; // Examine table node's children. for ( String childName : tableNode . getMemberNames ( ) ) { UNode childNode = tableNode . getMember ( childName ) ; // "fields" if ( childName . equals ( "fields" ) ) { // Process field definitions. for ( String fieldName : childNode . getMemberNames ( ) ) { // Create a FieldDefinition and parse the node's value into it. // This will throw if the definition is invalid. FieldDefinition fieldDef = new FieldDefinition ( ) ; fieldDef . parse ( childNode . getMember ( fieldName ) ) ; // Ensure field name is unique and add it to the table's field map. addFieldDefinition ( fieldDef ) ; } // "options" } else if ( childName . equals ( "options" ) ) { // Examine each option. for ( String optName : childNode . getMemberNames ( ) ) { // Each option must be a simple value and specified only once. 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" ) ; // Add option to option map, which performs some immediate validation. setOption ( optName , optNode . getValue ( ) ) ; } // "aliases" } else if ( childName . equals ( "aliases" ) ) { // Parse and add each AliasDefinition. for ( String aliasName : childNode . getMemberNames ( ) ) { AliasDefinition aliasDef = new AliasDefinition ( m_tableName ) ; aliasDef . parse ( childNode . getMember ( aliasName ) ) ; addAliasDefinition ( aliasDef ) ; } // Unrecognized } 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 . | 471 | 45 |
17,946 | 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 . | 59 | 28 |
17,947 | public Date computeShardStart ( int shardNumber ) { assert isSharded ( ) ; assert shardNumber > 0 ; assert m_shardingStartDate != null ; // Shard #1 always starts on the sharding-start date. Date result = null ; if ( shardNumber == 1 ) { result = m_shardingStartDate . getTime ( ) ; } else { // Clone m_shardingStartDate and adjust by shard number. GregorianCalendar shardDate = ( GregorianCalendar ) m_shardingStartDate . clone ( ) ; switch ( m_shardingGranularity ) { case HOUR : // Increment start date HOUR by shard number - 1. shardDate . add ( Calendar . HOUR_OF_DAY , shardNumber - 1 ) ; break ; case DAY : // Increment start date DAY by shard number - 1. shardDate . add ( Calendar . DAY_OF_MONTH , shardNumber - 1 ) ; break ; case WEEK : // Round the sharding-start date down to the MONDAY of the same week. // Then increment it's DAY by (shard number - 1) * 7. shardDate = Utils . truncateToWeek ( m_shardingStartDate ) ; shardDate . add ( Calendar . DAY_OF_MONTH , ( shardNumber - 1 ) * 7 ) ; break ; case MONTH : // Increment start date MONTH by shard number - 1, but the day is always 1. 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 . | 395 | 60 |
17,948 | public int computeShardNumber ( Date shardingFieldValue ) { assert shardingFieldValue != null ; assert isSharded ( ) ; assert m_shardingStartDate != null ; // Convert the sharding field value into a calendar object. Note that this value // will have non-zero time elements. GregorianCalendar objectDate = new GregorianCalendar ( Utils . UTC_TIMEZONE ) ; objectDate . setTime ( shardingFieldValue ) ; // Since the start date has no time elements, if the result is negative, the object's // date is before the start date. if ( objectDate . getTimeInMillis ( ) < m_shardingStartDate . getTimeInMillis ( ) ) { // Object date occurs before sharding start. Shard number -> 0. return 0 ; } // Determine the shard number based on the granularity. int shardNumber = 1 ; switch ( m_shardingGranularity ) { case HOUR : // Increment shard number by difference in millis-per-hours. shardNumber += ( objectDate . getTimeInMillis ( ) - m_shardingStartDate . getTimeInMillis ( ) ) / MILLIS_IN_HOUR ; break ; case DAY : // Since the dates are in UTC, which doesn't have DST, the difference in days // is simply the difference in whole number of millis-per-day. shardNumber += ( objectDate . getTimeInMillis ( ) - m_shardingStartDate . getTimeInMillis ( ) ) / MILLIS_IN_DAY ; break ; case WEEK : // Truncate the sharding-start date to MONDAY. The difference in weeks is then // the shard increment. GregorianCalendar shard1week = Utils . truncateToWeek ( m_shardingStartDate ) ; shardNumber += ( objectDate . getTimeInMillis ( ) - shard1week . getTimeInMillis ( ) ) / MILLIS_IN_WEEK ; break ; case MONTH : // Difference in months is 12 * (difference in years) + (difference in months) 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 > ; = 1 representing the shard in which the object should reside . | 574 | 94 |
17,949 | 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 . | 53 | 31 |
17,950 | 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 . | 44 | 20 |
17,951 | public void setOption ( String optionName , String optionValue ) { // Ensure option value is not empty and trim excess whitespace. 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 ) ; // sharding-granularity and sharding-start are validated here since we must set // local members when the table's definition is parsed. 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 . | 336 | 34 |
17,952 | 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 . | 76 | 14 |
17,953 | public boolean extractLinkValue ( String colName , Map < String , Set < String > > mvLinkValueMap ) { // Link column names always begin with '~'. if ( colName . length ( ) == 0 || colName . charAt ( 0 ) != ' ' ) { return false ; } // A '/' should separate the field name and object value. int slashInx = colName . indexOf ( ' ' ) ; if ( slashInx < 0 ) { return false ; } // Extract the field name and ensure we know about this field. String fieldName = colName . substring ( 1 , slashInx ) ; // Extract the link value's target object ID and add it to the value set for the field. String linkValue = colName . substring ( slashInx + 1 ) ; Set < String > valueSet = mvLinkValueMap . get ( fieldName ) ; if ( valueSet == null ) { // First value for this field. 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 . | 247 | 53 |
17,954 | private void addAliasDefinition ( AliasDefinition aliasDef ) { // Prerequisites: 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 . | 85 | 10 |
17,955 | 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 . | 193 | 20 |
17,956 | 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 . | 177 | 15 |
17,957 | 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 ) { // Turn into an IllegalArgumentException throw new IllegalArgumentException ( "Error parsing field value: " + e . getLocalizedMessage ( ) ) ; } } | Analyze the given String value and return the set of terms that should be indexed . | 158 | 17 |
17,958 | 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 . | 50 | 16 |
17,959 | 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 . | 47 | 15 |
17,960 | public UNode toDoc ( ) { // Root node is map with 1 child per result field and optionally "docs". 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 . | 150 | 22 |
17,961 | 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 . | 89 | 23 |
17,962 | 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 . | 87 | 25 |
17,963 | 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 . | 224 | 20 |
17,964 | 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 . | 186 | 18 |
17,965 | 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 . | 77 | 13 |
17,966 | 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 . | 131 | 10 |
17,967 | 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 . | 217 | 14 |
17,968 | private void attemptToExecuteTask ( ApplicationDefinition appDef , Task task , TaskRecord taskRecord ) { Tenant tenant = Tenant . getTenant ( appDef ) ; String taskID = taskRecord . getTaskID ( ) ; String claimID = "_claim/" + taskID ; long claimStamp = System . currentTimeMillis ( ) ; writeTaskClaim ( tenant , claimID , claimStamp ) ; if ( taskClaimedByUs ( tenant , claimID ) ) { startTask ( appDef , task , taskRecord ) ; } else { m_logger . info ( "Will not start task: it was claimed by another service" ) ; } } | Attempt to start the given task by creating claim and see if we win it . | 143 | 16 |
17,969 | private void startTask ( ApplicationDefinition appDef , Task task , TaskRecord taskRecord ) { try { task . setParams ( m_localHost , taskRecord ) ; m_executor . execute ( task ) ; } catch ( Exception e ) { m_logger . error ( "Failed to start task '" + task . getTaskID ( ) + "'" , e ) ; } } | Execute the given task by handing it to the ExecutorService . | 85 | 14 |
17,970 | private boolean taskClaimedByUs ( Tenant tenant , String claimID ) { waitForClaim ( ) ; Iterator < DColumn > colIter = DBService . instance ( tenant ) . getAllColumns ( TaskManagerService . TASKS_STORE_NAME , claimID ) . iterator ( ) ; if ( colIter == null ) { m_logger . warn ( "Claim record disappeared: {}" , claimID ) ; return false ; } String claimingHost = m_hostClaimID ; long earliestClaim = Long . MAX_VALUE ; while ( colIter . hasNext ( ) ) { DColumn col = colIter . next ( ) ; try { long claimStamp = Long . parseLong ( col . getValue ( ) ) ; // otarakanov: sometimes, the task writes a claim but does not start. The claim remains the lowest // and makes future tries to write new claims but not start. // we disregard claims older that ten minutes. long secondsSinceClaim = ( System . currentTimeMillis ( ) - claimStamp ) / 1000 ; if ( secondsSinceClaim > 600 ) continue ; String claimHost = col . getName ( ) ; if ( claimStamp < earliestClaim ) { claimingHost = claimHost ; earliestClaim = claimStamp ; } else if ( claimStamp == earliestClaim ) { // Two nodes chose the same claim stamp. Lower node name wins. if ( claimHost . compareTo ( claimingHost ) < 0 ) { claimingHost = claimHost ; } } } catch ( NumberFormatException e ) { // Ignore this column } } return claimingHost . equals ( m_hostClaimID ) && ! m_bShutdown ; } | Indicate if we won the claim to run the given task . | 358 | 13 |
17,971 | private void writeTaskClaim ( Tenant tenant , String claimID , long claimStamp ) { DBTransaction dbTran = DBService . instance ( tenant ) . startTransaction ( ) ; dbTran . addColumn ( TaskManagerService . TASKS_STORE_NAME , claimID , m_hostClaimID , claimStamp ) ; DBService . instance ( tenant ) . commit ( dbTran ) ; } | Write a claim record to the Tasks table . | 93 | 10 |
17,972 | private TaskRecord buildTaskRecord ( String taskID , Iterator < DColumn > colIter ) { TaskRecord taskRecord = new TaskRecord ( taskID ) ; while ( colIter . hasNext ( ) ) { DColumn col = colIter . next ( ) ; taskRecord . setProperty ( col . getName ( ) , col . getValue ( ) ) ; } return taskRecord ; } | Create a TaskRecord from a task status row read from the Tasks table . | 83 | 16 |
17,973 | private TaskRecord storeTaskRecord ( Tenant tenant , Task task ) { DBTransaction dbTran = DBService . instance ( tenant ) . startTransaction ( ) ; TaskRecord taskRecord = new TaskRecord ( task . getTaskID ( ) ) ; Map < String , String > propMap = taskRecord . getProperties ( ) ; assert propMap . size ( ) > 0 : "Need at least one property to store a row!" ; for ( String propName : propMap . keySet ( ) ) { dbTran . addColumn ( TaskManagerService . TASKS_STORE_NAME , task . getTaskID ( ) , propName , propMap . get ( propName ) ) ; } DBService . instance ( tenant ) . commit ( dbTran ) ; return taskRecord ; } | Create a TaskRecord for the given task and write it to the Tasks table . | 173 | 17 |
17,974 | private List < Task > getAppTasks ( ApplicationDefinition appDef ) { List < Task > appTasks = new ArrayList <> ( ) ; try { StorageService service = SchemaService . instance ( ) . getStorageService ( appDef ) ; Collection < Task > appTaskColl = service . getAppTasks ( appDef ) ; if ( appTaskColl != null ) { appTasks . addAll ( service . getAppTasks ( appDef ) ) ; } } catch ( IllegalArgumentException e ) { // StorageService has not been initialized; no tasks for this application. } return appTasks ; } | Ask the storage manager for the given application for its required tasks . | 133 | 13 |
17,975 | private void checkForDeadTask ( Tenant tenant , TaskRecord taskRecord ) { Calendar lastReport = taskRecord . getTime ( TaskRecord . PROP_PROGRESS_TIME ) ; if ( lastReport == null ) { lastReport = taskRecord . getTime ( TaskRecord . PROP_START_TIME ) ; if ( lastReport == null ) { return ; // corrupt/incomplete task record } } long minsSinceLastActivity = ( System . currentTimeMillis ( ) - lastReport . getTimeInMillis ( ) ) / ( 1000 * 60 ) ; if ( isOurActiveTask ( tenant , taskRecord . getTaskID ( ) ) ) { checkForHungTask ( tenant , taskRecord , minsSinceLastActivity ) ; } else { checkForAbandonedTask ( tenant , taskRecord , minsSinceLastActivity ) ; } } | See if the given in - progress task may be hung or abandoned . | 181 | 14 |
17,976 | private void checkForHungTask ( Tenant tenant , TaskRecord taskRecord , long minsSinceLastActivity ) { if ( minsSinceLastActivity > HUNG_TASK_THRESHOLD_MINS ) { String taskIdentity = createMapKey ( tenant , taskRecord . getTaskID ( ) ) ; String reason = "No progress reported in " + minsSinceLastActivity + " minutes" ; m_logger . warn ( "Local task {} has not reported progress in {} minutes; " + "restart the server if this continues for too long" , taskIdentity , minsSinceLastActivity ) ; taskRecord . setProperty ( TaskRecord . PROP_PROGRESS_TIME , Long . toString ( System . currentTimeMillis ( ) ) ) ; taskRecord . setProperty ( TaskRecord . PROP_PROGRESS , reason ) ; updateTaskStatus ( tenant , taskRecord , false ) ; } } | potentially harmful second task execution . | 197 | 7 |
17,977 | private void checkForAbandonedTask ( Tenant tenant , TaskRecord taskRecord , long minsSinceLastActivity ) { if ( minsSinceLastActivity > DEAD_TASK_THRESHOLD_MINS ) { String taskIdentity = createMapKey ( tenant , taskRecord . getTaskID ( ) ) ; String reason = "No progress reported in " + minsSinceLastActivity + " minutes" ; m_logger . error ( "Remote task {} has not reported progress in {} minutes; marking as failed" , taskIdentity , minsSinceLastActivity ) ; taskRecord . setProperty ( TaskRecord . PROP_FINISH_TIME , Long . toString ( System . currentTimeMillis ( ) ) ) ; taskRecord . setProperty ( TaskRecord . PROP_FAIL_REASON , reason ) ; taskRecord . setStatus ( TaskStatus . FAILED ) ; updateTaskStatus ( tenant , taskRecord , true ) ; } } | to restart upon the next check - tasks cycle . | 203 | 10 |
17,978 | private boolean isOurActiveTask ( Tenant tenant , String taskID ) { synchronized ( m_activeTasks ) { return m_activeTasks . containsKey ( createMapKey ( tenant , taskID ) ) ; } } | Return true if we are currently executing the given task . | 48 | 11 |
17,979 | private void commitTransaction ( ) { Tenant tenant = Tenant . getTenant ( m_tableDef ) ; DBTransaction dbTran = DBService . instance ( tenant ) . startTransaction ( ) ; m_parentTran . applyUpdates ( dbTran ) ; DBService . instance ( tenant ) . commit ( dbTran ) ; m_parentTran . clear ( ) ; } | Post all updates in the parent transaction to the database . | 88 | 11 |
17,980 | private boolean updateBatch ( DBObjectBatch dbObjBatch , BatchResult batchResult ) throws IOException { Map < String , Map < String , String > > objCurrScalarMap = getCurrentScalars ( dbObjBatch ) ; Map < String , Map < String , Integer > > targObjShardNos = getLinkTargetShardNumbers ( dbObjBatch ) ; for ( DBObject dbObj : dbObjBatch . getObjects ( ) ) { checkCommit ( ) ; Map < String , String > currScalarMap = objCurrScalarMap . get ( dbObj . getObjectID ( ) ) ; ObjectResult objResult = updateObject ( dbObj , currScalarMap , targObjShardNos ) ; batchResult . addObjectResult ( objResult ) ; } commitTransaction ( ) ; return batchResult . hasUpdates ( ) ; } | Update each object in the given batch updating BatchResult accordingly . | 199 | 13 |
17,981 | private ObjectResult updateObject ( DBObject dbObj , Map < String , String > currScalarMap , Map < String , Map < String , Integer > > targObjShardNos ) { ObjectResult objResult = null ; if ( Utils . isEmpty ( dbObj . getObjectID ( ) ) ) { objResult = ObjectResult . newErrorResult ( "Object ID is required" , null ) ; } else if ( currScalarMap == null ) { objResult = ObjectResult . newErrorResult ( "No object found" , dbObj . getObjectID ( ) ) ; } else { ObjectUpdater objUpdater = new ObjectUpdater ( m_tableDef ) ; if ( targObjShardNos . size ( ) > 0 ) { objUpdater . setTargetObjectShardNumbers ( targObjShardNos ) ; } objResult = objUpdater . updateObject ( m_parentTran , dbObj , currScalarMap ) ; } return objResult ; } | Update the given object which must exist using the given set of current scalar values . | 224 | 17 |
17,982 | private ObjectResult addOrUpdateObject ( DBObject dbObj , Map < String , String > currScalarMap , Map < String , Map < String , Integer > > targObjShardNos ) throws IOException { ObjectUpdater objUpdater = new ObjectUpdater ( m_tableDef ) ; if ( targObjShardNos . size ( ) > 0 ) { objUpdater . setTargetObjectShardNumbers ( targObjShardNos ) ; } if ( currScalarMap == null || currScalarMap . size ( ) == 0 ) { return objUpdater . addNewObject ( m_parentTran , dbObj ) ; } else { return objUpdater . updateObject ( m_parentTran , dbObj , currScalarMap ) ; } } | Add the given object if its current - value map is null otherwise update the object . | 182 | 17 |
17,983 | private void buildErrorStatus ( BatchResult result , Throwable ex ) { result . setStatus ( BatchResult . Status . ERROR ) ; result . setErrorMessage ( ex . getLocalizedMessage ( ) ) ; if ( ex instanceof IllegalArgumentException ) { m_logger . debug ( "Batch update error: {}" , ex . toString ( ) ) ; } else { result . setStackTrace ( Utils . getStackTrace ( ex ) ) ; m_logger . debug ( "Batch update error: {} stacktrace: {}" , ex . toString ( ) , Utils . getStackTrace ( ex ) ) ; } } | Add error fields to the given BatchResult due to the given exception . | 144 | 15 |
17,984 | private Map < String , Map < String , String > > getCurrentScalars ( DBObjectBatch dbObjBatch ) throws IOException { Set < String > objIDSet = new HashSet <> ( ) ; Set < String > fieldNameSet = new HashSet < String > ( ) ; for ( DBObject dbObj : dbObjBatch . getObjects ( ) ) { if ( ! Utils . isEmpty ( dbObj . getObjectID ( ) ) ) { Utils . require ( objIDSet . add ( dbObj . getObjectID ( ) ) , "Cannot update the same object ID twice: " + dbObj . getObjectID ( ) ) ; fieldNameSet . addAll ( dbObj . getUpdatedScalarFieldNames ( m_tableDef ) ) ; } } if ( m_tableDef . isSharded ( ) ) { fieldNameSet . add ( m_tableDef . getShardingField ( ) . getName ( ) ) ; } return SpiderService . instance ( ) . getObjectScalars ( m_tableDef , objIDSet , fieldNameSet ) ; } | Watch and complain about updates to the same ID . | 241 | 10 |
17,985 | private Map < String , Map < String , Integer > > getLinkTargetShardNumbers ( DBObjectBatch dbObjBatch ) { Map < String , Map < String , Integer > > result = new HashMap <> ( ) ; Map < String , Set < String > > tableTargetObjIDMap = getAllLinkTargetObjIDs ( dbObjBatch ) ; for ( String targetTableName : tableTargetObjIDMap . keySet ( ) ) { Map < String , Integer > shardNoMap = getShardNumbers ( targetTableName , tableTargetObjIDMap . get ( targetTableName ) ) ; if ( shardNoMap . size ( ) > 0 ) { Map < String , Integer > tableShardNoMap = result . get ( targetTableName ) ; if ( tableShardNoMap == null ) { tableShardNoMap = new HashMap <> ( ) ; result . put ( targetTableName , tableShardNoMap ) ; } tableShardNoMap . putAll ( shardNoMap ) ; } } return result ; } | objects that have no sharding - field value . | 228 | 10 |
17,986 | private Map < String , Set < String > > getAllLinkTargetObjIDs ( DBObjectBatch dbObjBatch ) { Map < String , Set < String > > resultMap = new HashMap <> ( ) ; for ( FieldDefinition fieldDef : m_tableDef . getFieldDefinitions ( ) ) { if ( ! fieldDef . isLinkField ( ) || ! fieldDef . getInverseTableDef ( ) . isSharded ( ) ) { continue ; } Set < String > targObjIDs = getLinkTargetObjIDs ( fieldDef , dbObjBatch ) ; if ( targObjIDs . size ( ) == 0 ) { continue ; // no assignments to this sharded link in the batch } String targetTableName = fieldDef . getInverseTableDef ( ) . getTableName ( ) ; Set < String > tableObjIDs = resultMap . get ( targetTableName ) ; if ( tableObjIDs == null ) { tableObjIDs = new HashSet <> ( ) ; resultMap . put ( targetTableName , tableObjIDs ) ; } tableObjIDs . addAll ( targObjIDs ) ; } return resultMap ; } | table in the given batch . | 245 | 6 |
17,987 | private Set < String > getLinkTargetObjIDs ( FieldDefinition linkDef , DBObjectBatch dbObjBatch ) { Set < String > targObjIDs = new HashSet <> ( ) ; for ( DBObject dbObj : dbObjBatch . getObjects ( ) ) { List < String > objIDs = dbObj . getFieldValues ( linkDef . getName ( ) ) ; if ( objIDs != null ) { targObjIDs . addAll ( objIDs ) ; } Set < String > removeIDs = dbObj . getRemoveValues ( linkDef . getName ( ) ) ; if ( removeIDs != null ) { targObjIDs . addAll ( removeIDs ) ; } } return targObjIDs ; } | Target object IDs can be in the add or remove set . | 154 | 12 |
17,988 | private Map < String , Integer > getShardNumbers ( String tableName , Set < String > targObjIDs ) { TableDefinition tableDef = m_tableDef . getAppDef ( ) . getTableDef ( tableName ) ; FieldDefinition shardField = tableDef . getShardingField ( ) ; Map < String , String > shardFieldMap = SpiderService . instance ( ) . getObjectScalar ( tableDef , targObjIDs , shardField . getName ( ) ) ; Map < String , Integer > shardNoMap = new HashMap <> ( ) ; for ( String objID : shardFieldMap . keySet ( ) ) { Date shardingFieldDate = Utils . dateFromString ( shardFieldMap . get ( objID ) ) ; int shardNo = tableDef . computeShardNumber ( shardingFieldDate ) ; shardNoMap . put ( objID , shardNo ) ; } return shardNoMap ; } | has no value for its sharding - field leave the map empty for that object ID . | 209 | 18 |
17,989 | public void parse ( UNode userNode ) { m_userID = userNode . getName ( ) ; m_password = null ; m_permissions . clear ( ) ; for ( String childName : userNode . getMemberNames ( ) ) { UNode childNode = userNode . getMember ( childName ) ; switch ( childNode . getName ( ) ) { case "password" : Utils . require ( childNode . isValue ( ) , "'password' must be a simple value: " + childNode ) ; m_password = childNode . getValue ( ) ; break ; case "hash" : Utils . require ( childNode . isValue ( ) , "Invalid 'hash' value" ) ; m_hash = childNode . getValue ( ) ; break ; case "permissions" : Utils . require ( childNode . isValue ( ) , "'permissions' must be a list of values: " + childNode ) ; String [ ] permissions = childNode . getValue ( ) . split ( "," ) ; for ( String permission : permissions ) { String permToken = permission . toUpperCase ( ) . trim ( ) ; try { m_permissions . add ( Permission . valueOf ( permToken ) ) ; } catch ( IllegalArgumentException e ) { Utils . require ( false , "Unrecognized permission: %s; allowed values are: %s" , permToken , Arrays . asList ( Permission . values ( ) ) . toString ( ) ) ; } } break ; default : Utils . require ( false , "Unknown 'user' property: " + childNode ) ; } } } | Parse a user definition expressed as a UNode tree . | 354 | 12 |
17,990 | public UNode toDoc ( ) { UNode userNode = UNode . createMapNode ( m_userID , "user" ) ; if ( ! Utils . isEmpty ( m_password ) ) { userNode . addValueNode ( "password" , m_password , true ) ; } if ( ! Utils . isEmpty ( m_hash ) ) { userNode . addValueNode ( "hash" , m_hash , true ) ; } String permissions = "ALL" ; if ( m_permissions . size ( ) > 0 ) { permissions = Utils . concatenate ( m_permissions , "," ) ; } userNode . addValueNode ( "permissions" , permissions ) ; return userNode ; } | Serialize this user definition into a UNode tree . | 158 | 11 |
17,991 | private DBObject parseObject ( TableDefinition tableDef , UNode docNode ) { assert tableDef != null ; assert docNode != null ; assert docNode . getName ( ) . equals ( "doc" ) ; // Create the DBObject that we will return and parse the child nodes into it. DBObject dbObj = new DBObject ( ) ; for ( UNode childNode : docNode . getMemberList ( ) ) { // Extract field name and characterize what we expect. String fieldName = childNode . getName ( ) ; FieldDefinition fieldDef = tableDef . getFieldDef ( fieldName ) ; boolean isLinkField = fieldDef == null ? false : fieldDef . isLinkField ( ) ; boolean isGroupField = fieldDef == null ? false : fieldDef . isGroupField ( ) ; boolean isCollection = fieldDef == null ? false : fieldDef . isCollection ( ) ; Utils . require ( ! isGroupField , // we currently don't expect group fields in query results "Unexpected group field in query results: " + fieldName ) ; // Parse value based on what we expect. if ( isLinkField ) { parseLinkValue ( dbObj , childNode , fieldDef ) ; } else if ( isCollection ) { parseMVScalarValue ( dbObj , childNode , fieldDef ) ; } else { // Simple SV scalar value. Utils . require ( childNode . isValue ( ) , "Value of an SV scalar must be a value: " + childNode ) ; dbObj . addFieldValue ( fieldName , childNode . getValue ( ) ) ; } } // Our object is complete return dbObj ; } | than the perspective table of the query . | 354 | 8 |
17,992 | private void parseLinkValue ( DBObject owningObj , UNode linkNode , FieldDefinition linkFieldDef ) { // Prerequisites: assert owningObj != null ; assert linkNode != null ; assert linkFieldDef != null ; assert linkFieldDef . isLinkField ( ) ; TableDefinition tableDef = linkFieldDef . getTableDef ( ) ; // Value should be an array, though it could be a map with one child. Utils . require ( linkNode . isCollection ( ) , "Value of link field should be a collection: " + linkNode ) ; // Iterate through child nodes. TableDefinition extentTableDef = tableDef . getAppDef ( ) . getTableDef ( linkFieldDef . getLinkExtent ( ) ) ; for ( UNode childNode : linkNode . getMemberList ( ) ) { // Ensure this element is "doc" node. Utils . require ( childNode . getName ( ) . equals ( "doc" ) , "link field array values should be 'doc' objects: " + childNode ) ; // Recurse and build a DBObject from the doc node. DBObject linkedObject = parseObject ( extentTableDef , childNode ) ; // Add the linked object to the cache and add its object ID to the set. String objID = linkedObject . getObjectID ( ) ; cacheLinkedObject ( owningObj . getObjectID ( ) , linkFieldDef . getName ( ) , linkedObject ) ; owningObj . addFieldValues ( linkFieldDef . getName ( ) , Arrays . asList ( objID ) ) ; } } | object and add it to the linked object cache for the owning object and link . | 336 | 16 |
17,993 | private void cacheLinkedObject ( String owningObjID , String linkFieldName , DBObject linkedObject ) { // Find or create map for the owning object. Map < String , Map < String , DBObject > > objMap = m_linkedObjectMap . get ( owningObjID ) ; if ( objMap == null ) { objMap = new HashMap < String , Map < String , DBObject > > ( ) ; m_linkedObjectMap . put ( owningObjID , objMap ) ; } // Find or create map for the link field. Map < String , DBObject > linkMap = objMap . get ( linkFieldName ) ; if ( linkMap == null ) { linkMap = new HashMap < String , DBObject > ( ) ; objMap . put ( linkFieldName , linkMap ) ; } // Add the object to the link map. linkMap . put ( linkedObject . getObjectID ( ) , linkedObject ) ; } | link field name . | 201 | 4 |
17,994 | public static RESTParameter fromUNode ( UNode paramNode ) { RESTParameter param = new RESTParameter ( ) ; String name = paramNode . getName ( ) ; Utils . require ( ! Utils . isEmpty ( name ) , "Missing parameter name: " + paramNode ) ; param . setName ( name ) ; for ( UNode childNode : paramNode . getMemberList ( ) ) { switch ( childNode . getName ( ) ) { case "_required" : param . setRequired ( Boolean . parseBoolean ( childNode . getValue ( ) ) ) ; break ; case "_type" : param . setType ( childNode . getValue ( ) ) ; break ; default : // Ignore system properties we don't recognize. if ( childNode . getName ( ) . charAt ( 0 ) != ' ' ) { param . add ( RESTParameter . fromUNode ( childNode ) ) ; } break ; } } return param ; } | Create a new RESTParameter object from the given UNode tree . | 202 | 13 |
17,995 | public UNode toDoc ( ) { UNode paramNode = UNode . createMapNode ( m_name ) ; if ( ! Utils . isEmpty ( m_type ) ) { paramNode . addValueNode ( "_type" , m_type ) ; } if ( m_isRequired ) { paramNode . addValueNode ( "_required" , Boolean . toString ( m_isRequired ) ) ; } if ( m_parameters . size ( ) > 0 ) { for ( RESTParameter param : m_parameters ) { paramNode . addChildNode ( param . toDoc ( ) ) ; } } return paramNode ; } | Serialize this RESTParameter into a UNode tree and return the root node . | 137 | 16 |
17,996 | public RESTParameter add ( RESTParameter childParam ) { Utils . require ( ! Utils . isEmpty ( childParam . getName ( ) ) , "Child parameter name cannot be empty" ) ; m_parameters . add ( childParam ) ; return this ; } | Add the given RESTParameter as a child of this parameter . This parameter is returned to support builder syntax . | 57 | 21 |
17,997 | public RESTParameter add ( String childParamName , String childParamType ) { return add ( new RESTParameter ( childParamName , childParamType ) ) ; } | Add a new child parameter with the given name and type to this parameter . The child parameter will not be marked as required . This parameter is returned to support builder syntax . | 34 | 34 |
17,998 | DBConn getDBConnection ( ) { DBConn dbConn = null ; synchronized ( m_dbConns ) { if ( m_dbConns . size ( ) > 0 ) { dbConn = m_dbConns . poll ( ) ; } else { dbConn = createAndConnectConn ( m_keyspace ) ; } } return dbConn ; } | Get an available database connection from the pool creating a new one if needed . | 83 | 15 |
17,999 | void connectDBConn ( DBConn dbConn ) throws DBNotAvailableException , RuntimeException { // If we're using failover hosts, see if it's time to try primary hosts again. if ( m_bUseSecondaryHosts && ( System . currentTimeMillis ( ) - m_lastPrimaryHostCheckTimeMillis ) > getParamInt ( "primary_host_recheck_millis" , 60000 ) ) { m_bUseSecondaryHosts = false ; } // Try all primary hosts first if possible. DBNotAvailableException lastException = null ; if ( ! m_bUseSecondaryHosts ) { String [ ] dbHosts = getParamString ( "dbhost" ) . split ( "," ) ; for ( int attempt = 1 ; ! dbConn . isOpen ( ) && attempt <= dbHosts . length ; attempt ++ ) { try { dbConn . connect ( chooseHost ( dbHosts ) ) ; } catch ( DBNotAvailableException ex ) { lastException = ex ; } catch ( RuntimeException ex ) { throw ex ; // bad keyspace; abort connection attempts } } m_lastPrimaryHostCheckTimeMillis = System . currentTimeMillis ( ) ; } // Try secondary hosts if needed and if configured. if ( ! dbConn . isOpen ( ) && ! Utils . isEmpty ( getParamString ( "secondary_dbhost" ) ) ) { if ( ! m_bUseSecondaryHosts ) { m_logger . info ( "All connections to 'dbhost' failed; trying 'secondary_dbhost'" ) ; } String [ ] dbHosts = getParamString ( "secondary_dbhost" ) . split ( "," ) ; for ( int attempt = 1 ; ! dbConn . isOpen ( ) && attempt <= dbHosts . length ; attempt ++ ) { try { dbConn . connect ( chooseHost ( dbHosts ) ) ; } catch ( DBNotAvailableException e ) { lastException = e ; } catch ( RuntimeException ex ) { throw ex ; // bad keyspace; abort connection attempts } } if ( dbConn . isOpen ( ) ) { m_bUseSecondaryHosts = true ; // stick with secondary hosts for now. } } if ( ! dbConn . isOpen ( ) ) { m_logger . error ( "All Thrift connection attempts failed." , lastException ) ; throw lastException ; } } | configured keyspace is not available a RuntimeException is thrown . | 519 | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.