/*
Method used to create the Session from a request
(non-Javadoc)

@see
com.ibm.wsspi.session.IGenericSessionManager#createSession(javax.servlet
.ServletRequest, javax.servlet.ServletResponse,
com.ibm.wsspi.session.SessionAffinityContext, boolean)
2885
@Override
    public Object createSession(ServletRequest req, ServletResponse res, SessionAffinityContext sac, boolean reuseTheId) {
        String id = _sam.getInUseSessionID(req, sac);
        int version = _sam.getInUseSessionVersion(req, sac); // sac.getRequestedSessionVersion();
        ISession isess = createISession(id, version, reuseTheId);
        return adaptAndSetCookie(req, res, sac, isess);
    }
874252
public Session session() {
        if (session == null || !validSession) {
            validSession(true);
            session = new Session(servletRequest.getSession(), this);
        }
        return session;
    }
994176
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
		if (active) {
			if (log.isDebugEnabled()) 
				log.debug("sessionCreated sessionId = "
						+ httpSessionEvent.getSession().getId());
		}
	}
365878
public ValidationSessionInfo createSession(HttpServletRequest req, HttpServletResponse res) {
        String key = this.getSessionKey();
        ValidationSessionInfo sessionInfo = new ValidationSessionInfo(req, key);
        this.sessionMap.put(key, sessionInfo);
        res.addCookie(new Cookie("AuthToken", key));
        return sessionInfo;
    }
985850
@Override
    public BrowserSession createSystemBrowserSession(SIDestinationAddress destAddress,
                                                     DestinationType destinationType,
                                                     SelectionCriteria criteria)

                    throws SIConnectionDroppedException, SIConnectionUnavailableException, SIErrorException, SIIncorrectCallException, SIResourceException, SINotPossibleInCurrentConfigurationException
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "createSystemBrowserSession",
                        new Object[] { destAddress, destinationType, criteria });

        // See if this connection has been closed
        checkNotClosed();

        checkBrowserSessionNullParameters(destAddress);

        if (!destAddress.getDestinationName().startsWith(SIMPConstants.SYSTEM_DESTINATION_PREFIX))
        {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                SibTr.exit(tc, "createSystemBrowserSession", "SIIncorrectCallException");
            throw new SIIncorrectCallException(
                            nls.getFormattedMessage(
                                                    "SYSTEM_DESTINATION_USAGE_ERROR_CWSIP0024",
                                                    new Object[] { destAddress.getDestinationName(),
                                                                  _messageProcessor.getMessagingEngineName() },
                                                    null));
        }

        BrowserSession session = null;
        try
        {
            session =
                            createBrowserSession(destAddress,
                                                 destinationType,
                                                 criteria,
                                                 true,
                                                 null, // alternateUser 
                                                 false);
        } catch (SITemporaryDestinationNotFoundException e)
        {
            // Temporary destination not found should not happen for a System destination
            // FFDC
            FFDCFilter.processException(
                                        e,
                                        "com.ibm.ws.sib.processor.impl.ConnectionImpl.createSystemBrowserSession",
                                        "1:4363:1.347.1.25",
                                        this);

            SibTr.error(tc, "INTERNAL_MESSAGING_ERROR_CWSIP0002",
                        new Object[] {
                                      "com.ibm.ws.sib.processor.impl.ConnectionImpl",
                                      "1:4369:1.347.1.25",
                                      e });

            SibTr.exception(tc, e);

            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                SibTr.exit(tc, "createSystemBrowserSession", "SIErrorException");

            throw new SIErrorException(nls.getFormattedMessage(
                                                               "INTERNAL_MESSAGING_ERROR_CWSIP0002",
                                                               new Object[] { "ConnectionImpl",
                                                                             "1:4380:1.347.1.25",
                                                                             e },
                                                               null),
                            e);
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "createSystemBrowserSession", session);

        return session;
    }
764303
protected IHttpSessionContext createSessionContextObject(SessionManagerConfig smc, SessionApplicationParameters sap)
    {
        return new HttpSessionContext31Impl(smc, sap, this.smgr.getSessionStoreService());
    }
1263640
public SipServletRequest createRequest(final String method) {
		if(logger.isDebugEnabled()) {
			logger.debug("createRequest - method="+ method);
			logger.debug("createRequest - getId()="+ getId());
		}
		if(method.equalsIgnoreCase(Request.ACK) || method.equalsIgnoreCase(Request.PRACK)
				|| method.equalsIgnoreCase(Request.CANCEL)) {
			throw new IllegalArgumentException(
					"Can not create ACK, PRACK or CANCEL requests with this method");
		}
		if(!isValid()) {
			throw new IllegalStateException("cannot create a subsequent request " + method + " because the session " + key + " is invalid");
		}
		if(State.TERMINATED.equals(state)) {
			throw new IllegalStateException("cannot create a subsequent request " + method + " because the session " + key + " is in TERMINATED state");
		}
		// Issue 2440 : http://code.google.com/p/mobicents/issues/detail?id=2440
		// SipSession.createRequest on proxy SipSession does not throw IllegalStateException
		if(proxy != null) {
			throw new IllegalStateException("cannot create a subsequent request " + method + " because the session " + key + " has been used for proxying. See JSR289 Section 6.2.2.1.");
		}
//		if((State.INITIAL.equals(state) && hasOngoingTransaction())) {
//			throw new IllegalStateException("cannot create a request because the session is in INITIAL state with ongoing transactions");
//		}
		if(logger.isDebugEnabled()) {
			logger.debug("dialog associated with this session to create the new request " + method + " within that dialog "+
					sessionCreatingDialog);
			if(sessionCreatingDialog != null) {
				logger.debug("dialog state " + sessionCreatingDialog.getState() + " for that dialog "+ sessionCreatingDialog);
			}
		}
		SipServletRequestImpl sipServletRequest = null;
		// Fix for Issue http://code.google.com/p/mobicents/issues/detail?id=2230 BYE is routed to unexpected IP
		// MSS should throw an IllegalStateException when a subsequent request is being created on a TERMINATED dialog
		// don't do it on the BYE method as a 408 within a dialog could have make the dialog TERMINATED and MSS should allow the app to create the subsequent BYE from any thread
		if(sessionCreatingDialog != null && DialogState.TERMINATED.equals(sessionCreatingDialog.getState()) && !method.equalsIgnoreCase(Request.BYE)) {
			// don't do it for authentication as the dialog will go back to TERMINATED state, so we should allow to create challenge requests
			if(sessionCreatingTransactionRequest == null || sessionCreatingTransactionRequest.getLastFinalResponse() == null ||
					(sessionCreatingTransactionRequest.getLastFinalResponse().getStatus() != 401 && sessionCreatingTransactionRequest.getLastFinalResponse().getStatus() != 407 &&
						// http://code.google.com/p/sipservlets/issues/detail?id=143 RFC 4028 Session Timer : Allow sending retry INVITE after receiving 422 response
						sessionCreatingTransactionRequest.getLastFinalResponse().getStatus() != SipServletResponse.SC_SESSION_INTERVAL_TOO_SMALL)) {
				throw new IllegalStateException("cannot create a subsequent request " + method + " because the dialog " + sessionCreatingDialog + " for session " + key + " is in TERMINATED state");
			}
		}
		// Issue http://code.google.com/p/mobicents/issues/detail?id=2230 BYE is routed to unexpected IP BYE can be sent on a TERMINATED Dialog
		if(this.sessionCreatingDialog != null &&
				(!DialogState.TERMINATED.equals(sessionCreatingDialog.getState()) ||
						(DialogState.TERMINATED.equals(sessionCreatingDialog.getState()) && method.equalsIgnoreCase(Request.BYE)))) {

			if(logger.isDebugEnabled()) {
				logger.debug("dialog " + sessionCreatingDialog + " used to create the new request " + method);
			}
			try {
				final Request methodRequest = this.sessionCreatingDialog.createRequest(method);

				if(methodRequest.getHeader(ContactHeader.NAME) != null) {
					// if a sip load balancer is present in front of the server, the contact header is the one from the sip lb
					// so that the subsequent requests can be failed over
					try {
						ContactHeader contactHeader = null;
						FromHeader from = (FromHeader) methodRequest.getHeader(FromHeader.NAME);
						String displayName = from.getAddress().getDisplayName();
						String userName = null;
						javax.sip.address.URI uri = from.getAddress().getURI();
						if(uri.isSipURI()) {
							userName = ((javax.sip.address.SipURI)uri).getUser();
						}
						if(sipFactory.isUseLoadBalancer()) {
							// https://github.com/RestComm/sip-servlets/issues/111
							MobicentsExtendedListeningPoint listeningPoint = JainSipUtils.findListeningPoint(sipFactory.getSipNetworkInterfaceManager(), methodRequest, outboundInterface);
							if(listeningPoint != null && listeningPoint.isUseLoadBalancer()) {
								// https://github.com/RestComm/sip-servlets/issues/137
								SipLoadBalancer loadBalancerToUse = null;
								if(listeningPoint.getLoadBalancer() == null) {
									loadBalancerToUse = sipFactory.getLoadBalancerToUse();
									if(logger.isDebugEnabled()) {
										logger.debug("Using listeningPoint " + listeningPoint + " for global load balancer " + sipFactory.getLoadBalancerToUse());
									}
								} else {
									loadBalancerToUse = listeningPoint.getLoadBalancer();
									if(logger.isDebugEnabled()) {
										logger.debug("Using listeningPoint " + listeningPoint + " for connector specific load balancer " + listeningPoint.getLoadBalancer());
									}
								}

								javax.sip.address.SipURI sipURI = SipFactoryImpl.addressFactory.createSipURI(userName, loadBalancerToUse.getAddress().getHostAddress());
								sipURI.setHost(loadBalancerToUse.getAddress().getHostAddress());
								sipURI.setPort(loadBalancerToUse.getSipPort());

								// TODO: Is this enough or we must specify the transport somewhere?
								// We can leave it like this. It will be updated if needed in the send() method
								sipURI.setTransportParam(ListeningPoint.UDP);

								javax.sip.address.Address contactAddress = SipFactoryImpl.addressFactory.createAddress(sipURI);
								contactHeader = SipFactoryImpl.headerFactory.createContactHeader(contactAddress);
							} else {
								if(logger.isDebugEnabled()) {
									logger.debug("Not Using load balancer as it is not enabled for listeningPoint " + listeningPoint);
								}
								contactHeader = JainSipUtils.createContactHeader(sipFactory.getSipNetworkInterfaceManager(), methodRequest, displayName, userName, outboundInterface);
							}
						} else {
							contactHeader = JainSipUtils.createContactHeader(sipFactory.getSipNetworkInterfaceManager(), methodRequest, displayName, userName, outboundInterface);
						}
						methodRequest.setHeader(contactHeader);
					} catch (Exception e) {
						logger.error("Can not create contact header for subsequent request " + method + " for session " + key, e);
					}
				}
				// Fix for Issue 1130 (http://code.google.com/p/mobicents/issues/detail?id=1130) :
				// NullPointerException when sending request to client which support both UDP and TCP transport
				// before removing the via header we store the transport into its app data
				ListIterator<ViaHeader> viaHeaders = methodRequest.getHeaders(ViaHeader.NAME);
				if(viaHeaders != null && viaHeaders.hasNext()) {
					ViaHeader viaHeader = viaHeaders.next();
					((MessageExt)methodRequest).setApplicationData(viaHeader.getTransport());
				}
				//Issue 112 fix by folsson
				methodRequest.removeHeader(ViaHeader.NAME);

				// cater to http://code.google.com/p/sipservlets/issues/detail?id=31 to be able to set the rport in applications
				final SipApplicationDispatcher sipApplicationDispatcher = sipFactory.getSipApplicationDispatcher();
				final String branch = JainSipUtils.createBranch(getSipApplicationSession().getKey().getId(),  sipApplicationDispatcher.getHashFromApplicationName(getKey().getApplicationName()));
				ViaHeader viaHeader = JainSipUtils.createViaHeader(
	    				sipFactory.getSipNetworkInterfaceManager(), methodRequest, branch, outboundInterface);
				methodRequest.addHeader(viaHeader);

				//if a SUBSCRIBE or BYE is sent for exemple, it will reuse the prexisiting dialog
				sipServletRequest = (SipServletRequestImpl) sipFactory.getMobicentsSipServletMessageFactory().createSipServletRequest(
						methodRequest, this, null, sessionCreatingDialog,
						false);
			} catch (SipException e) {
				logger.error("Cannot create the " + method + " request from the dialog " + sessionCreatingDialog,e);
				throw new IllegalArgumentException("Cannot create the " + method + " request from the dialog " + sessionCreatingDialog + " for sip session " + key,e);
			}
		} else {
			boolean treatAsInitialRequest = false;
			// http://code.google.com/p/sipservlets/issues/detail?id=19
			// Retried Request are not considered as initial
			if(sessionCreatingTransactionRequest != null && sessionCreatingTransactionRequest.getLastFinalResponse() != null &&
					sessionCreatingTransactionRequest.getLastFinalResponse().getStatus() >= 400 && sessionCreatingTransactionRequest.getLastFinalResponse().getStatus() < 500) {
				if(logger.isDebugEnabled()) {
					logger.debug("Treating as Initial Request");
				}
				treatAsInitialRequest = true;
			}
			//case where other requests are sent with the same session like REGISTER or for challenge requests
			if(sessionCreatingTransactionRequest != null) {
				if(logger.isDebugEnabled()) {
					logger.debug("createRequest - sessionCreatingTransactionRequest is not null - id:" + this.getId());
				}

				if(!isSessionCreatingTransactionServer) {
					if(logger.isDebugEnabled()) {
						logger.debug("orignal tx for creating susbequent request " + method + " on session " + key +" was a Client Tx");
					}
					Request request = (Request) sessionCreatingTransactionRequest.getMessage().clone();
					// Issue 1524 :	Caused by: java.text.ParseException: CSEQ method mismatch with Request-Line
					javax.sip.address.URI requestUri = (javax.sip.address.URI) request.getRequestURI().clone();
					try {
						request.setMethod(method);
					} catch (ParseException e) {
						throw new IllegalArgumentException("Unexpected exception happened on setting method " + method, e);
					}
					request.setRequestURI(requestUri);
					((MessageExt)request).setApplicationData(null);

					final CSeqHeader cSeqHeader = (CSeqHeader) request.getHeader((CSeqHeader.NAME));
					try {
						cSeqHeader.setSeqNumber(cSeqHeader.getSeqNumber() + 1l);
						cSeqHeader.setMethod(method);
					} catch (InvalidArgumentException e) {
						logger.error("Cannot increment the Cseq header to the new " + method + " on the susbequent request to create on session " + key,e);
						throw new IllegalArgumentException("Cannot create the " + method + " on the susbequent request to create on session " + key,e);
					} catch (ParseException e) {
						throw new IllegalArgumentException("Cannot set the " + method + " on the susbequent request to create on session " + key,e);
					}
					// Fix for Issue 1130 (http://code.google.com/p/mobicents/issues/detail?id=1130) :
					// NullPointerException when sending request to client which support both UDP and TCP transport
					// before removing the ViaHeader we store the transport into its app data
					ListIterator<ViaHeader> viaHeaders = request.getHeaders(ViaHeader.NAME);
					if(viaHeaders != null && viaHeaders.hasNext()) {
						ViaHeader viaHeader = viaHeaders.next();
						((MessageExt)request).setApplicationData(viaHeader.getTransport());
					}
					request.removeHeader(ViaHeader.NAME);

					final SipNetworkInterfaceManager sipNetworkInterfaceManager = sipFactory.getSipNetworkInterfaceManager();
					final SipProvider sipProvider = sipNetworkInterfaceManager.findMatchingListeningPoint(
							JainSipUtils.findTransport(request), false).getSipProvider();
					final SipApplicationDispatcher sipApplicationDispatcher = sipFactory.getSipApplicationDispatcher();
					final String branch = JainSipUtils.createBranch(getSipApplicationSession().getKey().getId(),  sipApplicationDispatcher.getHashFromApplicationName(getKey().getApplicationName()));

					ViaHeader viaHeader = JainSipUtils.createViaHeader(
		    				sipNetworkInterfaceManager, request, branch, outboundInterface);
		    		request.addHeader(viaHeader);

		    		// https://code.google.com/p/sipservlets/issues/detail?id=278
		    		request.removeContent();
		    		// http://code.google.com/p/sipservlets/issues/detail?id=161
		    		// Don't reuse the dialog for challenge requests as it can lead to the JAIN SIP Stack
		    		// reusing the Terminated dialog and drop 200 OK
		    		Dialog dialogToUse = sessionCreatingDialog;
		    		if(treatAsInitialRequest) {
		    			dialogToUse = null;
		    		}

					sipServletRequest = (SipServletRequestImpl) sipFactory.getMobicentsSipServletMessageFactory().createSipServletRequest(
							request, this, null, dialogToUse,
							true);

					// Fix for Issue http://code.google.com/p/mobicents/issues/detail?id=2230 BYE is routed to unexpected IP
					if(sessionCreatingDialog != null && sessionCreatingDialog.getRemoteTarget() != null) {
						SipUri sipUri = (SipUri) sessionCreatingDialog.getRemoteTarget().getURI().clone();
						sipUri.clearUriParms();
						if(logger.isDebugEnabled()) {
							logger.debug("setting request uri to " + sipUri);
						}
						request.setRequestURI(sipUri);
					}
					// http://code.google.com/p/sipservlets/issues/detail?id=130
					// removes the Route and Path Headers added previously for requests that the container originated
					// when the Load Balancer is used to avoid adding them again with each request going out.
					request.removeHeader(RouteHeader.NAME);
					request.removeHeader(PathHeader.NAME);
				} else {
					if(logger.isDebugEnabled()) {
						logger.debug("orignal tx for creating susbequent request " + method + " on session " + key +" was a Server Tx");
					}
					try {
						// copying original params and call id
						final Request originalRequest = (Request) sessionCreatingTransactionRequest.getMessage();
						final FromHeader fromHeader = (FromHeader) originalRequest.getHeader(FromHeader.NAME);
						final ToHeader toHeader = (ToHeader) originalRequest.getHeader(ToHeader.NAME);
						final AddressImpl currentLocalParty = (AddressImpl)this.getLocalParty().clone();
						final AddressImpl currentRemoteParty = (AddressImpl)this.getRemoteParty().clone();
						((Parameters)currentRemoteParty .getAddress().getURI()).removeParameter("tag");
						((Parameters)currentLocalParty .getAddress().getURI()).removeParameter("tag");
						final String originalCallId = ((CallIdHeader)originalRequest.getHeader(CallIdHeader.NAME)).getCallId();
						sipServletRequest =(SipServletRequestImpl) sipFactory.createRequest(
							getSipApplicationSession(),
							method,
							currentLocalParty,
							currentRemoteParty,
							handlerServlet,
							originalCallId,
							fromHeader.getTag());
						final Request request = ((Request)sipServletRequest.getMessage());
						sipServletRequest.getSipSession().setCseq(((CSeqHeader)request.getHeader(CSeqHeader.NAME)).getSeqNumber());
						final Map<String, String> fromParameters = new HashMap<String, String>();
						final Iterator<String> fromParameterNames = fromHeader.getParameterNames();
						while (fromParameterNames.hasNext()) {
							String parameterName = (String) fromParameterNames.next();
							if(sessionCreatingDialog != null || !SipFactoryImpl.FORBIDDEN_PARAMS.contains(parameterName)) {
								fromParameters.put(parameterName, fromHeader.getParameter(parameterName));
							}
						}
						final Map<String, String> toParameters = new HashMap<String, String>();
						final Iterator<String> toParameterNames = toHeader.getParameterNames();
						while (toParameterNames.hasNext()) {
							String parameterName = (String) toParameterNames.next();
							if(sessionCreatingDialog != null || !SipFactoryImpl.FORBIDDEN_PARAMS.contains(parameterName)) {
								toParameters.put(parameterName, toHeader.getParameter(parameterName));
							}
						}

						final ToHeader newTo = (ToHeader) request.getHeader(ToHeader.NAME);
						for (Entry<String, String> fromParameter : fromParameters.entrySet()) {
							String value = fromParameter.getValue();
							if(value == null) {
								value = "";
							}
							newTo.setParameter(fromParameter.getKey(),  value);
						}
						final FromHeader newFrom = (FromHeader) request.getHeader(FromHeader.NAME);
						for (Entry<String, String> toParameter : toParameters.entrySet()) {
							String value = toParameter.getValue();
							if(value == null) {
								value = "";
							}
							newFrom.setParameter(toParameter.getKey(),  value);
						}
						// Fix for Issue http://code.google.com/p/mobicents/issues/detail?id=2230 BYE is routed to unexpected IP
						if(sessionCreatingDialog != null && sessionCreatingDialog.getRemoteTarget() != null) {
							SipUri sipUri = (SipUri) sessionCreatingDialog.getRemoteTarget().getURI().clone();
							sipUri.clearUriParms();
							if(logger.isDebugEnabled()) {
								logger.debug("setting request uri to " + sipUri);
							}
							request.setRequestURI(sipUri);
						}
					} catch (ParseException e) {
						throw new IllegalArgumentException("Problem setting param on the newly created susbequent request " + sipServletRequest,e);
					}
				}

				if(sipSessionSecurity != null && sipSessionSecurity.getNextNonce() != null) {
					sipServletRequest.updateAuthorizationHeaders(true);
				}
				else if (sipSessionSecurity != null) {
					sipServletRequest.updateAuthorizationHeaders(false);
				}
				if(treatAsInitialRequest) {
					sipServletRequest.setRoutingState(RoutingState.INITIAL);
				}

				return sipServletRequest;
			} else {
				String errorMessage = "Couldn't create the subsequent request " + method + " for this session " + key + ", isValid " + isValid() + ", session state " + state + " , sessionCreatingDialog = " + sessionCreatingDialog;
				if(sessionCreatingDialog != null) {
					errorMessage += " , dialog state " + sessionCreatingDialog.getState();
				}
				errorMessage += " , sessionCreatingTransactionRequest = " + sessionCreatingTransactionRequest;
				throw new IllegalStateException(errorMessage);
			}
		}
		//Application Routing :
		//removing the route headers and adding them back again except the one
		//corresponding to the app that is creating the subsequent request
		//avoid going through the same app that created the subsequent request

		Request request = (Request) sipServletRequest.getMessage();
		final ListIterator<RouteHeader> routeHeaders = request.getHeaders(RouteHeader.NAME);
		request.removeHeader(RouteHeader.NAME);
		while (routeHeaders.hasNext()) {
			RouteHeader routeHeader = routeHeaders.next();
			String routeServerId = ((javax.sip.address.SipURI)routeHeader .getAddress().getURI()).
					getParameter(MessageDispatcher.RR_PARAM_SERVER_NAME);
			String routeAppNameHashed = ((javax.sip.address.SipURI)routeHeader .getAddress().getURI()).
				getParameter(MessageDispatcher.RR_PARAM_APPLICATION_NAME);
			String routeAppName = null;
			if(routeAppNameHashed != null) {
				routeAppName = sipFactory.getSipApplicationDispatcher().getApplicationNameFromHash(routeAppNameHashed);
			}
			if(routeAppName == null || !sipFactory.getSipApplicationDispatcher().getApplicationServerId().equals(routeServerId) ||
					!routeAppName.equals(getKey().getApplicationName())) {
				request.addHeader(routeHeader);
			}
		}

		if(sipSessionSecurity != null && sipSessionSecurity.getNextNonce() != null) {
			sipServletRequest.updateAuthorizationHeaders(true);
		}
		else if (sipSessionSecurity != null) {
			sipServletRequest.updateAuthorizationHeaders(false);
		}

		return sipServletRequest;
	}
73301
@Override
    public ProducerSession createProducerSession(SIDestinationAddress destAddr,
                                                 DestinationType destinationType,
                                                 OrderingContext extendedMessageOrderingContext,
                                                 String alternateUser)

                    throws SIConnectionDroppedException,
                    SIConnectionUnavailableException,
                    SITemporaryDestinationNotFoundException,
                    SIErrorException,
                    SIIncorrectCallException,
                    SIResourceException,
                    SINotPossibleInCurrentConfigurationException
    {
        if (TraceComponent.isAnyTracingEnabled() && CoreSPIConnection.tc.isEntryEnabled())
            SibTr.entry(CoreSPIConnection.tc, "createProducerSession",
                        new Object[] { destAddr,
                                      destinationType,
                                      extendedMessageOrderingContext,
                                      alternateUser,
                                      this });

        // See if this connection has been closed
        checkNotClosed();

        checkProducerSessionNullParameters(destAddr);

        SecurityContext secContext = null;
        // If security is enabled then we need to set up a security context
        if (_isBusSecure)
        {
            // Feature 219101: Add the alternate user string to the security context
            secContext = new SecurityContext(_subject,
                            alternateUser,
                            null,
                            _messageProcessor.getAuthorisationUtils());
        }

        boolean keepSecurityUserid = false;

        ProducerSession producer =
                        internalCreateProducerSession(destAddr,
                                                      destinationType,
                                                      false,
                                                      secContext,
                                                      keepSecurityUserid,
                                                      false,
                                                      true,
                                                      true,
                                                      null);

        if (TraceComponent.isAnyTracingEnabled() && CoreSPIConnection.tc.isEntryEnabled())
            SibTr.exit(CoreSPIConnection.tc, "createProducerSession", producer);
        //Destination is on the local bus
        return producer;
    }
239253
public SipServletRequest createRequest(SipSession session,
			SipServletRequest origRequest, Map<String, List<String>> headerMap) {

        if (logger.isDebugEnabled()) {
            logger.debug("createRequest - session=" + session + ", origRequest=" + origRequest);
        }

        if (origRequest == null) {
            throw new NullPointerException("original request cannot be null");
        }

		try {
			final SipServletRequestImpl origRequestImpl = (SipServletRequestImpl) origRequest;
			final MobicentsSipSession originalSession = origRequestImpl.getSipSession();
			final MobicentsSipSession sessionImpl = (MobicentsSipSession) session;

			final SipServletRequestImpl newSubsequentServletRequest = (SipServletRequestImpl) session.createRequest(origRequest.getMethod());

            //For non-REGISTER requests, the Contact header field is not copied
            //but is populated by the container as usual
            //commented since this is not true in this case since this is a subsequent request
            // this is needed for sending challenge requests
//			if(!Request.REGISTER.equalsIgnoreCase(origRequest.getMethod())) {
//				newSubsequentServletRequest.getMessage().removeHeader(ContactHeader.NAME);
//			}
            //If Contact header is present in the headerMap
            //then relevant portions of Contact header is to be used in the request created,
            //in accordance with section 4.1.3 of the specification.
            //They will be added later after the sip servlet request has been created
            final List<String> contactHeaderSet = retrieveContactHeaders(headerMap,
                    (Request) newSubsequentServletRequest.getMessage(),
                    originalSession.getServletContext());

            //If Contact header is present in the headerMap
            //then relevant portions of Contact header is to be used in the request created,
            //in accordance with section 4.1.3 of the specification.
            Request subsequentRequest = (Request) newSubsequentServletRequest.getMessage();

            // Issue 1490 : http://code.google.com/p/mobicents/issues/detail?id=1490
            // B2buaHelper.createRequest does not decrement Max-forwards
            MaxForwardsHeader maxForwardsHeader = (MaxForwardsHeader) subsequentRequest.getHeader(MaxForwardsHeader.NAME);
            try {
                maxForwardsHeader.setMaxForwards(maxForwardsHeader.getMaxForwards() - 1);
            } catch (InvalidArgumentException e) {
                throw new IllegalArgumentException(e);
            }

            ContactHeader contactHeader = (ContactHeader) subsequentRequest.getHeader(ContactHeader.NAME);
            if (contactHeader != null && contactHeaderSet.size() > 0) {
                subsequentRequest.removeHeader(ContactHeader.NAME);
                setContactHeaders(contactHeaderSet, newSubsequentServletRequest, contactHeader);
            }

            //Fix for Issue 585 by alexandre sova
            if (origRequest.getContent() != null && origRequest.getContentType() != null) {
                newSubsequentServletRequest.setContentLength(origRequest.getContentLength());
                newSubsequentServletRequest.setContent(origRequest.getContent(), origRequest.getContentType());
            }

            if (logger.isDebugEnabled()) {
                logger.debug("newSubsequentServletRequest = " + newSubsequentServletRequest);
            }

            // Added for Issue 1409 http://code.google.com/p/mobicents/issues/detail?id=1409
            copyNonSystemHeaders(origRequestImpl, newSubsequentServletRequest);

            linkedRequestMap.put(newSubsequentServletRequest, origRequestImpl);
            linkedRequestMap.put(origRequestImpl, newSubsequentServletRequest);

            sessionMap.put(originalSession.getId(), sessionImpl.getId());
            sessionMap.put(sessionImpl.getId(), originalSession.getId());
            dumpLinkedSessions();

            sessionImpl.setB2buaHelper(this);
            originalSession.setB2buaHelper(this);
            return newSubsequentServletRequest;
        } catch (Exception ex) {
            logger.error("Unexpected exception ", ex);
            throw new IllegalArgumentException(
                    "Illegal arg encountered while creating b2bua", ex);
        }
    }
518736
ServletContextHandler createServletContextHandler() {
    // Both security and session handlers are already created (Note: we don't want to create a new separate session
    // handler just for ServletContextHandler - we want to have just one SessionHandler & SessionManager)
    final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SECURITY | ServletContextHandler.NO_SESSIONS);

    if(null != config.context_path && ! config.context_path.isEmpty()) {
      context.setContextPath(config.context_path);
    } else {
      context.setContextPath("/");
    }
    return context;
  }
1090336
@Override
    public ProducerSession createProducerSession(
                                                 SIDestinationAddress destAddr,
                                                 String discriminator,
                                                 DestinationType destType,
                                                 OrderingContext extendedMessageOrderingContext,
                                                 String alternateUser)
                    throws SIConnectionDroppedException,
                    SIConnectionUnavailableException,
                    SITemporaryDestinationNotFoundException,
                    SIErrorException,
                    SIIncorrectCallException,
                    SIResourceException,
                    SINotPossibleInCurrentConfigurationException
    {
        ProducerSession session =
                        createProducerSession(destAddr,
                                              discriminator,
                                              destType,
                                              extendedMessageOrderingContext,
                                              alternateUser,
                                              false,
                                              false);

        return session;
    }
156452
protected RequestContext createRequestContext(HttpServletRequest request, HttpServletResponse response) {
        return new RequestContext(request, response, getServletContext());
    }
809345
private Session createNewSession() {
		Session session = model.newSession();
		getProxy().setIgnoreList(model.getOptionsParam().getGlobalExcludeURLParam().getTokensNames());
		return session;
	}
22659
public HttpSession getSession(boolean create)
    {
        // 321485
        if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) {  //306998.15
            logger.logp(Level.FINE, CLASS_NAME,"getSession", "create " + String.valueOf(create) + ", this -> "+this);
        }
        if (WCCustomProperties.CHECK_REQUEST_OBJECT_IN_USE){
            checkRequestObjectInUse();
        }
        // return _connContext.getSessionAPISupport().getSession(create);
        return _requestContext.getSession(create, ((WebAppDispatcherContext) this.getDispatchContext()).getWebApp());
    }
72097
@Trivial
    @Override
    public HttpSession getSession(boolean create) {
        HttpSession session = this.sessionData.getSession(create);
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "getSession(" + create + "): " + session);
        }
        return session;
    }
550320
@Override
    public HttpSession generateNewId(HttpServletRequest request, HttpServletResponse response, HttpSession existingSession) {
        SessionAffinityContext sac = getSessionAffinityContext(request);
        HttpSession session = (HttpSession) _coreHttpSessionManager.generateNewId(request, response, sac, ((SessionData) existingSession).getISession());
        return session;
    }
267991
@Override
    public ISession createSession(String id, boolean newId) {
        // assert (id!=null);
        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINER)) {
            StringBuffer sb = new StringBuffer("{").append(id).append(",").append(newId).append("} ").append(appNameForLogging);
            LoggingUtil.SESSION_LOGGER_CORE.entering(methodClassName, methodNames[CREATE_SESSION], sb.toString());
        }
        MemorySession sess = null;

        // need to test on a different language
        // try creating a temporary logger with the old resource bundle, and then
        // changing the environment to French or something
        if (inProcessOfStopping) {
            throwException("SessionContext.createWhenStop");
        }
        if ((!_smc.getEnableOverflow()) && (_sessions.size() >= _smc.getInMemorySize())) {
            // if we know we're in an overflow situation, don't bother
            // creating a new session
            if (_sessionStatistics != null) {
                _sessionStatistics.incNoRoomForNewSession();
            }
            sess = overflowSession;
        }
        // We expect the second part of check below - _sessions.get(id) == null --
        // to pass unless
        // the id generator generates a dup. This really should never happen.
        // The synchronization in SessionManager.createISession will prevent
        // multiple threads
        // with the same incoming id from both getting into this code. We're no
        // longer using
        // the newId parm...it could be removed, but its now part of the IStore
        // interface.
        if ((sess == null) && (_sessions.get(id) == null)) {
            if(!_removeAttrOnInvalidate)
                sess = new MemorySession(this, id, _storeCallback);
            else{
                if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
                    LoggingUtil.SESSION_LOGGER_CORE.logp(Level.FINE, methodClassName, methodNames[CREATE_SESSION], "Create MemorySession with _removeAttrOnInvalidate -->" + _removeAttrOnInvalidate );
                }
                sess = new MemorySession(this, id, _storeCallback, _removeAttrOnInvalidate);
            }
            sess.setUserName(ANONYMOUS_USER);
            // since this was a newly created session, we need to update the
            // lastAccessTime to the create time
            sess.updateLastAccessTime(sess.getCreationTime());
            try {
                _sessions.put(id, sess);
            } catch (TooManySessionsException tmse) {
                // could catch this exception if multiple threads get past the
                // first overflow check and then attempt to do the sessions.put
                sess = overflowSession;
            }
        }

        // Returns a new session if everything is good
        // Returns an overflowSession is overflow is not allowed and we've already
        // hit the maximum number in memory
        // Returns null if there was an existing session with this key - should
        // never happen

        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
            LoggingUtil.SESSION_LOGGER_CORE.exiting(methodClassName, methodNames[CREATE_SESSION], sess);
        }
        return sess;
    }