/*
(non-Javadoc)
@see org.mobicents.javax.servlet.sip.SipFactoryExt#createApplicationSession(boolean)
763177
public SipApplicationSession createApplicationSession(boolean managed) {
		MobicentsSipApplicationSession sipApplicationSessionImpl = null; 
		HttpSession httpSession = threadLocalHttpSession.get();
		// make sure we don't create a new sip app session if the http session has already one associated
		if(httpSession != null) {
			ConvergedSession convergedSession = (ConvergedSession) httpSession;
			sipApplicationSessionImpl = convergedSession.getApplicationSession(false);
		}
		if(sipApplicationSessionImpl == null) {
			sipApplicationSessionImpl =
				(MobicentsSipApplicationSession)sipFactoryImpl.createApplicationSessionByAppName(sipContext.getApplicationName(), managed);
			associateHttpSession(sipApplicationSessionImpl);
		}
		return sipApplicationSessionImpl;
	}
190260
@Override
  public IShSessionData getAppSessionData(Class<? extends AppSession> clazz, String sessionId) {
    if (clazz.equals(ClientShSession.class)) {
      ShClientSessionDataReplicatedImpl data = new ShClientSessionDataReplicatedImpl(sessionId, this.mobicentsCluster);
      return data;
    }
    else if (clazz.equals(ServerShSession.class)) {
      ShServerSessionDataReplicatedImpl data = new ShServerSessionDataReplicatedImpl(sessionId, this.mobicentsCluster);
      return data;
    }
    throw new IllegalArgumentException();
  }
449926
public void setIBMApplicationSession(IBMApplicationSession appSession) {
        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
            LoggingUtil.SESSION_LOGGER_CORE.logp(Level.FINE, methodClassName, methodNames[SET_IBM_APPLICATION_SESSION], "for app " + appName + " IBMApplicationSession "
                                                                                                                        + appSession);
        }
        mIBMApplicationSession = appSession;
    }
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;
	}
1049566
@Override
	public final Session createSession(boolean transacted, int acknowledgeMode) throws JMSException
    {
        if (!transacted && acknowledgeMode == Session.SESSION_TRANSACTED)
            throw new FFMQException("Acknowledge mode SESSION_TRANSACTED cannot be used for an non-transacted session","INVALID_ACK_MODE");
        
        externalAccessLock.readLock().lock();
    	try
		{
	        checkNotClosed();
	        RemoteSession session = new RemoteSession(idProvider.createID(),
	        		                                  this,
	                                                  transportHub.createEndpoint(),
	                                                  transacted,
	                                                  acknowledgeMode);
	        registerSession(session);
	        session.remoteInit();
	        return session;
		}
    	finally
    	{
    		externalAccessLock.readLock().unlock();
    	}
    }
626619
public void initializeSession()
    {
        ApplicationSessionInitializer asi = getApplicationSessionInitializer();
        if (asi != null)
        {
            asi.initializeSession();
            Map<String, Object> sessionAttributes = asi.getSessionAttributes();
            if (sessionAttributes != null)
            {
                    setSessionAttributes(sessionAttributes);
            }
            propertyChangeSupport.firePropertyChange(SESSION_ATTRIBUTES, null, sessionAttributes);
        }
    }
860350
func (api *Client) CreateApplication(data *ApplicationData) (string, error) {
	_, headers, err := api.makeRequest(http.MethodPost, api.concatUserPath(applicationsPath), nil, data)
	if err != nil {
		return "", err
	}
	return getIDFromLocationHeader(headers), nil
}
460102
public void init(String webAppRfsPath, String servletMapping, String defaultWebApplication) {

        try {
            // explicit set to null to overwrite exiting values from session
            m_availableModules = null;
            m_fullDatabaseKey = null;
            m_databaseKey = null;
            m_databaseKeys = null;
            m_databaseProperties = null;
            m_configuration = null;
            m_installModules = null;
            m_moduleDependencies = null;
            m_sortedDatabaseKeys = null;
            m_moduleFilenames = null;

            if (servletMapping == null) {
                servletMapping = "/opencms/*";
            }
            if (defaultWebApplication == null) {
                defaultWebApplication = "ROOT";
            }
            m_servletMapping = servletMapping;
            m_defaultWebApplication = defaultWebApplication;

            setWebAppRfsPath(webAppRfsPath);
            m_errors = new ArrayList<String>();

            if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(webAppRfsPath)) {
                m_configuration = new CmsParameterConfiguration(m_configRfsPath + CmsSystemInfo.FILE_PROPERTIES);
                readDatabaseConfig();
            }

            if (m_workplaceImportThread != null) {
                if (m_workplaceImportThread.isAlive()) {
                    m_workplaceImportThread.kill();
                }
                m_workplaceImportThread = null;
                m_newLoggingOffset = 0;
                m_oldLoggingOffset = 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
            m_errors.add(e.toString());
        }
    }
1190468
public ParticipantListener createSessionListener(String sessionId, ISessionUpdate callback) {
        return SessionService.create(self, sessionId, eventManager, callback);
    }
174521
@Override
    public <P> void pojoDaoCreated(PojoDaoFactoryEvent<P> event) {
        Schema schema = new Schema();
        event.getPojoBinding().describe(schema.createTable(event.getTableName()), schema);
        List<SchemaStatement> statements = schema.items().map(SchemaItem::createStatement).collect(Collectors.toList());
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Creating table(s) to support \"{}\":\n\t{}\n", event.getPojoBinding().getPojoType().getSimpleName(), statements.stream().map(SchemaStatement::getQueryString).collect(Collectors.joining("\n\t")));
        }
        statements.forEach(session::execute);
    }
679823
public void exitSipApp(MobicentsSipApplicationSession sipApplicationSession, MobicentsSipSession sipSession) {
		switch (concurrencyControlMode) {
			case SipSession:
				if(sipSession != null) {
					sipSession.release();
				} else {
					if(logger.isDebugEnabled()) {
						logger.debug("NOT RELEASING SipSession on exit sipApplicationSession=" + sipApplicationSession +
								" sipSession=" + sipSession + " semaphore=null");
					}
				}
				break;
			case SipApplicationSession:
				boolean wasSessionReleased = false;
				SipApplicationSessionCreationThreadLocal sipApplicationSessionCreationThreadLocal = SipApplicationSessionCreationThreadLocal.getTHRef().get();
				if(sipApplicationSessionCreationThreadLocal != null) {					
					for(MobicentsSipApplicationSession sipApplicationSessionAccessed : SipApplicationSessionCreationThreadLocal.getTHRef().get().getSipApplicationSessions()) {
						sipApplicationSessionAccessed.release();
						if(sipApplicationSessionAccessed.equals(sipApplicationSession)) {
							wasSessionReleased = true;
						}
					}		
					SipApplicationSessionCreationThreadLocal.getTHRef().get().getSipApplicationSessions().clear();
					SipApplicationSessionCreationThreadLocal.getTHRef().set(null);
					SipApplicationSessionCreationThreadLocal.getTHRef().remove();
				}
				isManagedThread.set(null);
				isManagedThread.remove();
				if(!wasSessionReleased) {
					if(sipApplicationSession != null) {
						sipApplicationSession.release();
					} else {
						if(logger.isDebugEnabled()) {
							logger.debug("NOT RELEASING SipApplicationSession on exit sipApplicationSession=" + sipApplicationSession +
									" sipSession=" + sipSession + " semaphore=null");
						}
					}
				}
				break;
			case None:
				break;
		}		
	}
1286372
SessionImpl createSession(ConversationState user) throws RepositoryException, LoginException
   {
      if (IdentityConstants.SYSTEM.equals(user.getIdentity().getUserId()))
      {
         // Need privileges to get system session.
         SecurityManager security = System.getSecurityManager();
         if (security != null)
         {
            security.checkPermission(JCRRuntimePermissions.CREATE_SYSTEM_SESSION_PERMISSION);
         }
      }
      else if (DynamicIdentity.DYNAMIC.equals(user.getIdentity().getUserId()))
      {
         // Need privileges to get Dynamic session.
         SecurityManager security = System.getSecurityManager();
         if (security != null)
         {
            security.checkPermission(JCRRuntimePermissions.CREATE_DYNAMIC_SESSION_PERMISSION);
         }
      }
      if (SessionReference.isStarted())
      {
         return new TrackedSession(workspaceName, user, container);
      }
      else
      {
         return new SessionImpl(workspaceName, user, container);
      }
   }
11223
public void sessionWillPassivate(SipApplicationSessionEvent event) {
		logger.info("Following sip application session just passivated " + event.getApplicationSession().getId() + " cause " + ((SipApplicationSessionActivationEvent)event).getCause());

	}
914065
private static ApplicationSession openApplication(ApplicationDefinition appDef, RESTClient restClient) {
        String storageService = appDef.getStorageService();
        if (storageService == null ||
                storageService.length() <= "Service".length() ||
                !storageService.endsWith("Service")) {
            throw new RuntimeException("Unknown storage-service for application '" + appDef.getAppName() + "': " + storageService);
        }
        
        // Using the application's StorageService, attempt to create an instance of the
        // ApplicationSession subclass XxxSession where Xxx is the storage prefix.
        try {
            String prefix = storageService.substring(0, storageService.length() - "Service".length());
            String className = Client.class.getPackage().getName() + "." + prefix + "Session";
            @SuppressWarnings("unchecked")
            Class<ApplicationSession> appClass = (Class<ApplicationSession>) Class.forName(className);
            Constructor<ApplicationSession> constructor = appClass.getConstructor(ApplicationDefinition.class, RESTClient.class);
            ApplicationSession appSession = constructor.newInstance(appDef, restClient);
            return appSession;
        } catch (Exception e) {
            restClient.close();
            throw new RuntimeException("Unable to load session class", e);
        }
    }
1062263
public void triggerSessionCreated(JingleSession jingleSession) {
        jingleSessions.add(jingleSession);
        jingleSession.addListener(this);
        for (CreatedJingleSessionListener createdJingleSessionListener : creationListeners) {
            try {
                createdJingleSessionListener.sessionCreated(jingleSession);
            } catch (Exception e) {
                LOGGER.log(Level.WARNING, "exception", e);
            }
        }
    }
38160
public MobicentsSipApplicationSession findSipApplicationSession(HttpSession httpSession) {
		for (MobicentsSipApplicationSession sipApplicationSessionImpl : sipApplicationSessions.values()) {			
			if(sipApplicationSessionImpl.findHttpSession(httpSession.getId()) != null) {
				return sipApplicationSessionImpl;
			}
		}
		return null;
	}
947906
public SipServletRequest createRequest(SipServletRequest origRequest,
			boolean sameCallId) {
		if (logger.isDebugEnabled()) {
			logger.debug("Creating SipServletRequest from original request["
					+ origRequest + "] with same call id[" + sameCallId + "]");
		}
	    
		final SipServletRequestImpl origRequestImpl = (SipServletRequestImpl) origRequest;
		final MobicentsSipApplicationSession originalAppSession = (MobicentsSipApplicationSession) origRequestImpl.getSipApplicationSession(false);		
		if (originalAppSession == null) {
			throw new IllegalStateException("original request's app session does not exists");
		}			
		final MobicentsSipSession originalSession = origRequestImpl.getSipSession();
		final Request newRequest = (Request) origRequestImpl.message.clone();
		((MessageExt)newRequest).setApplicationData(null);
		//removing the via header from original request
		newRequest.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 = getSipApplicationDispatcher();
		final String branch = JainSipUtils.createBranch(originalAppSession.getKey().getId(),  sipApplicationDispatcher.getHashFromApplicationName(originalAppSession.getKey().getApplicationName()));
		ViaHeader viaHeader = JainSipUtils.createViaHeader(
				getSipNetworkInterfaceManager(), newRequest, branch, null);
		newRequest.addHeader(viaHeader);
		
		final FromHeader newFromHeader = (FromHeader) newRequest.getHeader(FromHeader.NAME); 
		
		//assign a new from tag
		newFromHeader.removeParameter("tag");
		//remove the to tag
		((ToHeader) newRequest.getHeader(ToHeader.NAME))
				.removeParameter("tag");
		// Remove the route header ( will point to us ).
		// commented as per issue 649
//		newRequest.removeHeader(RouteHeader.NAME);
		
		// Remove the record route headers. This is a new call leg.
		newRequest.removeHeader(RecordRouteHeader.NAME);
		
		//For non-REGISTER requests, the Contact header field is not copied 
		//but is populated by the container as usual
		if(!Request.REGISTER.equalsIgnoreCase(newRequest.getMethod())) {
			try {
				//For non-REGISTER requests, the Contact header field is not copied
				//but is populated by the container as usual
				if(!Request.REGISTER.equalsIgnoreCase(newRequest.getMethod())) {
					
			
					//Adding default contact header for specific methods only
					if(JainSipUtils.CONTACT_HEADER_METHODS.contains(newRequest.getMethod())) {
						String fromName = null;
						String displayName = ((MessageExt)newRequest).getFromHeader().getAddress().getDisplayName();
						if(newRequest.getHeader(ContactHeader.NAME) != null && 
							((ContactHeader)newRequest.getHeader(ContactHeader.NAME)).getAddress().getURI() instanceof javax.sip.address.SipURI) {
							fromName = ((javax.sip.address.SipURI)((MessageExt)newRequest).getFromHeader().getAddress().getURI()).getUser();
						}
						// Create the contact name address.
						ContactHeader contactHeader = 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
						if(fromName != null) {
							if(useLoadBalancer) {
								javax.sip.address.SipURI sipURI = addressFactory.createSipURI(fromName, loadBalancerToUse.getAddress().getHostAddress());
								sipURI.setHost(loadBalancerToUse.getAddress().getHostAddress());
								sipURI.setPort(loadBalancerToUse.getSipPort());
								sipURI.setTransportParam(JainSipUtils.findTransport(newRequest));
								javax.sip.address.Address contactAddress = addressFactory.createAddress(sipURI);
								if(displayName != null && displayName.length() > 0) {
									contactAddress.setDisplayName(displayName);
								}
								contactHeader = headerFactory.createContactHeader(contactAddress);
							} else {
								contactHeader = JainSipUtils.createContactHeader(getSipNetworkInterfaceManager(), newRequest, displayName, fromName, null);
							}
						} else {
							if(logger.isDebugEnabled()) {
								logger.debug("Unable to create Contact Header. It will be added later on send.");
							}
						}
			
						newRequest.removeHeader(ContactHeader.NAME);
						if(contactHeader != null) {
							newRequest.addHeader(contactHeader);
						}
					} else {
						newRequest.removeHeader(ContactHeader.NAME);
					}
				}
			} catch (Exception ex) {
				logger.warn("Unable to create Contact Header. It will be added later on send.", ex);
			}
		}		
		try {
			if(!sameCallId) {
				//Creating new call id
				final Iterator<MobicentsExtendedListeningPoint> listeningPointsIterator = getSipNetworkInterfaceManager().getExtendedListeningPoints();				
				if(!listeningPointsIterator.hasNext()) {				
					throw new IllegalStateException("There is no SIP connectors available to create the request");
				}
				final MobicentsExtendedListeningPoint extendedListeningPoint = listeningPointsIterator.next();
				final CallIdHeader callIdHeader = sipApplicationDispatcher.getCallId(extendedListeningPoint, null);
				newRequest.setHeader(callIdHeader);
				if(logger.isDebugEnabled()) {
					logger.debug("not reusing same call id, new call id is " + callIdHeader);
				}
			} else {
				if(logger.isDebugEnabled()) {
					logger.debug("reusing same call id = " + ((MessageExt)newRequest).getCallIdHeader().getCallId());
				}
			}
									
			newFromHeader.setTag(ApplicationRoutingHeaderComposer.getHash(getSipApplicationDispatcher(), originalAppSession.getKey().getApplicationName(), originalAppSession.getKey().getId()));
			
			final MobicentsSipSessionKey key = SessionManagerUtil.getSipSessionKey(originalAppSession.getKey().getId(), originalAppSession.getKey().getApplicationName(), newRequest, false);
			final MobicentsSipSession session = originalAppSession.getSipContext().getSipManager().getSipSession(key, true, this, originalAppSession);			
			if(originalSession != null) {
				session.setHandler(originalSession.getHandler());
			} else if(originalAppSession.getCurrentRequestHandler() != null) {
				session.setHandler(originalAppSession.getCurrentRequestHandler());
			}
			
			final SipServletRequestImpl newSipServletRequest = (SipServletRequestImpl) mobicentsSipServletMessageFactory.createSipServletRequest(
					newRequest,
					session, 
					null, 
					null, 
					JainSipUtils.DIALOG_CREATING_METHODS.contains(newRequest.getMethod()));			
			//JSR 289 Section 15.1.6
			newSipServletRequest.setRoutingDirective(SipApplicationRoutingDirective.CONTINUE, origRequest);
			
			if(logger.isDebugEnabled()) {
				logger.debug("newSipServletRequest = " + newSipServletRequest);
			}	
			
			return newSipServletRequest;
		} catch (Exception ex) {
			logger.error("Unexpected exception ", ex);
			throw new IllegalArgumentException(
					"Illegal arg ecnountered while creatigng b2bua", ex);
		}			
	}