idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
13,600
public static boolean isApptentivePushNotification ( Intent intent ) { try { if ( ! ApptentiveInternal . checkRegistered ( ) ) { return false ; } return ApptentiveInternal . getApptentivePushNotificationData ( intent ) != null ; } catch ( Exception e ) { ApptentiveLog . e ( PUSH , e , "Exception while checking for Apptentive push notification intent" ) ; logException ( e ) ; } return false ; }
Determines whether this Intent is a push notification sent from Apptentive .
105
17
13,601
public static boolean isApptentivePushNotification ( Bundle bundle ) { try { if ( ! ApptentiveInternal . checkRegistered ( ) ) { return false ; } return ApptentiveInternal . getApptentivePushNotificationData ( bundle ) != null ; } catch ( Exception e ) { ApptentiveLog . e ( PUSH , e , "Exception while checking for Apptentive push notification bundle" ) ; logException ( e ) ; } return false ; }
Determines whether this Bundle came from an Apptentive push notification . This method is used with Urban Airship integrations .
105
27
13,602
public static boolean isApptentivePushNotification ( Map < String , String > data ) { try { if ( ! ApptentiveInternal . checkRegistered ( ) ) { return false ; } return ApptentiveInternal . getApptentivePushNotificationData ( data ) != null ; } catch ( Exception e ) { ApptentiveLog . e ( PUSH , e , "Exception while checking for Apptentive push notification data" ) ; logException ( e ) ; } return false ; }
Determines whether push payload data came from an Apptentive push notification .
110
17
13,603
public static void setRatingProvider ( IRatingProvider ratingProvider ) { try { if ( ApptentiveInternal . isApptentiveRegistered ( ) ) { ApptentiveInternal . getInstance ( ) . setRatingProvider ( ratingProvider ) ; } } catch ( Exception e ) { ApptentiveLog . e ( CONVERSATION , e , "Exception while setting rating provider" ) ; logException ( e ) ; } }
Use this to choose where to send the user when they are prompted to rate the app . This should be the same place that the app was downloaded from .
92
31
13,604
public static void showMessageCenter ( final Context context , final BooleanCallback callback , final Map < String , Object > customData ) { dispatchConversationTask ( new ConversationDispatchTask ( callback , DispatchQueue . mainQueue ( ) ) { @ Override protected boolean execute ( Conversation conversation ) { return ApptentiveInternal . getInstance ( ) . showMessageCenterInternal ( context , customData ) ; } } , "show message center" ) ; }
Opens the Apptentive Message Center UI Activity and allows custom data to be sent with the next message the user sends . If the user sends multiple messages this data will only be sent with the first message sent after this method is invoked . Additional invocations of this method with custom data will repeat this process . If Message Center is closed without a message being sent the custom data is cleared . This task is performed asynchronously . Message Center configuration may not have been downloaded yet when this is called .
94
101
13,605
public static void canShowMessageCenter ( BooleanCallback callback ) { dispatchConversationTask ( new ConversationDispatchTask ( callback , DispatchQueue . mainQueue ( ) ) { @ Override protected boolean execute ( Conversation conversation ) { return ApptentiveInternal . canShowMessageCenterInternal ( conversation ) ; } } , "check message center availability" ) ; }
Our SDK must connect to our server at least once to download initial configuration for Message Center . Call this method to see whether or not Message Center can be displayed . This task is performed asynchronously .
74
40
13,606
public static void addUnreadMessagesListener ( final UnreadMessagesListener listener ) { dispatchConversationTask ( new ConversationDispatchTask ( ) { @ Override protected boolean execute ( Conversation conversation ) { conversation . getMessageManager ( ) . addHostUnreadMessagesListener ( listener ) ; return true ; } } , "add unread message listener" ) ; }
Add a listener to be notified when the number of unread messages in the Message Center changes .
78
19
13,607
public static int getUnreadMessageCount ( ) { try { if ( ApptentiveInternal . isApptentiveRegistered ( ) ) { ConversationProxy conversationProxy = ApptentiveInternal . getInstance ( ) . getConversationProxy ( ) ; return conversationProxy != null ? conversationProxy . getUnreadMessageCount ( ) : 0 ; } } catch ( Exception e ) { ApptentiveLog . e ( MESSAGES , e , "Exception while getting unread message count" ) ; logException ( e ) ; } return 0 ; }
Returns the number of unread messages in the Message Center .
119
12
13,608
public static void sendAttachmentText ( final String text ) { dispatchConversationTask ( new ConversationDispatchTask ( ) { @ Override protected boolean execute ( Conversation conversation ) { CompoundMessage message = new CompoundMessage ( ) ; message . setBody ( text ) ; message . setRead ( true ) ; message . setHidden ( true ) ; message . setSenderId ( conversation . getPerson ( ) . getId ( ) ) ; message . setAssociatedFiles ( null ) ; conversation . getMessageManager ( ) . sendMessage ( message ) ; return true ; } } , "send attachment text" ) ; }
Sends a text message to the server . This message will be visible in the conversation view on the server but will not be shown in the client s Message Center .
130
33
13,609
public static synchronized void engage ( Context context , String event , BooleanCallback callback ) { engage ( context , event , callback , null , ( ExtendedData [ ] ) null ) ; }
This method takes a unique event string stores a record of that event having been visited determines if there is an interaction that is able to run for this event and then runs it . If more than one interaction can run then the most appropriate interaction takes precedence . Only one interaction at most will run per invocation of this method . This task is performed asynchronously .
37
71
13,610
public static synchronized void engage ( final Context context , final String event , final BooleanCallback callback , final Map < String , Object > customData , final ExtendedData ... extendedData ) { if ( context == null ) { throw new IllegalArgumentException ( "Context is null" ) ; } if ( StringUtils . isNullOrEmpty ( event ) ) { throw new IllegalArgumentException ( "Event is null or empty" ) ; } // first, we check if there's an engagement callback to inject final OnPreInteractionListener preInteractionListener = Apptentive . preInteractionListener ; // capture variable to avoid concurrency issues if ( preInteractionListener != null ) { dispatchConversationTask ( new ConversationDispatchTask ( callback , DispatchQueue . mainQueue ( ) ) { @ Override protected boolean execute ( Conversation conversation ) { if ( ! canShowLocalAppInteraction ( conversation , event ) ) { return false ; } boolean allowsInteraction = preInteractionListener . shouldEngageInteraction ( event , customData ) ; ApptentiveLog . i ( "Engagement callback allows interaction for event '%s': %b" , event , allowsInteraction ) ; if ( ! allowsInteraction ) { return false ; } return engageLocalAppEvent ( context , conversation , event , customData , extendedData ) ; // actually engage event } } , StringUtils . format ( "engage '%s' event" , event ) ) ; return ; } dispatchConversationTask ( new ConversationDispatchTask ( callback , DispatchQueue . mainQueue ( ) ) { @ Override protected boolean execute ( Conversation conversation ) { return engageLocalAppEvent ( context , conversation , event , customData , extendedData ) ; } } , StringUtils . format ( "engage '%s' event" , event ) ) ; }
This method takes a unique event string stores a record of that event having been visited determines if there is an interaction that is able to run for this event and then runs it . If more than one interaction can run then the most appropriate interaction takes precedence . Only one interaction at most will run per invocation of this method .
386
63
13,611
public static void login ( final String token , final LoginCallback callback ) { if ( StringUtils . isNullOrEmpty ( token ) ) { throw new IllegalArgumentException ( "Token is null or empty" ) ; } dispatchOnConversationQueue ( new DispatchTask ( ) { @ Override protected void execute ( ) { try { loginGuarded ( token , callback ) ; } catch ( Exception e ) { ApptentiveLog . e ( CONVERSATION , e , "Exception while trying to login" ) ; logException ( e ) ; notifyFailure ( callback , "Exception while trying to login" ) ; } } } ) ; }
Starts login process asynchronously . This call returns immediately . Using this method requires you to implement JWT generation on your server . Please read about it in Apptentive s Android Integration Reference Guide .
136
42
13,612
public static < T > String join ( List < T > list , String separator ) { StringBuilder builder = new StringBuilder ( ) ; int i = 0 ; for ( T t : list ) { builder . append ( t ) ; if ( ++ i < list . size ( ) ) builder . append ( separator ) ; } return builder . toString ( ) ; }
Constructs and returns a string object that is the result of interposing a separator between the elements of the list
78
23
13,613
public static String trim ( String str ) { return str != null && str . length ( ) > 0 ? str . trim ( ) : str ; }
Safely trims input string
31
6
13,614
public static String asJson ( String key , Object value ) { try { JSONObject json = new JSONObject ( ) ; json . put ( key , value ) ; return json . toString ( ) ; } catch ( Exception e ) { ApptentiveLog . e ( e , "Exception while creating json-string { %s:%s }" , key , value ) ; return null ; } }
Creates a simple json string from key and value
86
10
13,615
public static byte [ ] hexToBytes ( String hex ) { int length = hex . length ( ) ; byte [ ] ret = new byte [ length / 2 ] ; for ( int i = 0 ; i < length ; i += 2 ) { ret [ i / 2 ] = ( byte ) ( ( Character . digit ( hex . charAt ( i ) , 16 ) << 4 ) + Character . digit ( hex . charAt ( i + 1 ) , 16 ) ) ; } return ret ; }
Converts a hex String to a byte array .
104
10
13,616
void dispatchRequest ( final HttpRequest request ) { networkQueue . dispatchAsync ( new DispatchTask ( ) { @ Override protected void execute ( ) { request . dispatchSync ( networkQueue ) ; } } ) ; }
Handles request synchronously
46
5
13,617
public synchronized void cancelAll ( ) { if ( activeRequests . size ( ) > 0 ) { List < HttpRequest > temp = new ArrayList <> ( activeRequests ) ; for ( HttpRequest request : temp ) { request . cancel ( ) ; } } notifyCancelledAllRequests ( ) ; }
Cancel all active requests
69
5
13,618
synchronized void unregisterRequest ( HttpRequest request ) { assertTrue ( this == request . requestManager ) ; boolean removed = activeRequests . remove ( request ) ; assertTrue ( removed , "Attempted to unregister missing request: %s" , request ) ; if ( removed ) { notifyRequestFinished ( request ) ; } }
Unregisters active request
73
5
13,619
public HttpJsonRequest createConversationTokenRequest ( ConversationTokenRequest conversationTokenRequest , HttpRequest . Listener < HttpJsonRequest > listener ) { HttpJsonRequest request = createJsonRequest ( ENDPOINT_CONVERSATION , conversationTokenRequest , HttpRequestMethod . POST ) ; request . addListener ( listener ) ; return request ; }
region API Requests
81
4
13,620
public boolean validateAndUpdateState ( ) { boolean validationPassed = true ; List < Fragment > fragments = getRetainedChildFragmentManager ( ) . getFragments ( ) ; for ( Fragment fragment : fragments ) { SurveyQuestionView surveyQuestionView = ( SurveyQuestionView ) fragment ; answers . put ( surveyQuestionView . getQuestionId ( ) , surveyQuestionView . getAnswer ( ) ) ; boolean isValid = surveyQuestionView . isValid ( ) ; surveyQuestionView . updateValidationState ( isValid ) ; if ( ! isValid ) { validationPassed = false ; } } return validationPassed ; }
Run this when the user hits the send button and only send if it returns true . This method will update the visual validation state of all questions and update the answers instance variable with the latest answer state .
133
40
13,621
private void exitActivity ( ApptentiveViewExitType exitType ) { try { exitActivityGuarded ( exitType ) ; } catch ( Exception e ) { ApptentiveLog . e ( e , "Exception while trying to exit activity (type=%s)" , exitType ) ; logException ( e ) ; } }
Helper to clean up the Activity whether it is exited through the toolbar back button or the hardware back button .
70
21
13,622
public static void startSession ( final Context context , final String appKey , final String appSignature ) { dispatchOnConversationQueue ( new DispatchTask ( ) { @ Override protected void execute ( ) { try { startSessionGuarded ( context , appKey , appSignature ) ; } catch ( Exception e ) { ApptentiveLog . e ( TROUBLESHOOT , e , "Unable to start Apptentive Log Monitor" ) ; logException ( e ) ; } } } ) ; }
Attempts to start a new troubleshooting session . First the SDK will check if there is an existing session stored in the persistent storage and then check if the clipboard contains a valid access token . This call is async and returns immediately .
111
45
13,623
private static @ Nullable String readAccessTokenFromClipboard ( Context context ) { String text = Util . getClipboardText ( context ) ; if ( StringUtils . isNullOrEmpty ( text ) ) { return null ; } //Since the token string should never contain spaces, attempt to repair line breaks introduced in the copying process. text = text . replaceAll ( "\\s+" , "" ) ; if ( ! text . startsWith ( DEBUG_TEXT_HEADER ) ) { return null ; } // Remove the header return text . substring ( DEBUG_TEXT_HEADER . length ( ) ) ; }
Attempts to read access token from the clipboard
133
8
13,624
private static HttpRequest createTokenVerificationRequest ( String apptentiveAppKey , String apptentiveAppSignature , String token , HttpRequest . Listener < HttpJsonRequest > listener ) { // TODO: move this logic to ApptentiveHttpClient String URL = Constants . CONFIG_DEFAULT_SERVER_URL + "/debug_token/verify" ; HttpRequest request = new HttpJsonRequest ( URL , createVerityRequestObject ( token ) ) ; request . setTag ( TAG_VERIFICATION_REQUEST ) ; request . setMethod ( HttpRequestMethod . POST ) ; request . setRequestManager ( HttpRequestManager . sharedManager ( ) ) ; request . setRequestProperty ( "X-API-Version" , Constants . API_VERSION ) ; request . setRequestProperty ( "APPTENTIVE-KEY" , apptentiveAppKey ) ; request . setRequestProperty ( "APPTENTIVE-SIGNATURE" , apptentiveAppSignature ) ; request . setRequestProperty ( "Content-Type" , "application/json" ) ; request . setRequestProperty ( "Accept" , "application/json" ) ; request . setRequestProperty ( "User-Agent" , String . format ( USER_AGENT_STRING , Constants . getApptentiveSdkVersion ( ) ) ) ; request . setRetryPolicy ( createVerityRequestRetryPolicy ( ) ) ; request . addListener ( listener ) ; return request ; }
region Token Verification
332
4
13,625
public boolean clickOn ( int index ) { ImageItem item = getItem ( index ) ; if ( item == null || TextUtils . isEmpty ( item . mimeType ) ) { return false ; } // For non-image items, the first tap will start it downloading if ( ! Util . isMimeTypeImage ( item . mimeType ) ) { // It is being downloaded, do nothing (prevent double tap, etc) if ( downloadItems . contains ( item . originalPath ) ) { return true ; } else { // If no write permission, do not try to download. Instead let caller handles it by launching browser if ( ! bHasWritePermission ) { return false ; } File localFile = new File ( item . localCachePath ) ; if ( localFile . exists ( ) && ApptentiveAttachmentLoader . getInstance ( ) . isFileCompletelyDownloaded ( item . localCachePath ) ) { // If have right permission, and already downloaded, let caller open 3rd app to view it return false ; } else { // First tap detected and never download before, start download downloadItems . add ( item . originalPath ) ; notifyDataSetChanged ( ) ; return true ; } } } return false ; }
Click an image
263
3
13,626
public void select ( ImageItem image ) { if ( selectedImages . contains ( image ) ) { selectedImages . remove ( image ) ; } else { selectedImages . add ( image ) ; } notifyDataSetChanged ( ) ; }
Select an image
48
3
13,627
public void setDefaultSelected ( ArrayList < String > resultList ) { for ( String uri : resultList ) { ImageItem image = getImageByUri ( uri ) ; if ( image != null ) { selectedImages . add ( image ) ; } } if ( selectedImages . size ( ) > 0 ) { notifyDataSetChanged ( ) ; } }
Re - Select image from selected list result
78
8
13,628
public void setData ( List < ImageItem > images ) { selectedImages . clear ( ) ; if ( images != null && images . size ( ) > 0 ) { this . images = images ; } else { this . images . clear ( ) ; } notifyDataSetChanged ( ) ; }
Re - select image from selected image set
61
8
13,629
public void setItemSize ( int columnWidth , int columnHeight ) { if ( itemWidth == columnWidth ) { return ; } itemWidth = columnWidth ; itemHeight = columnHeight ; itemLayoutParams = new GridView . LayoutParams ( itemWidth , itemHeight ) ; notifyDataSetChanged ( ) ; }
Reset colum size
67
5
13,630
public static void sendError ( final Throwable throwable , final String description , final String extraData ) { if ( ! isConversationQueue ( ) ) { dispatchOnConversationQueue ( new DispatchTask ( ) { @ Override protected void execute ( ) { sendError ( throwable , description , extraData ) ; } } ) ; return ; } EventPayload . EventLabel type = EventPayload . EventLabel . error ; try { JSONObject data = new JSONObject ( ) ; data . put ( "thread" , Thread . currentThread ( ) . getName ( ) ) ; if ( throwable != null ) { JSONObject exception = new JSONObject ( ) ; exception . put ( "message" , throwable . getMessage ( ) ) ; exception . put ( "stackTrace" , Util . stackTraceAsString ( throwable ) ) ; data . put ( KEY_EXCEPTION , exception ) ; } if ( description != null ) { data . put ( "description" , description ) ; } if ( extraData != null ) { data . put ( "extraData" , extraData ) ; } Configuration config = Configuration . load ( ) ; if ( config . isMetricsEnabled ( ) ) { ApptentiveLog . v ( UTIL , "Sending Error Metric: %s, data: %s" , type . getLabelName ( ) , data . toString ( ) ) ; EventPayload event = new EventPayload ( type . getLabelName ( ) , data ) ; sendEvent ( event ) ; } } catch ( Exception e ) { // Since this is the last place in Apptentive code we can catch exceptions, we must catch all other Exceptions to // prevent the app from crashing. ApptentiveLog . w ( UTIL , e , "Error creating Error Metric. Nothing we can do but log this." ) ; } }
Used for internal error reporting when we intercept a Throwable that may have otherwise caused a crash .
403
19
13,631
public static Integer parseWebColorAsAndroidColor ( String input ) { // Swap if input is #RRGGBBAA, but not if it is #RRGGBB Boolean swapAlpha = ( input . length ( ) == 9 ) ; try { Integer ret = Color . parseColor ( input ) ; if ( swapAlpha ) { ret = ( ret >>> 8 ) | ( ( ret & 0x000000FF ) << 24 ) ; } return ret ; } catch ( IllegalArgumentException e ) { logException ( e ) ; } return null ; }
The web standard for colors is RGBA but Android uses ARGB . This method provides a way to convert RGBA to ARGB .
115
27
13,632
public static Drawable getCompatDrawable ( Context c , int drawableRes ) { Drawable d = null ; try { d = ContextCompat . getDrawable ( c , drawableRes ) ; } catch ( Exception ex ) { logException ( ex ) ; } return d ; }
helper method to get the drawable by its resource id specific to the correct android version
60
18
13,633
public static StateListDrawable getSelectableImageButtonBackground ( int selected_color ) { ColorDrawable selectedColor = new ColorDrawable ( selected_color ) ; StateListDrawable states = new StateListDrawable ( ) ; states . addState ( new int [ ] { android . R . attr . state_pressed } , selectedColor ) ; states . addState ( new int [ ] { android . R . attr . state_activated } , selectedColor ) ; return states ; }
helper method to generate the ImageButton background with specified highlight color .
105
14
13,634
public static boolean openFileAttachment ( final Context context , final String sourcePath , final String selectedFilePath , final String mimeTypeString ) { if ( ( Environment . MEDIA_MOUNTED . equals ( Environment . getExternalStorageState ( ) ) || ! Environment . isExternalStorageRemovable ( ) ) && hasPermission ( context , Manifest . permission . WRITE_EXTERNAL_STORAGE ) ) { File selectedFile = new File ( selectedFilePath ) ; String selectedFileName = null ; if ( selectedFile . exists ( ) ) { selectedFileName = selectedFile . getName ( ) ; final Intent intent = new Intent ( ) ; intent . setAction ( android . content . Intent . ACTION_VIEW ) ; /* Attachments were downloaded into app private data dir. In order for external app to open * the attachments, the file need to be copied to a download folder that is accessible to public * The folder will be sdcard/Downloads/apptentive-received/<file name> */ File downloadFolder = Environment . getExternalStoragePublicDirectory ( Environment . DIRECTORY_DOWNLOADS ) ; File apptentiveSubFolder = new File ( downloadFolder , "apptentive-received" ) ; if ( ! apptentiveSubFolder . exists ( ) ) { apptentiveSubFolder . mkdir ( ) ; } File tmpfile = new File ( apptentiveSubFolder , selectedFileName ) ; String tmpFilePath = tmpfile . getPath ( ) ; // If destination file already exists, overwrite it; otherwise, delete all existing files in the same folder first. if ( ! tmpfile . exists ( ) ) { String [ ] children = apptentiveSubFolder . list ( ) ; if ( children != null ) { for ( int i = 0 ; i < children . length ; i ++ ) { new File ( apptentiveSubFolder , children [ i ] ) . delete ( ) ; } } } if ( copyFile ( selectedFilePath , tmpFilePath ) == 0 ) { return false ; } intent . setDataAndType ( Uri . fromFile ( tmpfile ) , mimeTypeString ) ; try { context . startActivity ( intent ) ; return true ; } catch ( ActivityNotFoundException e ) { ApptentiveLog . e ( e , "Activity not found to open attachment: " ) ; logException ( e ) ; } } } else { Intent browserIntent = new Intent ( Intent . ACTION_VIEW , Uri . parse ( sourcePath ) ) ; if ( Util . canLaunchIntent ( context , browserIntent ) ) { context . startActivity ( browserIntent ) ; } } return false ; }
This function launchs the default app to view the selected file based on mime type
573
17
13,635
public static int copyFile ( String from , String to ) { InputStream inStream = null ; FileOutputStream fs = null ; try { int bytesum = 0 ; int byteread ; File oldfile = new File ( from ) ; if ( oldfile . exists ( ) ) { inStream = new FileInputStream ( from ) ; fs = new FileOutputStream ( to ) ; byte [ ] buffer = new byte [ 1444 ] ; while ( ( byteread = inStream . read ( buffer ) ) != - 1 ) { bytesum += byteread ; fs . write ( buffer , 0 , byteread ) ; } } return bytesum ; } catch ( Exception e ) { return 0 ; } finally { Util . ensureClosed ( inStream ) ; Util . ensureClosed ( fs ) ; } }
This function copies file from one location to another
179
9
13,636
public static StoredFile createLocalStoredFile ( String sourceUrl , String localFilePath , String mimeType ) { InputStream is = null ; try { Context context = ApptentiveInternal . getInstance ( ) . getApplicationContext ( ) ; if ( URLUtil . isContentUrl ( sourceUrl ) && context != null ) { Uri uri = Uri . parse ( sourceUrl ) ; is = context . getContentResolver ( ) . openInputStream ( uri ) ; } else { File file = new File ( sourceUrl ) ; is = new FileInputStream ( file ) ; } return createLocalStoredFile ( is , sourceUrl , localFilePath , mimeType ) ; } catch ( FileNotFoundException e ) { return null ; } finally { ensureClosed ( is ) ; } }
This method creates a cached file exactly copying from the input stream .
174
13
13,637
public static StoredFile createLocalStoredFile ( InputStream is , String sourceUrl , String localFilePath , String mimeType ) { if ( is == null ) { return null ; } // Copy the file contents over. CountingOutputStream cos = null ; BufferedOutputStream bos = null ; FileOutputStream fos = null ; try { File localFile = new File ( localFilePath ) ; /* Local cache file name may not be unique, and can be reused, in which case, the previously created * cache file need to be deleted before it is being copied over. */ if ( localFile . exists ( ) ) { localFile . delete ( ) ; } fos = new FileOutputStream ( localFile ) ; bos = new BufferedOutputStream ( fos ) ; cos = new CountingOutputStream ( bos ) ; byte [ ] buf = new byte [ 2048 ] ; int count ; while ( ( count = is . read ( buf , 0 , 2048 ) ) != - 1 ) { cos . write ( buf , 0 , count ) ; } ApptentiveLog . v ( UTIL , "File saved, size = " + ( cos . getBytesWritten ( ) / 1024 ) + "k" ) ; } catch ( IOException e ) { ApptentiveLog . e ( UTIL , "Error creating local copy of file attachment." ) ; logException ( e ) ; return null ; } finally { Util . ensureClosed ( cos ) ; Util . ensureClosed ( bos ) ; Util . ensureClosed ( fos ) ; } // Create a StoredFile database entry for this locally saved file. StoredFile storedFile = new StoredFile ( ) ; storedFile . setSourceUriOrPath ( sourceUrl ) ; storedFile . setLocalFilePath ( localFilePath ) ; storedFile . setMimeType ( mimeType ) ; return storedFile ; }
This method creates a cached file copy from the source input stream .
405
13
13,638
public static Resources . Theme buildApptentiveInteractionTheme ( Context context ) { Resources . Theme theme = context . getResources ( ) . newTheme ( ) ; // 1. Start by basing this on the Apptentive theme. theme . applyStyle ( R . style . ApptentiveTheme_Base_Versioned , true ) ; // 2. Get the theme from the host app. Overwrite what we have so far with the app's theme from // the AndroidManifest.xml. This ensures that the app's styling shows up in our UI. int appTheme ; try { PackageManager packageManager = context . getPackageManager ( ) ; PackageInfo packageInfo = packageManager . getPackageInfo ( context . getPackageName ( ) , 0 ) ; ApplicationInfo ai = packageInfo . applicationInfo ; appTheme = ai . theme ; if ( appTheme != 0 ) { theme . applyStyle ( appTheme , true ) ; } } catch ( PackageManager . NameNotFoundException e ) { // Can't happen return null ; } // Step 3: Restore Apptentive UI window properties that may have been overridden in Step 2. This // ensures Apptentive interaction has a modal feel and look. theme . applyStyle ( R . style . ApptentiveBaseFrameTheme , true ) ; // Step 4: Apply optional theme override specified in host app's style int themeOverrideResId = context . getResources ( ) . getIdentifier ( "ApptentiveThemeOverride" , "style" , context . getPackageName ( ) ) ; if ( themeOverrideResId != 0 ) { theme . applyStyle ( themeOverrideResId , true ) ; } return theme ; }
Builds out the main theme that we would like to use for all Apptentive UI basing it on the existing app theme and adding Apptentive s theme where it doesn t override the existing app s attributes . Finally it forces changes to the theme using ApptentiveThemeOverride .
360
61
13,639
public static File getInternalDir ( Context context , String path , boolean createIfNecessary ) { File filesDir = context . getFilesDir ( ) ; File internalDir = new File ( filesDir , path ) ; if ( ! internalDir . exists ( ) && createIfNecessary ) { boolean succeed = internalDir . mkdirs ( ) ; if ( ! succeed ) { ApptentiveLog . w ( UTIL , "Unable to create internal directory: %s" , internalDir ) ; } } return internalDir ; }
Returns and internal storage directory
117
5
13,640
public static String getManifestMetadataString ( Context context , String key ) { if ( context == null ) { throw new IllegalArgumentException ( "Context is null" ) ; } if ( key == null ) { throw new IllegalArgumentException ( "Key is null" ) ; } try { String appPackageName = context . getPackageName ( ) ; PackageManager packageManager = context . getPackageManager ( ) ; PackageInfo packageInfo = packageManager . getPackageInfo ( appPackageName , PackageManager . GET_META_DATA | PackageManager . GET_RECEIVERS ) ; Bundle metaData = packageInfo . applicationInfo . metaData ; if ( metaData != null ) { return Util . trim ( metaData . getString ( key ) ) ; } } catch ( Exception e ) { ApptentiveLog . e ( e , "Unexpected error while reading application or package info." ) ; logException ( e ) ; } return null ; }
Helper method for resolving manifest metadata string value
204
8
13,641
public static @ Nullable View . OnClickListener guarded ( @ Nullable final View . OnClickListener listener ) { if ( listener != null ) { return new View . OnClickListener ( ) { @ Override public void onClick ( View v ) { try { listener . onClick ( v ) ; } catch ( Exception e ) { ApptentiveLog . e ( e , "Exception while handling click listener" ) ; logException ( e ) ; } } } ; } return null ; }
Creates a fail - safe try .. catch wrapped listener
104
11
13,642
public static void assertMainThread ( ) { if ( imp != null && ! DispatchQueue . isMainQueue ( ) ) { imp . assertFailed ( StringUtils . format ( "Expected 'main' thread but was '%s'" , Thread . currentThread ( ) . getName ( ) ) ) ; } }
Asserts that code executes on the main thread .
68
11
13,643
public static void assertFail ( String format , Object ... args ) { assertFail ( StringUtils . format ( format , args ) ) ; }
General failure with a message
30
5
13,644
public T getValue ( ) { try { value = parse ( originalParameter ) ; } catch ( InvalidParameterException e ) { throw new WebApplicationException ( onError ( e ) ) ; } return value ; }
Returns the parsed value .
44
5
13,645
public static Builder builder ( ) { return new AutoValue_BeadledomClientConfiguration . Builder ( ) . connectionPoolSize ( DEFAULT_CONNECTION_POOL_SIZE ) . maxPooledPerRouteSize ( DEFAULT_MAX_POOLED_PER_ROUTE ) . socketTimeoutMillis ( DEFAULT_SOCKET_TIMEOUT_MILLIS ) . connectionTimeoutMillis ( DEFAULT_CONNECTION_TIMEOUT_MILLIS ) . ttlMillis ( DEFAULT_TTL_MILLIS ) ; }
Default client config builder .
120
5
13,646
private Object invokeInTransactionAndUnitOfWork ( MethodInvocation methodInvocation ) throws Throwable { boolean unitOfWorkAlreadyStarted = unitOfWork . isActive ( ) ; if ( ! unitOfWorkAlreadyStarted ) { unitOfWork . begin ( ) ; } Throwable originalThrowable = null ; try { return dslContextProvider . get ( ) . transactionResult ( ( ) -> { try { return methodInvocation . proceed ( ) ; } catch ( Throwable e ) { if ( e instanceof RuntimeException ) { throw ( RuntimeException ) e ; } throw new RuntimeException ( e ) ; } } ) ; } catch ( Throwable t ) { originalThrowable = t ; throw t ; } finally { if ( ! unitOfWorkAlreadyStarted ) { endUnitOfWork ( originalThrowable ) ; } } }
Invokes the method wrapped within a unit of work and a transaction .
177
14
13,647
private void endUnitOfWork ( Throwable originalThrowable ) throws Throwable { try { unitOfWork . end ( ) ; } catch ( Throwable t ) { if ( originalThrowable != null ) { throw originalThrowable ; } else { throw t ; } } }
Ends the unit of work .
58
7
13,648
public Integer getLimit ( ) { String limitFromRequest = uriInfo . getQueryParameters ( ) . getFirst ( LimitParameter . getDefaultLimitFieldName ( ) ) ; return limitFromRequest != null ? new LimitParameter ( limitFromRequest ) . getValue ( ) : LimitParameter . getDefaultLimit ( ) ; }
Retrieves the value of the limit field from the request . Will use the configured field name to find the parameter .
68
24
13,649
public Long getOffset ( ) { String offsetFromRequest = uriInfo . getQueryParameters ( ) . getFirst ( OffsetParameter . getDefaultOffsetFieldName ( ) ) ; return offsetFromRequest != null ? new OffsetParameter ( offsetFromRequest ) . getValue ( ) : OffsetParameter . getDefaultOffset ( ) ; }
Retrieves the value of the offset field from the request . Will use the configured field name to find the parameter
71
23
13,650
private void checkLimitRange ( int limit ) { int minLimit = offsetPaginationConfiguration . allowZeroLimit ( ) ? 0 : 1 ; if ( limit < minLimit || limit > offsetPaginationConfiguration . maxLimit ( ) ) { throw InvalidParameterException . create ( "Invalid value for '" + this . getParameterFieldName ( ) + "': " + limit + " - value between " + minLimit + " and " + offsetPaginationConfiguration . maxLimit ( ) + " is required." ) ; } }
Ensures that the limit is in the allowed range .
112
12
13,651
@ Override public String getSignature ( ) { String signature = super . getSignature ( ) ; if ( signature . indexOf ( ' ' ) == - 1 ) { return signature ; } if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "Condensing signature [{}]" , signature ) ; } int returnTypeSpace = signature . indexOf ( " " ) ; StringBuilder sb = new StringBuilder ( 100 ) ; sb . append ( signature . substring ( 0 , returnTypeSpace + 1 ) ) ; // Have to replace ".." to "." for classes generated by guice. e.g. // Object com.cerner.beadledom.health.resource.AvailabilityResource..FastClassByGuice..77b09000.newInstance(int, Object[]) String [ ] parts = signature . replaceAll ( "\\.\\." , "." ) . substring ( returnTypeSpace + 1 ) . split ( "\\." ) ; for ( int i = 0 ; i < parts . length - 2 ; i ++ ) { // Shorten each package name to only include the first character sb . append ( parts [ i ] . charAt ( 0 ) ) . append ( "." ) ; } sb . append ( parts [ parts . length - 2 ] ) . append ( "." ) . append ( parts [ parts . length - 1 ] ) ; return sb . toString ( ) ; }
Returns the signature with the packages names shortened to only include the first character .
311
15
13,652
public GenericResponseBuilder < T > errorEntity ( Object errorEntity , Annotation [ ] annotations ) { if ( body != null ) { throw new IllegalStateException ( "entity already set. Only one of entity and errorEntity may be set" ) ; } rawBuilder . entity ( errorEntity , annotations ) ; hasErrorEntity = true ; return this ; }
Sets the response error entity body on the builder .
74
11
13,653
public GenericResponseBuilder < T > header ( String name , Object value ) { rawBuilder . header ( name , value ) ; return this ; }
Adds a header to the response .
30
7
13,654
public GenericResponseBuilder < T > replaceAll ( MultivaluedMap < String , Object > headers ) { rawBuilder . replaceAll ( headers ) ; return this ; }
Replaces all of the headers with the these headers .
35
11
13,655
public GenericResponseBuilder < T > link ( URI uri , String rel ) { rawBuilder . link ( uri , rel ) ; return this ; }
Adds a link header .
32
5
13,656
public static HealthStatus create ( int status , String message , Throwable exception ) { return new AutoValue_HealthStatus ( message , status , Optional . ofNullable ( exception ) ) ; }
Create an instance with the given message status code and exception .
40
12
13,657
public static BuildInfo create ( Properties properties ) { checkNotNull ( properties , "properties: null" ) ; return builder ( ) . setArtifactId ( checkNotNull ( properties . getProperty ( "project.artifactId" ) , "project.artifactId: null" ) ) . setGroupId ( checkNotNull ( properties . getProperty ( "project.groupId" ) , "project.groupId: null" ) ) . setRawProperties ( properties ) . setScmRevision ( checkNotNull ( properties . getProperty ( "git.commit.id" ) , "git.commit.id: null" ) ) . setVersion ( checkNotNull ( properties . getProperty ( "project.version" ) , "project.version: null" ) ) . setBuildDateTime ( Optional . ofNullable ( properties . getProperty ( "project.build.date" ) ) ) . build ( ) ; }
Create an instance using the given properties .
200
8
13,658
public HealthDto doPrimaryHealthCheck ( ) { List < HealthDependency > primaryHealthDependencies = healthDependencies . values ( ) . stream ( ) . filter ( HealthDependency :: isPrimary ) . collect ( Collectors . toList ( ) ) ; return checkHealth ( primaryHealthDependencies ) ; }
Performs the Primary Health Check .
71
7
13,659
public List < HealthDependencyDto > doDependencyListing ( ) { List < HealthDependencyDto > listing = Lists . newArrayList ( ) ; for ( HealthDependency dependency : healthDependencies . values ( ) ) { listing . add ( dependencyDtoBuilder ( dependency ) . build ( ) ) ; } return listing ; }
Returns a list of all health dependencies but does not check their health .
78
14
13,660
public HealthDependencyDto doDependencyAvailabilityCheck ( String name ) { HealthDependency dependency = healthDependencies . get ( checkNotNull ( name ) ) ; if ( dependency == null ) { throw new WebApplicationException ( Response . status ( 404 ) . build ( ) ) ; } return checkDependencyHealth ( dependency ) ; }
Returns information about a dependency including the result of checking its health .
76
13
13,661
public static void checkParam ( boolean expression , Object errorMessage ) { if ( ! expression ) { Response response = Response . status ( Response . Status . BAD_REQUEST ) . type ( MediaType . TEXT_PLAIN ) . build ( ) ; throw new WebApplicationException ( String . valueOf ( errorMessage ) , response ) ; } }
Ensures the truth of an expression involving a jax - rs parameter .
72
16
13,662
private boolean isExcludedBinding ( Key < ? > key ) { Class < ? > rawType = key . getTypeLiteral ( ) . getRawType ( ) ; for ( Class < ? > excludedClass : excludedBindings ) { if ( excludedClass . isAssignableFrom ( rawType ) ) { return true ; } } return false ; }
This is to prevent circular dependency during binding resolution in the provider . As we loop through every binding in the injector we need to exclude certain bindings as they havent been created yet .
77
37
13,663
protected void addField ( String field ) { if ( field . contains ( "/" ) ) { // Splits the field into, at most, 2 strings - "prefix" / "suffix" - since we guarantee the // field contains a / this will ALWAYS have a length of 2. String [ ] fields = field . split ( "/" , 2 ) ; String prefix = fields [ 0 ] ; // This may be an empty string if the field passed in was "foo/" String suffix = fields [ 1 ] ; if ( "" . equals ( suffix ) ) { filters . put ( prefix , UNFILTERED_FIELD ) ; return ; } FieldFilter nestedFilter = filters . get ( prefix ) ; if ( filters . containsKey ( prefix ) && nestedFilter == UNFILTERED_FIELD ) { return ; } else if ( nestedFilter == null ) { nestedFilter = new FieldFilter ( true ) ; filters . put ( prefix , nestedFilter ) ; } nestedFilter . addField ( suffix ) ; } else { filters . put ( field , UNFILTERED_FIELD ) ; } }
Adds a field to be filtered for this FieldFilter .
228
11
13,664
public void writeJson ( JsonParser parser , JsonGenerator jgen ) throws IOException { checkNotNull ( parser , "JsonParser cannot be null for writeJson." ) ; checkNotNull ( jgen , "JsonGenerator cannot be null for writeJson." ) ; JsonToken curToken = parser . nextToken ( ) ; while ( curToken != null ) { curToken = processToken ( curToken , parser , jgen ) ; } jgen . flush ( ) ; }
Writes the json from the parser onto the generator using the filters to only write the objects specified .
109
20
13,665
private void processValue ( JsonToken valueToken , JsonParser parser , JsonGenerator jgen ) throws IOException { if ( valueToken . isBoolean ( ) ) { jgen . writeBoolean ( parser . getBooleanValue ( ) ) ; } else if ( valueToken . isNumeric ( ) ) { if ( parser . getNumberType ( ) == JsonParser . NumberType . INT ) { jgen . writeNumber ( parser . getIntValue ( ) ) ; } else if ( parser . getNumberType ( ) == JsonParser . NumberType . DOUBLE ) { jgen . writeNumber ( parser . getDoubleValue ( ) ) ; } else if ( parser . getNumberType ( ) == JsonParser . NumberType . FLOAT ) { jgen . writeNumber ( parser . getFloatValue ( ) ) ; } else if ( parser . getNumberType ( ) == JsonParser . NumberType . LONG ) { jgen . writeNumber ( parser . getLongValue ( ) ) ; } else if ( parser . getNumberType ( ) == JsonParser . NumberType . BIG_DECIMAL ) { jgen . writeNumber ( parser . getDecimalValue ( ) ) ; } else if ( parser . getNumberType ( ) == JsonParser . NumberType . BIG_INTEGER ) { jgen . writeNumber ( parser . getBigIntegerValue ( ) ) ; } else { LOGGER . error ( "Found unsupported numeric value with name {}." , parser . getCurrentName ( ) ) ; throw new RuntimeException ( "Found unsupported numeric value with name " + parser . getCurrentName ( ) ) ; } } else if ( valueToken . id ( ) == JsonTokenId . ID_STRING ) { jgen . writeString ( parser . getText ( ) ) ; } else { // Something bad just happened. Probably an unsupported type. LOGGER . error ( "Found unsupported value type {} for name {}." , valueToken . id ( ) , parser . getCurrentName ( ) ) ; throw new RuntimeException ( "Found unsupported value type " + valueToken . id ( ) + " for name " + parser . getCurrentName ( ) ) ; } }
Uses a JsonToken + JsonParser to determine how to write a value to the JsonGenerator .
472
24
13,666
String lastLink ( ) { if ( totalResults == null || currentLimit == 0L ) { return null ; } Long lastOffset ; if ( totalResults % currentLimit == 0L ) { lastOffset = totalResults - currentLimit ; } else { // Truncation due to integral division gives floor-like behavior for free. lastOffset = totalResults / currentLimit * currentLimit ; } return urlWithUpdatedPagination ( lastOffset , currentLimit ) ; }
Returns the last page link ; null if no last page link is available .
97
15
13,667
String prevLink ( ) { if ( currentOffset == 0 || currentLimit == 0 ) { return null ; } return urlWithUpdatedPagination ( Math . max ( 0 , currentOffset - currentLimit ) , currentLimit ) ; }
Returns the next prev link ; null if no prev page link is available .
49
15
13,668
public void resizeFBO ( int fboWidth , int fboHeight ) { if ( lightMap != null ) { lightMap . dispose ( ) ; } lightMap = new LightMap ( this , fboWidth , fboHeight ) ; }
Resize the FBO used for intermediate rendering .
52
10
13,669
public void setCombinedMatrix ( OrthographicCamera camera ) { this . setCombinedMatrix ( camera . combined , camera . position . x , camera . position . y , camera . viewportWidth * camera . zoom , camera . viewportHeight * camera . zoom ) ; }
Sets combined matrix basing on camera position rotation and zoom
58
12
13,670
public void prepareRender ( ) { lightRenderedLastFrame = 0 ; Gdx . gl . glDepthMask ( false ) ; Gdx . gl . glEnable ( GL20 . GL_BLEND ) ; simpleBlendFunc . apply ( ) ; boolean useLightMap = ( shadows || blur ) ; if ( useLightMap ) { lightMap . frameBuffer . begin ( ) ; Gdx . gl . glClearColor ( 0f , 0f , 0f , 0f ) ; Gdx . gl . glClear ( GL20 . GL_COLOR_BUFFER_BIT ) ; } ShaderProgram shader = customLightShader != null ? customLightShader : lightShader ; shader . begin ( ) ; { shader . setUniformMatrix ( "u_projTrans" , combined ) ; if ( customLightShader != null ) updateLightShader ( ) ; for ( Light light : lightList ) { if ( customLightShader != null ) updateLightShaderPerLight ( light ) ; light . render ( ) ; } } shader . end ( ) ; if ( useLightMap ) { if ( customViewport ) { lightMap . frameBuffer . end ( viewportX , viewportY , viewportWidth , viewportHeight ) ; } else { lightMap . frameBuffer . end ( ) ; } boolean needed = lightRenderedLastFrame > 0 ; // this way lot less binding if ( needed && blur ) lightMap . gaussianBlur ( ) ; } }
Prepare all lights for rendering .
318
7
13,671
public boolean pointAtLight ( float x , float y ) { for ( Light light : lightList ) { if ( light . contains ( x , y ) ) return true ; } return false ; }
Checks whether the given point is inside of any light volume
41
12
13,672
public void dispose ( ) { removeAll ( ) ; if ( lightMap != null ) lightMap . dispose ( ) ; if ( lightShader != null ) lightShader . dispose ( ) ; }
Disposes all this rayHandler lights and resources
42
9
13,673
public void removeAll ( ) { for ( Light light : lightList ) { light . dispose ( ) ; } lightList . clear ( ) ; for ( Light light : disabledLights ) { light . dispose ( ) ; } disabledLights . clear ( ) ; }
Removes and disposes both all active and disabled lights
56
11
13,674
public void setAmbientLight ( float r , float g , float b , float a ) { this . ambientLight . set ( r , g , b , a ) ; }
Sets ambient light color . Specifies how shadows colored and their brightness .
37
15
13,675
@ Override public void setDistance ( float dist ) { dist *= RayHandler . gammaCorrectionParameter ; this . distance = dist < 0.01f ? 0.01f : dist ; dirty = true ; }
Sets light distance
45
4
13,676
public void add ( RayHandler rayHandler ) { this . rayHandler = rayHandler ; if ( active ) { rayHandler . lightList . add ( this ) ; } else { rayHandler . disabledLights . add ( this ) ; } }
Adds light to specified RayHandler
51
6
13,677
public void remove ( boolean doDispose ) { if ( active ) { rayHandler . lightList . removeValue ( this , false ) ; } else { rayHandler . disabledLights . removeValue ( this , false ) ; } rayHandler = null ; if ( doDispose ) dispose ( ) ; }
Removes light from specified RayHandler and disposes it if requested
64
13
13,678
void setRayNum ( int rays ) { if ( rays < MIN_RAYS ) rays = MIN_RAYS ; rayNum = rays ; vertexNum = rays + 1 ; segments = new float [ vertexNum * 8 ] ; mx = new float [ vertexNum ] ; my = new float [ vertexNum ] ; f = new float [ vertexNum ] ; }
Internal method for mesh update depending on ray number
77
9
13,679
public void setContactFilter ( short categoryBits , short groupIndex , short maskBits ) { filterA = new Filter ( ) ; filterA . categoryBits = categoryBits ; filterA . groupIndex = groupIndex ; filterA . maskBits = maskBits ; }
Creates new contact filter for this light with given parameters
61
11
13,680
static public void setGlobalContactFilter ( short categoryBits , short groupIndex , short maskBits ) { globalFilterA = new Filter ( ) ; globalFilterA . categoryBits = categoryBits ; globalFilterA . groupIndex = groupIndex ; globalFilterA . maskBits = maskBits ; }
Creates new contact filter for ALL LIGHTS with give parameters
67
12
13,681
public void debugRender ( ShapeRenderer shapeRenderer ) { shapeRenderer . setColor ( Color . YELLOW ) ; FloatArray vertices = Pools . obtain ( FloatArray . class ) ; vertices . clear ( ) ; for ( int i = 0 ; i < rayNum ; i ++ ) { vertices . addAll ( mx [ i ] , my [ i ] ) ; } for ( int i = rayNum - 1 ; i > - 1 ; i -- ) { vertices . addAll ( startX [ i ] , startY [ i ] ) ; } shapeRenderer . polygon ( vertices . shrink ( ) ) ; Pools . free ( vertices ) ; }
Draws a polygon using ray start and end points as vertices
153
14
13,682
public void attachToBody ( Body body , float degrees ) { this . body = body ; this . bodyPosition . set ( body . getPosition ( ) ) ; bodyAngleOffset = MathUtils . degreesToRadians * degrees ; bodyAngle = body . getAngle ( ) ; applyAttachment ( ) ; if ( staticLight ) dirty = true ; }
Attaches light to specified body with relative direction offset
78
10
13,683
void applyAttachment ( ) { if ( body == null || staticLight ) return ; restorePosition . setToTranslation ( bodyPosition ) ; rotateAroundZero . setToRotationRad ( bodyAngle + bodyAngleOffset ) ; for ( int i = 0 ; i < rayNum ; i ++ ) { tmpVec . set ( startX [ i ] , startY [ i ] ) . mul ( rotateAroundZero ) . mul ( restorePosition ) ; startX [ i ] = tmpVec . x ; startY [ i ] = tmpVec . y ; tmpVec . set ( endX [ i ] , endY [ i ] ) . mul ( rotateAroundZero ) . mul ( restorePosition ) ; endX [ i ] = tmpVec . x ; endY [ i ] = tmpVec . y ; } }
Applies attached body initial transform to all lights rays
179
10
13,684
public void attachToBody ( Body body , float offsetX , float offSetY , float degrees ) { this . body = body ; bodyOffsetX = offsetX ; bodyOffsetY = offSetY ; bodyAngleOffset = degrees ; if ( staticLight ) dirty = true ; }
Attaches light to specified body with relative offset and direction
60
11
13,685
public static String escape ( String value , char quote ) { Map < CharSequence , CharSequence > lookupMap = new HashMap <> ( ) ; lookupMap . put ( Character . toString ( quote ) , "\\" + quote ) ; lookupMap . put ( "\\" , "\\\\" ) ; final CharSequenceTranslator escape = new LookupTranslator ( lookupMap ) . with ( new LookupTranslator ( EntityArrays . JAVA_CTRL_CHARS_ESCAPE ) ) . with ( JavaUnicodeEscaper . outsideOf ( 32 , 0x7f ) ) ; return quote + escape . translate ( value ) + quote ; }
Escape the string with given quote character .
147
9
13,686
public List < FunctionWrapper > compileFunctions ( ImportStack importStack , Context context , List < ? > objects ) { List < FunctionWrapper > callbacks = new LinkedList <> ( ) ; for ( Object object : objects ) { List < FunctionWrapper > objectCallbacks = compileFunctions ( importStack , context , object ) ; callbacks . addAll ( objectCallbacks ) ; } return callbacks ; }
Compile methods from all objects into libsass functions .
91
12
13,687
public List < FunctionWrapper > compileFunctions ( ImportStack importStack , Context context , Object object ) { Class < ? > functionClass = object . getClass ( ) ; Method [ ] methods = functionClass . getDeclaredMethods ( ) ; List < FunctionDeclaration > declarations = new LinkedList <> ( ) ; for ( Method method : methods ) { int modifiers = method . getModifiers ( ) ; if ( ! Modifier . isPublic ( modifiers ) ) { continue ; } FunctionDeclaration declaration = createDeclaration ( importStack , context , object , method ) ; declarations . add ( declaration ) ; } return declarations . stream ( ) . map ( FunctionWrapper :: new ) . collect ( Collectors . toList ( ) ) ; }
Compile methods from an object into libsass functions .
159
12
13,688
public FunctionDeclaration createDeclaration ( ImportStack importStack , Context context , Object object , Method method ) { StringBuilder signature = new StringBuilder ( ) ; Parameter [ ] parameters = method . getParameters ( ) ; List < ArgumentConverter > argumentConverters = new ArrayList <> ( method . getParameterCount ( ) ) ; signature . append ( method . getName ( ) ) . append ( "(" ) ; int parameterCount = 0 ; for ( Parameter parameter : parameters ) { ArgumentConverter argumentConverter = createArgumentConverter ( object , method , parameter ) ; argumentConverters . add ( argumentConverter ) ; List < FunctionArgumentSignature > list = argumentConverter . argumentSignatures ( object , method , parameter , functionArgumentSignatureFactory ) ; for ( FunctionArgumentSignature functionArgumentSignature : list ) { String name = functionArgumentSignature . getName ( ) ; Object defaultValue = functionArgumentSignature . getDefaultValue ( ) ; if ( parameterCount > 0 ) { signature . append ( ", " ) ; } signature . append ( "$" ) . append ( name ) ; if ( null != defaultValue ) { signature . append ( ": " ) . append ( formatDefaultValue ( defaultValue ) ) ; } parameterCount ++ ; } } signature . append ( ")" ) ; // Overwrite signature with special ones if ( method . isAnnotationPresent ( WarnFunction . class ) ) { signature . setLength ( 0 ) ; signature . append ( "@warn" ) ; } else if ( method . isAnnotationPresent ( ErrorFunction . class ) ) { signature . setLength ( 0 ) ; signature . append ( "@error" ) ; } else if ( method . isAnnotationPresent ( DebugFunction . class ) ) { signature . setLength ( 0 ) ; signature . append ( "@debug" ) ; } return new FunctionDeclaration ( importStack , context , signature . toString ( ) , object , method , argumentConverters ) ; }
Create a function declaration from an object method .
434
9
13,689
private String formatDefaultValue ( Object value ) { if ( value instanceof Boolean ) { return ( ( Boolean ) value ) ? "true" : "false" ; } if ( value instanceof Number ) { return value . toString ( ) ; } if ( value instanceof Collection ) { return formatCollectionValue ( ( Collection ) value ) ; } String string = value . toString ( ) ; if ( string . startsWith ( "$" ) ) { return string ; } return SassString . escape ( string ) ; }
Format a default value for libsass function signature .
108
11
13,690
public SassValue invoke ( List < ? > arguments ) { try { ArrayList < Object > values = new ArrayList <> ( argumentConverters . size ( ) ) ; for ( ArgumentConverter argumentConverter : argumentConverters ) { Object value = argumentConverter . convert ( arguments , importStack , context ) ; values . add ( value ) ; } Object result = method . invoke ( object , values . toArray ( ) ) ; return TypeUtils . convertToSassValue ( result ) ; } catch ( Throwable throwable ) { StringWriter stringWriter = new StringWriter ( ) ; PrintWriter printWriter = new PrintWriter ( stringWriter ) ; String message = throwable . getMessage ( ) ; if ( StringUtils . isNotEmpty ( message ) ) { printWriter . append ( message ) . append ( System . lineSeparator ( ) ) ; } throwable . printStackTrace ( printWriter ) ; return new SassError ( stringWriter . toString ( ) ) ; } }
Invoke the method with the given list of arguments .
218
11
13,691
public Output compileFile ( URI inputPath , URI outputPath , Options options ) throws CompilationException { FileContext context = new FileContext ( inputPath , outputPath , options ) ; return compile ( context ) ; }
Compile file .
45
4
13,692
public Output compile ( Context context ) throws CompilationException { Objects . requireNonNull ( context , "Parameter context must not be null" ) ; if ( context instanceof FileContext ) { return compile ( ( FileContext ) context ) ; } if ( context instanceof StringContext ) { return compile ( ( StringContext ) context ) ; } throw new UnsupportedContextException ( context ) ; }
Compile context .
81
4
13,693
public List < FunctionArgumentSignature > createDefaultArgumentSignature ( Parameter parameter ) { List < FunctionArgumentSignature > list = new LinkedList <> ( ) ; String name = getParameterName ( parameter ) ; Object defaultValue = getDefaultValue ( parameter ) ; list . add ( new FunctionArgumentSignature ( name , defaultValue ) ) ; return list ; }
Create a new factory .
83
5
13,694
public String getParameterName ( Parameter parameter ) { Name annotation = parameter . getAnnotation ( Name . class ) ; if ( null == annotation ) { return parameter . getName ( ) ; } return annotation . value ( ) ; }
Determine annotated name of a method parameter .
49
11
13,695
public Object getDefaultValue ( Parameter parameter ) { Class < ? > type = parameter . getType ( ) ; if ( TypeUtils . isaString ( type ) ) { return getStringDefaultValue ( parameter ) ; } if ( TypeUtils . isaByte ( type ) ) { return getByteDefaultValue ( parameter ) ; } if ( TypeUtils . isaShort ( type ) ) { return getShortDefaultValue ( parameter ) ; } if ( TypeUtils . isaInteger ( type ) ) { return getIntegerDefaultValue ( parameter ) ; } if ( TypeUtils . isaLong ( type ) ) { return getLongDefaultValue ( parameter ) ; } if ( TypeUtils . isaFloat ( type ) ) { return getFloatDefaultValue ( parameter ) ; } if ( TypeUtils . isaDouble ( type ) ) { return getDoubleDefaultValue ( parameter ) ; } if ( TypeUtils . isaCharacter ( type ) ) { return getCharacterDefaultValue ( parameter ) ; } if ( TypeUtils . isaBoolean ( type ) ) { return getBooleanDefaultValue ( parameter ) ; } return null ; }
Determine annotated default parameter value .
246
9
13,696
public int register ( Import importSource ) { int id = registry . size ( ) + 1 ; registry . put ( id , importSource ) ; return id ; }
Register a new import return the registration ID .
34
9
13,697
public static SassValue convertToSassValue ( Object value ) { if ( null == value ) { return SassNull . SINGLETON ; } if ( value instanceof SassValue ) { return ( SassValue ) value ; } Class cls = value . getClass ( ) ; if ( isaBoolean ( cls ) ) { return new SassBoolean ( ( Boolean ) value ) ; } if ( isaNumber ( cls ) ) { return new SassNumber ( ( ( Number ) value ) . doubleValue ( ) , "" ) ; } if ( isaString ( cls ) || isaCharacter ( cls ) ) { return new SassString ( value . toString ( ) ) ; } if ( value instanceof Collection ) { return new SassList ( ( ( Collection < ? > ) value ) . stream ( ) . map ( TypeUtils :: convertToSassValue ) . collect ( Collectors . toList ( ) ) ) ; } if ( value instanceof Map ) { return ( ( Map < ? , ? > ) value ) . entrySet ( ) . stream ( ) . collect ( Collectors . toMap ( entry -> entry . getKey ( ) . toString ( ) , entry -> TypeUtils . convertToSassValue ( entry . getValue ( ) ) , ( origin , duplicate ) -> origin , SassMap :: new ) ) ; } if ( value instanceof Throwable ) { Throwable throwable = ( Throwable ) value ; StringWriter stringWriter = new StringWriter ( ) ; PrintWriter printWriter = new PrintWriter ( stringWriter ) ; String message = throwable . getMessage ( ) ; if ( StringUtils . isNotEmpty ( message ) ) { printWriter . append ( message ) . append ( System . lineSeparator ( ) ) ; } throwable . printStackTrace ( printWriter ) ; return new SassError ( stringWriter . toString ( ) ) ; } return new SassError ( String . format ( "Could not convert object of type %s into a sass value" , value . getClass ( ) . toString ( ) ) ) ; }
Try to convert any java object into a responsible sass value .
447
13
13,698
private Collection < Import > resolveImport ( Path path ) throws IOException , URISyntaxException { URL resource = resolveResource ( path ) ; if ( null == resource ) { return null ; } // calculate a webapp absolute URI final URI uri = new URI ( Paths . get ( "/" ) . resolve ( Paths . get ( getServletContext ( ) . getResource ( "/" ) . toURI ( ) ) . relativize ( Paths . get ( resource . toURI ( ) ) ) ) . toString ( ) ) ; final String source = IOUtils . toString ( resource , StandardCharsets . UTF_8 ) ; final Import scssImport = new Import ( uri , uri , source ) ; return Collections . singleton ( scssImport ) ; }
Try to determine the import object for a given path .
171
11
13,699
private URL resolveResource ( Path path ) throws MalformedURLException { final Path dir = path . getParent ( ) ; final String basename = path . getFileName ( ) . toString ( ) ; for ( String prefix : new String [ ] { "_" , "" } ) { for ( String suffix : new String [ ] { ".scss" , ".css" , "" } ) { final Path target = dir . resolve ( prefix + basename + suffix ) ; final URL resource = getServletContext ( ) . getResource ( target . toString ( ) ) ; if ( null != resource ) { return resource ; } } } return null ; }
Try to find a resource for this path .
140
9