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...
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 , C...
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 ...
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 = ensureJsonHe...
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 ) . get...
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...
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 ( ...
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 ( Clie...
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 ( ) ; requ...
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 = ensurePostCreat...
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 ( ) ; requestB...
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 ) ) . acc...
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 , ...
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 , paramete...
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 , pa...
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...
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 . ri...
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 ...
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 ac...
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 . ha...
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 ( ite...
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 < interactionsJSONAr...
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...
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 = ge...
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 ...
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 . getA...
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 / imag...
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 ( countF...
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...
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 ( DataI...
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...
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 da...
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...
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...
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 ( ) { @ Ove...
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_KE...
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 ( ( Inte...
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_...
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 wh...
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 !...
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 ( Apptenti...
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 . getPubli...
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 . readStringFromInputStr...
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 atomi...
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 ,...
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_...
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 (...
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 ...
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 ; }...
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 , ObserverWeakReferen...
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 ( ) ) ; Apptentiv...
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_...
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 ( ExifInter...
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 ) ) {...
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'r...
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 ...
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 inser...
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 ( ) ; a...
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 ; } addA...
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 ...
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 . ge...
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 : un...
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...
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...
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