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 ; protected StashTable computeNext ( ) { String dir = null ; while ( dir == null ) { if ( _commonPrefixes . hasNext ( ) ) { dir = _commonPrefixes . next ( ) ; if ( dir . isEmpty ( ) ) { dir = null ; } else { dir = dir . substring ( prefix . length ( ) , dir . length ( ) - 1 ) ; } } else if ( _truncated ) { ObjectListing response = _s3 . listObjects ( new ListObjectsRequest ( ) . withBucketName ( _bucket ) . withPrefix ( prefix ) . withDelimiter ( "/" ) . withMarker ( _marker ) . withMaxKeys ( 1000 ) ) ; _commonPrefixes = response . getCommonPrefixes ( ) . iterator ( ) ; _marker = response . getNextMarker ( ) ; _truncated = response . isTruncated ( ) ; } else { return endOfData ( ) ; } } String tablePrefix = prefix + dir + "/" ; String tableName = StashUtil . decodeStashTable ( dir ) ; return new StashTable ( _bucket , tablePrefix , tableName ) ; } } ; } | 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 . hasNext ( ) ) { S3ObjectSummary objectSummary = objectSummaries . next ( ) ; String key = objectSummary . getKey ( ) ; splitsBuilder . add ( new StashSplit ( table , key . substring ( _rootPath . length ( ) + 1 ) , objectSummary . getSize ( ) ) ) ; } return splitsBuilder . build ( ) ; } | 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 ( 2 ) . getName ( ) ; } | 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 ) ; bufferIndex = bufferIndexAndUuuids . left ; if ( bufferIndex == - 1 ) { blockIndex ++ ; lastBlock = new TableBlock ( blockIndex * _blockSize ) ; _blocks . add ( lastBlock ) ; } else { uuids = bufferIndexAndUuuids . right ; } } int index = toIndex ( blockIndex , bufferIndex ) ; for ( Long tableUuid : uuids ) { _fileIndexByUuid . put ( tableUuid , index ) ; } return index ; } | 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 ( eventAndChangeId . first ( ) ) ; } } _eventStore . renew ( subscription , eventIdsToUnclaim , Duration . ZERO , false ) ; } | 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 ) ) ) ; } else { segments . add ( new PathSegmentImpl ( segment , decode ) ) ; } } | 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 = pathSegment . indexOf ( ';' , s ) ; if ( e == - 1 ) { decodeMatrixParam ( matrixMap , pathSegment . substring ( s ) , decode ) ; } else if ( e > s ) { decodeMatrixParam ( matrixMap , pathSegment . substring ( s , e ) , decode ) ; } s = e + 1 ; } while ( s > 0 && s < pathSegment . length ( ) ) ; return matrixMap ; } | 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 ( ) * 3 - 1 ; } } | 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 BasicUserPrincipal ( getId ( ) ) , roles ) ; } return _userIdentity ; } | 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 - 1 ) ) ; remainingIn = s3Object . getObjectContent ( ) ; } catch ( AmazonClientException e ) { attempt += 1 ; if ( ! e . isRetryable ( ) || attempt == 4 ) { throw e ; } try { Thread . sleep ( 200 * attempt ) ; } catch ( InterruptedException interrupt ) { throw Throwables . propagate ( interrupt ) ; } } } _in = remainingIn ; } | 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 ( ) ) { storageMapDelta . update ( storage . getUuidString ( ) , storageDelta ) ; } } for ( Storage facade : _facades ) { for ( Storage storage : facade . getPrimaryAndMirrors ( ) ) { storageMapDelta . update ( storage . getUuidString ( ) , storageDelta ) ; } } return Deltas . mapBuilder ( ) . remove ( UUID_ATTR . key ( ) ) . remove ( ATTRIBUTES . key ( ) ) . update ( STORAGE . key ( ) , storageMapDelta . build ( ) ) . removeRest ( ) . build ( ) ; } | 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 . update ( storage . getUuidString ( ) , storageDelta ) ; } return Deltas . mapBuilder ( ) . update ( STORAGE . key ( ) , storageMapDelta . build ( ) ) . build ( ) ; } | 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 ( destUuid , storageAttributesBuilder ( destPlacement , destShardsLog2 , src . isFacade ( ) ) . put ( StorageState . MIRROR_CREATED . getMarkerAttribute ( ) . key ( ) , now ( ) ) . put ( Storage . GROUP_ID . key ( ) , src . getGroupId ( ) ) . build ( ) ) . build ( ) ) . build ( ) ; } | 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 . getUuidString ( ) , Deltas . mapBuilder ( ) . put ( Storage . MOVE_TO . key ( ) , dest . getUuidString ( ) ) . build ( ) ) . update ( dest . getUuidString ( ) , Deltas . mapBuilder ( ) . update ( StorageState . MIRROR_CONSISTENT . getMarkerAttribute ( ) . key ( ) , consistentMarker ) . remove ( Storage . MOVE_TO . key ( ) ) . remove ( Storage . PROMOTION_ID . key ( ) ) . remove ( StorageState . PRIMARY . getMarkerAttribute ( ) . key ( ) ) . remove ( StorageState . MIRROR_EXPIRING . getMarkerAttribute ( ) . key ( ) ) . remove ( StorageState . MIRROR_EXPIRED . getMarkerAttribute ( ) . key ( ) ) . build ( ) ) . build ( ) ) . build ( ) ; } | 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 ) ; } } ; } catch ( TableNotStashedException e ) { throw propagateTableNotStashed ( e ) ; } } | 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 propagateTableNotStashed ( e ) ; } } | 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 ) . build ( ) , ImmutableMap . < String , String > of ( ) , new AuditBuilder ( ) . setComment ( "create table" ) . build ( ) ) ; } catch ( TableExistsException e ) { } } | 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 ReportNotFoundException ( reportId ) ; } if ( Intrinsic . isDeleted ( metadata ) ) { throw new ReportNotFoundException ( reportId ) ; } Date startTime = JsonHelper . parseTimestamp ( ( String ) metadata . get ( "startTime" ) ) ; Date completeTime = null ; if ( metadata . containsKey ( "completeTime" ) ) { completeTime = JsonHelper . parseTimestamp ( ( String ) metadata . get ( "completeTime" ) ) ; } Boolean success = ( Boolean ) metadata . get ( "success" ) ; List < String > placements ; Object placementMap = metadata . get ( "placements" ) ; if ( placementMap != null ) { placements = ImmutableList . copyOf ( JsonHelper . convert ( placementMap , new TypeReference < Map < String , Object > > ( ) { } ) . keySet ( ) ) ; } else { placements = ImmutableList . of ( ) ; } return new TableReportMetadata ( reportId , startTime , completeTime , success , placements ) ; } | 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 > alwaysTrue ( ) : Predicates . in ( query . getPlacements ( ) ) ; final Predicate < Boolean > droppedFilter = query . isIncludeDropped ( ) ? Predicates . < Boolean > alwaysTrue ( ) : Predicates . equalTo ( false ) ; final Predicate < Boolean > facadeFilter = query . isIncludeFacades ( ) ? Predicates . < Boolean > alwaysTrue ( ) : Predicates . equalTo ( false ) ; return new Iterable < TableReportEntry > ( ) { public Iterator < TableReportEntry > iterator ( ) { return Iterators . limit ( Iterators . filter ( Iterators . transform ( queryDataStoreForTableReportResults ( reportTable , query ) , new Function < Map < String , Object > , TableReportEntry > ( ) { public TableReportEntry apply ( Map < String , Object > map ) { if ( Intrinsic . getId ( map ) . startsWith ( "~" ) ) { return null ; } return convertToTableReportEntry ( map , placementFilter , droppedFilter , facadeFilter ) ; } } ) , Predicates . notNull ( ) ) , query . getLimit ( ) ) ; } } ; } | 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 < String , Object > > ( ) { public Map < String , Object > apply ( String tableName ) { return _dataStore . get ( reportTable , tableName , ReadConsistency . STRONG ) ; } } ) ) ; } return new AbstractIterator < Map < String , Object > > ( ) { private String _from = query . getFromTable ( ) ; private Iterator < Map < String , Object > > _batch = Iterators . emptyIterator ( ) ; private long _limit = 0 ; protected Map < String , Object > computeNext ( ) { if ( ! _batch . hasNext ( ) ) { if ( _limit == 0 ) { _limit = query . getLimit ( ) ; } else { _limit = Long . MAX_VALUE ; } _batch = _dataStore . scan ( reportTable , _from , _limit , false , ReadConsistency . STRONG ) ; if ( ! _batch . hasNext ( ) ) { return endOfData ( ) ; } } Map < String , Object > result = _batch . next ( ) ; _from = Intrinsic . getId ( result ) ; return result ; } } ; } | 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 < TableReportEntryTable > tables = Lists . newArrayListWithExpectedSize ( map . size ( ) ) ; for ( Map . Entry < String , Object > entry : toMap ( map . get ( "tables" ) ) . entrySet ( ) ) { TableReportEntryTable entryTable = convertToTableReportEntryTable ( entry . getKey ( ) , toMap ( entry . getValue ( ) ) , placementFilter , droppedFilter , facadeFilter ) ; if ( entryTable != null ) { tables . add ( entryTable ) ; } } if ( tables . isEmpty ( ) ) { return null ; } return new TableReportEntry ( tableName , tables ) ; } | 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 ( placement ) ) { return null ; } Boolean dropped = Objects . firstNonNull ( ( Boolean ) map . get ( "dropped" ) , false ) ; if ( ! droppedFilter . apply ( dropped ) ) { return null ; } Boolean facade = Objects . firstNonNull ( ( Boolean ) map . get ( "facade" ) , false ) ; if ( ! facadeFilter . apply ( facade ) ) { return null ; } List < Integer > shards = Lists . newArrayList ( ) ; TableStatistics . Aggregator aggregator = TableStatistics . newAggregator ( ) ; Object shardJson = map . get ( "shards" ) ; if ( shardJson != null ) { Map < String , TableStatistics > shardMap = JsonHelper . convert ( shardJson , new TypeReference < Map < String , TableStatistics > > ( ) { } ) ; for ( Map . Entry < String , TableStatistics > entry : shardMap . entrySet ( ) ) { Integer shardId = Integer . parseInt ( entry . getKey ( ) ) ; shards . add ( shardId ) ; aggregator . add ( entry . getValue ( ) ) ; } } TableStatistics tableStatistics = aggregator . aggregate ( ) ; Collections . sort ( shards ) ; return new TableReportEntryTable ( tableId , placement , shards , dropped , facade , tableStatistics . getRecordCount ( ) , tableStatistics . getColumnStatistics ( ) . toStatistics ( ) , tableStatistics . getSizeStatistics ( ) . toStatistics ( ) , tableStatistics . getUpdateTimeStatistics ( ) . toStatistics ( ) ) ; } | 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 ( ) && getChangeId ( _next = _iterator . next ( ) ) . equals ( correctChangeId ) ) { numBlocks ++ ; _list . add ( _next ) ; contentSize += getValue ( _next ) . remaining ( ) ; _next = null ; } Collections . reverse ( _list ) ; if ( getBlock ( _list . get ( 0 ) ) != 0 ) { _list . clear ( ) ; return null ; } int expectedBlocks = getNumBlocks ( _list . get ( 0 ) ) ; while ( expectedBlocks != _list . size ( ) ) { contentSize -= getValue ( _list . remove ( _list . size ( ) - 1 ) ) . remaining ( ) ; } return new BlockedDelta ( numBlocks , stitchContent ( contentSize ) ) ; } | 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 ( _iterator . hasNext ( ) ) { _next = _iterator . next ( ) ; if ( getChangeId ( _next ) . equals ( changeId ) ) { _list . add ( _next ) ; contentSize += getValue ( _next ) . remaining ( ) ; } else { _list . clear ( ) ; return null ; } } else { throw new DeltaStitchingException ( _rowKey , getChangeId ( _next ) . toString ( ) , numBlocks , i - 1 ) ; } } numBlocks += skipForward ( ) ; return new BlockedDelta ( numBlocks , stitchContent ( contentSize ) ) ; } | 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 ( clientFactory . getServiceName ( ) ) . withId ( dataCenter . getName ( ) ) . withPayload ( new PayloadBuilder ( ) . withUrl ( dataCenter . getServiceUri ( ) . resolve ( ReplicationClient . SERVICE_PATH ) ) . withAdminUrl ( dataCenter . getAdminUri ( ) ) . toString ( ) ) . build ( ) ; return ServicePoolBuilder . create ( ReplicationSource . class ) . withHostDiscovery ( new FixedHostDiscovery ( endPoint ) ) . withServiceFactory ( clientFactory ) . withCachingPolicy ( ServiceCachingPolicyBuilder . getMultiThreadedClientPolicy ( ) ) . withHealthCheckExecutor ( _healthCheckExecutor ) . withMetricRegistry ( _metrics ) . buildProxy ( new ExponentialBackoffRetry ( 30 , 1 , 10 , TimeUnit . SECONDS ) ) ; } | 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 ( MetricRegistry . name ( "bv.emodb.cql" , _metricName , "ConnectionPool" , "open-connections" ) , metrics . getOpenConnections ( ) ) ; _metricRegistry . register ( MetricRegistry . name ( "bv.emodb.cql" , _metricName , "ConnectionPool" , "trashed-connections" ) , metrics . getTrashedConnections ( ) ) ; _metricRegistry . register ( MetricRegistry . name ( "bv.emodb.cql" , _metricName , "ConnectionPool" , "executor-queue-depth" ) , metrics . getExecutorQueueDepth ( ) ) ; _metricRegistry . register ( MetricRegistry . name ( "bv.emodb.cql" , _metricName , "ConnectionPool" , "blocking-executor-queue-depth" ) , metrics . getBlockingExecutorQueueDepth ( ) ) ; _metricRegistry . register ( MetricRegistry . name ( "bv.emodb.cql" , _metricName , "ConnectionPool" , "reconnection-scheduler-task-count" ) , metrics . getReconnectionSchedulerQueueSize ( ) ) ; _metricRegistry . register ( MetricRegistry . name ( "bv.emodb.cql" , _metricName , "ConnectionPool" , "task-scheduler-task-count" ) , metrics . getTaskSchedulerQueueSize ( ) ) ; _metricRegistry . register ( MetricRegistry . name ( "bv.emodb.cql" , _metricName , "ConnectionPool" , "connection-errors" ) , metrics . getErrorMetrics ( ) . getConnectionErrors ( ) ) ; _metricRegistry . register ( MetricRegistry . name ( "bv.emodb.cql" , _metricName , "ConnectionPool" , "read-timeouts" ) , metrics . getErrorMetrics ( ) . getReadTimeouts ( ) ) ; _metricRegistry . register ( MetricRegistry . name ( "bv.emodb.cql" , _metricName , "ConnectionPool" , "write-timeouts" ) , metrics . getErrorMetrics ( ) . getWriteTimeouts ( ) ) ; _metricRegistry . register ( MetricRegistry . name ( "bv.emodb.cql" , _metricName , "ConnectionPool" , "client-timeouts" ) , metrics . getErrorMetrics ( ) . getClientTimeouts ( ) ) ; _metricRegistry . register ( MetricRegistry . name ( "bv.emodb.cql" , _metricName , "ConnectionPool" , "ignores" ) , metrics . getErrorMetrics ( ) . getIgnores ( ) ) ; _metricRegistry . register ( MetricRegistry . name ( "bv.emodb.cql" , _metricName , "ConnectionPool" , "unavailables" ) , metrics . getErrorMetrics ( ) . getUnavailables ( ) ) ; _metricRegistry . register ( MetricRegistry . name ( "bv.emodb.cql" , _metricName , "ConnectionPool" , "speculative-executions" ) , metrics . getErrorMetrics ( ) . getSpeculativeExecutions ( ) ) ; } | 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 . equals ( parent . getParent ( ) , rootPath ) ) { tablePath = parent ; } else { throw new IllegalArgumentException ( format ( "Path does not represent a table, split, or root (path=%s, root=%s)" , path , rootPath ) ) ; } return decode ( tablePath . getName ( ) ) ; } | 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 . add ( placement . getName ( ) ) ; } return placements ; } | 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 ( ) . setComment ( "Create scan status table" ) . build ( ) ) ; _tableChecked = true ; } } return _tableName ; } | 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 ) ) { Date queuedTime = status . getScanQueuedTime ( ) ; if ( queuedTime != null && ( startTime == null || queuedTime . before ( startTime ) ) ) { startTime = queuedTime ; } } if ( startTime == null ) { startTime = new Date ( 0 ) ; } return startTime ; } | 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 batchFetchTime = _timer . elapsed ( TimeUnit . MILLISECONDS ) ; _timer . reset ( ) ; if ( batchFetchException != null ) { boolean isTimeout = isTimeoutException ( batchFetchException ) ; boolean isDataSize = ! isTimeout && isDataSizeException ( batchFetchException ) ; if ( ! ( isTimeout || isDataSize ) || _currentBatchSize == _minBatchSize ) { throw Throwables . propagate ( batchFetchException ) ; } _currentBatchSize = Math . max ( _currentBatchSize / 2 , _minBatchSize ) ; if ( isTimeout ) { _lastTimeoutTime = batchFetchTime ; } return false ; } int nextBatchSize = Math . min ( _currentBatchSize + _batchIncrementSize , _maxBatchSize ) ; if ( nextBatchSize != _currentBatchSize ) { if ( _lastTimeoutTime != 0 ) { float msPerRow = ( float ) batchFetchTime / _currentBatchSize ; int estimatedMaxBatchSizeUntilTimeout = ( int ) ( _lastTimeoutTime / msPerRow ) ; if ( estimatedMaxBatchSizeUntilTimeout > 0 && estimatedMaxBatchSizeUntilTimeout < nextBatchSize ) { nextBatchSize = estimatedMaxBatchSizeUntilTimeout ; } } _currentBatchSize = nextBatchSize ; } return _batch . hasNext ( ) ; } | 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 ( ) - CLOSED_FILE_SUFFIX . length ( ) ) + COMPRESSED_FILE_SUFFIX ; try ( FileInputStream fileIn = new FileInputStream ( logFile ) ; FileOutputStream fileOut = new FileOutputStream ( new File ( logFile . getParentFile ( ) , fileName ) ) ; GzipCompressorOutputStream gzipOut = new GzipCompressorOutputStream ( fileOut ) ) { ByteStreams . copy ( fileIn , gzipOut ) ; moved = true ; } catch ( IOException e ) { _log . warn ( "Failed to compress audit log file: {}" , logFile , e ) ; moved = false ; } if ( moved ) { if ( ! logFile . delete ( ) ) { _log . warn ( "Failed to delete audit log file: {}" , logFile ) ; } } } } | 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 remains active the file will eventually be transferred . |
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 ) ; written = auditOutput . writeAudit ( audit ) ; } } } catch ( Exception e ) { _log . error ( "Processing of queued audits failed" , e ) ; } } | 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 ) { String cacheName = getAuthenticationCacheName ( ) ; if ( cacheName != null && name . equals ( cacheName ) ) { return new ValidatingCacheManager . CacheValidator < Object , AuthenticationInfo > ( Object . class , AuthenticationInfo . class ) { public boolean isCurrentValue ( Object key , AuthenticationInfo value ) { String id ; if ( AnonymousToken . isAnonymousPrincipal ( key ) ) { if ( _anonymousId == null ) { return false ; } id = _anonymousId ; } else { id = ( String ) key ; } AuthenticationInfo authenticationInfo = getUncachedAuthenticationInfoForKey ( id ) ; return Objects . equal ( authenticationInfo , value ) ; } } ; } cacheName = getAuthorizationCacheName ( ) ; if ( cacheName != null && name . equals ( cacheName ) ) { return new ValidatingCacheManager . CacheValidator < Object , AuthorizationInfo > ( Object . class , AuthorizationInfo . class ) { public boolean isCurrentValue ( Object key , AuthorizationInfo value ) { PrincipalCollection principalCollection = ( PrincipalCollection ) key ; AuthorizationInfo authorizationInfo = getUncachedAuthorizationInfoFromPrincipals ( principalCollection ) ; return authorizationInfo != null && authorizationInfo . getRoles ( ) . equals ( value . getRoles ( ) ) ; } } ; } cacheName = getIdAuthorizationCacheName ( ) ; if ( cacheName != null && name . equals ( cacheName ) ) { return new ValidatingCacheManager . CacheValidator < String , AuthorizationInfo > ( String . class , AuthorizationInfo . class ) { public boolean isCurrentValue ( String key , AuthorizationInfo value ) { AuthorizationInfo authorizationInfo = getUncachedAuthorizationInfoById ( key ) ; return authorizationInfo != null && authorizationInfo . getRoles ( ) . equals ( value . getRoles ( ) ) ; } } ; } cacheName = getRolesCacheName ( ) ; if ( cacheName != null && name . equals ( cacheName ) ) { return new ValidatingCacheManager . CacheValidator < String , RolePermissionSet > ( String . class , RolePermissionSet . class ) { public boolean isCurrentValue ( String key , RolePermissionSet value ) { Set < Permission > currentPermissions = _permissionReader . getPermissions ( PermissionIDs . forRole ( key ) ) ; return value . permissions ( ) . equals ( currentPermissions ) ; } } ; } return null ; } } ; } | 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 = ( ( ApiKeyAuthenticationToken ) token ) . getPrincipal ( ) ; } return getUncachedAuthenticationInfoForKey ( id ) ; } | 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 ) { for ( PrincipalWithRoles principal : getPrincipalsFromPrincipalCollection ( principals ) ) { if ( idAuthorizationCache . get ( principal . getId ( ) ) == null ) { cacheAuthorizationInfoById ( principal . getId ( ) , authorizationInfo ) ; } } } return authorizationInfo ; } | 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 rolePermissionSet = cache . get ( role ) ; if ( rolePermissionSet == null ) { Set < Permission > permissions = _permissionReader . getPermissions ( PermissionIDs . forRole ( role ) ) ; rolePermissionSet = new SimpleRolePermissionSet ( permissions ) ; cache . put ( role , rolePermissionSet ) ; } return rolePermissionSet . permissions ( ) ; } | 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 != null ) { if ( authorizationInfo != _nullAuthorizationInfo ) { _log . debug ( "Authorization info found cached for id {}" , id ) ; return authorizationInfo ; } else { _log . debug ( "Authorization info previously cached as not found for id {}" , id ) ; return null ; } } } authorizationInfo = getUncachedAuthorizationInfoById ( id ) ; cacheAuthorizationInfoById ( id , authorizationInfo ) ; return 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 . append ( '\t' ) ; break ; case 'n' : sb . append ( '\n' ) ; break ; case 'f' : sb . append ( '\f' ) ; break ; case 'r' : sb . append ( '\r' ) ; break ; case 'u' : sb . append ( ( char ) Integer . parseInt ( next ( 4 ) , 16 ) ) ; break ; default : sb . append ( c ) ; } break ; case '"' : return sb . toString ( ) ; default : if ( c < ' ' ) { throw syntaxError ( "Unescaped control character (ascii " + ( ( int ) c ) + ") in string" ) ; } sb . append ( c ) ; break ; } } } | 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 role identifier" ) ; return createRoleFromUpdateRequest ( group , id , new CreateEmoRoleRequest ( ) . setName ( role . getName ( ) ) . setDescription ( role . getDescription ( ) ) . setPermissions ( role . getPermissions ( ) ) , subject ) ; } | 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 conflicting role identifier" ) ; return updateRoleFromUpdateRequest ( group , id , new UpdateEmoRoleRequest ( ) . setName ( role . getName ( ) ) . setDescription ( role . getDescription ( ) ) . setGrantedPermissions ( role . getPermissions ( ) ) . setRevokeOtherPermissions ( true ) , subject ) ; } | 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 != null ) { range . setStart ( oldestSlab ) ; consistency = ConsistencyLevel . CL_LOCAL_ONE ; } else { consistency = ConsistencyLevel . CL_LOCAL_QUORUM ; } final Iterator < Column < ByteBuffer > > manifestColumns = executePaginated ( _keyspace . prepareQuery ( ColumnFamilies . MANIFEST , consistency ) . getKey ( channel ) . withColumnRange ( range . build ( ) ) . autoPaginate ( true ) ) ; if ( oldestSlab != null ) { return manifestColumns ; } else { PeekingIterator < Column < ByteBuffer > > peekingManifestColumns = Iterators . peekingIterator ( manifestColumns ) ; if ( peekingManifestColumns . hasNext ( ) ) { cacheOldestSlabForChannel ( channel , TimeUUIDSerializer . get ( ) . fromByteBuffer ( peekingManifestColumns . peek ( ) . getName ( ) ) ) ; return peekingManifestColumns ; } else { cacheOldestSlabForChannel ( channel , TimeUUIDs . newUUID ( ) ) ; return Iterators . emptyIterator ( ) ; } } } | 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 faster than a strong read but also means the call is not guaranteed to return the entire manifest . Because of this at least every 10 seconds a weak read for a channel is automatically promoted to a strong read . |
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 ( ColumnFamilies . SLAB , ConsistencyLevel . CL_LOCAL_QUORUM ) . getKey ( slabId ) . withColumnRange ( start , Constants . OPEN_SLAB_MARKER , false , Integer . MAX_VALUE ) ) ; boolean searching = true ; boolean empty = ( start == 0 ) ; boolean more = false ; int next = start ; for ( Column < Integer > eventColumn : eventColumns ) { int eventIdx = eventColumn . getName ( ) ; if ( eventIdx == Constants . OPEN_SLAB_MARKER ) { break ; } empty = false ; if ( ! searching ) { more = true ; break ; } EventId eventId = AstyanaxEventId . create ( channel , slabId , eventIdx ) ; ByteBuffer eventData = eventColumn . getByteBufferValue ( ) ; searching = sink . accept ( eventId , eventData ) ; next = eventIdx ; } cursor . set ( next ) ; boolean hasOpenSlabMarker = ! eventColumns . isEmpty ( ) && eventColumns . getColumnByIndex ( eventColumns . size ( ) - 1 ) . getName ( ) == Constants . OPEN_SLAB_MARKER ; boolean stale = open && ! recent && ! hasOpenSlabMarker ; if ( stale ) { _staleSlabMeter . mark ( ) ; } if ( empty && ( ! open || stale ) ) { deleteEmptySlabAsync ( channel , slabId ) ; open = false ; } else if ( stale ) { closeStaleSlabAsync ( channel , slabId ) ; open = false ; } if ( ! more && ! open ) { cursor . set ( SlabCursor . END ) ; } return searching ; } | 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 . getTokenRanges ( ) ; } } ) . toList ( ) ) ) ) ; } | 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 ) ) ; } return buf ; } | 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 ( eventId ) ; int commonPrefixLength ; if ( prevId == null ) { buf . append ( eventId ) ; } else if ( prevId . length ( ) == eventId . length ( ) && ( commonPrefixLength = getCommonPrefixLength ( prevId , eventId ) ) > 0 ) { buf . append ( DELIM_SHARED_PREFIX ) . append ( eventId . substring ( commonPrefixLength ) ) ; } else { buf . append ( DELIM_REGULAR ) . append ( eventId ) ; } prevId = eventId ; } return buf . toString ( ) ; } | 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 , eventKey . substring ( startIdx , i ) ) ) ; eventIds . add ( eventId ) ; prevId = ( ch == DELIM_REGULAR ) ? null : eventId ; startIdx = i + 1 ; } } eventIds . add ( checkValid ( combine ( prevId , eventKey . substring ( startIdx , eventKey . length ( ) ) ) ) ) ; } | 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 ) ; _rowsRead += 1 ; } catch ( Exception e ) { for ( Throwable cause : Throwables . getCausalChain ( e ) ) { Throwables . propagateIfInstanceOf ( cause , IOException . class ) ; } throw new IOException ( "Failed to read next row" , e ) ; } return true ; } | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.