idx int64 0 165k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
13,600 | void dispatchSync ( DispatchQueue networkQueue ) { long requestStartTime = System . currentTimeMillis ( ) ; try { sendRequestSync ( ) ; } catch ( NetworkUnavailableException e ) { responseCode = - 1 ; errorMessage = e . getMessage ( ) ; ApptentiveLog . w ( NETWORK , e . getMessage ( ) ) ; ApptentiveLog . w ( NETWORK , "Cancelled? %b" , isCancelled ( ) ) ; } catch ( Exception e ) { responseCode = - 1 ; errorMessage = e . getMessage ( ) ; ApptentiveLog . e ( NETWORK , "Cancelled? %b" , isCancelled ( ) ) ; if ( ! isCancelled ( ) ) { ApptentiveLog . e ( NETWORK , "Unable to perform request: %s" , this ) ; } } ApptentiveLog . d ( NETWORK , "Request finished in %d ms" , System . currentTimeMillis ( ) - requestStartTime ) ; if ( isFailed ( ) && retryRequest ( networkQueue , responseCode ) ) { return ; } if ( callbackQueue != null ) { callbackQueue . dispatchAsync ( new DispatchTask ( ) { protected void execute ( ) { finishRequest ( ) ; } } ) ; } else { finishRequest ( ) ; } } | Send request synchronously on a background network queue |
13,601 | public void setRequestProperty ( String key , Object value ) { if ( value != null ) { if ( requestProperties == null ) { requestProperties = new HashMap < > ( ) ; } requestProperties . put ( key , value ) ; } } | Sets HTTP request property |
13,602 | public boolean getWhoCardRequestEnabled ( ) { InteractionConfiguration configuration = getConfiguration ( ) ; if ( configuration == null ) { return false ; } JSONObject profile = configuration . optJSONObject ( KEY_PROFILE ) ; return profile . optBoolean ( KEY_PROFILE_REQUEST , true ) ; } | When enabled display Who Card to request profile info |
13,603 | public MessageCenterStatus getRegularStatus ( ) { InteractionConfiguration configuration = getConfiguration ( ) ; if ( configuration == null ) { return null ; } JSONObject status = configuration . optJSONObject ( KEY_STATUS ) ; if ( status == null ) { return null ; } String statusBody = status . optString ( KEY_STATUS_BODY ) ; if ( statusBody == null || statusBody . isEmpty ( ) ) { return null ; } return new MessageCenterStatus ( statusBody , null ) ; } | Regular status shows customer s hours expected time until response |
13,604 | public static boolean createScaledDownImageCacheFile ( String sourcePath , String cachedFileName ) { File localFile = new File ( cachedFileName ) ; int imageOrientation = 0 ; try { ExifInterface exif = new ExifInterface ( sourcePath ) ; imageOrientation = exif . getAttributeInt ( ExifInterface . TAG_ORIENTATION , ExifInterface . ORIENTATION_NORMAL ) ; } catch ( IOException e ) { } CountingOutputStream cos = null ; try { cos = new CountingOutputStream ( new BufferedOutputStream ( new FileOutputStream ( localFile ) ) ) ; System . gc ( ) ; Bitmap smaller = ImageUtil . createScaledBitmapFromLocalImageSource ( sourcePath , MAX_SENT_IMAGE_EDGE , MAX_SENT_IMAGE_EDGE , null , imageOrientation ) ; smaller . compress ( Bitmap . CompressFormat . JPEG , 95 , cos ) ; cos . flush ( ) ; ApptentiveLog . v ( UTIL , "Bitmap saved, size = " + ( cos . getBytesWritten ( ) / 1024 ) + "k" ) ; smaller . recycle ( ) ; System . gc ( ) ; } catch ( FileNotFoundException e ) { ApptentiveLog . e ( UTIL , e , "File not found while storing image." ) ; logException ( e ) ; return false ; } catch ( Exception e ) { ApptentiveLog . a ( UTIL , e , "Error storing image." ) ; logException ( e ) ; return false ; } finally { Util . ensureClosed ( cos ) ; } return true ; } | This method creates a cached version of the original image and compresses it in the process so it doesn t fill up the disk . Therefore do not use it to store an exact copy of the file in question . |
13,605 | public static synchronized boolean updateAdvertisingIdClientInfo ( Context context ) { ApptentiveLog . v ( ADVERTISER_ID , "Updating advertiser ID client info..." ) ; AdvertisingIdClientInfo clientInfo = resolveAdvertisingIdClientInfo ( context ) ; if ( clientInfo != null && clientInfo . equals ( cachedClientInfo ) ) { return false ; } ApptentiveLog . v ( ADVERTISER_ID , "Advertiser ID client info changed: %s" , clientInfo ) ; cachedClientInfo = clientInfo ; notifyClientInfoChanged ( cachedClientInfo ) ; return true ; } | Returns true if changed |
13,606 | synchronized boolean sendPayload ( final PayloadData payload ) { if ( payload == null ) { throw new IllegalArgumentException ( "Payload is null" ) ; } if ( isSendingPayload ( ) ) { return false ; } sendingFlag = true ; try { sendPayloadRequest ( payload ) ; } catch ( Exception e ) { ApptentiveLog . e ( e , "Exception while sending payload: %s" , payload ) ; logException ( e ) ; String message = e . getMessage ( ) ; if ( message == null ) { message = StringUtils . format ( "%s is thrown" , e . getClass ( ) . getSimpleName ( ) ) ; } handleFinishSendingPayload ( payload , false , message , - 1 , null ) ; } return true ; } | Sends payload asynchronously . Returns boolean flag immediately indicating if payload send was scheduled |
13,607 | private synchronized void handleFinishSendingPayload ( PayloadData payload , boolean cancelled , String errorMessage , int responseCode , JSONObject responseData ) { sendingFlag = false ; try { if ( listener != null ) { listener . onFinishSending ( this , payload , cancelled , errorMessage , responseCode , responseData ) ; } } catch ( Exception e ) { ApptentiveLog . e ( e , "Exception while notifying payload listener" ) ; logException ( e ) ; } } | Executed when we re done with the current payload |
13,608 | public CommerceExtendedData addItem ( Item item ) throws JSONException { if ( this . items == null ) { this . items = new ArrayList < > ( ) ; } items . add ( item ) ; return this ; } | Add information about a purchased item to this record . Calls to this method can be chained . |
13,609 | public void displayNewIncomingMessageItem ( ApptentiveMessage message ) { messagingActionHandler . sendEmptyMessage ( MSG_REMOVE_STATUS ) ; int insertIndex = listItems . size ( ) ; outside_loop : for ( int i = listItems . size ( ) - 1 ; i > 0 ; i -- ) { MessageCenterListItem item = listItems . get ( i ) ; switch ( item . getListItemType ( ) ) { case MESSAGE_COMPOSER : case MESSAGE_CONTEXT : case WHO_CARD : case STATUS : insertIndex -- ; break ; default : break outside_loop ; } } listItems . add ( insertIndex , message ) ; messageCenterRecyclerViewAdapter . notifyItemInserted ( insertIndex ) ; int firstIndex = messageCenterRecyclerView . getFirstVisiblePosition ( ) ; int lastIndex = messageCenterRecyclerView . getLastVisiblePosition ( ) ; boolean composingAreaTakesUpVisibleArea = firstIndex <= insertIndex && insertIndex < lastIndex ; if ( composingAreaTakesUpVisibleArea ) { View v = messageCenterRecyclerView . getChildAt ( 0 ) ; int top = ( v == null ) ? 0 : v . getTop ( ) ; updateMessageSentStates ( ) ; messagingActionHandler . sendMessage ( messagingActionHandler . obtainMessage ( MSG_SCROLL_FROM_TOP , insertIndex , top ) ) ; } else { updateMessageSentStates ( ) ; } } | Call only from handler . |
13,610 | public void clearImageAttachmentBand ( ) { attachments . setVisibility ( View . GONE ) ; images . clear ( ) ; attachments . setData ( null ) ; } | Remove all images from attachment band . |
13,611 | public void addImagesToImageAttachmentBand ( final List < ImageItem > imagesToAttach ) { if ( imagesToAttach == null || imagesToAttach . size ( ) == 0 ) { return ; } attachments . setupLayoutListener ( ) ; attachments . setVisibility ( View . VISIBLE ) ; images . addAll ( imagesToAttach ) ; setAttachButtonState ( ) ; addAdditionalAttachItem ( ) ; attachments . notifyDataSetChanged ( ) ; } | Add new images to attachment band . |
13,612 | public void removeImageFromImageAttachmentBand ( final int position ) { images . remove ( position ) ; attachments . setupLayoutListener ( ) ; setAttachButtonState ( ) ; if ( images . size ( ) == 0 ) { attachments . setVisibility ( View . GONE ) ; return ; } addAdditionalAttachItem ( ) ; } | Remove an image from attachment band . |
13,613 | public long getRetryTimeoutMillis ( int retryAttempt ) { long temp = Math . min ( MAX_RETRY_CAP , ( long ) ( retryTimeoutMillis * Math . pow ( 2.0 , retryAttempt - 1 ) ) ) ; return ( long ) ( ( temp / 2 ) * ( 1.0 + RANDOM . nextDouble ( ) ) ) ; } | Returns the delay in millis for the next retry |
13,614 | public boolean evaluate ( FieldManager fieldManager , IndentPrinter printer ) { Comparable fieldValue = fieldManager . getValue ( fieldName ) ; for ( ConditionalTest test : conditionalTests ) { boolean result = test . operator . apply ( fieldValue , test . parameter ) ; printer . print ( "- %s => %b" , test . operator . description ( fieldManager . getDescription ( fieldName ) , fieldValue , test . parameter ) , result ) ; if ( ! result ) { return false ; } } return true ; } | The test in this conditional clause are implicitly ANDed together so return false if any of them is false and continue the loop for each test that is true ; |
13,615 | public Serializable put ( String key , Serializable value ) { Serializable ret = super . put ( key , value ) ; notifyDataChanged ( ) ; return ret ; } | region Saving when modified |
13,616 | public static synchronized Apptentive . DateTime getTimeAtInstall ( Selector selector ) { ensureLoaded ( ) ; for ( VersionHistoryEntry entry : versionHistoryEntries ) { switch ( selector ) { case total : return new Apptentive . DateTime ( entry . getTimestamp ( ) ) ; case version_code : if ( entry . getVersionCode ( ) == RuntimeUtils . getAppVersionCode ( ApptentiveInternal . getInstance ( ) . getApplicationContext ( ) ) ) { return new Apptentive . DateTime ( entry . getTimestamp ( ) ) ; } break ; case version_name : Apptentive . Version entryVersionName = new Apptentive . Version ( ) ; Apptentive . Version currentVersionName = new Apptentive . Version ( ) ; entryVersionName . setVersion ( entry . getVersionName ( ) ) ; currentVersionName . setVersion ( RuntimeUtils . getAppVersionName ( ApptentiveInternal . getInstance ( ) . getApplicationContext ( ) ) ) ; if ( entryVersionName . equals ( currentVersionName ) ) { return new Apptentive . DateTime ( entry . getTimestamp ( ) ) ; } break ; } } return new Apptentive . DateTime ( Util . currentTimeSeconds ( ) ) ; } | Returns the number of seconds since the first time we saw this release of the app . Since the version entries are always stored in order the first matching entry happened first . |
13,617 | public static synchronized boolean isUpdate ( Selector selector ) { ensureLoaded ( ) ; Set < String > uniques = new HashSet < String > ( ) ; for ( VersionHistoryEntry entry : versionHistoryEntries ) { switch ( selector ) { case version_name : uniques . add ( entry . getVersionName ( ) ) ; break ; case version_code : uniques . add ( String . valueOf ( entry . getVersionCode ( ) ) ) ; break ; default : break ; } } return uniques . size ( ) > 1 ; } | Returns true if the current version or build is not the first version or build that we have seen . Basically it just looks for two or more versions or builds . |
13,618 | public static JSONArray getBaseArray ( ) { ensureLoaded ( ) ; JSONArray baseArray = new JSONArray ( ) ; for ( VersionHistoryEntry entry : versionHistoryEntries ) { baseArray . put ( entry ) ; } return baseArray ; } | Don t use this directly . Used for debugging only . |
13,619 | public static void addCustomDeviceData ( final String key , final String value ) { dispatchConversationTask ( new ConversationDispatchTask ( ) { protected boolean execute ( Conversation conversation ) { conversation . getDevice ( ) . getCustomData ( ) . put ( key , trim ( value ) ) ; return true ; } } , "add custom device data" ) ; } | Add a custom data String to the Device . Custom data will be sent to the server is displayed in the Conversation view and can be used in Interaction targeting . Calls to this method are idempotent . |
13,620 | public static void removeCustomDeviceData ( final String key ) { dispatchConversationTask ( new ConversationDispatchTask ( ) { protected boolean execute ( Conversation conversation ) { conversation . getDevice ( ) . getCustomData ( ) . remove ( key ) ; return true ; } } , "remove custom device data" ) ; } | Remove a piece of custom data from the device . Calls to this method are idempotent . |
13,621 | public static void addCustomPersonData ( final String key , final String value ) { dispatchConversationTask ( new ConversationDispatchTask ( ) { protected boolean execute ( Conversation conversation ) { conversation . getPerson ( ) . getCustomData ( ) . put ( key , trim ( value ) ) ; return true ; } } , "add custom person data" ) ; } | Add a custom data String to the Person . Custom data will be sent to the server is displayed in the Conversation view and can be used in Interaction targeting . Calls to this method are idempotent . |
13,622 | public static void removeCustomPersonData ( final String key ) { dispatchConversationTask ( new ConversationDispatchTask ( ) { protected boolean execute ( Conversation conversation ) { conversation . getPerson ( ) . getCustomData ( ) . remove ( key ) ; return true ; } } , "remove custom person data" ) ; } | Remove a piece of custom data from the Person . Calls to this method are idempotent . |
13,623 | 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 . |
13,624 | 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 . |
13,625 | 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 . |
13,626 | 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 . |
13,627 | public static void showMessageCenter ( final Context context , final BooleanCallback callback , final Map < String , Object > customData ) { dispatchConversationTask ( new ConversationDispatchTask ( callback , DispatchQueue . mainQueue ( ) ) { 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 . |
13,628 | public static void canShowMessageCenter ( BooleanCallback callback ) { dispatchConversationTask ( new ConversationDispatchTask ( callback , DispatchQueue . mainQueue ( ) ) { 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 . |
13,629 | public static void addUnreadMessagesListener ( final UnreadMessagesListener listener ) { dispatchConversationTask ( new ConversationDispatchTask ( ) { 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 . |
13,630 | 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 . |
13,631 | public static void sendAttachmentText ( final String text ) { dispatchConversationTask ( new ConversationDispatchTask ( ) { 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 . |
13,632 | 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 . |
13,633 | 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" ) ; } final OnPreInteractionListener preInteractionListener = Apptentive . preInteractionListener ; if ( preInteractionListener != null ) { dispatchConversationTask ( new ConversationDispatchTask ( callback , DispatchQueue . mainQueue ( ) ) { 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 ) ; } } , StringUtils . format ( "engage '%s' event" , event ) ) ; return ; } dispatchConversationTask ( new ConversationDispatchTask ( callback , DispatchQueue . mainQueue ( ) ) { 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 . |
13,634 | 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 ( ) { 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 . |
13,635 | 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 |
13,636 | public static String trim ( String str ) { return str != null && str . length ( ) > 0 ? str . trim ( ) : str ; } | Safely trims input string |
13,637 | 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 |
13,638 | 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 . |
13,639 | void dispatchRequest ( final HttpRequest request ) { networkQueue . dispatchAsync ( new DispatchTask ( ) { protected void execute ( ) { request . dispatchSync ( networkQueue ) ; } } ) ; } | Handles request synchronously |
13,640 | 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 |
13,641 | 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 |
13,642 | 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 |
13,643 | 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 . |
13,644 | 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 . |
13,645 | public static void startSession ( final Context context , final String appKey , final String appSignature ) { dispatchOnConversationQueue ( new DispatchTask ( ) { 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 . |
13,646 | private static String readAccessTokenFromClipboard ( Context context ) { String text = Util . getClipboardText ( context ) ; if ( StringUtils . isNullOrEmpty ( text ) ) { return null ; } text = text . replaceAll ( "\\s+" , "" ) ; if ( ! text . startsWith ( DEBUG_TEXT_HEADER ) ) { return null ; } return text . substring ( DEBUG_TEXT_HEADER . length ( ) ) ; } | Attempts to read access token from the clipboard |
13,647 | private static HttpRequest createTokenVerificationRequest ( String apptentiveAppKey , String apptentiveAppSignature , String token , HttpRequest . Listener < HttpJsonRequest > listener ) { 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 |
13,648 | public boolean clickOn ( int index ) { ImageItem item = getItem ( index ) ; if ( item == null || TextUtils . isEmpty ( item . mimeType ) ) { return false ; } if ( ! Util . isMimeTypeImage ( item . mimeType ) ) { if ( downloadItems . contains ( item . originalPath ) ) { return true ; } else { if ( ! bHasWritePermission ) { return false ; } File localFile = new File ( item . localCachePath ) ; if ( localFile . exists ( ) && ApptentiveAttachmentLoader . getInstance ( ) . isFileCompletelyDownloaded ( item . localCachePath ) ) { return false ; } else { downloadItems . add ( item . originalPath ) ; notifyDataSetChanged ( ) ; return true ; } } } return false ; } | Click an image |
13,649 | public void select ( ImageItem image ) { if ( selectedImages . contains ( image ) ) { selectedImages . remove ( image ) ; } else { selectedImages . add ( image ) ; } notifyDataSetChanged ( ) ; } | Select an image |
13,650 | 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 |
13,651 | 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 |
13,652 | 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 |
13,653 | public static void sendError ( final Throwable throwable , final String description , final String extraData ) { if ( ! isConversationQueue ( ) ) { dispatchOnConversationQueue ( new DispatchTask ( ) { 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 ) { 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 . |
13,654 | public static Integer parseWebColorAsAndroidColor ( String input ) { 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 . |
13,655 | 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 |
13,656 | 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 . |
13,657 | 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 ) ; 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 ( ! 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 |
13,658 | 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 |
13,659 | 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 . |
13,660 | public static StoredFile createLocalStoredFile ( InputStream is , String sourceUrl , String localFilePath , String mimeType ) { if ( is == null ) { return null ; } CountingOutputStream cos = null ; BufferedOutputStream bos = null ; FileOutputStream fos = null ; try { File localFile = new File ( localFilePath ) ; 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 ) ; } 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 . |
13,661 | public static Resources . Theme buildApptentiveInteractionTheme ( Context context ) { Resources . Theme theme = context . getResources ( ) . newTheme ( ) ; theme . applyStyle ( R . style . ApptentiveTheme_Base_Versioned , true ) ; 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 ) { return null ; } theme . applyStyle ( R . style . ApptentiveBaseFrameTheme , true ) ; 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 . |
13,662 | 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 |
13,663 | 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 |
13,664 | public static View . OnClickListener guarded ( final View . OnClickListener listener ) { if ( listener != null ) { return new View . OnClickListener ( ) { 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 |
13,665 | 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 . |
13,666 | public static void assertFail ( String format , Object ... args ) { assertFail ( StringUtils . format ( format , args ) ) ; } | General failure with a message |
13,667 | public T getValue ( ) { try { value = parse ( originalParameter ) ; } catch ( InvalidParameterException e ) { throw new WebApplicationException ( onError ( e ) ) ; } return value ; } | Returns the parsed value . |
13,668 | 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 . |
13,669 | 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 . |
13,670 | 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 . |
13,671 | 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 . |
13,672 | 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 |
13,673 | 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 . |
13,674 | 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 ) ) ; String [ ] parts = signature . replaceAll ( "\\.\\." , "." ) . substring ( returnTypeSpace + 1 ) . split ( "\\." ) ; for ( int i = 0 ; i < parts . length - 2 ; i ++ ) { 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 . |
13,675 | 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 . |
13,676 | public GenericResponseBuilder < T > header ( String name , Object value ) { rawBuilder . header ( name , value ) ; return this ; } | Adds a header to the response . |
13,677 | public GenericResponseBuilder < T > replaceAll ( MultivaluedMap < String , Object > headers ) { rawBuilder . replaceAll ( headers ) ; return this ; } | Replaces all of the headers with the these headers . |
13,678 | public GenericResponseBuilder < T > link ( URI uri , String rel ) { rawBuilder . link ( uri , rel ) ; return this ; } | Adds a link header . |
13,679 | 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 . |
13,680 | 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 . |
13,681 | public HealthDto doPrimaryHealthCheck ( ) { List < HealthDependency > primaryHealthDependencies = healthDependencies . values ( ) . stream ( ) . filter ( HealthDependency :: isPrimary ) . collect ( Collectors . toList ( ) ) ; return checkHealth ( primaryHealthDependencies ) ; } | Performs the Primary Health Check . |
13,682 | 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 . |
13,683 | 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 . |
13,684 | 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 . |
13,685 | 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 . |
13,686 | protected void addField ( String field ) { if ( field . contains ( "/" ) ) { String [ ] fields = field . split ( "/" , 2 ) ; String prefix = fields [ 0 ] ; 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 . |
13,687 | 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 . |
13,688 | 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 { 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 . |
13,689 | String lastLink ( ) { if ( totalResults == null || currentLimit == 0L ) { return null ; } Long lastOffset ; if ( totalResults % currentLimit == 0L ) { lastOffset = totalResults - currentLimit ; } else { lastOffset = totalResults / currentLimit * currentLimit ; } return urlWithUpdatedPagination ( lastOffset , currentLimit ) ; } | Returns the last page link ; null if no last page link is available . |
13,690 | 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 . |
13,691 | 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 . |
13,692 | 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 |
13,693 | 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 ; if ( needed && blur ) lightMap . gaussianBlur ( ) ; } } | Prepare all lights for rendering . |
13,694 | 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 |
13,695 | public void dispose ( ) { removeAll ( ) ; if ( lightMap != null ) lightMap . dispose ( ) ; if ( lightShader != null ) lightShader . dispose ( ) ; } | Disposes all this rayHandler lights and resources |
13,696 | 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 |
13,697 | 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 . |
13,698 | public void setDistance ( float dist ) { dist *= RayHandler . gammaCorrectionParameter ; this . distance = dist < 0.01f ? 0.01f : dist ; dirty = true ; } | Sets light distance |
13,699 | public void add ( RayHandler rayHandler ) { this . rayHandler = rayHandler ; if ( active ) { rayHandler . lightList . add ( this ) ; } else { rayHandler . disabledLights . add ( this ) ; } } | Adds light to specified RayHandler |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.