/// <summary> /// Creates new router on the server /// </summary> public Router(HorseMq server, string name, RouteMethod method) { Server = server; IsEnabled = true; Name = name; Method = method; }
/// <summary> /// Creates new router /// </summary> private async Task CreateRouter(MqClient client, HorseMessage message) { IRouter found = _server.FindRouter(message.Target); if (found != null) { await client.SendAsync(message.CreateResponse(HorseResultCode.Ok)); return; } string methodHeader = message.FindHeader(HorseHeaders.ROUTE_METHOD); RouteMethod method = RouteMethod.Distribute; if (!string.IsNullOrEmpty(methodHeader)) { method = (RouteMethod)Convert.ToInt32(methodHeader); } //check create queue access foreach (IClientAuthorization authorization in _server.Authorizations) { bool grant = await authorization.CanCreateRouter(client, message.Target, method); if (!grant) { await client.SendAsync(message.CreateResponse(HorseResultCode.Unauthorized)); return; } } _server.AddRouter(message.Target, method); await client.SendAsync(message.CreateResponse(HorseResultCode.Ok)); }
/// <summary> /// Adds new binding to a router /// </summary> /// <param name="routerName">Router name of the binding</param> /// <param name="type">Binding type</param> /// <param name="name">Binding name</param> /// <param name="target">Binding target. Queue name, tag name, direct receiver id, name, type, etc.</param> /// <param name="interaction">Binding interaction</param> /// <param name="bindingMethod">Binding method is used when multiple receivers available in same binding. It's used for Direct and Tag bindings.</param> /// <param name="contentType">Overwritten content type if specified</param> /// <param name="priority">Binding priority</param> /// <returns></returns> public async Task <HorseResult> AddBinding(string routerName, BindingType type, string name, string target, BindingInteraction interaction, RouteMethod bindingMethod = RouteMethod.Distribute, ushort?contentType = null, int priority = 1) { HorseMessage message = new HorseMessage(); message.Type = MessageType.Server; message.ContentType = KnownContentTypes.AddBinding; message.SetTarget(routerName); message.WaitResponse = true; message.SetMessageId(_client.UniqueIdGenerator.Create()); BindingInformation info = new BindingInformation { Name = name, Target = target, Interaction = interaction, ContentType = contentType, Priority = priority, BindingType = type, Method = bindingMethod }; message.Serialize(info, new NewtonsoftContentSerializer()); return(await _client.WaitResponse(message, true)); }
private IDictionary<string, RouteHandler> GetRouteTable(RouteMethod method) { IDictionary<string, RouteHandler> routes; switch (method) { case RouteMethod.Get: routes = _routesGet; break; case RouteMethod.Post: routes = _routesPost; break; case RouteMethod.Put: routes = _routesPut; break; case RouteMethod.Delete: routes = _routesDelete; break; default: throw new ArgumentOutOfRangeException("method"); } return routes; }
/// <summary> /// Creates a new instance. /// </summary> /// <param name="url">A route URL.</param> /// <param name="method">A HTTP method used for the route.</param> /// <param name="requestSerializer">A serializer for the route.</param> /// <param name="responseDeserializer">A deserializer for processing of the response.</param> /// <param name="contentType">A content type for the route.</param> public RouteDefinition(string url, RouteMethod method, ISerializer requestSerializer, IDeserializer responseDeserializer, string contentType) { Url = url; Method = method; RequestSerializer = requestSerializer; ResponseDeserializer = responseDeserializer; ContentType = contentType; }
public void GetAdapterShouldReturnNullForUnknownMethods() { var mapper = new RouteMapper(new RouteMetadata[0]); RouteMethod result = mapper.GetAdapter(ExampleMethodInfo); Assert.That(result, Is.Null); }
public void GetAdapterShouldReturnAnAdapterForKnownMethods() { var mapper = new RouteMapper(new[] { CreateRoute("GET", "/route") }); RouteMethod result = mapper.GetAdapter(ExampleMethodInfo); Assert.That(result, Is.Not.Null); }
public WhenRouteBuilder(RouteMethod <TContent, TConsumer> routemethod) { if (routemethod == null) { throw new ArgumentNullException(nameof(routemethod)); } _routemethod = routemethod; }
public RouteMethod getRoute(int id) { RouteMethod route = null; if (!mRoutes.TryGetValue(id, out route)) { return(null); } return(route); }
public void ShouldInvokeTheSpecifiedMethod() { IFakeInterface instance = Substitute.For <IFakeInterface>(); RouteMethod result = this.adapter.CreateMethod( () => instance, typeof(IFakeInterface).GetMethod(nameof(IFakeInterface.SimpleMethod))); result(null); instance.Received().SimpleMethod(); }
/// <summary> /// Creates new router. /// Returns success result if router already exists. /// </summary> public async Task <HorseResult> Create(string name, RouteMethod method) { HorseMessage message = new HorseMessage(); message.Type = MessageType.Server; message.ContentType = KnownContentTypes.CreateRouter; message.SetTarget(name); message.WaitResponse = true; message.AddHeader(HorseHeaders.ROUTE_METHOD, Convert.ToInt32(method).ToString()); message.SetMessageId(_client.UniqueIdGenerator.Create()); return(await _client.WaitResponse(message, true)); }
public void ShouldPassInTheTypesDefaultValueForParametersMarkedAsOptional() { IFakeInterface instance = Substitute.For <IFakeInterface>(); RouteMethod result = this.adapter.CreateMethod( () => instance, typeof(IFakeInterface).GetMethod(nameof(IFakeInterface.NonDefaultedOptions))); result(new Dictionary <string, object>()); instance.Received().NonDefaultedOptions(0); }
public void ShouldPassInDefaultedValuesForOptionalParametersWithDefaults() { IFakeInterface instance = Substitute.For <IFakeInterface>(); RouteMethod result = this.adapter.CreateMethod( () => instance, typeof(IFakeInterface).GetMethod(nameof(IFakeInterface.OptionalParameter))); result(new Dictionary <string, object>()); instance.Received().OptionalParameter(321); }
public IWhenMethodBuilder <TContent, THandler> With(Action <TContent, THandler, MessageContext> method) { if (method == null) { throw new ArgumentNullException(nameof(method)); } var routemethod = new RouteMethod <TContent, THandler>(method); _route.RouteMethods.Add(routemethod); return(new WhenRouteBuilder <TContent, THandler>(routemethod)); }
public async Task ShouldReturnNoContentValueForTaskMethods() { IFakeInterface instance = Substitute.For <IFakeInterface>(); RouteMethod wrapper = this.adapter.CreateMethod( () => instance, typeof(IFakeInterface).GetMethod(nameof(IFakeInterface.TaskMethod))); object result = await wrapper(null); Assert.That(result, Is.SameAs(NoContent.Value)); await instance.Received().TaskMethod(); }
public static RouteMethod Create(MethodInfo mi) { //参数名称中含有parent_开头的表示该接口需要父类的资料,路由中则父类需要带参数的形式 if (mi.GetParameters().Where(p => p.ParameterType != typeof(string) && (p.Name.ToLower().StartsWith("parent_") == false)).Count() > 0) { return(null); } //parent_开头的参数只允许有一个 if (mi.GetParameters().Where(p => p.Name.ToLower().StartsWith("parent_")).Count() > 1) { return(null); } var rtn = new RouteMethod(); rtn.Name = mi.Name.ToLower(); rtn.Method = mi; var r = new StringBuilder(); foreach (var p in mi.GetParameters()) { if (p.ParameterType == typeof(string)) { r.Append("/{" + p.Name + "}"); } } var pparam = mi.GetParameters().Where(p => p.Name.ToLower().StartsWith("parent_")); if (pparam.Count() > 0) { r.Insert(0, "#parent#"); rtn.ParameterType4Parent = pparam.First().ParameterType; } rtn.Route = r.ToString(); rtn.Key = GetRouteMethodKey(mi); var rattr = rtn.Method.GetCustomAttribute <RouteDescAttribute>(); if (rattr == null) { rtn.RouteDesc = rtn.Key; } else { rtn.RouteDesc = rattr.Desc; } return(rtn); }
public async Task ShouldConvertGenericTaskToTaskObject() { IFakeInterface instance = Substitute.For <IFakeInterface>(); instance.Int32Task().Returns(123); RouteMethod wrapper = this.adapter.CreateMethod( () => instance, typeof(IFakeInterface).GetMethod(nameof(IFakeInterface.Int32Task))); object result = await wrapper(null); Assert.That(result, Is.EqualTo(123)); }
/// <summary> /// Initializes a new instance of the <see cref="RouteMapper"/> class. /// </summary> /// <param name="routes">The routes to match.</param> public RouteMapper(IEnumerable <RouteMetadata> routes) { var adapter = new RouteMethodAdapter(); var builder = new NodeBuilder(); foreach (RouteMetadata route in routes) { IMatchNode[] nodes = builder.Parse(route.RouteUrl, route.Method.GetParameters()); this.AddRoute(route.Verb, nodes, route.Method); RouteMethod lambda = adapter.CreateMethod(route.Factory, route.Method); this.adapters[route.Method.MetadataToken] = lambda; } }
public void ShouldThrowExceptionsInsideTheConvertedTask() { IFakeInterface instance = Substitute.For <IFakeInterface>(); instance.TaskMethod().Returns(Task.FromException(new DivideByZeroException())); RouteMethod result = this.adapter.CreateMethod( () => instance, typeof(IFakeInterface).GetMethod(nameof(IFakeInterface.TaskMethod))); Exception ex = result(null).Exception.Flatten(); Assert.That(ex.InnerException, Is.InstanceOf <DivideByZeroException>()); }
public void ShouldPassInTheCapturedValueForOptionalParameters() { IFakeInterface instance = Substitute.For <IFakeInterface>(); RouteMethod result = this.adapter.CreateMethod( () => instance, typeof(IFakeInterface).GetMethod(nameof(IFakeInterface.OptionalParameter))); result(new Dictionary <string, object> { { "optional", 123 } }); instance.Received().OptionalParameter(123); }
public void ShouldConstructTheObjectWithTheFactoryDelegate() { bool delegateCalled = false; FakeClass.ClearConstructorCount(); RouteMethod result = this.adapter.CreateMethod( () => { delegateCalled = true; return(new FakeClass()); }, typeof(FakeClass).GetMethod(nameof(FakeClass.MyMethod))); Assert.That(delegateCalled, Is.False); Assert.That(FakeClass.ConstructorCount.Value, Is.EqualTo(0)); result(null); Assert.That(delegateCalled, Is.True); Assert.That(FakeClass.ConstructorCount.Value, Is.EqualTo(1)); }
public PointLogicEntity(Type t) { LogicType = t; var tmp = (EndPoint)Activator.CreateInstance(t, true); LogicName = tmp.Name; Route = "/" + LogicName; var ns = LogicType.Namespace; if (_reg_version_.IsMatch(ns)) { APIVersion = _reg_version_.Match(ns).Value.ToLower().Replace("_", ""); } var methods = t.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(p => _method_verbs_.Contains(p.Name.ToLower()) && (p.DeclaringType == t || p.DeclaringType == typeof(EndPoint))); RouteMethods = new Dictionary <string, RouteMethod>(); foreach (var m in methods) { var rm = RouteMethod.Create(m); if (rm == null) { continue; } var key = rm.Key; //优先获取本类型定义的同名方法,如果没有再才登记EndPoint的方法 if (RouteMethods.ContainsKey(key)) { if (RouteMethods[key].Method.DeclaringType != t && m.DeclaringType == t) { RouteMethods[key] = rm; } } else { RouteMethods.Add(key, rm); } } tmp = null; }
/// <summary> /// Invokes the registered handler and converts the response. /// </summary> /// <param name="request">The request data to process.</param> /// <returns> /// A task that represents the asynchronous operation. The value of the /// <c>TResult</c> parameter contains the response to send. /// </returns> protected internal virtual async Task <IResponseData> InvokeHandler(IRequestData request) { RouteMethod method = this.mapper.GetAdapter(request.Handler); if (method == null) { throw new InvalidOperationException("Request data contains an invalid method."); } // Check if result is NoContent.Value object result = await method(request.Parameters).ConfigureAwait(false); if (result == NoContent.Value) { return(ResponseData.NoContent); } else { // TODO: Plug in the serialization logic here... return(new ResponseData(string.Empty, (int)HttpStatusCode.OK)); } }
/// <summary> /// Kokoaa reitin useammasta ruutukentän symbolista. /// /// Määrittää, että tietyn ruutukentän symbolin (<c>tileSymbol</c>) kohdalla /// kutsutaan aliohjelmaa <c>f</c>. Huom! Käytä tämän aliohjelman kanssa metodia /// Execute. /// </summary> /// <param name="f">Aliohjelma, muotoa void LuoReittiolio(List<Vector> reitti, double leveys, double korkeus)</param> /// <param name="tileSymbols">Ruutukentän symbolit tiedostossa joista reitti muodostuu</param> public void SetRouteMethod(RouteMethod f, params TileType[] tileSymbols) { if (tileSymbols == null || tileSymbols.Length < 1) { throw new ArgumentException("Pass at least one tile symbol!"); } Vector[] vectorTable = new Vector[tileSymbols.Length]; int vectorsAdded = 0; for (int i = 0; i < tileSymbols.Length; i++) { int index = i; legend[tileSymbols[i]] = delegate(Vector p, double w, double h) { vectorTable[index] = p; if (++vectorsAdded >= tileSymbols.Length) { f(vectorTable.ToList(), w, h); } }; } }
/// <summary> /// Creates new Router and adds it to server routers. /// Throws exception if name is not eligible /// </summary> public IRouter AddRouter(string name, RouteMethod method) { try { if (!Filter.CheckNameEligibility(name)) { throw new InvalidOperationException("Invalid router name"); } if (_routers.Find(x => x.Name == name) != null) { throw new DuplicateNameException(); } Router router = new Router(this, name, method); _routers.Add(router); return(router); } catch (Exception e) { SendError("ADD_ROUTER", e, $"RouterName:{name}"); throw; } }
public static ServerUri Reslove(string uri, RouteMethod m) { var r = Parse(uri); return r.Resolve(m); }
public abstract ServerUri Resolve(RouteMethod method);
/// <summary> /// Creates new instance. /// </summary> /// <param name="url">Route URL.</param> /// <param name="method">HTTP method used for the route.</param> /// <param name="serialization">Serialization format used for the route.</param> public RouteDefinition(string url, RouteMethod method = RouteMethod.Get, RouteSerialization serialization = RouteSerialization.Json) { Url = url; Method = method; Serialization = serialization; }
/// <summary> /// Creates new direct binding. /// Name is the name of the binding. /// Target is the topic of queues. /// Content Type should be Queue Id. /// Priority for router binding. /// </summary> public TopicBinding(string name, string target, ushort?contentType, int priority, BindingInteraction interaction, RouteMethod routeMethod = RouteMethod.Distribute) : base(name, target, contentType, priority, interaction) { RouteMethod = routeMethod; }
public void Execute <TContent, THandler>(MessageContext context, TContent content, RouteMethod <TContent, THandler> routemethod, THandler handler) where THandler : class { if (routemethod.ConsumerWithContext != null) { routemethod.ConsumerWithContext(content, handler, context); } else { routemethod.Consumer?.Invoke(content, handler); } }
public void RegisterRoute(RouteMethod method, string path, RouteHandler handler) { var routes = GetRouteTable(method); routes.Add(path, handler); }
public void Execute <TContent, THandler, TData>(MessageContext context, TContent content, RouteMethod <TContent, THandler> routemethod, THandler handler, TData data) where THandler : class where TData : class, new() { if (routemethod.ConsumerWithContext != null) { routemethod.ConsumerWithContext(content, handler, context); } else { if (routemethod.Consumer != null) { routemethod.Consumer(content, handler); } else { if (routemethod.ConsumerWithDataAndContext != null) { routemethod.ConsumerWithDataAndContext(content, handler, context, data); } else { routemethod.ConsumerWithData?.Invoke(content, handler, data); } } } }
public void AddRoute(RouteMethod method, string path, RouteHandler function) { _routeManager.RegisterRoute(method, path, function); }
public ResolvableUri(string protocol, string serviceName) : base(protocol) { _serviceName = serviceName; _method = RouteMethod.Auto; }
public virtual void ParseArgs(string []v) { if (v[0] == "node_num") { readerNum = int.Parse(v[1]); readers = new Reader[readerNum]; } else if (v[0] == "object_num" && objectNodeConstructor != null) { objectNum = int.Parse(v[1]); objects = new ObjectNode[objectNum]; for (int i = 0; i < objectNum; i++) objects[i] = objectNodeConstructor(i); } else if (v[0] == "querier_num" && querierConstructor !=null) { querierNum = int.Parse(v[1]); queriers = new Querier[querierNum]; for (int i = 0; i < querierNum; i++) queriers[i] = querierConstructor(i); } else if (v[0] == "event_file") { eventsFileName = v[1]; int i1 = eventsFileName.IndexOf("-s")+2; int i2 = eventsFileName.IndexOf("-", i1+1); string s = eventsFileName.Substring(i1, i2 - i1); double s1 = double.Parse(s); refSpeed = 1 / Math.Sqrt((s1+1) / 5); if (refSpeed > 1) refSpeed *= 2; } else if (v[0] == "node_dist") nodeDist = float.Parse(v[1]); else if (v[0] == "node_maxdist") nodeMaxDist = float.Parse(v[1]); else if (v[0] == "object_maxdist") objectMaxDist = float.Parse(v[1]); else if (v[0] == "org_num") orgNum = int.Parse(v[1]); else if (v[0] == "org_func") { if (v[1] == "Poisson") orgGenType = OrgGenType.Poisson; else if (v[1] == "AVG") orgGenType = OrgGenType.AVG; else if (v[1] == "CUS1") { orgGenType = OrgGenType.CUS1; orgRatio = new double[orgNum]; for (int i = 0; i < v.Length - 2; i++) { double ratio = double.Parse(v[i + 2]); orgRatio[i] = ratio; } } } else if (v[0] == "Poisson_Lamda") PoissonLamda = float.Parse(v[1]); else if (v[0] == "layout_x") layoutX = double.Parse(v[1]); else if (v[0] == "layout_y") layoutY = double.Parse(v[1]); else if (v[0] == "start") startTime = float.Parse(v[1]); else if (v[0] == "end") endTime = float.Parse(v[1]); else if (v[0] == "step") step = float.Parse(v[1]); else if (v[0] == "beacon_interval") beaconInterval = float.Parse(v[1]); else if (v[0] == "beacon_warming") beaconWarming = float.Parse(v[1]); else if (v[0] == "beacon_warming_interval") beaconWarmingInterval = float.Parse(v[1]); else if (v[0] == "check_reverse_route_cache") CheckReverseRouteCache = bool.Parse(v[1]); else if (v[0] == "check_gateway_cache") CheckGatewayCache = bool.Parse(v[1]); else if (v[0] == "random_seed") { int seed = int.Parse(v[1]); Utility.ran = new Random(seed); } else if (v[0] == "ttl") TTL = int.Parse(v[1]); else if (v[0] == "nodraw") nodraw = bool.Parse(v[1]); else if (v[0] == "listenNeighborAODVReply") listenNeighborAODVReply = bool.Parse(v[1]); else if (v[0] == "debug") debug = bool.Parse(v[1]); else if (v[0] == "routeMethod") routeMethod = (RouteMethod)Enum.Parse(typeof(RouteMethod), v[1], true); Console.WriteLine(v[0] + ":" + v[1]); }
public static ServerUri Reslove(string uri, RouteMethod m) { var r = Parse(uri); return(r.Resolve(m)); }
public void GetDirections(string origin, string destination, TravelMode mode, RouteMethod method, Units unit, Action<IRestResponse<RoutesResponse>> callback) { var result = new RestResponse<RoutesResponse> { StatusCode = HttpStatusCode.OK, Data = JsonConvert.DeserializeObject<RoutesResponse>(RoutesResponse) }; callback(result); }
public static NotSupportedException NotSupportedMethod(this EnsureExceptionHelper ensure, RouteMethod method) { Ensure.NotNull(ensure, "ensure"); return(ensure.NotSupported("Not supported route method '{0}'.", method)); }