idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
6,900
private static < T > TypeReference < T > typeReferenceFrom ( final Type type ) { return new TypeReference < T > ( ) { public Type getType ( ) { return type ; } } ; }
Internal method for creating a TypeReference from a Java Type .
6,901
protected static AmazonS3 getS3Client ( URI stashRoot , AWSCredentialsProvider credentialsProvider ) { return getS3Client ( stashRoot , credentialsProvider , null ) ; }
Utility method to get the S3 client for a credentials provider .
6,902
public Iterator < StashTable > listTables ( ) { final String root = getRootPath ( ) ; final String prefix = String . format ( "%s/" , root ) ; return new AbstractIterator < StashTable > ( ) { Iterator < String > _commonPrefixes = Iterators . emptyIterator ( ) ; String _marker = null ; boolean _truncated = true ; protec...
Gets all tables available in this stash .
6,903
public List < StashSplit > getSplits ( String table ) throws StashNotAvailableException , TableNotStashedException { ImmutableList . Builder < StashSplit > splitsBuilder = ImmutableList . builder ( ) ; Iterator < S3ObjectSummary > objectSummaries = getS3ObjectSummariesForTable ( table ) ; while ( objectSummaries . hasN...
Get the splits for a record stored in stash . Each split corresponds to a file in the Stash table s directory .
6,904
private void getColumnNames ( ) { TableMetadata table = _keyspace . getKeyspaceMetadata ( ) . getTable ( CF_NAME ) ; _rowkeyColumn = table . getPrimaryKey ( ) . get ( 0 ) . getName ( ) ; _subscriptionNameColumn = table . getPrimaryKey ( ) . get ( 1 ) . getName ( ) ; _subscriptionColumn = table . getColumns ( ) . get ( ...
Because of the way databus tables were created historically using Astyanax and Cassandra 1 . 2 there may be inconsistency in the names of the CQL columns in the subscription table . To be safe read the table metadata to get the column names .
6,905
private int loadTable ( long uuid ) throws IOException { int bufferIndex = - 1 ; Set < Long > uuids = null ; int blockIndex = _blocks . size ( ) - 1 ; TableBlock lastBlock = _blocks . get ( blockIndex ) ; while ( bufferIndex == - 1 ) { Pair < Integer , Set < Long > > bufferIndexAndUuuids = lastBlock . writeTable ( uuid...
Loads a table from the source and places it into the next available space in the table blocks . Once the table is written it returns the index where the table is located for future reads .
6,906
private Table readTable ( int index ) { TableBlock block = _blocks . get ( getBlock ( index ) ) ; return block . getTable ( getBlockOffset ( index ) ) ; }
Reads the table located at the given index .
6,907
private void ensureBufferAvailable ( TableBlock block ) throws IOException { if ( ! block . hasBuffer ( ) ) { synchronized ( this ) { if ( ! block . hasBuffer ( ) ) { ByteBuffer buffer = getBuffer ( ) ; block . setBuffer ( buffer ) ; } } } }
Checks whether the given block has a buffer assigned to it . If not it synchronously gets an available buffer and assigns it to the block .
6,908
private List < Event > toEvents ( Collection < Item > items ) { if ( items . isEmpty ( ) ) { return ImmutableList . of ( ) ; } return items . stream ( ) . sorted ( ) . map ( Item :: toEvent ) . collect ( Collectors . toList ( ) ) ; }
Converts a collection of Items to Events .
6,909
private void unclaim ( String subscription , Collection < EventList > eventLists ) { List < String > eventIdsToUnclaim = Lists . newArrayList ( ) ; for ( EventList unclaimEvents : eventLists ) { for ( Pair < String , UUID > eventAndChangeId : unclaimEvents . getEventAndChangeIds ( ) ) { eventIdsToUnclaim . add ( eventA...
Convenience method to unclaim all of the events from a collection of event lists . This is to unclaim excess events when a padded poll returns more events than the requested limit .
6,910
public static String encode ( String s , Type t ) { return _encode ( s , t , false , false ) ; }
Encodes the characters of string that are either non - ASCII characters or are ASCII characters that must be percent - encoded using the UTF - 8 encoding .
6,911
public static List < PathSegment > decodePath ( URI u , boolean decode ) { String rawPath = u . getRawPath ( ) ; if ( rawPath != null && rawPath . length ( ) > 0 && rawPath . charAt ( 0 ) == '/' ) { rawPath = rawPath . substring ( 1 ) ; } return decodePath ( rawPath , decode ) ; }
Decode the path component of a URI as path segments .
6,912
public static void decodePathSegment ( List < PathSegment > segments , String segment , boolean decode ) { int colon = segment . indexOf ( ';' ) ; if ( colon != - 1 ) { segments . add ( new PathSegmentImpl ( ( colon == 0 ) ? "" : segment . substring ( 0 , colon ) , decode , decodeMatrix ( segment , decode ) ) ) ; } els...
Decode the path segment and add it to the list of path segments .
6,913
public static MultivaluedMap < String , String > decodeMatrix ( String pathSegment , boolean decode ) { MultivaluedMap < String , String > matrixMap = EmoMultivaluedMap . create ( ) ; int s = pathSegment . indexOf ( ';' ) + 1 ; if ( s == 0 || s == pathSegment . length ( ) ) { return matrixMap ; } do { int e = pathSegme...
Decode the matrix component of a URI path segment .
6,914
private static int decodeOctets ( int i , ByteBuffer bb , StringBuilder sb ) { if ( bb . limit ( ) == 1 && ( bb . get ( 0 ) & 0xFF ) < 0x80 ) { sb . append ( ( char ) bb . get ( 0 ) ) ; return i + 2 ; } else { CharBuffer cb = UTF_8_CHARSET . decode ( bb ) ; sb . append ( cb . toString ( ) ) ; return i + bb . limit ( ) ...
Decodes octets to characters using the UTF - 8 decoding and appends the characters to a StringBuffer .
6,915
public UserIdentity toUserIdentity ( ) { if ( _userIdentity == null ) { String [ ] roles = _roles . toArray ( new String [ _roles . size ( ) ] ) ; _userIdentity = new DefaultUserIdentity ( new javax . security . auth . Subject ( true , ImmutableSet . of ( this ) , ImmutableSet . of ( ) , ImmutableSet . of ( ) ) , new B...
Returns this instance as a Jetty UserIdentity . The returned instance is immutable and cached .
6,916
private void reopenS3InputStream ( ) throws IOException { try { closeS3InputStream ( ) ; } catch ( IOException ignore ) { } InputStream remainingIn = null ; int attempt = 0 ; while ( remainingIn == null ) { try { S3Object s3Object = _s3 . getObject ( new GetObjectRequest ( _bucket , _key ) . withRange ( _pos , _length ...
Re - opens the input stream starting at the first unread byte .
6,917
Delta newDropTable ( ) { Delta storageDelta = Deltas . mapBuilder ( ) . put ( StorageState . DROPPED . getMarkerAttribute ( ) . key ( ) , now ( ) ) . build ( ) ; MapDeltaBuilder storageMapDelta = Deltas . mapBuilder ( ) ; if ( _master != null ) { for ( Storage storage : _master . getPrimaryAndMirrors ( ) ) { storageMap...
Mark an entire table as dropped . A maintenance job will come along later and actually purge the data .
6,918
Delta newDropFacade ( Storage facade ) { Delta storageDelta = Deltas . mapBuilder ( ) . put ( StorageState . DROPPED . getMarkerAttribute ( ) . key ( ) , now ( ) ) . build ( ) ; MapDeltaBuilder storageMapDelta = Deltas . mapBuilder ( ) ; for ( Storage storage : facade . getPrimaryAndMirrors ( ) ) { storageMapDelta . up...
Mark a facade as dropped . A maintenance job will come along later and actually purge the data .
6,919
Delta newMoveStart ( Storage src , String destUuid , String destPlacement , int destShardsLog2 ) { return Deltas . mapBuilder ( ) . update ( STORAGE . key ( ) , Deltas . mapBuilder ( ) . update ( src . getUuidString ( ) , Deltas . mapBuilder ( ) . put ( Storage . MOVE_TO . key ( ) , destUuid ) . build ( ) ) . put ( des...
First step in a move creates the destination storage and sets up mirroring .
6,920
Delta newMoveRestart ( Storage src , Storage dest ) { Delta consistentMarker = dest . isConsistent ( ) ? Deltas . conditional ( Conditions . isUndefined ( ) , Deltas . literal ( now ( ) ) ) : Deltas . noop ( ) ; return Deltas . mapBuilder ( ) . update ( STORAGE . key ( ) , Deltas . mapBuilder ( ) . update ( src . getUu...
Start a move to an existing mirror that may or may not have once been primary .
6,921
public Iterable < StashTable > listStashTables ( ) throws StashNotAvailableException { final StashReader stashReader = _stashReader . getLockedView ( ) ; return new Iterable < StashTable > ( ) { public Iterator < StashTable > iterator ( ) { return stashReader . listTables ( ) ; } } ; }
Lists all tables present in Stash . Note that tables that were present in EmoDB but empty during the Stash operation are not listed .
6,922
public StashRowIterable scan ( final String table ) throws StashNotAvailableException , TableNotStashedException { try { final StashReader stashReader = _stashReader . getLockedView ( ) ; return new StashRowIterable ( ) { protected StashRowIterator createStashRowIterator ( ) { return stashReader . scan ( table ) ; } } ...
Scans all rows from Stash for the given table .
6,923
public Collection < String > getSplits ( String table ) throws StashNotAvailableException , TableNotStashedException { try { return FluentIterable . from ( _stashReader . getSplits ( table ) ) . transform ( Functions . toStringFunction ( ) ) . toList ( ) ; } catch ( TableNotStashedException e ) { throw propagateTableNo...
Gets the splits from Stash for the given table .
6,924
private RuntimeException propagateTableNotStashed ( TableNotStashedException e ) throws TableNotStashedException , UnknownTableException { if ( _dataStore . getTableExists ( e . getTable ( ) ) ) { throw e ; } throw new UnknownTableException ( e . getTable ( ) ) ; }
If a table exists but is empty then it will not be stashed . This method will surface this exception only if the table exists . Otherwise it converts it to an UnknownTableException .
6,925
public static boolean isLegalRoleName ( String role ) { return role != null && role . length ( ) > 0 && role . length ( ) <= 255 && ROLE_NAME_ALLOWED . matchesAllOf ( role ) ; }
Role names mostly follow the same conventions as table names except since they are only used internally are slightly more permissive such as allowing capital letters .
6,926
public void verifyOrCreateReport ( String reportId ) { checkNotNull ( reportId , "reportId" ) ; String tableName = getTableName ( reportId ) ; if ( _dataStore . getTableExists ( tableName ) ) { return ; } try { _dataStore . createTable ( tableName , new TableOptionsBuilder ( ) . setPlacement ( _systemTablePlacement ) ....
Verifies that the given report table exists or if not creates it .
6,927
public void updateReport ( AllTablesReportDelta delta ) { checkNotNull ( delta , "delta" ) ; updateMetadata ( delta ) ; if ( delta . getTable ( ) . isPresent ( ) ) { updateTableData ( delta , delta . getTable ( ) . get ( ) ) ; } }
Updates the metadata associated with the report .
6,928
public TableReportMetadata getReportMetadata ( String reportId ) { checkNotNull ( reportId , "reportId" ) ; final String reportTable = getTableName ( reportId ) ; Map < String , Object > metadata ; try { metadata = _dataStore . get ( reportTable , REPORT_METADATA_KEY ) ; } catch ( UnknownTableException e ) { throw new ...
Returns the table data for a given report . The caller can optionally return a partial report with ony the requested tables .
6,929
public Iterable < TableReportEntry > getReportEntries ( String reportId , final AllTablesReportQuery query ) { checkNotNull ( reportId , "reportId" ) ; final String reportTable = getTableName ( reportId ) ; final Predicate < String > placementFilter = query . getPlacements ( ) . isEmpty ( ) ? Predicates . < String > al...
Returns the matching table report entries for a report ID and query parameters .
6,930
private Iterator < Map < String , Object > > queryDataStoreForTableReportResults ( final String reportTable , final AllTablesReportQuery query ) { if ( ! query . getTableNames ( ) . isEmpty ( ) ) { return Iterators . concat ( Iterators . transform ( query . getTableNames ( ) . iterator ( ) , new Function < String , Map...
Returns an iterator of report results based on the query configuration . The results are guaranteed to be a superset of results matching the original query ; further filtering may be required to exactly match the query .
6,931
private TableReportEntry convertToTableReportEntry ( Map < String , Object > map , Predicate < String > placementFilter , Predicate < Boolean > droppedFilter , Predicate < Boolean > facadeFilter ) { if ( Intrinsic . isDeleted ( map ) ) { return null ; } final String tableName = Intrinsic . getId ( map ) ; List < TableR...
Accepts a row from the table report and returns it converted into a TableReportEntry . If the row is deleted or if it doesn t match all of the configured filters then null is returned .
6,932
private TableReportEntryTable convertToTableReportEntryTable ( String tableId , Map < String , Object > map , Predicate < String > placementFilter , Predicate < Boolean > droppedFilter , Predicate < Boolean > facadeFilter ) { String placement = ( String ) map . get ( "placement" ) ; if ( ! placementFilter . apply ( pla...
Accepts the table portion of a table report entry and converts it to a TableReportEntryTable . If the entry doesn t match all of the configured filters then null is returned .
6,933
@ JsonView ( EventViews . ContentOnly . class ) @ JsonProperty ( "content" ) private Map < String , Object > getJsonSerializingContent ( ) { return ( Map < String , Object > ) _content ; }
For purposes of JSON serialization wrapping the content in an unmodifiable view may cause the serializer to choose a less - optimal implementation . Since JSON serialization cannot modify the underlying content it is safe to return the original content object to the serializer .
6,934
private BlockedDelta reverseCompute ( ) { int contentSize = getValue ( _next ) . remaining ( ) ; UUID correctChangeId = getChangeId ( _next ) ; int numBlocks = 1 ; if ( _list == null ) { _list = Lists . newArrayListWithCapacity ( 3 ) ; } _list . add ( _next ) ; _oldDelta = _next ; while ( _iterator . hasNext ( ) && get...
stitch delta together in reverse
6,935
private BlockedDelta compute ( int numBlocks ) { int contentSize = getValue ( _next ) . remaining ( ) ; _oldDelta = _next ; UUID changeId = getChangeId ( _next ) ; if ( _list == null ) { _list = Lists . newArrayListWithCapacity ( numBlocks ) ; } _list . add ( _next ) ; for ( int i = 1 ; i < numBlocks ; i ++ ) { if ( _i...
stitch delta together and return it as one bytebuffer
6,936
private int skipForward ( ) { int numSkips = 0 ; _next = null ; while ( _iterator . hasNext ( ) && getBlock ( _next = _iterator . next ( ) ) != 0 ) { numSkips ++ ; _next = null ; } return numSkips ; }
This handles the edge case in which a client has explicity specified a changeId when writing and overwrote an exisiting delta .
6,937
private int getNumBlocks ( R delta ) { ByteBuffer content = getValue ( delta ) ; int numBlocks = 0 ; for ( int i = 0 ; i < _prefixLength ; i ++ ) { byte b = content . get ( i ) ; numBlocks = numBlocks << 4 | ( b <= '9' ? b - '0' : b - 'A' + 10 ) ; } return numBlocks ; }
converts utf - 8 encoded hex to int by building it digit by digit .
6,938
private ReplicationSource newRemoteReplicationSource ( DataCenter dataCenter ) { MultiThreadedServiceFactory < ReplicationSource > clientFactory = new ReplicationClientFactory ( _jerseyClient ) . usingApiKey ( _replicationApiKey ) ; ServiceEndPoint endPoint = new ServiceEndPointBuilder ( ) . withServiceName ( clientFac...
Creates a ReplicationSource proxy to the remote data center .
6,939
private void registerMetrics ( ) { if ( _metricName == null ) { return ; } Metrics metrics = _cluster . getMetrics ( ) ; _metricRegistry . register ( MetricRegistry . name ( "bv.emodb.cql" , _metricName , "ConnectionPool" , "connected-to-hosts" ) , metrics . getConnectedToHosts ( ) ) ; _metricRegistry . register ( Metr...
Registers metrics for this cluster . Ideally this would be done before the cluster is started so conflicting metric names could be detected earlier but since the CQL driver doesn t publish metrics until after it is initialized the metrics cannot be registered until then .
6,940
public static FileStatus getRootFileStatus ( Path rootPath ) { return new FileStatus ( 0 , true , 1 , 1024 , - 1 , - 1 , DIRECTORY_PERMISSION , null , null , rootPath ) ; }
Returns a FileStatus for the given root path .
6,941
public static FileStatus getTableFileStatus ( Path rootPath , String table ) { return new FileStatus ( 0 , true , 1 , 1024 , - 1 , - 1 , DIRECTORY_PERMISSION , null , null , getTablePath ( rootPath , table ) ) ; }
Returns a FileStatus for a table .
6,942
public static FileStatus getSplitFileStatus ( Path rootPath , String table , String split , long size , int blockSize ) { return new FileStatus ( size , false , 1 , blockSize , - 1 , - 1 , FILE_PERMISSION , null , null , getSplitPath ( rootPath , table , split ) ) ; }
Returns a FileStatus for a split .
6,943
public static String getTableName ( Path rootPath , Path path ) { path = qualified ( rootPath , path ) ; if ( rootPath . equals ( path ) ) { return null ; } Path tablePath ; Path parent = path . getParent ( ) ; if ( Objects . equals ( parent , rootPath ) ) { tablePath = path ; } else if ( parent != null && Objects . eq...
Gets the table name from a path or null if the path is the root path .
6,944
private static Path qualified ( Path rootPath , Path path ) { URI rootUri = rootPath . toUri ( ) ; return path . makeQualified ( rootUri , new Path ( rootUri . getPath ( ) ) ) ; }
Qualifies a path so it includes the schema and authority from the root path .
6,945
public static Path getTablePath ( Path rootPath , String table ) { return new Path ( rootPath , encode ( table ) ) ; }
Gets the path for a table from the given root .
6,946
public static Path getSplitPath ( Path rootPath , String table , String split ) { return new Path ( getTablePath ( rootPath , table ) , encode ( split ) ) ; }
Gets the path for a split from the given root .
6,947
private static String encode ( String pathElement ) { try { return URLEncoder . encode ( pathElement , Charsets . UTF_8 . name ( ) ) ; } catch ( UnsupportedEncodingException e ) { throw Throwables . propagate ( e ) ; } }
URL encodes a path element
6,948
private static String decode ( String pathElement ) { try { return URLDecoder . decode ( pathElement , Charsets . UTF_8 . name ( ) ) ; } catch ( UnsupportedEncodingException e ) { throw Throwables . propagate ( e ) ; } }
URL decodes a path element
6,949
public Collection < String > getLocalPlacements ( ) { List < String > placements = Lists . newArrayList ( ) ; for ( String placementName : _placementFactory . getValidPlacements ( ) ) { Placement placement ; try { placement = get ( placementName ) ; } catch ( UnknownPlacementException e ) { continue ; } placements . ad...
Returns all placements accessible in the local data center including internal placements .
6,950
private < Q , R > void recordFinalStatus ( JobIdentifier < Q , R > jobId , JobStatus < Q , R > jobStatus ) { try { _jobStatusDAO . updateJobStatus ( jobId , jobStatus ) ; } catch ( Exception e ) { _log . error ( "Failed to record final status for job: [id={}, status={}]" , jobId , jobStatus . getStatus ( ) , e ) ; } }
Attempts to record the final status for a job . Logs any errors but always returns without throwing an exception .
6,951
private void acknowledgeQueueMessage ( String messageId ) { try { _queueService . acknowledge ( _queueName , ImmutableList . of ( messageId ) ) ; } catch ( Exception e ) { _log . error ( "Failed to acknowledge message: [messageId={}]" , messageId , e ) ; } }
Attempts to acknowledge a message on the queue . Logs any errors but always returns without throwing an exception .
6,952
private String encode ( String str ) { if ( str == null ) { return null ; } try { return URLEncoder . encode ( str , Charsets . UTF_8 . name ( ) ) ; } catch ( UnsupportedEncodingException e ) { throw Throwables . propagate ( e ) ; } }
URL encodes the given string .
6,953
private String getTable ( ) { if ( ! _tableChecked ) { if ( ! _dataStore . getTableExists ( _tableName ) ) { _dataStore . createTable ( _tableName , new TableOptionsBuilder ( ) . setPlacement ( _tablePlacement ) . build ( ) , ImmutableMap . < String , Object > of ( ) , new AuditBuilder ( ) . setLocalHost ( ) . setComme...
Returns the scan status table name . On the first call it also verifies that the table exists then skips this check on future calls .
6,954
private Date extrapolateStartTimeFromScanRanges ( List < ScanRangeStatus > pendingScanRanges , List < ScanRangeStatus > activeScanRanges , List < ScanRangeStatus > completeScanRanges ) { Date startTime = null ; for ( ScanRangeStatus status : Iterables . concat ( pendingScanRanges , activeScanRanges , completeScanRanges...
For grandfathered in ScanStatuses that did not include a startTime attribute extrapolate it as the earliest time a scan range was queued .
6,955
private static int computeChecksum ( byte [ ] buf , int offset , int length , String channel ) { Hasher hasher = Hashing . murmur3_32 ( ) . newHasher ( ) ; hasher . putBytes ( buf , offset , length ) ; hasher . putUnencodedChars ( channel ) ; return hasher . hash ( ) . asInt ( ) & 0xffff ; }
Computes a 16 - bit checksum of the contents of the specific ByteBuffer and channel name .
6,956
private boolean ownerCanReadTable ( String ownerId , String table ) { return _internalAuthorizer . hasPermissionById ( ownerId , getReadPermission ( table ) ) ; }
Determines if an owner has read permission on a table . This always calls back to the authorizer and will not return a cached value .
6,957
private Permission getReadPermission ( String table ) { return _readPermissionCache != null ? _readPermissionCache . getUnchecked ( table ) : createReadPermission ( table ) ; }
Gets the Permission instance for read permission on a table . If caching is enabled the result is either returned from or added to the cache .
6,958
private Permission createReadPermission ( String table ) { return _permissionResolver . resolvePermission ( Permissions . readSorTable ( new NamedResource ( table ) ) ) ; }
Creates a Permission instance for read permission on a table . This always resolves a new instance and will not return a cached value .
6,959
private String splitNameWithoutGzipExtension ( String split ) throws IOException { if ( split == null ) { throw new IOException ( "Path is not a split" ) ; } if ( split . endsWith ( ".gz" ) ) { return split . substring ( 0 , split . length ( ) - 3 ) ; } return split ; }
Since we appended a gzip extension to the split file name we need to take it off to get the actual split .
6,960
public FSDataInputStream open ( Path path , int bufferSize ) throws IOException { String table = getTableName ( _rootPath , path ) ; String split = getSplitName ( _rootPath , path ) ; split = splitNameWithoutGzipExtension ( split ) ; return new FSDataInputStream ( new EmoSplitInputStream ( table , split ) ) ; }
Opens a split for reading . Note that the preferred and more efficient way to do this is by using an EmoInputFormat . However if using a MapReduce framework which does not support custom input formats such as Presto the splits can be opened directly using this method .
6,961
public FSDataOutputStream create ( Path f , FsPermission permission , boolean overwrite , int bufferSize , short replication , long blockSize , Progressable progress ) throws IOException { throw new IOException ( "Create not supported for EmoFileSystem: " + f ) ; }
All remaining FileSystem operations are not supported and will throw exceptions .
6,962
private EmoClientException asEmoClientException ( UniformInterfaceException e ) throws EmoClientException { throw new EmoClientException ( e . getMessage ( ) , e , toEmoResponse ( e . getResponse ( ) ) ) ; }
Returns an EmoClientException with a thin wrapper around the Jersey exception response .
6,963
private boolean loadNextBatch ( ) { if ( ! hasNextBatch ( ) ) { _batch = Iterators . emptyIterator ( ) ; return true ; } Exception batchFetchException = null ; _timer . start ( ) ; try { _batch = nextBatch ( _currentBatchSize ) ; } catch ( Exception e ) { batchFetchException = e ; } finally { _timer . stop ( ) ; } long...
Loads the next batch from the underlying resource .
6,964
private void prepareClosedLogFilesForTransfer ( ) { for ( final File logFile : _stagingDir . listFiles ( ( dir , name ) -> name . startsWith ( _logFilePrefix ) && name . endsWith ( CLOSED_FILE_SUFFIX ) ) ) { boolean moved ; String fileName = logFile . getName ( ) . substring ( 0 , logFile . getName ( ) . length ( ) - C...
This method takes all closed log files and GZIPs and renames them in preparation for transfer . If the operation fails the original file is unmodified so the next call should attempt to prepare the file again . This means the same file may be transferred more than once but this guarantees that so long as the host remai...
6,965
private void processQueuedAudits ( boolean interruptable ) { QueuedAudit audit ; try { while ( ! ( _auditService . isShutdown ( ) && interruptable ) && ( ( audit = _auditQueue . poll ( ) ) != null ) ) { boolean written = false ; while ( ! written ) { AuditOutput auditOutput = getAuditOutputForTime ( audit . time ) ; wr...
This method is run at regular intervals to remove audits from the audit queue and write them to a local file .
6,966
private CacheManager prepareCacheManager ( CacheManager cacheManager ) { if ( cacheManager == null || ! ( cacheManager instanceof InvalidatableCacheManager ) ) { return cacheManager ; } return new ValidatingCacheManager ( cacheManager ) { protected CacheValidator < ? , ? > getCacheValidatorForCache ( String name ) { St...
If necessary wraps the raw cache manager with a validating facade .
6,967
public boolean supports ( AuthenticationToken token ) { return super . supports ( token ) || ( _anonymousId != null && AnonymousToken . isAnonymous ( token ) ) ; }
Override the parent method to also accept anonymous tokens
6,968
@ SuppressWarnings ( "unchecked" ) protected AuthenticationInfo doGetAuthenticationInfo ( AuthenticationToken token ) throws AuthenticationException { String id ; if ( AnonymousToken . isAnonymous ( token ) ) { if ( _anonymousId != null ) { id = _anonymousId ; } else { return null ; } } else { id = ( ( ApiKeyAuthentica...
Gets the AuthenticationInfo that matches a token . This method is only called if the info is not already cached by the realm so this method does not need to perform any further caching .
6,969
private ApiKeyAuthenticationInfo createAuthenticationInfo ( String authenticationId , ApiKey apiKey ) { return new ApiKeyAuthenticationInfo ( authenticationId , apiKey , getName ( ) ) ; }
Simple method to build and AuthenticationInfo instance from an API key .
6,970
protected AuthorizationInfo doGetAuthorizationInfo ( PrincipalCollection principals ) { AuthorizationInfo authorizationInfo = getUncachedAuthorizationInfoFromPrincipals ( principals ) ; Cache < String , AuthorizationInfo > idAuthorizationCache = getAvailableIdAuthorizationCache ( ) ; if ( idAuthorizationCache != null )...
Gets the AuthorizationInfo that matches a token . This method is only called if the info is not already cached by the realm so this method does not need to perform any further caching .
6,971
protected Collection < Permission > getRolePermissions ( String role ) { if ( role == null ) { return null ; } Cache < String , RolePermissionSet > cache = getAvailableRolesCache ( ) ; if ( cache == null ) { return _permissionReader . getPermissions ( PermissionIDs . forRole ( role ) ) ; } RolePermissionSet rolePermiss...
Gets the permissions for a role . If possible the permissions are cached for efficiency .
6,972
private AuthorizationInfo getAuthorizationInfoById ( String id ) { AuthorizationInfo authorizationInfo ; Cache < String , AuthorizationInfo > idAuthorizationCache = getAvailableIdAuthorizationCache ( ) ; if ( idAuthorizationCache != null ) { authorizationInfo = idAuthorizationCache . get ( id ) ; if ( authorizationInfo...
Gets the authorization info for a user by their ID . If possible the value is cached for efficient lookup .
6,973
private void cacheAuthorizationInfoById ( String id , AuthorizationInfo authorizationInfo ) { Cache < String , AuthorizationInfo > idAuthorizationCache = getAvailableIdAuthorizationCache ( ) ; if ( idAuthorizationCache != null ) { idAuthorizationCache . put ( id , authorizationInfo ) ; } }
If possible this method caches the authorization info for an API key by its ID . This may be called either by an explicit call to get the authorization info by ID or as a side effect of loading the authorization info by API key and proactive caching by ID .
6,974
public char nextClean ( char c ) { char n = nextClean ( ) ; if ( n != c ) { throw syntaxError ( "Expected '" + c + "' and instead saw '" + n + "'" ) ; } return n ; }
Consume the next character skipping whitespace and check that it matches a specified character .
6,975
public String nextString ( ) { nextClean ( '"' ) ; StringBuilder sb = new StringBuilder ( ) ; for ( ; ; ) { char c = next ( ) ; switch ( c ) { case 0 : case '\n' : case '\r' : throw syntaxError ( "Unterminated string" ) ; case '\\' : c = next ( ) ; switch ( c ) { case 'b' : sb . append ( '\b' ) ; break ; case 't' : sb ...
Return the characters up to the next close quote character . Backslash processing is done . The formal JSON format does not allow strings in single quotes but an implementation is allowed to accept them .
6,976
public Object nextValue ( ) { char c = lookAhead ( ) ; switch ( c ) { case '"' : return nextString ( ) ; case '{' : return nextObject ( ) ; case '[' : return nextArray ( ) ; } String s = nextToken ( ) ; return tokenToValue ( s ) ; }
Get the next value . The value can be a Boolean Double Integer List Map Long or String or null .
6,977
public static long getVersionRetroactively ( PendingCompaction pendingCompaction ) { Compaction compaction = pendingCompaction . getCompaction ( ) ; return compaction . getCount ( ) - ( long ) pendingCompaction . getDeltasToArchive ( ) . size ( ) ; }
Find the version of the first delta of a pending compaction retroactively
6,978
public static Iterable < Table > listTables ( DataStore dataStore ) { return listTables ( dataStore , null , Long . MAX_VALUE ) ; }
Retrieves metadata about all DataStore tables .
6,979
public static Iterable < Map < String , Object > > scan ( DataStore dataStore , String table , boolean includeDeletes , ReadConsistency consistency ) { return scan ( dataStore , table , null , Long . MAX_VALUE , includeDeletes , consistency ) ; }
Retrieves all records from the specified table .
6,980
public static void updateAll ( DataStore dataStore , Iterable < Update > updates ) { updateAll ( dataStore , updates . iterator ( ) , ImmutableSet . < String > of ( ) ) ; }
Creates updates or deletes zero or more pieces of content in the data store .
6,981
public static void updateAll ( DataStore dataStore , Iterable < Update > updates , Set < String > tags ) { updateAll ( dataStore , updates . iterator ( ) , tags ) ; }
Creates updates or deletes zero or more pieces of content in the data store . You can attach a set of databus event tags for these updates
6,982
public Iterator < EmoRole > getAllRoles ( final Subject subject ) { return _uac . getAllRoles ( subject ) ; }
Returns all roles for which the caller has read access . Since the number of roles is typically low this call does not support from or limit parameters similar to the system or record .
6,983
@ Path ( "{group}" ) public Iterator < EmoRole > getAllRolesInGroup ( @ PathParam ( "group" ) String group , final Subject subject ) { return _uac . getAllRolesInGroup ( subject , group ) ; }
Returns all roles in the specified group for which the caller has read access . Since the number of roles is typically low this call does not support from or limit parameters similar to the system or record .
6,984
@ Path ( "{group}/{id}" ) public EmoRole getRole ( @ PathParam ( "group" ) String group , @ PathParam ( "id" ) String id , final Subject subject ) { return _uac . getRole ( subject , new EmoRoleKey ( group , id ) ) ; }
RESTful endpoint for viewing a role .
6,985
@ Path ( "{group}/{id}" ) @ Consumes ( MediaType . APPLICATION_JSON ) public Response createRole ( @ PathParam ( "group" ) String group , @ PathParam ( "id" ) String id , EmoRole role , final Subject subject ) { checkArgument ( role . getId ( ) . equals ( new EmoRoleKey ( group , id ) ) , "Body contains conflicting rol...
RESTful endpoint for creating a role .
6,986
@ Path ( "{group}/{id}" ) @ Consumes ( MediaType . APPLICATION_JSON ) public SuccessResponse updateRole ( @ PathParam ( "group" ) String group , @ PathParam ( "id" ) String id , EmoRole role , final Subject subject ) { checkArgument ( role . getId ( ) . equals ( new EmoRoleKey ( group , id ) ) , "Body contains conflict...
RESTful endpoint for updating a role . Note that all attributes of the role will be updated to match the provided object .
6,987
@ Path ( "{group}/{id}" ) public SuccessResponse deleteRole ( @ PathParam ( "group" ) String group , @ PathParam ( "id" ) String id , final Subject subject ) { _uac . deleteRole ( subject , new EmoRoleKey ( group , id ) ) ; return SuccessResponse . instance ( ) ; }
RESTful endpoint for deleting a role .
6,988
private Iterator < Column < ByteBuffer > > readManifestForChannel ( final String channel , final boolean weak ) { final ByteBuffer oldestSlab = weak ? _oldestSlab . getIfPresent ( channel ) : null ; final ConsistencyLevel consistency ; RangeBuilder range = new RangeBuilder ( ) . setLimit ( 50 ) ; if ( oldestSlab != nul...
Reads the ordered manifest for a channel . The read can either be weak or strong . A weak read will use CL1 and may use the cached oldest slab from a previous strong call to improve performance . A strong read will use CL local_quorum and will always read the entire manifest row . This makes a weak read significantly f...
6,989
private boolean readSlab ( String channel , ByteBuffer slabId , SlabCursor cursor , boolean open , EventSink sink ) { int start = cursor . get ( ) ; if ( start == SlabCursor . END ) { return true ; } boolean recent = isRecent ( slabId ) ; ColumnList < Integer > eventColumns = execute ( _keyspace . prepareQuery ( Column...
Returns true to keep searching for more events false to stop searching for events .
6,990
public ScanRangeSplits combineGroups ( ) { return new ScanRangeSplits ( ImmutableList . of ( new SplitGroup ( FluentIterable . from ( _splitGroups ) . transformAndConcat ( new Function < SplitGroup , Iterable < TokenRange > > ( ) { public Iterable < TokenRange > apply ( SplitGroup splitGroup ) { return splitGroup . get...
Returns a new ScanRangeSplits where all of the token ranges from all groups are combined into a single group . This is useful when the caller is going to perform an operation on all token ranges and is not concerned about creating hot spots .
6,991
public static byte [ ] asByteArray ( UUID uuid ) { long msb = uuid . getMostSignificantBits ( ) ; long lsb = uuid . getLeastSignificantBits ( ) ; byte [ ] buf = new byte [ 16 ] ; for ( int i = 0 ; i < 8 ; i ++ ) { buf [ i ] = ( byte ) ( msb >>> 8 * ( 7 - i ) ) ; buf [ i + 8 ] = ( byte ) ( lsb >>> 8 * ( 7 - i ) ) ; } re...
Returns the byte - array equivalent of the specified UUID in big - endian order .
6,992
private void closeShardFiles ( ShardFiles shardFiles ) { shardFiles . deleteAllShardFiles ( ) ; _lock . lock ( ) ; try { _openShardFiles . remove ( shardFiles . getKey ( ) ) ; _shardFilesClosedOrExceptionCaught . signalAll ( ) ; } finally { _lock . unlock ( ) ; } }
Cleans up any files associated with the ShardFiles instance and removes it from then open set of ShardFiles .
6,993
private void transferComplete ( ShardFiles shardFiles ) { _log . debug ( "Transfer complete: id={}, file={}" , _taskId , shardFiles . getFirstFile ( ) ) ; closeShardFiles ( shardFiles ) ; _openTransfers . dec ( ) ; }
Called when a shard file has been transferred successfully or otherwise . This also closes the ShardFiles .
6,994
public Map < String , Object > asJson ( ) { return ImmutableMap . < String , Object > of ( Intrinsic . TABLE , _table , Intrinsic . ID , _id ) ; }
Returns a Json map with two entries one for ~table and one for ~id similar to all System of Record objects .
6,995
static String encode ( List < String > eventIds ) { checkArgument ( ! eventIds . isEmpty ( ) , "Empty event ID list." ) ; if ( eventIds . size ( ) == 1 ) { return checkValid ( eventIds . get ( 0 ) ) ; } StringBuilder buf = new StringBuilder ( ) ; String prevId = null ; for ( String eventId : eventIds ) { checkValid ( e...
Combine multiple EventStore event IDs into a single Databus event key . To get the most compact encoded string sort the event ID list before encoding it .
6,996
static List < String > decodeAll ( Collection < String > eventKeys ) { List < String > eventIds = Lists . newArrayList ( ) ; for ( String eventKey : eventKeys ) { decodeTo ( eventKey , eventIds ) ; } return eventIds ; }
Split Databus event keys into EventStore event IDs .
6,997
static void decodeTo ( String eventKey , Collection < String > eventIds ) { int startIdx = 0 ; String prevId = null ; for ( int i = 0 ; i < eventKey . length ( ) ; i ++ ) { char ch = eventKey . charAt ( i ) ; if ( ch == DELIM_REGULAR || ch == DELIM_SHARED_PREFIX ) { String eventId = checkValid ( combine ( prevId , even...
Split a Databus event key into EventStore event IDs .
6,998
public boolean setNextKeyValue ( Text key , Row value ) throws IOException { if ( ! _rows . hasNext ( ) ) { Closeables . close ( this , true ) ; return false ; } try { Map < String , Object > content = _rows . next ( ) ; key . set ( Coordinate . fromJson ( content ) . toString ( ) ) ; value . set ( content ) ; _rowsRea...
Read the next row from the split storing the coordinate in key and the content in value . If there are no more rows then false is returned and key and value are not modified .
6,999
public float getProgress ( ) throws IOException { if ( ! _rows . hasNext ( ) ) { return 1 ; } else if ( _rowsRead < _approximateSize ) { return ( float ) _rowsRead / _approximateSize ; } else { return ( ( float ) ( _approximateSize - 1 ) + 0.5f ) / _approximateSize ; } }
Returns a rough approximate of the progress on a scale from 0 to 1