idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
13,500 | public E getUser ( HttpServletRequest servletRequest ) { AttributePrincipal principal = getUserPrincipal ( servletRequest ) ; E result = this . userDao . getByPrincipal ( principal ) ; if ( result == null ) { throw new HttpStatusException ( Status . FORBIDDEN , "User " + principal . getName ( ) + " is not authorized to use this resource" ) ; } return result ; } | Returns the user object or if there isn t one throws an exception . | 96 | 14 |
13,501 | @ Override public void attributeReplaced ( HttpSessionBindingEvent hse ) { Object possibleClient = hse . getValue ( ) ; closeClient ( possibleClient ) ; } | Attempts to close the old client . | 39 | 7 |
13,502 | @ Override public void attributeRemoved ( HttpSessionBindingEvent hse ) { Object possibleClient = hse . getValue ( ) ; closeClient ( possibleClient ) ; } | Attempts to close the client . | 38 | 6 |
13,503 | protected void doDelete ( String path , MultivaluedMap < String , String > headers ) throws ClientException { this . readLock . lock ( ) ; try { ClientResponse response = this . getResourceWrapper ( ) . rewritten ( path , HttpMethod . DELETE ) . delete ( ClientResponse . class ) ; errorIfStatusNotEqualTo ( response , ClientResponse . Status . OK , ClientResponse . Status . NO_CONTENT , ClientResponse . Status . ACCEPTED ) ; response . close ( ) ; } catch ( ClientHandlerException ex ) { throw new ClientException ( ClientResponse . Status . INTERNAL_SERVER_ERROR , ex . getMessage ( ) ) ; } finally { this . readLock . unlock ( ) ; } } | Deletes the resource specified by the path . | 161 | 9 |
13,504 | protected void doPut ( String path ) throws ClientException { this . readLock . lock ( ) ; try { ClientResponse response = this . getResourceWrapper ( ) . rewritten ( path , HttpMethod . PUT ) . put ( ClientResponse . class ) ; errorIfStatusNotEqualTo ( response , ClientResponse . Status . OK , ClientResponse . Status . NO_CONTENT ) ; response . close ( ) ; } catch ( ClientHandlerException ex ) { throw new ClientException ( ClientResponse . Status . INTERNAL_SERVER_ERROR , ex . getMessage ( ) ) ; } finally { this . readLock . unlock ( ) ; } } | Updates the resource specified by the path for situations where the nature of the update is completely specified by the path alone . | 140 | 24 |
13,505 | protected void doPut ( String path , Object o ) throws ClientException { doPut ( path , o , null ) ; } | Updates the resource specified by the path . Sends to the server a Content Type header for JSON . | 26 | 21 |
13,506 | protected < T > T doGet ( String path , Class < T > cls ) throws ClientException { return doGet ( path , cls , null ) ; } | Gets the resource specified by the path . Sends to the server an Accepts header for JSON . | 35 | 21 |
13,507 | protected < T > T doGet ( String path , Class < T > cls , MultivaluedMap < String , String > headers ) throws ClientException { this . readLock . lock ( ) ; try { WebResource . Builder requestBuilder = getResourceWrapper ( ) . rewritten ( path , HttpMethod . GET ) . getRequestBuilder ( ) ; requestBuilder = ensureJsonHeaders ( headers , requestBuilder , false , true ) ; ClientResponse response = requestBuilder . get ( ClientResponse . class ) ; errorIfStatusNotEqualTo ( response , ClientResponse . Status . OK ) ; return response . getEntity ( cls ) ; } catch ( ClientHandlerException ex ) { throw new ClientException ( ClientResponse . Status . INTERNAL_SERVER_ERROR , ex . getMessage ( ) ) ; } finally { this . readLock . unlock ( ) ; } } | Gets the resource specified by the path . | 187 | 9 |
13,508 | protected < T > T doGet ( String path , MultivaluedMap < String , String > queryParams , GenericType < T > genericType ) throws ClientException { return doGet ( path , queryParams , genericType , null ) ; } | Gets the requested resource . Adds an appropriate Accepts header . | 53 | 13 |
13,509 | protected < T > T doPost ( String path , MultivaluedMap < String , String > formParams , Class < T > cls , MultivaluedMap < String , String > headers ) throws ClientException { this . readLock . lock ( ) ; try { WebResource . Builder requestBuilder = getResourceWrapper ( ) . rewritten ( path , HttpMethod . POST ) . getRequestBuilder ( ) ; ensurePostFormHeaders ( headers , requestBuilder , true , true ) ; ClientResponse response = requestBuilder . post ( ClientResponse . class , formParams ) ; errorIfStatusNotEqualTo ( response , ClientResponse . Status . OK ) ; return response . getEntity ( cls ) ; } catch ( ClientHandlerException ex ) { throw new ClientException ( ClientResponse . Status . INTERNAL_SERVER_ERROR , ex . getMessage ( ) ) ; } finally { this . readLock . unlock ( ) ; } } | Submits a form and gets back a JSON object . | 201 | 11 |
13,510 | protected void doPost ( String path ) throws ClientException { this . readLock . lock ( ) ; try { ClientResponse response = getResourceWrapper ( ) . rewritten ( path , HttpMethod . POST ) . post ( ClientResponse . class ) ; errorIfStatusNotEqualTo ( response , ClientResponse . Status . OK , ClientResponse . Status . NO_CONTENT ) ; response . close ( ) ; } catch ( ClientHandlerException ex ) { throw new ClientException ( ClientResponse . Status . INTERNAL_SERVER_ERROR , ex . getMessage ( ) ) ; } finally { this . readLock . unlock ( ) ; } } | Makes a POST call to the specified path . | 137 | 10 |
13,511 | protected void doPostForm ( String path , MultivaluedMap < String , String > formParams ) throws ClientException { doPostForm ( path , formParams , null ) ; } | Submits a form . Adds appropriate Accepts and Content Type headers . | 40 | 14 |
13,512 | protected void doPostForm ( String path , MultivaluedMap < String , String > formParams , MultivaluedMap < String , String > headers ) throws ClientException { this . readLock . lock ( ) ; try { WebResource . Builder requestBuilder = getResourceWrapper ( ) . rewritten ( path , HttpMethod . POST ) . getRequestBuilder ( ) ; ensurePostFormHeaders ( headers , requestBuilder , true , false ) ; ClientResponse response = requestBuilder . post ( ClientResponse . class ) ; errorIfStatusNotEqualTo ( response , ClientResponse . Status . OK , ClientResponse . Status . NO_CONTENT ) ; response . close ( ) ; } catch ( ClientHandlerException ex ) { throw new ClientException ( ClientResponse . Status . INTERNAL_SERVER_ERROR , ex . getMessage ( ) ) ; } finally { this . readLock . unlock ( ) ; } } | Submits a form . | 194 | 5 |
13,513 | public void doPostMultipart ( String path , FormDataMultiPart formDataMultiPart ) throws ClientException { this . readLock . lock ( ) ; try { ClientResponse response = getResourceWrapper ( ) . rewritten ( path , HttpMethod . POST ) . type ( Boundary . addBoundary ( MediaType . MULTIPART_FORM_DATA_TYPE ) ) . post ( ClientResponse . class , formDataMultiPart ) ; errorIfStatusNotEqualTo ( response , ClientResponse . Status . OK , ClientResponse . Status . NO_CONTENT ) ; response . close ( ) ; } catch ( ClientHandlerException ex ) { throw new ClientException ( ClientResponse . Status . INTERNAL_SERVER_ERROR , ex . getMessage ( ) ) ; } finally { this . readLock . unlock ( ) ; } } | Submits a multi - part form . Adds appropriate Accepts and Content Type headers . | 179 | 17 |
13,514 | public void doPostMultipart ( String path , FormDataMultiPart formDataMultiPart , MultivaluedMap < String , String > headers ) throws ClientException { this . readLock . lock ( ) ; try { WebResource . Builder requestBuilder = getResourceWrapper ( ) . rewritten ( path , HttpMethod . POST ) . getRequestBuilder ( ) ; requestBuilder = ensurePostMultipartHeaders ( headers , requestBuilder ) ; ClientResponse response = requestBuilder . post ( ClientResponse . class , formDataMultiPart ) ; errorIfStatusNotEqualTo ( response , ClientResponse . Status . OK , ClientResponse . Status . NO_CONTENT ) ; response . close ( ) ; } catch ( ClientHandlerException ex ) { throw new ClientException ( ClientResponse . Status . INTERNAL_SERVER_ERROR , ex . getMessage ( ) ) ; } finally { this . readLock . unlock ( ) ; } } | Submits a multi - part form . | 198 | 8 |
13,515 | protected void doPostMultipart ( String path , InputStream inputStream ) throws ClientException { doPostMultipart ( path , inputStream , null ) ; } | Submits a multi - part form in an input stream . Adds appropriate Accepts and Content Type headers . | 35 | 21 |
13,516 | protected URI doPostCreate ( String path , Object o ) throws ClientException { return doPostCreate ( path , o , null ) ; } | Creates a resource specified as a JSON object . Adds appropriate Accepts and Content Type headers . | 29 | 19 |
13,517 | protected URI doPostCreate ( String path , Object o , MultivaluedMap < String , String > headers ) throws ClientException { this . readLock . lock ( ) ; try { WebResource . Builder requestBuilder = getResourceWrapper ( ) . rewritten ( path , HttpMethod . POST ) . getRequestBuilder ( ) ; requestBuilder = ensurePostCreateJsonHeaders ( headers , requestBuilder , true , false ) ; ClientResponse response = requestBuilder . post ( ClientResponse . class , o ) ; errorIfStatusNotEqualTo ( response , ClientResponse . Status . OK , ClientResponse . Status . CREATED ) ; try { return response . getLocation ( ) ; } finally { response . close ( ) ; } } catch ( ClientHandlerException ex ) { throw new ClientException ( ClientResponse . Status . INTERNAL_SERVER_ERROR , ex . getMessage ( ) ) ; } finally { this . readLock . unlock ( ) ; } } | Creates a resource specified as a JSON object . | 203 | 10 |
13,518 | protected URI doPostCreateMultipart ( String path , InputStream inputStream ) throws ClientException { return doPostCreateMultipart ( path , inputStream , null ) ; } | Creates a resource specified as a multi - part form in an input stream . Adds appropriate Accepts and Content Type headers . | 38 | 25 |
13,519 | protected URI doPostCreateMultipart ( String path , InputStream inputStream , MultivaluedMap < String , String > headers ) throws ClientException { this . readLock . lock ( ) ; try { WebResource . Builder requestBuilder = getResourceWrapper ( ) . rewritten ( path , HttpMethod . POST ) . getRequestBuilder ( ) ; requestBuilder = ensurePostCreateMultipartHeaders ( headers , requestBuilder ) ; ClientResponse response = requestBuilder . post ( ClientResponse . class , inputStream ) ; errorIfStatusNotEqualTo ( response , ClientResponse . Status . OK , ClientResponse . Status . CREATED ) ; try { return response . getLocation ( ) ; } finally { response . close ( ) ; } } catch ( ClientHandlerException ex ) { throw new ClientException ( ClientResponse . Status . INTERNAL_SERVER_ERROR , ex . getMessage ( ) ) ; } finally { this . readLock . unlock ( ) ; } } | Creates a resource specified as a multi - part form in an input stream . | 206 | 16 |
13,520 | protected URI doPostCreateMultipart ( String path , FormDataMultiPart formDataMultiPart ) throws ClientException { this . readLock . lock ( ) ; try { ClientResponse response = getResourceWrapper ( ) . rewritten ( path , HttpMethod . POST ) . type ( Boundary . addBoundary ( MediaType . MULTIPART_FORM_DATA_TYPE ) ) . accept ( MediaType . TEXT_PLAIN ) . post ( ClientResponse . class , formDataMultiPart ) ; errorIfStatusNotEqualTo ( response , ClientResponse . Status . OK , ClientResponse . Status . CREATED ) ; try { return response . getLocation ( ) ; } finally { response . close ( ) ; } } catch ( ClientHandlerException ex ) { throw new ClientException ( ClientResponse . Status . INTERNAL_SERVER_ERROR , ex . getMessage ( ) ) ; } finally { this . readLock . unlock ( ) ; } } | Creates a resource specified as a multi - part form . Adds appropriate Accepts and Content Type headers . | 203 | 21 |
13,521 | protected ClientResponse doPostForProxy ( String path , InputStream inputStream , MultivaluedMap < String , String > parameterMap , MultivaluedMap < String , String > headers ) throws ClientException { this . readLock . lock ( ) ; try { WebResource . Builder requestBuilder = getResourceWrapper ( ) . rewritten ( path , HttpMethod . POST , parameterMap ) . getRequestBuilder ( ) ; copyHeaders ( headers , requestBuilder ) ; return requestBuilder . post ( ClientResponse . class , inputStream ) ; } catch ( ClientHandlerException ex ) { throw new ClientException ( ClientResponse . Status . INTERNAL_SERVER_ERROR , ex . getMessage ( ) ) ; } finally { this . readLock . unlock ( ) ; } } | Passes a new resource form or other POST body to a proxied server . | 163 | 16 |
13,522 | protected ClientResponse doGetForProxy ( String path , MultivaluedMap < String , String > parameterMap , MultivaluedMap < String , String > headers ) throws ClientException { this . readLock . lock ( ) ; try { WebResource . Builder requestBuilder = getResourceWrapper ( ) . rewritten ( path , HttpMethod . GET , parameterMap ) . getRequestBuilder ( ) ; copyHeaders ( headers , requestBuilder ) ; return requestBuilder . get ( ClientResponse . class ) ; } catch ( ClientHandlerException ex ) { throw new ClientException ( ClientResponse . Status . INTERNAL_SERVER_ERROR , ex . getMessage ( ) ) ; } finally { this . readLock . unlock ( ) ; } } | Gets a resource from a proxied server . | 155 | 10 |
13,523 | protected ClientResponse doDeleteForProxy ( String path , MultivaluedMap < String , String > parameterMap , MultivaluedMap < String , String > headers ) throws ClientException { this . readLock . lock ( ) ; try { WebResource . Builder requestBuilder = getResourceWrapper ( ) . rewritten ( path , HttpMethod . DELETE , parameterMap ) . getRequestBuilder ( ) ; copyHeaders ( headers , requestBuilder ) ; return requestBuilder . delete ( ClientResponse . class ) ; } catch ( ClientHandlerException ex ) { throw new ClientException ( ClientResponse . Status . INTERNAL_SERVER_ERROR , ex . getMessage ( ) ) ; } finally { this . readLock . unlock ( ) ; } } | Deletes a resource from a proxied server . | 157 | 10 |
13,524 | protected void errorIfStatusEqualTo ( ClientResponse response , ClientResponse . Status ... status ) throws ClientException { errorIf ( response , status , true ) ; } | If there is an unexpected status code this method gets the status message closes the response and throws an exception . | 35 | 21 |
13,525 | protected Long extractId ( URI uri ) { String uriStr = uri . toString ( ) ; return Long . valueOf ( uriStr . substring ( uriStr . lastIndexOf ( "/" ) + 1 ) ) ; } | Extracts the id of the resource specified in the response body from a POST call . | 53 | 18 |
13,526 | private static boolean contains ( Object [ ] arr , Object member ) { for ( Object mem : arr ) { if ( Objects . equals ( mem , member ) ) { return true ; } } return false ; } | Tests array membership . | 43 | 5 |
13,527 | private static WebResource . Builder ensureJsonHeaders ( MultivaluedMap < String , String > headers , WebResource . Builder requestBuilder , boolean contentType , boolean accept ) { boolean hasContentType = false ; boolean hasAccept = false ; if ( headers != null ) { for ( Map . Entry < String , List < String > > entry : headers . entrySet ( ) ) { String key = entry . getKey ( ) ; for ( String val : entry . getValue ( ) ) { if ( contentType && HttpHeaders . CONTENT_TYPE . equalsIgnoreCase ( key ) ) { hasContentType = true ; } else if ( accept && HttpHeaders . ACCEPT . equalsIgnoreCase ( key ) ) { hasAccept = true ; } requestBuilder = requestBuilder . header ( key , val ) ; } } } if ( ! hasContentType ) { requestBuilder = requestBuilder . type ( MediaType . APPLICATION_JSON ) ; } if ( ! hasAccept ) { requestBuilder = requestBuilder . accept ( MediaType . APPLICATION_JSON ) ; } return requestBuilder ; } | Adds the specified headers to the request builder . Provides default headers for JSON objects requests and submissions . | 236 | 19 |
13,528 | private void checkBorderAndCenterWhenScale ( ) { RectF rect = getMatrixRectF ( ) ; float deltaX = 0 ; float deltaY = 0 ; int width = getWidth ( ) ; int height = getHeight ( ) ; if ( rect . width ( ) >= width ) { if ( rect . left > 0 ) { deltaX = - rect . left ; } if ( rect . right < width ) { deltaX = width - rect . right ; } } if ( rect . height ( ) >= height ) { if ( rect . top > 0 ) { deltaY = - rect . top ; } if ( rect . bottom < height ) { deltaY = height - rect . bottom ; } } // Always center the image when it's smaller than the imageView if ( rect . width ( ) < width ) { deltaX = width * 0.5f - rect . right + 0.5f * rect . width ( ) ; } if ( rect . height ( ) < height ) { deltaY = height * 0.5f - rect . bottom + 0.5f * rect . height ( ) ; } scaleMatrix . postTranslate ( deltaX , deltaY ) ; } | Prevent visual artifact when scaling | 250 | 6 |
13,529 | private RectF getMatrixRectF ( ) { Matrix matrix = scaleMatrix ; RectF rect = new RectF ( ) ; Drawable d = getDrawable ( ) ; if ( null != d ) { rect . set ( 0 , 0 , d . getIntrinsicWidth ( ) , d . getIntrinsicHeight ( ) ) ; matrix . mapRect ( rect ) ; } return rect ; } | Get image boundary from matrix | 87 | 5 |
13,530 | private void checkMatrixBounds ( ) { RectF rect = getMatrixRectF ( ) ; float deltaX = 0 , deltaY = 0 ; final float viewWidth = getWidth ( ) ; final float viewHeight = getHeight ( ) ; // Check if image boundary exceeds imageView boundary if ( rect . top > 0 && isCheckTopAndBottom ) { deltaY = - rect . top ; } if ( rect . bottom < viewHeight && isCheckTopAndBottom ) { deltaY = viewHeight - rect . bottom ; } if ( rect . left > 0 && isCheckLeftAndRight ) { deltaX = - rect . left ; } if ( rect . right < viewWidth && isCheckLeftAndRight ) { deltaX = viewWidth - rect . right ; } scaleMatrix . postTranslate ( deltaX , deltaY ) ; } | Check image bounday against imageView | 177 | 7 |
13,531 | private @ Nullable Conversation loadConversationFromMetadata ( ConversationMetadata metadata ) throws SerializerException , ConversationLoadException { // we're going to scan metadata in attempt to find existing conversations ConversationMetadataItem item ; // if the user was logged in previously - we should have an active conversation item = metadata . findItem ( LOGGED_IN ) ; if ( item != null ) { ApptentiveLog . i ( CONVERSATION , "Loading 'logged-in' conversation..." ) ; return loadConversation ( item ) ; } // if no users were logged in previously - we might have an anonymous conversation item = metadata . findItem ( ANONYMOUS ) ; if ( item != null ) { ApptentiveLog . i ( CONVERSATION , "Loading 'anonymous' conversation..." ) ; return loadConversation ( item ) ; } // check if we have a 'pending' anonymous conversation item = metadata . findItem ( ANONYMOUS_PENDING ) ; if ( item != null ) { ApptentiveLog . i ( CONVERSATION , "Loading 'anonymous pending' conversation..." ) ; final Conversation conversation = loadConversation ( item ) ; fetchConversationToken ( conversation ) ; return conversation ; } // check if we have a 'legacy pending' conversation item = metadata . findItem ( LEGACY_PENDING ) ; if ( item != null ) { ApptentiveLog . i ( CONVERSATION , "Loading 'legacy pending' conversation..." ) ; final Conversation conversation = loadConversation ( item ) ; fetchLegacyConversation ( conversation ) ; return conversation ; } // we only have LOGGED_OUT conversations ApptentiveLog . i ( CONVERSATION , "No active conversations to load: only 'logged-out' conversations available" ) ; return null ; } | Attempts to load an existing conversation based on metadata file | 395 | 10 |
13,532 | private void handleConversationStateChange ( Conversation conversation ) { ApptentiveLog . d ( CONVERSATION , "Conversation state changed: %s" , conversation ) ; checkConversationQueue ( ) ; assertTrue ( conversation != null && ! conversation . hasState ( UNDEFINED ) ) ; if ( conversation != null && ! conversation . hasState ( UNDEFINED ) ) { ApptentiveNotificationCenter . defaultCenter ( ) . postNotification ( NOTIFICATION_CONVERSATION_STATE_DID_CHANGE , NOTIFICATION_KEY_CONVERSATION , conversation ) ; if ( conversation . hasActiveState ( ) ) { if ( appIsInForeground ) { // ConversationManager listens to the foreground event to fetch interactions when it comes to foreground conversation . fetchInteractions ( getContext ( ) ) ; // Message Manager listens to foreground/background events itself conversation . getMessageManager ( ) . attemptToStartMessagePolling ( ) ; } // Fetch app configuration fetchAppConfiguration ( conversation ) ; // Update conversation with push configuration changes that happened while it wasn't active. SharedPreferences prefs = ApptentiveInternal . getInstance ( ) . getGlobalSharedPrefs ( ) ; int pushProvider = prefs . getInt ( Constants . PREF_KEY_PUSH_PROVIDER , - 1 ) ; String pushToken = prefs . getString ( Constants . PREF_KEY_PUSH_TOKEN , null ) ; if ( pushProvider != - 1 && pushToken != null ) { conversation . setPushIntegration ( pushProvider , pushToken ) ; } } updateMetadataItems ( conversation ) ; if ( ApptentiveLog . canLog ( VERBOSE ) ) { printMetadata ( conversationMetadata , "Updated Metadata" ) ; } } } | region Conversation fetching | 389 | 4 |
13,533 | public Apptentive . DateTime getTimeAtInstallTotal ( ) { // Simply return the first item's timestamp, if there is one. if ( versionHistoryItems . size ( ) > 0 ) { return new Apptentive . DateTime ( versionHistoryItems . get ( 0 ) . getTimestamp ( ) ) ; } return new Apptentive . DateTime ( Util . currentTimeSeconds ( ) ) ; } | Returns the timestamp at the first install of this app that Apptentive was aware of . | 92 | 19 |
13,534 | public Apptentive . DateTime getTimeAtInstallForVersionCode ( int versionCode ) { for ( VersionHistoryItem item : versionHistoryItems ) { if ( item . getVersionCode ( ) == versionCode ) { return new Apptentive . DateTime ( item . getTimestamp ( ) ) ; } } return new Apptentive . DateTime ( Util . currentTimeSeconds ( ) ) ; } | Returns the timestamp at the first install of the current versionCode of this app that Apptentive was aware of . | 90 | 24 |
13,535 | public Apptentive . DateTime getTimeAtInstallForVersionName ( String versionName ) { for ( VersionHistoryItem item : versionHistoryItems ) { Apptentive . Version entryVersionName = new Apptentive . Version ( ) ; Apptentive . Version currentVersionName = new Apptentive . Version ( ) ; entryVersionName . setVersion ( item . getVersionName ( ) ) ; currentVersionName . setVersion ( versionName ) ; if ( entryVersionName . equals ( currentVersionName ) ) { return new Apptentive . DateTime ( item . getTimestamp ( ) ) ; } } return new Apptentive . DateTime ( Util . currentTimeSeconds ( ) ) ; } | Returns the timestamp at the first install of the current versionName of this app that Apptentive was aware of . | 157 | 24 |
13,536 | public boolean isUpdateForVersionCode ( ) { Set < Integer > uniques = new HashSet < Integer > ( ) ; for ( VersionHistoryItem item : versionHistoryItems ) { uniques . add ( item . getVersionCode ( ) ) ; } return uniques . size ( ) > 1 ; } | Returns true if the current versionCode is not the first version or build that we have seen . Basically it just looks for two or more versionCodes . | 64 | 31 |
13,537 | public boolean isUpdateForVersionName ( ) { Set < String > uniques = new HashSet < String > ( ) ; for ( VersionHistoryItem item : versionHistoryItems ) { uniques . add ( item . getVersionName ( ) ) ; } return uniques . size ( ) > 1 ; } | Returns true if the current versionName is not the first version or build that we have seen . Basically it just looks for two or more versionNames . | 64 | 30 |
13,538 | public Interactions getInteractions ( ) { try { if ( ! isNull ( Interactions . KEY_NAME ) ) { Object obj = get ( Interactions . KEY_NAME ) ; if ( obj instanceof JSONArray ) { Interactions interactions = new Interactions ( ) ; JSONArray interactionsJSONArray = ( JSONArray ) obj ; for ( int i = 0 ; i < interactionsJSONArray . length ( ) ; i ++ ) { Interaction interaction = Interaction . Factory . parseInteraction ( interactionsJSONArray . getString ( i ) ) ; if ( interaction != null ) { interactions . put ( interaction . getId ( ) , interaction ) ; } else { // This is an unknown Interaction type. Probably for a future SDK version. } } return interactions ; } } } catch ( JSONException e ) { ApptentiveLog . w ( INTERACTIONS , e , "Unable to load Interactions from InteractionManifest." ) ; logException ( e ) ; } return null ; } | In addition to returning the Interactions contained in this payload this method reformats the Interactions from a list into a map . The map is then used for further Interaction lookup . | 210 | 36 |
13,539 | @ Override public Thread newThread ( Runnable r ) { return new Thread ( r , getName ( ) + " (thread-" + threadNumber . getAndIncrement ( ) + ")" ) ; } | region Thread factory | 45 | 3 |
13,540 | @ Override protected void onTextChanged ( final CharSequence text , final int start , final int before , final int after ) { mNeedsResize = true ; // Since this view may be reused, it is good to reset the text size resetTextSize ( ) ; } | When text changes set the force resize flag to true and reset the text size . | 59 | 16 |
13,541 | @ Override protected void onSizeChanged ( int w , int h , int oldw , int oldh ) { if ( w != oldw || h != oldh ) { mNeedsResize = true ; } } | If the text view size changed set the force resize flag to true | 47 | 13 |
13,542 | @ Override public void setLineSpacing ( float add , float mult ) { super . setLineSpacing ( add , mult ) ; mSpacingMult = mult ; mSpacingAdd = add ; } | Override the set line spacing to update our internal reference values | 44 | 11 |
13,543 | @ Override protected void onLayout ( boolean changed , int left , int top , int right , int bottom ) { if ( changed || mNeedsResize ) { int widthLimit = ( right - left ) - getCompoundPaddingLeft ( ) - getCompoundPaddingRight ( ) ; int heightLimit = ( bottom - top ) - getCompoundPaddingBottom ( ) - getCompoundPaddingTop ( ) ; resizeText ( widthLimit , heightLimit ) ; } super . onLayout ( changed , left , top , right , bottom ) ; } | Resize text after measuring | 119 | 5 |
13,544 | public void resizeText ( ) { int heightLimit = getHeight ( ) - getPaddingBottom ( ) - getPaddingTop ( ) ; int widthLimit = getWidth ( ) - getPaddingLeft ( ) - getPaddingRight ( ) ; resizeText ( widthLimit , heightLimit ) ; } | Resize the text size with default width and height | 64 | 10 |
13,545 | public void resizeText ( int width , int height ) { CharSequence text = getText ( ) ; // Do not resize if the view does not have dimensions or there is no text if ( text == null || text . length ( ) == 0 || height <= 0 || width <= 0 || mTextSize == 0 ) { return ; } if ( getTransformationMethod ( ) != null ) { text = getTransformationMethod ( ) . getTransformation ( text , this ) ; } // Get the text view's paint object TextPaint textPaint = getPaint ( ) ; // Store the current text size float oldTextSize = textPaint . getTextSize ( ) ; // If there is a max text size set, use the lesser of that and the default text size float targetTextSize = mMaxTextSize > 0 ? Math . min ( mTextSize , mMaxTextSize ) : mTextSize ; // Get the required text height int textHeight = getTextHeight ( text , textPaint , width , targetTextSize ) ; // Until we either fit within our text view or we had reached our min text size, incrementally try smaller sizes while ( textHeight > height && targetTextSize > mMinTextSize ) { targetTextSize = Math . max ( targetTextSize - 2 , mMinTextSize ) ; textHeight = getTextHeight ( text , textPaint , width , targetTextSize ) ; } // If we had reached our minimum text size and still don't fit, append an ellipsis if ( mAddEllipsis && targetTextSize == mMinTextSize && textHeight > height ) { // Draw using a static layout // modified: use a copy of TextPaint for measuring TextPaint paint = new TextPaint ( textPaint ) ; // Draw using a static layout StaticLayout layout = new StaticLayout ( text , paint , width , Alignment . ALIGN_NORMAL , mSpacingMult , mSpacingAdd , false ) ; // Check that we have a least one line of rendered text if ( layout . getLineCount ( ) > 0 ) { // Since the line at the specific vertical position would be cut off, // we must trim up to the previous line int lastLine = layout . getLineForVertical ( height ) - 1 ; // If the text would not even fit on a single line, clear it if ( lastLine < 0 ) { setText ( "" ) ; } // Otherwise, trim to the previous line and add an ellipsis else { int start = layout . getLineStart ( lastLine ) ; int end = layout . getLineEnd ( lastLine ) ; float lineWidth = layout . getLineWidth ( lastLine ) ; float ellipseWidth = textPaint . measureText ( mEllipsis ) ; // Trim characters off until we have enough room to draw the ellipsis while ( width < lineWidth + ellipseWidth ) { lineWidth = textPaint . measureText ( text . subSequence ( start , -- end + 1 ) . toString ( ) ) ; } setText ( text . subSequence ( 0 , end ) + mEllipsis ) ; } } } // Some devices try to auto adjust line spacing, so force default line spacing // and invalidate the layout as a side effect setTextSize ( TypedValue . COMPLEX_UNIT_PX , targetTextSize ) ; setLineSpacing ( mSpacingAdd , mSpacingMult ) ; // Notify the listener if registered if ( mTextResizeListener != null ) { mTextResizeListener . onTextResize ( this , oldTextSize , targetTextSize ) ; } // Reset force resize flag mNeedsResize = false ; } | Resize the text size with specified width and height | 790 | 10 |
13,546 | static void saveCurrentSession ( Context context , LogMonitorSession session ) { if ( context == null ) { throw new IllegalArgumentException ( "Context is null" ) ; } if ( session == null ) { throw new IllegalArgumentException ( "Session is null" ) ; } SharedPreferences prefs = getPrefs ( context ) ; SharedPreferences . Editor editor = prefs . edit ( ) ; editor . putString ( PREFS_KEY_EMAIL_RECIPIENTS , StringUtils . join ( session . emailRecipients ) ) ; editor . apply ( ) ; } | Saves current session to the persistent storage | 126 | 8 |
13,547 | static void deleteCurrentSession ( Context context ) { SharedPreferences . Editor editor = getPrefs ( context ) . edit ( ) ; editor . remove ( PREFS_KEY_EMAIL_RECIPIENTS ) ; editor . remove ( PREFS_KEY_FILTER_PID ) ; editor . apply ( ) ; } | Deletes current session from the persistent storage | 69 | 8 |
13,548 | protected static void registerSensitiveKeys ( Class < ? extends JsonPayload > cls ) { List < Field > fields = RuntimeUtils . listFields ( cls , new RuntimeUtils . FieldFilter ( ) { @ Override public boolean accept ( Field field ) { return Modifier . isStatic ( field . getModifiers ( ) ) && // static fields field . getAnnotation ( SensitiveDataKey . class ) != null && // marked as 'sensitive' field . getType ( ) . equals ( String . class ) ; // with type of String } } ) ; if ( fields . size ( ) > 0 ) { List < String > keys = new ArrayList <> ( fields . size ( ) ) ; try { for ( Field field : fields ) { field . setAccessible ( true ) ; String value = ( String ) field . get ( null ) ; keys . add ( value ) ; } SENSITIVE_KEYS_LOOKUP . put ( cls , keys ) ; } catch ( Exception e ) { ApptentiveLog . e ( e , "Exception while registering sensitive keys" ) ; logException ( e ) ; } } } | region Sensitive Keys | 248 | 4 |
13,549 | private ImageScale scaleImage ( int imageX , int imageY , int containerX , int containerY ) { ImageScale ret = new ImageScale ( ) ; // Compare aspects faster by multiplying out the divisors. if ( imageX * containerY > imageY * containerX ) { // Image aspect wider than container ret . scale = ( float ) containerX / imageX ; ret . deltaY = ( ( float ) containerY - ( ret . scale * imageY ) ) / 2.0f ; } else { // Image aspect taller than container ret . scale = ( float ) containerY / imageY ; ret . deltaX = ( ( float ) containerX - ( ret . scale * imageX ) ) / 2.0f ; } return ret ; } | This scales the image so that it fits within the container . The container may have empty space at the ends but the entire image will be displayed . | 160 | 29 |
13,550 | public void update ( double timestamp , String versionName , Integer versionCode ) { last = timestamp ; total ++ ; Long countForVersionName = versionNames . get ( versionName ) ; if ( countForVersionName == null ) { countForVersionName = 0L ; } Long countForVersionCode = versionCodes . get ( versionCode ) ; if ( countForVersionCode == null ) { countForVersionCode = 0L ; } versionNames . put ( versionName , countForVersionName + 1 ) ; versionCodes . put ( versionCode , countForVersionCode + 1 ) ; } | Initializes an event record or updates it with a subsequent event . | 126 | 13 |
13,551 | public static void serialize ( File file , SerializableObject object ) throws IOException { AtomicFile atomicFile = new AtomicFile ( file ) ; FileOutputStream stream = null ; try { stream = atomicFile . startWrite ( ) ; DataOutputStream out = new DataOutputStream ( stream ) ; object . writeExternal ( out ) ; atomicFile . finishWrite ( stream ) ; // serialization was successful } catch ( Exception e ) { atomicFile . failWrite ( stream ) ; // serialization failed throw new IOException ( e ) ; // throw exception up the chain } } | Writes an object ot a file | 120 | 7 |
13,552 | public static < T extends SerializableObject > T deserialize ( File file , Class < T > cls ) throws IOException { FileInputStream stream = null ; try { stream = new FileInputStream ( file ) ; DataInputStream in = new DataInputStream ( stream ) ; try { Constructor < T > constructor = cls . getDeclaredConstructor ( DataInput . class ) ; constructor . setAccessible ( true ) ; return constructor . newInstance ( in ) ; } catch ( Exception e ) { throw new IOException ( "Unable to instantiate class: " + cls , e ) ; } } finally { Util . ensureClosed ( stream ) ; } } | Reads an object from a file | 146 | 7 |
13,553 | public void storeInteractionManifest ( String interactionManifest ) { try { InteractionManifest payload = new InteractionManifest ( interactionManifest ) ; Interactions interactions = payload . getInteractions ( ) ; Targets targets = payload . getTargets ( ) ; if ( interactions != null && targets != null ) { setTargets ( targets . toString ( ) ) ; setInteractions ( interactions . toString ( ) ) ; } else { ApptentiveLog . e ( CONVERSATION , "Unable to save InteractionManifest." ) ; } } catch ( JSONException e ) { ApptentiveLog . w ( CONVERSATION , "Invalid InteractionManifest received." ) ; logException ( e ) ; } } | Made public for testing . There is no other reason to use this method directly . | 160 | 16 |
13,554 | boolean migrateConversationData ( ) throws SerializerException { long start = System . currentTimeMillis ( ) ; File legacyConversationDataFile = Util . getUnencryptedFilename ( conversationDataFile ) ; if ( legacyConversationDataFile . exists ( ) ) { try { ApptentiveLog . d ( CONVERSATION , "Migrating %sconversation data..." , hasState ( LOGGED_IN ) ? "encrypted " : "" ) ; FileSerializer serializer = isAuthenticated ( ) ? new EncryptedFileSerializer ( legacyConversationDataFile , getEncryptionKey ( ) ) : new FileSerializer ( legacyConversationDataFile ) ; conversationData = ( ConversationData ) serializer . deserialize ( ) ; ApptentiveLog . d ( CONVERSATION , "Conversation data migrated (took %d ms)" , System . currentTimeMillis ( ) - start ) ; return true ; } finally { boolean deleted = legacyConversationDataFile . delete ( ) ; ApptentiveLog . d ( CONVERSATION , "Legacy conversation file deleted: %b" , deleted ) ; } } return false ; } | Attempts to migrate from the legacy clear text format . | 257 | 10 |
13,555 | public void scrollToChild ( View child ) { child . getDrawingRect ( mTempRect ) ; /* Offset from child's local coordinates to ScrollView coordinates */ offsetDescendantRectToMyCoords ( child , mTempRect ) ; int scrollDelta = computeScrollDeltaToGetChildRectOnScreen ( mTempRect ) ; if ( scrollDelta != 0 ) { scrollBy ( 0 , scrollDelta ) ; } } | Scrolls the view to the given child . | 89 | 9 |
13,556 | public boolean isValid ( boolean questionIsRequired ) { // If required and checked, other types must have text if ( questionIsRequired && isChecked ( ) && isOtherType && ( getOtherText ( ) . length ( ) < 1 ) ) { otherTextInputLayout . setError ( " " ) ; return false ; } otherTextInputLayout . setError ( null ) ; return true ; } | An answer can only be invalid if it s checked the question is required and the type is other but nothing was typed . All answers must be valid to submit in addition to whatever logic the question applies . | 84 | 40 |
13,557 | void fetchAndStoreMessages ( final boolean isMessageCenterForeground , final boolean showToast , @ Nullable final MessageFetchListener listener ) { checkConversationQueue ( ) ; try { String lastMessageId = messageStore . getLastReceivedMessageId ( ) ; fetchMessages ( lastMessageId , new MessageFetchListener ( ) { @ Override public void onFetchFinish ( MessageManager messageManager , List < ApptentiveMessage > messages ) { try { if ( messages == null || messages . size ( ) == 0 ) return ; CompoundMessage messageOnToast = null ; ApptentiveLog . d ( MESSAGES , "Messages retrieved: %d" , messages . size ( ) ) ; // Also get the count of incoming unread messages. int incomingUnreadMessages = 0 ; // Mark messages from server where sender is the app user as read. for ( final ApptentiveMessage apptentiveMessage : messages ) { if ( apptentiveMessage . isOutgoingMessage ( ) ) { apptentiveMessage . setRead ( true ) ; } else { if ( messageOnToast == null ) { if ( apptentiveMessage . getMessageType ( ) == ApptentiveMessage . Type . CompoundMessage ) { messageOnToast = ( CompoundMessage ) apptentiveMessage ; } } incomingUnreadMessages ++ ; // for every new message received, notify Message Center notifyInternalNewMessagesListeners ( ( CompoundMessage ) apptentiveMessage ) ; } } messageStore . addOrUpdateMessages ( messages . toArray ( new ApptentiveMessage [ messages . size ( ) ] ) ) ; if ( incomingUnreadMessages > 0 ) { // Show toast notification only if the foreground activity is not already message center activity if ( ! isMessageCenterForeground && showToast ) { DispatchQueue . mainQueue ( ) . dispatchAsyncOnce ( toastMessageNotifierTask . setMessage ( messageOnToast ) ) ; } } // Send message to notify host app, such as unread message badge conversationQueue ( ) . dispatchAsyncOnce ( hostMessageNotifierTask . setMessageCount ( getUnreadMessageCount ( ) ) ) ; } finally { if ( listener != null ) { listener . onFetchFinish ( messageManager , messages ) ; } } } } ) ; } catch ( Exception e ) { ApptentiveLog . e ( MESSAGES , "Error retrieving last received message id from worker thread" ) ; logException ( e ) ; } } | Performs a request against the server to check for messages in the conversation since the latest message we already have . This method will either be run on MessagePollingThread or as an asyncTask when Push is received . | 547 | 43 |
13,558 | @ Override public void onReceiveNotification ( ApptentiveNotification notification ) { checkConversationQueue ( ) ; if ( notification . hasName ( NOTIFICATION_ACTIVITY_STARTED ) || notification . hasName ( NOTIFICATION_ACTIVITY_RESUMED ) ) { final Activity activity = notification . getRequiredUserInfo ( NOTIFICATION_KEY_ACTIVITY , Activity . class ) ; setCurrentForegroundActivity ( activity ) ; } else if ( notification . hasName ( NOTIFICATION_APP_ENTERED_FOREGROUND ) ) { appWentToForeground ( ) ; } else if ( notification . hasName ( NOTIFICATION_APP_ENTERED_BACKGROUND ) ) { setCurrentForegroundActivity ( null ) ; appWentToBackground ( ) ; } else if ( notification . hasName ( NOTIFICATION_PAYLOAD_WILL_START_SEND ) ) { final PayloadData payload = notification . getRequiredUserInfo ( NOTIFICATION_KEY_PAYLOAD , PayloadData . class ) ; if ( payload . getType ( ) . equals ( PayloadType . message ) ) { resumeSending ( ) ; } } else if ( notification . hasName ( NOTIFICATION_PAYLOAD_DID_FINISH_SEND ) ) { final boolean successful = notification . getRequiredUserInfo ( NOTIFICATION_KEY_SUCCESSFUL , Boolean . class ) ; final PayloadData payload = notification . getRequiredUserInfo ( NOTIFICATION_KEY_PAYLOAD , PayloadData . class ) ; final Integer responseCode = notification . getRequiredUserInfo ( NOTIFICATION_KEY_RESPONSE_CODE , Integer . class ) ; final JSONObject responseData = successful ? notification . getRequiredUserInfo ( NOTIFICATION_KEY_RESPONSE_DATA , JSONObject . class ) : null ; if ( responseCode == - 1 ) { pauseSending ( SEND_PAUSE_REASON_NETWORK ) ; } if ( payload . getType ( ) . equals ( PayloadType . message ) ) { onSentMessage ( payload . getNonce ( ) , responseCode , responseData ) ; } } } | region Notification Observer | 480 | 3 |
13,559 | public static Object parseValue ( Object value ) { if ( value == null ) { return null ; } if ( value instanceof Double ) { return new BigDecimal ( ( Double ) value ) ; } else if ( value instanceof Long ) { return new BigDecimal ( ( Long ) value ) ; } else if ( value instanceof Integer ) { return new BigDecimal ( ( Integer ) value ) ; } else if ( value instanceof Float ) { return new BigDecimal ( ( Float ) value ) ; } else if ( value instanceof Short ) { return new BigDecimal ( ( Short ) value ) ; } else if ( value instanceof String ) { return ( ( String ) value ) . trim ( ) ; } else if ( value instanceof Apptentive . Version ) { return value ; } else if ( value instanceof Apptentive . DateTime ) { return value ; } else if ( value instanceof JSONObject ) { JSONObject jsonObject = ( JSONObject ) value ; String typeName = jsonObject . optString ( KEY_COMPLEX_TYPE ) ; if ( typeName != null ) { try { if ( Apptentive . Version . TYPE . equals ( typeName ) ) { return new Apptentive . Version ( jsonObject ) ; } else if ( Apptentive . DateTime . TYPE . equals ( typeName ) ) { return new Apptentive . DateTime ( jsonObject ) ; } else { throw new RuntimeException ( String . format ( "Error parsing complex parameter with unrecognized name: \"%s\"" , typeName ) ) ; } } catch ( JSONException e ) { throw new RuntimeException ( String . format ( "Error parsing complex parameter: %s" , Util . classToString ( value ) ) , e ) ; } } else { throw new RuntimeException ( String . format ( "Error: Complex type parameter missing \"%s\"." , KEY_COMPLEX_TYPE ) ) ; } } // All other values, such as Boolean and String should be returned unaltered. return value ; } | Constructs complex types values from the JSONObjects that represent them . Turns all Numbers into BigDecimal for easier comparison . All fields and parameters must be run through this method . | 437 | 36 |
13,560 | private void invalidateCaches ( Conversation conversation ) { checkConversationQueue ( ) ; conversation . setInteractionExpiration ( 0L ) ; Configuration config = Configuration . load ( ) ; config . setConfigurationCacheExpirationMillis ( System . currentTimeMillis ( ) ) ; config . save ( ) ; } | We want to make sure the app is using the latest configuration from the server if the app or sdk version changes . | 67 | 24 |
13,561 | public static void dismissAllInteractions ( ) { if ( ! isConversationQueue ( ) ) { dispatchOnConversationQueue ( new DispatchTask ( ) { @ Override protected void execute ( ) { dismissAllInteractions ( ) ; } } ) ; return ; } ApptentiveNotificationCenter . defaultCenter ( ) . postNotification ( NOTIFICATION_INTERACTIONS_SHOULD_DISMISS ) ; } | Dismisses any currently - visible interactions . This method is for internal use and is subject to change . | 92 | 22 |
13,562 | private void storeManifestResponse ( Context context , String manifest ) { try { File file = new File ( ApptentiveLog . getLogsDirectory ( context ) , Constants . FILE_APPTENTIVE_ENGAGEMENT_MANIFEST ) ; Util . writeText ( file , manifest ) ; } catch ( Exception e ) { ApptentiveLog . e ( CONVERSATION , e , "Exception while trying to save engagement manifest data" ) ; logException ( e ) ; } } | region Engagement Manifest Data | 107 | 5 |
13,563 | private void updateConversationAdvertiserIdentifier ( Conversation conversation ) { checkConversationQueue ( ) ; try { Configuration config = Configuration . load ( ) ; if ( config . isCollectingAdID ( ) ) { AdvertisingIdClientInfo info = AdvertiserManager . getAdvertisingIdClientInfo ( ) ; String advertiserId = info != null && ! info . isLimitAdTrackingEnabled ( ) ? info . getId ( ) : null ; conversation . getDevice ( ) . setAdvertiserId ( advertiserId ) ; } } catch ( Exception e ) { ApptentiveLog . e ( ADVERTISER_ID , e , "Exception while updating conversation advertiser id" ) ; logException ( e ) ; } } | region Advertiser Identifier | 159 | 6 |
13,564 | private static Serializable jsonObjectToSerializableType ( JSONObject input ) { String type = input . optString ( Apptentive . Version . KEY_TYPE , null ) ; try { if ( type != null ) { if ( type . equals ( Apptentive . Version . TYPE ) ) { return new Apptentive . Version ( input ) ; } else if ( type . equals ( Apptentive . DateTime . TYPE ) ) { return new Apptentive . DateTime ( input ) ; } } } catch ( JSONException e ) { ApptentiveLog . e ( CONVERSATION , e , "Error migrating JSONObject." ) ; logException ( e ) ; } return null ; } | Takes a legacy Apptentive Custom Data object base on JSON and returns the modern serializable version | 152 | 21 |
13,565 | private static String wrapSymmetricKey ( KeyPair wrapperKey , SecretKey symmetricKey ) throws NoSuchPaddingException , NoSuchAlgorithmException , InvalidKeyException , IllegalBlockSizeException { Cipher cipher = Cipher . getInstance ( WRAPPER_TRANSFORMATION ) ; cipher . init ( Cipher . WRAP_MODE , wrapperKey . getPublic ( ) ) ; byte [ ] decodedData = cipher . wrap ( symmetricKey ) ; return Base64 . encodeToString ( decodedData , Base64 . DEFAULT ) ; } | region Key Wrapping | 116 | 4 |
13,566 | private synchronized ApptentiveNotificationObserverList resolveObserverList ( String name ) { ApptentiveNotificationObserverList list = observerListLookup . get ( name ) ; if ( list == null ) { list = new ApptentiveNotificationObserverList ( ) ; observerListLookup . put ( name , list ) ; } return list ; } | Find an observer list for the specified name or creates a new one if not found . | 80 | 17 |
13,567 | public static String getErrorResponse ( HttpURLConnection connection , boolean isZipped ) throws IOException { if ( connection != null ) { InputStream is = null ; try { is = connection . getErrorStream ( ) ; if ( is != null ) { if ( isZipped ) { is = new GZIPInputStream ( is ) ; } } return Util . readStringFromInputStream ( is , "UTF-8" ) ; } finally { Util . ensureClosed ( is ) ; } } return null ; } | Reads error response and returns it as a string . Handles gzipped streams . | 113 | 18 |
13,568 | public static void writeToEncryptedFile ( EncryptionKey encryptionKey , File file , byte [ ] data ) throws IOException , NoSuchPaddingException , InvalidAlgorithmParameterException , NoSuchAlgorithmException , IllegalBlockSizeException , BadPaddingException , InvalidKeyException , EncryptionException { AtomicFile atomicFile = new AtomicFile ( file ) ; FileOutputStream stream = null ; boolean successful = false ; try { stream = atomicFile . startWrite ( ) ; stream . write ( encrypt ( encryptionKey , data ) ) ; atomicFile . finishWrite ( stream ) ; successful = true ; } finally { if ( ! successful ) { atomicFile . failWrite ( stream ) ; } } } | region File IO | 146 | 3 |
13,569 | @ Override public void onFinishSending ( PayloadSender sender , PayloadData payload , boolean cancelled , String errorMessage , int responseCode , JSONObject responseData ) { ApptentiveNotificationCenter . defaultCenter ( ) . postNotification ( NOTIFICATION_PAYLOAD_DID_FINISH_SEND , NOTIFICATION_KEY_PAYLOAD , payload , NOTIFICATION_KEY_SUCCESSFUL , errorMessage == null && ! cancelled ? TRUE : FALSE , NOTIFICATION_KEY_RESPONSE_CODE , responseCode , NOTIFICATION_KEY_RESPONSE_DATA , responseData ) ; if ( cancelled ) { ApptentiveLog . v ( PAYLOADS , "Payload sending was cancelled: %s" , payload ) ; return ; // don't remove cancelled payloads from the queue } if ( errorMessage != null ) { ApptentiveLog . e ( PAYLOADS , "Payload sending failed: %s\n%s" , payload , errorMessage ) ; if ( appInBackground ) { ApptentiveLog . v ( PAYLOADS , "The app went to the background so we won't remove the payload from the queue" ) ; retrySending ( 5000 ) ; return ; } else if ( responseCode == - 1 ) { ApptentiveLog . v ( PAYLOADS , "Payload failed to send due to a connection error." ) ; retrySending ( 5000 ) ; return ; } else if ( responseCode >= 500 ) { ApptentiveLog . v ( PAYLOADS , "Payload failed to send due to a server error." ) ; retrySending ( 5000 ) ; return ; } } else { ApptentiveLog . v ( PAYLOADS , "Payload was successfully sent: %s" , payload ) ; } // Only let the payload be deleted if it was successfully sent, or got an unrecoverable client error. deletePayload ( payload . getNonce ( ) ) ; } | region PayloadSender . Listener | 434 | 8 |
13,570 | private void sendNextPayload ( ) { singleThreadExecutor . execute ( new Runnable ( ) { @ Override public void run ( ) { try { sendNextPayloadSync ( ) ; } catch ( Exception e ) { ApptentiveLog . e ( e , "Exception while trying to send next payload" ) ; logException ( e ) ; } } } ) ; } | region Payload Sending | 82 | 4 |
13,571 | @ Override public void onCreate ( SQLiteDatabase db ) { ApptentiveLog . d ( DATABASE , "ApptentiveDatabase.onCreate(db)" ) ; db . execSQL ( SQL_CREATE_PAYLOAD_TABLE ) ; // Leave legacy tables in place for now. db . execSQL ( TABLE_CREATE_MESSAGE ) ; db . execSQL ( TABLE_CREATE_FILESTORE ) ; db . execSQL ( TABLE_CREATE_COMPOUND_FILESTORE ) ; } | This function is called only for new installs and onUpgrade is not called in that case . Therefore you must include the latest complete set of DDL here . | 118 | 31 |
13,572 | @ Override public void onUpgrade ( SQLiteDatabase db , int oldVersion , int newVersion ) { ApptentiveLog . d ( DATABASE , "Upgrade database from %d to %d" , oldVersion , newVersion ) ; try { DatabaseMigrator migrator = createDatabaseMigrator ( oldVersion , newVersion ) ; if ( migrator != null ) { migrator . onUpgrade ( db , oldVersion , newVersion ) ; } } catch ( Exception e ) { ApptentiveLog . e ( DATABASE , e , "Exception while trying to migrate database from %d to %d" , oldVersion , newVersion ) ; logException ( e ) ; // if migration failed - create new table db . execSQL ( SQL_DELETE_PAYLOAD_TABLE ) ; onCreate ( db ) ; } } | This method is called when an app is upgraded . Add alter table statements here for each version in a non - breaking switch so that all the necessary upgrades occur for each older version . | 183 | 36 |
13,573 | void notifyObservers ( ApptentiveNotification notification ) { boolean hasLostReferences = false ; // create a temporary list of observers to avoid concurrent modification errors List < ApptentiveNotificationObserver > temp = new ArrayList <> ( observers . size ( ) ) ; for ( int i = 0 ; i < observers . size ( ) ; ++ i ) { ApptentiveNotificationObserver observer = observers . get ( i ) ; ObserverWeakReference observerRef = ObjectUtils . as ( observer , ObserverWeakReference . class ) ; if ( observerRef == null || ! observerRef . isReferenceLost ( ) ) { temp . add ( observer ) ; } else { hasLostReferences = true ; } } // notify observers for ( int i = 0 ; i < temp . size ( ) ; ++ i ) { try { temp . get ( i ) . onReceiveNotification ( notification ) ; } catch ( Exception e ) { ApptentiveLog . e ( e , "Exception while posting notification: %s" , notification ) ; logException ( e ) ; // TODO: add more context info } } // clean lost references if ( hasLostReferences ) { for ( int i = observers . size ( ) - 1 ; i >= 0 ; -- i ) { final ObserverWeakReference observerRef = ObjectUtils . as ( observers . get ( i ) , ObserverWeakReference . class ) ; if ( observerRef != null && observerRef . isReferenceLost ( ) ) { observers . remove ( i ) ; } } } } | Posts notification to all observers . | 326 | 6 |
13,574 | boolean addObserver ( ApptentiveNotificationObserver observer , boolean useWeakReference ) { if ( observer == null ) { throw new IllegalArgumentException ( "Observer is null" ) ; } if ( ! contains ( observer ) ) { observers . add ( useWeakReference ? new ObserverWeakReference ( observer ) : observer ) ; return true ; } return false ; } | Adds an observer to the list without duplicates . | 81 | 10 |
13,575 | boolean removeObserver ( ApptentiveNotificationObserver observer ) { int index = indexOf ( observer ) ; if ( index != - 1 ) { observers . remove ( index ) ; return true ; } return false ; } | Removes observer os its weak reference from the list | 49 | 10 |
13,576 | private int indexOf ( ApptentiveNotificationObserver observer ) { for ( int i = 0 ; i < observers . size ( ) ; ++ i ) { final ApptentiveNotificationObserver other = observers . get ( i ) ; if ( other == observer ) { return i ; } final ObserverWeakReference otherReference = ObjectUtils . as ( other , ObserverWeakReference . class ) ; if ( otherReference != null && otherReference . get ( ) == observer ) { return i ; } } return - 1 ; } | Returns an index of the observer or its weak reference . | 113 | 11 |
13,577 | void dispatchSync ( DispatchQueue networkQueue ) { long requestStartTime = System . currentTimeMillis ( ) ; try { sendRequestSync ( ) ; } catch ( NetworkUnavailableException e ) { responseCode = - 1 ; // indicates failure errorMessage = e . getMessage ( ) ; ApptentiveLog . w ( NETWORK , e . getMessage ( ) ) ; ApptentiveLog . w ( NETWORK , "Cancelled? %b" , isCancelled ( ) ) ; } catch ( Exception e ) { responseCode = - 1 ; // indicates failure errorMessage = e . getMessage ( ) ; ApptentiveLog . e ( NETWORK , "Cancelled? %b" , isCancelled ( ) ) ; if ( ! isCancelled ( ) ) { ApptentiveLog . e ( NETWORK , "Unable to perform request: %s" , this ) ; } // TODO: send error metrics with the details of the request } ApptentiveLog . d ( NETWORK , "Request finished in %d ms" , System . currentTimeMillis ( ) - requestStartTime ) ; // attempt a retry if request failed if ( isFailed ( ) && retryRequest ( networkQueue , responseCode ) ) { // we schedule request retry on the same queue as it was originally dispatched return ; } // use custom callback queue (if any) if ( callbackQueue != null ) { callbackQueue . dispatchAsync ( new DispatchTask ( ) { @ Override protected void execute ( ) { finishRequest ( ) ; } } ) ; } else { finishRequest ( ) ; // we don't care where the callback is dispatched until it's on a background queue } } | Send request synchronously on a background network queue | 362 | 9 |
13,578 | public void setRequestProperty ( String key , Object value ) { if ( value != null ) { if ( requestProperties == null ) { requestProperties = new HashMap <> ( ) ; } requestProperties . put ( key , value ) ; } } | Sets HTTP request property | 55 | 5 |
13,579 | 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 | 66 | 9 |
13,580 | 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 | 109 | 10 |
13,581 | public static boolean createScaledDownImageCacheFile ( String sourcePath , String cachedFileName ) { File localFile = new File ( cachedFileName ) ; // Retrieve image orientation int imageOrientation = 0 ; try { ExifInterface exif = new ExifInterface ( sourcePath ) ; imageOrientation = exif . getAttributeInt ( ExifInterface . TAG_ORIENTATION , ExifInterface . ORIENTATION_NORMAL ) ; } catch ( IOException e ) { } // Copy the file contents over. 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 ) ; // TODO: Is JPEG what we want here? 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 . | 387 | 42 |
13,582 | 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 ; // no changes } ApptentiveLog . v ( ADVERTISER_ID , "Advertiser ID client info changed: %s" , clientInfo ) ; cachedClientInfo = clientInfo ; notifyClientInfoChanged ( cachedClientInfo ) ; return true ; } | Returns true if changed | 134 | 4 |
13,583 | synchronized boolean sendPayload ( final PayloadData payload ) { if ( payload == null ) { throw new IllegalArgumentException ( "Payload is null" ) ; } // we don't allow concurrent payload sending if ( isSendingPayload ( ) ) { return false ; } // we mark the sender as "busy" so no other payloads would be sent until we're done sendingFlag = true ; try { sendPayloadRequest ( payload ) ; } catch ( Exception e ) { ApptentiveLog . e ( e , "Exception while sending payload: %s" , payload ) ; logException ( e ) ; // for NullPointerException, the message object would be null, we should handle it separately // TODO: add a helper class for handling that String message = e . getMessage ( ) ; if ( message == null ) { message = StringUtils . format ( "%s is thrown" , e . getClass ( ) . getSimpleName ( ) ) ; } // if an exception was thrown - mark payload as failed handleFinishSendingPayload ( payload , false , message , - 1 , null ) ; // TODO: a better approach } return true ; } | Sends payload asynchronously . Returns boolean flag immediately indicating if payload send was scheduled | 252 | 17 |
13,584 | private synchronized void handleFinishSendingPayload ( PayloadData payload , boolean cancelled , String errorMessage , int responseCode , JSONObject responseData ) { sendingFlag = false ; // mark sender as 'not busy' 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 | 113 | 10 |
13,585 | 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 . | 48 | 18 |
13,586 | public void displayNewIncomingMessageItem ( ApptentiveMessage message ) { messagingActionHandler . sendEmptyMessage ( MSG_REMOVE_STATUS ) ; // Determine where to insert the new incoming message. It will be in front of any eidting // area, i.e. composing, Who Card ... int insertIndex = listItems . size ( ) ; // If inserted onto the end, then the list will have grown by one. outside_loop : // Starting at end of list, go back up the list to find the proper place to insert the incoming message. 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 : // Any other type means we are past the temporary items. 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 ( ) ; // Restore the position of listview to composing view messagingActionHandler . sendMessage ( messagingActionHandler . obtainMessage ( MSG_SCROLL_FROM_TOP , insertIndex , top ) ) ; } else { updateMessageSentStates ( ) ; } } | Call only from handler . | 422 | 5 |
13,587 | public void clearImageAttachmentBand ( ) { attachments . setVisibility ( View . GONE ) ; images . clear ( ) ; attachments . setData ( null ) ; } | Remove all images from attachment band . | 37 | 7 |
13,588 | 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 . | 97 | 7 |
13,589 | public void removeImageFromImageAttachmentBand ( final int position ) { images . remove ( position ) ; attachments . setupLayoutListener ( ) ; setAttachButtonState ( ) ; if ( images . size ( ) == 0 ) { // Hide attachment band after last attachment is removed attachments . setVisibility ( View . GONE ) ; return ; } addAdditionalAttachItem ( ) ; } | Remove an image from attachment band . | 80 | 7 |
13,590 | @ Override 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 | 86 | 11 |
13,591 | @ Override 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 ; | 117 | 31 |
13,592 | @ Override public Serializable put ( String key , Serializable value ) { Serializable ret = super . put ( key , value ) ; notifyDataChanged ( ) ; return ret ; } | region Saving when modified | 39 | 4 |
13,593 | public static synchronized Apptentive . DateTime getTimeAtInstall ( Selector selector ) { ensureLoaded ( ) ; for ( VersionHistoryEntry entry : versionHistoryEntries ) { switch ( selector ) { case total : // Since the list is ordered, this will be the first and oldest entry. 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 . | 303 | 33 |
13,594 | 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 . | 117 | 32 |
13,595 | 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 . | 54 | 11 |
13,596 | public static void addCustomDeviceData ( final String key , final String value ) { dispatchConversationTask ( new ConversationDispatchTask ( ) { @ Override 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 . | 79 | 42 |
13,597 | public static void removeCustomDeviceData ( final String key ) { dispatchConversationTask ( new ConversationDispatchTask ( ) { @ Override 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 . | 70 | 20 |
13,598 | public static void addCustomPersonData ( final String key , final String value ) { dispatchConversationTask ( new ConversationDispatchTask ( ) { @ Override 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 . | 79 | 42 |
13,599 | public static void removeCustomPersonData ( final String key ) { dispatchConversationTask ( new ConversationDispatchTask ( ) { @ Override 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 . | 70 | 20 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.