/// <summary> /// return all the child entity ids, give it null get nod directly below root /// </summary> /// <param name="parent"></param> /// <returns></returns> public async Task <IEnumerable <Guid> > GetAllChildrenIdAsync(JDBCEntity parent = null) { //如果父节点为空,查找ParentId为空的节点,返回root节点 //如果父节点不为空,查找ParentId和此节点Id相同的节点,为他的所有子节点 Guid id = parent == null ? Guid.Empty : parent.Id; var filter = Builders <JDBCEntity> .Filter.Eq("ParentId", id); var projection = Builders <JDBCEntity> .Projection.Include("Id"); var options = new FindOptions <JDBCEntity, BsonDocument> { Projection = projection }; using (var cursor = await collection.FindAsync(filter, options)) { var list = cursor.ToListAsync().Result; List <Guid> listGuid = new List <Guid>(); foreach (var item in list) { listGuid.Add(item["_id"].AsGuid); } //如果没找到,返回长度为0的空list return(listGuid); } }
static void Main(string[] args) { var signal = JDBCEntity.getFixedIntervalWaveSignal("path/jtext/1/ws2"); var result = signal.GetData(); Console.ReadLine(); }
//todo:PBI INF,INF1,2is duplicated, it can be done using get children,give it a null or empty guid get root elementy //todo for those get methods that returns a collection, add paging functions, so you dont get awful big alot collection WHEN YOU HAVE large data //Note: you can split the file into partial class file it the implementation gets too long /// <summary> /// 查找entity,如果找不到entity==null,找到了返回实例 /// review 找不到返回null可以在下面的return里面在写一下 /// </summary> /// <param name="id"></param> /// <returns>如果找不到返回null,找到了返回实例</returns> public async Task <JDBCEntity> GetOneByIdAsync(Guid id) { IFindFluent <JDBCEntity, JDBCEntity> findFluent = collection.Find(x => x.Id == id); JDBCEntity entity = await findFluent.FirstOrDefaultAsync(); return(entity); }
/// <summary> /// 认证,此用户是否对JDBCEntity有某一操作权限 /// </summary> /// <param name="id">节点ID</param> /// <param name="user">发起操作用户</param> /// <param name="operation">操作类型:"421"(4代表读权限,2代表写权限,1代表节点管理权限)</param> /// <returns>Accreditation</returns> public async Task <bool> Authorization(Guid id, LoginClaim user, string operation) { JDBCEntity entity = await myCoreService.GetOneByIdAsync(id); //管理员或所有者直接拥有所有权限,包括根节点 if (IsRootRole(user) || (entity != null && entity.User.Equals(user.UserName))) { return(true); } //entity不存在直接返回false else if (entity == null) { return(false); } //验证某个用户是否拥有对当前节点的某操作权限 else if (entity.GroupPermission.ContainsKey(user.UserName) && entity.GroupPermission[user.UserName].Contains(operation)) { return(true); } //验证某个操作是否属于开放权限 else if (entity.OthersPermission.Contains(operation)) { return(true); } //当权限可继承时,验证某个用户是否拥有对(祖)父节点的某操作权限 else if (entity.QueryToParentPermission) { return(await Authorization(entity.ParentId, user, operation)); } else { return(false); } }
public Cursor(CoreService CoreService, Signal signal, List <long> start, List <long> count, List <long> decimationFactor = null) { leftPoint = 1; mySignal = signal; for (int i = 0; i < count.Count(); i++) { leftPoint *= count[i]; } myCoreService = CoreService; myStorageEngine = myCoreService.StorageEngine as IMatrixStorageEngineInterface; if (signal.ExtraInformation.Keys.Contains("expression")) { string code = (string)signal.ExtraInformation["expression"]; if (code.Contains("JDBC.Signal")) { CursorDictionary = new Dictionary <string, ICursor>(); MatchCollection mc = Regex.Matches(code, "(?<=JDBC.Signal\\(\").*?(?=\"\\))"); foreach (Match item in mc) { if (!CursorDictionary.Keys.Contains(item.Value)) { JDBCEntity waveSig = myCoreService.GetOneByPathAsync(item.Value).Result; ICursor cursor = myStorageEngine.GetCursorAsync <T>(waveSig.Id, start, count, decimationFactor).Result; CursorDictionary.Add(item.Value, cursor); } } } } }
/// <summary> /// delet a experiment, sig, the payload in the sig is also deleted /// </summary> /// <param name="jdbcId">the id</param> /// <param name="isRecuresive">do i delte the children, if set to false and the entity has child, it will throw exeption</param> /// <returns></returns> public async Task DeleteAsync(Guid jdbcId, bool isRecuresive = false) { JDBCEntity entity = await GetOneByIdAsync(jdbcId); if (entity == null) { throw new Exception(ErrorMessages.EntityNotFoundError); } List <JDBCEntity> list = (await GetAllChildrenAsync(jdbcId)).ToList(); //如果有孩子节点,又没指定递归,则不许删除 if (list.Count() > 0 && isRecuresive == false) { throw new Exception(ErrorMessages.DeleteEntityWithChildError); } //如果无孩子,则删除 if (list.Count() == 0) { var delfilter = Builders <JDBCEntity> .Filter.Eq(m => m.Id, jdbcId); if (entity.EntityType.Equals(JDBCEntityType.Signal)) { await myStorageEngine.DeleteDataAsync(jdbcId); } await collection.DeleteOneAsync(delfilter); } await recursiveDeleteAsync(entity); var delfilter1 = Builders <JDBCEntity> .Filter.Eq(m => m.Id, jdbcId); await collection.DeleteOneAsync(delfilter1); }
internal Writer(JDBCEntity signal, IMapper myMapper) { mySignal = signal; signalId = signal.Id; mapper = myMapper; this.sampleCount = signal.NumberOfSamples; lastDimension = "START"; cacheBuffer = new Dictionary <string, PayloadCache <T> >(); }
public async Task <HttpResponseMessage> Get(string format = "array") { var user = GetSessionUser(Request.Headers.GetCookies().FirstOrDefault()); JDBCEntity currentEntity = null;//当前处理的Entity信息 try { Uri uri = ParseToQueryUri(Request.RequestUri); List <JDBCEntity> findNode = (await MyCoreApi.FindNodeByUriAsync(uri)).ToList(); //根据uri查找父节点 if (findNode.Count != 1) //节点数不唯一 { throw new Exception("Please specify one Node!"); } else { currentEntity = findNode.FirstOrDefault(); } if (!await MyCoreApi.Authorization(currentEntity.Id, user, "4")) { throw new Exception("Not authorization!"); } if (currentEntity.EntityType != JDBCEntityType.Signal) { throw new Exception("The specifed node is not signal!"); } //get data ITypedSignal typedSignal = currentEntity as ITypedSignal; var result = await typedSignal.GetDataAsync(uri.Fragment, format); return(new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent(SerializeObjectToString(result), System.Text.Encoding.GetEncoding("UTF-8"), "application/json") }); } catch (Exception e) { if (currentEntity == null) { return(new HttpResponseMessage { StatusCode = HttpStatusCode.Forbidden, Content = new StringContent(e.InnerException != null ? e.InnerException.Message : e.Message) }); } var response = new ResponseDataMessage { Fail = new { Description = e.InnerException != null ? e.InnerException.Message : e.Message, Id = currentEntity.Id, Path = currentEntity.Path } }; return(new HttpResponseMessage { StatusCode = HttpStatusCode.Forbidden, Content = new StringContent(SerializeObjectToString(response), System.Text.Encoding.GetEncoding("UTF-8"), "application/json") }); } }
public async Task <HttpResponseMessage> Move() { var user = GetSessionUser(Request.Headers.GetCookies().FirstOrDefault()); List <NodeDto> successEntity = new List <NodeDto>(); //成功处理的Entity信息 JDBCEntity currentEntity = null; //当前处理的Entity信息 try { var dict = ParseToQueryDictionary(Request.RequestUri); NameValueCollection form = Request.Content.ReadAsFormDataAsync().Result; var fromNodes = await MyCoreApi.FindNodeByUriAsync(new Uri("jdbc://" + GetValueFromForm(form, "from").Replace(";", "&").Replace(",", "&").Trim("'\"()[]{}".ToCharArray()))); //获取源entity var toNodes = await MyCoreApi.FindNodeByUriAsync(new Uri("jdbc://" + GetValueFromForm(form, "to").Replace(";", "&").Replace(",", "&").Trim("'\"()[]{}".ToCharArray()))); //获取目的entity foreach (var fromNode in fromNodes) { foreach (var toNode in toNodes) { currentEntity = toNode; if (!await MyCoreApi.Authorization(currentEntity.Id, user, "1")) { throw new Exception("Not authorization!"); } var newNode = await MyCoreApi.MoveJdbcEntityAsync(toNode.Id, fromNode.Id); //迁移entity到新的父节点下 successEntity.Add(Mapper.Map <NodeDto>(toNode)); //保存处理结果 } } return(new HttpResponseMessage { Content = new StringContent(SerializeObjectToString(successEntity), System.Text.Encoding.GetEncoding("UTF-8"), "application/json") }); } catch (Exception e) { if (currentEntity == null) { return(new HttpResponseMessage { StatusCode = HttpStatusCode.Forbidden, Content = new StringContent(e.InnerException != null ? e.InnerException.Message : e.Message) }); } var response = new ResponseEntityMessage { Fail = new { Description = e.InnerException != null ? e.InnerException.Message : e.Message, Id = currentEntity.Id, Path = currentEntity.Path }, Success = successEntity }; return(new HttpResponseMessage { StatusCode = HttpStatusCode.Forbidden, Content = new StringContent(SerializeObjectToString(response), System.Text.Encoding.GetEncoding("UTF-8"), "application/json") }); } }
public void AddEntity() { // IEnumerable<JDBCEntity> parent1 =myCoreApi.FindAllChildrenByParentIdAsync(Guid.Empty).Result; JDBCEntity parent = myCoreApi.FindOneByPathAsync("/jtext").Result; for (int i = 0; i < 500; i++) { JDBCEntity exp = new Experiment("exp" + i); myCoreApi.AddOneToExperimentAsync(parent.Id, exp).Wait(); } }
/// <summary> /// 重置ExpressionRoot /// </summary> public static async void SetExpressionRoot() { var uri = new Uri("jdbc:///path/expression"); ExpressionRoot = (await MyCoreApi.FindNodeByUriAsync(uri)).FirstOrDefault(); if (ExpressionRoot != null) { await MyCoreApi.DeletAsync(ExpressionRoot.Id, true); } ExpressionRoot = await MyCoreApi.AddOneToExperimentAsync(Guid.Empty, new Experiment("expression")); }
/// <summary> /// return all the child entities,give it null get nod directly below root /// </summary> /// <param name="parent">the parent entity</param> /// <returns>return all the child entities,give it null get nod directly below root</returns> public async Task <IEnumerable <JDBCEntity> > GetAllChildrenAsync(JDBCEntity parent = null) { //如果父节点为空,查找ParentId为空的节点,返回root节点 //如果父节点不为空,查找ParentId和此节点Id相同的节点,为他的所有子节点 Guid id = parent == null ? Guid.Empty : parent.Id; var filter = Builders <JDBCEntity> .Filter.Eq("ParentId", id); using (var cursor = await collection.FindAsync(filter)) { return(await cursor.ToListAsync <JDBCEntity>()); } }
/// <summary> /// get the parent entity /// </summary> /// <param name="id">the child id</param> /// <returns></returns> public async Task <JDBCEntity> GetParentAsync(Guid id) { JDBCEntity child = await GetOneByIdAsync(id); if (child == null) { return(null); } JDBCEntity parent = await GetOneByIdAsync(child.ParentId); return(parent); }
public async Task <HttpResponseMessage> Get() { JDBCEntity currentEntity = null;//当前处理的Entity信息 try { Uri uri = ParseToQueryUri(Request.RequestUri); List <JDBCEntity> findNode = (await MyCoreApi.FindNodeByUriAsync(uri)).ToList(); //根据uri查找父节点 if (findNode.Count != 1) //节点数不唯一 { throw new Exception("Please specify one Node!"); } else { currentEntity = findNode.FirstOrDefault(); } if (currentEntity.EntityType != JDBCEntityType.Signal) { throw new Exception("The specifed node is not signal!"); } var stream = new SignalDataStream((ITypedSignal)currentEntity, uri.Fragment); var response = Request.CreateResponse(); response.Content = new PushStreamContent(stream.WriteToStream, new MediaTypeHeaderValue("data/stream")); return(response); } catch (Exception e) { if (currentEntity == null) { return(new HttpResponseMessage { StatusCode = HttpStatusCode.Forbidden, Content = new StringContent(e.Message) }); } var response = new ResponseDataMessage { Fail = new { Description = e.Message, Id = currentEntity.Id, Path = currentEntity.Path } }; StringWriter tw = new StringWriter(); JsonSerializer jsonSerializer = new JsonSerializer(); jsonSerializer.Serialize(tw, response, response.GetType()); return(new HttpResponseMessage { StatusCode = HttpStatusCode.Forbidden, Content = new StringContent(tw.ToString(), System.Text.Encoding.GetEncoding("UTF-8"), "application/json") }); } }
public async Task <HttpResponseMessage> Rename() { var user = GetSessionUser(Request.Headers.GetCookies().FirstOrDefault()); List <NodeDto> successEntity = new List <NodeDto>(); //成功处理的Entity信息 JDBCEntity currentEntity = null; //当前处理的Entity信息 try { var dict = ParseToQueryDictionary(Request.RequestUri); NameValueCollection form = Request.Content.ReadAsFormDataAsync().Result; var newname = GetValueFromForm(form, "name"); currentEntity = await MyCoreApi.FindNodeByIdAsync(new Guid(GetValueFromForm(form, "node"))); if (!await MyCoreApi.Authorization(currentEntity.Id, user, "1")) { throw new Exception("Not authorization!"); } var newNode = await MyCoreApi.ReNameNodeAsync(currentEntity.Id, newname); successEntity.Add(Mapper.Map <NodeDto>(newNode));//保存处理结果 return(new HttpResponseMessage { Content = new StringContent(SerializeObjectToString(successEntity), System.Text.Encoding.GetEncoding("UTF-8"), "application/json") }); } catch (Exception e) { if (currentEntity == null) { return(new HttpResponseMessage { StatusCode = HttpStatusCode.Forbidden, Content = new StringContent(e.InnerException != null ? e.InnerException.Message : e.Message) }); } var response = new ResponseEntityMessage { Fail = new { Description = e.InnerException != null ? e.InnerException.Message : e.Message, Id = currentEntity.Id, Path = currentEntity.Path }, Success = successEntity }; return(new HttpResponseMessage { StatusCode = HttpStatusCode.Forbidden, Content = new StringContent(SerializeObjectToString(response), System.Text.Encoding.GetEncoding("UTF-8"), "application/json") }); } }
/// <summary> /// 递归删除节点 /// </summary> /// <param name="entity"></param> /// <returns></returns> private async Task recursiveDeleteAsync(JDBCEntity entity) { List <JDBCEntity> list = (await GetAllChildrenAsync(entity)).ToList(); for (int i = 0; i < list.Count(); i++) { var item = list[i]; if (item.Equals(JDBCEntityType.Signal)) { await myStorageEngine.DeleteDataAsync(item.Id); //删除signal下的payload } //review var delfilter = Builders <JDBCEntity> .Filter.Eq(m => m.Id, item.Id); await collection.DeleteOneAsync(delfilter); await recursiveDeleteAsync(item); } }
public void DeleteEntityTest() { //delete mistakenly string errorDeleteNotExistedEntity = ""; try { myCoreApi.DeletAsync(Guid.NewGuid()).Wait(); } catch (Exception e) { errorDeleteNotExistedEntity = e.InnerException.Message; } string errorDeleteExperimentWithChildren = ""; try { myCoreApi.DeletAsync(exp12.Id).Wait(); } catch (Exception e) { errorDeleteExperimentWithChildren = e.InnerException.Message; } //delete properly JDBCEntity wavesig = myCoreApi.FindOneByPathAsync("/exp1/exp1-2/ws1").Result; //myCoreApi.DeletAsync(wavesig.Id).Wait(); myCoreApi.DeletAsync(exp11.Id).Wait(); myCoreApi.DeletAsync(exp12.Id, true).Wait(); //get child for later asserter var wavesigResult = myCoreApi.FindNodeByIdAsync(wavesig.Id).Result; var exp11Result = myCoreApi.FindNodeByIdAsync(exp11.Id).Result; var exp12Result = myCoreApi.FindNodeByIdAsync(exp12.Id).Result; var sig121Result = myCoreApi.FindNodeByIdAsync(sig121.Id).Result; //assert Assert.IsNull(wavesigResult); Assert.IsNull(exp11Result); Assert.IsNull(exp12Result); Assert.IsNull(sig121Result); }
/// <summary> /// 授权,给newuser一个指定权限 /// </summary> /// <param name="id">节点ID</param> /// <param name="user">发起授权用户</param> /// <param name="newuser">被授权用户</param> /// <param name="permisssion">键值对:("group", "1")</param> /// <returns></returns> public async Task AssignPermission(Guid id, LoginClaim user, string newuser, KeyValuePair <string, string> permisssion) { JDBCEntity entity = await myCoreService.GetOneByIdAsync(id); if (entity == null) { throw new Exception(ErrorMessages.EntityNotFoundError); } else if (!user.Equals(entity.User) && !IsRootRole(user)) { throw new Exception(ErrorMessages.WrongUserError); } else //管理员和所有者可进行权限设置 { switch (permisssion.Key.ToLower()) { case "user": //指定所有者 entity.SetUser(newuser); break; case "group": //设置其他用户权限 if (entity.GroupPermission.ContainsKey(newuser)) { entity.GroupPermission[newuser] = permisssion.Value; } else { entity.GroupPermission.Add(newuser, permisssion.Value); } break; case "others": //设置默认用户权限 entity.OthersPermission = permisssion.Value; break; default: throw new Exception(ErrorMessages.NotValidUpdateOperatorError); } await myCoreService.SaveAsync(entity); } }
private async Task RecursiveChangePathAsync(JDBCEntity entity) { // child:/a/b/c/d/e 父节点是c,子节点是e // children: /a/b/c/d/e/f/g 包含 parent: /a/b/c // 更改后得到 不用处理:/a/b/c/d 需要处理的:/a/b/c/e/f/g // 子节点 需要更新path 和 ParentId(改变了父节点) // 子节点的孩子 需要更新path /a/b/c/e/f/g List <JDBCEntity> list = (await GetAllChildrenAsync(entity)).ToList(); foreach (var item in list) { //更改子节点的路径 string path = entity.Path.Trim() + "/" + item.Name; //updata var filter = Builders <JDBCEntity> .Filter.Eq(m => m.Id, item.Id); var update = Builders <JDBCEntity> .Update.Set(m => m.Path, path); await collection.UpdateOneAsync(filter, update); await RecursiveChangePathAsync(item); } }
public async Task <HttpResponseMessage> Delete() { var user = GetSessionUser(Request.Headers.GetCookies().FirstOrDefault()); List <NodeDto> successEntity = new List <NodeDto>(); //成功处理的Entity信息 JDBCEntity currentEntity = null; //当前处理的Entity信息 try { if (Request.RequestUri.PathAndQuery.ToLower().Equals("/entity/all"))//清空数据库 { await MyCoreApi.clearDb(); return(new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent("Clear database successfully!") }); } Uri uri = ParseToQueryUri(Request.RequestUri); var nodes = await MyCoreApi.FindNodeByUriAsync(uri);//获取被删除entity var queryDict = ParseToQueryDictionary(Request.RequestUri); if ((!queryDict.ContainsKey("recursive") || queryDict["recursive"] == "false") && nodes.Count() > 1)//递归删除查询到的所有entity { throw new Exception("Please use [recursive=true] to delete queried entities!"); } if (nodes.Count() == 0)//entity不存在 { throw new Exception("No entity is found!"); } var deleteChildren = false; if (queryDict.ContainsKey("_recursive") && queryDict["_recursive"] == "true") { deleteChildren = true; } foreach (var entity in nodes) { currentEntity = entity; if (!await MyCoreApi.Authorization(currentEntity.Id, user, "1")) { throw new Exception("Not authorization!"); } await MyCoreApi.DeletAsync(entity.Id, deleteChildren); successEntity.Add(Mapper.Map <NodeDto>(currentEntity)); } return(new HttpResponseMessage { Content = new StringContent(SerializeObjectToString(successEntity), System.Text.Encoding.GetEncoding("UTF-8"), "application/json") }); } catch (Exception e) { if (currentEntity == null) { return(new HttpResponseMessage { StatusCode = HttpStatusCode.Forbidden, Content = new StringContent(e.InnerException != null ? e.InnerException.Message : e.Message) }); } var response = new ResponseEntityMessage { Fail = new { Description = e.InnerException != null ? e.InnerException.Message : e.Message, Id = currentEntity.Id, Path = currentEntity.Path }, Success = successEntity }; return(new HttpResponseMessage { StatusCode = HttpStatusCode.Forbidden, Content = new StringContent(SerializeObjectToString(response), System.Text.Encoding.GetEncoding("UTF-8"), "application/json") }); } }
public async Task <HttpResponseMessage> Restore() { var user = GetSessionUser(Request.Headers.GetCookies().FirstOrDefault()); List <NodeDto> successEntity = new List <NodeDto>(); //成功处理的Entity信息 JDBCEntity currentEntity = null; //当前处理的Entity信息 try { if (!await MyCoreApi.Authorization(Guid.Empty, user, "1")) { throw new Exception("Not authorization!"); } await MyCoreApi.clearDb(true); MyCoreApi.CoreService.StorageEngine.Init(BusinessConfig.cassandraInit); JDBCEntity root = new Experiment("jtext"); root.SetUser("root"); await MyCoreApi.AddOneToExperimentAsync(Guid.Empty, root); successEntity.Add(Mapper.Map <NodeDto>(root)); for (var shot = 1; shot < 3; shot++) { JDBCEntity exp = new Experiment(shot.ToString()); await MyCoreApi.AddOneToExperimentAsync(root.Id, exp); successEntity.Add(Mapper.Map <NodeDto>(exp)); //normal data var waveSignal1 = (FixedIntervalWaveSignal)MyCoreApi.CreateSignal("FixedWave-int", "ws1", @"StartTime=-2&SampleInterval=0.5"); await MyCoreApi.AddOneToExperimentAsync(exp.Id, waveSignal1); await waveSignal1.PutDataAsync("", GenerateIntArray()); await waveSignal1.DisposeAsync(); successEntity.Add(Mapper.Map <NodeDto>(waveSignal1)); //big data var waveSignal2 = (FixedIntervalWaveSignal)MyCoreApi.CreateSignal("FixedWave-double", "ws2", @"StartTime=-2&SampleInterval=0.001"); waveSignal2.NumberOfSamples = 2000; await MyCoreApi.AddOneToExperimentAsync(exp.Id, waveSignal2); for (int i = 0; i < 20; i++) { var array = GenerateDoubleArray(2000); await waveSignal2.PutDataAsync("", array); } await waveSignal2.DisposeAsync(); successEntity.Add(Mapper.Map <NodeDto>(waveSignal2)); } return(new HttpResponseMessage { Content = new StringContent(SerializeObjectToString(successEntity), System.Text.Encoding.GetEncoding("UTF-8"), "application/json") }); } catch (Exception e) { if (currentEntity == null) { return(new HttpResponseMessage { StatusCode = HttpStatusCode.Forbidden, Content = new StringContent(e.InnerException != null ? e.InnerException.Message : e.Message) }); } var response = new ResponseEntityMessage { Fail = new { Description = e.InnerException != null ? e.InnerException.Message : e.Message, Id = currentEntity.Id, Path = currentEntity.Path }, Success = successEntity }; return(new HttpResponseMessage { StatusCode = HttpStatusCode.Forbidden, Content = new StringContent(SerializeObjectToString(response), System.Text.Encoding.GetEncoding("UTF-8"), "application/json") }); } }
public async Task <HttpResponseMessage> Extra() { var user = GetSessionUser(Request.Headers.GetCookies().FirstOrDefault()); List <NodeDto> successEntity = new List <NodeDto>(); //成功处理的Entity信息 JDBCEntity currentEntity = null; //当前处理的Entity信息 try { var dict = ParseToQueryDictionary(Request.RequestUri); NameValueCollection form = Request.Content.ReadAsFormDataAsync().Result; var id = new Guid(GetValueFromForm(form, "node")); currentEntity = await MyCoreApi.FindNodeByIdAsync(id);//获取源entity if (!await MyCoreApi.Authorization(currentEntity.Id, user, "1")) { throw new Exception("Not authorization!"); } var extras = GetValuesFromForm(form, "extra[]", true); if (extras != null) { currentEntity.ExtraInformation.Clear(); foreach (var extra in extras) { var index = extra.IndexOf(":::"); if (index < 0) { return(new HttpResponseMessage(HttpStatusCode.Forbidden)); } var key = extra.Substring(0, index); var value = extra.Substring(index + 3); if (key.Equals("") || value.Equals("")) { return(new HttpResponseMessage(HttpStatusCode.Forbidden)); } currentEntity.AddExtraInformation(key, value); } await MyCoreApi.CoreService.SaveAsync(currentEntity); } successEntity.Add(Mapper.Map <NodeDto>(currentEntity)); return(new HttpResponseMessage { Content = new StringContent(SerializeObjectToString(successEntity), System.Text.Encoding.GetEncoding("UTF-8"), "application/json") }); } catch (Exception e) { if (currentEntity == null) { return(new HttpResponseMessage { StatusCode = HttpStatusCode.Forbidden, Content = new StringContent(e.InnerException != null ? e.InnerException.Message : e.Message) }); } var response = new ResponseEntityMessage { Fail = new { Description = e.InnerException != null ? e.InnerException.Message : e.Message, Id = currentEntity.Id, Path = currentEntity.Path }, Success = successEntity }; return(new HttpResponseMessage { StatusCode = HttpStatusCode.Forbidden, Content = new StringContent(SerializeObjectToString(response), System.Text.Encoding.GetEncoding("UTF-8"), "application/json") }); } }
/// <summary> /// Get the parent id /// </summary> /// <param name="id">the child id</param> /// <returns></returns> public async Task <Guid> GetParentIdAsync(Guid id) { JDBCEntity child = await GetOneByIdAsync(id); return(child == null ? Guid.Empty : child.ParentId); }
public IWriter <T> GetWriter <T>(JDBCEntity signal) { throw new NotImplementedException(); }
/// <summary> /// Save experiment or signal /// </summary> /// <param name="entity"></param> /// <returns></returns> public async Task SaveAsync(JDBCEntity entity) { var filter = Builders <JDBCEntity> .Filter.Eq("Id", entity.Id); await collection.ReplaceOneAsync(filter, entity); }
/// <summary> /// duplicate a entity /// </summary> /// <param name="sourceId">the id of the source entity</param> /// <param name="parentId">the parent entity id of the new entity, empty id for root</param> /// <param name="newName">give it a new name</param> /// <param name="isRecuresive">do i duplcate the children</param> /// <param name="duplicatePayload">du i dupplcate the pyload in the signal, apply to all child eneity</param> /// <returns>return new entity</returns> public async Task <JDBCEntity> DuplicateAsync(Guid sourceId, Guid parentId, string newName, bool isRecuresive = false, bool duplicatePayload = false) { //检查是否有源节点 JDBCEntity source = await GetOneByIdAsync(sourceId); if (source == null) { throw new Exception(ErrorMessages.ExperimentOrSignalNotFoundError); } var entityWithSameName = await GetChildByNameAsync(parentId, newName); if (entityWithSameName != null) { //如果父节点下有同名节点,报错 throw new Exception(ErrorMessages.NameDuplicateError); } JDBCEntity parent = await GetOneByIdAsync(parentId); if (source.EntityType.Equals(JDBCEntityType.Signal)) { if (parentId.Equals(Guid.Empty) || parent == null) { //如果parentId==Guid.Empty,源节点又是Signal,则报错 //检查是否有指定父节点 throw new Exception(ErrorMessages.ParentNotExistError); } if (!parent.EntityType.Equals(JDBCEntityType.Experiment)) { throw new Exception(ErrorMessages.NotValidParentError); } source.Id = Guid.NewGuid(); source.Path = parent.Path.Trim() + "/" + newName; source.Name = newName; source.ParentId = parentId; await collection.InsertOneAsync(source); if (duplicatePayload == true) { await myStorageEngine.CopyDataAsync(sourceId, source.Id); } return(source); } string path = ""; if (parentId.Equals(Guid.Empty)) { path = "/" + newName; } else { if (parent != null) { path = parent.Path.Trim() + "/" + newName; } else { throw new Exception(ErrorMessages.ExperimentOrSignalNotFoundError); } } source.Id = Guid.NewGuid(); source.Path = path; source.Name = newName; source.ParentId = parentId; await collection.InsertOneAsync(source); if (isRecuresive == false && duplicatePayload == true) { throw new Exception(ErrorMessages.NotValidDuplicateOperatorError); } if (isRecuresive == true) { if (duplicatePayload == true) { await recursiveCopyPayloadAsync(sourceId, source.Path, source.Id); } else { await recursiveCopyEntityAsync(sourceId, source.Path, source.Id); } } return(source); }
/// <summary> /// 添加Node实例到Experiment /// </summary> /// <param name="parentId"></param> /// <param name="entity"></param> /// <returns></returns> public async Task <JDBCEntity> AddOneToExperimentAsync(Guid parentId, JDBCEntity entity) { return(await CoreService.AddJdbcEntityToAsync(parentId, entity)); }
/// <summary> /// 支持以下查询: /// /path/?name=* 查询所有根节点 /// /path/root/exp1/ip 查询对应路径的节点 /// /path/root/exp1?name=* 查询对应路径下的所有直接子节点 /// /path/root/exp1?name=*&recursive=true 查询对应路径下的所有子节点 /// /path/root/exp1?name=sig1 查询对应路径下的所有直接子节点 /// </summary> /// <param name="query"></param> /// <returns></returns> public async Task <IEnumerable <JDBCEntity> > FindJdbcEntityAsync(string query) { // ?后为子节点查询字段 int index = query.IndexOf("?"); JDBCEntity parent = null; List <JDBCEntity> result = new List <JDBCEntity>(); if (index > 0) //存在?(子节点查询) { var path = query.Substring(5, index - 5); if (!path.Equals("/")) { parent = await myCoreService.GetOneByPathAsync(path); if (parent == null) { throw new Exception(ErrorMessages.ExperimentOrSignalNotFoundError); } } // 解析?后的子节点查询条件 string[] splitArray = query.Substring(index + 1).Split('&'); Dictionary <string, string> splitDic = new Dictionary <string, string>(); foreach (var item in splitArray) { int startIndex = item.IndexOf("="); string key = item.Substring(0, startIndex).Trim(); string value = item.Substring(startIndex + 1).Trim(); splitDic.Add(key, value); } // 执行子节点查询条件 if (splitDic.ContainsKey("name")) { if (splitDic.ContainsKey("recursive") && splitDic["recursive"].Equals("true")) { return(await myCoreService.FindJdbcEntityAsync(parent, splitDic["name"], true)); } else { return(await myCoreService.FindJdbcEntityAsync(parent, splitDic["name"], false)); } } else { result.Add(parent); return(result); } } else if (query.LastOrDefault().Equals('/') && query.Length == 6) //返回空列表 { return(result); } else // 不存在?,仅根据{id}查询节点 { var node = await myCoreService.GetOneByPathAsync(query.Substring(5)); if (node != null) { result.Add(node); } return(result); } }
/// <summary> /// add an entity to the db, if the entity is already saved in the db, this is used to change its parent /// </summary> /// <param name="parentId">empty for root, it must be a experiment, or exception will be thrown</param> /// <param name="entity">the entity to insert it must be a signal or experiment</param> /// <returns></returns> public async Task <JDBCEntity> AddJdbcEntityToAsync(Guid parentId, JDBCEntity entity) { //you should check if the new parent is a child of this entity!!! //use recursion to do this will only require one pass, i hava already find a way, hope you find easily //!!if the entity has many signal as its children, and the signales have many payload, re-calc the path would course a big overhead //查询到同名JdbcEntity抛出异常 //entity.Name 判断是不是为空 var entityWithSameName = await GetChildByNameAsync(parentId, entity.Name); if (entityWithSameName != null) { //如果父节点下有同名节点,报错 throw new Exception(ErrorMessages.NameDuplicateError); } if (parentId.Equals(Guid.Empty)) { var child = await GetOneByIdAsync(entity.Id); if (child == null) { if (entity.EntityType.Equals(JDBCEntityType.Experiment)) { entity.Path = "/" + entity.Name; await collection.InsertOneAsync(entity); } else { throw new Exception(ErrorMessages.NotValidParentError); } return(entity); } else { string path = "/" + child.Name; child.Path = path; var filter = Builders <JDBCEntity> .Filter.Eq(m => m.Id, child.Id); var update = Builders <JDBCEntity> .Update.Set("Path", path).Set("ParentId", Guid.Empty); await collection.UpdateOneAsync(filter, update); await RecursiveChangePathAsync(child); return(child); } } else { JDBCEntity parent = await GetOneByIdAsync(parentId); if (parent == null) { throw new Exception(ErrorMessages.ParentNotExistError); } if (!parent.EntityType.Equals(JDBCEntityType.Experiment)) { throw new Exception(ErrorMessages.NotValidParentError); } //如果是自己的子节点 //遍历函数 判断父节点路径下是否有子节点 //判断这个entity是新实例,还是原来在数据库的 var child = await GetOneByIdAsync(entity.Id); if (child == null) { entity.ParentId = parentId; string path = parent.Path; entity.Path = path.Trim() + "/" + entity.Name; await collection.InsertOneAsync(entity);//await return(entity); } else { // child:/a/b/c/d/e 父节点是c,子节点是e // children: /a/b/c/d/e/f/g 包含 parent: /a/b/c // 更改后得到 不用处理:/a/b/c/d 需要处理的:/a/b/c/e/f/g // 子节点 需要更新path 和 ParentId(改变了父节点) // 子节点的孩子 需要更新path /a/b/c/e/f/g var parentPath = parent.Path; var childPath = child.Path; if (parentPath.Count() >= childPath.Count()) { var compare = parentPath.Substring(0, childPath.Count()); if (compare.Equals(childPath)) { throw new Exception(ErrorMessages.ParentLoopError); } } string path = parent.Path.Trim() + "/" + child.Name; child.Path = path; //递归时有用 child.ParentId = parentId; var filter = Builders <JDBCEntity> .Filter.Eq(m => m.Id, child.Id); var update = Builders <JDBCEntity> .Update.Set("Path", path).Set("ParentId", parentId); await collection.UpdateOneAsync(filter, update); await RecursiveChangePathAsync(child); return(child); } } }
public async Task <HttpResponseMessage> Insert() { var user = GetSessionUser(Request.Headers.GetCookies().FirstOrDefault()); List <NodeDto> successEntity = new List <NodeDto>(); //成功处理的Entity信息 JDBCEntity currentEntity = null; //当前处理的Entity信息 try { Uri uri = ParseToQueryUri(Request.RequestUri); List <JDBCEntity> parents = (await MyCoreApi.FindNodeByUriAsync(uri)).ToList(); //根据uri查找父节点 if (uri.PathAndQuery.Equals("/path/") || uri.PathAndQuery.Equals("/id/")) //添加根节点的情形 { parents.Add(new Experiment { Id = Guid.Empty }); } else if (parents.Count() == 0)//根节点不存在 { throw new Exception("Parent node not exist!"); } NameValueCollection form = Request.Content.ReadAsFormDataAsync().Result; JDBCEntity newNode = null; var type = GetValueFromForm(form, "type"); var name = GetValueFromForm(form, "name"); var extras = GetValuesFromForm(form, "extra[]", true); if (string.IsNullOrWhiteSpace(name)) { throw new Exception("Entity name can not be empty!"); } switch (type.ToLower()) { case "experiment": { newNode = new Experiment(name); } break; case "signal": { var init = GetValueFromForm(form, "init"); var datatype = GetValueFromForm(form, "datatype"); newNode = MyCoreApi.CreateSignal(datatype, name, init.Replace(";", "&").Replace(",", "&").Trim("'\"()[]{}".ToCharArray())); } break; default: throw new Exception("Entity type is not supported!"); } if (extras != null)//添加ExtraInformation { foreach (var extra in extras) { var index = extra.IndexOf(":::"); if (index < 0) { return(new HttpResponseMessage(HttpStatusCode.Forbidden)); } var key = extra.Substring(0, index); var value = extra.Substring(index + 3); if (key.Equals("") || value.Equals("") || newNode.IfExtraInformationContainsKey(key)) { return(new HttpResponseMessage(HttpStatusCode.Forbidden)); } newNode.AddExtraInformation(key, value); } } if (newNode == null) { return(new HttpResponseMessage { StatusCode = HttpStatusCode.Forbidden, Content = new StringContent("Failed to create new node!") }); } foreach (var parent in parents) { if (!await MyCoreApi.Authorization(parent.Id, user, "1")) { throw new Exception("Not authorization!"); } currentEntity = parent; newNode.Id = Guid.NewGuid(); newNode.SetUser(user.UserName); var node = await MyCoreApi.AddOneToExperimentAsync(parent.Id, newNode); //添加signal successEntity.Add(Mapper.Map <NodeDto>(node)); //保存处理结果 } return(new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent(SerializeObjectToString(successEntity), System.Text.Encoding.GetEncoding("UTF-8"), "application/json") }); } catch (Exception e) { if (currentEntity == null) { return(new HttpResponseMessage { StatusCode = HttpStatusCode.Forbidden, Content = new StringContent(e.Message) }); } var response = new ResponseEntityMessage { Fail = new { Description = e.InnerException != null ? e.InnerException.Message : e.Message, Id = currentEntity.Id, Path = currentEntity.Path }, Success = successEntity }; return(new HttpResponseMessage { StatusCode = HttpStatusCode.Forbidden, Content = new StringContent(SerializeObjectToString(response), System.Text.Encoding.GetEncoding("UTF-8"), "application/json") }); } }