idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
16,100
public static byte [ ] encryptAsBytes ( final String plainText ) throws Exception { final SecretKey secretKey = KeyManager . getInstance ( ) . getSecretKey ( ) ; return encryptAsBytes ( secretKey , plainText ) ; }
Encrypts the specified plainText using AES - 256 . This method uses the default secret key .
16,101
public static String encryptAsString ( final SecretKey secretKey , final String plainText ) throws Exception { return Base64 . getEncoder ( ) . encodeToString ( encryptAsBytes ( secretKey , plainText ) ) ; }
Encrypts the specified plainText using AES - 256 and returns a Base64 encoded representation of the encrypted bytes .
16,102
public static byte [ ] decryptAsBytes ( final SecretKey secretKey , final byte [ ] encryptedIvTextBytes ) throws Exception { int ivSize = 16 ; final byte [ ] iv = new byte [ ivSize ] ; System . arraycopy ( encryptedIvTextBytes , 0 , iv , 0 , iv . length ) ; final IvParameterSpec ivParameterSpec = new IvParameterSpec ( iv ) ; final int encryptedSize = encryptedIvTextBytes . length - ivSize ; final byte [ ] encryptedBytes = new byte [ encryptedSize ] ; System . arraycopy ( encryptedIvTextBytes , ivSize , encryptedBytes , 0 , encryptedSize ) ; final Cipher cipherDecrypt = Cipher . getInstance ( "AES/CBC/PKCS5Padding" ) ; cipherDecrypt . init ( Cipher . DECRYPT_MODE , secretKey , ivParameterSpec ) ; return cipherDecrypt . doFinal ( encryptedBytes ) ; }
Decrypts the specified bytes using AES - 256 .
16,103
public static byte [ ] decryptAsBytes ( final byte [ ] encryptedIvTextBytes ) throws Exception { final SecretKey secretKey = KeyManager . getInstance ( ) . getSecretKey ( ) ; return decryptAsBytes ( secretKey , encryptedIvTextBytes ) ; }
Decrypts the specified bytes using AES - 256 . This method uses the default secret key .
16,104
private void setCurrentPage ( int page ) { if ( page >= totalPages ) { this . currentPage = totalPages ; } else if ( page <= 1 ) { this . currentPage = 1 ; } else { this . currentPage = page ; } startingIndex = pageSize * ( currentPage - 1 ) ; if ( startingIndex < 0 ) { startingIndex = 0 ; } endingIndex = startingIndex + pageSize ; if ( endingIndex > list . size ( ) ) { endingIndex = list . size ( ) ; } }
Specifies a specific page to jump to .
16,105
@ SuppressWarnings ( "unchecked" ) public static < T > T getSessionAttribute ( final HttpSession session , final String key ) { if ( session != null ) { return ( T ) session . getAttribute ( key ) ; } return null ; }
Returns a session attribute as the type of object stored .
16,106
@ SuppressWarnings ( "unchecked" ) public static < T > T getRequestAttribute ( final HttpServletRequest request , final String key ) { if ( request != null ) { return ( T ) request . getAttribute ( key ) ; } return null ; }
Returns a request attribute as the type of object stored .
16,107
public static < T > T readAsObjectOf ( Class < T > clazz , String value ) { final ObjectMapper mapper = new ObjectMapper ( ) ; try { return mapper . readValue ( value , clazz ) ; } catch ( IOException e ) { LOGGER . error ( e . getMessage ( ) , e . fillInStackTrace ( ) ) ; } return null ; }
Reads in a String value and returns the object for which it represents .
16,108
public boolean validateToken ( final String token ) { try { final JwtParser jwtParser = Jwts . parser ( ) . setSigningKey ( key ) ; jwtParser . parse ( token ) ; this . subject = jwtParser . parseClaimsJws ( token ) . getBody ( ) . getSubject ( ) ; this . expiration = jwtParser . parseClaimsJws ( token ) . getBody ( ) . getExpiration ( ) ; return true ; } catch ( SignatureException e ) { LOGGER . info ( SecurityMarkers . SECURITY_FAILURE , "Received token that did not pass signature verification" ) ; } catch ( ExpiredJwtException e ) { LOGGER . debug ( SecurityMarkers . SECURITY_FAILURE , "Received expired token" ) ; } catch ( MalformedJwtException e ) { LOGGER . debug ( SecurityMarkers . SECURITY_FAILURE , "Received malformed token" ) ; LOGGER . debug ( SecurityMarkers . SECURITY_FAILURE , e . getMessage ( ) ) ; } catch ( UnsupportedJwtException | IllegalArgumentException e ) { LOGGER . error ( SecurityMarkers . SECURITY_FAILURE , e . getMessage ( ) ) ; } return false ; }
Validates a JWT by ensuring the signature matches and validates against the SecretKey and checks the expiration date .
16,109
private Date addDays ( final Date date , final int days ) { final Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( date ) ; cal . add ( Calendar . DATE , days ) ; return cal . getTime ( ) ; }
Create a new future Date from the specified Date .
16,110
private Event linkChainIdentifier ( Event event ) { if ( event instanceof ChainableEvent ) { ChainableEvent chainableEvent = ( ChainableEvent ) event ; chainableEvent . setChainIdentifier ( this . getChainIdentifier ( ) ) ; return chainableEvent ; } return event ; }
Assigns the chain identifier for the specified event to the chain identifier value of this instance . This requires the specified event to be an instance of ChainableEvent .
16,111
public void executeUpgrades ( final List < Class < ? extends UpgradeItem > > classes ) throws UpgradeException { final Connection connection = getConnection ( qm ) ; final UpgradeMetaProcessor installedUpgrades = new UpgradeMetaProcessor ( connection ) ; DbUtil . initPlatformName ( connection ) ; try { installedUpgrades . updateSchemaVersion ( null ) ; } catch ( SQLException e ) { LOGGER . error ( "Failed to update schema version" , e ) ; return ; } for ( final Class < ? extends UpgradeItem > upgradeClass : classes ) { try { @ SuppressWarnings ( "unchecked" ) final Constructor constructor = upgradeClass . getConstructor ( ) ; final UpgradeItem upgradeItem = ( UpgradeItem ) constructor . newInstance ( ) ; if ( upgradeItem . shouldUpgrade ( qm , connection ) ) { if ( ! installedUpgrades . hasUpgradeRan ( upgradeClass ) ) { LOGGER . info ( "Upgrade class " + upgradeClass . getName ( ) + " about to run." ) ; final long startTime = System . currentTimeMillis ( ) ; upgradeItem . executeUpgrade ( qm , connection ) ; final long endTime = System . currentTimeMillis ( ) ; installedUpgrades . installUpgrade ( upgradeClass , startTime , endTime ) ; installedUpgrades . updateSchemaVersion ( new VersionComparator ( upgradeItem . getSchemaVersion ( ) ) ) ; LOGGER . info ( "Completed running upgrade class " + upgradeClass . getName ( ) + " in " + ( endTime - startTime ) + " ms." ) ; } else { LOGGER . debug ( "Upgrade class " + upgradeClass . getName ( ) + " has already ran, skipping." ) ; } } else { LOGGER . debug ( "Upgrade class " + upgradeClass . getName ( ) + " does not need to run." ) ; } } catch ( Exception e ) { DbUtil . rollback ( connection ) ; LOGGER . error ( "Error in executing upgrade class: " + upgradeClass . getName ( ) , e ) ; throw new UpgradeException ( e ) ; } } }
Performs the execution of upgrades in the order defined by the specified array .
16,112
private Connection getConnection ( AlpineQueryManager aqm ) { final JDOConnection jdoConnection = aqm . getPersistenceManager ( ) . getDataStoreConnection ( ) ; if ( jdoConnection != null ) { if ( jdoConnection . getNativeConnection ( ) instanceof Connection ) { return ( Connection ) jdoConnection . getNativeConnection ( ) ; } } return null ; }
This connection should never be closed .
16,113
public static boolean isValidUUID ( String uuid ) { return ! StringUtils . isEmpty ( uuid ) && UUID_PATTERN . matcher ( uuid ) . matches ( ) ; }
Determines if the specified string is a valid UUID .
16,114
private LdapUser autoProvision ( final AlpineQueryManager qm ) throws AlpineAuthenticationException { LOGGER . debug ( "Provisioning: " + username ) ; LdapUser user = null ; final LdapConnectionWrapper ldap = new LdapConnectionWrapper ( ) ; DirContext dirContext = null ; try { dirContext = ldap . createDirContext ( ) ; final SearchResult result = ldap . searchForSingleUsername ( dirContext , username ) ; if ( result != null ) { user = new LdapUser ( ) ; user . setUsername ( username ) ; user . setDN ( result . getNameInNamespace ( ) ) ; user . setEmail ( ldap . getAttribute ( result , LdapConnectionWrapper . ATTRIBUTE_MAIL ) ) ; user = qm . persist ( user ) ; if ( LdapConnectionWrapper . TEAM_SYNCHRONIZATION ) { final List < String > groupDNs = ldap . getGroups ( dirContext , user ) ; user = qm . synchronizeTeamMembership ( user , groupDNs ) ; } } else { LOGGER . warn ( "Could not find '" + username + "' in the directory while provisioning the user. Ensure '" + Config . AlpineKey . LDAP_ATTRIBUTE_NAME . getPropertyName ( ) + "' is defined correctly" ) ; throw new AlpineAuthenticationException ( AlpineAuthenticationException . CauseType . UNMAPPED_ACCOUNT ) ; } } catch ( NamingException e ) { LOGGER . error ( "An error occurred while auto-provisioning an authenticated user" , e ) ; throw new AlpineAuthenticationException ( AlpineAuthenticationException . CauseType . OTHER ) ; } finally { ldap . closeQuietly ( dirContext ) ; } return user ; }
Automatically creates an LdapUser sets the value of various LDAP attributes and persists the user to the database .
16,115
private boolean validateCredentials ( ) { LOGGER . debug ( "Validating credentials for: " + username ) ; final LdapConnectionWrapper ldap = new LdapConnectionWrapper ( ) ; DirContext dirContext = null ; LdapContext ldapContext = null ; try ( AlpineQueryManager qm = new AlpineQueryManager ( ) ) { final LdapUser ldapUser = qm . getLdapUser ( username ) ; if ( ldapUser != null && ldapUser . getDN ( ) != null && ldapUser . getDN ( ) . contains ( "=" ) ) { ldapContext = ldap . createLdapContext ( ldapUser . getDN ( ) , password ) ; LOGGER . debug ( "The supplied credentials are valid for: " + username ) ; return true ; } else { dirContext = ldap . createDirContext ( ) ; final SearchResult result = ldap . searchForSingleUsername ( dirContext , username ) ; if ( result != null ) { ldapContext = ldap . createLdapContext ( result . getNameInNamespace ( ) , password ) ; LOGGER . debug ( "The supplied credentials are invalid for: " + username ) ; return true ; } } } catch ( NamingException e ) { LOGGER . debug ( "An error occurred while attempting to validate credentials" , e ) ; } finally { ldap . closeQuietly ( ldapContext ) ; ldap . closeQuietly ( dirContext ) ; } return false ; }
Asserts a users credentials . Returns a boolean value indicating if assertion was successful or not .
16,116
public static PersistenceManager createPersistenceManager ( ) { if ( Config . isUnitTestsEnabled ( ) ) { pmf = ( JDOPersistenceManagerFactory ) JDOHelper . getPersistenceManagerFactory ( JdoProperties . unit ( ) , "Alpine" ) ; } if ( pmf == null ) { throw new IllegalStateException ( "Context is not initialized yet." ) ; } return pmf . getPersistenceManager ( ) ; }
Creates a new JDO PersistenceManager .
16,117
public LdapContext createLdapContext ( final String userDn , final String password ) throws NamingException { LOGGER . debug ( "Creating LDAP context for: " + userDn ) ; if ( StringUtils . isEmpty ( userDn ) || StringUtils . isEmpty ( password ) ) { throw new NamingException ( "Username or password cannot be empty or null" ) ; } final Hashtable < String , String > env = new Hashtable < > ( ) ; if ( StringUtils . isNotBlank ( LDAP_SECURITY_AUTH ) ) { env . put ( Context . SECURITY_AUTHENTICATION , LDAP_SECURITY_AUTH ) ; } env . put ( Context . SECURITY_PRINCIPAL , userDn ) ; env . put ( Context . SECURITY_CREDENTIALS , password ) ; env . put ( Context . INITIAL_CONTEXT_FACTORY , "com.sun.jndi.ldap.LdapCtxFactory" ) ; env . put ( Context . PROVIDER_URL , LDAP_URL ) ; if ( IS_LDAP_SSLTLS ) { env . put ( "java.naming.ldap.factory.socket" , "alpine.crypto.RelaxedSSLSocketFactory" ) ; } try { return new InitialLdapContext ( env , null ) ; } catch ( CommunicationException e ) { LOGGER . error ( "Failed to connect to directory server" , e ) ; throw ( e ) ; } catch ( NamingException e ) { throw new NamingException ( "Failed to authenticate user" ) ; } }
Asserts a users credentials . Returns an LdapContext if assertion is successful or an exception for any other reason .
16,118
public DirContext createDirContext ( ) throws NamingException { LOGGER . debug ( "Creating directory service context (DirContext)" ) ; final Hashtable < String , String > env = new Hashtable < > ( ) ; env . put ( Context . SECURITY_PRINCIPAL , BIND_USERNAME ) ; env . put ( Context . SECURITY_CREDENTIALS , BIND_PASSWORD ) ; env . put ( Context . INITIAL_CONTEXT_FACTORY , "com.sun.jndi.ldap.LdapCtxFactory" ) ; env . put ( Context . PROVIDER_URL , LDAP_URL ) ; if ( IS_LDAP_SSLTLS ) { env . put ( "java.naming.ldap.factory.socket" , "alpine.crypto.RelaxedSSLSocketFactory" ) ; } return new InitialDirContext ( env ) ; }
Creates a DirContext with the applications configuration settings .
16,119
public List < String > getGroups ( final DirContext dirContext , final LdapUser ldapUser ) throws NamingException { LOGGER . debug ( "Retrieving groups for: " + ldapUser . getDN ( ) ) ; final List < String > groupDns = new ArrayList < > ( ) ; final String searchFilter = variableSubstitution ( USER_GROUPS_FILTER , ldapUser ) ; final SearchControls sc = new SearchControls ( ) ; sc . setSearchScope ( SearchControls . SUBTREE_SCOPE ) ; final NamingEnumeration < SearchResult > ne = dirContext . search ( BASE_DN , searchFilter , sc ) ; while ( hasMoreEnum ( ne ) ) { final SearchResult result = ne . next ( ) ; groupDns . add ( result . getNameInNamespace ( ) ) ; LOGGER . debug ( "Found group: " + result . getNameInNamespace ( ) + " for user: " + ldapUser . getDN ( ) ) ; } closeQuietly ( ne ) ; return groupDns ; }
Retrieves a list of all groups the user is a member of .
16,120
public List < String > getGroups ( final DirContext dirContext ) throws NamingException { LOGGER . debug ( "Retrieving all groups" ) ; final List < String > groupDns = new ArrayList < > ( ) ; final SearchControls sc = new SearchControls ( ) ; sc . setSearchScope ( SearchControls . SUBTREE_SCOPE ) ; final NamingEnumeration < SearchResult > ne = dirContext . search ( BASE_DN , GROUPS_FILTER , sc ) ; while ( hasMoreEnum ( ne ) ) { final SearchResult result = ne . next ( ) ; groupDns . add ( result . getNameInNamespace ( ) ) ; LOGGER . debug ( "Found group: " + result . getNameInNamespace ( ) ) ; } closeQuietly ( ne ) ; return groupDns ; }
Retrieves a list of all the groups in the directory .
16,121
public String getAttribute ( final DirContext ctx , final String dn , final String attributeName ) throws NamingException { final Attributes attributes = ctx . getAttributes ( dn ) ; return getAttribute ( attributes , attributeName ) ; }
Retrieves an attribute by its name for the specified dn .
16,122
public String getAttribute ( final SearchResult result , final String attributeName ) throws NamingException { return getAttribute ( result . getAttributes ( ) , attributeName ) ; }
Retrieves an attribute by its name for the specified search result .
16,123
public String getAttribute ( final Attributes attributes , final String attributeName ) throws NamingException { if ( attributes == null || attributes . size ( ) == 0 ) { return null ; } else { final Attribute attribute = attributes . get ( attributeName ) ; if ( attribute != null ) { final Object o = attribute . get ( ) ; if ( o instanceof String ) { return ( String ) attribute . get ( ) ; } } } return null ; }
Retrieves an attribute by its name .
16,124
private static String formatPrincipal ( final String username ) { if ( StringUtils . isNotBlank ( LDAP_AUTH_USERNAME_FMT ) ) { return String . format ( LDAP_AUTH_USERNAME_FMT , username ) ; } return username ; }
Formats the principal in username
16,125
public static String generateHash ( String emailAddress ) { if ( StringUtils . isBlank ( emailAddress ) ) { return null ; } return DigestUtils . md5Hex ( emailAddress . trim ( ) . toLowerCase ( ) ) . toLowerCase ( ) ; }
Generates a hash value from the specified email address . Returns null if emailAddress is empty or null .
16,126
public static String getGravatarUrl ( String emailAddress ) { String hash = generateHash ( emailAddress ) ; if ( hash == null ) { return "https://www.gravatar.com/avatar/00000000000000000000000000000000" + ".jpg?d=mm" ; } else { return "https://www.gravatar.com/avatar/" + hash + ".jpg?d=mm" ; } }
Generates a Gravatar URL for the specified email address . If the email address is blank or does not have a Gravatar will fallback to usingthe mystery - man image .
16,127
@ SuppressWarnings ( "unchecked" ) public ApiKey getApiKey ( final String key ) { final Query query = pm . newQuery ( ApiKey . class , "key == :key" ) ; final List < ApiKey > result = ( List < ApiKey > ) query . execute ( key ) ; return Collections . isEmpty ( result ) ? null : result . get ( 0 ) ; }
Returns an API key .
16,128
public ApiKey regenerateApiKey ( final ApiKey apiKey ) { pm . currentTransaction ( ) . begin ( ) ; apiKey . setKey ( ApiKeyGenerator . generate ( ) ) ; pm . currentTransaction ( ) . commit ( ) ; return pm . getObjectById ( ApiKey . class , apiKey . getId ( ) ) ; }
Regenerates an API key . This method does not create a new ApiKey object rather it uses the existing ApiKey object and simply creates a new key string .
16,129
public ApiKey createApiKey ( final Team team ) { final List < Team > teams = new ArrayList < > ( ) ; teams . add ( team ) ; pm . currentTransaction ( ) . begin ( ) ; final ApiKey apiKey = new ApiKey ( ) ; apiKey . setKey ( ApiKeyGenerator . generate ( ) ) ; apiKey . setTeams ( teams ) ; pm . makePersistent ( apiKey ) ; pm . currentTransaction ( ) . commit ( ) ; return pm . getObjectById ( ApiKey . class , apiKey . getId ( ) ) ; }
Creates a new ApiKey object including a cryptographically secure API key string .
16,130
@ SuppressWarnings ( "unchecked" ) public LdapUser getLdapUser ( final String username ) { final Query query = pm . newQuery ( LdapUser . class , "username == :username" ) ; final List < LdapUser > result = ( List < LdapUser > ) query . execute ( username ) ; return Collections . isEmpty ( result ) ? null : result . get ( 0 ) ; }
Retrieves an LdapUser containing the specified username . If the username does not exist returns null .
16,131
@ SuppressWarnings ( "unchecked" ) public List < LdapUser > getLdapUsers ( ) { final Query query = pm . newQuery ( LdapUser . class ) ; query . setOrdering ( "username asc" ) ; return ( List < LdapUser > ) query . execute ( ) ; }
Returns a complete list of all LdapUser objects in ascending order by username .
16,132
public LdapUser createLdapUser ( final String username ) { pm . currentTransaction ( ) . begin ( ) ; final LdapUser user = new LdapUser ( ) ; user . setUsername ( username ) ; user . setDN ( "Syncing..." ) ; pm . makePersistent ( user ) ; pm . currentTransaction ( ) . commit ( ) ; EventService . getInstance ( ) . publish ( new LdapSyncEvent ( user . getUsername ( ) ) ) ; return getObjectById ( LdapUser . class , user . getId ( ) ) ; }
Creates a new LdapUser object with the specified username .
16,133
public LdapUser updateLdapUser ( final LdapUser transientUser ) { final LdapUser user = getObjectById ( LdapUser . class , transientUser . getId ( ) ) ; pm . currentTransaction ( ) . begin ( ) ; user . setDN ( transientUser . getDN ( ) ) ; pm . currentTransaction ( ) . commit ( ) ; return pm . getObjectById ( LdapUser . class , user . getId ( ) ) ; }
Updates the specified LdapUser .
16,134
public ManagedUser updateManagedUser ( final ManagedUser transientUser ) { final ManagedUser user = getObjectById ( ManagedUser . class , transientUser . getId ( ) ) ; pm . currentTransaction ( ) . begin ( ) ; user . setFullname ( transientUser . getFullname ( ) ) ; user . setEmail ( transientUser . getEmail ( ) ) ; user . setForcePasswordChange ( transientUser . isForcePasswordChange ( ) ) ; user . setNonExpiryPassword ( transientUser . isNonExpiryPassword ( ) ) ; user . setSuspended ( transientUser . isSuspended ( ) ) ; if ( transientUser . getPassword ( ) != null ) { if ( ! user . getPassword ( ) . equals ( transientUser . getPassword ( ) ) ) { user . setLastPasswordChange ( new Date ( ) ) ; } user . setPassword ( transientUser . getPassword ( ) ) ; } pm . currentTransaction ( ) . commit ( ) ; return pm . getObjectById ( ManagedUser . class , user . getId ( ) ) ; }
Updates the specified ManagedUser .
16,135
@ SuppressWarnings ( "unchecked" ) public ManagedUser getManagedUser ( final String username ) { final Query query = pm . newQuery ( ManagedUser . class , "username == :username" ) ; final List < ManagedUser > result = ( List < ManagedUser > ) query . execute ( username ) ; return Collections . isEmpty ( result ) ? null : result . get ( 0 ) ; }
Returns a ManagedUser with the specified username . If the username does not exist returns null .
16,136
@ SuppressWarnings ( "unchecked" ) public List < ManagedUser > getManagedUsers ( ) { final Query query = pm . newQuery ( ManagedUser . class ) ; query . setOrdering ( "username asc" ) ; return ( List < ManagedUser > ) query . execute ( ) ; }
Returns a complete list of all ManagedUser objects in ascending order by username .
16,137
public UserPrincipal getUserPrincipal ( String username ) { final UserPrincipal principal = getManagedUser ( username ) ; if ( principal != null ) { return principal ; } return getLdapUser ( username ) ; }
Resolves a UserPrincipal . Default order resolution is to first match on ManagedUser then on LdapUser . This may be configurable in a future release .
16,138
@ SuppressWarnings ( "unchecked" ) public List < Team > getTeams ( ) { pm . getFetchPlan ( ) . addGroup ( Team . FetchGroup . ALL . name ( ) ) ; final Query query = pm . newQuery ( Team . class ) ; query . setOrdering ( "name asc" ) ; return ( List < Team > ) query . execute ( ) ; }
Returns a complete list of all Team objects in ascending order by name .
16,139
public Team updateTeam ( final Team transientTeam ) { final Team team = getObjectByUuid ( Team . class , transientTeam . getUuid ( ) ) ; pm . currentTransaction ( ) . begin ( ) ; team . setName ( transientTeam . getName ( ) ) ; pm . currentTransaction ( ) . commit ( ) ; return pm . getObjectById ( Team . class , team . getId ( ) ) ; }
Updates the specified Team .
16,140
public boolean addUserToTeam ( final UserPrincipal user , final Team team ) { List < Team > teams = user . getTeams ( ) ; boolean found = false ; if ( teams == null ) { teams = new ArrayList < > ( ) ; } for ( final Team t : teams ) { if ( team . getUuid ( ) . equals ( t . getUuid ( ) ) ) { found = true ; } } if ( ! found ) { pm . currentTransaction ( ) . begin ( ) ; teams . add ( team ) ; user . setTeams ( teams ) ; pm . currentTransaction ( ) . commit ( ) ; return true ; } return false ; }
Associates a UserPrincipal to a Team .
16,141
public boolean removeUserFromTeam ( final UserPrincipal user , final Team team ) { final List < Team > teams = user . getTeams ( ) ; if ( teams == null ) { return false ; } boolean found = false ; for ( final Team t : teams ) { if ( team . getUuid ( ) . equals ( t . getUuid ( ) ) ) { found = true ; } } if ( found ) { pm . currentTransaction ( ) . begin ( ) ; teams . remove ( team ) ; user . setTeams ( teams ) ; pm . currentTransaction ( ) . commit ( ) ; return true ; } return false ; }
Removes the association of a UserPrincipal to a Team .
16,142
public Permission createPermission ( final String name , final String description ) { pm . currentTransaction ( ) . begin ( ) ; final Permission permission = new Permission ( ) ; permission . setName ( name ) ; permission . setDescription ( description ) ; pm . makePersistent ( permission ) ; pm . currentTransaction ( ) . commit ( ) ; return getObjectById ( Permission . class , permission . getId ( ) ) ; }
Creates a Permission object .
16,143
@ SuppressWarnings ( "unchecked" ) public Permission getPermission ( final String name ) { final Query query = pm . newQuery ( Permission . class , "name == :name" ) ; final List < Permission > result = ( List < Permission > ) query . execute ( name ) ; return Collections . isEmpty ( result ) ? null : result . get ( 0 ) ; }
Retrieves a Permission by its name .
16,144
@ SuppressWarnings ( "unchecked" ) public List < Permission > getPermissions ( ) { final Query query = pm . newQuery ( Permission . class ) ; query . setOrdering ( "name asc" ) ; return ( List < Permission > ) query . execute ( ) ; }
Returns a list of all Permissions defined in the system .
16,145
public List < Permission > getEffectivePermissions ( UserPrincipal user ) { final LinkedHashSet < Permission > permissions = new LinkedHashSet < > ( ) ; if ( user . getPermissions ( ) != null ) { permissions . addAll ( user . getPermissions ( ) ) ; } if ( user . getTeams ( ) != null ) { for ( final Team team : user . getTeams ( ) ) { final List < Permission > teamPermissions = getObjectById ( Team . class , team . getId ( ) ) . getPermissions ( ) ; if ( teamPermissions != null ) { permissions . addAll ( teamPermissions ) ; } } } return new ArrayList < > ( permissions ) ; }
Determines the effective permissions for the specified user by collecting a List of all permissions assigned to the user either directly or through team membership .
16,146
public boolean hasPermission ( final UserPrincipal user , String permissionName , boolean includeTeams ) { Query query ; if ( user instanceof ManagedUser ) { query = pm . newQuery ( Permission . class , "name == :permissionName && managedUsers.contains(:user)" ) ; } else { query = pm . newQuery ( Permission . class , "name == :permissionName && ldapUsers.contains(:user)" ) ; } query . setResult ( "count(id)" ) ; final long count = ( Long ) query . execute ( permissionName , user ) ; if ( count > 0 ) { return true ; } if ( includeTeams ) { for ( final Team team : user . getTeams ( ) ) { if ( hasPermission ( team , permissionName ) ) { return true ; } } } return false ; }
Determines if the specified UserPrincipal has been assigned the specified permission .
16,147
public boolean hasPermission ( final Team team , String permissionName ) { final Query query = pm . newQuery ( Permission . class , "name == :permissionName && teams.contains(:team)" ) ; query . setResult ( "count(id)" ) ; return ( Long ) query . execute ( permissionName , team ) > 0 ; }
Determines if the specified Team has been assigned the specified permission .
16,148
public boolean hasPermission ( final ApiKey apiKey , String permissionName ) { if ( apiKey . getTeams ( ) == null ) { return false ; } for ( final Team team : apiKey . getTeams ( ) ) { final List < Permission > teamPermissions = getObjectById ( Team . class , team . getId ( ) ) . getPermissions ( ) ; for ( final Permission permission : teamPermissions ) { if ( permission . getName ( ) . equals ( permissionName ) ) { return true ; } } } return false ; }
Determines if the specified ApiKey has been assigned the specified permission .
16,149
@ SuppressWarnings ( "unchecked" ) public MappedLdapGroup getMappedLdapGroup ( final Team team , final String dn ) { final Query query = pm . newQuery ( MappedLdapGroup . class , "team == :team && dn == :dn" ) ; final List < MappedLdapGroup > result = ( List < MappedLdapGroup > ) query . execute ( team , dn ) ; return Collections . isEmpty ( result ) ? null : result . get ( 0 ) ; }
Retrieves a MappedLdapGroup object for the specified Team and LDAP group .
16,150
@ SuppressWarnings ( "unchecked" ) public List < MappedLdapGroup > getMappedLdapGroups ( final Team team ) { final Query query = pm . newQuery ( MappedLdapGroup . class , "team == :team" ) ; return ( List < MappedLdapGroup > ) query . execute ( team ) ; }
Retrieves a List of MappedLdapGroup objects for the specified Team .
16,151
@ SuppressWarnings ( "unchecked" ) public List < MappedLdapGroup > getMappedLdapGroups ( final String dn ) { final Query query = pm . newQuery ( MappedLdapGroup . class , "dn == :dn" ) ; return ( List < MappedLdapGroup > ) query . execute ( dn ) ; }
Retrieves a List of MappedLdapGroup objects for the specified DN .
16,152
public MappedLdapGroup createMappedLdapGroup ( final Team team , final String dn ) { pm . currentTransaction ( ) . begin ( ) ; final MappedLdapGroup mapping = new MappedLdapGroup ( ) ; mapping . setTeam ( team ) ; mapping . setDn ( dn ) ; pm . makePersistent ( mapping ) ; pm . currentTransaction ( ) . commit ( ) ; return getObjectById ( MappedLdapGroup . class , mapping . getId ( ) ) ; }
Creates a MappedLdapGroup object .
16,153
public EventServiceLog updateEventServiceLog ( EventServiceLog eventServiceLog ) { if ( eventServiceLog != null ) { final EventServiceLog log = getObjectById ( EventServiceLog . class , eventServiceLog . getId ( ) ) ; if ( log != null ) { pm . currentTransaction ( ) . begin ( ) ; log . setCompleted ( new Timestamp ( new Date ( ) . getTime ( ) ) ) ; pm . currentTransaction ( ) . commit ( ) ; return pm . getObjectById ( EventServiceLog . class , log . getId ( ) ) ; } } return null ; }
Updates a EventServiceLog .
16,154
@ SuppressWarnings ( "unchecked" ) public ConfigProperty getConfigProperty ( final String groupName , final String propertyName ) { final Query query = pm . newQuery ( ConfigProperty . class , "groupName == :groupName && propertyName == :propertyName" ) ; final List < ConfigProperty > result = ( List < ConfigProperty > ) query . execute ( groupName , propertyName ) ; return Collections . isEmpty ( result ) ? null : result . get ( 0 ) ; }
Returns a ConfigProperty with the specified groupName and propertyName .
16,155
@ SuppressWarnings ( "unchecked" ) public List < ConfigProperty > getConfigProperties ( ) { final Query query = pm . newQuery ( ConfigProperty . class ) ; query . setOrdering ( "groupName asc, propertyName asc" ) ; return ( List < ConfigProperty > ) query . execute ( ) ; }
Returns a list of ConfigProperty objects .
16,156
public ConfigProperty createConfigProperty ( final String groupName , final String propertyName , final String propertyValue , final ConfigProperty . PropertyType propertyType , final String description ) { pm . currentTransaction ( ) . begin ( ) ; final ConfigProperty configProperty = new ConfigProperty ( ) ; configProperty . setGroupName ( groupName ) ; configProperty . setPropertyName ( propertyName ) ; configProperty . setPropertyValue ( propertyValue ) ; configProperty . setPropertyType ( propertyType ) ; configProperty . setDescription ( description ) ; pm . makePersistent ( configProperty ) ; pm . currentTransaction ( ) . commit ( ) ; return getObjectById ( ConfigProperty . class , configProperty . getId ( ) ) ; }
Creates a ConfigProperty object .
16,157
private String formatPolicy ( ) { final StringBuilder sb = new StringBuilder ( ) ; sb . append ( "pin-sha256" ) . append ( "=\"" ) . append ( primaryHash ) . append ( "\"; " ) ; sb . append ( "pin-sha256" ) . append ( "=\"" ) . append ( backupHash ) . append ( "\"; " ) ; sb . append ( "max-age" ) . append ( "=" ) . append ( maxAge ) ; if ( includeSubdomains ) { sb . append ( "; " ) . append ( "includeSubDomains" ) ; } if ( reportUri != null ) { sb . append ( "; " ) . append ( "report-uri" ) . append ( "=\"" ) . append ( reportUri ) . append ( "\"" ) ; } return sb . toString ( ) ; }
Formats the HPKP policy header .
16,158
@ SuppressWarnings ( "unchecked" ) public < T > List < T > getList ( Class < T > clazz ) { return ( List < T > ) objects ; }
Retrieves a List of objects from the result .
16,159
@ SuppressWarnings ( "unchecked" ) public < T > Set < T > getSet ( Class < T > clazz ) { return ( Set < T > ) objects ; }
Retrieves a Set of objects from the result .
16,160
public void setObjects ( Object object ) { if ( Collection . class . isAssignableFrom ( object . getClass ( ) ) ) { this . objects = ( Collection ) object ; } }
Specifies a Collection of objects from the result .
16,161
public void setAudioEncoding ( final int audioEncoding ) { if ( audioEncoding != AudioFormat . ENCODING_PCM_8BIT && audioEncoding != AudioFormat . ENCODING_PCM_16BIT ) { throw new IllegalArgumentException ( "Invalid encoding" ) ; } else if ( currentAudioState . get ( ) != PREPARED_STATE && currentAudioState . get ( ) != INITIALIZED_STATE ) { throw new IllegalStateException ( "Cannot modify audio encoding during a non-prepared and non-initialized state" ) ; } this . audioEncoding = audioEncoding ; }
Sets the encoding for the audio file .
16,162
public void setSampleRate ( final int sampleRateInHertz ) { if ( sampleRateInHertz != DEFAULT_AUDIO_SAMPLE_RATE_HERTZ && sampleRateInHertz != 22050 && sampleRateInHertz != 16000 && sampleRateInHertz != 11025 ) { throw new IllegalArgumentException ( "Invalid sample rate given" ) ; } else if ( currentAudioState . get ( ) != PREPARED_STATE && currentAudioState . get ( ) != INITIALIZED_STATE ) { throw new IllegalStateException ( "Recorder cannot have its sample rate changed when it is not in an initialized or prepared state" ) ; } this . sampleRateInHertz = sampleRateInHertz ; }
Sets the sample rate for the recording .
16,163
public void setChannel ( final int channelConfig ) { if ( channelConfig != AudioFormat . CHANNEL_IN_MONO && channelConfig != AudioFormat . CHANNEL_IN_STEREO && channelConfig != AudioFormat . CHANNEL_IN_DEFAULT ) { throw new IllegalArgumentException ( "Invalid channel given." ) ; } else if ( currentAudioState . get ( ) != PREPARED_STATE && currentAudioState . get ( ) != INITIALIZED_STATE ) { throw new IllegalStateException ( "Recorder cannot have its file changed when it is in an initialized or prepared state" ) ; } this . channelConfig = channelConfig ; }
Sets the channel .
16,164
public void pauseRecording ( ) { if ( currentAudioState . get ( ) == RECORDING_STATE ) { currentAudioState . getAndSet ( PAUSED_STATE ) ; onTimeCompletedTimer . cancel ( ) ; remainingMaxTimeInMillis = remainingMaxTimeInMillis - ( System . currentTimeMillis ( ) - recordingStartTimeMillis ) ; } else { Log . w ( TAG , "Audio recording is not recording" ) ; } }
Pauses the recording if the recorder is in a recording state . Does nothing if in another state . Paused media recorder halts the max time countdown .
16,165
public void resumeRecording ( ) { if ( currentAudioState . get ( ) == PAUSED_STATE ) { recordingStartTimeMillis = System . currentTimeMillis ( ) ; currentAudioState . getAndSet ( RECORDING_STATE ) ; onTimeCompletedTimer = new Timer ( true ) ; onTimeCompletionTimerTask = new MaxTimeTimerTask ( ) ; onTimeCompletedTimer . schedule ( onTimeCompletionTimerTask , remainingMaxTimeInMillis ) ; } else { Log . w ( TAG , "Audio recording is not paused" ) ; } }
Resumes the audio recording . Does nothing if the recorder is in a non - recording state .
16,166
public void stopRecording ( ) { if ( currentAudioState . get ( ) == PAUSED_STATE || currentAudioState . get ( ) == RECORDING_STATE ) { currentAudioState . getAndSet ( STOPPED_STATE ) ; onTimeCompletedTimer . cancel ( ) ; onTimeCompletedTimer = null ; onTimeCompletionTimerTask = null ; } else { Log . w ( TAG , "Audio recording is not in a paused or recording state." ) ; } currentAudioRecordingThread = null ; }
Stops the audio recording if it is in a paused or recording state . Does nothing if the recorder is already stopped .
16,167
private < T extends ValueDescriptor < ? > > T createValue ( Class < T > type , String name ) { if ( name != null ) { this . arrayValueDescriptor = null ; } String valueName ; if ( arrayValueDescriptor != null ) { valueName = "[" + getArrayValue ( ) . size ( ) + "]" ; } else { valueName = name ; } T valueDescriptor = visitorHelper . getValueDescriptor ( type ) ; valueDescriptor . setName ( valueName ) ; return valueDescriptor ; }
Create a value descriptor of given type and name and initializes it .
16,168
private void addValue ( String name , ValueDescriptor < ? > value ) { if ( arrayValueDescriptor != null && name == null ) { getArrayValue ( ) . add ( value ) ; } else { setValue ( descriptor , value ) ; } }
Add the descriptor as value to the current annotation or array value .
16,169
private List < ValueDescriptor < ? > > getArrayValue ( ) { List < ValueDescriptor < ? > > values = arrayValueDescriptor . getValue ( ) ; if ( values == null ) { values = new LinkedList < > ( ) ; arrayValueDescriptor . setValue ( values ) ; } return values ; }
Get the array of referenced values .
16,170
public static String getType ( final Type t ) { switch ( t . getSort ( ) ) { case Type . ARRAY : return getType ( t . getElementType ( ) ) ; default : return t . getClassName ( ) ; } }
Return the type name of the given ASM type .
16,171
public static String getMethodSignature ( String name , String rawSignature ) { StringBuilder signature = new StringBuilder ( ) ; String returnType = org . objectweb . asm . Type . getReturnType ( rawSignature ) . getClassName ( ) ; if ( returnType != null ) { signature . append ( returnType ) ; signature . append ( ' ' ) ; } signature . append ( name ) ; signature . append ( '(' ) ; org . objectweb . asm . Type [ ] types = org . objectweb . asm . Type . getArgumentTypes ( rawSignature ) ; for ( int i = 0 ; i < types . length ; i ++ ) { if ( i > 0 ) { signature . append ( ',' ) ; } signature . append ( types [ i ] . getClassName ( ) ) ; } signature . append ( ')' ) ; return signature . toString ( ) ; }
Return a method signature .
16,172
public static String getFieldSignature ( String name , String rawSignature ) { StringBuilder signature = new StringBuilder ( ) ; String returnType = org . objectweb . asm . Type . getType ( rawSignature ) . getClassName ( ) ; signature . append ( returnType ) ; signature . append ( ' ' ) ; signature . append ( name ) ; return signature . toString ( ) ; }
Return a field signature .
16,173
MethodDescriptor getMethodDescriptor ( TypeCache . CachedType < ? > cachedType , String signature ) { MethodDescriptor methodDescriptor = cachedType . getMethod ( signature ) ; if ( methodDescriptor == null ) { if ( signature . startsWith ( CONSTRUCTOR_METHOD ) ) { methodDescriptor = scannerContext . getStore ( ) . create ( ConstructorDescriptor . class ) ; } else { methodDescriptor = scannerContext . getStore ( ) . create ( MethodDescriptor . class ) ; } methodDescriptor . setSignature ( signature ) ; cachedType . addMember ( signature , methodDescriptor ) ; } return methodDescriptor ; }
Return the method descriptor for the given type and method signature .
16,174
void addInvokes ( MethodDescriptor methodDescriptor , final Integer lineNumber , MethodDescriptor invokedMethodDescriptor ) { InvokesDescriptor invokesDescriptor = scannerContext . getStore ( ) . create ( methodDescriptor , InvokesDescriptor . class , invokedMethodDescriptor ) ; invokesDescriptor . setLineNumber ( lineNumber ) ; }
Add a invokes relation between two methods .
16,175
void addReads ( MethodDescriptor methodDescriptor , final Integer lineNumber , FieldDescriptor fieldDescriptor ) { ReadsDescriptor readsDescriptor = scannerContext . getStore ( ) . create ( methodDescriptor , ReadsDescriptor . class , fieldDescriptor ) ; readsDescriptor . setLineNumber ( lineNumber ) ; }
Add a reads relation between a method and a field .
16,176
void addWrites ( MethodDescriptor methodDescriptor , final Integer lineNumber , FieldDescriptor fieldDescriptor ) { WritesDescriptor writesDescriptor = scannerContext . getStore ( ) . create ( methodDescriptor , WritesDescriptor . class , fieldDescriptor ) ; writesDescriptor . setLineNumber ( lineNumber ) ; }
Add a writes relation between a method and a field .
16,177
AnnotationVisitor addAnnotation ( TypeCache . CachedType containingDescriptor , AnnotatedDescriptor annotatedDescriptor , String typeName ) { if ( typeName == null ) { return null ; } if ( jQASuppress . class . getName ( ) . equals ( typeName ) ) { JavaSuppressDescriptor javaSuppressDescriptor = scannerContext . getStore ( ) . addDescriptorType ( annotatedDescriptor , JavaSuppressDescriptor . class ) ; return new SuppressAnnotationVisitor ( javaSuppressDescriptor ) ; } TypeDescriptor type = resolveType ( typeName , containingDescriptor ) . getTypeDescriptor ( ) ; AnnotationValueDescriptor annotationDescriptor = scannerContext . getStore ( ) . create ( AnnotationValueDescriptor . class ) ; annotationDescriptor . setType ( type ) ; annotatedDescriptor . getAnnotatedBy ( ) . add ( annotationDescriptor ) ; return new AnnotationValueVisitor ( containingDescriptor , annotationDescriptor , this ) ; }
Add an annotation descriptor of the given type name to an annotated descriptor .
16,178
public CachedType get ( String fullQualifiedName ) { CachedType cachedType = lruCache . getIfPresent ( fullQualifiedName ) ; if ( cachedType != null ) { return cachedType ; } cachedType = softCache . getIfPresent ( fullQualifiedName ) ; if ( cachedType != null ) { lruCache . put ( fullQualifiedName , cachedType ) ; } return cachedType ; }
Find a type by its fully qualified named .
16,179
private VisibilityModifier getVisibility ( int flags ) { if ( hasFlag ( flags , Opcodes . ACC_PRIVATE ) ) { return VisibilityModifier . PRIVATE ; } else if ( hasFlag ( flags , Opcodes . ACC_PROTECTED ) ) { return VisibilityModifier . PROTECTED ; } else if ( hasFlag ( flags , Opcodes . ACC_PUBLIC ) ) { return VisibilityModifier . PUBLIC ; } else { return VisibilityModifier . DEFAULT ; } }
Returns the AccessModifier for the flag pattern .
16,180
private Class < ? extends ClassFileDescriptor > getJavaType ( int flags ) { if ( hasFlag ( flags , Opcodes . ACC_ANNOTATION ) ) { return AnnotationTypeDescriptor . class ; } else if ( hasFlag ( flags , Opcodes . ACC_ENUM ) ) { return EnumTypeDescriptor . class ; } else if ( hasFlag ( flags , Opcodes . ACC_INTERFACE ) ) { return InterfaceTypeDescriptor . class ; } return ClassTypeDescriptor . class ; }
Determine the types label to be applied to a class node .
16,181
public Token peek ( ) { if ( ! splitTokens . isEmpty ( ) ) { return splitTokens . peek ( ) ; } final var value = stringIterator . peek ( ) ; if ( argumentEscapeEncountered ) { return new ArgumentToken ( value ) ; } if ( Objects . equals ( value , argumentTerminator ) ) { return new ArgumentToken ( value ) ; } if ( argumentTerminator != null ) { return new ArgumentToken ( value ) ; } if ( isArgumentEscape ( value ) ) { argumentEscapeEncountered = true ; return peek ( ) ; } if ( isSwitch ( value ) ) { if ( isShortSwitchList ( value ) ) { var tokens = splitSwitchTokens ( value ) ; return tokens . get ( 0 ) ; } else { return new SwitchToken ( value . substring ( 2 ) , value ) ; } } else { return new ArgumentToken ( value ) ; } }
this is a mess - need to be cleaned up
16,182
public Token next ( ) { if ( ! splitTokens . isEmpty ( ) ) { return splitTokens . remove ( ) ; } var value = stringIterator . next ( ) ; if ( argumentEscapeEncountered ) { return new ArgumentToken ( value ) ; } if ( Objects . equals ( value , argumentTerminator ) ) { argumentTerminator = null ; return new ArgumentToken ( value ) ; } if ( argumentTerminator != null ) { return new ArgumentToken ( value ) ; } if ( isArgumentEscape ( value ) ) { argumentEscapeEncountered = true ; return next ( ) ; } if ( isSwitch ( value ) ) { if ( isShortSwitchList ( value ) ) { splitTokens . addAll ( splitSwitchTokens ( value ) ) ; return splitTokens . remove ( ) ; } else { return new SwitchToken ( value . substring ( 2 ) , value ) ; } } else { return new ArgumentToken ( value ) ; } }
this is a mess - needs to be cleaned up
16,183
public static < T > T parse ( Class < T > optionClass , String [ ] args , OptionStyle style ) throws IllegalAccessException , InstantiationException , InvocationTargetException { T spec ; try { spec = optionClass . getConstructor ( ) . newInstance ( ) ; } catch ( NoSuchMethodException noSuchMethodException ) { throw new RuntimeException ( noSuchMethodException ) ; } var optionSet = new OptionSet ( spec , MAIN_OPTIONS ) ; Tokenizer tokenizer ; if ( style == SIMPLE ) { tokenizer = new SimpleTokenizer ( new PeekIterator < > ( new ArrayIterator < > ( args ) ) ) ; } else { tokenizer = new LongOrCompactTokenizer ( new PeekIterator < > ( new ArrayIterator < > ( args ) ) ) ; } optionSet . consumeOptions ( tokenizer ) ; return spec ; }
A command line parser . It takes two arguments a class and an argument list and returns an instance of the class populated from the argument list based on the annotations in the class . The class must have a no argument constructor .
16,184
public void onReceive ( Context context , Intent intent ) { String messageId = intent . getStringExtra ( ID ) ; MFPPush . getInstance ( ) . changeStatus ( messageId , MFPPushNotificationStatus . DISMISSED ) ; }
This method is called when a notification is dimissed or cleared from the notification tray .
16,185
public boolean isPushSupported ( ) { String version = android . os . Build . VERSION . RELEASE . substring ( 0 , 3 ) ; return ( Double . valueOf ( version ) >= MIN_SUPPORTED_ANDRIOD_VERSION ) ; }
Checks whether push notification is supported .
16,186
public void registerDeviceWithUserId ( String userId , MFPPushResponseListener < String > listener ) { if ( isInitialized ) { this . registerResponseListener = listener ; setAppForeground ( true ) ; logger . info ( "MFPPush:register() - Retrieving senderId from MFPPush server." ) ; getSenderIdFromServerAndRegisterInBackground ( userId ) ; } else { logger . error ( "MFPPush:register() - An error occured while registering for MFPPush service. Push not initialized with call to initialize()" ) ; } }
Registers the device for Push notifications with the given alias and consumerId
16,187
public void subscribe ( final String tagName , final MFPPushResponseListener < String > listener ) { if ( isAbleToSubscribe ( ) ) { MFPPushUrlBuilder builder = new MFPPushUrlBuilder ( applicationId ) ; String path = builder . getSubscriptionsUrl ( ) ; logger . debug ( "MFPPush:subscribe() - The tag subscription path is: " + path ) ; MFPPushInvoker invoker = MFPPushInvoker . newInstance ( appContext , path , Request . POST , clientSecret ) ; invoker . setJSONRequestBody ( buildSubscription ( tagName ) ) ; invoker . setResponseListener ( new ResponseListener ( ) { public void onSuccess ( Response response ) { logger . info ( "MFPPush:subscribe() - Tag subscription successfully created. The response is: " + response . toString ( ) ) ; listener . onSuccess ( tagName ) ; } public void onFailure ( Response response , Throwable throwable , JSONObject jsonObject ) { logger . error ( "MFPPush: Error while subscribing to tags" ) ; listener . onFailure ( getException ( response , throwable , jsonObject ) ) ; } } ) ; invoker . execute ( ) ; } }
Subscribes to the given tag
16,188
public void unsubscribe ( final String tagName , final MFPPushResponseListener < String > listener ) { if ( isAbleToSubscribe ( ) ) { MFPPushUrlBuilder builder = new MFPPushUrlBuilder ( applicationId ) ; String path = builder . getSubscriptionsUrl ( deviceId , tagName ) ; if ( path == DEVICE_ID_NULL ) { listener . onFailure ( new MFPPushException ( "The device is not registered yet. Please register device before calling subscriptions API" ) ) ; return ; } logger . debug ( "MFPPush:unsubscribe() - The tag unsubscription path is: " + path ) ; MFPPushInvoker invoker = MFPPushInvoker . newInstance ( appContext , path , Request . DELETE , clientSecret ) ; invoker . setResponseListener ( new ResponseListener ( ) { public void onSuccess ( Response response ) { logger . info ( "MFPPush:unsubscribe() - Tag unsubscription successful. The response is: " + response . toString ( ) ) ; listener . onSuccess ( tagName ) ; } public void onFailure ( Response response , Throwable throwable , JSONObject jsonObject ) { logger . error ( "MFPPush: Error while Unsubscribing to tags" ) ; listener . onFailure ( getException ( response , throwable , jsonObject ) ) ; } } ) ; invoker . execute ( ) ; } }
Unsubscribes to the given tag
16,189
public void unregister ( final MFPPushResponseListener < String > listener ) { MFPPushUrlBuilder builder = new MFPPushUrlBuilder ( applicationId ) ; if ( this . deviceId == null ) { this . deviceId = MFPPushUtils . getContentFromSharedPreferences ( appContext , applicationId + DEVICE_ID ) ; } String path = builder . getUnregisterUrl ( deviceId ) ; logger . debug ( "MFPPush:unregister() - The device unregister url is: " + path ) ; MFPPushInvoker invoker = MFPPushInvoker . newInstance ( appContext , path , Request . DELETE , clientSecret ) ; invoker . setResponseListener ( new ResponseListener ( ) { public void onSuccess ( Response response ) { logger . info ( "MFPPush:unregister() - Successfully unregistered device. Response is: " + response . toString ( ) ) ; isTokenUpdatedOnServer = false ; listener . onSuccess ( "Device Successfully unregistered from receiving push notifications." ) ; } public void onFailure ( Response response , Throwable throwable , JSONObject jsonObject ) { logger . error ( "MFPPush: Error while unregistered device" ) ; listener . onFailure ( getException ( response , throwable , jsonObject ) ) ; } } ) ; invoker . execute ( ) ; }
Unregister the device from Push Server
16,190
public void getTags ( final MFPPushResponseListener < List < String > > listener ) { MFPPushUrlBuilder builder = new MFPPushUrlBuilder ( applicationId ) ; String path = builder . getTagsUrl ( ) ; MFPPushInvoker invoker = MFPPushInvoker . newInstance ( appContext , path , Request . GET , clientSecret ) ; invoker . setResponseListener ( new ResponseListener ( ) { public void onSuccess ( Response response ) { logger . info ( "MFPPush:getTags() - Successfully retreived tags. The response is: " + response . toString ( ) ) ; List < String > tagNames = new ArrayList < String > ( ) ; try { String responseText = response . getResponseText ( ) ; JSONArray tags = ( JSONArray ) ( new JSONObject ( responseText ) ) . get ( TAGS ) ; Log . d ( "JSONArray of tags is: " , tags . toString ( ) ) ; int tagsCnt = tags . length ( ) ; for ( int tagsIdx = 0 ; tagsIdx < tagsCnt ; tagsIdx ++ ) { Log . d ( "Adding tag: " , tags . getJSONObject ( tagsIdx ) . toString ( ) ) ; tagNames . add ( tags . getJSONObject ( tagsIdx ) . getString ( NAME ) ) ; } listener . onSuccess ( tagNames ) ; } catch ( JSONException e ) { logger . error ( "MFPPush: getTags() - Error while retrieving tags. Error is: " + e . getMessage ( ) ) ; listener . onFailure ( new MFPPushException ( e ) ) ; } } public void onFailure ( Response response , Throwable throwable , JSONObject jsonObject ) { logger . error ( "MFPPush: Error while getting tags" ) ; listener . onFailure ( getException ( response , throwable , jsonObject ) ) ; } } ) ; invoker . execute ( ) ; }
Get the list of tags
16,191
public void getSubscriptions ( final MFPPushResponseListener < List < String > > listener ) { MFPPushUrlBuilder builder = new MFPPushUrlBuilder ( applicationId ) ; String path = builder . getSubscriptionsUrl ( deviceId , null ) ; if ( path == DEVICE_ID_NULL ) { listener . onFailure ( new MFPPushException ( "The device is not registered yet. Please register device before calling subscriptions API" ) ) ; return ; } MFPPushInvoker invoker = MFPPushInvoker . newInstance ( appContext , path , Request . GET , clientSecret ) ; invoker . setResponseListener ( new ResponseListener ( ) { public void onSuccess ( Response response ) { List < String > tagNames = new ArrayList < String > ( ) ; try { JSONArray tags = ( JSONArray ) ( new JSONObject ( response . getResponseText ( ) ) ) . get ( SUBSCRIPTIONS ) ; int tagsCnt = tags . length ( ) ; for ( int tagsIdx = 0 ; tagsIdx < tagsCnt ; tagsIdx ++ ) { tagNames . add ( tags . getJSONObject ( tagsIdx ) . getString ( TAG_NAME ) ) ; } listener . onSuccess ( tagNames ) ; } catch ( JSONException e ) { logger . error ( "MFPPush: getSubscriptions() - Failure while getting subscriptions. Failure response is: " + e . getMessage ( ) ) ; listener . onFailure ( new MFPPushException ( e ) ) ; } } public void onFailure ( Response response , Throwable throwable , JSONObject jsonObject ) { logger . error ( "MFPPush: Error while getSubscriptions" ) ; listener . onFailure ( getException ( response , throwable , jsonObject ) ) ; } } ) ; invoker . execute ( ) ; }
Get the list of tags subscribed to
16,192
private void setNotificationOptions ( Context context , MFPPushNotificationOptions options ) { if ( this . appContext == null ) { this . appContext = context . getApplicationContext ( ) ; } this . options = options ; Gson gson = new Gson ( ) ; String json = gson . toJson ( options ) ; SharedPreferences sharedPreferences = appContext . getSharedPreferences ( PREFS_NAME , Context . MODE_PRIVATE ) ; MFPPushUtils . storeContentInSharedPreferences ( sharedPreferences , MFPPush . PREFS_MESSAGES_OPTIONS , json ) ; }
Set the default push notification options for notifications .
16,193
public void setNotificationStatusListener ( MFPPushNotificationStatusListener statusListener ) { this . statusListener = statusListener ; synchronized ( pendingStatus ) { if ( ! pendingStatus . isEmpty ( ) ) { for ( Map . Entry < String , MFPPushNotificationStatus > entry : pendingStatus . entrySet ( ) ) { changeStatus ( entry . getKey ( ) , entry . getValue ( ) ) ; } pendingStatus . clear ( ) ; } } }
Set the listener class to receive the notification status changes .
16,194
public boolean getMessagesFromSharedPreferences ( int notificationId ) { boolean gotMessages = false ; SharedPreferences sharedPreferences = appContext . getSharedPreferences ( PREFS_NAME , Context . MODE_PRIVATE ) ; int countOfStoredMessages = sharedPreferences . getInt ( MFPPush . PREFS_NOTIFICATION_COUNT , 0 ) ; if ( countOfStoredMessages > 0 ) { String key = null ; try { Map < String , ? > allEntriesFromSharedPreferences = sharedPreferences . getAll ( ) ; Map < String , String > notificationEntries = new HashMap < String , String > ( ) ; for ( Map . Entry < String , ? > entry : allEntriesFromSharedPreferences . entrySet ( ) ) { String rKey = entry . getKey ( ) ; if ( entry . getKey ( ) . startsWith ( PREFS_NOTIFICATION_MSG ) ) { notificationEntries . put ( rKey , entry . getValue ( ) . toString ( ) ) ; } } for ( Map . Entry < String , String > entry : notificationEntries . entrySet ( ) ) { String nKey = entry . getKey ( ) ; key = nKey ; String msg = sharedPreferences . getString ( nKey , null ) ; if ( msg != null ) { gotMessages = true ; logger . debug ( "MFPPush:getMessagesFromSharedPreferences() - Messages retrieved from shared preferences." ) ; MFPInternalPushMessage pushMessage = new MFPInternalPushMessage ( new JSONObject ( msg ) ) ; if ( notificationId != 0 ) { if ( notificationId == pushMessage . getNotificationId ( ) ) { isFromNotificationBar = true ; messageFromBar = pushMessage ; MFPPushUtils . removeContentFromSharedPreferences ( sharedPreferences , nKey ) ; MFPPushUtils . storeContentInSharedPreferences ( sharedPreferences , MFPPush . PREFS_NOTIFICATION_COUNT , countOfStoredMessages - 1 ) ; break ; } } else { synchronized ( pending ) { pending . add ( pushMessage ) ; } MFPPushUtils . removeContentFromSharedPreferences ( sharedPreferences , nKey ) ; } } } } catch ( JSONException e ) { MFPPushUtils . removeContentFromSharedPreferences ( sharedPreferences , key ) ; } if ( notificationId == 0 ) { MFPPushUtils . storeContentInSharedPreferences ( sharedPreferences , MFPPush . PREFS_NOTIFICATION_COUNT , 0 ) ; } } return gotMessages ; }
Based on the PREFS_NOTIFICATION_COUNT value fetch all the stored notifications in the same order from the shared preferences and save it onto the list . This method will ensure that the notifications are sent to the Application in the same order in which they arrived .
16,195
public static void removeContentFromSharedPreferences ( SharedPreferences sharedPreferences , String key ) { Editor editor = sharedPreferences . edit ( ) ; String msg = sharedPreferences . getString ( key , null ) ; editor . remove ( key ) ; editor . commit ( ) ; }
Remove the key from SharedPreferences
16,196
public static void storeContentInSharedPreferences ( SharedPreferences sharedPreferences , String key , String value ) { Editor editor = sharedPreferences . edit ( ) ; editor . putString ( key , value ) ; editor . commit ( ) ; }
Store the key value in SharedPreferences
16,197
public void setText ( CharSequence text , TextView . BufferType type ) { mEditText . setText ( text , type ) ; }
Sets the EditText s text with label animation
16,198
public String [ ] getIds ( ) { String [ ] ids = new String [ recomms . length ] ; for ( int i = 0 ; i < recomms . length ; i ++ ) ids [ i ] = recomms [ i ] . getId ( ) ; return ids ; }
Get ids of recommended entities
16,199
public < P > P getListener ( Class < P > type ) { if ( mListener != null ) { return type . cast ( mListener ) ; } return null ; }
Gets the listener object that was passed into the Adapter through its constructor and cast it to a given type .