/*
(non-Javadoc)
@see gov.nist.javax.sip.SipListenerExt#processDialogTimeout(gov.nist.javax.sip.DialogTimeoutEvent)
188459
public void processDialogTimeout(final DialogTimeoutEvent timeoutEvent) {
		final Dialog dialog = timeoutEvent.getDialog();
		if(logger.isDebugEnabled()) {
			logger.info("dialog timeout " + dialog + " reason => " + timeoutEvent.getReason());
		}
		if(timeoutEvent.getReason() == Reason.AckNotReceived) {
			final TransactionApplicationData tad = (TransactionApplicationData) dialog.getApplicationData();
			if(tad != null && tad.getSipServletMessage() != null) {
				// https://github.com/RestComm/sip-servlets/issues/107 guard against NPEon concurrent cleanup
				final SipServletMessageImpl sipServletMessage = tad.getSipServletMessage();
				final MobicentsSipSessionKey sipSessionKey = sipServletMessage.getSipSessionKey();
				final MobicentsSipSession sipSession = sipServletMessage.getSipSession();
				getAsynchronousExecutor().execute(new Runnable() {
					public void run() {
						if(logger.isDebugEnabled()) {
							logger.info("Running process dialog timeout " + dialog + " reason => " + timeoutEvent.getReason());
						}
						try {
							if(sipSession != null) {
								SipContext sipContext = findSipApplication(sipSessionKey.getApplicationName());
								//the context can be null if the server is being shutdown
								if(sipContext != null) {
									MobicentsSipApplicationSession sipApplicationSession = sipSession.getSipApplicationSession();
									try {
										sipContext.enterSipApp(sipApplicationSession, sipSession, false, true);
										checkForAckNotReceived(sipServletMessage);
										checkForPrackNotReceived(sipServletMessage);
									} finally {
										sipContext.exitSipApp(sipApplicationSession, sipSession);
									}
									// Issue 1822 http://code.google.com/p/mobicents/issues/detail?id=1822
									// don't delete the dialog so that the app can send the BYE even after the noAckReceived has been called
									//								dialog.delete();
									tryToInvalidateSession(sipSessionKey, false);
								}
							}
							tad.cleanUp();
							tad.cleanUpMessage();
							dialog.setApplicationData(null);
						} catch (Exception e) {
							logger.error("Problem handling dialog timeout", e);
						}
					}
				});
			} else{
				dialog.setApplicationData(null);
			}
		} else {
			dialog.setApplicationData(null);
		}
	}
549784
@Deprecated
  public AtomixClusterBuilder withReachabilityTimeout(Duration timeout) {
    GroupMembershipProtocolConfig protocolConfig = config.getProtocolConfig();
    if (protocolConfig instanceof HeartbeatMembershipProtocolConfig) {
      ((HeartbeatMembershipProtocolConfig) protocolConfig).setFailureTimeout(timeout);
    }
    return this;
  }
254790
private static void applyTimeout(FrameworkMethod method) {
        // if default test timeout is defined
        if (LifecycleHooks.getConfig().containsKey(JUnitSettings.TEST_TIMEOUT.key())) {
            // get default test timeout
            long defaultTimeout = LifecycleHooks.getConfig().getLong(JUnitSettings.TEST_TIMEOUT.key());
            // get @Test annotation
            Test annotation = method.getAnnotation(Test.class);
            // if annotation declared and current timeout is less than default
            if ((annotation != null) && (annotation.timeout() < defaultTimeout)) {
                // set test timeout interval
                MutableTest.proxyFor(method.getMethod()).setTimeout(defaultTimeout);
            }
        }
    }
1161547
public static int waitForWithTimeout(final Process p, long timeout, TimeUnit unit)
      throws TimeoutException {

    ProcessThread t = new ProcessThread(p);
    t.start();
    try {
      unit.timedJoin(t, timeout);

    } catch (InterruptedException e) {
      t.interrupt();
      Thread.currentThread().interrupt();
    }

    if (!t.hasFinished()) {
      throw new TimeoutException("Process did not finish within timeout");
    }

    return t.exitValue();
  }
1043392
@Override
    public IPromise timeoutIn(long millis) {
        final Actor actor = Actor.sender.get();
        if ( actor != null )
            actor.delayed(millis, ()-> timedOut(Timeout.INSTANCE));
        else {
            Actors.delayedCalls.schedule( new TimerTask() {
                @Override
                public void run() {
                    timedOut(Timeout.INSTANCE);
                }
            },millis);
        }
        return this;
    }
651871
public void onTimerEvent(TimerEvent event, ActivityContextInterface aci) {
		// detaching so the null AC is claimed after the event handling
		aci.detach(sbbContext.getSbbLocalObject());
		try {
			DataSourceChildSbbLocalInterface child = (DataSourceChildSbbLocalInterface) getLocationChildRelation().create();
			child.getBindings(getSender().getURI().toString());
		} catch (Exception e) {
			tracer.severe("failed to create sip registrar child sbb, to lookup the sender's contacts",e);
			return;
		}
	}
840292
public ConverterServerBuilder processTimeout(long processTimeout, TimeUnit timeUnit) {
        assertNumericArgument(processTimeout, false);
        this.processTimeout = timeUnit.toMillis(processTimeout);
        return this;
    }
48354
public static void openDialogInWindow(final I_Callback callback, String windowCaption) {

        final Window window = CmsBasicDialog.prepareWindow();
        window.setCaption(windowCaption);
        CmsSiteSelectDialog dialog = new CmsSiteSelectDialog();
        window.setContent(dialog);
        dialog.setCallback(new I_Callback() {

            public void onCancel() {

                window.close();
                callback.onCancel();

            }

            public void onSiteSelect(String site) {

                window.close();
                callback.onSiteSelect(site);
            }
        });
        A_CmsUI.get().addWindow(window);
    }
1101007
@Override
  public void onTimeout()
  {
    try {
      //request().sendError(WebRequest.INTERNAL_SERVER_ERROR);
      if (true) throw new UnsupportedOperationException();
    } catch (Exception e) {
      log.log(Level.FINEST, e.toString(), e);
    }
    
    closeResponse();
  }
672539
public ZooKeeperUpdatingListenerBuilder sessionTimeout(Duration sessionTimeout) {
        requireNonNull(sessionTimeout, "sessionTimeout");
        checkArgument(!sessionTimeout.isZero() && !sessionTimeout.isNegative(),
                      "sessionTimeout: %s (expected: > 0)", sessionTimeout);
        return sessionTimeoutMillis(sessionTimeout.toMillis());
    }
360213
public static Timer setTimeout(int milliseconds, TimerCallback callback) {
		TimeoutTimer timeout = new TimeoutTimer(); 
		timeout.setId(nativeSetTimeout(milliseconds, callback, timeout));
		return timeout;
	}
334082
public void processEvent(EventObject event) // for asynchronous
  // (nonblocking) response
  // handling
  {
    synchronized (this) {
    } // wail til message sending has finished (transaction attribute set)

    if (event instanceof ResponseEvent) {
      processResponse((ResponseEvent) event);
    } else if (event instanceof TimeoutEvent) {
      processTimeout((TimeoutEvent) event);
    }

    // note, requests don't come through here, they are handled via the
    // listen/waitFor methods.
  }
361114
public void processRequest(RequestEvent requestEvent) {
		final SipProvider sipProvider = (SipProvider)requestEvent.getSource();
		ServerTransaction requestTransaction =  requestEvent.getServerTransaction();
		final Dialog dialog = requestEvent.getDialog();
		if(logger.isDebugEnabled()) {
			logger.debug("processRequest - dialog=" + dialog);
			if (dialog != null){
				logger.debug("processRequest - dialog.getDialogId()=" + dialog.getDialogId());
			}
		}
		final Request request = requestEvent.getRequest();
		// self routing makes the application data cloned, so we make sure to nullify it
		((MessageExt)request).setApplicationData(null);
		final String requestMethod = request.getMethod();

		final RouteHeader routeHeader = (RouteHeader) request
				.getHeader(RouteHeader.NAME);

		// congestion control is done here only if we drop messages to avoid generating STX
		if(CongestionControlPolicy.DropMessage.equals(congestionControlPolicy) && controlCongestion(request, null, dialog, routeHeader, sipProvider)) {
			return;
		}

		if((rejectSipMessages || memoryToHigh) && CongestionControlPolicy.DropMessage.equals(congestionControlPolicy)) {
			String method = requestEvent.getRequest().getMethod();
			boolean goodMethod = method.equals(Request.ACK) || method.equals(Request.PRACK) || method.equals(Request.BYE) || method.equals(Request.CANCEL) || method.equals(Request.UPDATE) || method.equals(Request.INFO);
			if(logger.isDebugEnabled()) {
				logger.debug("congestion control good method " + goodMethod + ", dialog "  + dialog + " routeHeader " + routeHeader);
			}
			if(!goodMethod) {
				if(dialog == null && (routeHeader == null || ((Parameters)routeHeader.getAddress().getURI()).getParameter(MessageDispatcher.RR_PARAM_PROXY_APP) == null)) {
					logger.error("dropping request, memory is too high or too many messages present in queues");
					return;
				}
			}
		}

		try {
			if(logger.isDebugEnabled()) {
				logger.debug("sipApplicationDispatcher " + this + ", Got a request event "  + request.toString());
			}
			if (!Request.ACK.equals(requestMethod) && requestTransaction == null ) {
				try {
					//folsson fix : Workaround broken Cisco 7940/7912
				    if(request.getHeader(MaxForwardsHeader.NAME) == null){
					    request.setHeader(SipFactoryImpl.headerFactory.createMaxForwardsHeader(70));
					}
				    requestTransaction = sipProvider.getNewServerTransaction(request);
				    JainSipUtils.setTransactionTimers(((TransactionExt)requestTransaction), this);
				} catch ( TransactionUnavailableException tae) {
					logger.error("cannot get a new Server transaction for this request " + request, tae);
					// Sends a 500 Internal server error and stops processing.
					MessageDispatcher.sendErrorResponse(this, Response.SERVER_INTERNAL_ERROR, requestTransaction, request, sipProvider);
	                return;
				} catch ( TransactionAlreadyExistsException taex ) {
					// This is a retransmission so just return.
					return;
				}
			}
			final ServerTransaction transaction = requestTransaction;

			if(logger.isDebugEnabled()) {
				logger.debug("ServerTx ref "  + transaction);
				logger.debug("Dialog ref "  + dialog);
			}

			final SipServletRequestImpl sipServletRequest = (SipServletRequestImpl) sipFactoryImpl.getMobicentsSipServletMessageFactory().createSipServletRequest(
						request,
						null,
						transaction,
						dialog,
						JainSipUtils.DIALOG_CREATING_METHODS.contains(requestMethod));
			updateRequestsStatistics(request, true);

			if(logger.isDebugEnabled()) {
				logger.debug("processRequest - routing state=" + sipServletRequest.getRoutingState());
			}

			// Check if the request is meant for me. If so, strip the topmost
			// Route header.

			//Popping the router header if it's for the container as
			//specified in JSR 289 - Section 15.8
			if(!isRouteExternal(routeHeader)) {
				if(logger.isDebugEnabled()) {
					logger.debug("processRequest - not external - =routeHeader" + routeHeader);
				}
				request.removeFirst(RouteHeader.NAME);
				sipServletRequest.setPoppedRoute(routeHeader);
				final Parameters poppedAddress = (Parameters)routeHeader.getAddress().getURI();
				if(poppedAddress.getParameter(MessageDispatcher.RR_PARAM_PROXY_APP) != null ||
						// Issue 2850 :	Use Request-URI custom Mobicents parameters to route request for misbehaving agents, workaround for Cisco-SIPGateway/IOS-12.x user agent
						(request.getRequestURI() instanceof javax.sip.address.SipURI && ((Parameters)request.getRequestURI()).getParameter(MessageDispatcher.RR_PARAM_PROXY_APP) != null)) {
					if(logger.isDebugEnabled()) {
						logger.debug("the request is for a proxy application, thus it is a subsequent request ");
					}
					sipServletRequest.setRoutingState(RoutingState.SUBSEQUENT);
				}
				if(transaction != null) {
					if(logger.isDebugEnabled()) {
						logger.debug("processRequest - transaction not null, transaction.getDialog()=" + transaction.getDialog());
						if (transaction.getDialog() != null){
							logger.debug("processRequest - transaction dialog not null, transaction.getDialog().getDialogId()=" + transaction.getDialog().getDialogId());
						}
					}
					TransactionApplicationData transactionApplicationData = (TransactionApplicationData)transaction.getApplicationData();
					if(transactionApplicationData != null && transactionApplicationData.getInitialPoppedRoute() == null) {
						if (transaction.getDialog() != null){
							logger.debug("processRequest - setInitialPoppedRoute, routeHeader.getAddress()=" + routeHeader.getAddress());
						}
						transactionApplicationData.setInitialPoppedRoute(new AddressImpl(routeHeader.getAddress(), null, ModifiableRule.NotModifiable));
					}
				}
			}
			if(logger.isDebugEnabled()) {
				logger.debug("Routing State " + sipServletRequest.getRoutingState());
			}

			try {
				// congestion control is done here so that the STX is created and a response can be generated back
				// and that
				if(controlCongestion(request, sipServletRequest, dialog, routeHeader, sipProvider)) {
					return;
				}

				if(logger.isDebugEnabled()) {
					logger.debug("processRequest - dispatching request with sipServletRequest.getAppSessionId()=" + sipServletRequest.getAppSessionId());
				}

				messageDispatcherFactory.getRequestDispatcher(sipServletRequest, this).
					dispatchMessage(sipProvider, sipServletRequest);
			} catch (DispatcherException e) {
				// Change log level from Error to debug: https://github.com/RestComm/jain-sip/issues/116
				if (logger.isDebugEnabled()) {
					logger.debug("Unexpected exception while processing request " + request,e);
				}
				// Sends an error response if the subsequent request is not an ACK (otherwise it violates RF3261) and stops processing.
				if(!Request.ACK.equalsIgnoreCase(requestMethod)) {
					MessageDispatcher.sendErrorResponse(this, e.getErrorCode(), sipServletRequest, sipProvider);
				}
				return;
			} catch (Throwable e) {
				// Change log level from Error to debug: https://github.com/RestComm/jain-sip/issues/116
				if (logger.isDebugEnabled()) {
					logger.debug("Unexpected exception while processing request " + request,e);
				}
				// Sends a 500 Internal server error if the subsequent request is not an ACK (otherwise it violates RF3261) and stops processing.
				if(!Request.ACK.equalsIgnoreCase(requestMethod)) {
					MessageDispatcher.sendErrorResponse(this, Response.SERVER_INTERNAL_ERROR, sipServletRequest, sipProvider);
				}
				return;
			}
		} catch (Throwable e) {
			// Change log level from Error to debug: https://github.com/RestComm/jain-sip/issues/116
			if (logger.isDebugEnabled()) {
				logger.debug("Unexpected exception while processing request " + request,e);
			}
			// Sends a 500 Internal server error if the subsequent request is not an ACK (otherwise it violates RF3261) and stops processing.
			if(!Request.ACK.equalsIgnoreCase(request.getMethod())) {
				MessageDispatcher.sendErrorResponse(this, Response.SERVER_INTERNAL_ERROR, requestTransaction, request, sipProvider);
			}
			return;
		}
	}
472171
public void processDialogTerminated(DialogTerminatedEvent dte) {
		final Dialog d = dte.getDialog();
		if (d!= null) {
			DialogWrapper dw = getDialogWrapper(d);
			if (dw != null) {
				processDialogTerminated(dw);
			} else {
				if (tracer.isFineEnabled()) {
					tracer.fine("DialogTerminatedEvent dropped due to null app data.");
				}
			}
		}
	}
773308
private void setQueryTimeout(final Statement statement, final int timeoutSec)
   {
      if (isQueryTimeoutSupported != FALSE) {
         try {
            statement.setQueryTimeout(timeoutSec);
            isQueryTimeoutSupported = TRUE;
         }
         catch (Exception e) {
            if (isQueryTimeoutSupported == UNINITIALIZED) {
               isQueryTimeoutSupported = FALSE;
               logger.info("{} - Failed to set query timeout for statement. ({})", poolName, e.getMessage());
            }
         }
      }
   }
1200100
@Override
  public void onTimer(String timerName) {
    if (timerName.equals(IDLE_SESSION_TIMER_NAME)) {
      checkIdleAppSession();
    }
    else if (timerName.equals(TIMER_NAME_TS)) {
      try {
        sendAndStateLock.lock();
        sessionData.setTsTimerId(null);
        handleEvent(new Event(TIMEOUT_EXPIRES, null));
      }
      catch (Exception e) {
        logger.debug("Can not handle event", e);
      }
      finally {
        sendAndStateLock.unlock();
      }
    }
    else {
      logger.warn("Received an unknown timer '{}' for Session-ID '{}'", timerName, getSessionId());
    }
  }
457985
public void processResponse(ResponseEvent responseEvent) {
				
		final ResponseEventExt responseEventExt = (ResponseEventExt)responseEvent;
		
		if (responseEventExt.isRetransmission() && responseEventExt.getDialog() != null) {
			if (tracer.isInfoEnabled()) {
				tracer.info("Dropping in dialog retransmission. Response:\n"+responseEventExt.getResponse());
			}
			return;
		}		
		
		if(responseEventExt.isForkedResponse()) {
			processResponseEventForked(responseEventExt);	 			
		}
		else {
			processResponseEventNotForked(responseEventExt);
		}		
	}