idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
32,200 | private void defineReadUnionMethod ( ) { MethodDefinition read = new MethodDefinition ( a ( PUBLIC ) , "read" , structType , arg ( "protocol" , TProtocol . class ) ) . addException ( Exception . class ) ; // TProtocolReader reader = new TProtocolReader(protocol); read . addLocalVariable ( type ( TProtocolReader . class ) , "reader" ) ; read . newObject ( TProtocolReader . class ) ; read . dup ( ) ; read . loadVariable ( "protocol" ) ; read . invokeConstructor ( type ( TProtocolReader . class ) , type ( TProtocol . class ) ) ; read . storeVariable ( "reader" ) ; // field id field. read . addInitializedLocalVariable ( type ( short . class ) , "fieldId" ) ; // read all of the data in to local variables Map < Short , LocalVariableDefinition > unionData = readSingleFieldValue ( read ) ; // build the struct LocalVariableDefinition result = buildUnion ( read , unionData ) ; // push instance on stack, and return it read . loadVariable ( result ) . retObject ( ) ; classDefinition . addMethod ( read ) ; } | Defines the read method for an union . | 259 | 9 |
32,201 | private Map < Short , LocalVariableDefinition > readSingleFieldValue ( MethodDefinition read ) { LocalVariableDefinition protocol = read . getLocalVariable ( "reader" ) ; // declare and init local variables here Map < Short , LocalVariableDefinition > unionData = new TreeMap <> ( ) ; for ( ThriftFieldMetadata field : metadata . getFields ( THRIFT_FIELD ) ) { LocalVariableDefinition variable = read . addInitializedLocalVariable ( toParameterizedType ( field . getThriftType ( ) ) , "f_" + field . getName ( ) ) ; unionData . put ( field . getId ( ) , variable ) ; } // protocol.readStructBegin(); read . loadVariable ( protocol ) . invokeVirtual ( TProtocolReader . class , "readStructBegin" , void . class ) ; // while (protocol.nextField()) read . visitLabel ( "while-begin" ) ; read . loadVariable ( protocol ) . invokeVirtual ( TProtocolReader . class , "nextField" , boolean . class ) ; read . ifZeroGoto ( "while-end" ) ; // fieldId = protocol.getFieldId() read . loadVariable ( protocol ) . invokeVirtual ( TProtocolReader . class , "getFieldId" , short . class ) ; read . storeVariable ( "fieldId" ) ; // switch (fieldId) read . loadVariable ( "fieldId" ) ; List < CaseStatement > cases = new ArrayList <> ( ) ; for ( ThriftFieldMetadata field : metadata . getFields ( THRIFT_FIELD ) ) { cases . add ( caseStatement ( field . getId ( ) , field . getName ( ) + "-field" ) ) ; } read . switchStatement ( "default" , cases ) ; for ( ThriftFieldMetadata field : metadata . getFields ( THRIFT_FIELD ) ) { // case field.id: read . visitLabel ( field . getName ( ) + "-field" ) ; // push protocol read . loadVariable ( protocol ) ; // push ThriftTypeCodec for this field FieldDefinition codecField = codecFields . get ( field . getId ( ) ) ; if ( codecField != null ) { read . loadThis ( ) . getField ( codecType , codecField ) ; } // read value Method readMethod = getReadMethod ( field . getThriftType ( ) ) ; if ( readMethod == null ) { throw new IllegalArgumentException ( "Unsupported field type " + field . getThriftType ( ) . getProtocolType ( ) ) ; } read . invokeVirtual ( readMethod ) ; // todo this cast should be based on readMethod return type and fieldType (or coercion type) // add cast if necessary if ( needsCastAfterRead ( field , readMethod ) ) { read . checkCast ( toParameterizedType ( field . getThriftType ( ) ) ) ; } // coerce the type if ( field . getCoercion ( ) . isPresent ( ) ) { read . invokeStatic ( field . getCoercion ( ) . get ( ) . getFromThrift ( ) ) ; } // store protocol value read . storeVariable ( unionData . get ( field . getId ( ) ) ) ; // go back to top of loop read . gotoLabel ( "while-begin" ) ; } // default case read . visitLabel ( "default" ) . loadVariable ( protocol ) . invokeVirtual ( TProtocolReader . class , "skipFieldData" , void . class ) . gotoLabel ( "while-begin" ) ; // end of while loop read . visitLabel ( "while-end" ) ; // protocol.readStructEnd(); read . loadVariable ( protocol ) . invokeVirtual ( TProtocolReader . class , "readStructEnd" , void . class ) ; return unionData ; } | Defines the code to read all of the data from the protocol into local variables . | 825 | 17 |
32,202 | private void invokeFactoryMethod ( MethodDefinition read , Map < Short , LocalVariableDefinition > structData , LocalVariableDefinition instance ) { if ( metadata . getBuilderMethod ( ) . isPresent ( ) ) { ThriftMethodInjection builderMethod = metadata . getBuilderMethod ( ) . get ( ) ; read . loadVariable ( instance ) ; // push parameters on stack for ( ThriftParameterInjection parameter : builderMethod . getParameters ( ) ) { read . loadVariable ( structData . get ( parameter . getId ( ) ) ) ; } // invoke the method read . invokeVirtual ( builderMethod . getMethod ( ) ) . storeVariable ( instance ) ; } } | Defines the code that calls the builder factory method . | 140 | 11 |
32,203 | private void defineReadBridgeMethod ( ) { classDefinition . addMethod ( new MethodDefinition ( a ( PUBLIC , BRIDGE , SYNTHETIC ) , "read" , type ( Object . class ) , arg ( "protocol" , TProtocol . class ) ) . addException ( Exception . class ) . loadThis ( ) . loadVariable ( "protocol" ) . invokeVirtual ( codecType , "read" , structType , type ( TProtocol . class ) ) . retObject ( ) ) ; } | Defines the generics bridge method with untyped args to the type specific read method . | 112 | 19 |
32,204 | private void defineWriteBridgeMethod ( ) { classDefinition . addMethod ( new MethodDefinition ( a ( PUBLIC , BRIDGE , SYNTHETIC ) , "write" , null , arg ( "struct" , Object . class ) , arg ( "protocol" , TProtocol . class ) ) . addException ( Exception . class ) . loadThis ( ) . loadVariable ( "struct" , structType ) . loadVariable ( "protocol" ) . invokeVirtual ( codecType , "write" , type ( void . class ) , structType , type ( TProtocol . class ) ) . ret ( ) ) ; } | Defines the generics bridge method with untyped args to the type specific write method . | 135 | 19 |
32,205 | public static ScopedBindingBuilder bindFrameCodecFactory ( Binder binder , String key , Class < ? extends ThriftFrameCodecFactory > frameCodecFactoryClass ) { return newMapBinder ( binder , String . class , ThriftFrameCodecFactory . class ) . addBinding ( key ) . to ( frameCodecFactoryClass ) ; } | helpers for binding frame codec factories | 79 | 7 |
32,206 | public static ScopedBindingBuilder bindProtocolFactory ( Binder binder , String key , Class < ? extends TDuplexProtocolFactory > protocolFactoryClass ) { return newMapBinder ( binder , String . class , TDuplexProtocolFactory . class ) . addBinding ( key ) . to ( protocolFactoryClass ) ; } | helpers for binding protocol factories | 74 | 6 |
32,207 | public static ScopedBindingBuilder bindWorkerExecutor ( Binder binder , String key , Class < ? extends ExecutorService > executorServiceClass ) { return workerExecutorBinder ( binder ) . addBinding ( key ) . to ( executorServiceClass ) ; } | Helpers for binding worker executors | 62 | 7 |
32,208 | public static Collection < Method > findAnnotatedMethods ( Class < ? > type , Class < ? extends Annotation > annotation ) { List < Method > result = new ArrayList <> ( ) ; // gather all publicly available methods // this returns everything, even if it's declared in a parent for ( Method method : type . getMethods ( ) ) { // skip methods that are used internally by the vm for implementing covariance, etc if ( method . isSynthetic ( ) || method . isBridge ( ) || isStatic ( method . getModifiers ( ) ) ) { continue ; } // look for annotations recursively in super-classes or interfaces Method managedMethod = findAnnotatedMethod ( type , annotation , method . getName ( ) , method . getParameterTypes ( ) ) ; if ( managedMethod != null ) { result . add ( managedMethod ) ; } } return result ; } | Find methods that are tagged with a given annotation somewhere in the hierarchy | 189 | 13 |
32,209 | @ Override public Void read ( TProtocol protocol ) throws Exception { Preconditions . checkNotNull ( protocol , "protocol is null" ) ; return null ; } | Always returns null without reading anything from the stream . | 37 | 10 |
32,210 | @ Override public void write ( Void value , TProtocol protocol ) throws Exception { Preconditions . checkNotNull ( protocol , "protocol is null" ) ; } | Always returns without writing to the stream . | 37 | 8 |
32,211 | @ Config ( "thrift.max-frame-size" ) public ThriftServerConfig setMaxFrameSize ( DataSize maxFrameSize ) { checkArgument ( maxFrameSize . toBytes ( ) <= 0x3FFFFFFF ) ; this . maxFrameSize = maxFrameSize ; return this ; } | Sets a maximum frame size | 66 | 6 |
32,212 | public HostAndPort getRemoteAddress ( Object client ) { NiftyClientChannel niftyChannel = getNiftyChannel ( client ) ; try { Channel nettyChannel = niftyChannel . getNettyChannel ( ) ; SocketAddress address = nettyChannel . getRemoteAddress ( ) ; InetSocketAddress inetAddress = ( InetSocketAddress ) address ; return HostAndPort . fromParts ( inetAddress . getHostString ( ) , inetAddress . getPort ( ) ) ; } catch ( NullPointerException | ClassCastException e ) { throw new IllegalArgumentException ( "Invalid swift client object" , e ) ; } } | Returns the remote address that a Swift client is connected to | 135 | 11 |
32,213 | protected final Set < String > inferThriftFieldIds ( ) { Set < String > fieldsWithConflictingIds = new HashSet <> ( ) ; // group fields by explicit name or by name extracted from field, method or property Multimap < String , FieldMetadata > fieldsByExplicitOrExtractedName = Multimaps . index ( fields , getOrExtractThriftFieldName ( ) ) ; inferThriftFieldIds ( fieldsByExplicitOrExtractedName , fieldsWithConflictingIds ) ; // group fields by name extracted from field, method or property // this allows thrift name to be set explicitly without having to duplicate the name on getters and setters // todo should this be the only way this works? Multimap < String , FieldMetadata > fieldsByExtractedName = Multimaps . index ( fields , extractThriftFieldName ( ) ) ; inferThriftFieldIds ( fieldsByExtractedName , fieldsWithConflictingIds ) ; return fieldsWithConflictingIds ; } | Assigns all fields an id if possible . Fields are grouped by name and for each group if there is a single id all fields in the group are assigned this id . If the group has multiple ids an error is reported . | 226 | 47 |
32,214 | protected final void verifyFieldType ( short id , String name , Collection < FieldMetadata > fields , ThriftCatalog catalog ) { boolean isSupportedType = true ; for ( FieldMetadata field : fields ) { if ( ! catalog . isSupportedStructFieldType ( field . getJavaType ( ) ) ) { metadataErrors . addError ( "Thrift class '%s' field '%s(%s)' type '%s' is not a supported Java type" , structName , name , id , TypeToken . of ( field . getJavaType ( ) ) ) ; isSupportedType = false ; // only report the error once break ; } } // fields must have the same type if ( isSupportedType ) { Set < ThriftTypeReference > types = new HashSet <> ( ) ; for ( FieldMetadata field : fields ) { types . add ( catalog . getFieldThriftTypeReference ( field ) ) ; } if ( types . size ( ) > 1 ) { metadataErrors . addError ( "Thrift class '%s' field '%s(%s)' has multiple types: %s" , structName , name , id , types ) ; } } } | Verifies that the the fields all have a supported Java type and that all fields map to the exact same ThriftType . | 253 | 25 |
32,215 | private static String escapeJavaString ( String input ) { int len = input . length ( ) ; // assume (for performance, not for correctness) that string will not expand by more than 10 chars StringBuilder out = new StringBuilder ( len + 10 ) ; for ( int i = 0 ; i < len ; i ++ ) { char c = input . charAt ( i ) ; if ( c >= 32 && c <= 0x7f ) { if ( c == ' ' ) { out . append ( ' ' ) ; out . append ( ' ' ) ; } else if ( c == ' ' ) { out . append ( ' ' ) ; out . append ( ' ' ) ; } else { out . append ( c ) ; } } else { out . append ( ' ' ) ; out . append ( ' ' ) ; // one liner hack to have the hex string of length exactly 4 out . append ( Integer . toHexString ( c | 0x10000 ) . substring ( 1 ) ) ; } } return out . toString ( ) ; } | in Guava 15 when released | 222 | 6 |
32,216 | public void addCodec ( ThriftCodec < ? > codec ) { catalog . addThriftType ( codec . getType ( ) ) ; typeCodecs . put ( codec . getType ( ) , codec ) ; } | Adds or replaces the codec associated with the type contained in the codec . This does not replace any current users of the existing codec associated with the type . | 49 | 30 |
32,217 | private Object convertToThrift ( Class < ? > cls ) { Set < ThriftService > serviceAnnotations = ReflectionHelper . getEffectiveClassAnnotations ( cls , ThriftService . class ) ; if ( ! serviceAnnotations . isEmpty ( ) ) { // it's a service ThriftServiceMetadata serviceMetadata = new ThriftServiceMetadata ( cls , codecManager . getCatalog ( ) ) ; if ( verbose ) { LOG . info ( "Found thrift service: %s" , cls . getSimpleName ( ) ) ; } return serviceMetadata ; } else { // it's a type (will throw if it's not) ThriftType thriftType = codecManager . getCatalog ( ) . getThriftType ( cls ) ; if ( verbose ) { LOG . info ( "Found thrift type: %s" , thriftTypeRenderer . toString ( thriftType ) ) ; } return thriftType ; } } | returns ThriftType ThriftServiceMetadata or null | 211 | 12 |
32,218 | static String parse ( final byte content [ ] , final Metadata metadata , final int limit ) throws TikaException , IOException { // check that its not unprivileged code like a script SecurityManager sm = System . getSecurityManager ( ) ; if ( sm != null ) { sm . checkPermission ( new SpecialPermission ( ) ) ; } try { return AccessController . doPrivileged ( new PrivilegedExceptionAction < String > ( ) { @ Override public String run ( ) throws TikaException , IOException { return TIKA_INSTANCE . parseToString ( StreamInput . wrap ( content ) , metadata , limit ) ; } } ) ; } catch ( PrivilegedActionException e ) { // checked exception from tika: unbox it Throwable cause = e . getCause ( ) ; if ( cause instanceof TikaException ) { throw ( TikaException ) cause ; } else if ( cause instanceof IOException ) { throw ( IOException ) cause ; } else { throw new AssertionError ( cause ) ; } } } | only package private for testing! | 222 | 6 |
32,219 | public static void initializeSmsRadarService ( Context context , SmsListener smsListener ) { SmsRadar . smsListener = smsListener ; Intent intent = new Intent ( context , SmsRadarService . class ) ; context . startService ( intent ) ; } | Starts the service and store the listener to be notified when a new incoming or outgoing sms be processed inside the SMS content provider | 60 | 26 |
32,220 | public static void stopSmsRadarService ( Context context ) { SmsRadar . smsListener = null ; Intent intent = new Intent ( context , SmsRadarService . class ) ; context . stopService ( intent ) ; } | Stops the service and remove the SmsListener added when the SmsRadar was initialized | 51 | 19 |
32,221 | private void saveAttributesBeforeInclude ( final Invocation inv ) { ServletRequest request = inv . getRequest ( ) ; logger . debug ( "Taking snapshot of request attributes before include" ) ; Map < String , Object > attributesSnapshot = new HashMap < String , Object > ( ) ; Enumeration < ? > attrNames = request . getAttributeNames ( ) ; while ( attrNames . hasMoreElements ( ) ) { String attrName = ( String ) attrNames . nextElement ( ) ; attributesSnapshot . put ( attrName , request . getAttribute ( attrName ) ) ; } inv . setAttribute ( "$$paoding-rose.attributesBeforeInclude" , attributesSnapshot ) ; } | Keep a snapshot of the request attributes in case of an include to be able to restore the original attributes after the include . | 158 | 24 |
32,222 | private void restoreRequestAttributesAfterInclude ( Invocation inv ) { logger . debug ( "Restoring snapshot of request attributes after include" ) ; HttpServletRequest request = inv . getRequest ( ) ; @ SuppressWarnings ( "unchecked" ) Map < String , Object > attributesSnapshot = ( Map < String , Object > ) inv . getAttribute ( "$$paoding-rose.attributesBeforeInclude" ) ; // Need to copy into separate Collection here, to avoid side effects // on the Enumeration when removing attributes. Set < String > attrsToCheck = new HashSet < String > ( ) ; Enumeration < ? > attrNames = request . getAttributeNames ( ) ; while ( attrNames . hasMoreElements ( ) ) { String attrName = ( String ) attrNames . nextElement ( ) ; attrsToCheck . add ( attrName ) ; } // Iterate over the attributes to check, restoring the original value // or removing the attribute, respectively, if appropriate. for ( String attrName : attrsToCheck ) { Object attrValue = attributesSnapshot . get ( attrName ) ; if ( attrValue != null ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Restoring original value of attribute [" + attrName + "] after include" ) ; } request . setAttribute ( attrName , attrValue ) ; } else { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Removing attribute [" + attrName + "] after include" ) ; } request . removeAttribute ( attrName ) ; } } } | Restore the request attributes after an include . | 358 | 9 |
32,223 | protected boolean isCandidateComponent ( MetadataReader metadataReader ) throws IOException { for ( TypeFilter tf : this . excludeFilters ) { if ( tf . match ( metadataReader , this . metadataReaderFactory ) ) { return false ; } } for ( TypeFilter tf : this . includeFilters ) { if ( tf . match ( metadataReader , this . metadataReaderFactory ) ) { return true ; } } return false ; } | Determine whether the given class does not match any exclude filter and does match at least one include filter . | 91 | 22 |
32,224 | @ Override protected AbstractPropertyBindingResult getInternalBindingResult ( ) { AbstractPropertyBindingResult bindingResult = super . getInternalBindingResult ( ) ; // by rose PropertyEditorRegistry registry = bindingResult . getPropertyEditorRegistry ( ) ; registry . registerCustomEditor ( Date . class , new DateEditor ( Date . class ) ) ; registry . registerCustomEditor ( java . sql . Date . class , new DateEditor ( java . sql . Date . class ) ) ; registry . registerCustomEditor ( java . sql . Time . class , new DateEditor ( java . sql . Time . class ) ) ; registry . registerCustomEditor ( java . sql . Timestamp . class , new DateEditor ( java . sql . Timestamp . class ) ) ; return bindingResult ; } | Return the internal BindingResult held by this DataBinder as AbstractPropertyBindingResult . | 166 | 18 |
32,225 | public final byte [ ] decode ( byte [ ] source , int off , int len ) { int len34 = len * 3 / 4 ; byte [ ] outBuff = new byte [ len34 ] ; // upper limit on size of output int outBuffPosn = 0 ; byte [ ] b4 = new byte [ 4 ] ; int b4Posn = 0 ; int i = 0 ; byte sbiCrop = 0 ; byte sbiDecode = 0 ; for ( i = off ; i < off + len ; i ++ ) { sbiCrop = ( byte ) ( source [ i ] & 0x7f ) ; // only the low seven bits sbiDecode = DECODABET [ sbiCrop ] ; if ( sbiDecode >= WHITE_SPACE_ENC ) { // white space, equals sign or better if ( sbiDecode >= PADDING_CHAR_ENC ) { b4 [ b4Posn ++ ] = sbiCrop ; if ( b4Posn > 3 ) { outBuffPosn += decode4to3 ( b4 , 0 , outBuff , outBuffPosn ) ; b4Posn = 0 ; // if that was the padding char, break out of 'for' loop if ( sbiCrop == PADDING_CHAR ) { break ; } } // end if: quartet built } // end if: equals sign or better } // end if: white space, equals sign or better else { //discard } } // each input character byte [ ] out = new byte [ outBuffPosn ] ; System . arraycopy ( outBuff , 0 , out , 0 , outBuffPosn ) ; return out ; } | Very low - level access to decoding ASCII characters in the form of a byte array . | 361 | 17 |
32,226 | protected void initialize ( ) { this . mappedFields = new HashMap < String , PropertyDescriptor > ( ) ; PropertyDescriptor [ ] pds = BeanUtils . getPropertyDescriptors ( mappedClass ) ; if ( checkProperties ) { mappedProperties = new HashSet < String > ( ) ; } for ( int i = 0 ; i < pds . length ; i ++ ) { PropertyDescriptor pd = pds [ i ] ; if ( pd . getWriteMethod ( ) != null ) { if ( checkProperties ) { this . mappedProperties . add ( pd . getName ( ) ) ; } this . mappedFields . put ( pd . getName ( ) . toLowerCase ( ) , pd ) ; for ( String underscoredName : underscoreName ( pd . getName ( ) ) ) { if ( underscoredName != null && ! pd . getName ( ) . toLowerCase ( ) . equals ( underscoredName ) ) { this . mappedFields . put ( underscoredName , pd ) ; } } } } } | Initialize the mapping metadata for the given class . | 238 | 10 |
32,227 | private String [ ] underscoreName ( String camelCaseName ) { StringBuilder result = new StringBuilder ( ) ; if ( camelCaseName != null && camelCaseName . length ( ) > 0 ) { result . append ( camelCaseName . substring ( 0 , 1 ) . toLowerCase ( ) ) ; for ( int i = 1 ; i < camelCaseName . length ( ) ; i ++ ) { char ch = camelCaseName . charAt ( i ) ; if ( Character . isUpperCase ( ch ) ) { result . append ( "_" ) ; result . append ( Character . toLowerCase ( ch ) ) ; } else { result . append ( ch ) ; } } } String name = result . toString ( ) ; // 当name为user1_name2时,使name2为user_1_name_2 // 这使得列user_1_name_2的列能映射到user1Name2属性 String name2 = null ; boolean digitFound = false ; for ( int i = name . length ( ) - 1 ; i >= 0 ; i -- ) { if ( Character . isDigit ( name . charAt ( i ) ) ) { // 遇到数字就做一个标识并continue,直到不是时才不continue digitFound = true ; continue ; } // 只有上一个字符是数字才做下划线 if ( digitFound && i < name . length ( ) - 1 && i > 0 ) { if ( name2 == null ) { name2 = name ; } name2 = name2 . substring ( 0 , i + 1 ) + "_" + name2 . substring ( i + 1 ) ; } digitFound = false ; } return new String [ ] { name , name2 } ; } | Convert a name in camelCase to an underscored name in lower case . Any upper case letters are converted to lower case with a preceding underscore . | 435 | 30 |
32,228 | public Options createOptions ( OptionsConfiguration optionsConfiguration ) throws MojoExecutionException { final Options options = new Options ( ) ; options . verbose = optionsConfiguration . isVerbose ( ) ; options . debugMode = optionsConfiguration . isDebugMode ( ) ; options . classpaths . addAll ( optionsConfiguration . getPlugins ( ) ) ; options . target = createSpecVersion ( optionsConfiguration . getSpecVersion ( ) ) ; final String encoding = optionsConfiguration . getEncoding ( ) ; if ( encoding != null ) { options . encoding = createEncoding ( encoding ) ; } options . setSchemaLanguage ( createLanguage ( optionsConfiguration . getSchemaLanguage ( ) ) ) ; options . entityResolver = optionsConfiguration . getEntityResolver ( ) ; for ( InputSource grammar : optionsConfiguration . getGrammars ( ) ) { options . addGrammar ( grammar ) ; } for ( InputSource bindFile : optionsConfiguration . getBindFiles ( ) ) { options . addBindFile ( bindFile ) ; } // Setup Other Options options . defaultPackage = optionsConfiguration . getGeneratePackage ( ) ; options . targetDir = optionsConfiguration . getGenerateDirectory ( ) ; options . strictCheck = optionsConfiguration . isStrict ( ) ; options . readOnly = optionsConfiguration . isReadOnly ( ) ; options . packageLevelAnnotations = optionsConfiguration . isPackageLevelAnnotations ( ) ; options . noFileHeader = optionsConfiguration . isNoFileHeader ( ) ; options . enableIntrospection = optionsConfiguration . isEnableIntrospection ( ) ; options . disableXmlSecurity = optionsConfiguration . isDisableXmlSecurity ( ) ; if ( optionsConfiguration . getAccessExternalSchema ( ) != null ) { System . setProperty ( "javax.xml.accessExternalSchema" , optionsConfiguration . getAccessExternalSchema ( ) ) ; } if ( optionsConfiguration . getAccessExternalDTD ( ) != null ) { System . setProperty ( "javax.xml.accessExternalDTD" , optionsConfiguration . getAccessExternalDTD ( ) ) ; } if ( optionsConfiguration . isEnableExternalEntityProcessing ( ) ) { System . setProperty ( "enableExternalEntityProcessing" , Boolean . TRUE . toString ( ) ) ; } options . contentForWildcard = optionsConfiguration . isContentForWildcard ( ) ; if ( optionsConfiguration . isExtension ( ) ) { options . compatibilityMode = Options . EXTENSION ; } final List < String > arguments = optionsConfiguration . getArguments ( ) ; try { options . parseArguments ( arguments . toArray ( new String [ arguments . size ( ) ] ) ) ; } catch ( BadCommandLineException bclex ) { throw new MojoExecutionException ( "Error parsing the command line [" + arguments + "]" , bclex ) ; } return options ; } | Creates and initializes an instance of XJC options . | 610 | 12 |
32,229 | public static InputSource getInputSource ( File file ) { try { final URL url = file . toURI ( ) . toURL ( ) ; return getInputSource ( url ) ; } catch ( MalformedURLException e ) { return new InputSource ( file . getPath ( ) ) ; } } | Creates an input source for the given file . | 65 | 10 |
32,230 | public void execute ( ) throws MojoExecutionException { synchronized ( lock ) { injectDependencyDefaults ( ) ; resolveArtifacts ( ) ; // Install project dependencies into classloader's class path // and execute xjc2. final ClassLoader currentClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; final ClassLoader classLoader = createClassLoader ( currentClassLoader ) ; Thread . currentThread ( ) . setContextClassLoader ( classLoader ) ; final Locale currentDefaultLocale = Locale . getDefault ( ) ; try { final Locale locale = LocaleUtils . valueOf ( getLocale ( ) ) ; Locale . setDefault ( locale ) ; // doExecute ( ) ; } finally { Locale . setDefault ( currentDefaultLocale ) ; // Set back the old classloader Thread . currentThread ( ) . setContextClassLoader ( currentClassLoader ) ; } } } | Execute the maven2 mojo to invoke the xjc2 compiler based on any configuration settings . | 197 | 21 |
32,231 | protected void setupMavenPaths ( ) { if ( getAddCompileSourceRoot ( ) ) { getProject ( ) . addCompileSourceRoot ( getGenerateDirectory ( ) . getPath ( ) ) ; } if ( getAddTestCompileSourceRoot ( ) ) { getProject ( ) . addTestCompileSourceRoot ( getGenerateDirectory ( ) . getPath ( ) ) ; } if ( getEpisode ( ) && getEpisodeFile ( ) != null ) { final String episodeFilePath = getEpisodeFile ( ) . getAbsolutePath ( ) ; final String generatedDirectoryPath = getGenerateDirectory ( ) . getAbsolutePath ( ) ; if ( episodeFilePath . startsWith ( generatedDirectoryPath + File . separator ) ) { final String path = episodeFilePath . substring ( generatedDirectoryPath . length ( ) + 1 ) ; final Resource resource = new Resource ( ) ; resource . setDirectory ( generatedDirectoryPath ) ; resource . addInclude ( path ) ; if ( getAddCompileSourceRoot ( ) ) { getProject ( ) . addResource ( resource ) ; } if ( getAddTestCompileSourceRoot ( ) ) { getProject ( ) . addTestResource ( resource ) ; } } } } | Augments Maven paths with generated resources . | 264 | 9 |
32,232 | protected void logConfiguration ( ) throws MojoExecutionException { super . logConfiguration ( ) ; // TODO clean up getLog ( ) . info ( "catalogURIs (calculated):" + getCatalogURIs ( ) ) ; getLog ( ) . info ( "resolvedCatalogURIs (calculated):" + getResolvedCatalogURIs ( ) ) ; getLog ( ) . info ( "schemaFiles (calculated):" + getSchemaFiles ( ) ) ; getLog ( ) . info ( "schemaURIs (calculated):" + getSchemaURIs ( ) ) ; getLog ( ) . info ( "resolvedSchemaURIs (calculated):" + getResolvedSchemaURIs ( ) ) ; getLog ( ) . info ( "bindingFiles (calculated):" + getBindingFiles ( ) ) ; getLog ( ) . info ( "bindingURIs (calculated):" + getBindingURIs ( ) ) ; getLog ( ) . info ( "resolvedBindingURIs (calculated):" + getResolvedBindingURIs ( ) ) ; getLog ( ) . info ( "xjcPluginArtifacts (resolved):" + getXjcPluginArtifacts ( ) ) ; getLog ( ) . info ( "xjcPluginFiles (resolved):" + getXjcPluginFiles ( ) ) ; getLog ( ) . info ( "xjcPluginURLs (resolved):" + getXjcPluginURLs ( ) ) ; getLog ( ) . info ( "episodeArtifacts (resolved):" + getEpisodeArtifacts ( ) ) ; getLog ( ) . info ( "episodeFiles (resolved):" + getEpisodeFiles ( ) ) ; getLog ( ) . info ( "dependsURIs (resolved):" + getDependsURIs ( ) ) ; } | Log the configuration settings . Shown when exception thrown or when verbose is true . | 405 | 17 |
32,233 | protected CatalogResolver createCatalogResolver ( ) throws MojoExecutionException { final CatalogManager catalogManager = new CatalogManager ( ) ; catalogManager . setIgnoreMissingProperties ( true ) ; catalogManager . setUseStaticCatalog ( false ) ; // TODO Logging if ( getLog ( ) . isDebugEnabled ( ) ) { catalogManager . setVerbosity ( Integer . MAX_VALUE ) ; } if ( getCatalogResolver ( ) == null ) { return new MavenCatalogResolver ( catalogManager , this , getLog ( ) ) ; } else { final String catalogResolverClassName = getCatalogResolver ( ) . trim ( ) ; return createCatalogResolverByClassName ( catalogResolverClassName ) ; } } | Creates an instance of catalog resolver . | 159 | 9 |
32,234 | MeetMeRoomImpl getOrCreateRoomImpl ( String roomNumber ) { MeetMeRoomImpl room ; boolean created = false ; synchronized ( rooms ) { room = rooms . get ( roomNumber ) ; if ( room == null ) { room = new MeetMeRoomImpl ( server , roomNumber ) ; populateRoom ( room ) ; rooms . put ( roomNumber , room ) ; created = true ; } } if ( created ) { logger . debug ( "Created MeetMeRoom " + roomNumber ) ; } return room ; } | Returns the room with the given number or creates a new one if none is there yet . | 109 | 18 |
32,235 | public String getDecodedMessage ( ) { if ( message == null ) { return null ; } return new String ( Base64 . base64ToByteArray ( message ) , Charset . forName ( "UTF-8" ) ) ; } | Returns the decoded message . | 52 | 6 |
32,236 | public static CallerID buildFromComponents ( final String firstname , final String lastname , final String number ) { String name = "" ; //$NON-NLS-1$ if ( firstname != null ) { name += firstname . trim ( ) ; } if ( lastname != null ) { if ( name . length ( ) > 0 ) { name += " " ; //$NON-NLS-1$ } name += lastname . trim ( ) ; } return PBXFactory . getActivePBX ( ) . buildCallerID ( number , name ) ; } | This is a little helper class which will buid the name component of a clid from the first and lastnames . If both firstname and lastname are null then the name component will be an empty string . | 125 | 43 |
32,237 | void idChanged ( Date date , String id ) { final String oldId = this . id ; if ( oldId != null && oldId . equals ( id ) ) { return ; } this . id = id ; firePropertyChange ( PROPERTY_ID , oldId , id ) ; } | Changes the id of this channel . | 62 | 7 |
32,238 | void nameChanged ( Date date , String name ) { final String oldName = this . name ; if ( oldName != null && oldName . equals ( name ) ) { return ; } this . name = name ; firePropertyChange ( PROPERTY_NAME , oldName , name ) ; } | Changes the name of this channel . | 62 | 7 |
32,239 | void setCallerId ( final CallerId callerId ) { final CallerId oldCallerId = this . callerId ; this . callerId = callerId ; firePropertyChange ( PROPERTY_CALLER_ID , oldCallerId , callerId ) ; } | Sets the caller id of this channel . | 58 | 9 |
32,240 | synchronized void stateChanged ( Date date , ChannelState state ) { final ChannelStateHistoryEntry historyEntry ; final ChannelState oldState = this . state ; if ( oldState == state ) { return ; } // System.err.println(id + " state change: " + oldState + " => " + state // + " (" + name + ")"); historyEntry = new ChannelStateHistoryEntry ( date , state ) ; synchronized ( stateHistory ) { stateHistory . add ( historyEntry ) ; } this . state = state ; firePropertyChange ( PROPERTY_STATE , oldState , state ) ; } | Changes the state of this channel . | 130 | 7 |
32,241 | void setAccount ( String account ) { final String oldAccount = this . account ; this . account = account ; firePropertyChange ( PROPERTY_ACCOUNT , oldAccount , account ) ; } | Sets the account code used to bill this channel . | 41 | 11 |
32,242 | void extensionVisited ( Date date , Extension extension ) { final Extension oldCurrentExtension = getCurrentExtension ( ) ; final ExtensionHistoryEntry historyEntry ; historyEntry = new ExtensionHistoryEntry ( date , extension ) ; synchronized ( extensionHistory ) { extensionHistory . add ( historyEntry ) ; } firePropertyChange ( PROPERTY_CURRENT_EXTENSION , oldCurrentExtension , extension ) ; } | Adds a visted dialplan entry to the history . | 86 | 11 |
32,243 | public List < AsteriskChannel > getDialedChannels ( ) { final List < AsteriskChannel > copy ; synchronized ( dialedChannels ) { copy = new ArrayList <> ( dialedChannels ) ; } return copy ; } | Retrives the conplete List of all dialed channels associated to ths calls | 51 | 17 |
32,244 | synchronized void channelLinked ( Date date , AsteriskChannel linkedChannel ) { final AsteriskChannel oldLinkedChannel ; synchronized ( this . linkedChannels ) { if ( this . linkedChannels . isEmpty ( ) ) { oldLinkedChannel = null ; this . linkedChannels . add ( linkedChannel ) ; } else { oldLinkedChannel = this . linkedChannels . get ( 0 ) ; this . linkedChannels . set ( 0 , linkedChannel ) ; } } final LinkedChannelHistoryEntry historyEntry ; historyEntry = new LinkedChannelHistoryEntry ( date , linkedChannel ) ; synchronized ( linkedChannelHistory ) { linkedChannelHistory . add ( historyEntry ) ; } this . wasLinked = true ; firePropertyChange ( PROPERTY_LINKED_CHANNEL , oldLinkedChannel , linkedChannel ) ; } | Sets the channel this channel is bridged with . | 181 | 11 |
32,245 | protected AsteriskVersion determineVersionByCoreSettings ( ) throws Exception { ManagerResponse response = sendAction ( new CoreSettingsAction ( ) ) ; if ( ! ( response instanceof CoreSettingsResponse ) ) { // NOTE: you need system or reporting permissions logger . info ( "Could not get core settings, do we have the necessary permissions?" ) ; return null ; } String ver = ( ( CoreSettingsResponse ) response ) . getAsteriskVersion ( ) ; return AsteriskVersion . getDetermineVersionFromString ( "Asterisk " + ver ) ; } | Get asterisk version by core settings actions . This is supported from Asterisk 1 . 6 onwards . | 118 | 20 |
32,246 | protected AsteriskVersion determineVersionByCoreShowVersion ( ) throws Exception { final ManagerResponse coreShowVersionResponse = sendAction ( new CommandAction ( CMD_SHOW_VERSION ) ) ; if ( coreShowVersionResponse == null || ! ( coreShowVersionResponse instanceof CommandResponse ) ) { // this needs 'command' permissions logger . info ( "Could not get response for 'core show version'" ) ; return null ; } final List < String > coreShowVersionResult = ( ( CommandResponse ) coreShowVersionResponse ) . getResult ( ) ; if ( coreShowVersionResult == null || coreShowVersionResult . isEmpty ( ) ) { logger . warn ( "Got empty response for 'core show version'" ) ; return null ; } final String coreLine = coreShowVersionResult . get ( 0 ) ; return AsteriskVersion . getDetermineVersionFromString ( coreLine ) ; } | Determine version by the core show version command . This needs command permissions . | 189 | 16 |
32,247 | protected synchronized void disconnect ( ) { if ( socket != null ) { logger . info ( "Closing socket." ) ; try { socket . close ( ) ; } catch ( IOException ex ) { logger . warn ( "Unable to close socket: " + ex . getMessage ( ) ) ; } socket = null ; } protocolIdentifier . reset ( ) ; } | Closes the socket connection . | 77 | 6 |
32,248 | public ManagerResponse sendAction ( ManagerAction action , long timeout ) throws IOException , TimeoutException , IllegalArgumentException , IllegalStateException { ResponseHandlerResult result = new ResponseHandlerResult ( ) ; SendActionCallback callbackHandler = new DefaultSendActionCallback ( result ) ; sendAction ( action , callbackHandler ) ; // definitely return null for the response of user events if ( action instanceof UserEventAction ) { return null ; } // only wait if we did not yet receive the response. // Responses may be returned really fast. if ( result . getResponse ( ) == null ) { try { result . await ( timeout ) ; } catch ( InterruptedException ex ) { logger . warn ( "Interrupted while waiting for result" ) ; Thread . currentThread ( ) . interrupt ( ) ; } } // still no response? if ( result . getResponse ( ) == null ) { throw new TimeoutException ( "Timeout waiting for response to " + action . getAction ( ) + ( action . getActionId ( ) == null ? "" : " (actionId: " + action . getActionId ( ) + ")" ) ) ; } return result . getResponse ( ) ; } | Implements synchronous sending of simple actions . | 249 | 10 |
32,249 | private String createInternalActionId ( ) { final StringBuilder sb ; sb = new StringBuilder ( ) ; sb . append ( this . hashCode ( ) ) ; sb . append ( "_" ) ; sb . append ( actionIdCounter . getAndIncrement ( ) ) ; return sb . toString ( ) ; } | Creates a new unique internal action id based on the hash code of this connection and a sequence . | 73 | 20 |
32,250 | public void dispatchEvent ( ManagerEvent event ) { // shouldn't happen if ( event == null ) { logger . error ( "Unable to dispatch null event. This should never happen. Please file a bug." ) ; return ; } dispatchLegacyEventIfNeeded ( event ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Dispatching event:\n" + event . toString ( ) ) ; } // Some events need special treatment besides forwarding them to the // registered eventListeners (clients) // These events are handled here at first: // Dispatch ResponseEvents to the appropriate responseEventListener if ( event instanceof ResponseEvent ) { ResponseEvent responseEvent ; String internalActionId ; responseEvent = ( ResponseEvent ) event ; internalActionId = responseEvent . getInternalActionId ( ) ; if ( internalActionId != null ) { synchronized ( responseEventListeners ) { ManagerEventListener listener ; listener = responseEventListeners . get ( internalActionId ) ; if ( listener != null ) { try { listener . onManagerEvent ( event ) ; } catch ( Exception e ) { logger . warn ( "Unexpected exception in response event listener " + listener . getClass ( ) . getName ( ) , e ) ; } } } } else { // ResponseEvent without internalActionId: // this happens if the same event class is used as response // event // and as an event that is not triggered by a Manager command // Example: QueueMemberStatusEvent. // logger.debug("ResponseEvent without " // + "internalActionId:\n" + responseEvent); } // NOPMD } if ( event instanceof DisconnectEvent ) { // When we receive get disconnected while we are connected start // a new reconnect thread and set the state to RECONNECTING. synchronized ( this ) { if ( state == CONNECTED ) { state = RECONNECTING ; // close socket if still open and remove reference to // readerThread // After sending the DisconnectThread that thread will die // anyway. cleanup ( ) ; Thread reconnectThread = new Thread ( new Runnable ( ) { public void run ( ) { reconnect ( ) ; } } ) ; reconnectThread . setName ( "Asterisk-Java ManagerConnection-" + id + "-Reconnect-" + reconnectThreadCounter . getAndIncrement ( ) ) ; reconnectThread . setDaemon ( true ) ; reconnectThread . start ( ) ; // now the DisconnectEvent is dispatched to registered // eventListeners // (clients) and after that the ManagerReaderThread is gone. // So effectively we replaced the reader thread by a // ReconnectThread. } else { // when we receive a DisconnectEvent while not connected we // ignore it and do not send it to clients return ; } } } if ( event instanceof ProtocolIdentifierReceivedEvent ) { ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent ; String protocolIdentifier ; protocolIdentifierReceivedEvent = ( ProtocolIdentifierReceivedEvent ) event ; protocolIdentifier = protocolIdentifierReceivedEvent . getProtocolIdentifier ( ) ; setProtocolIdentifier ( protocolIdentifier ) ; // no need to send this event to clients return ; } fireEvent ( event ) ; } | This method is called by the reader whenever a ManagerEvent is received . The event is dispatched to all registered ManagerEventHandlers . | 680 | 26 |
32,251 | private void dispatchLegacyEventIfNeeded ( ManagerEvent event ) { if ( event instanceof DialBeginEvent ) { DialEvent legacyEvent = new DialEvent ( ( DialBeginEvent ) event ) ; dispatchEvent ( legacyEvent ) ; } } | Enro 2015 - 03 Workaround to continue having Legacy Events from Asterisk 13 . | 51 | 17 |
32,252 | @ SuppressWarnings ( "unchecked" ) public void addServiceAgiScript ( Class < ? extends ServiceAgiScript > handler ) throws DuplicateScriptException , InstantiationException , IllegalAccessException { logger . info ( "loading agi handler {}" + handler . getCanonicalName ( ) ) ; ServiceAgiScript tmpHandler = handler . newInstance ( ) ; if ( handlers . containsKey ( tmpHandler . getScriptName ( ) ) ) { throw new DuplicateScriptException ( "Script " + tmpHandler . getScriptName ( ) + " already exists" ) ; } String [ ] parameters = tmpHandler . getParameters ( ) ; String sample = "Agi(agi://localhost/" + tmpHandler . getScriptName ( ) + ".agi" ; logger . info ( "********************************************" ) ; logger . info ( "registered new agi script: " + tmpHandler . getScriptName ( ) ) ; for ( int i = 0 ; i < parameters . length ; i ++ ) { logger . info ( "parameter: " + parameters [ i ] ) ; if ( i == 0 ) sample += "?" + parameters [ i ] + "=testdata" ; else sample += "&" + parameters [ i ] + "=testdata" ; } logger . info ( "sample usage..." ) ; logger . info ( sample + ")" ) ; Class < ServiceAgiScript > handler2 = ( Class < ServiceAgiScript > ) handler ; handlers . put ( tmpHandler . getScriptName ( ) , handler2 ) ; } | this will be a pluggable extension system for the agi core it s still a work in progress and is not useable | 331 | 26 |
32,253 | protected ScriptEngine getScriptEngine ( File file ) { final String extension = getExtension ( file . getName ( ) ) ; if ( extension == null ) { return null ; } return getScriptEngineManager ( ) . getEngineByExtension ( extension ) ; } | Searches for a ScriptEngine that can handle the given file . | 56 | 14 |
32,254 | protected ClassLoader getClassLoader ( ) { final ClassLoader parentClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; final List < URL > jarFileUrls = new ArrayList <> ( ) ; if ( libPath == null || libPath . length == 0 ) { return parentClassLoader ; } for ( String libPathEntry : libPath ) { final File libDir = new File ( libPathEntry ) ; if ( ! libDir . isDirectory ( ) ) { continue ; } final File [ ] jarFiles = libDir . listFiles ( new FilenameFilter ( ) { public boolean accept ( File dir , String name ) { return name . endsWith ( ".jar" ) ; } } ) ; if ( jarFiles != null ) { for ( File jarFile : jarFiles ) { try { jarFileUrls . add ( jarFile . toURI ( ) . toURL ( ) ) ; } catch ( MalformedURLException e ) { // should not happen } } } else { logger . error ( "Didn't find any jar files at " + libDir . getAbsolutePath ( ) ) ; } } if ( jarFileUrls . isEmpty ( ) ) { return parentClassLoader ; } return new URLClassLoader ( jarFileUrls . toArray ( new URL [ jarFileUrls . size ( ) ] ) , parentClassLoader ) ; } | Returns the ClassLoader to use for the ScriptEngineManager . Adds all jar files in the lib subdirectory of the current directory to the class path . Override this method to provide your own ClassLoader . | 297 | 41 |
32,255 | protected File searchFile ( String scriptName , String [ ] path ) { if ( scriptName == null || path == null ) { return null ; } for ( String pathElement : path ) { final File pathElementDir = new File ( pathElement ) ; // skip if pathElement is not a directory if ( ! pathElementDir . isDirectory ( ) ) { continue ; } final File file = new File ( pathElementDir , scriptName . replaceAll ( "/" , Matcher . quoteReplacement ( File . separator ) ) ) ; if ( ! file . exists ( ) ) { continue ; } try { // prevent attacks with scripts using ".." in their name. if ( ! isInside ( file , pathElementDir ) ) { return null ; } } catch ( IOException e ) { logger . warn ( "Unable to check whether '" + file . getPath ( ) + "' is below '" + pathElementDir . getPath ( ) + "'" ) ; continue ; } try { return file . getCanonicalFile ( ) ; } catch ( IOException e ) { logger . error ( "Unable to get canonical file for '" + file . getPath ( ) + "'" , e ) ; } } return null ; } | Searches for the file with the given name on the path . | 264 | 14 |
32,256 | @ Override public void onManagerEvent ( final org . asteriskjava . manager . event . ManagerEvent event ) { // logger.error(event); boolean wanted = false ; /** * Dump any events we arn't interested in ASAP to minimise the * processing overhead of these events. */ // Only enqueue the events that are of interest to one of our listeners. synchronized ( this . globalEvents ) { Class < ? extends ManagerEvent > shadowEvent = CoherentEventFactory . getShadowEvent ( event ) ; if ( this . globalEvents . contains ( shadowEvent ) ) { wanted = true ; } } if ( wanted ) { // We don't support all events. this . _eventQueue . add ( new EventLifeMonitor <> ( event ) ) ; final int queueSize = this . _eventQueue . size ( ) ; if ( this . _queueMaxSize < queueSize ) { this . _queueMaxSize = queueSize ; } this . _queueSum += queueSize ; this . _queueCount ++ ; if ( CoherentManagerEventQueue . logger . isDebugEnabled ( ) ) { if ( this . _eventQueue . size ( ) > ( ( this . _queueMaxSize + ( this . _queueSum / this . _queueCount ) ) / 2 ) ) { CoherentManagerEventQueue . logger . debug ( "queue gtr max avg: size=" + queueSize + " max:" //$NON-NLS-1$ //$NON-NLS-2$ + this . _queueMaxSize + " avg:" + ( this . _queueSum / this . _queueCount ) ) ; //$NON-NLS-1$ } } } } | handles manager events passed to us in our role as a listener . We queue the event so that it can be read by the run method of this class and subsequently passed on to the original listener . | 359 | 40 |
32,257 | public void dispatchEvent ( final ManagerEvent event ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "dispatch=" + event . toString ( ) ) ; //$NON-NLS-1$ } // take a copy of the listeners so they can be modified whilst we // iterate over them // The iteration may call some long running processes. final List < FilteredManagerListenerWrapper > listenerCopy ; synchronized ( this . listeners ) { listenerCopy = this . listeners . getCopyAsList ( ) ; } try { final LogTime totalTime = new LogTime ( ) ; CountDownLatch latch = new CountDownLatch ( listenerCopy . size ( ) ) ; for ( final FilteredManagerListenerWrapper filter : listenerCopy ) { if ( filter . requiredEvents . contains ( event . getClass ( ) ) ) { dispatchEventOnThread ( event , filter , latch ) ; } else { // this listener didn't want the event, so just decrease the // countdown latch . countDown ( ) ; } } latch . await ( ) ; if ( totalTime . timeTaken ( ) > 500 ) { logger . warn ( "Too long to process event " + event + " time taken: " + totalTime . timeTaken ( ) ) ; //$NON-NLS-1$ //$NON-NLS-2$ } } catch ( InterruptedException e ) { Thread . interrupted ( ) ; } } | Events are sent here from the CoherentManagerEventQueue after being converted from a ManagerEvent to an ManagerEvent . This method is called from a dedicated thread attached to the event queue which it uses for dispatching events . | 308 | 44 |
32,258 | public void addListener ( final FilteredManagerListener < ManagerEvent > listener ) { synchronized ( this . listeners ) { this . listeners . addListener ( listener ) ; synchronized ( this . globalEvents ) { Collection < Class < ? extends ManagerEvent > > expandEvents = expandEvents ( listener . requiredEvents ( ) ) ; this . globalEvents . addAll ( expandEvents ) ; } } logger . debug ( "listener added " + listener ) ; } | Adds a listener which will be sent all events that its filterEvent handler will accept . All events are dispatch by way of a shared queue which is read via a thread which is shared by all listeners . Whilst poor performance of you listener can affect other listeners you can t affect the read thread which takes events from asterisk and enqueues them . | 94 | 69 |
32,259 | Collection < Class < ? extends ManagerEvent > > expandEvents ( Collection < Class < ? extends ManagerEvent > > events ) { Collection < Class < ? extends ManagerEvent > > requiredEvents = new HashSet <> ( ) ; for ( Class < ? extends ManagerEvent > event : events ) { requiredEvents . add ( event ) ; if ( event . equals ( BridgeEvent . class ) ) { requiredEvents . add ( UnlinkEvent . class ) ; requiredEvents . add ( LinkEvent . class ) ; } } return requiredEvents ; } | in order to get Bridge Events we must subscribe to Link and Unlink events for asterisk 1 . 4 so we automatically add them if the Bridge Event is required | 112 | 32 |
32,260 | public void transferListeners ( CoherentManagerEventQueue eventQueue ) { synchronized ( this . listeners ) { synchronized ( eventQueue . listeners ) { Iterator < FilteredManagerListenerWrapper > itr = eventQueue . listeners . iterator ( ) ; while ( itr . hasNext ( ) ) { FilteredManagerListenerWrapper listener = itr . next ( ) ; this . addListener ( listener . _listener ) ; } eventQueue . listeners . clear ( ) ; } } } | transfers the listeners from one queue to another . | 103 | 11 |
32,261 | public CallImpl join ( OperandChannel originatingOperand , Call rhs , OperandChannel acceptingOperand , CallDirection direction ) throws PBXException { CallImpl joinTo = ( CallImpl ) rhs ; Channel originatingParty = null ; Channel acceptingParty = null ; // Pull the originating party from the this call. originatingParty = this . getOperandChannel ( originatingOperand ) ; if ( originatingParty != null && originatingParty . isLive ( ) ) originatingParty . removeListener ( this ) ; // Pull the accepting party from the other 'call' as the accepting // party. acceptingParty = rhs . getOperandChannel ( acceptingOperand ) ; if ( acceptingParty != null && acceptingParty . isLive ( ) ) acceptingParty . removeListener ( ( CallImpl ) rhs ) ; if ( originatingParty == null || ! originatingParty . isLive ( ) || acceptingParty == null || ! acceptingParty . isLive ( ) ) throw new PBXException ( "Call.HangupDuringJoin" ) ; //$NON-NLS-1$ CallImpl joined = new CallImpl ( originatingParty , direction ) ; joined . setAcceptingParty ( acceptingParty ) ; joined . _owner = OWNER . SELF ; joined . _callStarted = minDate ( this . _callStarted , joinTo . _callStarted ) ; joined . _holdStarted = minDate ( this . _holdStarted , joinTo . _holdStarted ) ; joined . _timeAtDialin = minDate ( this . _timeAtDialin , joinTo . _timeAtDialin ) ; logger . debug ( "Joined two calls lhs=" + this + ", rhs=" + joinTo ) ; //$NON-NLS-1$//$NON-NLS-2$ return joined ; } | Joins a specific channel from this call with a specific channel from another call which results in a new Call object being created . Channels that do not participate in the join are left in their original Call . | 389 | 41 |
32,262 | public Call split ( OperandChannel channelToSplit ) throws PBXException { Channel channel = this . getOperandChannel ( channelToSplit ) ; channel . removeListener ( this ) ; CallDirection direction = CallDirection . INBOUND ; // If this is the operator channel we need to flip the default // direction. if ( this . getLocalParty ( ) != null && this . getLocalParty ( ) . isSame ( channel ) ) { direction = CallDirection . OUTBOUND ; } CallImpl call = new CallImpl ( channel , direction ) ; call . _owner = OWNER . SELF ; // clear the channel have just split out. switch ( channelToSplit ) { case ACCEPTING_PARTY : this . setAcceptingParty ( null ) ; break ; case LOCAL_PARTY : if ( this . _direction == CallDirection . INBOUND ) { this . setAcceptingParty ( null ) ; } else { this . setOriginatingParty ( null ) ; } break ; case ORIGINATING_PARTY : this . setOriginatingParty ( null ) ; break ; case REMOTE_PARTY : if ( this . _direction == CallDirection . INBOUND ) this . setOriginatingParty ( null ) ; else this . setAcceptingParty ( null ) ; break ; case TRANSFER_TARGET_PARTY : this . setTransferTargetParty ( null ) ; break ; default : break ; } return call ; } | Splits a channel out of a call into a separate call . This method should only be called from the SplitActivity . | 311 | 24 |
32,263 | public boolean addHangupListener ( CallHangupListener listener ) { boolean callStillUp = true ; if ( ( this . _originatingParty != null && this . _originatingParty . isLive ( ) ) || ( this . _acceptingParty != null && this . _acceptingParty . isLive ( ) ) || ( this . _transferTargetParty != null && this . _transferTargetParty . isLive ( ) ) ) this . _hangupListeners . add ( listener ) ; else callStillUp = false ; return callStillUp ; } | Call this method to get a notification when this call hangs up . | 120 | 13 |
32,264 | public boolean isLive ( ) { boolean live = false ; if ( ( this . _originatingParty != null && this . _originatingParty . isLive ( ) ) || ( this . _acceptingParty != null && this . _acceptingParty . isLive ( ) ) || ( this . _transferTargetParty != null && this . _transferTargetParty . isLive ( ) ) ) live = true ; return live ; } | returns true if the call has any active channels . | 91 | 11 |
32,265 | @ Override public List < Channel > getChannels ( ) { List < Channel > channels = new LinkedList <> ( ) ; if ( _acceptingParty != null ) channels . add ( _acceptingParty ) ; if ( _originatingParty != null ) channels . add ( _originatingParty ) ; if ( _transferTargetParty != null ) channels . add ( _transferTargetParty ) ; return channels ; } | Returns all of the Channels associated with this call . | 90 | 11 |
32,266 | public void masquerade ( ChannelProxy cloneProxy ) throws InvalidChannelName { ChannelImpl originalChannel = this . _channel ; ChannelImpl cloneChannel = cloneProxy . _channel ; cloneChannel . masquerade ( this . _channel ) ; // detach the hangup listeners originalChannel . removeListener ( this ) ; cloneChannel . removeListener ( cloneProxy ) ; // Now we swap the channels. this . _channel = cloneChannel ; cloneProxy . _channel = originalChannel ; // Now re-attach the hangup listeners this . _channel . addHangupListener ( this ) ; cloneProxy . _channel . addHangupListener ( cloneProxy ) ; logger . debug ( originalChannel + " Channel proxy now points to " + this . _channel ) ; } | Used to handle a MasqueradeEvent . We essentially swap the two underlying channels between the two proxies . | 158 | 19 |
32,267 | public static boolean isClassAvailable ( String s ) { final ClassLoader classLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { classLoader . loadClass ( s ) ; return true ; } catch ( ClassNotFoundException e ) { return false ; } } | Checks if the class is available on the current thread s context class loader . | 60 | 16 |
32,268 | public static Object newInstance ( String s ) { final ClassLoader classLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { Class < ? > clazz = classLoader . loadClass ( s ) ; Constructor < ? > constructor = clazz . getConstructor ( ) ; return constructor . newInstance ( ) ; } catch ( ClassNotFoundException e ) { return null ; } catch ( IllegalAccessException e ) { return null ; } catch ( InstantiationException e ) { return null ; } catch ( NoSuchMethodException e ) { // no default constructor return null ; } catch ( InvocationTargetException e ) { // constructor threw an exception return null ; } } | Creates a new instance of the given class . The class is loaded using the current thread s context class loader and instantiated using its default constructor . | 146 | 30 |
32,269 | private static Set < String > getClassNamesFromPackage ( String packageName ) throws IOException , URISyntaxException { ClassLoader classLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; Enumeration < URL > packageURLs ; Set < String > names = new HashSet < String > ( ) ; packageName = packageName . replace ( "." , "/" ) ; packageURLs = classLoader . getResources ( packageName ) ; while ( packageURLs . hasMoreElements ( ) ) { URL packageURL = packageURLs . nextElement ( ) ; if ( packageURL . getProtocol ( ) . equals ( "jar" ) ) { String jarFileName ; Enumeration < JarEntry > jarEntries ; String entryName ; // build jar file name, then loop through entries jarFileName = URLDecoder . decode ( packageURL . getFile ( ) , "UTF-8" ) ; jarFileName = jarFileName . substring ( 5 , jarFileName . indexOf ( "!" ) ) ; logger . info ( ">" + jarFileName ) ; try ( JarFile jf = new JarFile ( jarFileName ) ; ) { jarEntries = jf . entries ( ) ; while ( jarEntries . hasMoreElements ( ) ) { entryName = jarEntries . nextElement ( ) . getName ( ) ; if ( entryName . startsWith ( packageName ) && entryName . endsWith ( ".class" ) ) { entryName = entryName . substring ( packageName . length ( ) + 1 , entryName . lastIndexOf ( ' ' ) ) ; names . add ( entryName ) ; } } } // loop through files in classpath } else { URI uri = new URI ( packageURL . toString ( ) ) ; File folder = new File ( uri . getPath ( ) ) ; // won't work with path which contains blank (%20) // File folder = new File(packageURL.getFile()); File [ ] files = folder . listFiles ( ) ; if ( files != null ) { for ( File actual : files ) { String entryName = actual . getName ( ) ; entryName = entryName . substring ( 0 , entryName . lastIndexOf ( ' ' ) ) ; names . add ( entryName ) ; } } } } // clean up Iterator < String > itr = names . iterator ( ) ; while ( itr . hasNext ( ) ) { String name = itr . next ( ) ; if ( name . equals ( "package" ) || name . endsWith ( "." ) || name . length ( ) == 0 ) { itr . remove ( ) ; } } return names ; } | retrieve all the classes that can be found on the classpath for the specified packageName | 581 | 18 |
32,270 | @ SuppressWarnings ( "unchecked" ) public ManagerResponse buildResponse ( Class < ? extends ManagerResponse > responseClass , Map < String , Object > attributes ) { final ManagerResponse response ; final String responseType = ( String ) attributes . get ( RESPONSE_KEY ) ; if ( RESPONSE_TYPE_ERROR . equalsIgnoreCase ( responseType ) ) { response = new ManagerError ( ) ; } else if ( responseClass == null ) { response = new ManagerResponse ( ) ; } else { try { response = responseClass . newInstance ( ) ; } catch ( Exception ex ) { logger . error ( "Unable to create new instance of " + responseClass . getName ( ) , ex ) ; return null ; } } setAttributes ( response , attributes , ignoredAttributes ) ; if ( response instanceof CommandResponse ) { final CommandResponse commandResponse = ( CommandResponse ) response ; final List < String > result = new ArrayList <> ( ) ; //For Asterisk 14 if ( attributes . get ( OUTPUT_RESPONSE_KEY ) != null ) { if ( attributes . get ( OUTPUT_RESPONSE_KEY ) instanceof List ) { for ( String tmp : ( List < String > ) attributes . get ( OUTPUT_RESPONSE_KEY ) ) { if ( tmp != null && tmp . length ( ) != 0 ) { result . add ( tmp . trim ( ) ) ; } } } else { result . add ( ( String ) attributes . get ( OUTPUT_RESPONSE_KEY ) ) ; } } else { for ( String resultLine : ( ( String ) attributes . get ( ManagerReader . COMMAND_RESULT_RESPONSE_KEY ) ) . split ( "\n" ) ) { // on error there is a leading space if ( ! resultLine . equals ( "--END COMMAND--" ) && ! resultLine . equals ( " --END COMMAND--" ) ) { result . add ( resultLine ) ; } } } commandResponse . setResult ( result ) ; } if ( response . getResponse ( ) != null && attributes . get ( PROXY_RESPONSE_KEY ) != null ) { response . setResponse ( ( String ) attributes . get ( PROXY_RESPONSE_KEY ) ) ; } // make the map of all attributes available to the response // but clone it as it is reused by the ManagerReader response . setAttributes ( new HashMap <> ( attributes ) ) ; return response ; } | Asterisk 14 . 3 . 0 | 535 | 8 |
32,271 | private synchronized void handleEvent ( final StatusCompleteEvent event ) { for ( final Peer peer : this . peerList ) { peer . endSweep ( ) ; } PeerMonitor . logger . debug ( "Channel Mark and Sweep complete" ) ; //$NON-NLS-1$ } | We receive the StatusComplete event once the Mark and Sweep channel operation has completed . We now call endSweep which will remove any channels that were not marked during the operation . | 61 | 35 |
32,272 | public void startSweep ( ) { PeerMonitor . logger . debug ( "Starting channel mark and sweep" ) ; //$NON-NLS-1$ // Mark every channel as 'clearing' synchronized ( PeerMonitor . class ) { for ( final Peer peer : this . peerList ) { peer . startSweep ( ) ; } } /** * Request Asterisk to send us a status update for every channel. */ final StatusAction sa = new StatusAction ( ) ; try { AsteriskPBX pbx = ( AsteriskPBX ) PBXFactory . getActivePBX ( ) ; pbx . sendAction ( sa , 5000 ) ; } catch ( final Exception e ) { PeerMonitor . logger . error ( e , e ) ; } } | Check every channel to make certain they are still active . We do this in case we missed a hangup event along the way somewhere . This allows us to cleanup any old channels . We start by clearing the mark on all channels and then generates a Asterisk status message for every active channel . At the end of the process any channels which haven t been marked are then discarded . | 161 | 75 |
32,273 | private synchronized Map < String , String [ ] > parseParameters ( String s ) { Map < String , List < String > > parameterMap ; Map < String , String [ ] > result ; StringTokenizer st ; parameterMap = new HashMap <> ( ) ; result = new HashMap <> ( ) ; if ( s == null ) { return result ; } st = new StringTokenizer ( s , "&" ) ; while ( st . hasMoreTokens ( ) ) { String parameter ; Matcher parameterMatcher ; String name ; String value ; List < String > values ; parameter = st . nextToken ( ) ; parameterMatcher = PARAMETER_PATTERN . matcher ( parameter ) ; if ( parameterMatcher . matches ( ) ) { try { name = URLDecoder . decode ( parameterMatcher . group ( 1 ) , "UTF-8" ) ; value = URLDecoder . decode ( parameterMatcher . group ( 2 ) , "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { logger . error ( "Unable to decode parameter '" + parameter + "'" , e ) ; continue ; } } else { try { name = URLDecoder . decode ( parameter , "UTF-8" ) ; value = "" ; } catch ( UnsupportedEncodingException e ) { logger . error ( "Unable to decode parameter '" + parameter + "'" , e ) ; continue ; } } if ( parameterMap . get ( name ) == null ) { values = new ArrayList <> ( ) ; values . add ( value ) ; parameterMap . put ( name , values ) ; } else { values = parameterMap . get ( name ) ; values . add ( value ) ; } } for ( Map . Entry < String , List < String > > entry : parameterMap . entrySet ( ) ) { String [ ] valueArray ; valueArray = new String [ entry . getValue ( ) . size ( ) ] ; result . put ( entry . getKey ( ) , entry . getValue ( ) . toArray ( valueArray ) ) ; } return result ; } | Parses the given parameter string and caches the result . | 449 | 12 |
32,274 | protected AgiChannel getChannel ( ) { AgiChannel threadBoundChannel ; if ( channel != null ) { return channel ; } threadBoundChannel = AgiConnectionHandler . getChannel ( ) ; if ( threadBoundChannel == null ) { throw new IllegalStateException ( "Trying to send command from an invalid thread" ) ; } return threadBoundChannel ; } | Returns the channel to operate on . | 76 | 7 |
32,275 | public ManagerConnection connect ( final AsteriskSettings asteriskSettings ) throws IOException , AuthenticationFailedException , TimeoutException , IllegalStateException { checkIfAsteriskRunning ( asteriskSettings ) ; this . makeConnection ( asteriskSettings ) ; return this . managerConnection ; } | Establishes a Asterisk ManagerConnection as well as performing the login required by Asterisk . | 59 | 19 |
32,276 | private void checkIfAsteriskRunning ( AsteriskSettings asteriskSettings ) throws UnknownHostException , IOException { try ( Socket socket = new Socket ( ) ) { socket . setSoTimeout ( 2000 ) ; InetSocketAddress asteriskHost = new InetSocketAddress ( asteriskSettings . getAsteriskIP ( ) , asteriskSettings . getManagerPortNo ( ) ) ; socket . connect ( asteriskHost , 2000 ) ; } } | This method will try to make a simple tcp connection to the asterisk manager to establish it is up . We do this as the default makeConnection doesn t have a timeout and will sit trying to connect for a minute or so . By using method when the user realises they have a problem on start up they can go to the asterisk panel . Fix the problem and then we can retry with the new connection settings within a couple of seconds rather than waiting a minute for a timeout . | 95 | 98 |
32,277 | synchronized private MeetmeRoom findMeetmeRoom ( final String roomNumber ) { MeetmeRoom foundRoom = null ; for ( final MeetmeRoom room : this . rooms ) { if ( room . getRoomNumber ( ) . compareToIgnoreCase ( roomNumber ) == 0 ) { foundRoom = room ; break ; } } return foundRoom ; } | Returns the MeetmeRoom for the given room number . The room number will be an integer value offset from the meetme base address . | 76 | 27 |
32,278 | public static AsteriskVersion getDetermineVersionFromString ( String coreLine ) { for ( AsteriskVersion version : knownVersions ) { for ( Pattern pattern : version . patterns ) { if ( pattern . matcher ( coreLine ) . matches ( ) ) { return version ; } } } return null ; } | Determine the Asterisk version from the string returned by Asterisk . The string should contain Asterisk followed by a version number . | 65 | 27 |
32,279 | void updateQueue ( String queue ) throws ManagerCommunicationException { ResponseEvents re ; try { QueueStatusAction queueStatusAction = new QueueStatusAction ( ) ; queueStatusAction . setQueue ( queue ) ; re = server . sendEventGeneratingAction ( queueStatusAction ) ; } catch ( ManagerCommunicationException e ) { final Throwable cause = e . getCause ( ) ; if ( cause instanceof EventTimeoutException ) { // this happens with Asterisk 1.0.x as it doesn't send a // QueueStatusCompleteEvent re = ( ( EventTimeoutException ) cause ) . getPartialResult ( ) ; } else { throw e ; } } for ( ManagerEvent event : re . getEvents ( ) ) { // 101119 OLB: solo actualizamos el QUEUE por ahora if ( event instanceof QueueParamsEvent ) { handleQueueParamsEvent ( ( QueueParamsEvent ) event ) ; } else if ( event instanceof QueueMemberEvent ) { handleQueueMemberEvent ( ( QueueMemberEvent ) event ) ; } else if ( event instanceof QueueEntryEvent ) { handleQueueEntryEvent ( ( QueueEntryEvent ) event ) ; } } } | Method to ask for a Queue data update | 258 | 9 |
32,280 | private void handleQueueParamsEvent ( QueueParamsEvent event ) { AsteriskQueueImpl queue ; final String name = event . getQueue ( ) ; final Integer max = event . getMax ( ) ; final String strategy = event . getStrategy ( ) ; final Integer serviceLevel = event . getServiceLevel ( ) ; final Integer weight = event . getWeight ( ) ; final Integer calls = event . getCalls ( ) ; final Integer holdTime = event . getHoldTime ( ) ; final Integer talkTime = event . getTalkTime ( ) ; final Integer completed = event . getCompleted ( ) ; final Integer abandoned = event . getAbandoned ( ) ; final Double serviceLevelPerf = event . getServiceLevelPerf ( ) ; queue = getInternalQueueByName ( name ) ; if ( queue == null ) { queue = new AsteriskQueueImpl ( server , name , max , strategy , serviceLevel , weight , calls , holdTime , talkTime , completed , abandoned , serviceLevelPerf ) ; logger . info ( "Adding new queue " + queue ) ; addQueue ( queue ) ; } else { // We should never reach that code as this method is only called for // initialization // So the queue should never be in the queues list synchronized ( queue ) { synchronized ( queuesLRU ) { if ( queue . setMax ( max ) | queue . setServiceLevel ( serviceLevel ) | queue . setWeight ( weight ) | queue . setCalls ( calls ) | queue . setHoldTime ( holdTime ) | queue . setTalkTime ( talkTime ) | queue . setCompleted ( completed ) | queue . setAbandoned ( abandoned ) | queue . setServiceLevelPerf ( serviceLevelPerf ) ) { queuesLRU . remove ( queue . getName ( ) ) ; queuesLRU . put ( queue . getName ( ) , queue ) ; } } } } } | Called during initialization to populate the list of queues . | 402 | 11 |
32,281 | private void handleQueueMemberEvent ( QueueMemberEvent event ) { final AsteriskQueueImpl queue = getInternalQueueByName ( event . getQueue ( ) ) ; if ( queue == null ) { logger . error ( "Ignored QueueEntryEvent for unknown queue " + event . getQueue ( ) ) ; return ; } AsteriskQueueMemberImpl member = queue . getMember ( event . getLocation ( ) ) ; if ( member == null ) { member = new AsteriskQueueMemberImpl ( server , queue , event . getLocation ( ) , QueueMemberState . valueOf ( event . getStatus ( ) ) , event . getPaused ( ) , event . getPenalty ( ) , event . getMembership ( ) , event . getCallsTaken ( ) , event . getLastCall ( ) ) ; queue . addMember ( member ) ; } else { manageQueueMemberChange ( queue , member , event ) ; } } | Called during initialization to populate the members of the queues . | 200 | 12 |
32,282 | void handleJoinEvent ( JoinEvent event ) { final AsteriskQueueImpl queue = getInternalQueueByName ( event . getQueue ( ) ) ; final AsteriskChannelImpl channel = channelManager . getChannelImplByName ( event . getChannel ( ) ) ; if ( queue == null ) { logger . error ( "Ignored JoinEvent for unknown queue " + event . getQueue ( ) ) ; return ; } if ( channel == null ) { logger . error ( "Ignored JoinEvent for unknown channel " + event . getChannel ( ) ) ; return ; } if ( queue . getEntry ( event . getChannel ( ) ) != null ) { logger . error ( "Ignored duplicate queue entry in queue " + event . getQueue ( ) + " for channel " + event . getChannel ( ) ) ; return ; } // Asterisk gives us an initial position but doesn't tell us when he // shifts the others // We won't use this data for ordering until there is a appropriate // event in AMI. // (and refreshing the whole queue is too intensive and suffers // incoherencies // due to asynchronous shift that leaves holes if requested too fast) int reportedPosition = event . getPosition ( ) ; queue . createNewEntry ( channel , reportedPosition , event . getDateReceived ( ) ) ; } | Called from AsteriskServerImpl whenever a new entry appears in a queue . | 275 | 16 |
32,283 | void handleLeaveEvent ( LeaveEvent event ) { final AsteriskQueueImpl queue = getInternalQueueByName ( event . getQueue ( ) ) ; final AsteriskChannelImpl channel = channelManager . getChannelImplByName ( event . getChannel ( ) ) ; if ( queue == null ) { logger . error ( "Ignored LeaveEvent for unknown queue " + event . getQueue ( ) ) ; return ; } if ( channel == null ) { logger . error ( "Ignored LeaveEvent for unknown channel " + event . getChannel ( ) ) ; return ; } final AsteriskQueueEntryImpl existingQueueEntry = queue . getEntry ( event . getChannel ( ) ) ; if ( existingQueueEntry == null ) { logger . error ( "Ignored leave event for non existing queue entry in queue " + event . getQueue ( ) + " for channel " + event . getChannel ( ) ) ; return ; } queue . removeEntry ( existingQueueEntry , event . getDateReceived ( ) ) ; } | Called from AsteriskServerImpl whenever an enty leaves a queue . | 212 | 15 |
32,284 | void handleQueueMemberStatusEvent ( QueueMemberStatusEvent event ) { AsteriskQueueImpl queue = getInternalQueueByName ( event . getQueue ( ) ) ; if ( queue == null ) { logger . error ( "Ignored QueueMemberStatusEvent for unknown queue " + event . getQueue ( ) ) ; return ; } AsteriskQueueMemberImpl member = queue . getMemberByLocation ( event . getLocation ( ) ) ; if ( member == null ) { logger . error ( "Ignored QueueMemberStatusEvent for unknown member " + event . getLocation ( ) ) ; return ; } manageQueueMemberChange ( queue , member , event ) ; queue . fireMemberStateChanged ( member ) ; } | Challange a QueueMemberStatusEvent . Called from AsteriskServerImpl whenever a member state changes . | 150 | 21 |
32,285 | AsteriskQueueImpl getQueueByName ( String queueName ) { refreshQueueIfForced ( queueName ) ; AsteriskQueueImpl queue = getInternalQueueByName ( queueName ) ; if ( queue == null ) { logger . error ( "Requested queue '" + queueName + "' not found!" ) ; } return queue ; } | Retrieves a queue by its name . | 73 | 9 |
32,286 | public void handleQueueMemberRemovedEvent ( QueueMemberRemovedEvent event ) { final AsteriskQueueImpl queue = getInternalQueueByName ( event . getQueue ( ) ) ; if ( queue == null ) { logger . error ( "Ignored QueueMemberRemovedEvent for unknown queue " + event . getQueue ( ) ) ; return ; } final AsteriskQueueMemberImpl member = queue . getMember ( event . getLocation ( ) ) ; if ( member == null ) { logger . error ( "Ignored QueueMemberRemovedEvent for unknown agent name: " + event . getMemberName ( ) + " location: " + event . getLocation ( ) + " queue: " + event . getQueue ( ) ) ; return ; } queue . removeMember ( member ) ; } | Challange a QueueMemberRemovedEvent . | 164 | 9 |
32,287 | void fireNewEntry ( AsteriskQueueEntryImpl entry ) { synchronized ( listeners ) { for ( AsteriskQueueListener listener : listeners ) { try { listener . onNewEntry ( entry ) ; } catch ( Exception e ) { logger . warn ( "Exception in onNewEntry()" , e ) ; } } } } | Notifies all registered listener that an entry joins the queue . | 67 | 12 |
32,288 | void fireEntryLeave ( AsteriskQueueEntryImpl entry ) { synchronized ( listeners ) { for ( AsteriskQueueListener listener : listeners ) { try { listener . onEntryLeave ( entry ) ; } catch ( Exception e ) { logger . warn ( "Exception in onEntryLeave()" , e ) ; } } } } | Notifies all registered listener that an entry leaves the queue . | 67 | 12 |
32,289 | void fireMemberAdded ( AsteriskQueueMemberImpl member ) { synchronized ( listeners ) { for ( AsteriskQueueListener listener : listeners ) { try { listener . onMemberAdded ( member ) ; } catch ( Exception e ) { logger . warn ( "Exception in onMemberAdded()" , e ) ; } } } } | Notifies all registered listener that a member has been added to the queue . | 67 | 15 |
32,290 | void fireMemberRemoved ( AsteriskQueueMemberImpl member ) { synchronized ( listeners ) { for ( AsteriskQueueListener listener : listeners ) { try { listener . onMemberRemoved ( member ) ; } catch ( Exception e ) { logger . warn ( "Exception in onMemberRemoved()" , e ) ; } } } } | Notifies all registered listener that a member has been removed from the queue . | 67 | 15 |
32,291 | public Collection < AsteriskQueueMember > getMembers ( ) { List < AsteriskQueueMember > listOfMembers = new ArrayList <> ( members . size ( ) ) ; synchronized ( members ) { listOfMembers . addAll ( members . values ( ) ) ; } return listOfMembers ; } | Returns a collection of members of this queue . | 63 | 9 |
32,292 | AsteriskQueueMemberImpl getMember ( String location ) { synchronized ( members ) { if ( members . containsKey ( location ) ) { return members . get ( location ) ; } } return null ; } | Returns a member by its location . | 43 | 7 |
32,293 | void addMember ( AsteriskQueueMemberImpl member ) { synchronized ( members ) { // Check if member already exists if ( members . containsValue ( member ) ) { return ; } // If not, add the new member. logger . info ( "Adding new member to the queue " + getName ( ) + ": " + member . toString ( ) ) ; members . put ( member . getLocation ( ) , member ) ; } fireMemberAdded ( member ) ; } | Add a new member to this queue . | 99 | 8 |
32,294 | AsteriskQueueMemberImpl getMemberByLocation ( String location ) { AsteriskQueueMemberImpl member ; synchronized ( members ) { member = members . get ( location ) ; } if ( member == null ) { logger . error ( "Requested member at location " + location + " not found!" ) ; } return member ; } | Retrieves a member by its location . | 69 | 9 |
32,295 | void fireMemberStateChanged ( AsteriskQueueMemberImpl member ) { synchronized ( listeners ) { for ( AsteriskQueueListener listener : listeners ) { try { listener . onMemberStateChange ( member ) ; } catch ( Exception e ) { logger . warn ( "Exception in onMemberStateChange()" , e ) ; } } } } | Notifies all registered listener that a queue member changes its state . | 70 | 13 |
32,296 | AsteriskQueueEntryImpl getEntry ( String channelName ) { synchronized ( entries ) { for ( AsteriskQueueEntryImpl entry : entries ) { if ( entry . getChannel ( ) . getName ( ) . equals ( channelName ) ) { return entry ; } } } return null ; } | Gets an entry of the queue by its channel name . | 62 | 12 |
32,297 | public void removeMember ( AsteriskQueueMemberImpl member ) { synchronized ( members ) { // Check if member exists if ( ! members . containsValue ( member ) ) { return ; } // If so, remove the member. logger . info ( "Remove member from the queue " + getName ( ) + ": " + member . toString ( ) ) ; members . remove ( member . getLocation ( ) ) ; } fireMemberRemoved ( member ) ; } | Removes a member from this queue . | 96 | 8 |
32,298 | @ Override public boolean isSIP ( ) { return this . _tech == TechType . SIP || this . _tech == TechType . IAX || this . _tech == TechType . IAX2 ; } | For the purposes of asterisk IAX and SIP are both considered SIP . | 47 | 17 |
32,299 | public char getDigit ( ) { final String digit = agiReply . getAttribute ( "digit" ) ; if ( digit == null || digit . length ( ) == 0 ) { return 0x0 ; } return digit . charAt ( 0 ) ; } | Returns the DTMF digit that was received . | 55 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.