idx int64 0 165k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
13,500 | public Integer getColWidth ( ) { final Object result = getStateHelper ( ) . eval ( PropertyKeys . colWidth , null ) ; if ( result == null ) { return null ; } return Integer . valueOf ( result . toString ( ) ) ; } | The column width |
13,501 | public Collection < SelectItem > getFilterOptions ( ) { return ( Collection < SelectItem > ) getStateHelper ( ) . eval ( PropertyKeys . filterOptions , null ) ; } | The filterOptions expression |
13,502 | public Sheet getSheet ( ) { if ( sheet != null ) { return sheet ; } UIComponent parent = getParent ( ) ; while ( parent != null && ! ( parent instanceof Sheet ) ) { parent = parent . getParent ( ) ; } return ( Sheet ) parent ; } | Get the parent sheet |
13,503 | protected boolean validateRequired ( final FacesContext context , final Object newValue ) { if ( isValid ( ) && isRequired ( ) && isEmpty ( newValue ) ) { final String requiredMessageStr = getRequiredMessage ( ) ; FacesMessage message ; if ( null != requiredMessageStr ) { message = new FacesMessage ( FacesMessage . SEVERITY_ERROR , requiredMessageStr , requiredMessageStr ) ; } else { message = new FacesMessage ( FacesMessage . SEVERITY_ERROR , MESSAGE_REQUIRED , MESSAGE_REQUIRED ) ; } context . addMessage ( getClientId ( context ) , message ) ; final Sheet sheet = getSheet ( ) ; if ( sheet != null ) { sheet . getInvalidUpdates ( ) . add ( new SheetInvalidUpdate ( sheet . getRowKeyValue ( context ) , sheet . getColumns ( ) . indexOf ( this ) , this , newValue , message . getDetail ( ) ) ) ; } setValid ( false ) ; return false ; } return true ; } | Validates the value against the required flags on this column . |
13,504 | private void requestCameraPermission ( ) { Log . w ( "BARCODE-SCANNER" , "Camera permission is not granted. Requesting permission" ) ; final String [ ] permissions = new String [ ] { Manifest . permission . CAMERA } ; if ( ! shouldShowRequestPermissionRationale ( Manifest . permission . CAMERA ) ) { requestPermissions ( permissions , RC_HANDLE_CAMERA_PERM ) ; return ; } Snackbar . make ( mGraphicOverlay , R . string . permission_camera_rationale , Snackbar . LENGTH_INDEFINITE ) . setAction ( R . string . ok , new View . OnClickListener ( ) { public void onClick ( View view ) { requestPermissions ( permissions , RC_HANDLE_CAMERA_PERM ) ; } } ) . show ( ) ; } | Handles the requesting of the camera permission . This includes showing a Snackbar message of why the permission is needed then sending the request . |
13,505 | public boolean onTouch ( View v , MotionEvent event ) { boolean b = scaleGestureDetector . onTouchEvent ( event ) ; boolean c = gestureDetector . onTouchEvent ( event ) ; return b || c || v . onTouchEvent ( event ) ; } | Called when a touch event is dispatched to a view . This allows listeners to get a chance to respond before the target view . |
13,506 | protected boolean onTap ( float rawX , float rawY ) { Log . d ( "CAPTURE-FRAGMENT" , "got tap at: (" + rawX + ", " + rawY + ")" ) ; Barcode barcode = null ; if ( mMode == MVBarcodeScanner . ScanningMode . SINGLE_AUTO ) { BarcodeGraphic graphic = mGraphicOverlay . getFirstGraphic ( ) ; if ( graphic != null ) { barcode = graphic . getBarcode ( ) ; if ( barcode != null && mListener != null ) { mListener . onBarcodeScanned ( barcode ) ; } } } else if ( mMode == MVBarcodeScanner . ScanningMode . SINGLE_MANUAL ) { Set < BarcodeGraphic > graphicSet = mGraphicOverlay . getAllGraphics ( ) ; if ( graphicSet != null && ! graphicSet . isEmpty ( ) ) { for ( BarcodeGraphic graphic : graphicSet ) { if ( graphic != null && graphic . isPointInsideBarcode ( rawX , rawY ) ) { Log . d ( "CAPTURE-FRAGMENT" , "got tap inside barcode" ) ; barcode = graphic . getBarcode ( ) ; break ; } } if ( mListener != null && barcode != null ) { mListener . onBarcodeScanned ( barcode ) ; } } } else { Set < BarcodeGraphic > graphicSet = mGraphicOverlay . getAllGraphics ( ) ; if ( graphicSet != null && ! graphicSet . isEmpty ( ) ) { List < Barcode > barcodes = new ArrayList < > ( ) ; for ( BarcodeGraphic graphic : graphicSet ) { if ( graphic != null && graphic . getBarcode ( ) != null ) { barcode = graphic . getBarcode ( ) ; barcodes . add ( barcode ) ; } } if ( mListener != null && ! barcodes . isEmpty ( ) ) { mListener . onBarcodesScanned ( barcodes ) ; } } } return barcode != null ; } | onTap is called to capture the oldest barcode currently detected and return it to the caller . |
13,507 | public void onNewItem ( int id , Barcode item ) { mGraphic . setId ( id ) ; if ( mListener != null ) mListener . onNewBarcodeDetected ( id , item ) ; } | Start tracking the detected item instance within the item overlay . |
13,508 | public void draw ( Canvas canvas ) { Barcode barcode = mBarcode ; if ( barcode == null ) { return ; } RectF rect = getViewBoundingBox ( barcode ) ; canvas . drawRect ( rect , mOverlayPaint ) ; canvas . drawLine ( rect . left , rect . top , rect . left + CORNER_WIDTH , rect . top , mRectPaint ) ; canvas . drawLine ( rect . left , rect . top , rect . left , rect . top + CORNER_WIDTH , mRectPaint ) ; canvas . drawLine ( rect . left , rect . bottom , rect . left , rect . bottom - CORNER_WIDTH , mRectPaint ) ; canvas . drawLine ( rect . left , rect . bottom , rect . left + CORNER_WIDTH , rect . bottom , mRectPaint ) ; canvas . drawLine ( rect . right , rect . top , rect . right - CORNER_WIDTH , rect . top , mRectPaint ) ; canvas . drawLine ( rect . right , rect . top , rect . right , rect . top + CORNER_WIDTH , mRectPaint ) ; canvas . drawLine ( rect . right , rect . bottom , rect . right - CORNER_WIDTH , rect . bottom , mRectPaint ) ; canvas . drawLine ( rect . right , rect . bottom , rect . right , rect . bottom - CORNER_WIDTH , mRectPaint ) ; } | Draws the barcode annotations for position size and raw value on the supplied canvas . |
13,509 | protected int addClasspathElements ( Collection < ? > elements , URL [ ] urls , int startPosition ) throws MojoExecutionException { for ( Object object : elements ) { try { if ( object instanceof Artifact ) { urls [ startPosition ] = ( ( Artifact ) object ) . getFile ( ) . toURI ( ) . toURL ( ) ; } else if ( object instanceof Resource ) { urls [ startPosition ] = new File ( ( ( Resource ) object ) . getDirectory ( ) ) . toURI ( ) . toURL ( ) ; } else { urls [ startPosition ] = new File ( ( String ) object ) . toURI ( ) . toURL ( ) ; } } catch ( MalformedURLException e ) { throw new MojoExecutionException ( "Failed to convert original classpath element " + object + " to URL." , e ) ; } startPosition ++ ; } return startPosition ; } | Add classpath elements to a classpath URL set |
13,510 | public Collection < File > getClasspath ( String scope ) throws MojoExecutionException { try { Collection < File > files = classpathBuilder . buildClasspathList ( getProject ( ) , scope , getProjectArtifacts ( ) , isGenerator ( ) ) ; if ( getLog ( ) . isDebugEnabled ( ) ) { getLog ( ) . debug ( "GWT SDK execution classpath :" ) ; for ( File f : files ) { getLog ( ) . debug ( " " + f . getAbsolutePath ( ) ) ; } } return files ; } catch ( ClasspathBuilderException e ) { throw new MojoExecutionException ( e . getMessage ( ) , e ) ; } } | Build the GWT classpath for the specified scope |
13,511 | private void checkGwtUserVersion ( ) throws MojoExecutionException { InputStream inputStream = Thread . currentThread ( ) . getContextClassLoader ( ) . getResourceAsStream ( "org/codehaus/mojo/gwt/mojoGwtVersion.properties" ) ; Properties properties = new Properties ( ) ; try { properties . load ( inputStream ) ; } catch ( IOException e ) { throw new MojoExecutionException ( "Failed to load plugin properties" , e ) ; } finally { IOUtils . closeQuietly ( inputStream ) ; } Artifact gwtUser = project . getArtifactMap ( ) . get ( GWT_USER ) ; if ( gwtUser != null ) { String mojoGwtVersion = properties . getProperty ( "gwt.version" ) ; ArtifactVersion mojoGwtArtifactVersion = new DefaultArtifactVersion ( mojoGwtVersion ) ; ArtifactVersion userGwtArtifactVersion = new DefaultArtifactVersion ( gwtUser . getVersion ( ) ) ; if ( userGwtArtifactVersion . compareTo ( mojoGwtArtifactVersion ) < 0 ) { getLog ( ) . warn ( "Your project declares dependency on gwt-user " + gwtUser . getVersion ( ) + ". This plugin is designed for at least gwt version " + mojoGwtVersion ) ; } } } | Check gwt - user dependency matches plugin version |
13,512 | public String getProjectName ( MavenProject project ) { File dotProject = new File ( project . getBasedir ( ) , ".project" ) ; try { Xpp3Dom dom = Xpp3DomBuilder . build ( ReaderFactory . newXmlReader ( dotProject ) ) ; return dom . getChild ( "name" ) . getValue ( ) ; } catch ( Exception e ) { getLogger ( ) . warn ( "Failed to read the .project file" ) ; return project . getArtifactId ( ) ; } } | Read the Eclipse project name for . project file . Fall back to artifactId on error |
13,513 | private List < Artifact > getScopeArtifacts ( final MavenProject project , final String scope ) { if ( SCOPE_COMPILE . equals ( scope ) ) { return project . getCompileArtifacts ( ) ; } if ( SCOPE_RUNTIME . equals ( scope ) ) { return project . getRuntimeArtifacts ( ) ; } else if ( SCOPE_TEST . equals ( scope ) ) { return project . getTestArtifacts ( ) ; } else { throw new RuntimeException ( "Not allowed scope " + scope ) ; } } | Get artifacts for specific scope . |
13,514 | private List < String > getSourceRoots ( final MavenProject project , final String scope ) { if ( SCOPE_COMPILE . equals ( scope ) || SCOPE_RUNTIME . equals ( scope ) ) { return project . getCompileSourceRoots ( ) ; } else if ( SCOPE_TEST . equals ( scope ) ) { List < String > sourceRoots = new ArrayList < String > ( ) ; sourceRoots . addAll ( project . getTestCompileSourceRoots ( ) ) ; sourceRoots . addAll ( project . getCompileSourceRoots ( ) ) ; return sourceRoots ; } else { throw new RuntimeException ( "Not allowed scope " + scope ) ; } } | Get source roots for specific scope . |
13,515 | private List < Resource > getResources ( final MavenProject project , final String scope ) { if ( SCOPE_COMPILE . equals ( scope ) || SCOPE_RUNTIME . equals ( scope ) ) { return project . getResources ( ) ; } else if ( SCOPE_TEST . equals ( scope ) ) { List < Resource > resources = new ArrayList < Resource > ( ) ; resources . addAll ( project . getTestResources ( ) ) ; resources . addAll ( project . getResources ( ) ) ; return resources ; } else { throw new RuntimeException ( "Not allowed scope " + scope ) ; } } | Get resources for specific scope . |
13,516 | private String getProjectReferenceId ( final String groupId , final String artifactId , final String version ) { return groupId + ":" + artifactId + ":" + version ; } | Cut from MavenProject . java |
13,517 | public String [ ] getModules ( ) { if ( module != null ) { return new String [ ] { module } ; } if ( modules == null ) { Set < String > mods = new HashSet < String > ( ) ; Collection < String > sourcePaths = getProject ( ) . getCompileSourceRoots ( ) ; for ( String sourcePath : sourcePaths ) { File sourceDirectory = new File ( sourcePath ) ; if ( sourceDirectory . exists ( ) ) { DirectoryScanner scanner = new DirectoryScanner ( ) ; scanner . setBasedir ( sourceDirectory . getAbsolutePath ( ) ) ; scanner . setIncludes ( new String [ ] { "**/*" + DefaultGwtModuleReader . GWT_MODULE_EXTENSION } ) ; scanner . scan ( ) ; mods . addAll ( Arrays . asList ( scanner . getIncludedFiles ( ) ) ) ; } } Collection < Resource > resources = getProject ( ) . getResources ( ) ; for ( Resource resource : resources ) { File resourceDirectoryFile = new File ( resource . getDirectory ( ) ) ; if ( ! resourceDirectoryFile . exists ( ) ) { continue ; } DirectoryScanner scanner = new DirectoryScanner ( ) ; scanner . setBasedir ( resource . getDirectory ( ) ) ; scanner . setIncludes ( new String [ ] { "**/*" + DefaultGwtModuleReader . GWT_MODULE_EXTENSION } ) ; scanner . scan ( ) ; mods . addAll ( Arrays . asList ( scanner . getIncludedFiles ( ) ) ) ; } if ( mods . isEmpty ( ) ) { getLog ( ) . warn ( "GWT plugin is configured to detect modules, but none were found." ) ; } modules = new String [ mods . size ( ) ] ; int i = 0 ; for ( String fileName : mods ) { String path = fileName . substring ( 0 , fileName . length ( ) - DefaultGwtModuleReader . GWT_MODULE_EXTENSION . length ( ) ) ; modules [ i ++ ] = path . replace ( File . separatorChar , '.' ) ; } if ( modules . length > 0 ) { getLog ( ) . info ( "auto discovered modules " + Arrays . asList ( modules ) ) ; } } return modules ; } | FIXME move to DefaultGwtModuleReader ! |
13,518 | private boolean isDeprecated ( JavaMethod method ) { if ( method == null ) return false ; for ( Annotation annotation : method . getAnnotations ( ) ) { if ( "java.lang.Deprecated" . equals ( annotation . getType ( ) . getFullyQualifiedName ( ) ) ) { return true ; } } return method . getTagByName ( "deprecated" ) != null ; } | Determine if a client service method is deprecated . |
13,519 | public Set < GwtModule > getInherits ( ) throws GwtModuleReaderException { if ( inherits != null ) { return inherits ; } inherits = new HashSet < GwtModule > ( ) ; addInheritedModules ( inherits , getLocalInherits ( ) ) ; return inherits ; } | Build the set of inhertied modules . Due to xml inheritence mecanism there may be cicles in the inheritence graph so we build a set of inherited modules |
13,520 | protected Collection < ResourceFile > getAllResourceFiles ( ) throws MojoExecutionException { try { Set < ResourceFile > sourcesAndResources = new HashSet < ResourceFile > ( ) ; Set < String > sourcesAndResourcesPath = new HashSet < String > ( ) ; sourcesAndResourcesPath . addAll ( getProject ( ) . getCompileSourceRoots ( ) ) ; for ( Resource resource : getProject ( ) . getResources ( ) ) { sourcesAndResourcesPath . add ( resource . getDirectory ( ) ) ; } for ( String name : getModules ( ) ) { GwtModule module = readModule ( name ) ; sourcesAndResources . add ( getDescriptor ( module , sourcesAndResourcesPath ) ) ; int count = 1 ; for ( String source : module . getSources ( ) ) { getLog ( ) . debug ( "GWT sources from " + name + '.' + source ) ; Collection < ResourceFile > files = getAsResources ( module , source , sourcesAndResourcesPath , "**/*.java" ) ; sourcesAndResources . addAll ( files ) ; count += files . size ( ) ; Collection < ResourceFile > uifiles = getAsResources ( module , source , sourcesAndResourcesPath , "**/*.ui.xml" ) ; sourcesAndResources . addAll ( uifiles ) ; count += uifiles . size ( ) ; } for ( String source : module . getSuperSources ( ) ) { getLog ( ) . debug ( "GWT super-sources from " + name + '.' + source ) ; Collection < ResourceFile > files = getAsResources ( module , source , sourcesAndResourcesPath , "**/*.java" ) ; sourcesAndResources . addAll ( files ) ; count += files . size ( ) ; Collection < ResourceFile > uifiles = getAsResources ( module , source , sourcesAndResourcesPath , "**/*.ui.xml" ) ; sourcesAndResources . addAll ( uifiles ) ; count += uifiles . size ( ) ; } getLog ( ) . info ( count + " source files from GWT module " + name ) ; } return sourcesAndResources ; } catch ( GwtModuleReaderException e ) { throw new MojoExecutionException ( e . getMessage ( ) , e ) ; } } | Collect GWT java source code and module descriptor to be added as resources . |
13,521 | private String escapeHtml ( String html ) { if ( html == null ) { return null ; } return html . replaceAll ( "&" , "&" ) . replaceAll ( "<" , "<" ) . replaceAll ( ">" , ">" ) ; } | Escape an html string . Escaping data received from the client helps to prevent cross - site script vulnerabilities . |
13,522 | public boolean parse ( String criteria , Map < String , ? extends Object > attributes ) throws CriteriaParseException { if ( criteria == null ) { return true ; } else { try { return Boolean . parseBoolean ( FREEMARKER_BUILTINS . eval ( criteria , attributes ) ) ; } catch ( TemplateException ex ) { throw new CriteriaParseException ( ex ) ; } } } | Parses the provided criteria expression which must have a boolean value . |
13,523 | 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 . |
13,524 | public void attributeReplaced ( HttpSessionBindingEvent hse ) { Object possibleClient = hse . getValue ( ) ; closeClient ( possibleClient ) ; } | Attempts to close the old client . |
13,525 | public void attributeRemoved ( HttpSessionBindingEvent hse ) { Object possibleClient = hse . getValue ( ) ; closeClient ( possibleClient ) ; } | Attempts to close the client . |
13,526 | 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 . |
13,527 | 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 . |
13,528 | 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 . |
13,529 | 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 . |
13,530 | 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 . |
13,531 | 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 . |
13,532 | 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 . |
13,533 | 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 . |
13,534 | 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 . |
13,535 | 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 . |
13,536 | 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 . |
13,537 | 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 . |
13,538 | 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 . |
13,539 | 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 . |
13,540 | 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 . |
13,541 | 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 . |
13,542 | 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 . |
13,543 | 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 . |
13,544 | 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 . |
13,545 | 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 . |
13,546 | 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 . |
13,547 | 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 . |
13,548 | 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 . |
13,549 | private static boolean contains ( Object [ ] arr , Object member ) { for ( Object mem : arr ) { if ( Objects . equals ( mem , member ) ) { return true ; } } return false ; } | Tests array membership . |
13,550 | 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 . |
13,551 | 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 ; } } 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 |
13,552 | 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 |
13,553 | private void checkMatrixBounds ( ) { RectF rect = getMatrixRectF ( ) ; float deltaX = 0 , deltaY = 0 ; final float viewWidth = getWidth ( ) ; final float viewHeight = getHeight ( ) ; 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 |
13,554 | private Conversation loadConversationFromMetadata ( ConversationMetadata metadata ) throws SerializerException , ConversationLoadException { ConversationMetadataItem item ; item = metadata . findItem ( LOGGED_IN ) ; if ( item != null ) { ApptentiveLog . i ( CONVERSATION , "Loading 'logged-in' conversation..." ) ; return loadConversation ( item ) ; } item = metadata . findItem ( ANONYMOUS ) ; if ( item != null ) { ApptentiveLog . i ( CONVERSATION , "Loading 'anonymous' conversation..." ) ; return loadConversation ( item ) ; } item = metadata . findItem ( ANONYMOUS_PENDING ) ; if ( item != null ) { ApptentiveLog . i ( CONVERSATION , "Loading 'anonymous pending' conversation..." ) ; final Conversation conversation = loadConversation ( item ) ; fetchConversationToken ( conversation ) ; return 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 ; } 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 |
13,555 | 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 ) { conversation . fetchInteractions ( getContext ( ) ) ; conversation . getMessageManager ( ) . attemptToStartMessagePolling ( ) ; } fetchAppConfiguration ( conversation ) ; 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 |
13,556 | public Apptentive . DateTime getTimeAtInstallTotal ( ) { 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 . |
13,557 | 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 . |
13,558 | 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 . |
13,559 | 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 . |
13,560 | 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 . |
13,561 | 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 { } } 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 . |
13,562 | public Thread newThread ( Runnable r ) { return new Thread ( r , getName ( ) + " (thread-" + threadNumber . getAndIncrement ( ) + ")" ) ; } | region Thread factory |
13,563 | protected void onTextChanged ( final CharSequence text , final int start , final int before , final int after ) { mNeedsResize = true ; resetTextSize ( ) ; } | When text changes set the force resize flag to true and reset the text size . |
13,564 | 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 |
13,565 | 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 |
13,566 | 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 |
13,567 | 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 |
13,568 | public void resizeText ( int width , int height ) { CharSequence text = getText ( ) ; if ( text == null || text . length ( ) == 0 || height <= 0 || width <= 0 || mTextSize == 0 ) { return ; } if ( getTransformationMethod ( ) != null ) { text = getTransformationMethod ( ) . getTransformation ( text , this ) ; } TextPaint textPaint = getPaint ( ) ; float oldTextSize = textPaint . getTextSize ( ) ; float targetTextSize = mMaxTextSize > 0 ? Math . min ( mTextSize , mMaxTextSize ) : mTextSize ; int textHeight = getTextHeight ( text , textPaint , width , targetTextSize ) ; while ( textHeight > height && targetTextSize > mMinTextSize ) { targetTextSize = Math . max ( targetTextSize - 2 , mMinTextSize ) ; textHeight = getTextHeight ( text , textPaint , width , targetTextSize ) ; } if ( mAddEllipsis && targetTextSize == mMinTextSize && textHeight > height ) { TextPaint paint = new TextPaint ( textPaint ) ; StaticLayout layout = new StaticLayout ( text , paint , width , Alignment . ALIGN_NORMAL , mSpacingMult , mSpacingAdd , false ) ; if ( layout . getLineCount ( ) > 0 ) { int lastLine = layout . getLineForVertical ( height ) - 1 ; if ( lastLine < 0 ) { setText ( "" ) ; } else { int start = layout . getLineStart ( lastLine ) ; int end = layout . getLineEnd ( lastLine ) ; float lineWidth = layout . getLineWidth ( lastLine ) ; float ellipseWidth = textPaint . measureText ( mEllipsis ) ; while ( width < lineWidth + ellipseWidth ) { lineWidth = textPaint . measureText ( text . subSequence ( start , -- end + 1 ) . toString ( ) ) ; } setText ( text . subSequence ( 0 , end ) + mEllipsis ) ; } } } setTextSize ( TypedValue . COMPLEX_UNIT_PX , targetTextSize ) ; setLineSpacing ( mSpacingAdd , mSpacingMult ) ; if ( mTextResizeListener != null ) { mTextResizeListener . onTextResize ( this , oldTextSize , targetTextSize ) ; } mNeedsResize = false ; } | Resize the text size with specified width and height |
13,569 | 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 |
13,570 | 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 |
13,571 | protected static void registerSensitiveKeys ( Class < ? extends JsonPayload > cls ) { List < Field > fields = RuntimeUtils . listFields ( cls , new RuntimeUtils . FieldFilter ( ) { public boolean accept ( Field field ) { return Modifier . isStatic ( field . getModifiers ( ) ) && field . getAnnotation ( SensitiveDataKey . class ) != null && field . getType ( ) . equals ( String . class ) ; } } ) ; 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 |
13,572 | private ImageScale scaleImage ( int imageX , int imageY , int containerX , int containerY ) { ImageScale ret = new ImageScale ( ) ; if ( imageX * containerY > imageY * containerX ) { ret . scale = ( float ) containerX / imageX ; ret . deltaY = ( ( float ) containerY - ( ret . scale * imageY ) ) / 2.0f ; } else { 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 . |
13,573 | 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 . |
13,574 | 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 ) ; } catch ( Exception e ) { atomicFile . failWrite ( stream ) ; throw new IOException ( e ) ; } } | Writes an object ot a file |
13,575 | 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 |
13,576 | 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 . |
13,577 | 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 . |
13,578 | public void scrollToChild ( View child ) { child . getDrawingRect ( mTempRect ) ; offsetDescendantRectToMyCoords ( child , mTempRect ) ; int scrollDelta = computeScrollDeltaToGetChildRectOnScreen ( mTempRect ) ; if ( scrollDelta != 0 ) { scrollBy ( 0 , scrollDelta ) ; } } | Scrolls the view to the given child . |
13,579 | public boolean isValid ( boolean questionIsRequired ) { 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 . |
13,580 | void fetchAndStoreMessages ( final boolean isMessageCenterForeground , final boolean showToast , final MessageFetchListener listener ) { checkConversationQueue ( ) ; try { String lastMessageId = messageStore . getLastReceivedMessageId ( ) ; fetchMessages ( lastMessageId , new MessageFetchListener ( ) { 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 ( ) ) ; int incomingUnreadMessages = 0 ; 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 ++ ; notifyInternalNewMessagesListeners ( ( CompoundMessage ) apptentiveMessage ) ; } } messageStore . addOrUpdateMessages ( messages . toArray ( new ApptentiveMessage [ messages . size ( ) ] ) ) ; if ( incomingUnreadMessages > 0 ) { if ( ! isMessageCenterForeground && showToast ) { DispatchQueue . mainQueue ( ) . dispatchAsyncOnce ( toastMessageNotifierTask . setMessage ( messageOnToast ) ) ; } } 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 . |
13,581 | 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 |
13,582 | 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 ) ) ; } } 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 . |
13,583 | 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 . |
13,584 | public static void dismissAllInteractions ( ) { if ( ! isConversationQueue ( ) ) { dispatchOnConversationQueue ( new DispatchTask ( ) { 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 . |
13,585 | 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 |
13,586 | 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 |
13,587 | 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 |
13,588 | 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 |
13,589 | 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 . |
13,590 | 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 . |
13,591 | 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 |
13,592 | 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 ; } 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 ) ; } deletePayload ( payload . getNonce ( ) ) ; } | region PayloadSender . Listener |
13,593 | private void sendNextPayload ( ) { singleThreadExecutor . execute ( new Runnable ( ) { public void run ( ) { try { sendNextPayloadSync ( ) ; } catch ( Exception e ) { ApptentiveLog . e ( e , "Exception while trying to send next payload" ) ; logException ( e ) ; } } } ) ; } | region Payload Sending |
13,594 | public void onCreate ( SQLiteDatabase db ) { ApptentiveLog . d ( DATABASE , "ApptentiveDatabase.onCreate(db)" ) ; db . execSQL ( SQL_CREATE_PAYLOAD_TABLE ) ; 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 . |
13,595 | 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 ) ; 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 . |
13,596 | void notifyObservers ( ApptentiveNotification notification ) { boolean hasLostReferences = false ; 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 ; } } 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 ) ; } } 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 . |
13,597 | 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 . |
13,598 | 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 |
13,599 | 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 . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.