public IEnumerable<ControllerMethod> GetMethods(Resource resource, string url, ControllerObject parent, string objectName) { var methodsNames = new List<string>(); if (parent != null && parent.Methods != null) methodsNames = parent.Methods.Select(m => m.Name).ToList(); var generatorMethods = new Collection<ControllerMethod>(); if (resource.Methods == null) return generatorMethods; foreach (var method in resource.Methods) { var generatedMethod = BuildControllerMethod(url, method, resource, parent); if (IsVerbForMethod(method)) { if (methodsNames.Contains(generatedMethod.Name)) generatedMethod.Name = GetUniqueName(methodsNames, generatedMethod.Name, resource.RelativeUri); if (method.QueryParameters != null && method.QueryParameters.Any()) { var queryParameters = QueryParametersParser.ParseParameters(method); generatedMethod.QueryParameters = queryParameters; } generatorMethods.Add(generatedMethod); methodsNames.Add(generatedMethod.Name); } } return generatorMethods; }
private void AddGeneratedMethod(Resource resource, string url, string objectName, Method method, ICollection<string> methodsNames, ICollection<ClientGeneratorMethod> generatorMethods) { var generatedMethod = BuildClassMethod(url, method, resource); if (generatedMethod.ReturnType != "string") { var returnType = CollectionTypeHelper.GetBaseType(generatedMethod.ReturnType); generatedMethod.ReturnTypeObject = schemaResponseObjects.Values .First(o => o.Name == returnType ); generatedMethod.OkReturnType = GetOkReturnType(generatedMethod); } uriParametersGenerator.Generate(resource, url, generatedMethod, uriParameterObjects); if (!IsVerbForMethod(method)) return; if (methodsNames.Contains(generatedMethod.Name)) generatedMethod.Name = GetUniqueName(methodsNames, generatedMethod.Name, resource.RelativeUri); GetQueryParameters(objectName, method, generatedMethod); GetHeaders(objectName, method, generatedMethod); GetResponseHeaders(objectName, generatedMethod, method); generatorMethods.Add(generatedMethod); methodsNames.Add(generatedMethod.Name); }
protected static void GetInheritedUriParams(IDictionary<string, Parameter> parentUriParameters, Resource resource) { foreach (var uriParams in resource.UriParameters) { if (!parentUriParameters.ContainsKey(uriParams.Key)) parentUriParameters.Add(uriParams); } }
public void Setup() { var raml = new RamlParser().Load("files/box.raml"); var raml2 = new RamlParser().Load("files/congo-drones-5-f.raml"); deliveriesResource = raml2.Resources.First(r => r.RelativeUri == "/deliveries"); searchResource = raml.Resources.First(r => r.RelativeUri == "/search"); foldersResource = raml.Resources.First(r => r.RelativeUri == "/folders"); }
private List<Property> GetProperties(IEnumerable<Response> responses, Resource resource, Method method, string key, string fullUrl) { var properties = new List<Property>(); foreach (var response in responses) { AddProperty(resource, method, key, response, properties, fullUrl); } return properties; }
private ICollection<Resource> GetResources(IDictionary<string, object> dynamicRaml) { object value; var resources = new Resource[0]; if (dynamicRaml.TryGetValue("resources", out value)) resources = ((object[])value).Select(o => new ResourceBuilder().Build((IDictionary<string, object>)o)).ToArray(); return resources; }
public string Parse(string schema, Resource resource, Method method, string fullUrl) { var url = GetResourcePath(resource, fullUrl); var res = ReplaceReservedParameters(schema, method, url); res = ReplaceCustomParameters(resource, res); res = ReplaceParametersWithFunctions(resource, res, url); return res; }
public IEnumerable<GeneratorParameter> GetUriParameters(Resource resource, string url) { var parameters = resource.BaseUriParameters .Select(p => new GeneratorParameter { Name = p.Key, Type = NetTypeMapper.Map(p.Value.Type), Description = p.Value.Description }) .ToList(); parameters.AddRange(resource.UriParameters .Select(p => new GeneratorParameter { Name = p.Key, Type = NetTypeMapper.Map(p.Value.Type), Description = p.Value.Description }) .ToList()); var urlParameters = ExtractParametersFromUrl(url).ToArray(); parameters.AddRange(urlParameters.Where(up => parameters.All(p => up.Name != p.Name)).ToArray()); return parameters; }
protected string GetComment(Resource resource, BasicInfo method) { var description = resource.Description; if (!string.IsNullOrWhiteSpace(method.Description)) description += string.IsNullOrWhiteSpace(description) ? method.Description : ". " + method.Description; description = ParserHelpers.RemoveNewLines(description); if (!string.IsNullOrWhiteSpace(resource.DisplayName)) description += string.IsNullOrWhiteSpace(description) ? resource.DisplayName : " - " + resource.DisplayName; return description; }
private void AddMethodsToRootController(IList<ControllerObject> classes, ICollection<string> classesNames, IDictionary<string, ControllerObject> classesObjectsRegistry, Resource resource, string fullUrl, ControllerObject rootController, IDictionary<string, Parameter> parentUriParameters) { var generatedMethods = webApiMethodsGenerator.GetMethods(resource, fullUrl, rootController, rootController.Name, parentUriParameters); foreach (var method in generatedMethods) { rootController.Methods.Add(method); } classesNames.Add(rootController.Name); classesObjectsRegistry.Add(CalculateClassKey("/"), rootController); classes.Add(rootController); }
private static string GetResourcePath(Resource resource, string fullUrl) { var url = resource.RelativeUri; url = ReplaceUriParameters(url); if (string.IsNullOrWhiteSpace(url) || url.Trim() == "/") { fullUrl = ReplaceUriParameters(fullUrl); url = fullUrl; } url = url.TrimEnd('/'); if (!url.StartsWith("/")) url = "/" + url; return url; }
protected string GetReturnType(string key, Method method, Resource resource, string fullUrl) { if (!method.Responses.Any(r => r.Body != null && r.Body.Any(b => !string.IsNullOrWhiteSpace(b.Value.Schema)))) return "string"; var responses = method.Responses .Where(r => r.Body != null && r.Body.Any(b => !string.IsNullOrWhiteSpace(b.Value.Schema))) .ToArray(); var returnType = HandleMultipleSchemaType(responses, resource, method, key, fullUrl); if (!string.IsNullOrWhiteSpace(returnType)) return returnType; return "string"; }
private ClientGeneratorMethod BuildClassMethod(string url, Method method, Resource resource) { var generatedMethod = new ClientGeneratorMethod { Name = NetNamingMapper.GetMethodName(method.Verb ?? "Get" + resource.RelativeUri), ReturnType = GetReturnType(GeneratorServiceHelper.GetKeyForResource(method, resource), method, resource, url), Parameter = GetParameter(GeneratorServiceHelper.GetKeyForResource(method, resource), method, resource, url), Comment = GetComment(resource, method), Url = url, Verb = NetNamingMapper.Capitalize(method.Verb), Parent = null, UseSecurity = raml.SecuredBy != null && raml.SecuredBy.Any() || resource.Methods.Any(m => m.Verb == method.Verb && m.SecuredBy != null && m.SecuredBy.Any()) }; return generatedMethod; }
public ICollection<ClientGeneratorMethod> GetMethods(Resource resource, string url, ClassObject parent, string objectName) { var methodsNames = new List<string>(); if (parent != null) methodsNames = parent.Methods.Select(m => m.Name).ToList(); var generatorMethods = new Collection<ClientGeneratorMethod>(); if (resource.Methods == null) return generatorMethods; foreach (var method in resource.Methods) { AddGeneratedMethod(resource, url, objectName, method, methodsNames, generatorMethods); } return generatorMethods; }
protected GeneratorParameter GetParameter(string key, Method method, Resource resource, string fullUrl) { var schema = GetJsonSchemaOrDefault(method.Body); if (schema != null) { var generatorParameter = GetGeneratorParameterWhenNamed(method, resource, schema, fullUrl); if (generatorParameter != null) return generatorParameter; } if (resource.Type != null && resource.Type.Any() && raml.ResourceTypes.Any(rt => rt.ContainsKey(resource.GetResourceType()))) { var verb = GetResourceTypeVerb(method, resource); if (verb != null && verb.Body != null && !string.IsNullOrWhiteSpace(verb.Body.Schema)) { var generatorParameter = GetGeneratorParameterWhenNamed(method, resource, verb.Body.Schema, fullUrl); if (generatorParameter != null) return generatorParameter; } } if (RequestHasKey(key)) return GetGeneratorParameterByKey(key); var requestKey = key + GeneratorServiceBase.RequestContentSuffix; if (RequestHasKey(requestKey)) return GetGeneratorParameterByKey(requestKey); if (linkKeysWithObjectNames.ContainsKey(key)) { var linkedKey = linkKeysWithObjectNames[key]; if (RequestHasKey(linkedKey)) return GetGeneratorParameterByKey(linkedKey); } if (linkKeysWithObjectNames.ContainsKey(requestKey)) { var linkedKey = linkKeysWithObjectNames[requestKey]; if (RequestHasKey(linkedKey)) return GetGeneratorParameterByKey(linkedKey); } return new GeneratorParameter {Name = "content", Type = "string"}; }
public Resource Build(IDictionary<string, object> dynamicRaml) { var resource = new Resource(); new BasicInfoBuilder().Set(dynamicRaml, resource); resource.RelativeUri = dynamicRaml.ContainsKey("relativeUri") ? (string) dynamicRaml["relativeUri"] : null; resource.BaseUriParameters = ParametersBuilder.GetUriParameters(dynamicRaml, "baseUriParameters"); resource.UriParameters = ParametersBuilder.GetUriParameters(dynamicRaml, "uriParameters"); resource.DisplayName = dynamicRaml.ContainsKey("displayName") ? (string) dynamicRaml["displayName"] : null; resource.Protocols = ProtocolsBuilder.Get(dynamicRaml); resource.Resources = GetResources(dynamicRaml); resource.Methods = dynamicRaml.ContainsKey("methods") ? new MethodsBuilder(((object[]) dynamicRaml["methods"]).Cast<IDictionary<string, object>>()).Get() : null; return resource; }
private string ReplaceParametersWithFunctions(Resource resource, string res, string url) { var regex = new Regex(@"\<\<([a-z_-]+)\s?\|\s?\!(pluralize|singularize)\>\>", RegexOptions.IgnoreCase); var matchCollection = regex.Matches(res); foreach (Match match in matchCollection) { string replacementWord; switch (match.Groups[1].Value) { case "resourcePathName": replacementWord = url.Substring(1); break; case "resourcePath": replacementWord = url.Substring(1); break; case "methodName": replacementWord = url.Substring(1); break; default: var paramFound = match.Groups[1].Value; var type = resource.GetResourceType(); if (string.IsNullOrWhiteSpace(type)) continue; if (!resource.Type[type].ContainsKey(paramFound)) continue; replacementWord = resource.Type[type][paramFound]; break; } if (match.Groups[2].Value == "singularize") { res = res.Replace(match.Groups[0].Value, Singularize(replacementWord)); } else if (match.Groups[2].Value == "pluralize") { res = res.Replace(match.Groups[0].Value, Pluralize(replacementWord)); } } return res; }
private ControllerMethod BuildControllerMethod(string url, Method method, Resource resource, ControllerObject parent) { var relativeUri = UrlGeneratorHelper.GetRelativeUri(url, parent.PrefixUri); return new ControllerMethod { Name = NetNamingMapper.GetMethodName(method.Verb ?? "Get" + resource.RelativeUri), Parameter = GetParameter(GeneratorServiceHelper.GetKeyForResource(method, resource), method, resource, url), UriParameters = uriParametersGenerator.GetUriParameters(resource, url), ReturnType = GetReturnType(GeneratorServiceHelper.GetKeyForResource(method, resource), method, resource, url), Comment = GetComment(resource, method), Url = relativeUri, Verb = NetNamingMapper.Capitalize(method.Verb), Parent = null, UseSecurity = raml.SecuredBy != null && raml.SecuredBy.Any() || resource.Methods.Any(m => m.Verb == method.Verb && m.SecuredBy != null && m.SecuredBy.Any()), SecurityParameters = GetSecurityParameters(raml, method) }; }
private static string ReplaceCustomParameters(Resource resource, string res) { var regex = new Regex(@"\<\<([^>]+)\>\>", RegexOptions.IgnoreCase); var matchCollection = regex.Matches(res); foreach (Match match in matchCollection) { if(resource.Type == null) continue; var paramFound = match.Groups[1].Value; var type = resource.GetResourceType(); if (string.IsNullOrWhiteSpace(type) || !resource.Type.ContainsKey(type) || resource.Type[type] == null || !resource.Type[type].ContainsKey(paramFound)) continue; var value = resource.Type[type][paramFound]; res = res.Replace("<<" + paramFound + ">>", value); } return res; }
public Resource Build(IDictionary<string, object> dynamicRaml, IEnumerable<IDictionary<string, ResourceType>> resourceTypes, IEnumerable<IDictionary<string, Method>> traits, string defaultMediaType) { var resource = new Resource(); new BasicInfoBuilder().Set(dynamicRaml, resource); resource.RelativeUri = dynamicRaml.ContainsKey("relativeUri") ? (string) dynamicRaml["relativeUri"] : null; resource.BaseUriParameters = ParametersBuilder.GetUriParameters(dynamicRaml, "baseUriParameters"); resource.UriParameters = ParametersBuilder.GetUriParameters(dynamicRaml, "uriParameters"); resource.DisplayName = dynamicRaml.ContainsKey("displayName") ? (string) dynamicRaml["displayName"] : null; resource.Protocols = ProtocolsBuilder.Get(dynamicRaml); resource.Resources = GetResources(dynamicRaml, resourceTypes, traits, defaultMediaType); resource.Methods = GetMethods(dynamicRaml, traits, defaultMediaType); resource.Annotations = AnnotationsBuilder.GetAnnotations(dynamicRaml); resource.Is = IsExtractor.Get(dynamicRaml); return resource; }
private ControllerObject CreateControllerAndAddMethods(IList<ControllerObject> classes, ICollection<string> classesNames, IDictionary<string, ControllerObject> classesObjectsRegistry, Resource resource, string fullUrl, IDictionary<string, Parameter> parentUriParameters) { var controller = new ControllerObject { Name = GetUniqueObjectName(resource, null), PrefixUri = UrlGeneratorHelper.FixControllerRoutePrefix(fullUrl), Description = resource.Description, }; var methods = webApiMethodsGenerator.GetMethods(resource, fullUrl, controller, controller.Name, parentUriParameters); foreach (var method in methods) { controller.Methods.Add(method); } classesNames.Add(controller.Name); classes.Add(controller); classesObjectsRegistry.Add(CalculateClassKey(fullUrl), controller); return controller; }
public void Generate(Resource resource, string url, ClientGeneratorMethod clientGeneratorMethod, IDictionary<string, ApiObject> uriParameterObjects, IDictionary<string, Parameter> parentUriParameters) { var parameters = GetUriParameters(resource, url, parentUriParameters).ToArray(); clientGeneratorMethod.UriParameters = parameters; if (!parameters.Any()) return; var name = NetNamingMapper.GetObjectName(url) + "UriParameters"; clientGeneratorMethod.UriParametersType = name; if (uriParameterObjects.ContainsKey(name)) return; var properties = new List<Property>(); if (resource.BaseUriParameters != null) properties.AddRange(QueryParametersParser.ConvertParametersToProperties(resource.BaseUriParameters)); if (resource.UriParameters != null) properties.AddRange(QueryParametersParser.ConvertParametersToProperties(resource.UriParameters) .Where(up => properties.All(p => !String.Equals(up.Name, p.Name, StringComparison.InvariantCultureIgnoreCase)))); var urlParameters = ExtractParametersFromUrl(url).ToArray(); var matchedParameters = MatchParameters(parentUriParameters, urlParameters); foreach (var urlParameter in matchedParameters) { var property = ConvertGeneratorParamToProperty(urlParameter); if (properties.All(p => !String.Equals(property.Name, p.Name, StringComparison.InvariantCultureIgnoreCase))) properties.Add(property); } var apiObject = new ApiObject { Name = name, Description = "Uri Parameters for resource " + resource.RelativeUri, Properties = properties }; uriParameterObjects.Add(name, apiObject); }
private string HandleMultipleSchemaType(IEnumerable<Response> responses, Resource resource, Method method, string key, string fullUrl) { var properties = GetProperties(responses, resource, method, key, fullUrl); if (properties.Count == 0) return "string"; if (properties.Count == 1) return properties.First().Type; // Build a new response object containing all types var name = NetNamingMapper.GetObjectName("Multiple" + key); var apiObject = new ApiObject { Name = name, Description = "Multiple Response Types " + string.Join(", ", properties.Select(p => p.Name)), Properties = properties, IsMultiple = true }; schemaResponseObjects.Add(new KeyValuePair<string, ApiObject>(name, apiObject)); return name; }
private void AddProperty(Resource resource, Method method, string key, Response response, ICollection<Property> properties, string fullUrl) { var mimeType = GeneratorServiceHelper.GetMimeType(response); if (mimeType == null) return; var type = GetReturnTypeFromResponse(method, resource, mimeType, key, response.Code, fullUrl); if (string.IsNullOrWhiteSpace(type)) return; var property = new Property { Name = CollectionTypeHelper.GetBaseType(type), Description = response.Description + " " + mimeType.Description, Example = mimeType.Example, Type = type, StatusCode = (HttpStatusCode) Enum.Parse(typeof (HttpStatusCode), response.Code), JSONSchema = mimeType.Schema == null ? null : mimeType.Schema.Replace(Environment.NewLine, "").Replace("\r\n", "").Replace("\n", "").Replace("\"", "\\\"") }; properties.Add(property); }
public void Should_Generate_One_Method_Per_Verb() { var methods = new List<Method> { new Method { Verb = "get" }, new Method { Verb = "post" } }; var resource = new Resource { RelativeUri = "/abc{token}{code}", Methods = methods, }; var schemaResponseObjects = new Dictionary<string, ApiObject>(); var schemaRequestObjects = new Dictionary<string, ApiObject>(); var ramlDocument = new RamlDocument(); var uriParameterObjects = new Dictionary<string, ApiObject>(); var queryObjects = new Dictionary<string, ApiObject>(); var headerObjects = new Dictionary<string, ApiObject>(); var responseHeadersObjects = new Dictionary<string, ApiObject>(); var linkedKeyWithObjectNames = new Dictionary<string, string>(); var classObject = new ClassObject(); var schemaObjects = new Dictionary<string, ApiObject>(); var generator = new ClientMethodsGenerator(ramlDocument, schemaResponseObjects, uriParameterObjects, queryObjects, headerObjects, responseHeadersObjects, schemaRequestObjects, linkedKeyWithObjectNames, schemaObjects); var generatorMethods = generator.GetMethods(resource, "/", classObject, "Test", new Dictionary<string, Parameter>()); Assert.AreEqual(2, generatorMethods.Count); }
public void Should_Build_Uri_Parameters() { var uriParameters = new Dictionary<string, Parameter> { { "code", new Parameter { DisplayName = "code", Type = "integer" } } }; var methods = new List<Method> { new Method { Verb = "get" } }; var resource = new Resource { RelativeUri = "/abc{token}{code}", Methods = methods, UriParameters = uriParameters }; var generator = new UriParametersGenerator(); var uriParameterObjects = new Dictionary<string, ApiObject>(); var generatorMethod = new ClientGeneratorMethod { Name = "MethodOne"}; generator.Generate(resource, "/movies/{bucket}/abc{token}{code}", generatorMethod, uriParameterObjects); Assert.AreEqual(1, uriParameterObjects.Count); Assert.AreEqual(3, generatorMethod.UriParameters.Count()); Assert.AreEqual(uriParameterObjects.First().Value.Name, generatorMethod.UriParametersType); }
public RamlDocument GetRaml(string title = null) { if (string.IsNullOrWhiteSpace(title)) title = "Api"; var raml = new RamlDocument {Title = title, BaseUri = baseUri}; var resourcesDic = new Dictionary<string, Resource>(); var parameterDescriptionsDic = new Dictionary<string, Collection<ApiParameterDescription>>(); foreach (var api in apiExplorer.ApiDescriptions) { var relativeUri = !api.Route.RouteTemplate.StartsWith("/") ? "/" + api.Route.RouteTemplate : api.Route.RouteTemplate; if (relativeUri.Contains("{controller}")) { relativeUri = relativeUri.Replace("{controller}", api.ActionDescriptor.ControllerDescriptor.ControllerName); if (relativeUri.EndsWith("/")) relativeUri = relativeUri.Substring(0, relativeUri.Length - 1); } foreach (var apiParam in GetParametersFromUrl(relativeUri)) { relativeUri = RemoveNonExistingParametersFromRoute(relativeUri, api, apiParam.Key); } Resource resource; if (!resourcesDic.ContainsKey(relativeUri)) { resource = new Resource { Methods = GetMethods(api, new Collection<string>()), RelativeUri = relativeUri, }; parameterDescriptionsDic.Add(relativeUri, api.ParameterDescriptions); resourcesDic.Add(relativeUri, resource); } else { resource = resourcesDic[relativeUri]; foreach (var apiParameterDescription in api.ParameterDescriptions) { parameterDescriptionsDic[relativeUri].Add(apiParameterDescription); } AddMethods(resource, api, resource.Methods.Select(m => m.Verb).ToList()); } if(SetResourceProperties != null) SetResourceProperties(resource, api); if(SetResourcePropertiesByAction != null) SetResourcePropertiesByAction(resource, api.ActionDescriptor); if(SetResourcePropertiesByController != null) SetResourcePropertiesByController(resource, api.ActionDescriptor.ControllerDescriptor); } raml.Schemas = new List<IDictionary<string, string>> { schemas }; OrganizeResourcesHierarchically(raml, resourcesDic); SetUriParameters(raml.Resources, parameterDescriptionsDic, string.Empty); if(SetRamlProperties != null) SetRamlProperties(raml); if (SecuritySchemes != null) raml.SecuritySchemes = SecuritySchemes; if (!string.IsNullOrWhiteSpace(securityType) && securityScheme != null) SetSecurityScheme(raml); if (SecuredBy != null) raml.SecuredBy = SecuredBy; if(Protocols != null) raml.Protocols = Protocols; return raml; }
private void AddMethods(Resource resource, ApiDescription api, ICollection<string> verbs) { var methods = resource.Methods.ToList(); var newMethods = GetMethods(api, verbs); methods.AddRange(newMethods); resource.Methods = methods; }
private void SerializeResource(StringBuilder sb, Resource resource, int indentation) { sb.AppendLine((resource.RelativeUri + ":").Indent(indentation)); SerializeParameters(sb, "baseUriParameters", resource.BaseUriParameters, indentation + 2); SerializeDescriptionProperty(sb, resource.Description, indentation + 2); SerializeProperty(sb, "displayName", resource.DisplayName, indentation + 2); SerializeProtocols(sb, resource.Protocols, indentation + 2); SerializeParameters(sb, "uriParameters", resource.UriParameters, indentation + 2); SerializeMethods(sb, resource.Methods, indentation + 2); //SerializeType(sb, resource.Type, indentation + 2); SerializeResources(sb, resource.Resources, indentation + 2); }
// avois infinite recursion private string GetReturnTypeFromResponseWithoutCheckingResourceTypes(Method method, Resource resource, MimeType mimeType, string key, string responseCode, string fullUrl) { var returnType = GetNamedReturnType(method, resource, mimeType, fullUrl); if (!string.IsNullOrWhiteSpace(returnType)) return returnType; if (ResponseHasKey(key)) return GetReturnTypeFromResponseByKey(key); var responseKey = key + ParserHelpers.GetStatusCode(responseCode) + GeneratorServiceBase.ResponseContentSuffix; if (ResponseHasKey(responseKey)) return GetReturnTypeFromResponseByKey(responseKey); if (linkKeysWithObjectNames.ContainsKey(key)) { var linkedKey = linkKeysWithObjectNames[key]; if (ResponseHasKey(linkedKey)) return GetReturnTypeFromResponseByKey(linkedKey); } if (linkKeysWithObjectNames.ContainsKey(responseKey)) { var linkedKey = linkKeysWithObjectNames[responseKey]; if (ResponseHasKey(linkedKey)) return GetReturnTypeFromResponseByKey(linkedKey); } return returnType; }