Exemplo n.º 1
0
        public void StartBulkAnalysis(IList <Alias> apis, bool preferredOnly)
        {
            bool   csvHeaderAdded = false;
            string startDate      = DateTime.Now.ToString(String.Format("yyyy-MM-dd_HH.mm.ss.FFF"));

            Out.PrintHeaderBulkAnalysisStart(startDate);

            foreach (Alias api in apis)
            {
                //load API info
                ApiGuruApi apiInfo = GetApiInfo(api.Key, ProjectFolderPath);
                if (apiInfo == null)
                {
                    continue;
                }

                //load all versions
                IList <Alias> versions = GetVersionAlias(api.Key, ProjectFolderPath);
                if (versions == null)
                {
                    continue;
                }

                foreach (Alias version in versions)
                {
                    if (!preferredOnly || (preferredOnly && apiInfo.Preferred.CompareTo(version.Value) == 0))
                    {
                        //load version Info
                        ApiGuruApiVersion versionInfo = apiInfo.Versions.Versions[version.Value];

                        //determine documentation path
                        string rawContent = LoadOpenApiFile(api.Key, version.Key, ProjectFolderPath);

                        //start analysis
                        AnalysisResult analysisResult = AnalyzeSingleApi(rawContent, api.Key, api.Value, version.Key, version.Value, apiInfo.Added, versionInfo.Added, LinkAnalyzerFactory.Create(IsNameCaseInvariant, AllowExactMatch, AllowPropertyNameContainsParameterName, AllowParameterNameContainsPropertyName));
                        Out.PrintResult(analysisResult);

                        //append results to file
                        string csvContent = "";
                        if (!csvHeaderAdded)
                        {
                            csvContent    += analysisResult.CsvHeader;
                            csvHeaderAdded = true;
                        }
                        csvContent += analysisResult.ToCsv;
                        File.AppendAllText(ProjectFolderPath + @"\" + startDate + ".csv", csvContent);
                    }
                }
            }
            Out.PrintHeaderBulkAnalysisFinish(DateTime.Now.ToString(String.Format("yyyy-MM-dd_HH.mm.ss.FFF")));
        }
Exemplo n.º 2
0
        public static void Main(string[] args)
        {
            //step 0: load arguments
            CustomizedArguments arguments = CustomizedArguments.Parse(args);

            if (!arguments.Has(CustomizedArguments.ARG_SOURCE))
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Path to OpenAPI documentation is missing. Use the parameter '" + CustomizedArguments.ARG_SOURCE + "' to specify the path to the JSON or YAML file");
            }

            //step 1a: load open API documentation and create URI Model
            Console.WriteLine("Load OpenAPI documentation from: '" + arguments.Get(CustomizedArguments.ARG_SOURCE) + "'");
            UriModel uriModel = CustomizedUriModelFactory.Instance.Create(arguments.Get(CustomizedArguments.ARG_SOURCE));

            Console.WriteLine(uriModel);
            Console.WriteLine("");

            //step 1b: calculate metrics
            int roots = 0;

            if (uriModel.Root.HasOperations)
            {
                roots = 1;
            }
            else
            {
                roots = uriModel.Root.NextDescendantsWithOperations.Count;
            }
            Console.WriteLine("Number of roots: " + roots);
            Console.WriteLine("Height (without root): " + (uriModel.Root.Height - 1));
            Console.WriteLine("Number of Path Segments (without root): " + (uriModel.Root.QuerySubTree.Results.Count - 1));
            Console.WriteLine("Number of Var. Path Segments: " + uriModel.Root.QuerySubTree.IsVariable().Results.Count);
            Console.WriteLine("Number of Resources: " + uriModel.Root.QuerySubTree.HasOperations().Results.Count);
            Console.WriteLine();

            //step 2: identity reachability paths for all path segments representing resources
            Console.Write("Identify reachability paths");
            IList <PathSegment> pathSegmentsRepresentingResources = uriModel.Root.QuerySubTree.HasOperations().Results;

            foreach (PathSegment pathSegmentRepresentingResources in pathSegmentsRepresentingResources)
            {
                ((CustomizedPathSegment)pathSegmentRepresentingResources).IdentifyReachabilityPaths(LinkAnalyzerFactory.Create());
            }
            Console.WriteLine(" - completed");

            //step 3: print identified reachability paths:
            foreach (PathSegment pathSegmentRepresentingResources in pathSegmentsRepresentingResources)
            {
                Console.WriteLine(pathSegmentRepresentingResources.UriPath + ":");
                foreach (ReachabilityPath reachabilityPath in ((CustomizedPathSegment)pathSegmentRepresentingResources).ReachabilityPaths)
                {
                    Console.WriteLine(reachabilityPath);
                }
                Console.WriteLine("");
            }

            //step 4: calculate reachability paths
            ISet <PathSegment>  reachedPathSegments  = new HashSet <PathSegment>();
            IList <PathSegment> apiStartPathSegments = new List <PathSegment>();

            if (uriModel.Root.HasOperations)
            {
                apiStartPathSegments.Add(uriModel.Root);
            }
            else
            {
                apiStartPathSegments = ((CustomizedPathSegment)uriModel.Root).NextDescendantsRepresentingOneResource;
            }
            /********************************************* api.version.links.#ReachableResources*********/
            foreach (PathSegment pathSegment in apiStartPathSegments)
            {
                FollowReachabilityPaths(pathSegment, reachedPathSegments, "2", new List <HttpMethod>()
                {
                    HttpMethod.GET
                }, new List <LinkMatchType>());
            }
            int numberOfReachedPathSegments = GetNumberOfPathSegmentsRepresentingResources(reachedPathSegments);

            Console.WriteLine("Number of reached resources: " + numberOfReachedPathSegments + " of " + uriModel.Root.QuerySubTree.HasOperations().Results.Count);

            /********************************************* api.version.links.%ReachableResourcesWithExactMatch*********/
            Console.WriteLine("Share of reached resources: " + (((double)numberOfReachedPathSegments / (double)uriModel.Root.QuerySubTree.HasOperations().Results.Count) * 100) + " %");
            Console.WriteLine();
            foreach (PathSegment resourcePathSegment in uriModel.Root.QuerySubTree.HasOperations().Results)
            {
                if (reachedPathSegments.Contains(resourcePathSegment))
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                }
                Console.WriteLine(resourcePathSegment.UriPath);
            }
            Console.ForegroundColor = ConsoleColor.White;
            Console.ReadKey();
        }
Exemplo n.º 3
0
        public static void Main(string[] args)
        {
            //step 1: load arguments
            CustomizedArguments arguments = CustomizedArguments.Parse(args);

            //step 2: load log writer
            if (arguments.Has(CustomizedArguments.ARG_LOG_OUT))
            {
                //console
                if (arguments.Get(CustomizedArguments.ARG_LOG_OUT).CompareTo(CustomizedArguments.OPT_LOG_OUT_CONSOLE) == 0)
                {
                    Log.LogWriters.Add(new CustomizedConsoleLogWriter()
                    {
                        LogLevel = arguments.LogLevel
                    });
                }
                //file
                else
                {
                    Log.LogWriters.Add(new FileLogWriter(arguments.LogPath + DateTime.Now.ToString(String.Format("yyyy-MM-dd_HH.mm.ss.FFF")) + ".log")
                    {
                        LogLevel = arguments.LogLevel
                    });
                }
                Log.Debug(TAG, "log_out:" + arguments.Get(CustomizedArguments.ARG_LOG_OUT));
            }
            //default (console)
            else
            {
                Log.LogWriters.Add(new CustomizedConsoleLogWriter()
                {
                    LogLevel = arguments.LogLevel
                });
            }

            //step 3: load OpenAPI documentation
            Log.Info(TAG, "Load OpenAPI documentation from '" + arguments.Get(CustomizedArguments.ARG_SOURCE) + "'");
            OpenApiDiagnostic openApiDiagnostic = new OpenApiDiagnostic();
            OpenApiDocument   openApiDocument   = new OpenApiStringReader().Read(File.ReadAllText(arguments.Get(CustomizedArguments.ARG_SOURCE)), out openApiDiagnostic);

            foreach (OpenApiError openApiError in openApiDiagnostic.Errors)
            {
                Log.Error(TAG, "OpenAPI Reader Error: " + openApiError.Message);
            }
            Log.Info(TAG, "Load OpenAPI documentation - completed\n");

            //step 4: create URI Model
            Log.Info(TAG, "Create URI Model:");
            UriModel uriModel = CustomizedUriModelFactory.Instance.Create(openApiDocument);

            Log.Info(TAG, "\n" + uriModel.ToString() + "\n");

            //step 5: identify reachability associations
            Log.Info(TAG, "Identify reachability associations:");
            ILinkAnalyzer       linkAnalyzer = LinkAnalyzerFactory.Create();
            IList <PathSegment> pathSegmentsRepresentingResources = uriModel.Root.QuerySubTree.HasOperations().Results;

            foreach (PathSegment pathSegmentRepresentingResources in pathSegmentsRepresentingResources)
            {
                ((CustomizedPathSegment)pathSegmentRepresentingResources).IdentifyReachabilityPaths(linkAnalyzer);
                Log.Info(TAG, pathSegmentRepresentingResources.UriPath);
                foreach (ReachabilityPath association in ((CustomizedPathSegment)pathSegmentRepresentingResources).ReachabilityPaths)
                {
                    Log.Info(TAG, association.ToString());
                }
            }

            //step 6: set base path
            string basePath = "";

            if (arguments.Has(CustomizedArguments.ARG_API_BASE_PATH))
            {
                basePath = arguments.Get(CustomizedArguments.ARG_API_BASE_PATH);
            }
            else
            {
                foreach (OpenApiServer openApiServer in openApiDocument.Servers)
                {
                    basePath = openApiServer.Url;
                }
            }
            Log.Info(TAG, "\nBase path of remote API: '" + basePath + "'");

            //step 7: load property name prefix of injected properties
            string propertyNamePrefix = "";

            if (arguments.Has(CustomizedArguments.ARG_INJECTION_PREFIX))
            {
                propertyNamePrefix = arguments.Get(CustomizedArguments.ARG_INJECTION_PREFIX);
            }

            //step 8: prepare proxy
            IProxyHandler handler = new CustomizedProxyHandler(basePath, uriModel, propertyNamePrefix, arguments.Has(CustomizedArguments.ARG_EXTENDED_HYPERLINK), arguments.Has(CustomizedArguments.ARG_PREFLIGHT_HEAD_COUNTER)?Int32.Parse(arguments.Get(CustomizedArguments.ARG_PREFLIGHT_HEAD_COUNTER)):10);

            ApiRequest.IgnoreBadCertificates();

            if (arguments.Has(CustomizedArguments.ARG_ACCESS_TOKEN))
            {
                handler.UpdateAcessTokenAutomatically = false;
                handler.UpdateAuthorization(arguments.Get(CustomizedArguments.ARG_ACCESS_TOKEN));
                Log.Info(TAG, "Access token has been loaded from arguments and will be injected into API requests automatically");
            }
            else
            {
                handler.UpdateAcessTokenAutomatically = true;
                Log.Warning(TAG, "Access token is not specified in arguments. If the API expects an access token, make sure that the client specifies this token in each request.");
            }

            HttpController controller = new ProxyController(handler);

            //step 9: start proxy
            HttpService service = new DefaultHttpSysService(false, "+", Int32.Parse(arguments.Get(CustomizedArguments.ARG_PORT)));

            service.AddController(controller);

            Log.Info(TAG, "Proxy routes:");
            Log.Info(TAG, service.Routes);
            service.Start();
            Log.Info(TAG, "Proxy is listening on port '" + arguments.Get(CustomizedArguments.ARG_PORT) + "'");

            Console.WriteLine("PRESS KEY TO TERMINATE SERVICE");
            Console.ReadKey();
        }