https://code.google.com/p/sipservlets/issues/detail?id=238
345575
public void removeTransaction(String branch) {
		synchronized(this.ongoingTransactions) {
			TransactionRequest remove = null;
			for(TransactionRequest tr : this.ongoingTransactions) {
				if(tr.branchId.equals(branch)) {
					remove = tr;
					break;
				}
			}
			if(remove != null) {
				boolean removed = this.ongoingTransactions.remove(remove);
				if(logger.isDebugEnabled()) {
					logger.debug("Removed transaction " + branch + " from proxy branch ? " + removed);
				}
			} else {
				if(logger.isDebugEnabled()) {
					logger.debug("Removing transaction " + branch + " from proxy branch FAILED. Not found.");
				}
			}
		}
	}
1040262
protected void doProvisionalResponse(javax.servlet.sip.SipServletResponse resp) throws javax.servlet.ServletException, java.io.IOException{
       
    }
1316944
@Override
    public void doGet(HttpServletRequest request,
            HttpServletResponse response)
            throws IOException, ServletException {

        super.doGet(request, response);

        //jsonp is specified when response is expected to go to javascript function.
        String jsonp = request.getParameter(HTTPClientInterface.JSONP);
        AuthenticationResult authResult = null;
        String target = request.getPathInfo();
        try {
            response.setContentType(JSON_CONTENT_TYPE);
            if (!HTTPClientInterface.validateJSONP(jsonp, (Request )request, response)) {
                return;
            }
            response.setStatus(HttpServletResponse.SC_OK);

            //Requests require authentication.
            authResult = authenticate(request);
            if (!authResult.isAuthenticated()) {
                response.getWriter().print(buildClientResponse(jsonp, ClientResponse.UNEXPECTED_FAILURE, authResult.m_message));
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return;
            }
            //Authenticated but has no permissions.
            if (!authResult.m_authUser.hasPermission(Permission.ADMIN)) {
                response.getWriter().print(buildClientResponse(jsonp, ClientResponse.UNEXPECTED_FAILURE, "Permission denied"));
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return;
            }

            if (target != null && !target.endsWith("/")) { // the URI may or may not end with /
                target += "/";
            }
            if (target == null) {
                target = "/"; //Default.
            }
            //Authenticated and has ADMIN permission
            if (target.equals("/download/")) {
                //Deployment xml is text/xml
                response.setContentType("text/xml;charset=utf-8");
                DeploymentType dt = CatalogUtil.shallowClusterAndPathsClone(this.getDeployment());
                // reflect the actual number of cluster members
                dt.getCluster().setHostcount(getCatalogContext().getClusterSettings().hostcount());

                response.getWriter().write(CatalogUtil.getDeployment(dt, true));
            } else if (target.startsWith("/users/")) { // username may be passed in after the / (not as a param)
                if (request.getMethod().equalsIgnoreCase("POST")) {
                    handleUpdateUser(jsonp, target, request, response, authResult);
                } else if (request.getMethod().equalsIgnoreCase("PUT")) {
                    handleCreateUser(jsonp, target, request, response, authResult);
                } else if (request.getMethod().equalsIgnoreCase("DELETE")) {
                    handleRemoveUser(jsonp, target, request, response, authResult);
                } else {
                    handleGetUsers(jsonp, target, request, response);
                }
            } else if (target.equals("/export/types/")) {
                handleGetExportTypes(jsonp, response);
            } else if (target.equals("/")) { // just deployment
                if (request.getMethod().equalsIgnoreCase("POST")) {
                    handleUpdateDeployment(jsonp, request, response, authResult);
                } else {
                    //non POST
                    response.setCharacterEncoding("UTF-8");
                    if (jsonp != null) {
                        response.getWriter().write(jsonp + "(");
                    }
                    DeploymentType dt = getDeployment();
                    // reflect the actual number of cluster members
                    dt.getCluster().setHostcount(getCatalogContext().getClusterSettings().hostcount());

                    m_mapper.writeValue(response.getWriter(), dt);
                    if (jsonp != null) {
                        response.getWriter().write(")");
                    }
                }
            } else {
                response.getWriter().print(buildClientResponse(jsonp, ClientResponse.UNEXPECTED_FAILURE, "Resource not found"));
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            }
        } catch (Exception ex) {
            m_log.info("Not servicing url: " + target + " Details: " + ex.getMessage(), ex);
        }
    }
256813
@Override
	public Request createRequest(Request origRequest) throws SipException {
		Request request = super.createRequest(origRequest);
        if (wrappedDialog == null) {
			// hack uri and address headers
			final SIPRequest sipRequest = (SIPRequest) request;
			final SleeSipProviderImpl provider = ra.getProviderWrapper();
			final HeaderFactory headerFactory = provider.getHeaderFactory();
			try {
				// hack request with local addresses
				final URI requestURI = (URI) toAddress.getURI().clone();
				if(requestURI.isSipURI()) {
					((SipUri)requestURI).clearUriParms();					
				}
				sipRequest.setRequestURI(requestURI);
				final FromHeader fromHeader = headerFactory.createFromHeader(
						fromAddress, getLocalTag());
				sipRequest.setFrom(fromHeader);
				final ToHeader toHeader = headerFactory.createToHeader(
						toAddress, null);
				sipRequest.setTo(toHeader);
			} catch (Exception e) {
				throw new SipException(e.getMessage(), e);
			}
		}
		return request;
	}
452546
public SipStack initializeSipStack(String transport, String myPort, Properties myProperties) throws Exception {

		/*
		 * http://code.google.com/p/mobicents/issues/detail?id=3121
		 * Reset sipStack when calling initializeSipStack method
		 */
		tearDown();
		
		try
		{
			sipStack = new SipStack(transport, Integer.valueOf(myPort), myProperties);
			logger.info("SipStack - "+sipStackName+" - created!");
		}
		catch (Exception ex)
		{
			logger.info("Exception: " + ex.getClass().getName() + ": "
					+ ex.getMessage());
			throw ex;
		}
		
		initialized = true;
		return sipStack;
	}
140380
private static void parseServlets(final ServletType servletType, final WebApp webApp) {
		final WebAppServlet servlet = new WebAppServlet();
		servlet.setServletName(servletType.getServletName().getValue());
		if (servletType.getServletClass() != null) {
			servlet.setServletClassName(servletType.getServletClass().getValue());
			webApp.addServlet(servlet);
		} else {
			String jspFile = servletType.getJspFile().getValue();
			if (jspFile != null) {
				WebAppJspServlet jspServlet = new WebAppJspServlet();
				jspServlet.setServletName(servletType.getServletName().getValue());
				jspServlet.setJspPath(jspFile);
				webApp.addServlet(jspServlet);
			}
		}
		servlet.setLoadOnStartup(servletType.getLoadOnStartup());
		if (servletType.getAsyncSupported() != null) {
			servlet.setAsyncSupported(servletType.getAsyncSupported().isValue());
		}

		MultipartConfigType multipartConfig = servletType.getMultipartConfig();
		if (multipartConfig != null) {
			String location;
			if (multipartConfig.getLocation() == null) {
				location = null;
			} else {
				location = multipartConfig.getLocation().getValue();
			}
			long maxFileSize;
			if (multipartConfig.getMaxFileSize() == null) {
				maxFileSize = -1L;
			} else {
				maxFileSize = multipartConfig.getMaxFileSize();
			}
			long maxRequestSize;
			if (multipartConfig.getMaxRequestSize() == null) {
				maxRequestSize = -1L;
			} else {
				maxRequestSize = multipartConfig.getMaxRequestSize();
			}
			int fileSizeThreshold;
			if (multipartConfig.getFileSizeThreshold() == null) {
				fileSizeThreshold = 0;
			} else {
				fileSizeThreshold = multipartConfig.getFileSizeThreshold().intValue();
			}
			MultipartConfigElement multipartConfigElement = new MultipartConfigElement(location, maxFileSize, maxRequestSize,
					fileSizeThreshold);
			servlet.setMultipartConfig(multipartConfigElement);
		}

		List<ParamValueType> servletInitParams = servletType.getInitParam();
		for (ParamValueType initParamElement : servletInitParams) {
			final WebAppInitParam initParam = new WebAppInitParam();
			initParam.setParamName(initParamElement.getParamName().getValue());
			initParam.setParamValue(initParamElement.getParamValue().getValue());
			servlet.addInitParam(initParam);
		}

	}
1299099
public void doTag()
            throws JspException
    {
        // report error if there are any
        if (hasErrors()) {
            reportErrors();
            return;
        }

        PageContext pageContext = getPageContext();
        ServletContainerAdapter sa = AdapterManager.getServletContainerAdapter(pageContext.getServletContext());
        ServletRequest request = pageContext.getRequest();
        assert(sa != null);

        // check to see if we are supposed to report the error
        boolean prodMode = sa.isInProductionMode();
        if (prodMode && !_alwaysReport)
            return;

        LinkedHashMap map = (LinkedHashMap)
                InternalUtils.getBindingUpdateErrors(request);

        if (map == null)
            return;

        if (_expression != null) {
            String expr = "{" + _expression + "}";
            BindingUpdateError err = (BindingUpdateError) map.get(expr);
            if (err != null) {
                Throwable cause = err.getCause();
                String msg = (cause != null) ? cause.getMessage() : err.getMessage();
                String s = Bundle.getString("Tags_BindingUpdateError", new Object[]{_expression, msg});
                registerTagError(s, null);
                reportErrors();
            }
            return;
        }

        Iterator it = map.values().iterator();
        while (it.hasNext()) {
            BindingUpdateError err = (BindingUpdateError) it.next();
            Throwable cause = err.getCause();
            String msg = (cause != null) ? cause.getMessage() : err.getMessage();
            String s = Bundle.getString("Tags_BindingUpdateError", new Object[]{err.getExpression(), msg});
            registerTagError(s, null);
        }
        reportErrors();
    }
1081374
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);
    }
638983
public void doGet(HttpServletRequest sreq, HttpServletResponse sres) 
        throws ServletException, IOException
    {
        String path = (String)
            sreq.getAttribute("javax.servlet.include.servlet_path");
        if (path==null)
            path=sreq.getServletPath();
        if (path.length()==0)
        {
            path=(String)sreq.getAttribute("javax.servlet.include.path_info");
            if (path==null)
                path=sreq.getPathInfo();
        }

        String forward=(String)_forwardMap.get(path);
        if(log.isDebugEnabled())log.debug("Forward "+path+" to "+forward);
        if (forward!=null)
        {            
            ServletContext context =
                getServletContext().getContext(forward);
            String contextPath=sreq.getContextPath();
            if (contextPath.length()>1)
                forward=forward.substring(contextPath.length());
            
            RequestDispatcher dispatch =
                context.getRequestDispatcher(forward);
            if (dispatch!=null)
            {
                dispatch.forward(sreq,sres);
                return;
            }
        }

        sres.sendError(404);
    }
921478
@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
		final String sourceMethod = "doGet"; //$NON-NLS-1$
		boolean isTraceLogging = log.isLoggable(Level.FINER);
		if (isTraceLogging) {
			log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[]{req, resp});
			log.finer("Request URL=" + req.getRequestURI()); //$NON-NLS-1$
		}

		if (isShuttingDown) {
			// Server has been shut-down, or is in the process of shutting down.
			resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
			if (isTraceLogging) {
				log.finer("Processing request after server shutdown.  Returning SC_SERVICE_UNAVAILABLE"); //$NON-NLS-1$
				log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
			}
			return;
		}
		req.setAttribute(AGGREGATOR_REQATTRNAME, this);
		resp.addHeader("Server", "JavaScript Aggregator"); //$NON-NLS-1$ //$NON-NLS-2$

		// Check for forced error response in development mode
		if (forcedErrorResponse != null && getOptions().isDevelopmentMode()) {
			int status = forcedErrorResponse.getStatus();
			if (status > 0) {
				// return a forced error status
				resp.setStatus(status);
				URI uri = forcedErrorResponse.getResponseBody();
				if (uri != null) {
					resp.setContentType(getContentType(uri.getPath()));
					try {
						CopyUtil.copy(newResource(uri).getInputStream(), resp.getOutputStream());
					} catch (IOException e) {
						throw new ServletException(e);
					}
				}
				log.logp(Level.WARNING, AbstractAggregatorImpl.class.getName(), sourceMethod, "Returning forced error status " + status); //$NON-NLS-1$
				return;
			} else if (status < 0) {
				// Forced error response is spent.  Remove it.
				forcedErrorResponse = null;
			}
		}

		String pathInfo = req.getPathInfo();
		if (pathInfo == null  || (ILayer.SOURCEMAP_RESOURCE_PATH).equals(pathInfo)) {
			currentRequest.set(req);
			try {
				processAggregatorRequest(req, resp);
			} finally {
				currentRequest.set(null);
			}
		} else {
			boolean processed = false;
			// search resource paths to see if we should treat as aggregator request or resource request
			for (Map.Entry<String, URI> entry : resourcePaths.entrySet()) {
				String path = entry.getKey();
				if (entry.getValue() == null) {
					if (path.equals(pathInfo) || (path + ILayer.SOURCEMAP_RESOURCE_PATH).equals(pathInfo)) {
						processAggregatorRequest(req, resp);
						processed = true;
						break;
					} else if (pathInfo.startsWith(path) && pathInfo.charAt(path.length()) == '/') {
						// Request for a resource in this bundle
						String resPath = pathInfo.substring(path.length()+1);
						processResourceRequest(req, resp, webContentUri, resPath);
						processed = true;
						break;
					}
				}
				if (pathInfo.startsWith(path)) {
					if ((path.length() == pathInfo.length() || pathInfo.charAt(path.length()) == '/') && entry.getValue() != null) {
						String resPath = path.length() == pathInfo.length() ? "" : pathInfo.substring(path.length()+1); //$NON-NLS-1$
						URI res = entry.getValue();
						processResourceRequest(req, resp, res, resPath);
						processed = true;
						break;
					}
				}
			}
			if (!processed) {
				// No mapping found.  Try to locate the resource in this bundle.
				String resPath = pathInfo.substring(1);
				processResourceRequest(req, resp, webContentUri, resPath);
			}
		}
		if (isTraceLogging) {
			log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
		}
	}
1357590
function SipConnection(connection, connectCallback) {
    function isData(session) {
        return !session.audio && !session.video && !session.screen && session.data;
    }

    connection.socket = {
        send: function(data) {
            var remoteSipURI = data.remoteUserId + '@yourServer.com';
            sip.publish(remoteSipURI, data); // maybe JSON.stringify(data)
        }
    };

    // connect/subscribe to SIP here

    // ref: http://sipjs.com/demo-phone/
    // and: http://sipjs.com/demo-phone/js/ua.js
    var config = {
        userAgentString: 'SIP.js/0.7.0 BB',
        traceSip: true,
        register: false,
        displayName: '',
        uri: '', // connection.userid + '@yourServer.com'
        authorizationUser: '',
        password: '',
        wsServers: 'wss://edge.sip.onsip.com'
    };

    var sip = new SIP.UA(config);

    sip.on('invite', function(session) {
        // do the stuff!
    });

    sip.on('message', function(data) {
        data = JSON.parse(data);

        if (data.eventName === connection.socketMessageEvent) {
            onMessagesCallback(data.data);
        }

        if (data.eventName === 'presence') {
            data = data.data;
            if (data.userid === connection.userid) return;
            connection.onUserStatusChanged({
                userid: data.userid,
                status: data.isOnline === true ? 'online' : 'offline',
                extra: connection.peers[data.userid] ? connection.peers[data.userid].extra : {}
            });
        }
    });

    // connected or registered
    sip.on('connected', function() {
        if (connection.enableLogs) {
            console.info('SIP connection is opened.');
        }

        connection.socket.emit('presence', {
            userid: connection.userid,
            isOnline: true
        });

        if (connectCallback) connectCallback(connection.socket);
    });

    sip.on('unregistered', function() {
        if (!connection.enableLogs) return;
        console.warn('Socket connection is closed.');
    });

    connection.socket.emit = function(eventName, data, callback) {
        if (eventName === 'changed-uuid') return;
        if (data.message && data.message.shiftedModerationControl) return;

        connection.socket.send({
            eventName: eventName,
            data: data
        });

        if (callback) {
            callback(true);
        }
    };

    var mPeer = connection.multiPeersHandler;

    function onMessagesCallback(message) {
        if (message.remoteUserId != connection.userid) return;

        if (connection.peers[message.sender] && connection.peers[message.sender].extra != message.message.extra) {
            connection.peers[message.sender].extra = message.message.extra;
            connection.onExtraDataUpdated({
                userid: message.sender,
                extra: message.message.extra
            });
        }

        if (message.message.streamSyncNeeded && connection.peers[message.sender]) {
            var stream = connection.streamEvents[message.message.streamid];
            if (!stream || !stream.stream) {
                return;
            }

            var action = message.message.action;

            if (action === 'ended' || action === 'stream-removed') {
                connection.onstreamended(stream);
                return;
            }

            var type = message.message.type != 'both' ? message.message.type : null;
            stream.stream[action](type);
            return;
        }

        if (message.message === 'connectWithAllParticipants') {
            if (connection.broadcasters.indexOf(message.sender) === -1) {
                connection.broadcasters.push(message.sender);
            }

            mPeer.onNegotiationNeeded({
                allParticipants: connection.getAllParticipants(message.sender)
            }, message.sender);
            return;
        }

        if (message.message === 'removeFromBroadcastersList') {
            if (connection.broadcasters.indexOf(message.sender) !== -1) {
                delete connection.broadcasters[connection.broadcasters.indexOf(message.sender)];
                connection.broadcasters = removeNullEntries(connection.broadcasters);
            }
            return;
        }

        if (message.message === 'dropPeerConnection') {
            connection.deletePeer(message.sender);
            return;
        }

        if (message.message.allParticipants) {
            if (message.message.allParticipants.indexOf(message.sender) === -1) {
                message.message.allParticipants.push(message.sender);
            }

            message.message.allParticipants.forEach(function(participant) {
                mPeer[!connection.peers[participant] ? 'createNewPeer' : 'renegotiatePeer'](participant, {
                    localPeerSdpConstraints: {
                        OfferToReceiveAudio: connection.sdpConstraints.mandatory.OfferToReceiveAudio,
                        OfferToReceiveVideo: connection.sdpConstraints.mandatory.OfferToReceiveVideo
                    },
                    remotePeerSdpConstraints: {
                        OfferToReceiveAudio: connection.session.oneway ? !!connection.session.audio : connection.sdpConstraints.mandatory.OfferToReceiveAudio,
                        OfferToReceiveVideo: connection.session.oneway ? !!connection.session.video || !!connection.session.screen : connection.sdpConstraints.mandatory.OfferToReceiveVideo
                    },
                    isOneWay: !!connection.session.oneway || connection.direction === 'one-way',
                    isDataOnly: isData(connection.session)
                });
            });
            return;
        }

        if (message.message.newParticipant) {
            if (message.message.newParticipant == connection.userid) return;
            if (!!connection.peers[message.message.newParticipant]) return;

            mPeer.createNewPeer(message.message.newParticipant, message.message.userPreferences || {
                localPeerSdpConstraints: {
                    OfferToReceiveAudio: connection.sdpConstraints.mandatory.OfferToReceiveAudio,
                    OfferToReceiveVideo: connection.sdpConstraints.mandatory.OfferToReceiveVideo
                },
                remotePeerSdpConstraints: {
                    OfferToReceiveAudio: connection.session.oneway ? !!connection.session.audio : connection.sdpConstraints.mandatory.OfferToReceiveAudio,
                    OfferToReceiveVideo: connection.session.oneway ? !!connection.session.video || !!connection.session.screen : connection.sdpConstraints.mandatory.OfferToReceiveVideo
                },
                isOneWay: !!connection.session.oneway || connection.direction === 'one-way',
                isDataOnly: isData(connection.session)
            });
            return;
        }

        if (message.message.readyForOffer || message.message.addMeAsBroadcaster) {
            connection.addNewBroadcaster(message.sender);
        }

        if (message.message.newParticipationRequest && message.sender !== connection.userid) {
            if (connection.peers[message.sender]) {
                connection.deletePeer(message.sender);
            }

            var userPreferences = {
                extra: message.message.extra || {},
                localPeerSdpConstraints: message.message.remotePeerSdpConstraints || {
                    OfferToReceiveAudio: connection.sdpConstraints.mandatory.OfferToReceiveAudio,
                    OfferToReceiveVideo: connection.sdpConstraints.mandatory.OfferToReceiveVideo
                },
                remotePeerSdpConstraints: message.message.localPeerSdpConstraints || {
                    OfferToReceiveAudio: connection.session.oneway ? !!connection.session.audio : connection.sdpConstraints.mandatory.OfferToReceiveAudio,
                    OfferToReceiveVideo: connection.session.oneway ? !!connection.session.video || !!connection.session.screen : connection.sdpConstraints.mandatory.OfferToReceiveVideo
                },
                isOneWay: typeof message.message.isOneWay !== 'undefined' ? message.message.isOneWay : !!connection.session.oneway || connection.direction === 'one-way',
                isDataOnly: typeof message.message.isDataOnly !== 'undefined' ? message.message.isDataOnly : isData(connection.session),
                dontGetRemoteStream: typeof message.message.isOneWay !== 'undefined' ? message.message.isOneWay : !!connection.session.oneway || connection.direction === 'one-way',
                dontAttachLocalStream: !!message.message.dontGetRemoteStream,
                connectionDescription: message,
                successCallback: function() {
                    // if its oneway----- todo: THIS SEEMS NOT IMPORTANT.
                    if (typeof message.message.isOneWay !== 'undefined' ? message.message.isOneWay : !!connection.session.oneway || connection.direction === 'one-way') {
                        connection.addNewBroadcaster(message.sender, userPreferences);
                    }

                    if (!!connection.session.oneway || connection.direction === 'one-way' || isData(connection.session)) {
                        connection.addNewBroadcaster(message.sender, userPreferences);
                    }
                }
            };

            connection.onNewParticipant(message.sender, userPreferences);
            return;
        }

        if (message.message.shiftedModerationControl) {
            connection.onShiftedModerationControl(message.sender, message.message.broadcasters);
            return;
        }

        if (message.message.changedUUID) {
            if (connection.peers[message.message.oldUUID]) {
                connection.peers[message.message.newUUID] = connection.peers[message.message.oldUUID];
                delete connection.peers[message.message.oldUUID];
            }
        }

        if (message.message.userLeft) {
            mPeer.onUserLeft(message.sender);

            if (!!message.message.autoCloseEntireSession) {
                connection.leave();
            }

            return;
        }

        mPeer.addNegotiatedMessage(message.message, message.sender);
    }

    window.addEventListener('beforeunload', function() {
        connection.socket.emit('presence', {
            userid: connection.userid,
            isOnline: false
        });
    }, false);
}
1045540
public SipServletRequest createRequest(SipServletRequest origRequest) {
        final SipServletRequestImpl newSipServletRequest = (SipServletRequestImpl) sipFactoryImpl.createRequest(origRequest, false);
        final SipServletRequestImpl origRequestImpl = (SipServletRequestImpl) origRequest;

        final MobicentsSipSession originalSession = origRequestImpl.getSipSession();
        final MobicentsSipSession session = newSipServletRequest.getSipSession();
        // B2buaHelperTest.testLinkSipSessions101 assumes the sessions shouldn't be linked together
//		sessionMap.put(originalSession.getKey(), session.getKey());
//		sessionMap.put(session.getKey(), originalSession.getKey());
//		dumpLinkedSessions();

//		linkedRequestMap.put(newSipServletRequest, origRequestImpl);
//		linkedRequestMap.put(origRequestImpl, newSipServletRequest);
        session.setB2buaHelper(this);
        originalSession.setB2buaHelper(this);
        setOriginalRequest(session, newSipServletRequest);
        dumpAppSession(session);
        return newSipServletRequest;
    }
84282
public SipServletRequest createRequest(SipApplicationSession sipAppSession,
			String method, URI from, URI to, String handler) {
		if (logger.isDebugEnabled()) {
			logger
					.debug("Creating new SipServletRequest for SipApplicationSession["
							+ sipAppSession
							+ "] METHOD["
							+ method
							+ "] FROM_URI[" + from + "] TO_URI[" + to + "]");
		}

		validateCreation(method, sipAppSession);

		//javadoc specifies that a copy of the uri should be done hence the clone
		Address toA = this.createAddress(to.clone());
		Address fromA = this.createAddress(from.clone());

		try {
			return createSipServletRequest(sipAppSession, method, fromA, toA, handler, null, null);
		} catch (ServletParseException e) {
			logger.error("Error creating sipServletRequest", e);
			return null;
		}

	}
1177417
public void requestSmsVerificationCode(boolean androidSmsRetrieverSupported, Optional<String> captchaToken) throws IOException {
    this.pushServiceSocket.requestSmsVerificationCode(androidSmsRetrieverSupported, captchaToken);
  }
115144
public void patchSipMessageForNAT(javax.sip.message.Message sipMessage, boolean isIpv6) {
        //Need to patch the response so the subsequent requests are directly correctly at the public IP Address of the LB
        // Useful for NAT environment such as Amazon EC2
    	String currentPublicIp = null;
    	if(!isIpv6)
    		currentPublicIp = balancerRunner.balancerContext.publicIP;
    	else
    		currentPublicIp = balancerRunner.balancerContext.publicIPv6;
        if (currentPublicIp != null && !currentPublicIp.isEmpty()) {
        	int [] ports = new int[5];
//        	int udpPort = 0;
//    		int tcpPort = 0;
//    		int tlsPort = 0;
//    		int wsPort = 0;
//    		int wssPort = 0;
        	if(!isIpv6)
        	{
        		for(int i = 0; i < 5; i++)
        			ports[i] = balancerRunner.balancerContext.externalPorts[i];
//        		udpPort = balancerRunner.balancerContext.externalUdpPort;
//        		tcpPort = balancerRunner.balancerContext.externalTcpPort;
//        		tlsPort = balancerRunner.balancerContext.externalTlsPort;
//        		wsPort = balancerRunner.balancerContext.externalWsPort;
//        		wssPort = balancerRunner.balancerContext.externalWssPort;
        	}
        	else
        	{
        		for(int i = 0; i < 5; i++)
        			ports[i] = balancerRunner.balancerContext.externalIpv6Ports[i];
//        		udpPort = balancerRunner.balancerContext.externalIpv6UdpPort;
//        		tcpPort = balancerRunner.balancerContext.externalIpv6TcpPort;
//        		tlsPort = balancerRunner.balancerContext.externalIpv6TlsPort;
//        		wsPort = balancerRunner.balancerContext.externalIpv6WsPort;
//        		wssPort = balancerRunner.balancerContext.externalIpv6WssPort;
        	}

			String transport = null;
			if (sipMessage instanceof Response)
				transport = ((ViaHeader) sipMessage.getHeader(ViaHeader.NAME)).getTransport().toLowerCase();
			else {
				URI requestURI = ((Request) sipMessage).getRequestURI();
				transport = ((ViaHeader) sipMessage.getHeader(ViaHeader.NAME)).getTransport().toLowerCase();
				if (requestURI.isSipURI()) {
					if (((SipUri) requestURI).getTransportParam() != null)
						transport = ((SipUri) requestURI).getTransportParam();
				}
			}

            String privateIp = balancerRunner.balancerContext.host;
            @SuppressWarnings("unchecked")
			ListIterator<RecordRouteHeader> recordRouteHeaderList = sipMessage.getHeaders(RecordRouteHeader.NAME);
            
            try {
                HeaderFactory headerFactory = SipFactory.getInstance().createHeaderFactory(); 
                Header contactHeader = null;
                
                if (!recordRouteHeaderList.hasNext()) {
                	if(logger.isDebugEnabled()) {
                		logger.debug("Record Route header list is empty");
                	}
                }

                while (recordRouteHeaderList.hasNext()) {
                    RecordRouteHeader recordRouteHeader = (RecordRouteHeader) recordRouteHeaderList.next();
                    
                    if(logger.isDebugEnabled()) {
                    	logger.debug("About to check Record-Route header: "+recordRouteHeader.toString());
                    }
                    if (((SipURI)recordRouteHeader.getAddress().getURI()).getHost().equals(privateIp)) { //If this RecordRoute header is from LB
                    	for(int port : ports)
                    		if(((SipURI)recordRouteHeader.getAddress().getURI()).getPort()==port)
                    		{ // And if the port is the external Port
                    			SipURI sipURI = (SipURI) recordRouteHeader.getAddress().getURI();
                    			sipURI.setHost(currentPublicIp);                            
                    		}                        
                    } else {
                    	if(logger.isDebugEnabled()) {
                    		logger.debug("Didn't patched the Record-Route because ip address is not the private one: "+((SipURI)recordRouteHeader.getAddress().getURI()).getHost());
                    	}
                    }
                }

                if (sipMessage.getHeader(ContactHeader.NAME) != null) {                	
                    final String displayedName = ((ContactHeader)sipMessage.getHeader("Contact")).getAddress().getDisplayName();
                    
                    int currPort=balancerRunner.balancerContext.getExternalPortByTransport(transport,isIpv6);
                    
                    if (displayedName != null && !displayedName.isEmpty()) {
                        final String contactURI = "sip:"+displayedName+"@"+currentPublicIp+":"+currPort;
                        contactHeader = headerFactory.createHeader("Contact", contactURI);
                        ((ContactHeader)contactHeader).getAddress().setDisplayName(displayedName);
                    } else {
                        final String contactURI = "sip:"+currentPublicIp+":"+currPort;
                        contactHeader = headerFactory.createHeader("Contact", contactURI);
                    }
                    if (contactHeader != null) {
                        sipMessage.removeFirst("Contact");
                        sipMessage.addHeader(contactHeader);
                    }
                }

                if(logger.isDebugEnabled() && contactHeader != null) {
                		logger.debug("Patched the Contact header with : "+contactHeader.toString());
                }
            } catch (PeerUnavailableException peerUnavailableException) {
                logger.error("Unexpected exception while forwarding the response \n" + sipMessage, peerUnavailableException);
            } catch (ParseException parseException) {
                logger.error("Unexpected exception while forwarding the response \n" + sipMessage, parseException);
            } catch (NullPointerException e) {
                logger.error("Unexpected exception while forwarding the response \n" + sipMessage, e);
            }
        }
    }
1197586
private void pushRoute(javax.sip.address.SipURI sipUri) {
		if(!isInitial() && getSipSession().getProxy() == null) {
			//as per JSR 289 Section 11.1.3 Pushing Route Header Field Values
			// pushRoute can only be done on the initial requests.
			// Subsequent requests within a dialog follow the route set.
			// Any attempt to do a pushRoute on a subsequent request in a dialog
			// MUST throw and IllegalStateException.
			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);
			}
		}
	}
160681
protected void doSubscribe(javax.servlet.sip.SipServletRequest req) throws javax.servlet.ServletException, java.io.IOException{
    	if (req.isInitial())
			notImplemented(req);
    }