Ejemplo n.º 1
0
        public static void Main(string[] args)
        {
            //Step 1: create Business Layer
            IContactHandler businessLayer = new ContactHandler();

            //Step 2: create REST Layer and link Business Layer
            HttpController restLayer = new ContactManagementController(businessLayer);

            //Step 3: add test object
            Contact contact = new Contact();

            contact.Surname = "Max";
            contact.Name    = "Mustermann";

            Address address = new Address();

            address.City    = "Hamburg";
            address.Zip     = "20359";
            address.Street  = "Bei den St. Pauli-Landungsbrücken";
            address.Country = "Deutschland";
            contact.Address = address;

            Phone phone = new Phone();

            phone.Number = "+4940428771234";
            phone.Type   = PhoneNumberType.home;

            Phone phone2 = new Phone();

            phone2.Number = "+491572343865";
            phone2.Type   = PhoneNumberType.mobile;

            businessLayer.AddContact(contact);
            businessLayer.AddPhone(contact.Id, phone);
            businessLayer.AddPhone(contact.Id, phone2);

            //Step 4: create server and link REST Layer
            HttpService service = new DefaultHttpSysService(true, "+", 500);

            service.AddController(restLayer, false);
            service.AddController(new AdministrationRestController());

            //Step 5: Start server

            Console.WriteLine("Routes:");
            Console.WriteLine(service.Routes);
            service.Start();

            Console.WriteLine("Webserver has been started");
            Console.WriteLine(service.Prefix);
            Console.ReadKey();
        }
Ejemplo n.º 2
0
        public static void Main(string[] args)
        {
            //load settings
            Settings settings = Settings.Load();

            if (settings == null)
            {
                Console.WriteLine("Invalid settings - check the Settings.json file");
                Console.ReadKey();
                return;
            }
            settings.Save();

            //prepare storage
            FileBasedControllerStorage controllerStorage = new FileBasedControllerStorage();
            FileBasedFirmwareStorage   firmwareStorage   = new FileBasedFirmwareStorage();
            MemoryBasedLedStorage      ledStorage        = new MemoryBasedLedStorage();
            FileBasedGroupStorage      groupStorage      = new FileBasedGroupStorage();

            //initialize storage
            controllerStorage.Initialize(settings.ControllerPath);
            firmwareStorage.Initialize(settings.FirmwarePath);
            ledStorage.Initialize();
            groupStorage.Initialize(settings.GroupPath);

            //initialize business logic (handlers)
            ControllerHandler controllerHandler = new ControllerHandler(controllerStorage, groupStorage, ledStorage);
            FirmwareHandler   firmwareHandler   = new FirmwareHandler(firmwareStorage, settings);
            LedHandler        ledHandler        = new LedHandler(ledStorage, controllerStorage);
            GroupHandler      groupHandler      = new GroupHandler(groupStorage, ledStorage);
            TrunkEndpoint     trunkEndpoint     = new TrunkEndpoint(controllerStorage, ledStorage);

            //initialize API endpoints (controllers)
            BaseController       baseController       = new BaseController(settings.Oauth);
            ControllerController controllerController = new ControllerController(controllerHandler);
            ControllerTrunk      controllerTrunk      = new ControllerTrunk(trunkEndpoint);
            FirmwareController   firmwareController   = new FirmwareController(firmwareHandler);
            LedController        ledController        = new LedController(ledHandler);
            GroupController      groupController      = new GroupController(groupHandler);

            //initialize web server
            HttpService service = new DefaultHttpSysService(false, "+", settings.ServerPort);

            service.AddController(baseController, settings.Multithreaded);
            service.AddController(controllerController, settings.Multithreaded);
            service.AddController(controllerTrunk, "Trunk", true);
            service.AddController(firmwareController, settings.Multithreaded);
            service.AddController(ledController, settings.Multithreaded);
            service.AddController(groupController, settings.Multithreaded);
            //service.GetProcessorPostManipulation(DefaultHttpSysService.INTERNAL_PROCESSING_GROUP).Add(new OptionsPayloadInjector("OptionsInjector"));

            //if OAuth is enabled...
            if (settings.Oauth)
            {
                //prepare OAuth storage
                ClientAccountFileStorage clientStorage       = new ClientAccountFileStorage();
                UserAccountFileStorage   userStorage         = new UserAccountFileStorage();
                RefreshTokenFileStorage  refreshTokenStorage = new RefreshTokenFileStorage();

                //initialize oauth storage
                clientStorage.Initialize(settings.ClientPath);
                refreshTokenStorage.Initialize(settings.RefreshTokenPath);
                userStorage.Initialize(settings.UserPath);

                //prepare OAuth core
                OAuth2 oauth = new OAuth2("fwehnvd3432nfre7r834nfsfiu43kmvrew!");
                oauth.ClientCredentialsAuthorization = new ClientCredentialsAuthorization(oauth, clientStorage);
                oauth.PasswordAuthorization          = new PasswordAuthorization(oauth, clientStorage, userStorage);
                oauth.RefreshTokenAuthorization      = new RefreshTokenAuthorization(oauth, clientStorage, userStorage, refreshTokenStorage);
                service.GetProcessorPreManipulation(false).Add(new CustomizedAccessTokenValidator(oauth.AccessTokenValidator));

                //prepare OAuth Webkit
                IScopeHandler  scopeHandler  = new ScopeHandler(service, oauth);
                IClientHandler clientHandler = new ClientHandler(clientStorage);
                IUserHandler   userHandler   = new UserHandler(clientStorage, userStorage);

                //initialize API endpoints (controllers) for OAuth + Webkit
                service.AddController(new AuthController(oauth));
                service.AddController(new ClientController(clientHandler));
                service.AddController(new ScopeController(scopeHandler));
                service.AddController(new UserController(userHandler));

                //assign scopes to OAuth Webkit API endpoints
                ClientController.AssignScopesToEndpoints(skotstein.app.ledserver.tools.Scopes.AUTH_CLIENT_READ, skotstein.app.ledserver.tools.Scopes.AUTH_CLIENT_WRITE, oauth);
                ScopeController.AssignScopeToEndpoint(skotstein.app.ledserver.tools.Scopes.AUTH_SCOPE_READ, oauth);
                UserController.AssignScopesToEndpoints(skotstein.app.ledserver.tools.Scopes.AUTH_USER_READ, skotstein.app.ledserver.tools.Scopes.AUTH_USER_WRITE, oauth);
            }



            //generate YAML file
            OpenApiDocumentBuilder documentBuilder = new OpenApiDocumentBuilder();
            OpenApiDocument        document        = documentBuilder.Build("V1");

            if (settings.Oauth)
            {
                document = documentBuilder.AddSecuritySchema(document, new List <HttpController> {
                    baseController, controllerController, groupController, ledController, firmwareController
                }, /*@"http://*****:*****@"http://localhost:4000/api/v1/auth/token");
            }
            string json = documentBuilder.AsJson(document);

            json = documentBuilder.Replace(json, new ExampleValues());


            json = documentBuilder.Replace(json, new HostValue("http://*****:*****@".\OpenApi.json", json);

            //start server
            Console.WriteLine(service.Routes);
            service.Start();
            Console.WriteLine("Service is listening on port:" + settings.ServerPort);
            if (settings.Oauth)
            {
                Console.WriteLine("OAuth 2.0 is enabled");
                Console.WriteLine("Access Token URL: POST " + restlayer.ApiBase.API_V1 + "/auth/token");
            }
            else
            {
                Console.WriteLine("OAuth 2.0 is disabled");
            }
            Console.WriteLine("Press key to terminate");
            Console.ReadKey();
        }
Ejemplo 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();
        }