idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
37,500
public ImmutableList < InstanceInfo > getRoleInstances ( String roleName ) { return getRoleInstancesWithMetadataImpl ( roleName , Collections . < String , String > emptyMap ( ) ) ; }
Retrieve information about instances of a particular role from the Conqueso Server .
37,501
protected final void checkNotNull ( final ConversionStringency stringency , final Logger logger ) { if ( stringency == null ) { throw new NullPointerException ( "stringency must not be null" ) ; } if ( logger == null ) { throw new NullPointerException ( "logger must not be null" ) ; } }
Check the specified conversion stringency and logger are not null .
37,502
protected final void warnOrThrow ( final S source , final String message , final Throwable cause , final ConversionStringency stringency , final Logger logger ) throws ConversionException { checkNotNull ( stringency , logger ) ; if ( stringency . isLenient ( ) ) { if ( cause != null ) { logger . warn ( String . format ( "could not convert %s to %s, %s" , sourceClass . toString ( ) , targetClass . toString ( ) , message ) , cause ) ; } else { logger . warn ( "could not convert {} to {}, {}" , sourceClass . toString ( ) , targetClass . toString ( ) , message ) ; } } else if ( stringency . isStrict ( ) ) { throw new ConversionException ( String . format ( "could not convert %s to %s, %s" , sourceClass . toString ( ) , targetClass . toString ( ) , message ) , cause , source , sourceClass , targetClass ) ; } }
If the conversion stringency is lenient log a warning with the specified message or if the conversion stringency is strict throw a ConversionException with the specified message and cause .
37,503
public static String buildJDBCString ( final String sJdbcURL , final Map < EMySQLConnectionProperty , String > aConnectionProperties ) { ValueEnforcer . notEmpty ( sJdbcURL , "JDBC URL" ) ; ValueEnforcer . isTrue ( sJdbcURL . startsWith ( CJDBC_MySQL . CONNECTION_PREFIX ) , "The JDBC URL '" + sJdbcURL + "' does not seem to be a MySQL connection string!" ) ; final SimpleURL aURL = new SimpleURL ( sJdbcURL ) ; if ( aConnectionProperties != null ) for ( final Map . Entry < EMySQLConnectionProperty , String > aEntry : aConnectionProperties . entrySet ( ) ) aURL . add ( aEntry . getKey ( ) . getName ( ) , aEntry . getValue ( ) ) ; return aURL . getAsStringWithoutEncodedParameters ( ) ; }
Build the final connection string from the base JDBC URL and an optional set of connection properties .
37,504
public Pattern updatePattern ( final Collection < String > prefixes ) { final String XML_PREFIX = prefixes . stream ( ) . map ( s -> Pattern . quote ( s + "/" ) ) . collect ( Collectors . joining ( "|" ) ) ; return XML_PATH_PATTERN = Pattern . compile ( "^/?(?:" + XML_PREFIX + ")?(?:" + IDX_PREFIX + ")?(?<fieldPath>[^/]+(?:/[^/]+)*)$" ) ; }
We have to do it this way to break the circular dependency between the FieldsInfo deserializer and this .
37,505
public static String resolveTitle ( final String title , final String reference ) { if ( StringUtils . isBlank ( title ) && ! StringUtils . isBlank ( reference ) ) { final String [ ] splitReference = PATH_SEPARATOR_REGEX . split ( reference ) ; final String lastPart = splitReference [ splitReference . length - 1 ] ; return StringUtils . isBlank ( lastPart ) || reference . endsWith ( "/" ) || reference . endsWith ( "\\" ) ? reference : lastPart ; } else { return title ; } }
Determine a title to use for a document given it s title and reference fields .
37,506
public static int getJDBCTypeFromClass ( final Class < ? > aClass ) { ValueEnforcer . notNull ( aClass , "Class" ) ; if ( ! ClassHelper . isArrayClass ( aClass ) ) { if ( aClass . equals ( String . class ) ) return Types . VARCHAR ; if ( aClass . equals ( BigDecimal . class ) ) return Types . NUMERIC ; if ( aClass . equals ( Boolean . class ) || aClass . equals ( boolean . class ) ) return Types . BOOLEAN ; if ( aClass . equals ( Byte . class ) || aClass . equals ( byte . class ) ) return Types . TINYINT ; if ( aClass . equals ( Character . class ) || aClass . equals ( char . class ) ) return Types . CHAR ; if ( aClass . equals ( Double . class ) || aClass . equals ( double . class ) ) return Types . DOUBLE ; if ( aClass . equals ( Float . class ) || aClass . equals ( float . class ) ) return Types . REAL ; if ( aClass . equals ( Integer . class ) || aClass . equals ( int . class ) ) return Types . INTEGER ; if ( aClass . equals ( Long . class ) || aClass . equals ( long . class ) ) return Types . BIGINT ; if ( aClass . equals ( Short . class ) || aClass . equals ( short . class ) ) return Types . SMALLINT ; if ( aClass . equals ( java . sql . Date . class ) ) return Types . DATE ; if ( aClass . equals ( java . sql . Time . class ) ) return Types . TIME ; if ( aClass . equals ( java . sql . Timestamp . class ) ) return Types . TIMESTAMP ; if ( aClass . equals ( java . time . ZonedDateTime . class ) ) return Types . TIMESTAMP ; if ( aClass . equals ( java . time . OffsetDateTime . class ) ) return Types . TIMESTAMP ; if ( aClass . equals ( java . time . LocalDateTime . class ) ) return Types . TIMESTAMP ; if ( aClass . equals ( java . time . LocalDate . class ) ) return Types . DATE ; if ( aClass . equals ( java . time . LocalTime . class ) ) return Types . TIME ; } else { final Class < ? > aComponentType = aClass . getComponentType ( ) ; if ( aComponentType . equals ( byte . class ) ) return Types . VARBINARY ; } LOGGER . warn ( "Failed to resolve JDBC type from class " + aClass . getName ( ) ) ; return Types . JAVA_OBJECT ; }
Determine the JDBC type from the passed class .
37,507
public final ESuccess dumpDatabase ( final OutputStream aOS ) { ValueEnforcer . notNull ( aOS , "OutputStream" ) ; try { LOGGER . info ( "Dumping database '" + getDatabaseName ( ) + "' to OutputStream" ) ; try ( final PrintWriter aPrintWriter = new PrintWriter ( new NonBlockingBufferedWriter ( StreamHelper . createWriter ( aOS , StandardCharsets . UTF_8 ) ) ) ) { final DBExecutor aExecutor = new DBExecutor ( this ) ; final ESuccess ret = aExecutor . queryAll ( "SCRIPT SIMPLE" , aCurrentObject -> { if ( aCurrentObject != null ) { aPrintWriter . println ( aCurrentObject . get ( 0 ) . getValue ( ) ) ; } } ) ; aPrintWriter . flush ( ) ; return ret ; } } finally { StreamHelper . close ( aOS ) ; } }
Dump the database to the passed output stream and closed the passed output stream .
37,508
public final ESuccess createBackup ( final File fDestFile ) { ValueEnforcer . notNull ( fDestFile , "DestFile" ) ; LOGGER . info ( "Backing up database '" + getDatabaseName ( ) + "' to " + fDestFile ) ; final DBExecutor aExecutor = new DBExecutor ( this ) ; return aExecutor . executeStatement ( "BACKUP TO '" + fDestFile . getAbsolutePath ( ) + "'" ) ; }
Create a backup file . The file is a ZIP file .
37,509
private HodSearchResult addDomain ( final Iterable < ResourceName > indexIdentifiers , final HodSearchResult document ) { final String index = document . getIndex ( ) ; String domain = null ; for ( final ResourceName indexIdentifier : indexIdentifiers ) { if ( index . equals ( indexIdentifier . getName ( ) ) ) { domain = indexIdentifier . getDomain ( ) ; break ; } } if ( domain == null ) { domain = PUBLIC_INDEX_NAMES . contains ( index ) ? ResourceName . PUBLIC_INDEXES_DOMAIN : getDomain ( ) ; } return document . toBuilder ( ) . domain ( domain ) . build ( ) ; }
Add a domain to a FindDocument given the collection of indexes which were queried against to return it from HOD
37,510
List < String > splitEffects ( final String s ) { return Splitter . on ( "&" ) . omitEmptyStrings ( ) . splitToList ( s ) ; }
Split the specified string into a list of effects .
37,511
List < VariantAnnotationMessage > splitMessages ( final String s , final ConversionStringency stringency , final Logger logger ) throws ConversionException { return Splitter . on ( "&" ) . omitEmptyStrings ( ) . splitToList ( s ) . stream ( ) . map ( m -> variantAnnotationMessageConverter . convert ( m , stringency , logger ) ) . collect ( toList ( ) ) ; }
Split the specified string into a list of variant annotation messages .
37,512
static Integer emptyToNullInteger ( final String s ) { return "" . equals ( s ) ? null : Integer . parseInt ( s ) ; }
Parse the specified string into an integer returning null if the string is empty .
37,513
static Integer numerator ( final String s ) { if ( "" . equals ( s ) ) { return null ; } String [ ] tokens = s . split ( "/" ) ; return emptyToNullInteger ( tokens [ 0 ] ) ; }
Parse the specified string as a fraction and return the numerator if any .
37,514
static Integer denominator ( final String s ) { if ( "" . equals ( s ) ) { return null ; } String [ ] tokens = s . split ( "/" ) ; return ( tokens . length < 2 ) ? null : emptyToNullInteger ( tokens [ 1 ] ) ; }
Parse the specified string as a fraction and return the denominator if any .
37,515
public static < T > JPAExecutionResult < T > createSuccess ( final T aObj ) { return new JPAExecutionResult < > ( ESuccess . SUCCESS , aObj , null ) ; }
Create a new success object .
37,516
public static < T > JPAExecutionResult < T > createFailure ( final Exception ex ) { return new JPAExecutionResult < > ( ESuccess . FAILURE , null , ex ) ; }
Create a new failure object .
37,517
public static void doOnMainThread ( final OnMainThreadJob onMainThreadJob ) { uiHandler . post ( new Runnable ( ) { public void run ( ) { onMainThreadJob . doInUIThread ( ) ; } } ) ; }
Executes the provided code immediately on the UI Thread
37,518
public static void doInBackground ( final OnBackgroundJob onBackgroundJob ) { new Thread ( new Runnable ( ) { public void run ( ) { onBackgroundJob . doOnBackground ( ) ; } } ) . start ( ) ; }
Executes the provided code immediately on a background thread
37,519
public static FutureTask doInBackground ( final OnBackgroundJob onBackgroundJob , ExecutorService executor ) { FutureTask task = ( FutureTask ) executor . submit ( new Runnable ( ) { public void run ( ) { onBackgroundJob . doOnBackground ( ) ; } } ) ; return task ; }
Executes the provided code immediately on a background thread that will be submitted to the provided ExecutorService
37,520
public void start ( ) { if ( actionInBackground != null ) { Runnable jobToRun = new Runnable ( ) { public void run ( ) { result = ( JobResult ) actionInBackground . doAsync ( ) ; onResult ( ) ; } } ; if ( getExecutorService ( ) != null ) { asyncFutureTask = ( FutureTask ) getExecutorService ( ) . submit ( jobToRun ) ; } else { asyncThread = new Thread ( jobToRun ) ; asyncThread . start ( ) ; } } }
Begins the background execution providing a result similar to an AsyncTask . It will execute it on a new Thread or using the provided ExecutorService
37,521
public void cancel ( ) { if ( actionInBackground != null ) { if ( executorService != null ) { asyncFutureTask . cancel ( true ) ; } else { asyncThread . interrupt ( ) ; } } }
Cancels the AsyncJob interrupting the inner thread .
37,522
public static String replacePathParam ( final String url , final String param , final String value ) throws EncoderException { final String pathParam = param . startsWith ( "{" ) ? param : "{" + param + "}" ; final String encodedValue = encode ( value ) ; return StringUtils . replace ( url , pathParam , encodedValue ) ; }
Replaces path param in uri to a valid encoded value
37,523
public static List < String > extractPathParams ( final String url ) { final List < String > pathParams = new ArrayList < > ( ) ; int index = url . indexOf ( '{' ) ; while ( index >= 0 ) { final int endIndex = url . indexOf ( '}' , index ) ; final String pathParam = url . substring ( index + 1 , endIndex ) ; pathParams . add ( pathParam ) ; index = url . indexOf ( '{' , endIndex ) ; } return pathParams ; }
Extracts all path params in url
37,524
private void prepareRequestBody ( ) throws IOException { if ( bodyByteArray != null ) { setByteArrayBody ( ) ; } else if ( bodyString != null ) { setStringBody ( ) ; } else if ( bodyObject != null ) { setTypedBody ( ) ; } }
Prepares the request body - setting the body charset and content length by body type
37,525
public Observable < String > helloUserStream ( final String name , final int repeats ) { return interval ( 100 , TimeUnit . MILLISECONDS ) . map ( i -> "Hello, " + name + "! (#" + i + ")" ) . take ( repeats ) ; }
Endpoint which receives username and repeats number and returns stream of messages limited by the repeat number size
37,526
public static < T , R > Observable < List < R > > batchToStream ( final List < T > elements , final int batchSize , final FutureSuccessHandler < T , R > producer ) { return Observable . create ( subscriber -> batchToStream ( elements , batchSize , 0 , subscriber , producer ) ) ; }
Execute the producer on each element in the list in batches and return a stream of batch results . Every batch is executed in parallel and the next batch begins only after the previous one ended . The result of each batch is the next element in the stream . An error in one of the futures produced by the producer will end the stream with the error
37,527
public static < T > ComposableFuture < T > submit ( final Callable < T > task ) { return submit ( false , task ) ; }
sends a callable task to the default thread pool and returns a ComposableFuture that represent the result .
37,528
public static < T > ComposableFuture < T > buildLazy ( final Producer < T > producer ) { return LazyComposableFuture . build ( producer ) ; }
builds a lazy future from a producer . the producer itself is cached and used afresh on every consumption .
37,529
public static < T > ComposableFuture < T > withTimeout ( final ComposableFuture < T > future , final long duration , final TimeUnit unit ) { return future . withTimeout ( SchedulerServiceHolder . INSTANCE , duration , unit ) ; }
adds a time cap to the provided future . if response do not arrive after the specified time a TimeoutException is returned from the returned future .
37,530
public static < T > ComposableFuture < T > retry ( final int retries , final long duration , final TimeUnit unit , final FutureAction < T > action ) { return action . execute ( ) . withTimeout ( duration , unit ) . recoverWith ( error -> { if ( retries < 1 ) { return ComposableFutures . fromError ( error ) ; } return retry ( retries - 1 , action ) ; } ) ; }
reties an eager future on failure retries times . each try is time capped with the specified time limit .
37,531
public static < T > ComposableFuture < T > doubleDispatch ( final long duration , final TimeUnit unit , final FutureAction < T > action ) { return EagerComposableFuture . doubleDispatch ( action , duration , unit , getScheduler ( ) ) ; }
creates a future that fires the first future immediately and a second one after a specified time period if result hasn t arrived yet . should be used with eager futures .
37,532
public static < T > Observable < T > toColdObservable ( final List < ComposableFuture < T > > futures , final boolean failOnError ) { return Observable . create ( subscriber -> { final AtomicInteger counter = new AtomicInteger ( futures . size ( ) ) ; final AtomicBoolean errorTrigger = new AtomicBoolean ( false ) ; for ( final ComposableFuture < T > future : futures ) { future . consume ( provideObserverResult ( subscriber , counter , errorTrigger , failOnError ) ) ; } } ) ; }
translate a list of lazy futures to a cold Observable stream
37,533
public static < T > Observable < T > toColdObservable ( final RecursiveFutureProvider < T > futureProvider ) { return Observable . create ( new Observable . OnSubscribe < T > ( ) { public void call ( final Subscriber < ? super T > subscriber ) { recursiveChain ( subscriber , futureProvider . createStopCriteria ( ) ) ; } private void recursiveChain ( final Subscriber < ? super T > subscriber , final Predicate < T > stopCriteria ) { futureProvider . provide ( ) . consume ( result -> { if ( result . isSuccess ( ) ) { final T value = result . getValue ( ) ; subscriber . onNext ( value ) ; if ( stopCriteria . apply ( value ) ) { subscriber . onCompleted ( ) ; } else { recursiveChain ( subscriber , stopCriteria ) ; } } else { subscriber . onError ( result . getError ( ) ) ; } } ) ; } } ) ; }
creates new cold observable given future provider on each subscribe will consume the provided future and repeat until stop criteria will exists each result will be emitted to the stream
37,534
public static < T > Observable < T > toHotObservable ( final List < ComposableFuture < T > > futures , final boolean failOnError ) { final ReplaySubject < T > subject = ReplaySubject . create ( futures . size ( ) ) ; final AtomicInteger counter = new AtomicInteger ( futures . size ( ) ) ; final AtomicBoolean errorTrigger = new AtomicBoolean ( false ) ; for ( final ComposableFuture < T > future : futures ) { future . consume ( provideObserverResult ( subject , counter , errorTrigger , failOnError ) ) ; } return subject ; }
translate a list of eager futures into a hot Observable stream the results of the futures will be stored in the stream for any future subscriber .
37,535
public static < T > Observable < T > toObservable ( final FutureProvider < T > provider ) { return Observable . create ( new FutureProviderToStreamHandler < > ( provider ) ) ; }
creates new observable given future provider translating the future results into stream . the sequence will be evaluated on subscribe .
37,536
public static AuthenticationCookie fromDelimitedString ( final String delimitedString ) { Preconditions . checkArgument ( delimitedString != null && delimitedString . length ( ) > 0 , "delimitedString cannot be empty" ) ; final String [ ] cookieElements = delimitedString . split ( DELIMITER ) ; Preconditions . checkArgument ( cookieElements . length == 4 , "delimitedString should contain exactly 4 elements" ) ; return new AuthenticationCookie ( cookieElements [ 0 ] , DateTime . parse ( cookieElements [ 1 ] , DATE_TIME_FORMATTER ) , cookieElements [ 2 ] , cookieElements [ 3 ] ) ; }
Converted the given delimited string into an Authentication cookie . Expected a string in the format username ; creationTime ; appId ; authenticatorId
37,537
public RequestBuilder get ( final String url ) { checkNotNull ( url , "url may not be null" ) ; final AsyncHttpClient . BoundRequestBuilder ningRequestBuilder = asyncHttpClient . prepareGet ( url ) ; return createNewRequestBuilder ( url , ningRequestBuilder ) ; }
Http get request
37,538
public RequestBuilder post ( final String url ) { checkNotNull ( url , "url may not be null" ) ; final AsyncHttpClient . BoundRequestBuilder ningRequestBuilder = asyncHttpClient . preparePost ( url ) ; return createNewRequestBuilder ( url , ningRequestBuilder ) ; }
Http post request
37,539
public RequestBuilder put ( final String url ) { checkNotNull ( url , "url may not be null" ) ; final AsyncHttpClient . BoundRequestBuilder ningRequestBuilder = asyncHttpClient . preparePut ( url ) ; return createNewRequestBuilder ( url , ningRequestBuilder ) ; }
Http put request
37,540
public RequestBuilder delete ( final String url ) { checkNotNull ( url , "url may not be null" ) ; final AsyncHttpClient . BoundRequestBuilder ningRequestBuilder = asyncHttpClient . prepareDelete ( url ) ; return createNewRequestBuilder ( url , ningRequestBuilder ) ; }
Http delete request
37,541
public RequestBuilder head ( final String url ) { checkNotNull ( url , "url may not be null" ) ; final AsyncHttpClient . BoundRequestBuilder ningRequestBuilder = asyncHttpClient . prepareHead ( url ) ; return createNewRequestBuilder ( url , ningRequestBuilder ) ; }
Http head request
37,542
public boolean acceptInboundMessage ( final Object msg ) throws Exception { if ( ! ( msg instanceof FullHttpRequest ) ) return false ; final FullHttpRequest request = ( FullHttpRequest ) msg ; final String uri = request . getUri ( ) ; return pathResolver . isStaticPath ( uri ) ; }
here to make sure that the message is not released twice by the dispatcherHandler and by this handler
37,543
private static void setDateHeader ( final FullHttpResponse response ) { final SimpleDateFormat dateFormatter = new SimpleDateFormat ( HTTP_DATE_FORMAT , Locale . US ) ; dateFormatter . setTimeZone ( TimeZone . getTimeZone ( HTTP_DATE_GMT_TIMEZONE ) ) ; final Calendar time = new GregorianCalendar ( ) ; response . headers ( ) . set ( DATE , dateFormatter . format ( time . getTime ( ) ) ) ; }
Sets the Date header for the HTTP response
37,544
public static boolean isResolved ( Type type ) { if ( type instanceof GenericArrayType ) { return isResolved ( ( ( GenericArrayType ) type ) . getGenericComponentType ( ) ) ; } if ( type instanceof ParameterizedType ) { for ( Type t : ( ( ParameterizedType ) type ) . getActualTypeArguments ( ) ) { if ( ! isResolved ( t ) ) { return false ; } } return true ; } return type instanceof Class ; }
Checks if the given type is fully resolved .
37,545
public static void visit ( Object instance , TypeToken < ? > inspectType , Visitor firstVisitor , Visitor ... moreVisitors ) { try { List < Visitor > visitors = ImmutableList . < Visitor > builder ( ) . add ( firstVisitor ) . add ( moreVisitors ) . build ( ) ; for ( TypeToken < ? > type : inspectType . getTypes ( ) . classes ( ) ) { if ( Object . class . equals ( type . getRawType ( ) ) ) { break ; } for ( Field field : type . getRawType ( ) . getDeclaredFields ( ) ) { if ( ! field . isAccessible ( ) ) { field . setAccessible ( true ) ; } for ( Visitor visitor : visitors ) { visitor . visit ( instance , inspectType , type , field ) ; } } for ( Method method : type . getRawType ( ) . getDeclaredMethods ( ) ) { if ( ! method . isAccessible ( ) ) { method . setAccessible ( true ) ; } for ( Visitor visitor : visitors ) { visitor . visit ( instance , inspectType , type , method ) ; } } } } catch ( Exception e ) { throw Throwables . propagate ( e ) ; } }
Inspect all members in the given type . Fields and Methods that are given to Visitor are always having accessible flag being set .
37,546
public static byte [ ] getQueueRowPrefix ( QueueName queueName ) { if ( queueName . isStream ( ) ) { return Bytes . EMPTY_BYTE_ARRAY ; } String flowlet = queueName . getThirdComponent ( ) ; String output = queueName . getSimpleName ( ) ; byte [ ] idWithinFlow = ( flowlet + "/" + output ) . getBytes ( Charsets . US_ASCII ) ; return getQueueRowPrefix ( idWithinFlow ) ; }
Returns a byte array representing prefix of a queue . The prefix is formed by first two bytes of MD5 of the queue name followed by the queue name .
37,547
private static byte [ ] getQueueRowPrefix ( byte [ ] queueIdWithinFlow ) { byte [ ] bytes = new byte [ queueIdWithinFlow . length + 1 ] ; Hashing . md5 ( ) . hashBytes ( queueIdWithinFlow ) . writeBytesTo ( bytes , 0 , 1 ) ; System . arraycopy ( queueIdWithinFlow , 0 , bytes , 1 , queueIdWithinFlow . length ) ; return bytes ; }
Returns a byte array representing prefix of a queue . The prefix is formed by first byte of MD5 of the queue name followed by the queue name .
37,548
public static boolean isCommittedProcessed ( byte [ ] stateBytes , Transaction tx ) { long writePointer = Bytes . toLong ( stateBytes , 0 , Longs . BYTES ) ; if ( ! tx . isVisible ( writePointer ) ) { return false ; } byte state = stateBytes [ Longs . BYTES + Ints . BYTES ] ; return state == ConsumerEntryState . PROCESSED . getState ( ) ; }
For a queue entry consumer state serialized to byte array return whether it is processed and committed .
37,549
private String [ ] getAlternateNames ( String name ) { String oldName , altNames [ ] = null ; DeprecatedKeyInfo keyInfo = deprecatedKeyMap . get ( name ) ; if ( keyInfo == null ) { altNames = ( reverseDeprecatedKeyMap . get ( name ) != null ) ? new String [ ] { reverseDeprecatedKeyMap . get ( name ) } : null ; if ( altNames != null && altNames . length > 0 ) { keyInfo = deprecatedKeyMap . get ( altNames [ 0 ] ) ; } } if ( keyInfo != null && keyInfo . newKeys . length > 0 ) { List < String > list = new ArrayList < String > ( ) ; if ( altNames != null ) { list . addAll ( Arrays . asList ( altNames ) ) ; } list . addAll ( Arrays . asList ( keyInfo . newKeys ) ) ; altNames = list . toArray ( new String [ list . size ( ) ] ) ; } return altNames ; }
Returns the alternate name for a key if the property name is deprecated or if deprecates a property name .
37,550
public IntegerRanges getRange ( String name ) { String valueString = get ( name ) ; Preconditions . checkNotNull ( valueString ) ; return new IntegerRanges ( valueString ) ; }
Parse the given attribute as a set of integer ranges .
37,551
public Map < String , String > getValByRegex ( String regex ) { Pattern p = Pattern . compile ( regex ) ; Map < String , String > result = new HashMap < String , String > ( ) ; Matcher m ; for ( Map . Entry < Object , Object > item : getProps ( ) . entrySet ( ) ) { if ( item . getKey ( ) instanceof String && item . getValue ( ) instanceof String ) { m = p . matcher ( ( String ) item . getKey ( ) ) ; if ( m . find ( ) ) { result . put ( ( String ) item . getKey ( ) , ( String ) item . getValue ( ) ) ; } } } return result ; }
get keys matching the the regex .
37,552
protected final < V > void error ( Throwable t , SettableFuture < V > future ) { state . set ( State . ERROR ) ; if ( future != null ) { future . setException ( t ) ; } caller . error ( t ) ; }
Force this controller into error state .
37,553
protected final void started ( ) { if ( ! state . compareAndSet ( State . STARTING , State . ALIVE ) ) { LOG . info ( "Program already started {} {}" , programName , runId ) ; return ; } LOG . info ( "Program started: {} {}" , programName , runId ) ; executor ( State . ALIVE ) . execute ( new Runnable ( ) { public void run ( ) { state . set ( State . ALIVE ) ; caller . alive ( ) ; } } ) ; }
Children call this method to signal the program is started .
37,554
private Arguments createProgramArguments ( TwillContext context , Map < String , String > configs ) { Map < String , String > args = ImmutableMap . < String , String > builder ( ) . put ( ProgramOptionConstants . INSTANCE_ID , Integer . toString ( context . getInstanceId ( ) ) ) . put ( ProgramOptionConstants . INSTANCES , Integer . toString ( context . getInstanceCount ( ) ) ) . put ( ProgramOptionConstants . RUN_ID , context . getApplicationRunId ( ) . getId ( ) ) . putAll ( Maps . filterKeys ( configs , Predicates . not ( Predicates . in ( ImmutableSet . of ( "hConf" , "cConf" ) ) ) ) ) . build ( ) ; return new BasicArguments ( args ) ; }
Creates program arguments . It includes all configurations from the specification excluding hConf and cConf .
37,555
@ SuppressWarnings ( "unchecked" ) protected final Schema doGenerate ( TypeToken < ? > typeToken , Set < String > knownRecords , boolean acceptRecursion ) throws UnsupportedTypeException { Type type = typeToken . getType ( ) ; Class < ? > rawType = typeToken . getRawType ( ) ; if ( SIMPLE_SCHEMAS . containsKey ( rawType ) ) { return SIMPLE_SCHEMAS . get ( rawType ) ; } if ( rawType . isEnum ( ) ) { return Schema . enumWith ( ( Class < Enum < ? > > ) rawType ) ; } if ( rawType . isArray ( ) ) { Schema componentSchema = doGenerate ( TypeToken . of ( rawType . getComponentType ( ) ) , knownRecords , acceptRecursion ) ; if ( rawType . getComponentType ( ) . isPrimitive ( ) ) { return Schema . arrayOf ( componentSchema ) ; } return Schema . arrayOf ( Schema . unionOf ( componentSchema , Schema . of ( Schema . Type . NULL ) ) ) ; } if ( ! ( type instanceof Class || type instanceof ParameterizedType ) ) { throw new UnsupportedTypeException ( "Type " + type + " is not supported. " + "Only Class or ParameterizedType are supported." ) ; } if ( Collection . class . isAssignableFrom ( rawType ) ) { if ( ! ( type instanceof ParameterizedType ) ) { throw new UnsupportedTypeException ( "Only supports parameterized Collection type." ) ; } TypeToken < ? > componentType = typeToken . resolveType ( ( ( ParameterizedType ) type ) . getActualTypeArguments ( ) [ 0 ] ) ; Schema componentSchema = doGenerate ( componentType , knownRecords , acceptRecursion ) ; return Schema . arrayOf ( Schema . unionOf ( componentSchema , Schema . of ( Schema . Type . NULL ) ) ) ; } if ( Map . class . isAssignableFrom ( rawType ) ) { if ( ! ( type instanceof ParameterizedType ) ) { throw new UnsupportedTypeException ( "Only supports parameterized Map type." ) ; } Type [ ] typeArgs = ( ( ParameterizedType ) type ) . getActualTypeArguments ( ) ; TypeToken < ? > keyType = typeToken . resolveType ( typeArgs [ 0 ] ) ; TypeToken < ? > valueType = typeToken . resolveType ( typeArgs [ 1 ] ) ; Schema valueSchema = doGenerate ( valueType , knownRecords , acceptRecursion ) ; return Schema . mapOf ( doGenerate ( keyType , knownRecords , acceptRecursion ) , Schema . unionOf ( valueSchema , Schema . of ( Schema . Type . NULL ) ) ) ; } String recordName = typeToken . getRawType ( ) . getName ( ) ; if ( knownRecords . contains ( recordName ) ) { if ( acceptRecursion ) { return Schema . recordOf ( recordName ) ; } else { throw new UnsupportedTypeException ( "Recursive type not supported for class " + recordName ) ; } } return generateRecord ( typeToken , knownRecords , acceptRecursion ) ; }
Actual schema generation . It recursively resolves container types .
37,556
void open ( int groupSize ) { try { close ( ) ; ConsumerConfig config = consumerConfig ; if ( groupSize != config . getGroupSize ( ) ) { config = new ConsumerConfig ( consumerConfig . getGroupId ( ) , consumerConfig . getInstanceId ( ) , groupSize , consumerConfig . getDequeueStrategy ( ) , consumerConfig . getHashKey ( ) ) ; } if ( queueName . isQueue ( ) ) { QueueConsumer queueConsumer = dataFabricFacade . createConsumer ( queueName , config , numGroups ) ; consumerConfig = queueConsumer . getConfig ( ) ; consumer = queueConsumer ; } } catch ( Exception e ) { throw Throwables . propagate ( e ) ; } }
Updates number of instances for the consumer group that this instance belongs to . It ll close existing consumer and create a new one with the new group size .
37,557
public void close ( ) throws IOException { try { if ( consumer != null && consumer instanceof Closeable ) { TransactionContext txContext = dataFabricFacade . createTransactionManager ( ) ; txContext . start ( ) ; try { ( ( Closeable ) consumer ) . close ( ) ; txContext . finish ( ) ; } catch ( TransactionFailureException e ) { LOG . warn ( "Fail to commit transaction when closing consumer." ) ; txContext . abort ( ) ; } } } catch ( Exception e ) { LOG . warn ( "Fail to close queue consumer." , e ) ; } consumer = null ; }
Close the current consumer if there is one .
37,558
public boolean isCompatible ( Schema target ) { if ( equals ( target ) ) { return true ; } Multimap < String , String > recordCompared = HashMultimap . create ( ) ; return checkCompatible ( target , recordCompared ) ; }
Checks if the given target schema is compatible with this schema meaning datum being written with this schema could be projected correctly into the given target schema .
37,559
private < V > BiMap < V , Integer > createIndex ( Set < V > values ) { if ( values == null ) { return null ; } ImmutableBiMap . Builder < V , Integer > builder = ImmutableBiMap . builder ( ) ; int idx = 0 ; for ( V value : values ) { builder . put ( value , idx ++ ) ; } return builder . build ( ) ; }
Creates a map of indexes based on the iteration order of the given set .
37,560
private Map < String , Field > populateRecordFields ( Map < String , Field > fields ) { if ( fields == null ) { return null ; } Map < String , Schema > knownRecordSchemas = Maps . newHashMap ( ) ; knownRecordSchemas . put ( recordName , this ) ; ImmutableMap . Builder < String , Field > builder = ImmutableMap . builder ( ) ; for ( Map . Entry < String , Field > fieldEntry : fields . entrySet ( ) ) { String fieldName = fieldEntry . getKey ( ) ; Field field = fieldEntry . getValue ( ) ; Schema fieldSchema = resolveSchema ( field . getSchema ( ) , knownRecordSchemas ) ; if ( fieldSchema == field . getSchema ( ) ) { builder . put ( fieldName , field ) ; } else { builder . put ( fieldName , Field . of ( fieldName , fieldSchema ) ) ; } } return builder . build ( ) ; }
Resolves all field schemas .
37,561
private Schema resolveSchema ( final Schema schema , final Map < String , Schema > knownRecordSchemas ) { switch ( schema . getType ( ) ) { case ARRAY : Schema componentSchema = resolveSchema ( schema . getComponentSchema ( ) , knownRecordSchemas ) ; return ( componentSchema == schema . getComponentSchema ( ) ) ? schema : Schema . arrayOf ( componentSchema ) ; case MAP : Map . Entry < Schema , Schema > entry = schema . getMapSchema ( ) ; Schema keySchema = resolveSchema ( entry . getKey ( ) , knownRecordSchemas ) ; Schema valueSchema = resolveSchema ( entry . getValue ( ) , knownRecordSchemas ) ; return ( keySchema == entry . getKey ( ) && valueSchema == entry . getValue ( ) ) ? schema : Schema . mapOf ( keySchema , valueSchema ) ; case UNION : ImmutableList . Builder < Schema > schemaBuilder = ImmutableList . builder ( ) ; boolean changed = false ; for ( Schema input : schema . getUnionSchemas ( ) ) { Schema output = resolveSchema ( input , knownRecordSchemas ) ; if ( output != input ) { changed = true ; } schemaBuilder . add ( output ) ; } return changed ? Schema . unionOf ( schemaBuilder . build ( ) ) : schema ; case RECORD : if ( schema . fields == null ) { Schema knownSchema = knownRecordSchemas . get ( schema . recordName ) ; Preconditions . checkArgument ( knownSchema != null , "Undefined schema %s" , schema . recordName ) ; return knownSchema ; } else { knownRecordSchemas . put ( schema . recordName , schema ) ; return schema ; } } return schema ; }
This method is to recursively resolves all name only record schema in the given schema .
37,562
private String buildString ( ) { if ( type . isSimpleType ( ) ) { return '"' + type . name ( ) . toLowerCase ( ) + '"' ; } StringBuilder builder = new StringBuilder ( ) ; JsonWriter writer = new JsonWriter ( CharStreams . asWriter ( builder ) ) ; try { new SchemaTypeAdapter ( ) . write ( writer , this ) ; writer . close ( ) ; return builder . toString ( ) ; } catch ( IOException e ) { throw Throwables . propagate ( e ) ; } }
Helper method to encode this schema into json string .
37,563
private void waitForInstances ( String flowletId , int expectedInstances ) throws InterruptedException , TimeoutException { int numRunningFlowlets = getNumberOfProvisionedInstances ( flowletId ) ; int secondsWaited = 0 ; while ( numRunningFlowlets != expectedInstances ) { LOG . debug ( "waiting for {} instances of {} before suspending flowlets" , expectedInstances , flowletId ) ; TimeUnit . SECONDS . sleep ( SECONDS_PER_WAIT ) ; secondsWaited += SECONDS_PER_WAIT ; if ( secondsWaited > MAX_WAIT_SECONDS ) { String errmsg = String . format ( "waited %d seconds for instances of %s to reach expected count of %d, but %d are running" , secondsWaited , flowletId , expectedInstances , numRunningFlowlets ) ; LOG . error ( errmsg ) ; throw new TimeoutException ( errmsg ) ; } numRunningFlowlets = getNumberOfProvisionedInstances ( flowletId ) ; } }
it cannot change instances without being in the suspended state .
37,564
private void setDefaultConfiguration ( HTableDescriptor tableDescriptor , Configuration conf ) { String compression = conf . get ( CFG_HBASE_TABLE_COMPRESSION , DEFAULT_COMPRESSION_TYPE . name ( ) ) ; CompressionType compressionAlgo = CompressionType . valueOf ( compression ) ; for ( HColumnDescriptor hcd : tableDescriptor . getColumnFamilies ( ) ) { setCompression ( hcd , compressionAlgo ) ; setBloomFilter ( hcd , BloomType . ROW ) ; } }
which doesn t support certain compression type
37,565
public static Map < String , CoprocessorInfo > getCoprocessorInfo ( HTableDescriptor tableDescriptor ) { Map < String , CoprocessorInfo > info = Maps . newHashMap ( ) ; for ( Map . Entry < ImmutableBytesWritable , ImmutableBytesWritable > entry : tableDescriptor . getValues ( ) . entrySet ( ) ) { String key = Bytes . toString ( entry . getKey ( ) . get ( ) ) . trim ( ) ; String spec = Bytes . toString ( entry . getValue ( ) . get ( ) ) . trim ( ) ; if ( ! HConstants . CP_HTD_ATTR_KEY_PATTERN . matcher ( key ) . matches ( ) ) { continue ; } try { Matcher matcher = HConstants . CP_HTD_ATTR_VALUE_PATTERN . matcher ( spec ) ; if ( ! matcher . matches ( ) ) { continue ; } String className = matcher . group ( 2 ) . trim ( ) ; Path path = matcher . group ( 1 ) . trim ( ) . isEmpty ( ) ? null : new Path ( matcher . group ( 1 ) . trim ( ) ) ; int priority = matcher . group ( 3 ) . trim ( ) . isEmpty ( ) ? Coprocessor . PRIORITY_USER : Integer . valueOf ( matcher . group ( 3 ) ) ; String cfgSpec = null ; try { cfgSpec = matcher . group ( 4 ) ; } catch ( IndexOutOfBoundsException ex ) { } Map < String , String > properties = Maps . newHashMap ( ) ; if ( cfgSpec != null ) { cfgSpec = cfgSpec . substring ( cfgSpec . indexOf ( '|' ) + 1 ) ; Matcher m = HConstants . CP_HTD_ATTR_VALUE_PARAM_PATTERN . matcher ( cfgSpec ) ; while ( m . find ( ) ) { properties . put ( m . group ( 1 ) , m . group ( 2 ) ) ; } } info . put ( className , new CoprocessorInfo ( className , path , priority , properties ) ) ; } catch ( Exception ex ) { LOG . warn ( "Coprocessor attribute '{}' has invalid coprocessor specification '{}'" , key , spec , ex ) ; } } return info ; }
Returns information for all coprocessor configured for the table .
37,566
private void invoke ( Method method , Object event , InputContext inputContext ) throws Exception { if ( needContext ) { method . invoke ( flowlet , event , inputContext ) ; } else { method . invoke ( flowlet , event ) ; } }
Calls the user process method .
37,567
public static CConfiguration create ( ) { CConfiguration conf = new CConfiguration ( ) ; conf . addResource ( "tigon-default.xml" ) ; conf . addResource ( "tigon-site.xml" ) ; return conf ; }
Creates an instance of configuration .
37,568
protected void upgradeTable ( String tableNameStr ) throws IOException { byte [ ] tableName = Bytes . toBytes ( tableNameStr ) ; HTableDescriptor tableDescriptor = getAdmin ( ) . getTableDescriptor ( tableName ) ; boolean needUpgrade = upgradeTable ( tableDescriptor ) ; ProjectInfo . Version version = new ProjectInfo . Version ( tableDescriptor . getValue ( TIGON_VERSION ) ) ; if ( ! needUpgrade && version . compareTo ( ProjectInfo . getVersion ( ) ) >= 0 ) { LOG . info ( "Table '{}' was upgraded with same or newer version '{}'. Current version is '{}'" , tableNameStr , version , ProjectInfo . getVersion ( ) ) ; return ; } CoprocessorJar coprocessorJar = createCoprocessorJar ( ) ; Location jarLocation = coprocessorJar . getJarLocation ( ) ; Map < String , HBaseTableUtil . CoprocessorInfo > coprocessorInfo = HBaseTableUtil . getCoprocessorInfo ( tableDescriptor ) ; for ( Class < ? extends Coprocessor > coprocessor : coprocessorJar . getCoprocessors ( ) ) { HBaseTableUtil . CoprocessorInfo info = coprocessorInfo . get ( coprocessor . getName ( ) ) ; if ( info != null ) { if ( ! jarLocation . getName ( ) . equals ( info . getPath ( ) . getName ( ) ) ) { needUpgrade = true ; tableDescriptor . removeCoprocessor ( info . getClassName ( ) ) ; addCoprocessor ( tableDescriptor , coprocessor , jarLocation , coprocessorJar . getPriority ( coprocessor ) ) ; } } else { needUpgrade = true ; addCoprocessor ( tableDescriptor , coprocessor , jarLocation , coprocessorJar . getPriority ( coprocessor ) ) ; } } Set < String > coprocessorNames = ImmutableSet . copyOf ( Iterables . transform ( coprocessorJar . coprocessors , CLASS_TO_NAME ) ) ; for ( String remove : Sets . difference ( coprocessorInfo . keySet ( ) , coprocessorNames ) ) { needUpgrade = true ; tableDescriptor . removeCoprocessor ( remove ) ; } if ( ! needUpgrade ) { LOG . info ( "No upgrade needed for table '{}'" , tableNameStr ) ; return ; } tableDescriptor . setValue ( TIGON_VERSION , ProjectInfo . getVersion ( ) . toString ( ) ) ; LOG . info ( "Upgrading table '{}'..." , tableNameStr ) ; boolean enableTable = false ; try { getAdmin ( ) . disableTable ( tableName ) ; enableTable = true ; } catch ( TableNotEnabledException e ) { LOG . debug ( "Table '{}' not enabled when try to disable it." , tableNameStr ) ; } getAdmin ( ) . modifyTable ( tableName , tableDescriptor ) ; if ( enableTable ) { getAdmin ( ) . enableTable ( tableName ) ; } LOG . info ( "Table '{}' upgrade completed." , tableNameStr ) ; }
Performs upgrade on a given HBase table .
37,569
public static void mkdirsIfNotExists ( Location location ) throws IOException { if ( ! location . isDirectory ( ) && ! location . mkdirs ( ) && ! location . isDirectory ( ) ) { throw new IOException ( "Failed to create directory at " + location . toURI ( ) ) ; } }
Create the directory represented by the location if not exists .
37,570
public static Manifest getManifest ( Location jarLocation ) throws IOException { URI uri = jarLocation . toURI ( ) ; if ( "file" . equals ( uri . getScheme ( ) ) ) { JarFile jarFile = new JarFile ( new File ( uri ) ) ; try { return jarFile . getManifest ( ) ; } finally { jarFile . close ( ) ; } } JarInputStream is = new JarInputStream ( new BufferedInputStream ( jarLocation . getInputStream ( ) ) ) ; try { Manifest manifest = is . getManifest ( ) ; if ( manifest != null ) { return manifest ; } JarEntry jarEntry = is . getNextJarEntry ( ) ; while ( jarEntry != null ) { if ( JarFile . MANIFEST_NAME . equals ( jarEntry . getName ( ) ) ) { return new Manifest ( is ) ; } jarEntry = is . getNextJarEntry ( ) ; } } finally { is . close ( ) ; } return null ; }
Load the manifest inside the given jar .
37,571
protected int persist ( Iterable < QueueEntry > entries , Transaction transaction ) throws IOException { long writePointer = transaction . getWritePointer ( ) ; byte [ ] rowKeyPrefix = Bytes . add ( queueRowPrefix , Bytes . toBytes ( writePointer ) ) ; int count = 0 ; List < Put > puts = Lists . newArrayList ( ) ; int bytes = 0 ; for ( QueueEntry entry : entries ) { byte [ ] rowKey = Bytes . add ( rowKeyPrefix , Bytes . toBytes ( count ++ ) ) ; rowKey = HBaseQueueAdmin . ROW_KEY_DISTRIBUTOR . getDistributedKey ( rowKey ) ; rollbackKeys . add ( rowKey ) ; Put put = new Put ( rowKey ) ; put . add ( QueueEntryRow . COLUMN_FAMILY , QueueEntryRow . DATA_COLUMN , entry . getData ( ) ) ; put . add ( QueueEntryRow . COLUMN_FAMILY , QueueEntryRow . META_COLUMN , QueueEntry . serializeHashKeys ( entry . getHashKeys ( ) ) ) ; puts . add ( put ) ; bytes += entry . getData ( ) . length ; } hTable . put ( puts ) ; hTable . flushCommits ( ) ; return bytes ; }
Persist queue entries into HBase .
37,572
public static Credentials obtainToken ( Configuration hConf , Credentials credentials ) { if ( ! User . isHBaseSecurityEnabled ( hConf ) ) { return credentials ; } try { Class c = Class . forName ( "org.apache.hadoop.hbase.security.token.TokenUtil" ) ; Method method = c . getMethod ( "obtainToken" , Configuration . class ) ; Token < ? extends TokenIdentifier > token = castToken ( method . invoke ( null , hConf ) ) ; credentials . addToken ( token . getService ( ) , token ) ; return credentials ; } catch ( Exception e ) { LOG . error ( "Failed to get secure token for HBase." , e ) ; throw Throwables . propagate ( e ) ; } }
Gets a HBase delegation token and stores it in the given Credentials .
37,573
public void suspend ( ) { if ( suspension . compareAndSet ( null , new CountDownLatch ( 1 ) ) ) { try { suspendBarrier . await ( ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } catch ( BrokenBarrierException e ) { LOG . error ( "Exception during suspend: " + flowletContext , e ) ; } } }
Suspend the running of flowlet . This method will block until the flowlet running thread actually suspended .
37,574
public void resume ( ) { CountDownLatch latch = suspension . getAndSet ( null ) ; if ( latch != null ) { suspendBarrier . reset ( ) ; latch . countDown ( ) ; } }
Resume the running of flowlet .
37,575
private void postProcess ( ProcessMethodCallback callback , TransactionContext txContext , InputDatum input , ProcessMethod . ProcessResult result ) { InputContext inputContext = input . getInputContext ( ) ; Throwable failureCause = null ; FailureReason . Type failureType = FailureReason . Type . IO_ERROR ; try { if ( result . isSuccess ( ) ) { if ( input . getRetry ( ) > 0 ) { input . reclaim ( ) ; } txContext . finish ( ) ; } else { failureCause = result . getCause ( ) ; failureType = FailureReason . Type . USER ; txContext . abort ( ) ; } } catch ( Throwable e ) { LOG . error ( "Transaction operation failed: {}" , e . getMessage ( ) , e ) ; failureType = FailureReason . Type . IO_ERROR ; if ( failureCause == null ) { failureCause = e ; } try { if ( result . isSuccess ( ) ) { txContext . abort ( ) ; } } catch ( Throwable ex ) { LOG . error ( "Fail to abort transaction: {}" , inputContext , ex ) ; } } try { if ( failureCause == null ) { callback . onSuccess ( result . getEvent ( ) , inputContext ) ; } else { callback . onFailure ( result . getEvent ( ) , inputContext , new FailureReason ( failureType , failureCause . getMessage ( ) , failureCause ) , createInputAcknowledger ( input ) ) ; } } catch ( Throwable t ) { LOG . error ( "Failed to invoke callback." , t ) ; } }
Process the process result . This method never throws .
37,576
public static int putBytes ( byte [ ] tgtBytes , int tgtOffset , byte [ ] srcBytes , int srcOffset , int srcLength ) { System . arraycopy ( srcBytes , srcOffset , tgtBytes , tgtOffset , srcLength ) ; return tgtOffset + srcLength ; }
Put bytes at the specified byte array position .
37,577
public static byte [ ] toBytes ( ByteBuffer bb ) { int length = bb . limit ( ) ; byte [ ] result = new byte [ length ] ; System . arraycopy ( bb . array ( ) , bb . arrayOffset ( ) , result , 0 , length ) ; return result ; }
Returns a new byte array copied from the passed ByteBuffer .
37,578
public static String toStringBinary ( ByteBuffer buf ) { if ( buf == null ) { return "null" ; } return toStringBinary ( buf . array ( ) , buf . arrayOffset ( ) , buf . limit ( ) ) ; }
Converts the given byte buffer from its array offset to its limit to a string . The position and the mark are ignored .
37,579
public static long toLong ( byte [ ] bytes , int offset , final int length ) { if ( length != SIZEOF_LONG || offset + length > bytes . length ) { throw explainWrongLengthOrOffset ( bytes , offset , length , SIZEOF_LONG ) ; } long l = 0 ; for ( int i = offset ; i < offset + length ; i ++ ) { l <<= 8 ; l ^= bytes [ i ] & 0xFF ; } return l ; }
Converts a byte array to a long value .
37,580
public static int putLong ( byte [ ] bytes , int offset , long val ) { if ( bytes . length - offset < SIZEOF_LONG ) { throw new IllegalArgumentException ( "Not enough room to put a long at" + " offset " + offset + " in a " + bytes . length + " byte array" ) ; } for ( int i = offset + 7 ; i > offset ; i -- ) { bytes [ i ] = ( byte ) val ; val >>>= 8 ; } bytes [ offset ] = ( byte ) val ; return offset + SIZEOF_LONG ; }
Put a long value out to the specified byte array position .
37,581
public static int putFloat ( byte [ ] bytes , int offset , float f ) { return putInt ( bytes , offset , Float . floatToRawIntBits ( f ) ) ; }
Put a float value out to the specified byte array position .
37,582
public static int putDouble ( byte [ ] bytes , int offset , double d ) { return putLong ( bytes , offset , Double . doubleToLongBits ( d ) ) ; }
Put a double value out to the specified byte array position .
37,583
public static byte [ ] toBytes ( int val ) { byte [ ] b = new byte [ 4 ] ; for ( int i = 3 ; i > 0 ; i -- ) { b [ i ] = ( byte ) val ; val >>>= 8 ; } b [ 0 ] = ( byte ) val ; return b ; }
Convert an int value to a byte array .
37,584
public static int putInt ( byte [ ] bytes , int offset , int val ) { if ( bytes . length - offset < SIZEOF_INT ) { throw new IllegalArgumentException ( "Not enough room to put an int at" + " offset " + offset + " in a " + bytes . length + " byte array" ) ; } for ( int i = offset + 3 ; i > offset ; i -- ) { bytes [ i ] = ( byte ) val ; val >>>= 8 ; } bytes [ offset ] = ( byte ) val ; return offset + SIZEOF_INT ; }
Put an int value out to the specified byte array position .
37,585
public static short toShort ( byte [ ] bytes , int offset , final int length ) { if ( length != SIZEOF_SHORT || offset + length > bytes . length ) { throw explainWrongLengthOrOffset ( bytes , offset , length , SIZEOF_SHORT ) ; } short n = 0 ; n ^= bytes [ offset ] & 0xFF ; n <<= 8 ; n ^= bytes [ offset + 1 ] & 0xFF ; return n ; }
Converts a byte array to a short value .
37,586
public static byte [ ] getBytes ( ByteBuffer buf ) { int savedPos = buf . position ( ) ; byte [ ] newBytes = new byte [ buf . remaining ( ) ] ; buf . get ( newBytes ) ; buf . position ( savedPos ) ; return newBytes ; }
This method will get a sequence of bytes from pos - > limit but will restore pos after .
37,587
public static int putShort ( byte [ ] bytes , int offset , short val ) { if ( bytes . length - offset < SIZEOF_SHORT ) { throw new IllegalArgumentException ( "Not enough room to put a short at" + " offset " + offset + " in a " + bytes . length + " byte array" ) ; } bytes [ offset + 1 ] = ( byte ) val ; val >>= 8 ; bytes [ offset ] = ( byte ) val ; return offset + SIZEOF_SHORT ; }
Put a short value out to the specified byte array position .
37,588
public static byte [ ] toBytes ( BigDecimal val ) { byte [ ] valueBytes = val . unscaledValue ( ) . toByteArray ( ) ; byte [ ] result = new byte [ valueBytes . length + SIZEOF_INT ] ; int offset = putInt ( result , 0 , val . scale ( ) ) ; putBytes ( result , offset , valueBytes , 0 , valueBytes . length ) ; return result ; }
Convert a BigDecimal value to a byte array .
37,589
public static BigDecimal toBigDecimal ( byte [ ] bytes , int offset , final int length ) { if ( bytes == null || length < SIZEOF_INT + 1 || ( offset + length > bytes . length ) ) { return null ; } int scale = toInt ( bytes , offset ) ; byte [ ] tcBytes = new byte [ length - SIZEOF_INT ] ; System . arraycopy ( bytes , offset + SIZEOF_INT , tcBytes , 0 , length - SIZEOF_INT ) ; return new BigDecimal ( new BigInteger ( tcBytes ) , scale ) ; }
Converts a byte array to a BigDecimal value .
37,590
public static int putBigDecimal ( byte [ ] bytes , int offset , BigDecimal val ) { if ( bytes == null ) { return offset ; } byte [ ] valueBytes = val . unscaledValue ( ) . toByteArray ( ) ; byte [ ] result = new byte [ valueBytes . length + SIZEOF_INT ] ; offset = putInt ( result , offset , val . scale ( ) ) ; return putBytes ( result , offset , valueBytes , 0 , valueBytes . length ) ; }
Put a BigDecimal value out to the specified byte array position .
37,591
public static boolean startsWith ( byte [ ] bytes , byte [ ] prefix ) { return bytes != null && prefix != null && bytes . length >= prefix . length && LexicographicalComparerHolder . BEST_COMPARER . compareTo ( bytes , 0 , prefix . length , prefix , 0 , prefix . length ) == 0 ; }
Return true if the byte array on the right is a prefix of the byte array on the left .
37,592
public static int hashBytes ( byte [ ] bytes , int offset , int length ) { int hash = 1 ; for ( int i = offset ; i < offset + length ; i ++ ) { hash = ( 31 * hash ) + bytes [ i ] ; } return hash ; }
Compute hash for binary data .
37,593
public static byte [ ] add ( final byte [ ] a , final byte [ ] b , final byte [ ] c ) { byte [ ] result = new byte [ a . length + b . length + c . length ] ; System . arraycopy ( a , 0 , result , 0 , a . length ) ; System . arraycopy ( b , 0 , result , a . length , b . length ) ; System . arraycopy ( c , 0 , result , a . length + b . length , c . length ) ; return result ; }
Concatenate three byte arrays .
37,594
public static byte [ ] [ ] split ( final byte [ ] a , final byte [ ] b , boolean inclusive , final int num ) { byte [ ] [ ] ret = new byte [ num + 2 ] [ ] ; int i = 0 ; Iterable < byte [ ] > iter = iterateOnSplits ( a , b , inclusive , num ) ; if ( iter == null ) { return null ; } for ( byte [ ] elem : iter ) { ret [ i ++ ] = elem ; } return ret ; }
Split passed range . Expensive operation relatively . Uses BigInteger math . Useful splitting ranges for MapReduce jobs .
37,595
public static Iterable < byte [ ] > iterateOnSplits ( final byte [ ] a , final byte [ ] b , final int num ) { return iterateOnSplits ( a , b , false , num ) ; }
Iterate over keys within the passed range splitting at an [ a b ) boundary .
37,596
public static Iterable < byte [ ] > iterateOnSplits ( final byte [ ] a , final byte [ ] b , boolean inclusive , final int num ) { byte [ ] aPadded ; byte [ ] bPadded ; if ( a . length < b . length ) { aPadded = padTail ( a , b . length - a . length ) ; bPadded = b ; } else if ( b . length < a . length ) { aPadded = a ; bPadded = padTail ( b , a . length - b . length ) ; } else { aPadded = a ; bPadded = b ; } if ( compareTo ( aPadded , bPadded ) >= 0 ) { throw new IllegalArgumentException ( "b <= a" ) ; } if ( num <= 0 ) { throw new IllegalArgumentException ( "num cannot be < 0" ) ; } byte [ ] prependHeader = { 1 , 0 } ; final BigInteger startBI = new BigInteger ( add ( prependHeader , aPadded ) ) ; final BigInteger stopBI = new BigInteger ( add ( prependHeader , bPadded ) ) ; BigInteger diffBI = stopBI . subtract ( startBI ) ; if ( inclusive ) { diffBI = diffBI . add ( BigInteger . ONE ) ; } final BigInteger splitsBI = BigInteger . valueOf ( num + 1 ) ; if ( diffBI . compareTo ( splitsBI ) < 0 ) { return null ; } final BigInteger intervalBI ; try { intervalBI = diffBI . divide ( splitsBI ) ; } catch ( Exception e ) { return null ; } final Iterator < byte [ ] > iterator = new Iterator < byte [ ] > ( ) { private int i = - 1 ; public boolean hasNext ( ) { return this . i < num + 1 ; } public byte [ ] next ( ) { this . i ++ ; if ( this . i == 0 ) { return a ; } if ( this . i == num + 1 ) { return b ; } BigInteger curBI = startBI . add ( intervalBI . multiply ( BigInteger . valueOf ( this . i ) ) ) ; byte [ ] padded = curBI . toByteArray ( ) ; if ( padded [ 1 ] == 0 ) { padded = tail ( padded , padded . length - 2 ) ; } else { padded = tail ( padded , padded . length - 1 ) ; } return padded ; } public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; return new Iterable < byte [ ] > ( ) { public Iterator < byte [ ] > iterator ( ) { return iterator ; } } ; }
Iterate over keys within the passed range .
37,597
public static byte [ ] [ ] toByteArrays ( final String [ ] t ) { byte [ ] [ ] result = new byte [ t . length ] [ ] ; for ( int i = 0 ; i < t . length ; i ++ ) { result [ i ] = Bytes . toBytes ( t [ i ] ) ; } return result ; }
Returns an array of byte arrays made from passed array of Text .
37,598
public static void writeStringFixedSize ( final DataOutput out , String s , int size ) throws IOException { byte [ ] b = toBytes ( s ) ; if ( b . length > size ) { throw new IOException ( "Trying to write " + b . length + " bytes (" + toStringBinary ( b ) + ") into a field of length " + size ) ; } out . writeBytes ( s ) ; for ( int i = 0 ; i < size - s . length ( ) ; ++ i ) { out . writeByte ( 0 ) ; } }
Writes a string as a fixed - size field padded with zeros .
37,599
private Filter createFilter ( ) { return new FilterList ( FilterList . Operator . MUST_PASS_ONE , processedStateFilter , new SingleColumnValueFilter ( QueueEntryRow . COLUMN_FAMILY , stateColumnName , CompareFilter . CompareOp . GREATER , new BinaryPrefixComparator ( Bytes . toBytes ( transaction . getReadPointer ( ) ) ) ) ) ; }
Creates a HBase filter that will filter out rows that that has committed state = PROCESSED .