idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
25,100
public static < U > SimpleReactStream < U > firstOf ( final SimpleReactStream < U > ... futureStreams ) { final List < Tuple2 < SimpleReactStream < U > , QueueReader > > racers = Stream . of ( futureStreams ) . map ( s -> Tuple . tuple ( s , new Queue . QueueReader ( s . toQueue ( ) , null ) ) ) . collect ( Collectors . toList ( ) ) ; while ( true ) { for ( final Tuple2 < SimpleReactStream < U > , Queue . QueueReader > q : racers ) { if ( q . _2 ( ) . notEmpty ( ) ) { EagerFutureStreamFunctions . closeOthers ( q . _2 ( ) . getQueue ( ) , racers . stream ( ) . map ( t -> t . _2 ( ) . getQueue ( ) ) . collect ( Collectors . toList ( ) ) ) ; closeOthers ( q . _1 ( ) , racers . stream ( ) . map ( t -> t . _1 ( ) ) . collect ( Collectors . toList ( ) ) ) ; return q . _1 ( ) . fromStream ( q . _2 ( ) . getQueue ( ) . stream ( q . _1 ( ) . getSubscription ( ) ) ) ; } } LockSupport . parkNanos ( 1l ) ; } }
Return first Stream out of provided Streams that starts emitted results
25,101
public static < T > MultipleStreamSource < T > ofMultiple ( final QueueFactory < ? > q ) { Objects . requireNonNull ( q ) ; return new MultipleStreamSource < T > ( StreamSource . of ( q ) . createQueue ( ) ) ; }
Construct a StreamSource that supports multiple readers of the same data backed by a Queue created from the supplied QueueFactory
25,102
public < T > PushableFutureStream < T > futureStream ( final LazyReact s ) { final Queue < T > q = createQueue ( ) ; return new PushableFutureStream < T > ( q , s . fromStream ( q . stream ( ) ) ) ; }
Create a pushable FutureStream using the supplied ReactPool
25,103
public < T > PushableStream < T > stream ( ) { final Queue < T > q = createQueue ( ) ; return new PushableStream < T > ( q , q . jdkStream ( ) ) ; }
Create a pushable JDK 8 Stream
25,104
public static Runnable softenRunnable ( final CheckedRunnable s ) { return ( ) -> { try { s . run ( ) ; } catch ( final Throwable e ) { throw throwSoftenedException ( e ) ; } } ; }
Soften a Runnable that throws a ChecekdException into a plain old Runnable
25,105
public static < T > Supplier < T > softenSupplier ( final CheckedSupplier < T > s ) { return ( ) -> { try { return s . get ( ) ; } catch ( final Throwable e ) { throw throwSoftenedException ( e ) ; } } ; }
Soften a Supplier that throws a ChecekdException into a plain old Supplier
25,106
public static < T > Supplier < T > softenCallable ( final Callable < T > s ) { return ( ) -> { try { return s . call ( ) ; } catch ( final Throwable e ) { throw throwSoftenedException ( e ) ; } } ; }
Soften a Callable that throws a ChecekdException into a Supplier
25,107
public static BooleanSupplier softenBooleanSupplier ( final CheckedBooleanSupplier s ) { return ( ) -> { try { return s . getAsBoolean ( ) ; } catch ( final Throwable e ) { throw throwSoftenedException ( e ) ; } } ; }
Soften a BooleanSuppler that throws a checked exception into one that still throws the exception but doesn t need to declare it .
25,108
public static < X extends Throwable > void throwIf ( final X e , final Predicate < X > p ) { if ( p . test ( e ) ) throw ExceptionSoftener . < RuntimeException > uncheck ( e ) ; }
Throw the exception as upwards if the predicate holds otherwise do nothing
25,109
public static < X extends Throwable > void throwOrHandle ( final X e , final Predicate < X > p , final Consumer < X > handler ) { if ( p . test ( e ) ) throw ExceptionSoftener . < RuntimeException > uncheck ( e ) ; else handler . accept ( e ) ; }
Throw the exception as upwards if the predicate holds otherwise pass to the handler
25,110
public static < T , R1 , R > Optional < R > forEach2 ( Optional < ? extends T > value1 , Function < ? super T , Optional < R1 > > value2 , BiFunction < ? super T , ? super R1 , ? extends R > yieldingFunction ) { return value1 . flatMap ( in -> { Optional < R1 > a = value2 . apply ( in ) ; return a . map ( in2 -> yieldingFunction . apply ( in , in2 ) ) ; } ) ; }
Perform a For Comprehension over a Optional accepting a generating function . This results in a two level nested internal iteration over the provided Optionals .
25,111
@ Synchronized ( "lock" ) public void disconnect ( final ReactiveSeq < T > stream ) { Option < Queue < T > > o = streamToQueue . get ( stream ) ; distributor . removeQueue ( streamToQueue . getOrElse ( stream , new Queue < > ( ) ) ) ; this . streamToQueue = streamToQueue . remove ( stream ) ; this . index -- ; }
Topic will maintain a queue for each Subscribing Stream If a Stream is finished with a Topic it is good practice to disconnect from the Topic so messages will no longer be stored for that Stream
25,112
public static < T > Future < T > narrowK ( final Higher < future , T > future ) { return ( Future < T > ) future ; }
Convert the raw Higher Kinded Type for FutureType types into the FutureType type definition class
25,113
public static < T > Future < T > anyOf ( Future < T > ... fts ) { CompletableFuture < T > [ ] array = new CompletableFuture [ fts . length ] ; for ( int i = 0 ; i < fts . length ; i ++ ) { array [ i ] = fts [ i ] . getFuture ( ) ; } return ( Future < T > ) Future . of ( CompletableFuture . anyOf ( array ) ) ; }
Select the first Future to complete
25,114
public static < T > Future < T > fromPublisher ( final Publisher < T > pub , final Executor ex ) { final ValueSubscriber < T > sub = ValueSubscriber . subscriber ( ) ; pub . subscribe ( sub ) ; return sub . toFutureAsync ( ex ) ; }
Construct a Future asynchronously that contains a single value extracted from the supplied reactive - streams Publisher
25,115
public static < T > Future < T > fromIterable ( final Iterable < T > iterable ) { if ( iterable instanceof Future ) { return ( Future ) iterable ; } return Future . ofResult ( Eval . fromIterable ( iterable ) ) . map ( e -> e . get ( ) ) ; }
Construct a Future syncrhonously that contains a single value extracted from the supplied Iterable
25,116
public static < T , X extends Throwable > Future < T > fromTry ( final Try < T , X > value ) { return value . fold ( s -> Future . ofResult ( s ) , e -> Future . < T > of ( CompletableFutures . error ( e ) ) ) ; }
Construct a Future syncrhonously from the Supplied Try
25,117
public static < T > Future < ReactiveSeq < T > > sequence ( final Stream < ? extends Future < T > > fts ) { return sequence ( ReactiveSeq . fromStream ( fts ) ) ; }
Sequence operation that convert a Stream of Futures to a Future with a Stream
25,118
public < R > Future < R > visitAsync ( Function < ? super T , ? extends R > success , Function < ? super Throwable , ? extends R > failure ) { return foldAsync ( success , failure ) ; }
Non - blocking visit on the state of this Future
25,119
public < R > R fold ( Function < ? super T , ? extends R > success , Function < ? super Throwable , ? extends R > failure ) { try { return success . apply ( future . join ( ) ) ; } catch ( Throwable t ) { return failure . apply ( t ) ; } }
Blocking analogue to visitAsync . Visit the state of this Future block until ready .
25,120
public < R > Future < R > map ( final Function < ? super T , ? extends R > fn , Executor ex ) { return new Future < R > ( future . thenApplyAsync ( fn , ex ) ) ; }
Asyncrhonous transform operation
25,121
public < R > Future < R > flatMapCf ( final Function < ? super T , ? extends CompletionStage < ? extends R > > mapper ) { return Future . < R > of ( future . < R > thenCompose ( t -> ( CompletionStage < R > ) mapper . apply ( t ) ) ) ; }
A flatMap operation that accepts a CompleteableFuture CompletionStage as the return type
25,122
public Future < T > recover ( final Function < ? super Throwable , ? extends T > fn ) { return Future . of ( toCompletableFuture ( ) . exceptionally ( ( Function ) fn ) ) ; }
Returns a new Future that when this Future completes exceptionally is executed with this Future exception as the argument to the supplied function . Otherwise if this Future completes normally applyHKT the returned Future also completes normally with the same value .
25,123
public < R > Future < R > map ( final Function < ? super T , R > success , final Function < Throwable , R > failure ) { return Future . of ( future . thenApply ( success ) . exceptionally ( failure ) ) ; }
Map this Future differently depending on whether the previous stage completed successfully or failed
25,124
public static < T > Future < T > ofResult ( final T result ) { return Future . of ( CompletableFuture . completedFuture ( result ) ) ; }
Construct a successfully completed Future from the given value
25,125
public static < T > Future < T > ofError ( final Throwable error ) { final CompletableFuture < T > cf = new CompletableFuture < > ( ) ; cf . completeExceptionally ( error ) ; return Future . < T > of ( cf ) ; }
Construct a completed - with - error Future from the given Exception
25,126
public static < T > Future < T > of ( final Supplier < T > s ) { return Future . of ( CompletableFuture . supplyAsync ( s ) ) ; }
Create a Future object that asyncrhonously populates using the Common ForkJoinPool from the user provided Supplier
25,127
public static < T > Future < T > of ( final Supplier < T > s , final Executor ex ) { return Future . of ( CompletableFuture . supplyAsync ( s , ex ) ) ; }
Create a Future object that asyncrhonously populates using the provided Executor and Supplier
25,128
public static MutableFloat fromExternal ( final Supplier < Float > s , final Consumer < Float > c ) { return new MutableFloat ( ) { public float getAsFloat ( ) { return s . get ( ) ; } public Float get ( ) { return getAsFloat ( ) ; } public MutableFloat set ( final float value ) { c . accept ( value ) ; return this ; } } ; }
Construct a MutableFloat that gets and sets an external value using the provided Supplier and Consumer
25,129
public static MutableBoolean fromExternal ( final BooleanSupplier s , final Consumer < Boolean > c ) { return new MutableBoolean ( ) { public boolean getAsBoolean ( ) { return s . getAsBoolean ( ) ; } public Boolean get ( ) { return getAsBoolean ( ) ; } public MutableBoolean set ( final boolean value ) { c . accept ( value ) ; return this ; } } ; }
Construct a MutableBoolean that gets and sets an external value using the provided Supplier and Consumer
25,130
public < T > SimpleReactStream < T > fromPublisher ( final Publisher < ? extends T > publisher ) { Objects . requireNonNull ( publisher ) ; Publisher < T > narrowed = ( Publisher < T > ) publisher ; return from ( Spouts . from ( narrowed ) ) ; }
Construct a SimpleReactStream from an Publisher
25,131
public static SimpleReact parallelBuilder ( final int parallelism ) { return SimpleReact . builder ( ) . executor ( new ForkJoinPool ( parallelism ) ) . async ( true ) . build ( ) ; }
Construct a new SimpleReact builder with a new task executor and retry executor with configured number of threads
25,132
@ SuppressWarnings ( "unchecked" ) public < U > SimpleReactStream < U > fromIterable ( final Iterable < U > iter ) { if ( iter instanceof SimpleReactStream ) { return ( SimpleReactStream < U > ) iter ; } return this . from ( StreamSupport . stream ( Spliterators . spliteratorUnknownSize ( iter . iterator ( ) , Spliterator . ORDERED ) , false ) ) ; }
Start a reactive flow from a JDK Iterator
25,133
public < T2 , T3 , R1 , R2 , R3 > Unrestricted < R3 > forEach4 ( Function < ? super T , ? extends Unrestricted < R1 > > value2 , BiFunction < ? super T , ? super R1 , ? extends Unrestricted < R2 > > value3 , Function3 < ? super T , ? super R1 , ? super R2 , ? extends Unrestricted < R3 > > value4 ) { return this . flatMap ( in -> { Unrestricted < R1 > a = value2 . apply ( in ) ; return a . flatMap ( ina -> { Unrestricted < R2 > b = value3 . apply ( in , ina ) ; return b . flatMap ( inb -> { Unrestricted < R3 > c = value4 . apply ( in , ina , inb ) ; return c ; } ) ; } ) ; } ) ; }
Perform a For Comprehension over a Unrestricted accepting 3 generating function . This results in a four level nested internal iteration over the provided Computationss .
25,134
public < T2 , R1 , R2 > Unrestricted < R2 > forEach3 ( Function < ? super T , ? extends Unrestricted < R1 > > value2 , BiFunction < ? super T , ? super R1 , ? extends Unrestricted < R2 > > value3 ) { return this . flatMap ( in -> { Unrestricted < R1 > a = value2 . apply ( in ) ; return a . flatMap ( ina -> { Unrestricted < R2 > b = value3 . apply ( in , ina ) ; return b ; } ) ; } ) ; }
Perform a For Comprehension over a Unrestricted accepting 2 generating function . This results in a three level nested internal iteration over the provided Computationss .
25,135
public < R1 > Unrestricted < R1 > forEach2 ( Function < ? super T , Unrestricted < R1 > > value2 ) { return this . flatMap ( in -> { Unrestricted < R1 > a = value2 . apply ( in ) ; return a ; } ) ; }
Perform a For Comprehension over a Unrestricted accepting a generating function . This results in a two level nested internal iteration over the provided Computationss .
25,136
public static final < T , W extends Unit < T > > Function1 < ? super T , ? extends W > arrowUnit ( Unit < ? > w ) { return t -> ( W ) w . unit ( t ) ; }
Use an existing instance of a type that implements Unit to create a KleisliM arrow for that type
25,137
public static < T > Try < T , Throwable > CofromPublisher ( final Publisher < T > pub ) { return new Try < > ( LazyEither . fromPublisher ( pub ) , new Class [ 0 ] ) ; }
Construct a Try that contains a single value extracted from the supplied reactive - streams Publisher
25,138
public static < T , X extends Throwable > Try < T , X > fromIterable ( final Iterable < T > iterable , T alt ) { if ( iterable instanceof Try ) { return ( Try ) iterable ; } return new Try < > ( LazyEither . fromIterable ( iterable , alt ) , new Class [ 0 ] ) ; }
Construct a Try that contains a single value extracted from the supplied Iterable
25,139
public final < R > Try < R , X > mapOrCatch ( CheckedFunction < ? super T , ? extends R , X > fn , Class < ? extends X > ... classes ) { return new Try < R , X > ( xor . flatMap ( i -> safeApply ( i , fn . asFunction ( ) , classes ) ) , this . classes ) ; }
Perform a mapping operation that may catch the supplied Exception types The supplied Exception types are only applied during this map operation
25,140
public final < R > Try < R , X > flatMapOrCatch ( CheckedFunction < ? super T , ? extends Try < ? extends R , X > , X > fn , Class < ? extends X > ... classes ) { return new Try < > ( xor . flatMap ( i -> safeApplyM ( i , fn . asFunction ( ) , classes ) . toEither ( ) ) , classes ) ; }
Perform a flatMapping operation that may catch the supplied Exception types The supplied Exception types are only applied during this map operation
25,141
public Try < T , X > recoverFor ( Class < ? extends X > t , Function < ? super X , ? extends T > fn ) { return new Try < T , X > ( xor . flatMapLeftToRight ( x -> { if ( t . isAssignableFrom ( x . getClass ( ) ) ) return Either . right ( fn . apply ( x ) ) ; return xor ; } ) , classes ) ; }
Recover if exception is of specified type
25,142
public static < T , X extends Throwable > Try < T , X > withCatch ( final CheckedSupplier < T , X > cf , final Class < ? extends X > ... classes ) { Objects . requireNonNull ( cf ) ; try { return Try . success ( cf . get ( ) ) ; } catch ( final Throwable t ) { if ( classes . length == 0 ) return Try . failure ( ( X ) t ) ; val error = Stream . of ( classes ) . filter ( c -> c . isAssignableFrom ( t . getClass ( ) ) ) . findFirst ( ) ; if ( error . isPresent ( ) ) return Try . failure ( ( X ) t ) ; else throw ExceptionSoftener . throwSoftenedException ( t ) ; } }
Try to execute supplied Supplier and will Catch specified Excpetions or java . lang . Exception if none specified .
25,143
public static < X extends Throwable > Try < Void , X > runWithCatch ( final CheckedRunnable < X > cf , final Class < ? extends X > ... classes ) { Objects . requireNonNull ( cf ) ; try { cf . run ( ) ; return Try . success ( null ) ; } catch ( final Throwable t ) { if ( classes . length == 0 ) return Try . failure ( ( X ) t ) ; val error = Stream . of ( classes ) . filter ( c -> c . isAssignableFrom ( t . getClass ( ) ) ) . findFirst ( ) ; if ( error . isPresent ( ) ) return Try . failure ( ( X ) t ) ; else throw ExceptionSoftener . throwSoftenedException ( t ) ; } }
Try to execute supplied Runnable and will Catch specified Excpetions or java . lang . Exception if none specified .
25,144
public static < T > Single < T > anyOf ( Single < T > ... fts ) { return Single . fromPublisher ( Future . anyOf ( futures ( fts ) ) ) ; }
Select the first Single to complete
25,145
public static < T , R1 , R > Single < R > forEach ( Single < ? extends T > value1 , Function < ? super T , Single < R1 > > value2 , BiFunction < ? super T , ? super R1 , ? extends R > yieldingFunction ) { Single < R > res = value1 . flatMap ( in -> { Single < R1 > a = value2 . apply ( in ) ; return a . map ( ina -> yieldingFunction . apply ( in , ina ) ) ; } ) ; return narrow ( res ) ; }
Perform a For Comprehension over a Single accepting a generating function . This results in a two level nested internal iteration over the provided Singles .
25,146
public static < T > Single < T > fromIterable ( Iterable < T > t ) { return Single . fromPublisher ( Future . fromIterable ( t ) ) ; }
Construct a Single from Iterable by taking the first value from Iterable
25,147
public < B > ListT < W , B > map ( final Function < ? super T , ? extends B > f ) { return of ( run . map ( o -> o . map ( f ) ) ) ; }
Map the wrapped List
25,148
public static < W extends WitnessType < W > , A > ListT < W , A > of ( final AnyM < W , ? extends IndexedSequenceX < A > > monads ) { return new ListT < > ( monads ) ; }
Construct an ListT from an AnyM that wraps a monad containing Lists
25,149
public String [ ] getFamilyNames ( ) { HashSet < String > familyNameSet = new HashSet < String > ( ) ; if ( familyNames == null ) { for ( String columnName : columns ( null , this . valueFields ) ) { int pos = columnName . indexOf ( ":" ) ; familyNameSet . add ( hbaseColumn ( pos > 0 ? columnName . substring ( 0 , pos ) : columnName ) ) ; } } else { for ( String familyName : familyNames ) { familyNameSet . add ( familyName ) ; } } return familyNameSet . toArray ( new String [ 0 ] ) ; }
Method getFamilyNames returns the set of familyNames of this HBaseScheme object .
25,150
@ SuppressWarnings ( "deprecation" ) public static void getAsciiBytes ( String element , int charStart , int charLen , byte [ ] bytes , int byteOffset ) { element . getBytes ( charStart , charLen , bytes , byteOffset ) ; }
This method is faster for ASCII data but unsafe otherwise it is used by our macros AFTER checking that the string is ASCII following a pattern seen in Kryo which benchmarking showed helped . Scala cannot supress warnings like this so we do it here
25,151
public static MessageType getSchemaForRead ( MessageType fileMessageType , MessageType projectedMessageType ) { assertGroupsAreCompatible ( fileMessageType , projectedMessageType ) ; return projectedMessageType ; }
Updated method from ReadSupport which checks if the projection s compatible instead of a stricter check to see if the file s schema contains the projection
25,152
public static void assertGroupsAreCompatible ( GroupType fileType , GroupType projection ) { List < Type > fields = projection . getFields ( ) ; for ( Type otherType : fields ) { if ( fileType . containsField ( otherType . getName ( ) ) ) { Type thisType = fileType . getType ( otherType . getName ( ) ) ; assertAreCompatible ( thisType , otherType ) ; if ( ! otherType . isPrimitive ( ) ) { assertGroupsAreCompatible ( thisType . asGroupType ( ) , otherType . asGroupType ( ) ) ; } } else if ( otherType . getRepetition ( ) == Type . Repetition . REQUIRED ) { throw new InvalidRecordException ( otherType . getName ( ) + " not found in " + fileType ) ; } } }
Validates that the requested group type projection is compatible . This allows the projection schema to have extra optional fields .
25,153
public static void assertAreCompatible ( Type fileType , Type projection ) { if ( ! fileType . getName ( ) . equals ( projection . getName ( ) ) || ( fileType . getRepetition ( ) != projection . getRepetition ( ) && ! fileType . getRepetition ( ) . isMoreRestrictiveThan ( projection . getRepetition ( ) ) ) ) { throw new InvalidRecordException ( projection + " found: expected " + fileType ) ; } }
Validates that the requested projection is compatible . This makes it possible to project a required field using optional since it is less restrictive .
25,154
public static < T extends ThriftStruct > Class < T > getThriftClass ( Map < String , String > fileMetadata , Configuration conf ) throws ClassNotFoundException { String className = conf . get ( THRIFT_READ_CLASS_KEY , null ) ; if ( className == null ) { final ThriftMetaData metaData = ThriftMetaData . fromExtraMetaData ( fileMetadata ) ; if ( metaData == null ) { throw new ParquetDecodingException ( "Could not read file as the Thrift class is not provided and could not be resolved from the file" ) ; } return ( Class < T > ) metaData . getThriftClass ( ) ; } else { return ( Class < T > ) Class . forName ( className ) ; } }
Getting thrift class from extra metadata
25,155
public static void showKeyboard ( Context context , EditText target ) { if ( context == null || target == null ) { return ; } InputMethodManager imm = getInputMethodManager ( context ) ; imm . showSoftInput ( target , InputMethodManager . SHOW_IMPLICIT ) ; }
Show keyboard and focus to given EditText
25,156
public static void showKeyboardInDialog ( Dialog dialog , EditText target ) { if ( dialog == null || target == null ) { return ; } dialog . getWindow ( ) . setSoftInputMode ( WindowManager . LayoutParams . SOFT_INPUT_STATE_VISIBLE ) ; target . requestFocus ( ) ; }
Show keyboard and focus to given EditText . Use this method if target EditText is in Dialog .
25,157
public static void setEventListener ( final Activity activity , final KeyboardVisibilityEventListener listener ) { final Unregistrar unregistrar = registerEventListener ( activity , listener ) ; activity . getApplication ( ) . registerActivityLifecycleCallbacks ( new AutoActivityLifecycleCallback ( activity ) { protected void onTargetActivityDestroyed ( ) { unregistrar . unregister ( ) ; } } ) ; }
Set keyboard visibility change event listener . This automatically remove registered event listener when the Activity is destroyed
25,158
public static Unregistrar registerEventListener ( final Activity activity , final KeyboardVisibilityEventListener listener ) { if ( activity == null ) { throw new NullPointerException ( "Parameter:activity must not be null" ) ; } int softInputAdjust = activity . getWindow ( ) . getAttributes ( ) . softInputMode & WindowManager . LayoutParams . SOFT_INPUT_MASK_ADJUST ; if ( ( softInputAdjust & WindowManager . LayoutParams . SOFT_INPUT_ADJUST_NOTHING ) == WindowManager . LayoutParams . SOFT_INPUT_ADJUST_NOTHING ) { throw new IllegalArgumentException ( "Parameter:activity window SoftInputMethod is SOFT_INPUT_ADJUST_NOTHING. In this case window will not be resized" ) ; } if ( listener == null ) { throw new NullPointerException ( "Parameter:listener must not be null" ) ; } final View activityRoot = getActivityRoot ( activity ) ; final ViewTreeObserver . OnGlobalLayoutListener layoutListener = new ViewTreeObserver . OnGlobalLayoutListener ( ) { private final Rect r = new Rect ( ) ; private boolean wasOpened = false ; public void onGlobalLayout ( ) { activityRoot . getWindowVisibleDisplayFrame ( r ) ; int screenHeight = activityRoot . getRootView ( ) . getHeight ( ) ; int heightDiff = screenHeight - r . height ( ) ; boolean isOpen = heightDiff > screenHeight * KEYBOARD_MIN_HEIGHT_RATIO ; if ( isOpen == wasOpened ) { return ; } wasOpened = isOpen ; listener . onVisibilityChanged ( isOpen ) ; } } ; activityRoot . getViewTreeObserver ( ) . addOnGlobalLayoutListener ( layoutListener ) ; return new SimpleUnregistrar ( activity , layoutListener ) ; }
Set keyboard visibility change event listener .
25,159
public static boolean isKeyboardVisible ( Activity activity ) { Rect r = new Rect ( ) ; View activityRoot = getActivityRoot ( activity ) ; activityRoot . getWindowVisibleDisplayFrame ( r ) ; int screenHeight = activityRoot . getRootView ( ) . getHeight ( ) ; int heightDiff = screenHeight - r . height ( ) ; return heightDiff > screenHeight * KEYBOARD_MIN_HEIGHT_RATIO ; }
Determine if keyboard is visible
25,160
public Bitmap toBitmap ( ) { if ( mSizeX == - 1 || mSizeY == - 1 ) { actionBar ( ) ; } Bitmap bitmap = Bitmap . createBitmap ( getIntrinsicWidth ( ) , getIntrinsicHeight ( ) , Bitmap . Config . ARGB_8888 ) ; style ( Paint . Style . FILL ) ; Canvas canvas = new Canvas ( bitmap ) ; setBounds ( 0 , 0 , canvas . getWidth ( ) , canvas . getHeight ( ) ) ; draw ( canvas ) ; return bitmap ; }
Creates a BitMap to use in Widgets or anywhere else
25,161
public IconicsDrawable iconOffsetXDp ( @ Dimension ( unit = DP ) int sizeDp ) { return iconOffsetXPx ( Utils . convertDpToPx ( mContext , sizeDp ) ) ; }
set the icon offset for X as dp
25,162
public IconicsDrawable iconOffsetXPx ( @ Dimension ( unit = PX ) int sizePx ) { mIconOffsetX = sizePx ; invalidateSelf ( ) ; return this ; }
set the icon offset for X
25,163
public IconicsDrawable iconOffsetYDp ( @ Dimension ( unit = DP ) int sizeDp ) { return iconOffsetYPx ( Utils . convertDpToPx ( mContext , sizeDp ) ) ; }
set the icon offset for Y as dp
25,164
public IconicsDrawable iconOffsetYPx ( @ Dimension ( unit = PX ) int sizePx ) { mIconOffsetY = sizePx ; invalidateSelf ( ) ; return this ; }
set the icon offset for Y
25,165
public IconicsDrawable paddingDp ( @ Dimension ( unit = DP ) int sizeDp ) { return paddingPx ( Utils . convertDpToPx ( mContext , sizeDp ) ) ; }
Set the padding in dp for the drawable
25,166
public IconicsDrawable paddingPx ( @ Dimension ( unit = PX ) int sizePx ) { if ( mIconPadding != sizePx ) { mIconPadding = sizePx ; if ( mDrawContour ) { mIconPadding += mContourWidth ; } if ( mDrawBackgroundContour ) { mIconPadding += mBackgroundContourWidth ; } invalidateSelf ( ) ; } return this ; }
Set a padding for the .
25,167
public IconicsDrawable contourWidthDp ( @ Dimension ( unit = DP ) int sizeDp ) { return contourWidthPx ( Utils . convertDpToPx ( mContext , sizeDp ) ) ; }
Set contour width from dp for the icon
25,168
public IconicsDrawable contourWidthPx ( @ Dimension ( unit = PX ) int sizePx ) { mContourWidth = sizePx ; mContourBrush . getPaint ( ) . setStrokeWidth ( sizePx ) ; drawContour ( true ) ; invalidateSelf ( ) ; return this ; }
Set contour width for the icon .
25,169
public IconicsDrawable backgroundContourWidthDp ( @ Dimension ( unit = DP ) int sizeDp ) { return backgroundContourWidthPx ( Utils . convertDpToPx ( mContext , sizeDp ) ) ; }
Set background contour width from dp for the icon
25,170
public IconicsDrawable backgroundContourWidthPx ( @ Dimension ( unit = PX ) int sizePx ) { mBackgroundContourWidth = sizePx ; mBackgroundContourBrush . getPaint ( ) . setStrokeWidth ( sizePx ) ; drawBackgroundContour ( true ) ; invalidateSelf ( ) ; return this ; }
Set background contour width for the icon .
25,171
public IconicsAnimationProcessor start ( ) { mAnimator . setInterpolator ( mInterpolator ) ; mAnimator . setDuration ( mDuration ) ; mAnimator . setRepeatCount ( mRepeatCount ) ; mAnimator . setRepeatMode ( mRepeatMode ) ; if ( mDrawable != null ) { mIsStartRequested = false ; mAnimator . start ( ) ; } else { mIsStartRequested = true ; } return this ; }
Starts the animation if processor is attached to drawable otherwise sets flag to start animation immediately after attaching
25,172
private static Class resolveRClass ( String packageName ) { do { try { return Class . forName ( packageName + ".R$string" ) ; } catch ( ClassNotFoundException e ) { packageName = packageName . contains ( "." ) ? packageName . substring ( 0 , packageName . lastIndexOf ( '.' ) ) : "" ; } } while ( ! TextUtils . isEmpty ( packageName ) ) ; return null ; }
a helper class to resolve the correct R Class for the package
25,173
private static String getStringResourceByName ( Context ctx , String resourceName ) { String packageName = ctx . getPackageName ( ) ; int resId = ctx . getResources ( ) . getIdentifier ( resourceName , "string" , packageName ) ; if ( resId == 0 ) { return "" ; } else { return ctx . getString ( resId ) ; } }
helper class to retrieve a string by it s resource name
25,174
public static void applyStyles ( Context ctx , Spannable text , List < StyleContainer > styleContainers , List < CharacterStyle > styles , HashMap < String , List < CharacterStyle > > stylesFor ) { for ( StyleContainer styleContainer : styleContainers ) { if ( styleContainer . style != null ) { text . setSpan ( styleContainer . style , styleContainer . startIndex , styleContainer . endIndex , styleContainer . flags ) ; } else if ( styleContainer . span != null ) { text . setSpan ( styleContainer . span , styleContainer . startIndex , styleContainer . endIndex , styleContainer . flags ) ; } else { text . setSpan ( new IconicsTypefaceSpan ( "sans-serif" , styleContainer . font . getTypeface ( ctx ) ) , styleContainer . startIndex , styleContainer . endIndex , Spannable . SPAN_EXCLUSIVE_EXCLUSIVE ) ; } if ( stylesFor != null && stylesFor . containsKey ( styleContainer . icon ) ) { for ( CharacterStyle style : stylesFor . get ( styleContainer . icon ) ) { text . setSpan ( CharacterStyle . wrap ( style ) , styleContainer . startIndex , styleContainer . endIndex , styleContainer . flags ) ; } } else if ( styles != null ) { for ( CharacterStyle style : styles ) { text . setSpan ( CharacterStyle . wrap ( style ) , styleContainer . startIndex , styleContainer . endIndex , styleContainer . flags ) ; } } } }
Applies all given styles on the given Spannable
25,175
public RandomAccessData getCentralDirectory ( RandomAccessData data ) { long offset = Bytes . littleEndianValue ( this . block , this . offset + 16 , 4 ) ; long length = Bytes . littleEndianValue ( this . block , this . offset + 12 , 4 ) ; return data . getSubsection ( offset , length ) ; }
Return the bytes of the Central directory based on the offset indicated in this record .
25,176
public static String getLocalHostName ( ) throws UnknownHostException { String preffered = System . getProperty ( PREFERED_ADDRESS_PROPERTY_NAME ) ; return chooseAddress ( preffered ) . getHostName ( ) ; }
Returns the local hostname . It loops through the network interfaces and returns the first non loopback address
25,177
public static String getLocalIp ( ) throws UnknownHostException { String preffered = System . getProperty ( PREFERED_ADDRESS_PROPERTY_NAME ) ; return chooseAddress ( preffered ) . getHostAddress ( ) ; }
Returns the local IP . It loops through the network interfaces and returns the first non loopback address
25,178
protected void doGet ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { if ( authConfiguration . isKeycloakEnabled ( ) ) { redirector . doRedirect ( request , response , "/" ) ; } else { redirector . doForward ( request , response , "/login.html" ) ; } }
GET simply returns login . html
25,179
public String findClassAbsoluteFileName ( String fileName , String className , List < String > sourceRoots ) { int lastIdx = className . lastIndexOf ( '.' ) ; if ( lastIdx > 0 && ! ( fileName . contains ( "/" ) || fileName . contains ( File . separator ) ) ) { String packagePath = className . substring ( 0 , lastIdx ) . replace ( '.' , File . separatorChar ) ; fileName = packagePath + File . separator + fileName ; } File baseDir = getBaseDir ( ) ; String answer = findInSourceFolders ( baseDir , fileName ) ; if ( answer == null && sourceRoots != null ) { for ( String sourceRoot : sourceRoots ) { answer = findInSourceFolders ( new File ( sourceRoot ) , fileName ) ; if ( answer != null ) break ; } } return answer ; }
Given a class name and a file name try to find the absolute file name of the source file on the users machine or null if it cannot be found
25,180
public String ideaOpenAndNavigate ( String fileName , int line , int column ) throws Exception { if ( line < 0 ) line = 0 ; if ( column < 0 ) column = 0 ; String xml = "<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\n" + "<methodCall>\n" + " <methodName>fileOpener.openAndNavigate</methodName>\n" + " <params>\n" + " <param><value><string>" + fileName + "</string></value></param>\n" + " <param><value><int>" + line + "</int></value></param>\n" + " <param><value><int>" + column + "</int></value></param>\n" + " </params>\n" + "</methodCall>\n" ; return ideaXmlRpc ( xml ) ; }
Uses Intellij s XmlRPC mechanism to open and navigate to a file
25,181
public static int recursiveDelete ( File file ) { int answer = 0 ; if ( file . isDirectory ( ) ) { File [ ] files = file . listFiles ( ) ; if ( files != null ) { for ( File child : files ) { answer += recursiveDelete ( child ) ; } } } if ( file . delete ( ) ) { answer += 1 ; } return answer ; }
Recursively deletes the given file whether its a file or directory returning the number of files deleted
25,182
public void showOptions ( ) { showOptionsHeader ( ) ; for ( Option option : options ) { System . out . println ( option . getInformation ( ) ) ; } }
Displays the command line options .
25,183
protected String findWar ( String ... paths ) { if ( paths != null ) { for ( String path : paths ) { if ( path != null ) { File file = new File ( path ) ; if ( file . exists ( ) ) { if ( file . isFile ( ) ) { String name = file . getName ( ) ; if ( isWarFileName ( name ) ) { return file . getPath ( ) ; } } if ( file . isDirectory ( ) ) { File [ ] wars = file . listFiles ( ( dir , name ) -> isWarFileName ( name ) ) ; if ( wars != null && wars . length > 0 ) { return wars [ 0 ] . getPath ( ) ; } } } } } } return null ; }
Strategy method where we could use some smarts to find the war using known paths or maybe the local maven repository?
25,184
protected String defaultKeycloakConfigLocation ( ) { String karafBase = System . getProperty ( "karaf.base" ) ; if ( karafBase != null ) { return karafBase + "/etc/keycloak.json" ; } String jettyHome = System . getProperty ( "jetty.home" ) ; if ( jettyHome != null ) { return jettyHome + "/etc/keycloak.json" ; } String tomcatHome = System . getProperty ( "catalina.home" ) ; if ( tomcatHome != null ) { return tomcatHome + "/conf/keycloak.json" ; } String jbossHome = System . getProperty ( "jboss.server.config.dir" ) ; if ( jbossHome != null ) { return jbossHome + "/keycloak.json" ; } return "classpath:keycloak.json" ; }
Will try to guess the config location based on the server where hawtio is running . Used just if keycloakClientConfig is not provided
25,185
public static void createZipFile ( Logger log , File sourceDir , File outputZipFile ) throws IOException { FileFilter filter = null ; createZipFile ( log , sourceDir , outputZipFile , filter ) ; }
Creates a zip fie from the given source directory and output zip file name
25,186
public static void zipDirectory ( Logger log , File directory , ZipOutputStream zos , String path , FileFilter filter ) throws IOException { File [ ] dirList = directory . listFiles ( ) ; byte [ ] readBuffer = new byte [ 8192 ] ; int bytesIn = 0 ; if ( dirList != null ) { for ( File f : dirList ) { if ( f . isDirectory ( ) ) { String prefix = path + f . getName ( ) + "/" ; if ( matches ( filter , f ) ) { zos . putNextEntry ( new ZipEntry ( prefix ) ) ; zipDirectory ( log , f , zos , prefix , filter ) ; } } else { String entry = path + f . getName ( ) ; if ( matches ( filter , f ) ) { FileInputStream fis = new FileInputStream ( f ) ; try { ZipEntry anEntry = new ZipEntry ( entry ) ; zos . putNextEntry ( anEntry ) ; bytesIn = fis . read ( readBuffer ) ; while ( bytesIn != - 1 ) { zos . write ( readBuffer , 0 , bytesIn ) ; bytesIn = fis . read ( readBuffer ) ; } } finally { fis . close ( ) ; } if ( log . isDebugEnabled ( ) ) { log . debug ( "zipping file " + entry ) ; } } } zos . closeEntry ( ) ; } } }
Zips the directory recursively into the ZIP stream given the starting path and optional filter
25,187
public static void unzip ( InputStream in , File toDir ) throws IOException { ZipInputStream zis = new ZipInputStream ( new BufferedInputStream ( in ) ) ; try { ZipEntry entry = zis . getNextEntry ( ) ; while ( entry != null ) { if ( ! entry . isDirectory ( ) ) { String entryName = entry . getName ( ) ; File toFile = new File ( toDir , entryName ) ; toFile . getParentFile ( ) . mkdirs ( ) ; OutputStream os = new FileOutputStream ( toFile ) ; try { try { copy ( zis , os ) ; } finally { zis . closeEntry ( ) ; } } finally { closeQuietly ( os ) ; } } entry = zis . getNextEntry ( ) ; } } finally { closeQuietly ( zis ) ; } }
Unzips the given input stream of a ZIP to the given directory
25,188
public static String readFully ( BufferedReader reader ) throws IOException { if ( reader == null ) { return null ; } StringBuilder sb = new StringBuilder ( BUFFER_SIZE ) ; char [ ] buf = new char [ BUFFER_SIZE ] ; try { int len ; while ( ( len = reader . read ( buf ) ) != - 1 ) { sb . append ( buf , 0 , len ) ; } } finally { IOHelper . close ( reader , "reader" , LOG ) ; } return sb . toString ( ) ; }
Reads the entire reader into memory as a String
25,189
public static void close ( Closeable closeable , String name , Logger log ) { if ( closeable != null ) { try { closeable . close ( ) ; } catch ( IOException e ) { if ( log == null ) { log = LOG ; } if ( name != null ) { log . warn ( "Cannot close: " + name + ". Reason: " + e . getMessage ( ) , e ) ; } else { log . warn ( "Cannot close. Reason: " + e . getMessage ( ) , e ) ; } } } }
Closes the given resource if it is available logging any closing exceptions to the given log .
25,190
public static void write ( File file , String text , boolean append ) throws IOException { FileWriter writer = new FileWriter ( file , append ) ; try { writer . write ( text ) ; } finally { writer . close ( ) ; } }
Writes the given text to the file ; either in append mode or replace mode depending the append flag
25,191
public static void write ( File file , byte [ ] data , boolean append ) throws IOException { FileOutputStream stream = new FileOutputStream ( file , append ) ; try { stream . write ( data ) ; } finally { stream . close ( ) ; } }
Writes the given data to the file ; either in append mode or replace mode depending the append flag
25,192
@ Bean ( initMethod = "init" ) public ConfigFacade configFacade ( ) throws Exception { final URL loginResource = this . getClass ( ) . getClassLoader ( ) . getResource ( "login.conf" ) ; if ( loginResource != null ) { setSystemPropertyIfNotSet ( JAVA_SECURITY_AUTH_LOGIN_CONFIG , loginResource . toExternalForm ( ) ) ; } LOG . info ( "Using loginResource " + JAVA_SECURITY_AUTH_LOGIN_CONFIG + " : " + System . getProperty ( JAVA_SECURITY_AUTH_LOGIN_CONFIG ) ) ; final URL loginFile = this . getClass ( ) . getClassLoader ( ) . getResource ( "realm.properties" ) ; if ( loginFile != null ) { setSystemPropertyIfNotSet ( "login.file" , loginFile . toExternalForm ( ) ) ; } LOG . info ( "Using login.file : " + System . getProperty ( "login.file" ) ) ; setSystemPropertyIfNotSet ( AuthenticationConfiguration . HAWTIO_ROLES , "admin" ) ; setSystemPropertyIfNotSet ( AuthenticationConfiguration . HAWTIO_REALM , "hawtio" ) ; setSystemPropertyIfNotSet ( AuthenticationConfiguration . HAWTIO_ROLE_PRINCIPAL_CLASSES , "org.eclipse.jetty.jaas.JAASRole" ) ; if ( ! Boolean . getBoolean ( "debugMode" ) ) { System . setProperty ( AuthenticationConfiguration . HAWTIO_AUTHENTICATION_ENABLED , "true" ) ; } return new ConfigFacade ( ) ; }
Configure facade to use authentication .
25,193
public static String sanitizeDirectory ( String name ) { if ( isBlank ( name ) ) { return name ; } return sanitize ( name ) . replace ( "." , "" ) ; }
Also remove any dots in the directory name
25,194
public static void addThrowableAndCauses ( List < ThrowableDTO > exceptions , Throwable exception ) { if ( exception != null ) { ThrowableDTO dto = new ThrowableDTO ( exception ) ; exceptions . add ( dto ) ; Throwable cause = exception . getCause ( ) ; if ( cause != null && cause != exception ) { addThrowableAndCauses ( exceptions , cause ) ; } } }
Adds the exception and all of the causes to the given list of exceptions
25,195
@ SuppressWarnings ( "unchecked" ) public static int compare ( Object a , Object b ) { if ( a == b ) { return 0 ; } if ( a == null ) { return - 1 ; } if ( b == null ) { return 1 ; } if ( a instanceof Comparable ) { Comparable comparable = ( Comparable ) a ; return comparable . compareTo ( b ) ; } int answer = a . getClass ( ) . getName ( ) . compareTo ( b . getClass ( ) . getName ( ) ) ; if ( answer == 0 ) { answer = a . hashCode ( ) - b . hashCode ( ) ; } return answer ; }
A helper method for performing an ordered comparison on the objects handling nulls and objects which do not handle sorting gracefully
25,196
protected String getKeycloakUsername ( final HttpServletRequest req , HttpServletResponse resp ) { AtomicReference < String > username = new AtomicReference < > ( ) ; Authenticator . authenticate ( authConfiguration , req , subject -> { username . set ( AuthHelpers . getUsername ( subject ) ) ; req . getSession ( true ) ; } ) ; return username . get ( ) ; }
With Keycloak integration the Authorization header is available in the request to the UserServlet .
25,197
protected boolean filterUnwantedArtifacts ( Artifact artifact ) { if ( artifact . getGroupId ( ) . startsWith ( "org.apache.maven" ) ) { return true ; } else if ( artifact . getGroupId ( ) . startsWith ( "org.codehaus.plexus" ) ) { return true ; } return false ; }
Filter unwanted artifacts
25,198
protected void addRelevantPluginDependencies ( Set < Artifact > artifacts ) throws MojoExecutionException { if ( pluginDependencies == null ) { return ; } Iterator < Artifact > iter = this . pluginDependencies . iterator ( ) ; while ( iter . hasNext ( ) ) { Artifact classPathElement = iter . next ( ) ; getLog ( ) . debug ( "Adding plugin dependency artifact: " + classPathElement . getArtifactId ( ) + " to classpath" ) ; artifacts . add ( classPathElement ) ; } }
Add any relevant project dependencies to the classpath .
25,199
protected Collection < Artifact > getAllDependencies ( ) throws Exception { List < Artifact > artifacts = new ArrayList < Artifact > ( ) ; for ( Iterator < ? > dependencies = project . getDependencies ( ) . iterator ( ) ; dependencies . hasNext ( ) ; ) { Dependency dependency = ( Dependency ) dependencies . next ( ) ; String groupId = dependency . getGroupId ( ) ; String artifactId = dependency . getArtifactId ( ) ; VersionRange versionRange ; try { versionRange = VersionRange . createFromVersionSpec ( dependency . getVersion ( ) ) ; } catch ( InvalidVersionSpecificationException e ) { throw new MojoExecutionException ( "unable to parse version" , e ) ; } String type = dependency . getType ( ) ; if ( type == null ) { type = "jar" ; } String classifier = dependency . getClassifier ( ) ; boolean optional = dependency . isOptional ( ) ; String scope = dependency . getScope ( ) ; if ( scope == null ) { scope = Artifact . SCOPE_COMPILE ; } Artifact art = this . artifactFactory . createDependencyArtifact ( groupId , artifactId , versionRange , type , classifier , scope , null , optional ) ; if ( scope . equalsIgnoreCase ( Artifact . SCOPE_SYSTEM ) ) { art . setFile ( new File ( dependency . getSystemPath ( ) ) ) ; } List < String > exclusions = new ArrayList < String > ( ) ; for ( Iterator < ? > j = dependency . getExclusions ( ) . iterator ( ) ; j . hasNext ( ) ; ) { Exclusion e = ( Exclusion ) j . next ( ) ; exclusions . add ( e . getGroupId ( ) + ":" + e . getArtifactId ( ) ) ; } ArtifactFilter newFilter = new ExcludesArtifactFilter ( exclusions ) ; art . setDependencyFilter ( newFilter ) ; artifacts . add ( art ) ; } return artifacts ; }
generic method to retrieve all the transitive dependencies