EnergySourceContainer
EnergySourceHelper::Install (NodeContainer c) const
{
  EnergySourceContainer container;
  for (NodeContainer::Iterator i = c.Begin (); i != c.End (); ++i)
    {
      Ptr<EnergySource> src = DoInstall (*i);
      container.Add (src);
      /*
       * Check if EnergySourceContainer is already aggregated to target node. If
       * not, create a new EnergySourceContainer and aggregate it to node.
       */
      Ptr<EnergySourceContainer> EnergySourceContrainerOnNode =
        (*i)->GetObject<EnergySourceContainer> ();
      if (EnergySourceContrainerOnNode == NULL)
        {
          ObjectFactory fac;
          fac.SetTypeId ("ns3::EnergySourceContainer");
          EnergySourceContrainerOnNode = fac.Create<EnergySourceContainer> ();
          EnergySourceContrainerOnNode->Add (src);
          (*i)->AggregateObject (EnergySourceContrainerOnNode);
        }
      else
        {
          EnergySourceContrainerOnNode->Add (src);  // append new EnergySource
        }
    }
  return container;
}
void TestEmbeddedObjectAddDistToRoot(void)
{
	ObjectsInit();

	Ptr<CRoot>				pRoot = ORoot();
	Ptr<CGameWorld>			pWorld = OMalloc(CGameWorld)->Init();

	pRoot->Add(pWorld);

	Ptr<CClusterMissile>	pMissile = ONMalloc(CClusterMissile, "Frank")->Init(pWorld);
	Ptr<CHarrier>			pHarrier = OMalloc(CHarrier)->Init(pWorld);
	
	pWorld->AddPlayer(pHarrier);
	AssertInt(3, pHarrier->GetDistToRoot());

	pRoot->Add(pMissile);

	AssertInt(2, pMissile->GetDistToRoot());
	AssertInt(2, pMissile->mcMissile1.GetDistToRoot());
	AssertInt(2, pMissile->mcMissile2.GetDistToRoot());

	pMissile->mcMissile1.SetTarget(pHarrier);

	AssertInt(3, pHarrier->GetDistToRoot());

	ObjectsKill();
}
Example #3
0
void MgServerSiteService::ValidateAuthorOrSelf(CREFSTRING user, CREFSTRING group)
{
    bool bAllowed = false;

    Ptr<MgUserInformation> userInfo = MgUserInformation::GetCurrentUserInfo();
    STRING currUser = userInfo->GetUserName();
    if (currUser.empty())
    {
        currUser = GetUserForSession();
    }

    // Is user an Author or Admin?
    Ptr<MgSecurityCache> securityCache = GetResourceService().CreateSecurityCache();

    Ptr<MgStringCollection> roles = new MgStringCollection;
    roles->Add(MgRole::Administrator);
    roles->Add(MgRole::Author);
    if (securityCache->IsUserInRoles(currUser, roles))
    {
        bAllowed = true;
    }

    // Are we looking ourselves up?
    if (group.empty() && currUser == user)
    {
        bAllowed = true;
    }

    if (!bAllowed)
    {
        throw new MgUnauthorizedAccessException(L"MgServerSiteService.ValidateAuthorOrSelf",
                __LINE__, __WFILE__, NULL, L"", NULL);
    }
}
void TestObjectGraphDeserialiserBuildGraph1(void)
{
	Ptr<CTestSaveableObject2>	cStart1;
	Ptr<CTestSaveableObject2>	cStart2;
	Ptr<CRoot>					cRoot;
	Ptr<CTestSaveableObject1>	cShared;
	Ptr<CString>				cString1;
	Ptr<CString>				cString2;
	Ptr<CTestInteger>			cIgnored;

	cRoot = ORoot();
	cStart1 = ONMalloc(CTestSaveableObject2, "Ow/Start 1")->Init("Battery");
	cStart2 = ONMalloc(CTestSaveableObject2, "Ow/Start 2")->Init("Charger");
	cShared = ONMalloc(CTestSaveableObject1, "Ow/Shared")->Init();
	cString1 = OMalloc(CString)->Init("Black");
	cString2 = OMalloc(CString)->Init("Jack");
	cIgnored = OMalloc(CTestInteger)->Init(0, 1, 0);
	
	cRoot->Add(cStart1);
	cRoot->Add(cStart2);

	cStart1->mp1 = cShared;
	cStart2->mp1 = cShared;

	cShared->miInt = 89;
	cShared->mpObject = cShared;

	cStart1->mp2 = cString1;
	cStart2->mp2 = cString2;

	cRoot->Add(cIgnored);
}
void TestEmbeddedObjectRemoveDistToRoot(void)
{
	ObjectsInit();

	Ptr<CRoot>				pRoot = ORoot();
	Ptr<CGameWorld>			pWorld = OMalloc(CGameWorld)->Init();

	pRoot->Add(pWorld);

	Ptr<CClusterMissile>	pMissile = ONMalloc(CClusterMissile, "Frank")->Init(pWorld);
	Ptr<CHarrier>			pHarrier = OMalloc(CHarrier)->Init(pWorld);
	Ptr<CMissile>			pHolder = OMalloc(CMissile)->Init(pWorld);
	
	pWorld->AddTickable(pHolder);
	AssertInt(4, pHolder->GetDistToRoot());

	pHolder->SetTarget(pHarrier);
	AssertInt(5, pHarrier->GetDistToRoot());

	Ptr<CClusterLauncher>	pLauncher = OMalloc(CClusterLauncher)->Init();

	pRoot->Add(pLauncher);
	AssertInt(2, pLauncher->GetDistToRoot());

	pLauncher->mpMissile = pMissile;

	AssertInt(3, pMissile->GetDistToRoot());
	AssertInt(3, pMissile->mcMissile1.GetDistToRoot());
	AssertInt(3, pMissile->mcMissile2.GetDistToRoot());
	AssertInt(5, pHarrier->GetDistToRoot());
	AssertInt(1, pHarrier->NumHeapFroms());

	pMissile->mcMissile1.SetTarget(pHarrier);
	AssertInt(4, pHarrier->GetDistToRoot());
	AssertInt(2, pHarrier->NumHeapFroms());

	pWorld->RemoveTickable(pHolder);
	pHolder = NULL;

	AssertInt(4, pHarrier->GetDistToRoot());
	AssertInt(1, pHarrier->NumHeapFroms());

	pRoot->Add(pHarrier);
	AssertInt(2, pHarrier->GetDistToRoot());

	pRoot->Remove(pHarrier);
	AssertInt(4, pHarrier->GetDistToRoot());

	ObjectsKill();
}
Ptr<FaceContainer>
StackHelper::Install(Ptr<Node> node) const
{
  Ptr<FaceContainer> faces = Create<FaceContainer>();

  if (node->GetObject<L3Protocol>() != 0) {
    NS_FATAL_ERROR("Cannot re-install NDN stack on node "
                   << node->GetId());
    return 0;
  }

  Ptr<L3Protocol> ndn = m_ndnFactory.Create<L3Protocol>();
  ndn->getConfig().put("tables.cs_max_packets", (m_maxCsSize == 0) ? 1 : m_maxCsSize);

  // Create and aggregate content store if NFD's contest store has been disabled
  if (m_maxCsSize == 0) {
    ndn->AggregateObject(m_contentStoreFactory.Create<ContentStore>());
  }

  // Aggregate L3Protocol on node (must be after setting ndnSIM CS)
  node->AggregateObject(ndn);

  for (uint32_t index = 0; index < node->GetNDevices(); index++) {
    Ptr<NetDevice> device = node->GetDevice(index);
    // This check does not make sense: LoopbackNetDevice is installed only if IP stack is installed,
    // Normally, ndnSIM works without IP stack, so no reason to check
    // if (DynamicCast<LoopbackNetDevice> (device) != 0)
    //   continue; // don't create face for a LoopbackNetDevice

    faces->Add(this->createAndRegisterFace(node, ndn, device));
  }

  return faces;
}
Example #7
0
void TestKillLongCyclicSelfPointer(void)
{
	ObjectsInit();

	Ptr<CRoot>				pRoot;
	Ptr<CTestNamedObject>	pObject1;
	Ptr<CTestNamedObject>	pObject2;
	Ptr<CTestNamedObject>	pObjectBase;
	BOOL					bResult;

	pRoot = ORoot();

	pObjectBase = OMalloc(CTestNamedObject);
	pObject1 = OMalloc(CTestNamedObject);
	pObjectBase->Init(0);
	pObject1->Init(1);
	pObjectBase->mpNamedTest1 = pObject1;
	pObject1->mpNamedTest1 = pObjectBase;

	pRoot->Add(pObjectBase);

	//pObject should be destroyed here and not cause a stack overflow.
	bResult = pRoot->Remove(pObjectBase);
	AssertTrue(bResult);

	ObjectsKill();
}
Example #8
0
void TestKillSelfPointer2(void)
{
	ObjectsInit();

	Ptr<CRoot>				pRoot;
	Ptr<CTestNamedObject>	pObject;
	BOOL					bResult;

	pRoot = ORoot();

	pObject = OMalloc(CTestNamedObject);
	pObject->Init(1);
	pObject->mpNamedTest1 = pObject;

	pRoot->Add(pObject);
	AssertInt(1, pRoot->NumObjects());

	AssertLongLongInt(3, gcObjects.NumMemoryIndexes());

	//pObject should not be destroyed here and not cause a stack overflow.
	bResult = pRoot->Remove(pObject);
	AssertTrue(bResult);
	AssertInt(0, pRoot->NumObjects());
	AssertLongLongInt(3, gcObjects.NumMemoryIndexes());

	//If there were cyclic pointers then the object cannot tell it should be freed when a stack pointer is removed.
	pObject = NULL;
	AssertLongLongInt(2, gcObjects.NumMemoryIndexes());

	ObjectsKill();
}
Example #9
0
void TestKillSelfPointer1(void)
{
	ObjectsInit();

	Ptr<CRoot>				pRoot;
	Ptr<CTestNamedObject>	pObject;
	BOOL					bResult;
	CBaseObject*			pvObject;

	pRoot = ORoot();

	pObject = OMalloc(CTestNamedObject);
	pObject->Init(1);
	pObject->mpNamedTest1 = pObject;

	pRoot->Add(pObject);
	AssertInt(1, pRoot->NumObjects());

	AssertLongLongInt(3, gcObjects.NumMemoryIndexes());

	pvObject = pObject.BaseObject();
	pObject = NULL;

	//pObject should be destroyed here and not cause a stack overflow.
	bResult = pRoot->Remove(pvObject);
	AssertTrue(bResult);
	AssertInt(0, pRoot->NumObjects());

	AssertLongLongInt(2, gcObjects.NumMemoryIndexes());

	ObjectsKill();
}
void TestObjectsFlushClearGetByName(void)
{
	CFileUtil						cFileUtil;
	CPointer						pObject;
	Ptr<CTestDoubleNamedString>		pDouble;
	Ptr<CRoot>						pRoot;

	cFileUtil.RemoveDir("Output");
	cFileUtil.MakeDir("Output/Dehollowfication");

	ObjectsInit("Output/Dehollowfication");
	SetupObjectsConstructors();

	pRoot = ORoot();
	pDouble = ONMalloc(CTestDoubleNamedString, "Double")->Init();
	pRoot->Add(pDouble);
	AssertLongLongInt(0, gcObjects.NumDatabaseObjects());
	AssertLongLongInt(0, gcObjects.NumDatabaseNames());
	pObject = gcObjects.Get(3);
	AssertNotNull(pObject.Object());
	AssertString("CTestDoubleNamedString", pObject.ClassName());

	gcObjects.Flush(TRUE, TRUE);
	AssertLongLongInt(3, gcObjects.NumDatabaseObjects());
	AssertLongLongInt(2, gcObjects.NumDatabaseNames());

	pObject = gcObjects.Get("Double");
	AssertNotNull(pObject.Object());
	AssertString("CTestDoubleNamedString", pObject.ClassName());

	ObjectsKill();
}
Ptr<CTestDoubleNamedString> SetupObjectsForDehollowfication(void)
{
	Ptr<CTestNamedString>			cNS1;
	Ptr<CTestNamedString>			cNS2;
	Ptr<CTestNamedString>			cNS3;
	Ptr<CTestNamedString>			cDiamond;
	Ptr<CTestDoubleNamedString>		pDouble;
	Ptr<CRoot>						pRoot;
	Ptr<CString>					cS1;
	Ptr<CString>					cS2;

	pRoot = ORoot();

	cDiamond = ONMalloc(CTestNamedString, "Diamond")->Init();

	cS1 = OMalloc(CString)->Init("CS1");
	cNS1 = ONMalloc(CTestNamedString, "NS1")->Init(cS1, cDiamond, "NS1");

	cNS2 = ONMalloc(CTestNamedString, "NS2")->Init(ONull, cDiamond, "NS2");

	cNS3 = ONMalloc(CTestNamedString, "NS3")->Init(ONull, cNS1, "NS3");

	cS2 = OMalloc(CString)->Init("CS2");
	cDiamond->Init(cS2, ONull, "Diamond");

	pDouble = ONMalloc(CTestDoubleNamedString, "Double")->Init(ONull, cNS2, cNS3);

	pRoot->Add(pDouble);
	return pDouble;
}
Example #12
0
///////////////////////////////////////////////////////////////////////////////
/// \brief
/// Find a schema based on name.
///
MgFeatureSchemaCollection* MgFeatureServiceCacheEntry::FindSchema(MgFeatureSchemaCollection* schemas, CREFSTRING schemaName)
{
    Ptr<MgFeatureSchemaCollection> data;

    if (NULL != schemas)
    {
        INT32 schemaCount = schemas->GetCount();

        for (INT32 i = 0; i < schemaCount; ++i)
        {
            Ptr<MgFeatureSchema> currSchema = schemas->GetItem(i);
            STRING currSchemaName = currSchema->GetName();

            // Make a schema copy when a match is found.
            if (schemaName == currSchemaName)
            {
                data = new MgFeatureSchemaCollection();
                data->Add(currSchema);
                break;
            }
        }
    }

    return data.Detach();
}
Example #13
0
void CCoordinateSystemGridBoundary::SetBoundaryExtents (MgCoordinate* southwest,
                                                        MgCoordinate* northeast)
{
    MgGeometryFactory factory;
    Ptr<MgCoordinate> swPnt;
    Ptr<MgCoordinate> sePnt;
    Ptr<MgCoordinate> nePnt;
    Ptr<MgCoordinate> nwPnt;
    Ptr<MgCoordinate> clPnt;
    Ptr<MgCoordinateCollection> collection;

    MG_TRY()
        swPnt = factory.CreateCoordinateXY(southwest->GetX(),southwest->GetY());
        sePnt = factory.CreateCoordinateXY(northeast->GetX(),southwest->GetY());
        nePnt = factory.CreateCoordinateXY(northeast->GetX(),northeast->GetY());
        nwPnt = factory.CreateCoordinateXY(southwest->GetX(),northeast->GetY());
        clPnt = factory.CreateCoordinateXY(southwest->GetX(),southwest->GetY());

        if (!swPnt|| !swPnt || !nePnt || !nwPnt ||!clPnt)
        {
            throw new MgOutOfMemoryException(L"MgCoordinateSystemGridBoundary.SetBoundaryExtents",
                                             __LINE__, __WFILE__, NULL, L"", NULL);
        }

        collection = new MgCoordinateCollection();
        if (collection == NULL)
        {
            throw new MgOutOfMemoryException(L"MgCoordinateSystemGridBoundary.SetBoundaryExtents",
                                             __LINE__, __WFILE__, NULL, L"", NULL);
        }
        collection->Add (swPnt);
        collection->Add (sePnt);
        collection->Add (nePnt);
        collection->Add (nwPnt);
        collection->Add (clPnt);

        Ptr<MgLinearRing> ring = factory.CreateLinearRing (collection);
        if (ring == 0)
        {
            throw new MgOutOfMemoryException(L"MgCoordinateSystemGridBoundary.SetBoundaryExtents",
                                             __LINE__, __WFILE__, NULL, L"", NULL);
        }
        m_GridBoundary = factory.CreatePolygon (ring,NULL);
    MG_CATCH_AND_THROW(L"MgCoordinateSystemGridBoundary.SetBoundaryExtents")
}
void
HwmpReactiveRegressionTest::CreateNodes ()
{
  m_nodes = new NodeContainer;
  m_nodes->Create (6);
  MobilityHelper mobility;
  Ptr<ListPositionAllocator> positionAlloc = CreateObject<ListPositionAllocator>();
  positionAlloc->Add (Vector (  0,   0, 0));
  positionAlloc->Add (Vector (  0, 150, 0));
  positionAlloc->Add (Vector (  0, 300, 0));
  positionAlloc->Add (Vector (  0, 450, 0));
  positionAlloc->Add (Vector (  0, 600, 0));
  positionAlloc->Add (Vector (  0, 750, 0));
  mobility.SetPositionAllocator (positionAlloc);
  mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
  mobility.Install (*m_nodes);
  Simulator::Schedule (Seconds (5.0), &HwmpReactiveRegressionTest::ResetPosition, this);
}
Example #15
0
MgStringCollection* MgSecurityCache::EnumerateRoles(CREFSTRING user)
{
    Ptr<MgStringCollection> roles = new MgStringCollection();

    if (IsUserInRole(user, MgRole::Administrator))
    {
        roles->Add(MgRole::Administrator);
    }

    if (IsUserInRole(user, MgRole::Author))
    {
        roles->Add(MgRole::Author);
    }

    if (IsUserInRole(user, MgRole::Viewer))
    {
        roles->Add(MgRole::Viewer);
    }

    return roles.Detach();
}
Example #16
0
//----------------------------------------------------------
MgDisposableCollection* CCoordinateSystemEnumCategory::Next(UINT32 ulCount)
{
    Ptr<MgDisposableCollection> pOutput;

    MG_TRY()
    pOutput=new MgDisposableCollection;
    if (!pOutput)
    {
        throw new MgOutOfMemoryException(L"MgCoordinateSystemEnum.Next", __LINE__, __WFILE__, NULL, L"", NULL);
    }

    wchar_t* pStr;

    for (; m_iter != m_pCategoryNameList->end(); ++m_iter)
    {
        if (pOutput->GetCount() == ulCount)
        {
            //success
            return pOutput.Detach();
        }

        //get the category definition for the next name in the list
        const char *kpName = (*(m_iter)).Name();
        pStr = Convert_Ascii_To_Wide(kpName);
        if (NULL == pStr)
        {
            throw new MgOutOfMemoryException(L"MgCoordinateSystemEnum.Next", __LINE__, __WFILE__, NULL, L"", NULL);
        }
        STRING str(pStr);
        delete[] pStr;
        Ptr<MgGuardDisposable> pDef = m_pDict->Get(str);
        assert(pDef);
        if (!pDef)
        {
            MgStringCollection arguments;
            arguments.Add(str);
            throw new MgCoordinateSystemLoadFailedException(L"MgCoordinateSystemEnum.Next", __LINE__, __WFILE__, &arguments, L"", NULL);
        }

        //check if this category is filtered out or not
        if (IsFilteredOut(pDef))
        {
            continue;
        }

        //add the category defintion to the output list
        pOutput->Add(pDef);
    }

    MG_CATCH_AND_THROW(L"MgCoordinateSystemEnum.Next")
    return pOutput.Detach();
}
Example #17
0
///////////////////////////////////////////////////////////////////////////
// Returns a transformed copy of this geometric entity.
//
MgGeometricEntity* MgMultiLineString::Transform(MgTransform* transform)
{
    Ptr<MgLineStringCollection> lineStrings = new MgLineStringCollection();

    INT32 count = m_lineStrings->GetCount();
    for (int i = 0; i < count; i++)
    {
        Ptr<MgLineString> lineString = m_lineStrings->GetItem(i);
        Ptr<MgLineString> newLineString = (MgLineString*)lineString->Transform(transform);
        lineStrings->Add(newLineString);
    }

    return new MgMultiLineString(lineStrings);
}
Example #18
0
///////////////////////////////////////////////////////////////////////////
// Returns a transformed copy of this geometric entity.
//
MgGeometricEntity* MgLinearRing::Transform(MgTransform* transform)
{
    Ptr<MgCoordinateCollection> coords = new MgCoordinateCollection();

    INT32 count = m_coordinates->GetCount();

    for (int i = 0; i < count; i++)
    {
        Ptr<MgCoordinate> coord = m_coordinates->GetItem(i);
        Ptr<MgCoordinate> newCoord = transform->Transform(coord);
        coords->Add(newCoord);
    }

    return new MgLinearRing(coords);
}
void TestEmbeddedObjectPointTo(void)
{
	BOOL		bResult;
	CFileUtil	cFileUtil;
	OIndex		oiComplex;
	char*		szClassName;
	
	cFileUtil.RemoveDir("Output/EmbeddedObject");

	MemoryInit();
	ObjectsInit("Output/EmbeddedObject/");
	SetupEmbeddedObjectConstructors();

	Ptr<CRoot> pRoot = ORoot();
	Ptr<CEmbeddedComplex> pComplex = OMalloc(CEmbeddedComplex)->Init();
	oiComplex = pComplex->GetOI();

	Ptr<CEmbeddedContainer> pContainer = &pComplex->mcContainer;
	pRoot->Add(pContainer);

	bResult = gcObjects.Flush(TRUE, TRUE);
	AssertTrue(bResult);

	ObjectsKill();
	MemoryKill();

	AssertNull(&pContainer);

	MemoryInit();
	ObjectsInit("Output/EmbeddedObject/");
	SetupEmbeddedObjectConstructors();

	pRoot = gcObjects.GetRoot();
	AssertTrue(pRoot.IsNotNull());
	pContainer = pRoot->Get(0);
	AssertTrue(pContainer.IsHollow());
	AssertInt(0, pContainer.Object()->GetNumEmbedded());
	AssertLongLongInt(-1, pContainer.GetIndex());

	szClassName = pContainer->ClassName();
	AssertString("CEmbeddedContainer", szClassName);

	pComplex = pContainer->GetEmbeddingContainer();
	//Kinda feels like this test just stopped...

	ObjectsKill();
	MemoryKill();
}
Example #20
0
File: Layer.cpp Project: asir6/Colt
//////////////////////////////////////////////////////////////
// Parse the layer definition XML and extracts scale ranges,
// feature source and feature class from it
//
void MgLayer::GetLayerInfoFromDefinition(MgResourceService* resourceService)
{
    MgLayerBase::GetLayerInfoFromDefinition(resourceService);

    if(m_initIdProps && resourceService != NULL)
    {
        MG_TRY()

        // Generate Id field information for feature sources
        m_idProps.clear();
        if (!m_featureName.empty())
        {
            // If we cannot pull the identity properties, silently ignore it.
            try
            {
                //TODO: Pull site connection directly from resource service
                Ptr<MgUserInformation> userInfo = resourceService->GetUserInfo();
                Ptr<MgSiteConnection> conn = new MgSiteConnection();
                conn->Open(userInfo);

                Ptr<MgFeatureService> featureService = dynamic_cast<MgFeatureService*>(conn->CreateService(MgServiceType::FeatureService));
                Ptr<MgResourceIdentifier> resId = new MgResourceIdentifier(m_featureSourceId);

                // If the class name is fully qualified (prefixed with a schema name),
                // then use it to determine the schema name.
                STRING className;
                STRING schemaName;
                ParseFeatureName(featureService, className, schemaName);

                // Get the identity properties
                Ptr<MgStringCollection> classNames = new MgStringCollection();
                classNames->Add(className);
                Ptr<MgClassDefinitionCollection> classDefs = featureService->GetIdentityProperties(resId, schemaName, classNames);
                if (NULL != classDefs.p && classDefs->GetCount() == 1)
                {
                    Ptr<MgClassDefinition> classDef = classDefs->GetItem(0);
                    PopulateIdentityProperties(classDef);
                }
            }
            catch (MgException* e)
            {
                e->Release();
                // Do nothing here.  A failure to pull selection id's is not critical at this point
            }
        }
        MG_CATCH_AND_THROW(L"MgLayer.GetLayerInfoFromDefinition")
    }
Example #21
0
MgCoordinateIterator* MgMultiLineString::GetCoordinates()
{
    Ptr<MgCoordinateCollection> coords = new MgCoordinateCollection();
    INT32 count = m_lineStrings->GetCount();

    for (int i = 0; i < count; i++)
    {
        Ptr<MgLineString> lineString = m_lineStrings->GetItem(i);
        Ptr<MgCoordinateIterator> lineIterator = lineString->GetCoordinates();

        while (lineIterator->MoveNext())
        {
            coords->Add(Ptr<MgCoordinate>(lineIterator->GetCurrent()));
        }
    }

    return new MgCoordinateIterator(coords);
}
void TestObjectsObjectKillInGraph(void)
{
	Ptr<CTestNamedString>	cNS1;
	Ptr<CTestNamedString>	cNS2;
	Ptr<CRoot>				pRoot;
	Ptr<CString>			cS1;
	Ptr<CString>			cS2;
	CTestNamedString*		pcNS2;
	CString*				pcS2;

	ObjectsInit();

	pRoot = ORoot();

	cS1 = OMalloc(CString);
	cS1->Init("CS1");
	cNS1 = ONMalloc(CTestNamedString, "NS1")->Init(cS1, ONull, "NS1");

	cS2 = OMalloc(CString)->Init("CS2");
	cNS2 = ONMalloc(CTestNamedString, "NS2")->Init(cS2, cNS1, "NS2");

	pRoot->Add(cNS2);
	
	AssertPointer(cNS2->mpAnother.Object(), cNS1.Object());
	AssertLongLongInt(6, gcObjects.NumMemoryIndexes());
	pcNS2 = &cNS2;
	cNS2 = NULL;
	pRoot = NULL;
	cS1 = NULL;
	pcS2 = &cS2;
	cS2 = NULL;
	AssertLongLongInt(6, gcObjects.NumMemoryIndexes());

	cNS1->Kill();

	AssertNull(pcNS2->mpAnother.Object());
	AssertLongLongInt(4, gcObjects.NumMemoryIndexes());
	AssertPointer(pcNS2->mszString.Object(), pcS2);

	ObjectsKill();
}
void TestObjectsObjectKillInArrayInGraph(void)
{
	Ptr<CTestNamedString>	cNS1;
	Ptr<CArrayObject>		cA1;
	Ptr<CArrayObject>		cA2;
	Ptr<CRoot>				pRoot;
	Ptr<CString>			cS1;

	ObjectsInit();

	pRoot = ORoot();

	cS1 = OMalloc(CString)->Init("CS1");
	cNS1 = ONMalloc(CTestNamedString, "NS1")->Init(cS1, ONull, "NS1");

	cA1 = OMalloc(CArrayObject)->Init();
	cA2 = OMalloc(CArrayObject)->Init();

	cA1->Add(cNS1);
	cA2->Add(cNS1);

	pRoot->Add(cA1);
	pRoot->Add(cA2);

	AssertInt(1, cA1->NumPointerTos());
	AssertInt(1, cA2->NumPointerTos());
	AssertLongLongInt(6, gcObjects.NumMemoryIndexes());
	pRoot = NULL;
	cS1 = NULL;
	AssertLongLongInt(6, gcObjects.NumMemoryIndexes());

	cNS1->Kill();
	AssertLongLongInt(4, gcObjects.NumMemoryIndexes());

	AssertInt(0, cA1->NumPointerTos());
	AssertInt(0, cA2->NumPointerTos());


	ObjectsKill();
}
Example #24
0
// The Polygon returned by this function will not (usually) be a simple
// rectangle, but a series of complex curves which (usually) approximate
// a trapazoid.
MgPolygon* CCoordinateSystemGridBoundary::GetBoundary (MgCoordinateSystemTransform* transform,
                                                       double precision)
{
    MgGeometryFactory factory;

    INT32 index;
    INT32 interiorRingCount;

    Ptr<MgPolygon> result;
    Ptr<MgLinearRing> sourceRing;
    Ptr<MgLinearRing> targetRing;
    Ptr<MgLinearRing> exteriorRing;
    Ptr<MgLinearRingCollection> interiorRings;

    MG_TRY()
        // Convert the outer ring.
        sourceRing = m_GridBoundary->GetExteriorRing ();
        exteriorRing = TransformLinearRing (sourceRing,transform,precision);

        interiorRingCount = m_GridBoundary->GetInteriorRingCount ();
        if (interiorRingCount > 0)
        {
            // Create the repository for the interior rings, now that we know
            // there are some (this is rare).
            interiorRings = new MgLinearRingCollection ();

            for (index = 0;index < interiorRingCount;index += 1)
            {
                sourceRing = m_GridBoundary->GetInteriorRing (index);
                targetRing = TransformLinearRing (sourceRing,transform,precision);
                interiorRings->Add (targetRing);
            }
        }
        result = new MgPolygon (exteriorRing,interiorRings);
    MG_CATCH_AND_THROW(L"MgCoordinateSystemGridBoundary.GetBoundary")
    return result.Detach ();
}
Example #25
0
//----------------------------------------------------------
//Fetches the names of the next ulCount items.  The caller
//is responsible for freeing the returned strings via delete[]
//
MgStringCollection* CCoordinateSystemEnumCategory::NextName(UINT32 ulCount)
{
    Ptr<MgStringCollection> pOutput;
    MG_TRY()
    pOutput=new MgStringCollection;
    if (!pOutput)
    {
        throw new MgOutOfMemoryException(L"MgCoordinateSystemEnum.NextName", __LINE__, __WFILE__, NULL, L"", NULL);
    }

    for (; m_iter != m_pCategoryNameList->end(); ++m_iter)
    {
        if (pOutput->GetCount() == ulCount)
        {
            //success
            return pOutput.Detach();
        }

        const char *kpName = (*m_iter).Name();
        if (IsFilteredOut(kpName))
        {
            continue;
        }

        wchar_t *pwName = Convert_Ascii_To_Wide(kpName);
        if (NULL == pwName)
        {
            throw new MgOutOfMemoryException(L"MgCoordinateSystemEnum.NextName", __LINE__, __WFILE__, NULL, L"", NULL);
        }
        pOutput->Add(pwName);
        delete[] pwName;
    }

    MG_CATCH_AND_THROW(L"MgCoordinateSystemEnum.NextName")
    return pOutput.Detach();
}
Example #26
0
// Executes the commands
MgPropertyCollection* MgdUpdateFeaturesCommand::Execute(MgResourceIdentifier* resource,
                                                      MgFeatureCommandCollection* commands,
                                                      bool useTransaction)
{
    Ptr<MgPropertyCollection> propCol;
    FdoITransaction* transaction = NULL;
    bool commited = false;

    MG_FEATURE_SERVICE_TRY()

    if (resource == NULL || commands == NULL)
    {
        throw new MgNullArgumentException(L"MgdUpdateFeaturesCommand.UpdateFeatures", __LINE__, __WFILE__, NULL, L"", NULL);
    }

    INT32 cnt = commands->GetCount();
    if (cnt == 0)
    {
        MgStringCollection arguments;
        arguments.Add(L"2");
        arguments.Add(L"0");

        throw new MgInvalidArgumentException(L"MgdUpdateFeaturesCommand.UpdateFeatures",
            __LINE__, __WFILE__, &arguments, L"MgCollectionEmpty", NULL);
    }

    // Connect to provider
    Connect(resource, NULL);

    propCol = new MgPropertyCollection();

    FdoPtr<FdoIConnection> fdoConn = m_SrvrFeatConn->GetConnection();
    if (useTransaction)
    {
        transaction = fdoConn->BeginTransaction();
    }

    for (INT32 i = 0; i < cnt; i++)
    {
        Ptr<MgProperty> result;
        Ptr<MgFeatureCommand> command = commands->GetItem(i);
        Ptr<MgdFeatureManipulationCommand> fmServerCommand = MgdFeatureManipulationCommand::CreateCommand(command, m_SrvrFeatConn, i);

        MG_FEATURE_SERVICE_TRY()
        // Execute the manipulation command
        result = fmServerCommand->Execute();

        MG_FEATURE_SERVICE_CATCH(L"MgdUpdateFeaturesCommand.UpdateFeatures")

        if (transaction != NULL)
        {
            MG_FEATURE_SERVICE_THROW() // rethrow if updates are done in transaction
        }
        else
        {
            if (mgException != NULL)
            {
                // When an exception is thrown, we need to communicate this back to user in non-transactional case.
                // We can do this either by setting warnings or a string property. Making it as StringProperty would
                // let users know exactly which ones failed and why.
                STRING str;
                MgUtil::Int32ToString(i, str);
                STRING errMsg = mgException->GetDetails();

                result = new MgStringProperty(str, errMsg);  // If there is an exception which means result would null from execute
                mgException = NULL; // Release the pointer
            }
        }
        // NULL property should not be added.
        if (result != NULL)
        {
            propCol->Add(result);
        }
    }

    if (transaction != NULL)
    {
        transaction->Commit();
        commited = true;
    }

    MG_FEATURE_SERVICE_CHECK_CONNECTION_CATCH(resource, L"MgdUpdateFeaturesCommand.UpdateFeatures")

    if (transaction != NULL && !commited)
    {
        transaction->Rollback();
    }

    MG_FEATURE_SERVICE_THROW()

    return propCol.Detach();
}
Example #27
0
MgPropertyCollection* MgdUpdateFeaturesCommand::ExecuteInsert(MgResourceIdentifier* resource, CREFSTRING className, MgBatchPropertyCollection* batchPropertyValues, MgTransaction* trans)
{
    Ptr<MgPropertyCollection> ret;

    MG_FEATURE_SERVICE_TRY()

    CHECK_FEATURE_SOURCE_ARGUMENT(resource, L"MgdUpdateFeaturesCommand::ExecuteInsert");
	CHECKARGUMENTNULL(batchPropertyValues, L"MgdUpdateFeaturesCommand::ExecuteInsert");
	if (className.empty())
		throw new MgNullArgumentException(L"MgdUpdateFeaturesCommand::ExecuteInsert", __LINE__, __WFILE__, NULL, L"", NULL);
	
    ret = new MgPropertyCollection();

    Ptr<MgdFeatureConnection> connWrap;
	FdoPtr<FdoIConnection> conn;
    FdoPtr<FdoITransaction> fdoTrans;
    Ptr<MgdTransaction> mgTrans = dynamic_cast<MgdTransaction*>(trans);
    if (NULL != mgTrans)
    {
        SAFE_ADDREF(mgTrans.p);
        Ptr<MgResourceIdentifier> origFeatureSource = mgTrans->GetFeatureSource();
        //Check that the transaction originates from the same feature source
        if (origFeatureSource->ToString() != resource->ToString())
            throw new MgInvalidArgumentException(L"MgdUpdateFeaturesCommand::ExecuteInsert", __LINE__, __WFILE__, NULL, L"", NULL);

        connWrap = mgTrans->GetConnection(); //Connection is already open
        fdoTrans = mgTrans->GetFdoTransaction();
    }
    else
    {    
        connWrap = new MgdFeatureConnection(resource);
    }

    conn = connWrap->GetConnection();
	FdoPtr<FdoIInsert> insert = (FdoIInsert*)conn->CreateCommand(FdoCommandType_Insert);
	
	insert->SetFeatureClassName(className.c_str());

	FdoPtr<FdoPropertyValueCollection> propVals = insert->GetPropertyValues();
	
    if (NULL != fdoTrans.p)
        insert->SetTransaction(fdoTrans);

    //TODO: Support batch parameters, the main beneficiary of this API. Even then,
    //the value flipping approach employed here has performance benefits for certain
    //providers, like SQLite

    for (INT32 i = 0; i < batchPropertyValues->GetCount(); i++)
    {
        Ptr<MgPropertyCollection> propertyValues = batchPropertyValues->GetItem(i);

        //First feature, set up the FDO property value collection
        if (i == 0)
        {
            for (INT32 i = 0; i < propertyValues->GetCount(); i++)
	        {
		        Ptr<MgProperty> mgp = propertyValues->GetItem(i);
		        FdoPtr<FdoPropertyValue> pv = MgdFeatureUtil::MgPropertyToFdoProperty(mgp);

		        propVals->Add(pv);
	        }
        }
        else //Feature after the first
        {
            //Set all to null
            for (INT32 i = 0; i < propVals->GetCount(); i++)
            {
                FdoPtr<FdoPropertyValue> fp = propVals->GetItem(i);
                FdoPtr<FdoValueExpression> expr = fp->GetValue();
                FdoDataValue* fdv = dynamic_cast<FdoDataValue*>(expr.p);
                FdoGeometryValue* fgv = dynamic_cast<FdoGeometryValue*>(expr.p);
                if (fdv)
                {
                    fdv->SetNull();
                }
                else if (fgv)
                {
                    fgv->SetNullValue();
                }
            }

            //Now set the appropriate values. MgdFeatureUtil does the work
            for (INT32 i = 0; i < propertyValues->GetCount(); i++)
	        {
                Ptr<MgNullableProperty> mgp = (MgNullableProperty*)propertyValues->GetItem(i);
                if (!mgp->IsNull())
                {
                    FdoPtr<FdoPropertyValue> fp = propVals->GetItem(mgp->GetName().c_str());
                    MgdFeatureUtil::UpdateFdoPropertyValue(fp, mgp);
                }
            }
        }

        STRING sIndex;
        MgUtil::Int32ToString(i, sIndex);

        //Insert and stash the result in the property collection
	    FdoPtr<FdoIFeatureReader> insertRes = insert->Execute();

	    Ptr<MgFeatureReader> fr = new MgdFeatureReader(connWrap, insertRes);
        Ptr<MgFeatureProperty> fp = new MgFeatureProperty(sIndex, fr);
        ret->Add(fp);
    }

    MG_FEATURE_SERVICE_CATCH_AND_THROW_WITH_FEATURE_SOURCE(L"MgdUpdateFeaturesCommand::ExecuteInsert", resource)

    return ret.Detach();
}
int InputTestApp::OnStartup(int argc, const char** argv)
{
    if (!pPlatform->SetupWindow(1200,800))
        return 1;
    

    pManager = *DeviceManager::Create();
    
    // This initialization logic supports running two sensors at the same time.
   
    DeviceEnumerator<SensorDevice> isensor = pManager->EnumerateDevices<SensorDevice>();
    DeviceEnumerator<SensorDevice> oculusSensor;
    DeviceEnumerator<SensorDevice> oculusSensor2;
    
    while(isensor)
    {
        DeviceInfo di;
        if (isensor.GetDeviceInfo(&di))
        {
            if (strstr(di.ProductName, "Tracker"))
            {
                if (!oculusSensor)
                    oculusSensor = isensor;
                else if (!oculusSensor2)
                    oculusSensor2 = isensor;
            }
        }

        isensor.Next();
    }

    if (oculusSensor)
    {
        pSensor = *oculusSensor.CreateDevice();

        if (pSensor)
            pSensor->SetRange(SensorRange(4 * 9.81f, 8 * Math<float>::Pi, 1.0f), true);

        if (oculusSensor2)
        {
            // Second Oculus sensor, useful for comparing firmware behavior & settings.
            pSensor2 = *oculusSensor2.CreateDevice();

            if (pSensor2)
                pSensor2->SetRange(SensorRange(4 * 9.81f, 8 * Math<float>::Pi, 1.0f), true);
        }
    }

    oculusSensor.Clear();
    oculusSensor2.Clear();
       
    
    /*
    DeviceHandle hHMD = pManager->EnumerateDevices<HMDDevice>();
    HMDInfo      hmdInfo;
    if (hHMD)
    {        
        hHMD.GetDeviceInfo(&hmdInfo);
    }
    */

    if (pSensor)
        SFusion.AttachToSensor(pSensor);
    if (pSensor2)
        SFusion2.AttachToSensor(pSensor2);

    /*
    // Test rotation: This give rotations clockwise (CW) while looking from
    // origin in the direction of the axis.

    Vector3f xV(1,0,0);
    Vector3f zV(0,0,1);

    Vector3f rxV = Matrix4f::RotationZ(DegreeToRad(10.0f)).Transform(xV);
    Vector3f ryV = Matrix4f::RotationY(DegreeToRad(10.0f)).Transform(xV);
    Vector3f rzV = Matrix4f::RotationX(DegreeToRad(10.0f)).Transform(zV);
    */

    // Report relative mouse motion (not absolute position)
   // pPlatform->SetMouseMode(Mouse_Relative);

    const char* graphics = "d3d10";
    for (int i = 1; i < argc; i++)
        if (!strcmp(argv[i], "-r") && i < argc-1)
            graphics = argv[i+1];

    pRender = pPlatform->SetupGraphics(OVR_DEFAULT_RENDER_DEVICE_SET, graphics,
                                       RendererParams());
  
    //WireframeFill = pRender->CreateSimpleFill(Fill::F_Wireframe);


    
    // *** Rotating Box
    
    pBox = *new Container;
    pBox->Add(Ptr<Model>(        
       *Model::CreateAxisFaceColorBox(-2.0f, 2.0f, Color(0,   0xAA, 0),        // x = green
                                      -1.0f, 1.0f, Color(0xAA,0,    0),        // y = red
                                      -1.0f, 1.0f, Color(0,   0,    0xAA)) )); // z = blue 
    // Drop-down line from box, to make it easier to see differences in angle.
    Ptr<Model> downLine = *new Model(Prim_Lines);
    downLine->AddLine(Vertex(0.0f,-4.5f, 0.0f, 0xFFE0B0B0),
                      Vertex(0.0f, 0.0f, 0.0f, 0xFFE0B0B0));
    pBox->Add(downLine);
    Sc.World.Add(pBox);

    
    // Secondary rotating coordinate object, if we have two values.
    if (pSensor2)
    {
        pBox2 = *new Container;

        // Drop-down line from box, to make it easier to see differences in angle.
        Ptr<Model> lines = *new Model(Prim_Lines);
        lines->AddLine(Vertex( 0.0f,-4.0f, 0.0f, 0xFFA07070),  // -Y
                       Vertex( 0.0f, 0.0f, 0.0f, 0xFFA07070));
        lines->AddLine(Vertex(-4.0f, 0.0f, 0.0f, 0xFF70A070),  // -X
                       Vertex( 0.0f, 0.0f, 0.0f, 0xFF70A070));
        lines->AddLine(Vertex( 0.0f, 0.0f,-4.0f, 0xFF7070A0),  // -Z
                       Vertex( 0.0f, 0.0f, 0.0f, 0xFF7070A0));
        pBox2->Add(lines);
        Sc.World.Add(pBox2);
    }


    // *** World axis X,Y,Z rendering.

    pAxes = *new Model(Prim_Lines);
    pAxes->AddLine(Vertex(-8.0f, 0.0f, 0.0f, 0xFF40FF40),
                   Vertex( 8.0f, 0.0f, 0.0f, 0xFF40FF40)); // X
    pAxes->AddLine(Vertex( 7.6f, 0.4f, 0.4f, 0xFF40FF40),
                   Vertex( 8.0f, 0.0f, 0.0f, 0xFF40FF40)); // X - arrow
    pAxes->AddLine(Vertex( 7.6f,-0.4f,-0.4f, 0xFF40FF40),
                   Vertex( 8.0f, 0.0f, 0.0f, 0xFF40FF40)); // X - arrow

    pAxes->AddLine(Vertex( 0.0f,-8.0f, 0.0f, 0xFFFF4040),
                   Vertex( 0.0f, 8.0f, 0.0f, 0xFFFF4040)); // Y
    pAxes->AddLine(Vertex( 0.4f, 7.6f, 0.0f, 0xFFFF4040),
                   Vertex( 0.0f, 8.0f, 0.0f, 0xFFFF4040)); // Y - arrow
    pAxes->AddLine(Vertex(-0.4f, 7.6f, 0.0f, 0xFFFF4040),
                   Vertex( 0.0f, 8.0f, 0.0f, 0xFFFF4040)); // Y
    
    pAxes->AddLine(Vertex( 0.0f, 0.0f,-8.0f, 0xFF4040FF),
                   Vertex( 0.0f, 0.0f, 8.0f, 0xFF4040FF)); // Z
    pAxes->AddLine(Vertex( 0.4f, 0.0f, 7.6f, 0xFF4040FF),
                   Vertex( 0.0f, 0.0f, 8.0f, 0xFF4040FF)); // Z - arrow
    pAxes->AddLine(Vertex(-0.4f, 0.0f, 7.6f, 0xFF4040FF),
                   Vertex( 0.0f, 0.0f, 8.0f, 0xFF4040FF)); // Z - arrow
    Sc.World.Add(pAxes);
   

    SetView(CurrentView);


    LastUpdate = pPlatform->GetAppTime();
    return 0;
}
int
main (int argc, char *argv[])
{
#ifdef NS3_CLICK

  //
  // Enable logging
  //
  LogComponentEnable ("NsclickUdpClientServerWifi", LOG_LEVEL_INFO);

  //
  // Explicitly create the nodes required by the topology (shown above).
  //
  NS_LOG_INFO ("Create nodes.");
  NodeContainer n;
  n.Create (4);

  NS_LOG_INFO ("Create channels.");
  //
  // Explicitly create the channels required by the topology (shown above).
  //
  std::string phyMode ("DsssRate1Mbps");

  // disable fragmentation for frames below 2200 bytes
  Config::SetDefault ("ns3::WifiRemoteStationManager::FragmentationThreshold", StringValue ("2200"));
  // turn off RTS/CTS for frames below 2200 bytes
  Config::SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold", StringValue ("2200"));
  // Fix non-unicast data rate to be the same as that of unicast
  Config::SetDefault ("ns3::WifiRemoteStationManager::NonUnicastMode",
                      StringValue (phyMode));

  WifiHelper wifi;
  wifi.SetStandard (WIFI_PHY_STANDARD_80211b);

  YansWifiPhyHelper wifiPhy =  YansWifiPhyHelper::Default ();
  // This is one parameter that matters when using FixedRssLossModel
  // set it to zero; otherwise, gain will be added
  wifiPhy.Set ("RxGain", DoubleValue (0) );
  // ns-3 supports RadioTap and Prism tracing extensions for 802.11b
  wifiPhy.SetPcapDataLinkType (YansWifiPhyHelper::DLT_IEEE802_11_RADIO);

  YansWifiChannelHelper wifiChannel;
  wifiChannel.SetPropagationDelay ("ns3::ConstantSpeedPropagationDelayModel");
  // The below FixedRssLossModel will cause the rss to be fixed regardless
  // of the distance between the two stations, and the transmit power
  wifiChannel.AddPropagationLoss ("ns3::FixedRssLossModel","Rss",DoubleValue (-80));
  wifiPhy.SetChannel (wifiChannel.Create ());

  // Add a non-QoS upper mac, and disable rate control
  NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default ();
  wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager",
                                "DataMode",StringValue (phyMode),
                                "ControlMode",StringValue (phyMode));
  // Set it to adhoc mode
  wifiMac.SetType ("ns3::AdhocWifiMac");
  NetDeviceContainer d = wifi.Install (wifiPhy, wifiMac, n);

  MobilityHelper mobility;
  Ptr<ListPositionAllocator> positionAlloc = CreateObject<ListPositionAllocator> ();
  positionAlloc->Add (Vector (0.0, 0.0, 0.0));
  positionAlloc->Add (Vector (10.0, 0.0, 0.0));
  positionAlloc->Add (Vector (20.0, 0.0, 0.0));
  positionAlloc->Add (Vector (0.0, 10.0, 0.0));
  mobility.SetPositionAllocator (positionAlloc);
  mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
  mobility.Install (n);

  //
  // Install Click on the nodes
  //
  ClickInternetStackHelper clickinternet;
  clickinternet.SetClickFile (n.Get (0), "src/click/examples/nsclick-wifi-single-interface.click");
  clickinternet.SetClickFile (n.Get (1), "src/click/examples/nsclick-wifi-single-interface.click");
  clickinternet.SetClickFile (n.Get (2), "src/click/examples/nsclick-wifi-single-interface.click");

  // Node 4 is to run in promiscuous mode. This can be verified
  // from the pcap trace Node4_in_eth0.pcap generated after running
  // this script.
  clickinternet.SetClickFile (n.Get (3), "src/click/examples/nsclick-wifi-single-interface-promisc.click");
  clickinternet.SetRoutingTableElement (n, "rt");
  clickinternet.Install (n);
  Ipv4AddressHelper ipv4;
  //
  // We've got the "hardware" in place.  Now we need to add IP addresses.
  //
  NS_LOG_INFO ("Assign IP Addresses.");
  ipv4.SetBase ("172.16.1.0", "255.255.255.0");
  Ipv4InterfaceContainer i = ipv4.Assign (d);

  NS_LOG_INFO ("Create Applications.");
  //
  // Create one udpServer applications on node one.
  //
  uint16_t port = 4000;
  UdpServerHelper server (port);
  ApplicationContainer apps = server.Install (n.Get (1));
  apps.Start (Seconds (1.0));
  apps.Stop (Seconds (10.0));

  //
  // Create one UdpClient application to send UDP datagrams from node zero to
  // node one.
  //
  uint32_t MaxPacketSize = 1024;
  Time interPacketInterval = Seconds (0.5);
  uint32_t maxPacketCount = 320;
  UdpClientHelper client (i.GetAddress (1), port);
  client.SetAttribute ("MaxPackets", UintegerValue (maxPacketCount));
  client.SetAttribute ("Interval", TimeValue (interPacketInterval));
  client.SetAttribute ("PacketSize", UintegerValue (MaxPacketSize));
  apps = client.Install (NodeContainer (n.Get (0), n.Get (2)));
  apps.Start (Seconds (2.0));
  apps.Stop (Seconds (10.0));

  wifiPhy.EnablePcap ("nsclick-udp-client-server-wifi", d);

  // Force the MAC address of the second node: The current ARP
  // implementation of Click sends only one ARP request per incoming
  // packet for an unknown destination and does not retransmit if no
  // response is received. With the scenario of this example, all ARP
  // requests of node 3 are lost due to interference from node
  // 1. Hence, we fill in the ARP table of node 2 before at the
  // beginning of the simulation
  Simulator::Schedule (Seconds (0.5), &ReadArp, n.Get (2)->GetObject<Ipv4ClickRouting> ());
  Simulator::Schedule (Seconds (0.6), &WriteArp, n.Get (2)->GetObject<Ipv4ClickRouting> ());
  Simulator::Schedule (Seconds (0.7), &ReadArp, n.Get (2)->GetObject<Ipv4ClickRouting> ());

  //
  // Now, do the actual simulation.
  //
  NS_LOG_INFO ("Run Simulation.");
  Simulator::Stop (Seconds (20.0));
  Simulator::Run ();
  Simulator::Destroy ();
  NS_LOG_INFO ("Done.");
#else
  NS_FATAL_ERROR ("Can't use ns-3-click without NSCLICK compiled in");
#endif
}
int main (int argc, char *argv[])
{
  std::string phyMode ("DsssRate1Mbps");
  double rss = -80;  // -dBm
  uint32_t packetSize = 1000; // bytes
  uint32_t numPackets = 1;
  double interval = 1.0; // seconds
  bool verbose = false;

  CommandLine cmd;

  cmd.AddValue ("phyMode", "Wifi Phy mode", phyMode);
  cmd.AddValue ("rss", "received signal strength", rss);
  cmd.AddValue ("packetSize", "size of application packet sent", packetSize);
  cmd.AddValue ("numPackets", "number of packets generated", numPackets);
  cmd.AddValue ("interval", "interval (seconds) between packets", interval);
  cmd.AddValue ("verbose", "turn on all WifiNetDevice log components", verbose);

  cmd.Parse (argc, argv);
  // Convert to time object
  Time interPacketInterval = Seconds (interval);

  // disable fragmentation for frames below 2200 bytes
  Config::SetDefault ("ns3::WifiRemoteStationManager::FragmentationThreshold", StringValue ("2200"));
  // turn off RTS/CTS for frames below 2200 bytes
  Config::SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold", StringValue ("2200"));
  // Fix non-unicast data rate to be the same as that of unicast
  Config::SetDefault ("ns3::WifiRemoteStationManager::NonUnicastMode", 
                      StringValue (phyMode));

  NodeContainer c;
  c.Create (2);

  // The below set of helpers will help us to put together the wifi NICs we want
  WifiHelper wifi;
  if (verbose)
    {
      wifi.EnableLogComponents ();  // Turn on all Wifi logging
    }
  wifi.SetStandard (WIFI_PHY_STANDARD_80211b);

  YansWifiPhyHelper wifiPhy =  YansWifiPhyHelper::Default ();
  // This is one parameter that matters when using FixedRssLossModel
  // set it to zero; otherwise, gain will be added
  wifiPhy.Set ("RxGain", DoubleValue (0) ); 
  // ns-3 supports RadioTap and Prism tracing extensions for 802.11b
  wifiPhy.SetPcapDataLinkType (YansWifiPhyHelper::DLT_IEEE802_11_RADIO); 

  YansWifiChannelHelper wifiChannel;
  wifiChannel.SetPropagationDelay ("ns3::ConstantSpeedPropagationDelayModel");
  // The below FixedRssLossModel will cause the rss to be fixed regardless
  // of the distance between the two stations, and the transmit power
  wifiChannel.AddPropagationLoss ("ns3::FixedRssLossModel","Rss",DoubleValue (rss));
  wifiPhy.SetChannel (wifiChannel.Create ());

  // Add a non-QoS upper mac, and disable rate control
  NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default ();
  wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager",
                                "DataMode",StringValue (phyMode),
                                "ControlMode",StringValue (phyMode));
  // Set it to adhoc mode
  wifiMac.SetType ("ns3::AdhocWifiMac");
  NetDeviceContainer devices = wifi.Install (wifiPhy, wifiMac, c);

  // Note that with FixedRssLossModel, the positions below are not 
  // used for received signal strength. 
  MobilityHelper mobility;
  Ptr<ListPositionAllocator> positionAlloc = CreateObject<ListPositionAllocator> ();
  positionAlloc->Add (Vector (0.0, 0.0, 0.0));
  positionAlloc->Add (Vector (5.0, 0.0, 0.0));
  mobility.SetPositionAllocator (positionAlloc);
  mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
  mobility.Install (c);

  InternetStackHelper internet;
  internet.Install (c);

  Ipv4AddressHelper ipv4;
  NS_LOG_INFO ("Assign IP Addresses.");
  ipv4.SetBase ("10.1.1.0", "255.255.255.0");
  Ipv4InterfaceContainer i = ipv4.Assign (devices);

  TypeId tid = TypeId::LookupByName ("ns3::UdpSocketFactory");
  Ptr<Socket> recvSink = Socket::CreateSocket (c.Get (0), tid);
  InetSocketAddress local = InetSocketAddress (Ipv4Address::GetAny (), 80);
  recvSink->Bind (local);
  recvSink->SetRecvCallback (MakeCallback (&ReceivePacket));

  Ptr<Socket> source = Socket::CreateSocket (c.Get (1), tid);
  InetSocketAddress remote = InetSocketAddress (Ipv4Address ("255.255.255.255"), 80);
  source->SetAllowBroadcast (true);
  source->Connect (remote);

  // Tracing
  wifiPhy.EnablePcap ("wifi-simple-adhoc", devices);

  // Output what we are doing
  NS_LOG_UNCOND ("Testing " << numPackets  << " packets sent with receiver rss " << rss );

  Simulator::ScheduleWithContext (source->GetNode ()->GetId (),
                                  Seconds (1.0), &GenerateTraffic, 
                                  source, packetSize, numPackets, interPacketInterval);

  Simulator::Run ();
  Simulator::Destroy ();

  return 0;
}