idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
25,100
@ SafeVarargs 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
94
25
25,101
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
94
8
25,102
@ SafeVarargs 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 .
170
23
25,103
@ SafeVarargs 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 .
170
24
25,104
public static < T > Single < T > anyOf ( Single < T > ... fts ) { return Single . fromPublisher ( Future . anyOf ( futures ( fts ) ) ) ; }
Select the first Single to complete
41
6
25,105
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 .
121
30
25,106
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
38
14
25,107
@ Override 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
49
4
25,108
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
55
15
25,109
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 .
139
18
25,110
@ 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
61
48
25,111
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
45
27
25,112
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 .
182
22
25,113
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 .
104
26
25,114
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
167
7
25,115
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
62
8
25,116
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 .
71
21
25,117
public static void setEventListener ( final Activity activity , final KeyboardVisibilityEventListener listener ) { final Unregistrar unregistrar = registerEventListener ( activity , listener ) ; activity . getApplication ( ) . registerActivityLifecycleCallbacks ( new AutoActivityLifecycleCallback ( activity ) { @ Override protected void onTargetActivityDestroyed ( ) { unregistrar . unregister ( ) ; } } ) ; }
Set keyboard visibility change event listener . This automatically remove registered event listener when the Activity is destroyed
93
18
25,118
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 ; // fix for #37 and #38. // The window will not be resized in case of SOFT_INPUT_ADJUST_NOTHING 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 ; @ Override 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 ) { // keyboard state has not changed return ; } wasOpened = isOpen ; listener . onVisibilityChanged ( isOpen ) ; } } ; activityRoot . getViewTreeObserver ( ) . addOnGlobalLayoutListener ( layoutListener ) ; return new SimpleUnregistrar ( activity , layoutListener ) ; }
Set keyboard visibility change event listener .
449
7
25,119
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
97
7
25,120
@ NonNull 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
132
13
25,121
@ NonNull public IconicsDrawable iconOffsetXDp ( @ Dimension ( unit = DP ) int sizeDp ) { return iconOffsetXPx ( Utils . convertDpToPx ( mContext , sizeDp ) ) ; }
set the icon offset for X as dp
53
9
25,122
@ NonNull public IconicsDrawable iconOffsetXPx ( @ Dimension ( unit = PX ) int sizePx ) { mIconOffsetX = sizePx ; invalidateSelf ( ) ; return this ; }
set the icon offset for X
46
6
25,123
@ NonNull public IconicsDrawable iconOffsetYDp ( @ Dimension ( unit = DP ) int sizeDp ) { return iconOffsetYPx ( Utils . convertDpToPx ( mContext , sizeDp ) ) ; }
set the icon offset for Y as dp
52
9
25,124
@ NonNull public IconicsDrawable iconOffsetYPx ( @ Dimension ( unit = PX ) int sizePx ) { mIconOffsetY = sizePx ; invalidateSelf ( ) ; return this ; }
set the icon offset for Y
46
6
25,125
@ NonNull public IconicsDrawable paddingDp ( @ Dimension ( unit = DP ) int sizeDp ) { return paddingPx ( Utils . convertDpToPx ( mContext , sizeDp ) ) ; }
Set the padding in dp for the drawable
50
10
25,126
@ NonNull 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 .
98
6
25,127
@ NonNull public IconicsDrawable contourWidthDp ( @ Dimension ( unit = DP ) int sizeDp ) { return contourWidthPx ( Utils . convertDpToPx ( mContext , sizeDp ) ) ; }
Set contour width from dp for the icon
54
10
25,128
@ NonNull 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 .
77
8
25,129
@ NonNull public IconicsDrawable backgroundContourWidthDp ( @ Dimension ( unit = DP ) int sizeDp ) { return backgroundContourWidthPx ( Utils . convertDpToPx ( mContext , sizeDp ) ) ; }
Set background contour width from dp for the icon
56
11
25,130
@ NonNull 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 .
81
9
25,131
@ NonNull 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
106
20
25,132
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
97
12
25,133
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
85
12
25,134
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
332
11
25,135
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 .
75
16
25,136
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
55
20
25,137
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
55
19
25,138
@ Override 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
81
6
25,139
@ Override public String findClassAbsoluteFileName ( String fileName , String className , List < String > sourceRoots ) { // usually the fileName is just the name of the file without any package information // so lets turn the package name into a path 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
232
30
25,140
@ Override 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
209
18
25,141
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
81
20
25,142
public void showOptions ( ) { showOptionsHeader ( ) ; for ( Option option : options ) { System . out . println ( option . getInformation ( ) ) ; } }
Displays the command line options .
37
7
25,143
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 ( ) ) { // lets look for a war in this directory 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?
169
25
25,144
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" ; } // Fallback to classpath inside hawtio.war 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
214
29
25,145
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
47
16
25,146
public static void zipDirectory ( Logger log , File directory , ZipOutputStream zos , String path , FileFilter filter ) throws IOException { // get a listing of the directory content File [ ] dirList = directory . listFiles ( ) ; byte [ ] readBuffer = new byte [ 8192 ] ; int bytesIn = 0 ; // loop through dirList, and zip the files 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
324
18
25,147
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
188
14
25,148
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 ; // read until we reach then end which is the -1 marker 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
134
10
25,149
public static void close ( Closeable closeable , String name , Logger log ) { if ( closeable != null ) { try { closeable . close ( ) ; } catch ( IOException e ) { if ( log == null ) { // then fallback to use the own Logger 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 .
130
18
25,150
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
51
20
25,151
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
55
20
25,152
@ 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 .
382
7
25,153
public static String sanitizeDirectory ( String name ) { if ( isBlank ( name ) ) { return name ; } return sanitize ( name ) . replace ( "." , "" ) ; }
Also remove any dots in the directory name
43
8
25,154
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
92
14
25,155
@ 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
146
23
25,156
protected String getKeycloakUsername ( final HttpServletRequest req , HttpServletResponse resp ) { AtomicReference < String > username = new AtomicReference <> ( ) ; Authenticator . authenticate ( authConfiguration , req , subject -> { username . set ( AuthHelpers . getUsername ( subject ) ) ; // Start httpSession req . getSession ( true ) ; } ) ; return username . get ( ) ; }
With Keycloak integration the Authorization header is available in the request to the UserServlet .
93
19
25,157
protected boolean filterUnwantedArtifacts ( Artifact artifact ) { // filter out maven and plexus stuff (plexus used by maven plugins) if ( artifact . getGroupId ( ) . startsWith ( "org.apache.maven" ) ) { return true ; } else if ( artifact . getGroupId ( ) . startsWith ( "org.codehaus.plexus" ) ) { return true ; } return false ; }
Filter unwanted artifacts
94
3
25,158
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 .
119
10
25,159
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
433
9
25,160
public void setClassLoaderProvider ( String id , ClassLoaderProvider classLoaderProvider ) { if ( classLoaderProvider != null ) { classLoaderProviderMap . put ( id , classLoaderProvider ) ; } else { classLoaderProviderMap . remove ( id ) ; } }
Registers a named class loader provider or removes it if the classLoaderProvider is null
56
17
25,161
public SortedSet < String > findClassNames ( String search , Integer limit ) { Map < Package , ClassLoader [ ] > packageMap = Packages . getPackageMap ( getClassLoaders ( ) , ignorePackages ) ; return findClassNamesInPackages ( search , limit , packageMap ) ; }
Searches for the available class names given the text search
66
12
25,162
public SortedMap < String , Class < ? > > getAllClassesMap ( ) { Package [ ] packages = Package . getPackages ( ) ; return getClassesMap ( packages ) ; }
Returns all the classes found in a sorted map
43
9
25,163
public SortedMap < String , Class < ? > > getClassesMap ( Package ... packages ) { SortedMap < String , Class < ? > > answer = new TreeMap < String , Class < ? > > ( ) ; Map < String , ClassResource > urlSet = new HashMap < String , ClassResource > ( ) ; for ( Package aPackage : packages ) { addPackageResources ( aPackage , urlSet , classLoaders ) ; } for ( ClassResource classResource : urlSet . values ( ) ) { Set < Class < ? > > classes = getClassesForPackage ( classResource , null , null ) ; for ( Class < ? > aClass : classes ) { answer . put ( aClass . getName ( ) , aClass ) ; } } return answer ; }
Returns all the classes found in a sorted map for the given list of packages
168
15
25,164
public Class < ? > findClass ( String className ) throws ClassNotFoundException { for ( String skip : SKIP_CLASSES ) { if ( skip . equals ( className ) ) { return null ; } } for ( ClassLoader classLoader : getClassLoaders ( ) ) { try { return classLoader . loadClass ( className ) ; } catch ( ClassNotFoundException e ) { // ignore } } return Class . forName ( className ) ; }
Finds a class from its name
99
7
25,165
public List < Class < ? > > optionallyFindClasses ( Iterable < String > classNames ) { List < Class < ? > > answer = new ArrayList < Class < ? > > ( ) ; for ( String className : classNames ) { Class < ? > aClass = optionallyFindClass ( className ) ; if ( aClass != null ) { answer . add ( aClass ) ; } } return answer ; }
Tries to find as many of the class names on the class loaders as possible and return them
90
20
25,166
protected boolean withinLimit ( Integer limit , Collection < ? > collection ) { if ( limit == null ) { return true ; } else { int value = limit . intValue ( ) ; return value <= 0 || value > collection . size ( ) ; } }
Returns true if we are within the limit value for the number of results in the collection
53
17
25,167
protected static Class findClass ( final String className ) throws ClassNotFoundException { try { return Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( className ) ; } catch ( ClassNotFoundException e ) { try { return Class . forName ( className ) ; } catch ( ClassNotFoundException e1 ) { return MavenCoordHelper . class . getClassLoader ( ) . loadClass ( className ) ; } } }
Find class given class name .
99
6
25,168
public File getConfigDirectory ( ) { String dirName = getConfigDir ( ) ; File answer = null ; if ( Strings . isNotBlank ( dirName ) ) { answer = new File ( dirName ) ; } else { answer = new File ( ".hawtio" ) ; } answer . mkdirs ( ) ; return answer ; }
Returns the configuration directory ; lazily attempting to create it if it does not yet exist
75
17
25,169
public void start ( ) { MBeanServer server = getMbeanServer ( ) ; if ( server != null ) { registerMBeanServer ( server ) ; } else { LOG . error ( "No MBeanServer available so cannot register mbean" ) ; } }
Registers the object with JMX
59
7
25,170
protected String checkAgentUrl ( Object pVm ) throws NoSuchMethodException , InvocationTargetException , IllegalAccessException { Properties systemProperties = getAgentSystemProperties ( pVm ) ; return systemProperties . getProperty ( JvmAgent . JOLOKIA_AGENT_URL ) ; }
borrowed these from AbstractBaseCommand for now
66
10
25,171
protected int indexOf ( String text , String ... values ) { int answer = - 1 ; for ( String value : values ) { int idx = text . indexOf ( value ) ; if ( idx >= 0 ) { if ( answer < 0 || idx < answer ) { answer = idx ; } } } return answer ; }
Returns the lowest index of the given list of values
71
10
25,172
public static FileLocker getLock ( File lockFile ) { lockFile . getParentFile ( ) . mkdirs ( ) ; if ( ! lockFile . exists ( ) ) { try { IOHelper . write ( lockFile , "I have the lock!" ) ; lockFile . deleteOnExit ( ) ; return new FileLocker ( lockFile ) ; } catch ( IOException e ) { // Ignore } } return null ; }
Attempts to grab the lock for the given file returning a FileLock if the lock has been created ; otherwise it returns null
94
24
25,173
public static String getVersion ( Class < ? > aClass , String groupId , String artifactId ) { String version = null ; // lets try find the maven property - as the Java API rarely works :) InputStream is = null ; String fileName = "/META-INF/maven/" + groupId + "/" + artifactId + "/pom.properties" ; // try to load from maven properties first try { Properties p = new Properties ( ) ; is = aClass . getResourceAsStream ( fileName ) ; if ( is != null ) { p . load ( is ) ; version = p . getProperty ( "version" , "" ) ; } } catch ( Exception e ) { // ignore } finally { if ( is != null ) { IOHelper . close ( is , fileName , LOG ) ; } } if ( version == null ) { Package aPackage = aClass . getPackage ( ) ; if ( aPackage != null ) { version = aPackage . getImplementationVersion ( ) ; if ( Strings . isBlank ( version ) ) { version = aPackage . getSpecificationVersion ( ) ; } } } if ( version == null ) { Enumeration < URL > resources = null ; try { resources = aClass . getClassLoader ( ) . getResources ( "META-INF/MANIFEST.MF" ) ; } catch ( IOException e ) { // ignore } if ( resources != null ) { String expectedBundleName = groupId + "." + artifactId ; while ( resources . hasMoreElements ( ) ) { try { Manifest manifest = new Manifest ( resources . nextElement ( ) . openStream ( ) ) ; Attributes attributes = manifest . getMainAttributes ( ) ; String bundleName = attributes . getValue ( "Bundle-SymbolicName" ) ; if ( Objects . equals ( expectedBundleName , bundleName ) ) { version = attributes . getValue ( "Implementation-Version" ) ; if ( Strings . isNotBlank ( version ) ) break ; } } catch ( IOException e ) { // ignore } } } } return version ; }
Returns the version of the given class s package or the group and artifact of the jar
455
17
25,174
public void clear ( ) { mCardNumberEditText . setText ( "" ) ; mExpiryDateEditText . setText ( "" ) ; mCvcEditText . setText ( "" ) ; mPostalCodeEditText . setText ( "" ) ; mCardNumberEditText . setShouldShowError ( false ) ; mExpiryDateEditText . setShouldShowError ( false ) ; mCvcEditText . setShouldShowError ( false ) ; mPostalCodeEditText . setShouldShowError ( false ) ; updateBrand ( Card . UNKNOWN ) ; }
Clear all entered data and hide all error messages .
126
10
25,175
public boolean validateCardNumber ( ) { boolean cardNumberIsValid = CardUtils . isValidCardNumber ( mCardNumberEditText . getCardNumber ( ) ) ; mCardNumberEditText . setShouldShowError ( ! cardNumberIsValid ) ; return cardNumberIsValid ; }
Checks whether the current card number is valid
61
9
25,176
public void setExpiryDate ( @ IntRange ( from = 1 , to = 12 ) int month , @ IntRange ( from = 0 , to = 9999 ) int year ) { mExpiryDateEditText . setText ( DateUtils . createDateStringFromIntegerInput ( month , year ) ) ; }
Set the expiration date . Method invokes completion listener and changes focus to the CVC field if a valid date is entered .
69
25
25,177
public void clear ( ) { if ( mCardNumberEditText . hasFocus ( ) || mExpiryDateEditText . hasFocus ( ) || mCvcNumberEditText . hasFocus ( ) || this . hasFocus ( ) ) { mCardNumberEditText . requestFocus ( ) ; } mCvcNumberEditText . setText ( "" ) ; mExpiryDateEditText . setText ( "" ) ; mCardNumberEditText . setText ( "" ) ; }
Clear all text fields in the CardInputWidget .
104
10
25,178
public void setEnabled ( boolean isEnabled ) { mCardNumberEditText . setEnabled ( isEnabled ) ; mExpiryDateEditText . setEnabled ( isEnabled ) ; mCvcNumberEditText . setEnabled ( isEnabled ) ; }
Enable or disable text fields
49
5
25,179
public void setHintDelayed ( @ StringRes final int hintResource , long delayMilliseconds ) { final Runnable hintRunnable = new Runnable ( ) { @ Override public void run ( ) { setHint ( hintResource ) ; } } ; mHandler . postDelayed ( hintRunnable , delayMilliseconds ) ; }
Change the hint value of this control after a delay .
78
11
25,180
public void setShouldShowError ( boolean shouldShowError ) { if ( mErrorMessage != null && mErrorMessageListener != null ) { String errorMessage = shouldShowError ? mErrorMessage : null ; mErrorMessageListener . displayErrorMessage ( errorMessage ) ; mShouldShowError = shouldShowError ; } else { mShouldShowError = shouldShowError ; if ( mShouldShowError ) { setTextColor ( mErrorColor ) ; } else { setTextColor ( mCachedColorStateList ) ; } refreshDrawableState ( ) ; } }
Sets whether or not the text should be put into error mode which displays the text in an error color determined by the original text color .
117
28
25,181
private void showDialog ( @ NonNull final Source source ) { // Caching the source object here because this app makes a lot of them. mRedirectSource = source ; final SourceRedirect sourceRedirect = source . getRedirect ( ) ; final String redirectUrl = sourceRedirect != null ? sourceRedirect . getUrl ( ) : null ; if ( redirectUrl != null ) { mRedirectDialogController . showDialog ( redirectUrl ) ; } }
Show a dialog with a link to the external verification site .
97
12
25,182
private void handlePostAuthReturn ( ) { final Uri intentUri = getIntent ( ) . getData ( ) ; if ( intentUri != null ) { if ( "stripe" . equals ( intentUri . getScheme ( ) ) && "payment-auth-return" . equals ( intentUri . getHost ( ) ) ) { final String paymentIntentClientSecret = intentUri . getQueryParameter ( "payment_intent_client_secret" ) ; if ( paymentIntentClientSecret != null ) { final Stripe stripe = new Stripe ( getApplicationContext ( ) , PaymentConfiguration . getInstance ( ) . getPublishableKey ( ) ) ; final PaymentIntentParams paymentIntentParams = PaymentIntentParams . createRetrievePaymentIntentParams ( paymentIntentClientSecret ) ; mCompositeDisposable . add ( Observable . fromCallable ( ( ) -> stripe . retrievePaymentIntentSynchronous ( paymentIntentParams , PaymentConfiguration . getInstance ( ) . getPublishableKey ( ) ) ) . subscribeOn ( Schedulers . io ( ) ) . observeOn ( AndroidSchedulers . mainThread ( ) ) . subscribe ( ( paymentIntent -> { if ( paymentIntent != null ) { handleRetrievedPaymentIntent ( paymentIntent ) ; } } ) ) ) ; } } } }
If the intent URI matches the post auth deep - link URI the user attempted to authenticate payment and was returned to the app . Retrieve the PaymentIntent and inform the user about the state of their payment .
302
43
25,183
@ Size ( 2 ) @ NonNull static String [ ] separateDateStringParts ( @ NonNull @ Size ( max = 4 ) String expiryInput ) { String [ ] parts = new String [ 2 ] ; if ( expiryInput . length ( ) >= 2 ) { parts [ 0 ] = expiryInput . substring ( 0 , 2 ) ; parts [ 1 ] = expiryInput . substring ( 2 ) ; } else { parts [ 0 ] = expiryInput ; parts [ 1 ] = "" ; } return parts ; }
Separates raw string input of the format MMYY into a month group and a year group . Either or both of these may be incomplete . This method does not check to see if the input is valid .
113
42
25,184
@ IntRange ( from = 1000 , to = 9999 ) static int convertTwoDigitYearToFour ( @ IntRange ( from = 0 , to = 99 ) int inputYear ) { return convertTwoDigitYearToFour ( inputYear , Calendar . getInstance ( ) ) ; }
Converts a two - digit input year to a four - digit year . As the current calendar year approaches a century we assume small values to mean the next century . For instance if the current year is 2090 and the input value is 18 the user probably means 2118 not 2018 . However in 2017 the input 18 probably means 2018 . This code should be updated before the year 9981 .
61
79
25,185
@ NonNull public static SourceParams createSourceFromTokenParams ( String tokenId ) { SourceParams sourceParams = SourceParams . createCustomParams ( ) ; sourceParams . setType ( Source . CARD ) ; sourceParams . setToken ( tokenId ) ; return sourceParams ; }
Create parameters necessary for converting a token into a source
67
10
25,186
@ NonNull public static Map < String , Object > createRetrieveSourceParams ( @ NonNull @ Size ( min = 1 ) String clientSecret ) { final Map < String , Object > params = new HashMap <> ( ) ; params . put ( API_PARAM_CLIENT_SECRET , clientSecret ) ; return params ; }
Create parameters needed to retrieve a source .
73
8
25,187
public void clearReferences ( ) { if ( mAsyncTaskController != null ) { mAsyncTaskController . detach ( ) ; } if ( mRxTokenController != null ) { mRxTokenController . detach ( ) ; } if ( mIntentServiceTokenController != null ) { mIntentServiceTokenController . detach ( ) ; } mAsyncTaskController = null ; mRxTokenController = null ; mIntentServiceTokenController = null ; }
Clear all the references so that we can start over again .
98
12
25,188
public Surface rotate ( float angle ) { float sr = ( float ) Math . sin ( angle ) ; float cr = ( float ) Math . cos ( angle ) ; transform ( cr , sr , - sr , cr , 0 , 0 ) ; return this ; }
Rotates the current transformation matrix by the specified angle in radians .
54
14
25,189
public Surface transform ( float m00 , float m01 , float m10 , float m11 , float tx , float ty ) { AffineTransform top = tx ( ) ; Transforms . multiply ( top , m00 , m01 , m10 , m11 , tx , ty , top ) ; return this ; }
Multiplies the current transformation matrix by the given matrix .
66
12
25,190
public boolean intersects ( float x , float y , float w , float h ) { tx ( ) . transform ( intersectionTestPoint . set ( x , y ) , intersectionTestPoint ) ; tx ( ) . transform ( intersectionTestSize . set ( w , h ) , intersectionTestSize ) ; float ix = intersectionTestPoint . x , iy = intersectionTestPoint . y ; float iw = intersectionTestSize . x , ih = intersectionTestSize . y ; if ( scissorDepth > 0 ) { Rectangle scissor = scissors . get ( scissorDepth - 1 ) ; return scissor . intersects ( ( int ) ix , ( int ) iy , ( int ) iw , ( int ) ih ) ; } float tw = target . width ( ) , th = target . height ( ) ; return ( ix + iw > 0 ) && ( ix < tw ) && ( iy + ih > 0 ) && ( iy < th ) ; }
Returns whether the given rectangle intersects the render target area of this surface .
215
15
25,191
public Surface fillRect ( float x , float y , float width , float height ) { if ( patternTex != null ) { batch . addQuad ( patternTex , tint , tx ( ) , x , y , width , height ) ; } else { batch . addQuad ( colorTex , Tint . combine ( fillColor , tint ) , tx ( ) , x , y , width , height ) ; } return this ; }
Fills the specified rectangle .
91
6
25,192
private String [ ] platformNames ( String libraryName ) { if ( isWindows ) return new String [ ] { libraryName + ( is64Bit ? "64.dll" : ".dll" ) } ; if ( isLinux ) return new String [ ] { "lib" + libraryName + ( is64Bit ? "64.so" : ".so" ) } ; if ( isMac ) return new String [ ] { "lib" + libraryName + ".jnilib" , "lib" + libraryName + ".dylib" } ; return new String [ ] { libraryName } ; }
Maps a platform independent library name to one or more platform dependent names .
125
14
25,193
private String crc ( InputStream input ) { if ( input == null ) throw new IllegalArgumentException ( "input cannot be null." ) ; CRC32 crc = new CRC32 ( ) ; byte [ ] buffer = new byte [ 4096 ] ; try { while ( true ) { int length = input . read ( buffer ) ; if ( length == - 1 ) break ; crc . update ( buffer , 0 , length ) ; } } catch ( Exception ex ) { try { input . close ( ) ; } catch ( Exception ignored ) { } } return Long . toString ( crc . getValue ( ) ) ; }
Returns a CRC of the remaining bytes in the stream .
132
11
25,194
public CharBuffer put ( String str , int start , int end ) { int length = str . length ( ) ; if ( start < 0 || end < start || end > length ) { throw new IndexOutOfBoundsException ( ) ; } if ( end - start > remaining ( ) ) { throw new BufferOverflowException ( ) ; } for ( int i = start ; i < end ; i ++ ) { put ( str . charAt ( i ) ) ; } return this ; }
Writes chars of the given string to the current position of this buffer and increases the position by the number of chars written .
103
25
25,195
public RFuture < String > get ( String url ) { return req ( url ) . execute ( ) . map ( GET_PAYLOAD ) ; }
Performs an HTTP GET request to the specified URL .
32
11
25,196
public RFuture < String > post ( String url , String data ) { return req ( url ) . setPayload ( data ) . execute ( ) . map ( GET_PAYLOAD ) ; }
Performs an HTTP POST request to the specified URL .
42
11
25,197
public Region region ( final float rx , final float ry , final float rwidth , final float rheight ) { final Image image = this ; return new Region ( ) { private Tile tile ; @ Override public boolean isLoaded ( ) { return image . isLoaded ( ) ; } @ Override public Tile tile ( ) { if ( tile == null ) tile = image . texture ( ) . tile ( rx , ry , rwidth , rheight ) ; return tile ; } @ Override public RFuture < Tile > tileAsync ( ) { return image . state . map ( new Function < Image , Tile > ( ) { public Tile apply ( Image image ) { return tile ( ) ; } } ) ; } @ Override public float width ( ) { return rwidth ; } @ Override public float height ( ) { return rheight ; } @ Override public void draw ( Object ctx , float x , float y , float width , float height ) { image . draw ( ctx , x , y , width , height , rx , ry , rwidth , rheight ) ; } @ Override public void draw ( Object ctx , float dx , float dy , float dw , float dh , float sx , float sy , float sw , float sh ) { image . draw ( ctx , dx , dy , dw , dh , rx + sx , ry + sy , sw , sh ) ; } } ; }
Returns a region of this image which can be drawn independently .
306
12
25,198
public void resize ( float width , float height ) { if ( canvas != null ) canvas . close ( ) ; canvas = gfx . createCanvas ( width , height ) ; }
Resizes the canvas that is displayed by this layer .
38
11
25,199
public void end ( ) { Texture tex = ( Texture ) tile ( ) ; Image image = canvas . image ; // if our texture is already the right size, just update it if ( tex != null && tex . pixelWidth == image . pixelWidth ( ) && tex . pixelHeight == image . pixelHeight ( ) ) tex . update ( image ) ; // otherwise we need to create a new texture (setTexture will unreference the old texture which // will cause it to be destroyed) else super . setTile ( canvas . image . createTexture ( Texture . Config . DEFAULT ) ) ; }
Informs this layer that a drawing operation has just completed . The backing canvas image data is uploaded to the GPU .
123
23