idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
16,100 | @ 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 . | 92 | 5 |
16,101 | 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 . | 79 | 35 |
16,102 | 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 . | 132 | 17 |
16,103 | @ 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 . | 97 | 22 |
16,104 | @ 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 . | 74 | 17 |
16,105 | 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 . | 130 | 14 |
16,106 | 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 . | 106 | 9 |
16,107 | 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 . | 238 | 8 |
16,108 | @ 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 . | 92 | 19 |
16,109 | @ 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 . | 70 | 16 |
16,110 | 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 . | 49 | 35 |
16,111 | @ 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 . | 88 | 14 |
16,112 | public Team updateTeam ( final Team transientTeam ) { final Team team = getObjectByUuid ( Team . class , transientTeam . getUuid ( ) ) ; pm . currentTransaction ( ) . begin ( ) ; team . setName ( transientTeam . getName ( ) ) ; //todo assign permissions pm . currentTransaction ( ) . commit ( ) ; return pm . getObjectById ( Team . class , team . getId ( ) ) ; } | Updates the specified Team . | 96 | 6 |
16,113 | 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 . | 144 | 11 |
16,114 | 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 . | 137 | 13 |
16,115 | 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 . | 93 | 7 |
16,116 | @ 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 . | 87 | 10 |
16,117 | @ 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 . | 66 | 12 |
16,118 | 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 . | 159 | 28 |
16,119 | 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 . | 188 | 16 |
16,120 | 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 . | 76 | 14 |
16,121 | 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 . | 122 | 16 |
16,122 | @ 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 . | 121 | 20 |
16,123 | @ 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 . | 82 | 18 |
16,124 | @ 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 . | 84 | 18 |
16,125 | 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 . | 116 | 11 |
16,126 | 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 . | 129 | 7 |
16,127 | @ 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 . | 106 | 13 |
16,128 | @ 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 . | 72 | 8 |
16,129 | 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 . | 153 | 7 |
16,130 | 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 . | 200 | 9 |
16,131 | @ SuppressWarnings ( "unchecked" ) public < T > List < T > getList ( Class < T > clazz ) { return ( List < T > ) objects ; } | Retrieves a List of objects from the result . | 41 | 11 |
16,132 | @ SuppressWarnings ( "unchecked" ) public < T > Set < T > getSet ( Class < T > clazz ) { return ( Set < T > ) objects ; } | Retrieves a Set of objects from the result . | 41 | 11 |
16,133 | public void setObjects ( Object object ) { if ( Collection . class . isAssignableFrom ( object . getClass ( ) ) ) { this . objects = ( Collection ) object ; } } | Specifies a Collection of objects from the result . | 42 | 10 |
16,134 | 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 . | 139 | 9 |
16,135 | 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 . | 168 | 9 |
16,136 | 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 . | 144 | 5 |
16,137 | 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 . | 100 | 31 |
16,138 | 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 . | 124 | 19 |
16,139 | 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 ; //The existing thread will die out on its own, but not before attempting to convert the file into WAV format. } | Stops the audio recording if it is in a paused or recording state . Does nothing if the recorder is already stopped . | 136 | 24 |
16,140 | 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 . | 124 | 14 |
16,141 | 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 . | 57 | 13 |
16,142 | 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 . | 75 | 7 |
16,143 | 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 . | 53 | 11 |
16,144 | 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 . | 196 | 5 |
16,145 | 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 . | 87 | 5 |
16,146 | 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 . | 154 | 12 |
16,147 | 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 . | 86 | 9 |
16,148 | 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 . | 82 | 11 |
16,149 | 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 . | 82 | 11 |
16,150 | 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 . | 243 | 15 |
16,151 | 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 . | 91 | 9 |
16,152 | 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 . | 113 | 10 |
16,153 | 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 . | 115 | 14 |
16,154 | 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 | 196 | 10 |
16,155 | 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 | 205 | 10 |
16,156 | 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 . | 188 | 44 |
16,157 | @ Override 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 . | 58 | 18 |
16,158 | 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 . | 54 | 8 |
16,159 | 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 | 124 | 14 |
16,160 | 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 ( ) { @ Override public void onSuccess ( Response response ) { //Subscription successfully created. logger . info ( "MFPPush:subscribe() - Tag subscription successfully created. The response is: " + response . toString ( ) ) ; listener . onSuccess ( tagName ) ; } @ Override public void onFailure ( Response response , Throwable throwable , JSONObject jsonObject ) { //Error while subscribing to tags. logger . error ( "MFPPush: Error while subscribing to tags" ) ; listener . onFailure ( getException ( response , throwable , jsonObject ) ) ; } } ) ; invoker . execute ( ) ; } } | Subscribes to the given tag | 284 | 7 |
16,161 | 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 ( ) { @ Override public void onSuccess ( Response response ) { logger . info ( "MFPPush:unsubscribe() - Tag unsubscription successful. The response is: " + response . toString ( ) ) ; listener . onSuccess ( tagName ) ; } @ Override public void onFailure ( Response response , Throwable throwable , JSONObject jsonObject ) { //Error while Unsubscribing to tags. logger . error ( "MFPPush: Error while Unsubscribing to tags" ) ; listener . onFailure ( getException ( response , throwable , jsonObject ) ) ; } } ) ; invoker . execute ( ) ; } } | Unsubscribes to the given tag | 323 | 8 |
16,162 | 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 ( ) { @ Override 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." ) ; } @ Override 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 | 301 | 7 |
16,163 | 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 ( ) { @ Override 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 ) ) ; } } @ Override public void onFailure ( Response response , Throwable throwable , JSONObject jsonObject ) { //Error while getting tags. logger . error ( "MFPPush: Error while getting tags" ) ; listener . onFailure ( getException ( response , throwable , jsonObject ) ) ; } } ) ; invoker . execute ( ) ; } | Get the list of tags | 437 | 5 |
16,164 | 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 ( ) { @ Override 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 ) ) ; } } @ Override public void onFailure ( Response response , Throwable throwable , JSONObject jsonObject ) { //Error while getSubscriptions. logger . error ( "MFPPush: Error while getSubscriptions" ) ; listener . onFailure ( getException ( response , throwable , jsonObject ) ) ; } } ) ; invoker . execute ( ) ; } | Get the list of tags subscribed to | 413 | 7 |
16,165 | 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 . | 142 | 9 |
16,166 | 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 . | 100 | 11 |
16,167 | 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 . | 582 | 54 |
16,168 | 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 | 62 | 7 |
16,169 | 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 | 53 | 8 |
16,170 | public void setText ( CharSequence text , TextView . BufferType type ) { mEditText . setText ( text , type ) ; } | Sets the EditText s text with label animation | 31 | 10 |
16,171 | 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 | 67 | 6 |
16,172 | @ Nullable 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 . | 40 | 22 |
16,173 | @ Override public void onSetListeners ( ) { imageViewPerson . setOnClickListener ( new View . OnClickListener ( ) { @ Override public void onClick ( View v ) { PersonHolderListener listener = getListener ( PersonHolderListener . class ) ; if ( listener != null ) { listener . onPersonImageClicked ( getItem ( ) ) ; } } } ) ; } | Optionally override onSetListeners to add listeners to the views . | 86 | 14 |
16,174 | public static List < Person > getMockPeopleSet1 ( ) { List < Person > listPeople = new ArrayList < Person > ( ) ; listPeople . add ( new Person ( "Henry Blair" , "07123456789" , R . drawable . male1 ) ) ; listPeople . add ( new Person ( "Jenny Curtis" , "07123456789" , R . drawable . female1 ) ) ; listPeople . add ( new Person ( "Vincent Green" , "07123456789" , R . drawable . male2 ) ) ; listPeople . add ( new Person ( "Ada Underwood" , "07123456789" , R . drawable . female2 ) ) ; listPeople . add ( new Person ( "Daniel Erickson" , "07123456789" , R . drawable . male3 ) ) ; listPeople . add ( new Person ( "Maria Ramsey" , "07123456789" , R . drawable . female3 ) ) ; listPeople . add ( new Person ( "Rosemary Munoz" , "07123456789" , R . drawable . female4 ) ) ; listPeople . add ( new Person ( "John Singleton" , "07123456789" , R . drawable . male4 ) ) ; listPeople . add ( new Person ( "Lorena Bowen" , "07123456789" , R . drawable . female5 ) ) ; listPeople . add ( new Person ( "Kevin Stokes" , "07123456789" , R . drawable . male5 ) ) ; listPeople . add ( new Person ( "Johnny Sanders" , "07123456789" , R . drawable . male6 ) ) ; listPeople . add ( new Person ( "Jim Ramirez" , "07123456789" , R . drawable . male7 ) ) ; listPeople . add ( new Person ( "Cassandra Hunter" , "07123456789" , R . drawable . female6 ) ) ; listPeople . add ( new Person ( "Viola Guerrero" , "07123456789" , R . drawable . female7 ) ) ; return listPeople ; } | Returns a mock List of Person objects | 483 | 7 |
16,175 | public static ItemViewHolder createViewHolder ( View view , Class < ? extends ItemViewHolder > itemViewHolderClass ) { try { Constructor < ? extends ItemViewHolder > constructor = itemViewHolderClass . getConstructor ( View . class ) ; return constructor . newInstance ( view ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( e ) ; } catch ( NoSuchMethodException e ) { throw new RuntimeException ( "Unable to find a public constructor that takes an argument View in " + itemViewHolderClass . getSimpleName ( ) , e ) ; } catch ( InvocationTargetException e ) { throw new RuntimeException ( e . getTargetException ( ) ) ; } catch ( InstantiationException e ) { throw new RuntimeException ( "Unable to instantiate " + itemViewHolderClass . getSimpleName ( ) , e ) ; } } | Create a new ItemViewHolder using Java reflection | 194 | 10 |
16,176 | public static Integer parseItemLayoutId ( Class < ? extends ItemViewHolder > itemViewHolderClass ) { Integer itemLayoutId = ClassAnnotationParser . getLayoutId ( itemViewHolderClass ) ; if ( itemLayoutId == null ) { throw new LayoutIdMissingException ( ) ; } return itemLayoutId ; } | Parses the layout ID annotation form the itemViewHolderClass | 70 | 14 |
16,177 | @ Nonnull public static final String getSingletonScopeKey ( @ Nonnull final Class < ? extends AbstractSingleton > aClass ) { ValueEnforcer . notNull ( aClass , "Class" ) ; // Preallocate some bytes return new StringBuilder ( DEFAULT_KEY_LENGTH ) . append ( "singleton." ) . append ( aClass . getName ( ) ) . toString ( ) ; } | Create the key which is used to reference the object within the scope . | 89 | 14 |
16,178 | public static final boolean isSingletonInstantiated ( @ Nullable final IScope aScope , @ Nonnull final Class < ? extends AbstractSingleton > aClass ) { return getSingletonIfInstantiated ( aScope , aClass ) != null ; } | Check if a singleton is already instantiated inside a scope | 54 | 12 |
16,179 | @ Nonnull public static final < T extends AbstractSingleton > T getSingleton ( @ Nonnull final IScope aScope , @ Nonnull final Class < T > aClass ) { ValueEnforcer . notNull ( aScope , "aScope" ) ; ValueEnforcer . notNull ( aClass , "Class" ) ; final String sSingletonScopeKey = getSingletonScopeKey ( aClass ) ; // check if already contained in passed scope T aInstance = s_aRWLock . readLocked ( ( ) -> aScope . attrs ( ) . getCastedValue ( sSingletonScopeKey ) ) ; if ( aInstance == null || aInstance . isInInstantiation ( ) ) { // Not yet present or just in instantiation // Safe instantiation check in write lock s_aRWLock . writeLock ( ) . lock ( ) ; try { // Check again in write lock aInstance = aScope . attrs ( ) . getCastedValue ( sSingletonScopeKey ) ; if ( aInstance == null ) { // Main instantiation aInstance = _instantiateSingleton ( aClass , aScope ) ; // Set in scope so that recursive calls to the same singleton are // caught appropriately aScope . attrs ( ) . putIn ( sSingletonScopeKey , aInstance ) ; // Start the initialization process // Do this after the instance was added to the scope aInstance . setInInstantiation ( true ) ; try { // Invoke callback method aInstance . onAfterInstantiation ( aScope ) ; // Set "instantiated" only if no exception was thrown aInstance . setInstantiated ( true ) ; } finally { // Ensure field is reset even in case of an exception aInstance . setInInstantiation ( false ) ; } // And some statistics s_aStatsCounterInstantiate . increment ( sSingletonScopeKey ) ; } else { // May not be instantiated if this method is called from the same // thread as the original instantiation } // We have the instance - maybe from re-querying the scope, maybe from // instantiation } finally { s_aRWLock . writeLock ( ) . unlock ( ) ; } } // This happens too often in practice, therefore this is disabled if ( SingletonHelper . isDebugConsistency ( ) ) { // Just a small note in case we're returning an unusable object if ( ! aInstance . isUsableObject ( ) ) if ( LOGGER . isWarnEnabled ( ) ) LOGGER . warn ( "Singleton '" + aClass . getName ( ) + "' is not usable - please check your calling order: " + aInstance . toString ( ) , SingletonHelper . getDebugStackTrace ( ) ) ; } return aInstance ; } | Get the singleton object in the passed scope using the passed class . If the singleton is not yet instantiated a new instance is created . | 589 | 29 |
16,180 | @ Nonnull @ ReturnsMutableCopy public static final < T extends AbstractSingleton > ICommonsList < T > getAllSingletons ( @ Nullable final IScope aScope , @ Nonnull final Class < T > aDesiredClass ) { ValueEnforcer . notNull ( aDesiredClass , "DesiredClass" ) ; final ICommonsList < T > ret = new CommonsArrayList <> ( ) ; if ( aScope != null ) for ( final Object aScopeValue : aScope . attrs ( ) . values ( ) ) if ( aScopeValue != null && aDesiredClass . isAssignableFrom ( aScopeValue . getClass ( ) ) ) ret . add ( aDesiredClass . cast ( aScopeValue ) ) ; return ret ; } | Get all singleton objects registered in the respective sub - class of this class . | 170 | 16 |
16,181 | @ Nonnull public final ITEMTYPE createChildItem ( @ Nullable final DATATYPE aData ) { // create new item final ITEMTYPE aItem = m_aFactory . create ( thisAsT ( ) ) ; if ( aItem == null ) throw new IllegalStateException ( "null item created!" ) ; aItem . setData ( aData ) ; internalAddChild ( aItem ) ; return aItem ; } | Add a child item to this item . | 93 | 8 |
16,182 | @ Nonnull public static < ELEMENTTYPE > Iterator < ELEMENTTYPE > getCombinedIterator ( @ Nullable final Iterator < ? extends ELEMENTTYPE > aIter1 , @ Nullable final Iterator < ? extends ELEMENTTYPE > aIter2 ) { return new CombinedIterator <> ( aIter1 , aIter2 ) ; } | Get a merged iterator of both iterators . The first iterator is iterated first the second one afterwards . | 74 | 21 |
16,183 | @ Nonnull public static < ELEMENTTYPE > Enumeration < ELEMENTTYPE > getEnumeration ( @ Nullable final Iterator < ELEMENTTYPE > aIter ) { if ( aIter == null ) return new EmptyEnumeration <> ( ) ; return new EnumerationFromIterator <> ( aIter ) ; } | Get an Enumeration object based on an Iterator object . | 71 | 13 |
16,184 | @ Nonnull public static < KEYTYPE , VALUETYPE > Enumeration < Map . Entry < KEYTYPE , VALUETYPE > > getEnumeration ( @ Nullable final Map < KEYTYPE , VALUETYPE > aMap ) { if ( aMap == null ) return new EmptyEnumeration <> ( ) ; return getEnumeration ( aMap . entrySet ( ) ) ; } | Get an Enumeration object based on a Map object . | 91 | 12 |
16,185 | @ Nonnull public EChange addAllFrom ( @ Nonnull final MapBasedXPathFunctionResolver aOther , final boolean bOverwrite ) { ValueEnforcer . notNull ( aOther , "Other" ) ; EChange eChange = EChange . UNCHANGED ; for ( final Map . Entry < XPathFunctionKey , XPathFunction > aEntry : aOther . m_aMap . entrySet ( ) ) if ( bOverwrite || ! m_aMap . containsKey ( aEntry . getKey ( ) ) ) { m_aMap . put ( aEntry . getKey ( ) , aEntry . getValue ( ) ) ; eChange = EChange . CHANGED ; } return eChange ; } | Add all functions from the other function resolver into this resolver . | 156 | 14 |
16,186 | @ Nonnull public EChange removeFunctionsWithName ( @ Nullable final QName aName ) { EChange eChange = EChange . UNCHANGED ; if ( aName != null ) { // Make a copy of the key set to allow for inline modification for ( final XPathFunctionKey aKey : m_aMap . copyOfKeySet ( ) ) if ( aKey . getFunctionName ( ) . equals ( aName ) ) eChange = eChange . or ( removeFunction ( aKey ) ) ; } return eChange ; } | Remove all functions with the same name . This can be helpful when the same function is registered for multiple parameters . | 117 | 22 |
16,187 | @ Nonnull public static ESuccess parseJson ( @ Nonnull @ WillClose final Reader aReader , @ Nonnull final IJsonParserHandler aParserHandler ) { return parseJson ( aReader , aParserHandler , ( IJsonParserCustomizeCallback ) null , ( IJsonParseExceptionCallback ) null ) ; } | Simple JSON parse method taking only the most basic parameters . | 72 | 11 |
16,188 | @ Nonnull private static EValidity _validateJson ( @ Nonnull @ WillClose final Reader aReader ) { // Force silent parsing :) final ESuccess eSuccess = parseJson ( aReader , new DoNothingJsonParserHandler ( ) , ( IJsonParserCustomizeCallback ) null , ex -> { } ) ; return EValidity . valueOf ( eSuccess . isSuccess ( ) ) ; } | Validate a JSON without building the tree in memory . | 89 | 11 |
16,189 | @ Nullable public static IJson readJson ( @ Nonnull @ WillClose final Reader aReader , @ Nullable final IJsonParserCustomizeCallback aCustomizeCallback , @ Nullable final IJsonParseExceptionCallback aCustomExceptionCallback ) { final CollectingJsonParserHandler aHandler = new CollectingJsonParserHandler ( ) ; if ( parseJson ( aReader , aHandler , aCustomizeCallback , aCustomExceptionCallback ) . isFailure ( ) ) return null ; return aHandler . getJson ( ) ; } | Main reading of the JSON | 118 | 5 |
16,190 | public static boolean getBooleanValue ( @ Nullable final Boolean aObj , final boolean bDefault ) { return aObj == null ? bDefault : aObj . booleanValue ( ) ; } | Get the primitive value of the passed object value . | 40 | 10 |
16,191 | @ Nonnull public static String urlDecode ( @ Nonnull final String sValue , @ Nonnull final Charset aCharset ) { ValueEnforcer . notNull ( sValue , "Value" ) ; ValueEnforcer . notNull ( aCharset , "Charset" ) ; boolean bNeedToChange = false ; final int nLen = sValue . length ( ) ; final StringBuilder aSB = new StringBuilder ( nLen ) ; int nIndex = 0 ; byte [ ] aBytes = null ; while ( nIndex < nLen ) { char c = sValue . charAt ( nIndex ) ; switch ( c ) { case ' ' : aSB . append ( ' ' ) ; nIndex ++ ; bNeedToChange = true ; break ; case ' ' : /* * Starting with this instance of %, process all consecutive * substrings of the form %xy. Each substring %xy will yield a byte. * Convert all consecutive bytes obtained this way to whatever * character(s) they represent in the provided encoding. */ try { // (numChars-i)/3 is an upper bound for the number // of remaining bytes if ( aBytes == null ) aBytes = new byte [ ( nLen - nIndex ) / 3 ] ; int nPos = 0 ; while ( ( nIndex + 2 ) < nLen && c == ' ' ) { final int nValue = Integer . parseInt ( sValue . substring ( nIndex + 1 , nIndex + 3 ) , 16 ) ; if ( nValue < 0 ) throw new IllegalArgumentException ( "URLDecoder: Illegal hex characters in escape (%) pattern - negative value" ) ; aBytes [ nPos ++ ] = ( byte ) nValue ; nIndex += 3 ; if ( nIndex < nLen ) c = sValue . charAt ( nIndex ) ; } // A trailing, incomplete byte encoding such as // "%x" will cause an exception to be thrown if ( nIndex < nLen && c == ' ' ) throw new IllegalArgumentException ( "URLDecoder: Incomplete trailing escape (%) pattern" ) ; aSB . append ( StringHelper . decodeBytesToChars ( aBytes , 0 , nPos , aCharset ) ) ; } catch ( final NumberFormatException e ) { throw new IllegalArgumentException ( "URLDecoder: Illegal hex characters in escape (%) pattern - " + e . getMessage ( ) ) ; } bNeedToChange = true ; break ; default : aSB . append ( c ) ; nIndex ++ ; break ; } } return bNeedToChange ? aSB . toString ( ) : sValue ; } | URL - decode the passed value automatically handling charset issues . The implementation is ripped from URLDecoder but does not throw an UnsupportedEncodingException for nothing . | 565 | 33 |
16,192 | @ Nonnull public static String urlEncode ( @ Nonnull final String sValue , @ Nonnull final Charset aCharset ) { ValueEnforcer . notNull ( sValue , "Value" ) ; ValueEnforcer . notNull ( aCharset , "Charset" ) ; NonBlockingCharArrayWriter aCAW = null ; try { final int nLen = sValue . length ( ) ; boolean bChanged = false ; final StringBuilder aSB = new StringBuilder ( nLen * 2 ) ; final char [ ] aSrcChars = sValue . toCharArray ( ) ; int nIndex = 0 ; while ( nIndex < nLen ) { char c = aSrcChars [ nIndex ] ; if ( NO_URL_ENCODE . get ( c ) ) { if ( c == ' ' ) { c = ' ' ; bChanged = true ; } aSB . append ( c ) ; nIndex ++ ; } else { // convert to external encoding before hex conversion if ( aCAW == null ) aCAW = new NonBlockingCharArrayWriter ( ) ; else aCAW . reset ( ) ; while ( true ) { aCAW . write ( c ) ; /* * If this character represents the start of a Unicode surrogate * pair, then pass in two characters. It's not clear what should be * done if a bytes reserved in the surrogate pairs range occurs * outside of a legal surrogate pair. For now, just treat it as if * it were any other character. */ if ( Character . isHighSurrogate ( c ) && nIndex + 1 < nLen ) { final char d = aSrcChars [ nIndex + 1 ] ; if ( Character . isLowSurrogate ( d ) ) { aCAW . write ( d ) ; nIndex ++ ; } } nIndex ++ ; if ( nIndex >= nLen ) break ; // Try next char c = aSrcChars [ nIndex ] ; if ( NO_URL_ENCODE . get ( c ) ) break ; } final byte [ ] aEncodedBytes = aCAW . toByteArray ( aCharset ) ; for ( final byte nEncByte : aEncodedBytes ) { aSB . append ( ' ' ) . append ( URL_ENCODE_CHARS [ ( nEncByte >> 4 ) & 0xF ] ) . append ( URL_ENCODE_CHARS [ nEncByte & 0xF ] ) ; } bChanged = true ; } } return bChanged ? aSB . toString ( ) : sValue ; } finally { StreamHelper . close ( aCAW ) ; } } | URL - encode the passed value automatically handling charset issues . This is a ripped optimized version of URLEncoder . encode but without the UnsupportedEncodingException . | 568 | 34 |
16,193 | @ Nullable public static String getCleanURLPartWithoutUmlauts ( @ Nullable final String sURLPart ) { if ( s_aCleanURLOld == null ) _initCleanURL ( ) ; final char [ ] ret = StringHelper . replaceMultiple ( sURLPart , s_aCleanURLOld , s_aCleanURLNew ) ; return new String ( ret ) ; } | Clean an URL part from nasty Umlauts . This mapping needs extension! | 82 | 15 |
16,194 | @ Nonnull public static ISimpleURL getAsURLData ( @ Nonnull final String sHref , @ Nullable final IDecoder < String , String > aParameterDecoder ) { ValueEnforcer . notNull ( sHref , "Href" ) ; final String sRealHref = sHref . trim ( ) ; // Is it a protocol that does not allow for query parameters? final IURLProtocol eProtocol = URLProtocolRegistry . getInstance ( ) . getProtocol ( sRealHref ) ; if ( eProtocol != null && ! eProtocol . allowsForQueryParameters ( ) ) return new URLData ( sRealHref , null , null ) ; if ( GlobalDebug . isDebugMode ( ) ) if ( eProtocol != null ) try { new URL ( sRealHref ) ; } catch ( final MalformedURLException ex ) { if ( LOGGER . isWarnEnabled ( ) ) LOGGER . warn ( "java.net.URL claims URL '" + sRealHref + "' to be invalid: " + ex . getMessage ( ) ) ; } String sPath ; URLParameterList aParams = null ; String sAnchor ; // First get the anchor out String sRemainingHref = sRealHref ; final int nIndexAnchor = sRemainingHref . indexOf ( HASH ) ; if ( nIndexAnchor >= 0 ) { // Extract anchor sAnchor = sRemainingHref . substring ( nIndexAnchor + 1 ) . trim ( ) ; sRemainingHref = sRemainingHref . substring ( 0 , nIndexAnchor ) . trim ( ) ; } else sAnchor = null ; // Find parameters final int nQuestionIndex = sRemainingHref . indexOf ( QUESTIONMARK ) ; if ( nQuestionIndex >= 0 ) { // Use everything after the '?' final String sQueryString = sRemainingHref . substring ( nQuestionIndex + 1 ) . trim ( ) ; // Maybe empty, if the URL ends with a '?' if ( StringHelper . hasText ( sQueryString ) ) aParams = getParsedQueryParameters ( sQueryString , aParameterDecoder ) ; sPath = sRemainingHref . substring ( 0 , nQuestionIndex ) . trim ( ) ; } else sPath = sRemainingHref ; return new URLData ( sPath , aParams , sAnchor ) ; } | Parses the passed URL into a structured form | 544 | 10 |
16,195 | public void iterateAllRegisteredMicroTypeConverters ( @ Nonnull final IMicroTypeConverterCallback aCallback ) { // Create a static copy of the map (HashMap not weak!) final ICommonsMap < Class < ? > , IMicroTypeConverter < ? > > aCopy = m_aRWLock . readLocked ( m_aMap :: getClone ) ; // And iterate the copy for ( final Map . Entry < Class < ? > , IMicroTypeConverter < ? > > aEntry : aCopy . entrySet ( ) ) if ( aCallback . call ( aEntry . getKey ( ) , aEntry . getValue ( ) ) . isBreak ( ) ) break ; } | Iterate all registered micro type converters . For informational purposes only . | 156 | 14 |
16,196 | @ Nullable public static String safeDecodeAsString ( @ Nullable final String sEncoded , @ Nonnull final Charset aCharset ) { ValueEnforcer . notNull ( aCharset , "Charset" ) ; if ( sEncoded != null ) try { final byte [ ] aDecoded = decode ( sEncoded , DONT_GUNZIP ) ; return new String ( aDecoded , aCharset ) ; } catch ( final IOException ex ) { // Fall through } return null ; } | Decode the string and convert it back to a string . | 117 | 12 |
16,197 | @ Override public boolean ready ( ) throws IOException { _ensureOpen ( ) ; /* * If newline needs to be skipped and the next char to be read is a newline * character, then just skip it right away. */ if ( m_bSkipLF ) { /* * Note that in.ready() will return true if and only if the next read on * the stream will not block. */ if ( m_nNextCharIndex >= m_nChars && m_aReader . ready ( ) ) _fill ( ) ; if ( m_nNextCharIndex < m_nChars ) { if ( m_aBuf [ m_nNextCharIndex ] == ' ' ) m_nNextCharIndex ++ ; m_bSkipLF = false ; } } return m_nNextCharIndex < m_nChars || m_aReader . ready ( ) ; } | Tells whether this stream is ready to be read . A buffered character stream is ready if the buffer is not empty or if the underlying character stream is ready . | 194 | 33 |
16,198 | @ Nonnull public EChange addAllFrom ( @ Nonnull final MapBasedXPathVariableResolver aOther , final boolean bOverwrite ) { ValueEnforcer . notNull ( aOther , "Other" ) ; EChange eChange = EChange . UNCHANGED ; for ( final Map . Entry < String , ? > aEntry : aOther . getAllVariables ( ) . entrySet ( ) ) { // Local part only to QName final QName aKey = new QName ( aEntry . getKey ( ) ) ; if ( bOverwrite || ! m_aMap . containsKey ( aKey ) ) { m_aMap . put ( aKey , aEntry . getValue ( ) ) ; eChange = EChange . CHANGED ; } } return eChange ; } | Add all variables from the other variable resolver into this resolver . This methods creates a QName with an empty namespace URI . | 171 | 26 |
16,199 | public static void setDefaultJMXDomain ( @ Nonnull @ Nonempty final String sDefaultJMXDomain ) { ValueEnforcer . notEmpty ( sDefaultJMXDomain , "DefaultJMXDomain" ) ; if ( sDefaultJMXDomain . indexOf ( ' ' ) >= 0 || sDefaultJMXDomain . indexOf ( ' ' ) >= 0 ) throw new IllegalArgumentException ( "defaultJMXDomain contains invalid chars: " + sDefaultJMXDomain ) ; s_aRWLock . writeLocked ( ( ) -> s_sDefaultJMXDomain = sDefaultJMXDomain ) ; } | Set the default JMX domain | 131 | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.