text:
#include "DumUserAgent.hxx"
#include "tfm/PortAllocator.hxx"
#include "tfm/SequenceSet.hxx"
#include "tfm/ActionBase.hxx"
#include "tfm/TestProxy.hxx"

#include "DumEvent.hxx"
#include "DumExpect.hxx"
#include "DumUaAction.hxx"

#include "BindHandle.hxx"
#include "ClientSubscriptionEvent.hxx"
#include "ServerOutOfDialogReqEvent.hxx"
#include "ClientOutOfDialogReqEvent.hxx"
#include "TestClientSubscription.hxx"
#include "TestServerSubscription.hxx"
#include "TestServerOutOfDialogReq.hxx"
#include "TestClientPagerMessage.hxx"
#include "TestServerPagerMessage.hxx"
#include "tfm/EndPoint.hxx"
#include "ClientRegistrationEvent.hxx"
#include "InviteSessionEvent.hxx"
#include "ClientPagerMessageEvent.hxx"
#include "ServerPagerMessageEvent.hxx"
#include "DialogEventHandlerEvent.hxx"

#include "resip/dum/AppDialogSet.hxx"
#include "resip/dum/AppDialogSetFactory.hxx"
#include "resip/dum/ClientAuthManager.hxx"
#include "resip/dum/ClientRegistration.hxx"
#include "resip/dum/DialogUsageManager.hxx"
#include "resip/dum/UserProfile.hxx"
#include "resip/dum/MasterProfile.hxx"
#include "resip/stack/SipMessage.hxx"
#include "resip/stack/SdpContents.hxx"

#include <boost/bind.hpp>
#include <boost/function.hpp>

#include "rutil/Random.hxx"
#include "rutil/Logger.hxx"

#define RESIPROCATE_SUBSYSTEM resip::Subsystem::TEST

using namespace resip;

template<class C, class E> void
dispatchEventHelper(E* event, C& container)
{
   StackLog(<<"dispatchEventHelper: " << *event << " looking through: " << Inserter(container));
   for (typename C::iterator it = container.begin(); it != container.end(); ++it)
   {
      if ((*it)->isMyEvent(event))
      {
         (*it)->handleEvent(event);
         return;
      }
   }

   ErrLog(<< "No matching endpoint for event " << typeid(*event).name());
   assert(0);
   throw TestEndPoint::GlobalFailure("No matching endpoint for the event", __FILE__, __LINE__);
}

resip::SharedPtr<resip::MasterProfile>
DumUserAgent::makeProfile(const resip::Uri& aor, const Data& password)
{
   resip::SharedPtr<resip::MasterProfile> profile(new MasterProfile);

   //profile->addAllowedEvent(resip::Token("conference"));
   profile->validateAcceptEnabled() = false;
   profile->validateContentEnabled() = false;
   profile->setDefaultFrom(NameAddr(aor));
   profile->setUserAgent("dum/tfm");
   profile->setDigestCredential(aor.host(), aor.user(), aor.password());
   profile->setInstanceId(resip::Random::getRandomHex(4));
   profile->gruuEnabled() = true;

   return profile;
}

const resip::NameAddr&
DumUserAgent::getAor() const
{
   return getProfile()->getDefaultFrom();
}

ExpectAction* DumUserAgent::setOfferToProvideInNextOnAnswerCallback(boost::shared_ptr<resip::SdpContents> offer)
{
   mOfferToProvideInNextOnAnswerCallback = offer;
   return new NoAction();
}

// DumUaAction*
// DumUserAgent::start()
// {
//    return new Start(*this);
// }

DumUaAction*
DumUserAgent::shutdownUa()
{
   return new Shutdown(*this);
}

void
DumUserAgent::clean()
{
   mTestUsages.clear();
   getDum().createDialogEventStateManager(0);
   //clear out handles/etc here
}

DumUserAgent::DumUserAgent(resip::SharedPtr<resip::MasterProfile> profile) :
   mProfile(profile),
   mDum(mStack, true),
   mTestProxy(0),
   mAppDialogSet(0),
   mNatNavigator(false),
   mStunAddr(),
   mStunPort(0),
   mLocalPort(0)
{
   registerWithTransportDriver();
}

DumUserAgent::DumUserAgent(resip::SharedPtr<resip::MasterProfile> profile,
                           TestProxy* proxy) :
   mProfile(profile),
   mDum(mStack, true),
   mTestProxy(proxy),
   mAppDialogSet(0),
   mNatNavigator(false),
   mStunAddr(),
   mStunPort(0),
   mLocalPort(0)
{
   proxy->addUser(mProfile->getDefaultFrom().uri().user(),
                  mProfile->getDefaultFrom().uri(),
                  mProfile->getDigestCredential(mProfile->getDefaultFrom().uri().host()).password);
   registerWithTransportDriver();
}

DumUserAgent::~DumUserAgent()
{
   if(mTestProxy)
   {
      mTestProxy->deleteUser(mProfile->getDefaultFrom().uri().user(),
                             mProfile->getDefaultFrom().uri());
   }
   unregisterFromTransportDriver();
}

void
DumUserAgent::init()
{
   mIp = PortAllocator::getNextLocalIpAddress();
   mPort = PortAllocator::getNextPort();
   if( !mNatNavigator )
   {
      mDum.addTransport(resip::UDP, mPort, resip::V4, mIp);
   }
   mDum.addTransport(resip::TCP, mPort, resip::V4, mIp);

   mProfile->setFixedTransportInterface(mIp);

   mProfile->addSupportedMethod(SUBSCRIBE);
   mProfile->addSupportedMethod(NOTIFY);
   mProfile->addSupportedMethod(INFO);
   mProfile->addSupportedMethod(MESSAGE);
   mProfile->addSupportedMethod(REFER);
   mProfile->addSupportedMethod(PRACK);

   mDum.setMasterProfile(mProfile);

   mDum.setClientRegistrationHandler(this);

   mDum.setDialogSetHandler(this);
   //mDum.addServerSubscriptionHandler("presence", this);
   //mDum.addClientSubscriptionHandler("presence", this);
   //mDum.addClientSubscriptionHandler("message-summary", this);
   //mDum.addServerSubscriptionHandler("message-summary", this);
   mDum.setInviteSessionHandler(this);

   std::auto_ptr<resip::ClientAuthManager> clam(new resip::ClientAuthManager());
   mDum.setClientAuthManager(clam);

   //!dcm! -- use TestAP/dumv2 pattern
//   mDum.addOutOfDialogHandler(REFER, this);
}

void
DumUserAgent::addClientSubscriptionHandler(const Data& eventType, ClientSubscriptionHandler* h)
{
   mDum.addClientSubscriptionHandler(eventType, h);
}

void
DumUserAgent::addServerSubscriptionHandler(const Data& eventType, ServerSubscriptionHandler* h)
{
   mDum.addServerSubscriptionHandler(eventType, h);
}

void
DumUserAgent::addClientPublicationHandler(const Data& eventType, ClientPublicationHandler* h)
{
   mDum.addClientPublicationHandler(eventType, h);
}

void
DumUserAgent::addServerPublicationHandler(const Data& eventType, ServerPublicationHandler* h)
{
   mDum.addServerPublicationHandler(eventType, h);
}

void
DumUserAgent::addClientPagerMessageHandler(ClientPagerMessageHandler* h)
{
   mDum.setClientPagerMessageHandler(h);
}

void
DumUserAgent::addServerPagerMessageHandler(ServerPagerMessageHandler* h)
{
   mDum.setServerPagerMessageHandler(h);
}

void
DumUserAgent::addOutOfDialogHandler(MethodTypes methodType, OutOfDialogHandler* h)
{
   mDum.addOutOfDialogHandler(methodType, h);
}

void
DumUserAgent::addSupportedOptionTag(const Token& tag)
{
   mDum.getMasterProfile()->addSupportedOptionTag(tag);
}

void
DumUserAgent::setOutboundProxy(const Uri& proxy)
{
   mDum.getMasterProfile()->setOutboundProxy(proxy);
}

void
DumUserAgent::unsetOutboundProxy()
{
   mDum.getMasterProfile()->unsetOutboundProxy();
}

void
DumUserAgent::setDefaultFrom(const Uri& from)
{
   mDum.getMasterProfile()->setDefaultFrom(NameAddr(from));
}

ClientPagerMessageHandle
DumUserAgent::makePagerMessage(const resip::NameAddr& target)
{
   return mDum.makePagerMessage(target);
}

// void
// DumUserAgent::stop()
// {
// //    mStackThread.shutdown();
// //    shutdown();
// }

void
DumUserAgent::buildFdSet(resip::FdSet& fdset)
{
   mStack.buildFdSet(fdset);
}

void
DumUserAgent::process(resip::FdSet& fdset)
{
   mStack.process(fdset);
   try
   {
      while(mDum.process());
   }
   catch (BaseException& e)
   {
      WarningLog (<< "Unhandled exception: " << e);

      // should cause the test to fail
      assert(0);
   }
}

const Data&
DumUserAgent::getInstanceId() const
{
   return mProfile->getInstanceId();
}

resip::Uri
DumUserAgent::getContact() const
{
   Uri localContact = getProfile()->getDefaultFrom().uri();
   localContact.host() = getIp();
   localContact.port() = getPort();
   return localContact;
}

resip::Data
DumUserAgent::getName() const
{
   return mProfile->getDefaultFrom().uri().getAor();
}

/*
void
DumUserAgent::handleEvent(Event* eventRaw)
{
   boost::shared_ptr<Event> event(eventRaw);
   DebugLog(<< "DumUserAgent::handeEvent: " << *eventRaw);
   if (getSequenceSet())
   {
      getSequenceSet()->enqueue(event);
   }
   else
   {
      WarningLog(<< *this << " has no associated SequenceSet: discarding event " << *event);
   }
}
*/

DumUaAction*
DumUserAgent::invite(const NameAddr& target,
                     const SdpContents* initialOffer,
                     const SdpContents* alternative,
                     DialogUsageManager::EncryptionLevel level)
{
  resip::SharedPtr<resip::SipMessage> (resip::DialogUsageManager::*fn)(const NameAddr&, const Contents*, DialogUsageManager::EncryptionLevel, const Contents*, AppDialogSet*) = &resip::DialogUsageManager::makeInviteSession;
  return new DumUaSendingCommand(this, boost::bind(fn, boost::ref(mDum),
                                                   target, initialOffer, level, alternative, (AppDialogSet*)0));
}

DumUaAction*
DumUserAgent::inviteFromRefer(const resip::SipMessage& refer,
                              resip::ServerSubscriptionHandle& h,
                              const resip::SdpContents* initialOffer,
                              resip::DialogUsageManager::EncryptionLevel level,
                              const resip::SdpContents* alternative)
{
  return new DumUaSendingCommand(this, boost::bind(&resip::DialogUsageManager::makeInviteSessionFromRefer, boost::ref(mDum),
                                                   boost::ref(refer), boost::ref(h), initialOffer, level, alternative, (AppDialogSet*)0));
}

DumUaAction*
DumUserAgent::subscribe(const NameAddr& target, const Data& eventType)
{
   return new DumUaSendingCommand(this, boost::bind(&resip::DialogUsageManager::makeSubscription, boost::ref(mDum),
                                                    target, eventType, (AppDialogSet*)0));
}

DumUaAction*
DumUserAgent::publish(const resip::NameAddr& target, const resip::Contents& body,
                      const resip::Data& eventType, unsigned expiresSeconds)
{
   return new DumUaSendingCommand(this, boost::bind(&resip::DialogUsageManager::makePublication, boost::ref(mDum),
                                                    target, boost::ref(body), eventType, expiresSeconds, (AppDialogSet*)0));
}

DumUaAction*
DumUserAgent::registerUa(bool tcp)
{
   NameAddr& target = mDum.getMasterUserProfile()->getDefaultFrom();
   if (tcp)
   {
      target.uri().param(resip::p_transport) = "tcp";
   }

   return new DumUaSendingCommand(this, boost::bind(&resip::DialogUsageManager::makeRegistration, boost::ref(mDum),
                                                    target, (AppDialogSet*)0));
}

DumUaAction*
DumUserAgent::send(resip::SharedPtr<resip::SipMessage> msg)
{
   return new DumUaCommand(this, boost::bind(&resip::DialogUsageManager::send, boost::ref(mDum), msg));
}

DumUaAction*
DumUserAgent::cancelInvite()
{
   assert(mAppDialogSet);
   return new DumUaCommand(this, boost::bind(&resip::AppDialogSet::end, mAppDialogSet));
}

DumUaAction*
DumUserAgent::refer(const resip::NameAddr& target, const resip::NameAddr& referTo)
{
   return new DumUaSendingCommand(this, boost::bind(&resip::DialogUsageManager::makeRefer, boost::ref(mDum), target, referTo, (AppDialogSet*)0));
}

DumUaAction*
DumUserAgent::referNoReferSub(const resip::NameAddr& target, const resip::NameAddr& referTo)
{
   ReferAdornment* adorner = new ReferAdornment(referTo);
   return new DumUaSendingCommand(this, boost::bind(&resip::DialogUsageManager::makeOutOfDialogRequest, boost::ref(mDum), target, REFER, (AppDialogSet*)0), adorner);
}

DumUaAction*
DumUserAgent::referNoReferSubWithoutReferSubHeader(const resip::NameAddr& target, const resip::NameAddr& referTo)
{
   ReferAdornmentRemoveReferSubHeader* adorner = new ReferAdornmentRemoveReferSubHeader(referTo);
   return new DumUaSendingCommand(this, boost::bind(&resip::DialogUsageManager::makeOutOfDialogRequest, boost::ref(mDum), target, REFER, (AppDialogSet*)0), adorner);
}

// ClientRegistrationHandler
void
DumUserAgent::onSuccess(resip::ClientRegistrationHandle h, const resip::SipMessage& response)
{
   DebugLog(<< "ClientRegistrationHandler::onSuccess");
   handleEvent(new ClientRegistrationEvent(this, Register_Success, h, response));
}

void
DumUserAgent::onRemoved(resip::ClientRegistrationHandle h, const resip::SipMessage& response)
{
   DebugLog(<< "ClientRegistrationHandler::onRemoved");
   handleEvent(new ClientRegistrationEvent(this, Register_Removed, h, response));
}

void
DumUserAgent::onFailure(resip::ClientRegistrationHandle h, const resip::SipMessage& response)
{
   DebugLog(<< "ClientRegistrationHandler::onFailure");
   handleEvent(new ClientRegistrationEvent(this, Register_Failure, h, response));
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(ClientRegistrationEvent::Type t,
                      MessageMatcher* matcher,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<ClientRegistrationEvent>(t),
                        matcher,
                        *TestEndPoint::AlwaysTruePred,
                        timeoutMs,
                        expectAction);
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(ClientRegistrationEvent::Type t,
                     TestClientRegistration& clientReg,
                     MessageMatcher* matcher,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<ClientRegistrationEvent>(t),
                        matcher,
                        *TestEndPoint::AlwaysTruePred,
                        timeoutMs,
                        expectAction,
                        new BindHandle<ClientRegistrationEvent>(this, "BindClientRegistrationHandle", clientReg.getHandleRef()));
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(ClientRegistrationEvent::Type t,
                     TestClientRegistration& clientReg,
                     MessageMatcher* matcher,
                     ExpectPreCon& pred,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<ClientRegistrationEvent>(t),
                        matcher,
                        pred,
                        timeoutMs,
                        expectAction,
                        new BindHandle<ClientRegistrationEvent>(this, "BindClientRegistrationHandle", clientReg.getHandleRef()));
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(ClientRegistrationEvent::Type t,
                     TestClientRegistration& clientReg,
                     ExpectPreCon& pred,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<ClientRegistrationEvent>(t),
                        0,
                        pred,
                        timeoutMs,
                        expectAction,
                        new BindHandle<ClientRegistrationEvent>(this, "BindClientRegistrationHandle", clientReg.getHandleRef()));
}

// InviteSessionHandler
void
DumUserAgent::onNewSession(ClientInviteSessionHandle h, InviteSession::OfferAnswerType oat, const SipMessage& msg)
{
   DebugLog(<< "onNewSession - client");
   handleEvent(new ClientInviteEvent(this, Invite_NewClientSession, h, msg));
}

void
DumUserAgent::onNewSession(ServerInviteSessionHandle h, InviteSession::OfferAnswerType oat, const SipMessage& msg)
{
   DebugLog(<< "onNewSession - server");
   handleEvent(new ServerInviteEvent(this, Invite_NewServerSession, h, msg));
}

void
DumUserAgent::onFailure(ClientInviteSessionHandle h, const SipMessage& msg)
{
   DebugLog(<< "onFailure");
   handleEvent(new ClientInviteEvent(this, Invite_Failure, h, msg));
}

void
DumUserAgent::onEarlyMedia(ClientInviteSessionHandle h, const SipMessage& msg, const SdpContents& sdp)
{
   DebugLog(<< "onEarlyMedia");
   handleEvent(new ClientInviteEvent(this, Invite_EarlyMedia, h, msg));
}

void
DumUserAgent::onProvisional(ClientInviteSessionHandle h, const SipMessage& msg)
{
   DebugLog(<< "onProvisional");
   handleEvent(new ClientInviteEvent(this, Invite_Provisional, h, msg));
}

void
DumUserAgent::onStaleCallTimeout(ClientInviteSessionHandle h)
{
   DebugLog(<< "onStaleCallTimeout");
   handleEvent(new ClientInviteEvent(this, Invite_StaleCallTimeout, h));
}

void
DumUserAgent::onConnected(ClientInviteSessionHandle h, const SipMessage& msg)
{
   DebugLog(<< "onConnected - client");
   handleEvent(new ClientInviteEvent(this, Invite_Connected, h, msg));
}

void
DumUserAgent::onConnected(InviteSessionHandle h, const SipMessage& msg)
{
   DebugLog(<< "onConnected");
   handleEvent(new InviteEvent(this, Invite_Connected, h, msg));
}

void
DumUserAgent::onTerminated(InviteSessionHandle h, InviteSessionHandler::TerminatedReason reason, const SipMessage* related)
{
   DebugLog(<< "onTerminated");
//   dispatchEvent(new InviteEvent(this, Invite_Terminated, h));
   handleEvent(new InviteEvent(this, Invite_Terminated, h));
}

void
DumUserAgent::onForkDestroyed(ClientInviteSessionHandle h)
{
   DebugLog(<< "onForkDestroyed");
   handleEvent(new ClientInviteEvent(this, Invite_ForkDestroyed, h));
}

void
DumUserAgent::onRedirected(ClientInviteSessionHandle h, const SipMessage& msg)
{
   DebugLog(<< "onRedirected");
   handleEvent(new ClientInviteEvent(this, Invite_Redirected, h, msg));
}

void
DumUserAgent::onAnswer(InviteSessionHandle h, const SipMessage& msg, const SdpContents&)
{
   DebugLog(<< "onAnswer");
   handleEvent(new InviteEvent(this, Invite_Answer, h, msg));
   if(mOfferToProvideInNextOnAnswerCallback.get())
   {
      DebugLog(<< "onAnswer - calling provideOffer from onAnswer callback");
      h->provideOffer(*mOfferToProvideInNextOnAnswerCallback);
      mOfferToProvideInNextOnAnswerCallback.reset();
   }
}

void
DumUserAgent::onOffer(InviteSessionHandle h, const SipMessage& msg, const SdpContents&)
{
   DebugLog(<< "onOffer");
   handleEvent(new InviteEvent(this, Invite_Offer, h, msg));
}

void
DumUserAgent::onRemoteSdpChanged(InviteSessionHandle h, const SipMessage& msg, const SdpContents&)
{
   DebugLog(<< "onRemoteSdpChanged");
   handleEvent(new InviteEvent(this, Invite_RemoteSdpChanged, h, msg));
}

void
DumUserAgent::onOfferRequestRejected(InviteSessionHandle h, const SipMessage& msg)
{
   DebugLog(<< "onOfferRequestRejected");
   handleEvent(new InviteEvent(this, Invite_OfferRequestRejected, h, msg));
}

void
DumUserAgent::onOfferRequired(InviteSessionHandle h, const SipMessage& msg)
{
   DebugLog(<< "onOfferRequired");
   handleEvent(new InviteEvent(this, Invite_OfferRequired, h, msg));
}

void
DumUserAgent::onOfferRejected(InviteSessionHandle h, const SipMessage* msg)
{
   DebugLog(<< "onOfferRejected");
   if( msg )
   {
      handleEvent(new InviteEvent(this, Invite_OfferRejected, h, *msg));
   }
   else
   {
      handleEvent(new InviteEvent(this, Invite_OfferRejected, h));
   }
}

void
DumUserAgent::onInfo(InviteSessionHandle h, const SipMessage& msg)
{
   DebugLog(<< "onInfo");
   handleEvent(new InviteEvent(this, Invite_Info, h, msg));
}

void
DumUserAgent::onInfoSuccess(InviteSessionHandle h, const SipMessage& msg)
{
   DebugLog(<< "onInfoSuccess");
   handleEvent(new InviteEvent(this, Invite_InfoSuccess, h, msg));
}

void
DumUserAgent::onInfoFailure(InviteSessionHandle h, const SipMessage& msg)
{
   DebugLog(<< "onInfoFailure");
   handleEvent(new InviteEvent(this, Invite_InfoFailure, h, msg));
}

void
DumUserAgent::onMessage(InviteSessionHandle h, const SipMessage& msg)
{
   DebugLog(<< "onMessage");
   handleEvent(new InviteEvent(this, Invite_Message, h, msg));
}

void
DumUserAgent::onMessageSuccess(InviteSessionHandle h, const SipMessage& msg)
{
   DebugLog(<< "onMessageSuccess");
   handleEvent(new InviteEvent(this, Invite_MessageSuccess, h, msg));
}

void
DumUserAgent::onMessageFailure(InviteSessionHandle h, const SipMessage& msg)
{
   DebugLog(<< "onMessageFailure");
   handleEvent(new InviteEvent(this, Invite_MessageFailure, h, msg));
}

void
DumUserAgent::onRefer(InviteSessionHandle h, ServerSubscriptionHandle serverSubHandle, const SipMessage& msg)
{
   DebugLog(<< "onRefer");
   InviteEvent* event = new InviteEvent(this, Invite_Refer, h, msg, serverSubHandle);
   TestUsage* usage = findUsage(event);
   assert(usage);
   static_cast<TestInviteSession*>(usage)->setServerSubscription(serverSubHandle);
   static_cast<TestInviteSession*>(usage)->setReferMessage(msg);
   handleEvent(event);
}

void
DumUserAgent::onReferNoSub(InviteSessionHandle h, const SipMessage& msg)
{
   DebugLog(<< "onReferNoSub");
   InviteEvent event(this, Invite_Refer, h, msg);
   TestUsage* usage = findUsage(&event);
   assert(usage);
   static_cast<TestInviteSession*>(usage)->setReferMessage(msg);
   handleEvent(new InviteEvent(this, Invite_ReferNoSub, h, msg));
}

void
DumUserAgent::onReferRejected(InviteSessionHandle h, const SipMessage& msg)
{
   DebugLog(<< "onReferRejected");
   handleEvent(new InviteEvent(this, Invite_ReferRejected, h, msg));
}

void
DumUserAgent::onReferAccepted(InviteSessionHandle h, ClientSubscriptionHandle clientSubHandle, const SipMessage& msg)
{
   DebugLog(<< "onReferAccepted");
   handleEvent(new InviteEvent(this, Invite_ReferAccepted, h, msg, clientSubHandle));
}

// void
// DumUserAgent::onAckNotReceived(InviteSessionHandle h)
// {
//    handleEvent(new InviteEvent(this, Invite_AckNotReceived, h));
// }

void
DumUserAgent::onIllegalNegotiation(InviteSessionHandle h, const SipMessage& msg)
{
   DebugLog(<< "onIllegalNegotiation");
   handleEvent(new InviteEvent(this, Invite_IllegalNegotiation, h, msg));
}

void
DumUserAgent::onSessionExpired(InviteSessionHandle h)
{
   DebugLog(<< "onSessionExpired");
   handleEvent(new InviteEvent(this, Invite_SessionExpired, h));
}

void
DumUserAgent::onPrack(ServerInviteSessionHandle h, const SipMessage &msg)
{
   DebugLog(<< "onPrack");
   handleEvent(new ServerInviteEvent(this, Invite_Prack, h, msg));
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(InviteEvent::Type t,
                      MessageMatcher* matcher,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<InviteEvent>(t),
                        matcher,
                        *TestEndPoint::AlwaysTruePred,
                        timeoutMs,
                        expectAction);
 }

DumUserAgent::ExpectBase*
DumUserAgent::expect(InviteEvent::Type t,
                     TestClientInviteSession& clientInv,
                     MessageMatcher* matcher,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<InviteEvent>(t),
                        matcher,
                        *TestEndPoint::AlwaysTruePred,
                        timeoutMs,
                        expectAction,
                        new BindHandleInvite<ClientInviteEvent>(this, "BindClientInviteSessionHandle", clientInv.getHandleRef(), clientInv.getSessionHandleRef()));
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(InviteEvent::Type t,
                     TestClientInviteSession& clientInv,
                     MessageMatcher* matcher,
                     ExpectPreCon& pred,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<InviteEvent>(t),
                        matcher,
                        pred,
                        timeoutMs,
                        expectAction,
                        new BindHandleInvite<ClientInviteEvent>(this, "BindClientInviteSessionHandle", clientInv.getHandleRef(), clientInv.getSessionHandleRef()));
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(InviteEvent::Type t,
                     TestClientInviteSession& clientInv,
                     ExpectPreCon& pred,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<InviteEvent>(t),
                        0,
                        pred,
                        timeoutMs,
                        expectAction,
                        new BindHandleInvite<ClientInviteEvent>(this, "BindClientInviteSessionHandle", clientInv.getHandleRef(), clientInv.getSessionHandleRef()));
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(InviteEvent::Type t,
                     ExpectPreCon& pred,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<InviteEvent>(t),
                        0,
                        pred,
                        timeoutMs,
                        expectAction);
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(InviteEvent::Type t,
                     TestServerInviteSession& serverInv,
                     MessageMatcher* matcher,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<InviteEvent>(t),
                        matcher,
                        *TestEndPoint::AlwaysTruePred,
                        timeoutMs,
                        expectAction,
                        new BindHandleInvite<ServerInviteEvent>(this, "BindServerInviteSessionHandle", serverInv.getHandleRef(), serverInv.getSessionHandleRef()));
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(InviteEvent::Type t,
                     TestServerInviteSession& serverInv,
                     MessageMatcher* matcher,
                     ExpectPreCon& pred,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<InviteEvent>(t),
                        matcher,
                        pred,
                        timeoutMs,
                        expectAction,
                        new BindHandleInvite<ServerInviteEvent>(this, "BindServerInviteSessionHandle", serverInv.getHandleRef(), serverInv.getSessionHandleRef()));
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(InviteEvent::Type t,
                     TestServerInviteSession& serverInv,
                     ExpectPreCon& pred,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<InviteEvent>(t),
                        0,
                        pred,
                        timeoutMs,
                        expectAction,
                        new BindHandleInvite<ServerInviteEvent>(this, "BindServerInviteSessionHandle", serverInv.getHandleRef(), serverInv.getSessionHandleRef()));
}

/*
//actions from ClientPagerMessage
DumUaAction*
DumUserAgent::getMessageRequest()
{
   return new ClientPagerMessageAction(this, boost::bind(&resip::ClientPagerMessage::getMessageRequest, _1));
}

DumUaAction*
DumUserAgent::page(std::auto_ptr<resip::Contents> contents, resip::DialogUsageManager::EncryptionLevel level)
{
   // contents needs to outlive the boost::bind(...) to assure this to work.
   return new ClientPagerMessageAction(this, boost::bind(&resip::ClientPagerMessage::page, _1, boost::ref(contents), level));
}

DumUaAction*
DumUserAgent::endClientPagerMsg()
{
   return new ClientPagerMessageAction(this, boost::bind(&resip::ClientPagerMessage::end, _1));
}
*/

/*
//actions from ServerPagerMessage
DumUaAction*
DumUserAgent::acceptServerPagerMsg(int statusCode)
{
   return new ServerPagerMessageAction(this, boost::bind(&resip::ServerPagerMessage::accept, _1, statusCode), NoAdornment::instance());
}

DumUaAction*
DumUserAgent::rejectServerPagerMsg(int statusCode)
{
   return new ServerPagerMessageAction(this, boost::bind(&resip::ServerPagerMessage::reject, _1, statusCode), NoAdornment::instance());
}

DumUaAction*
DumUserAgent::endServerPagerMsg()
{
   return new ServerPagerMessageAction(this, boost::bind(&resip::ServerPagerMessage::end, _1));
}

DumUaAction*
DumUserAgent::sendServerPagerMsg(resip::SharedPtr<resip::SipMessage> msg)
{
   return new ServerPagerMessageAction(this, boost::bind(&resip::ServerPagerMessage::send, _1, msg));
}
*/

// ClientPublicationHandler
void
DumUserAgent::onSuccess(resip::ClientPublicationHandle h, const resip::SipMessage& msg)
{
   DebugLog(<< "onSuccess - ClientPublication");
   handleEvent(new ClientPublicationEvent(this, ClientPublication_Success, h, msg));
}

void
DumUserAgent::onRemove(resip::ClientPublicationHandle h, const resip::SipMessage& msg)
{
   DebugLog(<< "onRemove - ClientPublication");
   handleEvent(new ClientPublicationEvent(this, ClientPublication_Remove, h, msg));
}

void
DumUserAgent::onFailure(resip::ClientPublicationHandle h, const resip::SipMessage& msg)
{
   DebugLog(<< "onFailure - ClientPublication");
   handleEvent(new ClientPublicationEvent(this, ClientPublication_Failure, h, msg));
}

void
DumUserAgent::onStaleUpdate(resip::ClientPublicationHandle h, const resip::SipMessage& msg)
{
   DebugLog(<< "onStaleUpdate - ClientPublication");
   handleEvent(new ClientPublicationEvent(this, ClientPublication_StaleUpdate, h, msg));
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(ClientPublicationEvent::Type t,
                     TestClientPublication& clientPub,
                     MessageMatcher* matcher,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<ClientPublicationEvent>(t),
                        matcher,
                        *TestEndPoint::AlwaysTruePred,
                        timeoutMs,
                        expectAction,
                        new BindHandle<ClientPublicationEvent>(this, "BindClientPublicationHandle", clientPub.getHandleRef()));
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(ClientPublicationEvent::Type t,
                     TestClientPublication& clientPub,
                     MessageMatcher* matcher,
                     ExpectPreCon& pred,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<ClientPublicationEvent>(t),
                        matcher,
                        pred,
                        timeoutMs,
                        expectAction,
                        new BindHandle<ClientPublicationEvent>(this, "BindClientPublicationHandle", clientPub.getHandleRef()));
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(ClientPublicationEvent::Type t,
                     TestClientPublication& clientPub,
                     ExpectPreCon& pred,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<ClientPublicationEvent>(t),
                        0,
                        pred,
                        timeoutMs,
                        expectAction,
                        new BindHandle<ClientPublicationEvent>(this, "BindClientPublicationHandle", clientPub.getHandleRef()));
}

// ClientSubscriptionHandler
void
DumUserAgent::onUpdatePending(resip::ClientSubscriptionHandle h, const resip::SipMessage& notify, bool outOfOrder)
{
   DebugLog(<< "onUpdatePending");
   handleEvent(new ClientSubscriptionEvent(this, ClientSubscription_UpdatePending, h, &notify, outOfOrder));
}

void
DumUserAgent::onUpdateActive(resip::ClientSubscriptionHandle h, const resip::SipMessage& notify, bool outOfOrder)
{
   DebugLog(<< "onUpdateActive");
   handleEvent(new ClientSubscriptionEvent(this, ClientSubscription_UpdateActive, h, &notify, outOfOrder));
}

void
DumUserAgent::onUpdateExtension(resip::ClientSubscriptionHandle h, const resip::SipMessage& notify, bool outOfOrder)
{
   DebugLog(<< "onUpdateExtension");
   handleEvent(new ClientSubscriptionEvent(this, ClientSubscription_UpdateExtension, h, &notify, outOfOrder));
}

void
DumUserAgent::onTerminated(resip::ClientSubscriptionHandle h, const resip::SipMessage* msg)
{
   DebugLog(<< "ClientSubscriptionHandler::onTerminated");
   handleEvent(new ClientSubscriptionEvent(this, ClientSubscription_Terminated, h, msg));
}

void
DumUserAgent::onNewSubscription(resip::ClientSubscriptionHandle h, const resip::SipMessage& notify)
{
   DebugLog(<< "ClientSubscriptionHandler:onNewSubscription");
   handleEvent(new ClientSubscriptionEvent(this, ClientSubscription_NewSubscription, h, &notify));
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(ClientSubscriptionEvent::Type t,
                     ExpectPreCon& pred,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<ClientSubscriptionEvent>(t),
                        0,
                        pred,
                        timeoutMs,
                        expectAction);
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(ClientSubscriptionEvent::Type t,
                     TestClientSubscription& clientSub,
                     MessageMatcher* matcher,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<ClientSubscriptionEvent>(t),
                        matcher,
                        *TestEndPoint::AlwaysTruePred,
                        timeoutMs,
                        expectAction,
                        new BindHandle<ClientSubscriptionEvent>(this, "BindClientSubscriptionHandle", clientSub.getHandleRef()));
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(ClientSubscriptionEvent::Type t,
                     TestClientSubscription& clientSub,
                     MessageMatcher* matcher,
                     ExpectPreCon& pred,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<ClientSubscriptionEvent>(t),
                        matcher,
                        pred,
                        timeoutMs,
                        expectAction,
                        new BindHandle<ClientSubscriptionEvent>(this, "BindClientSubscriptionHandle", clientSub.getHandleRef()));
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(ClientSubscriptionEvent::Type t,
                     TestClientSubscription& clientSub,
                     ExpectPreCon& pred,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<ClientSubscriptionEvent>(t),
                        0,
                        pred,
                        timeoutMs,
                        expectAction,
                        new BindHandle<ClientSubscriptionEvent>(this, "BindClientSubscriptionHandle", clientSub.getHandleRef()));
}

// ServerSubscriptionHandler
void
DumUserAgent::onNewSubscription(ServerSubscriptionHandle h, const SipMessage& sub)
{
   DebugLog(<< "ServerSubscriptionHandler::onNewSubscription");
   handleEvent(new ServerSubscriptionEvent(this, ServerSubscription_NewSubscription, h, sub));
}

void
DumUserAgent::onNewSubscriptionFromRefer(ServerSubscriptionHandle h, const SipMessage& sub)
{
   DebugLog(<< "ServerSubscriptionHandler::onNewSubscriptionFromRefer");
   mReferMessage = sub;
   mServerSubscription = h;
   handleEvent(new ServerSubscriptionEvent(this, ServerSubscription_NewSubscriptionFromRefer, h, sub));
}

void
DumUserAgent::onTerminated(ServerSubscriptionHandle h)
{
   DebugLog(<< "ServerSubscriptionHandler::onTerminated");
   handleEvent(new ServerSubscriptionEvent(this, ServerSubscription_Terminated, h));
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(ServerSubscriptionEvent::Type t,
                     TestServerSubscription& serverSub,
                     MessageMatcher* matcher,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<ServerSubscriptionEvent>(t),
                        matcher,
                        *TestEndPoint::AlwaysTruePred,
                        timeoutMs,
                        expectAction,
                        new BindHandle<ServerSubscriptionEvent>(this, "BindServerSubscriptionHandle", serverSub.getHandleRef()));
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(ServerSubscriptionEvent::Type t,
                     TestServerSubscription& serverSub,
                     MessageMatcher* matcher,
                     ExpectPreCon& pred,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<ServerSubscriptionEvent>(t),
                        matcher,
                        pred,
                        timeoutMs,
                        expectAction,
                        new BindHandle<ServerSubscriptionEvent>(this, "BindServerSubscriptionHandle", serverSub.getHandleRef()));
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(ServerSubscriptionEvent::Type t,
                     TestServerSubscription& serverSub,
                     ExpectPreCon& pred,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<ServerSubscriptionEvent>(t),
                        0,
                        pred,
                        timeoutMs,
                        expectAction,
                        new BindHandle<ServerSubscriptionEvent>(this, "BindServerSubscriptionHandle", serverSub.getHandleRef()));
}

// ClientPagerMessageHandler
void
DumUserAgent::onSuccess(resip::ClientPagerMessageHandle h, const resip::SipMessage& status)
{
   DebugLog(<< "ClientPagerMessageHandler-onSuccess");
   handleEvent(new ClientPagerMessageEvent(this, ClientPagerMessage_Success, h, status));
}

void
DumUserAgent::onFailure(resip::ClientPagerMessageHandle h, const resip::SipMessage& status, std::auto_ptr<resip::Contents> contents)
{
   DebugLog(<< "ClientPagerMessageHandler-onFailure");
   handleEvent(new ClientPagerMessageEvent(this, ClientPagerMessage_Failure, h, status, contents));
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(ClientPagerMessageEvent::Type t,
                     TestClientPagerMessage& clientPager,
                     MessageMatcher* matcher,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<ClientPagerMessageEvent>(t),
                        matcher,
                        *TestEndPoint::AlwaysTruePred,
                        timeoutMs,
                        expectAction,
                        new BindHandle<ClientPagerMessageEvent>(this, "BindClientPagerMessageHandle", clientPager.getHandleRef()));
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(ClientPagerMessageEvent::Type t,
                     TestClientPagerMessage& clientPager,
                     MessageMatcher* matcher,
                     ExpectPreCon& pred,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<ClientPagerMessageEvent>(t),
                        matcher,
                        pred,
                        timeoutMs,
                        expectAction,
                        new BindHandle<ClientPagerMessageEvent>(this, "BindClientPagerMessageHandle", clientPager.getHandleRef()));
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(ClientPagerMessageEvent::Type t,
                     TestClientPagerMessage& clientPager,
                     ExpectPreCon& pred,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<ClientPagerMessageEvent>(t),
                        0,
                        pred,
                        timeoutMs,
                        expectAction,
                        new BindHandle<ClientPagerMessageEvent>(this, "BindClientPagerMessageHandle", clientPager.getHandleRef()));
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(ClientPagerMessageEvent::Type t,
                      ExpectPreCon& pred,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<ClientPagerMessageEvent>(t),
                        0,
                        pred,
                        timeoutMs,
                        expectAction);
}

// ServerPagerMessageHandler
void
DumUserAgent::onMessageArrived(resip::ServerPagerMessageHandle h, const resip::SipMessage& message)
{
   DebugLog(<< "onMessageArrived");
   handleEvent(new ServerPagerMessageEvent(this, ServerPagerMessage_MessageArrived, h, message));
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(ServerPagerMessageEvent::Type t,
                     TestServerPagerMessage& svrPager,
                     MessageMatcher* matcher,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<ServerPagerMessageEvent>(t),
                        matcher,
                        *TestEndPoint::AlwaysTruePred,
                        timeoutMs,
                        expectAction,
                        new BindHandle<ServerPagerMessageEvent>(this, "BindServerPagerMessageHandle", svrPager.getHandleRef()));
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(ServerPagerMessageEvent::Type t,
                     TestServerPagerMessage& svrPager,
                     MessageMatcher* matcher,
                     ExpectPreCon& pred,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<ServerPagerMessageEvent>(t),
                        matcher,
                        pred,
                        timeoutMs,
                        expectAction,
                        new BindHandle<ServerPagerMessageEvent>(this, "BindServerPagerMessageHandle", svrPager.getHandleRef()));
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(ServerPagerMessageEvent::Type t,
                     TestServerPagerMessage& svrPager,
                     ExpectPreCon& pred,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<ServerPagerMessageEvent>(t),
                        0,
                        pred,
                        timeoutMs,
                        expectAction,
                        new BindHandle<ServerPagerMessageEvent>(this, "BindServerPagerMessageHandle", svrPager.getHandleRef()));
}

/*
// actions from ClientOutOfDialogReq
DumUaAction*
DumUserAgent::endClientOutOfDialogReq()
{
   return new ClientOutOfDialogReqAction(this, boost::bind(&resip::ClientOutOfDialogReq::end, _1));
}
*/

// ClientOutOfDialogReqHandler
void
DumUserAgent::onSuccess(resip::ClientOutOfDialogReqHandle h, const resip::SipMessage& success)
{
   handleEvent(new ClientOutOfDialogReqEvent(this, ClientOutOfDialogReq_Success, h, success));
}

void
DumUserAgent::onFailure(resip::ClientOutOfDialogReqHandle h, const resip::SipMessage& error)
{
   handleEvent(new ClientOutOfDialogReqEvent(this, ClientOutOfDialogReq_Failure, h, error));
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(ClientOutOfDialogReqEvent::Type t,
                     MessageMatcher* matcher,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<ClientOutOfDialogReqEvent>(t),
                        matcher,
                        *TestEndPoint::AlwaysTruePred,
                        timeoutMs,
                        expectAction);
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(ClientOutOfDialogReqEvent::Type t,
                     MessageMatcher* matcher,
                     ExpectPreCon& pred,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<ClientOutOfDialogReqEvent>(t),
                        matcher,
                        pred,
                        timeoutMs,
                        expectAction);
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(ClientOutOfDialogReqEvent::Type t,
                     ExpectPreCon& pred,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<ClientOutOfDialogReqEvent>(t),
                        0,
                        pred,
                        timeoutMs,
                        expectAction);
}

/*
//actions from ServerOutOfDialogReq
DumUaAction*
DumUserAgent::acceptServerOutOfDialogReq(int statusCode)
{
   return new ServerOutOfDialogReqAction(this, boost::bind(&resip::ServerOutOfDialogReq::accept, _1, statusCode), NoAdornment::instance());
}

DumUaAction*
DumUserAgent::rejectServerOutOfDialogReq(int statusCode)
{
   return new ServerOutOfDialogReqAction(this, boost::bind(&resip::ServerOutOfDialogReq::reject, _1, statusCode), NoAdornment::instance());
}

DumUaAction*
DumUserAgent::endServerOutOfDialogReq()
{
   return new ServerOutOfDialogReqAction(this, boost::bind(&resip::ServerOutOfDialogReq::end, _1));
}

DumUaAction*
DumUserAgent::answerOptions()
{
   return new ServerOutOfDialogReqAction(this, boost::bind(&resip::ServerOutOfDialogReq::answerOptions, _1), NoAdornment::instance());
}

DumUaAction*
DumUserAgent::sendServerOutOfDialogReq(SharedPtr<resip::SipMessage> msg)
{
   return new ServerOutOfDialogReqAction(this, boost::bind(&resip::ServerOutOfDialogReq::send, _1, msg));
}
*/

// ServerOutOfDialogReqHandler
void
DumUserAgent::onReceivedRequest(resip::ServerOutOfDialogReqHandle h, const resip::SipMessage& request)
{
   handleEvent(new ServerOutOfDialogReqEvent(this, ServerOutOfDialogReq_ReceivedRequest, h, request));
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(ServerOutOfDialogReqEvent::Type t,
                     TestServerOutOfDialogReq& serverReq,
                     MessageMatcher* matcher,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<ServerOutOfDialogReqEvent>(t),
                        matcher,
                        *TestEndPoint::AlwaysTruePred,
                        timeoutMs,
                        expectAction,
                        new BindHandle<ServerOutOfDialogReqEvent>(this, "BindServerOutOfDialogReqHandle", serverReq.getHandleRef()));
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(ServerOutOfDialogReqEvent::Type t,
                     TestServerOutOfDialogReq& serverReq,
                     MessageMatcher* matcher,
                     ExpectPreCon& pred,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<ServerOutOfDialogReqEvent>(t),
                        matcher,
                        pred,
                        timeoutMs,
                        expectAction,
                        new BindHandle<ServerOutOfDialogReqEvent>(this, "BindServerOutOfDialogReqHandle", serverReq.getHandleRef()));
}

DumUserAgent::ExpectBase*
DumUserAgent::expect(ServerOutOfDialogReqEvent::Type t,
                     TestServerOutOfDialogReq& serverReq,
                     ExpectPreCon& pred,
                     int timeoutMs,
                     ActionBase* expectAction)
{
   return new DumExpect(*this,
                        new DumEventMatcherSpecific<ServerOutOfDialogReqEvent>(t),
                        0,
                        pred,
                        timeoutMs,
                        expectAction,
                        new BindHandle<ServerOutOfDialogReqEvent>(this, "BindServerOutOfDialogReqHandle", serverReq.getHandleRef()));
}

// DialogSetHandler
void
DumUserAgent::onTrying(AppDialogSetHandle h, const SipMessage& msg)
{
   DebugLog(<< "onTrying called" );
   mAppDialogSet = h.get();
}

// DialogEventHandler
void
DumUserAgent::onTrying(const resip::TryingDialogEvent& evt)
{
   handleEvent(new DialogEventHandlerEvent(this, DialogEvent_Trying, evt.getEventInfo()));
}

void
DumUserAgent::onProceeding(const resip::ProceedingDialogEvent& evt)
{
   handleEvent(new DialogEventHandlerEvent(this, DialogEvent_Proceeding, evt.getEventInfo()));
}

void
DumUserAgent::onEarly(const resip::EarlyDialogEvent& evt)
{
   handleEvent(new DialogEventHandlerEvent(this, DialogEvent_Early, evt.getEventInfo()));
}

void
DumUserAgent::onConfirmed(const resip::ConfirmedDialogEvent& evt)
{
   handleEvent(new DialogEventHandlerEvent(this, DialogEvent_Confirmed, evt.getEventInfo()));
}

void
DumUserAgent::onTerminated(const resip::TerminatedDialogEvent& evt)
{
   handleEvent(new DialogEventHandlerEvent(this, DialogEvent_Terminated, evt.getEventInfo(), evt.getTerminatedReason(), evt.getResponseCode()));
}

void
DumUserAgent::onMultipleEvents(const resip::MultipleEventDialogEvent& evt)
{
   const resip::MultipleEventDialogEvent::EventVector& v = evt.getEvents();
   resip::MultipleEventDialogEvent::EventVector::const_iterator it = v.begin();
   for (; it != v.end(); ++it)
   {
      if (resip::TerminatedDialogEvent* termEvt = dynamic_cast<resip::TerminatedDialogEvent*>(it->get()))
      {
         onTerminated(*termEvt);
      }
   }
}

DumUserAgent::From::From(const DumUserAgent& dua)
   : mUa(&dua),
     mProxy(0)
{
   assert(mUa);
}

DumUserAgent::From::From(TestProxy* proxy)
   : mUa(0),
     mProxy(proxy)
{
   assert(proxy);
}

Data
DumUserAgent::From::toString() const
{
   assert(mUa || mProxy);

   if (mUa)
   {
      return "from(" + mUa->getName() + ")";
   }
   else
   {
      return "from(" + mProxy->toString() + ")";
   }
}

bool
DumUserAgent::From::isMatch(const boost::shared_ptr<resip::SipMessage>& message) const
{
   if (mUa)
   {
      StackLog(<< "matching stored agent...");
      Uri localContact(mUa->getContact());

      if (message->exists(h_Contacts) && message->header(h_Contacts).size() == 1)
      {
         if (localContact.getAor() == message->header(h_Contacts).front().uri().getAor())
         {
            DebugLog(<< "matched");
            return true;
         }
      }

      if (message->isRequest())
      {
         Via& via = message->header(h_Vias).back(); // via of originator
         StackLog(<< "Trying to match: " << via.sentHost() << ":" << via.sentPort() << " against: " << localContact);

         if ((via.sentHost() != localContact.host()
              && !(via.exists(p_received) && via.param(p_received) == localContact.host()))
             || via.sentPort() != localContact.port())
         {
            InfoLog(<< "From::isMatch failed for (UA) "
                    << mUa->getName()
                    << ". Via did not match in command");
            return false;
         }
         StackLog(<< "matched");
         return true;
      }
      else
      {
         StackLog(<< "matched");
         return true;
      }

   }
   else if (mProxy)
   {
      StackLog(<< "using proxy->isFromMe");
      //return mProxy->isFromMe(*message);
      return true;
   }

   assert(0);
   return false;
}

DumUserAgent::FindMatchingDialogToReplace::FindMatchingDialogToReplace(DumUserAgent& dua)
   : mUa(&dua)
{
   assert(mUa);
}

Data
DumUserAgent::FindMatchingDialogToReplace::toString() const
{
   return "FindMatchingDialogToReplace";
}

bool
DumUserAgent::FindMatchingDialogToReplace::isMatch(const boost::shared_ptr<resip::SipMessage>& message) const
{
   if (!message->exists(h_Replaces))
   {
      DebugLog(<< "replaces head missing");
      return false;
   }
   else
   {
      return true;
// !bwc! This code is not safe. Maybe we could fire a DumCommand that did the
// check, and asserted if not the case? If there is no match, won't the test
// fail anyhow?
//      std::pair<InviteSessionHandle, int> inv = mUa->getDum().findInviteSession(message->header(h_Replaces));
//      if (inv.first.isValid())
//      {
//         DebugLog(<< "matching dialog to replace found");
//         return true;
//      }
//      else
//      {
//         DebugLog(<< "matching dialog to replace not found");
//         return false;
//      }
   }
}

DumUserAgent::From*
dumFrom(const DumUserAgent& dua)
{
   return new DumUserAgent::From(dua);
}

DumUserAgent::From*
dumFrom(const DumUserAgent* dua)
{
   return new DumUserAgent::From(*dua);
}

DumUserAgent::From*
dumFrom(TestProxy* proxy)
{
   return new DumUserAgent::From(proxy);
}

DumUserAgent::FindMatchingDialogToReplace*
findMatchingDialogToReplace(DumUserAgent& dua)
{
   return new DumUserAgent::FindMatchingDialogToReplace(dua);
}

DumUserAgent::FindMatchingDialogToReplace*
findMatchingDialogToReplace(DumUserAgent* dua)
{
   return new DumUserAgent::FindMatchingDialogToReplace(*dua);
}

bool
DumUserAgent::HasRinstance::isMatch(const boost::shared_ptr<resip::SipMessage>& message) const
{
   // assume there is only one contact.
   return message->header(h_Contacts).begin()->uri().exists(p_rinstance);
}

DumUserAgent::HasRinstance*
hasRinstance()
{
   return new DumUserAgent::HasRinstance();
}

Data
DumUserAgent::HasRinstance::toString() const
{
   return "HasRinstance";
}

bool
DumUserAgent::NoRinstance::isMatch(const boost::shared_ptr<resip::SipMessage>& message) const
{
   return !message->header(h_Contacts).begin()->uri().exists(p_rinstance);
}

Data
DumUserAgent::NoRinstance::toString() const
{
   return "NoRinstance";
}

DumUserAgent::NoRinstance*
noRinstance()
{
   return new DumUserAgent::NoRinstance();
}

bool
DumUserAgent::HasMethodsParam::isMatch(const boost::shared_ptr<resip::SipMessage>& message) const
{
   // assume there is only one contact.
   return message->header(h_Contacts).begin()->exists(p_methods);
}

DumUserAgent::HasMethodsParam*
hasMethodsParam()
{
   return new DumUserAgent::HasMethodsParam();
}

Data
DumUserAgent::HasMethodsParam::toString() const
{
   return "HasMethodsParam";
}

bool
DumUserAgent::NoMethodsParam::isMatch(const boost::shared_ptr<resip::SipMessage>& message) const
{
   return !message->header(h_Contacts).begin()->exists(p_methods);
}

Data
DumUserAgent::NoMethodsParam::toString() const
{
   return "NoMethodsParam";
}

DumUserAgent::NoMethodsParam*
noMethodsParam()
{
   return new DumUserAgent::NoMethodsParam();
}

/*
bool
DumUserAgent::HasInstanceId::isMatch(const boost::shared_ptr<resip::SipMessage>& message) const
{
   // assume there is only one contact.
   return message->header(h_Contacts).begin()->exists(p_Instance);
}

DumUserAgent::HasInstanceId*
hasInstanceId()
{
   return new DumUserAgent::HasInstanceId();
}

Data
DumUserAgent::HasInstanceId::toString() const
{
   return "HasInstanceId";
}

bool
DumUserAgent::NoInstanceId::isMatch(const boost::shared_ptr<resip::SipMessage>& message) const
{
   return !message->header(h_Contacts).begin()->exists(p_Instance);
}

Data
DumUserAgent::NoInstanceId::toString() const
{
   return "NoInstanceId";
}

DumUserAgent::NoInstanceId*
noInstanceId()
{
   return new DumUserAgent::NoInstanceId();
}
*/

void
DumUserAgent::dispatchEvent(ClientSubscriptionEvent* event)
{
   dispatchEventHelper(event, mTestUsages);
}

void
DumUserAgent::dispatchEvent(ServerSubscriptionEvent* event)
{
   dispatchEventHelper(event, mTestUsages);
}

void
DumUserAgent::dispatchEvent(ClientRegistrationEvent* event)
{
   StackLog(<< "dispatch ClientRegistrationEvent");
   dispatchEventHelper(event, mTestUsages);
}

void
DumUserAgent::dispatchEvent(InviteEvent* event)
{
   StackLog(<< "dispatch InviteEvent");
   dispatchEventHelper(event, mTestUsages);
}

void
DumUserAgent::dispatchEvent(ClientPublicationEvent* event)
{
   StackLog(<< "dispatch ClientPublicationEvent");
   dispatchEventHelper(event, mTestUsages);
}

void
DumUserAgent::dispatchEvent(ServerOutOfDialogReqEvent* event)
{
   StackLog(<< "dispatch ServerOutOfDialogReqEvent");
   dispatchEventHelper(event, mTestUsages);
}

void
DumUserAgent::add(TestUsage* usage)
{
   mTestUsages.insert(usage);
}

void
DumUserAgent::remove(TestUsage* usage)
{
   mTestUsages.erase(usage);
}

bool
DumUserAgent::matchEvent(Event* event)
{
   for (TestUsages::iterator it = mTestUsages.begin(); it != mTestUsages.end(); ++it)
   {
      if ((*it)->isMyEvent(event))
      {
         return true;
      }
   }

   return false;
}

void
DumUserAgent::handleEvent(Event* eventRaw)
{
   boost::shared_ptr<Event> event(eventRaw);
   StackLog(<< "DumUserAgent::handleEvent: " << *eventRaw);

   boost::shared_ptr<SequenceSet> sset = getSequenceSet().lock();
   if (sset)
   {
      StackLog(<< " DumUserAgent::handleEvent to own sequenceset");
      sset->enqueue(event);
      return;
   }
   else
   {
      for(TestUsages::iterator it = mTestUsages.begin(); it != mTestUsages.end(); it++)
      {
         boost::shared_ptr<SequenceSet> tusset= (*it)->getSequenceSet().lock();
         if (tusset)
         {
            StackLog(<< " DumUserAgent::handleEvent to nested usage sequenceSet");
            tusset->enqueue(event);
            return;
         }
      }
   }
   WarningLog(<< "DumUserAgent::handleEvent has no associated SequenceSet: discarding event " << *event);
}

TestUsage*
DumUserAgent::findUsage(Event* e)
{
   for (TestUsages::iterator it = mTestUsages.begin(); it != mTestUsages.end(); ++it)
   {
      if ((*it)->isMyEvent(e))
      {
         return *it;
      }
   }

   return 0;
}

ext: cxx

max_stars_repo_name: dulton/reSipServer

max_issues_repo_name: dulton/reSipServer

max_forks_repo_name: dulton/reSipServer


text: #include <boost/spirit/include/qi_lazy.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/**************************************************************
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 *************************************************************/

#ifndef CONNECTIVITY_STATEMENTCOMPOSER_HXX
#define CONNECTIVITY_STATEMENTCOMPOSER_HXX

/** === begin UNO includes === **/
#include <com/sun/star/sdbc/XConnection.hpp>
#include <com/sun/star/sdb/XSingleSelectQueryComposer.hpp>
/** === end UNO includes === **/

#include <boost/noncopyable.hpp>

#include <memory>
#include "connectivity/dbtoolsdllapi.hxx"

//........................................................................
namespace dbtools
{
//........................................................................

	//====================================================================
	//= StatementComposer
	//====================================================================
    struct StatementComposer_Data;
    /** a class which is able to compose queries (SELECT statements) from a command and a command type
    */
    class OOO_DLLPUBLIC_DBTOOLS StatementComposer : public ::boost::noncopyable
	{
        ::std::auto_ptr< StatementComposer_Data >   m_pData;

    public:
        /** constructs an instance

            @param _rxConnection
                the connection to work with. Must not be <NULL/>.
        */
        StatementComposer(
            const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection,
            const ::rtl::OUString&  _rCommand,
            const sal_Int32         _nCommandType,
            const sal_Bool          _bEscapeProcessing
        );

        ~StatementComposer();

        /** controls whether or not the instance disposes its XSingleSelectQueryComposer upon
            destruction

            Unless you explicitly call this method with the parameter being <TRUE/>,
            the XSingleSelectQueryComposer will be disposed when the StatementComposer
            instance is destroyed.
        */
        void    setDisposeComposer( bool _bDoDispose );
        bool    getDisposeComposer() const;

        void    setFilter( const ::rtl::OUString& _rFilter );
        void    setOrder( const ::rtl::OUString& _rOrder );

        /** returns the composer which has been fed with the current settings

            @throws ::com::sun::star::sdbc::SQLException
                if such an exception occurs while creating the composer
        */
        ::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSingleSelectQueryComposer >
                getComposer();

        /** returns the composer statement

            Effectively, this is equivalent to calling getComposer, and asking the composer
            for its Query attribute.

            @throws ::com::sun::star::sdbc::SQLException
                if such an exception occurs while creating the composer
        */
        ::rtl::OUString
                getQuery();

    private:
        StatementComposer();    // not implemented
	};

//........................................................................
} // namespace dbtools
//........................................................................

#endif // CONNECTIVITY_STATEMENTCOMPOSER_HXX

ext: hxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice


text:
#pragma once

#include <boost/asio.hpp>
#include <boost/container/vector.hpp>
#include <boost/container/string.hpp>
#include <boost/filesystem.hpp>
#include <map>
#include <string>
#include <memory>
#include <cstdint>
#include "misc/helper.hpp"

#define POUSSEY_SERVER_VERSION "1.0"
#define DEFAULT_PORT 6028

#ifndef POUSSEY_DIR
#define POUSSEY_DIR "."
#endif

#define LOG_ERROR_EXIT(error) ()

namespace PousseyServer
{
	namespace container = std;

	struct server_settings_t
	{
		boost::filesystem::path	configPath;
		bool					checkingConfiguration;
		bool					usingDaemon;

		server_settings_t( boost::filesystem::path path, bool checkingConfig, bool useDaemon ) :
			configPath( path ), checkingConfiguration( checkingConfig ), usingDaemon( useDaemon )
		{
		}
	};

	struct server_binding_t
	{
		std::string			bindingName;
		std::string			bindingIPAddress;
		unsigned int		bindingMaximumKeepAlive;
		unsigned short		bindingPort = 0;
		uint64_t			bindingMaximumRequestSize = 128; // 128KB
		uint64_t			bindingMaximumUploadSize = 2048; // 2MB
		bool				bindingReuseAdddress = true;
	};

	struct server_directory_t
	{
		boost::filesystem::path		serverConfigPath;
		boost::filesystem::path		serverLogFilepath;
		boost::filesystem::path		serverErrorFilepath;
		boost::filesystem::path		serverExploitFilepath;
		boost::filesystem::path		serverDatabaseFilepath;
	};

	struct server_config_t
	{
		container::string					serverVersion;
		container::string					hostName;
		container::string					serverLogFile;
		std::vector<server_binding_t>		configBindings;
		std::vector<container::string>		supportedCGIExtensions;
		PousseyServer::server_directory_t	paths;

		server_config_t( server_settings_t settings_ );
		bool  HasError() const;
		std::string  Error() const;
	private:
		void InitializeServerConfig();
		void UseDefaultConfigOptions();
		void ReadConfigurationFile( std::string const & path );
		void ActivateServerRecord( boost::filesystem::ifstream & file );
	private:
		std::string							error;
		bool								errorFlag;
		server_settings_t					settings;
		std::map<std::string, std::string>	environmentVariables;
	};

	class server_t : public boost::noncopyable
	{
	public:
		using http_socket_ptr_t = std::shared_ptr<boost::asio::ip::tcp::socket>;
		server_t( server_settings_t settings, boost::asio::io_service & );
		void StartServer();
		void StopServer();
	private:
		void StartAcceptingIncomingConnection( std::shared_ptr<boost::asio::ip::tcp::acceptor> );
		void StartReadingRequests( http_socket_ptr_t socket );
		void OnReadCompleted( boost::system::error_code const &, size_t, http_socket_ptr_t,
			std::shared_ptr<http::request_t> );
	private:
		std::shared_ptr<server_config_t>	serverConfigurationPtr;
		boost::asio::io_service	&			ioService;
	};
}

max_stars_repo_name: iamOgunyinka/PSS

max_issues_repo_name: iamOgunyinka/PSS

max_forks_repo_name: iamOgunyinka/PSS


text: #include <boost/log/utility/permissions.hpp>


text:
// Distributed under the MIT License.
// See LICENSE.txt for details.

#pragma once

#include <boost/optional.hpp>
#include <cstddef>
#include <utility>
#include <vector>

#include "DataStructures/DataBox/DataBox.hpp"
#include "DataStructures/DataBox/DataBoxTag.hpp"
#include "DataStructures/Tensor/TypeAliases.hpp"
#include "NumericalAlgorithms/Interpolation/InterpolatedVars.hpp"
#include "NumericalAlgorithms/Interpolation/TryToInterpolate.hpp"
#include "Utilities/Gsl.hpp"
#include "Utilities/Requires.hpp"
#include "Utilities/TaggedTuple.hpp"

/// \cond
// IWYU pragma: no_forward_declare db::DataBox
namespace Parallel {
template <typename Metavariables>
class ConstGlobalCache;
}  // namespace Parallel
namespace domain {
class BlockId;
}  // namespace domain
template <typename IdType, typename DataType>
class IdPair;
namespace intrp {
namespace Tags {
struct NumberOfElements;
template <typename Metavariables>
struct InterpolatedVarsHolders;
}  // namespace Tags
}  // namespace intrp
/// \endcond

namespace intrp {
namespace Actions {

/// \ingroup ActionsGroup
/// \brief Receives target points from an InterpolationTarget.
///
/// After receiving the points, interpolates volume data onto them
/// if it already has all the volume data.
///
/// Uses:
/// - Databox:
///   - `Tags::NumberOfElements`
///   - `Tags::InterpolatedVarsHolders<Metavariables>`
///   - `Tags::VolumeVarsInfo<Metavariables>`
///
/// DataBox changes:
/// - Adds: nothing
/// - Removes: nothing
/// - Modifies:
///   - `Tags::InterpolatedVarsHolders<Metavariables>`
///
/// For requirements on InterpolationTargetTag, see InterpolationTarget
template <typename InterpolationTargetTag>
struct ReceivePoints {
  template <
      typename ParallelComponent, typename DbTags, typename Metavariables,
      typename ArrayIndex, size_t VolumeDim,
      Requires<tmpl::list_contains_v<DbTags, ::intrp::Tags::NumberOfElements>> =
          nullptr>
  static void apply(
      db::DataBox<DbTags>& box,
      Parallel::ConstGlobalCache<Metavariables>& cache,
      const ArrayIndex& /*array_index*/,
      const typename Metavariables::temporal_id::type& temporal_id,
      std::vector<boost::optional<
          IdPair<domain::BlockId,
                 tnsr::I<double, VolumeDim, typename ::Frame::Logical>>>>&&
          block_logical_coords) noexcept {
    db::mutate<intrp::Tags::InterpolatedVarsHolders<Metavariables>>(
        make_not_null(&box),
        [
          &temporal_id, &block_logical_coords
        ](const gsl::not_null<
            db::item_type<intrp::Tags::InterpolatedVarsHolders<Metavariables>>*>
              vars_holders) noexcept {
          auto& vars_infos =
              get<intrp::Vars::HolderTag<InterpolationTargetTag,
                                         Metavariables>>(*vars_holders)
                  .infos;

          // Add the target interpolation points at this temporal_id.
          vars_infos.emplace(std::make_pair(
              temporal_id,
              intrp::Vars::Info<VolumeDim, typename InterpolationTargetTag::
                                               vars_to_interpolate_to_target>{
                  std::move(block_logical_coords)}));
        });

    try_to_interpolate<InterpolationTargetTag>(
        make_not_null(&box), make_not_null(&cache), temporal_id);
  }
};

}  // namespace Actions
}  // namespace intrp

max_stars_repo_name: keefemitman/spectre

max_issues_repo_name: keefemitman/spectre

max_forks_repo_name: keefemitman/spectre


text:
/*
Copyright 2017-2018 Lars Pastewka, Andreas Greiner

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

--------
| OPT1 |
--------

This is an implementation of the D2Q9 Lattice Boltzmann lattice in the simple
relaxation time approximation. The code reports the amplitude of a decaying
shear wave which can be used to measure viscosity.

The present implementation contains was optimized with respect to opt1.
The optimization is identical to the opt1 Python code.

This code requires pybind11, Eigen and boost. Compile with
c++ -O3 -Wall -std=c++11 -I/usr/local/Cellar/pybind11/2.2.3/include -I/usr/local/Cellar/eigen/3.3.5/include/eigen3 shear_wave_opt0.cpp -o shear_wave_opt0
*/

#include <boost/range/combine.hpp>
#include <iostream>
#include <vector>

#include <Eigen/Dense>

class D2Q9 {
public:
    using Density_t = double;
    using Velocity_t = double;
    using Probability_t = Eigen::Matrix<double, 9, 1>;

    using ChannelVelocity_t = Eigen::Matrix<int, 2, 9>;
    using Weight_t = Eigen::Array<double, 9, 1>;

    using DensityField_t = std::vector<Density_t>;
    using VelocityField_t = std::vector<Velocity_t>;
    using ProbabilityField_t = std::vector<Probability_t>;

    const ChannelVelocity_t c_ci;

    static constexpr double w_0 = 4./9;
    static constexpr double w_1234 = 1./9;
    static constexpr double w_5678 = 1./36;

    D2Q9(int nx, int ny, double omega):
        c_ci((ChannelVelocity_t() << 0,  1,  0, -1,  0,  1, -1, -1,  1,
                                     0,  0,  1,  0, -1,  1,  1, -1, -1).finished()) {
        this->nx = nx;
        this->ny = ny;
        this->omega = omega;
    }

    Probability_t equilibrium(double rho, Velocity_t ux, Velocity_t uy) {
        double cu5 = ux + uy;
        double cu6 = -ux + uy;
        double cu7 = -ux - uy;
        double cu8 = ux - uy;
        double uu = ux*ux + uy*uy;
        return (Probability_t() <<
            w_0*rho*(1 - 3./2*uu),
            w_1234*rho*(1 + 3*ux + 9./2*ux*ux - 3./2*uu),
            w_1234*rho*(1 + 3*uy + 9./2*uy*uy - 3./2*uu),
            w_1234*rho*(1 - 3*ux + 9./2*ux*ux - 3./2*uu),
            w_1234*rho*(1 - 3*uy + 9./2*uy*uy - 3./2*uu),
            w_5678*rho*(1 + 3*cu5 + 9./2*cu5*cu5 - 3./2*uu),
            w_5678*rho*(1 + 3*cu6 + 9./2*cu6*cu6 - 3./2*uu),
            w_5678*rho*(1 + 3*cu7 + 9./2*cu7*cu7 - 3./2*uu),
            w_5678*rho*(1 + 3*cu8 + 9./2*cu8*cu8 - 3./2*uu)).finished();
    }

    void equilibrium(DensityField_t &rho_kl,
                     VelocityField_t &ux_kl, VelocityField_t &uy_kl,
                     ProbabilityField_t &f_kli) {
        for (auto && tup: boost::combine(rho_kl, ux_kl, uy_kl, f_kli)) {
            auto && rho = tup.get<0>();
            auto && ux = tup.get<1>();
            auto && uy = tup.get<2>();
            auto && f_i = tup.get<3>();
            f_i = this->equilibrium(rho, ux, uy);
        }
    }

    void equilibrium(double rho, Velocity_t &ux, Velocity_t &uy,
                     ProbabilityField_t &f_kli) {
        for (auto && f_i: f_kli) {
            f_i = this->equilibrium(rho, ux, uy);
        }
    }

    void collide(ProbabilityField_t &f_kli) {
        for (auto && f_i: f_kli) {
            double rho = f_i.sum();
            Velocity_t ux = (f_i(1) - f_i(3) + f_i(5) - f_i(6) - f_i(7) + f_i(8))/rho;
            Velocity_t uy = (f_i(2) - f_i(4) + f_i(5) + f_i(6) - f_i(7) - f_i(8))/rho;
            f_i += this->omega*(equilibrium(rho, ux, uy) - f_i);
        }
    }

    void stream(ProbabilityField_t &f_kli) {
        ProbabilityField_t g_kli(f_kli.size());
        auto f_i = f_kli.begin();
        for (int l = 0; l < this->ny; ++l) {
            for (int k = 0; k < this->nx; ++k, ++f_i) {
                for (int i = 0; i < 9; i++) {
                    int k1 = k + this->c_ci(0, i);
                    while (k1 < 0) k1 += this->nx;
                    while (k1 >= this->nx) k1 -= this->nx;
                    int l1 = l + this->c_ci(1, i);
                    while (l1 < 0) l1 += this->ny;
                    while (l1 >= this->ny) l1 -= this->ny;
                    g_kli[l1*this->nx + k1](i) = (*f_i)(i);
                }
            }
        }
        f_kli = g_kli;
    }
private:
    int nx, ny;
    double omega;
};

int main(int argc, char *argv[])
{
    int nx = 300;
    int ny = 300;
    int nsteps = 1000;
    double omega = 0.3;
    D2Q9 lb(nx, ny, omega);
    D2Q9::ProbabilityField_t f_kli(nx*ny);

    auto f_i = f_kli.begin();
    for (int l = 0; l < ny; ++l) {
        for (int k = 0; k < nx; ++k, ++f_i) {
            D2Q9::Velocity_t uy = std::sin(2*M_PI/nx*k);
            *f_i = lb.equilibrium(1.0, 0.0, uy);
        }
    }

    for (int n = 0; n < nsteps; ++n) {
        lb.stream(f_kli);
        lb.collide(f_kli);

        double accum = 0.0;
        for (int k = 0; k < nx; ++k)
            accum += (lb.c_ci.cast<double>()*f_kli[ny/2*nx+k])(1)*std::sin(2*M_PI/nx*k);
        std::cout << accum*2/nx << std::endl;
    }
}

ext: cpp

max_stars_repo_name: pastewka/LBWithPython

max_issues_repo_name: IMTEK-Simulation/LBWithPython

max_forks_repo_name: IMTEK-Simulation/LBWithPython


text:
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2014-2014. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/move for documentation.
//
//////////////////////////////////////////////////////////////////////////////

#ifndef BOOST_MOVE_DEFAULT_DELETE_HPP_INCLUDED
#define BOOST_MOVE_DEFAULT_DELETE_HPP_INCLUDED

#ifndef BOOST_CONFIG_HPP
#  include <boost/config.hpp>
#endif
#
#if defined(BOOST_HAS_PRAGMA_ONCE)
#  pragma once
#endif

#include <boost/move/detail/config_begin.hpp>
#include <boost/move/detail/workaround.hpp>
#include <boost/move/detail/unique_ptr_meta_utils.hpp>
#include <boost/move/utility_core.hpp>
#include <boost/static_assert.hpp>

#include <cstddef>   //For std::size_t,std::nullptr_t

//!\file
//! Describes the default deleter (destruction policy) of <tt>unique_ptr</tt>: <tt>default_delete</tt>.

namespace boost{
// @cond
namespace move_upd {

namespace bmupmu = ::boost::move_upmu;

////////////////////////////////////////
////        enable_def_del
////////////////////////////////////////

//compatible with a pointer type T*:
//When either Y* is convertible to T*
//Y is U[N] and T is U cv []
template<class U, class T>
struct def_del_compatible_cond
   : bmupmu::is_convertible
{};

template<class U, class T, std::size_t N>
struct def_del_compatible_cond
   : def_del_compatible_cond
{};

template<class U, class T, class Type = bmupmu::nat>
struct enable_def_del
   : bmupmu::enable_if_c<def_del_compatible_cond::value, Type>
{};

////////////////////////////////////////
////        enable_defdel_call
////////////////////////////////////////

//When 2nd is T[N], 1st(*)[N] shall be convertible to T(*)[N];
//When 2nd is T[],  1st(*)[] shall be convertible to T(*)[];
//Otherwise, 1st* shall be convertible to 2nd*.

template<class U, class T, class Type = bmupmu::nat>
struct enable_defdel_call
   : public enable_def_del
{};

template<class U, class T, class Type>
struct enable_defdel_call
   : public enable_def_del
{};

template<class U, class T, class Type, std::size_t N>
struct enable_defdel_call
   : public enable_def_del
{};

////////////////////////////////////////
////     Some bool literal zero conversion utilities
////////////////////////////////////////

struct bool_conversion {int for_bool; int for_arg(); };
typedef int bool_conversion::* explicit_bool_arg;

#if !defined(BOOST_NO_CXX11_NULLPTR) && !defined(BOOST_NO_CXX11_DECLTYPE)
   typedef decltype(nullptr) nullptr_type;
#elif !defined(BOOST_NO_CXX11_NULLPTR)
   typedef std::nullptr_t nullptr_type;
#else
   typedef int (bool_conversion::*nullptr_type)();
#endif

template<bool B>
struct is_array_del
{};

template<class T>
void call_delete(T *p, is_array_del<true>)
{
   delete [] p;
}

template<class T>
void call_delete(T *p, is_array_del<false>)
{
   delete p;
}

}  //namespace move_upd {
// @endcond

namespace movelib {

namespace bmupd = boost::move_upd;
namespace bmupmu = ::boost::move_upmu;

//!The class template <tt>default_delete</tt> serves as the default deleter
//!(destruction policy) for the class template <tt>unique_ptr</tt>.
//!
//! \tparam T The type to be deleted. It may be an incomplete type
template <class T>
struct default_delete
{
   //! Default constructor.
   //!
   BOOST_CONSTEXPR default_delete()
   //Avoid "defaulted on its first declaration must not have an exception-specification" error for GCC 4.6
   #if !defined(BOOST_GCC) || (BOOST_GCC < 40600 && BOOST_GCC >= 40700) || defined(BOOST_MOVE_DOXYGEN_INVOKED)
   BOOST_NOEXCEPT
   #endif
   #if !defined(BOOST_NO_CXX11_DEFAULTED_FUNCTIONS) || defined(BOOST_MOVE_DOXYGEN_INVOKED)
   = default;
   #else
   {};
   #endif

   #if defined(BOOST_MOVE_DOXYGEN_INVOKED)
   //! Trivial copy constructor
   //!
   default_delete(const default_delete&) BOOST_NOEXCEPT = default;
   //! Trivial assignment
   //!
   default_delete &operator=(const default_delete&) BOOST_NOEXCEPT = default;
   #else
   typedef typename bmupmu::remove_extent<T>::type element_type;
   #endif

   //! Effects: Constructs a default_delete object from another <tt>default_delete</tt> object.
   //!
   //! Remarks: This constructor shall not participate in overload resolution unless:
   //!   - If T is not an array type and U* is implicitly convertible to T*.
   //!   - If T is an array type and U* is a more CV qualified pointer to remove_extent<T>::type.
   template <class U>
   default_delete(const default_delete&
      BOOST_MOVE_DOCIGN(BOOST_MOVE_I typename bmupd::enable_def_del::type* =0)
      ) BOOST_NOEXCEPT
   {
      //If T is not an array type, U derives from T
      //and T has no virtual destructor, then you have a problem
      BOOST_STATIC_ASSERT(( !::boost::move_upmu::missing_virtual_destructor<default_delete, U>::value ));
   }

   //! Effects: Constructs a default_delete object from another <tt>default_delete</tt> object.
   //!
   //! Remarks: This constructor shall not participate in overload resolution unless:
   //!   - If T is not an array type and U* is implicitly convertible to T*.
   //!   - If T is an array type and U* is a more CV qualified pointer to remove_extent<T>::type.
   template <class U>
   BOOST_MOVE_DOC1ST(default_delete&,
      typename bmupd::enable_def_del::type)
      operator=(const default_delete&) BOOST_NOEXCEPT
   {
      //If T is not an array type, U derives from T
      //and T has no virtual destructor, then you have a problem
      BOOST_STATIC_ASSERT(( !::boost::move_upmu::missing_virtual_destructor<default_delete, U>::value ));
      return *this;
   }

   //! Effects: if T is not an array type, calls <tt>delete</tt> on static_cast<T*>(ptr),
   //!   otherwise calls <tt>delete[]</tt> on static_cast<remove_extent<T>::type*>(ptr).
   //!
   //! Remarks: If U is an incomplete type, the program is ill-formed.
   //!   This operator shall not participate in overload resolution unless:
   //!      - T is not an array type and U* is convertible to T*, OR
   //!      - T is an array type, and remove_cv::type is the same type as
   //!         remove_cv<remove_extent<T>::type>::type and U* is convertible to remove_extent<T>::type*.
   template <class U>
   BOOST_MOVE_DOC1ST(void, typename bmupd::enable_defdel_call::type)
      operator()(U* ptr) const BOOST_NOEXCEPT
   {
      //U must be a complete type
      BOOST_STATIC_ASSERT(sizeof(U) > 0);
      //If T is not an array type, U derives from T
      //and T has no virtual destructor, then you have a problem
      BOOST_STATIC_ASSERT(( !::boost::move_upmu::missing_virtual_destructor<default_delete, U>::value ));
      element_type * const p = static_cast<element_type*>(ptr);
      move_upd::call_delete(p, move_upd::is_array_del<bmupmu::is_array<T>::value>());
   }

   //! Effects: Same as <tt>(*this)(static_cast<element_type*>(nullptr))</tt>.
   //!
   void operator()(BOOST_MOVE_DOC0PTR(bmupd::nullptr_type)) const BOOST_NOEXCEPT
   {  BOOST_STATIC_ASSERT(sizeof(element_type) > 0);  }
};

}  //namespace movelib {
}  //namespace boost{

#include <boost/move/detail/config_end.hpp>

#endif   //#ifndef BOOST_MOVE_DEFAULT_DELETE_HPP_INCLUDED

max_stars_repo_name: iProgramMC/proton

max_issues_repo_name: iProgramMC/proton

max_forks_repo_name: iProgramMC/proton