idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
37,500
public final boolean isViaHeaderExternal ( ViaHeader viaHeader ) { if ( viaHeader != null ) { return isExternal ( viaHeader . getHost ( ) , viaHeader . getPort ( ) , viaHeader . getTransport ( ) ) ; } return true ; }
Check if the via header is external
37,501
public final boolean isExternal ( String host , int port , String transport ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "isExternal - host=" + host + ", port=" + port + ", transport=" + transport ) ; } boolean isExternal = true ; MobicentsExtendedListeningPoint listeningPoint = sipNetworkInterfaceManager . findMatchingListeningPoint ( host , port , transport ) ; if ( ( hostNames . contains ( host ) || hostNames . contains ( host + ":" + port ) || listeningPoint != null ) ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "hostNames.contains(" + host + ")=" + hostNames . contains ( host ) + "hostNames.contains(" + host + ":" + port + ")=" + hostNames . contains ( host + ":" + port ) + " | listeningPoint found = " + listeningPoint ) ; } isExternal = false ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "the triplet host/port/transport : " + host + "/" + port + "/" + transport + " is external : " + isExternal ) ; } return isExternal ; }
Check whether or not the triplet host port and transport are corresponding to an interface
37,502
private void resetOutboundInterfaces ( ) { List < SipURI > outboundInterfaces = sipNetworkInterfaceManager . getOutboundInterfaces ( ) ; for ( SipContext sipContext : applicationDeployed . values ( ) ) { sipContext . getServletContext ( ) . setAttribute ( javax . servlet . sip . SipServlet . OUTBOUND_INTERFACES , outboundInterfaces ) ; } }
set the outbound interfaces on all servlet context of applications deployed
37,503
public void creditGranted ( long amount , boolean finalUnits ) throws Exception { if ( CURRENT_STATE == SENT_INITIAL_RESERVATION ) { CURRENT_STATE = GRANTED_INITIAL_RESERVATION ; if ( logger . isInfoEnabled ( ) ) { logger . info ( "credit granted : " ) ; } doInviteChargingAllowed ( this . inviteRequest ) ; } }
Ro Client Listener Implementation
37,504
public void recycle ( ) { proxyConfig . isProxyConfigSet = false ; sessionConfig . isSessionConfigSet = false ; loginConfig . isLoginConfigSet = false ; servletSelection . isMainServlet = false ; servletSelection . isServletMapping = false ; }
Reset counter used for validating the web . xml file .
37,505
private JBossConvergedSipMetaData mergeSipMetaDataAndSipAnnMetaData ( final DeploymentUnit deploymentUnit ) { final WarMetaData warMetaData = deploymentUnit . getAttachment ( WarMetaData . ATTACHMENT_KEY ) ; SipMetaData sipMetaData = deploymentUnit . getAttachment ( SipMetaData . ATTACHMENT_KEY ) ; SipAnnotationMetaData sipAnnotationMetaData = deploymentUnit . getAttachment ( SipAnnotationMetaData . ATTACHMENT_KEY ) ; JBossConvergedSipMetaData mergedMetaData = new JBossConvergedSipMetaData ( ) ; final JBossWebMetaData override = warMetaData . getJBossWebMetaData ( ) ; final WebMetaData original = null ; JBossWebMetaDataMerger . merge ( mergedMetaData , override , original ) ; if ( sipMetaData == null && sipAnnotationMetaData != null && sipAnnotationMetaData . isSipApplicationAnnotationPresent ( ) ) { sipMetaData = new Sip11MetaData ( ) ; } if ( sipMetaData != null ) { try { augmentAnnotations ( mergedMetaData , sipMetaData , sipAnnotationMetaData ) ; } catch ( ServletException e ) { logger . error ( "Error while augmenting annotation: " + e . getMessage ( ) , e ) ; } } else { logger . debug ( "Deployment does not consist SIP application." ) ; } return mergedMetaData ; }
merge DD and annotation meta data and store in WarMetaData . mergedJBossWebMetaData based on SIPWebContext code
37,506
private final void forwardResponseStatefully ( final SipServletResponseImpl sipServletResponse ) { final Response response = sipServletResponse . getResponse ( ) ; final ListIterator < ViaHeader > viaHeadersLeft = response . getHeaders ( ViaHeader . NAME ) ; if ( viaHeadersLeft . hasNext ( ) ) { viaHeadersLeft . next ( ) ; } if ( viaHeadersLeft . hasNext ( ) ) { final ClientTransaction clientTransaction = ( ClientTransaction ) sipServletResponse . getTransaction ( ) ; final Dialog dialog = sipServletResponse . getDialog ( ) ; final Response newResponse = ( Response ) response . clone ( ) ; ( ( MessageExt ) newResponse ) . setApplicationData ( null ) ; newResponse . removeFirst ( ViaHeader . NAME ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "forwarding the response statefully " + newResponse ) ; } TransactionApplicationData applicationData = null ; if ( clientTransaction != null ) { applicationData = ( TransactionApplicationData ) clientTransaction . getApplicationData ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "ctx application Data " + applicationData ) ; } } else if ( dialog != null ) { applicationData = ( TransactionApplicationData ) dialog . getApplicationData ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "dialog application data " + applicationData ) ; } } if ( applicationData != null ) { final ServerTransaction serverTransaction = ( ServerTransaction ) applicationData . getTransaction ( ) ; try { serverTransaction . sendResponse ( newResponse ) ; } catch ( SipException e ) { logger . error ( "cannot forward the response statefully" , e ) ; } catch ( InvalidArgumentException e ) { logger . error ( "cannot forward the response statefully" , e ) ; } } else { try { String transport = JainSipUtils . findTransport ( newResponse ) ; SipProvider sipProvider = sipApplicationDispatcher . getSipNetworkInterfaceManager ( ) . findMatchingListeningPoint ( transport , false ) . getSipProvider ( ) ; sipProvider . sendResponse ( newResponse ) ; } catch ( SipException e ) { logger . error ( "cannot forward the response statelessly" , e ) ; } sipApplicationDispatcher . updateResponseStatistics ( newResponse , false ) ; } } else { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Not forwarding the response statefully. " + "It was either an endpoint or a B2BUA, ie an endpoint too " + response ) ; } } }
this method is called when a B2BUA got the response so we don t have anything to do here or an app that didn t do anything with it or when handling the request an app had to be called but wasn t deployed the topmost via header is stripped from the response and the response is forwarded statefully
37,507
public void startNextUntriedBranch ( ) { if ( this . parallel ) throw new IllegalStateException ( "This method is only for sequantial proxying" ) ; for ( final MobicentsProxyBranch pbi : this . proxyBranches . values ( ) ) { if ( ! pbi . isStarted ( ) && ! pbi . isCanceled ( ) ) { pbi . start ( ) ; return ; } } }
In sequential proxying get some untried branch and start it then wait for response and repeat
37,508
public static DeploymentUnit getSipContextAnchorDu ( final DeploymentUnit du ) { DeploymentUnit parentDu = du . getParent ( ) ; if ( parentDu == null ) { return du ; } else if ( DeploymentTypeMarker . isType ( DeploymentType . EAR , parentDu ) ) { return parentDu ; } else { logger . error ( "Can't find proper anchor deployment unit for " + du . getName ( ) + " - This is probably a bug" ) ; return null ; } }
returns the anchor deployment unit that will have attached a SIPWebContext
37,509
private void pushRoute ( javax . sip . address . SipURI sipUri ) { if ( ! isInitial ( ) && getSipSession ( ) . getProxy ( ) == null ) { throw new IllegalStateException ( "Cannot push route on subsequent requests, only intial ones" ) ; } else { if ( logger . isDebugEnabled ( ) ) logger . debug ( "Pushing route into message of value [" + sipUri + "]" ) ; sipUri . setLrParam ( ) ; try { javax . sip . header . Header p = SipFactoryImpl . headerFactory . createRouteHeader ( SipFactoryImpl . addressFactory . createAddress ( sipUri ) ) ; this . message . addFirst ( p ) ; } catch ( SipException e ) { logger . error ( "Error while pushing route [" + sipUri + "]" ) ; throw new IllegalArgumentException ( "Error pushing route " , e ) ; } } }
Pushes a route header on initial request based on the jain sip sipUri given on parameter
37,510
private javax . sip . address . URI resolveSipOutbound ( final javax . sip . address . URI uriToResolve ) { if ( ! uriToResolve . isSipURI ( ) ) { return uriToResolve ; } final javax . sip . address . SipURI sipURI = ( javax . sip . address . SipURI ) uriToResolve ; if ( sipURI . getParameter ( MessageDispatcher . SIP_OUTBOUND_PARAM_OB ) == null ) { return uriToResolve ; } final MobicentsSipSession session = getSipSession ( ) ; final javax . sip . address . SipURI flow = session . getFlow ( ) ; if ( flow != null ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Found a flow \"" + flow + "\" for the original uri \"" + uriToResolve + "\"" ) ; } return flow ; } return uriToResolve ; }
Check to see if the uri to resolve contains a ob parameter and if so try and locate a flow for this uri .
37,511
private void updateLinkedRequestAppDataMapping ( final ClientTransaction ctx , Dialog dialog ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "updateLinkedRequestAppDataMapping" ) ; } final Transaction linkedTransaction = linkedRequest . getTransaction ( ) ; final Dialog linkedDialog = linkedRequest . getDialog ( ) ; if ( linkedTransaction != null && linkedTransaction . getApplicationData ( ) != null ) { ( ( TransactionApplicationData ) linkedTransaction . getApplicationData ( ) ) . setTransaction ( ctx ) ; } if ( linkedDialog != null && linkedDialog . getApplicationData ( ) != null ) { ( ( TransactionApplicationData ) linkedDialog . getApplicationData ( ) ) . setTransaction ( ctx ) ; } this . transactionApplicationData . setTransaction ( linkedTransaction ) ; if ( dialog != null && dialog . getApplicationData ( ) != null ) { ( ( TransactionApplicationData ) dialog . getApplicationData ( ) ) . setTransaction ( linkedTransaction ) ; } }
Keeping the transactions mapping in application data for CANCEL handling
37,512
private void addInfoForRoutingBackToContainer ( SipApplicationRouterInfo routerInfo , String applicationSessionId , String applicationName ) throws ParseException , SipException { final Request request = ( Request ) super . message ; final javax . sip . address . SipURI sipURI = JainSipUtils . createRecordRouteURI ( sipFactoryImpl . getSipNetworkInterfaceManager ( ) , request ) ; sipURI . setLrParam ( ) ; sipURI . setParameter ( MessageDispatcher . ROUTE_PARAM_DIRECTIVE , routingDirective . toString ( ) ) ; if ( getSipSession ( ) . getRegionInternal ( ) != null ) { sipURI . setParameter ( MessageDispatcher . ROUTE_PARAM_REGION_LABEL , getSipSession ( ) . getRegionInternal ( ) . getLabel ( ) ) ; sipURI . setParameter ( MessageDispatcher . ROUTE_PARAM_REGION_TYPE , getSipSession ( ) . getRegionInternal ( ) . getType ( ) . toString ( ) ) ; } sipURI . setParameter ( MessageDispatcher . ROUTE_PARAM_PREV_APPLICATION_NAME , applicationName ) ; sipURI . setParameter ( MessageDispatcher . ROUTE_PARAM_PREV_APP_ID , applicationSessionId ) ; final javax . sip . address . Address routeAddress = SipFactoryImpl . addressFactory . createAddress ( sipURI ) ; final RouteHeader routeHeader = SipFactoryImpl . headerFactory . createRouteHeader ( routeAddress ) ; request . addFirst ( routeHeader ) ; final MobicentsSipSession session = getSipSession ( ) ; session . setNextSipApplicationRouterInfo ( routerInfo ) ; }
Add a route header to route back to the container
37,513
private static RoutingState checkRoutingState ( SipServletRequestImpl sipServletRequest , Dialog dialog ) { if ( dialog != null && DialogState . CONFIRMED . equals ( dialog . getState ( ) ) ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "checkRoutingState - dialog not null and dialog state is CONFIRMED" ) ; } return RoutingState . SUBSEQUENT ; } if ( NON_INITIAL_SIP_REQUEST_METHODS . contains ( sipServletRequest . getMethod ( ) ) ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "checkRoutingState - sipServletRequest.getMethod() is element of NON_INITIAL_SIP_REQUEST_METHODS, sipServletRequest.getMethod()=" + sipServletRequest . getMethod ( ) ) ; } return RoutingState . SUBSEQUENT ; } if ( dialog != null && ! DialogState . EARLY . equals ( dialog . getState ( ) ) ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "checkRoutingState - dialog not null and dialog state is not EARLY" ) ; } return RoutingState . SUBSEQUENT ; } return RoutingState . INITIAL ; }
Method checking whether or not the sip servlet request in parameter is initial according to algorithm defined in JSR289 Appendix B
37,514
public MobicentsExtendedListeningPoint findMatchingListeningPoint ( String transport , final boolean strict ) { String tmpTransport = transport ; if ( tmpTransport == null ) { tmpTransport = ListeningPoint . UDP ; } Set < MobicentsExtendedListeningPoint > extendedListeningPoints = transportMappingCacheMap . get ( tmpTransport . toLowerCase ( ) ) ; if ( extendedListeningPoints . size ( ) > 0 ) { MobicentsExtendedListeningPoint extendedListeningPoint = extendedListeningPoints . iterator ( ) . next ( ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Found first listening point " + extendedListeningPoint + " with transport " + transport ) ; } return extendedListeningPoint ; } if ( strict ) { return null ; } else { if ( extendedListeningPointList . size ( ) > 0 ) { MobicentsExtendedListeningPoint extendedListeningPoint = extendedListeningPointList . iterator ( ) . next ( ) ; if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Found first listening point " + extendedListeningPoint + " with transport " + transport ) ; } return extendedListeningPoint ; } else { throw new RuntimeException ( "no valid sip connectors could be found to create the sip application session !!!" ) ; } } }
Retrieve the first matching listening point corresponding to the transport .
37,515
public MobicentsExtendedListeningPoint findMatchingListeningPoint ( final String ipAddress , int port , String transport ) { String tmpTransport = transport ; int portChecked = checkPortRange ( port , tmpTransport ) ; if ( tmpTransport == null ) { tmpTransport = ListeningPoint . UDP ; } MobicentsExtendedListeningPoint listeningPoint = null ; if ( ipAddress . indexOf ( ':' ) != - 1 ) { String ipAddressTmp = extractIPV6Brackets ( ipAddress ) ; for ( String key : extendedListeningPointsCacheMap . keySet ( ) ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Find listening point for IPv6: " + key + " compare: " + ipAddressTmp + " port " + portChecked + " transport " + tmpTransport . toLowerCase ( ) ) ; } if ( key . contains ( ipAddressTmp ) && key . contains ( String . valueOf ( portChecked ) + ":" + tmpTransport . toLowerCase ( ) ) ) { listeningPoint = extendedListeningPointsCacheMap . get ( key ) ; break ; } } } else { listeningPoint = extendedListeningPointsCacheMap . get ( ipAddress + "/" + portChecked + ":" + tmpTransport . toLowerCase ( ) ) ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Checked Listening Point " + ipAddress + "/" + portChecked + ":" + tmpTransport . toLowerCase ( ) + " against existing listening points, found " + listeningPoint ) ; } if ( listeningPoint == null && ! Inet6Util . isValidIP6Address ( ipAddress ) && ! Inet6Util . isValidIPV4Address ( ipAddress ) ) { Queue < Hop > hops = null ; try { hops = sipApplicationDispatcher . getDNSServerLocator ( ) . getDnsLookupPerformer ( ) . locateHopsForNonNumericAddressWithPort ( ipAddress , portChecked , tmpTransport . toLowerCase ( ) ) ; } catch ( Exception e ) { } if ( hops != null ) { for ( Hop hop : hops ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Checking Hop " + hop . getHost ( ) + "/" + portChecked + ":" + tmpTransport . toLowerCase ( ) + " against existing listening points" ) ; } listeningPoint = extendedListeningPointsCacheMap . get ( hop . getHost ( ) + "/" + portChecked + ":" + tmpTransport . toLowerCase ( ) ) ; if ( listeningPoint != null ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Found listening point " + listeningPoint ) ; } return listeningPoint ; } } } } return listeningPoint ; }
Retrieve the first matching listening Point corresponding to the ipAddress port and transport given in parameter .
37,516
protected void computeOutboundInterfaces ( ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Outbound Interface List : " ) ; } List < SipURI > newlyComputedOutboundInterfaces = new CopyOnWriteArrayList < SipURI > ( ) ; Set < String > newlyComputedOutboundInterfacesIpAddresses = new CopyOnWriteArraySet < String > ( ) ; Iterator < MobicentsExtendedListeningPoint > it = getExtendedListeningPoints ( ) ; while ( it . hasNext ( ) ) { MobicentsExtendedListeningPoint extendedListeningPoint = it . next ( ) ; for ( String ipAddress : extendedListeningPoint . getIpAddresses ( ) ) { try { newlyComputedOutboundInterfacesIpAddresses . add ( ipAddress ) ; javax . sip . address . SipURI jainSipURI = SipFactoryImpl . addressFactory . createSipURI ( null , ipAddress ) ; jainSipURI . setPort ( extendedListeningPoint . getPort ( ) ) ; jainSipURI . setTransportParam ( extendedListeningPoint . getTransport ( ) ) ; SipURI sipURI = new SipURIImpl ( jainSipURI , ModifiableRule . NotModifiable ) ; newlyComputedOutboundInterfaces . add ( sipURI ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Outbound Interface : " + jainSipURI ) ; } } catch ( ParseException e ) { logger . error ( "cannot add the following listening point " + ipAddress + ":" + extendedListeningPoint . getPort ( ) + ";transport=" + extendedListeningPoint . getTransport ( ) + " to the outbound interfaces" , e ) ; } } } outboundInterfaces = newlyComputedOutboundInterfaces ; outboundInterfacesIpAddresses = newlyComputedOutboundInterfacesIpAddresses ; }
Compute all the outbound interfaces for this manager
37,517
private DatagramSocket initRandomPortSocket ( ) { int bindRetries = 5 ; int currentlyTriedPort = getRandomPortNumber ( JainSipUtils . MIN_PORT_NUMBER , JainSipUtils . MAX_PORT_NUMBER ) ; DatagramSocket resultSocket = null ; for ( int i = 0 ; i < bindRetries ; i ++ ) { try { resultSocket = new DatagramSocket ( currentlyTriedPort ) ; break ; } catch ( SocketException exc ) { if ( exc . getMessage ( ) . indexOf ( "Address already in use" ) == - 1 ) { logger . fatal ( "An exception occurred while trying to create" + "a local host discovery socket." , exc ) ; return null ; } logger . debug ( "Port " + currentlyTriedPort + " seems in use." ) ; currentlyTriedPort = getRandomPortNumber ( JainSipUtils . MIN_PORT_NUMBER , JainSipUtils . MAX_PORT_NUMBER ) ; logger . debug ( "Retrying bind on port " + currentlyTriedPort ) ; } } return resultSocket ; }
Initializes and binds a socket that on a random port number . The method would try to bind on a random port and retry 5 times until a free port is found .
37,518
public void setToTag ( String toTag , boolean recomputeSessionId ) { this . toTag = toTag ; if ( toTag != null && recomputeSessionId ) { computeToString ( ) ; } }
Sets the to tag on the key when we receive a response . We recompute the session id only for derived session otherwise the id will change when the a request is received or sent and the response is sent back or received which should not happen See TCK test SipSessionListenerTest . testSessionDestroyed001
37,519
public static void removeSipSubcontext ( Context envCtx ) { try { envCtx . destroySubcontext ( SIP_SUBCONTEXT ) ; } catch ( NamingException e ) { logger . error ( sm . getString ( "naming.unbindFailed" , e ) ) ; } }
Removes the sip subcontext from JNDI
37,520
public static void addSipSubcontext ( Context envCtx ) { try { envCtx . createSubcontext ( SIP_SUBCONTEXT ) ; } catch ( NamingException e ) { logger . error ( sm . getString ( "naming.bindFailed" , e ) ) ; } }
Add the sip subcontext to JNDI
37,521
public static void removeAppNameSubContext ( Context envCtx , String appName ) { if ( envCtx != null ) { try { javax . naming . Context sipContext = ( javax . naming . Context ) envCtx . lookup ( SIP_SUBCONTEXT ) ; sipContext . destroySubcontext ( appName ) ; } catch ( NamingException e ) { logger . error ( sm . getString ( "naming.unbindFailed" , e ) ) ; } } }
Removes the app name subcontext from the jndi mapping
37,522
public static void removeSipSessionsUtil ( Context envCtx , String appName , SipSessionsUtil sipSessionsUtil ) { if ( envCtx != null ) { try { javax . naming . Context sipContext = ( javax . naming . Context ) envCtx . lookup ( SIP_SUBCONTEXT + "/" + appName ) ; sipContext . unbind ( SIP_SESSIONS_UTIL_JNDI_NAME ) ; } catch ( NamingException e ) { logger . error ( sm . getString ( "naming.unbindFailed" , e ) ) ; } } }
Removes the sip sessions util binding from the jndi mapping
37,523
public static void removeTimerService ( Context envCtx , String appName , TimerService timerService ) { if ( envCtx != null ) { try { javax . naming . Context sipContext = ( javax . naming . Context ) envCtx . lookup ( SIP_SUBCONTEXT + "/" + appName ) ; sipContext . unbind ( TIMER_SERVICE_JNDI_NAME ) ; } catch ( NamingException e ) { logger . error ( sm . getString ( "naming.unbindFailed" , e ) ) ; } } }
Removes the Timer Service binding from the jndi mapping
37,524
public static void removeSipFactory ( Context envCtx , String appName , SipFactory sipFactory ) { if ( envCtx != null ) { try { javax . naming . Context sipContext = ( javax . naming . Context ) envCtx . lookup ( SIP_SUBCONTEXT + "/" + appName ) ; sipContext . unbind ( SIP_FACTORY_JNDI_NAME ) ; } catch ( NamingException e ) { logger . error ( sm . getString ( "naming.unbindFailed" , e ) ) ; } } }
Removes the sip factory binding from the jndi mapping
37,525
protected void handleSipOutbound ( final SipServletRequestImpl sipServletRequest ) { if ( ! JainSipUtils . DIALOG_CREATING_METHODS . contains ( sipServletRequest . getMethod ( ) ) ) { return ; } final Request request = ( Request ) sipServletRequest . getMessage ( ) ; final ContactHeader contact = ( ContactHeader ) request . getHeader ( ContactHeader . NAME ) ; final URI requestUri = request . getRequestURI ( ) ; if ( ( contact != null && contact . getAddress ( ) . getURI ( ) instanceof Parameters && ( ( Parameters ) contact . getAddress ( ) . getURI ( ) ) . getParameter ( SIP_OUTBOUND_PARAM_OB ) != null ) ) { final String remoteHost = sipServletRequest . getRemoteAddr ( ) ; final int remotePort = sipServletRequest . getRemotePort ( ) ; final String transport = sipServletRequest . getTransport ( ) ; final MobicentsSipSession sipSessionImpl = sipServletRequest . getSipSession ( ) ; try { final javax . sip . address . SipURI flowURI = SipFactoryImpl . addressFactory . createSipURI ( null , remoteHost ) ; flowURI . setPort ( remotePort ) ; flowURI . setTransportParam ( transport ) ; sipSessionImpl . setFlow ( flowURI ) ; } catch ( final ParseException e ) { logger . warn ( "Unable to create new flow URI from " + remoteHost + ":" + remotePort + ";transport=" + transport + " due to a parse exception" ) ; } } else if ( sipServletRequest . getPoppedRouteHeader ( ) != null && ( requestUri instanceof javax . sip . address . SipURI && ( ( javax . sip . address . SipURI ) requestUri ) . getParameter ( SIP_OUTBOUND_PARAM_OB ) != null ) ) { final javax . sip . address . SipURI poppedURI = ( javax . sip . address . SipURI ) sipServletRequest . getPoppedRouteHeader ( ) . getAddress ( ) . getURI ( ) ; String flowToken = poppedURI . getUser ( ) ; return ; } }
NOTE! This is only a partial implementation and will only work when we are acting as a UAS as per RFC 5626 Section 4 . 3 . Sending Non - REGISTER Requests . Need to add some more logic for proxy scenarios . See RFC 5626 for exact details .
37,526
protected void registerSipConnector ( Connector connector ) { try { ObjectName objectName = createSipConnectorObjectName ( connector , getName ( ) , "SipConnector" ) ; Registry . getRegistry ( null , null ) . registerComponent ( connector , objectName , null ) ; } catch ( Exception e ) { logger . error ( "Error registering connector " , e ) ; } if ( logger . isDebugEnabled ( ) ) logger . debug ( "Creating name for connector " + getObjectName ( ) ) ; }
Register the sip connector under a different name than HTTP Connector and we add the transport to avoid clashing with 2 connectors having the same port and address
37,527
public void initializeSystemPortProperties ( ) { for ( Connector connector : connectors ) { if ( connector . getProtocol ( ) . contains ( "HTTP" ) ) { if ( connector . getSecure ( ) ) { System . setProperty ( "org.mobicents.properties.sslPort" , Integer . toString ( connector . getPort ( ) ) ) ; } else { System . setProperty ( "org.mobicents.properties.httpPort" , Integer . toString ( connector . getPort ( ) ) ) ; } } } }
This method simply makes the HTTP and SSL ports avaialble everywhere in the JVM in order jsip ha to read them for balancer description purposes . There is no other good way to communicate the properies to jsip ha without adding more dependencies .
37,528
public static String [ ] getMissingSipMethods ( Collection < String > sipMethods ) { String [ ] methods = { } ; if ( sipMethods . size ( ) > 0 && sipMethods . containsAll ( ALL_SIP_METHODS ) == false ) { HashSet < String > missingMethods = new HashSet < String > ( ALL_SIP_METHODS ) ; missingMethods . removeAll ( sipMethods ) ; methods = new String [ missingMethods . size ( ) ] ; missingMethods . toArray ( methods ) ; } return methods ; }
Get sip methods in ALL_SIP_METHODS not in the argument sipMethods .
37,529
private Set < String > getAllComponentClasses ( DeploymentUnit deploymentUnit , CompositeIndex index , SipMetaData sipMetaData , SipAnnotationMetaData sipAnnotationMetaData ) { final Set < String > classes = new HashSet < String > ( ) ; if ( sipAnnotationMetaData != null ) { for ( Map . Entry < String , SipMetaData > metaData : sipAnnotationMetaData . entrySet ( ) ) { getAllComponentClasses ( metaData . getValue ( ) , classes ) ; } } if ( sipMetaData != null ) { getAllComponentClasses ( sipMetaData , classes ) ; } return classes ; }
Gets all classes that are eligible for injection etc
37,530
public void addSipServletResponse ( SipServletResponseImpl sipServletResponse ) { if ( sipServletResponses == null ) { sipServletResponses = new CopyOnWriteArraySet < SipServletResponseImpl > ( ) ; } sipServletResponses . add ( sipServletResponse ) ; }
used to get access from the B2BUA to pending messages on the transaction
37,531
public void setMaxActiveSipSessions ( int max ) { int oldMaxActiveSipSessions = this . sipManagerDelegate . getMaxActiveSipSessions ( ) ; this . sipManagerDelegate . setMaxActiveSipSessions ( max ) ; support . firePropertyChange ( "maxActiveSipSessions" , Integer . valueOf ( oldMaxActiveSipSessions ) , Integer . valueOf ( this . sipManagerDelegate . getMaxActiveSipSessions ( ) ) ) ; }
Set the maximum number of actives Sip Sessions allowed or - 1 for no limit .
37,532
public void setMaxActiveSipApplicationSessions ( int max ) { int oldMaxActiveSipApplicationSessions = this . sipManagerDelegate . getMaxActiveSipApplicationSessions ( ) ; this . sipManagerDelegate . setMaxActiveSipApplicationSessions ( max ) ; support . firePropertyChange ( "maxActiveSipApplicationSessions" , Integer . valueOf ( oldMaxActiveSipApplicationSessions ) , Integer . valueOf ( this . sipManagerDelegate . getMaxActiveSipApplicationSessions ( ) ) ) ; }
Set the maximum number of actives Sip Application Sessions allowed or - 1 for no limit .
37,533
public static boolean findPackageInfoinDirectory ( File file ) { if ( file . getName ( ) . equals ( "package-info.class" ) ) { FileInputStream stream = null ; try { stream = new FileInputStream ( file ) ; if ( findSipApplicationAnnotation ( stream ) ) return true ; } catch ( Exception e ) { } finally { try { stream . close ( ) ; } catch ( IOException e ) { } } } if ( file . isDirectory ( ) ) { for ( File subFile : file . listFiles ( ) ) { if ( findPackageInfoinDirectory ( subFile ) ) return true ; } } return false ; }
Determine if there is a sip application in this folder .
37,534
public static boolean findSipApplicationAnnotation ( InputStream stream ) { try { byte [ ] rawClassBytes ; rawClassBytes = new byte [ stream . available ( ) ] ; stream . read ( rawClassBytes ) ; boolean one = contains ( rawClassBytes , SIP_APPLICATION_BYTES ) ; boolean two = contains ( rawClassBytes , ANNOTATION_BYTES ) ; if ( one && two ) return true ; } catch ( Exception e ) { } return false ; }
Determine if this stream contains SipApplication annotations
37,535
public String auth_getSession ( String authToken ) throws FacebookException , IOException { if ( null != this . _sessionKey ) { return this . _sessionKey ; } Document d = this . callMethod ( FacebookMethod . AUTH_GET_SESSION , new Pair < String , CharSequence > ( "auth_token" , authToken . toString ( ) ) ) ; this . _sessionKey = d . getElementsByTagName ( "session_key" ) . item ( 0 ) . getFirstChild ( ) . getTextContent ( ) ; this . _userId = Integer . parseInt ( d . getElementsByTagName ( "uid" ) . item ( 0 ) . getFirstChild ( ) . getTextContent ( ) ) ; if ( this . _isDesktop ) { this . _sessionSecret = d . getElementsByTagName ( "secret" ) . item ( 0 ) . getFirstChild ( ) . getTextContent ( ) ; } return this . _sessionKey ; }
Call this function to retrieve the session information after your user has logged in .
37,536
protected URL extractURL ( Document doc ) throws IOException { String url = doc . getFirstChild ( ) . getTextContent ( ) ; return ( null == url || "" . equals ( url ) ) ? null : new URL ( url ) ; }
Extracts a URL from a document that consists of a URL only .
37,537
private static void stripEmptyTextNodes ( Node n ) { NodeList children = n . getChildNodes ( ) ; int length = children . getLength ( ) ; for ( int i = 0 ; i < length ; i ++ ) { Node c = children . item ( i ) ; if ( ! c . hasChildNodes ( ) && c . getNodeType ( ) == Node . TEXT_NODE && c . getTextContent ( ) . trim ( ) . length ( ) == 0 ) { n . removeChild ( c ) ; i -- ; length -- ; children = n . getChildNodes ( ) ; } else { stripEmptyTextNodes ( c ) ; } } }
Hack ... since DOM reads newlines as textnodes we want to strip out those nodes to make it easier to use the tree .
37,538
public static void printDom ( Node n , String prefix ) { String outString = prefix ; if ( n . getNodeType ( ) == Node . TEXT_NODE ) { outString += "'" + n . getTextContent ( ) . trim ( ) + "'" ; } else { outString += n . getNodeName ( ) ; } System . out . println ( outString ) ; NodeList children = n . getChildNodes ( ) ; int length = children . getLength ( ) ; for ( int i = 0 ; i < length ; i ++ ) { FacebookXmlRestClient . printDom ( children . item ( i ) , prefix + " " ) ; } }
Prints out the DOM tree .
37,539
public void run ( ) { final MobicentsSipApplicationSession sipApplicationSession = getApplicationSession ( ) ; SipContext sipContext = sipApplicationSession . getSipContext ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "running Servlet Timer " + id + " for sip application session " + sipApplicationSession ) ; } boolean batchStarted = false ; ClassLoader oldClassLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { sipContext . enterSipContext ( ) ; sipContext . enterSipApp ( sipApplicationSession , null , false , true ) ; batchStarted = sipContext . enterSipAppHa ( true ) ; if ( isCanceled == false ) { listener . timeout ( this ) ; } else { logger . debug ( "running Servlet Timer " + id + " for sip application session " + sipApplicationSession + " is cancelled, so we skip its timerListener's timeout() method call!" ) ; } } catch ( Throwable t ) { logger . error ( "An unexpected exception happened in the timer callback!" , t ) ; } finally { try { sipContext . exitSipContext ( oldClassLoader ) ; if ( isRepeatingTimer ) { estimateNextExecution ( ) ; } else { cancel ( ) ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Servlet Timer " + id + " for sip application session " + sipApplicationSession + " ended" ) ; } } finally { sipContext . exitSipAppHa ( null , null , batchStarted ) ; sipContext . exitSipApp ( sipApplicationSession , null ) ; } } }
Method that actually
37,540
private void estimateNextExecution ( ) { synchronized ( TIMER_LOCK ) { if ( fixedDelay ) { scheduledExecutionTime = period + System . currentTimeMillis ( ) ; } else { if ( firstExecution == 0 ) { firstExecution = scheduledExecutionTime ; } long now = System . currentTimeMillis ( ) ; long executedTime = ( numInvocations ++ * period ) ; scheduledExecutionTime = firstExecution + executedTime ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "next execution estimated to run at " + scheduledExecutionTime ) ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "current time is " + now ) ; } } } }
Helper to calculate when next execution time is .
37,541
public void addPermission ( String path ) { if ( path == null ) { return ; } if ( securityManager != null ) { Permission permission = null ; if ( path . startsWith ( "jndi:" ) || path . startsWith ( "jar:jndi:" ) ) { if ( ! path . endsWith ( "/" ) ) { path = path + "/" ; } permission = new JndiPermission ( path + "*" ) ; addPermission ( permission ) ; } else { if ( ! path . endsWith ( File . separator ) ) { permission = new FilePermission ( path , "read" ) ; addPermission ( permission ) ; path = path + File . separator ; } permission = new FilePermission ( path + "-" , "read" ) ; addPermission ( permission ) ; } } }
If there is a Java SecurityManager create a read FilePermission or JndiPermission for the file directory path .
37,542
public void addPermission ( Permission permission ) { if ( ( securityManager != null ) && ( permission != null ) ) { permissionList . add ( permission ) ; } }
If there is a Java SecurityManager create a Permission .
37,543
public void stop ( ) throws LifecycleException { clearReferences ( ) ; int length = files . length ; for ( int i = 0 ; i < length ; i ++ ) { files [ i ] = null ; } length = jarFiles . length ; for ( int i = 0 ; i < length ; i ++ ) { try { if ( jarFiles [ i ] != null ) { jarFiles [ i ] . close ( ) ; } } catch ( IOException e ) { } jarFiles [ i ] = null ; } notFoundResources . clear ( ) ; resourceEntries . clear ( ) ; resources = null ; repositories = null ; repositoryURLs = null ; files = null ; jarFiles = null ; jarRealFiles = null ; jarPath = null ; jarNames = null ; lastModifiedDates = null ; paths = null ; hasExternalRepositories = false ; parent = null ; permissionList . clear ( ) ; loaderPC . clear ( ) ; if ( loaderDir != null ) { deleteDir ( loaderDir ) ; } }
Stop the class loader .
37,544
protected void clearReferences ( ) { Enumeration drivers = DriverManager . getDrivers ( ) ; while ( drivers . hasMoreElements ( ) ) { Driver driver = ( Driver ) drivers . nextElement ( ) ; if ( driver . getClass ( ) . getClassLoader ( ) == this ) { try { DriverManager . deregisterDriver ( driver ) ; } catch ( SQLException e ) { log . warn ( "SQL driver deregistration failed" , e ) ; } } } if ( ENABLE_CLEAR_REFERENCES ) { Iterator loadedClasses = ( ( HashMap ) ( ( HashMap ) resourceEntries ) . clone ( ) ) . values ( ) . iterator ( ) ; while ( loadedClasses . hasNext ( ) ) { ResourceEntry entry = ( ResourceEntry ) loadedClasses . next ( ) ; if ( entry . loadedClass != null ) { Class clazz = entry . loadedClass ; try { Field [ ] fields = clazz . getDeclaredFields ( ) ; for ( int i = 0 ; i < fields . length ; i ++ ) { Field field = fields [ i ] ; int mods = field . getModifiers ( ) ; if ( field . getType ( ) . isPrimitive ( ) || ( field . getName ( ) . indexOf ( "$" ) != - 1 ) ) { continue ; } if ( Modifier . isStatic ( mods ) ) { try { field . setAccessible ( true ) ; if ( Modifier . isFinal ( mods ) ) { if ( ! ( ( field . getType ( ) . getName ( ) . startsWith ( "java." ) ) || ( field . getType ( ) . getName ( ) . startsWith ( "javax." ) ) ) ) { nullInstance ( field . get ( null ) ) ; } } else { field . set ( null , null ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Set field " + field . getName ( ) + " to null in class " + clazz . getName ( ) ) ; } } } catch ( Throwable t ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Could not set field " + field . getName ( ) + " to null in class " + clazz . getName ( ) , t ) ; } } } } } catch ( Throwable t ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Could not clean fields for class " + clazz . getName ( ) , t ) ; } } } } } IntrospectionUtils . clear ( ) ; org . apache . juli . logging . LogFactory . release ( this ) ; java . beans . Introspector . flushCaches ( ) ; }
Clear references .
37,545
protected boolean loadedByThisOrChild ( Class clazz ) { boolean result = false ; for ( ClassLoader classLoader = clazz . getClassLoader ( ) ; null != classLoader ; classLoader = classLoader . getParent ( ) ) { if ( classLoader . equals ( this ) ) { result = true ; break ; } } return result ; }
Determine whether a class was loaded by this class loader or one of its child class loaders .
37,546
protected Class findClassInternal ( String name ) throws ClassNotFoundException { if ( ! validate ( name ) ) throw new ClassNotFoundException ( name ) ; String tempPath = name . replace ( '.' , '/' ) ; String classPath = tempPath + ".class" ; ResourceEntry entry = null ; entry = findResourceInternal ( name , classPath ) ; if ( entry == null ) throw new ClassNotFoundException ( name ) ; Class clazz = entry . loadedClass ; if ( clazz != null ) return clazz ; synchronized ( this ) { if ( entry . binaryContent == null && entry . loadedClass == null ) throw new ClassNotFoundException ( name ) ; String packageName = null ; int pos = name . lastIndexOf ( '.' ) ; if ( pos != - 1 ) packageName = name . substring ( 0 , pos ) ; Package pkg = null ; if ( packageName != null ) { pkg = getPackage ( packageName ) ; if ( pkg == null ) { try { if ( entry . manifest == null ) { definePackage ( packageName , null , null , null , null , null , null , null ) ; } else { definePackage ( packageName , entry . manifest , entry . codeBase ) ; } } catch ( IllegalArgumentException e ) { } pkg = getPackage ( packageName ) ; } } if ( securityManager != null ) { if ( pkg != null ) { boolean sealCheck = true ; if ( pkg . isSealed ( ) ) { sealCheck = pkg . isSealed ( entry . codeBase ) ; } else { sealCheck = ( entry . manifest == null ) || ! isPackageSealed ( packageName , entry . manifest ) ; } if ( ! sealCheck ) throw new SecurityException ( "Sealing violation loading " + name + " : Package " + packageName + " is sealed." ) ; } } if ( entry . loadedClass == null ) { clazz = defineClass ( name , entry . binaryContent , 0 , entry . binaryContent . length , new CodeSource ( entry . codeBase , entry . certificates ) ) ; entry . loadedClass = clazz ; entry . binaryContent = null ; entry . source = null ; entry . codeBase = null ; entry . manifest = null ; entry . certificates = null ; } else { clazz = entry . loadedClass ; } } return clazz ; }
Find specified class in local repositories .
37,547
protected ResourceEntry findResourceInternal ( File file , String path ) { ResourceEntry entry = new ResourceEntry ( ) ; try { entry . source = getURI ( new File ( file , path ) ) ; entry . codeBase = getURL ( new File ( file , path ) , false ) ; } catch ( MalformedURLException e ) { return null ; } return entry ; }
Find specified resource in local repositories . This block will execute under an AccessControl . doPrivilege block .
37,548
protected boolean filter ( String name ) { if ( name == null ) return false ; String packageName = null ; int pos = name . lastIndexOf ( '.' ) ; if ( pos != - 1 ) packageName = name . substring ( 0 , pos ) ; else return false ; for ( int i = 0 ; i < packageTriggers . length ; i ++ ) { if ( packageName . startsWith ( packageTriggers [ i ] ) ) return true ; } return false ; }
Filter classes .
37,549
protected static void deleteDir ( File dir ) { String files [ ] = dir . list ( ) ; if ( files == null ) { files = new String [ 0 ] ; } for ( int i = 0 ; i < files . length ; i ++ ) { File file = new File ( dir , files [ i ] ) ; if ( file . isDirectory ( ) ) { deleteDir ( file ) ; } else { try { file . delete ( ) ; } catch ( SecurityException se ) { log . error ( "The file " + file . getAbsolutePath ( ) + " couldn't be deleted" ) ; } } } try { dir . delete ( ) ; } catch ( SecurityException se ) { log . error ( "The directory " + dir . getAbsolutePath ( ) + " couldn't be deleted" ) ; } }
Delete the specified directory including all of its contents and subdirectories recursively .
37,550
private final static String basePhoneNumber ( String number ) throws ParseException { StringBuffer s = new StringBuffer ( ) ; Lexer lexer = new Lexer ( "sip_urlLexer" , number ) ; int lc = 0 ; while ( lexer . hasMoreChars ( ) ) { char w = lexer . lookAhead ( 0 ) ; if ( Lexer . isDigit ( w ) || w == '-' || w == '.' || w == '(' || w == ')' ) { lexer . consume ( 1 ) ; s . append ( w ) ; lc ++ ; } else throw new IllegalArgumentException ( "unexpected " + w + " in the phone number" ) ; } return s . toString ( ) ; }
the part in comment
37,551
private static Properties loadProperties ( String defaultsName , String propertiesName ) throws IOException { Properties bundle = new Properties ( ) ; ClassLoader loader = SecurityActions . getContextClassLoader ( ) ; URL defaultUrl = null ; URL url = null ; if ( loader instanceof URLClassLoader ) { URLClassLoader ucl = ( URLClassLoader ) loader ; defaultUrl = SecurityActions . findResource ( ucl , defaultsName ) ; url = SecurityActions . findResource ( ucl , propertiesName ) ; PicketBoxLogger . LOGGER . traceAttemptToLoadResource ( propertiesName ) ; } if ( defaultUrl == null ) { defaultUrl = loader . getResource ( defaultsName ) ; if ( defaultUrl == null ) { try { defaultUrl = new URL ( defaultsName ) ; } catch ( MalformedURLException mue ) { PicketBoxLogger . LOGGER . debugFailureToOpenPropertiesFromURL ( mue ) ; File tmp = new File ( defaultsName ) ; if ( tmp . exists ( ) ) { defaultUrl = tmp . toURI ( ) . toURL ( ) ; } } } } if ( url == null ) { url = loader . getResource ( propertiesName ) ; if ( url == null ) { try { url = new URL ( propertiesName ) ; } catch ( MalformedURLException mue ) { PicketBoxLogger . LOGGER . debugFailureToOpenPropertiesFromURL ( mue ) ; File tmp = new File ( propertiesName ) ; if ( tmp . exists ( ) ) { url = tmp . toURI ( ) . toURL ( ) ; } } } } if ( url == null && defaultUrl == null ) { String propertiesFiles = propertiesName + "/" + defaultsName ; throw PicketBoxMessages . MESSAGES . unableToFindPropertiesFile ( propertiesFiles ) ; } if ( url != null ) { InputStream is = null ; try { is = SecurityActions . openStream ( url ) ; } catch ( PrivilegedActionException e ) { throw new IOException ( e . getLocalizedMessage ( ) ) ; } if ( is != null ) { try { bundle . load ( is ) ; } finally { safeClose ( is ) ; } } else { throw PicketBoxMessages . MESSAGES . unableToLoadPropertiesFile ( propertiesName ) ; } PicketBoxLogger . LOGGER . tracePropertiesFileLoaded ( propertiesName , bundle . keySet ( ) ) ; } else { InputStream is = null ; try { is = defaultUrl . openStream ( ) ; bundle . load ( is ) ; PicketBoxLogger . LOGGER . tracePropertiesFileLoaded ( defaultsName , bundle . keySet ( ) ) ; } catch ( Throwable e ) { PicketBoxLogger . LOGGER . debugFailureToLoadPropertiesFile ( defaultsName , e ) ; } finally { safeClose ( is ) ; } } return bundle ; }
helper method to load digest user property file . Copied from org . jboss . security . auth . spi . Util
37,552
protected static String removeQuotes ( String quotedString , boolean quotesRequired ) { if ( quotedString . length ( ) > 0 && quotedString . charAt ( 0 ) != '"' && ! quotesRequired ) { return quotedString ; } else if ( quotedString . length ( ) > 2 ) { return quotedString . substring ( 1 , quotedString . length ( ) - 1 ) ; } else { return "" ; } }
Removes the quotes on a string . RFC2617 states quotes are optional for all parameters except realm .
37,553
protected synchronized MessageDigest getDigest ( ) { if ( this . digest == null ) { try { this . digest = MessageDigest . getInstance ( algorithm ) ; } catch ( NoSuchAlgorithmException e ) { try { this . digest = MessageDigest . getInstance ( DEFAULT_ALGORITHM ) ; } catch ( NoSuchAlgorithmException f ) { this . digest = null ; } } } return ( this . digest ) ; }
Return the MessageDigest object to be used for calculating session identifiers . If none has been created yet initialize one the first time this method is called .
37,554
protected synchronized Random getRandom ( ) { if ( this . random == null ) { try { Class clazz = Class . forName ( randomClass ) ; this . random = ( Random ) clazz . newInstance ( ) ; long seed = System . currentTimeMillis ( ) ; char [ ] entropy = getEntropy ( ) . toCharArray ( ) ; for ( int i = 0 ; i < entropy . length ; i ++ ) { long update = ( ( byte ) entropy [ i ] ) << ( ( i % 8 ) * 8 ) ; seed ^= update ; } this . random . setSeed ( seed ) ; } catch ( Exception e ) { this . random = new java . util . Random ( ) ; } } return ( this . random ) ; }
Return the random number generator instance we should use for generating session identifiers . If there is no such generator currently defined construct and seed a new one .
37,555
public static int getAddressOutboundness ( String address ) { if ( address . startsWith ( "127.0" ) ) return 0 ; if ( address . startsWith ( "192.168" ) ) return 1 ; if ( address . startsWith ( "10." ) ) return 2 ; if ( address . startsWith ( "172.16" ) || address . startsWith ( "172.17" ) || address . startsWith ( "172.18" ) || address . startsWith ( "172.19" ) || address . startsWith ( "172.20" ) || address . startsWith ( "172.21" ) || address . startsWith ( "172.22" ) || address . startsWith ( "172.23" ) || address . startsWith ( "172.24" ) || address . startsWith ( "172.25" ) || address . startsWith ( "172.26" ) || address . startsWith ( "172.27" ) || address . startsWith ( "172.28" ) || address . startsWith ( "172.29" ) || address . startsWith ( "172.30" ) || address . startsWith ( "172.31" ) ) return 3 ; if ( address . indexOf ( "." ) > 0 ) return 4 ; return - 1 ; }
RFC 1918 address spaces
37,556
public ViaHeader createViaHeader ( String branch , boolean usePublicAddress ) { try { String host = getIpAddress ( usePublicAddress ) ; ViaHeader via = SipFactoryImpl . headerFactory . createViaHeader ( host , port , transport , branch ) ; return via ; } catch ( ParseException ex ) { logger . error ( "Unexpected error while creating a via header" , ex ) ; throw new IllegalArgumentException ( "Unexpected exception when creating via header " , ex ) ; } catch ( InvalidArgumentException e ) { logger . error ( "Unexpected error while creating a via header" , e ) ; throw new IllegalArgumentException ( "Unexpected exception when creating via header " , e ) ; } }
Create a Via Header based on the host port and transport of this listening point
37,557
public javax . sip . address . SipURI createRecordRouteURI ( boolean usePublicAddress ) { try { String host = getIpAddress ( usePublicAddress ) ; SipURI sipUri = SipFactoryImpl . addressFactory . createSipURI ( null , host ) ; sipUri . setPort ( port ) ; sipUri . setTransportParam ( transport ) ; return sipUri ; } catch ( ParseException ex ) { logger . error ( "Unexpected error while creating a record route URI" , ex ) ; throw new IllegalArgumentException ( "Unexpected exception when creating a record route URI" , ex ) ; } }
Create a Record Route URI based on the host port and transport of this listening point
37,558
public void removeCorrespondingSipApplicationSession ( MobicentsSipApplicationSessionKey sipApplicationSession ) { joinApplicationSession . remove ( sipApplicationSession ) ; replacesApplicationSession . remove ( sipApplicationSession ) ; Iterator < MobicentsSipApplicationSessionKey > it = joinApplicationSession . values ( ) . iterator ( ) ; boolean found = false ; while ( it . hasNext ( ) && ! found ) { MobicentsSipApplicationSessionKey sipApplicationSessionKey = it . next ( ) ; if ( sipApplicationSessionKey . equals ( sipApplicationSession ) ) { joinApplicationSession . remove ( sipApplicationSessionKey ) ; found = true ; } } it = replacesApplicationSession . values ( ) . iterator ( ) ; found = false ; while ( it . hasNext ( ) && ! found ) { MobicentsSipApplicationSessionKey sipApplicationSessionKey = it . next ( ) ; if ( sipApplicationSessionKey . equals ( sipApplicationSession ) ) { replacesApplicationSession . remove ( sipApplicationSessionKey ) ; found = true ; } } }
Add a mapping between a corresponding sipSession related to a headerName . See Also getCorrespondingSipSession method .
37,559
public void notifySipSessionListeners ( SipSessionEventType sipSessionEventType ) { MobicentsSipApplicationSession sipApplicationSession = getSipApplicationSession ( ) ; if ( sipApplicationSession != null ) { SipContext sipContext = sipApplicationSession . getSipContext ( ) ; List < SipSessionListener > sipSessionListeners = sipContext . getListeners ( ) . getSipSessionListeners ( ) ; if ( sipSessionListeners . size ( ) > 0 ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "notifying sip session listeners of context " + sipContext . getApplicationName ( ) + " of following event " + sipSessionEventType ) ; } ClassLoader oldClassLoader = java . lang . Thread . currentThread ( ) . getContextClassLoader ( ) ; sipContext . enterSipContext ( ) ; SipSessionEvent sipSessionEvent = new SipSessionEvent ( this . getFacade ( ) ) ; for ( SipSessionListener sipSessionListener : sipSessionListeners ) { try { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "notifying sip session listener " + sipSessionListener . getClass ( ) . getName ( ) + " of context " + key . getApplicationName ( ) + " of following event " + sipSessionEventType ) ; } if ( SipSessionEventType . CREATION . equals ( sipSessionEventType ) ) { sipSessionListener . sessionCreated ( sipSessionEvent ) ; } else if ( SipSessionEventType . DELETION . equals ( sipSessionEventType ) ) { sipSessionListener . sessionDestroyed ( sipSessionEvent ) ; } else if ( SipSessionEventType . READYTOINVALIDATE . equals ( sipSessionEventType ) ) { sipSessionListener . sessionReadyToInvalidate ( sipSessionEvent ) ; } } catch ( Throwable t ) { logger . error ( "SipSessionListener threw exception" , t ) ; } } sipContext . exitSipContext ( oldClassLoader ) ; } } }
Notifies the listeners that a lifecycle event occured on that sip session
37,560
protected boolean hasOngoingTransaction ( ) { if ( ! isSupervisedMode ( ) ) { return false ; } else { if ( ongoingTransactions != null ) { for ( Transaction transaction : ongoingTransactions ) { if ( TransactionState . CALLING . equals ( transaction . getState ( ) ) || TransactionState . TRYING . equals ( transaction . getState ( ) ) || TransactionState . PROCEEDING . equals ( transaction . getState ( ) ) || TransactionState . COMPLETED . equals ( transaction . getState ( ) ) || TransactionState . CONFIRMED . equals ( transaction . getState ( ) ) ) { return true ; } } } return false ; } }
Removed from the interface in PFD stage so making it protected
37,561
public void addOngoingTransaction ( Transaction transaction ) { if ( transaction != null && ongoingTransactions != null && ! isReadyToInvalidate ( ) ) { boolean added = this . ongoingTransactions . add ( transaction ) ; if ( added ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "transaction " + transaction + " has been added to sip session's ongoingTransactions" ) ; } setReadyToInvalidate ( false ) ; } } }
Add an ongoing tx to the session .
37,562
public void removeOngoingTransaction ( Transaction transaction ) { boolean removed = false ; if ( this . ongoingTransactions != null ) { removed = this . ongoingTransactions . remove ( transaction ) ; } if ( proxy != null ) { proxy . removeTransaction ( transaction . getBranchId ( ) ) ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "transaction " + transaction + " has been removed from sip session's ongoingTransactions ? " + removed ) ; } updateReadyToInvalidate ( transaction ) ; final String branchId = transaction . getBranchId ( ) ; if ( sessionCreatingTransactionRequest != null && branchId != null ) { final Transaction sessionCreatingTransactionRequestTransaction = sessionCreatingTransactionRequest . getTransaction ( ) ; String sessionCreatingTransactionRequestTransactionBranchId = null ; if ( sessionCreatingTransactionRequestTransaction != null ) { sessionCreatingTransactionRequestTransactionBranchId = sessionCreatingTransactionRequestTransaction . getBranchId ( ) ; } final String sessionCreatingTransactionRequestMethod = sessionCreatingTransactionRequest . getMethod ( ) ; if ( sessionCreatingTransactionRequestTransaction != null && branchId . equals ( sessionCreatingTransactionRequestTransactionBranchId ) ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Session " + key + ": cleaning up " + sessionCreatingTransactionRequest + " since transaction " + transaction + " with branch id " + branchId + " is the same as sessionCreatingRequestTransaction " + sessionCreatingTransactionRequestTransaction + " with branch id " + sessionCreatingTransactionRequestTransactionBranchId + " and method " + sessionCreatingTransactionRequestMethod ) ; } sessionCreatingTransactionRequest . cleanUp ( ) ; if ( sessionCreatingDialog != null || proxy != null || JainSipUtils . DIALOG_CREATING_METHODS . contains ( sessionCreatingTransactionRequestMethod ) ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "removeOngoingTransaction - sessionCreatingTransactionRequest=" + sessionCreatingTransactionRequest ) ; } if ( logger . isDebugEnabled ( ) && sessionCreatingTransactionRequest != null ) { logger . debug ( "nullifying sessionCreatingTransactionRequest" + sessionCreatingTransactionRequest + " from Session " + key ) ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "invalidate - setting the sessionCreatingTransactionRequest to null, id:" + this . getId ( ) ) ; } sessionCreatingTransactionRequest = null ; } } } }
Remove an ongoing tx to the session .
37,563
public void onReadyToInvalidate ( ) { if ( isB2BUAOrphan ( ) ) { logger . debug ( "Session is B2BUA Orphaned, lets invalidate" ) ; setReadyToInvalidate ( true ) ; } if ( ! readyToInvalidate ) { logger . debug ( "Session not ready to invalidate, wait next chance." ) ; return ; } boolean allDerivedReady = true ; Iterator < MobicentsSipSession > derivedSessionsIterator = this . getDerivedSipSessions ( ) ; while ( derivedSessionsIterator . hasNext ( ) ) { MobicentsSipSession mobicentsSipSession = ( MobicentsSipSession ) derivedSessionsIterator . next ( ) ; boolean derivedIsOrphaned = mobicentsSipSession . isB2BUAOrphan ( ) ; boolean derivedReady = ! mobicentsSipSession . isValid ( ) || derivedIsOrphaned ; allDerivedReady = allDerivedReady & derivedReady ; } if ( logger . isDebugEnabled ( ) ) { String msg = String . format ( "Session [%s] onReadyToInvalidate, hasParent [%s], hasDerivedSessions [%s], will invalidate [%s]" , key , parentSession != null , derivedSipSessions != null , allDerivedReady ) ; logger . debug ( msg ) ; } if ( ! allDerivedReady ) { logger . debug ( "Cant invalidate yet, lets wait until all derived to be ready." ) ; return ; } else { logger . debug ( "All Derived ready, lets proceed." ) ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "invalidateWhenReady flag is set to " + invalidateWhenReady ) ; } if ( isValid ( ) && this . invalidateWhenReady ) { this . notifySipSessionListeners ( SipSessionEventType . READYTOINVALIDATE ) ; if ( isValid ( ) ) { invalidate ( true ) ; } } }
This method is called immediately when the conditions for read to invalidate session are met
37,564
public void setAckReceived ( long cSeq , boolean ackReceived ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "setting AckReceived to : " + ackReceived + " for CSeq " + cSeq ) ; } acksReceived . put ( cSeq , ackReceived ) ; if ( ackReceived ) { cleanupAcksReceived ( cSeq ) ; } }
Setting ackReceived for CSeq to specified value in second param . if the second param is true it will try to cleanup earlier cseq as well to save on memory
37,565
protected boolean isAckReceived ( long cSeq ) { if ( acksReceived == null ) { return true ; } Boolean ackReceived = acksReceived . get ( cSeq ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "isAckReceived for CSeq " + cSeq + " : " + ackReceived ) ; } if ( ackReceived == null ) { return true ; } return ackReceived ; }
check if the ack has been received for the cseq in param it may happen that the ackReceived has been removed already if that s the case it will return true
37,566
protected void cleanupAcksReceived ( long remoteCSeq ) { List < Long > toBeRemoved = new ArrayList < Long > ( ) ; final Iterator < Entry < Long , Boolean > > cSeqs = acksReceived . entrySet ( ) . iterator ( ) ; while ( cSeqs . hasNext ( ) ) { final Entry < Long , Boolean > entry = cSeqs . next ( ) ; final long cSeq = entry . getKey ( ) ; final boolean ackReceived = entry . getValue ( ) ; if ( ackReceived && cSeq < remoteCSeq ) { toBeRemoved . add ( cSeq ) ; } } for ( Long cSeq : toBeRemoved ) { acksReceived . remove ( cSeq ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "removed ackReceived for CSeq " + cSeq ) ; } } }
We clean up the stored acks received when the remoteCSeq in param is greater and that the ackReceived is true
37,567
public boolean validateCSeq ( MobicentsSipServletRequest sipServletRequest ) { final Request request = ( Request ) sipServletRequest . getMessage ( ) ; final long localCseq = cseq ; final long remoteCSeq = ( ( CSeqHeader ) request . getHeader ( CSeqHeader . NAME ) ) . getSeqNumber ( ) ; final String method = request . getMethod ( ) ; final boolean isAck = Request . ACK . equalsIgnoreCase ( method ) ; final boolean isPrackCancel = Request . PRACK . equalsIgnoreCase ( method ) || Request . CANCEL . equalsIgnoreCase ( method ) ; boolean resetLocalCSeq = true ; if ( isAck && isAckReceived ( remoteCSeq ) ) { logger . debug ( "ACK filtered out as a retransmission. This Sip Session already has been ACKed." ) ; return false ; } if ( isAck ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "localCSeq : " + localCseq + ", remoteCSeq : " + remoteCSeq ) ; } setAckReceived ( remoteCSeq , true ) ; } if ( localCseq == remoteCSeq && ! isAck ) { logger . debug ( "dropping retransmission " + request + " since it matches the current sip session cseq " + localCseq ) ; return false ; } if ( localCseq > remoteCSeq ) { if ( ! isAck && ! isPrackCancel ) { logger . error ( "CSeq out of order for the following request " + sipServletRequest ) ; if ( Request . INVITE . equalsIgnoreCase ( method ) ) { setAckReceived ( remoteCSeq , false ) ; } final SipServletResponse response = sipServletRequest . createResponse ( Response . SERVER_INTERNAL_ERROR , "CSeq out of order" ) ; try { response . send ( ) ; } catch ( IOException e ) { logger . error ( "Can not send error response" , e ) ; } return false ; } else { resetLocalCSeq = false ; } } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "resetLocalCSeq : " + resetLocalCSeq ) ; } if ( resetLocalCSeq ) { setCseq ( remoteCSeq ) ; if ( Request . INVITE . equalsIgnoreCase ( method ) ) { setAckReceived ( remoteCSeq , false ) ; } } return true ; }
CSeq validation should only be done for non proxy applications
37,568
protected void doMessage ( SipServletRequest request ) throws ServletException , IOException { request . createResponse ( SipServletResponse . SC_OK ) . send ( ) ; Object message = request . getContent ( ) ; String from = request . getFrom ( ) . getURI ( ) . toString ( ) ; logger . info ( "from is " + from ) ; if ( message . toString ( ) . equalsIgnoreCase ( "/quit" ) ) { sendToUser ( from , "Bye" ) ; removeUser ( from ) ; return ; } if ( ! containsUser ( from ) ) { sendToUser ( from , "Welcome to chatroom " + serverAddress + ". Type '/quit' to exit." ) ; addUser ( from ) ; } if ( message . toString ( ) . equalsIgnoreCase ( "/who" ) ) { String users = "List of users:\n" ; List < String > list = ( List < String > ) getServletContext ( ) . getAttribute ( USER_LIST ) ; for ( String user : list ) { users += user + "\n" ; } sendToUser ( from , users ) ; return ; } if ( message . toString ( ) . equalsIgnoreCase ( "/join" ) ) { return ; } sendToAll ( from , message , request . getHeader ( "Content-Type" ) ) ; }
This is called by the container when a MESSAGE message arrives .
37,569
protected void doErrorResponse ( SipServletResponse response ) throws ServletException , IOException { String receiver = response . getTo ( ) . toString ( ) ; removeUser ( receiver ) ; }
This is called by the container when an error is received regarding a sent message including timeouts .
37,570
private static MimeMultipart getContentAsMimeMultipart ( ContentTypeHeader contentTypeHeader , byte [ ] rawContent ) { String delimiter = contentTypeHeader . getParameter ( MULTIPART_BOUNDARY ) ; String start = contentTypeHeader . getParameter ( MULTIPART_START ) ; MimeMultipart mimeMultipart = new MimeMultipart ( contentTypeHeader . getContentSubType ( ) ) ; if ( delimiter == null ) { MimeBodyPart mbp = new MimeBodyPart ( ) ; DataSource ds = new ByteArrayDataSource ( rawContent , contentTypeHeader . getContentSubType ( ) ) ; try { mbp . setDataHandler ( new DataHandler ( ds ) ) ; mimeMultipart . addBodyPart ( mbp ) ; } catch ( MessagingException e ) { throw new IllegalArgumentException ( "couldn't create the multipart object from the message content " + rawContent , e ) ; } } else { String [ ] fragments = new String ( rawContent ) . split ( MULTIPART_BOUNDARY_DELIM + delimiter ) ; for ( String fragment : fragments ) { final String trimmedFragment = fragment . trim ( ) ; if ( trimmedFragment . length ( ) > 0 && ! MULTIPART_BOUNDARY_DELIM . equals ( trimmedFragment ) ) { String fragmentHeaders = null ; String fragmentBody = fragment ; if ( start != null && start . length ( ) > 0 ) { int indexOfStart = fragment . indexOf ( start ) ; if ( indexOfStart != - 1 ) { fragmentHeaders = fragmentBody . substring ( 0 , indexOfStart + start . length ( ) ) ; fragmentBody = fragmentBody . substring ( indexOfStart + start . length ( ) ) . trim ( ) ; } } MimeBodyPart mbp = new MimeBodyPart ( ) ; try { String contentType = contentTypeHeader . getContentSubType ( ) ; if ( fragmentBody . startsWith ( ContentTypeHeader . NAME ) ) { int indexOfLineReturn = fragmentBody . indexOf ( LINE_RETURN_DELIM ) ; contentType = fragmentBody . substring ( 0 , indexOfLineReturn - 1 ) . trim ( ) ; fragmentBody = fragmentBody . substring ( indexOfLineReturn ) . trim ( ) ; } mbp . setContent ( fragmentBody , contentType ) ; mbp . addHeaderLine ( contentType ) ; if ( fragmentHeaders != null ) { StringTokenizer stringTokenizer = new StringTokenizer ( fragmentHeaders , LINE_RETURN_DELIM ) ; while ( stringTokenizer . hasMoreTokens ( ) ) { String token = stringTokenizer . nextToken ( ) . trim ( ) ; if ( token != null && token . length ( ) > 0 ) { mbp . addHeaderLine ( token ) ; } } } mimeMultipart . addBodyPart ( mbp ) ; } catch ( MessagingException e ) { throw new IllegalArgumentException ( "couldn't create the multipart object from the message content " + rawContent , e ) ; } } } } return mimeMultipart ; }
Return a mimemultipart from raw Content FIXME Doesn t support nested multipart in the body content
37,571
public final MobicentsSipSession getSipSession ( ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "getSipSession" ) ; } if ( sipSession == null && sessionKey == null ) { sessionKey = getSipSessionKey ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "sessionKey is " + sessionKey ) ; } if ( sessionKey == null ) { if ( sipSession == null ) { if ( transactionApplicationData != null ) { this . sessionKey = transactionApplicationData . getSipSessionKey ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "session Key is " + sessionKey + ", retrieved from the txAppData " + transactionApplicationData ) ; } } else if ( transaction != null && transaction . getApplicationData ( ) != null ) { this . sessionKey = ( ( TransactionApplicationData ) transaction . getApplicationData ( ) ) . getSipSessionKey ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "session Key is " + sessionKey + ", retrieved from the transaction txAppData " + ( TransactionApplicationData ) transaction . getApplicationData ( ) ) ; } } else { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "txAppData and transaction txAppData are both null, there is no wya to retrieve the sessionKey anymore" ) ; } } } else { this . sessionKey = sipSession . getKey ( ) ; } } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "sessionKey is " + sessionKey ) ; } } if ( sipSession == null && sessionKey != null ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "session is null, trying to load the session from the sessionKey " + sessionKey ) ; } final String applicationName = sessionKey . getApplicationName ( ) ; final SipContext sipContext = sipFactoryImpl . getSipApplicationDispatcher ( ) . findSipApplication ( applicationName ) ; SipApplicationSessionKey sipApplicationSessionKey = new SipApplicationSessionKey ( sessionKey . getApplicationSessionId ( ) , sessionKey . getApplicationName ( ) , null ) ; MobicentsSipApplicationSession sipApplicationSession = sipContext . getSipManager ( ) . getSipApplicationSession ( sipApplicationSessionKey , false ) ; sipSession = sipContext . getSipManager ( ) . getSipSession ( sessionKey , false , sipFactoryImpl , sipApplicationSession ) ; if ( logger . isDebugEnabled ( ) ) { if ( sipSession == null ) { logger . debug ( "couldn't find any session with sessionKey " + sessionKey ) ; } else { logger . debug ( "reloaded session session " + sipSession + " with sessionKey " + sessionKey ) ; } } } return sipSession ; }
Retrieve the sip session implementation
37,572
protected ModifiableRule retrieveModifiableOverriden ( ) { ModifiableRule overridenRule = null ; SipSession session = getSession ( ) ; if ( session != null && session . getServletContext ( ) != null ) { String overridenRuleStr = session . getServletContext ( ) . getInitParameter ( SYS_HDR_MOD_OVERRIDE ) ; if ( overridenRuleStr != null ) { overridenRule = ModifiableRule . valueOf ( overridenRuleStr ) ; } } return overridenRule ; }
Allows to override the System header modifiable rule assignment .
37,573
protected static String getFullHeaderName ( String headerName ) { String fullName = null ; if ( JainSipUtils . HEADER_COMPACT_2_FULL_NAMES_MAPPINGS . containsKey ( headerName ) ) { fullName = JainSipUtils . HEADER_COMPACT_2_FULL_NAMES_MAPPINGS . get ( headerName ) ; } else { fullName = headerName ; } if ( logger . isDebugEnabled ( ) ) logger . debug ( "Fetching full header name for [" + headerName + "] returning [" + fullName + "]" ) ; return fullName ; }
This method tries to resolve header name - meaning if it is compact - it returns full name if its not it returns passed value .
37,574
public static String getCompactName ( String headerName ) { String compactName = null ; if ( JainSipUtils . HEADER_COMPACT_2_FULL_NAMES_MAPPINGS . containsKey ( headerName ) ) { compactName = JainSipUtils . HEADER_COMPACT_2_FULL_NAMES_MAPPINGS . get ( headerName ) ; } else { compactName = JainSipUtils . HEADER_FULL_TO_COMPACT_NAMES_MAPPINGS . get ( headerName ) ; } if ( logger . isDebugEnabled ( ) ) logger . debug ( "Fetching compact header name for [" + headerName + "] returning [" + compactName + "]" ) ; return compactName ; }
This method tries to determine compact header name - if passed value is compact form it is returned otherwise method tries to find compact name - if it is found string rpresenting compact name is returned otherwise null!!!
37,575
protected boolean containsRel100 ( Message message ) { ListIterator < SIPHeader > requireHeaders = message . getHeaders ( RequireHeader . NAME ) ; if ( requireHeaders != null ) { while ( requireHeaders . hasNext ( ) ) { if ( REL100_OPTION_TAG . equals ( requireHeaders . next ( ) . getValue ( ) ) ) { return true ; } } } ListIterator < SIPHeader > supportedHeaders = message . getHeaders ( SupportedHeader . NAME ) ; if ( supportedHeaders != null ) { while ( supportedHeaders . hasNext ( ) ) { if ( REL100_OPTION_TAG . equals ( supportedHeaders . next ( ) . getValue ( ) ) ) { return true ; } } } return false ; }
we check all the values of Require and Supported headers to make sure the 100rel is present
37,576
protected void processConcurrencyAnnotation ( Class clazz ) { if ( sipContext . getConcurrencyControlMode ( ) == null ) { Package pack = clazz . getPackage ( ) ; if ( pack != null ) { ConcurrencyControl concurrencyControl = pack . getAnnotation ( ConcurrencyControl . class ) ; if ( concurrencyControl != null ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Concurrency control annotation found " + concurrencyControl . mode ( ) ) ; } sipContext . setConcurrencyControlMode ( concurrencyControl . mode ( ) ) ; } } } }
Check if the
37,577
public void sendHeartBeat ( String ipAddress , int port ) throws Exception { MBeanServer mbeanServer = getMBeanServer ( ) ; Set < ObjectName > queryNames = mbeanServer . queryNames ( new ObjectName ( "*:type=Service,*" ) , null ) ; for ( ObjectName objectName : queryNames ) { mbeanServer . invoke ( objectName , "sendHeartBeat" , new Object [ ] { this . ipAddress , this . port , this . transport , ipAddress , port } , new String [ ] { String . class . getName ( ) , "int" , String . class . getName ( ) , String . class . getName ( ) , "int" } ) ; } }
Send a heartbeat to the specified Ip address and port via this listening point . This method can be used to send out a period Double CR - LF for NAT keepalive as defined in RFC5626
37,578
protected void doRequest ( javax . servlet . sip . SipServletRequest req ) throws javax . servlet . ServletException , java . io . IOException { String m = req . getMethod ( ) ; if ( "INVITE" . equals ( m ) ) doInvite ( req ) ; else if ( "ACK" . equals ( m ) ) doAck ( req ) ; else if ( "OPTIONS" . equals ( m ) ) doOptions ( req ) ; else if ( "BYE" . equals ( m ) ) doBye ( req ) ; else if ( "CANCEL" . equals ( m ) ) doCancel ( req ) ; else if ( "REGISTER" . equals ( m ) ) doRegister ( req ) ; else if ( "SUBSCRIBE" . equals ( m ) ) doSubscribe ( req ) ; else if ( "NOTIFY" . equals ( m ) ) doNotify ( req ) ; else if ( "MESSAGE" . equals ( m ) ) doMessage ( req ) ; else if ( "INFO" . equals ( m ) ) doInfo ( req ) ; else if ( "REFER" . equals ( m ) ) doRefer ( req ) ; else if ( "PUBLISH" . equals ( m ) ) doPublish ( req ) ; else if ( "UPDATE" . equals ( m ) ) doUpdate ( req ) ; else if ( "PRACK" . equals ( m ) ) doPrack ( req ) ; else if ( req . isInitial ( ) ) notHandled ( req ) ; }
Invoked to handle incoming requests . This method dispatched requests to one of the doXxx methods where Xxx is the SIP method used in the request . Servlets will not usually need to override this method .
37,579
protected void doResponse ( javax . servlet . sip . SipServletResponse resp ) throws javax . servlet . ServletException , java . io . IOException { int status = resp . getStatus ( ) ; if ( status < 200 ) { doProvisionalResponse ( resp ) ; } else { if ( status < 300 ) { doSuccessResponse ( resp ) ; } else if ( status < 400 ) { doRedirectResponse ( resp ) ; } else { doErrorResponse ( resp ) ; } } }
Invoked to handle incoming responses . This method dispatched responses to one of the . Servlets will not usually need to override this method .
37,580
public static String decode ( String uri ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "uri to decode " + uri ) ; } if ( uri == null ) { return null ; } if ( uri . indexOf ( UTF8_ESCAPE_CHAR ) < 0 ) { return uri ; } StringBuffer translatedUri = new StringBuffer ( uri . length ( ) ) ; byte [ ] encodedchars = new byte [ uri . length ( ) / 3 ] ; int i = 0 ; int length = uri . length ( ) ; int encodedcharsLength = 0 ; while ( i < length ) { if ( uri . charAt ( i ) == UTF8_ESCAPE_CHAR ) { while ( i < length && uri . charAt ( i ) == UTF8_ESCAPE_CHAR ) { if ( i + 2 < length ) { try { byte x = ( byte ) Integer . parseInt ( uri . substring ( i + 1 , i + 3 ) , 16 ) ; encodedchars [ encodedcharsLength ] = x ; } catch ( NumberFormatException e ) { } encodedcharsLength ++ ; i += 3 ; } else { } } try { String translatedPart = new String ( encodedchars , 0 , encodedcharsLength , UTF_8 ) ; translatedUri . append ( translatedPart ) ; } catch ( UnsupportedEncodingException e ) { throw new IllegalArgumentException ( "Problem in decodePath: UTF-8 encoding not supported." ) ; } encodedcharsLength = 0 ; } else { translatedUri . append ( uri . charAt ( i ) ) ; i ++ ; } } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "decoded uri " + translatedUri ) ; } return translatedUri . toString ( ) ; }
Decode a path .
37,581
private void dispatchOutsideContainer ( SipServletRequestImpl sipServletRequest ) throws DispatcherException { final Request request = ( Request ) sipServletRequest . getMessage ( ) ; if ( logger . isInfoEnabled ( ) ) { logger . info ( "Dispatching the request event outside the container" ) ; } if ( request . getRequestURI ( ) instanceof TelURL || ! ( request . getRequestURI ( ) instanceof javax . sip . address . SipURI ) ) { throw new DispatcherException ( Response . SERVER_INTERNAL_ERROR , "cannot dispatch a request with a tel url or generic request uri outside the container " ) ; } javax . sip . address . SipURI sipRequestUri = ( javax . sip . address . SipURI ) request . getRequestURI ( ) ; String host = sipRequestUri . getHost ( ) ; int port = sipRequestUri . getPort ( ) ; String transport = JainSipUtils . findTransport ( request ) ; boolean isAnotherDomain = sipApplicationDispatcher . isExternal ( host , port , transport ) ; ListIterator < String > routeHeaders = sipServletRequest . getHeaders ( RouteHeader . NAME ) ; if ( isAnotherDomain || routeHeaders . hasNext ( ) ) { try { forwardRequestStatefully ( sipServletRequest , SipSessionRoutingType . PREVIOUS_SESSION , SipRouteModifier . NO_ROUTE ) ; } catch ( Exception e ) { throw new DispatcherException ( Response . SERVER_INTERNAL_ERROR , "Unexpected Exception while trying to forward statefully the following initial request " + request , e ) ; } } else { throw new DispatcherException ( Response . NOT_FOUND , "the Request-URI does not point to another domain, and there is no Route header," + "the container should not send the request as it will cause a loop. " + "Instead, the container must reject the request with 404 Not Found final response with no Retry-After header. You may want to check your dar configuration file to see if the request can be handled or make sure you use the correct Application Router jar." ) ; } }
Dispatch a request outside the container
37,582
private final MobicentsSipApplicationSession retrieveTargetedApplication ( String targetedApplicationKey ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "retrieveTargetedApplication - targetedApplicationKey=" + targetedApplicationKey ) ; } if ( targetedApplicationKey != null && targetedApplicationKey . length ( ) > 0 ) { targetedApplicationKey = RFC2396UrlDecoder . decode ( targetedApplicationKey ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "retrieveTargetedApplication - decoded targetedApplicationKey=" + targetedApplicationKey ) ; } SipApplicationSessionKey targetedApplicationSessionKey ; try { targetedApplicationSessionKey = SessionManagerUtil . parseSipApplicationSessionKey ( targetedApplicationKey ) ; } catch ( ParseException e ) { logger . error ( "Couldn't parse the targeted application key " + targetedApplicationKey , e ) ; return null ; } SipContext sipContext = sipApplicationDispatcher . findSipApplication ( targetedApplicationSessionKey . getApplicationName ( ) ) ; if ( sipContext != null ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "retrieveTargetedApplication - sipContext not null" ) ; } return sipContext . getSipManager ( ) . getSipApplicationSession ( targetedApplicationSessionKey , false ) ; } } return null ; }
Section 15 . 11 . 3 Encode URI Mechanism The container MUST use the encoded URI to locate the targeted SipApplicationSession object . If a valid SipApplicationSession is found the container must determine the name of the application that owns the SipApplicationSession object .
37,583
private MobicentsSipSession retrieveSipSession ( Dialog dialog ) { if ( dialog != null ) { Iterator < SipContext > iterator = sipApplicationDispatcher . findSipApplications ( ) ; while ( iterator . hasNext ( ) ) { SipContext sipContext = iterator . next ( ) ; SipManager sipManager = sipContext . getSipManager ( ) ; Iterator < MobicentsSipSession > sipSessionsIt = sipManager . getAllSipSessions ( ) ; while ( sipSessionsIt . hasNext ( ) ) { MobicentsSipSession mobicentsSipSession = ( MobicentsSipSession ) sipSessionsIt . next ( ) ; MobicentsSipSessionKey sessionKey = mobicentsSipSession . getKey ( ) ; if ( sessionKey . getCallId ( ) . trim ( ) . equals ( dialog . getCallId ( ) . getCallId ( ) ) ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "found session with the same Call Id " + sessionKey + ", to Tag " + sessionKey . getToTag ( ) ) ; logger . debug ( "dialog localParty = " + dialog . getLocalParty ( ) . getURI ( ) + ", localTag " + dialog . getLocalTag ( ) ) ; logger . debug ( "dialog remoteParty = " + dialog . getRemoteParty ( ) . getURI ( ) + ", remoteTag " + dialog . getRemoteTag ( ) ) ; } if ( sessionKey . getFromTag ( ) . equals ( dialog . getLocalTag ( ) ) && sessionKey . getToTag ( ) . equals ( dialog . getRemoteTag ( ) ) ) { if ( mobicentsSipSession . getProxy ( ) == null ) { return mobicentsSipSession ; } } else if ( sessionKey . getFromTag ( ) . equals ( dialog . getRemoteTag ( ) ) && sessionKey . getToTag ( ) . equals ( dialog . getLocalTag ( ) ) ) { if ( mobicentsSipSession . getProxy ( ) == null ) { return mobicentsSipSession ; } } } } } } return null ; }
Try to find a matching Sip Session to a given dialog
37,584
public String getBasePath ( ) { String docBase = null ; Container container = this ; while ( container != null ) { if ( container instanceof Host ) break ; container = container . getParent ( ) ; } File file = new File ( getDocBase ( ) ) ; if ( ! file . isAbsolute ( ) ) { if ( container == null ) { docBase = ( new File ( engineBase ( ) , getDocBase ( ) ) ) . getPath ( ) ; } else { String appBase = ( ( Host ) container ) . getAppBase ( ) ; file = new File ( appBase ) ; if ( ! file . isAbsolute ( ) ) file = new File ( engineBase ( ) , appBase ) ; docBase = ( new File ( file , getDocBase ( ) ) ) . getPath ( ) ; } } else { docBase = file . getPath ( ) ; } return docBase ; }
Get base path . Copy pasted from StandardContext Tomcat class
37,585
private String getNamingContextName ( ) { if ( namingContextName == null ) { Container parent = getParent ( ) ; if ( parent == null ) { namingContextName = getName ( ) ; } else { Stack < String > stk = new Stack < String > ( ) ; StringBuffer buff = new StringBuffer ( ) ; while ( parent != null ) { stk . push ( parent . getName ( ) ) ; parent = parent . getParent ( ) ; } while ( ! stk . empty ( ) ) { buff . append ( "/" + stk . pop ( ) ) ; } buff . append ( getName ( ) ) ; namingContextName = buff . toString ( ) ; } } return namingContextName ; }
Get naming context full name .
37,586
public JSONObject jsonify ( ) { JSONObject ret = new JSONObject ( ) ; if ( null != this . _attributesString ) { for ( Map . Entry < ApplicationProperty , CharSequence > entry : this . _attributesString . entrySet ( ) ) { ret . put ( entry . getKey ( ) . propertyName ( ) , entry . getValue ( ) . toString ( ) ) ; } } if ( null != this . _attributesBool ) { for ( Map . Entry < ApplicationProperty , Boolean > entry : this . _attributesBool . entrySet ( ) ) { ret . put ( entry . getKey ( ) . propertyName ( ) , entry . getValue ( ) ) ; } } return ret ; }
Return a JSON representation of this property set object
37,587
public MobicentsSipSession removeSipSession ( final MobicentsSipSessionKey key ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Removing a sip session with the key : " + key ) ; } return sipSessions . remove ( key ) ; }
Removes a sip session from the manager by its key
37,588
public MobicentsSipApplicationSession removeSipApplicationSession ( final MobicentsSipApplicationSessionKey key ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Removing a sip application session with the key : " + key ) ; } MobicentsSipApplicationSession sipApplicationSession = sipApplicationSessions . remove ( key ) ; if ( sipApplicationSession != null ) { final String appGeneratedKey = sipApplicationSession . getKey ( ) . getAppGeneratedKey ( ) ; if ( appGeneratedKey != null ) { sipApplicationSessionsByAppGeneratedKey . remove ( appGeneratedKey ) ; } } return sipApplicationSession ; }
Removes a sip application session from the manager by its key
37,589
public MobicentsSipApplicationSession getSipApplicationSession ( final SipApplicationSessionKey key , final boolean create ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "getSipApplicationSession with key=" + key ) ; } MobicentsSipApplicationSession sipApplicationSessionImpl = null ; final String appGeneratedKey = key . getAppGeneratedKey ( ) ; if ( appGeneratedKey != null ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "trying to find sip application session with generated key " + appGeneratedKey ) ; } sipApplicationSessionImpl = sipApplicationSessionsByAppGeneratedKey . get ( appGeneratedKey ) ; } if ( sipApplicationSessionImpl == null ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "getSipApplicationSession - trying to find sip application session with key " + key ) ; logger . debug ( "getSipApplicationSession - sip application session keyset: " ) ; for ( SipApplicationSessionKey tmp : sipApplicationSessions . keySet ( ) ) { logger . debug ( "getSipApplicationSession - element=" + tmp ) ; } } sipApplicationSessionImpl = sipApplicationSessions . get ( key ) ; } if ( sipApplicationSessionImpl == null && create ) { sipApplicationSessionImpl = createSipApplicationSession ( key ) ; } return sipApplicationSessionImpl ; }
Retrieve a sip application session from its key . If none exists one can enforce the creation through the create parameter to true .
37,590
public MobicentsSipSession getSipSession ( final SipSessionKey key , final boolean create , final SipFactoryImpl sipFactoryImpl , final MobicentsSipApplicationSession sipApplicationSessionImpl ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "getSipSession - key=" + key + ", create=" + create + ", sipApplicationSessionImpl=" + sipApplicationSessionImpl ) ; if ( sipApplicationSessionImpl != null ) { logger . debug ( "getSipSession - sipApplicationSessionImpl.getId()=" + sipApplicationSessionImpl . getId ( ) ) ; } } if ( create && sipFactoryImpl == null ) { throw new IllegalArgumentException ( "the sip factory should not be null" ) ; } MobicentsSipSession sipSessionImpl = sipSessions . get ( key ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "getSipSession - existing sip session keys:" ) ; if ( sipSessions != null ) { for ( SipSessionKey tmp : sipSessions . keySet ( ) ) { logger . debug ( "getSipSession - key.getApplicationSessionId()=" + tmp . getApplicationSessionId ( ) + ", key.getApplicationName()=" + key . getApplicationName ( ) + ", key.getCallId()=" + key . getCallId ( ) + ", key.getFromTag()=" + key . getFromTag ( ) + ", key.getToTag()=" + key . getToTag ( ) ) ; } } logger . debug ( "getSipSession - existing sipSessionImpl=" + sipSessionImpl ) ; } if ( sipSessionImpl == null && create ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "getSipSession - creating new sip session" ) ; } sipSessionImpl = createSipSession ( key , create , sipFactoryImpl , sipApplicationSessionImpl ) ; } if ( sipSessionImpl != null ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "getSipSession - calling setToTag" ) ; } return setToTag ( key , sipSessionImpl ) ; } return sipSessionImpl ; }
Retrieve a sip session from its key . If none exists one can enforce the creation through the create parameter to true . the sip factory cannot be null if create is set to true .
37,591
public MobicentsSipApplicationSession findSipApplicationSession ( HttpSession httpSession ) { for ( MobicentsSipApplicationSession sipApplicationSessionImpl : sipApplicationSessions . values ( ) ) { if ( sipApplicationSessionImpl . findHttpSession ( httpSession . getId ( ) ) != null ) { return sipApplicationSessionImpl ; } } return null ; }
Retrieves the sip application session holding the converged http session in parameter
37,592
public void removeAllSessions ( ) { List < SipSessionKey > sipSessionsToRemove = new ArrayList < SipSessionKey > ( ) ; for ( SipSessionKey sipSessionKey : sipSessions . keySet ( ) ) { sipSessionsToRemove . add ( sipSessionKey ) ; } for ( SipSessionKey sipSessionKey : sipSessionsToRemove ) { removeSipSession ( sipSessionKey ) ; } List < SipApplicationSessionKey > sipApplicationSessionsToRemove = new ArrayList < SipApplicationSessionKey > ( ) ; for ( SipApplicationSessionKey sipApplicationSessionKey : sipApplicationSessions . keySet ( ) ) { sipApplicationSessionsToRemove . add ( sipApplicationSessionKey ) ; } for ( SipApplicationSessionKey sipApplicationSessionKey : sipApplicationSessionsToRemove ) { removeSipApplicationSession ( sipApplicationSessionKey ) ; } }
Remove the sip sessions and sip application sessions
37,593
public MobicentsSipApplicationSession createApplicationSession ( SipContext sipContext ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Creating new application session for sip context " + sipContext . getApplicationName ( ) ) ; } SipApplicationSessionKey sipApplicationSessionKey = SessionManagerUtil . getSipApplicationSessionKey ( sipContext . getApplicationName ( ) , null , null ) ; MobicentsSipApplicationSession sipApplicationSession = sipContext . getSipManager ( ) . getSipApplicationSession ( sipApplicationSessionKey , true ) ; if ( StaticServiceHolder . sipStandardService . isHttpFollowsSip ( ) ) { String jvmRoute = StaticServiceHolder . sipStandardService . getJvmRoute ( ) ; if ( jvmRoute != null ) { sipApplicationSession . setJvmRoute ( jvmRoute ) ; } } return sipApplicationSession . getFacade ( ) ; }
Creates an application session associated with the context
37,594
private static void validateCreation ( String method , SipApplicationSession app ) { if ( method . equals ( Request . ACK ) ) { throw new IllegalArgumentException ( "Wrong method to create request with[" + Request . ACK + "]!" ) ; } if ( method . equals ( Request . PRACK ) ) { throw new IllegalArgumentException ( "Wrong method to create request with[" + Request . PRACK + "]!" ) ; } if ( method . equals ( Request . CANCEL ) ) { throw new IllegalArgumentException ( "Wrong method to create request with[" + Request . CANCEL + "]!" ) ; } if ( ! ( ( MobicentsSipApplicationSession ) app ) . isValidInternal ( ) ) { throw new IllegalArgumentException ( "Cant associate request with invalidaded sip session application!" ) ; } }
Does basic check for illegal methods wrong state if it finds it throws exception
37,595
public void init ( ) { defaultApplicationRouterParser . init ( ) ; try { defaultSipApplicationRouterInfos = defaultApplicationRouterParser . parse ( ) ; } catch ( ParseException e ) { log . fatal ( "Impossible to parse the default application router configuration file" , e ) ; throw new IllegalArgumentException ( "Impossible to parse the default application router configuration file" , e ) ; } }
load the configuration file as defined in appendix C of JSR289
37,596
public static void pushRunAsIdentity ( final RunAsIdentity principal ) { AccessController . doPrivileged ( new PrivilegedAction < Void > ( ) { public Void run ( ) { SecurityContext sc = getSecurityContext ( ) ; if ( sc == null ) throw MESSAGES . noSecurityContext ( ) ; sc . setOutgoingRunAs ( principal ) ; return null ; } } ) ; }
Sets the run as identity
37,597
public static RunAs popRunAsIdentity ( ) { return AccessController . doPrivileged ( new PrivilegedAction < RunAs > ( ) { public RunAs run ( ) { SecurityContext sc = getSecurityContext ( ) ; if ( sc == null ) throw MESSAGES . noSecurityContext ( ) ; RunAs principal = sc . getOutgoingRunAs ( ) ; sc . setOutgoingRunAs ( null ) ; return principal ; } } ) ; }
Removes the run as identity
37,598
public static String hashString ( String input , int length ) { MessageDigest md ; try { md = MessageDigest . getInstance ( "SHA" ) ; } catch ( NoSuchAlgorithmException e ) { throw new IllegalArgumentException ( "The SHA Algorithm could not be found" , e ) ; } byte [ ] bytes = input . getBytes ( ) ; md . update ( bytes ) ; String hashed = convertToHex ( md . digest ( ) ) ; hashed = reduceHash ( hashed , length ) ; return hashed ; }
Compute hash value of a string
37,599
public void deploy ( final DeploymentPhaseContext phaseContext ) throws DeploymentUnitProcessingException { final DeploymentUnit deploymentUnit = phaseContext . getDeploymentUnit ( ) ; SipAnnotationMetaData sipAnnotationsMetaData = deploymentUnit . getAttachment ( SipAnnotationMetaData . ATTACHMENT_KEY ) ; if ( sipAnnotationsMetaData == null ) { sipAnnotationsMetaData = new SipAnnotationMetaData ( ) ; deploymentUnit . putAttachment ( SipAnnotationMetaData . ATTACHMENT_KEY , sipAnnotationsMetaData ) ; } Map < ResourceRoot , Index > indexes = AnnotationIndexUtils . getAnnotationIndexes ( deploymentUnit ) ; for ( final Entry < ResourceRoot , Index > entry : indexes . entrySet ( ) ) { if ( logger . isDebugEnabled ( ) ) logger . debug ( "doDeploy(): processing annotations from " + entry . getKey ( ) . getRootName ( ) ) ; final Index jarIndex = entry . getValue ( ) ; SipMetaData sipMetaData = processAnnotations ( sipAnnotationsMetaData , jarIndex ) ; if ( sipMetaData != null ) { sipAnnotationsMetaData . put ( entry . getKey ( ) . getRootName ( ) , sipMetaData ) ; } } }
Process web annotations .