idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
32,300
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 .
32,301
public ManagerResponse sendAction ( ManagerAction action , long timeout ) throws IOException , TimeoutException , IllegalArgumentException , IllegalStateException { ResponseHandlerResult result = new ResponseHandlerResult ( ) ; SendActionCallback callbackHandler = new DefaultSendActionCallback ( result ) ; sendAction ( action , callbackHandler ) ; if ( action instanceof UserEventAction ) { return null ; } if ( result . getResponse ( ) == null ) { try { result . await ( timeout ) ; } catch ( InterruptedException ex ) { logger . warn ( "Interrupted while waiting for result" ) ; Thread . currentThread ( ) . interrupt ( ) ; } } 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 .
32,302
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 .
32,303
public void dispatchEvent ( ManagerEvent event ) { 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 ( ) ) ; } 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 { } } if ( event instanceof DisconnectEvent ) { synchronized ( this ) { if ( state == CONNECTED ) { state = RECONNECTING ; 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 ( ) ; } else { return ; } } } if ( event instanceof ProtocolIdentifierReceivedEvent ) { ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent ; String protocolIdentifier ; protocolIdentifierReceivedEvent = ( ProtocolIdentifierReceivedEvent ) event ; protocolIdentifier = protocolIdentifierReceivedEvent . getProtocolIdentifier ( ) ; setProtocolIdentifier ( protocolIdentifier ) ; return ; } fireEvent ( event ) ; }
This method is called by the reader whenever a ManagerEvent is received . The event is dispatched to all registered ManagerEventHandlers .
32,304
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 .
32,305
@ 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
32,306
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 .
32,307
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 ) { } } } 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 .
32,308
protected File searchFile ( String scriptName , String [ ] path ) { if ( scriptName == null || path == null ) { return null ; } for ( String pathElement : path ) { final File pathElementDir = new File ( pathElement ) ; if ( ! pathElementDir . isDirectory ( ) ) { continue ; } final File file = new File ( pathElementDir , scriptName . replaceAll ( "/" , Matcher . quoteReplacement ( File . separator ) ) ) ; if ( ! file . exists ( ) ) { continue ; } try { 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 .
32,309
public void onManagerEvent ( final org . asteriskjava . manager . event . ManagerEvent event ) { boolean wanted = false ; synchronized ( this . globalEvents ) { Class < ? extends ManagerEvent > shadowEvent = CoherentEventFactory . getShadowEvent ( event ) ; if ( this . globalEvents . contains ( shadowEvent ) ) { wanted = true ; } } if ( wanted ) { 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:" + this . _queueMaxSize + " avg:" + ( this . _queueSum / this . _queueCount ) ) ; } } } }
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 .
32,310
public void dispatchEvent ( final ManagerEvent event ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "dispatch=" + event . toString ( ) ) ; } 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 { latch . countDown ( ) ; } } latch . await ( ) ; if ( totalTime . timeTaken ( ) > 500 ) { logger . warn ( "Too long to process event " + event + " time taken: " + totalTime . timeTaken ( ) ) ; } } 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 .
32,311
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 .
32,312
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
32,313
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 .
32,314
public CallImpl join ( OperandChannel originatingOperand , Call rhs , OperandChannel acceptingOperand , CallDirection direction ) throws PBXException { CallImpl joinTo = ( CallImpl ) rhs ; Channel originatingParty = null ; Channel acceptingParty = null ; originatingParty = this . getOperandChannel ( originatingOperand ) ; if ( originatingParty != null && originatingParty . isLive ( ) ) originatingParty . removeListener ( this ) ; 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" ) ; 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 ) ; 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 .
32,315
public Call split ( OperandChannel channelToSplit ) throws PBXException { Channel channel = this . getOperandChannel ( channelToSplit ) ; channel . removeListener ( this ) ; CallDirection direction = CallDirection . INBOUND ; if ( this . getLocalParty ( ) != null && this . getLocalParty ( ) . isSame ( channel ) ) { direction = CallDirection . OUTBOUND ; } CallImpl call = new CallImpl ( channel , direction ) ; call . _owner = OWNER . SELF ; 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 .
32,316
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 .
32,317
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 .
32,318
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 .
32,319
public void masquerade ( ChannelProxy cloneProxy ) throws InvalidChannelName { ChannelImpl originalChannel = this . _channel ; ChannelImpl cloneChannel = cloneProxy . _channel ; cloneChannel . masquerade ( this . _channel ) ; originalChannel . removeListener ( this ) ; cloneChannel . removeListener ( cloneProxy ) ; this . _channel = cloneChannel ; cloneProxy . _channel = originalChannel ; 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 .
32,320
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 .
32,321
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 ) { return null ; } catch ( InvocationTargetException e ) { 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 .
32,322
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 ; 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 ) ; } } } } else { URI uri = new URI ( packageURL . toString ( ) ) ; File folder = new File ( uri . getPath ( ) ) ; File [ ] files = folder . listFiles ( ) ; if ( files != null ) { for ( File actual : files ) { String entryName = actual . getName ( ) ; entryName = entryName . substring ( 0 , entryName . lastIndexOf ( '.' ) ) ; names . add ( entryName ) ; } } } } 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
32,323
@ 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 < > ( ) ; 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" ) ) { 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 ) ) ; } response . setAttributes ( new HashMap < > ( attributes ) ) ; return response ; }
Asterisk 14 . 3 . 0
32,324
private synchronized void handleEvent ( final StatusCompleteEvent event ) { for ( final Peer peer : this . peerList ) { peer . endSweep ( ) ; } PeerMonitor . logger . debug ( "Channel Mark and Sweep complete" ) ; }
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 .
32,325
public void startSweep ( ) { PeerMonitor . logger . debug ( "Starting channel mark and sweep" ) ; synchronized ( PeerMonitor . class ) { for ( final Peer peer : this . peerList ) { peer . startSweep ( ) ; } } 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 .
32,326
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 .
32,327
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 .
32,328
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 .
32,329
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 .
32,330
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 .
32,331
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 .
32,332
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 ) { re = ( ( EventTimeoutException ) cause ) . getPartialResult ( ) ; } else { throw e ; } } for ( ManagerEvent event : re . getEvents ( ) ) { 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
32,333
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 { 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 .
32,334
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 .
32,335
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 ; } int reportedPosition = event . getPosition ( ) ; queue . createNewEntry ( channel , reportedPosition , event . getDateReceived ( ) ) ; }
Called from AsteriskServerImpl whenever a new entry appears in a queue .
32,336
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 .
32,337
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 .
32,338
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 .
32,339
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 .
32,340
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 .
32,341
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 .
32,342
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 .
32,343
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 .
32,344
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 .
32,345
AsteriskQueueMemberImpl getMember ( String location ) { synchronized ( members ) { if ( members . containsKey ( location ) ) { return members . get ( location ) ; } } return null ; }
Returns a member by its location .
32,346
void addMember ( AsteriskQueueMemberImpl member ) { synchronized ( members ) { if ( members . containsValue ( member ) ) { return ; } 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 .
32,347
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 .
32,348
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 .
32,349
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 .
32,350
public void removeMember ( AsteriskQueueMemberImpl member ) { synchronized ( members ) { if ( ! members . containsValue ( member ) ) { return ; } logger . info ( "Remove member from the queue " + getName ( ) + ": " + member . toString ( ) ) ; members . remove ( member . getLocation ( ) ) ; } fireMemberRemoved ( member ) ; }
Removes a member from this queue .
32,351
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 .
32,352
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 .
32,353
public int getNumberOfResults ( ) { final String numberOfResults = agiReply . getAttribute ( "results" ) ; return numberOfResults == null ? 0 : Integer . parseInt ( numberOfResults ) ; }
Returns how many results have been recoginized . Usually there is only one result but if multiple rules in the grammar match multiple results may be returned .
32,354
void performPostCreationTasks ( ) { StatusAction statusAction = new StatusAction ( ) ; try { ResponseEvents events = CoherentManagerConnection . sendEventGeneratingAction ( statusAction , 1000 ) ; for ( ResponseEvent event : events . getEvents ( ) ) { if ( event instanceof StatusEvent ) { } } } catch ( IllegalArgumentException | IllegalStateException | IOException | TimeoutException e ) { logger . error ( e , e ) ; } }
Find all the channels that came into existence before startup . This can t be done during the Constructor call because it requires calls back to AsteriskPBX which isn t finished constructing until after the Constructor returns .
32,355
void mergeCalls ( CallTracker rhs ) { synchronized ( this . _associatedChannels ) { this . _associatedChannels . addAll ( rhs . _associatedChannels ) ; rhs . _associatedChannels . clear ( ) ; } }
Used to merge two calls into a single call . This is required as during a masquerade a new channel is created an initially we will create a CallTracker for it . When the masquerade event finally turns up we will realise it belongs to an existing CallTracker and as such we need to merge the two CallTrackers .
32,356
public void remove ( Channel channel ) { synchronized ( this . _associatedChannels ) { int index = findChannel ( channel ) ; if ( index != - 1 ) { if ( logger . isDebugEnabled ( ) ) logger . debug ( "CallTracker removing channel: " + this . toString ( ) + " " + channel . getExtendedChannelName ( ) ) ; this . _associatedChannels . remove ( index ) ; } } }
Remove a channel from the call .
32,357
ManagerEvent addMember ( BridgeEnterEvent event ) { List < BridgeEnterEvent > remaining = null ; synchronized ( members ) { if ( members . put ( event . getChannel ( ) , event ) == null && members . size ( ) == 2 ) { remaining = new ArrayList < > ( members . values ( ) ) ; } } if ( remaining == null ) { return null ; } logger . info ( "Members size " + remaining . size ( ) + " " + event ) ; BridgeEvent bridgeEvent = buildBridgeEvent ( BridgeEvent . BRIDGE_STATE_LINK , remaining ) ; logger . info ( "Bridge " + bridgeEvent . getChannel1 ( ) + " " + bridgeEvent . getChannel2 ( ) ) ; return bridgeEvent ; }
if there are exactly 2 members in the bridge return a BridgeEvent
32,358
ManagerEvent removeMember ( BridgeLeaveEvent event ) { List < BridgeEnterEvent > remaining = null ; synchronized ( members ) { if ( members . remove ( event . getChannel ( ) ) != null && members . size ( ) == 2 ) { remaining = new ArrayList < > ( members . values ( ) ) ; } } if ( remaining == null ) { return null ; } return buildBridgeEvent ( BridgeEvent . BRIDGE_STATE_UNLINK , remaining ) ; }
If there are exactly 2 members in the bridge return a BridgeEvent
32,359
public synchronized static Log getLog ( Class < ? > clazz ) { if ( slf4jLoggingAvailable == null ) { try { classLoader . loadClass ( "org.slf4j.Logger" ) ; slf4jLoggingAvailable = Boolean . TRUE ; } catch ( Exception e ) { slf4jLoggingAvailable = Boolean . FALSE ; } } if ( slf4jLoggingAvailable ) { try { return new Slf4JLogger ( clazz ) ; } catch ( Throwable e ) { slf4jLoggingAvailable = Boolean . FALSE ; } } if ( log4jLoggingAvailable == null ) { try { classLoader . loadClass ( "org.apache.log4j.Logger" ) ; log4jLoggingAvailable = Boolean . TRUE ; } catch ( Exception e ) { log4jLoggingAvailable = Boolean . FALSE ; } } if ( log4jLoggingAvailable ) { return new Log4JLogger ( clazz ) ; } if ( javaLoggingAvailable == null ) { try { classLoader . loadClass ( "java.util.logging.Logger" ) ; javaLoggingAvailable = Boolean . TRUE ; } catch ( Exception e ) { javaLoggingAvailable = Boolean . FALSE ; } } if ( javaLoggingAvailable ) { return new JavaLoggingLog ( clazz ) ; } return new NullLog ( ) ; }
Returns an instance of Log suitable for logging from the given class .
32,360
public void handleEvent ( final MasqueradeEvent b ) { if ( this . isConnectedToSelf ( b . getClone ( ) ) ) { CallTracker original = findCall ( b . getOriginal ( ) ) ; CallTracker clone = findCall ( b . getClone ( ) ) ; if ( original != null && clone != null ) { clone . mergeCalls ( original ) ; clone . setState ( b . getCloneState ( ) ) ; this . evaluateState ( ) ; } else logger . warn ( "When processing masquradeEvent we could not find the expected calls. event=" + b . toString ( ) + " original=" + original + " clone=" + clone ) ; } }
We handle the masqurade event is it contains channel state information . During a masquerade we will have two channels for the one peer the original and the clone . As the clone is taking over from the original peer we now need to use that as true indicator of state .
32,361
public void handleEvent ( final NewChannelEvent b ) { if ( ( b . getChannel ( ) == null ) || ( b . getChannel ( ) . isConsole ( ) ) ) { return ; } if ( this . isConnectedToSelf ( b . getChannel ( ) ) ) { CallTracker call = this . registerChannel ( b . getChannel ( ) ) ; if ( call != null ) { call . setState ( b . getChannelState ( ) ) ; this . evaluateState ( ) ; } } }
When a new channel comes up associated it with the peer . Be warned a peer can have multiple calls associated with it .
32,362
private void evaluateState ( ) { synchronized ( this . callList ) { PeerState newState = PeerState . NOTSET ; for ( CallTracker call : this . callList ) { if ( call . getState ( ) . getPriority ( ) > newState . getPriority ( ) ) newState = call . getState ( ) ; } this . _state = newState ; } }
Called each time the state of a call changes to determine the Peers overall state .
32,363
public final void registerEventClass ( String eventType , Class < ? extends ManagerEvent > clazz ) throws IllegalArgumentException { Constructor < ? > defaultConstructor ; if ( ! ManagerEvent . class . isAssignableFrom ( clazz ) ) { throw new IllegalArgumentException ( clazz + " is not a ManagerEvent" ) ; } if ( ( clazz . getModifiers ( ) & Modifier . ABSTRACT ) != 0 ) { throw new IllegalArgumentException ( clazz + " is abstract" ) ; } try { defaultConstructor = clazz . getConstructor ( Object . class ) ; } catch ( NoSuchMethodException ex ) { throw new IllegalArgumentException ( clazz + " has no usable constructor" ) ; } if ( ( defaultConstructor . getModifiers ( ) & Modifier . PUBLIC ) == 0 ) { throw new IllegalArgumentException ( clazz + " has no public default constructor" ) ; } registeredEventClasses . put ( eventType . toLowerCase ( Locale . US ) , clazz ) ; logger . debug ( "Registered event type '" + eventType + "' (" + clazz + ")" ) ; }
Registers a new event class for the event given by eventType .
32,364
public void masquerade ( Channel channel ) { if ( channel . hasCallerID ( ) ) { this . _callerID = channel . getCallerID ( ) ; } else if ( this . _callerID != null && ( ( ChannelImpl ) channel ) . _callerID != null ) { PBX pbx = PBXFactory . getActivePBX ( ) ; if ( this . _callerID != null ) { ( ( ChannelImpl ) channel ) . _callerID = pbx . buildCallerID ( this . _callerID . getNumber ( ) , this . _callerID . getName ( ) ) ; } } this . _muted = channel . isMute ( ) ; this . _parked = channel . isParked ( ) ; this . _marked = true ; this . _sweepStartTime = null ; }
designed for use by the ChannelProxy when a channel is being cloned as a result of Asterisk undertaking an Masquerade . This is not intended to be a complete clone just the key elements that we generally track on our side rather than getting directly from asterisk .
32,365
private void validateChannelName ( final String channelName ) throws InvalidChannelName { if ( ! this . _isConsole ) { if ( ! TechType . hasValidTech ( channelName ) ) { throw new InvalidChannelName ( "Invalid channelName: " + channelName + ". Unknown tech." ) ; } final int hypen = channelName . indexOf ( "-" ) ; if ( hypen == - 1 ) { throw new InvalidChannelName ( "Invalid channelName: " + channelName + ". Missing hypen." ) ; } final int slash = channelName . indexOf ( "/" ) ; if ( slash == - 1 ) { throw new InvalidChannelName ( "Invalid channelName: " + channelName + ". Missing slash." ) ; } if ( hypen < slash ) { throw new InvalidChannelName ( "Invalid channelName: " + channelName + ". Hypen must be after the slash." ) ; } if ( ( hypen - slash ) < 2 ) { throw new InvalidChannelName ( "Invalid channelName: " + channelName + ". Must be one character between the hypen and the slash." ) ; } if ( ( channelName . length ( ) - hypen ) < 2 ) { throw new InvalidChannelName ( "Invalid channelName: " + channelName + ". The channel sequence number must be at least 1 character." ) ; } } }
validates the channel name . Validate is to be called after the channel has been cleaned .
32,366
public boolean sameUniqueID ( String uniqueID ) { boolean equals = false ; if ( ( this . _uniqueID . compareTo ( ChannelImpl . UNKNOWN_UNIQUE_ID ) != 0 ) && ( uniqueID . compareTo ( ChannelImpl . UNKNOWN_UNIQUE_ID ) != 0 ) ) { if ( this . _uniqueID . compareTo ( uniqueID ) == 0 ) { equals = true ; } } return equals ; }
Try to match a channel based solely on its unique ID
32,367
public void notifyHangupListeners ( Integer cause , String causeText ) { this . _isLive = false ; if ( this . hangupListener != null ) { this . hangupListener . channelHangup ( this , cause , causeText ) ; } else { logger . warn ( "Hangup listener is null" ) ; } }
Called by Peer when we have been hungup . This can happen when Peer receives a HangupEvent or during a periodic sweep done by PeerMonitor to find the status of all channels . Notify any listeners that this channel has been hung up .
32,368
public String getExtendedChannelName ( ) { final StringBuilder name = new StringBuilder ( ) ; if ( this . _isInAction ) { name . append ( this . _actionPrefix ) ; name . append ( "/" ) ; } name . append ( this . _channelName ) ; if ( this . _isMasqueraded ) { name . append ( ChannelImpl . MASQ ) ; } if ( this . _isZombie ) { name . append ( ChannelImpl . ZOMBIE ) ; } return name . toString ( ) ; }
Returns the full channel name including the masquerade prefix and the zombie suffix .
32,369
@ SuppressWarnings ( "unchecked" ) protected AgiScript createAgiScriptInstance ( String className ) { Class < ? > tmpClass ; Class < AgiScript > agiScriptClass ; Constructor < AgiScript > constructor ; AgiScript agiScript ; agiScript = null ; try { tmpClass = getClassLoader ( ) . loadClass ( className ) ; } catch ( ClassNotFoundException e1 ) { logger . debug ( "Unable to create AgiScript instance of type " + className + ": Class not found, make sure the class exists and is available on the CLASSPATH" ) ; return null ; } if ( ! AgiScript . class . isAssignableFrom ( tmpClass ) ) { logger . warn ( "Unable to create AgiScript instance of type " + className + ": Class does not implement the AgiScript interface" ) ; return null ; } agiScriptClass = ( Class < AgiScript > ) tmpClass ; try { constructor = agiScriptClass . getConstructor ( ) ; agiScript = constructor . newInstance ( ) ; } catch ( Exception e ) { logger . warn ( "Unable to create AgiScript instance of type " + className , e ) ; } return agiScript ; }
Creates a new instance of an AGI script .
32,370
protected String escapeAndQuote ( String s ) { String tmp ; if ( s == null ) { return "\"\"" ; } tmp = s ; tmp = tmp . replaceAll ( "\\\\" , "\\\\\\\\" ) ; tmp = tmp . replaceAll ( "\\\"" , "\\\\\"" ) ; tmp = tmp . replaceAll ( "\\\n" , "" ) ; return "\"" + tmp + "\"" ; }
Escapes and quotes a given String according to the rules set by Asterisk s AGI .
32,371
public void setVariables ( Map < String , String > variables ) { if ( this . variables != null ) { this . variables . putAll ( variables ) ; } else { this . variables = variables ; } }
Sets the variables to set on the originated call .
32,372
public void setControlDigits ( String forwardDigit , String rewindDigit , String pauseDigit ) { this . forwardDigit = forwardDigit ; this . rewindDigit = rewindDigit ; this . pauseDigit = pauseDigit ; }
Sets the control digits for fast forward rewind and pause .
32,373
Collection < AsteriskChannel > getChannels ( ) { Collection < AsteriskChannel > copy ; synchronized ( channels ) { copy = new ArrayList < > ( channels . size ( ) + 2 ) ; for ( AsteriskChannel channel : channels . values ( ) ) { if ( channel . getState ( ) != ChannelState . HUNGUP ) { copy . add ( channel ) ; } } } return copy ; }
Returns a collection of all active AsteriskChannels .
32,374
AsteriskChannelImpl getChannelImplByName ( String name ) { Date dateOfCreation = null ; AsteriskChannelImpl channel = null ; if ( name == null ) { return null ; } synchronized ( channels ) { for ( AsteriskChannelImpl tmp : channels . values ( ) ) { if ( name . equals ( tmp . getName ( ) ) ) { if ( dateOfCreation == null || tmp . getDateOfCreation ( ) . after ( dateOfCreation ) || ( tmp . getDateOfCreation ( ) . equals ( dateOfCreation ) && tmp . getState ( ) != ChannelState . HUNGUP ) ) { channel = tmp ; dateOfCreation = channel . getDateOfCreation ( ) ; } } } } return channel ; }
Returns a channel from the ChannelManager s cache with the given name If multiple channels are found returns the most recently CREATED one . If two channels with the very same date exist avoid HUNGUP ones .
32,375
AsteriskChannelImpl getChannelImplByNameAndActive ( String name ) { AsteriskChannelImpl channel = null ; if ( name == null ) { return null ; } synchronized ( channels ) { for ( AsteriskChannelImpl tmp : channels . values ( ) ) { if ( name . equals ( tmp . getName ( ) ) && tmp . getState ( ) != ChannelState . HUNGUP ) { channel = tmp ; } } } return channel ; }
Returns a NON - HUNGUP channel from the ChannelManager s cache with the given name .
32,376
static private void syncDial ( ) { try { PBX pbx = PBXFactory . getActivePBX ( ) ; Trunk trunk = pbx . buildTrunk ( "default" ) ; EndPoint from = pbx . buildEndPoint ( TechType . SIP , "100" ) ; CallerID fromCallerID = pbx . buildCallerID ( "100" , "My Phone" ) ; CallerID toCallerID = pbx . buildCallerID ( "83208100" , "Asterisk Java is calling" ) ; EndPoint to = pbx . buildEndPoint ( TechType . SIP , trunk , "5551234" ) ; DialActivity dial = pbx . dial ( from , fromCallerID , to , toCallerID ) ; Call call = dial . getNewCall ( ) ; Thread . sleep ( 20000 ) ; logger . warn ( "Hanging up" ) ; pbx . hangup ( call ) ; } catch ( PBXException | InterruptedException e ) { System . out . println ( e ) ; } }
Simple synchronous dial . The dial method won t return until the dial starts . Using this method will lockup your UI until the dial starts . For better control use the async Dial method below .
32,377
public final Logger getLogger ( ) { if ( logger == null ) { logger = LoggerFactory . getLogger ( clazz ) ; } if ( logger instanceof LocationAwareLogger ) { return new LocationAwareWrapper ( FQCN , ( LocationAwareLogger ) logger ) ; } return this . logger ; }
Return the native Logger instance we are using .
32,378
void initialize ( ) throws ManagerCommunicationException { ResponseEvents re ; re = server . sendEventGeneratingAction ( new AgentsAction ( ) ) ; for ( ManagerEvent event : re . getEvents ( ) ) { if ( event instanceof AgentsEvent ) { logger . info ( event ) ; handleAgentsEvent ( ( AgentsEvent ) event ) ; } } }
Retrieves all agents registered at Asterisk server by sending an AgentsAction .
32,379
void handleAgentsEvent ( AgentsEvent event ) { AsteriskAgentImpl agent = new AsteriskAgentImpl ( server , event . getName ( ) , "Agent/" + event . getAgent ( ) , AgentState . valueOf ( event . getStatus ( ) ) ) ; logger . info ( "Adding agent " + agent . getName ( ) + "(" + agent . getAgentId ( ) + ")" ) ; addAgent ( agent ) ; }
On AgentsEvent create a new Agent .
32,380
private void addAgent ( AsteriskAgentImpl agent ) { synchronized ( agents ) { agents . put ( agent . getAgentId ( ) , agent ) ; } server . fireNewAgent ( agent ) ; }
Add a new agent to the manager .
32,381
void handleAgentCalledEvent ( AgentCalledEvent event ) { AsteriskAgentImpl agent = getAgentByAgentId ( event . getAgentCalled ( ) ) ; if ( agent == null ) { logger . error ( "Ignored AgentCalledEvent for unknown agent " + event . getAgentCalled ( ) ) ; return ; } updateRingingAgents ( event . getChannelCalling ( ) , agent ) ; updateAgentState ( agent , AgentState . AGENT_RINGING ) ; }
Update state if agent was called .
32,382
private void updateAgentState ( AsteriskAgentImpl agent , AgentState newState ) { logger . info ( "Set state of agent " + agent . getAgentId ( ) + " to " + newState ) ; synchronized ( agent ) { agent . updateState ( newState ) ; } }
Set state of agent .
32,383
private void updateRingingAgents ( String channelCalling , AsteriskAgentImpl agent ) { synchronized ( ringingAgents ) { if ( ringingAgents . containsKey ( channelCalling ) ) { updateAgentState ( ringingAgents . get ( channelCalling ) , AgentState . AGENT_IDLE ) ; } ringingAgents . put ( channelCalling , agent ) ; } }
Updates state of agent if the call in a queue was redirect to the next agent because the ringed agent doesn t answer the call . After reset state put the next agent in charge .
32,384
void handleAgentConnectEvent ( AgentConnectEvent event ) { AsteriskAgentImpl agent = getAgentByAgentId ( event . getChannel ( ) ) ; if ( agent == null ) { logger . error ( "Ignored AgentConnectEvent for unknown agent " + event . getChannel ( ) ) ; return ; } agent . updateState ( AgentState . AGENT_ONCALL ) ; }
Update state if agent was connected to channel .
32,385
Collection < AsteriskAgent > getAgents ( ) { Collection < AsteriskAgent > copy ; synchronized ( agents ) { copy = new ArrayList < AsteriskAgent > ( agents . values ( ) ) ; } return copy ; }
Return all agents registered at Asterisk server .
32,386
void handleAgentCompleteEvent ( AgentCompleteEvent event ) { AsteriskAgentImpl agent = getAgentByAgentId ( event . getChannel ( ) ) ; if ( agent == null ) { logger . error ( "Ignored AgentCompleteEvent for unknown agent " + event . getChannel ( ) ) ; return ; } agent . updateState ( AgentState . AGENT_IDLE ) ; }
Change state if connected call was terminated .
32,387
public void setReason ( String s ) { int spaceIdx ; if ( s == null ) { return ; } spaceIdx = s . indexOf ( ' ' ) ; if ( spaceIdx <= 0 ) { spaceIdx = s . length ( ) ; } try { this . reason = Integer . valueOf ( s . substring ( 0 , spaceIdx ) ) ; } catch ( NumberFormatException e ) { return ; } if ( s . length ( ) > spaceIdx + 3 ) { this . reasonTxt = s . substring ( spaceIdx + 3 , s . length ( ) ) ; } }
Sets the reason for disabling logging .
32,388
private void fireChainListeners ( ManagerEvent event ) { synchronized ( this . chainListeners ) { for ( ManagerEventListener listener : this . chainListeners ) listener . onManagerEvent ( event ) ; } }
dispatch the event to the chainListener if they exist .
32,389
public static String getInternalActionId ( String actionId ) { final int delimiterIndex ; if ( actionId == null ) { return null ; } delimiterIndex = actionId . indexOf ( INTERNAL_ACTION_ID_DELIMITER ) ; if ( delimiterIndex > 0 ) { return actionId . substring ( 0 , delimiterIndex ) ; } return null ; }
Returns the internal action id contained in the given action id .
32,390
public static String stripInternalActionId ( String actionId ) { int delimiterIndex ; delimiterIndex = actionId . indexOf ( INTERNAL_ACTION_ID_DELIMITER ) ; if ( delimiterIndex > 0 ) { if ( actionId . length ( ) > delimiterIndex + 1 ) { return actionId . substring ( delimiterIndex + 1 ) ; } return null ; } return null ; }
Strips the internal action id from the given action id .
32,391
public static String addInternalActionId ( String actionId , String internalActionId ) { if ( actionId == null ) { return internalActionId + INTERNAL_ACTION_ID_DELIMITER ; } return internalActionId + INTERNAL_ACTION_ID_DELIMITER + actionId ; }
Adds the internal action id to the given action id .
32,392
public static void main ( String [ ] args ) throws Exception { final AgiServer server ; server = new DefaultAgiServer ( ) ; server . startup ( ) ; }
Creates a new DefaultAgiServer and starts it .
32,393
public String getVariable ( final Channel channel , final String variableName ) { String value = "" ; final GetVarAction var = new GetVarAction ( channel , variableName ) ; try { PBX pbx = PBXFactory . getActivePBX ( ) ; if ( ! pbx . waitForChannelToQuiescent ( channel , 3000 ) ) throw new PBXException ( "Channel: " + channel + " cannot be retrieved as it is still in transition." ) ; ManagerResponse convertedResponse = sendAction ( var , 500 ) ; if ( convertedResponse != null ) { value = convertedResponse . getAttribute ( "value" ) ; if ( value == null ) value = "" ; CoherentManagerConnection . logger . debug ( "getVarAction returned name:" + variableName + " value:" + value ) ; } } catch ( final Exception e ) { CoherentManagerConnection . logger . debug ( e , e ) ; CoherentManagerConnection . logger . error ( "getVariable: " + e ) ; } return value ; }
Retrieves and returns the value of a variable associated with a channel . If the variable is empty or null then an empty string is returned .
32,394
public static void sendActionNoWait ( final ManagerAction action ) { final Thread background = new Thread ( ) { public void run ( ) { try { CoherentManagerConnection . sendAction ( action , 5000 ) ; } catch ( final Exception e ) { CoherentManagerConnection . logger . error ( e , e ) ; } } } ; background . setName ( "sendActionNoWait" ) ; background . setDaemon ( true ) ; background . start ( ) ; }
Allows the caller to send an action to asterisk without waiting for the response . You should only use this if you don t care whether the action actually succeeds .
32,395
public static ManagerResponse sendAction ( final ManagerAction action , final int timeout ) throws IllegalArgumentException , IllegalStateException , IOException , TimeoutException { if ( logger . isDebugEnabled ( ) ) CoherentManagerConnection . logger . debug ( "Sending Action: " + action . toString ( ) ) ; CoherentManagerConnection . getInstance ( ) ; if ( ( CoherentManagerConnection . managerConnection != null ) && ( CoherentManagerConnection . managerConnection . getState ( ) == ManagerConnectionState . CONNECTED ) ) { final org . asteriskjava . manager . action . ManagerAction ajAction = action . getAJAction ( ) ; org . asteriskjava . manager . response . ManagerResponse response = CoherentManagerConnection . managerConnection . sendAction ( ajAction , timeout ) ; ManagerResponse convertedResponse = null ; if ( response != null ) convertedResponse = CoherentEventFactory . build ( response ) ; if ( ( convertedResponse != null ) && ( convertedResponse . getResponse ( ) . compareToIgnoreCase ( "Error" ) == 0 ) ) { CoherentManagerConnection . logger . warn ( "Action '" + ajAction + "' failed, Response: " + convertedResponse . getResponse ( ) + " Message: " + convertedResponse . getMessage ( ) ) ; } return convertedResponse ; } throw new IllegalStateException ( "not connected." ) ; }
Sends an Asterisk action and waits for a ManagerRespose .
32,396
public Map < Integer , String > getCategories ( ) { if ( categories == null ) { categories = new TreeMap < > ( ) ; } Map < String , Object > responseMap = super . getAttributes ( ) ; for ( Entry < String , Object > response : responseMap . entrySet ( ) ) { String key = response . getKey ( ) ; if ( key . toLowerCase ( Locale . US ) . contains ( "category" ) ) { String [ ] keyParts = key . split ( "-" ) ; if ( keyParts . length < 2 ) continue ; Integer categoryNumber ; try { categoryNumber = Integer . parseInt ( keyParts [ 1 ] ) ; } catch ( Exception exception ) { continue ; } categories . put ( categoryNumber , ( String ) response . getValue ( ) ) ; } } return categories ; }
Returns the map of category numbers to category names .
32,397
public Map < Integer , String > getLines ( int categoryNumber ) { if ( lines == null ) { lines = new TreeMap < > ( ) ; } Map < String , Object > responseMap = super . getAttributes ( ) ; for ( Entry < String , Object > response : responseMap . entrySet ( ) ) { String key = response . getKey ( ) ; if ( key . toLowerCase ( Locale . US ) . contains ( "line" ) ) { String [ ] keyParts = key . split ( "-" ) ; if ( keyParts . length < 3 ) { continue ; } Integer potentialCategoryNumber ; try { potentialCategoryNumber = Integer . parseInt ( keyParts [ 1 ] ) ; } catch ( Exception exception ) { continue ; } Integer potentialLineNumber ; try { potentialLineNumber = Integer . parseInt ( keyParts [ 2 ] ) ; } catch ( Exception exception ) { continue ; } Map < Integer , String > linesForCategory = lines . get ( potentialCategoryNumber ) ; if ( linesForCategory == null ) { linesForCategory = new TreeMap < > ( ) ; } linesForCategory . put ( potentialLineNumber , ( String ) response . getValue ( ) ) ; if ( ! lines . containsKey ( potentialCategoryNumber ) ) { lines . put ( potentialCategoryNumber , linesForCategory ) ; } } } return lines . get ( categoryNumber ) ; }
Returns the map of line number to line value for a given category .
32,398
protected void ping ( ManagerConnection c ) { try { if ( timeout <= 0 ) { c . sendAction ( new PingAction ( ) , null ) ; } else { final ManagerResponse response ; response = c . sendAction ( new PingAction ( ) , timeout ) ; logger . debug ( "Ping response '" + response + "' for " + c . toString ( ) ) ; } } catch ( Exception e ) { logger . warn ( "Exception on sending Ping to " + c . toString ( ) , e ) ; } }
Sends a ping to Asterisk and logs any errors that may occur .
32,399
public void addCommand ( String action , String cat , String var , String value , String match ) { final String stringCounter = String . format ( "%06d" , this . actionCounter ) ; if ( action != null ) { actions . put ( "Action-" + stringCounter , action ) ; } if ( cat != null ) { actions . put ( "Cat-" + stringCounter , cat ) ; } if ( var != null ) { actions . put ( "Var-" + stringCounter , var ) ; } if ( value != null ) { actions . put ( "Value-" + stringCounter , value ) ; } if ( match != null ) { actions . put ( "Match-" + stringCounter , match ) ; } this . actionCounter ++ ; }
Adds a command to update a config file while sparing you the details of the Manager s required syntax . If you want to omit one of the command s sections provide a null value to this method . The command index will be incremented even if you supply a null for all parameters though the map will be unaffected .