idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
130,700
public ScanStatus resubmitWorkflowTasks ( String scanId ) { ScanStatus status = _scanStatusDAO . getScanStatus ( scanId ) ; if ( status == null ) { return null ; } if ( status . getCompleteTime ( ) == null ) { for ( ScanRangeStatus active : status . getActiveScanRanges ( ) ) { _scanWorkflow . addScanRangeTask ( scanId ...
Sometimes due to unexpected errors while submitting scan ranges to the underlying queues a scan can get stuck . This method takes all available tasks for a scan and resubmits them . This method is safe because the underlying system is resilient to task resubmissions and concurrent work on the same task .
130,701
public Instant getNextExecutionTimeAfter ( Instant now ) { OffsetTime timeOfDay = OffsetTime . from ( TIME_OF_DAY_FORMAT . parse ( getTimeOfDay ( ) ) ) ; Instant nextExecTime = now . atOffset ( ZoneOffset . UTC ) . with ( timeOfDay ) . toInstant ( ) ; while ( nextExecTime . isBefore ( now ) ) { nextExecTime = nextExecT...
Gets the first execution time for the given scan and upload which is at or after now .
130,702
public ScanWriter createScanWriter ( final int taskId , Set < ScanDestination > destinations ) { checkArgument ( ! destinations . isEmpty ( ) , "destinations.isEmpty()" ) ; if ( destinations . size ( ) == 1 ) { return createScanWriter ( taskId , Iterables . getOnlyElement ( destinations ) ) ; } return new MultiScanWrit...
Creates a scan writer from the given desintations .
130,703
public ScanWriter createScanWriter ( int taskId , ScanDestination destination ) { if ( destination . isDiscarding ( ) ) { return _scanWriterFactory . createDiscardingScanWriter ( taskId , Optional . < Integer > absent ( ) ) ; } URI uri = destination . getUri ( ) ; String scheme = uri . getScheme ( ) ; if ( "file" . equ...
Creates a scan writer for the given destination .
130,704
public < K , C > ColumnMutation prepareColumnMutation ( ColumnFamily < K , C > cf , K rowKey , C column , ConsistencyLevel consistency ) { return _astyanaxKeyspace . prepareColumnMutation ( cf , rowKey , column ) . setConsistencyLevel ( clamp ( consistency ) ) ; }
Mutation for a single column .
130,705
private String getMismatchedPartitioner ( Class < ? extends IPartitioner > expectedPartitioner ) { String partitioner = null ; try { partitioner = _astyanaxKeyspace . describePartitioner ( ) ; boolean matches = CassandraPartitioner . fromClass ( partitioner ) . matches ( expectedPartitioner . getName ( ) ) ; if ( match...
Returns the actual partitioner in use by Cassandra if it does not match the expected partitioner null if it matches .
130,706
public synchronized SlabAllocation attachAndAllocate ( SlabRef slab , PeekingIterator < Integer > eventSizes ) { attach ( slab ) ; return allocate ( eventSizes ) ; }
Attaches a slab and allocates from it in a single atomic operation .
130,707
public synchronized void attach ( SlabRef slab ) { checkState ( ! isAttached ( ) ) ; _slab = slab ; _slabConsumed = 0 ; _slabBytesConsumed = 0 ; _slabExpiresAt = System . currentTimeMillis ( ) + Constants . SLAB_ROTATE_TTL . toMillis ( ) ; }
Attaches a new slab to the channel with the specified capacity .
130,708
public synchronized SlabRef detach ( ) { if ( ! isAttached ( ) ) { return null ; } SlabRef slab = _slab ; _slab = null ; _slabExpiresAt = 0 ; return slab ; }
Detaches a slab from the channel and returns it to the caller to dispose of .
130,709
private MaintenanceOp getNextMaintenanceOp ( final TableJson json , boolean includeTask ) { if ( json . isDeleted ( ) || json . getStorages ( ) . isEmpty ( ) ) { return null ; } MaintenanceOp op = NULLS_LAST . min ( Iterables . transform ( json . getStorages ( ) , new Function < Storage , MaintenanceOp > ( ) { public M...
Returns the next maintenance operation that should be performed on the specified table .
130,710
public boolean checkFacadeAllowed ( String table , FacadeOptions options ) throws FacadeExistsException { return checkFacadeAllowed ( readTableJson ( table , true ) , options . getPlacement ( ) , null ) ; }
Returns true if facade may be created for the specified table and placement . Throws an exception if a facade is not allowed because of a conflict with the master or another facade . Returns false if there is already a facade at the specified placement so facade creation would be idempotent .
130,711
private void purgeData ( TableJson json , Storage storage , int iteration , Runnable progress ) { _log . info ( "Purging data for table '{}' and table uuid '{}' (facade={}, iteration={})." , json . getTable ( ) , storage . getUuidString ( ) , storage . isFacade ( ) , iteration ) ; Runnable rateLimitedProgress = rateLim...
Purge a dropped table or facade . Executed twice once for fast cleanup and again much later for stragglers .
130,712
private void deleteFinal ( TableJson json , Storage storage ) { Delta delta = json . newDeleteStorage ( storage ) ; Audit audit = new AuditBuilder ( ) . set ( "_op" , "doDeleteFinal" ) . set ( "_uuid" , storage . getUuidString ( ) ) . build ( ) ; updateTableMetadata ( json . getTable ( ) , delta , audit , InvalidationS...
Last step in dropping a table or facade .
130,713
private void moveCancel ( TableJson json , Storage src , Storage dest ) { Delta delta = json . newMoveCancel ( src ) ; Audit audit = new AuditBuilder ( ) . set ( "_op" , "doMoveCancel" ) . set ( "_srcUuid" , src . getUuidString ( ) ) . set ( "_srcPlacement" , src . getPlacement ( ) ) . set ( "_destUuid" , dest . getUui...
Cancel a move before mirror promotion has taken place .
130,714
Delta newUnpublishedDatabusEventUpdate ( String tableName , String updateType , String datetime ) { return Deltas . mapBuilder ( ) . update ( "tables" , Deltas . setBuilder ( ) . add ( ImmutableMap . of ( "table" , tableName , "date" , datetime , "event" , updateType ) ) . build ( ) ) . build ( ) ; }
Delta for storing the unpublished databus events .
130,715
private boolean conditionsEqual ( Collection < Condition > conditions ) { if ( conditions . size ( ) != _conditions . size ( ) ) { return false ; } List < Condition > unvalidatedConditions = new ArrayList < > ( conditions ) ; for ( Condition condition : _conditions ) { if ( ! unvalidatedConditions . remove ( condition ...
The order of the conditions is irrelevant just check the set is the same .
130,716
public CloseableDataStore getDataStore ( URI location , String apiKey , MetricRegistry metricRegistry ) throws IOException { String id = LocationUtil . getDataStoreIdentifier ( location , apiKey ) ; CloseableDataStore dataStore = null ; while ( dataStore == null ) { DataStoreMonitor dataStoreMonitor = _dataStoreByLocat...
Returns a DataStore for a given location . If a cached instance already exists its reference count is incremented and returned otherwise a new instance is created and cached .
130,717
private MultiThreadedServiceFactory < AuthDataStore > createDataStoreServiceFactory ( String cluster , MetricRegistry metricRegistry ) { HttpClientConfiguration clientConfig = new HttpClientConfiguration ( ) ; clientConfig . setKeepAlive ( Duration . seconds ( 1 ) ) ; clientConfig . setConnectionTimeout ( Duration . se...
Creates a ServiceFactory for a cluster with reasonable configurations .
130,718
private ResultSet columnScan ( DeltaPlacement placement , TableDDL tableDDL , ByteBuffer rowKey , Range < RangeTimeUUID > columnRange , boolean ascending , ConsistencyLevel consistency ) { Select . Where where = ( tableDDL == placement . getBlockedDeltaTableDDL ( ) ? selectDeltaFrom ( placement . getBlockedDeltaTableDD...
Reads columns from the delta or delta history table . The range of columns order and limit can be parameterized .
130,719
private boolean moveParserToField ( JsonParser parser , String path ) throws IOException { List < String > segments = getFieldPath ( path ) ; for ( String segment : segments ) { if ( parser . getCurrentToken ( ) != JsonToken . START_OBJECT ) { return false ; } boolean found = false ; JsonToken currentToken = parser . n...
Don t materialize the entire parser content do a targeted search for the value that matches the path .
130,720
static ByteBuffer getRowKeyRaw ( int shardId , long tableUuid , byte [ ] contentKeyBytes ) { checkArgument ( shardId >= 0 && shardId < 256 ) ; ByteBuffer rowKey = ByteBuffer . allocate ( 9 + contentKeyBytes . length ) ; rowKey . put ( ( byte ) shardId ) ; rowKey . putLong ( tableUuid ) ; rowKey . put ( contentKeyBytes ...
Constructs a row key when the row s shard ID is already known which is rare . Generally this is used for range queries to construct the lower or upper bound for a query so it doesn t necessarily need to produce a valid row key .
130,721
private List < ClaimedTask > claimMigrationRangeTasks ( int max ) { try { Date claimTime = new Date ( ) ; List < ScanRangeTask > migrationRangeTasks = _workflow . claimScanRangeTasks ( max , QUEUE_CLAIM_TTL ) ; if ( migrationRangeTasks . isEmpty ( ) ) { return ImmutableList . of ( ) ; } List < ClaimedTask > newlyClaime...
Claims migration range tasks that have been queued by the leader and are ready to scan .
130,722
static Storage initializeGroup ( Collection < Storage > group ) { List < Storage > sorted = Ordering . natural ( ) . immutableSortedCopy ( group ) ; Storage primary = sorted . get ( 0 ) ; if ( ! primary . isConsistent ( ) ) { return null ; } for ( Storage storage : sorted ) { storage . _group = sorted ; } return primar...
Post - construction initialization links all non - dropped members of group together . Returns the primary member of the group other members are mirrors .
130,723
Storage getMoveTo ( ) { String destUuid = get ( MOVE_TO ) ; return destUuid != null ? find ( getMirrors ( ) , destUuid ) : null ; }
Move - related properties
130,724
public int compareTo ( Storage o ) { return ComparisonChain . start ( ) . compareTrueFirst ( isConsistent ( ) , o . isConsistent ( ) ) . compareTrueFirst ( _masterPrimary , o . _masterPrimary ) . compare ( o . getPromotionId ( ) , getPromotionId ( ) , TimeUUIDs . ordering ( ) . nullsLast ( ) ) . compare ( _uuid , o . _...
Storage objects sort such that primaries sort first mirrors after .
130,725
private void renewClaimedTasks ( ) { try { List < ClaimedTask > claimedTasks = ImmutableList . copyOf ( _claimedTasks . values ( ) ) ; List < ScanRangeTask > tasks = Lists . newArrayList ( ) ; for ( ClaimedTask claimedTask : claimedTasks ) { if ( claimedTask . isComplete ( ) ) { _log . info ( "Complete claimed task fou...
Renews all claimed scan range tasks that have not been released . Unless this is called periodically the scan workflow will make this task available to be claimed again .
130,726
private void unclaimTask ( ClaimedTask claimedTask , boolean releaseTask ) { _claimedTasks . remove ( claimedTask . getTaskId ( ) ) ; claimedTask . setComplete ( true ) ; if ( releaseTask ) { try { _scanWorkflow . releaseScanRangeTask ( claimedTask . getTask ( ) ) ; _log . info ( "Released scan range task: {}" , claime...
Unclaims a previously claimed task . Effectively this stops the renewing the task and if releaseTask is true removes the task permanently from the workflow queue .
130,727
private boolean asyncRangeScan ( ScanRangeTask task ) { final String scanId = task . getScanId ( ) ; final int taskId = task . getId ( ) ; final String placement = task . getPlacement ( ) ; final ScanRange range = task . getRange ( ) ; RangeScanUploaderResult result ; try { ScanStatus status = _scanStatusDAO . getScanS...
Performs a range scan and updates the global scan status with the scan result .
130,728
protected Set < String > getUpdatedRolesFrom ( Set < String > roles ) { Set < String > updatedRoles = Sets . newHashSet ( roles ) ; updatedRoles . addAll ( _rolesAdded ) ; updatedRoles . removeAll ( _rolesRemoved ) ; return updatedRoles ; }
Helper method for subclasses which given a set of roles returns a new set of roles with all added and removed roles from this modification applied .
130,729
public static String getString ( ByteBuffer buf , Charset encoding ) { return getString ( buf , 0 , buf . remaining ( ) , encoding ) ; }
Converts all remaining bytes in the buffer a String using the specified encoding . Does not move the buffer position .
130,730
public static String getString ( ByteBuffer buf , int offset , int length , Charset encoding ) { buf = buf . duplicate ( ) ; buf . position ( buf . position ( ) + offset ) ; if ( buf . hasArray ( ) ) { return new String ( buf . array ( ) , buf . arrayOffset ( ) + buf . position ( ) , length , encoding ) ; } else { byte...
Converts the specified number of bytes in the buffer and converts them to a String using the specified encoding . Does not move the buffer position .
130,731
public void addThrottle ( AdHocThrottleEndpoint endpoint , AdHocThrottle throttle ) { checkNotNull ( throttle , "throttle" ) ; String key = endpoint . toString ( ) ; try { if ( throttle . isUnlimited ( ) ) { _throttleMap . remove ( key ) ; } _throttleMap . set ( key , throttle ) ; } catch ( Exception e ) { throw Throwa...
Adds a throttle for an HTTP method and path .
130,732
public void removeThrottle ( AdHocThrottleEndpoint endpoint ) { try { _throttleMap . remove ( endpoint . toString ( ) ) ; } catch ( Exception e ) { _log . warn ( "Failed to remove throttle for {} {}" , endpoint . getMethod ( ) , endpoint . getPath ( ) , e ) ; } }
Removes the throttle for an HTTP method and path . This effectively allows umlimited concurrency .
130,733
public AdHocThrottle getThrottle ( AdHocThrottleEndpoint endpoint ) { String key = endpoint . toString ( ) ; AdHocThrottle throttle = _throttleMap . get ( key ) ; if ( throttle == null ) { throttle = AdHocThrottle . unlimitedInstance ( ) ; } else if ( throttle . getExpiration ( ) . isBefore ( Instant . now ( ) ) ) { if...
Returns the throttle in effect for the given HTTP method and path . This method is always guaranteed to return a non - null throttle that is not expired . If no throttle has been configured or if the configured throttle has expired then it will return an unlimited throttle with an effectively infinite expiration date .
130,734
public static LocationType getLocationType ( URI location ) { String scheme = location . getScheme ( ) ; if ( EMODB_SCHEME . equals ( scheme ) ) { if ( LOCATOR_PATTERN . matcher ( location . getHost ( ) ) . matches ( ) ) { return LocationType . EMO_HOST_DISCOVERY ; } else { return LocationType . EMO_URL ; } } else if (...
Returns the location type from a location URI .
130,735
public static String getDataStoreIdentifier ( URI location , String apiKey ) { checkArgument ( getLocationType ( location ) != LocationType . STASH , "Stash locations do not have a data source ID" ) ; UriBuilder uriBuilder = UriBuilder . fromUri ( location ) . userInfo ( apiKey ) . replacePath ( null ) . replaceQuery (...
Converts a location URI to a data source identifier .
130,736
public static Optional < CuratorFramework > getCuratorForLocation ( URI location ) { final String defaultConnectionString ; final String namespace ; if ( getLocationType ( location ) != LocationType . EMO_HOST_DISCOVERY ) { return Optional . absent ( ) ; } if ( getHostOverride ( location ) . isPresent ( ) ) { return Op...
Returns a configured started Curator for a given location or absent if the location does not use host discovery .
130,737
public static String getClusterForLocation ( URI location ) { Matcher matcher = getLocatorMatcher ( location ) ; checkArgument ( matcher . matches ( ) , "Invalid location: %s" , location ) ; final String clusterPrefix ; if ( matcher . group ( "universe" ) != null ) { clusterPrefix = matcher . group ( "universe" ) ; } e...
Returns the EmoDB cluster name associated with the given location .
130,738
public static URI toLocation ( String source , String table ) { URI sourceUri = URI . create ( source ) ; return toLocation ( sourceUri , table ) ; }
Returns a location URI from a source and table name .
130,739
public static URI toLocation ( URI sourceUri , String table ) { getLocationType ( sourceUri ) ; return UriBuilder . fromUri ( sourceUri ) . path ( table ) . build ( ) ; }
Returns a Location URI from a source URI and table name .
130,740
public String replayAsync ( String apiKey , String subscription ) { return replayAsyncSince ( apiKey , subscription , null ) ; }
Any server can initiate a replay request no need for
130,741
public String moveAsync ( String apiKey , String from , String to ) { checkNotNull ( from , "from" ) ; checkNotNull ( to , "to" ) ; try { URI uri = _databus . clone ( ) . segment ( "_move" ) . queryParam ( "from" , from ) . queryParam ( "to" , to ) . build ( ) ; Map < String , Object > response = _client . resource ( u...
Any server can initiate a move request no need for
130,742
public MoveSubscriptionStatus getMoveStatus ( String apiKey , String reference ) { checkNotNull ( reference , "reference" ) ; try { URI uri = _databus . clone ( ) . segment ( "_move" ) . segment ( reference ) . build ( ) ; return _client . resource ( uri ) . header ( ApiKeyRequest . AUTHENTICATION_HEADER , apiKey ) . g...
Any server can get the move status no need for
130,743
private Map < String , Object > deserialized ( ) { DeserializationState deserState ; while ( ! ( deserState = _deserState . get ( ) ) . isDeserialized ( ) ) { Map < String , Object > deserialized = JsonHelper . fromJson ( deserState . json , new TypeReference < Map < String , Object > > ( ) { } ) ; deserialized . putAl...
Returns the JSON as a Map . If necessary the JSON is converted to a Map as a result of this call .
130,744
public Object put ( String key , Object value ) { DeserializationState deserializationState = _deserState . get ( ) ; if ( deserializationState . isDeserialized ( ) ) { return deserializationState . deserialized . put ( key , value ) ; } return deserializationState . overrides . put ( key , value ) ; }
For efficiency this method breaks the contract that the old value is returned . Otherwise common operations such as adding intrinsics and template attributes would require deserializing the object .
130,745
void writeTo ( JsonGenerator generator ) throws IOException { DeserializationState deserState = _deserState . get ( ) ; if ( deserState . isDeserialized ( ) ) { generator . writeObject ( deserState . deserialized ) ; return ; } if ( deserState . overrides . isEmpty ( ) ) { try { generator . writeRaw ( deserState . json...
Writes this record to the provided generator in the most efficient manner possible in the current state .
130,746
private SortedQueue getQueueReadOnly ( String queueName , Duration waitDuration ) { DedupQueue service = getQueueReadWrite ( queueName , waitDuration ) ; if ( service != null ) { try { return service . getQueue ( ) ; } catch ( ReadOnlyQueueException e ) { } } return _sortedQueueFactory . create ( queueName , true , _qu...
Returns the persistent sorted queue managed by this JVM or a stub that supports only read - only operations if not managed by this JVM .
130,747
public void setCustomRequestParameter ( String param , String ... values ) { _customRequestParameters . putAll ( param , Arrays . asList ( values ) ) ; }
Sets custom request parameters . Custom parameters may include new features not yet officially supported or additional parameters to existing calls not intended for widespread use . As such this method is not typically used by most clients . Furthermore adding additional parameters may cause the request to fail .
130,748
void remove ( T obj ) { _queue . remove ( obj ) ; if ( _prioritize == obj ) { _prioritize = null ; } }
Removes an object from the queue .
130,749
T cycle ( ) { if ( _prioritize != null ) { return _prioritize ; } if ( ! _queue . isEmpty ( ) ) { T first = _queue . keySet ( ) . iterator ( ) . next ( ) ; _queue . get ( first ) ; return first ; } return null ; }
Returns the head of the queue then cycles it to the back of the queue .
130,750
private Delta createDelta ( PermissionUpdateRequest request ) { MapDeltaBuilder builder = Deltas . mapBuilder ( ) ; for ( String permissionString : request . getPermitted ( ) ) { builder . put ( "perm_" + validated ( permissionString ) , 1 ) ; } for ( String permissionString : request . getRevoked ( ) ) { builder . rem...
Returns a delta constructed from this request or null if the request contained no changes .
130,751
public void addTokenRangeToCurrentBatchForCluster ( String cluster , String placement , Collection < ScanRange > ranges ) { PlanBatch batch = _clusterTails . get ( cluster ) ; if ( batch == null ) { batch = new PlanBatch ( ) ; _clusterHeads . put ( cluster , batch ) ; _clusterTails . put ( cluster , batch ) ; } batch ....
Adds a collection of scan ranges to the plan for a specific placement . The range collection should all belong to a single token range in the ring .
130,752
public ScanStatus toScanStatus ( ) { List < ScanRangeStatus > pendingRangeStatuses = Lists . newArrayList ( ) ; int taskId = 0 ; int batchId = 0 ; int concurrencyId = 0 ; for ( PlanBatch batch : _clusterHeads . values ( ) ) { Integer lastBatchId = null ; while ( batch != null ) { List < PlanItem > items = batch . getIt...
Creates a ScanStatus based on the current state of the plan . All scan ranges are added as pending tasks .
130,753
public ScanDestination getDestinationWithSubpath ( String path ) { if ( isDiscarding ( ) ) { return discard ( ) ; } if ( path == null ) { return new ScanDestination ( _uri ) ; } return new ScanDestination ( UriBuilder . fromUri ( _uri ) . path ( path ) . build ( ) ) ; }
Creates a new scan destination at the given path rooted at the current scan destination .
130,754
synchronized public void performHostDiscovery ( MetricRegistry metricRegistry ) { if ( _hostDiscoveryPerformed ) { return ; } Iterable < String > hosts = null ; if ( _seeds != null ) { hosts = Splitter . on ( ',' ) . trimResults ( ) . split ( _seeds ) ; } if ( _zooKeeperServiceName != null ) { checkState ( hosts == nul...
Discover Cassandra seeds and partitioner if not statically configured .
130,755
private void setJettyAuthentication ( Subject subject ) { HttpConnection connection = HttpConnection . getCurrentConnection ( ) ; if ( connection == null ) { return ; } Request jettyRequest = connection . getHttpChannel ( ) . getRequest ( ) ; if ( jettyRequest == null ) { return ; } PrincipalWithRoles principal = ( Pri...
Certain aspects of the container such as logging need the authentication information to behave properly . This method updates the request with the necessary objects to recognize the authenticated user .
130,756
public static boolean isPotentiallyEncryptedBytes ( byte [ ] bytes ) { checkNotNull ( bytes , "bytes" ) ; try { return bytes . length != 0 && bytes . length % Cipher . getInstance ( CIPHER ) . getBlockSize ( ) == 0 ; } catch ( Throwable t ) { throw Throwables . propagate ( t ) ; } }
Returns true if the provided bytes _could_ be encrypted credentials even if they can t be decrypted by a specific instance .
130,757
public static boolean isPotentiallyEncryptedString ( String string ) { checkNotNull ( string , "string" ) ; byte [ ] encryptedBytes ; try { encryptedBytes = BaseEncoding . base64 ( ) . omitPadding ( ) . decode ( string ) ; } catch ( IllegalArgumentException e ) { return false ; } return isPotentiallyEncryptedBytes ( en...
Returns true if the provided String _could_ be encrypted credentials even if it can t be decrypted by a specific instance .
130,758
public List < LeaderService > getPartitionLeaderServices ( ) { return _partitionLeaders . stream ( ) . map ( PartitionLeader :: getLeaderService ) . collect ( Collectors . toList ( ) ) ; }
Returns the underlying leader services for each partition . The services are guaranteed to be returned ordered by partition number .
130,759
private Iterator < Record > decodeRows ( Iterator < Row < ByteBuffer , UUID > > iter , final AstyanaxTable table , final int largeRowThreshold , final ReadConsistency consistency ) { return Iterators . transform ( iter , new Function < Row < ByteBuffer , UUID > , Record > ( ) { public Record apply ( Row < ByteBuffer , ...
Decodes rows returned by scanning a table .
130,760
private Map < String , Function < HttpRequestContext , String > > createSubstitutionMap ( String [ ] permissions , AbstractMethod am ) { Map < String , Function < HttpRequestContext , String > > map = Maps . newLinkedHashMap ( ) ; for ( String permission : permissions ) { Matcher matcher = SUBSTITUTION_MATCHER . matche...
Returns a mapping from permissions found in the annotations to functions which can perform any necessary substitutions based on actual values in the request .
130,761
private synchronized void removeEmptyClaimSets ( ) { Iterables . removeIf ( _map . values ( ) , new Predicate < Handle > ( ) { public boolean apply ( Handle handle ) { handle . getClaimSet ( ) . pump ( ) ; return handle . getRefCount ( ) . get ( ) == 0 && handle . getClaimSet ( ) . size ( ) == 0 ; } } ) ; }
Cleans up old claim sets for subscriptions that have become inactive . Ensures the map of claim sets doesn t grow forever .
130,762
private ObjectInspector getObjectInspectorForType ( TypeInfo type ) throws SerDeException { switch ( type . getCategory ( ) ) { case PRIMITIVE : PrimitiveTypeInfo primitiveType = ( PrimitiveTypeInfo ) type ; if ( isSupportedPrimitive ( primitiveType ) ) { return PrimitiveObjectInspectorFactory . getPrimitiveJavaObjectI...
Returns the associated ObjectInspector for a type . This most delegates the to Hive java implementations but filters out primitives not supported by EmoDB .
130,763
private Object getRawValue ( String columnName , Map < String , Object > content ) throws ColumnNotFoundException { String field = columnName ; Object value = content ; while ( field != null ) { if ( value == null ) { throw new ColumnNotFoundException ( ) ; } if ( ! ( value instanceof Map ) ) { throw new ColumnNotFound...
Returns the raw value for a given Map . If the value was found is and is null then null is returned . If no value is present then ColumnNotFoundException is thrown .
130,764
private Object deserialize ( TypeInfo type , Object rawValue ) throws SerDeException { Object value = null ; if ( rawValue != null ) { switch ( type . getCategory ( ) ) { case PRIMITIVE : value = deserializePrimitive ( ( PrimitiveTypeInfo ) type , rawValue ) ; break ; case STRUCT : value = deserializeStruct ( ( StructT...
Deserializes a raw value to the provided type .
130,765
private boolean isSupportedPrimitive ( PrimitiveTypeInfo type ) { switch ( type . getPrimitiveCategory ( ) ) { case VOID : case STRING : case BOOLEAN : case BYTE : case SHORT : case INT : case LONG : case FLOAT : case DOUBLE : case DATE : case TIMESTAMP : return true ; default : return false ; } }
Determines if the given primitive is supported by this deserializer . At this time the only exclusions are BINARY DECIMAL VARCHAR CHAR and UNKNOWN .
130,766
private Object deserializePrimitive ( PrimitiveTypeInfo type , Object value ) throws SerDeException { switch ( type . getPrimitiveCategory ( ) ) { case VOID : return null ; case STRING : return deserializeString ( value ) ; case BOOLEAN : return deserializeBoolean ( value ) ; case BYTE : case SHORT : case INT : case LO...
Deserializes a primitive to its corresponding Java type doing a best - effort conversion when necessary .
130,767
public static ListenableFuture < ResultSet > executeAdaptiveQueryAsync ( Session session , Statement statement , int fetchSize ) { return executeAdaptiveQueryAsync ( session , statement , fetchSize , MAX_ADAPTATIONS ) ; }
Executes a query asychronously dynamically adjusting the fetch size down if necessary .
130,768
public static ResultSet executeAdaptiveQuery ( Session session , Statement statement , int fetchSize ) { int remainingAdaptations = MAX_ADAPTATIONS ; while ( true ) { try { statement . setFetchSize ( fetchSize ) ; ResultSet resultSet = session . execute ( statement ) ; return new AdaptiveResultSet ( session , resultSet...
Executes a query sychronously dynamically adjusting the fetch size down if necessary .
130,769
private static boolean isAdaptiveException ( Throwable t ) { if ( t instanceof FrameTooLongException ) { return true ; } if ( t instanceof NoHostAvailableException ) { Collection < Throwable > hostExceptions = ( ( NoHostAvailableException ) t ) . getErrors ( ) . values ( ) ; return ! hostExceptions . isEmpty ( ) && hos...
Returns true if the exception is one which indicates that the frame size may be too large false otherwise .
130,770
private boolean reduceFetchSize ( Throwable reason ) { if ( ! isAdaptiveException ( reason ) || -- _remainingAdaptations == 0 ) { return false ; } ExecutionInfo executionInfo = _delegate . getExecutionInfo ( ) ; Statement statement = executionInfo . getStatement ( ) ; PagingState pagingState = executionInfo . getPaging...
Reduces the fetch size and retries the query . Returns true if the query succeeded false if the root cause of the exception does not indicate a frame size issue if the frame size cannot be adjusted down any further or if the retried query fails for an unrelated reason .
130,771
public ByteBuffer skipPrefix ( ByteBuffer value ) { value . position ( value . position ( ) + _prefixLength ) ; return value ; }
removes the hex prefix that indicates the number of blocks in the delta
130,772
public ReplicationClientFactory usingApiKey ( String apiKey ) { if ( Objects . equal ( _apiKey , apiKey ) ) { return this ; } return new ReplicationClientFactory ( _jerseyClient , apiKey ) ; }
Creates a view of this instance using the given API Key and sharing the same underlying resources . Note that this method may return a new instance so the caller must use the returned value .
130,773
private AnnotatedContent resolveAnnotated ( Record record , final ReadConsistency consistency ) { final Resolved resolved = resolve ( record , consistency ) ; final Table table = record . getKey ( ) . getTable ( ) ; return new AnnotatedContent ( ) { public Map < String , Object > getContent ( ) { return toContent ( res...
Resolve a set of changes returning an interface that includes info about specific change IDs .
130,774
public void createFacade ( String table , FacadeOptions facadeOptions , Audit audit ) { checkLegalTableName ( table ) ; checkNotNull ( facadeOptions , "facadeDefinition" ) ; checkNotNull ( audit , "audit" ) ; _tableDao . createFacade ( table , facadeOptions , audit ) ; }
Facade related methods
130,775
public T startIfOwner ( String name , Duration waitDuration ) { long timeoutAt = System . currentTimeMillis ( ) + waitDuration . toMillis ( ) ; LeaderService leaderService = _leaderMap . getUnchecked ( name ) . orNull ( ) ; if ( leaderService == null || ! awaitRunning ( leaderService , timeoutAt ) ) { return null ; } S...
Returns the specified managed service if this server is responsible for the specified object and has won a ZooKeeper - managed leader election .
130,776
private boolean awaitRunning ( Service service , long timeoutAt ) { if ( service . isRunning ( ) ) { return true ; } long waitMillis = timeoutAt - System . currentTimeMillis ( ) ; if ( waitMillis <= 0 ) { return false ; } try { service . start ( ) . get ( waitMillis , TimeUnit . MILLISECONDS ) ; } catch ( Exception e )...
Returns true if the Guava service entered the RUNNING state within the specified time period .
130,777
public static int compare ( UUID uuid1 , UUID uuid2 ) { int timeResult = Longs . compare ( uuid1 . timestamp ( ) , uuid2 . timestamp ( ) ) ; if ( timeResult != 0 ) { return timeResult ; } return uuid1 . compareTo ( uuid2 ) ; }
Compare two time UUIDs deterministically first by their embedded timestamp next by their node - specific sequence number finally breaking ties using their embedded node identifier . \
130,778
public static int compareTimestamps ( UUID uuid1 , UUID uuid2 ) { return Longs . compare ( uuid1 . timestamp ( ) , uuid2 . timestamp ( ) ) ; }
Compare the embedded timestamps of the given UUIDs . This is used when it is OK to return an equality based on timestamps alone
130,779
public static Iterable < SplitPath > getSplits ( final Configuration config , Path [ ] paths ) { final int splitSize = getSplitSize ( config ) ; return FluentIterable . from ( Arrays . asList ( paths ) ) . transformAndConcat ( new Function < Path , Iterable < ? extends SplitPath > > ( ) { public Iterable < ? extends Sp...
Gets the splits for a given list of EmoDB paths .
130,780
public static BaseRecordReader createRecordReader ( Configuration config , Path path ) throws IOException { EmoInputSplittable emoFs = ( EmoInputSplittable ) path . getFileSystem ( config ) ; return emoFs . getBaseRecordReader ( config , path , getSplitSize ( config ) ) ; }
Gets a record reader for a given split .
130,781
boolean hasUUID ( long uuid ) { if ( _readStorage . hasUUID ( uuid ) ) { return true ; } for ( AstyanaxStorage storage : _writeStorage ) { if ( storage . hasUUID ( uuid ) ) { return true ; } } return false ; }
Test if a given UUID matches this table .
130,782
static Type parse ( String str ) { try { return doParse ( str ) ; } catch ( RuntimeException ex ) { throw ex ; } catch ( Exception ex ) { throw new RuntimeException ( ex ) ; } }
Parses the TypeToken string format .
130,783
private static Type doParse ( String str ) throws Exception { Class < ? > token = PRIMITIVES . get ( str ) ; if ( token != null ) { return token ; } int first = str . indexOf ( '<' ) ; if ( first < 0 ) { return StringConvert . loadType ( str ) ; } int last = str . lastIndexOf ( '>' ) ; String baseStr = str . substring ...
parse an element
130,784
private static List < String > split ( String str ) { List < String > result = new ArrayList < String > ( ) ; int genericCount = 0 ; int startPos = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str . charAt ( i ) == ',' && genericCount == 0 ) { result . add ( str . substring ( startPos , i ) . trim ( ) ) ;...
split by comma handling nested generified types
130,785
private void tryRegisterGuava ( ) { try { Class < ? > moduleClass = Class . class . getMethod ( "getModule" ) . getReturnType ( ) ; Object convertModule = Class . class . getMethod ( "getModule" ) . invoke ( StringConvert . class ) ; Object layer = convertModule . getClass ( ) . getMethod ( "getLayer" ) . invoke ( conv...
Tries to register the Guava converters class .
130,786
private void tryRegisterJava8Optionals ( ) { try { loadType ( "java.util.OptionalInt" ) ; @ SuppressWarnings ( "unchecked" ) Class < ? > cls1 = ( Class < TypedStringConverter < ? > > ) loadType ( "org.joda.convert.OptionalIntStringConverter" ) ; TypedStringConverter < ? > conv1 = ( TypedStringConverter < ? > ) cls1 . g...
Tries to register the Java 8 optional classes .
130,787
private void tryRegisterTimeZone ( ) { try { registered . put ( SimpleTimeZone . class , JDKStringConverter . TIME_ZONE ) ; } catch ( Throwable ex ) { if ( LOG ) { System . err . println ( "tryRegisterTimeZone1: " + ex ) ; } } try { TimeZone zone = TimeZone . getDefault ( ) ; registered . put ( zone . getClass ( ) , JD...
Tries to register the subclasses of TimeZone . Try various things doesn t matter if the map entry gets overwritten .
130,788
private void tryRegisterJava8 ( ) { try { tryRegister ( "java.time.Instant" , "parse" ) ; tryRegister ( "java.time.Duration" , "parse" ) ; tryRegister ( "java.time.LocalDate" , "parse" ) ; tryRegister ( "java.time.LocalTime" , "parse" ) ; tryRegister ( "java.time.LocalDateTime" , "parse" ) ; tryRegister ( "java.time.Of...
Tries to register Java 8 classes .
130,789
private void tryRegisterThreeTenBackport ( ) { try { tryRegister ( "org.threeten.bp.Instant" , "parse" ) ; tryRegister ( "org.threeten.bp.Duration" , "parse" ) ; tryRegister ( "org.threeten.bp.LocalDate" , "parse" ) ; tryRegister ( "org.threeten.bp.LocalTime" , "parse" ) ; tryRegister ( "org.threeten.bp.LocalDateTime" ...
Tries to register ThreeTen backport classes .
130,790
static Class < ? > loadType ( String fullName ) throws ClassNotFoundException { try { ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; return loader != null ? loader . loadClass ( fullName ) : Class . forName ( fullName ) ; } catch ( ClassNotFoundException ex ) { return loadPrimitiveType ( ...
loads a type avoiding nulls context class loader if available
130,791
private static Class < ? > loadPrimitiveType ( String fullName , ClassNotFoundException ex ) throws ClassNotFoundException { if ( fullName . equals ( "int" ) ) { return int . class ; } else if ( fullName . equals ( "long" ) ) { return long . class ; } else if ( fullName . equals ( "double" ) ) { return double . class ;...
handle primitive types
130,792
private < T > StringConverter < T > findAnnotatedConverter ( final Class < T > cls ) { Method toString = findToStringMethod ( cls ) ; if ( toString == null ) { return null ; } MethodConstructorStringConverter < T > con = findFromStringConstructor ( cls , toString ) ; MethodsStringConverter < T > mth = findFromStringMet...
Finds a converter searching annotated .
130,793
private Class < ? > eliminateEnumSubclass ( Class < ? > cls ) { Class < ? > sup = cls . getSuperclass ( ) ; if ( sup != null && sup . getSuperclass ( ) == Enum . class ) { return sup ; } return cls ; }
eliminates enum subclass as they are pesky
130,794
private static RenameHandler createInstance ( ) { RenameHandler instance = create ( false ) ; try { instance . loadFromClasspath ( ) ; } catch ( IllegalStateException ex ) { System . err . println ( "ERROR: " + ex . getMessage ( ) ) ; ex . printStackTrace ( ) ; } catch ( Throwable ex ) { System . err . println ( "ERROR...
this is a method to aid IDE debugging of class initialization
130,795
public Class < ? > lookupType ( String name ) throws ClassNotFoundException { if ( name == null ) { throw new IllegalArgumentException ( "name must not be null" ) ; } Class < ? > type = typeRenames . get ( name ) ; if ( type == null ) { type = StringConvert . loadType ( name ) ; } return type ; }
Lookup a type from a name handling renames .
130,796
public < T extends Enum < T > > T lookupEnum ( Class < T > type , String name ) { if ( type == null ) { throw new IllegalArgumentException ( "type must not be null" ) ; } if ( name == null ) { throw new IllegalArgumentException ( "name must not be null" ) ; } Map < String , Enum < ? > > map = getEnumRenames ( type ) ; ...
Lookup an enum from a name handling renames .
130,797
private byte [ ] getSerializedEntity ( ClientRequest request ) { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream ( ) ; try { writeRequestEntity ( request , new RequestEntityWriterListener ( ) { public void onRequestEntitySize ( long size ) throws IOException { } public OutputStream onGetOutputStrea...
Get the serialized representation of the request entity . This is used when generating the client signature because this is the representation that the server will receive and use when it generates the server - side signature to compare to the client - side signature .
130,798
protected void cachePrincipal ( String apiKey , Principal principal ) { cache . put ( apiKey , Optional . fromNullable ( principal ) ) ; }
Put this principal directly into cache . This can avoid lookup on user request and prepay the lookup cost .
130,799
private boolean validateTimestamp ( String timestamp ) { DateTime requestTime = TimeUtils . parse ( timestamp ) ; long difference = Math . abs ( new Duration ( requestTime , nowInUTC ( ) ) . getMillis ( ) ) ; return difference <= allowedTimestampRange ; }
To protect against replay attacks make sure the timestamp on the request is valid by ensuring that the difference between the request time and the current time on the server does not fall outside the acceptable time range . Note that the request time may have been generated on a different machine and so it may be ahead...