public void Unlock() { if (IsDisposed() || id == null) { return; } try { Zookeeper.Delete(id, -1); } catch (ThreadInterruptedException e) { Thread.CurrentThread.Interrupt(); } catch (KeeperException.NoNodeException e) { //do nothing } catch (KeeperException e) { LOG.Warn("Caught: " + e, e); throw; } finally { OnLockReleased(); id = null; } }
public void Unlock() { if (IsDisposed() || id == null) { return; } try { Zookeeper.Delete(id, -1); } catch (ThreadInterruptedException) { #if NET451 Thread.CurrentThread.Interrupt(); #endif } catch (KeeperException.NoNodeException) { //do nothing } catch (KeeperException e) { LOG.WarnFormat("Caught: {0} {1}", e, e.StackTrace); throw; } finally { OnLockReleased(); id = null; } }
private void FindPrefixInChildren(String prefix, ZooKeeper zookeeper, String dir) { List <String> names = Zookeeper.GetChildren(dir, false); foreach (string name in names) { if (name.StartsWith(prefix)) { id = name; if (LOG.IsDebugEnabled) { LOG.Debug("Found id created last time: " + id); } break; } } if (id == null) { id = zookeeper.Create(dir.Combine(prefix), data, Acl, CreateMode.EphemeralSequential); if (LOG.IsDebugEnabled) { LOG.Debug("Created id: " + id); } } }
public IHttpActionResult CreateAnimal(Animal animalToCreate) { Animal animalCreated = _ctx.Animals.Add(animalToCreate); Zookeeper zookeeperToIncrement = _ctx.Zookeepers.Find(animalToCreate.ZookeeperId); zookeeperToIncrement.AnimalsCaringFor += 1; _ctx.SaveChanges(); return(Ok()); }
public string Watch(string path) { var stat = Zookeeper.Exists(path, new ConfigCenterWatcher(Zookeeper, ZkCache)); if (stat != null) { var data = Zookeeper.GetData(path, false, null).GetString(); ZkCache.SetValue(path, data); return(data); } return(null); }
public void SetNode(string path, string value, IEnumerable <ACL> acl) { var stat = Zookeeper.Exists(path, false); if (stat == null) { var createRet = Zookeeper.Create(path, value.GetBytes(), acl, CreateMode.Persistent); } else { Zookeeper.SetData(path, value.GetBytes(), stat.Version); } }
static void Main(string[] args) { Mammal dog = new Dog(); Mammal cat = new Cat(); Elephant elephant = new Elephant(); Lion lion = new Lion(); Zookeeper keeper = new Zookeeper(); keeper.Wash(dog); keeper.Wash(cat); keeper.Wash(elephant); keeper.Wash(lion); }
public void CanOrderBeSend_NoOrderlines_ExceptionThrown() { //Arrange Order order = InitializeOrder(); order.Status = 0; Zookeeper zookeeper = MakeZookeeper(); zookeeper.Id = 2; order.OrderedByID = zookeeper.Id; //Act And Arrange Assert.Throws <CanNotSendEmptyOrderException>(() => order.CanOrderBeSend()); }
public void AttackZookeeperToOrder_ZookeeperAlreadyAttached_ExceptionThrown() { //Arrange Zookeeper zookeeper = MakeZookeeper(); zookeeper.Id = 2; Order order = InitializeOrder(); //Act order.AttachZookeeperToOrder(zookeeper); //Assert Assert.Throws <ZookeeperAllReadyAddedException>(() => order.AttachZookeeperToOrder(zookeeper)); }
public void AttackZookeeperToOrder_ValidZookeeper_ZookeeperAdded() { //Arrange Zookeeper zookeeper = MakeZookeeper(); zookeeper.Id = 2; Order order = InitializeOrder(); //Act order.AttachZookeeperToOrder(zookeeper); //Assert Assert.AreEqual(zookeeper.Id, order.OrderedByID); }
public void CanOrderBeSend_WrongStatus_ExceptionThrown() { //Arrange Order order = InitializeOrder(); order.OrderLines.Add(MakeOrderLine()); order.Status = 1; //Sent Zookeeper zookeeper = MakeZookeeper(); zookeeper.Id = 2; order.OrderedByID = zookeeper.Id; //Act And Arrange Assert.Throws <OrderIsNotUnderAnSendableStateException>(() => order.CanOrderBeSend()); }
public void Init() { var ret = RetryOperation(() => { return(Zookeeper.Exists("/", false) != null); }); if (!ret) { if (ZkSerialization.Enable) { var str = File.ReadAllText(LocalZkFilePath); ZkSerialization.Deserilize(ZkCache, str); } } }
public void CanOrderBeSend_None_CanBeSend() { //Arrange Order order = InitializeOrder(); order.OrderLines.Add(MakeOrderLine()); order.Status = 0; //UnderContruktion Zookeeper zookeeper = MakeZookeeper(); zookeeper.Id = 2; order.OrderedByID = zookeeper.Id; //Act bool result = order.CanOrderBeSend(); //Assert Assert.IsTrue(result); }
public void SendOrder_CanBeSendWorks_OrderCanBeSend() { //Arrange Order order = InitializeOrder(); order.OrderLines.Add(MakeOrderLine()); order.Status = 0; Zookeeper zookeeper = MakeZookeeper(); zookeeper.Id = 2; order.OrderedByID = zookeeper.Id; //Act order.SendOrder(); //Assert Assert.AreEqual(1, order.Status); MockRep.Verify(x => x.AddOrder(order), Times.Once()); }
/// <summary> /// Gets all the Zookeepers in the database. /// </summary> /// <returns></returns> public List <Zookeeper> GetAllZookeepers() { List <Zookeeper> AllZookeepers = new List <Zookeeper>(); using (var db = new AalborgZooContainer()) { var temp = new List <Employee>(db.EmployeeSet); foreach (Employee e in temp) { Zookeeper tempZookeeper = e as Zookeeper; if (tempZookeeper != null) { AllZookeepers.Add(tempZookeeper); } } return(AllZookeepers); } }
/** * Ensures that the given path exists with the given data, ACL and flags * @param path * @param acl * @param flags */ protected void EnsureExists(string path, byte[] data, List <ACL> acl, CreateMode flags) { try { var components = path.Split(PathUtils.PathSeparatorCharAsArray, StringSplitOptions.RemoveEmptyEntries); var pathBuilder = new StringBuilder(path.Length); for (var i = 0; i < components.Length; ++i) { // Create a loop-scoped variable to avoid closure troubles // inside RetryOperation. var isLastComponent = (i == components.Length - 1); var component = components[i]; pathBuilder.Append(PathUtils.PathSeparator); pathBuilder.Append(component); var currentPartialPath = pathBuilder.ToString(); RetryOperation(() => { var stat = Zookeeper.Exists(currentPartialPath, false); if (stat != null) { return(true); } Zookeeper.Create(currentPartialPath, isLastComponent ? data : null, acl, flags); return(true); }); } } catch (KeeperException e) { LOG.WarnFormat("Caught: {0} {1}", e, e.StackTrace); } catch (ThreadInterruptedException e) { LOG.WarnFormat("Caught: {0} {1}", e, e.StackTrace); } }
/** * Ensures that the given path exists with the given data, ACL and flags * @param path * @param acl * @param flags */ protected void EnsureExists(string path, byte[] data, List <ACL> acl, CreateMode flags) { try { RetryOperation(() => { Stat stat = Zookeeper.Exists(path, false); if (stat != null) { return(true); } Zookeeper.Create(path, data, acl, flags); return(true); }); } catch (KeeperException e) { LOG.WarnFormat("Caught: {0} {1}", e, e.StackTrace); } catch (ThreadInterruptedException e) { LOG.WarnFormat("Caught: {0} {1}", e, e.StackTrace); } }
//[Required]?? public ViewResult Register(RegisterModel Rm, HttpPostedFileBase ProfilePicture) { //HttpPostedFileBase - Use to retrieve picture uploaded from form //We have to verify the mime type and the image size List <string> matchContentType = new List <string>() { "image/jpeg", "image/png", "image/gif" }; if (!matchContentType.Contains(ProfilePicture.ContentType) || ProfilePicture.ContentLength > 80000) { ViewBag.ErrorMessage = "You need to use the following image extensions: png, jpg, gif"; return(View("Login")); } //We can't save the file before to save the member in the database //Check if data annotations are respected ==> See the RegisterModel Class if (!ModelState.IsValid) { //I want to get all error on the model like wrong email format, wrong password repetiton,.... foreach (ModelState modelState in ViewData.ModelState.Values) { foreach (ModelError error in modelState.Errors) { //add the error message into a viewbag to display on the view ViewBag.ErrorMessage += error.ErrorMessage + "<br>"; } } } else { ZookeeperRepository Zr = new ZookeeperRepository(ConfigurationManager.ConnectionStrings["CnstrDev"].ConnectionString); //I have to call the Insert function from ZookeeperRepository //If the insert succeeds, we get a complete Zookeeper with id value (calculated by the database) //If the insert failed, we receive a null value //We have to convert the registerModel(viewmodel) to a ZookeeperModel(Dal) before to call the function // this is why we call the static function RegisterToMembre from the Static class MapToDBModel Zookeeper ZM = Zr.Insert(MapToDBModel.RegisterToZookeeper(Rm)); if (M != null) { //Now I can save the picture //1 - Get the filename and extract the extension string[] splitFileName = ProfilePicture.FileName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries); string ext = splitFileName[splitFileName.Length - 1]; //Get the last collumn of the array which contains the extension of the picture //2- Generate the new file name string newFileName = M.Id + "." + ext; //3- Save the picture //3.1 - Get the physic path of the photos folder string folderpath = Server.MapPath("~/photos/"); //3.2 - Combine folder path and new filename string FileNameToSave = folderpath + "/" + newFileName; //3.3 - Save try { //SaveAs is a procedure and not a function thus we have to surround with try catch to // get error if the SaveAs failed ProfilePicture.SaveAs(FileNameToSave); } catch (Exception) { ViewBag.ErrorMessage = "L'image n'a pas pu être sauvée"; throw; } //I want to pre-fill the login html input if the register succeed. //Thus , I use ViewBag to store the Email and a success message to communicate with the guest ViewBag.Login = Rm.Email; ViewBag.SuccessMessage = "Vous pouvez vous connecter"; } else { //If there is an issuer, I want to dispay a message on the view. //Thus I use Viewbag to send the message to the view ViewBag.ErrorMessage = "Erreur lors de l'insertion"; } } return(View("Login")); }
public IHttpActionResult CreateZookeeper(Zookeeper zookeeperToCreate) { _ctx.Zookeepers.Add(zookeeperToCreate); _ctx.SaveChanges(); return(Ok()); }
static public void PopulateDatabase() { using (db = new AalborgZooContainer()) { /* Shopper */ Shopper shp = new Shopper() { DateHired = DateTime.Today.AddMonths(-1), Name = "Tobias Palludan", Password = "******", Username = "******" }; db.EmployeeSet.Add(shp); shp = new Shopper() { DateHired = DateTime.Today.AddMonths(-1), Name = "Mikkel Jessen", Password = "******", Username = "******", }; db.EmployeeSet.Add(shp); db.SaveChanges(); /* Departments */ Department depSydAmerika = new Department() { DateCreated = DateTime.Today.AddMonths(-1), Name = "Sydamerika", }; db.DepartmentSet.Add(depSydAmerika); Department depAfrika = new Department() { DateCreated = DateTime.Today.AddMonths(-1), Name = "Afrika", }; db.DepartmentSet.Add(depAfrika); db.SaveChanges(); /* Zookeepers */ Zookeeper zkp = new Zookeeper() { DateHired = DateTime.Today.AddMonths(-1), Department = depSydAmerika, Name = "Anh Tuan Truong" }; db.EmployeeSet.Add(zkp); zkp = new Zookeeper() { DateHired = DateTime.Today.AddMonths(-1), Department = depSydAmerika, Name = "Casper Corfitz Christensen" }; db.EmployeeSet.Add(zkp); zkp = new Zookeeper() { DateHired = DateTime.Today.AddMonths(-1), Department = depSydAmerika, Name = "Kristoffer Jensen" }; db.EmployeeSet.Add(zkp); zkp = new Zookeeper() { DateHired = DateTime.Today.AddMonths(-1), Department = depSydAmerika, Name = "Jacob Gosch" }; db.EmployeeSet.Add(zkp); Zookeeper zkpAfrika = new Zookeeper() { DateHired = DateTime.Today.AddMonths(-1), Department = depAfrika, Name = "Afrika Medarbejder, burde ikke vises" }; db.EmployeeSet.Add(zkpAfrika); db.SaveChanges(); /* Product */ Product prodBanan = new Product() { CreatedByID = zkp.Id, DateCreated = DateTime.Today.AddMonths(-1), Name = "Banan", }; db.ProductSet.Add(prodBanan); Product prodPære = new Product() { CreatedByID = zkp.Id, DateCreated = DateTime.Today.AddMonths(-1), Name = "Pære", }; db.ProductSet.Add(prodPære); Product prodÆble = new Product() { CreatedByID = zkp.Id, DateCreated = DateTime.Today.AddMonths(-1), Name = "Æble", }; db.ProductSet.Add(prodÆble); Product prodAbrikos = new Product() { CreatedByID = zkp.Id, DateCreated = DateTime.Today.AddMonths(-1), Name = "Abrikos", }; db.ProductSet.Add(prodAbrikos); Product prodTuttiFruttiMix = new Product() { CreatedByID = zkp.Id, DateCreated = DateTime.Today.AddMonths(-1), Name = "TuttiFruttiMix, burde ikke vises", }; db.ProductSet.Add(prodTuttiFruttiMix); db.SaveChanges(); /* Product versions */ ProductVersion prodvBanan = new ProductVersion() { Name = "Banan", Product = prodBanan, IsActive = true, Supplier = "FrugtKarl", Units = db.UnitSet.ToList(), DateCreated = DateTime.Today, CreatedByID = shp.Id }; db.ProductVersionSet.Add(prodvBanan); ProductVersion prodvÆble = new ProductVersion() { Name = "Æble", Product = prodÆble, IsActive = true, Supplier = "FrugtKarl", Units = db.UnitSet.ToList(), DateCreated = DateTime.Today, CreatedByID = shp.Id }; db.ProductVersionSet.Add(prodvÆble); ProductVersion prodvPære = new ProductVersion() { Name = "Pære", Product = prodPære, IsActive = true, Supplier = "FrugtKarl", DateCreated = DateTime.Today, Units = db.UnitSet.ToList(), CreatedByID = shp.Id }; db.ProductVersionSet.Add(prodvPære); ProductVersion prodvAbrikos = new ProductVersion() { Name = "Abrikos", Product = prodAbrikos, IsActive = true, Supplier = "FrugtKarl", DateCreated = DateTime.Today, Units = db.UnitSet.ToList(), CreatedByID = shp.Id }; db.ProductVersionSet.Add(prodvAbrikos); ProductVersion prodvTuttiFrutti = new ProductVersion() { Name = "Tutti Frutti Mix, burde ikke vises", Product = prodTuttiFruttiMix, IsActive = true, Supplier = "Tivoli", DateCreated = DateTime.Today, Units = db.UnitSet.ToList(), CreatedByID = shp.Id }; db.ProductVersionSet.Add(prodvTuttiFrutti); db.SaveChanges(); /* Department Specific Products */ DepartmentSpecificProduct departmentSpecificProduct = new DepartmentSpecificProduct() { Department = depSydAmerika, Product = prodBanan }; db.DepartmentSpecificProductSet.Add(departmentSpecificProduct); departmentSpecificProduct = new DepartmentSpecificProduct() { Department = depSydAmerika, Product = prodÆble }; db.DepartmentSpecificProductSet.Add(departmentSpecificProduct); departmentSpecificProduct = new DepartmentSpecificProduct() { Department = depSydAmerika, Product = prodPære }; db.DepartmentSpecificProductSet.Add(departmentSpecificProduct); departmentSpecificProduct = new DepartmentSpecificProduct() { Department = depSydAmerika, Product = prodAbrikos }; db.DepartmentSpecificProductSet.Add(departmentSpecificProduct); departmentSpecificProduct = new DepartmentSpecificProduct() { Department = depAfrika, Product = prodTuttiFruttiMix }; db.DepartmentSpecificProductSet.Add(departmentSpecificProduct); db.SaveChanges(); /* Shopping list */ ShoppingList shoppingList = new ShoppingList() { CreatedByID = shp.Id, DateCreated = DateTime.Today, Shopper = shp, Status = 2, }; db.ShoppingListSet.Add(shoppingList); db.SaveChanges(); /* Orders */ Order order = new Order() { DateCreated = DateTime.Today, Status = 2, DepartmentID = depSydAmerika.Id, OrderedByID = zkp.Id, ShoppingList = shoppingList, DateOrdered = DateTime.Today, }; db.OrderSet.Add(order); db.SaveChanges(); /* OrderLine */ OrderLine orderLineBanan = new OrderLine() { Order = order, ProductVersion = prodvBanan, Quantity = 15, Unit = db.UnitSet.First() }; db.OrderLineSet.Add(orderLineBanan); db.SaveChanges(); OrderLine orderLineÆble = new OrderLine() { Order = order, ProductVersion = prodvÆble, Quantity = 15, Unit = db.UnitSet.First() }; db.OrderLineSet.Add(orderLineÆble); db.SaveChanges(); OrderLine orderLinePære = new OrderLine() { Order = order, ProductVersion = prodvPære, Quantity = 15, Unit = db.UnitSet.First() }; db.OrderLineSet.Add(orderLinePære); db.SaveChanges(); OrderLine orderLineAbrikos = new OrderLine() { Order = order, ProductVersion = prodvAbrikos, Quantity = 15, Unit = db.UnitSet.First() }; db.OrderLineSet.Add(orderLineAbrikos); db.SaveChanges(); OrderLine orderLineTuttiFruttiMix = new OrderLine() { Order = order, ProductVersion = prodvTuttiFrutti, Quantity = 15, Unit = db.UnitSet.First() }; db.OrderLineSet.Add(orderLineTuttiFruttiMix); db.SaveChanges(); } }
private object LockOperation() { do { if (id == null) { long sessionId = Zookeeper.SessionId; string prefix = "x-" + sessionId + "-"; FindPrefixInChildren(prefix, Zookeeper, dir); idName = new ZNodeName(id); } if (id == null) { continue; } List <string> names = Zookeeper.GetChildren(dir, false); if (names.IsEmpty()) { LOG.Warn("No children in: " + dir + " when we've just " + "created one! Lets recreate it..."); // lets force the recreation of the id id = null; } else { // lets sort them explicitly (though they do seem to come back in order ususally :) var sortedNames = new SortedSet <ZNodeName>(); foreach (string name in names) { sortedNames.Add(new ZNodeName(dir.Combine(name))); } ownerId = sortedNames.First().Name; SortedSet <ZNodeName> lessThanMe = sortedNames.HeadSet(idName); if (!lessThanMe.IsEmpty()) { ZNodeName lastChildName = lessThanMe.Last(); lastChildId = lastChildName.Name; if (LOG.IsDebugEnabled) { LOG.Debug("watching less than me node: " + lastChildId); } Stat stat = Zookeeper.Exists(lastChildId, new LockWatcher(this)); if (stat != null) { return(false); } LOG.Warn("Could not find the stats for less than me: " + lastChildName.Name); } else { if (Owner) { OnLockAcquired(); return(true); } } } } while (id == null); return(false); }
public bool RunForLeader() { long sessionId = Zookeeper.SessionId; string prefix = "election-" + sessionId + "-"; var names = Zookeeper.GetChildren(path, false); // See whether we have already run for election in this process foreach (string name in names) { if (name.StartsWith(prefix)) { id = name; if (LOG.IsDebugEnabled) { LOG.DebugFormat("Found id created last time: {0}", id); } } } if (id == null) { id = Zookeeper.Create(path.Combine(prefix), data, Acl, CreateMode.EphemeralSequential); if (LOG.IsDebugEnabled) { LOG.DebugFormat("Created id: {0}", id); } } idName = new ZNodeName(id); names = Zookeeper.GetChildren(path, false); var sortedNames = new SortedSet <ZNodeName>(); foreach (var name in names) { sortedNames.Add(new ZNodeName(name)); } var priors = sortedNames.HeadSet(idName); if (priors.Count == 0) { throw new InvalidOperationException("Count of priors is 0, but should at least include this node."); } if (priors.Count == 1) { IsOwner = true; watcher.TakeLeadership(); return(true); } // only watch the node directly before us ZNodeName penultimate = null, last = null; foreach (var name in sortedNames) { penultimate = last; last = name; } if (penultimate == null) { throw new InvalidOperationException("Penultimate value in priors is null, but count shoudl have been at least 2."); } var penultimatePath = path.Combine(penultimate.Name); if (Zookeeper.Exists(penultimatePath, new LeaderWatcher(Zookeeper, this, penultimatePath, watcher, path, id)) == null) { IsOwner = true; watcher.TakeLeadership(); return(true); } return(false); }
public void Close() { IsOwner = false; Zookeeper.Delete(id, -1); }
public void ZookeeperSelected(Zookeeper zookeeper) { ActiveZookeeper = zookeeper; }