idx
int64 0
41.2k
| question
stringlengths 73
5.81k
| target
stringlengths 5
918
|
|---|---|---|
1,800
|
public void run ( ) { while ( running ) { try { handleIO ( ) ; } catch ( IOException e ) { logRunException ( e ) ; } catch ( CancelledKeyException e ) { logRunException ( e ) ; } catch ( ClosedSelectorException e ) { logRunException ( e ) ; } catch ( IllegalStateException e ) { logRunException ( e ) ; } catch ( ConcurrentModificationException e ) { logRunException ( e ) ; } } getLogger ( ) . info ( "Shut down memcached client" ) ; }
|
Handle IO as long as the application is running .
|
1,801
|
private void logRunException ( final Exception e ) { if ( shutDown ) { getLogger ( ) . debug ( "Exception occurred during shutdown" , e ) ; } else { getLogger ( ) . warn ( "Problem handling memcached IO" , e ) ; } }
|
Log a exception to different levels depending on the state .
|
1,802
|
public void retryOperation ( Operation op ) { if ( retryQueueSize >= 0 && retryOps . size ( ) >= retryQueueSize ) { if ( ! op . isCancelled ( ) ) { op . cancel ( ) ; } } retryOps . add ( op ) ; }
|
Add a operation to the retry queue .
|
1,803
|
public < T > Future < T > decode ( final Transcoder < T > tc , final CachedData cachedData ) { assert ! pool . isShutdown ( ) : "Pool has already shut down." ; TranscodeService . Task < T > task = new TranscodeService . Task < T > ( new Callable < T > ( ) { public T call ( ) { return tc . decode ( cachedData ) ; } } ) ; if ( tc . asyncDecode ( cachedData ) ) { this . pool . execute ( task ) ; } return task ; }
|
Perform a decode .
|
1,804
|
private Object deserialize ( ) { SerializingTranscoder tc = new SerializingTranscoder ( ) ; CachedData d = new CachedData ( this . getItemFlags ( ) , this . getValue ( ) , CachedData . MAX_SIZE ) ; Object rv = null ; rv = tc . decode ( d ) ; return rv ; }
|
Attempt to get the object represented by the given serialized bytes .
|
1,805
|
public static void close ( Closeable closeable ) { if ( closeable != null ) { try { closeable . close ( ) ; } catch ( Exception e ) { logger . info ( "Unable to close %s" , closeable , e ) ; } } }
|
Close a closeable .
|
1,806
|
public static synchronized HashAlgorithm lookupHashAlgorithm ( String name ) { validateName ( name ) ; return REGISTRY . get ( name . toLowerCase ( ) ) ; }
|
Tries to find selected hash algorithm using name provided .
|
1,807
|
public Collection < SocketAddress > getUnavailableServers ( ) { ArrayList < SocketAddress > rv = new ArrayList < SocketAddress > ( ) ; for ( MemcachedNode node : mconn . getLocator ( ) . getAll ( ) ) { if ( ! node . isActive ( ) ) { rv . add ( node . getSocketAddress ( ) ) ; } } return rv ; }
|
Get the addresses of unavailable servers .
|
1,808
|
public < T > OperationFuture < Boolean > touch ( final String key , final int exp ) { return touch ( key , exp , transcoder ) ; }
|
Touch the given key to reset its expiration time with the default transcoder .
|
1,809
|
public < T > OperationFuture < Boolean > touch ( final String key , final int exp , final Transcoder < T > tc ) { final CountDownLatch latch = new CountDownLatch ( 1 ) ; final OperationFuture < Boolean > rv = new OperationFuture < Boolean > ( key , latch , operationTimeout , executorService ) ; Operation op = opFact . touch ( key , exp , new OperationCallback ( ) { public void receivedStatus ( OperationStatus status ) { rv . set ( status . isSuccess ( ) , status ) ; } public void complete ( ) { latch . countDown ( ) ; rv . signalComplete ( ) ; } } ) ; rv . setOperation ( op ) ; mconn . enqueueOperation ( key , op ) ; return rv ; }
|
Touch the given key to reset its expiration time .
|
1,810
|
public OperationFuture < CASResponse > asyncCAS ( String key , long casId , Object value ) { return asyncCAS ( key , casId , value , transcoder ) ; }
|
Asynchronous CAS operation using the default transcoder .
|
1,811
|
public CASResponse cas ( String key , long casId , Object value ) { return cas ( key , casId , value , transcoder ) ; }
|
Perform a synchronous CAS operation with the default transcoder .
|
1,812
|
public < T > OperationFuture < Boolean > add ( String key , int exp , T o , Transcoder < T > tc ) { return asyncStore ( StoreType . add , key , exp , o , tc ) ; }
|
Add an object to the cache iff it does not exist already .
|
1,813
|
public < T > GetFuture < T > asyncGet ( final String key , final Transcoder < T > tc ) { final CountDownLatch latch = new CountDownLatch ( 1 ) ; final GetFuture < T > rv = new GetFuture < T > ( latch , operationTimeout , key , executorService ) ; Operation op = opFact . get ( key , new GetOperation . Callback ( ) { private Future < T > val ; public void receivedStatus ( OperationStatus status ) { rv . set ( val , status ) ; } public void gotData ( String k , int flags , byte [ ] data ) { assert key . equals ( k ) : "Wrong key returned" ; val = tcService . decode ( tc , new CachedData ( flags , data , tc . getMaxSize ( ) ) ) ; } public void complete ( ) { latch . countDown ( ) ; rv . signalComplete ( ) ; } } ) ; rv . setOperation ( op ) ; mconn . enqueueOperation ( key , op ) ; return rv ; }
|
Get the given key asynchronously .
|
1,814
|
public < T > CASValue < T > getAndTouch ( String key , int exp , Transcoder < T > tc ) { try { return asyncGetAndTouch ( key , exp , tc ) . get ( operationTimeout , TimeUnit . MILLISECONDS ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( "Interrupted waiting for value" , e ) ; } catch ( ExecutionException e ) { if ( e . getCause ( ) instanceof CancellationException ) { throw ( CancellationException ) e . getCause ( ) ; } else { throw new RuntimeException ( "Exception waiting for value" , e ) ; } } catch ( TimeoutException e ) { throw new OperationTimeoutException ( "Timeout waiting for value" , e ) ; } }
|
Get with a single key and reset its expiration .
|
1,815
|
public CASValue < Object > getAndTouch ( String key , int exp ) { return getAndTouch ( key , exp , transcoder ) ; }
|
Get a single key and reset its expiration using the default transcoder .
|
1,816
|
public < T > T get ( String key , Transcoder < T > tc ) { try { return asyncGet ( key , tc ) . get ( operationTimeout , TimeUnit . MILLISECONDS ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( "Interrupted waiting for value" , e ) ; } catch ( ExecutionException e ) { if ( e . getCause ( ) instanceof CancellationException ) { throw ( CancellationException ) e . getCause ( ) ; } else { throw new RuntimeException ( "Exception waiting for value" , e ) ; } } catch ( TimeoutException e ) { throw new OperationTimeoutException ( "Timeout waiting for value: " + buildTimeoutMessage ( operationTimeout , TimeUnit . MILLISECONDS ) , e ) ; } }
|
Get with a single key .
|
1,817
|
public < T > BulkFuture < Map < String , T > > asyncGetBulk ( Transcoder < T > tc , String ... keys ) { return asyncGetBulk ( Arrays . asList ( keys ) , tc ) ; }
|
Varargs wrapper for asynchronous bulk gets .
|
1,818
|
public BulkFuture < Map < String , Object > > asyncGetBulk ( String ... keys ) { return asyncGetBulk ( Arrays . asList ( keys ) , transcoder ) ; }
|
Varargs wrapper for asynchronous bulk gets with the default transcoder .
|
1,819
|
public OperationFuture < CASValue < Object > > asyncGetAndTouch ( final String key , final int exp ) { return asyncGetAndTouch ( key , exp , transcoder ) ; }
|
Get the given key to reset its expiration time .
|
1,820
|
public Map < SocketAddress , String > getVersions ( ) { final Map < SocketAddress , String > rv = new ConcurrentHashMap < SocketAddress , String > ( ) ; CountDownLatch blatch = broadcastOp ( new BroadcastOpFactory ( ) { public Operation newOp ( final MemcachedNode n , final CountDownLatch latch ) { final SocketAddress sa = n . getSocketAddress ( ) ; return opFact . version ( new OperationCallback ( ) { public void receivedStatus ( OperationStatus s ) { rv . put ( sa , s . getMessage ( ) ) ; } public void complete ( ) { latch . countDown ( ) ; } } ) ; } } ) ; try { blatch . await ( operationTimeout , TimeUnit . MILLISECONDS ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( "Interrupted waiting for versions" , e ) ; } return rv ; }
|
Get the versions of all of the connected memcacheds .
|
1,821
|
public Map < SocketAddress , Map < String , String > > getStats ( final String arg ) { final Map < SocketAddress , Map < String , String > > rv = new HashMap < SocketAddress , Map < String , String > > ( ) ; CountDownLatch blatch = broadcastOp ( new BroadcastOpFactory ( ) { public Operation newOp ( final MemcachedNode n , final CountDownLatch latch ) { final SocketAddress sa = n . getSocketAddress ( ) ; rv . put ( sa , new HashMap < String , String > ( ) ) ; return opFact . stats ( arg , new StatsOperation . Callback ( ) { public void gotStat ( String name , String val ) { rv . get ( sa ) . put ( name , val ) ; } @ SuppressWarnings ( "synthetic-access" ) public void receivedStatus ( OperationStatus status ) { if ( ! status . isSuccess ( ) ) { getLogger ( ) . warn ( "Unsuccessful stat fetch: %s" , status ) ; } } public void complete ( ) { latch . countDown ( ) ; } } ) ; } } ) ; try { blatch . await ( operationTimeout , TimeUnit . MILLISECONDS ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( "Interrupted waiting for stats" , e ) ; } return rv ; }
|
Get a set of stats from all connections .
|
1,822
|
public long incr ( String key , int by ) { return mutate ( Mutator . incr , key , by , 0 , - 1 ) ; }
|
Increment the given key by the given amount .
|
1,823
|
public long decr ( String key , long by ) { return mutate ( Mutator . decr , key , by , 0 , - 1 ) ; }
|
Decrement the given key by the given value .
|
1,824
|
public OperationFuture < Long > asyncDecr ( String key , int by , long def , int exp ) { return asyncMutate ( Mutator . decr , key , by , def , exp ) ; }
|
Asynchronous decrement .
|
1,825
|
public OperationFuture < Long > asyncIncr ( String key , long by , long def ) { return asyncMutate ( Mutator . incr , key , by , def , 0 ) ; }
|
Asychronous increment .
|
1,826
|
public long incr ( String key , long by , long def ) { return mutateWithDefault ( Mutator . incr , key , by , def , 0 ) ; }
|
Increment the given counter returning the new value .
|
1,827
|
public OperationFuture < Boolean > delete ( String key , long cas ) { final CountDownLatch latch = new CountDownLatch ( 1 ) ; final OperationFuture < Boolean > rv = new OperationFuture < Boolean > ( key , latch , operationTimeout , executorService ) ; DeleteOperation . Callback callback = new DeleteOperation . Callback ( ) { public void receivedStatus ( OperationStatus s ) { rv . set ( s . isSuccess ( ) , s ) ; } public void gotData ( long cas ) { rv . setCas ( cas ) ; } public void complete ( ) { latch . countDown ( ) ; rv . signalComplete ( ) ; } } ; DeleteOperation op ; if ( cas == 0 ) { op = opFact . delete ( key , callback ) ; } else { op = opFact . delete ( key , cas , callback ) ; } rv . setOperation ( op ) ; mconn . enqueueOperation ( key , op ) ; return rv ; }
|
Delete the given key from the cache of the given CAS value applies .
|
1,828
|
public OperationFuture < Boolean > flush ( final int delay ) { final AtomicReference < Boolean > flushResult = new AtomicReference < Boolean > ( null ) ; final ConcurrentLinkedQueue < Operation > ops = new ConcurrentLinkedQueue < Operation > ( ) ; CountDownLatch blatch = broadcastOp ( new BroadcastOpFactory ( ) { public Operation newOp ( final MemcachedNode n , final CountDownLatch latch ) { Operation op = opFact . flush ( delay , new OperationCallback ( ) { public void receivedStatus ( OperationStatus s ) { flushResult . set ( s . isSuccess ( ) ) ; } public void complete ( ) { latch . countDown ( ) ; } } ) ; ops . add ( op ) ; return op ; } } ) ; return new OperationFuture < Boolean > ( null , blatch , flushResult , operationTimeout , executorService ) { public void set ( Boolean o , OperationStatus s ) { super . set ( o , s ) ; notifyListeners ( ) ; } public boolean cancel ( boolean ign ) { boolean rv = false ; for ( Operation op : ops ) { op . cancel ( ) ; rv |= op . getState ( ) == OperationState . WRITE_QUEUED ; } notifyListeners ( ) ; return rv ; } public Boolean get ( long duration , TimeUnit units ) throws InterruptedException , TimeoutException , ExecutionException { status = new OperationStatus ( true , "OK" , StatusCode . SUCCESS ) ; return super . get ( duration , units ) ; } public boolean isCancelled ( ) { boolean rv = false ; for ( Operation op : ops ) { rv |= op . isCancelled ( ) ; } return rv ; } public boolean isDone ( ) { boolean rv = true ; for ( Operation op : ops ) { rv &= op . getState ( ) == OperationState . COMPLETE ; } return rv || isCancelled ( ) ; } } ; }
|
Flush all caches from all servers with a delay of application .
|
1,829
|
public boolean waitForQueues ( long timeout , TimeUnit unit ) { CountDownLatch blatch = broadcastOp ( new BroadcastOpFactory ( ) { public Operation newOp ( final MemcachedNode n , final CountDownLatch latch ) { return opFact . noop ( new OperationCallback ( ) { public void complete ( ) { latch . countDown ( ) ; } public void receivedStatus ( OperationStatus s ) { } } ) ; } } , mconn . getLocator ( ) . getAll ( ) , false ) ; try { return blatch . await ( timeout , unit ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( "Interrupted waiting for queues" , e ) ; } }
|
Wait for the queues to die down .
|
1,830
|
public ConnectionFactoryBuilder setProtocol ( Protocol prot ) { switch ( prot ) { case TEXT : opFact = new AsciiOperationFactory ( ) ; break ; case BINARY : opFact = new BinaryOperationFactory ( ) ; break ; default : assert false : "Unhandled protocol: " + prot ; } return this ; }
|
Convenience method to specify the protocol to use .
|
1,831
|
public T cas ( final String key , final T initial , int initialExp , final CASMutation < T > m ) throws Exception { T rv = initial ; boolean done = false ; for ( int i = 0 ; ! done && i < max ; i ++ ) { CASValue < T > casval = client . gets ( key , transcoder ) ; T current = null ; if ( casval != null ) { T tmp = casval . getValue ( ) ; current = tmp ; } if ( current != null ) { assert casval != null : "casval was null with a current value" ; rv = m . getNewValue ( current ) ; if ( client . cas ( key , casval . getCas ( ) , initialExp , rv , transcoder ) == CASResponse . OK ) { done = true ; } } else { if ( initial == null ) { done = true ; rv = null ; } else if ( client . add ( key , initialExp , initial , transcoder ) . get ( ) ) { done = true ; rv = initial ; } } } if ( ! done ) { throw new RuntimeException ( "Couldn't get a CAS in " + max + " attempts" ) ; } return rv ; }
|
CAS a new value in for a key .
|
1,832
|
public void run ( ) { try { barrier . await ( ) ; rv = callable . call ( ) ; } catch ( Throwable t ) { throwable = t ; } latch . countDown ( ) ; }
|
Wait for the barrier invoke the callable and capture the result or an exception .
|
1,833
|
public static < T > Collection < SyncThread < T > > getCompletedThreads ( int num , Callable < T > callable ) throws InterruptedException { Collection < SyncThread < T > > rv = new ArrayList < SyncThread < T > > ( num ) ; CyclicBarrier barrier = new CyclicBarrier ( num ) ; for ( int i = 0 ; i < num ; i ++ ) { rv . add ( new SyncThread < T > ( barrier , callable ) ) ; } for ( SyncThread < T > t : rv ) { t . join ( ) ; } return rv ; }
|
Get a collection of SyncThreads that all began as close to the same time as possible and have all completed .
|
1,834
|
public static < T > int getDistinctResultCount ( int num , Callable < T > callable ) throws Throwable { IdentityHashMap < T , Object > found = new IdentityHashMap < T , Object > ( ) ; Collection < SyncThread < T > > threads = getCompletedThreads ( num , callable ) ; for ( SyncThread < T > s : threads ) { found . put ( s . getResult ( ) , new Object ( ) ) ; } return found . size ( ) ; }
|
Get the distinct result count for the given callable at the given concurrency .
|
1,835
|
public void log ( Level level , Object message , Throwable e ) { org . apache . log4j . Level pLevel = org . apache . log4j . Level . DEBUG ; switch ( level == null ? Level . FATAL : level ) { case TRACE : pLevel = org . apache . log4j . Level . TRACE ; break ; case DEBUG : pLevel = org . apache . log4j . Level . DEBUG ; break ; case INFO : pLevel = org . apache . log4j . Level . INFO ; break ; case WARN : pLevel = org . apache . log4j . Level . WARN ; break ; case ERROR : pLevel = org . apache . log4j . Level . ERROR ; break ; case FATAL : pLevel = org . apache . log4j . Level . FATAL ; break ; default : pLevel = org . apache . log4j . Level . FATAL ; l4jLogger . log ( "net.spy.compat.log.AbstractLogger" , pLevel , "Unhandled " + "log level: " + level + " for the following message" , null ) ; } l4jLogger . log ( "net.spy.compat.log.AbstractLogger" , pLevel , message , e ) ; }
|
Wrapper around log4j .
|
1,836
|
protected String decodeString ( byte [ ] data ) { String rv = null ; try { if ( data != null ) { rv = new String ( data , charset ) ; } } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } return rv ; }
|
Decode the string with the current character set .
|
1,837
|
public < T > Future < ? > loadData ( Iterator < Map . Entry < String , T > > i ) { Future < Boolean > mostRecent = null ; while ( i . hasNext ( ) ) { Map . Entry < String , T > e = i . next ( ) ; mostRecent = push ( e . getKey ( ) , e . getValue ( ) ) ; watch ( e . getKey ( ) , mostRecent ) ; } return mostRecent == null ? new ImmediateFuture ( true ) : mostRecent ; }
|
Load data from the given iterator .
|
1,838
|
public < T > Future < ? > loadData ( Map < String , T > map ) { return loadData ( map . entrySet ( ) . iterator ( ) ) ; }
|
Load data from the given map .
|
1,839
|
public < T > Future < Boolean > push ( String k , T value ) { Future < Boolean > rv = null ; while ( rv == null ) { try { rv = client . set ( k , expiration , value ) ; } catch ( IllegalStateException ex ) { try { if ( rv != null ) { rv . get ( 250 , TimeUnit . MILLISECONDS ) ; } else { Thread . sleep ( 250 ) ; } } catch ( InterruptedException ie ) { Thread . currentThread ( ) . interrupt ( ) ; } catch ( Exception e2 ) { } } } return rv ; }
|
Push a value into the cache .
|
1,840
|
public void log ( Level level , Object message , Throwable e ) { java . util . logging . Level sLevel = java . util . logging . Level . SEVERE ; switch ( level == null ? Level . FATAL : level ) { case TRACE : sLevel = java . util . logging . Level . FINEST ; break ; case DEBUG : sLevel = java . util . logging . Level . FINE ; break ; case INFO : sLevel = java . util . logging . Level . INFO ; break ; case WARN : sLevel = java . util . logging . Level . WARNING ; break ; case ERROR : sLevel = java . util . logging . Level . SEVERE ; break ; case FATAL : sLevel = java . util . logging . Level . SEVERE ; break ; default : sLevel = java . util . logging . Level . SEVERE ; sunLogger . log ( sLevel , "Unhandled log level: " + level + " for the following message" ) ; } Throwable t = new Throwable ( ) ; StackTraceElement [ ] ste = t . getStackTrace ( ) ; StackTraceElement logRequestor = null ; String alclass = AbstractLogger . class . getName ( ) ; for ( int i = 0 ; i < ste . length && logRequestor == null ; i ++ ) { if ( ste [ i ] . getClassName ( ) . equals ( alclass ) ) { if ( i + 1 < ste . length ) { logRequestor = ste [ i + 1 ] ; if ( logRequestor . getClassName ( ) . equals ( alclass ) ) { logRequestor = null ; } } } } if ( logRequestor != null ) { if ( e != null ) { sunLogger . logp ( sLevel , logRequestor . getClassName ( ) , logRequestor . getMethodName ( ) , message . toString ( ) , e ) ; } else { sunLogger . logp ( sLevel , logRequestor . getClassName ( ) , logRequestor . getMethodName ( ) , message . toString ( ) ) ; } } else { if ( e != null ) { sunLogger . log ( sLevel , message . toString ( ) , e ) ; } else { sunLogger . log ( sLevel , message . toString ( ) ) ; } } }
|
Wrapper around sun logger .
|
1,841
|
public static String join ( final Collection < String > chunks , final String delimiter ) { StringBuilder sb = new StringBuilder ( ) ; if ( ! chunks . isEmpty ( ) ) { Iterator < String > itr = chunks . iterator ( ) ; sb . append ( itr . next ( ) ) ; while ( itr . hasNext ( ) ) { sb . append ( delimiter ) ; sb . append ( itr . next ( ) ) ; } } return sb . toString ( ) ; }
|
Join a collection of strings together into one .
|
1,842
|
public static boolean isJsonObject ( final String s ) { if ( s == null || s . isEmpty ( ) ) { return false ; } if ( s . startsWith ( "{" ) || s . startsWith ( "[" ) || "true" . equals ( s ) || "false" . equals ( s ) || "null" . equals ( s ) || decimalPattern . matcher ( s ) . matches ( ) ) { return true ; } return false ; }
|
Check if a given string is a JSON object .
|
1,843
|
public static void validateKey ( final String key , final boolean binary ) { byte [ ] keyBytes = KeyUtil . getKeyBytes ( key ) ; int keyLength = keyBytes . length ; if ( keyLength > MAX_KEY_LENGTH ) { throw KEY_TOO_LONG_EXCEPTION ; } if ( keyLength == 0 ) { throw KEY_EMPTY_EXCEPTION ; } if ( ! binary ) { for ( byte b : keyBytes ) { if ( b == ' ' || b == '\n' || b == '\r' || b == 0 ) { throw new IllegalArgumentException ( "Key contains invalid characters: ``" + key + "''" ) ; } } } }
|
Check if a given key is valid to transmit .
|
1,844
|
public String getKeyForNode ( MemcachedNode node , int repetition ) { String nodeKey = nodeKeys . get ( node ) ; if ( nodeKey == null ) { switch ( this . format ) { case LIBMEMCACHED : InetSocketAddress address = ( InetSocketAddress ) node . getSocketAddress ( ) ; nodeKey = address . getHostName ( ) ; if ( address . getPort ( ) != 11211 ) { nodeKey += ":" + address . getPort ( ) ; } break ; case SPYMEMCACHED : nodeKey = String . valueOf ( node . getSocketAddress ( ) ) ; if ( nodeKey . startsWith ( "/" ) ) { nodeKey = nodeKey . substring ( 1 ) ; } break ; default : assert false ; } nodeKeys . put ( node , nodeKey ) ; } return nodeKey + "-" + repetition ; }
|
Returns a uniquely identifying key suitable for hashing by the KetamaNodeLocator algorithm .
|
1,845
|
protected final OperationStatus matchStatus ( String line , OperationStatus ... statii ) { OperationStatus rv = null ; for ( OperationStatus status : statii ) { if ( line . equals ( status . getMessage ( ) ) ) { rv = status ; } } if ( rv == null ) { rv = new OperationStatus ( false , line , StatusCode . fromAsciiLine ( line ) ) ; } return rv ; }
|
Match the status line provided against one of the given OperationStatus objects . If none match return a failure status with the given line .
|
1,846
|
protected final void setArguments ( ByteBuffer bb , Object ... args ) { boolean wasFirst = true ; for ( Object o : args ) { if ( wasFirst ) { wasFirst = false ; } else { bb . put ( ( byte ) ' ' ) ; } bb . put ( KeyUtil . getKeyBytes ( String . valueOf ( o ) ) ) ; } bb . put ( CRLF ) ; }
|
Set some arguments for an operation into the given byte buffer .
|
1,847
|
private Animator preparePressedAnimation ( ) { Animator animation = ObjectAnimator . ofFloat ( drawable , CircularProgressDrawable . CIRCLE_SCALE_PROPERTY , drawable . getCircleScale ( ) , 0.65f ) ; animation . setDuration ( 120 ) ; return animation ; }
|
This animation was intended to keep a pressed state of the Drawable
|
1,848
|
private Animator preparePulseAnimation ( ) { AnimatorSet animation = new AnimatorSet ( ) ; Animator firstBounce = ObjectAnimator . ofFloat ( drawable , CircularProgressDrawable . CIRCLE_SCALE_PROPERTY , drawable . getCircleScale ( ) , 0.88f ) ; firstBounce . setDuration ( 300 ) ; firstBounce . setInterpolator ( new CycleInterpolator ( 1 ) ) ; Animator secondBounce = ObjectAnimator . ofFloat ( drawable , CircularProgressDrawable . CIRCLE_SCALE_PROPERTY , 0.75f , 0.83f ) ; secondBounce . setDuration ( 300 ) ; secondBounce . setInterpolator ( new CycleInterpolator ( 1 ) ) ; Animator thirdBounce = ObjectAnimator . ofFloat ( drawable , CircularProgressDrawable . CIRCLE_SCALE_PROPERTY , 0.75f , 0.80f ) ; thirdBounce . setDuration ( 300 ) ; thirdBounce . setInterpolator ( new CycleInterpolator ( 1 ) ) ; animation . playSequentially ( firstBounce , secondBounce , thirdBounce ) ; return animation ; }
|
This animation will make a pulse effect to the inner circle
|
1,849
|
private Animator prepareStyle1Animation ( ) { AnimatorSet animation = new AnimatorSet ( ) ; final Animator indeterminateAnimation = ObjectAnimator . ofFloat ( drawable , CircularProgressDrawable . PROGRESS_PROPERTY , 0 , 3600 ) ; indeterminateAnimation . setDuration ( 3600 ) ; Animator innerCircleAnimation = ObjectAnimator . ofFloat ( drawable , CircularProgressDrawable . CIRCLE_SCALE_PROPERTY , 0f , 0.75f ) ; innerCircleAnimation . setDuration ( 3600 ) ; innerCircleAnimation . addListener ( new AnimatorListenerAdapter ( ) { public void onAnimationStart ( Animator animation ) { drawable . setIndeterminate ( true ) ; } public void onAnimationEnd ( Animator animation ) { indeterminateAnimation . end ( ) ; drawable . setIndeterminate ( false ) ; drawable . setProgress ( 0 ) ; } } ) ; animation . playTogether ( innerCircleAnimation , indeterminateAnimation ) ; return animation ; }
|
Style 1 animation will simulate a indeterminate loading while taking advantage of the inner circle to provide a progress sense
|
1,850
|
private Animator prepareStyle2Animation ( ) { AnimatorSet animation = new AnimatorSet ( ) ; ObjectAnimator progressAnimation = ObjectAnimator . ofFloat ( drawable , CircularProgressDrawable . PROGRESS_PROPERTY , 0f , 1f ) ; progressAnimation . setDuration ( 3600 ) ; progressAnimation . setInterpolator ( new AccelerateDecelerateInterpolator ( ) ) ; ObjectAnimator colorAnimator = ObjectAnimator . ofInt ( drawable , CircularProgressDrawable . RING_COLOR_PROPERTY , getResources ( ) . getColor ( android . R . color . holo_red_dark ) , getResources ( ) . getColor ( android . R . color . holo_green_light ) ) ; colorAnimator . setEvaluator ( new ArgbEvaluator ( ) ) ; colorAnimator . setDuration ( 3600 ) ; animation . playTogether ( progressAnimation , colorAnimator ) ; return animation ; }
|
Style 2 animation will fill the outer ring while applying a color effect from red to green
|
1,851
|
private int readDefaultLine ( Text str , int maxLineLength , int maxBytesToConsume ) throws IOException { str . clear ( ) ; int txtLength = 0 ; int newlineLength = 0 ; boolean prevCharCR = false ; long bytesConsumed = 0 ; do { int startPosn = bufferPosn ; if ( bufferPosn >= bufferLength ) { startPosn = bufferPosn = 0 ; if ( prevCharCR ) { ++ bytesConsumed ; } bufferLength = fillBuffer ( in , buffer , prevCharCR ) ; if ( bufferLength <= 0 ) { break ; } } for ( ; bufferPosn < bufferLength ; ++ bufferPosn ) { if ( buffer [ bufferPosn ] == LF ) { newlineLength = ( prevCharCR ) ? 2 : 1 ; ++ bufferPosn ; break ; } if ( prevCharCR ) { newlineLength = 1 ; break ; } prevCharCR = ( buffer [ bufferPosn ] == CR ) ; } int readLength = bufferPosn - startPosn ; if ( prevCharCR && newlineLength == 0 ) { -- readLength ; } bytesConsumed += readLength ; int appendLength = readLength - newlineLength ; if ( appendLength > maxLineLength - txtLength ) { appendLength = maxLineLength - txtLength ; if ( appendLength > 0 ) { throw new TextLineLengthLimitExceededException ( "Too many bytes before newline: " + maxLineLength ) ; } } if ( appendLength > 0 ) { int newTxtLength = txtLength + appendLength ; if ( str . getBytes ( ) . length < newTxtLength && Math . max ( newTxtLength , txtLength << 1 ) > MAX_ARRAY_SIZE ) { throw new TextLineLengthLimitExceededException ( "Too many bytes before newline: " + newTxtLength ) ; } str . append ( buffer , startPosn , appendLength ) ; txtLength = newTxtLength ; } } while ( newlineLength == 0 && bytesConsumed < maxBytesToConsume ) ; if ( newlineLength == 0 && bytesConsumed >= maxBytesToConsume ) { throw new TextLineLengthLimitExceededException ( "Too many bytes before newline: " + bytesConsumed ) ; } return ( int ) bytesConsumed ; }
|
Read a line terminated by one of CR LF or CRLF .
|
1,852
|
public void installOrUpdateScanner ( File installDirectory ) throws BlackDuckIntegrationException { File scannerExpansionDirectory = new File ( installDirectory , ScannerZipInstaller . BLACK_DUCK_SIGNATURE_SCANNER_INSTALL_DIRECTORY ) ; scannerExpansionDirectory . mkdirs ( ) ; File versionFile = null ; try { versionFile = retrieveVersionFile ( scannerExpansionDirectory ) ; } catch ( IOException e ) { throw new BlackDuckIntegrationException ( "Trying to install the scanner but could not create the version file: " + e . getMessage ( ) ) ; } String downloadUrl = getDownloadUrl ( ) ; try { downloadIfModified ( scannerExpansionDirectory , versionFile , downloadUrl ) ; } catch ( Exception e ) { throw new BlackDuckIntegrationException ( "The Black Duck Signature Scanner could not be downloaded successfully: " + e . getMessage ( ) ) ; } logger . info ( "The Black Duck Signature Scanner downloaded/found successfully: " + installDirectory . getAbsolutePath ( ) ) ; }
|
The Black Duck Signature Scanner will be download if it has not previously been downloaded or if it has been updated on the server . The absolute path to the install location will be returned if it was downloaded or found successfully otherwise an Optional . empty will be returned and the log will contain details concerning the failure .
|
1,853
|
public List < ScanCommand > createScanCommands ( final File defaultInstallDirectory , final ScanPathsUtility scanPathsUtility , final IntEnvironmentVariables intEnvironmentVariables ) throws BlackDuckIntegrationException { String scanCliOptsToUse = scanCliOpts ; if ( null != intEnvironmentVariables && StringUtils . isBlank ( scanCliOptsToUse ) ) { final String scanCliOptsEnvironment = intEnvironmentVariables . getValue ( "SCAN_CLI_OPTS" ) ; if ( StringUtils . isNotBlank ( scanCliOptsEnvironment ) ) { scanCliOptsToUse = scanCliOptsEnvironment ; } } final boolean commandDryRun = blackDuckUrl == null || dryRun ; final boolean snippetMatching = SnippetMatching . SNIPPET_MATCHING == snippetMatchingMode || SnippetMatching . FULL_SNIPPET_MATCHING == snippetMatchingMode ; final boolean snippetMatchingOnly = SnippetMatching . SNIPPET_MATCHING_ONLY == snippetMatchingMode || SnippetMatching . FULL_SNIPPET_MATCHING_ONLY == snippetMatchingMode ; final boolean fullSnippetScan = SnippetMatching . FULL_SNIPPET_MATCHING == snippetMatchingMode || SnippetMatching . FULL_SNIPPET_MATCHING_ONLY == snippetMatchingMode ; String commandScheme = null ; String commandHost = null ; int commandPort = 0 ; if ( ! commandDryRun ) { commandScheme = blackDuckUrl . getProtocol ( ) ; commandHost = blackDuckUrl . getHost ( ) ; if ( blackDuckUrl . getPort ( ) > 0 ) { commandPort = blackDuckUrl . getPort ( ) ; } else if ( blackDuckUrl . getDefaultPort ( ) > 0 ) { commandPort = blackDuckUrl . getDefaultPort ( ) ; } } final List < ScanCommand > scanCommands = new ArrayList < > ( ) ; for ( final ScanTarget scanTarget : scanTargets ) { File commandOutputDirectory = null ; if ( StringUtils . isNotBlank ( scanTarget . getOutputDirectoryPath ( ) ) ) { if ( scanTarget . isOutputDirectoryPathAbsolute ( ) ) { commandOutputDirectory = new File ( scanTarget . getOutputDirectoryPath ( ) ) ; } else { commandOutputDirectory = new File ( outputDirectory , scanTarget . getOutputDirectoryPath ( ) ) ; } commandOutputDirectory . mkdirs ( ) ; } else { commandOutputDirectory = scanPathsUtility . createSpecificRunOutputDirectory ( outputDirectory ) ; } File installDirectoryForCommand = signatureScannerInstallDirectory ; if ( null == installDirectoryForCommand && null != defaultInstallDirectory ) { installDirectoryForCommand = defaultInstallDirectory ; } final ScanCommand scanCommand = new ScanCommand ( installDirectoryForCommand , commandOutputDirectory , commandDryRun , proxyInfo , scanCliOptsToUse , scanMemoryInMegabytes , commandScheme , commandHost , blackDuckApiToken , blackDuckUsername , blackDuckPassword , commandPort , alwaysTrustServerCertificate , scanTarget . getCodeLocationName ( ) , snippetMatching , snippetMatchingOnly , fullSnippetScan , uploadSource , scanTarget . getExclusionPatterns ( ) , additionalScanArguments , scanTarget . getPath ( ) , verbose , debug , projectName , projectVersionName ) ; scanCommands . add ( scanCommand ) ; } return scanCommands ; }
|
The default install directory will be used if the batch does not already have an install directory .
|
1,854
|
private String createPrintableCommand ( final List < String > cmd ) { final List < String > cmdToOutput = new ArrayList < > ( ) ; cmdToOutput . addAll ( cmd ) ; int passwordIndex = cmdToOutput . indexOf ( "--password" ) ; if ( passwordIndex > - 1 ) { passwordIndex ++ ; } int proxyPasswordIndex = - 1 ; for ( int commandIndex = 0 ; commandIndex < cmdToOutput . size ( ) ; commandIndex ++ ) { final String commandParameter = cmdToOutput . get ( commandIndex ) ; if ( commandParameter . contains ( "-Dhttp.proxyPassword=" ) ) { proxyPasswordIndex = commandIndex ; } } maskIndex ( cmdToOutput , passwordIndex ) ; maskIndex ( cmdToOutput , proxyPasswordIndex ) ; return StringUtils . join ( cmdToOutput , " " ) ; }
|
Code to mask passwords in the logs
|
1,855
|
public void populateApplicationId ( ProjectView projectView , String applicationId ) throws IntegrationException { List < ProjectMappingView > projectMappings = blackDuckService . getAllResponses ( projectView , ProjectView . PROJECT_MAPPINGS_LINK_RESPONSE ) ; boolean canCreate = projectMappings . isEmpty ( ) ; if ( canCreate ) { if ( ! projectView . hasLink ( ProjectView . PROJECT_MAPPINGS_LINK ) ) { throw new BlackDuckIntegrationException ( String . format ( "The supplied projectView does not have the link (%s) to create a project mapping." , ProjectView . PROJECT_MAPPINGS_LINK ) ) ; } String projectMappingsLink = projectView . getFirstLink ( ProjectView . PROJECT_MAPPINGS_LINK ) . get ( ) ; ProjectMappingView projectMappingView = new ProjectMappingView ( ) ; projectMappingView . setApplicationId ( applicationId ) ; blackDuckService . post ( projectMappingsLink , projectMappingView ) ; } else { ProjectMappingView projectMappingView = projectMappings . get ( 0 ) ; projectMappingView . setApplicationId ( applicationId ) ; blackDuckService . put ( projectMappingView ) ; } }
|
Sets the applicationId for a project
|
1,856
|
public String generateBlackDuckNoticesReport ( ProjectVersionView version , ReportFormatType reportFormat ) throws InterruptedException , IntegrationException { if ( version . hasLink ( ProjectVersionView . LICENSEREPORTS_LINK ) ) { try { logger . debug ( "Starting the Notices Report generation." ) ; String reportUrl = startGeneratingBlackDuckNoticesReport ( version , reportFormat ) ; logger . debug ( "Waiting for the Notices Report to complete." ) ; ReportView reportInfo = isReportFinishedGenerating ( reportUrl ) ; String contentLink = reportInfo . getFirstLink ( ReportView . CONTENT_LINK ) . orElse ( null ) ; if ( contentLink == null ) { throw new BlackDuckIntegrationException ( "Could not find content link for the report at : " + reportUrl ) ; } logger . debug ( "Getting the Notices Report content." ) ; String noticesReport = getNoticesReportContent ( contentLink ) ; logger . debug ( "Finished retrieving the Notices Report." ) ; logger . debug ( "Cleaning up the Notices Report on the server." ) ; deleteBlackDuckReport ( reportUrl ) ; return noticesReport ; } catch ( IntegrationRestException e ) { if ( e . getHttpStatusCode ( ) == 402 ) { logger . warn ( "Can not create the notice report, the Black Duck notice module is not enabled." ) ; } else { throw e ; } } } else { logger . warn ( "Can not create the notice report, the Black Duck notice module is not enabled." ) ; } return null ; }
|
Assumes the BOM has already been updated
|
1,857
|
public ReportView isReportFinishedGenerating ( String reportUri ) throws InterruptedException , IntegrationException { long startTime = System . currentTimeMillis ( ) ; long elapsedTime = 0 ; Date timeFinished = null ; ReportView reportInfo = null ; while ( timeFinished == null ) { reportInfo = blackDuckService . getResponse ( reportUri , ReportView . class ) ; timeFinished = reportInfo . getFinishedAt ( ) ; if ( timeFinished != null ) { break ; } if ( elapsedTime >= timeoutInMilliseconds ) { String formattedTime = String . format ( "%d minutes" , TimeUnit . MILLISECONDS . toMinutes ( timeoutInMilliseconds ) ) ; throw new BlackDuckIntegrationException ( "The Report has not finished generating in : " + formattedTime ) ; } Thread . sleep ( 5000 ) ; elapsedTime = System . currentTimeMillis ( ) - startTime ; } return reportInfo ; }
|
Checks the report URL every 5 seconds until the report has a finished time available then we know it is done being generated . Throws BlackDuckIntegrationException after 30 minutes if the report has not been generated yet .
|
1,858
|
public Set < UserView > getAllActiveUsersForProject ( ProjectView projectView ) throws IntegrationException { Set < UserView > users = new HashSet < > ( ) ; List < AssignedUserGroupView > assignedGroups = getAssignedGroupsToProject ( projectView ) ; for ( AssignedUserGroupView assignedUserGroupView : assignedGroups ) { if ( assignedUserGroupView . getActive ( ) ) { UserGroupView userGroupView = blackDuckService . getResponse ( assignedUserGroupView . getGroup ( ) , UserGroupView . class ) ; if ( userGroupView . getActive ( ) ) { List < UserView > groupUsers = blackDuckService . getAllResponses ( userGroupView , UserGroupView . USERS_LINK_RESPONSE ) ; users . addAll ( groupUsers ) ; } } } List < AssignedUserView > assignedUsers = getAssignedUsersToProject ( projectView ) ; for ( AssignedUserView assignedUser : assignedUsers ) { UserView userView = blackDuckService . getResponse ( assignedUser . getUser ( ) , UserView . class ) ; users . add ( userView ) ; } return users . stream ( ) . filter ( userView -> userView . getActive ( ) ) . collect ( Collectors . toSet ( ) ) ; }
|
This will get all explicitly assigned users for a project as well as all users who are assigned to groups that are explicitly assigned to a project .
|
1,859
|
public String createPolicyRuleForExternalId ( ComponentService componentService , ExternalId externalId , String policyName ) throws IntegrationException { Optional < ComponentVersionView > componentVersionView = componentService . getComponentVersion ( externalId ) ; if ( ! componentVersionView . isPresent ( ) ) { throw new BlackDuckIntegrationException ( String . format ( "The external id (%s) provided could not be found, so no policy can be created for it." , externalId . createExternalId ( ) ) ) ; } PolicyRuleExpressionSetBuilder builder = new PolicyRuleExpressionSetBuilder ( ) ; builder . addComponentVersionCondition ( PolicyRuleConditionOperatorType . EQ , componentVersionView . get ( ) ) ; PolicyRuleExpressionSetView expressionSet = builder . createPolicyRuleExpressionSetView ( ) ; PolicyRuleView policyRuleView = new PolicyRuleView ( ) ; policyRuleView . setName ( policyName ) ; policyRuleView . setEnabled ( true ) ; policyRuleView . setOverridable ( true ) ; policyRuleView . setExpression ( expressionSet ) ; return createPolicyRule ( policyRuleView ) ; }
|
This will create a policy rule that will be violated by the existence of a matching external id in the project s BOM .
|
1,860
|
public static void kill ( final long pid ) throws IOException , InterruptedException { if ( isUnix ( ) ) { final Process process = new ProcessBuilder ( ) . command ( "bash" , "-c" , "kill" , "-9" , String . valueOf ( pid ) ) . start ( ) ; final int returnCode = process . waitFor ( ) ; LOG . fine ( "Kill returned: " + returnCode ) ; } else if ( isWindows ( ) ) { final Process process = new ProcessBuilder ( ) . command ( "taskkill.exe" , "/f" , "/pid" , String . valueOf ( pid ) ) . start ( ) ; final int returnCode = process . waitFor ( ) ; LOG . fine ( "Kill returned: " + returnCode ) ; } else { throw new UnsupportedOperationException ( "Unable to execute kill on unknown OS" ) ; } }
|
Kill the process .
|
1,861
|
@ SuppressWarnings ( "checkstyle:hiddenfield" ) public < T , U extends T > void register ( final Class < T > type , final Set < EventHandler < U > > handlers ) { this . handlers . put ( type , new ExceptionHandlingEventHandler < > ( new BroadCastEventHandler < > ( handlers ) , this . errorHandler ) ) ; }
|
Register a new event handler .
|
1,862
|
@ SuppressWarnings ( "unchecked" ) public < T , U extends T > void onNext ( final Class < T > type , final U message ) { if ( this . isClosed ( ) ) { LOG . log ( Level . WARNING , "Dispatcher {0} already closed: ignoring message {1}: {2}" , new Object [ ] { this . stage , type . getCanonicalName ( ) , message } ) ; } else { final EventHandler < T > handler = ( EventHandler < T > ) this . handlers . get ( type ) ; this . stage . onNext ( new DelayedOnNext ( handler , message ) ) ; } }
|
Dispatch a new message by type . If the stage is already closed log a warning and ignore the message .
|
1,863
|
public InetSocketAddress lookup ( final Identifier id ) throws Exception { return cache . get ( id , new Callable < InetSocketAddress > ( ) { public InetSocketAddress call ( ) throws Exception { final int origRetryCount = NameLookupClient . this . retryCount ; int retriesLeft = origRetryCount ; while ( true ) { try { return remoteLookup ( id ) ; } catch ( final NamingException e ) { if ( retriesLeft <= 0 ) { throw e ; } else { final int currentRetryTimeout = NameLookupClient . this . retryTimeout * ( origRetryCount - retriesLeft + 1 ) ; LOG . log ( Level . WARNING , "Caught Naming Exception while looking up " + id + " with Name Server. Will retry " + retriesLeft + " time(s) after waiting for " + currentRetryTimeout + " msec." ) ; Thread . sleep ( currentRetryTimeout ) ; -- retriesLeft ; } } } } } ) ; }
|
Finds an address for an identifier .
|
1,864
|
public InetSocketAddress remoteLookup ( final Identifier id ) throws Exception { synchronized ( this ) { LOG . log ( Level . INFO , "Looking up {0} on NameServer {1}" , new Object [ ] { id , serverSocketAddr } ) ; final List < Identifier > ids = Arrays . asList ( id ) ; final Link < NamingMessage > link = transport . open ( serverSocketAddr , codec , new LoggingLinkListener < NamingMessage > ( ) ) ; link . write ( new NamingLookupRequest ( ids ) ) ; final NamingLookupResponse resp ; for ( ; ; ) { try { resp = replyQueue . poll ( timeout , TimeUnit . MILLISECONDS ) ; break ; } catch ( final InterruptedException e ) { LOG . log ( Level . INFO , "Lookup interrupted" , e ) ; throw new NamingException ( e ) ; } } final List < NameAssignment > list = resp == null ? Collections . < NameAssignment > emptyList ( ) : resp . getNameAssignments ( ) ; if ( list . isEmpty ( ) ) { throw new NamingException ( "Cannot find " + id + " from the name server" ) ; } else { return list . get ( 0 ) . getAddress ( ) ; } } }
|
Retrieves an address for an identifier remotely .
|
1,865
|
public void scheduleTasklet ( final int taskletId ) { synchronized ( stateLock ) { if ( ! outstandingTasklets ( ) ) { timer . schedule ( new Runnable ( ) { public void run ( ) { aggregateTasklets ( AggregateTriggerType . ALARM ) ; synchronized ( stateLock ) { if ( outstandingTasklets ( ) ) { timer . schedule ( this , taskletAggregationRequest . getPolicy ( ) . getPeriodMilliseconds ( ) , TimeUnit . MILLISECONDS ) ; } } } } , taskletAggregationRequest . getPolicy ( ) . getPeriodMilliseconds ( ) , TimeUnit . MILLISECONDS ) ; } if ( ! pendingTasklets . containsKey ( taskletId ) ) { pendingTasklets . put ( taskletId , 0 ) ; } pendingTasklets . put ( taskletId , pendingTasklets . get ( taskletId ) + 1 ) ; } }
|
Schedule aggregation tasks on a Timer . Creates a new timer schedule for triggering the aggregation function if this is the first time the aggregation function has tasklets scheduled on it . Adds the Tasklet to pending Tasklets .
|
1,866
|
public void taskletComplete ( final int taskletId , final Object result ) { final boolean aggregateOnCount ; synchronized ( stateLock ) { completedTasklets . add ( new ImmutablePair < > ( taskletId , result ) ) ; removePendingTaskletReferenceCount ( taskletId ) ; aggregateOnCount = aggregateOnCount ( ) ; } if ( aggregateOnCount ) { aggregateTasklets ( AggregateTriggerType . COUNT ) ; } }
|
Reported when an associated tasklet is complete and adds it to the completion pool .
|
1,867
|
public void taskletFailed ( final int taskletId , final Exception e ) { final boolean aggregateOnCount ; synchronized ( stateLock ) { failedTasklets . add ( new ImmutablePair < > ( taskletId , e ) ) ; removePendingTaskletReferenceCount ( taskletId ) ; aggregateOnCount = aggregateOnCount ( ) ; } if ( aggregateOnCount ) { aggregateTasklets ( AggregateTriggerType . COUNT ) ; } }
|
Reported when an associated tasklet is complete and adds it to the failure pool .
|
1,868
|
public void onNext ( final Integer integer ) { while ( ! runningWorkers . isTerminated ( ) ) { try { final Tasklet tasklet = pendingTasklets . takeFirst ( ) ; runningWorkers . launchTasklet ( tasklet ) ; } catch ( InterruptedException e ) { LOG . log ( Level . INFO , "Interrupted upon termination" ) ; } } }
|
Repeatedly take a tasklet from the pending queue and launch it via RunningWorkers .
|
1,869
|
private String getQueue ( final JobSubmissionEvent jobSubmissionEvent ) { try { return Tang . Factory . getTang ( ) . newInjector ( jobSubmissionEvent . getConfiguration ( ) ) . getNamedInstance ( JobQueue . class ) ; } catch ( final InjectionException e ) { return this . defaultQueueName ; } }
|
Extract the queue name from the jobSubmissionEvent or return default if none is set .
|
1,870
|
public void onNext ( final ResourceStatusEvent resourceStatusEvent ) { final String id = resourceStatusEvent . getIdentifier ( ) ; final Optional < EvaluatorManager > evaluatorManager = this . evaluators . get ( id ) ; LOG . log ( Level . FINEST , "Evaluator {0} status: {1}" , new Object [ ] { evaluatorManager , resourceStatusEvent . getState ( ) } ) ; if ( evaluatorManager . isPresent ( ) ) { final EvaluatorManager evaluatorManagerImpl = evaluatorManager . get ( ) ; evaluatorManagerImpl . onResourceStatusMessage ( resourceStatusEvent ) ; if ( evaluatorManagerImpl . isClosed ( ) ) { this . evaluators . removeClosedEvaluator ( evaluatorManagerImpl ) ; } } else { if ( this . evaluators . wasClosed ( id ) ) { LOG . log ( Level . WARNING , "Unexpected resource status from closed evaluator {0} with state {1}" , new Object [ ] { id , resourceStatusEvent . getState ( ) } ) ; } if ( driverRestartManager . get ( ) . getEvaluatorRestartState ( id ) . isFailedOrExpired ( ) ) { final EvaluatorManager previousEvaluatorManager = this . evaluatorManagerFactory . getNewEvaluatorManagerForEvaluatorFailedDuringDriverRestart ( resourceStatusEvent ) ; previousEvaluatorManager . onResourceStatusMessage ( resourceStatusEvent ) ; } else { throw new RuntimeException ( "Unknown resource status from evaluator " + id + " with state " + resourceStatusEvent . getState ( ) ) ; } } }
|
This resource status message comes from the ResourceManager layer telling me what it thinks about the state of the resource executing an Evaluator . This method simply passes the message off to the referenced EvaluatorManager
|
1,871
|
public byte [ ] encode ( final NamingLookupResponse obj ) { final List < AvroNamingAssignment > assignments = new ArrayList < > ( obj . getNameAssignments ( ) . size ( ) ) ; for ( final NameAssignment nameAssignment : obj . getNameAssignments ( ) ) { assignments . add ( AvroNamingAssignment . newBuilder ( ) . setId ( nameAssignment . getIdentifier ( ) . toString ( ) ) . setHost ( nameAssignment . getAddress ( ) . getHostName ( ) ) . setPort ( nameAssignment . getAddress ( ) . getPort ( ) ) . build ( ) ) ; } return AvroUtils . toBytes ( AvroNamingLookupResponse . newBuilder ( ) . setTuples ( assignments ) . build ( ) , AvroNamingLookupResponse . class ) ; }
|
Encodes name assignments to bytes .
|
1,872
|
public NamingLookupResponse decode ( final byte [ ] buf ) { final AvroNamingLookupResponse avroResponse = AvroUtils . fromBytes ( buf , AvroNamingLookupResponse . class ) ; final List < NameAssignment > nas = new ArrayList < > ( avroResponse . getTuples ( ) . size ( ) ) ; for ( final AvroNamingAssignment tuple : avroResponse . getTuples ( ) ) { nas . add ( new NameAssignmentTuple ( factory . getNewInstance ( tuple . getId ( ) . toString ( ) ) , new InetSocketAddress ( tuple . getHost ( ) . toString ( ) , tuple . getPort ( ) ) ) ) ; } return new NamingLookupResponse ( nas ) ; }
|
Decodes bytes to an iterable of name assignments .
|
1,873
|
public List < MonitorInfo > getMonitorLockedElements ( final ThreadInfo threadInfo , final StackTraceElement stackTraceElement ) { final Map < StackTraceElement , List < MonitorInfo > > elementMap = monitorLockedElements . get ( threadInfo ) ; if ( null == elementMap ) { return Collections . EMPTY_LIST ; } final List < MonitorInfo > monitorList = elementMap . get ( stackTraceElement ) ; if ( null == monitorList ) { return Collections . EMPTY_LIST ; } return monitorList ; }
|
Get a list of monitor locks that were acquired by this thread at this stack element .
|
1,874
|
public String getWaitingLockString ( final ThreadInfo threadInfo ) { if ( null == threadInfo . getLockInfo ( ) ) { return null ; } else { return threadInfo . getLockName ( ) + " held by " + threadInfo . getLockOwnerName ( ) ; } }
|
Get a string identifying the lock that this thread is waiting on .
|
1,875
|
private static void storeCommandLineArgs ( final Configuration commandLineConf ) throws InjectionException { final Injector injector = Tang . Factory . getTang ( ) . newInjector ( commandLineConf ) ; local = injector . getNamedInstance ( Local . class ) ; dimensions = injector . getNamedInstance ( ModelDimensions . class ) ; numberOfReceivers = injector . getNamedInstance ( NumberOfReceivers . class ) ; }
|
copy the parameters from the command line required for the Client configuration .
|
1,876
|
public byte [ ] encode ( final T obj ) { final Encoder < T > encoder = ( Encoder < T > ) clazzToEncoderMap . get ( obj . getClass ( ) ) ; if ( encoder == null ) { throw new RemoteRuntimeException ( "Encoder for " + obj . getClass ( ) + " not known." ) ; } final WakeTuplePBuf . Builder tupleBuilder = WakeTuplePBuf . newBuilder ( ) ; tupleBuilder . setClassName ( obj . getClass ( ) . getName ( ) ) ; tupleBuilder . setData ( ByteString . copyFrom ( encoder . encode ( obj ) ) ) ; return tupleBuilder . build ( ) . toByteArray ( ) ; }
|
Encodes an object to a byte array .
|
1,877
|
public byte [ ] encode ( final NamingUnregisterRequest obj ) { final AvroNamingUnRegisterRequest result = AvroNamingUnRegisterRequest . newBuilder ( ) . setId ( obj . getIdentifier ( ) . toString ( ) ) . build ( ) ; return AvroUtils . toBytes ( result , AvroNamingUnRegisterRequest . class ) ; }
|
Encodes the naming un - registration request to bytes .
|
1,878
|
public NamingUnregisterRequest decode ( final byte [ ] buf ) { final AvroNamingUnRegisterRequest result = AvroUtils . fromBytes ( buf , AvroNamingUnRegisterRequest . class ) ; return new NamingUnregisterRequest ( factory . getNewInstance ( result . getId ( ) . toString ( ) ) ) ; }
|
Decodes the bytes to a naming un - registration request .
|
1,879
|
public synchronized void sendTaskStatus ( final ReefServiceProtos . TaskStatusProto taskStatusProto ) { this . sendHeartBeat ( this . getEvaluatorHeartbeatProto ( this . evaluatorRuntime . get ( ) . getEvaluatorStatus ( ) , this . contextManager . get ( ) . getContextStatusCollection ( ) , Optional . of ( taskStatusProto ) ) ) ; }
|
Called with a specific TaskStatus that must be delivered to the driver .
|
1,880
|
public synchronized void sendContextStatus ( final ReefServiceProtos . ContextStatusProto contextStatusProto ) { final Collection < ReefServiceProtos . ContextStatusProto > contextStatusList = new ArrayList < > ( ) ; contextStatusList . add ( contextStatusProto ) ; contextStatusList . addAll ( this . contextManager . get ( ) . getContextStatusCollection ( ) ) ; final EvaluatorRuntimeProtocol . EvaluatorHeartbeatProto heartbeatProto = this . getEvaluatorHeartbeatProto ( this . evaluatorRuntime . get ( ) . getEvaluatorStatus ( ) , contextStatusList , Optional . < ReefServiceProtos . TaskStatusProto > empty ( ) ) ; this . sendHeartBeat ( heartbeatProto ) ; }
|
Called with a specific ContextStatus that must be delivered to the driver .
|
1,881
|
public synchronized void sendEvaluatorStatus ( final ReefServiceProtos . EvaluatorStatusProto evaluatorStatusProto ) { this . sendHeartBeat ( EvaluatorRuntimeProtocol . EvaluatorHeartbeatProto . newBuilder ( ) . setTimestamp ( System . currentTimeMillis ( ) ) . setEvaluatorStatus ( evaluatorStatusProto ) . build ( ) ) ; }
|
Called with a specific EvaluatorStatus that must be delivered to the driver .
|
1,882
|
private synchronized void sendHeartBeat ( final EvaluatorRuntimeProtocol . EvaluatorHeartbeatProto heartbeatProto ) { if ( LOG . isLoggable ( Level . FINEST ) ) { LOG . log ( Level . FINEST , "Heartbeat message:\n" + heartbeatProto , new Exception ( "Stack trace" ) ) ; } this . evaluatorHeartbeatHandler . onNext ( heartbeatProto ) ; }
|
Sends the actual heartbeat out and logs it if so desired .
|
1,883
|
private synchronized void initialize ( ) { if ( this . runtimes != null ) { return ; } this . runtimes = new HashMap < > ( ) ; for ( final AvroRuntimeDefinition rd : runtimeDefinition . getRuntimes ( ) ) { try { final Injector rootInjector = Tang . Factory . getTang ( ) . newInjector ( ) ; initializeInjector ( rootInjector ) ; final Configuration runtimeConfig = Tang . Factory . getTang ( ) . newConfigurationBuilder ( ) . bindNamedParameter ( RuntimeName . class , rd . getRuntimeName ( ) . toString ( ) ) . bindImplementation ( Runtime . class , RuntimeImpl . class ) . build ( ) ; final Configuration config = new AvroConfigurationSerializer ( ) . fromString ( rd . getSerializedConfiguration ( ) . toString ( ) ) ; final Injector runtimeInjector = rootInjector . forkInjector ( config , runtimeConfig ) ; this . runtimes . put ( rd . getRuntimeName ( ) . toString ( ) , runtimeInjector . getInstance ( Runtime . class ) ) ; } catch ( final IOException | InjectionException e ) { throw new RuntimeException ( "Unable to initialize runtimes." , e ) ; } } }
|
Initializes the configured runtimes .
|
1,884
|
private void initializeInjector ( final Injector runtimeInjector ) throws InjectionException { copyEventHandler ( runtimeInjector , RuntimeParameters . ResourceStatusHandler . class ) ; copyEventHandler ( runtimeInjector , RuntimeParameters . NodeDescriptorHandler . class ) ; copyEventHandler ( runtimeInjector , RuntimeParameters . ResourceAllocationHandler . class ) ; copyEventHandler ( runtimeInjector , RuntimeParameters . RuntimeStatusHandler . class ) ; try { runtimeInjector . bindVolatileInstance ( HttpServer . class , this . originalInjector . getInstance ( HttpServer . class ) ) ; LOG . log ( Level . INFO , "Binding http server for the runtime implementation" ) ; } catch ( final InjectionException e ) { LOG . log ( Level . INFO , "Http Server is not configured for the runtime" , e ) ; } }
|
Initializes injector by copying needed handlers .
|
1,885
|
private Runtime getRuntime ( final String requestedRuntimeName ) { final String runtimeName = StringUtils . isBlank ( requestedRuntimeName ) ? this . defaultRuntimeName : requestedRuntimeName ; final Runtime runtime = this . runtimes . get ( runtimeName ) ; Validate . notNull ( runtime , "Couldn't find runtime for name " + runtimeName ) ; return runtime ; }
|
Retrieves requested runtime if requested name is empty a default runtime will be used .
|
1,886
|
public void advanceClock ( final int offset ) { this . currentTime += offset ; final Iterator < Alarm > iter = this . alarmList . iterator ( ) ; while ( iter . hasNext ( ) ) { final Alarm alarm = iter . next ( ) ; if ( alarm . getTimestamp ( ) <= this . currentTime ) { alarm . run ( ) ; iter . remove ( ) ; } } }
|
Advances the clock by the offset amount .
|
1,887
|
public byte [ ] call ( final byte [ ] memento ) { LOG . log ( Level . INFO , "RUN: command: {0}" , this . command ) ; final String result = CommandUtils . runCommand ( this . command ) ; LOG . log ( Level . INFO , "RUN: result: {0}" , result ) ; return CODEC . encode ( result ) ; }
|
Execute the shell command and return the result which is sent back to the JobDriver and surfaced in the CompletedTask object .
|
1,888
|
public synchronized void send ( final EvaluatorRuntimeProtocol . EvaluatorControlProto evaluatorControlProto ) { if ( ! this . wrapped . isPresent ( ) ) { throw new IllegalStateException ( "Trying to send an EvaluatorControlProto before the Evaluator ID is set." ) ; } if ( ! this . stateManager . isRunning ( ) ) { LOG . log ( Level . WARNING , "Trying to send an EvaluatorControlProto to Evaluator [{0}] that is in state [{1}], " + "not [RUNNING]. The control message was: {2}" , new Object [ ] { this . evaluatorId , this . stateManager , evaluatorControlProto } ) ; return ; } this . wrapped . get ( ) . onNext ( evaluatorControlProto ) ; }
|
Send the evaluatorControlProto to the Evaluator .
|
1,889
|
synchronized void setRemoteID ( final String evaluatorRID ) { if ( this . wrapped . isPresent ( ) ) { throw new IllegalStateException ( "Trying to reset the evaluator ID. This isn't supported." ) ; } else { LOG . log ( Level . FINE , "Registering remoteId [{0}] for Evaluator [{1}]" , new Object [ ] { evaluatorRID , evaluatorId } ) ; this . wrapped = Optional . of ( remoteManager . getHandler ( evaluatorRID , EvaluatorRuntimeProtocol . EvaluatorControlProto . class ) ) ; } }
|
Set the remote ID used to communicate with this Evaluator .
|
1,890
|
private String convertTime ( final long time ) { final Date date = new Date ( time ) ; return FORMAT . format ( date ) ; }
|
convert time from long to formatted string .
|
1,891
|
public JobFolder createJobFolderWithApplicationId ( final String applicationId ) throws IOException { final Path jobFolderPath = jobSubmissionDirectoryProvider . getJobSubmissionDirectoryPath ( applicationId ) ; final String finalJobFolderPath = jobFolderPath . toString ( ) ; LOG . log ( Level . FINE , "Final job submission Directory: " + finalJobFolderPath ) ; return createJobFolder ( finalJobFolderPath ) ; }
|
Creates the Job folder on the DFS .
|
1,892
|
public JobFolder createJobFolder ( final String finalJobFolderPath ) throws IOException { LOG . log ( Level . FINE , "Final job submission Directory: " + finalJobFolderPath ) ; return new JobFolder ( this . fileSystem , new Path ( finalJobFolderPath ) ) ; }
|
Convenience override for int ids .
|
1,893
|
public void onNext ( final RemoteMessage < EvaluatorShimProtocol . EvaluatorShimControlProto > remoteMessage ) { final EvaluatorShimProtocol . EvaluatorShimCommand command = remoteMessage . getMessage ( ) . getCommand ( ) ; switch ( command ) { case LAUNCH_EVALUATOR : LOG . log ( Level . INFO , "Received a command to launch the Evaluator." ) ; this . threadPool . submit ( new Runnable ( ) { public void run ( ) { EvaluatorShim . this . onEvaluatorLaunch ( remoteMessage . getMessage ( ) . getEvaluatorLaunchCommand ( ) , remoteMessage . getMessage ( ) . getEvaluatorConfigString ( ) , remoteMessage . getMessage ( ) . getEvaluatorFileResourcesUrl ( ) ) ; } } ) ; break ; case TERMINATE : LOG . log ( Level . INFO , "Received a command to terminate the EvaluatorShim." ) ; this . threadPool . submit ( new Runnable ( ) { public void run ( ) { EvaluatorShim . this . onStop ( ) ; } } ) ; break ; default : LOG . log ( Level . WARNING , "An unknown command was received by the EvaluatorShim: {0}." , command ) ; throw new IllegalArgumentException ( "An unknown command was received by the EvaluatorShim." ) ; } }
|
This method is invoked by the Remote Manager when a command message from the Driver is received .
|
1,894
|
public void unregister ( final Identifier id ) throws IOException { final Link < NamingMessage > link = transport . open ( serverSocketAddr , codec , new LoggingLinkListener < NamingMessage > ( ) ) ; link . write ( new NamingUnregisterRequest ( id ) ) ; }
|
Unregisters an identifier .
|
1,895
|
public Path upload ( final File localFile ) throws IOException { if ( ! localFile . exists ( ) ) { throw new FileNotFoundException ( localFile . getAbsolutePath ( ) ) ; } final Path source = new Path ( localFile . getAbsolutePath ( ) ) ; final Path destination = new Path ( this . path , localFile . getName ( ) ) ; try { this . fileSystem . copyFromLocalFile ( source , destination ) ; } catch ( final IOException ex ) { LOG . log ( Level . SEVERE , "Unable to upload " + source + " to " + destination , ex ) ; throw ex ; } LOG . log ( Level . FINE , "Uploaded {0} to {1}" , new Object [ ] { source , destination } ) ; return destination ; }
|
Upload given file to the DFS .
|
1,896
|
public LocalResource uploadAsLocalResource ( final File localFile , final LocalResourceType type ) throws IOException { final Path remoteFile = upload ( localFile ) ; return getLocalResourceForPath ( remoteFile , type ) ; }
|
Shortcut to first upload the file and then form a LocalResource for the YARN submission .
|
1,897
|
public byte [ ] encode ( final T obj ) { try ( final ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; final ObjectOutputStream out = new ObjectOutputStream ( bos ) ) { out . writeObject ( obj ) ; return bos . toByteArray ( ) ; } catch ( final IOException ex ) { throw new RemoteRuntimeException ( ex ) ; } }
|
Encodes the object to bytes .
|
1,898
|
@ SuppressWarnings ( "unchecked" ) public T decode ( final byte [ ] buf ) { try ( final ObjectInputStream in = new ObjectInputStream ( new ByteArrayInputStream ( buf ) ) ) { return ( T ) in . readObject ( ) ; } catch ( final ClassNotFoundException | IOException ex ) { throw new RemoteRuntimeException ( ex ) ; } }
|
Decodes an object from the bytes .
|
1,899
|
public static void main ( final String [ ] args ) throws InjectionException , IOException , ParseException { final Configuration runtimeConfiguration = YarnClientConfiguration . CONF . build ( ) ; runTaskScheduler ( runtimeConfiguration , args ) ; }
|
Launch the scheduler with YARN client configuration .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.