private WebResponse <TContract> AcquireEntity(MdmId sourceIdentifier, Func <WebResponse <TContract> > finder)
        {
            // Pretty sure we will have a cache miss if we get here, so do the OOP call outside the
            // critical section
            Logger.Debug("Start: CachePolicyMdmEntityService.AcquireEntity - Invoking finder");
            var response = finder.Invoke();

            // NB Single-threaded on requests, but can't avoid that somewhere
            lock (this.syncLock)
            {
                Logger.DebugFormat("CachePolicyMdmEntityService.AcquireEntity : checking cache for {0}", sourceIdentifier.Identifier);

                var entity = cache.Get <TContract>(sourceIdentifier);
                if (entity != null)
                {
                    Logger.DebugFormat("CachePolicyMdmEntityService.AcquireEntity : Found in cache {0}", sourceIdentifier.Identifier);
                    var webResponse = new WebResponse <TContract> {
                        Code = HttpStatusCode.OK, Message = entity, IsValid = true
                    };
                    webResponse.LogResponse();
                    return(webResponse);
                }

                // Otherwise process the response from the web call
                Logger.Debug("CachePolicyMdmEntityService.AcquireEntity : Not found in cache. Processing response from the web call");
                if (response.IsValid)
                {
                    this.ProcessContract(response);
                }
            }
            response.LogResponse();
            return(response);
        }
        private IDictionary <string, List <MdmId> > BuildCommodityInstrumentTypeLookups()
        {
            var search = SearchBuilder.CreateSearch();

            var webResponse = Client.Search <CommodityInstrumentType>(search);

            if (!webResponse.IsValid)
            {
                throw new Exception(String.Format("Unable to obtain search results for CommodityInstrumentType: {0}", webResponse.Fault.Message));
            }

            var dictionary = new Dictionary <string, List <MdmId> >();

            foreach (var result in webResponse.Message)
            {
                MdmId adcCommodityId = result.Identifiers.FirstOrDefault(x => x.SystemName == "ADC");
                if (adcCommodityId != null)
                {
                    string adcCommodity = AdcCommodity(adcCommodityId.Identifier);

                    if (!dictionary.ContainsKey(adcCommodity))
                    {
                        dictionary.Add(adcCommodity, new List <MdmId>());
                    }

                    MdmId nexusId = result.Identifiers.First(x => x.IsMdmId);
                    dictionary[adcCommodity].Add(nexusId);
                }
            }

            return(dictionary);
        }
Ejemplo n.º 3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="mdmId"></param>
        /// <returns></returns>
        public TContract Get <TContract>(MdmId mdmId) where TContract : class, IMdmEntity
        {
            var entity = default(TContract);

            if (mdmId == null)
            {
                return(entity);
            }

            if (mdmId.IsMdmId)
            {
                int id;
                if (int.TryParse(mdmId.Identifier, out id))
                {
                    return(Get <TContract>(id));
                }
            }

            var mdmIdCacheKey = CreateCacheKeyFromMdmId(mdmId);

            var identifier = Get <int?>(mdmIdCacheKey);

            if (identifier.HasValue)
            {
                entity = Get <TContract>(identifier.Value);
                //If mapping doesnt belong to entity (may be mapping got removed) then clear it from cache
                if (entity == null || !entity.Identifiers.Any(a => a.Identifier == mdmId.Identifier && a.SystemName == mdmId.SystemName))
                {
                    Remove(mdmIdCacheKey);
                    entity = null;
                }
            }

            return(entity);
        }
        private EntityId GetInstrumentType(string adcCommodity)
        {
            if (string.IsNullOrWhiteSpace(adcCommodity))
            {
                return(null);
            }

            var instrumentType         = string.Empty;
            var partyCrossMapCommodity = adcCommodity.ToLower();

            if (partyCrossMapCommodity.Contains("swap"))
            {
                instrumentType = "Swap";
            }
            else if (partyCrossMapCommodity.Contains("future"))
            {
                instrumentType = "Future";
            }

            if (string.IsNullOrWhiteSpace(instrumentType))
            {
                return(null);
            }

            var nexusId = new MdmId {
                Identifier = instrumentType, SystemName = "ADC", IsMdmId = false
            };

            return(new EntityId {
                Identifier = nexusId, Name = instrumentType
            });
        }
Ejemplo n.º 5
0
        public WebResponse <TContract> Get(MdmId identifier, DateTime?validAt)
        {
            try
            {
                Logger.DebugFormat("Start: CachingMdmEntityService.Get<{0}> {1} asOf {2}", this.entityName, identifier, validAt);
                int entityId;
                WebResponse <TContract> response;

                Logger.DebugFormat("CachingMdmEntityService.Get - Checking {0} in cache", identifier);

                if (this.mappings.TryGetValue(identifier, out entityId))
                {
                    Logger.DebugFormat("CachingMdmEntityService.Get - {0} found in cache", identifier);
                    response = new WebResponse <TContract> {
                        Code = HttpStatusCode.OK, Message = this.entities[entityId]
                    };
                }
                else
                {
                    Logger.DebugFormat("CachingMdmEntityService.Get - {0} not found in cache. Invoking Service...", identifier);
                    response = this.AcquireEntity(identifier, () => this.service.Get(identifier, validAt));
                }

                response.LogResponse();

                return(response);
            }
            finally
            {
                Logger.DebugFormat("Stop: CachingMdmEntityService.Get {0} asOf {1}", identifier, validAt);
            }
        }
        public void ReturnIdentifierOfMdmId()
        {
            var value = new MdmId { Identifier = "A" };

            var candidate = value.ToIdentifier();
            Assert.AreEqual("A", candidate);
        }
        public void ValidContractAdded()
        {
            // Arrange
            var validatorFactory = new Mock<IValidatorEngine>();
            var mappingEngine = new Mock<IMappingEngine>();
            var repository = new Mock<IRepository>();
            var searchCache = new Mock<ISearchCache>();

            var service = new PartyService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object);
            var identifier = new MdmId { SystemName = "Test", Identifier = "A" };
            var message = new CreateMappingRequest
            {
                EntityId = 12,
                Mapping = identifier
            };

            var system = new MDM.SourceSystem { Name = "Test" };
            var mapping = new PartyMapping { System = system, MappingValue = "A" };
            validatorFactory.Setup(x => x.IsValid(It.IsAny<CreateMappingRequest>(), It.IsAny<IList<IRule>>())).Returns(true);
            mappingEngine.Setup(x => x.Map<EnergyTrading.Mdm.Contracts.MdmId, PartyMapping>(identifier)).Returns(mapping);

            var party = new MDM.Party();
            repository.Setup(x => x.FindOne<MDM.Party>(12)).Returns(party);

            // Act
            var candidate = (PartyMapping)service.CreateMapping(message);

            // Assert
            Assert.AreSame(mapping, candidate);
            repository.Verify(x => x.Save(party));
            repository.Verify(x => x.Flush());
        }
        public void NotEqualOnNull()
        {
            var value = new MdmId {
                SystemName = "CME", Identifier = "MFF"
            };

            Assert.IsFalse(value.Equals(null));
        }
Ejemplo n.º 9
0
        public static EntityId CreateNexusEntityId(this IEntity entity, Func <string> name)
        {
            MdmId mdmMapping = CreateNexusMapping(entity);

            return(mdmMapping == null ? null : new EntityId {
                Identifier = mdmMapping, Name = name()
            });
        }
        public void ReturnValueIfSystemFound()
        {
            var expected = new MdmId { SystemName = "A", Identifier = "A" };
            var identifiers = new List<MdmId> { new MdmId(), expected };

            var candidate = identifiers.SystemId("A");
            Assert.AreSame(expected, candidate);
        }
        public void ReturnNullIfMdmIdIsNull()
        {
            MdmId value = null;

            var candidate = value.ToIdentifier();

            Assert.IsNull(candidate);
        }
        public void ReturnNullIfSystemNotFound()
        {
            var expected = new MdmId { SystemName = "A", Identifier = "A" };
            var identifiers = new List<MdmId> { new MdmId(), expected };

            var candidate = identifiers.SystemId("B");
            Assert.IsNull(candidate);
        }
        public void ToStringDisplaysSystemAndIdentifier()
        {
            var value = new MdmId {
                SystemName = "CME", Identifier = "MFF"
            };

            Assert.AreEqual("CME/MFF", value.ToString());
        }
        public void ShouldReturnFalseOnNullEntity()
        {
            SourceSystem entity = null;

            var value = new MdmId { SystemName = "B", Identifier = "B" };

            Assert.IsFalse(entity.HasIdentifier(value));
        }
Ejemplo n.º 15
0
 public WebResponse <MdmId> CreateMapping <TContract>(int id, MdmId identifier, MdmRequestInfo requestInfo, uint version = 0) where TContract : IMdmEntity
 {
     if (Logger.IsDebugEnabled)
     {
         Logger.DebugFormat("MdmService.CreateMapping<{0}>: {1} {2}", typeof(TContract).Name, id, identifier);
     }
     return(this.factory.EntityService <TContract>(version).CreateMapping(id, identifier, requestInfo));
 }
Ejemplo n.º 16
0
 /// <summary>
 /// Map from a MdmId to another system
 /// </summary>
 /// <param name="identifier"></param>
 /// <param name="targetSystem"></param>
 /// <returns></returns>
 public WebResponse <MappingResponse> CrossMap <TContract>(MdmId identifier, string targetSystem, uint version = 0)
     where TContract : IMdmEntity
 {
     if (Logger.IsDebugEnabled)
     {
         Logger.DebugFormat("MdmService.CrossMap<{0}>: {1} {2}", typeof(TContract).Name, identifier, targetSystem);
     }
     return(this.factory.EntityService <TContract>(version).CrossMap(identifier, targetSystem));
 }
        public void ReturnSystemIdentifierIfPresent()
        {
            var expected = new MdmId { SystemName = "A"};

            var identifiers = new List<MdmId> { new MdmId(), expected };

            var candidate = identifiers.PrimaryIdentifier("A");
            Assert.AreSame(expected, candidate);
        }
        public void ShouldReturnFalseIfNotPresent()
        {
            var entity = new SourceSystem();
            entity.Identifiers.Add(new MdmId { SystemName = "A", Identifier = "A" });

            var value = new MdmId { SystemName = "B", Identifier = "B" };

            Assert.IsFalse(entity.HasIdentifier(value));
        }
Ejemplo n.º 19
0
 public WebResponse <TContract> Get <TContract>(MdmId identifier, DateTime?asof, uint version = 0)
     where TContract : IMdmEntity
 {
     if (Logger.IsDebugEnabled)
     {
         Logger.DebugFormat("MdmService.Get<{0}>: {1} {2}", typeof(TContract).Name, identifier, asof);
     }
     return(this.factory.EntityService <TContract>(version).Get(identifier));
 }
        public void ReturnNexusIdentifier()
        {
            var expected = new MdmId { Identifier = "1", SystemName = SystemName };
            var entity = new SourceSystem { Identifiers = new MdmIdList { new MdmId(), expected } };

            var candidate = entity.ToSystemId(SystemName);

            Assert.AreEqual(expected, candidate);
        }
Ejemplo n.º 21
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="mdmId"></param>
        /// <param name="identifier"></param>
        /// <param name="policy"></param>
        public void Add(MdmId mdmId, int identifier, CacheItemPolicy policy = null)
        {
            if (mdmId == null || (string.IsNullOrWhiteSpace(mdmId.SystemName) || string.IsNullOrWhiteSpace(mdmId.Identifier)))
            {
                return;
            }

            Add(CreateCacheKeyFromMdmId(mdmId), new int?(identifier));
        }
        public void ReturnOriginatingIdentifierIfPresent()
        {
            var expected = new MdmId { SourceSystemOriginated = true };

            var identifiers = new List<MdmId> { new MdmId(), expected };

            var candidate = identifiers.PrimaryIdentifier();
            Assert.AreSame(expected, candidate);
        }
        public void ReturnFirstIdentiiferIfOtherRulesFail()
        {
            var expected = new MdmId { SystemName = "A" };

            var identifiers = new List<MdmId> { expected, new MdmId() };

            var candidate = identifiers.PrimaryIdentifier("B");
            Assert.AreSame(expected, candidate);
        }
        public void ReturnNexusIdentifier()
        {
            var expected = new MdmId { Identifier = "1", IsMdmId = true };
            var entity = new SourceSystem { Identifiers = new MdmIdList { new MdmId(), expected } };

            var candidate = entity.ToMdmKey();

            Assert.AreEqual(1, candidate);
        }
Ejemplo n.º 25
0
        public WebResponse <MappingResponse> CrossMap(MdmId identifier, string targetSystem)
        {
            if (identifier == null)
            {
                throw new ArgumentNullException("identifier");
            }

            return(this.CrossMap(identifier.SystemName, identifier.Identifier, targetSystem));
        }
 public MappingUpdateViewModel(
     IEventAggregator eventAggregator,
     IRegionManager regionManager,
     IMappingService mappingService)
 {
     this.nexusId         = this.NewMdmId();
     this.eventAggregator = eventAggregator;
     this.regionManager   = regionManager;
     this.mappingService  = mappingService;
 }
        public void ReturnValueForEntityIfSystemFound()
        {
            var expected = new MdmId { SystemName = "A", Identifier = "A" };
            var entity = new SourceSystem();
            entity.Identifiers.Add(new MdmId());
            entity.Identifiers.Add(expected);

            var candidate = entity.SystemId("A");
            Assert.AreSame(expected, candidate);
        }
        public void ShouldReturnFalseOnNullEntity()
        {
            SourceSystem entity = null;

            var value = new MdmId {
                SystemName = "B", Identifier = "B"
            };

            Assert.IsFalse(entity.HasIdentifier(value));
        }
        public void ReturnIdentifierOfMdmId()
        {
            var value = new MdmId {
                Identifier = "A"
            };

            var candidate = value.ToIdentifier();

            Assert.AreEqual("A", candidate);
        }
 public MappingUpdateViewModel(
     IEventAggregator eventAggregator, 
     IRegionManager regionManager, 
     IMappingService mappingService)
 {
     this.nexusId = this.NewMdmId();
     this.eventAggregator = eventAggregator;
     this.regionManager = regionManager;
     this.mappingService = mappingService;
 }
        private EntityId GetCommodity(string adcCommodity)
        {
            var commodity = string.Empty;

            if (string.IsNullOrWhiteSpace(adcCommodity))
            {
                return(null);
            }

            var partyCrossMapCommodity = adcCommodity.ToLower();

            if (partyCrossMapCommodity.Contains("fx"))
            {
                commodity = "FX";
            }
            else if (partyCrossMapCommodity.Contains("coal"))
            {
                commodity = "Coal";
            }
            else if (partyCrossMapCommodity.Contains("carbon"))
            {
                commodity = "Carbon";
            }
            else if (partyCrossMapCommodity.Contains("gas"))
            {
                commodity = "Natural Gas";
            }
            else if (partyCrossMapCommodity.Contains("oil"))
            {
                commodity = "Oil";
            }
            else if (partyCrossMapCommodity.Contains("power"))
            {
                commodity = "Power";
            }
            else if (partyCrossMapCommodity.Contains("freightdry"))
            {
                commodity = "Freight (Dry)";
            }

            if (string.IsNullOrWhiteSpace(commodity))
            {
                return(null);
            }

            var commodityId = new MdmId()
            {
                Identifier = commodity, SystemName = "ADC", IsMdmId = false
            };

            return(new EntityId()
            {
                Identifier = commodityId, Name = commodity
            });
        }
Ejemplo n.º 32
0
 /// <summary>
 /// Unifies get and create for a particular mapping
 /// </summary>
 /// <typeparam name="TContract"></typeparam>
 /// <param name="id"></param>
 /// <param name="mapping">mapping to update</param>
 /// <returns></returns>
 protected MdmId GetOrCreateMapping <TContract>(int id, MdmId mapping) where TContract : class, IMdmEntity
 {
     return(GetCreate(
                () => this.GetOrDeleteMappingWithDefaultReverseCheck <TContract>(id, mapping),
                () =>
                Client.CreateMapping <TContract>(
                    id,
                    mapping.SystemName,
                    mapping.Identifier,
                    mapping.DefaultReverseIndSpecified ? mapping.DefaultReverseInd.Value : false)));
 }
        public void ReturnOriginatingIdentifierForEntityIfPresent()
        {
            var expected = new MdmId { SourceSystemOriginated = true };

            var entity = new SourceSystem();
            entity.Identifiers.Add(new MdmId());
            entity.Identifiers.Add(expected);

            var candidate = entity.PrimaryIdentifier();
            Assert.AreSame(expected, candidate);
        }
        public void ShouldReturnDefaultWhenUnableToLocateEntity()
        {
            // given
            var nexusId = new MdmId { SystemName = "Nexus", Identifier = "0" };

            // when
            var candidate = this.MdmEntityLocatorService.Get<PartyRole>(nexusId);

            // then
            Assert.AreEqual(default(PartyRole), candidate);
        }
Ejemplo n.º 35
0
 public WebResponse <MdmId> CreateMapping(int id, MdmId identifier, MdmRequestInfo requestInfo)
 {
     try
     {
         Logger.DebugFormat("Start : CachingMdmEntityService.CreateMapping<{0}> - {1} {2}", this.entityName, id, identifier);
         return(this.service.CreateMapping(id, identifier));
     }
     finally
     {
         Logger.DebugFormat("Stop : CachingMdmEntityService.CreateMapping<{0}>", this.entityName);
     }
 }
        private bool TryCreateMapping(string entityName, MdmId newMapping, MappingUpdatedEvent updatedEvent)
        {
            var response = mappingService.CreateMapping(entityName, updatedEvent.EntityId, newMapping);

            if (!response.IsValid)
            {
                this.eventAggregator.Publish(
                    new ErrorEvent(response.Fault != null ? response.Fault.Message : "Unknown Error"));
                return(false);
            }
            return(true);
        }
 public WebResponse <MdmId> CreateMapping(int id, MdmId identifier, MdmRequestInfo requestInfo)
 {
     try
     {
         Logger.DebugFormat("Start:  CachePolicyMdmEntityService.CreateMapping<{0}>: {1}. Calling service to create mapping", this.entityName, identifier);
         return(this.service.CreateMapping(id, identifier, requestInfo));
     }
     finally
     {
         Logger.DebugFormat("Stop: CachePolicyMdmEntityService.CreateMapping<{0}>: {1}", this.entityName, identifier);
     }
 }
Ejemplo n.º 38
0
        public PortfolioHierarchyList Build(List <PortfolioHierarchyFake> fakes)
        {
            var portfolioHierarchys = new List <PortfolioHierarchy>();

            foreach (var fake in fakes)
            {
                logger.InfoFormat("Building Portfolio {0} of {1}", portfolioHierarchys.Count, fakes.Count);
                var portfolioHierarchy = new PortfolioHierarchy {
                    Identifiers = fake.Identifiers
                };

                // child
                var childResponse = EntityFind(fake.Details.ChildPortfolio);
                if (childResponse.IsValid && childResponse.Message != null)
                {
                    MdmId nexusId = childResponse.Message.ToMdmId();

                    portfolioHierarchy.Details.ChildPortfolio = new EntityId {
                        Identifier = nexusId
                    };
                }

                // parent
                var parentResponse = EntityFind(fake.Details.ParentPortfolio);
                if (parentResponse.IsValid && parentResponse.Message != null)
                {
                    portfolioHierarchy.Details.ParentPortfolio = new EntityId
                    {
                        Identifier =
                            parentResponse.Message.ToMdmId()
                    };
                }

                portfolioHierarchy.Details.Hierarchy = new EntityId
                {
                    Identifier =
                        new MdmId
                    {
                        Identifier = "1",
                        IsMdmId    = true
                    },
                    Name = "Coal"
                };

                portfolioHierarchys.Add(portfolioHierarchy);
            }

            var list = new PortfolioHierarchyList();

            list.AddRange(portfolioHierarchys);

            return(list);
        }
        public MappingViewModel(IEventAggregator eventAggregator)
        {
            this.eventAggregator = eventAggregator;
            this.nexusId         = this.NewMdmId();

            this.SystemName             = this.nexusId.SystemName;
            this.MappingString          = this.nexusId.Identifier;
            this.SourceSystemOriginated = this.nexusId.SourceSystemOriginated;
            this.DefaultReverseInd      = this.nexusId.DefaultReverseInd.Value;
            this.StartDate = this.nexusId.StartDate.Value;
            this.EndDate   = this.nexusId.EndDate.Value;
        }
        public void ValidDetailsSaved()
        {
            const int mappingId = 12;

            // Arrange
            var validatorFactory = new Mock <IValidatorEngine>();
            var mappingEngine    = new Mock <IMappingEngine>();
            var repository       = new Mock <IRepository>();
            var searchCache      = new Mock <ISearchCache>();

            var service = new SourceSystemService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object);

            // NB Don't put mappingId here - service assigns it
            var identifier = new MdmId {
                SystemName = "Test", Identifier = "A"
            };
            var message = new AmendMappingRequest {
                MappingId = mappingId, Mapping = identifier, Version = 34
            };

            var start  = new DateTime(2000, 12, 31);
            var finish = DateUtility.Round(SystemTime.UtcNow().AddDays(5));
            var s1     = new SourceSystem {
                Name = "Test"
            };
            var m1 = new SourceSystemMapping {
                Id = mappingId, System = s1, MappingValue = "1", Version = 34UL.GetVersionByteArray(), Validity = new DateRange(start, DateUtility.MaxDate)
            };
            var m2 = new SourceSystemMapping {
                Id = mappingId, System = s1, MappingValue = "1", Validity = new DateRange(start, finish)
            };

            // NB We deliberately bypasses the business logic
            var entity = new MDM.SourceSystem();

            m1.SourceSystem = entity;
            entity.Mappings.Add(m1);

            validatorFactory.Setup(x => x.IsValid(It.IsAny <AmendMappingRequest>(), It.IsAny <IList <IRule> >())).Returns(true);
            repository.Setup(x => x.FindOne <SourceSystemMapping>(mappingId)).Returns(m1);
            mappingEngine.Setup(x => x.Map <EnergyTrading.Mdm.Contracts.MdmId, SourceSystemMapping>(identifier)).Returns(m2);

            // Act
            service.UpdateMapping(message);

            // Assert
            Assert.AreEqual(mappingId, identifier.MappingId, "Mapping identifier differs");
            // Proves we have an update not an add
            Assert.AreEqual(1, entity.Mappings.Count, "Mapping count differs");
            // NB Don't verify result of Update - already covered by SourceSystemMappingFixture
            repository.Verify(x => x.Save(entity));
            repository.Verify(x => x.Flush());
        }
        public void ShouldReturnFalseOnNullIdentifier()
        {
            var entity = new SourceSystem();

            entity.Identifiers.Add(new MdmId {
                SystemName = "A", Identifier = "A"
            });

            MdmId value = null;

            Assert.IsFalse(entity.HasIdentifier(value));
        }
        public void ShouldRetrieveFromCacheIfClientRequestBySystemMapping()
        {
            const string CacheKey = "MDM.SourceSystem";

            // Given
            var mockMdmEntityService = new Mock <IMdmEntityService <SourceSystem> >();
            var mockConfigManager    = new Mock <IConfigurationManager>();
            var inmemoryCacheRepo    = new DefaultMdmClientCacheRepository(new InMemoryCacheRepository());

            mockConfigManager.Setup(x => x.AppSettings).Returns(new NameValueCollection {
                { "CacheItemPolicy.Expiration." + CacheKey, "3500" }
            });

            var cachePolicyFactory    = new AbsoluteCacheItemPolicyFactory(CacheKey, mockConfigManager.Object);
            var locationEntityService = new CachePolicyMdmEntityService <SourceSystem>(mockMdmEntityService.Object, cachePolicyFactory, inmemoryCacheRepo);
            var nexusId = new MdmId {
                SystemName = "Nexus", Identifier = "1", IsMdmId = true
            };
            var adcId = new MdmId {
                SystemName = "ADC", Identifier = "123", IsMdmId = false
            };
            var location = new SourceSystem
            {
                Identifiers = new MdmIdList {
                    nexusId, adcId
                },
                Details = new SourceSystemDetails {
                    Name = "Blah"
                }
            };

            //Setup a context, i.e. calling once to retrieve location should cache an entity..
            mockMdmEntityService.Setup(x => x.Get(adcId, It.IsAny <DateTime?>())).Returns(
                new WebResponse <SourceSystem> {
                Code = HttpStatusCode.OK, IsValid = true, Message = location
            });

            var response = locationEntityService.Get(adcId);

            response.Code.Should().Be(HttpStatusCode.OK);
            response.Message.ToMdmId().Identifier.Should().Be(nexusId.Identifier);

            // When , we call second time..
            response = locationEntityService.Get(adcId);

            // Then
            // It should not call mdm service again... should retrive form cache, so that verify...
            mockMdmEntityService.Verify(x => x.Get(adcId, It.IsAny <DateTime?>()), Times.Once());
            mockMdmEntityService.Verify(x => x.Get(It.IsAny <int>(), It.IsAny <DateTime?>()), Times.Never());
            response.Code.Should().Be(HttpStatusCode.OK);
            response.Message.ToMdmId().Identifier.Should().Be(nexusId.Identifier);
        }
        public CommodityInstrumentTypeList BuildCommodityInstrumentTypes(IQueryable data)
        {
            var commodityInstrumentTypes = new CommodityInstrumentTypeList();

            var adcCommodityList = data.Cast <PartyCrossMap>()
                                   .Where(x => x.Commodity != null)
                                   .Select(x => x.Commodity)
                                   .Distinct()
                                   .ToList();

            foreach (var adcCommodity in adcCommodityList)
            {
                if (string.IsNullOrWhiteSpace(adcCommodity))
                {
                    continue;
                }

                var nexusId = new MdmId
                {
                    Identifier             = adcCommodity,
                    SourceSystemOriginated = false,
                    IsMdmId    = false,
                    SystemName = "ADC"
                };

                var commodity          = this.GetCommodity(adcCommodity);
                var instrumentType     = this.GetInstrumentType(adcCommodity);
                var instrumentDelivery = this.GetInstrumentDelivery(adcCommodity);

                if (commodity == null)
                {
                    continue;
                }

                var commodityInstrumentType = new CommodityInstrumentType
                {
                    Identifiers = new MdmIdList {
                        nexusId
                    },
                    Details =
                    {
                        Commodity          = commodity,
                        InstrumentType     = instrumentType,
                        InstrumentDelivery = instrumentDelivery
                    }
                };

                commodityInstrumentTypes.Add(commodityInstrumentType);
            }

            return(commodityInstrumentTypes);
        }
        public void ReturnNullIfSystemNotFound()
        {
            var expected = new MdmId {
                SystemName = "A", Identifier = "A"
            };
            var identifiers = new List <MdmId> {
                new MdmId(), expected
            };

            var candidate = identifiers.SystemIdentifier("B");

            Assert.IsNull(candidate);
        }
        public void ShouldReturnDefaultWhenUnableToLocateEntity()
        {
            // given
            var nexusId = new MdmId {
                SystemName = "Nexus", Identifier = "0"
            };

            // when
            var candidate = this.MdmEntityLocatorService.Get <SourceSystem>(nexusId);

            // then
            Assert.AreEqual(default(SourceSystem), candidate);
        }
        public void EqualOnSystemNameIdentifier()
        {
            var value = new MdmId
            {
                SystemName = "CME",
                Identifier = "MFF",
                IsMdmId = true,
                StartDate = DateTime.Now,
                EndDate = DateTime.Now.AddDays(5)
            };
            var candidate = new MdmId { SystemName = "CME", Identifier = "MFF" };

            Assert.IsTrue(value.Equals(candidate));
        }
        public CommodityInstrumentTypeList BuildCommodityInstrumentTypes(IQueryable data)
        {
            var commodityInstrumentTypes = new CommodityInstrumentTypeList();

            var adcCommodityList = data.Cast<PartyCrossMap>()
                                    .Where(x => x.Commodity != null)
                                    .Select(x => x.Commodity)
                                    .Distinct()
                                    .ToList();

            foreach (var adcCommodity in adcCommodityList)
            {
                if (string.IsNullOrWhiteSpace(adcCommodity))
                {
                    continue;
                }

                var nexusId = new MdmId
                {
                    Identifier = adcCommodity,
                    SourceSystemOriginated = false,
                    IsMdmId = false,
                    SystemName = "ADC"
                };

                var commodity = this.GetCommodity(adcCommodity);
                var instrumentType = this.GetInstrumentType(adcCommodity);
                var instrumentDelivery = this.GetInstrumentDelivery(adcCommodity);

                if (commodity == null)
                {
                    continue;
                }

                var commodityInstrumentType = new CommodityInstrumentType
                    {
                        Identifiers = new MdmIdList { nexusId },
                        Details =
                            {
                                Commodity = commodity,
                                InstrumentType = instrumentType,
                                InstrumentDelivery = instrumentDelivery
                            }
                    };

                commodityInstrumentTypes.Add(commodityInstrumentType);
            }

            return commodityInstrumentTypes;
        }
        protected static void Establish_context()
        {
            client = new HttpClient();
            entity = Script.PersonData.CreateBasicEntityWithOneMapping();
            var getResponse = client.Get(ServiceUrl["Person"] + entity.Id);
            person = getResponse.Content.ReadAsDataContract<EnergyTrading.MDM.Contracts.Sample.Person>();
            mappingId = person.Identifiers.Where(x => !x.IsMdmId).First();

            var mappingGetResponse = client.Get(ServiceUrl["Person"] +  person.NexusId() + "/mapping/" + mappingId.MappingId);
            var mapping_etag = mappingGetResponse.Headers.ETag;
            var mappingFromService = mappingGetResponse.Content.ReadAsDataContract<MappingResponse>();

            MdmId postMapping = mappingFromService.Mappings[0];
            newEndDate = mappingFromService.Mappings[0].EndDate.Value.AddDays(1);
            postMapping.EndDate = newEndDate;
            var content = HttpContentExtensions.CreateDataContract(postMapping);
            client.DefaultHeaders.Add("If-Match", mapping_etag != null ? mapping_etag.Tag : string.Empty);
            mappingUpdateResponse = client.Post(ServiceUrl["Person"] +  string.Format("{0}/Mapping/{1}", entity.Id, mappingFromService.Mappings[0].MappingId), content);
        }
        public void ShouldRetrieveFromCacheIfClientRequestByNexusIdMapping()
        {
            const string CacheKey = "MDM.SourceSystem";

            // Given
            var mockMdmEntityService = new Mock<IMdmEntityService<SourceSystem>>();
            var mockConfigManager = new Mock<IConfigurationManager>();
            var inmemoryCacheRepo = new DefaultMdmClientCacheRepository(new InMemoryCacheRepository());
            mockConfigManager.Setup(x => x.AppSettings).Returns(new NameValueCollection { { "CacheItemPolicy.Expiration." + CacheKey, "3500" } });
            var cachePolicyFactory = new AbsoluteCacheItemPolicyFactory(CacheKey, mockConfigManager.Object);
            var locationEntityService = new CachePolicyMdmEntityService<SourceSystem>(mockMdmEntityService.Object, cachePolicyFactory,inmemoryCacheRepo);
            var nexusId = new MdmId { SystemName = "Nexus", Identifier = "1", IsMdmId = true };
            var location = new SourceSystem
            {
                Identifiers = new MdmIdList { nexusId },
                Details = new SourceSystemDetails { Name = "Blah" }
            };

            //Setup a context, i.e. calling once to retrieve location should cache an entity..
            mockMdmEntityService.Setup(x => x.Get(1, It.IsAny<DateTime?>())).Returns(
                new WebResponse<SourceSystem> { Code = HttpStatusCode.OK, IsValid = true, Message = location });

            var response = locationEntityService.Get(nexusId);

            response.Code.Should().Be(HttpStatusCode.OK);
            response.Message.ToMdmId().Identifier.Should().Be(nexusId.Identifier);

            // When , we call second time..
            response = locationEntityService.Get(nexusId);

            // Then
            // It should not call mdm service again... should retrive form cache, so that verify...
            mockMdmEntityService.Verify(x => x.Get(1, It.IsAny<DateTime?>()), Times.Once());
            mockMdmEntityService.Verify(x => x.Get(It.IsAny<MdmId>(), It.IsAny<DateTime?>()), Times.Never());
            response.Code.Should().Be(HttpStatusCode.OK);
            response.Message.ToMdmId().Identifier.Should().Be(nexusId.Identifier);
        }
        public void ValidDetailsSaved()
        {
            // Arrange
            var validatorFactory = new Mock<IValidatorEngine>();
            var mappingEngine = new Mock<IMappingEngine>();
            var repository = new Mock<IRepository>();
            var searchCache = new Mock<ISearchCache>();

            var service = new PartyService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object);

            var identifier = new MdmId { SystemName = "Test", Identifier = "A" };
            var message = new AmendMappingRequest { MappingId = 12, Mapping = identifier, Version = 34 };

            var start = new DateTime(2000, 12, 31);
            var finish = DateUtility.Round(SystemTime.UtcNow().AddDays(5));
            var s1 = new MDM.SourceSystem { Name = "Test" };
            var m1 = new PartyMapping { Id = 12, System = s1, MappingValue = "1", Version = 34UL.GetVersionByteArray(), Validity = new DateRange(start, DateUtility.MaxDate) };
            var m2 = new PartyMapping { Id = 12, System = s1, MappingValue = "1", Validity = new DateRange(start, finish) };

            // NB We deliberately bypasses the business logic
            var party = new MDM.Party();
            m1.Party = party;
            party.Mappings.Add(m1);

            validatorFactory.Setup(x => x.IsValid(It.IsAny<AmendMappingRequest>(), It.IsAny<IList<IRule>>())).Returns(true);
            repository.Setup(x => x.FindOne<PartyMapping>(12)).Returns(m1);
            mappingEngine.Setup(x => x.Map<EnergyTrading.Mdm.Contracts.MdmId, PartyMapping>(identifier)).Returns(m2);

            // Act
            service.UpdateMapping(message);

            // Assert
            // NB Don't verify result of Update - already covered by PartyMappingFixture
            repository.Verify(x => x.Save(party));
            repository.Verify(x => x.Flush());
        }
        public void GetMappingMissingSystemId()
        {
            var requester = new Mock<IMessageRequester>();
            var service = new MdmEntityService<SourceSystem>("sourcesystem", requester.Object);

            var tpIdentifier = new MdmId { SystemName = "Trayport", Identifier = "A" };
            var entity = new SourceSystem
            {
                Details = new SourceSystemDetails
                {
                    Name = "Gas"
                },
                Identifiers = new MdmIdList
                {
                    new MdmId { SystemName = "Nexus", Identifier = "1", IsMdmId = true},
                    tpIdentifier,
                    new MdmId { SystemName = "Endur", Identifier = "B"},
                }
            };

            var response = new WebResponse<SourceSystem>
            {
                Code = HttpStatusCode.OK,
                Message = entity,
                Tag = "1"
            };

            requester.Setup(x => x.Request<SourceSystem>(It.IsAny<string>())).Returns(response);

            // Act
            var candidate = service.Map(1, "Fred");

            // Assert
            Assert.AreEqual(HttpStatusCode.NotFound, candidate.Code, "Code differs");
            Assert.AreEqual(false, candidate.IsValid, "IsValid differs");
        }
        public void ValidDetailsSaved()
        {
            const int mappingId = 12;

            // Arrange
            var validatorFactory = new Mock<IValidatorEngine>();
            var mappingEngine = new Mock<IMappingEngine>();
            var repository = new Mock<IRepository>();
            var searchCache = new Mock<ISearchCache>();

            var service = new LocationService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object);

            // NB Don't put mappingId here - service assigns it
            var identifier = new MdmId { SystemName = "Test", Identifier = "A" };
            var message = new AmendMappingRequest { MappingId = mappingId, Mapping = identifier, Version = 34 };

            var start = new DateTime(2000, 12, 31);
            var finish = DateUtility.Round(SystemTime.UtcNow().AddDays(5));
            var s1 = new SourceSystem { Name = "Test" };
            var m1 = new LocationMapping { Id = mappingId, System = s1, MappingValue = "1", Version = 34UL.GetVersionByteArray(), Validity = new DateRange(start, DateUtility.MaxDate) };
            var m2 = new LocationMapping { Id = mappingId, System = s1, MappingValue = "1", Validity = new DateRange(start, finish) };

            // NB We deliberately bypasses the business logic
            var entity = new MDM.Location();
            m1.Location = entity;
            entity.Mappings.Add(m1);

            validatorFactory.Setup(x => x.IsValid(It.IsAny<AmendMappingRequest>(), It.IsAny<IList<IRule>>())).Returns(true);
            repository.Setup(x => x.FindOne<LocationMapping>(mappingId)).Returns(m1);
            mappingEngine.Setup(x => x.Map<EnergyTrading.Mdm.Contracts.MdmId, LocationMapping>(identifier)).Returns(m2);

            // Act
            service.UpdateMapping(message);

            // Assert
            Assert.AreEqual(mappingId, identifier.MappingId, "Mapping identifier differs");
            // Proves we have an update not an add
            Assert.AreEqual(1, entity.Mappings.Count, "Mapping count differs");
            // NB Don't verify result of Update - already covered by LocationMappingFixture
            repository.Verify(x => x.Save(entity));
            repository.Verify(x => x.Flush());
        }
        public void ToStringDisplaysSystemAndIdentifier()
        {
            var value = new MdmId { SystemName = "CME", Identifier = "MFF" };

            Assert.AreEqual("CME/MFF", value.ToString());
        }
        private bool TryCreateMapping(string entityName, MdmId newMapping, MappingUpdatedEvent updatedEvent)
        {
            var response = mappingService.CreateMapping(entityName, updatedEvent.EntityId, newMapping);
            if (!response.IsValid)
            {
                this.eventAggregator.Publish(
                    new ErrorEvent(response.Fault != null ? response.Fault.Message : "Unknown Error"));
                return false;
            }

            return true;
        }
        private EntityId GetInstrumentType(string adcCommodity)
        {
            if (string.IsNullOrWhiteSpace(adcCommodity))
            {
                return null;
            }

            var instrumentType = string.Empty;
            var partyCrossMapCommodity = adcCommodity.ToLower();

            if (partyCrossMapCommodity.Contains("swap"))
            {
                instrumentType = "Swap";
            }
            else if (partyCrossMapCommodity.Contains("future"))
            {
                instrumentType = "Future";
            }

            if (string.IsNullOrWhiteSpace(instrumentType))
            {
                return null;
            }

            var nexusId = new MdmId { Identifier = instrumentType, SystemName = "ADC", IsMdmId = false };
            return new EntityId { Identifier = nexusId, Name = instrumentType };
        }
        public void NotEqualOnNull()
        {
            var value = new MdmId { SystemName = "CME", Identifier = "MFF" };

            Assert.IsFalse(value.Equals(null));
        }
        private EntityId GetCommodity(string adcCommodity)
        {
            var commodity = string.Empty;

            if (string.IsNullOrWhiteSpace(adcCommodity))
            {
                return null;
            }

            var partyCrossMapCommodity = adcCommodity.ToLower();

            if (partyCrossMapCommodity.Contains("fx")) commodity = "FX";
            else if (partyCrossMapCommodity.Contains("coal")) commodity = "Coal";
            else if (partyCrossMapCommodity.Contains("carbon")) commodity = "Carbon";
            else if (partyCrossMapCommodity.Contains("gas")) commodity = "Natural Gas";
            else if (partyCrossMapCommodity.Contains("oil")) commodity = "Oil";
            else if (partyCrossMapCommodity.Contains("power")) commodity = "Power";
            else if (partyCrossMapCommodity.Contains("freightdry")) commodity = "Freight (Dry)";

            if (string.IsNullOrWhiteSpace(commodity))
            {
                return null;
            }

            var commodityId = new MdmId() { Identifier = commodity, SystemName = "ADC", IsMdmId = false };
            return new EntityId() { Identifier = commodityId, Name = commodity };
        }
        public void SuccessMatch()
        {
            // Arrange
            var validatorFactory = new Mock<IValidatorEngine>();
            var mappingEngine = new Mock<IMappingEngine>();
            var repository = new Mock<IRepository>();
            var searchCache = new Mock<ISearchCache>();
            var service = new PersonService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object);

            // Domain details
            var system = new MDM.SourceSystem { Name = "Endur" };
            var mapping = new PersonMapping
                {
                    System = system,
                    MappingValue = "A"
                };
            var targetSystem = new MDM.SourceSystem { Name = "Trayport" };
            var targetMapping = new PersonMapping
                {
                    System = targetSystem,
                    MappingValue = "B",
                    IsDefault = true
                };
            var details = new MDM.PersonDetails
                {
                    FirstName = "John",
                    LastName = "Smith",
                    Email = "*****@*****.**"
                };
            var person = new MDM.Person
                {
                    Id = 1
                };
            person.AddDetails(details);
            person.ProcessMapping(mapping);
            person.ProcessMapping(targetMapping);

            // Contract details
            var targetIdentifier = new MdmId
                {
                    SystemName = "Trayport",
                    Identifier = "B"
                };

            mappingEngine.Setup(x => x.Map<PersonMapping, MdmId>(targetMapping)).Returns(targetIdentifier);

            var list = new List<PersonMapping> { mapping };
            repository.Setup(x => x.Queryable<PersonMapping>()).Returns(list.AsQueryable());

            var request = new CrossMappingRequest
            {
                SystemName = "Endur",
                Identifier = "A",
                TargetSystemName = "trayport",
                ValidAt = SystemTime.UtcNow(),
                Version = 1
            };

            // Act
            var response = service.CrossMap(request);
            var candidate = response.Contract;

            // Assert
            Assert.IsNotNull(response, "Contract null");
            Assert.IsTrue(response.IsValid, "Contract invalid");
            Assert.IsNotNull(candidate, "Mapping null");
            Assert.AreEqual(1, candidate.Mappings.Count, "Identifier count incorrect");
            Assert.AreSame(targetIdentifier, candidate.Mappings[0], "Different identifier assigned");
        }
 public WebResponse<MdmId> CreateMapping(string entityName, int id, MdmId identifier)
 {
     return this.requester.Create(string.Format(this.mappingUri, entityName, id), identifier);
 }
        public void SuccessMatchSameVersion()
        {
            // Arrange
            var validatorFactory = new Mock<IValidatorEngine>();
            var mappingEngine = new Mock<IMappingEngine>();
            var repository = new Mock<IRepository>();
            var searchCache = new Mock<ISearchCache>();

            var service = new LocationService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object);

            // Domain details
            var system = new MDM.SourceSystem { Name = "Endur" };
            var mapping = new LocationMapping
            {
                System = system,
                MappingValue = "A"
            };
            var targetSystem = new MDM.SourceSystem { Name = "Trayport" };
            var targetMapping = new LocationMapping
            {
                System = targetSystem,
                MappingValue = "B",
                IsDefault = true
            };
            var location = new MDM.Location
            {
                Id = 1,
            };
            //Location.AddDetails(details);
            location.ProcessMapping(mapping);
            location.ProcessMapping(targetMapping);

            // Contract details
            var targetIdentifier = new MdmId
            {
                SystemName = "Trayport",
                Identifier = "B"
            };

            mappingEngine.Setup(x => x.Map<LocationMapping, MdmId>(targetMapping)).Returns(targetIdentifier);

            var list = new List<LocationMapping> { mapping };
            repository.Setup(x => x.Queryable<LocationMapping>()).Returns(list.AsQueryable());

            var request = new CrossMappingRequest
            {
                SystemName = "Endur",
                Identifier = "A",
                TargetSystemName = "trayport",
                ValidAt = SystemTime.UtcNow(),
                Version = 0
            };

            // Act
            var response = service.CrossMap(request);
            var candidate = response.Contract;

            // Assert
            Assert.IsNotNull(response, "Contract null");
            Assert.IsTrue(response.IsValid, "Contract not valid");
            Assert.IsNull(candidate, "Mapping null");
        }